/*======================================================================*\
|| #################################################################### ||
|| # PMNet Version 3.0												  #	||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2003-2008 John Slone. All Rights Reserved. 			  #	||
|| # This file may not be redistributed in whole or significant part. # ||
|| #  																  # ||
|| #################################################################### ||
\*======================================================================*/

/* functions.js */

/* Things we should always do */
$(document).ready(function()
{
	// Initialize Menus
	Menu.init();

	// Add a little div for the preview popups and format appropriate links
	Popup.init();
	
	// Initialize the main part of the site
	Main.init();
	
	// Initialize the stars rating system
	Stars.init();
	
	// Initalize Toolbar
	Toolbar.init();
		
});

/*
 *		Site objects..eventually move everything over to this object/format
 *
 */
var Main = {
	refreshRandom : function()
	{
		$.ajax({
			url : '/ajax.php',
			data : { 'action' : 'getrandomcontent' },
			success : function(d)
			{
				$("#randomContentWrapper").html(d);
			}
		});
		return false;
	},

	beforeSlide : function (curr,next,opts) {
		var $slide = $(next);
		var w = $slide.outerWidth();
		var h = $slide.outerHeight();
		$slide.css({
			marginTop: (200 - h) / 2,
			marginLeft: (240 - w) / 2
		});
	},
	
	castVote : function(f)
	{
		var pollid = $("input[name='pollid']").val();
		if ( $("input[name='maxopts']",f).val() > 1 )
		{
			// Allows for multiple selections
		}
		else
		{
			// Allows only one selection
			if ( $("input[name='polloptionid']:checked").length > 0 )
			{
				var optionid = $("input[name='polloptionid']:checked").val();
				$.ajax({
					url : '/ajax.php',
					type : 'POST',
					data : { 'action' : 'castvote', 'pollid' : pollid, 'polloptionid' : optionid },
					success : function(d)
					{
						$("#pollOptions").html(d);
						$("#pollsubmitBtns").remove();
					}
				});
			}
			else
			{
				alert("Sorry, but you must choose an option to vote on!");
				return false;
			}
		}
		return false;
	},
	
	leaveNewsComment : function(newsid)
	{
		$.ajax({
			url : '/ajax.php',
			data : { 'action' : 'newscomm', 'newsid' : newsid },
			success : function(d)
			{
				$.facebox(d);
				$('#newscommbox').focus();
			}
		});
		return false;
	},
	
	addNewsComm : function(f)
	{
		d = $(f).serialize();
		$.ajax({
			url : '/ajax.php',
			type : 'post',
			data : d,
			success : function(da)
			{
				$.facebox(da);
				setTimeout("$.facebox.close()",1000);
			}
		});
		return false;
	},
	
	init : function()
	{
		// Sets up many of the site's functions/settings
		// Facebox
		$("a[rel='facebox']").facebox({'opacity' : 0.9,'overlay':true});
		
		// Get the big searchbox ready
			$("#bigSearchBox").autocomplete('/ajax_search.php',
			{'minChars' : 3, extraParams : { 'action' : 'dosearch' }, width : '550',cellSeparator : '||', delay: 400, matchSubset : 0, rightAlign : true,
				onItemSelect : function(d) { navigateSearch(d); }
		});
		
		// Spoiler tags! -- for sunain!
		$("div.spoiler_warning").click(function(){
			$(this).parents('div.spoiler').find('div.spoiler_content').show();
			$(this).remove();
		});
		
		// Stripes
		$("table.stripeme").each(function(i)
		{
			alternateColors($(this).find('tbody'), 'epRowOne', 'epRowTwo');
		});
		$("table.sortme").each(function(i)
		{
			if ( $(this).find('tbody').length > 0 )
			{
				$(this).tablesorter({'cssHeader':'headerSortable'}).bind('sortEnd',function(){
					alternateColors($(this).find('tbody'), 'epRowOne','epRowTwo');
				});
			}
		});
		
		// When the page loads, we need to get the online users from ajax_bits
		// Random content
		$.ajax({
			url : '/ajax_panel.php',
			data : { 'action' : 'mainbits' },
			success : function(d)
			{
				// Fill in random content
				$("#randomContentBox").html($(d).find('randomcontent').text());
				// Poll questions
				$("#pollQuestionBox").html($(d).find('pollcontent').text());
				// Online Users
				$("#onlineBox").replaceWith($(d).find('onlineusers').text());
				if ( parseInt($(d).find('onlineusercount').text()) > 0 )
				{
					$("#onlineusercountbox").html($(d).find('onlineusercount').text()).removeClass('nodisplay').show();
				}
				// PJ's!
				if ( parseInt($(d).find('projcount').text()) > 0 )
				{
					$("#projectcountbox").html($(d).find('projcount').text()).removeClass('nodisplay').show();
				}
				$("#tooltip_widget_projbox").html($(d).find('projbox').text());
			}
		});
		
		// Make the AJAX icon appear whenever there's an ajax request made
		$("#ajaxWorking").ajaxStart(function() {
			if ( !donotbar )
			{
				$(this).show();
			}
		}).ajaxStop(function() {
			// Stripes
			$("table.stripeme").each(function(i)
			{
				alternateColors($(this).find('tbody'), 'epRowOne', 'epRowTwo');
			});
			$(this).hide();
		});
				
		
	},
	
	tabsupdate : function()
	{
		Popup.reset();
	},
	
	showTagPages : function(el)
	{
		// Get tag id
		var tagid = $(el).attr('tagid');
		$.ajax({
			url : '/ajax.php',
			data : { 'action' : 'getpageresults', 'tagid' : tagid },
			type : 'POST',
			success : function(d)
			{
				$("#tagresults_"+tagid).html(d).css('display','block');
			}
		});
		return false;
	},
	
	toggleImageSlider : function(curr,el)
	{
		if ( curr != 1 )
		{
			$('#ib-slider').remove();
			d = new Date();
			d.setTime(d.getTime()+365*24*60*60*1000);
			document.cookie = 'hideslider'+'='+'1;expires='+d.toGMTString()+';path=/';
			$(el).html('Show Image Slider');
			hideslider = 1;
		}
		else
		{
			d = new Date();
			d.setTime(d.getTime()-1000000);
			document.cookie = 'hideslider'+'='+'0;expires='+d.toGMTString()+';path=/';
			if ( $('#ib-slider').length == 0 )
			{
				$(el).parents('div.choicediv').before('<div id="ib-slider" class="c" style="visibility:hidden;"><ul id="slider-list" class="c ma" style=""></ul><a href="#" onclick="return Main.refreshImages();">Refresh Image List</a></div>');
			}
			Main.refreshImages();
			$(el).html('Hide Image Slider');
			hideslider = 0;
		}
		
		return false;
	},
	
	refreshImages : function()
	{
		$.ajax({
			url : '/ajax.php',
			data : { 'action' : 'getlatestib' },
			type : 'POST',
			success : function(d)
			{
				$('#slider-list').html(d);
				$('#ib-slider').css('display','').css('height','200px');
				$('#ib-slider').css('visibility','visible');
				$('#slider-list').css('visibility','visible');
				$('#slider-list').cycle({ fx: 'scrollUp', before : Main.beforeSlide, pause : true, timeout : 2500 })
			}
		});
		return false;
	}
	
}

