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

	Event listening function
	
**********************************/

function addEventSimple(obj,evt,fn) {
	if (obj.addEventListener){
		obj.addEventListener(evt,fn,false);
	}
	else if (obj.attachEvent){
		obj.attachEvent('on'+evt,fn);
	}
}
	
function removeEventSimple(obj,evt,fn) {
	if (obj.removeEventListener){
		obj.removeEventListener(evt,fn,false);
	}
	else if (obj.detachEvent){
			obj.detachEvent('on'+evt,fn);
	}
}

//
// Function for getting cookies
//

var affID ='';

function getCookie(name) 
	{
    var prefix = name + "=";
    var begin = document.cookie.indexOf(prefix);
    if (begin == -1) return null;
    var end = document.cookie.indexOf(";", begin);

    if (end == -1) end = document.cookie.length;
    return (unescape(document.cookie.substring(begin + prefix.length, end)));
	} 

function set_cookie(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 to add affliate id in the URL of game menu more info links
// 
function affLink(linkurl){
  var affIDTrue = getCookie("AFF_ID");
	//var affIDTrue = 3;
	if (affIDTrue != null){
		linkurl = linkurl + "?AFF_ID=" + affIDTrue;
	}
		
	new_win = window.open('http://casino-games.paddypower.com/'+linkurl+'','dw', 'width=780,height=600,toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=0');
}
		
///open account function 

function go_casino_register(){
	var loc = document.location.href;
	var launchUrl = regUrl;
	/*  var btag = /[?|&]btag=\d+/;
	var tag = loc.match(btag);
	//var hasQuest = /\?/l
	if(/\?/.test(tag)){
		var str = tag.toString();
		tag = str.replace(/\?/,'&');
	}*/
	

	
	var odCookie = getCookie("AFF_ID");
	var tdCookie = getCookie("TDAFFID");
	var adCookie = getCookie("AID");
	var sdCookie = getCookie("SID");
	var pdCookie = getCookie("PID");
	var btag = getCookie("BTAG");
	var prCookie = getCookie("PRMID");
	var tuCookie = getCookie("TDUID");
	var arCookie = getCookie("ARRID");	
	var comCookie;
	if(btag){
		launchUrl +='&BTAG=' +btag;
	}
		
	if(adCookie || sdCookie || pdCookie)
		{
			comCookie = "AID=" + adCookie + "&SID=" + sdCookie + "&PID=" + pdCookie;
		}	 
	if(odCookie){
		launchUrl +='&AFF_ID=' + odCookie;
		}
		
	//check for openbet and comj cookies
		if(comCookie){
			launchUrl += '&'+ comCookie;
	 	}
		//Check for both tradedoubler and comj cookies
		if(tdCookie){
			launchUrl += '&TDAFFID=' + tdCookie;
 	 }
	 if(prCookie){
		 launchUrl += '&PRMID=' + prCookie;
 	 }
	 
	 if(arCookie){
		 launchUrl += '&ARRID=' + arCookie;
 	 }
	 
	 if(tuCookie){
		launchUrl += '&TDUID=' + tuCookie;
 	 }
	 //open the window
						window.open(launchUrl, "pp_registration" , "width=642, height=600, scrollbars=no,  menubar=no, status=no, scrollbars=no, resizable=yes,screenX=5, screenY=5, left=5, top=5");
			
		 }


//
// This should add the affiliates to the skill tab
function encode_url (u) {
	var url = "" + u;
	var l = url.length;
	var i;
	var ret = "";
	var c;

	for (i = 0; i < l; i++) {
		c = url.charAt(i);
		if (c == '&') {
			ret = ret + '~';
		} else {
			if (c == ':') {
				ret = ret + '^';
			} else {
				ret = ret + c;
			}
		}
	}
	return ret;
}

function open_game_account() {
	var tdCookie = getCookie("TDAFFID");
	var odCookie = getCookie("AFF_ID");
	var adCookie = getCookie("AID");
	var sdCookie = getCookie("SID");
	var pdCookie = getCookie("PID");
	var comCookie = "AID="+adCookie + "&SID="+ sdCookie + "&PID=" + pdCookie;
  var url = "http://www.paddypower.com/bet?action=go_thirdparty_url&redirect=GAMEACCOUNT";
  var login_url = encode_url("http://www.paddypower.com/bet?action=go_thirdparty_login");

  url = url + "&login_url=" + login_url;
  if(tdCookie && odCookie){
  	var ret_url = encode_url("http://www.paddypower.com/bet?action=go_ppower_games&TDAFFID="+tdCookie +"AFF_ID=" + odCookie);
  } else if(adCookie && odCookie){
     var ret_url = encode_url("http://www.paddypower.com/bet?action=go_ppower_games&"+comCookie + "AFF_ID=" + odCookie);
  } else if(tdCookie && adCookie){
		var ret_url = encode_url("http://www.paddypower.com/bet?action=go_ppower_games&TDAFFID="+tdCookie + "&" + comCookie);
  }	else if (tdCookie){
		var ret_url = encode_url("http://www.paddypower.com/bet?action=go_ppower_games&TDAFFID=" + tdCookie );
  }	else if (adCookie){
		var ret_url = encode_url("http://www.paddypower.com/bet?action=go_ppower_games&" + comCookie );
  }	else if (odCookie){
		var ret_url = encode_url("http://www.paddypower.com/bet?action=go_ppower_games&AFF_ID=" + odCookie );
  }	else{
		var ret_url = encode_url("http://www.paddypower.com/bet?action=go_ppower_games" );
  }
  
	
   url = url + "&ret_url=" + ret_url;
	 self.location.href = url;
/*	I'm taking the redundancy out but saving if needed later - john

	 Test for affiliate cookies then add them accordingly 
     if(tdCookie != null && odCookie != null){
         self.location.href = url + "&TDAFFID="+tdCookie + "&AFF_ID=" +odCookie;
       } else if(adCookie != null && odCookie != null){
          self.location.href = url + "&" + comCookie + "AFF_ID=" +odCookie;
       } else if (tdCookie != null && adCookie != null){
				 	self.location.href = url + "&TDAFFID=" + tdCookie + "&" + comCookie;
       } else if (tdCookie != null){
			 		self.location.href = url + "&TDAFFID=" + tdCookie;
       } else if (adCookie != null){
			 		self.location.href = url + "&" + comCookie;
       } else if (odCookie != null){
			 		self.location.href = url + "&AFF_ID=" + odCookie;
       }			 
			  else{
           self.location.href = url;
 		} */
 }
 
//this function is for game console to play game without activate flash control in IE
function fixMovie(movieURL, bgValue, embedvalue){
var objectStr = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='100%' height='100%'>\n" 
+ "<param name='movie' value='" + movieURL + "' />\n"
+ "<param name='menu' value='false' />\n"
+ "<param name='quality' value='high'/>\n"
+"<param name='bgcolor' value='" + bgValue+ "' />\n"
+ "<embed src='" + embedvalue + "' menu='false' quality='high' bgcolor='"+ bgValue+ "' width='100%' height='100%' type='application/x-shockwave-flash'>\n"
+ "</embed>\n</object>";
document.write(objectStr);
}

//this is for other flash movies, can define size & allow transparent background
function addFlash(movieURL, bgValue, embedvalue, w, h){
var objectStr = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='" + w + "' height='" + h + "'>\n" 
+ "<param name='movie' value='" + movieURL + "' />\n"
+ "<param name='menu' value='false' />\n"
+ "<param name='wmode' value='" + bgValue+ "'/>\n"
+ "<param name='quality' value='high'/>\n"
+"<param name='bgcolor' value='" + bgValue+ "' />\n"
+ "<embed src='" + embedvalue + "' menu='false' quality='high' wmode='"+ bgValue+ "' width='" + w + "' height='" + h + " type='application/x-shockwave-flash'>\n"
+ "</embed>\n</object>";
document.write(objectStr);
} 
 
// generic window
////////////////////////////////////////////////////////////////////////////////
var gamewin;
function newWindow(file,windowName,features) {
	if (gamewin && !gamewin.closed)		//make sure it comes to focus 
				gamewin.close();

	gamewin = window.open(file,windowName,features);
  gamewin.focus();
}

// close window
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
function closeWindow() {
  self.close();
}

// pop up window
////////////////////////////////////////////////////////////////////////////////
var popWin;
function pop_up(file, w_name, width, height) {
	w = screen.availWidth;
   	h = screen.availHeight;
	topPos = (h-height)/2;
	leftPos = (w-width)/2;
	if (popWin && !popWin.closed){		//make sure it comes to focus 
				popWin.focus();
				popWin.location.href=file;
	}else{		
  		popWin = window.open(file, w_name, "width="+width+",height="+height+",resizable=no,toolbar=no,menubar=no,location=no,scrollbars=no,menubar=no,status=no,left="+leftPos+"top="+topPos+"");
	}
}
function pop_upScroll(file, w_name, width, height) {
	var w = screen.availWidth;
   	var h = screen.availHeight;
	var topPos = (h-height)/2;
	var leftPos = (w-width)/2;
	if (popWin && !popWin.closed){		//make sure it comes to focus 
				popWin.focus();
				popWin.location.href=file;
	}else{
  			popWin=window.open(file, w_name, "width="+width+",height="+height+",resizable,location=no,scrollbars,status=no, left="+leftPos+"top="+topPos+"");
	}
}

// function to go home from popup
function goHome(){
	window.opener.location.href=document.domain+ "/index.do";
	self.close();
	
}
// generic targeted new full window function
var newWin;
function goNew(file,tgt){
	if (newWin && !newWin.closed){
		newWin.focus();
		newWin.location.href=file;
	}
	else{	newWin = window.open(file,tgt);	}
}
//Refreshes the Game menu screen 
////////////////////////////////////////////////////////////////////////////////
function refreshModal() { 
	//used for iframe page within modal to refresh main window
			
			if (window.parent.location.href.match('security')) { //do not reload logon/logoff page			
				window.parent.location.href = "/game/menu.do";
			}
			else if(window.parent.location.href.match('rgsRef')){
				window.parent.location.href='/index.do';
			}
			else {  //try refresh now
				window.parent.history.go(0); //for IE
				
				if (navigator.userAgent.indexOf("Firefox") != -1) {
					window.parent.location.reload();					
				} //for FF
			}
		}
                            
//Refreshes the Game menu screen 
////////////////////////////////////////////////////////////////////////////////
function refreshParentGameMenuScreen() 
{
  if(opener != null && !opener.closed){
	 opener.location.href="/game/menu.do";
 } 
     self.close();


}

function refreshGameMenuScreen() 
{
  if(window.mainGenWindow != null && !window.mainGenWindow){
	 window.mainGenWindow.location.href="/game/menu.do";
 } 
     self.close();


}

function refreshGameMenuNoClose() {
  if(opener != null && !opener.closed){
	 opener.location.href="/game/menu.do";
	 } 
}


// logout
////////////////////////////////////////////////////////////////////////////////
function logOut(){
    self.location.href="/security/logoff.do";
}



/*
 * Function to create bookmark of page
 */
function addToFavorites() {

	var urlAddress = window.location.href;
	var pageName = "Paddy Power Instant Casino";
	
	 if (BrowserDetect.browser == "Explorer") {
	 	window.external.AddFavorite(urlAddress, pageName)
	 }else if(BrowserDetect.browser == "Firefox"){
		window.sidebar.addPanel(pageName,urlAddress,"") 	
	 
	} else { 
		alert("Sorry! Your browser doesn't support this function."); 
	} 
} 

function closeGameWindow() {
 if (gamewin && !gamewin.closed)
  {
    gamewin.close();
  }
}

function validateDropDown(fieldName,messageString){
 if (fieldName.value=='select'){
    alert(messageString);
    return false;
 } 
 else {
    return true;
 }
}

// You must also have Dispatcher.js imported to call this function
function checkFlashVersion() {
  var contentURL="";
  var contentVersion="7.0";
  requireLatestRevision=false;
  var upgradeURL="";
  install=true;
  var installURL="";
  var altURL="";
  overridePluginsPage=false;

  MM_FlashDispatch(contentURL, contentVersion, requireLatestRevision,
			  upgradeURL, install, installURL, altURL,
			  overridePluginsPage)
}


function rdOpener(rd_url){
  if(window.mainGenWindow != null && !window.mainGenWindow.closed){
		window.mainGenWindow.location=rd_url;
	}
//	window.close();
}

function goThenClose(loc){
opener.location.href=loc;
window.blur();
self.setTimeout('self.close()', 1000); 
}

function refreshParent()
{
	if (window.opener!=null){
    	curloc = opener.parent.location.href;
    	opener.parent.location.replace(curloc);
 	} 
}


/*if (self.parent.frames.length != 0)
self.parent.location=document.location;
*/
// start modal functions

// replace chars
function replaceCharacters(conversionString,inChar,outChar) {
  var convertedString = conversionString.split(inChar);
  convertedString = convertedString.join(outChar);
  return convertedString;
}

function cleanString(string){
	replaceCharacters(string,'\r','<br />');
	return string;
}

// centers a named element crossbrowser with scrollers
function centerWindow(element) {
     if($(element) != null) {
          if(typeof window.innerHeight != 'undefined') { // if not IE
               $(element).style.top = 100 + 'px'; // set distance from top of page
               $(element).style.left = 
                    Math.round(document.viewport.getScrollOffsets().left + 
                    ((window.innerWidth - $(element).getWidth()))/2)+'px';
          } else { // if IE
               $(element).style.top = document.body.scrollTop = 100 + 'px'; // set distance from top of page
               $(element).style.left = 
                    Math.round(document.body.scrollLeft + 
                    (($$('body')[0].clientWidth - $(element).getWidth()))/2)+200+'px';
          }
     }
}

/**
 * This is the function to dynamically create a conanical tag
 * if a user comes to the site with an affiliate parameter, the script will check all parameters
 * and create the link when needed.
 */
function doCanonical(){
	var affs = new Array("aff_id", "btag", "pid", "aid", "sid", "cid", "gid", "arrid", "prmid"); // Array of affiliates to check
	var session = new RegExp('jsession'); // regex for checking if freeplay session has been created to perform split
	var loc = document.location.href; // get the url
	
	for (var i = 0; i < affs.length; i++) { // iterate through the array of affiliates.
		var pattern = new RegExp(affs[i]);
		if (pattern.test(document.location)) {
			if (session.test(loc)) {
				var url = loc.split(";", 1);
			}
			else {
				var url = loc.split("?", 1);
			}
			var linkTag = document.createElement('link');
			linkTag.setAttribute('rel', 'canonical');
			linkTag.setAttribute('href', url[0]);
			document.getElementsByTagName('body')[0].insertBefore(linkTag, document.getElementsByTagName('div')[0]);
			break;
		}
	}
}
////////////////////////////////////
// left nav functions start here
////////////////////////////////////
function knowLocation(section,page) {
/*	
	// Logged In States
	if (mode == 'realplay') {
	  if (section == 'Promotions' && page == 'Winners') {
		  $('winnersDiv').className= 'nvLeftItemOn';
	  } else if (section == 'Promotions' && page == 'Loyalty Points') {
		  $('loyaltyDiv').className= 'nvLeftItemOn';
	  } else if (section == 'Promotions' && page == 'Daily Promotions') {
		  $('promotionsDiv').className= 'nvLeftItemOn';
	  } else if (section == 'Promotions' && page == 'Monthly Promotions') {
		  $('promotionsDiv').className= 'nvLeftItemOn';
	  } else if (section == 'Promotions' && page == 'Sign Up Bonus') {
		  $('promotionsDiv').className= 'nvLeftItemOn';
	  }else if (section == 'Casino Games' && page == 'game') {
		  $('instantDiv').className= 'nvLeftItemOn';
	  }
	}
	
	// Logged Out States
	if (mode == 'freeplay') {


	  if (section == 'Casino Games' && page == 'game') {
		  $('instantDiv').className= 'nvLeftItemOn';
	  } else if (section == 'Help' && page == 'Getting Started') {
		  $('helpDiv').className= 'nvLeftItemOn';
	  } else if (section == 'Promotions') {
		  $('promotionsDiv').className= 'nvLeftItemOn';
	  }else if (section == 'Casino Games' && page == 'game') {
		  $('instantDiv').className= 'nvLeftItemOn';
	  }
	} */
}

////////////////////////////////////
// modal window functions start here
////////////////////////////////////
var modal =
{

// create info
createInfo: function(gameCd,realID,gameName,gameMode) {
	var urlReal = gameCd + "\',\'" + realID + "\',\'" + gameName + "\',\'" + gameMode; // url for ajax call
	var urlFree = "";
	
	if (gameMode=="freeplay") { // test for freeplay
	var freePlayBtn = "<a id=\"but_gmFreePlay\" onclick=\"newWindow(\'/game/loadDenomWindow.do?gameCd=" + gameID + "&amp;gameImg=" + realID + "&amp;gameNa=" + gameName + "\', \'gameWindow\',\'height=550,width=560, menubar=no,toobar=no,scrollbar=no,resizable=yes,status=no\');Modalbox.hide();return false;\">Free Play</a>";
	} else {
	var freePlayBtn = "";
	}
	
	Modalbox.show('', {title: 'Game Info', width: 500, height: 360});
	$('MB_loading').remove();
	
	// myContent is the html placed into the modal
	var myContent = "<div class=\"modal_Text\"><p class=\"modal_textTitle\">" + gameName +"</p><p id=\"textDesc\" class=\"textDesc\"></p></div>\
	  <div class=\"modal_Img\"><img alt=\"preview image\" title=\"preview image\" src=\"/images/games/preview/gm_preview" + realID +".jpg\" /></div>\
	  <div class=\"modal_clear\"></div>\
	  <div class=\"modal_buttons\">\
	  <a id=\"but_gmCloseWindow\" onclick=\"Modalbox.hide();\">Close Window</a>\
	  <a id=\"but_gmRealPlay\" onclick=\"Modalbox.hide(); modal.createGamePlay.delay(1,\'" + urlReal + "\');\">Real Play</a>\
	  " + freePlayBtn + "\
	  </div>"; // the html of the overlay
		$('MB_content').insert(myContent);
		var descContent = gameID + "Desc";
		var myVar = $(descContent).innerHTML;
		$('textDesc').insert(myVar.unescapeHTML());
	}, 
createPromoEnroll: function(url,promoName){
	var myContent = "<iframe id=\"modalIframe\" src=\"" +url+ "\" scrolling=\"no\" width=\"600\" height=\"300\" frameborder=\"0\"/>"; 
	Modalbox.show('',{title:'Opt in for '+promoName,width:600,height:500});
	$('MB_loading').remove();
	$('MB_content').insert(myContent);
},
createPromoDepLogin: function(){
		var myContent = "<iframe id=\"modalIframe\" src=\"/security/popDepLogin.do\" scrolling=\"no\" width=\"600\" height=\"300\" frameborder=\"0\"/>"; 
		Modalbox.show('',{title:"Login",width:600,height:500});
		$('MB_loading').remove();
		$('MB_content').insert(myContent);
	},
/* // all games create info
createInfoAllGames: function(url,gameMode) {	
	Modalbox.resize(-140,-120);
	new Ajax.Updater("MB_Content",url, { method: 'get' }); // ajax call
/*createInfoAllGames: function(gameID,realID,gameName,description,gameMode) {
	var urlReal = gameID + "\',\'" + realID + "\',\'" + gameName + "\',\'" + gameMode; // url for ajax call
	var urlFree = "";
	
	Modalbox.show('', {title: 'Game Info', width: 500, height: 360});
	$('MB_loading').remove();
	
	// myContent is the html placed into the modal
	var myContent = "<div class=\"modal_Text\"><p class=\"modal_textTitle\">" + gameName +"</p><p id=\"textDesc\" class=\"textDesc\">" + description + "</p></div>\
	  <div class=\"modal_Img\"><img alt=\"preview image\" title=\"preview image\" src=\"/images/games/preview/gm_preview" + realID +".jpg\" /></div>\
	  <div class=\"modal_clear\"></div>\
	  <div class=\"modal_buttons\">\
	  <a id=\"but_gmCloseWindow\" onclick=\"Modalbox.hide();\">Close Window</a>\
	  <a id=\"but_gmRealPlay\" onclick=\"Modalbox.hide(); modal.createGamePlay.delay(1,\'" + urlReal + "\');\">Real Play</a>\
	  <a id=\"but_gmFreePlay\" onclick=\"Modalbox.hide(); newWindow.delay(1,\'/game/loadDenomWindow.do?gameId=" + gameID + "&amp;gameImg=" + realID + "&amp;gameNa=" + gameName + "\', \'gameWindow\',\'height=550,width=560, menubar=no,toobar=no,scrollbar=no,resizable=yes,status=no\'); return false;\">Free Play</a>\
	  </div>"; // the html of the overlay
		$('MB_content').insert(myContent);
	},*/

// create realplay
createGamePlay: function(gameCd,gameImg,gameName,gameMode) {  
  if (gameMode=="freeplay") { // test for freeplay
	var url = "/security/popLogin.do?gameCd=" + gameCd + "&gameImg=" + gameImg + "&gameNa=" + gameName; // url for ajax call
	var realPlayBtn = "<img class=\"menuBtn\" onclick=\"$(\'modalIframe\').src=\'" + url + "\';\" src=\"/images/but_gmRealPlay.gif\" id=\"but_gmCloseWindow\" name=\"realplay\" alt=\"Real Play\" title=\"Real Play\" width=\"89\" height=\"22\" /> ";
	} else {
	var realPlayBtn = "";
	var url = "/game/loadDenomWindow.do?gameCd=" + gameCd + "&gameImg=" + gameImg + "&gameNa=" + gameName; // url for ajax call

	}

  var myContent = "<iframe id=\"modalIframe\" src=\"" + url + "\" scrolling=\"no\" frameborder=\"0\" height=\"560px\"></iframe>\
  <div class=\"modal_buttons\"></div>"; // the html of the overlay
  	Modalbox.show('', {title: gameName, width: 600, height: 500});
		//new Ajax.Updater($('MB_content'), url)
	$('MB_loading').remove();
	$('MB_content').insert(myContent);
  },
 
// create modal game window
createGameWindow:function(url,w,h){
	var myContent = "<iframe id=\"modalIframe\" src=\"" + url + "\" scrolling=\"no\" width=\"700\" height=\"600\" frameborder=\"0\"></iframe>\
  	<div class=\"modal_buttons\"></div>"; // the html of the overlay
  	Modalbox.show("",{ width:700, height:600});
  	$('MB_loading').remove();
  	$('MB_content').insert(myContent);
},
// create realplay
createGamePlayCat: function(gameCategory) {
  var id = "modal_window";
  var url = "/security/popLogin.do?gameCategory=" + gameCategory; // url for ajax call

  var myContent = "<div id=\"modal_windowContentDiv\" class=\"modal_windowContentDiv\">\
  <iframe id=\"modalIframe\" src=\"" + url + "\" scrolling=\"no\" frameborder=\"0\"></iframe>\
  </div>\
  <div class=\"modal_buttons\"><div class=\"btnGameCloseWindow\"  id=\"but_gmCloseWindow\" onclick=\"modal.killOverlay(\'" + id + "\');\" />Close Window</div>"; // the html of the overlay

  Modalbox.show('', {title: gameName, width: 535, height: 480});
  $('MB_loading').remove();
  $('MB_content').insert(myContent);
  },
  
// destroy overlay and background
killOverlay: function() {
	var id = "modal_window";
	$(id).remove();
	$('myDivBack').remove();
	},

// to load the all games window
loadAllGames: function(url) {
/*	var myContent = "<div id=\"modal_windowContentDiv\" class=\"modal_windowConentDiv\"><img style=\'margin: 10px;\' src=\'/images/ajax_loader.gif\' height=\'16\' width=\'16\' alt=\'loading...\' /></div>\
	<div class=\"modal_buttons\"></div>"; // the html of the overlay
	
	Modalbox.show('', {title: "All Games", width: 640, height: 480});
	$('MB_content').insert(myContent);
	  new Ajax.Updater("modal_windowContentDiv",url, { method: 'get' }); // ajax call */
	  Modalbox.show(url, {title: "All Games", width: 640, height: 480});
	  },
loadFavorites: function(){
	
	Modalbox.show("/game/favoritesList.do",{title: "My Favourites", width:680, height:460});	
	}
};


/*****************
**
**	Script for my favorites
**
********************/
var count; // Keep track of the number of favorites
var favs = [];
var cName = "Favorite"; //Name of the cookie for favorite games

if(!readCookie(cName)){ // If there are no favorites set the count to 0
	count = 0;
	}else{ //otherwise get the number of favorites
		count = getCount();
	}
	function addFavorite(id){
		obj = $(id);
		if(obj.checked){
			cookieMe(obj);
		} else{
			unCookieMe(id);
		}
	}

// Grab the number of favorites.
function getCount(){
	cookie = readCookie(cName);
	cookies = cookie.split('|');
	return count = cookies.length;
}

// Sets the favorite cookie with all the games selected
function cookieMe(obj){	
		var name = obj.getAttribute('name');
		var image = obj.getAttribute('image');
		var id = obj.getAttribute('id');
		var cValue = "name="+name+",image="+image+",id="+id;
		if(count < 6){
			if(!readCookie(cName)){
				createCookie(cName,cValue,30);
			}else {
				var c = readCookie(cName);
				createCookie(cName,c+"|"+cValue,30);
			}
			count++;
		} else {
			alert("You've reached the maximum allowed favourites (6).");
			obj.checked = false;
		}
	}
	
	/*******************
	**
	**	unCoookieMe:
	**	function to allow users to remove games from their favorites list. This will update the existing cookie, and reset it with the changes
	** 	@parameters obj: the input element on the favorites menu
	**
	*************************/
	function unCookieMe(id){
		//Check to see if there's even a cookie to work with
		obj = $(id);
		if(!readCookie(cName)){
			obj.checked = false;
					return;
		} else {
			var c = readCookie(cName);	//Grab the cookie
			var cookies = c.split("|"); //Split it by |
			var patt = new RegExp("id="+id); //Create a regex to test against the cookie array
			if(cookies.length == 1){
				eraseCookie(cName);
				count = 0;
			} else{
			  	for(var i=0; i < cookies.length; i++){
					if(patt.test(cookies[i]) == true){
						cookies.splice([i], 1);
					}
				}	
				//Reset the cookie with the values that are left over
				cValue = cookies.join("|");
				createCookie(cName,cValue,30);
				count--;
				if(count<6){
					$('addFav').style.display="";	
					}
			}

		}
		
	}
	
	/*******************
	**	removeMe:
	**	function remove fav item 
	*************************/
	function removeMe(id){
		//Check to see if there's even a cookie to work with
		thisDiv = "fav_" + id;
		$(thisDiv).remove();		
	}

	/********************
	** function buildIt():
	** function to write out the page with the current favorites
	*********************/
/* this is no longer in use
	function buildIt(){
		var cookie = readCookie(cName);
		var games = cookie.split("|");
		games = games.toString();
		games = games.split(',');
		var names = [];
		var images = [];
		var ids =[];
		var idPatt = /id=[0-9\-]/;
		var namePatt = /name=[A-Za-z0-9].*/;
/*  var imagePatt = /[0|1]\d+_\d/;
		for(var i=0; i<games.length;i++){
			if(idPatt.test(games[i])){
				ids.push(games[i].match(/\d*\-[0-9]/));

			} else if(namePatt.test(games[i])){
				names.push(games[i].match(namePatt));
			}else if(imagePatt.test(games[i])){
				images.push(games[i].match(imagePatt));
			}
		}
		for (var i = 0; i < names.length; i++) {
			if (names.length == 6) {
				$('addFav').style.display = "none"
			}
			name = names[i].toString();
			name = name.replace(/name=/, "");
			desc = images[i].toString();
			desc = desc.replace(/_/, '-');//This is used to pull in the game description and it's being used as the game code as it's combination of the game family and game number''
			imgUrl = "<img src='/images/games/icons/icon_gm" + images[i] + ".gif />";
			var gameLaunchUrl;
			
			if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == '8') {
				// going old school on the create elements
				var parentDiv = document.getElementById("gameContainer"); //  container div for  the favorites menu.
				//  Create the game box, and set its class name
				var gameBox = document.createElement('div');
				gameBox.setAttribute("class", "gameBox");
				gameBox.setAttribute("id", ids[i].toString());
				
				//Create the top of the game box
				var gameBoxTop = document.createElement('div');
				gameBoxTop.setAttribute("class", "gameBoxTop");
				
				//Create the bottom game box
				var gameBoxBot = document.createElement('div');
				gameBoxBot.setAttribute("class", "gameBoxBot");
				
				
				var h2 = document.createElement('h2');
				h2.setAttribute("class", "gameTitle");
				h2.appendChild(document.createTextNode(name));
				
				var leftSideBox = document.createElement('div');
				leftSideBox.setAttribute("class", "leftSideBox");
				
				// Create element for game image
				var gmImg = document.createElement('img');
				gmImg.setAttribute("src", "/images/games/icons/icon_gm" + images[i] + ".gif ");
				
				// add the game image to the left box
				leftSideBox.appendChild(gmImg);
				
				//Create the right box
				var rightSideBox = document.createElement('div');
				rightSideBox.setAttribute("class", "rightSideBox");
				
				//  Content for right box
				var rightBoxCont;
											
				rightBoxCont ="<p class='btnRealPlay' title='Real Play " + name + "' name='realplay' onclick='modal.createGamePlay(\"" + desc + "\",\"" + images[i] + "\",\"" + name + "\",\"realplay\");'>Real Play</p><p class='btnGameInfo' title='" + name + " Game Info' onclick='Modalbox.show(\"/game/info.do?gameCd=" + desc + "&gameDesc=" + desc + "&gameImg=" + images[i] + "&gameNa=" + name + "\",{title:\"Game Info\",width:500,height:360});'>Game Info</p><p class='btnRemoveGame'  onclick='unCookieMe(\"" + ids[i] + "\");$(\"" + ids[i] + "\").remove();'><span> Remove</span></p>"; 

					 
				rightSideBox.innerHTML = rightBoxCont;
				
				
				gameBoxTop.appendChild(h2);
				gameBoxTop.appendChild(leftSideBox);
				gameBoxTop.appendChild(rightSideBox);
				gameBox.appendChild(gameBoxTop);
				gameBox.appendChild(gameBoxBot);
				parentDiv.insertBefore(gameBox, document.getElementById("addFavs"));
			}
			else {
					//Now we're going to build the actual divs for the games.
			var div = new Element('div', {'class':'gameBox','id':ids[i]});
			var divTop = new Element('div', {'class':'gameBoxTop' });
			var h2 = new Element('h2',{ 'class':'gmTitle'}).update(name);
			var leftBox = new Element('div',{'class':'leftSideBox'});
			var gmImg = new Element('img',{'src':'/images/games/icons/icon_gm'+images[i] + '.gif '});
			var rightBox = new Element('div', {'class':'rightSideBox'});
			var rightBoxCont;
						
						rightBoxCont ="<p class='btnRealPlay' title='Real Play " + name + "' name='realplay' onclick='modal.createGamePlay(\"" + desc + "\",\"" + images[i] + "\",\"" + name + "\",\"realplay\");'>Real Play</p><p class='btnGameInfo' title='" + name + " Game Info' onclick='Modalbox.show(\"/game/info.do?gameCd=" + desc + "&gameDesc=" + desc + "&gameImg=" + images[i] + "&gameNa=" + name + "\",{title:\"Game Info\",width:500,height:360});'>Game Info</p><p class='btnRemoveGame'  onclick='unCookieMe(\"" + ids[i] + "\");$(\"" + ids[i] + "\").remove();'><span> Remove</span></p>"; 
				
			/*
				Prototype way of adding elements not working in IE. Commenting out until fix is found
				
				
				var playBut = new Element('p',{'class':'btnRealPlay loggedInButs', 'title':name, 'onclick':'modal.createGamePlay("'+ids[i]+'","'+images[i]+'","'+name+'","realplay");'}).update('Real Play');
				var gameInfo = new Element('p',{'class':'btnGameInfo','title':name,'onclick':'Modalbox.show("/game/info.do?gameId='+ids[i]+'&gameImg='+images[i]+'&gameNa='+name+'&gameDesc='+desc+'",{title:\'Game Info\',width:500,height:360})'}).update('Game Info');
				var remove = new Element('p',{'class':'btnRemoveGame'}).update('Remove');
				*/
/*  var divBot = new Element('div',{'class':'gameBoxBot'});
			$('gameContainer').insertBefore(div,$('addFavs'));
			div.insert(divTop);
			divTop.insert(h2);
			divTop.insert(leftBox);
			leftBox.insert(gmImg);
			divTop.insert(rightBox);
			rightBox.insert(rightBoxCont);
			div.insert(divBot);
	 
			}
		}
	}
	
	function clickEvent(e){
		obj = e.element();
		alert(obj);
	}
/*	function clickListener(){
	var buttons = document.getElementsByTagName('p');
	for	(i=0;i<buttons.length;i++){
		if(buttons[i].className=="btnRemoveGame"){
		addEventSimple(buttons[i],'click', clickEvent);
		}
	}
 }
 */
 
 /* addEventSimple(window, 'load',clickListener);*/
 
	/******************
	**
	**	checkEm(): 
	**	function to grab favorite cookie, and check the games that have been selected as a favorite
	**	on the favorites list
	**
	***********************/
	function checkEm(){
		var gIds = getIds();
		if(!gIds){return;} 
		for(var i=0;i<gIds.length;i++){
			var elm = gIds[i].toString();
			elm = elm.match(/[0-9\-]+\d+/);
			document.getElementById(elm).checked=true;
		}
	}
	
	/*******************************
	**
	**	getIds():
	**	function to parse the cookie, and return the id values for each game in the cookie
	**
	*******************************/
	function getIds(){
		var c = readCookie(cName);
		if(!c){return;}
		var ids = [];
		var games = c.split(',');
		for(var i=0;i<games.length; i++){
			if(/id=[0-9\-]/.test(games[i])){
				ids.push(games[i].match(/id=[0-9\-]+\d+/));
			}
		}
		return ids;
	}
	
	
	/*******************************
	**
	**	getIds2():
	**	function to parse the cookie, and return the id values for each game in the cookie
	**
	*******************************/
	function getGIds(){
		var c = readCookie(cName);
		if(!c){return;}
		var ids = [];
		var games = c.split(',');
		for(var i=0;i<games.length; i++){
			if(/id=[0-9\-]/.test(games[i])){
				ids.push(games[i].match(/[0-9\-]+\d+/));
			}
		}
		return ids;
	}	
	
	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);
	}
