/*global jQuery, window*/

/* ===========================================================================
 *
 * JQuery URL Parser
 * Version 1.0
 * Parses URLs and provides easy access to information within them.
 *
 * Author: Mark Perkins
 * Author email: mark@allmarkedup.com
 *
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_url_parser/
 *
 * ---------------------------------------------------------------------------
 *
 * CREDITS:
 *
 * Parser based on the Regex-based URI parser by Steven Levithan.
 * For more information (including a detailed explaination of the differences
 * between the 'loose' and 'strict' pasing modes) visit http://blog.stevenlevithan.com/archives/parseuri
 *
 * ---------------------------------------------------------------------------
 *
 * LICENCE:
 *
 * Released under a MIT Licence. See licence.txt that should have been supplied with this file,
 * or visit http://projects.allmarkedup.com/jquery_url_parser/licence.txt
 *
 * ---------------------------------------------------------------------------
 * 
 * EXAMPLES OF USE:
 *
 * Get the domain name (host) from the current page URL
 * jQuery.url.attr("host")
 *
 * Get the query string value for 'item' for the current page
 * jQuery.url.param("item") // null if it doesn't exist
 *
 * Get the second segment of the URI of the current page
 * jQuery.url.segment(2) // null if it doesn't exist
 *
 * Get the protocol of a manually passed in URL
 * jQuery.url.setUrl("http://allmarkedup.com/").attr("protocol") // returns 'http'
 *
 */

jQuery.url = function ()
{
	var segments = {};
	var parsed = {};

    /**
    * Options object. Only the URI and strictMode values can be changed via the setters below.
    */
	var options = {
	
		url : window.location, // default URI is the page in which the script is running
		
		strictMode: false, // 'loose' parsing by default
	
		key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], // keys available to query 
		
		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
		}
		
	};
	
	/**
	* Deals with the parsing of the URI according to the regex above.
	* Written by Steven Levithan - see credits at top.
	*/		
	var parseUri = function ()
	{
		str = decodeURI(options.url);
		
		var m = options.parser[options.strictMode ? "strict" : "loose"].exec(str);
		var uri = {};
		var i = 14;

		while (i--) {
			uri[options.key[i]] = m[i] || "";
		}

		uri[options.q.name] = {};
		uri[options.key[12]].replace(options.q.parser, function ($0, $1, $2) {
			if ($1) {
				uri[options.q.name][$1] = $2;
			}
		});

		return uri;
	};

    /**
     * Returns the value of the passed in key from the parsed URI.
     * 
     * @param string key The key whose value is required
     */		
	var key = function (key)
	{
		if (!parsed.length)
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		} 
		if (key === "base")
		{
			if (parsed.port !== null && parsed.port !== "")
			{
				return parsed.protocol + "://" + parsed.host + ":" + parsed.port + "/";	
			}
			else
			{
				return parsed.protocol + "://" + parsed.host + "/";
			}
		}
	
		return (parsed[key] === "") ? null : parsed[key];
	};
	
	/**
     * Returns the value of the required query string parameter.
     * 
     * @param string item The parameter whose value is required
     */		
	var param = function (item)
	{
		if (!parsed.length)
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		}
		return (parsed.queryKey[item] === null) ? null : parsed.queryKey[item];
	};

    /**
     * 'Constructor' (not really!) function.
     *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. 
     */	
	var setUp = function ()
	{
		parsed = parseUri();
		
		getSegments();	
	};
	
    /**
     * Splits up the body of the URI into segments (i.e. sections delimited by '/')
     */
	var getSegments = function ()
	{
		var p = parsed.path;
		segments = []; // clear out segments array
		segments = parsed.path.length == 1 ? {} : (p.charAt(p.length - 1) == "/" ? p.substring(1, p.length - 1) : path = p.substring(1) ).split("/");
	};
	
	return {
		
	    /**
	     * Sets the parsing mode - either strict or loose. Set to loose by default.
	     *
	     * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
	     */
		setMode : function (mode)
		{
			strictMode = mode == "strict" ? true : false;
			return this;
		},
		
		/**
	     * Sets URI to parse if you don't want to to parse the current page's URI.
		 * Calling the function with no value for newUri resets it to the current page's URI.
	     *
	     * @param string newUri The URI to parse.
	     */		
		setUrl : function (newUri)
		{
			options.url = newUri === undefined ? window.location : newUri;
			setUp();
			return this;
		},		
		
		/**
	     * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
		 * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
		 *
		 * If no integer is passed into the function it returns the number of segments in the URI.
	     *
	     * @param int pos The position of the segment to return. Can be empty.
	     */	
		segment : function (pos)
		{
			if (!parsed.length)
			{
				setUp(); // if the URI has not been parsed yet then do this first...	
			} 
			if (pos === undefined)
			{
				return segments.length;
			}
			return (segments[pos] === "" || segments[pos] === undefined) ? null : segments[pos];
		},
		
		attr : key, // provides public access to private 'key' function - see above
		
		param : param // provides public access to private 'param' function - see above
		
	};
	
}();