// Private Messaging Object
var PM = {
	
	newPM : function(username)
	{
		// Display popup menu to send a new private message; called from a link, return false.
		$.facebox.settings.opacity = 0.95;
		$.facebox( function() {
					$.get('/ajax.php?action=newpm&to='+username, function(d) {
						$.facebox(d);
						$('#to_box').focus();
					});
		});
		return false;
	},
	
	sendPM : function(f)
	{
		// Sends a PM via AJAX call - f is the calling form
		d = $(f).serialize();
		// Disable the button so they can't send again
		$("#sendMsgBtn").attr('disabled','disabled').css('opacity','0.1');
		$.ajax({
			url : '/ajax.php',
			data : d,
			type : 'post',
			success : function(d)
			{
				$.facebox(d);
				setTimeout(function(){$.facebox.close();}, 400);
			}
		});
		return false;
	},
	
	replyToPM : function(pmid)
	{
		$.facebox.settings.opacity = 0.95;
		$.facebox( function() {
					$.get('/ajax.php?action=newpm&replyto='+pmid, function(d) {
						$.facebox(d);
						$('#msg_box').focus().setCursorPosition(0);
					});
		});
		return false;
	}
}


var Signup = {
	checkUserAvail : function(el)
	{
		if ( $(el).val() != '' )
		{
			$.ajax({
				url : '/ajax.php',
				data : { 'action' : 'checkusername', 'checkuser' : $(el).val() },
				success : function(d)
				{
					$("#availString").text(d);
				}
			});
		}
	}
}

