//right now we have 7 meter images, change this if we add more
var num_meters = 13;

//time before we hide the info divs (in ms)
var slideTimeout = 10000;

//threshold for voting
var vote_threshold = 5;

//enable debug mode to not show the "already voted" message
debug = false;

var weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
var topten = [];
var comictags = null;

$().ready(function() {

	$('.ellipsis').each(ellipsis);

	$("#tagInput").autocomplete(
		"search.php",
		{
			delay:10,
			minChars:2,
			matchSubset:1,
			matchContains:1,
			cacheLength:10,
			formatItem:formatItem,
			autoFill:true
		}
	);
	
	$("#favoriteInput").autocomplete(
		"searchFavorite.php",
		{
			delay:10,
			minChars:2,
			matchSubset:1,
			matchContains:1,
			cacheLength:10,
			formatItem:formatItem,
			autoFill:true
		}
	);
	
	$("#tagInput").keypress(function(e) {
		var keychar = String.fromCharCode(e.which);
		var numcheck = /[a-z]/;
		return numcheck.test(keychar) || e.which == 8 || e.which == 13 || e.which == 0;
	});
});

function formatItem(row) {
	return row[0];
}


		
function showTagBox(){

	$('#tagInput').show(); 
	
	$('#tagLink').hide(); 
	
	$('#tagInput').focus(); 

}

function hideTextBox(){

	$('#tagInput').hide(); 
	
	$('#tagInput').val('');
	
	$('#tagLink').show(); 

}

var lastDiv = null;
var lastTimeout = null;
var wait = false;

function infoClick(divId)
{
	var div = $("#"+divId);
	div.find(".ajaxinfo").hide();
	div.find(".info").show();
	
	if(lastDiv != null && lastDiv.attr('id') != div.attr('id'))
		lastDiv.find('.dropdown').slideUp();		
	if(lastTimeout != null)
	    clearTimeout(lastTimeout);
	
	div.find(".dropdown").slideDown();
	lastDiv = div;

	lastTimeout = setTimeout("$('#'+'"+divId+" .dropdown').slideUp();", slideTimeout);
}

function voteClick(vote, divId)
{
	if(wait) return;
	
	var div = $("#"+divId);
	var comicId = div.attr('class');
	
	var infodiv = div.find(".ajaxinfo");
	infodiv.show();	
	div.find(".info").hide();
	
	if(lastDiv != null && lastDiv.attr('id') != div.attr('id'))
		lastDiv.find('.dropdown').slideUp();		
	if(lastTimeout != null)
	    clearTimeout(lastTimeout);

	var choice = vote==0?'no':'yes';
	
	infodiv.html('Are you sure you want to vote	' + choice + '?  &nbsp; \
							<a href="#" onClick="doVote('+vote+',\''+divId+'\','+comicId
							+'); return false;" class="noVisited" style="text-decoration: underline;">Okay</a>&nbsp;&nbsp;<a href="#" onClick="$(\'#'
							+divId+' .dropdown\').slideUp(); return false;"  class="noVisited" style="text-decoration: underline;">Cancel</a>');
	
	div.find('.dropdown').slideDown();
	lastDiv = div;
}

function doVote(vote, divId, comicId)
{
	var div = $("#"+divId);
	var key = $("#key").text();
	div.find(".info").hide();
	
	var infodiv = div.find(".ajaxinfo");
	infodiv.show();
	infodiv.html('&nbsp;');
	infodiv.addClass('progressbar');

	$.ajax({
		url: 'includes/vote.php',
		type: 'POST',
		data: {	'id':  comicId,
				'v':   vote,
				'key': key},
		div: div,
		infodiv: infodiv,
		comicId: comicId,
		vote: vote,
		jsonback: topten,
		success: voteCallback,
		error: voteError
	});

	return true;
}

function voteError(response)
{
	this.infodiv.removeClass('progressbar')
	this.infodiv.html('Network error.');

	lastDiv = this.div;
	lastTimeout = setTimeout("$('#'+'"+this.div.attr('id')+" .dropdown').slideUp();", slideTimeout);	
}