/* =========================================================================== */

var win = null, sideStatus = 1, vpWidth, vpMargin, returnVal, resetWRtext = "               Are you sure you want to do this?\nThis can take a long time with a lot of racers in the team\n  as this script uses free pubstats, 5 seconds per racer!";

// Viewport Dimensions
window.viewpoint =
{
    height: function () {
        return $(window).height();
    },
   
    width: function () {
        return $(window).width();
    },
   
    scrollTop: function () {
        return $(window).scrollTop();
    },
   
    scrollLeft: function () {
        return $(window).scrollLeft();
    }
};

// Basic hideDiv routine but also replacing text in the URL
function toggleLayer(whichLayer, whichLink) {
	var elem = $('#' + whichLink), etext;
	$('#' + whichLayer).toggle();
	etext = (elem.text() === 'Collapse') ? 'Expand' : 'Collapse';
	elem.text(etext);
}

// Basic hideDiv routine
function toggleDiv(whichLayer) {
	$('#' + whichLayer).toggle();
}

// Open new window but close any already open
function NewBrowserWindow(url) {
	if (win !== null) {
		win.close();
	}
	var settings = 'width=800, height=600, screenX=0, screenY=0, left=0, top=0, resizable=yes, scrollbars=auto, toolbar=no, location=no, directories=no, status=no, menubar=no, copyhistory=no';
	win = window.open(url, "RaceProgress" + new Date().getTime(), settings);
	win.focus();
}

// Simple routine to display text in an alert
function disp_confirm(url_location, disp_text) {
	var confirm_res = confirm(disp_text);
	if (confirm_res === true) {
		window.location = url_location;
	}
}

// Routine to display LFS Progress in its own pop-up window
function progress(url) {
	var settings = 'width=800,height=600,screenX=0,screenY=0,left=0,top=0,resizable=yes,scrollbars=auto,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no';
	win = window.open("", "Progress" + new Date().getTime(), settings);
	win.document.clear();
	win.document.open();
	win.document.write("<html><head><title>LFS Progress</title></head>\n<body style=\"margin: 0; padding: 0;\"><center>\n");
	win.document.write("<iframe src=\"" + url + "\" width=\"100%\" height=\"100%\"></iframe>\n</center></body></html>");
	win.document.close();
	win.focus();
}

// Routine to display LFS Remote in its own pop-up window
function remote(url) {
	var settings = 'width=800,height=750,screenX=0,screenY=0,left=0,top=0,resizable=yes,scrollbars=auto,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no';
	win = window.open("", "Remote" + new Date().getTime(), settings);
	win.document.clear();
	win.document.open();
	win.document.write("<html><head><title>LFS Remote</title></head>\n<body style=\"margin: 0; padding: 0;\"><center>\n");
	win.document.write("<iframe src=\"" + url + "\" width=\"100%\" height=\"100%\"></iframe>\n</center></body></html>");
	win.document.close();
	win.focus();
}