var Menu = {
	// Menu 2.0!
	// (horizontal version)
	
	timeouts : {},
	// Time in ms before hiding menu
	timeouttime : 1000,
	
	init : function()
	{
		$p = $("#shortcut_bar");
		$p.find('div').hover(
			function(e){
				Menu.show(this);
			},
			function(e){
				Menu.hide(this);
			}
		);
		$("div.menu_submenu").hover(
			function(e){
				Menu.keepalive(this);
				// Highlight parent row
				$('div#shortcut_bar').css('background-color','#828282');
			},
			function(e){
				Menu.hide($("#menu_item_"+this.id.substring(8))[0]);
				$('div#shortcut_bar').css('background-color','');
			}
		);
	},
	
	show: function(el)
	{
		tokenName = el.id.substring(10);
		// Hide all submenus
		$("div.menu_submenu").hide();
		// Clear timeouts
		for ( key in this.timeouts )
		{
			clearTimeout(this.timeouts[key]);
		}
		
		// Get submenu
		s = $("div#submenu_"+tokenName);
		pos = $(el).position();
		// Move to proper position
		s.css('top', pos.top+$(el).height()+7);
		s.css('left', pos.left);
		// Show submenu
		s.show();
	},
	
	hide : function(el)
	{
		tokenName = el.id.substring(10);
		this.timeouts[tokenName] = setTimeout(function(){Menu.hidemenu(el)}, Menu.timeouttime);
	},
	
	hidemenu: function(el)
	{
		tokenName = el.id.substring(10);
		$("div#submenu_"+tokenName).hide();
	},
	
	keepalive : function(el2)
	{
		tokenName = el2.id.substring(8);
		clearTimeout(this.timeouts[tokenName]);
	}
	
}

var Toolbar = {
	/* functions for the v4 toolbar */
		
	timeouts: {},
	permcancel : {},
	timeoutdelay: 1500,
		
	init : function()
	{
		//$("#icon_onlineusers, #icon_searchbox").hover(
		$("#tooltip_bar_iconrow div[id]").hover(
			function(){
				Toolbar.show(this);
			},
			function(){
				Toolbar.hide(this);
			}
		);
		$("div.iconrow_popup").hover(
			function(ev){
				Toolbar.show($(this).parents('div.iconrow_container')[0]);
				 //ev.stopPropagation();
			},
			function(ev){
				Toolbar.hide($(this).parents('div.iconrow_container')[0]);
				 ev.stopPropagation();
			}
		);
		$("div.tooltip_widget").hover(
			function(){
				Toolbar.cancelHide(this,false);
			},
			
			function(){
				Toolbar.hide2(this);
			}
		);
		// Make sure the searchbox stays up if you're 'focused' on it
		$("#bigSearchBox").focusin(function(){Toolbar.cancelHide($("#tooltip_widget_searchbox")[0],true);});
		$("#bigSearchBox").focusout(function(){Toolbar.cancelPermShow($("#tooltip_widget_searchbox")[0]);Toolbar.hide2($("#tooltip_widget_searchbox")[0]);});
		// Same thing for login, password
		$("#loginForm input").focusin(function(){Toolbar.cancelHide($("#tooltip_widget_userbox")[0],true);});
		$("#loginForm input").focusout(function(){Toolbar.cancelPermShow($("#tooltip_widget_userbox")[0]);Toolbar.hide2($("#tooltip_widget_userbox")[0]);});
	},
	
	show : function(el)
	{
		var tokenName = el.id.substring(5);
		clearTimeout(this.timeouts[tokenName]);
		pos = $(el).position();

		// Hide all current widgets
		for( var obj in this.timeouts )
		{
			clearTimeout(this.timeouts[obj]);
		}
		this.timeouts = {};
		$("div.tooltip_widget").hide();
		p = $("div#tooltip_widget_"+tokenName);
		p.show();
		p.css('left',pos.left - p.width() + $(el).width()/2);
		// Make the toolbar itself solid grey so it blends better
		$("#tooltip_bar").css('background-color','#828282');
		
	},
	
	hide : function(el)
	{
		var tokenName = el.id.substring(5);
		this.timeouts[tokenName] = setTimeout(function(){Toolbar.hidemenu(el)},Toolbar.timeoutdelay);
	},
	
	hide2: function(el)
	{
		var tokenName = el.id.substring(15);
		var newel = $("#icon_"+tokenName)[0];
		this.timeouts[tokenName] = setTimeout(function(){Toolbar.hidemenu(newel)},Toolbar.timeoutdelay);
	},
	
	hidemenu : function(el)
	{
		var tokenName = el.id.substring(5);
		if ( this.permcancel[tokenName] == true )
		{
			return false;
		}
		p = $("div#tooltip_widget_"+tokenName);
		p.hide();
		$("#tooltip_bar").css('background-color','');
	},
	
	cancelHide: function(el,cancelall)
	{
		var tokenName = el.id.substring(15);
		if ( cancelall == true )
		{
			this.permcancel[tokenName] = true;
		}
		clearTimeout(this.timeouts[tokenName]);
	},
	
	cancelPermShow : function(el)
	{
		var tokenName = el.id.substring(15);
		this.permcancel[tokenName] = false;
	},
	
	showLogin : function()
	{
		this.show($("#icon_userbox")[0]);
		$("#loginForm input[name='username']")[0].focus();
		// prevent the link from activating!
		return false;
	}
	
}

