var show_alert_error = 0;

/* --- Tab Setup --- */
function gz_Tabs(vars, postVars) {
	this.tabs = {};
	this.self = this;	
	this.hash = location.hash.replace('#','');
	
	this.id_tabs = vars.id_tabs;
	this.tabBar = $i(this.id_tabs);
	this.id_contents = vars.id_contents;
	this.contents = $i(this.id_contents);	
	this.url = vars.url ? vars.url : '/ajax/gamezone_content_handler.php';
	this.lazy_load = vars.lazy_load;
	this.default_tab = vars.default_tab;
	this.o = {showTabSpinner:false};
	
	for(var i in vars) {
		this.o[i] = vars[i];
	}
	
	this.postVars = postVars;
	
	this.init();
}
gz_Tabs.prototype = {
	
	init : function() {
		
		//Watch Events
		var self = this;
		setInterval(function() { self.WatchHash() }, 25);
		
		
		//Get Tab Referances
		var As = this.tabBar.getElementsByTagName('A');
		for(var i=0; i<As.length; i++) {
			this.tabs[ As[i].href.replace(/([^#])+?#/,'') ] = {o:As[i].parentNode};
			As[i].onclick = function() { setTimeout(function() { self.WatchHash() }, 25); };
		}
		
		//load first tab
		if ( !this.hash || !this.SwitchToTab(this.hash) ) {
			this.SwitchToTab(this.default_tab); // Default Tab
		}
		
		this.lazyloader();
		
		// IE6 Hover
		if ($i('ie6')) {
			tr_setup_sfhover( this.tabBar.getElementsByTagName('LI') );
		}
		
	},
	
	WatchHash : function() {
		var h=location.hash.replace('#','');
		if (h != this.hash) { 
			this.hash = h;
			this.TabSelected();
		}
	},
	
	TabSelected : function(tabName) {
		if (!tabName) { tabName = this.hash; }
		var content = this.GetContent( tabName );
		if (content) {
			this.SwitchToTab( tabName );
		} else {			
			this.LoadTab( tabName );
		}
	},
	
	SwitchToTab : function(tabName) {
		
		if (this.tabs[ tabName ]) {
		
			var tab = this.tabs[ tabName ].o;	
			var content = this.GetContent( tabName );
			
			if (content) {
				
				this.UnselectOldTab();
		
				this.Select( tab );
				this.Select( content );
						
				this.selectedTab = tab;
				this.selectedContent = content;
				
				if ( gz_Events[ tabName ] ) {
					gz_Events[ tabName ](this);
				}
				
			} else {
				
				this.LoadTab( tabName );
				
			}
			
			return true;
		
		}
	},
	
	UnselectOldTab : function() {
		if (this.selectedTab) {
			this.Unselect( this.selectedTab );
			this.Unselect( this.selectedContent );
		}
	},
	
	LoadTab : function(c, noSelect, noSpinner) {
		if (this.tabs[c] && !this.tabs[c].loading) { 
			this.tabs[c].loading = true;
			
			var content = this.GetContent( c, true );
			content.innerHTML = 'test';
			
			if (!noSpinner) {
				content.defaultWidth = 975;
				content.defaultHeight = 200;
				this.tabs[c].spinner = new Spinner( content , this.tabs[c].o  ? this.tabs[c].o.firstChild.innerHTML : '' );
			}
			if (!noSelect) {
				this.SwitchToTab( c );
			}
			
			var A = new Ajax();	
			A.o = this;
			A.c = c;
			A.fire( this.url , function(r) { A.o.LoadTabReceived(r, A) }, 'c='+c+this.postVarStr());
		}
	},
	
	LoadTabReceived : function(r, A) {
		obj = A.o;
		c = A.c;
		
		if (r != '-1') {
			var content = obj.GetContent( c, true );
			content.innerHTML = r;
			
			if (obj.tabs[ c ].spinner) {
				obj.tabs[ c ].spinner.destroy();
				obj.tabs[ c ].spinner = null;
			}
			
			obj.tabs[c].loading = false;

			if ( gz_Events[ c + '_loaded' ] ) {
				gz_Events[ c + '_loaded' ](obj);
			}
		}
	},
	
	postVarStr : function() {			
		var qStr = '';
		for(i in this.dropdowns) {
			qStr += '&' + i + '=' + this.dropdowns[i].obj.value;
		}
		
		postVars = this.postVars;
		for(var i in postVars) {
			qStr += '&' + i + '=' + postVars[i];
		}
		return qStr;
	},
	
	
	// -- Preloader -- //
	
	lazyloader : function() {		
		for(var i in this.lazy_load) {
			this.LoadTab( this.lazy_load[i], true );
		}		
	},
	
	
	// -- Generic -- //
	
		
	GetContent : function(tab, create) {
		content = $i(this.ContentId(tab));
		if (create && !content) {
			var content = createNode('div');
			content.setAttribute('id', this.ContentId( tab ) ); 
			content.className = 'gz_content';
			this.contents.appendChild( content );
		}
		return content;
	},
	
	ContentId : function(tab) {
		return this.id_contents + '_' + tab;
	},
		
	Select : function( obj ) {
		if (!obj.className.match('tr_selected')) {
			obj.className += ' tr_selected';
		}
		if (obj.parentNode.parentNode.className.match(/gz_drop/)) {
			Addclass( obj.parentNode.parentNode , 'tr_selected_sub' );	
		}
	},	
	Unselect : function( obj ) {
		obj.className = obj.className.replace('tr_selected', '');
		if (obj.parentNode.parentNode.className.match(/gz_drop/)) {
			Removeclass( obj.parentNode.parentNode , 'tr_selected_sub' );	
		}
	}
	
}


function gz_Events() {}






// -- General Functions -- //

function Spread(n) {
	if (n>0) {
		return '+'+n;	
	} else if (n == 0) {
		return 'pick';	
	} else {
		return n;	
	}
}


// -- Adv Arrows -- //

function GetArrow(a) {
	a += '';
	if (a.match('d')) {
		a = a.replace('d','');
		newHTML = '';
		newHTML += '<div class="tr_arrowed_double">';
		newHTML += '<span class="tr_arrowed_l"><span class="tr_arrowed_'+a+'"></span></span>';
		newHTML += '<span class="tr_arrowed_r"><span class="tr_arrowed_'+a+'"></span></span>';
		newHTML += '</div>';
		//return newHTML;
		return '';
	} else {
		a *= 1;
		direction = a * 1 > 0 ? 'r':'l';
		a = Math.abs(a);
		if (a == 0) { return ''; }
		return '<span class="tr_arrowed_'+direction+'"><span class="tr_arrowed_'+a+'"></span></span>';
	}
}

function gz_ArrowTables( ids ) {
	var i, t, tds, j, a, m;
	for(i in ids) {
		t = $i(ids[i]);
		if ( t ) {
			m = t.getAttribute('arrow_mode');
			m = m ? m : 'fade';
			tds = t.getElementsByTagName('TD');
			for(j in tds) {
				if (tds[j].tagName == 'TD') {
					a = tds[j].getAttribute('adv');
					if (a) {
						tds[j].innerHTML = GetArrow( a );
						Addclass(tds[j], 'gz_a_adv gz_a_adv_'+m );
					}
				}
			}
		}
	}
}



// -- Game Chooser Scroller -- //

var gc_scroll_TO;
var gc_scroll_speed = 5;
var gc_offset = 0;
var gc_dest = 0;
var maxWidth, gameWidth;

function gc_Scroll(d, jumpTo) {
	i = window.innerHeight || document.documentElement.clientHeight;
	h = $i('gz_gc_games_wrapper').scrollWidth;
	a = $i('gz_gc_games_list').style.left.replace('px','') * 1;
	if(d>a)
		if(h-d>i)
			a+=Math.ceil((d-a)/gc_scroll_speed)
		else
			a+=Math.ceil((d-a-(h-d))/gc_scroll_speed)
	else
		a = a+(d-a)/gc_scroll_speed;
		
	if (Math.abs( a - d ) < 5 || jumpTo) { a = d; }		
	$i('gz_gc_games_list').style.left = a + 'px';	
	
	if(a==d || gc_offset==a) { 
		clearInterval(gc_scroll_TO);
		gc_Scroll_CheckSides();	
		gc_scroll_TO = false;
		$i('gz_gc_games_wrapper').style.visibility = 'visible';
	}
	gc_offset=a
}
function gc_Scroll_Go(direction, d) {
	if (gc_scroll_TO) {
		clearInterval(gc_scroll_TO);
		gc_offset = gc_dest;
		$i('gz_gc_games_list').style.left = gc_offset + 'px';
	}
	
	var games = $i('gz_gc_games_list').getElementsByTagName('LI');
	gc_dest = d ? d : $i('gz_gc_games_wrapper').offsetWidth * direction + gc_offset; 

	gameWidth = games[0].offsetWidth; 
	maxWidth = games.length * games[0].offsetWidth - $i('gz_gc_games_wrapper').offsetWidth;
	
	if (gc_dest > 0) { gc_dest = 0; }
	if (gc_dest < -1 * maxWidth ) { gc_dest = -1 * maxWidth; }
	gc_scroll_TO = setInterval('gc_Scroll(' + gc_dest + ')',10);
}
function gc_Scroll_CheckSides() {
	if ( $i('gz_gc_games_list').style.left.replace('px','') * 1 >= 0) {
		Addclass( $i('gz_gc_prev'), 'gz_dim' );
	} else {
		Removeclass( $i('gz_gc_prev'), 'gz_dim' );			
	}
	if ( $i('gz_gc_games_list').style.left.replace('px','') * 1 <= -1 * maxWidth) {
		Addclass( $i('gz_gc_next'), 'gz_dim' );
	} else {
		Removeclass( $i('gz_gc_next'), 'gz_dim' );			
	}
}
function gc_Scroll_GoSelected() {
	var sel = getElementsByClassName( $i('gz_gc_games_list'), 'li', 'tr_selected' )[0];
	if (sel) {
		width = $i('gz_gc_games_list').getElementsByTagName('LI')[0].offsetWidth; 
		ParCoords = findPos( $i('gz_gc_games_wrapper') );
		coords = findPos( sel );
		//alert( '('+ParCoords[0] +'-'+ coords[0] + ' | ' + $i('gz_gc_games_wrapper').offsetWidth + ' / ' +  2 + ' - ' + width + ' / ' + 2 + ')' );
		gc_Scroll_Go(null,  (ParCoords[0] - coords[0] + $i('gz_gc_games_wrapper').offsetWidth / 2 - width/2) );
	} else {
		$i('gz_gc_games_wrapper').style.visibility = 'visible';	
	}
}

function gz_Chooser_SelectTeam() {
	if ($i('gz_gc_team').value > 0) {
		document.location.href='/' + $i('gz_gc_sport').value + '/gamezone/matchup.php?tm=' + $i('gz_gc_team').value + '&s=' + $i('gz_gc_season').value + '&dt=' + $i('gz_gc_date').value +  document.location.hash;
	}
}

function gz_Chooser_SelectDate() {
	if ($i('gz_gc_date').value != '') {
		document.location.href='/' + $i('gz_gc_sport').value + '/gamezone/index.php?v=' + $i('gz_gc_page').value + '&dt=' + $i('gz_gc_date').value +  document.location.hash;
	}
}

function bb_Chooser_SelectDate() {
	if ($i('gz_gc_date').value != '') {
		document.location.href='/bracket-brains/betting/index.php?v=' + $i('gz_gc_page').value + '&dt=' + $i('gz_gc_date').value +  document.location.hash;
	}
}



// -- //

function gz_gc_Toggle(o) {
	if ( o.innerHTML == 'hide game boxes' ) {
		$i('gz_gc_games').style.display = 'none';
		o.innerHTML = 'show game boxes';
	} else {
		$i('gz_gc_games').style.display = 'block';
		o.innerHTML = 'hide game boxes';			
	}
}

//

function gz_MouseRows(id) {
	try {
		if (window.attachEvent && tr_setup_sfhover) {
			tr_setup_sfhover( $i(id).getElementsByTagName('TR') );
		}
	} catch(e) {}
}




// -- General Functions -- //
function clone(s) {
for(var p in s)
this[p] = (typeof(s[p]) == 'object')? new clone(s[p]) : s[p];
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
	
function AddStyleRule(selector, rule) {
	styleSheetObj=document.styleSheets[0];
	if (styleSheetObj.addRule) {
		styleSheetObj.addRule(selector,rule);
	} else {
		styleSheetObj.insertRule(selector+" { "+rule+"; } ", styleSheetObj.cssRules.length);			
	}
}

function postVarStr() {
  var qStr = '';
  for(var i in gz_postVars) {
      qStr += '&' + i + '=' + gz_postVars[i];
  }
  return qStr;
}

/*************************************************************
* NLB Background Color Fader v1.0
* Author: Justin Barlow - www.netlobo.com
* MODIFIED FOR TEAM RANKINGS
*
* Description:
* The Background Color Fader allows you to gradually fade the
* background of any HTML element.
*
* Usage:
* Call the Background Color Fader as follows:
*   NLBfadeBg( elementId, startBgColor, endBgColor, fadeTime );
*
* Description of Parameters
*   elementId - The id of the element you wish to fade the
*             background of.
*   startBgColor - The background color you wish to start the
*             fade from.
*   endBgColor - The background color you want to fade to.
*   fadeTime - The duration of the fade in milliseconds.
*************************************************************/

var nlbFade_hextable = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // used for RGB to Hex and Hex to RGB conversions
var nlbFade_elemTable = new Array( ); // global array to keep track of faded elements
var nlbFade_t = new Array( ); // global array to keep track of fading timers
function NLBfadeBg( elementId, startBgColor, endBgColor, fadeTime )
{
	var timeBetweenSteps = Math.round( Math.max( fadeTime / 300, 30 ) );
	var nlbFade_elemTableId = nlbFade_elemTable.indexOf( elementId );
	if( nlbFade_elemTableId > -1 )
	{
		for( var i = 0; i < nlbFade_t[nlbFade_elemTableId].length; i++ )
			clearTimeout( nlbFade_t[nlbFade_elemTableId][i] );
	}
	else
	{
		nlbFade_elemTable.push( elementId );
		nlbFade_elemTableId = nlbFade_elemTable.indexOf( elementId );
	}
	var startBgColorRGB = hexToRGB( startBgColor );
	var endBgColorRGB = hexToRGB( endBgColor );
	var diffRGB = new Array( );
	for( var i = 0; i < 3; i++ )
		diffRGB[i] = endBgColorRGB[i] - startBgColorRGB[i];
	var steps = Math.ceil( fadeTime / timeBetweenSteps );
	var nlbFade_s = new Array( );
	for( var i = 1; i <= steps; i++ )
	{
		var changes = new Array( );
		for( var j = 0; j < diffRGB.length; j++ )
			changes[j] = startBgColorRGB[j] + Math.round( ( diffRGB[j] / steps ) * i );
		if( i == steps )
			nlbFade_s[i - 1] = setTimeout( 'document.getElementById("'+elementId+'").style.backgroundColor = "'+endBgColor+'";', timeBetweenSteps*(i-1) );
		else
			nlbFade_s[i - 1] = setTimeout( 'document.getElementById("'+elementId+'").style.backgroundColor = "'+RGBToHex( changes )+'";', timeBetweenSteps*(i-1) );
	}
	nlbFade_t[nlbFade_elemTableId] = nlbFade_s;
}
function hexToRGB( hexVal )
{
	hexVal = hexVal.toUpperCase( );
	if( hexVal.substring( 0, 1 ) == '#' )
		hexVal = hexVal.substring( 1 );
	var hexArray = new Array( );
	var rgbArray = new Array( );
	hexArray[0] = hexVal.substring( 0, 2 );
	hexArray[1] = hexVal.substring( 2, 4 );
	hexArray[2] = hexVal.substring( 4, 6 );
	for( var k = 0; k < hexArray.length; k++ )
	{
		var num = hexArray[k];
		var res = 0;
		var j = 0;
		for( var i = num.length - 1; i >= 0; i-- )
			res += parseInt( nlbFade_hextable.indexOf( num.charAt( i ) ) ) * Math.pow( 16, j++ );
		rgbArray[k] = res;
	}
	return rgbArray;
}
function RGBToHex( rgbArray )
{
	var retval = new Array( );
	for( var j = 0; j < rgbArray.length; j++ )
	{
		var result = new Array( );
		var val = rgbArray[j];
		var i = 0;
		while( val > 16 )
		{
			result[i++] = val%16;
			val = Math.floor( val/16 );
		}
		result[i++] = val%16;
		var out = '';
		for( var k = result.length - 1; k >= 0; k-- )
			out += nlbFade_hextable[result[k]];
		retval[j] = padLeft( out, '0', 2 );
	}
	out = '#';
	for( var i = 0; i < retval.length; i++ )
		out += retval[i];
	return out;
}
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function( val, fromIndex ) {
		if( typeof( fromIndex ) != 'number' ) fromIndex = 0;
		for( var index = fromIndex, len = this.length; index < len; index++ )
			if( this[index] == val ) return index;
		return -1;
	}
}
function padLeft( string, character, paddedWidth )
{
	if( string.length >= paddedWidth )
		return string;
	else
	{
		while( string.length < paddedWidth )
			string = character + string;
	}
	return string;
}



// ------- Javascript Fade ----- //

function opacity(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++)
			{
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function shiftOpacity(id, millisec) {
	//if an element is invisible, make it visible, else make it ivisible
	if(document.getElementById(id).style.opacity == 0) {
		opacity(id, 0, 100, millisec);
	} else {
		opacity(id, 100, 0, millisec);
	}
}

function blendimage(divid, imageid, imagefile, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;
	
	//set the current image as background
	document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")";
	
	//make image transparent
	changeOpac(0, imageid);
	
	//make new image
	document.getElementById(imageid).src = imagefile;

	//fade in image
	for(i = 0; i <= 100; i++) {
		setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed));
		timer++;
	}
}

function currentOpac(id, opacEnd, millisec) {
	//standard opacity is 100
	var currentOpac = 100;
	
	//if the element has an opacity set, get it
	if(document.getElementById(id).style.opacity < 100) {
		currentOpac = document.getElementById(id).style.opacity * 100;
	}

	//call for the function that changes the opacity
	opacity(id, currentOpac, opacEnd, millisec)
}

//

function removeChildrenFromNode(node) {
	if (node != null) {
		var len = node.childNodes.length;
		
		while (node.hasChildNodes()) {
		  node.removeChild(node.firstChild);		  
		}
	}
}

function whatkeys(obj) {		
	var str = '';
	for(var keys in obj) { str += ' | ' + keys; }
	alert( str );
}
function loadScript(scriptURL) { var scriptElem = document.createElement('SCRIPT'); scriptElem.setAttribute('language', 'JavaScript'); scriptElem.setAttribute('src', scriptURL); document.body.appendChild(scriptElem);}
function xray() { loadScript('http://westciv.com/xray/thexray.js'); }

var profileTests = {};
function ProfileStart(what) {
	var d = new Date();
	profileTests[ what ] = {'start':d.getTime(),'split':d.getTime()};
	$i('profiling').innerHTML += '------- <BR>'
}
function ProfileSplit(what, it) {
	var d = new Date();
	$i('profiling').innerHTML += what + ' | ' + it + ' | ' + ( (d.getTime() - profileTests[what].start) / 1000 ) + ' | ' + ( (d.getTime() - profileTests[what].split) / 1000 ) + ' <BR>';
	profileTests[ what ].split = d.getTime();
}


/* --- */

function invertSpreadsInThisTable(sel) {
	var obj = sel;
	var state = sel.value;
	var i, ii, tds, tbodys;
	
	//Get Table
	while( obj.parentNode.tagName != 'TABLE' ) {
		obj = obj.parentNode;
	}
	var table = obj.parentNode;
	
	if (state != table.getAttribute('spreadInvertState')) {
		
		tbodys = table.getElementsByTagName('tbody');
		for(i in tbodys) {
			if (tbodys[i].getElementsByTagName) {
				tds = tbodys[i].getElementsByTagName('td');
				for(ii in tds) {
					if (tds[ii].innerHTML) {
						if (tds[ii].innerHTML.match( new RegExp("\\-([0-9\\.]+)") )) {
							tds[ii].innerHTML = '+' + RegExp.$1;
						} else
						if (tds[ii].innerHTML.match( new RegExp("\\+([0-9\\.]+)") )) {
							tds[ii].innerHTML = '-' + RegExp.$1;
						}
					}
				}
			}
		}
		
		table.setAttribute('spreadInvertState', state);
	}
	
}


