function getDomain()
{
	var rootHarrahsDomain = 'https://www.harrahs.com';
	
	//support staging
	if(window.location.hostname.indexOf('harrahs.org')>-1)
	{
		rootHarrahsDomain = window.location.protocol + '//' + window.location.hostname;
	}
	
	return rootHarrahsDomain;
	
}




// Method to submit Login Form in the Global Navigation
function submitGlobalLoginForm() {
	if(isCookieExist('userSessionCookie')) {
		eraseCookie('userSessionCookie');
	}
	if(isCookieExist('userInfoCookie')) {
		eraseCookie('userInfoCookie');
	}
	if(isCookieExist('demarcationCookie')) {
		eraseCookie('demarcationCookie');
	}
	if(isCookieExist('omnitureCookie')) {
		eraseCookie('omnitureCookie');
	}
	if(isCookieExist('lastsync')) {
		eraseCookie('lastsync');
	}
	var referdomainString=readQueryString('referdomain');
	//alert(referdomainString);
	//alert(document.location));
	var lastSync=readQueryString('lastsync');
	document.PINLogin.referdomain.value=referdomainString;
	document.PINLogin.lastsync.value=lastSync;
	document.PINLogin.submit();
}

// Method for forgot pin
function forgotpin() {
	
	window.parent.location = getDomain() + '/TotalRewards/TotalRewards.do';
}

// Method for get pin
function getpin() {
	window.parent.location = getDomain() + '/TotalRewards/TotalRewards.do';
}

// Method for logout 
function logout() {
	var lastsync = readCookie('lastsync');
	var refererPage = window.location;
	window.parent.location=getDomain() + '/TotalRewards/Login.do?action=ACTION_LOGOUT&referdomain='+readQueryString('referdomain')+'&lastsync='+lastsync+'&globalLogoutFlag=true&refererPage='+refererPage;
	if(isCookieExist('userSessionCookie')) {
		eraseCookie('userSessionCookie');
	}
	if(isCookieExist('userInfoCookie')) {
		eraseCookie('userInfoCookie');
	}
	if(isCookieExist('demarcationCookie')) {
		eraseCookie('demarcationCookie');
	}
	if(isCookieExist('omnitureCookie')) {
		eraseCookie('omnitureCookie');
	}
	if(isCookieExist('lastsync')) {
		eraseCookie('lastsync');
	}
}

// Method to call My Tr page
function mytr() {
	window.parent.location = getDomain() + '/MyTr.do';
}

// Method to call My offers page
function myoffers() {
	window.parent.location = getDomain() + '/TotalRewards/Offers.do';
}

function earn() {
	window.parent.location = getDomain() + '/total_rewards/earn.jsp';
}

function readCookie(name) {
	var cookie = unescape(document.cookie);
	cookie = ';' + cookie;

	var pattern = '; ' + name + '=';
	return getValue(cookie, pattern, ';');
}

function getValue(str, pattern, delim) {
	var q_start = str.indexOf(pattern);
	var value = '';
	if (q_start != -1) {
		q_start = q_start + pattern.length;
		var q_end = str.indexOf(delim, q_start);
		if (q_end == -1) q_end = str.length;
		value = str.substring(q_start, q_end);
	}
	return unescape(value);
}



// Method to display Tr card image in brand global login pages
function switchTRCardImage(tier) {
  var imagePath = "";
  //if (console) {
  //  console.debug("got tier: " + tier);
  //}
    
  switch (tier) {
    case "DIAMOND":
      imagePath = "/images/corporate/navElements/trng/trModuleBg-diamond.jpg";
      break;
    case "TOTAL GOLD":
      imagePath = "/images/corporate/navElements/trng/trModuleBg-gold.jpg";
      break;
    case "GOLD":
      imagePath = "/images/corporate/navElements/trng/trModuleBg-gold.jpg";
      break;
    case "PLATINUM":
      imagePath = "/images/corporate/navElements/trng/trModuleBg-platinum.jpg";
      break;
    case "SEVEN STAR":
    case "7StarsClub":
    case "Seven Stars Club":
      imagePath = "/images/corporate/navElements/trng/trModuleBg-7star.jpg";
      break;
    case "Chairman's Club":
      imagePath = "/images/corporate/navElements/trng/trModuleBg-chairman.jpg";
      break;
    case "NOT_LOGGED_IN":
      imagePath = "/images/corporate/navElements/trng/trModuleBg-notloggedin.jpg";
      break;
    default:
      imagePath = "/images/corporate/navElements/trng/trModuleBg-notloggedin.jpg";
  }

  //if (console) {
  //  console.debug("setting image: " + imagePath);
  //}

  container = document.getElementById('cntTtlRewards');
  if (container) {  
    tds = container.getElementsByTagName('td');
    
    for (var i = 0; i < tds.length; i++) {
      if (tds[i].className == 'ttlRewardsCards') {
        //if (console) {
        //  console.debug("flipping image!");
        //}
        tds[i].style.backgroundImage = "url(" + imagePath + ")";
        break;
      }
    }
  }
}
// Global variables
var isLoggedIn=false;
var name='';
var tier='';
var accountBalance=0;
var tierScore = 0;
var offersCount = 0;
var lastUpdate = '1/1/1900';
var lastsync = readCookie('lastsync');

