/*
* jQuery TinySort 1.0.4
*/
(function(b){b.tinysort={id:"TinySort",version:"1.0.4",defaults:{order:"asc",attr:"",place:"start",returns:false}};b.fn.extend({tinysort:function(h,j){if(h&&typeof(h)!="string"){j=h;h=null}var e=b.extend({},b.tinysort.defaults,j);var p={};this.each(function(t){var v=(!h||h=="")?b(this):b(this).find(h);var u=e.order=="rand"?""+Math.random():(e.attr==""?v.text():v.attr(e.attr));var s=b(this).parent();if(!p[s]){p[s]={s:[],n:[]}}if(v.length>0){p[s].s.push({s:u,e:b(this),n:t})}else{p[s].n.push({e:b(this),n:t})}});for(var g in p){var d=p[g];d.s.sort(function k(t,s){var i=t.s.toLowerCase?t.s.toLowerCase():t.s;var u=s.s.toLowerCase?s.s.toLowerCase():s.s;if(c(t.s)&&c(s.s)){i=parseFloat(t.s);u=parseFloat(s.s)}return(e.order=="asc"?1:-1)*(i<u?-1:(i>u?1:0))})}var m=[];for(var g in p){var d=p[g];var n=[];var f=b(this).length;switch(e.place){case"first":b.each(d.s,function(s,t){f=Math.min(f,t.n)});break;case"org":b.each(d.s,function(s,t){n.push(t.n)});break;case"end":f=d.n.length;break;default:f=0}var q=[0,0];for(var l=0;l<b(this).length;l++){var o=l>=f&&l<f+d.s.length;if(a(n,l)){o=true}var r=(o?d.s:d.n)[q[o?0:1]].e;r.parent().append(r);if(o||!e.returns){m.push(r.get(0))}q[o?0:1]++}}return this.pushStack(m)}});function c(e){var d=/^\s*?[\+-]?(\d*\.?\d*?)\s*?$/.exec(e);return d&&d.length>0?d[1]:false}function a(e,f){var d=false;b.each(e,function(h,g){if(!d){d=g==f}});return d}b.fn.TinySort=b.fn.Tinysort=b.fn.tsort=b.fn.tinysort})(jQuery);
/*
* jQuery Color Animations
*/
(function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(fx.state==0){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end);}
fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")";}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)
return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];return colors[jQuery.trim(color).toLowerCase()];}
function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body"))
break;attr="backgroundColor";}while(elem=elem.parentNode);return getRGB(color);};var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]};})(jQuery);

jQuery(document).ready(function() {
	// Remove the hashvar from more links
	jQuery('a.more-link').each(function(){
		var pos = this.href.indexOf('#');
		var newLink = this.href.substr(0, pos);
		this.href = newLink;
	});
	
	var order = readCookie('liveblog_sorting');
	var hashvars = getHashVars();
	
	if ( order == 'asc' || order == 'desc' ) {
		change_sorting(order);
	} else if ( hashvars['sort'] == 'asc' || hashvars['sort'] == 'desc' ) {
		change_sorting(hashvars['sort']);
	}
	
	// Get the refresh url
	var refreshUrl = jQuery('#refreshurl').text();
	
	// Check the refreshUrl exists
	if ( refreshUrl != '' ) {
	
		// Get the current refresh rate
		var grabbedRate = jQuery('#ajaxrefresh').text();
		var refresh = grabbedRate*1000;
	
		// Schedule the update, if greater than 0
		if ( refresh > 0 )
			setTimeout("updateContent('" + refreshUrl + "')", refresh);
	
		// Update the refresh notice
		if ( grabbedRate == '-1' )
			updateRefreshNote(grabbedRate);
		else
			updateRefreshNote(refresh);
	
		// Get the current most recent update
		displayNewUpdates();
	
	}
});