function voteCallback(response)
{
	this.infodiv.removeClass('progressbar');
	
	if(!debug && response.charAt(0) != '1')
	{
		this.infodiv.html(response);
		lastTimeout = setTimeout("$('#'+'"+this.div.attr('id')+" .dropdown').slideUp();", 5000);
		lastDiv = this.div;
		return;
	}
		
	wait = true;
	var comicId = this.comicId;
	var comicInfo = $.grep(this.jsonback, function(v, i)
	{
		if(comicId == v.comicId)
			return true;		
		else
			return false;
	})[0];
	
	var changed = false;
	if(comicInfo == null)
	{
		comicInfo = Object();
		comicInfo.no = parseInt(this.div.find(".no").text());
		comicInfo.yes = parseInt(this.div.find(".yes").text());
		comicInfo.comicId = comicId;
		comicInfo.weekday = null;
		
		if(this.vote == 0)
			comicInfo.no++;
		else
			comicInfo.yes++;
		
		comicInfo.ratio = comicInfo.yes/(comicInfo.yes+comicInfo.no);
	}
	else
	{
		comicInfo.no = parseInt(comicInfo.no);
		comicInfo.yes = parseInt(comicInfo.yes);
		if(this.vote == 0)
			comicInfo.no++;
		else
			comicInfo.yes++;
		comicInfo.ratio = comicInfo.yes/(comicInfo.yes+comicInfo.no);
		comicInfo.tags = comictags[comicInfo.comicId];
		changed = sortComics('topTen', this.jsonback, comicId, this.div);
	}
	
	
	if(!changed)
	{
		regenInfo(comicInfo);
		infoClick(this.div.attr('id'));
	}
	
	wait = false;
}
function sortComics(tableclass, jsonback, comicId, inputdiv)
{
	var topdivs = $("#topTen");
	var changed = false;
	
	if(topdivs.length > 0)
	{
		jsonback.sort(function(a,b)
		{
			var r = b.ratio - a.ratio;
			if(r == 0)
				r = (parseInt(b.yes)-parseInt(b.no))-(parseInt(a.yes)-parseInt(a.no));
			if(r == 0)
				r = b.date - a.date;
				
			return r;
		});
		
		var i=0;
		topdivs.children().each(function()
		{
			var div = $(this);
			if(div.attr('class') != jsonback[i].comicId)
			{
				div.attr('class', 'refreshInfo');
				div.attr('i', i);
				changed = true;
			}
			
			i++;
		});
		
		if(changed)
		{
			inputdiv.find('.dropdown').slideUp(function()
			{
				this.a = function(jsonback, comicId, inputdiv)
				{
					refreshItems(jsonback, comicId, inputdiv);
				};
				
				this.a(jsonback, comicId, inputdiv);
			});
		}
	}	
	return changed;
	
}

function refreshItems(jsonback, comicId, inputdiv)
{
	var meterdivs = $('.refreshInfo .meter');
	var titledivs= $('.refreshInfo .ellipsis');
	
	meterdivs.fadeOut(500, function()
	{
		this.a = function(jsonback)
		{
			var div = $(this);
			var i = div.parents('.refreshInfo').attr('i');
			setMeter(div, jsonback[i]);
			div.fadeIn(500);
		};
		this.a(jsonback);
		
	});

	titledivs.fadeOut(500, function()
	{
		this.a = function(jsonback, comicId, inputdiv)
		{
			var div = $(this);
			var cdiv = div.parents('.refreshInfo');
			var i = cdiv.attr('i');
			cdiv.attr('class',''+jsonback[i].comicId);
			regenInfo(jsonback[i]);
			div.html('<a href="'+jsonback[i].url+'">'+jsonback[i].comic+' - <span class="secondLinks">'+jsonback[i].title+'</span></a>');
			div.fadeIn(500, function() { $(this).each(ellipsis); });
			if(jsonback[i].comicId == comicId)
				if(inputdiv.attr('class') == comicId)
					infoClick(inputdiv.attr('id'));
				else
					infoClick(cdiv.attr('id'));
		};
		this.a(jsonback, comicId, inputdiv);
		
	});
}

function regenInfo(comicInfo)
{
	var comics = $('.'+comicInfo.comicId);
	comics.find('.yes').text(comicInfo.yes);
	comics.find('.no').text(comicInfo.no);

	var day = 0;
	day = comicInfo.weekday;
	if(day == null)
	{
		var d = new Date();
		d.setTime(comicInfo.date*1000-18000000);
		var day = 0;
		day = d.getDay();
		comics.find(".day").text(weekdays[day]);
	}

	if(comicInfo.comment_count)
		comics.find(".commentLink").attr('href','comments.php?id='+comicInfo.comicId).text('Comments: '+comicInfo.comment_count);
	if(comicInfo.tags)
		comics.find('.tags').html(comicInfo.tags);

	setMeter(comics.find('.meter'), comicInfo)
}

function setMeter(meterDiv, comicinfo)
{
	if(comicinfo.yes+comicinfo.no >= vote_threshold)
	{
		var i = getMeterNumber(comicinfo.ratio, num_meters);
	
		meterDiv.attr('src','images/meter/meterSmall'+i+'.png');
		meterDiv.attr('alt',num_meters-(i-1)+'/'+num_meters);
	}
}

