/******************************************************
*  general.js - consumer site 'master' javascript file - this contains all sorts
*		of goodies and 'stuff'.
*
*  mod log:
*  -------
*  05/22/09  pjs  create new remoraBASE for remora tracker (instead of hard-coding xmlbeta.varvee.com)
*		  NOTE - this should be 'http://xmlbeta.varvee.com/' on live and
*					'http://xmlbeta.varvee.com/' on preps
*
*		  in CVS, this is always 'xml'.  Override the preps setting manually for now
*
*  07/31/09  pjs  2009-?2010 season rollover
*
*  08/07/09  pjs  replace jQuery shortcut with $vj to resolve library conflicts
*  
*  08/08/09  pjs  rename 'Menu' function to 'vvMenu' to avoid naming conflict with fox's menu app
*  
*  08/10/09  pjs  rename buildLink to vvBuildLink to resolve naming conflict with prototype library
*
*  08/13/09  pjs  add display:in-line style to coach promo varvee logo to fix IE display issues
*  		  (where coach promo box breaks into 2 line) 
*  		
*  08/19/09  pjs  more for/in fixes
*  
*  09/05/09  pjs  nav_year fix for browsing to the selected year
*  
*  09/14/09  pjs  fixed 'inArray' to work with fox skin under IE.  Needed to specify index order because
*  			'for/in was putting functions FIRST in IE and last in Firefox.  (functions first
*  			caused search loop to terminate early)
*
* 10/07/09  pjs  in vvMenu, if we run into a type 'function', just continue instead of breaking.  This
* 			fixes premature exists in track nav submenus
* 			
* 11/23/09  pjs  added ice hockey & swimming to sport list
* 
* 01/26/10  pjs  added wrestling to sports list
* 
* 02/26/10  jjb  removed the default setting of group id.  It was over-riding it being set dynamically
* 
* 03/10/10  pjs  switched (legacy) ad server from www.varvee.com to co.varvee.com
* 
* 05/16/10  pjs  remove test for sportDir == undefined
* 
* 06/28/10  pjs  fix coach services page link to go to consumer site
*
* 07/05/10  pjs  support girls ice hockey
*/


/*********** old logging function
function log (value){
	return value;
}
**********************************/

// new functions take from new tennis
log = (function(i,j){ return ((j != undefined) ? j: i); })
error = function(i,j) { return log(i,j); }

function nonempty_result(doc)
{
	if((items = $vj("channel item",doc)).length <= 0 )  return error("feed has no items: " + doc.baseURI.toString().match(/\&url=http:\/\/[\-a-zA-Z\?\&_0-9\/\=]+/ig),false)
	//this will prevent a true value if errors and total value are returned.
	if( items.children().length < 3 ) return error('feedserver: ' + $vj.makeArray($vj('mysql_error, error',items).text()).join(','),false)
	return true;	
}


// remora tracker BASE URL - this defines where the page loads get logged
var remoraBASE = 'http://:xml.co.varvee.com/';		// change to 'xmlbeta' on preps

var teamID = 0;
var standOrder = "c";
var teamSort = null
var indivSort = ""
var leadType = "off"; //this should have no default value in this context, should be set in <sport>/js/<defaults|<sport>>.js
var defSort = "";  //this should have no default value in this context, should be set in <sport>/js/<defaults|<sport>>.js
var teamSort = "";
var divID = "";
var confID = "";
var scratchFilter = "";
var thisPage = 1;
var thisSport = 0; //this should have no default value
var sportName  = "";
var gameID = 0;
var dorc = null;
var thisDate = '2008-08-28';

var baseURL = "http://granite/";
var statsURL = "http://vvx/";
var adsURL = "http://co.varvee.com/js/partner_sponsor.php";	// multistate: changed from www
var siteTitle = "";
var siteDir = "";
var proxyURL = baseURL + "proxy/xml.php?url=" + statsURL; //this needs to be changed into a function.

var validSports = Array(6,7,8,9,12,13,15,16,18,19,20,23,24,27,28,29,30,31,32,33,34);
var recordsPerPage = 20;
var theLetter = 'a';
var thePlayer = 0;
//var groupID = 35; //don't do this anymore!!

var statYear = 2011;			// rollover to new season
var statYearLimit = 4;
var yearAbbr = Array('Sr.','Jr.','So.','Fr.','8th','7th','6th','5th','4th','3rd','2nd','1st','Knd','PrK');

var season = "";
var dispall = "false";

var rc = Array('evenRow','oddRow');
var k;
var startDate;
var endDate;
var uri = location.href;
if ( uri.indexOf("?") >= 0 ) 
	uri_parts = uri.split("?");
else 
	uri_parts = uri.split(".php");

var k
var uri = location.href;
var debug_level = 0;
var keys = {}

if ( uri.indexOf("?") >= 0 ) 
	uri_parts = uri.split("?");  //technically, this should always show up
else 
	uri_parts = uri.split(".php");