var Popup = {
	
	isanimating : false,
	popup_on : false,
	// The currently highlighted popup/etc.
	current : null,
	// Timeout for the popup to disappear, in milliseconds
	timeout : 1500,
	// duration of 'sliding' animation, in milliseconds
	animationtime : 400,
	// duration of fadeout
	fadeouttime : 1500,
	// duration that they have to hover over a link before it 'activates' the ajax..can save a few server calls and stop them from having annoying popups
	// when they're just scrolling over an area
	delay : 800,
	// Containers to hold previously loaded data
	containers : { 'epg' : {}, 'dvd' : {}, 'char' : {}, 'evpoke' : {}, 'attack' : {} },
	// Are we in delay?
	isdelayed : false,
	// Timeout object
	toobj : 0,
	
	
	// Function to add the popup to the page
	init : function()
	{
		$pop = this;
		$("body").append('<div id="previewpopup" class="nodisplay smalltext"><img src="/images/templates/progress_circle.gif" alt="Working" /></div>');
		$("#previewpopup").hover(
			function(ev){
				$pop.isdelayed = false;
				$pop.popup_on = true;
				if ( $pop.isanimating == true )
				{
					// It's currently disappearing..we need to stop that from happening
					$pop.cancelhide();
				}
			},
			function(ev){
				$pop.popup_on = false;
				setTimeout("Popup.hide()",$pop.timeout);
			}).click(function(ev){
				// We need to cancel the bubbling when they click inside the preview popup - just in case I ever add video playback for OP/ED, etc.
				if ( ev.stopPropagation )
				{
					ev.stopPropagation();
				}
				else
				{
					ev.cancelBubble = true;
				}
			});
		// Cycle through the links and change all the appropriate episode links to have popup windows
		this.reset();
	},
	
	reset : function()
	{
		$pop = this;
		// Cycle through the links and change all the appropriate episode links to have popup windows
		$("a[rel*='epg'],a[rel*='dvd'],a[rel*='char'],a[rel*='evpoke'],a[rel*='attack']").hover(
			function(ev){
				$pop.popup_on = true;
				//$pop.show(this,ev);
				t = this;
				$pop.current = $(t).attr('rel');
				this.isdelayed = false;
				this.toobj = setTimeout(function(){$pop.isdelayed=false;$pop.show(t,ev);}, $pop.delay);
			},
			function(ev){
				$pop.popup_on = false;
				if ( this.isdelayed )
				{
					Popup.hide();
					clearTimeout(this.toobj);
					this.toobj = 0;
				}
				else
				{
					setTimeout("Popup.hide()",1500);
				}
			}
		);
	},
	
	show : function(el, ev)
	{
		this.isdelayed = false;
		$p = $("#previewpopup");
		$p.show().css('visibility','hidden');
		$pop = this;
		// is the popup currently loaded?
		if ( $pop.popup_on )
		{
			$pop.hide();
		}
		if ( this.isanimating )
		{
			this.cancelhide();
		}
		
		// Do we need to get the data?
		m = $(el).attr('rel').split(/\-/);
		if ( typeof($pop.containers[m[0]]) != 'undefined' && typeof($pop.containers[m[0]][m[1]]) != 'undefined' )
		{
			// The data was previously loaded
			$pop.fill(m, el);
		}
		else
		{
			// New data, we need to poll the site for it
			switch(m[0])
			{
				case 'epg':
					$.ajax({
						url : '/ajax_popup.php',
						data : {'action' : 'showep', 'epid' : m[1]},
						success : function(d) {
							$pop.containers[m[0]][m[1]] = d;
							$pop.fill(m, el);
						}
					});
				break;
				case 'dvd':
					$.ajax({
						url : '/ajax_popup.php',
						data : { 'action' : 'showdvd', 'dvdid' : m[1] },
						success : function(d) { 
							$pop.containers[m[0]][m[1]] = d;
							$pop.fill(m, el); 
						}
					});
				break;
				case 'char':
					$.ajax({
						url : '/ajax_popup.php',
						data : { 'action' : 'showchar', 'charid' : m[1] },
						success : function(d) { 
							$pop.containers[m[0]][m[1]] = d;
							$pop.fill(m, el); 
						}
					});
				break;
				case 'evpoke':
					$.ajax({
						url : '/ajax_popup.php',
						data : { 'action' : 'showevpoke', 'eventpokemonid' : m[1] },
						success : function(d) { 
							$pop.containers[m[0]][m[1]] = d;
							$pop.fill(m, el); 
						}
					});	
				break;
				case 'attack':
					$.ajax({
						url : '/ajax_popup.php',
						data : { 'action' : 'showattack', 'attackid' : m[1] },
						success : function(d) {
							$pop.containers[m[0]][m[1]] = d;
							$pop.fill(m, el);
						}						
					});
				break;
				default:
					return false;
				break;
			}
		}
	},
	
	hide : function()
	{
		$pop = this;
		this.isdelayed = false;
		if ( this.popup_on != true )
		{
			$("#previewpopup").fadeOut($pop.fadeouttime,function(){$(this).addClass('nodisplay').html('')});
			$pop.isanimating = true;
		}
	},
	
	hidenow : function()
	{
		$("#previewpopup").addClass('nodisplay').hide();
	},
	
	cancelhide : function()
	{
		$p = $("#previewpopup");
		// Stop animations/clear queued animation
		$p.stop(true).css({'opacity' : 1, 'width' : 0, 'height' : 0, 'display' : 'none'});
		this.isanimating = false;
	},
	
	fill : function(m, el)
	{
		// Is the element we're going to fill in the same as the currently highlighted one?
		// If not, the user has already moved focus
		if ( this.current != $(el).attr('rel') ) 
		{
			return false;
		}
		// m[0] = type of popup, m[1] = id number for element
		m = $(el).attr('rel').split(/\-/);
		
		$p = $("#previewpopup");
		$("#previewpopup").html(this.containers[m[0]][m[1]]);
		x = $("body").append("<div id=\"dumbstupidbox\">"+this.containers[m[0]][m[1]]+"</div>");
		$("#dumbstupidbox").css({'visibility':'none','position':'absolute','top':-1000,'left':-1000,'width':'400px'});
		$height = $("#dumbstupidbox").height();
		$("#dumbstupidbox").remove();
		
		if ( !this.popup_on )
		{
			return false;
		}
		
		// Now we need to get positioning for the popup
		offsets = $(el).offset();
		// For the character guide, i want the popup to be centered and under the image
		$p.css({
			'position' : 'absolute',
			'width' : '400px',
			'height' : 'auto'
		});
		if ( m[0] == 'char' )
		{
			$left = offsets.left - (( ($p).width() - $(el).width()) / 2);
			$top = offsets.top + 12;
		}
		else
		{
			//$left = offsets.left + $(el).width();
			$left = offsets.left - (( ($p).width() - $(el).width()) / 2);
			$top = offsets.top + $(el).height();
		}
		$p.css({
			'top' : $top,
			'left' : $left,
		});
		// We need to do a quick check to make sure the box doesn't go past the end of the window!
		if ( ( parseInt($p.css('left')) + parseInt($p.width()) ) > $(window).width() )
		{
			// Adjust a little bit
			$p.css('left', parseInt(parseInt( $(window).width() - (parseInt($p.width()) ) ) ) - 20 );
		}
		// Save the height for the animation
		//$height = $p.height();
		$p.find('.popupcontainer').css({'width':'400px' ,'height':$height+'px'});
				$p.removeClass('nodisplay');
		$p.css({'width':0, 'height':0,'visibility':'visible','overflow' : 'hidden'});
		if ( m[0] == 'char' )
		{
			$p.css('width','400px');
		}
		$p.animate({'height':$height,'width': '400px'},this.animationtime);
		this.popup_on = true;
	}
	
}

