/********************************************************************
The following functions will only manipulate data passed by the 
PHP tournaments functions. Therefore all input data and js settings 
below must be formatted as specified by the PHP functions file.
********************************************************************/
var isSet = "N";
var sec = ","   					// set the countdown seconds (comma set as [0] is reserved)
var min = ","						// set the countdown minutes (comma set as [0] is reserved)
var secs = new Array();   			// set the countdown seconds
var mins = new Array();   			// set the countdown minutes
var cmillisecs = 0;					// set the countdown milliseconds
var chgColor5 = new Array();		// Change colour variable for 5 mins to stop it repeating
var chgColor10 = new Array();		// Change colour variable for 5 mins to stop it repeating
var chgColor20 = new Array();		// Change colour variable for 5 mins to stop it repeating
var cntr = 1;						// Increment array variable passed to ticker
var tourneyList=new Array();
var anecdote = "";
var status = "open";		// Status of tournament
var clockID = 0;			// Used in clock
var hl = "N";				// Highlight tournament variable

var browserName = sniffBrowser();

function sniffBrowser() { // only used for playing sounds right now
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1) return 'Opera';
	if (agt.indexOf("staroffice") != -1) return 'Star Office';
	if (agt.indexOf("webtv") != -1) return 'WebTV';
	if (agt.indexOf("beonex") != -1) return 'Beonex';
	if (agt.indexOf("chimera") != -1) return 'Chimera';
	if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	if (agt.indexOf("firefox") != -1) return 'Firefox';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	if (agt.indexOf("msie") != -1) return 'Internet Explorer';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	if (agt.indexOf('\/') != -1) {
	if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
		return navigator.userAgent.substr(0,agt.indexOf('\/'));}
	else
		return 'Netscape';
		}
	else if (agt.indexOf(' ') != -1)
		return navigator.userAgent.substr(0,agt.indexOf(' '));
	else
		return navigator.userAgent;
}

function playMusic(nm) {
	if (browserName == "Firefox" || browserName == "Netscape" || browserName == "Mozilla" || browserName == "Opera") {
		obj = document.embeds[nm];
		if(obj.Play) obj.Play();
		return true;
		}
	else { // Assume IE
		document.myMusic.play();
		}
}

/*
	<button type="button" onclick="return playMusic('myMusic');">Play Music</button>
	<embed name="myMusic" src="notify.wav" type="audio/midi" autostart="false" hidden="" loop="false" mastersound width="128" height="128"></embed>
*/
 
function leadingZero(nr)
{
	if (nr < 10) nr = "0" + nr;
	return nr;
}

function checkTimeZone() {
	// Function coutesy http://www.csgnetwork.com/timezoneproginfo.html
   	var rightNow = new Date();
   	var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
   	var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
   	var temp = date1.toGMTString();
   	var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   	var temp = date2.toGMTString();
   	var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   	var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
   	return hoursDiffStdTime;
}

