//<script language="javascript">
// Simply pass the string to this function and it will return 
// the string with the leading and trailing spaces taken out.
function trim(strText) { 
    strText = new String(strText);
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);
	
	var regExp = /[\"\',?~#$%^&*()]/g;
	strText = strText.replace(regExp,"");

   return strText;
}



// gets form values
function getRequestData(thisField) {
	var thisValue = thisField.value;
	if ("undefined" == thisValue) {
		return "";
	} else {
		return trim(thisValue);
	}
}

// Function to parse semicolon delimited error strings and displays
// it in an order list format.
function parseErrTxt(sErrors) {
	var sErrorString = new String(sErrors);
	var splitString = sErrorString.split(';');
	var iStrings = splitString.length;
	var sOutputStrings = '<ul><ol>';
	for (var i=0; i < iStrings - 1; i++) {
		sOutputStrings += '<li>' + splitString[i];
	}
	sOutputStrings += '</ol></ul>';
	
	return sOutputStrings;
}

// Scrolls the screen down to amount of pixels
function gotoBottom(iBottom) {
	window.scrollBy(0,iBottom);
}

// Scrolls the screen down to amount of pixels
function scrollToBottom(iStart, iBottom) {
	for (var i=iStart; i < iBottom; i += 2) {
		window.scroll(1,i);
	}
}


// Function to dynamically change content
function writeLayer(layerID,txt) {
	if(document.getElementById){
    	document.getElementById(layerID).innerHTML=txt;
	}else if(document.all){
		document.all[layerID].innerHTML=txt;
	}else if(document.layers){
		with(document.layers[layerID].document){
			open();
			write(txt);
			close();
		}
	}
}

// This function is called where it contains the verisign verification logo
// Purpose: pops up the window containing information about our verisign certificate.
function verisignPopUp()
{
	window.open('https://digitalid.verisign.com/as2/4e6bfcc4da863643be0de0995c9ebbce','YBNET_verisign','toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=690,height=450');
}

// explanation of four digit code and signature bar number
// this takes one parameter, the PAGE parameter.
// Parameter: page (int)
//			3 - Signature Bar explaination page	
//			4 - Four digit code explaination page	
function Explain(page) {
	sURL = HTTPS_APP_ROOT + "account/" + page + "digits.html";
	window.open(sURL,'YBNET_CCExtra','toolbars=no,menubar=no,resizable=no,width=243,height=281');
}

// Open SEC Filing Window.
function OpenSECFilings() {
	var secWin = window.open('http://www.sec.gov/cgi-bin/browse-edgar?CIK=0000814055&owner=include&action=getcompany','YBNET_SECfilings','toolbar=yes,scrollbars=yes,resizable=yes,width=780,height=580,top=0,left=0');
	secWin.focus();
}

// Open the CAB Account Issue
var isCABFunding = false;

function popUpWagerAccountIssue() {
	var url;
	if (isCABFunding) {
		url = "wagerAccountIssueCAB.htm";
	} else {
		url = "wagerAccountIssuePopUp.htm";
	}
	window.open(url,"YBNET_accountIssues","menubar=0,toolbars=0,resizable=0,scrollbars=0,statusbar=0,width=400,height=250");
}

// Deposit declined details...
function openDeclineDetailsFirePay() {
	// This procedure will open a dialog with extra details about the decline.
	window.open("depositDeclinedDetailsFirePay.htm","YBNET_declined","menubar=0,toolbars=0,resizable=0,scrollbars=0,statusbar=0,width=500,height=300");
	// alert("Special Notice: Many institutions are now rejecting credit card transactions related to the gaming industry.\nIf you have previously used your credit card successfully and are now being declined, we highly recommend\nthat you fund your account using ExpressCash. It is an efficient way of moving funds in and out of your\nwagering account and it is free of any proccessing charges.\n");
}

// Deposit declined details...
function openDeclineDetailsBank() {
	// This procedure will open a dialog with extra details about the decline.
	window.open("depositDeclinedDetailsBank.htm","YBNET_declined","menubar=0,toolbars=0,resizable=0,scrollbars=0,statusbar=0,width=500,height=300");
	// alert("Special Notice: Many institutions are now rejecting credit card transactions related to the gaming industry.\nIf you have previously used your credit card successfully and are now being declined, we highly recommend\nthat you fund your account using ExpressCash. It is an efficient way of moving funds in and out of your\nwagering account and it is free of any proccessing charges.\n");
}