/*************************
**
**	End Favorites Scripts
**
****************************/
inProgress=false;
// end modal functions

/*****************************************
	Content show/hide function
**********************************/
last_def = 'lyr0';
function show(layerName) {
document.getElementById(layerName).style.display = '';
}
function hide(layerName) {
document.getElementById(layerName).style.display = 'none';
}
function show_next(next_def) {
document.getElementById(last_def).className = 'off';
var curr = document.getElementById(next_def);
curr.className='selected';
hide(last_def+'_content');
show(next_def+'_content');
last_def=next_def;
}

/*****************************************
	FAQ show/hide function
**********************************/
//QA = 4; // number of hidden layers

	function showAnswer(id){
		for(i=1;i<=QA;i++){
			document.getElementById('a'+i).style.display = "none";
			document.getElementById('q'+i).className = "off";
		}
			document.getElementById('a'+id).style.display = "block";
			document.getElementById('q'+id).className="on";
	}
	
function closeErrorMessage(element){
	$(element).remove();
	
	if ($('MB_window')) {
		Modalbox.hide();
	}
}

/* 
 *	 Login form validation
*	 Just checks to see if the fields are blank, and messages the user
* */
   
 /*  var form = $('loginForm')
   function validateLogonForm(form)    {
        var un = form.username.value;
        var un1 = eval(un.length);
        var unp = form.password.value;
        var unp1 = eval(unp.length);

        if(un1 ==0 || unp1==0)
        {
            alert("Username and Password are required");
            return false;
        }
        return true;
    }

	*/