//Similar to the above but for Toolbar version: more parameters, different output
function tbfSet(tourneyDate,tourneyTime,regDate,regTime,tName,tID,tFee,tRoom,pCode,pLink,tStatus,page,tPeriod,highLight) {

	//get current local time
	var today = new Date();
	var lYear = today.getYear();
	var lMonth = leadingZero(today.getMonth()+1);
	var lDay = leadingZero(today.getDate());
	var lHour = leadingZero(today.getHours());
	var lMin = leadingZero(today.getMinutes());
	var lSec = leadingZero(today.getSeconds());
	
	//Tourney times
	var tDay = tourneyDate.substr(0,2); // tournament start date
	var tMonth = tourneyDate.substr(3,2); // tournament start date
	var tYear = tourneyDate.substr(6,4); // tournament start date
	var tHour = tourneyTime.substr(0,2); // tournament start time
	var tMin = tourneyTime.substr(3,2); // tournament start time
	var tSec = tourneyTime.substr(6,2); // tournament start time
	
	//Reg times
	var rDay = regDate.substr(0,2); // registration start date
	var rMonth = regDate.substr(3,2); // registration start date
	var rYear = regDate.substr(6,4); // registration start date
	var rHour = regTime.substr(0,2); // registration start time
	var rMin = regTime.substr(3,2); // registration start time
	var rSec = regTime.substr(6,2); // registration start time
	
	//Get timezone of user
	var da = new Date();
	var diff = checkTimeZone();
	
	//Set new tourney start time (local)
	var newtHour = Number(diff)+Number(tHour);
	var tt = new Date ( tYear, tMonth-1, tDay, newtHour, tMin, tSec );
	
	//Set new registration start time (local)
	var newrHour = Number(diff)+Number(rHour);
	var rt = new Date ( rYear, rMonth-1, rDay, newrHour, rMin, rSec );
	
	//format tourney output
	var tyr = leadingZero(tt.getYear());
	var tmon = leadingZero(tt.getMonth()+1);
	var tday = leadingZero(tt.getDate());
	var thr = leadingZero(tt.getHours());
	var tmi = leadingZero(tt.getMinutes());
	
	//format registration output
	var ryr = leadingZero(rt.getYear());
	var rmon = leadingZero(rt.getMonth()+1);
	var rday = leadingZero(rt.getDate());
	var rhr = leadingZero(rt.getHours());
	var rmi = leadingZero(rt.getMinutes());
	
	//compare dates in milliseconds since 1970 (3,600,000 ms = 1 hr)
	var l1970 = Date.UTC(lYear,lMonth,lDay,lHour,lMin,lSec); // current time
	var t1970 = Date.UTC(tyr,tmon,tday,thr,tmi,0); // tournament start time
	var r1970 = Date.UTC(ryr,rmon,rday,rhr,rmi,0); // registration start time
	
	if (tStatus == "RUNNING" || tStatus == "OPEN") {
		status = "show"; // not used at the moment
		}

	if (!pLink) {
		pLink = "http://www.pokersites.co.uk/goto-poker-room.php?c="+pCode;
		}
		
	hl = "N";
	if (highLight && highLight != "N") {
		hl = "class=\""+highLight+"hl\"";
		}

	var linebreak = "";
	// The following section also happens in ticker.js function checkClockColor()
	// however that shouldn't need changing unless you a) changes the class names
	// below or b) change the times at which to change colors (these are specified 
	// in both places)
	var spclass = "tbcountdownB";
	cmillisecs = (t1970 - l1970) / 1000 ; 	// seconds
	min = Math.floor(cmillisecs/60);  		// The minutes
	sec = cmillisecs % 60;             		// The balance of seconds
	if (min < 5) {
		spclass = "tbcountdownR";
		}
	else if (min < 15)  {
		spclass = "tbcountdownG";
		}

	if ((l1970 < t1970 && l1970 > (t1970 - tPeriod)) || (l1970 < t1970 && tStatus == "NOTICE")) {
		if (tStatus == "NOTICE" && page == "Toolbar") {
			tourneyList[cntr] = "<nobr align=\"center\"><a href=\""+pLink+"\" target=\"_blank\" title=\"Click me\" class=\"notice\">"+tRoom+": "+tName+" &raquo;</a></nobr>";
			linebreak = "<br><br>";
			document.write(tourneyList[cntr]+linebreak);
			++cntr;
			}
		else if (page == "Toolbar") {
			//plink variable removed from first a href (poker room direct link) and replaced with tourney details link
			tourneyList[cntr] = "<!--|"+t1970+"|--><nobr align=\"center\"><span class='"+spclass+"'>"+thr+":"+tmi+"</span><a href=\"http://www.pokersites.co.uk/poker-tournaments/feeds/show_tournament.php?tid="+tID+"&proom="+pCode+"&r=ticker\" target=\"_tourneyinfo\" title=\"View Full Tournament Info...\" "+hl+">"+tRoom+": "+tName+" ["+tFee+"] </a><a href=\"http://www.pokersites.co.uk/poker-tournaments/feeds/index.php?r=ticker\" target=\"_blank\"><img src=\"/images/wld.gif\" alt=\"View Your Tournament List\" width=\"16\" height=\"16\" border=\"0\" align=\"center\"></a></nobr>";
			linebreak = "<br>";
			document.write(tourneyList[cntr]+linebreak);
			//Set countdown min,sec			
			++cntr;
			}
		else if (tStatus != "NOTICE") { // display on web pages in a table (IE: index.php and tournament_ssearch.php)
			tourneyList[cntr] = "<tr><td valign=\"top\"><nobr align=\"center\">"+tday+"/"+tmon+" <span class='"+spclass+"'>"+thr+":"+tmi+"</span></nobr></td><td valign=\"top\" align=\"center\"><a href=\"/goto-poker-room?c="+pCode+"\" target=\"_blank\"><img src=\"/images/website.gif\" alt=\"Visit the "+tRoom+" website\" width=\"17\" height=\"16\" border=\"0\"></a></td><td valign=\"top\"><nobr align=\"center\"><a href=\"/poker-tournaments/feeds/index.php?overridefilters=y&room="+tRoom+"\" title=\"Show all tournaments from "+tRoom+"\" "+hl+">"+tRoom+"</a></nobr></td><td valign=\"top\"> - "+tName+" ["+tFee+"] &nbsp; <a href=\"http://www.pokersites.co.uk/poker-tournaments/feeds/show_tournament.php?tid="+tID+"&proom="+pCode+"\" target=\"_blank\" title=\"View tournament details (TID: "+tID+")\" "+hl+">&raquo; More Info...</a> </td></tr>";
			document.write(tourneyList[cntr]+linebreak);
			++cntr;
			}
		}
	}
	