// Routine to display a screenshot in a pop-up window after closing previous windows
function screenshot(name, width, height) {
	if (win !== null) {
		win.close();
	}
	var settings = 'width=' + width + ',height=' + height + ',screenX=0,screenY=0,left=0,top=0,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no';
	win = window.open("", "screenshot", settings);
	win.document.clear();
	win.document.open();
	win.document.write("<html><head><title>Sonicrealms Racing Screenshots</title></head>\n<body style=\"margin: 0; padding: 0;\"><center>\n");
	win.document.write("<a href=\"#\" onClick=\"window.close()\"><img src=\"http://www.sonicrealmsracing.co.uk/images/" + name + "\" alt=\"" + name + "\" border=0></a>\n</center></body></html>");
	win.document.close();
	win.focus();
}

// Routine to display a slideshow in a pop-up window  after closing any previous pop-up windows
function slideshow(Images) {
	if (win !== null) {
		win.close();
	}
	var i = 0, NumImg = Images.length, settings = 'width=800,height=640,screenX=0,screenY=0,left=0,top=0,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no';
	win = window.open("", "screenshot", settings);
	win.document.clear();
	win.document.open();
	win.document.write("<html><head><title>Sonicrealms Racing Slideshow</title>\n<script type=\"text/javascript\">\nNewImg = new Array (\n");
	for (i = 0; i < NumImg; i = i + 1) {
		win.document.write("\"http://www.sonicrealmsracing.co.uk/images/" + Images[i] + "\"");
		if (i < NumImg - 1) {
			win.document.write(",\n");
		}
	}
	win.document.write("\n);\nvar ImgNum = 0;\nvar ImgLength = NewImg.length;\nvar delay = 6000;\nvar run;\n");
	win.document.write("var preLoad = new Array();for (i = 0; i < ImgLength; i++){preLoad[i] = new Image();preLoad[i].src = NewImg[i];}\n");
	win.document.write("function chgImg() {if (document.images) {ImgNum = ImgNum + 1;if (ImgNum == ImgLength) {ImgNum = 0;}document.slideshow.src = preLoad[ImgNum].src;\ndocument.getElementById(\"sstext\").innerHTML = \"Displaying slideshow picture \"+(ImgNum+1)+\" of \"+ImgLength;}}\n");
	win.document.write("run = setInterval(\"chgImg()\", delay);\n");
	win.document.write("\n<\/script>\n<style type=\"text/css\">html, body {font-family: tahoma, verdana, arial, helvetica, sans-serif;font-size: 0.9em;background-color: black;color: white;}</style></head>\n");
	win.document.write("<body style=\"margin: 0; padding: 0;\"><center>\n<a href=\"#\" onClick=\"window.close()\">");
	win.document.write("<img src=\"http://www.sonicrealmsracing.co.uk/images/" + Images[0] + "\" name=\"slideshow\" alt=\"Slideshow Images\" border=0></a>\n");
	win.document.write("<p id=\"sstext\">Displaying slideshow picture 1 of " + NumImg + "</p></center></body></html>");
	win.document.close();
	win.focus();
}

// Basic mouseover toggle class
function sfHover() {
	$('#navbar li').mouseover(function () {
		$(this).toggleClass('sfhover');
	});
}

// Functions to initialise tooltips
function initServersTooltip() {
	$("#servers a[title]").tooltip({position: "top center", delay: 0, opacity: 0.8, tip: '.tooltip', lazy: false}).dynamic();
	$("#servers img[title]").tooltip({position: "top center", delay: 0, opacity: 0.8, tip: '.tooltip', lazy: false}).dynamic();
}