/**
**	PPY Account menu function
**/

function ma_nav(state){
	if($('ma_nav')){
		if(($('pageTypeId')||$('monthId'))&& state == 'show'){
			$('pageTypeId').hide();
			$('monthId').hide();
		}
		document.getElementById("ma_nav").style.display = (state == "show") ? "block" : "none";
	}else{
		return;
	}
}



function setLeftHeight(){

		if ($('main')) {
			var mainHeight = $('main').getHeight();

			var leftNavHeight = $('leftNavContainer').getStyle('height');
			if (mainHeight > 700) {
				var stageLeftHeight = mainHeight - 700;
				$('leftNavContainer').setStyle({
					height: mainHeight + 'px'
				});
				
				$('stageLeft').setStyle({
					height: stageLeftHeight + 'px'
				});

			}
		}else{
			return;
		}
}
/*	comment out due to IE quirk
document.observe('dom:loaded', function(){
	setLeftHeight()
});
*/
/*
 * script to resize ppy iframe
 * 
 */
var balURL;
	function updateMyBalance(){
		$('balance').update('Retrieving..');
		
		var params = { 'dummy': Math.random }
	    var ajx = new Ajax.Request(
	        		balURL, {
			        method:         'get',
		    	    parameters:     params,
		        	onComplete:      function() {
			            var rs = ajx.getHeader('json').evalJSON();
			            if(rs){
			            				            	
   				            	if(rs.WITHDRAWBALANCE != null){
										
									var bal = /[0-9,]+\.\d+/;
									var headerBal  =  rs.WITHDRAWBALANCE.match(bal);								
//				            		$('withdrawBal').innerHTML = rs.WITHDRAWBALANCE;
									$('balance').update(rs.WITHDRAWBALANCE);
			            	}

			            	
			            	
			            }
			        },
			        requestHeaders: ["If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT"]
		       });
	      
	}

	document.onclick = function (e) {
		e = e || event
		

		var target = e.target || e.srcElement;
		do {
			if (document.getElementById("ma_nav") == target || document.getElementById("ma-nav-trigger") == target) {
				return;
			}
			target = target.parentNode;
		} while (target)
		ma_nav("hide");
		
		
		
	}
	function resizeto(h){
      document.getElementById("orbisIframe").style.height = h + "px"; 
	  }


/**
 *  Script for hide/show balance
 */

	function displayBalance(){
		if ($('balance')) {
			if (!getCookie('BAL') || getCookie('BAL') == '0') {
				$('balance').hide();
				$('balTrigger').update('Show');
			}
			else {
				$('balance').show();
				$('balance').update('<mercury:currency value="${user.balance}"/>');
				if ($('balTrigger')) 
					updateMyBalance();
				$('balTrigger').update('Hide')
			}
		} else{
			return
		}
	}	
	function toggleBalance(elm){
		if(getCookie('BAL') == 1){
			set_cookie('BAL',"0");
			
		}else {
			set_cookie('BAL',"1");
			}
		displayBalance();		
		
	}


	document.observe("dom:loaded", function() {
		displayBalance();
		//$('orbisIframe').observe('load',updateMyBalance);
});
/*** 
** Browser detection script to fix favorites
*/
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