var separator = '';

//Method to set global variables
function setGlobalUserVariables(){
  if(isCookieExist("userSessionCookie") == "true") {
      // reset the maxe age of the cookie to expire in 30 minutes
      var date = new Date();
      date.setTime(date.getTime()+(30*60*1000));
      document.cookie = 'userSessionCookie' + "=" + escape ('true') + "; expires=" + date.toGMTString() + "; path=/";
      if(readCookie("userInfoCookie") != '' && readCookie("demarcationCookie") != '') {
	        separator = readCookie("demarcationCookie");
	        var userInfo = readCookie("userInfoCookie");
	        var userInfoArray = userInfo.split(separator);
		isLoggedIn = true;
		if(userInfoArray.length==6){
			name = userInfoArray[0];
			if(userInfoArray[1]=="TOTAL GOLD") {
			    userInfoArray[1]="GOLD";
			}
			tier = userInfoArray[1];
			accountBalance = userInfoArray[2].replace(" ", ",");
			tierScore = userInfoArray[3].replace(" ", ",");
			offersCount = userInfoArray[4];
			lastUpdate = userInfoArray[5];
		}
	} else {
		isLoggedIn = false;
	}
  } else {
	isLoggedIn = false;
  }
}

function renderBrandGlobalLoginWidget() {
	var iframeUrl='';
	var cookiestoset = '';
		
		if(typeof(page_cookiestoset) != "undefined")
		{
			cookiestoset=escape(page_cookiestoset);
		}
	iframeUrl = getDomain() + '/CookieHandler.jsp?set=' + cookiestoset + '&action=action_testcookie&lastsync='+lastsync+'&referdomain='+escape(window.location.host)+'&source=brand&randomNumber='+Math.random();

	//alert(iframeUrl);

	switchTRCardImage("NOT_LOGGED_IN");
	isLoggedIn = false;
	document.write('<iframe width=\'198\' allowtransparency=true src=\''+iframeUrl+'\' scrolling=\'no\' frameborder=\'no\' class=\'login_iframe\'></iframe>');
	
	//DELAY UNTIL AFTER WRITING IFRAME
	write_pzn_code();
	write_special_tag();
  return false;
}





function renderHomePageGlobalLoginWidget() {
	
	var iframeUrl='';
	var cookiestoset = '';
		
		if(typeof(page_cookiestoset) != "undefined")
		{
			cookiestoset=escape(page_cookiestoset);
		}
	if('localhost' == document.domain)
	{
		var accountId = readCookie('accountId');
		iframeUrl = getDomain() +  '/GlobalLogin.jsp?referdomain=' +escape(window.location.host)+'&lastsync='+lastsync+'&source=home&login=false&randomNumber='+Math.random()+'&accountId='+accountId;
		//alert(iframeUrl);
	}else
		iframeUrl = getDomain() + '/CookieHandler.jsp?set=' + cookiestoset + '&action=action_testcookie&lastsync='+lastsync+'&referdomain='+escape(window.location.host)+'&source=home&randomNumber='+Math.random();
				   
	switchTRCardImage("NOT_LOGGED_IN");
	isLoggedIn = false;
	document.write('<iframe width=\'242\' allowtransparency=true height=\'114\' src=\''+iframeUrl+'\' scrolling=\'no\' frameborder=\'no\' ></iframe>');
	
	//DELAY UNTIL AFTER WRITING IFRAME
	write_pzn_code();
	//write_special_tag();
 	return false;
}