function initUsersTooltip() {
	$("#users a[title]").tooltip({position: "top center", offset: [-7, 0], delay: 0, opacity: 0.8, tip: '.tooltip', lazy: false}).dynamic();
	$("#users img[title]").tooltip({position: "top center", offset: [-7, 0], delay: 0, opacity: 0.8, tip: '.tooltip', lazy: false}).dynamic();
}

function initPayPalTooltip() {
	$("#paypal[title]").tooltip({position: "top center", offset: [-7, 0], delay: 0, opacity: 0.8, tip: '.tooltip', lazy: false}).dynamic();
}

function initLeagueTooltip() {
	$("#content_container a.hoverhelp[title]").tooltip({position: "center right", offset: [0, 0], delay: 0, opacity: 0.9, tip: '.laptimett', lazy: false}).dynamic();
}

function initLeaguePrizeTip() {
	$("#league_tbl_inner td.prize[title]").tooltip({position: "top center", offset: [-7, 0], delay: 0, opacity: 0.85, tip: '.prizetip', lazy: false}).dynamic();
}

function initForumInfo() {
	$("#login a.[title]").tooltip({position: "top center", offset: [-7, 0], delay: 0, opacity: 0.8, tip: '.logintip', lazy: false}).dynamic();
}

function initLeagueLapTimes() {
	var getCommands, carid;
	$("#content_container p.event span.caricon a").click(function (e) {
		$('#content_container p.event span.caricon a.active').removeClass('active');
		getCommands = $(this).attr("href").split("?",2);
		carid = getCommands[1].split("=",2);
		$('#loading_message').fadeIn('300');
		$(this).addClass('active');
		$.get("league_ajax_laptimes.php?carid=" + carid[1], function (data) {
			$('#current_event_inner').html(data);
			initLeagueTooltip();
			$('#loading_message').fadeOut('300');
		});
		return false;
	});
}

function initPrevLapTimes() {
	var getCommands, splitCmds, carid, trackid, leagueid;
	$("#content_container p.prev_event span.caricon a").click(function (e) {
		$('#content_container p.prev_event span.caricon a.active').removeClass('active');
		getCommands = $(this).attr("href").split("?",2);
		splitCmds = getCommands[1].split("&",3);
		carid = splitCmds[0].split("=",2);
		trackid = splitCmds[1].split("=",2);
		leagueid = splitCmds[2].split("=",2);
		$('#loading_message1').fadeIn('300');
		$(this).addClass('active');
		$.get("league_ajax_laptimes.php?previd=" + carid[1] + "&trackid=" + trackid[1] + "&leagueid=" + leagueid[1], function (data) {
			$('#previous_event_inner').html(data);
			initLeagueTooltip();
			$('#loading_message1').fadeOut('300');
		});
		return false;
	});
}

function initLatestTooltip() {
	$("div#latestpb").scrollable({vertical: true, size: 3}).circular().navigator(".pbnavi").mousewheel(); /* .find("a[title]").tooltip({tip: '#latestpbtip', cancelDefault: true}).autoscroll({steps: 3, interval: 20000} */
	$("div#latestpb .items a[title]").tooltip({tip: '#latestpbtip', cancelDefault: true, lazy: false}).mouseover( function (e) {
		var offset = $(this).offset();
		$('#latestpbtip').css('left', (e.pageX - offset.left + 35) + 'px');
	}).mousemove( function (e) {
		var offset = $(this).offset();
		$('#latestpbtip').css('left', (e.pageX - offset.left + 35) + 'px');
	});
	$("div#latestposts").scrollable({vertical: true, size: 3}).circular().navigator(".lpnavi").mousewheel(); /* .find("a[title]").tooltip({tip: '#newstip', cancelDefault: true}) */
	$("div#latestposts .items a[title]").tooltip({tip: '#newstip', cancelDefault: true, lazy: false}).mouseover( function (e) {
		var offset = $(this).offset(), addWidth = $('#latestpb').width();
		$('#newstip').css('left', (e.pageX - offset.left + addWidth + 30) + 'px');
	}).mousemove( function (e) {
		var offset = $(this).offset(), addWidth = $('#latestpb').width();
		$('#newstip').css('left', (e.pageX - offset.left + addWidth + 30) + 'px');
	});
	$("div#events").scrollable({vertical: true, size: 3}).circular().navigator(".enavi").mousewheel();
}

