/*
common javascript functions included on all pages throughout site
*/


/* no framing! */
if (top.location != location) {
  top.location.href = document.location.href ;
}


/* user must have cookies enabled to play */
var tmpcookie = new Date();
chkcookie = (tmpcookie.getTime() + '');
document.cookie = "chkcookie=" + chkcookie + "; path=/";
if (document.cookie.indexOf(chkcookie,0) < 0 && location.href.indexOf('cookies.asp') == -1) {	
	window.location = '/cookies.asp';
}


//open the bracket window
function openBracket(url) {	
	var winWidth = 770; //regular window width
	//ie on pc gets shorter window
	if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.platform.indexOf("Win") != -1) {			
		var winHeight = 605; //regular window height
	}
	else {
		var winHeight = 625; //regular window height
	}
		
	if (screen.width) {
		if (screen.width < winWidth) {
			winWidth = screen.width - 100; //adjusted window width
		}
		
		if (screen.height < winHeight) {
			winHeight = screen.height - 200; //adjusted window height
		}
				
	}	
	
	//alert("width=" + winWidth + ";height=" + winHeight)
	
	var bracketwin = window.open(url, 'bracket', 'top=0,left=0,width=' + winWidth + ',height=' + winHeight + ',scrollbars=1,resizable=1,toolbar=0,location=0,directories=0,status=0,menubar=1');			
	bracketwin.focus();
}

//change the url of a page
function changePage(url) {
	if (url != '') location.href = url;
}

//count characters left in a form field
function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) // if too long...this trims it!
		field.value = field.value.substring(0, maxlimit);
	else // otherwise, update 'characters left' counter
		countfield.value = maxlimit - field.value.length;
}

//display a div
function displayBlock(ID) {
	if (ID != '') {	
		document.getElementByID(ID).style.display = 'block';
	}
}

//generic wndow opener
function openWin(url, winName, specs) {
	if (winName == '') winName = 'win';	
	window.open(url, winName, specs);								
}

//mouseover function
function rollOver(name, source) { 	
	if(document.getElementById) {
		document.getElementById(name).src = eval(source + ".src");
	}
	else if(document.images) {		
		document.images[name].src = eval(source + ".src");
	}	
}

//clear all form fields
//whichForm: name of form we're dealing with
//ignoreFields: comma-delimited list of field names we don't want to touch
function clearForm(whichForm, ignoreFields) {	
	for (var i=0; i<whichForm.elements.length; i++) {
		curElement = whichForm.elements[i];
		//alert(curElement.type)
		if (ignoreFields.indexOf(',' + curElement.name + ',') == -1) {
			if (curElement.type == 'text') {		
				curElement.value = '';
			}
			else if (curElement.type == 'select-one') {		
				curElement.selectedIndex = 0;
			}		
		}
	}
}


var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

if (checkIt('konqueror'))
{
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (!checkIt('compatible'))
{
	browser = "Netscape Navigator"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac"
	else if (checkIt('win')) OS = "Windows"
	else OS = "an unknown operating system";
}

function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}


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);
}

/*
link for a given user's bracket
*/
function getUserBracketLink() {	
	var userID = readCookie("userID");
	
	if (!GLOBALS_BRACKET_MAKE_PICKS) {	 //see _config.js
		location.href='/notyet.asp?view=mypicks';
	}
	else if (userID == "" || userID == null) {	
		location.href='/requirelogin.asp';
	}
	else {	
		openBracket('/bracket/bracket.asp?action=mybracket&userID=' + userID);					
	}	
}


/*
link for current bracket
*/
function getCurrentBracketLink() {
	var userID = readCookie("userID");
	if (userID == "" || userID == null) {	
		location.href='/requirelogin.asp';
	}
	else if (GLOBALS_BRACKET_MAKE_PICKS || GLOBALS_BRACKET_TOURNEY_STARTED) {	 //see _config.js
		openBracket('/bracket/bracket.asp');				
	}
	else {
		location.href='/notyet.asp?view=bracket';
	}	
}


//hide user emails on site so they can't be farmed by spiders
function hideEmail(domain, user, strDisplay) {
	document.write('<a href=\"mailto:' + user + '@' + domain + '\">');
	if (strDisplay == null || strDisplay == '') {
		document.write(user + '@' + domain + '</a>');
	}
	else {
		document.write(strDisplay + '</a>');
	}
}

/* see asp version as well! */
function isValidUserName(strUserName) {			
	if (strUserName.length < 6 || strUserName.length > 15) {		
		return false;
	}
	else {		
		var lettersNums = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		for (i=0; i<lettersNums.length; i++) { //>
			curChar = strUserName.substring(i,i+1);
			//alert(curChar)
			if (lettersNums.indexOf(curChar) == -1) {
				return false;
			}
		}		
	}
	return true;
}


