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');
	});
	
	$(".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') + '" height="70" 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);
	});
	
	$(".tockCountDown").mouseover(function(){
		dmz = $(this).attr('id').replace('cd-', '');
		$(this).addClass('paused');
	});
	
	$(".tockCountDown").mouseout(function(){
		$(this).removeClass('paused');
		dmz = '';
	});
	
	$(".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()+9;
				var offX = 10;
				$("#not_res").css( {'left':(pos.left+offX)+'px','top':(pos.top+offY)+'px'} );
				$("#not_res").slideDown(250);
			} else {
				$("#not_res").fadeOut(250);
			}
		} else {
			$("#not_load").html('<img id="notimg" src="/images/loading.gif" /> My 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()+9;
					var offX = 10;
					$("#not_res").css( {'left':(pos.left+offX)+'px','top':(pos.top+offY)+'px'} );
					$("#not_res").slideDown(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.');
     $("#cbox").prepend('<div align="center"><img src="/images/konami.jpg" /></dov>');
   });

	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!');								
	});

	checkVisitorTimezone();

	$(window).focus(checkNotes);	
	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()
{
	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);
		
		$("#years-" + i).html( (years ? years + '<span class="unit">yrs </span>' : '') );
		$("#months-" + i).html( (months ? months + '<span class="unit">mon </span>' : '') );
		$("#days-" + i).html( (days ? days + '<span class="unit">days </span>' : '') );
		$("#hours-" + i).html( (hours ? hours + '<span class="unit">hrs </span>' : '') );
		$("#minutes-" + i).html( (minutes ? minutes + '<span class="unit">min </span>' : '') );
		$("#seconds-" + i).html( seconds + '<span class="unit">sec </span> ' + (past ? '<span class="tockInTxt">ago</span>' : '') );
	}
}

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(data.n + ' New Notification(s)');
				} 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(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('0');
				}
			}
		}, '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()
{
	$("#actual_calendar").css({'display':'none'});
	
	$(".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"><p class="byline"><a href="/' + data.url + '"><img src="';
	
	if (data.avatar) {
		html += data.avatar;
	} else {
		html += '/images/unverified.png';
	}
	
	html += '" alt="' + data.username + '" width="50" height="50" class="cmt_avatar" /> ' + data.username + '</a> on ' + data.date + '.</p><p class="comment_body">' + data.comment + '</p></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)');
}

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 d = new Date();
		var aoffset = (d.getTimezoneOffset() / 60);
		var soffset = parseInt(chopped[2]) + parseInt(chopped[3] / 60);
		if (chopped[1] == '-')
			soffset = -soffset;

		//alert(soffset + ' => ' + aoffset);
	}
}

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.');
}