var Stars = {
	
	// start variables
	templatedir : '/templates/stars/',
	timeoutobj : null,
	timeout : 800,
	
	
	// start functions
	
	init : function()
	{
		// basically we just need to pre-load images
		for ( i = 1; i <= 9; i++ )
		{
			a = new Image(20,20);
			a.src = this.templatedir+'redstar'+i+'.png';
		}
		a = new Image(20,20);a.src=this.templatedir+'clearstar.png';
		a = new Image(20,20);a.src=this.templatedir+'goldenstar.png';
		
		// add confirmation message
		$("#pmBody").append('<div id="ratingconfirm">Rating Saved!</div>');
	},
	
	// Resets the star row to show the user's original rating.
	reset : function(el)
	{
		$rating = $(el).attr('current');
		if ( $rating == 0 )
		{
			$(el).find('img').attr('src',this.templatedir+'clearstar.png');
		}
		else if ( $rating == 10 )
		{
			$(el).find('img').attr('src',this.templatedir+'goldenstar.png');
		}
		else
		{
			// New method: use jquery selectors rather than the generic img selector and each(i) function
			$(el).find('img:lt('+$rating+')').attr('src',this.templatedir+'redstar.png');
			$(el).find('img:gt('+ ($rating-1) +')').attr('src',this.templatedir+'clearstar.png');
		}
	},
	
	// Highlights all the stars up to a particular hover'ed number
	to : function(el)
	{
		// get parent
		$p = $(el).parents('div.ratingsbox');
		// get index
		$i = $('img', $p).index($(el))+1;
		
		// Now, fill in the stars accordingly
		if ( $i == 10 )
		{
			$('img', $p).attr('src', this.templatedir+'goldenstar.png');
		}
		else
		{
			for ( i=1; i<= $i; i++ )
			{
				$p.find('img:nth-child('+ i +')').attr('src', this.templatedir + 'redstar' + i + '.png');
			}
		}
	},
	
	// Sets the actual star rating
	set : function(el)
	{
		// el = the actual star clicked, along with its rel="$i" component
		$p = $(el).parents('div.ratingsbox');
		$subid = $p.attr('subid');
		$type = $p.attr('type');
		$rating = $(el).attr('rel');

		$.ajax({
			data : {'action' : 'setrating', 'ratingtype' : $type, 'subid' : $subid, 'rating' : $rating},
			url : '/ajax.php',
			success : function(d) { Stars.confirm(el,$rating,d);}
		});	
	},
	
	// accepts confirmation of the rating change
	confirm : function(el, rate, d)
	{
		// get parent
		$p = $(el).parents('div.ratingsbox');
		$type = $p.attr('type');
		$subid = $p.attr('subid');
		$p.attr('current', rate);
		
		// Are there average ratings to update?
		$("span."+$type+'-'+$subid).text( $(d).find('avgrating').text() );
		
		// Are there vote totals to update?
		$("span.votecount"+$type+'-'+$subid).text( $(d).find('numvotes').text() );
		
		// Is there a rating bar that applies to this?
		$(".ratingbar-"+$type+'-'+$subid).each(function(i){
			totalwid = $(this).width();
			var new_wid = Math.floor(totalwid * $(d).find('avgrating').text() / 10);
			$(this).find('div').width(new_wid);
		});
		
		// Finally, show the user confirmation that the action was successful
		$b = $("div#ratingconfirm");
		// Stop any pending animations from previous clicks
		$b.stop().css('opacity','1.0');
		$b.css( {'left' : $p.offset().left, 'top' : $p.offset().top }).show();
		this.timeoutobj = setTimeout("$b.fadeOut(1000)", this.timeout);
	}
	
}