if (uri_parts.length > 1 && uri_parts[1] != "") 	
{
	thisPart = uri_parts[1].split("&");
	for ( p = 0; p < thisPart.length; ++p)
	{

		parameter = thisPart[p]
		pair = parameter.split("=");
		key = pair[0];
		
		value = (pair[1] || "").split(/#/g).shift() //remove all of the '#'s and keep everything before the first one.
		if (value != 0)
		{
			log(key + ":'" + value + "'");
			if (key == "cid") divID = value; 
			if (key == "dsrt") defSort = value;
			if (key == "gid") gameID = value;
			if (key == "groupSeasons" ) season = ((value == 'false') ? "display_as_column" : value); 
			if (key == "grpid") groupID = value;
			if (key == "isrt") indivSort = value;
			if (key == "lid") confID = value; 
			if (key == "scratch") scratchFilter = value; 
			if (key == "ltr") theLetter = value;
			if (key == "ltype") leadType = value;
			if (key == "oid") orgID = value;
			if (key == "page") thisPage = value;
			if (key == "pid") thePlayer = value;
			if (key == "sid") thisSport = value;
			if (key == "tid") teamID = value;
			if (key == "tsrt") teamSort = value;
			if (key == "wlt") standOrder = value;
			if (key == "yid") statYear = value;
			if (key == "dispall") dispall = value;
			if (key == "date") thisDate = value;
			if (key == "sdt") startDate = value;
			if (key == "edt") endDate = value;
			keys[key] = value;
		}
	}
}



function sortPage(sp,pg,key,val)
{
	url = baseURL + sp + "/" + pg + ".php?yid=" + statYear + "&sid=" + thisSport + "&tid=" + teamID + "&" + key + "=" + val;
	location.href = url;
}
function buildURL(sp,pg)
{
	url = baseURL + sp + "/" + pg + ".php?yid=" + statYear + "&sid=" + thisSport + "&tid=" + teamID;
	location.href = url;
}
function buildURLConf(sp,pg)
{
	url = baseURL + sp + "/" + pg + ".php?yid=" + statYear + "&sid=" + thisSport + "&cid=" + divID + "&lid=" + confID + "&tid=" + teamID;
	location.href = url;
}
/*
 * Convert an annual Year to a High-School Year
 */
function player_year(gyr)
{
	//statYearLimit defaults to 4
	var gyr = parseInt(gyr)
	if (gyr != 0)
	{
		var year_differential = (gyr - statYear)
		if (year_differential < statYearLimit)
		{
			if ( year_differential > yearAbbr.length ) return yearAbbr[yearAbbr.length]
			else if (year_differential > -1 ) return yearAbbr[year_differential]; //this is the target case.
			else return "<span class=\"nogradyear\">&nbsp;</span>";
		}
		else
		{
			return gyr;
		}
	}
	else return "<span class=\"nogradyear\">&nbsp;</span>";
}

/*
 *  Check to see if the needle is in the haystack array.
 *  ----------------------------------------------------
 *  Built primarily for checking for valid sports.
 */
function inArray(needle,haystack)
{
	var myType='';

	var mySize = haystack.length;
	var i;

	// changed to force the index order for fix fox skin on IE
	for (i = 0; i < mySize; ++i) {

		myType = typeof(haystack[i]);

		if (myType == 'function')
			break;

		if (haystack[i] == needle) 
			return true;
	} 
	return false;
}


/*  Remora Log Include  */
/************************************  defunct in new model *****************
remoraURL = location.href;
var cci = getCookie("varveePartner");
//$vj.getScript('http://xmlbeta.varvee.com/remora?url=' + remoraURL + "&cci=" + cci);  //this breaks, hangs if no internet connection available., perhaps we should put this in a funcion? put it in in the site-config?

// call remora tracker on same site as stats feed to log in the correct database, which is not always 'live'
$vj.getScript(remoraBASE + 'remora?url=' + remoraURL + "&cci=" + cci);  //this breaks, hangs if no internet connection available., perhaps we should put this in a funcion? put it in in the site-config?

****************************************************************************/

/*  Cookie Functions  */
function setCookie(cn,v) {
	document.cookie = cn + "=" + v; 
}
function getCookie(cn) {
	if (document.cookie.length > 0) {
		cs = document.cookie.indexOf(cn + "=");
		if (cs != -1) {
			cs += cn.length + 1;
			ce = document.cookie.indexOf(";",cs);
			if (ce == -1) ce = document.cookie.length;
			return unescape(document.cookie.substring(cs,ce));
		}
	}
	return "";
}

/*  NavCrumbs   */

var timeout	= 500;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id)
{	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose; 


function handleBreadNavTeam(doc) {
	 
		 //  Used to parse the XML
	 var root = doc.documentElement;
	 var nds;
	 
	 //Hack
	var pyid = parseInt(statYear) - 1;
	var yrid = pyid + "-" + statYear;
	 document.getElementById('yearNav').innerHTML = '<a href="#">' + yrid + '</a>';
	 //  Look for child nodes in the XML
	 if(root.hasChildNodes())  
	 {
		   nds=root.childNodes;
		   //  Look through the child nodes and find nodes named "school"
		   for (var i = 0; i < nds.length; i++)
		   {
		   	   if (nds[i].nodeName == "year") nav_year(nds[i])
		   	   if (nds[i].nodeName == "sport") nav_sport(nds[i])
		   	   if (nds[i].nodeName == "state") nav_group(nds[i])
		   	   if (nds[i].nodeName == "division") nav_class(nds[i])
		   	   if (nds[i].nodeName == "conference") nav_league(nds[i])
			   if (nds[i].nodeName == "school") nav_school(nds[i])
			   if (nds[i].nodeName == "team") nav_team(nds[i])
		   }
	 }
}

function handleBreadNavBrowse(doc) {
	//  Used to parse the XML
	var root = doc.documentElement;
    var nds;
    
	//  Look for child nodes in the XML
	if(root.hasChildNodes())
	{
		nds=root.childNodes;
		//  Look through the child nodes and find nodes named "school"
		for (var i = 0; i < nds.length; i++)
		{
               if (nds[i].nodeName == "year") nav_year(nds[i])
		   	   if (nds[i].nodeName == "sport") nav_sport(nds[i])
		   	   if (nds[i].nodeName == "state") nav_group(nds[i])
		}
	}
}

function handleBreadNavGame(doc) {
	 
		 //  Used to parse the XML
	 var root = doc.documentElement;
	 var nds;	   
	 //  Look for child nodes in the XML
	 if(root.hasChildNodes())  
	 {
		   nds=root.childNodes;
		   //  Look through the child nodes and find nodes named "school"
		   for (var i = 0; i < nds.length; i++)
		   {
		   	   if (nds[i].nodeName == "year") nav_year(nds[i])
	 		   if (nds[i].nodeName == "sport") nav_sport(nds[i])
	 		   if (nds[i].nodeName == "state") nav_group(nds[i])
		   }
	 }
}

function handleBreadNavConfDiv(doc) {
		 //  Used to parse the XML
	 var root = doc.documentElement;
	 var nds;
	 
	 //  Look for child nodes in the XML
	 if(root.hasChildNodes())  
	 {
		   nds=root.childNodes;
		   //  Look through the child nodes and find nodes named "school"
		   for (var i = 0; i < nds.length; i++)
		   {
		   	   if (nds[i].nodeName == "year") nav_year(nds[i])
	 		   if (nds[i].nodeName == "sport") nav_sport(nds[i])
	 		   if (nds[i].nodeName == "state") nav_group(nds[i])
		   	   if (nds[i].nodeName == "division") nav_class(nds[i])
		   	   if (nds[i].nodeName == "conference") nav_league(nds[i])
		   }
	 }
}

function format_year(year)
{
	if (typeof(year) == 'undefined' || year == "0" || year == 0) return "&nbsp;";
	return (parseInt(year) - 1).toString() + "-" + year
}

function nav_year(elements)
{
	//setup vars
	var aid = Array();
	var yid = 0;

	
	 //document.getElementById('yearNav').innerHTML = '<a href="#">' + fmt_yr + '</a>';
	//get values
	if(elements.hasChildNodes())
	{	
		
		sNds = elements.childNodes;
		for (var j=0;j<sNds.length;j++)
		{
			if (sNds[j].hasChildNodes())
			{
				//alert(sNds[j].nodeName);
				if (sNds[j].nodeName == "alternate" ) aid[aid.length] = sNds[j].firstChild.nodeValue;
				if (sNds[j].nodeName == "selected" ) yid = sNds[j].firstChild.nodeValue;
			}
		}
		if (yid == 0 && aid.length > 0) 
		{
			if (statYear != 0  && statYear != aid[0]) yid = statYear
			else yid = aid.shift()
		}
		var d = document.getElementById('yearNav')
//
//- don't include the sport on a browse link - this confuses the browse and omits all the data.
//  this is the 'general' browse that should show ALL teams for the season
///////		splink = baseURL + 'browse.php?yid=' + yid + '&sid=' + thisSport + '&ltr=a';
		splink = baseURL + 'browse.php?yid=' + yid  + '&ltr=a';
		if (aid.length > 0)
		{
			d.innerHTML = '<a href="' + splink + '" onmouseover="mopen(' + "'m0\'" + ')"  onmouseout="mclosetime()">' + format_year(yid) + '</a><div id="m0" onmouseover="mcancelclosetime()"  onmouseout="mclosetime()"></div>';
			e = document.getElementById('m0');
			e.innerHTML = "";
			for (x=0;x<aid.length;x++)
			{
				e.innerHTML += '<a href="' + baseURL + 'browse.php?yid=' + aid[x] + '&ltr=a" >' + format_year(aid[x]) + '</a>';
			}
		}
		else
		{
			d.innerHTML = '<a href="' + splink + '">' + format_year(yid) + '</a>';
		}
	}  // nds.subnodes

	//assign values in document
		   	   
}
function nav_group(elements)
{
	//groupNav
	var aid = Array();
	var anm = Array();
	var sid = 0;
	var sname = ""
	//  Look through the children of the nodes named "school" and find what we want
	if(elements.hasChildNodes())
	{	
		sNds = elements.childNodes;
		for (var j=0;j<sNds.length;j++)
		{
			//alert(sNds[j].nodeName);
			if (sNds[j].nodeName == "alternate" && sNds[j].hasChildNodes()) anm[anm.length] = sNds[j].firstChild.nodeValue;
			if (sNds[j].nodeName == "alternate_id" && sNds[j].hasChildNodes()) aid[aid.length] = sNds[j].firstChild.nodeValue;
			if (sNds[j].nodeName == "selected" && sNds[j].hasChildNodes()) sname = sNds[j].firstChild.nodeValue;
			if (sNds[j].nodeName == "selected_id" && sNds[j].hasChildNodes()) sid = sNds[j].firstChild.nodeValue;
		}
		var d = document.getElementById('groupNav');
		
		if (sid == 0 && aid.length)
		{
			sname = anm.shift()
			sid = sid.shift()
		}
		splink = baseURL + 'browse.php?yid=' + statYear + '&groupID=' + sid + '&ltr=a' ;
		if (aid.length > 0)
		{
			d.innerHTML = '<a href="' + splink + '" onmouseover="mopen(' + "'mneg1\'" + ')"  onmouseout="mclosetime()">' + sname + '</a><div id="mneg1" onmouseover="mcancelclosetime()"  onmouseout="mclosetime()"></div>';
			e = document.getElementById('mneg1');
			e.innerHTML = "";
			for (x=0;x<anm.length;x++)
			{
				e.innerHTML += '<a href="' + baseURL + '/browse.php?yid=' + statYear + '&groupID=' + aid[x] +'>' + anm[x] + '</a>';
			}
		}
		else
		{
			d.innerHTML = '<a href="' + splink + '" >' + sname + '</a>';
		}
	}  // nds.subnodes
	
}
function nav_sport(elements)
{
	var aid = Array();
	var anm = Array();
	var aab = Array();
	var xid = Array()
	var xnm = Array()
	var xab = Array()


//	if (typeof(sportDir) == 'undefined' ) 
//		var sportDir = '';
	
	var sid = 0
	var saab = ""
	var sname = ""
	//  Look through the children of the nodes named "school" and find what we want
	if(elements.hasChildNodes())
	{	
		sNds = elements.childNodes;
		
		for (var j=0;j<sNds.length;j++)
		{
			//alert(sNds[j].nodeName);
			if (sNds[j].nodeName == "alternate" && sNds[j].hasChildNodes()) 
				xnm[xnm.length] = sNds[j].firstChild.nodeValue;

			if (sNds[j].nodeName == "alternate_id" && sNds[j].hasChildNodes()) 
				xid[xid.length] = sNds[j].firstChild.nodeValue;

			if (sNds[j].nodeName == "alternate_abbr" && sNds[j].hasChildNodes()) 
				xab[xab.length] = sNds[j].firstChild.nodeValue;
			
			if (sNds[j].nodeName == "selected" && sNds[j].hasChildNodes()) 
				sname = sNds[j].firstChild.nodeValue;

			if (sNds[j].nodeName == "selected_id" && sNds[j].hasChildNodes()) 
				sid = sNds[j].firstChild.nodeValue;

			if (sNds[j].nodeName == "selected_abbr" && sNds[j].hasChildNodes()) 
				saab = sNds[j].firstChild.nodeValue;

		}

		
		
		//the following is designed to determine valid sports:
		
		//~ xid.unshift(sid)
		//~ xnm.unshift(sname)
		//~ xab.unshift(saab)
		
		while ( xid.length > 0 )
		{
			var id = xid.shift(); var name = xnm.shift(); var abbr = xab.shift()

			if (inArray(id,validSports)) 
			{
				aid[aid.length] = id
				anm[anm.length] = name
				aab[aab.length] = abbr
			}
		}
	
		//I don't suppose it matters if the sport is valid _IF_ it's selected, does it?  maybe we should address that by using a js redirect at the top of general, or as soon as sid is determined?  
		/* '''
		 * Ex:
		 * 	if ( ! inArray(sid,validSports) )
		 *  {
		 	* 	alert("Specified Sport not implemented on this site?"
		 	* 	document.location.href = "/browse.php"
		 *	}
		 * ''' 
		 * Alternately, We can redirect to the next sport here: document.location.href="/" + aab[0] + "/browse.php?sid= " + aid[0] + "&ltr=a"
		 * */
		
		
		var d = document.getElementById('sportNav');
		if (aid.length > 1)
		{
			if ( sid == 0 || sname == "" || saab == "")
			{
				
				sid = aid.shift()
				sname = anm.shift()
				saab = aab.shift()	
				
			}
			splink = baseURL + sportDir + '/browse.php?yid=' + statYear + '&sid=' + sid + '&ltr=a';
			
			d.innerHTML = '<a href="' + splink + '" onmouseover="mopen(' + "'m1\'" + ')"  onmouseout="mclosetime()">' + sname + '</a><div id="m1" onmouseover="mcancelclosetime()"  onmouseout="mclosetime()"></div>';
			e = document.getElementById('m1');
			e.innerHTML = "";
			for (x=0;x<aid.length;x++)
			{
				e.innerHTML += '<a href="' + baseURL + aab[x] + '/browse.php?yid=' + statYear + '&sid=' + aid[x] + '&ltr=a" >' + anm[x] + '</a>';
			}
		}
		else
		{
			if (sid == 0) 
			{
				$vj(d).hide()
			}
			else
			{
				splink = baseURL + saab + '/browse.php?yid=' + statYear + '&sid=' + thisSport + '&ltr=a';
				d.innerHTML = '<a href="' + splink + '" >' + sname + '</a>';
			}
		}
		sportName = sname
	}  // nds.subnodes
}
function nav_class(elements)
{
	var aid = Array();
	var anm = Array();
	var sid = 0;
	var sname = ""

//	if (typeof(sportDir) == 'undefined' ) 
//		var sportDir = '';


	//  Look through the children of the nodes named "school" and find what we want
	if(elements.hasChildNodes())
	{	
		sNds = elements.childNodes;
		for (var j=0;j<sNds.length;j++)
		{
			//alert(sNds[j].nodeName);
			if (sNds[j].nodeName == "alternate" && sNds[j].hasChildNodes()) anm[anm.length] = sNds[j].firstChild.nodeValue;
			if (sNds[j].nodeName == "alternate_id" && sNds[j].hasChildNodes()) aid[aid.length] = sNds[j].firstChild.nodeValue;
			if (sNds[j].nodeName == "selected" && sNds[j].hasChildNodes()) sname = sNds[j].firstChild.nodeValue;
			if (sNds[j].nodeName == "selected_id" && sNds[j].hasChildNodes()) sid = sNds[j].firstChild.nodeValue;
		}
		var d = document.getElementById('divisionNav');
		if (!sid)
		{
			$vj(d).hide()
		}
		else 
		{
			divID = sid;
		}
		var dlink = baseURL + sportDir + '/overview.php?yid=' + statYear + '&sid=' + thisSport + '&cid=' + sid;
		
		
		theDiv = sid;
		d.innerHTML = '<a href="' + dlink + '" onmouseover="mopen(' + "'m2\'" + ')"  onmouseout="mclosetime()">' + sname + '</a><div id="m2" onmouseover="mcancelclosetime()"  onmouseout="mclosetime()"></div>';
		var e = document.getElementById('m2');
		
		e.innerHTML = "";
		for (x=0;x<anm.length;x++)
		{
			e.innerHTML += '<a href="' + baseURL + sportDir + '/overview.php?yid=' + statYear + '&sid=' + thisSport + '&cid=' + aid[x] + '" >' + anm[x] + '</a>';
		}
	}  // nds.subnodes
}
function nav_league(elements)
{
	var aid = Array();
	var anm = Array();
	var sname = ""
	var sid = 0

//	if (typeof(sportDir) == 'undefined' ) 
//		var sportDir = '';
	
	if(elements.hasChildNodes())
	{	
		sNds = elements.childNodes;
		for (var j=0;j<sNds.length;j++)
		{
			//alert(sNds[j].nodeName);
			if (sNds[j].nodeName == "alternate" && sNds[j].hasChildNodes()) anm[anm.length] = sNds[j].firstChild.nodeValue;
			if (sNds[j].nodeName == "alternate_id" && sNds[j].hasChildNodes()) aid[aid.length] = sNds[j].firstChild.nodeValue;
			if (sNds[j].nodeName == "selected" && sNds[j].hasChildNodes()) sname = sNds[j].firstChild.nodeValue;
			if (sNds[j].nodeName == "selected_id" && sNds[j].hasChildNodes()) sid = sNds[j].firstChild.nodeValue;
		}
		confID = sid
		var d = document.getElementById('conferenceNav');
		var clink = baseURL + sportDir + '/overview.php?yid=' + statYear + '&sid=' + thisSport + '&cid=' + divID + '&lid=' + sid;
		if (!sid)
		{
			$vj(d).hide()
		}
		else if ( anm.length > 0 ) 
		{
			d.innerHTML = '<a href="' + clink + '" onmouseover="mopen(' + "'m3\'" + ')"  onmouseout="mclosetime()">' + sname + '</a><div id="m3" onmouseover="mcancelclosetime()"  onmouseout="mclosetime()"></div>';
			e = document.getElementById('m3');
			e.innerHTML = "";
			for (x=0;x<anm.length;x++)
			{
				e.innerHTML += '<a href="' + baseURL + sportDir + '/overview.php?yid=' + statYear + '&sid=' + thisSport + '&lid=' + aid[x] + '&cid=' + divID + '" >' + anm[x] + '</a>';
			}
		}
		else
		{
			d.innerHTML = '<a href="' + clink + '" >' + sname + '</a>';
		}
	}
}
function nav_school(elements)
{
	var aid = Array();
	var anm = Array();
	var aoid = Array();


//	if (typeof(sportDir) == 'undefined' ) 
//		var sportDir = '';
	
	
	//  Look through the children of the nodes named "school" and find what we want

	if(elements.hasChildNodes())
	{	
		sname = "";
		var sid = 0;
		var soid = 0;
		var nodes_found = 0;
		sNds = elements.childNodes;
		for (var j=0;j<sNds.length;j++)
		{
			if (sNds[j].hasChildNodes())
			{
				tagName = sNds[j].nodeName
				value = sNds[j].firstChild.nodeValue;
				
				if (tagName == "alternate" ) 		
				{
					anm[anm.length] 	= "" + value;
					nodes_found++
				}
				if (tagName == "alternate_id" ) 	
				{
					aid[aid.length] 	= 0 + parseInt(value);
					nodes_found++
				}
				if (tagName == "alternate_oid" ) 
				{
					aoid[aoid.length]	= 0 + parseInt(value);
					nodes_found++
				}
				
				if (tagName == "selected" ) 		
				{
					sname 				= value;
					nodes_found++
				}
				if (tagName == "selected_id" ) 	
				{
					sid 				= value;
					nodes_found++
				}
				if (tagName == "selected_oid" ) {
					soid 				= value;
					nodes_found++
				}
			}

			/* The following code is neccesitated by bad data, and seems to cause some issues 
			 * cross-browser in part because of the way we're encoding the data
			 * 
			 * specifically, IE doesn't consider #Text to be a node and FF3 does, so we have to 
			 * figure out where the first non-text node falls in the list, this will be selected, 
			 * unless there is no <selected> in the results.  in that case the first <alternate>
			 * tag should trigger the appropriate action: the assignment of 'selected'.
			 * 
			 * the whole point of this code is to fix a bug where (for example, in lacrosse) 
			 * there is no value for alternate, but there is one for alternate_id, the result 
			 * is that the numbers get mixed up unless on the third tag they are synced up.
			 * 
			 * when this happens at the wrong time (say on the second item of a set [of 3] we
			 * end up getting 'undefined's in the navbar (bad)
			 * bw 11/02/2009 - 05:03 MST
			 * 
			 * NOTE: this probably needs to be done using jQuery to eliminate this problem
			 * bw 26/05/2009 - 12:27 MDT
			 */			
			if (((nodes_found) % 3) == 0) 
			{
				//one more than others:
				if (aid.length > aoid.length && aid.length > anm.length) aid.pop() //aid
				if (aoid.length > aid.length && aoid.length > anm.length) aoid.pop() //aoid
				if (anm.length > aid.length && anm.length > aoid.length) anm.pop() //anm
				
				//one less than others
				if (aid.length > anm.length && aoid.length > anm.length){aid.pop();aoid.pop();} //anm
				if (aoid.length > aid.length && anm.length > aid.length){anm.pop();aoid.pop();} //aid
				if (aid.length > aoid.length && anm.length > aoid.length){aid.pop();anm.pop();} //aoid
			}	
		}
		var d = document.getElementById('schoolNav');
		//tmlink = baseURL + sportName + '/team.php?yr=' + statYear + '&sid=' + thisSport + '&tid=' + sid; //switching to organization sport browse instead
		if ( thisSport == 0  && sportDir == "")
		{
			if (soid = 0 && aoid.length > 0)
			{
				soid = aoid.shift()
				sname = anm.shift()
			}
			tmlink = baseURL + 'school.php?yid=' + statYear + '&sid=' + thisSport + '&oid=' + soid;
			if (aoid.length > 0)
			{
				d.innerHTML = '<a href="' + tmlink + '" onmouseover="mopen(' + "'m4\'" + ')"  onmouseout="mclosetime()">' + sname + '</a><div id="m4" onmouseover="mcancelclosetime()"  onmouseout="mclosetime()"></div>';
				e = document.getElementById('m4');
				e.innerHTML = "";
				for (x=0;x<aoid.length;x++)
				{
					//eLinks = baseURL + sportName + '/team.php?yr=' + statYear + '&sid=' + thisSport + '&tid=' + aid[x] //replaceing with up-one-level-school links
					eLinks = baseURL + 'school.php?yid=' + statYear + '&sid=' + thisSport + '&oid=' + aoid[x]
					e.innerHTML += '<a href="' + eLinks + '" >' + anm[x] + '</a>';
				}
			}
			else
			{
				if (sname != "") d.innerHTML = '<a href="' + tmlink + '">' + sname + '</a>';
			}
		}
		else
		{
			if (sid == 0 && aid.length > 0)
			{
				sid = aid.shift()
				sname = anm.shift()
			}
			tmlink = baseURL + sportDir + '/team.php?yid=' + statYear + '&sid=' + thisSport + '&tid=' + sid;
			if (aid.length > 0)
			{
				d.innerHTML = '<a href="' + tmlink + '" onmouseover="mopen(' + "'m4\'" + ')"  onmouseout="mclosetime()">' + sname + '</a><div id="m4" onmouseover="mcancelclosetime()"  onmouseout="mclosetime()"></div>';
				e = document.getElementById('m4');
				e.innerHTML = "";
				for (x=0;x<aid.length;x++)
				{
					//eLinks = baseURL + sportName + '/team.php?yr=' + statYear + '&sid=' + thisSport + '&tid=' + aid[x] //replaceing with up-one-level-school links
					eLinks = baseURL + sportDir + '/team.php?yid=' + statYear + '&sid=' + thisSport + '&tid=' + aid[x]
					e.innerHTML += '<a href="' + eLinks + '" >' + anm[x] + '</a>';
				}
			}
			else
			{
				if (sname != "") d.innerHTML = '<a href="' + tmlink + '" >' + sname + '</a>';
			}
		}
	} 
}
function nav_team(elements)
{
	var aid = Array();
	var anm = Array();
	var aan = Array();
	san = "";
	sname = "";
	sid = 0;

//	if (typeof(sportDir) == 'undefined' ) 
//		var sportDir = '';


	//  Look through the children of the nodes named "school" and find what we want
	if(elements.hasChildNodes())
	{	
		
		
		sNds = elements.childNodes;
		for (var j=0;j<sNds.length;j++)
		{
			if (sNds[j].hasChildNodes())
			{
				tagName = sNds[j].nodeName
				value = sNds[j].firstChild.nodeValue;
				
				if (tagName == "alternate" ) 			anm[anm.length] = value;
				if (tagName == "alternate_id" ) 		aid[aid.length] = value;
				if (tagName == "alternate_AbbrName" ) 	aan[aan.length] = value;
				if (tagName == "selected" ) 			sname 			= value;
				if (tagName == "selected_id" ) 			sid 			= value;
				if (tagName == "selected_AbbrName" ) 	san 			= value;
			}
		}
		var d = document.getElementById('teamNav');
		if (aid.length > 1)
		{
			if (sid == 0 || sname == "" || san == "")
			{
				sid = aid.shift();
				sname = anm.shift();
				san = aan.shift();
			}
			tmlink = baseURL + san + '/team.php?yr=' + statYear + '&sid=' + thisSport + '&tid=' + sid;
			d.innerHTML = '<a href="' + tmlink + '" onmouseover="mopen(' + "'m5\'" + ')"  onmouseout="mclosetime()">' + sname + '</a><div id="m5" onmouseover="mcancelclosetime()"  onmouseout="mclosetime()"></div>';
			e = document.getElementById('m5');
			e.innerHTML = "";
			for (x=0;x<anm.length;x++)
			{
				e.innerHTML += '<a href="' + baseURL + aan[x] + '/team.php?yr=' + statYear + '&sid=' + thisSport + '&tid=' + aid[x] + '" >' + anm[x] + '</a>';
			}
		}
		else
		{
			if (sid == 0)
			{
				$vj(d).hide();
			}
			else
			{
				tmlink = baseURL + san + '/team.php?yr=' + statYear + '&sid=' + thisSport + '&tid=' + sid;
				d.innerHTML = '<a href="' + tmlink + '" >' + sname + '</a>';
				
			}
		}

	}  // nds.subnodes	
}

/*this gets the real value from a node reached using 
 * $vj("channel item",xml).each(function(i,n)
 * {
 * 		thisItem = {}
 * 		$vj(n).children().each(function(i,n){
 *			thisItem[n.tagName] = get_real_value(n);
 *		});
 *  	//do some stuff with thisItem...
 * }
 */
function get_real_value(value)
{
	
	//return ((isNaN(parseInt( RealValue = $vj(value).text())) || parseInt( RealValue = $vj(value).text()).toString() != RealValue) ? RealValue : parseInt(RealValue));
	realValue = $vj(value).text()
	//if the value is not a number return it as a string
	if (isNaN(parseInt(realValue)) || parseInt(realValue).toString() != realValue)
		return realValue
	else //return as a numeric value
		return parseInt(realValue)
}
function date_from_datetime(datetime)
{
	return /^[^\ ]+/.exec(datetime);
}
function time_from_datetime(datetime)
{
	return /[^\ ]+$vj/.exec(datetime)
}

/* this is a differencing link-builder, just pass in an object in 
 * the form, {uri_key:value} and the link-builer will make a 
 * current-state change to that, and serialize it into uri form, 
 * and pass it back, you can send the target page as either a 
 * component of the input or as the second parm 'target'
 * bw -15/07/2009 10:56 - documented
 */
function vvBuildLink(input_values,target)
{
	var values = {}, dn;
 	if (typeof(input_values) == "string")
 	{	//convert values specfied as uri-delimeted string into an object
 		var tempvalues = {};
		var items = input_values.replace(/^\??/,"").split("&")
 		for(x in items) 
		{ 
			if (typeof(items[x]) == 'function')
				break;

			var pair = items[x].split("="); 
			var key = pair[0]; 
			var value = pair[1]; 
			tempvalues[key] = value; 
		}
		values = tempvalues;
	}
	else {
		if (typeof(input_values) != 'undefined' ) 
			values = input_values;
	}
	
 	var get = Array();
	var myKeys = Array();			// hold the key values
	var gidx = 0;
 	if(typeof(values.page_name) != 'undefined') {
 		var page = values.page_name + ".php"
 		delete values.page_name
	}
	else
	{
		var page = false;
	}
	if (typeof(values.clean) == 'undefined' || !(values.clean) )  {
		for ( x in keys) {
			if (typeof(keys[x]) == 'function')
				break;

			// tennis abomination to work around the schedview/altset issue
			// replace 'schedview' with 'altset' when building URL links
			var newX = x;
//			if (x == 'schedview' && typeof(keys['altset']) == 'undefined')
//				newX = 'altset';

			get[newX] = keys[x]; 
			myKeys[gidx++] = newX;		// track the key values
		}	
	}
	values.clean = false, delete values.clean;
	
	
	for (x in values) { 
		if (typeof(values[x]) == 'function')
			break;


		// tennis abomination to work around the schedview/altset issue
		// replace 'schedview' with 'altset' when building URL links
		var newX = x;
//		if (x == 'schedview' && typeof(keys['altset']) == 'undefined')
//			newX = 'altset';

		get[newX] = values[x] 
		myKeys[gidx++] = newX;		// track the key values
	}
	link = "";

	// need to iterate arrays differently

	for (i = 0; i < gidx; ++i) { 
		y = myKeys[i];			// property name for 'get' array


		//added null checking bw -15/07/2009 07:04
		if (get[y] != null)	
			link += ( ("" + get[y]) == 'undefined' || get[y].toString() == '') ? "" : "&" + y + "=" + get[y]; 
	}
	link = ((page) ? baseURL + (((dn = getDirName()) == '') ? '' : dn + "/") + page : document.location.protocol + "//" + document.location.hostname + document.location.pathname ) + "?" + link.replace(/^&/,"")

	if (typeof(target) != 'undefined') 
		link += "#" + target;
	return link;
}

function toURI(oObj)
{
	var myStr = '';
	if (typeof(oObj) != 'object') return false;
	for (x in oObj) { 
		if (typeof(oObj[x]) == 'function')
			break;

		myStr += "&" + x + "=" + oObj[x]; 
	}
	return myStr;
}


/* vvMenu:
 * Last Modified: bw 19/03/2009 - 10:18 MDT
 * This creates a dropdown menu in the style of navigation bar, and uses the same stylesheet to display it
 *
 */
function vvMenu(destPageName)
{

	this.destinationPageName = destPageName || getPageName();
	this.destinationObject = new $vj;
	this.items = [];
	this.anchor = function(destObj)
	{
		if (typeof(destObj) != 'undefined' ) this.destinationObject = destObj;
		return this.destinationObject;
	};
	this.dest_page = function(destPageName)
	{
		if (typeof(destPageName) != 'undefined' ) this.destinationPageName = destPageName;
		return this.destinationPageName;
	}
	this.add_item = function(item)
	{
		return this.items[this.items.length] = item
	}
	this.get_item = function(i)
	{
		return this.items[i];
	}
	this.create = function (name)
	{
		if (! $vj(this.destinationObject).length) 
			return void(0);

		items = this.items;
		name = ( name || '');
		var selected_item = null;
		
		for ( i in items) { 
			if (typeof(items[i]) == 'function')
				continue;		// changed from 'break'

			if ('selected' in items[i]) 
				{ selected_item=items.splice(i,1).shift(); 
					break; 
				} 
		}

		if ( selected_item == null ) 
			selected_item = items.shift();
		
		d = $vj('<div />')
		d.attr('id',name + '_menu');

		var item_name = "" ;

		// this this only if we have something selected
		if (selected_item != null ) {
			selected_item.page_name = this.destinationPageName
			item_name = ("" + selected_item.name);
			delete selected_item.name
			delete selected_item.selected
			log(selected_item)
			d.html((item_name).link(vvBuildLink(selected_item)))
		}

		if (items.length > 0)
		{
			d.find('a')
					.mouseover(function(){ mopen(name + '_dropdown'); })
					.mouseout(mclosetime)
			d.append(dropdown = $vj('<div style="" id="' + name + '_dropdown"></div>'));
			for (i in items)
			{
				if (typeof(items[i]) == 'function')
					continue;		// changed from 'break'

				item_name = items[i].name;
				delete items[i].name
				items[i].page_name = this.destinationPageName
				dropdown
					.append(item_name.link(vvBuildLink(items[i])))
					.mouseover(mcancelclosetime)
					.mouseout(mclosetime)
			}
		}
		$vj(this.destinationObject).append(d.children());
		return true;
	}
}

/*
 * a pager widget in general...
 * the only required param is totalRecs,
 * destRow should be a HTMLTableRowElement object or implement it's interfaces. Otherwise a new row will be created and returned.
 * colspan1,2 are for fixing display issues so that the label and the page-list will fit into appropriate numbers of columns, YMMV
 * currently this really only works well in the leaderbaord and overview contexts, and your feed requests need to be pager-aware.  recomend exactly 1 per page, eh? bw 27/01/2009 - 13:07 MST
 */
function pager(totalRecs,destRow,colspan1,colspan2,additives)
{
	if (typeof(totalRecs) == 'undefined') 
	{
		//log("pager: no params");
		return "&page_len=" + recordsPerPage + "&page_no=" + (thisPage -1)
		return void(0);
	}
	else if( totalRecs == 'schedule')
	{
		return "&page_len=" + recordsPerPage + "&page_no=" + (thisPage -1) + "&" + ((!(dispall) || dispall == "false") ? 'upcomming' : '_displayall')
	}

	var base_uri = vvBuildLink(additives);
	if (typeof(totalRecs) == 'string' && totalRecs.split(",").shift().toLowerCase() == 'more')
	{
		thisPage = 2;
		var arg_order = ['totalRecs','destRow','colspan1','colspan2','additives'];
	}
	if (totalRecs > recordsPerPage)
	{
		//destRow = tbody.insertRow(tbody.rows.length);
		var firstRecord = ( (thisPage - 1) * recordsPerPage ) + 1
		var lastRecord = Math.min((firstRecord + recordsPerPage - 1 ),totalRecs)
		var lastpage = ((totalRecs - (totalRecs % recordsPerPage)) / recordsPerPage) + ((totalRecs % recordsPerPage) > 0)
		var start = ((thisPage - 6 > 0) ? (thisPage - 6) : 0);
		var end = ((start + 10) < lastpage) ? start + 10 : lastpage;
		
		//duck-typing for the interface we need in order to complete the process, and substituting on failure
		if (!(typeof(destRow) != 'undefined' && typeof(destRow.insertCell) != 'undefined')) destRow = document.createElement("TR");
		if (typeof(destRow.innerText) != 'undefined'){
			$vj(destRow).text('')
		}
		else log(destRow);
		while(destRow.firstChild != null) {destRow.removeChild(destRow.firstChild);}
		var col = 0;
		if ( !( $vj(destRow).hasClass(rc[0]) || $vj(destRow).hasClass(rc[1]))) $vj(destRow).addClass(rc[(lastRecord ) % 2]);
		$vj(destRow.insertCell(col++)).attr('colSpan',( colspan1 || 3)).html('Page ' + thisPage + ': Displaying Results ' + firstRecord + ' - ' + lastRecord + " of " + totalRecs + ". " + lastpage + ' Total Pages.');
		var PageNavigation = $vj(newCell = destRow.insertCell(col++)).attr('align','center').attr('colSpan',( colspan2 || 50))
		//add first, prev links
		if ( thisPage > 1 ){
			$vj(newCell).html("First".link(base_uri + "&page=1") + " ")
				.append("Prev".link(base_uri + "&page=" + (thisPage - 1).toString()) + " ");
		}
		else $vj(newCell).html("First".bold() + " \n");
		//add page links
		for (i = (start + 1); i < ( Math.ceil(totalRecs / recordsPerPage) + 1 ) && i < (end + 1); i++)
		{
			if ( i == thisPage) $vj(newCell).append(i.toString().bold() + " ");
			else  $vj(newCell).append(i.toString().link(base_uri + "&page=" + i) + " ")
		}
		//add next,last links
		if ( thisPage < lastpage ) {
			$vj(newCell).append("Next".link(base_uri + "&page=" + (parseInt(thisPage) + 1).toString()) + " ")
				.append("Last".link(base_uri + "&page=" + lastpage ) + " ");			
		}
		else $vj(newCell).append("Last".bold());
		//in the event that nothing was specified and the pager is being included inline as with <td class='looklikelink' onclick = "this.parentElement.innerHTML = pager(60,void(0),5,6)">More ...</td>
		return destRow;
	}
	return void(0);
}

getPageName = new Function();
getPageName = (function(){
	var pageName //this implements a static variable as a local variable in a closure using Javascript's nested scope.  the value can only be assigned inside the function returned
	return function ()
	{
		return (pageName || (pageName = document.location.pathname.toString().replace(baseURL.replace(/\/$/,""),"").split("/").pop().split(".php").shift()))
	}
})();

/* this slices baseURL off of the URI */
function rel_uri()
{
	return document.location.href.toString().replace(baseURL.replace(/\/$/,"/"),"");
}

getDirName = function()
{
	R = /(\w+)\//ig
	if(typeof(sportDir) == 'undefined' )
	{
		return [(M = R.exec(rel_uri())), (M != null) ? M[1] : ''][1]
	}
	else
	{
		return sportDir
	}
}


function add_coach_link()
{
	var n = getPageName();

	if ( n == 'player') coachContent = '<div id="coachPromo" style="width:650px"><strong>Don\'t see your stats?</strong> Ask your coach to register at <span><a href="http://www.varvee.com"> www.varvee.com. It\'s easy to do and great for you.<img src="' + baseURL + 'img/smalllogo.gif" style="border:none; margin-top:3px; display: inline;" alt="" /></a></div><div style="clear:both"></span></div>';
	else coachContent = '<div id="coachPromo"><strong>Coach</strong> - Don\'t see your stats?  <span><a href="http://www.varvee.com/coaches" title="VarVee.com" target="_blank" >Register by clicking here to enter your stats.&nbsp;&nbsp;<img src="' + baseURL + 'img/smalllogo.gif" style="border:none; margin-top:3px; display: inline;" alt="" /></a></span></div>';

	//if the coach promo isn't already loaded at least once, add it after #breadcrumbsNav
	if (! $vj('#breadcrumbsNav + #coachPromo').length) $vj('#breadcrumbsNav').after(coachContent);
}
$vj(document).ready(add_coach_link);

function add_ads(partnerID)
{
////	var ps = $vj.getScript(adsURL + "?page=" + getPageName() + "&sid=" + thisSport + "&pid=" + partnerID); 
	return;
}

function setTeamPageLinks() {
	// Set links & text for team pages ease of navigation (top) links
	var linkExtra = "?cid=" + confID + "&did=" + divID + "&sid=" + thisSport + "&tid=" + teamID + "&yid=" + statYear;
	$vj("#topTeamRoster").append('<a href="roster.php' + linkExtra + '">Team Roster</a>');
	$vj("#topTeamSchedule").append('<a href="schedule.php' + linkExtra + '">Team Schedule</a>');
	$vj("#topTeamLeadersT").append("<a href=\"javascript:buildURL('" + sportDir + "','leaders-team');\">Leaderboard by Team</a>");
	$vj("#topTeamLeaders").append("<a href=\"javascript:buildURL('" + sportDir + "','leaders');\">Individual Leaderboard</a>");
}