// This masked the input fields to restrict only numeric values.  If the user types in a non-numeric value,
// this deletes it.
// Usage: use the onKeyUp event handler on html forms.
// example:  <input name="CreditCardNumber" onKeyUp="maskNumField()">
function maskNumField(thisElement) {
	var tempValue = new String(thisElement.value);
	var regExp = /[^0-9]/g;
	if (regExp.test(tempValue) == true) {
		thisElement.value = tempValue.replace(regExp,"");
	}
}

// Handles the login throughout all web pages
function handleGoButtonPressed() {	
	try {
		ybxLogin.fireEvent('onsubmit'); // autocomplete info saved on form submit
	} catch(e) {
		// fireEvent not supported by IE 5.0. catch and ignore this.
	}
	
	if (validateFormInput()) {
		MM_swapImage('tracker','','/images/clicked_go_button.gif',1);
		autoLoginToYBX(document.ybxLogin.handle.value, 
			document.ybxLogin.password.value, 
			"CA",
			false);
	}
}

// This logs user in from web site when the "Return" key is pressed
function processEnterKey(myfield, e) {

	if (window.event.srcElement.id == "inpHandle") {
		doAOLCheck();	
	}

	var keycode;

	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13) {
		handleGoButtonPressed();
		return false;
	}
	else {
		return true;
	}
		
}

// Pop a dialog if the user is using an embedded AOL browser
// Catches all exceptions
function doAOLCheck(bUseModalDialog) {
	try {
		if (top.AOLchecked) { 
			// bail if we already ran this check
			return;
		} else {	
			top.AOLchecked = true;
			if (navigator.appVersion.indexOf("AOL") >= 0) { 
				// using AOL browser
				var sCookie = new String(document.cookie);
				if (sCookie.match(/YBDontShowAOLWarning/) == null) {
					// no 'dont show again' cookie
					var sDialogAgs = "dialogHeight:400px;dialogWidth:520px;center;yes";
					if (bUseModalDialog) {
						window.showModalDialog(AOL_WARNING_URL,null,sDialogAgs);						
					} else {	
						window.showModelessDialog(AOL_WARNING_URL,null,sDialogAgs);						
					}
				}	
			} 	
		}	
	} catch (e) {
		// ignore exceptions
	}
}

// Validates YBX Login from all pages
function validateFormInput() {	
	if (document.ybxLogin.handle.value == "") {
		alert("The 'Handle' field cannot be blank.");
		return false;
	}
	
	if (document.ybxLogin.password.value == "") {
		alert("The 'Password' field cannot be blank.");
		return false;
	}
	
	if (document.ybxLogin.handle.value.match(/ /) != null) {
		alert("The 'Handle' field cannot contain spaces.");
		return false;
	}
	
	if (document.ybxLogin.password.value.match(/ /) != null) {
		alert("The 'Password' field cannot contain spaces.");
		return false;
	}
	
	return true;
}

// auto login to ybx with hostname determination
// if it's the live web hostname, then direct to www.youbet.net
// else, direct to www.test.youbet.net
// Usage: call this function from anywhere that requires autoLogin to youbet.net
// 		  by passing the following parameters:
//		sHandle varchar(10)
//		sPassword varchar(10)
//		sLocation varchar(2) i.e. CA, NJ, AZ....
// 		bIsPopUp boolean (	true - is called from a popup, need to open in the calling window.
//							false - not from a popup, simply redirect to the top frame. )
function autoLoginToYBX(sHandle, sPassword, sLocation, bIsPopUp) {
	// store password into secured cookie
	try {
		setSecuredCookie("password", sPassword);
	} catch(e) {
		alert('error setting cookie: ' + e.description);
	}

	var autoLoginURL = HTTPS_APP_ROOT + "login/login.asp?handle=" + sHandle
		+ "&location=" + sLocation
		+ "&br=" + BR_CODE + "&brsub=" + BRSUB_CODE
		+ "&autoLogin=true";

	if (!bIsPopUp) {
		location.href = autoLoginURL;
	} else {
		if (top.opener.closed) {
  			intWidth = screen.availWidth - 10; 	//Adjust for the end of screen (don't know why?)
  			intHeight = screen.availHeight - 162; //Adjust for the Icon Bar at the bottom of the window.
			strWinProp = " toolbar=yes"      //Back, Forward, etc...
               + ",location=yes"      		//URL field
               + ",status=yes"       		//Status Bar at bottom of window.
               + ",menubar=yes"       		//Menubar at top of window.
               + ",resizable=yes"     		//Allow resizing by dragging.
               + ",scrollbars=yes"   		//Displays scrollbars is document is larger than window.
               + ",titlebar=yes"     		//Enable/Disable titlebar resize capability.
               + ",width="+intWidth			//Standard 640,800/788, 800/788
               + ",height="+intHeight  		//Standard 480,600/541, 600/566 
               + ",top=0"              		//Offset of windows top edge from screen.
               + ",left=0"             		//Offset of windows left edge from screen.
               + "";
			window.open(autoLoginURL,'YBNET_YoubetExpress',strWinProp);
			self.close();
 		} else {
			top.opener.top.location.href = autoLoginURL;
			top.opener.focus();
		}
	}
}