var TabSet = function(tabobj, updatescr, updateact, extra)
{
	this.tabs = tabobj;
	this.hidden = $(this.tabs).find('.hiddenNavTabs');
	this.activearea = $(this.tabs).find('.navTabContent');
	this.activetab = null;
	this.datasource = updatescr;
	this.dataaction = {'action' : updateact, 'tabid' : ''};
	this.extraargs = extra;
	this.data = null;
	this.updatefunctions = {};
	
	// Combine action+extraargs
	if (this.extraargs != null )
	{
		$.extend(this.dataaction, this.extraargs);
	}
	
	this.init = function()
	{
		// Will set this up to get the tabs ready to work
		// Preload an image
		i = new Image(300, 64);
		i.src = '/images/templates/bigbluebar.gif';
		
		// Format the links inside the tabobj to load up the new tab
		$($t.tabs).find("li.navTab a").click(function(){
			x = $(this).attr('href').substring(1);
			$t.setActive(x);
		});
		
		// Check the anchor for the name of the tab
		this.checkAnchor();
		
		// Now, if there's still no active tab, get it from the tabset itself
		if ( this.activetab == null )
		{
			if ( $($t.tabs).find("li.activeTab").length > 0 )
			{
				this.activetab = $($t.tabs).find("li.activeTab").find('a').attr('href').substring(1);
			}
		}
		
	}
	
	this.setActive = function(f)
	{
		// Make sure this tab isn't already active
		if ( f != this.activetab )
		{
			// Remove active status from all tabs
			$(this.tabs).find('li.navTab').removeClass('activeTab');
			$(this.tabs).find("a[href='#"+f+"']").parents("li.navTab").addClass('activeTab');
			
			// Is there a tab already loaded inside the box? If so, move it to the hidden area
			if ( this.activearea.find('div').length > 0 )
			{
				//this.hidden.append();
				this.activearea.find("div[class*='TabContent']").appendTo(this.hidden);
			}
			
			// Does the new tab already exist, or do we need to POOF it into being?
			if ( $(this.tabs).find('.TabContent_'+f).length > 0 )
			{
				this.activearea.append($(this.tabs).find('.TabContent_'+f));
				$(this.tabs).find('.TabContent_'+f).css('display','block').css('position','relative');
			}
			else
			{
				this.dataaction.tabid = f;
				this.activearea.html('<div class="c"><img src="/images/templates/bigbluebar.gif" alt="Working!" /></div>');
				// Now, we need to get the ajax'ed information
				$.ajax({
					url : this.datasource,
					data : this.dataaction,
					success : function(d)
					{
						$t.activearea.html('');
						$('<div class="TabContent_'+f+'">'+d+'</div>').appendTo($t.activearea);
						Main.tabsupdate();
						if ( Main.secondTarget != null )
						{
							setTimeout(function(){document.getElementById(Main.secondTarget).scrollIntoView(true);Main.secondTarget=null;},1000);
						}
					}
				});
			}
			this.activetab = f;
			/*
			if ( this.updatefunctions[f] != null )
			{
				this.updatefunctions[f]();
			}
			*/
			
			return false;
		}
	}
	
	this.checkAnchor = function()
	{
		if ( location.hash.length > 0 )
		{
			x = location.hash.substring(1);
			if ( x.indexOf("-") != -1 )
			{
				p = x.split(/\-/);
				x = p[0];
				if ( p[1] != '' )
				{
					save = p[1];
					Main.secondTarget = save;
					this.dataaction['secondtarget'] = save;
				}
			}
			else
			{
				Main.secondTarget = null;
			}
			this.setActive(x);
		}	
	}
	
	$t = this;
	return this;
}

