var starttime = [];
var timestamps = [];
var dmz = '';
var voting = false;
var lastpoll = (+new Date().getTime());

$(document).ready(function(){

	$(".toggle-follow").click(function(){
		var id = $(this).attr('title').replace(/Follow /, '');
		$.post('/ajax/follow', {'username':id}, function(data){
		   //$("#follow-" + data.name).html(data.response);
		   $(".follow-" + data.name).addClass(data.addclass).removeClass(data.remclass);
		}, 'json');
	});
	
	$("#dismisswelcome").click(function(){
		$("#welcome").slideUp(200);
		$.getJSON('/ajax/unwelcome', function(data){ });						
	});
	
	$("#add_comment").click(function(){
		$(this).css('display', 'none');
		$("#comment_form").slideDown(200);
	});
	
	$("#submit_comment").click(function(){ 
		var cmt = $("#comment").val();
		$("#comment_form").slideUp(200);
		$("#comment").val('');
		$("#add_comment").css('display', 'block');
		$.post('/ajax/comment', {'comment':cmt, 'descriptor':cdtor}, function(data){
			addComment(data);											  
		}, 'json');
	});
	
	$("#embedLinkSWF").click(function(){
		if (typeof(facebookShare) != 'undefined') {
			FB.ui(facebookShare, 
			function(response) {
			  if (!response || response.error) {
				alert('Sorry the countdown couldn\'t be posted to your facebook stream. Please try again later!\nError: ' + response.error);
			  } else {
				$("#embedLinkSWF").fadeOut(250);
			  }
			}); 
		}
	});
	
	$(".repcmt").click(function(){
		if (confirm('Are you sure you want to report this comment? A moderator will look at it and decide if it needs to be removed. You only need to report it once.'))
		{
			$(this).html('Reported!');
			$(this).fadeOut(1000);
			$(this).unbind('click');
			
			$.getJSON('/ajax/report_comment/'+$(this).attr('id'), function(data){
				
		    });
		}
	});
	
	$(".ccp").focus(function(){
		if ($(this).val())
		{
			$(this).select();
			/*if (window.clipboardData && clipboardData.setData){
				clipboardData.setData("Text", $(this).val());
			} else {
				if (!document.all) return; // IE only
				r = text_val.createTextRange();
			    r.execCommand("Copy");
			}*/
		}
	});
	
	$("#embedLink").click(function(){ 
		$(this).css({'display':'none'});
		$("#embedCode").slideDown(300);
		if ($("#embedPreview").length && $("#embedPreview").html() == '') {
			$("#embedPreview").html('<iframe src="http://ticktocker.com' + $(this).attr('link') + '" id="ttwidget" height="75" width="300" border="0" style="border:0" scrolling="no"></iframe>');
		}
	});
	
	$("#embedCancel").click(function(){
		$("#embedCode").slideUp(200);
		$("#embedLink").css({'display':'inline'});
	});

	$("#tockInput").placeholder();
	$("#searchBox").placeholder();
	
	$("#tockInput").change(function(){
		if ($(this).val() && !$("#tags").val() && $(this).attr('placeholder') != $(this).val()) {
			var words = $(this).val().replace(/[\'\"\/\\!.:!@#$%^&*(),\[\]{}<>_-]/i, '');
			var words = words.replace(/\b(the|when|my|of|to|and|a|i|in|is|it|you|that|was|he|she|for|on|are|with|as|his|they|be|at|have|this|from|or|we|some|on|off|get|got|shit|fuck)\b/ig, '');
			var tags = words.match(/\b([a-z0-9]+)\b/ig);
			$("#tags").val( tags.join(', ') );
		}
	});
	
	$("#tockInput").focus(function(){
		if ($("#actual_calendar").html() == '')
      		loadCalendar();
      
		$("#tockForm").slideDown(250);
	});
	
	$("#addtockform").submit(function(){
		var errors = false;
		var t1 = $("#tockInput").val().trim();
		if (!t1 || t1 == $("#tockInput").attr('placeholder')) {
			errors = true;
			$("#e1").slideDown(100);
		} else {
			$("#e1").slideUp(100);
		}

		t1 = $("#date").val();
		var d1 = Date.parse(t1 + ' ' + $('#t1 :selected').val() + ':' + $('#t2 :selected').text() + ' ' + $('#t3 :selected').text());
		if (!t1 || !d1 || !(t1.match(/^[a-zA-Z]{3,9} [0-9]{1,2}, [0-9]{4}$/) || t1.match(/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/))) {
			errors = true;
			$("#e2").slideDown(100);
		} else {
			$("#e2").slideUp(100);
		}
		
		t1 = $("#dateend").val();
		if (t1)
		{
			var d2 = Date.parse(t1 + ' ' + $('#t4 :selected').val() + ':' + $('#t5 :selected').text() + ' ' + $('#t6 :selected').text());
			if (!d2 || (d2 < d1) || !(t1.match(/^[a-zA-Z]{3,9} [0-9]{1,2}, [0-9]{4}$/) || t1.match(/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/))) {
				errors = true;
				$("#e4").slideDown(100);
			} else {
				$("#e4").slideUp(100);
			}
		}
		
		/*t1 = $("#description").val();
		if (!t1)
		{
			errors = true;
			$("#e3").slideDown(100);
		}
		else
			$("#e3").slideUp(100);*/
			
		return (!errors);
	});

	$("#tockInput_cancel").click(function(){
		$(".at_error").slideUp(100);
		$("#tockForm").slideUp(250);
	});
	
	$(".addtock").click(function(){
		var id = $(this).attr('id').match(/[0-9]+/);
		$("#wi" + id).addClass('loading');
		$.getJSON('/ajax/watch/' + id, function(data){ 
			if (!data) return;
	        if (data.error) return showError(data.error);									    
			$("#wi" + data.id).removeClass('loading');
			if (data.toggle == 1) {
				$("#wl" + data.id).html('Stop Watching');
				$("#wl" + data.id).addClass('watched');
				$("#wi" + data.id).addClass('watched');
			} else {
				$("#wl" + data.id).html('Watch this Tock');
				$("#wl" + data.id).removeClass('watched');
				$("#wi" + data.id).removeClass('watched');
			}
		});
	});
	
	$(".focusable").focus(function(){
		$(".focusable").parent().removeClass("has_focus");
		$(this).parent().addClass("has_focus");
	});

	$(".upvote").click(function(){ 
		if (!voting) {
			voting = true;
			var id = $(this).attr('id').match(/[0-9]+/);
			if (!$(this).hasClass('upvoted')) {
				$(this).addClass('upvoted');
				$.getJSON('/ajax/upvote/' + id, function(data){ setVote(data); });
			} else {
				$(this).removeClass('upvoted');
				$.getJSON('/ajax/unvote/' + id, function(data){ setVote(data); });
			}
		}
	});

	$(".dnvote").click(function(){ 
		if (!voting) {
			voting = true;
			var id = $(this).attr('id').match(/[0-9]+/);
			
			if (!$(this).hasClass('dnvoted')) {
				$(this).addClass('dnvoted');
				$.getJSON('/ajax/dnvote/' + id, function(data){ setVote(data); });
			} else {
				$(this).removeClass('dnvoted');
				$.getJSON('/ajax/unvote/' + id, function(data){ setVote(data); });
			}
		}
	});
	
	$(".mapper").click(function(){
		//$(this).unbind('click');
		var id = $(this).attr('id').replace('open', 'map');
		var holder = $(this).attr('id').replace('open', 'hold');
		
		if ($("#"+id).length)
		{
			if ($("#"+id).hasClass('hm')) {
				$("#"+holder).slideDown(300);
				$("#"+id).removeClass('hm')
			} else {
				$("#"+holder).slideUp(300);	
				$("#"+id).addClass('hm')
			}
			//$("#"+id).remove();
		}
		else
		{
			$("#"+holder).slideDown(300);
			$("#"+holder).html( '<iframe id="'+id+'" class="gmap" src="http://ticktocker.com/ajax/google_map/'+$(this).attr('rel')+'" width="415" height="200" border="0" scrolling="no"></iframe>' );
		}
	});
	
	$("#mytock-edit").click(function(){
		$("#mytock-edit").css('display', 'none');
		$("#mytock-delete").css('display', 'none');
		$("#mytock-editform").slideDown(250);
	});
	
	$(".tockDownHolder").mouseover(dmzThis);
	$(".tockDownHolder").mouseout(dmzThis);
	$(".tockDownHolderE").mouseover(dmzThis);
	$(".tockDownHolderE").mouseout(dmzThis);
	$(".tockDownHolderB").mouseover(dmzThis);
	$(".tockDownHolderB").mouseout(dmzThis);
	$(".cdc").mouseover(dmzThis);
	$(".cdc").mouseout(dmzThis);
	$(".cdcE").mouseover(dmzThis);
	$(".cdcE").mouseout(dmzThis);
	$(".cdcB").mouseover(dmzThis);
	$(".cdcB").mouseout(dmzThis);

	$(".tock-delete").click(function(){
		return confirm('Are you sure you want to permanantly delete this tock?');					 
	});
	
	$("#reverify a").click(function(){
		$("#reverify").html('One Moment...');
		$.getJSON('/ajax/resend_welcome', function(data){
			$("#reverify").html(data.result);
		});
	});
	/*
	 	var inner = $(this).text();
	 	inner = inner.replace(/[\n\r\t]/g,'');
	 	
	 	var id = $(this).attr('id').replace('cd', 'ttitle');
	 	var string = $('#'+id).html() + ' is ' + inner;
	 	
	 	$(this).
		//alert(title + ' is ' + inner);
	});*/
	
	$("#tockFormAdvanced").click(function(){
		$(this).remove();
		$("#tockadv2").slideDown(200);
	});
	
	$("#tockFormDuration").click(function(){
		$(this).parent().remove();
		$("#tockadv1").slideDown(200);
	});
	
	$("#not_load").click(function(){
		//$("#not_box").html('<h3>Loading Notifications...</h3>');
		$("#not_load").removeClass('hasnots');
		
		if ($("#not_res").length) {
			if ($("#not_res").css('display') == 'none') {
				var pos = $("#not_box").position();
				var offY = $("#not_box").height()+7;
				var offX = -61;
				$("#not_res").css( {'left':(pos.left+offX)+'px','top':(pos.top+offY)+'px'} );
				$("#not_res").fadeIn(250);
			} else {
				$("#not_res").fadeOut(250);
			}
		} else {
			$("#not_load").html('<img id="notimg" src="/images/loading.gif" />Notifications');
			$.post('/ajax/my_notifications', {'j':1}, function(data){
				$("#notimg").remove();
				if (data) {
					$("#not_box").parent().append('<div id="not_res">'+data+'</div>');
					var pos = $("#not_box").position();
					var offY = $("#not_box").height()+7;
					var offX = -61;
					$("#not_res").css( {'left':(pos.left+offX)+'px','top':(pos.top+offY)+'px'} );
					$("#not_res").fadeIn(250);
					$("#not_can").click(function(){
						$("#not_res").fadeOut(250);
					});
					$(window).resize(function(){
						$("#not_res").css({'display':'none'});
					});
				} else {
					$("#not_box").html('Notifications temporarily unavailable.');
				}
			}, 'html');
		}
	});

	$(".al").autolink();

	var support = 'cker.' + 'com'; //wow real tough, eh
	support = 'info' + '@' + 'tickto' + support;
	
	$(".info-email").html('<a href="mailto:' + support + '">' + support + '</a>'); 

   $(document).konami(function(){
      //alert('30 lives enabled! We haven\'t quite figured out what to do here.');
	var _0x7349=["\x3C\x64\x69\x76\x20\x61\x6C\x69\x67\x6E\x3D\x22\x63\x65\x6E\x74\x65\x72\x22\x3E\x3C\x69\x6D\x67\x20\x73\x72\x63\x3D\x22\x2F\x69\x6D\x61\x67\x65\x73\x2F\x6B\x6F\x6E\x61\x6D\x69\x2E\x6A\x70\x67\x22\x20\x2F\x3E\x3C\x2F\x64\x69\x76\x3E"];
	var t=_0x7349[0];
	if ($("#cbox").length)
		$("#cbox").prepend(t);
	else if ($("#maintext").length)
		$("#maintext").prepend(t);
   });

	for (i in starttime)
		timestamps[i] = starttime[i].getTime();
		
	if ($("#my_calendar").length)
		myCalendar();
		
	$(".invite").click(inviter);
	
	$(".reject").click(function(){
		return confirm('Are you sure you want to reject this tock? This is permanent!');								
	});
	
	$(".taggle").click(function(){
		var tag = $(this).attr('id').match(/ttt_([^_]*?)_(.*?)/i);
		var data = {'id':tag[1], 'url':tag[2], 'tag':$(this).attr('alt'), 'parent':$(this).attr('id')};
		$.post('/ajax/tag_follow', data, function(result){
			if (result.error)
				alert(result.error);
			else if (result.response) {
				//$('#'+result.parent).parent().html(result.response);
				$('#'+result.parent).removeClass('gsubd').removeClass('gunsubd');
				$("#subcount_"+result.url).html(result.subcount);
				if (result.add == -1) {
					$("#tl_"+result.url).slideUp(200);
					$("#"+result.parent).addClass('gunsubd');
				} else if (result.add == 1) {
					if (!$("#tl_"+result.url).length) {
						$("#my_tag_list").append('<li id="tl_'+result.url+'"><a href="/tag/'+result.url+'">'+result.tag+' <span class="uses">'+result.uses+'</span></a></li>');
						$("#tl_"+result.url).css('display','none').slideDown(500);
					} else {
						$("#tl_"+result.url).css('display','none').slideDown(500);
					}
					$("#"+result.parent).addClass('gsubd');
				}
			}
		}, 'json');
	});
	
	$("#invite_friend").click(function(){ 
		$(this).remove();
		$("#invite_form").slideDown(200);
	});
	
	$(".mini-stream-tab").click(function(){
		if (!$(this).hasClass('active')) {
			$(".activeTab").removeClass('activeTab');
			$(".activePanel").removeClass('activePanel');
			$(this).addClass('activeTab');
			var id = $(this).attr('id').replace('tab', 'panel');
			$('#'+id).addClass('activePanel');
		}
	});

	checkVisitorTimezone();

	if ($("#not_load").length)
		$(window).focus(checkNotes);
		
	$("#signin").click(function(){
		if ($("#loginform").css('display') == 'none') {
			$("#loginform").fadeIn(200);
			$("#welcome").animate( {'opacity':0.25}, 100 );
		} else {
			$("#loginform").fadeOut(100);
			$("#welcome").animate( {'opacity':1}, 100 );
		}
			
		return false;
	});
	
	$(".embed_item").change(function(){
		var iw = parseInt($("#embed_width").val());
		var ih = parseInt($("#embed_height").val());
		var width =  iw ? iw : 300;
		var height = ih ? ih : 75;
		
		if (width < 150 || width > 600) {
			width = 300;
			$("#embed_width").val(width);
		}
			
		if (height < 75 || height > 300) {
			height = 75;
			$("#embed_height").val(height);
		}
		
		var dimensions = width + 'x' + height;
		$("#ttwidget").attr('width', width).attr('height', height).css({'width':width+'px','height':height+'px'});
		var html = '<' + 'scr' + 'ipt type="text/javascript" src="http://ticktocker.com/' + $("#embed_code").attr('seg') + '/js/'+dimensions+'"><'+'/'+'script>';
		$("#embed_code").val( html );
	});
	
	$(".invite_fbfriend").click(function(){
		$(this).unbind('click');
		$(this).html('Invited!');
		invitefber($(this).attr('uid'), $(this).attr('first'), username, my_url);
	});	

	$("#newcd").click(function(){
		var h = parseInt($("#cdh").val());
		var m = parseInt($("#cdm").val());
		var s = parseInt($("#cds").val());

		if (h || m || s) {
			document.location.href = "/cd/" + (h ? h+'h':'') + (m ? m+'m':'') + (s ? s+'s':'');
		}
	});
	
	setInterval('dectmr();', 1000);
	//setInterval('checkNotes();', 120000);
});


function inviter()
{
	$(this).unbind('click');
	var t = $(this).attr('tag');

	//$(this).attr({'otag':t, 'tag':'-1'});
	var url = '/ajax/' + (t == 1 ? 'un' : '') + 'invite';
	var input_data = { 'user':$(this).attr('user'), 'tock':$(this).attr('tock'), 'id':$(this).attr('id') };
	$.post(url, input_data, function(data){
		if (data.error) {
			$('#'+data.id).click(inviter);
			alert(data.error);
		} else {
			$('#'+data.id).attr('tag', ($('#'+data.id).attr('tag')==1 ? 0 : 1));
			$('#'+data.id).html(data.html);
			$('#'+data.id).click(inviter);
		}
	}, 'json');
}

function dectmr()
{
	if (!starttime)
		return;
		
	var ctime = new Date();
	var ctimestamp = ctime.getTime();
	
	for (i in starttime)
	{
		if (i == dmz) continue;
			
		var cdiff = parseInt( (timestamps[i] - ctimestamp) / 1000);
		var past = (cdiff < 0);
		cdiff = Math.abs(cdiff);

		var years = parseInt( Math.floor(cdiff / 31536000.0) );
		cdiff %= 31536000.0;
		
		var months = parseInt( Math.floor(cdiff / 2592000.0) );
		cdiff %= 2592000.0;
		
		var days = parseInt( Math.floor(cdiff / 86400.0) );
		cdiff %= 86400.0;
		
		var hours = parseInt( Math.floor(cdiff / 3600.0) );
		cdiff %= 3600.0;
		
		var minutes = parseInt( Math.floor(cdiff / 60.0) ); 
		cdiff %= 60.0;
		
		var seconds = parseInt(cdiff);
		
		if (typeof(smallCountdown)=='undefined') {
			if (past && !$("#cd-"+i).parent().hasClass('tockDownHolderE')) {
				$("#cd-"+i).parent().removeClass('tockDownHolder').addClass('tockDownHolderE');
				$("#desc-"+i).html('was:');
			}
			countDownItem($("#years-"+i), years, '<div class="smallUnit"><span class="unit">yr</span></div>');
			countDownItem($("#months-"+i), months, '<div class="smallUnit"><span class="unit">mo</span></div>');
			countDownItem($("#days-"+i), days, '<div class="smallUnit"><span class="unit">dy</span></div>');
			countDownItem($("#hours-"+i), hours, '<div class="smallUnit"><span class="unit">hr</span></div>');
			countDownItem($("#minutes-"+i), minutes, '<div class="smallUnit"><span class="unit">mn</span></div>');
			$("#seconds-" + i).html( seconds + '<div class="smallUnit"><span class="unit">sc</span></div> ' + (past ? '<div class="tockInTxt">ago</div>' : '') );
		} else {
			countDownSmall($("#years-"+i), years, 'yrs');
			countDownSmall($("#months-"+i), months, 'mos');
			countDownSmall($("#days-"+i), days, 'dys');
			countDownSmall($("#hours-"+i), hours, 'hrs');
			countDownSmall($("#minutes-"+i), minutes, 'mins');
			$("#seconds-" + i).html( seconds + ' secs ' + (past ? ' ago' : '') );
		}
	}
}

function countDownItem(node, value, units) {
	if (value) {
		if (node.attr('lv')!=value) {
			node.html( value + '<span class="unit">'+units+'</span>' );
			node.attr('lv', value);
		}
		if (node.css('display') == 'none') {	
			node.css('display','block');			
 		}
	} else if (node.css('display') != 'none') {
		node.css('display','none');
		node.attr('lv', value);
	}
}

function countDownSmall(node, value, units) {
	if (value) {
		if (node.attr('lv')!=value) {
			node.html( value + ' '+units+'' );
			node.attr('lv', value);
		}
		if (node.css('display') == 'inline') {	
			node.css('display','inline');			
 		}
	} else if (node.css('display') != 'none') {
		node.css('display','none');
		node.attr('lv', value);
	}
}

function checkNotes()
{
	var n = (+new Date().getTime());
	if (lastpoll < (n - 120000)) //120000
 	{
 		lastpoll = n;
		$.post('/ajax/pnot', {'j':1}, function(data){
			if (data) {
				if (data.n > 0) {
					if (!$("#not_load").hasClass('hasnots'))
						$("#not_res").remove();
						
					$("#not_load").addClass('hasnots').html('Notifications (' + data.n +')');
				} else if (data.n == 0 && $("#not_load").hasClass('hasnots')) {
					$("#not_load").removeClass('hasnots').html('No New Notifications');
					//$("#not_res").remove();
				}
				
				if (data.m > 0) {
					$("#mailbox").html('Mail ('+data.m+')');
					if ( $("#mailbox").hasClass('nomail') ) {
						$("#mailbox").removeClass('nomail');
						$("#mailbox").addClass('hasmail');
					}
				} else if (data.m == 0 && $("#mailbox").hasClass('hasmail') ) {
					$("#mailbox").removeClass('hasmail').addClass('nomail').html('Mail');
				}
			}
		}, 'json');
	}
}

function loadCalendar(req)
{
	if ($("#actual_calendar").length) {
		var request = '/ajax/calendar/';
		if (req)
			request += req;
			
		$("#actual_calendar").stop().animate({opacity: 0},250);
		$("#event_date").val('');
		
		$.get(request, function(response){
			$("#actual_calendar").html(response);
			$("#actual_calendar").stop().animate({opacity: 1},250);
			
			$(".cal_link").click(function(){
				loadCalendar($(this).attr('alt'));
			});
			
			$(".iv").click(function(){
				$(".iv").removeClass("selected");
				$(this).addClass("selected");
				
				var day = $(this).html();
				var parts = $("#calendar_title").html().split('&nbsp;');
				var date_string = parts[0] + ' ' + day + ', ' + parts[1];
				
				$(".has_focus").find('.focusable').val(date_string);
			});
			
		}, 'html');
	}
}

function myCalendar()
{
	$(".biv").each(function(){
		var id = $(this).attr('id').replace('calday', 'ctd');
		$(this).append( $("#"+id).html() );
	});
	
	$("#my_calendar td").each(function(){
		var $x = $(this).find("div");
		
		if ($x.hasClass('mt')) {
			$(this).addClass('mt');
		} else if ($x.hasClass('highlight')) {
			$(this).addClass('highlight');
		} else if ($x.hasClass('biv')) {
			$(this).addClass('biv');
			$(this).attr('title', 'Start a New Tock Here');
		}
	});
	
	/*$("td.biv").click(function(){
		$(".biv").removeClass("selected");
		$(this).addClass("selected");
		
		var day = $(this).find('p:first').html();
		var parts = $("#large_calendar_title").html().split('&nbsp;');
		var date_string = parts[0] + ' ' + day + ', ' + parts[1];

		$("#date").val(date_string);
		$("#tockForm").slideDown(250);
	});*/
	
	$("#calendar_filter").change(function(){
		var value = parseInt($("#calendar_filter option:selected").val());

		setCalendarFilter(value);
		$.getJSON('/ajax/setCalendarFilter/' + value);
	});
}

function setCalendarFilter(value)
{
	var chosen = '';	
	
	switch (value) {
		case 2: chosen = 'p.cal_mine'; break;
		case 3: chosen = 'p.cal_watched'; break;
		case 4: chosen = 'p.cal_upvoted'; break;
		case 5: chosen = 'p.cal_followed'; break;
		default:
	}
	
	if (!chosen) {
		$("p.cal_item").css({'display':'block'});
	} else {
		$("p.cal_item").css({'display':'none'});
		$(chosen).css({'display':'block'});
	}	
}

function addComment(data)
{
  if (data.error)
    return showError(data.error);
    
 	if (!data.comment)
		return;
		
	var html='<div class="comment"><div class="commentImage"><img src="';
	
	if (data.avatar) {
		html += data.avatar;
	} else {
		html += '/images/unverified.png';
	}
	
	html += '" alt="' + data.username + '" width="30" height="30" class="imagePaddingFeatured" /></div><div class="commentBody"><a href="/' + data.url + '">- ' + data.username + '</a> <span class="commentOnDate">on ' + data.date + '.</span><br/>' + data.comment + '</div>';
 	$("#comments").append(html);
	
	$("#cmt_count").html(''+(parseInt($("#cmt_count").html()) + 1));
	
	$("#nocomments").fadeOut(500);
}

function setVote(data)
{
  if (data.error)
    return showError(data.error);
    
	if (data.id) {
		var cscore = parseInt($("#sc" + data.id).html().replace(',', '').match(/-?[0-9]+/));
		
		if (data.upvote) {
			$("#up" + data.id).addClass('upvoted');
			$("#dn" + data.id).removeClass('dnvoted');
			$("#sc" + data.id).html(addCommas(cscore + parseInt(data.adjust)));
		} else if (data.dnvote)	{
			$("#up" + data.id).removeClass('upvoted');
			$("#dn" + data.id).addClass('dnvoted');
			$("#sc" + data.id).html(addCommas(cscore + parseInt(data.adjust)));
		} else  {
			$("#up" + data.id).removeClass('upvoted');
			$("#dn" + data.id).removeClass('dnvoted');
			$("#sc" + data.id).html(addCommas(cscore + parseInt(data.adjust)));
		}
		
		voting = false;
	}
}

function showError(msg)
{
  //alert(msg + '\nTODO: Replace alerts with something less annoying. (Sorry, still beta)');
  document.location.href = 'https://ticktocker.com/u/register/oops';
}

function refreshComments()
{

}

// addCommas released into public domain by Keith Jenci
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function checkVisitorTimezone()
{
	if (!$('#tzc').length)
		return;

	var offset = $('#tzc').attr('class');
	var chopped = offset.match(/tz(-|_)(\d{2})(\d{2})/i);

	if (chopped.length)
	{
		var offset = (TimezoneDetect() / 60);
		if (offset != -5) {		
			$.post('/ajax/detect_timezone', { tz:offset }, function(response) {
				$("#tzc").html(response.response);
				$("#my_tz").attr('title',response.long).html(response.short);
				$("#tzc").slideDown(200);
				if ($("#timezone").length) {
					$("#timezone").val(response.long);
				}
			}, 'json');
	
			$('.tockDateMyTime').removeClass('tockDateMyTime').addClass('tockDate');
	
			$(".tocks").each(function(){
				var id = $(this).attr('id');
				var stamp = $(this).attr('alt');
	
				var d = new Date(stamp * 1000);
				var html = '<div class="tockDateMyTime"><div class="tockTxtWhenMyTime">my time:</div> ' + d + '</div>'; 
				$(this).find('.tockDate').after(html);
			});
		}
	}
}

function popout(url, name)
{
	var w = window.open(url, name, 'status=0,toolbar=0,location=0,menubar=0,directories=0,width=510,height=250,scrollbars=0,resizable=0,');
	if (!w)
		alert('We were unable to pop this tock out. Please disable your pop-up blocker for this website and try again.');
}

//Pause countdown for an item.. Not sure why I named it dmz
function dmzThis() {
	var t = $(this);
	var f = $(this).children(":first");
	if (f.hasClass('tockCountDown')) {
		if (!f.hasClass('paused')) {
			dmz = f.attr('id').replace('cd-', '');
			f.addClass('paused');
		} else {
			dmz = '';
			f.removeClass('paused');
		}
	} else {
		if (!t.hasClass('paused')) {
			dmz = t.attr('id').replace('cdc-', '');
			t.addClass('paused');
		} else {
			dmz = '';
			t.removeClass('paused');
		}
	}
}

//See /js/licenses.txt for source of this function
function TimezoneDetect(){
    var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
    var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
    var intMonth;
    var intHoursUtc;
    var intHours;
    var intDaysMultiplyBy;

    //go through each month to find the lowest offset to account for DST
    for (intMonth=0;intMonth < 12;intMonth++){
        //go to the next month
        dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);

        //To ignore daylight saving time look for the lowest offset.
        //Since, during DST, the clock moves forward, it'll be a bigger number.
        if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
            intOffset = (dtDate.getTimezoneOffset() * (-1));
        }
    }

    return intOffset;
}