// Function called every x seconds on index page
function grabFile(file) {
	if (sideStatus === 1) {
		$.get("right_login.php", function (data) {
			$('#login').html(data);
			sideStatus = 2;
		});
	} else if (sideStatus === 2) {
		$.get("right_servers.php", function (data) {
			$('#servers').html(data);
			initServersTooltip();
			sideStatus = 3;
		});
	} else if (sideStatus === 3) {
		$.get("right_users.php", function (data) {
			$('#users').html(data);
			initUsersTooltip();
			sideStatus = 4;
		});
	} else if (sideStatus === 4) {
		$.get("index_active.php", function (data) {
			$('#latest_wrapper').html(data);
			initLatestTooltip();
			sideStatus = 5;
		});
	} else if (sideStatus === 5) {
		$.get("update_cache.php", function () {
			sideStatus = 1;
		});
	}

	/* Rotate banner images */
	$('#banrot img').fadeTo(1000, 0.01, function () {
		$('#banrot').load('right_rotate.php', function () {
			$('#banrot img').css('opacity',0.01);
			$('#banrot img').fadeTo(1000, 1);
		});
	});
}

// Set page margins based on viweport size
function setViewPort() {
	var vpWidth = $(window).width() - 16;
	if (vpWidth < 1200 && vpWidth >= 990) {
		vpMargin = Math.floor((vpWidth - 880) / 2);
		$('#page').css('min-width', vpWidth + 'px');
		$('#wrapper').css('margin', '-149px ' + vpMargin + 'px 0');
		$('#footer').css('margin', '0 ' + vpMargin + 'px 0 ' + Math.abs(vpMargin + 33) + 'px');
	} else if (vpWidth < 990) {
		$('#page').css('min-width', '990px');
		$('#wrapper').css('margin', '-149px 55px 0');
		$('#footer').css('margin', '0 55px 0 88px');
	}
}
function resizeWindow( e ) {
	var newWindowWidth = $(window).width();
	$("#container").css("min-height", newWindowHeight );
}