function renderBrandLoginDetails(){
	if(isLoggedIn) {
		switchTRCardImage(tier);
    		if(tier=="TOTAL GOLD") tier="GOLD";
		var  displaySection = "<form action='#' method='post' id='ttlRewardsLogin' name='brandLoginForm'>";
		displaySection += "	<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
		displaySection += "		<tr>";
		displaySection += "			<td align='center'>";
		displaySection += "				<table class='ttlRewardsLogin' style='color: white;' cellpadding='0' cellspacing='0' border='0'>";
		displaySection += "					<tr align='left'>";
		displaySection += "						<td style='font-size:9pt;text-align:center'><b>Welcome Back, " + name + "</b></td>";
		displaySection += "					</tr>";
		displaySection += "					<tr height='10px'>";
		displaySection += "						<td style='font-size:6pt'><a href='javascript:earn()' onclick='s_linkType=\"o\";s_linkName=\"TR:TRNG:TRMODULE LINK\";s_lnk=s_co(this); s_gs(\"harrahsglobal\")'><img src='/images/corporate/navElements/spacer.gif' width='100px' height='68px' border='0' /></a></td>";
		displaySection += "					</tr>";
		displaySection += "					<tr>";
		displaySection += "						<td class='acct' style='line-height:14px;'>";
		displaySection += "							Current Tier: " + tier + "<br/> ";
		displaySection += "							Tier Score: " + tierScore + "<br/>";
		displaySection += "							Rewards Credit Balance: " + accountBalance + "<br/>";
		if (offersCount == "0")
		{
			displaySection += " Last Updated: " + lastUpdate;
		} 
		else
		{
			displaySection += " You currently have " + offersCount + " offers";
		}
		displaySection += "						</td>";
		displaySection += "					</tr>";
		displaySection += "					<tr align='center'>";
		displaySection += "						<td width='*' align='center' class='botLinks' style='padding-top:0px;padding-bottom:0px;'>";
		displaySection += "							<a style='color:#90B6C4;text-decoration:underline;padding-left:5px' href='javascript:mytr();'>My TR</a>&nbsp;&nbsp;<a style='color:#90B6C4;text-decoration:underline;' href='javascript:myoffers();'>My Offers</a>&nbsp;&nbsp;";
		displaySection += "							<a style='color:#90B6C4;text-decoration:underline;' href='javascript:logout();'>Sign Out</a>";
		displaySection += "						</td>";
		displaySection += "					</tr>";
		displaySection += "				</table>";
		displaySection += "			</td>";
		displaySection += "		</tr>";
		displaySection += "	</table>";
		displaySection += "</form>";		
		document.write(displaySection);
		
		if(isCookieExist("detectCookie") == "true") {
	              eraseCookie("detectCookie");
	        }
	        if(isCookieExist("omnitureCookie") == "true") {
	              var omnitureVariables = readCookie("omnitureCookie");
	              omnitureVariablesArray = omnitureVariables.split(separator);  
          	}
          } else {
          	renderBrandGlobalLoginWidget();
          }
	return false;
	
}
function renderHomePageLoginDetails(){
	if(isLoggedIn) {
		//switchTRCardImage(tier);
    		//if(tier=="TOTAL GOLD") tier="GOLD";
		var displaySection = "<s" + "cript language='JavaScript' src='/javascript_includes/logIn/MM_functions.js'></s" + "cript>";
		displaySection += "<form action='#' method='post' id='ttlRewardsLogin' name='brandLoginForm'>";
		displaySection += "	<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
		displaySection += "		<tr>";
		displaySection += "			<td>";
		displaySection += "				<div id='trLogin'>";
		displaySection += "					<div id='trWelcome'>Welcome Back<br />" + name + " </div>";
		displaySection += "						<div id='trStats'>";
		displaySection += "				  			<table width='100%' border='0' cellpadding='0' cellspacing='0'>";
		displaySection += "								<tr>";
		displaySection += "									<td align='left'>Current Tier: <span class='trData'>"+ tier +"</span></td>";						
		displaySection += "									<td align='left'>Tier Score: <span class='trData'>" + tierScore + "</span></td>";
		displaySection += "								</tr>";
		displaySection += "								<tr>";
		displaySection += "						 			<td colspan='2'>";
		displaySection += "										<table width='100%' border='0' cellpadding='0' cellspacing='0'>";
		displaySection += "											<tr>";
		displaySection += "												<td width='140' align='left'>Rewards Credit Balance:</td>";
		displaySection += "												<td class='trData'>" + accountBalance + "</td>";
		displaySection += "											</tr>";
		displaySection += "											<tr>";
		displaySection += "												<td width='140' align='left'>You Currently Have:</td>";
		displaySection += "												<td class='trData'>" + offersCount + " Offers</td>";
		displaySection += "											</tr>";
		displaySection += "							 			</table>";
		displaySection += "						 			</td>";
		displaySection += "								</tr>";
		displaySection += "							</table>";
		displaySection += "						</div>";
		displaySection += "						<div id='trBottomLinks'>";
		displaySection += "							<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
		displaySection += "								<tr>";
		displaySection += "									<td><a href='javascript:mytr();'><img src='/images/hcom-home/trmodule/myTR.gif' alt='My TR' name='myTR' width='52' height='22' border='0' id='myTR' onmouseover=\"MM_swapImage('myTR','','/images/hcom-home/trmodule/myTR-over.gif',1)\" onmouseout=\"MM_swapImgRestore()\" /></a></td>";
		displaySection += "									<td><a href='javascript:myoffers();' style='text-decoration:none; font-family:Verdana, Geneva, sans-serif; font-size:9px; color:#000;'><img src='/images/hcom-home/trmodule/myOffers.gif' align=absmiddle alt='My Offers' name='myOffers' width='56' height='22' border='0' id='myOffers' onmouseover=\"MM_swapImage('myOffers','','/images/hcom-home/trmodule/myOffers-over.gif',1)\" onmouseout=\"MM_swapImgRestore()\" /></a><span class='smOfferCount'>(" + offersCount + ")</span></td>";
		displaySection += "									<td><a href='javascript:logout();'><img src='/images/hcom-home/trmodule/signout-.gif' alt='Signout' name='signOut' width='71' height='22' border='0' id='signOut' onmouseover=\"MM_swapImage('signOut','','/images/hcom-home/trmodule/signout-over.gif',1)\" onmouseout=\"MM_swapImgRestore()\" /></a></td>";
		displaySection += "								</tr>";
		displaySection += "							 </table>";
		displaySection += "						</div>";
		displaySection += "					</div>";
		displaySection += "			</td>";
		displaySection += "		</tr>";
		displaySection += "	</table>";
		displaySection += "</form>";		
		document.write(displaySection);
		
		if(isCookieExist("detectCookie") == "true") {
	              eraseCookie("detectCookie");
	        }
	        if(isCookieExist("omnitureCookie") == "true") {
	              var omnitureVariables = readCookie("omnitureCookie");
	              omnitureVariablesArray = omnitureVariables.split(separator);  
          	}
          } else {
          	renderHomePageGlobalLoginWidget();
          }
	return false;
	
		
}