/* see asp version as well! */
function isValidGroupName(strGroupName) {			
	if (strGroupName.length < 6 || strGroupName.length > 100) {		
		return false;
	}
	else {		
		var lettersNums = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
		for (i=0; i<lettersNums.length; i++) { //>
			curChar = strGroupName.substring(i,i+1);
			//alert(curChar)
			if (lettersNums.indexOf(curChar) == -1) {
				return false;
			}
		}		
	}
	return true;
}

function clearError(frmObj) {
	frmObj.className = '';
}
	
function raiseError(msg, frmObj) {
	//alert(msg);
	frmObj.className = 'fielderror';		
	//frmObj.focus();
		
	if (msg.length > 0)
		return msg + '\n';
	else
		return '';
}

function isValidEmail(strEmail) {
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(strEmail))
		return false;
	else
		return true;
}



// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	//var plaintext = document.URLForm.F1.value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	
	return encoded;
};

function URLDecode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   //var encoded = document.URLForm.F2.value;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   //document.URLForm.F1.value = plaintext;
   return plaintext;
}

//force user to be logged in
function requireLogin() {
	if (userID == "" || userID == null) {
		location.href = '/requirelogin.asp';
	}
}

function formatGameTime(format, gmtTime){ 
	var IE_tz = (document.all) ? 1 : 0;
	var MAC_tz = ((navigator.appVersion.indexOf("PPC") >0) || (navigator.appVersion.indexOf("Mac") >0)) ? 1 : 0;
	var tzOffset = 5;


    gmtTime = new String(gmtTime);
	if(!parseInt(gmtTime) || gmtTime.indexOf(':') != -1 ||  gmtTime.indexOf('.') != -1)
		return gmtTime;
	var time;
	var offset = 0;
	if(tzOffset != -1 && tzOffset != new Date().getTimezoneOffset()){
		offset = 60 * (new Date().getTimezoneOffset() - (tzOffset * 60));
    }
	time = new Date((parseInt(gmtTime) + parseInt(offset))*1000);
	var t = '';
	var H = time.getHours();
	var M = time.getMinutes();
	var S = time.getSeconds();
	var d = time.getDate();
	var m = time.getMonth();
	var w = time.getDay();
	var Y = time.getYear();
	//This will need to be adjusted every year
	if(MAC_tz && IE_tz && (time<Date.parse('Sun Oct 31 01:00:00 EDT 2004') || time>Date.parse('Sun Apr 3 01:00:00 EDT 2005')) && tzOffset != -1 && tzOffset!=4){
	time = new Date(time - (60*60*1000));
	var H = time.getHours();
	var M = time.getMinutes();
	var S = time.getSeconds();
	var d = time.getDate();
	var m = time.getMonth();
	var w = time.getDay();
	var Y = time.getYear();
	}
	if(Y<1900){Y+=1900;}
	var y = Y % 100;
	for(var i=0;i<format.length;i++){
		if(format.charAt(i)=='%' && (i+1)<format.length){
			var c = format.charAt(i+1);
			switch(c){ 
				case 'a':{ t+=days[w]; break; }
				case 'A':{ t+=DAYS[w]; break; }
				case 'b':{ t+=months[m]; break; }
				case 'B':{ t+=MONTHS[m]; break; }
				case 'd':{ if(d<10){ t+='0';} t+=new String(d); break;}
				case 'D':{ t+=new String(d); break;}
				case 'H':{ t+=new String(H); break;}
				case 'I':{ if(H>12){ t+=new String(H - 12); }else if(H==0){ t+='12'; }else{ t+=new String(H); }break; }
				case 'm':{ t+=new String(m+1); break;}
				case 'n':{ if(m<9){ t+='0';} t+=new String(m+1); break;}
				case 'M':{ if(M<10){ t+='0';} t+=new String(M); break;}
				case 'p':{ if(H<12){ t+='am';}else{ t+='pm' } break;}
				case 'S':{ if(S<10){ t+='0';} t+=new String(S); break;}
				case 'w':{ t+=w; break; }
				case 'y':{ if(y<10){ t+='0';} t+=new String(y); break;}
				case 'Y':{ t+=new String(Y); break;}
				case 'Z':{ t+=new String(tzAbbrev); break;}
				case '%':{ t+='%'; break;}
			}
			i++;
		}else{
			t+=format.charAt(i);
		}
	}
	return t;
}


function revealModal(bgDiv)
{    
    document.getElementById("modalPage").style.display = "block";
    document.getElementById("modalPage").style.top = document.body.scrollTop;
                
    document.getElementById(bgDiv).style.display = "block";                    
}

function hideModal(bgDiv)
{
    document.getElementById("modalPage").style.display = "none";
    document.getElementById(bgDiv).style.display = "none";        
}