function getMeterNumber(ratio, maxmeter)
{
	var r = ratio * maxmeter;
	for(var i=1; i <= maxmeter; i++)
	{
		if(r <= i)
			return maxmeter-(i-1);
	}

	return maxmeter;
}

function ellipsis(){
	var div = $(this);
	div.css({marginRight: '-10000px'});
	var w = div.width() - 10000;
	div.html('<span>'+ $(this).html() +'</span>');
	var span = div.children();
	var comicTitle = span.find("span");
	var origTitle = comicTitle.html();
	
	if(span.width()>=w)
	{
		var begin=0;
		var end=origTitle.length;
		while(true) {
			var s = begin + Math.floor((end-begin)/2);			
			comicTitle.html(origTitle.substr(0, s) + "...");
			
			if(s == begin)
				break;
			else if(span.width()>=w) 
				end = s;
			else
				begin = s;
		}
		
		comicTitle.attr("title",origTitle);
	}

	div.css({marginRight: ''});
}

function shownews(newsinfo)
{
	var entry = newsinfo.feed.entry[0];
	var postdate = entry.published.$t;

	var cdyear = postdate.substring(0,4);
	var cdmonth = postdate.substring(5,7);
	var cdday = postdate.substring(8,10);

	var myDate=new Date();
	myDate.setFullYear(cdyear,cdmonth-1,cdday);
	var today = new Date();
	today.setDate(today.getDate()-30);

	if(today > myDate) return;

	$('#newspost').show();
	$('#newstitle').html('<span class="underlineLinks"><a href="'+newsinfo.feed.entry[0].link[4].href+'">News: '+newsinfo.feed.entry[0].title.$t+'</a></span>');
	$('#news').html(newsinfo.feed.entry[0].content.$t.replace("<br />", " "));
	var txt = '<span>'+$('#news').text().replace('\n', ' ')+'</span> (<a href="'+newsinfo.feed.entry[0].link[4].href+'" class="noVisited">read more</a>)';
	$('#news').html(txt);
	$('#news').each(ellipsis);
	
}

function favoriteClick(divId, siteId)
{
	if(wait) return;
	
	var div = $("#"+divId);
	var infodiv = div.find(".ajaxinfo");
	infodiv.show();	
	div.find(".info").hide();
	
	if(lastDiv != null && lastDiv.attr('id') != div.attr('id'))
		lastDiv.find('.dropdown').slideUp();		
	if(lastTimeout != null)
	    clearTimeout(lastTimeout);
	
	infodiv.html(".ajaxinfo").html('Are you sure you want to add this site to your favorites?<br /><a style="text-decoration: underline;" onclick="doAddFav(\''+divId+'\', '+siteId+'); return false;" href="#">Okay</a>&nbsp;&nbsp;&nbsp;<a style="text-decoration: underline;" onClick="$(\'#'+divId+' .dropdown\').slideUp(); return false;" href="#">Cancel</a>');
	div.find('.dropdown').slideDown();
	lastDiv = div;

}


function doAddFav(divId, siteId)
{
	var div = $("#"+divId);
	div.find(".info").hide();
	
	var infodiv = div.find(".ajaxinfo");
	infodiv.show();
	infodiv.html('&nbsp;');
	infodiv.addClass('progressbar');

	$.ajax({
		url: 'includes/fav.php',
		type: 'POST',
		data: {	'id':  siteId },
		div: div,
		infodiv: infodiv,
		siteId: siteId,
		success: favCallback,
		error: voteError
	});

	return false;
}

function favCallback(response)
{	
	this.infodiv.removeClass('progressbar')
	
	if(response.charAt(0) != '1')
		this.infodiv.text(response);
	else
		this.infodiv.text('Favorited!');
	
	lastTimeout = setTimeout("$('#'+'"+this.div.attr('id')+" .dropdown').slideUp();", slideTimeout);	
}

function checkFavorite(siteId)
{	
	$('#favStatus').show();
	$('#favLink').hide();

	$.ajax({
		url: 'includes/fav.php',
		type: 'POST',
		data: {	'id':  siteId },
		success: checkFavCallback,
		error: checkFavError
	});

	return false;
}

function checkFavCallback(response)
{
	if(response.charAt(0) == '1')
	{
		$('.fav').attr('alt', 'ok');
		$('.fav').attr('src', 'images/check.png');
	}
	else
	{
		$('#favStatus').text(response);
	}
}

function checkFavError(response)
{
	$('#favStatus').text("Network Error, please try again.");
		
}