// load youbet.net
// if it's the live web hostname, then direct to www.youbet.net
// else, direct to www.test.youbet.net
// Usage: call this function from anywhere that requires loading of youbet.net
// 		  by passing the following parameter:
//
// 		bIsPopUp boolean (	true - is called from a popup, need to open in the calling window.
//							false - not from a popup, simply redirect to the top frame. )
// Author: Armen
//
function loadYBX(bIsPopUp) {
	var hostname = document.location.hostname;
	var racingHostname;

	if (hostname.search(/www1/) != -1) {		
		racingHostname = hostname.replace(/www1/,'racing1');
	}
	else if (hostname.search(/www/) != -1) {		
		racingHostname = hostname.replace(/www/,'racing');
	}
	else {		
		racingHostname = "racing." + hostname;
	}
	
	racingHostname = 'http://' + racingHostname + '/';

	if (!bIsPopUp) {
		top.location.href = racingHostname;
	} else {
		if (top.opener.closed) {
  			intWidth = screen.availWidth - 10; 	//Adjust for the end of screen (don't know why?)
  			intHeight = screen.availHeight - 162; //Adjust for the Icon Bar at the bottom of the window.
			strWinProp = " toolbar=yes"      //Back, Forward, etc...
               + ",location=yes"      		//URL field
               + ",status=yes"       		//Status Bar at bottom of window.
               + ",menubar=yes"       		//Menubar at top of window.
               + ",resizable=yes"     		//Allow resizing by dragging.
               + ",scrollbars=yes"   		//Displays scrollbars is document is larger than window.
               + ",titlebar=yes"     		//Enable/Disable titlebar resize capability.
               + ",width="+intWidth			//Standard 640,800/788, 800/788
               + ",height="+intHeight  		//Standard 480,600/541, 600/566 
               + ",top=0"              		//Offset of windows top edge from screen.
               + ",left=0"             		//Offset of windows left edge from screen.
               + "";
			window.open(racingHostname,'YBNET_YoubetExpress',strWinProp);
 		} else {
			top.opener.location.href = racingHostname;
			top.opener.focus();
		}
	}
}


function loginToYBXAsGuest() { 
	doAOLCheck(true);
	var sURL = location.href;
	var bIsPopup = false;
	if (sURL.indexOf('signup') != -1) {
		bIsPopup = true;
	}
	autoLoginToYBX('guest','guest666','PA',bIsPopup); 
}

// function to automatically jump to the next field
function jumpToNextField(thisElement, iMaxLength) {
	var iIndex = getNextIndex(thisElement);
	iIndex++;
	maskNumField(thisElement);
	if (thisElement.value.length >= iMaxLength) {
		thisElement.form[iIndex].focus();
	}			
}

// gets the index of the next field
function getNextIndex(formElement) {
	var index = -1, i = 0;
	while (i < formElement.form.length && index == -1) {
		if (formElement.form[i] == formElement)
			index = i;
		else 
			i++;
	}
	return index;
}

// selects the correct selection to populate a drop down form field on Netscape and IE
function selectDropDown(field, sValue) {
	var iLength = field.options.length;
	for (var i=0; i < iLength; i++) {
		if (field.options[i].value == sValue) {
			field.selectedIndex = i;
			break;
		}
	}
}