///////////////////
// Begin functions
///////////////////


/*
 *	tabbed browsing funtions
 */
function setActiveTab(link)
{
	if ( $(link).parent('li').hasClass('activeTab') ) { return false; } // Tab already active
	// Figure out what nav group we're in
	par = $(link).parents('div.navContainer');
	var new_tab = $(link).attr('href').substring(1);
	par.find("li.activeTab").removeClass("activeTab");
	$(link).parent('li').addClass("activeTab");
	// Move current tab to inactive status
	if ( par.find("div.TabContent_"+new_tab).length > 0 )
	{

		$(".navTabContent div[class*='TabContent']").appendTo(".hiddenNavTabs");
		par.find("div.TabContent_"+new_tab).appendTo(".navTabContent");
	}
	else
	{
		$(".navTabContent div[class*='TabContent']").appendTo(".hiddenNavTabs");
		$(".navTabContent div[class*='TabContent']").html("<div class=\"c\"><img src=\"/images/templates/bigbluebar.gif\" alt=\"Working\" /></div>");

		// The tab has not yet been loaded, we'll need to AJAX it into being.
		d = { 'action' : tabsdata.updateaction, 'tabid' : new_tab };
		if ( typeof(tabsdata.extraData) != "undefined" )
		{
			for ( key in tabsdata.extraData )
			{
				d[key] = tabsdata.extraData[key];
			}
		}
		$.ajax({
			url : tabsdata.updatescr,
			type : 'get',
			data : d,
			success : function(d,s) { addTabData(d,new_tab); }
		});
	}
	return false;
}