function renderSkinnyGlobalLoginWidget() {
	var iframeUrl='';
	var cookiestoset = '';
	
	if(typeof(page_cookiestoset) != "undefined")
	{
		cookiestoset=escape(page_cookiestoset);
	}
	iframeUrl = getDomain() + '/CookieHandler.jsp?set=' + cookiestoset + '&action=action_testcookie&lastsync='+lastsync+'&referdomain='+escape(window.location.host)+'&source=skinny';
	//alert('Iframe will load page on TOTALREWARDS.com to test the cookies.\nIf cookies are in sync page will redirect to property login/loggedin page.');
	isLoggedIn = false;
  document.write('<iframe style="background-color:#172D69;" name=\'trIfame\' width=\'100%\' height=\'25\' allowtransparency=true src=\''+iframeUrl+'\' scrolling=\'no\' frameborder=\'no\' ></iframe>');
	
	//DELAY UNTIL AFTER WRITING IFRAME
	write_pzn_code();
	write_special_tag();
	return false;
}

function renderSkinnyLoginDetails() {
	if(isLoggedIn){
		var displaySection = "<table cellpadding='0' cellspacing='0' border='0' style='white-space: nowrap; width: 100%;'><tr><th style='color:white'>Hello, <span class='bold' style='color:white'>" +  name + "</span></th><td style='color:white'>TIER: <span class='bold'>"  + tier + "</span></td><td style='color:white'>BALANCE: <span class='bold'>" + accountBalance + "</span></td><td align='right' class='rtPad5' style='color:white;text-align: right;'><a style='color:white' href='javascript:mytr();'>MY TR </a> | <a style='color:white' href='javascript:myoffers();'>MY OFFERS (" + offersCount + ")</a> | <a style='color:white' href='javascript:logout();'>SIGN-OUT</a></td></tr></table>";
		document.write(displaySection);
		renderFlashTRMod(name,tier,accountBalance,offersCount);
		if(isCookieExist("detectCookie") == "true") {
		      eraseCookie("detectCookie");
		}
		if(isCookieExist("omnitureCookie") == "true") {
		      var omnitureVariables = readCookie("omnitureCookie");
		      omnitureVariablesArray = omnitureVariables.split(separator);  
		}
        } else {
          	renderSkinnyGlobalLoginWidget();
        }
	return false;
}