function change_sorting(ord) {
	createCookie('liveblog_sorting', ord, '7');
	jQuery('#main .updates > p.update').tsort({order:ord,attr:"id"});
	
	// Change the selected
	if ( ord == 'asc') {
		jQuery('.updates-order a.asc').addClass('selected');
		jQuery('.updates-order a.desc').removeClass('selected');
	} else {
		jQuery('.updates-order a.asc').removeClass('selected');
		jQuery('.updates-order a.desc').addClass('selected');
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function getHashVars()
{
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');

	for (var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}

	return vars;
}

// Keep track of the most recent update
var mostRecent = 0;

function displayNewUpdates() {
	// Check this isn't the first run through
	var firstRun;
	if ( mostRecent == 0 )
		firstRun = true;
	else
		firstRun = false;
	
	// Set a variable for the most recent update this round
	var highest = 0;
	
	// Go through each added update and display a new effect if needed
	jQuery('#main .updates p.update').each(function(i){
		// Parse just the date from the id
		var id = this.id;
		var date = id.substr(0, 10);
		
		// Set the highest value this round
		if ( highest < date )
			highest = date;
		
		// Determine if the new update is a recent update
		if ( mostRecent < date ) {
			// If this isn't the first run
			if ( !firstRun ) {
				jQuery('#' + id).hide().slideDown('slow').css({'background-color':'#dceebf'}).animate({backgroundColor:'#fff'}, 1500);
			}
		} else {
			// Set the background color to white to stop stuck updates
			jQuery('#' + id).css({'background-color':'#fff'});
		}
	});
	
	// Set the highest this round to the most recent
	mostRecent = highest;
}

// Keep track of the most recent links
var mostRecentLink = 0;

function displayNewLinks() {
	// Check this isn't the first run through
	var firstRun;
	if ( mostRecentLink == 0 )
		firstRun = true;
	else
		firstRun = false;
	
	// Set a variable for the most recent link this round
	var highest = 0;
	
	// Go through each added update and display a new effect if needed
	jQuery('#links li').each(function(i){
		// Parse just the date from the id
		var id = this.id;
		var date = id.substr(11, 21);
		
		// Set the highest value this round
		if ( highest < date )
			highest = date;
		
		// Determine if the new update is a recent update
		if ( mostRecentLink < date ) {
			// If this isn't the first run
			if ( !firstRun ) {
				jQuery('#' + id).hide().slideDown('slow').css({'background-color':'#dceebf'}).animate({backgroundColor:'#fff'}, 1500);
			}
		}
	});
	
	// Set the highest this round to the most recent
	mostRecentLink = highest;
}

// Keep track of the number of updates
var numberOfUpdates = 0;

function updateContent(url) {
	// Generate the current unix timestamp for use in the random number (prevents IE from caching)
	var foo = new Date; // Generic JS date object
	var unixtime_ms = foo.getTime(); // Returns milliseconds since the epoch
	var unixtime = parseInt(unixtime_ms / 1000);
	
	// Grab the latest updates
	jQuery.get(url, {random: unixtime},
		function(updates){
			// Check to see if the whole page of updates loaded
			if ( updates.indexOf('<span id="done"></span>') > -1 ) {
				
				// Push out the latest content to the staging area
				jQuery('#main .updates-staging').html(updates);
				
				// Check to make sure we still have the same post
				if ( jQuery('#postid').text() == jQuery('#originalid').text() ) {
					
					var currentNumberOfUpdates = jQuery('#main .updates-staging p.update').size();
					
					// Verify that we have at least one update
					if ( currentNumberOfUpdates > 0 ) {
						
						// Check that we didn't have a drop of updates by more than 50%
						if ( ( currentNumberOfUpdates >= numberOfUpdates ) || ( currentNumberOfUpdates < numberOfUpdates && (currentNumberOfUpdates/numberOfUpdates) >= 0.5 ) ) {
							
							// Update the amount of updates
							numberOfUpdates = currentNumberOfUpdates;
				
							// Get the current refresh rate
							var grabbedRate = jQuery('#main .updates-staging #ajaxrefresh').text();
							var refresh = grabbedRate*1000;
					
							// Get the current link set
							var grabbedLinks = jQuery('#main .updates-staging #links').html();
						
							// Add the new links to the sidebar
							jQuery('#aside #links ul').html(grabbedLinks);
						
							// Display the links section if not already enabled
							if ( grabbedLinks.length > 0 ) {
								if ( jQuery('#aside #links').css('display') == 'none' )
									jQuery('#aside #links').slideDown('slow').css({'background-color':'#dceebf'}).animate({backgroundColor:'#fff'}, 1500);
							} else {
								jQuery('#aside #links').hide();
							}
						
							// Determine what updates are new, edited, and deleted
							determineNewUpdates();
						
							// Clean up the staging area
							jQuery('#main .updates-staging #links').remove();
							jQuery('#main .updates-staging #postid').remove();
							jQuery('#main .updates-staging #ajaxrefresh').remove();
							jQuery('#main .updates-staging #done').remove();

							// Move the content from the staging area to the real area
							jQuery('#main .updates').prepend( jQuery('#main .updates-staging').html() );
						
							// Clear the staging area
							jQuery('#main .updates-staging').html('');

							// Get the information needed to determine order sorting
							var order = readCookie('liveblog_sorting');
							var hashvars = getHashVars();

							// Sort the updates properly
							if ( order == 'asc' || order == 'desc' ) {
								change_sorting(order);
							} else if ( hashvars['sort'] == 'asc' || hashvars['sort'] == 'desc' ) {
								change_sorting(hashvars['sort']);
							}

							// Adds the animation for new incoming updates
							displayNewUpdates();
							displayNewLinks();
						
						}
					}
				}
			}
			
			// Send a new event to Google Analytics
			var analyticsDate = convertUnixtime(mostRecent);
			pageTracker_gdgtlive._trackEvent('General', 'page_forward', analyticsDate);
		//	pageTracker_gdgt._trackEvent('General', 'page_forward', analyticsDate);
			
			// Check to make sure the refresh value has a real number, if not, set the refresh for 30 seconds
			if ( grabbedRate == '' || grabbedRate == undefined )
				refresh = 30000;
			
			// Schedule the update again, if greater than 0
			if ( refresh > 0 ) {
				setTimeout("updateContent('" + url + "')", refresh);
			}
			
			// Update the refresh notice
			if ( grabbedRate == '-1' )
				updateRefreshNote(grabbedRate);
			else
				updateRefreshNote(refresh);
		}
	);
}

// Determine what updates are new, delete old updates, and edit existing ones
function determineNewUpdates() {
	var existingUpdates = [];
	var lastUpdate;
	
	// Loop through the new updates
	jQuery.each(jQuery('#main .updates-staging > p.update'), function() {
		
		// Set the current update as the last update
		lastUpdate = this.id;
		
		// Check if the update already exists
		if ( jQuery('#main .updates .' + this.id).length > 0 ) {
			
			// Add the update to the current list
			existingUpdates[this.id] = 'y';
			
			// Update the text to the current version, if a text update
			if ( this.id.substr(11, 15) != 'image' )
				jQuery('#main .updates .' + this.id).html( jQuery(this).html() );
			
			// Remove the update from the staging area
			jQuery('#main .updates-staging .' + this.id).remove();
			
		}
		
	});
	
	// Get the information needed to determine order sorting
	var order = readCookie('liveblog_sorting');
	var hashvars = getHashVars();
	
	// Used to determine if we should start processing deletions
	var startDeleting = false;
	
	// Loop through the existing updates and remove ones that don't belong
	jQuery.each(jQuery('#main .updates > p.update'), function() {
		
		// Check how we're sorting orders
		if ( order == 'asc' || hashvars['sort'] == 'asc' ) {
			
			// Check if we're on the first update to start processing, if we aren't continue
			if ( this.id != lastUpdate && startDeleting == false )
				return;
			else if ( this.id == lastUpdate )
				startDeleting = true;
			
		} else {
		
			// Check if this is the last known update, if so, stop deleting
			if ( this.id == lastUpdate )
				return false;
		
		}
		
		// Check if the current update is in the list of existing updates, if not, remove it
		if ( existingUpdates[this.id] == undefined )
			jQuery('#main .updates .' + this.id).remove();
		
	});
	
}

function updateRefreshNote(refresh) {
	if ( refresh > 0 )
		jQuery('#coverage .note').html('Automatically refreshing, no need for F5!');
	else if ( refresh == '-1' )
		jQuery('#coverage .note').html('Manual updating, hit F5!');
	else
		jQuery('#coverage .note').html('Manual updating, hit F5!');
}

function convertUnixtime(time) {
	time = new Date(time * 1000);
	
	var hours = padNumber(time.getHours());
	var minutes = padNumber(time.getMinutes());
	var seconds = padNumber(time.getSeconds());
	
	var year = time.getFullYear();
	var day = padNumber(time.getDate());
	var month = padNumber(time.getMonth() + 1);
	
	var date = year + '/' + month + '/' + day + ' - ' + hours + ':' + minutes + ':' + seconds;
	
	return date;
}

function padNumber(number) {
	if ( number < 10 )
		number = '0' + number;
	return number;
}