function fbpub(prompt, name, link, caption, desc, timestamp) {
	var payload = {
		"method":"stream.publish",
		//"message":"Thing from ticktocker",
		//"body":"thingamabob",
		"user_message_prompt": prompt,
		"attachment":{
			"name":name,
			"href":link,
			"caption":caption,
			"description":desc,
			"media": [{
				"type":"flash",
				"swfsrc":"http://ticktocker.com/images/countdown.swf?timestamp=" + timestamp,
				"imgsrc":"http://ticktocker.com/images/fblike.png",
				"width":"90",
				"height":"90",
				"expanded_width":"300",
				"expanded_height":"200"
			}] //*/
		}
	};
	
	fbui(payload);
}


function invitefber(uid, first, username, my_url) {
	var map = {
		"message" : "Hey " + first + ", you should follow me on TickTocker! Sign up, it's free.",
		"picture" : 'http://ticktocker.com/images/fblike.png',
		"link" : "http://ticktocker.com/" + my_url,
		"name":username + " on TickTocker.com",
		"caption":"Check out my list of events.",
		"description":'TickTocker is a community-driven social networking and scheduling tool that lets you share and keep track of events, releases, important dates and deadlines.',
	};
	
	FB.api("/"+uid+"/notes", 'post', map, function(response){
		if (!response || response.error) {
			alert('Error occured!' + response.error)
		}
	});
	
}


function fbui(payload) {
	FB.ui(payload, 
	function(response) {
	  if (!response || response.error) {
	    alert('Error occured: ' + response.error);
	  } else {
	    alert('Post ID: ' + response.id);
	  }
	}); 
}