function renderFlashTRMod(fName,fTier,fAccountBalance,fOffersCount){
	//document.write("<script language='JavaScript'>try{parent.document.TRMod.sendToFlashTR('"+fName+"','"+fTier+"','"+fAccountBalance+"','"+fOffersCount+"');}catch(e){}<script>");
	//document.write("<script language='JavaScript'>try{window.parent.test();}catch(e){}<script>");
}
function getParentObj(ObjName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window.parent[ObjName] : parent.document[ObjName];
}

function write_pzn_code()
{
	//
	// New PZN code added 1/26/08
	//
	// only execute this code if we're not on the global login iFrame
	try
	{
		if (window.location.href.indexOf('GlobalLogin.jsp') < 0) {
			if (window['getXMLHttpObj'] == null) {
				try //adding try catch since window.parent will fail if domains not same ...
				{
					if (window.parent.location.href.indexOf('debug=') >= 0)
						alert('Adding [getXMLHttpObj] method');
				}catch(e){}
						
				eval("function getXMLHttpObj(){ " +
					"	if(typeof(XMLHttpRequest)!='undefined') " +
					"		return new XMLHttpRequest(); " +
					"	var axO=['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.4.0', " +
					"		'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'], i; " +
					"	for(i=0;i<axO.length;i++) " +
					"		try{ " +
					"			return new ActiveXObject(axO[i]); " +
					"		}catch(e){} " +
					"	return null; " +
					"} ");
				window['getXMLHttpObj'] = eval('getXMLHttpObj');
			}

			if (window['loadScript'] == null) {
				try //adding try catch since window.parent will fail if domains not same ...
				{
					if (window.parent.location.href.indexOf('debug=') >= 0)
						alert('Adding [loadScript] method');
				}catch(e){}
				eval("function loadScript(scriptpath, functions){ " +
					"	if (window.parent.location.href.indexOf('debug=') >= 0) " +
					"		alert('Loading required JS methods...'); " +
					"	var oXML = getXMLHttpObj(); " +
					"	oXML.open('GET', scriptpath, false); " +
					"	oXML.send(''); " +
					"	eval(oXML.responseText); " +
					"	for(var i=0; i<functions.length; i++) " +
					"		window[functions[i]] = eval(functions[i]); " +
					"} ");
				window['loadScript'] = eval('loadScript');
			}

			if (window['pznAlreadyLoaded'] != true) {
				try //adding try catch since window.parent will fail if domains not same ...
				{
					if (window.parent.location.href.indexOf('debug=') >= 0)
						alert('PZN iFrame has not been loaded. Loading...');
				}catch(e){}	
				// prevent this code from executing multiple times
				window['pznAlreadyLoaded'] = true;

			// load the utility functions for the PZN code below
			if (window['readQueryString'] == null)
				loadScript('/javascript_includes/utility.js', ['getValue', 'readQueryString']);

				// personalization tag
				var loc = window.location;
				loc = (readQueryString('loc')!='') ? readQueryString('loc') : loc; //allow of location override
				loc = escape(loc);
				var pzn_iframe = '<iframe id="pznIframeExists" name="pznIframeExists" src="/pzn.htm?loc=' + loc + '" height="2" width="2" style="display:none;"></iframe>'	
				try //adding try catch since window.parent will fail if domains not same ...
				{
					if (window.parent.location.href.indexOf('debug=') >= 0)
						alert('iFrame tag: ' + pzn_iframe);
				}catch(e){}
				document.write(pzn_iframe);
			}
		}
	}catch(e){}

}


function write_special_tag()
{
	document.write('<s' + 'cript id=\'__s14\'></s' + 'cript>');
	
	var special_tag = function()
	{
		if(readQueryString('debug_special_tag') != '') alert('Good news, no other function hijacked the onload event.');
		document.getElementById("__s14").src="https://view.atdmt.com/jaction/heihb9_HarrahsSiteWideRemessagingTag_10";
	}
	
	var _o = window.onload;
	if(typeof _o != 'function')
	{
		window.onload = special_tag;	
	}
	else
	{
		window.onload = function(){
				_o();
				special_tag();
			}
	}
}