// converts numeric dollar amounts to text amount.
function FormatCurrencyText(sDollarAmount, sCents) {
	sCents = new String(sCents);
	var BigOnes = new Array("","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety");
	var SmallOnes = new Array("","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen");
	var Words = "";
	var Chunk;
	var digits;
	var leftdigit;
	var rightdigit;
	
	if (parseInt(sDollarAmount,10) > 999999) {
		alert('Dollar amount is too large');
		return null;
	}
	
	if (parseInt(sDollarAmount,10) == 0) {
		Words = "Zero";
	} else {
		sDollarAmount = FormatDollar(sDollarAmount);
		Chunk = sDollarAmount.substr(0,3);
		if ((Chunk + 0) > 0) {
			digits = Chunk.substr(0,1);
			if ((digits + 0) > 0) {
				Words += " " + SmallOnes[parseInt(digits,10)] + " Hundred";
			}
			digits = Chunk.substr(1,2);
			if ((digits + 0) > 19) {
				leftdigit = Chunk.substr(1,1);
				rightdigit = Chunk.substr(2,1);
				Words += " " + BigOnes[parseInt(leftdigit,10)];
				if ((rightdigit + 0) > 0) {
					Words += " " + SmallOnes[parseInt(rightdigit,10)];
				}
			} else {
				if ((digits + 0) > 0) {
					Words += " " + SmallOnes[parseInt(digits,10)];
				}
			}
			
			Words += " Thousand";
		}
		
		Chunk = sDollarAmount.substr(3,3);
		if ((Chunk + 0) > 0) {
			digits = Chunk.substr(0,1);
			if ((digits + 0) > 0) {
				Words += " " + SmallOnes[parseInt(digits,10)] + " Hundred";
			}
			digits = Chunk.substr(1,2);
			if (parseInt(digits,10) > 19) {
				leftdigit = Chunk.substr(1,1);
				rightdigit = Chunk.substr(2,1);
				if ((leftdigit + 0) > 0) {
					Words += " " + BigOnes[parseInt(leftdigit,10)];
				}
				if (parseInt(rightdigit) > 0) {
					Words += " " + SmallOnes[parseInt(rightdigit,10)];
				}
			} else {
				if ((digits + 0) > 0) {
					Words += " " + SmallOnes[parseInt(digits,10)];
				}
			}
		}
	}
	
	if ((parseInt(sCents,10) == 0) || (sCents == "")) { sCents = "00"; }
	Words += " and " + sCents + "/100";
	return Words;
}

// formats the dollar amount to six digits.
function FormatDollar(Amount) {
	var maxLength = 6;
	var iAmountLength = Amount.length;
	var iRemain;
	Amount = new String(Amount);
	if (iAmountLength < maxLength) {
		iRemain = maxLength - iAmountLength;
		for (var i=0; i < iRemain; i++) {
			Amount = "0" + Amount;
		}
	} else if (iAmountLength > maxLength) {
		Amount = Amount.substring(iAmountLength - maxLength, iAmountLength);
	}
	return Amount;		
}

// Netscape warning when user resizes browser.
var m_screenWidth = self.innerWidth;
var m_screenHeight = self.innerHeight;

function CheckAndReload() {
	if (document.layers) {
		if (self.top.innerWidth != m_screenWidth || self.top.innerHeight != m_screenHeight) {
			window.location.reload();
			m_screenWidth = self.top.innerWidth;
			m_screenHeight = self.top.innerHeight;
			alert('BROWSER WARNING!\n\nPlease do not resize this window again while filling out the form.  \nYou will lose all your data and will have to re-enter the data again.\n\nCause: This browser refreshes the page when you resize the window.');
		}
	}
	self.setTimeout('CheckAndReload()', 500);
}

/* ==================================================================
   THIS FUNCTION IS TAKEN DIRECTLY FROM NETSCAPE FROM:
   http://developer.netscape.com/library/examples/...
                    .../javascript/formval/FormChek.js
   which is a bunch of functions to validate forms
    
   FUNCTION: isCreditCard(st)
   INPUT:    st - a string representing a credit card number
   RETURNS:  true, if the credit card number passes the Luhn Mod-10 test
	         false, otherwise
   ================================================================== */