function checkanchor()
{
	m = window.location.href;
	if ( m.indexOf('#') != -1 )
	{
		p = m.split('#');
		setActiveTab($("a[href='#"+p[1]+"']"));
	}
}
function addTabData(d,new_tab)
{
	$(".navTabContent").html('<div class="TabContent_'+new_tab+'">'+d+'</div>');
	// Call tabs update stuff
	Main.tabsupdate();
}

function navigateSearch(d)
{
	location.href=d.extra[0];
	$("#bigSearchBox").val(d.extra[1]);
	return false;
}
function alternateColors( el, classOne, classTwo )
{
	$(el).find('tr').removeClass(classOne).removeClass(classTwo);
	$(el).find("tr[class!='headerRow'][class!='dexHeaderRow'][class!='boardHeader']").each(function(i){
		if ( i % 2 == 1 )
		{
			$(this).addClass(classOne);
		}
		else
		{
			$(this).addClass(classTwo);
		}
	});
}
// Used on the search pages to fill in default values when a page is refreshed/copied to others
// Breaks the location.hash up to reset variables
function resetVars(h)
{
	p = h.substring(1).split(/\&/);
	for ( i = 0; i < p.length; i++ )
	{
		c = p[i].split(/\=/);
		if ( $("input[name='"+c[0]+"']").length > 0 )
		{
			$("input[name='"+c[0]+"']").val(c[1]);
		}
		else if ( c[0].match(/[\[\]]/) )
		{
			$("select[name='"+c[0]+"']").find("option[value='"+c[1]+"']").attr('selected','selected');
		}
		else
		{
			$("select[name='"+c[0]+"']").find("option[value='"+c[1]+"']").attr('selected','selected');
		}
	}
}

var donotbar = false;
// Table sorter
(function($){$.extend({tablesorter:new function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'.',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}var rows=table.tBodies[0].rows;if(table.tBodies[0].rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,cells[i]);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,node){var l=parsers.length;for(var i=1;i<l;i++){if(parsers[i].is($.trim(getElementText(table.config,node)),table,node)){return parsers[i];}}return parsers[0];}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=table.tBodies[0].rows[i],cols=[];cache.row.push($(c));for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));}cols.push(i);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){if(!node)return"";var t="";if(config.textExtraction=="simple"){if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){t=node.childNodes[0].innerHTML;}else{t=node.innerHTML;}}else{if(typeof(config.textExtraction)=="function"){t=config.textExtraction(node);}else{t=$(node).text();}}return t;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){rows.push(r[n[i][checkCell]]);if(!table.config.appender){var o=r[n[i][checkCell]];var l=o.length;for(var j=0;j<l;j++){tableBody[0].appendChild(o[j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false,tableHeadersRows=[];for(var i=0;i<table.tHead.rows.length;i++){tableHeadersRows[i]=0;};$tableHeaders=$("thead th",table);$tableHeaders.each(function(index){this.count=0;this.column=index;this.order=formatSortingOrder(table.config.sortInitialOrder);if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(!this.sortDisabled){$(this).addClass(table.config.cssHeader);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){i=(v.toLowerCase()=="desc")?1:0;}else{i=(v==(0||1))?v:0;}return i;}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(getCachedSortType(table.config.parsers,c)=="text")?((order==0)?"sortText":"sortTextDesc"):((order==0)?"sortNumeric":"sortNumericDesc");var e="e"+i;dynamicExp+="var "+e+" = "+s+"(a["+c+"],b["+c+"]); ";dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function sortText(a,b){return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){$this.trigger("sortStart");var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){var $cell=$(this);var i=this.column;this.order=this.count++%2;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){var DECIMAL='\\'+config.decimal;var exp='/(^[+]?0('+DECIMAL+'0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)'+DECIMAL+'(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*'+DECIMAL+'0+$)/';return RegExp(exp).test($.trim(s));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}$("tr:visible",table.tBodies[0]).filter(':even').removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0]).end().filter(':odd').removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);
// Set cursor position
new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);



/* //////////////////
///	End function definitions - begin "do this on every page" section
/////////////////// */

/*======================================================================*\
|| ####################################################################
|| # File Revision:    $Revision: 1498 $
|| # Last Change:      $LastChangedDate: 2011-12-08 16:56:55 -0800 (Thu, 08 Dec 2011) $
|| # Last Commit By:   $Author: JDS $
|| ####################################################################
\*======================================================================*/