/*******************
** Document Ready **
*******************/
$(document).ready(function () {

	setViewPort();
	$(window).bind("resize", setViewPort);
	$.get("update_cache.php", function (data) {
		if (data == 'True') {
			$.get("right_servers.php", function (data) {
				$('#servers').html(data);
				initServersTooltip();
			});
			$.get("right_users.php", function (data) {
				$('#users').html(data);
				initUsersTooltip();
			});
		} else {
			initServersTooltip();
			initUsersTooltip();
		}
	});

	// Initialise Tooltips
	initPayPalTooltip();
	if ($("div#latestpb").length > 0) {
		initLatestTooltip();
	}

	$('#resetwr').click(function () {
		disp_confirm('compare_resetwr.php', resetWRtext);
		return false;
	});

	// Sonicrealms Logo pop-up
	$("#logo[title]").tooltip({position: "center right", offset: [-18, 10], delay: 300, opacity: 0.8, tip: '.tooltip', lazy: false, effect: 'toggle', predelay: 500}).dynamic();
	
	// Hotlap League Donations
	$('#league_fund a[title]').tooltip({position: "center left", offset: [-30, -5], delay: 300, opacity: 0.8, tip: '.tooltip', lazy: false, effect: 'toggle', predelay: 500}).dynamic();
	$('#league_fund a[rel]').overlay({absolute: true, effect: 'apple', top: 220});
	$('#league_fund span.small').mouseover(function () {
		$('#server_popup').css('display', 'block');
	}).mouseout(function () {
		$('#server_popup').css('display', 'none');
	});

	// League Lap Times Tooltip
	initLeagueTooltip();

	// League event lap times
	initLeagueLapTimes();
	initPrevLapTimes();

	// League Prize Tooltip
	initLeaguePrizeTip();

	// Login area tooltip
	initForumInfo();

	// Ventrillo Pop-up
	$('#vent').click(function () {
		var settings = 'width=250,height=300,screenX=0,screenY=0,left=0,top=0,resizable=yes,scrollbars=auto,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no';
		win = window.open("", "Vent" + new Date().getTime(), settings);
		win.document.clear();
		win.document.open();
		win.document.write("<html><head><title>Ventrilo Status</title></head>\n<body style=\"margin: 0; padding: 0;\"><center>\n");
		win.document.write("<iframe src=\"http://vspy.guildlaunch.net/srv/minispy.php?Address=hydrogen.typefrag.com&Port=39845&J=&Scroll=&T=8&E=&Main=Sonicrealms Racing&Color=888888&S=&C=&U=&Names=&Compact=\" width=\"100%\" height=\"100%\"></iframe>\n</center></body></html>");
		win.document.close();
		win.focus();
		return false;
	});
	$('#tspeak').click(function () {
		var settings = 'width=164,height=287,screenX=0,screenY=0,left=0,top=0,resizable=yes,scrollbars=auto,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no';
		win = window.open("", "Vent" + new Date().getTime(), settings);
		win.document.clear();
		win.document.open();
		win.document.write("<html><head><title>Ventrilo Status</title></head>\n<body style=\"margin:0;padding:0;\"><center>\n");
		win.document.write("<a href=\"http://www.tsviewer.com/index.php?page=ts_viewer&ID=915120\"><img src=\"http://www.tsviewer.com/promotion/dynamic_sig/sig.php/clan160x283_simr/915120.png\" alt=\"Sonicrealms Racing TeamSpeak Viewer\" /></a></center></body></html>");
		win.document.close();
		win.focus();
		return false;
	});
	// Twitter Pop-up
	$('#twitter').click(function () {
		var settings = 'width=258,height=390,screenX=0,screenY=0,left=150,top=130,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no';
		win = window.open("twitter.php", "Twitter" + new Date().getTime(), settings);
		win.focus();
		return false;
	});
	$('#toggle').live("click", function () {
		$('#upload-9').toggle('slow');
		return false;
	});
	$('#show').live("click", function (event) {
		var toLoad = 'right_users.php' + $(this).attr('href');
		function showNewContent() {
			$('#users').slideDown(1500, initUsersTooltip);
		}
		function hideLoader() {
			$('#load').fadeOut('normal', showNewContent);
		}
		function loadContent() {
			$('#users').load(toLoad, '', hideLoader);
		}
		function showLoading() {
			$('#load').fadeIn('normal', loadContent);
		}

		$('#users').slideUp(1500, showLoading);
		if ($(this).attr('href') === '?usersmax=Hide')
		{
			$('a#show').attr('href', '?usersmax=Show');
			$('a#show').attr('title', 'Show whole team');
			$('a#show').html('<img src="images/expand.png" alt="Show whole team" />');
		}
		else if ($(this).attr('href') === '?usersmax=Show')
		{
			$('a#show').attr('href', '?usersmax=Hide');
			$('a#show').attr('title', 'Show minimum team');
			$('a#show').html('<img src="images/contract.png" alt="Show less team" />');
		}
		return false;
	});

	$('a.morenews').live("click", function (event) {
		$.url.setUrl($(this).attr('href'));
		var openNews = $.url.param("opennews"), closeNews = $.url.param("closenews"), toLoadNews = 'news_story.php' + $(this).attr('href');
		if (openNews === 'league' || closeNews === 'league') {
			$('#league').slideUp('slow', function () {
				$('#league').load(toLoadNews, function () {
					$('#league').slideDown('slow');
				});
			});
		} else if (isNaN(openNews) === false) {
			$('#news' + openNews).slideUp('slow', function () {
				$('#news' + openNews).load(toLoadNews, function () {
					$('#news' + openNews).slideDown('slow');
				});
			});
		} else if (isNaN(closeNews) === false) {
			$('#news' + closeNews).slideUp('slow', function () {
				$('#news' + closeNews).load(toLoadNews, function () {
					$('#news' + closeNews).slideDown('slow');
				});
			});
		}
		event.preventDefault();
	});
	
	$('#moreactive').click(function (event) {
		$.url.setUrl($(this).attr('href'));
		var activeCMD = $.url.param("disp"), toLoadAct = 'index_active.php' + $(this).attr('href');
		event.preventDefault();
		$('#latest_wrapper').slideUp('slow', function () {
			if (activeCMD === "active") {
				$('#moreactive').attr('href', '?disp=less');
				$('#moreactive').attr('title', 'Display less...');
				$('#moreactive').text('Less');
			} else if (activeCMD === "less") {
				$('#moreactive').attr('href', '?disp=active');
				$('#moreactive').attr('title', 'Display more...');
				$('#moreactive').text('More');
			}
			$('#latest_wrapper').load(toLoadAct, function () {
				$('#latest_wrapper').slideDown('slow');
			});
		});
	});

	$('#currenttbl a').live("click", function (event) {
		var toLoadCT = 'airio_current_table.php' + $(this).attr('href');
		$('#currenttbl').fadeTo('normal', 0.01, function () {
			$('#currenttbl').load(toLoadCT, function () {
				$('#currenttbl').fadeTo('slow', 1);
			});
		});
		event.preventDefault();
	});
	$('#searchcur').live("click", function (event) {
		var toPostCT = 'airio_current_table.php', curUsrnameVal = $('#cur_usrname').val();
		$('#currenttbl').fadeTo('normal', 0.01, function () {
			$('#currenttbl').load(toPostCT, {cur_usrname: curUsrnameVal}, function () {
				$('#currenttbl').fadeTo('normal', 1);
			});
		});
		event.preventDefault();
	});
	$('#monthlytbl a').live("click", function (event) {
		var toLoadMT = 'airio_monthly_table.php' + $(this).attr('href');
		$('#monthlytbl').fadeTo('normal', 0.01, function () {
			$('#monthlytbl').load(toLoadMT, function () {
				$('#monthlytbl').fadeTo('slow', 1);
			});
		});
		event.preventDefault();
	});
	$('#searchmon').live("click", function (event) {
		var toPostMT = 'airio_monthly_table.php', monUsrnameVal = $('#mon_usrname').val();
		$('#monthlytbl').fadeTo('normal', 0.01, function () {
			$('#monthlytbl').load(toPostMT, {week_usrname: monUsrnameVal}, function () {
				$('#monthlytbl').fadeTo('normal', 1);
			});
		});
		event.preventDefault();
	});
	$('#yearlytbl a').live("click", function (event) {
		var toLoadYT = 'airio_yearly_table.php' + $(this).attr('href');
		$('#yearlytbl').fadeTo('normal', 0.01, function () {
			$('#yearlytbl').load(toLoadYT, function () {
				$('#yearlytbl').fadeTo('slow', 1);
			});
		});
		event.preventDefault();
	});
	$('#searchtot').live("click", function (event) {
		var toPostYT = 'airio_yearly_table.php', totUsrnameVal = $('#tot_usrname').val();
		$('#yearlytbl').fadeTo('normal', 0.01, function () {
			$('#yearlytbl').load(toPostYT, {tot_usrname: totUsrnameVal}, function () {
				$('#yearlytbl').fadeTo('normal', 1);
			});
		});
		event.preventDefault();
	});

});