function setDefaultMessage() {
	if (cntr == 1) {
		tourneyList[1] = "<nobr align=\"center\"><a href=\"http://www.pokersites.co.uk/poker-tournaments/feeds/tb_options.php\" target=\"_parent\" title=\"Click here to change your filters\">No matching tournaments found. <strong>Click here to check your filters.</strong> &raquo;</a></nobr>";
		self.setTimeout('refresh()', 600000);  // wait 10 minutes, then refresh
		}
	}
	
function sendTournamentsToTickerFrame() {
	tourneyList[0] = "<nobr align=\"center\" style=\"color:#AA0000;\">Use the menu (left) to configure the toolbar and tournament filters.</nobr>";
	parent.singletext = tourneyList;
	}


function refresh() {
	self.location.href = "/poker-tournaments/feeds/tb_feed.php";
	}
	
function refreshToolbar() {
	var mess = "Refreshing Tournament Ticker";
	if (anecdote) {
		anecdote = "\r\r"+anecdote;
		}
	alert(anecdote+mess);
	self.location.href = "/poker-tournaments/feeds/toolbar.php";
	}

//NOT CURRENTLY CALLED
function startCountDowns(cntr,min,sec) { // pass in no. of tournies and times as a , seperated string
	mins = min.split('T'); // Split out to array - set by tbfSet() above
	secs = sec.split('T'); // Split out to array - set by tbfSet() above
	for (var i = 1; i < cntr; i++) { // loop through each SPAN created setting up the timer
		countDown(i,mins[i],secs[i]);
		}
	}
	
function countDown(i,min,sec) {
		sec--;
		if (sec == -01) {
	    	sec = 59;
	    	min = min - 1;
	  		}
		else {
	   		min = min;
	  		}
		if (sec<=9) {
			sec = "0" + sec;
			}
	  	
		time = (min <= 9 ? "0" + min : min) + ":" + sec; // format output
		var timespan = "theTime"+i;
		if (document.getElementById && min < 20) { // show for last 20 minutes only
			document.getElementById(timespan).innerHTML = time;
			}
	  	
		SD=window.setTimeout("countDown("+i+","+min+","+sec+");", 1000);
		if (min < 10 && min > 4 && !chgColor10[i]) {
			document.getElementById(timespan).style.backgroundColor = "#ff7700"; // orange
			chgColor10[i] = "Y";
			}
		else if (min < 5 && !chgColor5[i]) {
			document.getElementById(timespan).style.backgroundColor = "#ee0000"; // red
			chgColor5[i] = "Y";
			}
		else if (min == '00' && sec == '00' && !chgColor20[i]) {
			sec = "00";
			window.clearTimeout(SD);
			document.getElementById(timespan).style.backgroundColor = "#000099"; // blue
			document.getElementById(timespan).innerHTML = "Started";
			chgColor20[i] = "Y";
			//self.setTimeout('refresh()', 600000);  // wait 10 minutes, then refresh
			}

	}
	
function silentErrorHandler() {return true;}

window.onerror=silentErrorHandler;

//Toolbar clock functions
// Clock Script Generated By Maxx Blade's Clock v2.0d
// http://www.maxxblade.co.uk/clock
function tS() {
	x=new Date();
	x.setTime(x.getTime());
	return x;
	} 
	
function lZ(x) {
	return (x>9)?x:'0'+x;
	} 
function dT() {
	document.getElementById('tP').innerHTML=eval(oT);
	setTimeout('dT()',1000);
	} 
	
var oT="lZ(tS().getHours())+':'+lZ(tS().getMinutes())";