function isCreditCard(st) {
  if (st.length > 19)
    return (false);

  var sum = 0; 
  var mul = 1; 
  var l = st.length;
  for (var i = 0; i < l; i++) {
    var digit = st.substring(l-i-1,l-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);
}

// function to open signup page - version 2 use only
function OpenAnAccount() {
	var sURL = HTTPS_APP_ROOT + "account/";
//	location.href = sURL;
	window.open(sURL,'YBNET_OpenAnAccount','toolbar=no,status=yes,scrollbars=no,resizable=yes,width=790,height=550,top=5,left=5');
}

// function to Add Ladbroke Account Request to Bookmaker
function addLadbrokeAccountRequest(sHandle) {
	var sURL = "processLadbrokeAccountRequest.asp?handle=" + sHandle;
	
	// create and send the request (sync)
	var oXML = new ActiveXObject("Microsoft.XMLDOM");

	// send request
	oXML.async = false;
	oXML.validateOnParse = false; 
	oXML.resolveExternals = false; 	
	oXML.load(sURL);

	// don't need to return anything.  Server side will log errors	
	return 0;
}

// function to parse Names (i.e. First letter uppercase and the rest lowercase.)
function formatNameString(oField) {
	var sString = new String(oField.value);
	var arrSplitString = sString.split(" ");
	var iLength = arrSplitString.length;
	var resultString;
	for (var i=0; i < iLength; i++) {
		var sFirstTwo = arrSplitString[i].substring(0,2).toLowerCase();
		var sThird = arrSplitString[i].substring(2,3).toLowerCase();
		var iStringLength = arrSplitString[i].length;
		if (iStringLength > 3 && "mc" == sFirstTwo) {
			arrSplitString[i] = arrSplitString[i].substring(0,1).toUpperCase() + arrSplitString[i].substring(1,2).toLowerCase() + arrSplitString[i].substring(2,3).toUpperCase() + arrSplitString[i].substring(3,iStringLength).toLowerCase();
		} else if (iStringLength > 3 && ("on" == sFirstTwo || "or" == sFirstTwo) && ("e" == sThird || "i" == sThird)) {
			arrSplitString[i] = arrSplitString[i].substring(0,2).toUpperCase() + arrSplitString[i].substring(2,iStringLength).toLowerCase();
//		} else if (iStringLength > 3 && "ma" == sFirstTwo && "c" == sThird) {
//			arrSplitString[i] = arrSplitString[i].substring(0,1).toUpperCase() + arrSplitString[i].substring(1,3).toLowerCase() + arrSplitString[i].substring(3,4).toUpperCase() + arrSplitString[i].substring(4,iStringLength).toLowerCase();
		} else {
			arrSplitString[i] = arrSplitString[i].substring(0,1).toUpperCase() + arrSplitString[i].substring(1,iStringLength).toLowerCase();
		}
	}
	resultString = arrSplitString.join(" ");
	
//	alert('String: ' + sString + '\nWords: ' + iLength + '\nFirst 2 Letters: ' + sFirstTwo + '\nResult: ' + resultString);
	oField.value = resultString;
}

// The following group of functions is to block specific keys from being entered into a form field
// isLettersNumbers(key): only allows letters and numbers and / symbol.
// isLettersOnly(key): only allows letters.
// isNumbers(key): only allows numbers.
// To call this from the form, do this:
// 
// <input name="id" onKeyPress="event.returnValue = isNumbers(event.keyCode);">
// 
// This will prevent letters and symbols from being entered into the field.  
// NOTE: This will only work on Internet Explorer.  Not tested in Netscape.

function isLettersNumbers(key) {
	if ((key > 32 && key < 47) || (key > 57 && key < 65) || (key > 90 && key < 97) || (key > 122)) {
		return false;
	} else {
		return true;
	}
}

function isLettersOnly(key) {
	if ((key > 32 && key < 65) || (key > 90 && key < 97) || (key > 122)) {
		return false;
	} else {
		return true;
	}
}

function isNumbers(key) {
	if ((key < 48) || (key > 57)) {
		return false;
	} else {
		return true;
	}
}

function setSecuredCookie(sCookieName, sCookieValue) {
	var sCookieString = sCookieName + "=" + escape(sCookieValue);
	sCookieString += "; path=/";

	if (new String(location.hostname).match(/youbet\.net/) != null) {
		sCookieString +="; domain=youbet.net";
	}
	
	sCookieString += "; secure=true";
	
	document.cookie = sCookieString;
}

//  Guest message for guest to test quick cash and withdrawal forms.
var sGuestMessage = "Youbet.net members can transfer funds between their checking and\nwagering accounts with a click of a mouse!  Open an account\nwith Youbet.net by selecting the OPEN AN ACCOUNT option\non the main guest page or by calling Member Services at\n1-877-40-WAGER.";
