﻿/* *****************************************************************************
   The following variables are constants used for video streaming 
*******************************************************************************/
var TVGBypassMediaCheckCookie = "TVGBypassMediaCheckCookie";
var ForceBandwidthAutoDetect = true;
var TVGLiveConnectionSpeedCookie = "TVGLiveSpeedCookie";
var TVGReplayConnectionSpeedCookie = "TVGReplaySpeedCookie";
var iFirefoxHeightAdjustment = 40;
var InsincSuperParamValue = "SUPER";
var InsincHighParamValue = "HIGH";
var InsincLowParamValue = "LOW";


function GetClientDisplayTime()
{
    try
    {
        var dtCurrent = new Date();
        var iHours = dtCurrent.getHours();
        var iMinutes = dtCurrent.getMinutes();
        var iSeconds = dtCurrent.getSeconds();
        var tod;
        if (iHours >= 12)
        {
            tod = "PM";
            iHours -= 12;
        }              
        else
        {
            tod = "AM";
        }                  
        if (iHours == 0)
        {
            iHours = 12;
        }
        
        if (iMinutes < 10)
        {
            iMinutes = "0" + iMinutes;
        }
        
        if (iSeconds < 10)
        {
            iSeconds = "0" + iSeconds;
        }
        
        return(iHours + ":" + iMinutes + ":" + iSeconds + " " + tod + "ET");
    }
    catch (ex)
    {
        var caller = "Caller Unknown"; try {caller = arguments.callee.caller.toString().match(/^function (\w+)/)[1];} catch (ex) {}
        var callee = "Unknown"; try {callee = arguments.callee.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		HandleException(caller + " -> " + callee + ": " + ex.message, null, '', '');
    }
}

function IsTrue(value){
	var truepattern = /^true$/i;
	return truepattern.test(value); // convert to boolean
}

function IsInteger(value){
	var intpattern = /^\d+$/;
	return intpattern.test(value); // true if integer
}

function IsCurrency(value){
	var curpattern = /^\d+(\.\d\d)?$/;	
	return curpattern.test(value); // true if currency
}

function FormatDollarsAndCents(value) 
{ 
	var money = "$NA";
	try {
		if (isFinite(value)) {
			var valueCents = value - Math.floor(value)
			if (valueCents > 0) {
				var moneyArr = value.toString().split(".")
				var dollars = moneyArr[0];
				var cents = moneyArr[1];
				if (cents.length < 2) { //value = e.g. $10.2
					money = "$" + value + "0"
				} else if (cents.length > 2) {
					money = "$" + dollars + "." + cents.substring(0,2)
				} else {
					money = "$" + value
				}
			} else {
				money = "$" + value
			}
		}
	}
	catch (ex) {}
	return money;
}

function HyphenateHorseList(str) {
	var tempstring="", last="", first=""
	var temparray
	var tempholder
	
	try {
		str = str.replace(/,+/g,","); // remove any duplicate commas
		str = str.replace(/^,/g,""); // remove preceding comma
		str = str.replace(/,$/g,""); // remove ending comma

		temparray = str.split(",");

		if (temparray.length == 0) 
			tempstring = "";
		else if (temparray.length == 1) 
			tempstring = temparray[0]
		else {
			first = temparray[0]
			tempholder = first
			for(var hIndex=1; hIndex<temparray.length; hIndex++) {
				if (parseInt(temparray[hIndex]) == parseInt(tempholder) + 1) {
					last = temparray[hIndex]
					if (hIndex == temparray.length-1) {
						if (last == "")
							tempstring += first
						else {
							if (parseInt(last) == parseInt(first) + 1)
								tempstring += first + "," + last
							else
								tempstring += first + "-" + last
						}
					}
				} else { // if last element in array
					if (hIndex == temparray.length-1) {
						if (last == "")
							tempstring += first + "," + temparray[hIndex]
						else {
							if (parseInt(last) == parseInt(first) + 1)
								tempstring += first + "," + last + "," + temparray[hIndex]
							else
								tempstring += first + "-" + last + "," + temparray[hIndex]
						}
					} else {
							            
						if (last == "")
							tempstring += first + ","
						else {
							if (parseInt(last) == parseInt(first) + 1)
								tempstring += first + "," + last + ","
							else
								tempstring += first + "-" + last + ","
						}
						first = temparray[hIndex]
						last = ""
					}
				}
				tempholder = temparray[hIndex]
			} // end for
		}
    }
	catch (ex) {
		var caller = "Caller Unknown"; try {caller = arguments.callee.caller.toString().match(/^function (\w+)/)[1];} catch (ex) {}
        var callee = "Unknown"; try {callee = arguments.callee.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		HandleException(caller + " -> " + callee + ": " + ex.message, null, '', '');
	}
	return tempstring
}

function GetXMLHTTPConnection()
{    
    var request = null;
    try 
    {
        request = new XMLHttpRequest();
    }
    catch (trymicrosoft)
    {
        try
        {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (othermicrosoft)
        {
            try
            {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (failed)
            {
                request = null;
            }  
        }
    }
    return request;
}

function InitPageControl(UpdateAlertIntervalinSecs)
{
	UpdateAlertInterval = UpdateAlertIntervalinSecs;
	
	SendSubscriberAlertRequest();
}

var UpdateAlertTimerID=0, UpdateAlertInterval=0;

function StopUpdateAlertTimer(){
	if(UpdateAlertTimerID !== 0) {
		clearTimeout(UpdateAlertTimerID);
		UpdateAlertTimerID = 0;
	}
	return true;
}

// When this timer expires refresh alert
function StartUpdateAlertTimer(){
	StopUpdateAlertTimer();
	if (UpdateAlertInterval > 0)
		UpdateAlertTimerID = setTimeout(SendSubscriberAlertRequest, UpdateAlertInterval*1000)
	return true;
}

function SendSubscriberAlertRequest()
{
	try
	{
		xmlhttpSubscriberAlert = GetXMLHTTPConnection();
		var link = window.location.protocol + "//" + window.location.host + BaseFolder + 'Authenticated/handlers/InformationHandler.ashx?sectionname=SubscriberAlert';
		xmlhttpSubscriberAlert.open("GET", link, true);
		xmlhttpSubscriberAlert.onreadystatechange = _ProcessSubscriberAlertRequest;
		xmlhttpSubscriberAlert.send(null);
	}
	catch (ex)
    {
		CloseSubscriberAlert();
    }
}

var xmlhttpSubscriberAlert = null;

function CloseSubscriberAlert() {
	var SubscriberAlertDiv = document.getElementById('SubscriberAlertDiv');
	if (SubscriberAlertDiv !== null) {
		SubscriberAlertDiv.style.display = "none";
		setCookie("alertVersion", alertVersion);
	}
	var TrackTiles = document.getElementById('TrackTiles');
	if (TrackTiles !== null) { // force redraw of tracktiles to correct layout in IE
		TrackTiles.innerHTML = TrackTiles.innerHTML;
	}
}

var alertVersion = getCookie("alertVersion");

function _ProcessSubscriberAlertRequest()
{
	try 
	{
		var oError = {number:-1, text:""};
		var xmlDoc = ProcessGeneralXmlResponse(xmlhttpSubscriberAlert, oError);

		if (xmlDoc !== null && oError.number == 0) {
			var SubscriberAlertDiv = document.getElementById('SubscriberAlertDiv');
			if (SubscriberAlertDiv !== null) {
	        
				if(xmlDoc.childNodes.length>0){
					var newVersion = xmlDoc.getAttribute("version");
					if (newVersion != alertVersion) {
						var node = xmlDoc.childNodes.item(0);
						var alertContents = node.nodeValue;
						if (alertContents.length > 0) {
							SubscriberAlertDiv.style.display = "inline";
						} else {
							SubscriberAlertDiv.style.display = "none";
						}
						var TrackTiles = document.getElementById('TrackTiles');
						if (TrackTiles !== null) { // force redraw of tracktiles to correct layout in IE
							TrackTiles.innerHTML = TrackTiles.innerHTML;
						}
						SubscriberAlertDiv.innerHTML = alertContents;
						alertVersion = newVersion;
					}
				} else {
					SubscriberAlertDiv.style.display = "none";
				}
			}
		}
	}
	catch (ex)
	{
		CloseSubscriberAlert();
	}
	StartUpdateAlertTimer();
}

function isOdd(number){
	var retval = false;
	try{
		var numberB = (number / 2);
		var numberC = (Math.floor(numberB));
		if (numberB != numberC) {
			retval = true;
		}
    }
	catch (ex) {}
	return retval;
}

function trimString(s)
{
  return s.replace(/^\s+|\s+$/g,"");
}

function popWagerWindow(TrackInfo, RaceNumber, Amount, WagerType, Horses){ 
  
  var selectedTrack="";
  var selectedRace="";
  var selectedAmount="";
  var selectedWagerType="";
  var selectedHorses="";
	
  if (typeof TrackInfo != "undefined") {
	  selectedTrack = TrackInfo;
  } else {
	  try{
		  var oTrack = GetSelectedTrack();
		  if (oTrack instanceof Track)
		      selectedTrack = oTrack.GetAbbr();
	  }catch(er){}
  }
  if (typeof RaceNumber != "undefined") {
	  selectedRace = RaceNumber;
  } else {
	  try{
		  var oRaceSelection = GetSelectedRace();
		  if (oRaceSelection instanceof Race)
			  selectedRace = oRaceSelection.GetNumber();
	  }catch(er){}
  }
  if (typeof Amount != "undefined") {
	  selectedAmount = Amount;
  }
  if (typeof WagerType != "undefined") {
	  selectedWagerType = WagerType;
  }
  if (typeof Horses != "undefined") {
	  selectedHorses = Horses;
  }
  if (typeof BaseFolder == "undefined") {
	  BaseFolder = "/";
  }
  var wagerWindowLink = BaseFolder + "TVGBetTicket/Default.aspx?TrackAbbr=" + selectedTrack + "&RaceNum=" + selectedRace +
	  "&amount=" + selectedAmount + "&wagertype=" + selectedWagerType + "&Horses=" + selectedHorses;
		
  if (typeof window.showModelessDialog != "undefined") 
  {
	  // try/catch added to help solve the "Exception InitialLoad -> ReferPopUp: Access is denied." error some customers are getting.
	  try
	  	{
	  		var betTicketWidth = "285";
	  		var betTicketHeight = "580";
	  		var useragent = navigator.userAgent.toLowerCase();
			if (/msie (\d+\.\d+);/.test(useragent))
			{ //test for msie x.x; If IE 6 increase the height to appear as other browsers.
				var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
				if (ieversion >= 6 && ieversion < 7)
				{
					betTicketWidth = "294";
					betTicketHeight = "627";
				} 			
			}
			window.showModelessDialog(wagerWindowLink, '', 'help:no;resizable:yes;status:no;dialogWidth:' + betTicketWidth + 'px;dialogHeight:' + betTicketHeight + 'px;scroll:yes;center:no;');								
		}
		catch (ex) 
		{	   
			// Here's a hack to handle the "Access Is Denied" error for blocked popups until we can get BrowserHawk
			// to check for popup blockers
			HandlePopupException(ex.message);	  			
		}
  } 
  else
	  window.open(wagerWindowLink,"","resizable=yes,status=yes,width=285px,height=580px,scrollbars=yes");
}

function HandlePopupException(message)
{
  try
  {
    if (trimString(message.toLower()) == "access is denied.")
    {	      
      //alert("You browser is currently running popup blocking software.\n" + 
        //    "It is highly recommended that you allow www.tvg.com to use\n" + 
          //  "popups so that you may enjoy every feature TVG has to offer.");
    }
    else
    {	
      var caller;		      
      try
      {
        caller = arguments.callee.caller.caller.toString().match(/^function (\w+)/)[1];
      }
      catch(exCaller)
      {      
        caller = "Caller Unknown"; 			
      }
  		
  		var callee;
  		try
  		{
        callee = arguments.callee.caller.toString().match(/^function (\w+)/)[1];
      }
      catch(exCallee)
      {      
        callee = "Callee Unknown"; 									
      }
  		
      if (typeof HandleException != "undefined") 		          
        HandleException(caller + " -> " + callee + ": " + message + " wagerWindowLink: " + wagerWindowLink, null, '', '');			    
      else 		    
        throw new Error(message + " (Caught in " + callee + ")");    
    }
  }
  catch(ex){}
}

function setCookie( cookieName, cookieValue, expires, path, domain, secure ) 
{
	try {
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime( today.getTime() );

		/*
		if the expires variable is set, make the correct 
		expires time, the current script below will set 
		it for x number of days, to make it for hours, 
		delete * 24, for minutes, delete * 60 * 24
		*/
		if ( expires )
		{
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );

		document.cookie = cookieName + "=" +escape( cookieValue ) +
			( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
			( ( path ) ? ";path=" + path : "" ) + 
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
	}
	catch (ex) {}
}

function getCookie(cookieName)
{
	var cookieValue = "";
	try {
		if (document.cookie.length>0)
		{
			var c_start = document.cookie.indexOf(cookieName + "=");
			if (c_start != -1)
			{ 
				c_start = c_start + cookieName.length+1; 
				c_end = document.cookie.indexOf(";",c_start);
				if (c_end == -1) 
					c_end = document.cookie.length;
				cookieValue = unescape(document.cookie.substring(c_start,c_end));
			} 
		}
	}
	catch (ex) {}
	return cookieValue;
}

function GetQueryStringParameter(strParamName)
{
    var strQueryString = window.location.search.substring(1);
	var strParamValue = "";
	try {
		if (strQueryString.length>0)
		{
			var c_start = strQueryString.indexOf(strParamName + "=");
			if (c_start != -1)
			{ 
				c_start = c_start + strParamName.length+1; 
				c_end = strQueryString.indexOf("&",c_start);
				if (c_end == -1) 
					c_end = strQueryString.length;
				strParamValue = unescape(strQueryString.substring(c_start,c_end));
			} 
		}
	}
	catch (ex) {}
	return strParamValue;
}

/*
function getCookie(cookieName){
	var cookieValue = "";
	try{
		var cookieLabelLen = cookieName.length +1;
		var cookieString = top.document.cookie;
		var cookieLength = cookieString.length;
		var c1Index = 0;
		var cEnd;
		while(c1Index<cookieLength){
			var c2Index = c1Index + cookieLabelLen;
			if (cookieString.substring(c1Index,c2Index)==cookieName + '='){
				cEnd = cookieString.indexOf(";",c2Index);
				if(cEnd==-1){
					cEnd = cookieString.length;
				}
				cookieValue = unescape(cookieString.substring(c2Index,cEnd));
				break;
			}
			c1Index++;
		}
    }
	catch (ex) {}
	return cookieValue;
}
*/

// Pass in a integer and return a twos complement string representing 32 bits
// Convert integer to string to avoid losing the leading zeroes that would happen using the "~" complement operator.
function TwosComplement(integer)
{
	var newInteger = integer;
	var newHexStr;
	try {
		if (!isFinite(newInteger)) {
			newHexStr = (NaN).toString();
		}
		else if (Math.abs(newInteger) > parseInt("0xFFFFFFFF",16)) {
			newHexStr = (NaN).toString();
		}
		else {
			if (newInteger < 0) {
				// create a binary string of the absolute value of the integer
				bin = (Math.abs(newInteger)).toString(2);
				// prepend the number of binary zero digits needed to make the whole string 32 bits
				bin = "00000000000000000000000000000000".substring(0,32-bin.length) + bin;
				// The next three steps are used to toggle all the bit values.
				// Convert all ones to a temporary character to avoid losing them in the next step
				bin = bin.replace(/1/g, "X");
				// Convert all zeroes to ones
				bin = bin.replace(/0/g, "1");
				// Convert all temporary characters to zeroes
				bin = bin.replace(/X/g, "0");
				// Now convert back to an integer from a binary string.
				newInteger = parseInt(bin,2);
				// Add one to go from one's complement to two's complement
				newInteger += 1;
			}
			// Convert to a hexidecimal string to return for display
			newHexStr = newInteger.toString(16).toUpperCase();
		}
	}
	catch (ex) {
		//alert(ex.message)
		newHexStr = (NaN).toString();
	}
	return newHexStr;
}

function newWindow(theURL,winName,features)
{ 
    window.open(theURL,winName,features);
}
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';
  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        //args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
function AC_AX_RunContent(){
  var ret = AC_AX_GetArgs(arguments);
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_AX_GetArgs(args){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "pluginspage":
      case "type":
      case "src":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "data":
      case "codebase":
      case "classid":
      case "id":
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  return ret;
}
function HideButton(clickedButton)
{
    try
    {
        clickedButton.style.visibility = 'hidden';
    }catch(e){}
}

function DisplayProgressBar(divProgressBarContainer, divStaticProgressBar, divGrowingProgressBar, divToHide, Timer, TimeDurationSeconds)
{            
    // Show the container
    divProgressBarContainer.style.display = "block";

    // Hide the div    
    divToHide.style.display = "none";
    
    // Display the progress bars    
    divStaticProgressBar.style.display = "block";
    divGrowingProgressBar.style.display = "block";
    divGrowingProgressBar.style.width = "0px";

    // Set the timer to update the progress bar
    Timer = window.setInterval("UpdateProgressBar(" + "divStaticProgressBar" + ", " + 
                                                      "divGrowingProgressBar" + ", " + 
                                                      TimeDurationSeconds + ", " + 
                                                      Timer + ");", 1000); 
    return Timer;    
}

function UpdateProgressBar(divStaticProgressBar, divGrowingProgressBar, iProgressBarDuration, Timer)
{          
    try
    {   
        // This is the base number
        var iRadix = 10;
        
        // Get the current width of the static div        
        var iStaticWidth = divStaticProgressBar.clientWidth;        
                           
        // Get the current width of the growing div        
        var iGrowingWidth = divGrowingProgressBar.clientWidth;                
        
        // As long as the static div isn't completely covered        
        if (iGrowingWidth < iStaticWidth)
        {
            // Increase the width of the growing div
            var iWidthIncrement = parseInt(iStaticWidth / iProgressBarDuration, iRadix);
            if ((iGrowingWidth + iWidthIncrement) > iStaticWidth)
            {
                divGrowingProgressBar.style.width = iStaticWidth.toString() + "px";
            }
            else
            {                
                iGrowingWidth = iGrowingWidth + iWidthIncrement;
                divGrowingProgressBar.style.width = iGrowingWidth.toString() + "px"; 
            }            
        }                
        else
        {
            window.clearInterval(Timer);
        }
    }
    catch(e)
    {
        alert(e.message);
    }            
} 

function AppendTextElementToRoot(doc, sName, sContent)
{
    var xElement = doc.createElement(sName);
    var xContent = doc.createTextNode(sContent);
    xElement.appendChild(xContent);
    doc.documentElement.appendChild(xElement);        
}

function GetNewXMLDocument()
{  
  var doc = null;

  // Code for IE
  if (window.ActiveXObject)
  {
    doc = new ActiveXObject("Microsoft.XMLDOM");
    doc.async = false;
    return doc;
  }
  // Code for Mozilla, Firefox and Safari
  else if(document.implementation &&
          document.implementation.createDocument)
  {
    doc = document.implementation.createDocument("", "", null);
    return doc;
  }
  else
  {
    alert("This browser is unable to handle the creation of XML documents");
  }
}

function printit(){  
    if (window.print) {
	    window.print() ;  
    } else {
	    var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
	    document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
	    WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box    WebBrowser1.outerHTML = "";  
    }
}

// These methods are needed by the calendar control and were included in menu.js
// which is not used any more

/*	Hide Select Function for Dropdown
---------------------------------------------*/

var hideID = ["recordsPerPage","ddlTrack","ddlRace","ddlAnnouncer","hideNavigation"];
	//"ctl00_ContentPlaceHolder1_SuffixDropDownList_NameSuffixDropList",

function hideSelect(){
	
		var i=0;
		for (i=0; i<hideID.length; i++) {
			if (document.getElementById(hideID[i]) != null) {
					document.getElementById(hideID[i]).style.visibility="hidden";} 
		}
}

function unhideSelect(){
	
		var i=0;
		for (i=0; i<hideID.length; i++) {
			if (document.getElementById(hideID[i]) != null) {
					document.getElementById(hideID[i]).style.visibility="visible";} 
		}
}

function AppendCellToRow(trRow, sValue, sClass, sColSpan)
{
    var tdCell = document.createElement("td");
    tdCell.innerHTML = sValue;
    tdCell.className = sClass;
    tdCell.colSpan = sColSpan;
    trRow.appendChild(tdCell);
}

function DisplayValidator(validator, message)
{
  validator.style.display = "inline";
  validator.innerHTML = message;
}

function SetLogoUrl(sProgramPagePath, lnkLogoClientID)
{   
    try
    {
        var lnkLogo = document.getElementById(lnkLogoClientID);
        var sCookie = getCookie("UID");    
        var sUrl = "http://" + window.location.host + "/";
        if ((sCookie != null) &&
            (sCookie != "") &&
            (sCookie != "logouttvg"))
        {    
            sUrl += sProgramPagePath;
        }
    
        lnkLogo.href = sUrl;
    }
    catch(ex)
    {
    }     
}

function GetToteFormattedBIString(arrBIs, oWagerType)
{
    var sFormattedList = "";
    var sCurrentLeg = "";

    try
    {        
        if (arrBIs != null && arrBIs.length > 0)
        {            
            sCurrentLeg = arrBIs[0].join();            
            if (sCurrentLeg.length > 0)
            {
                if (oWagerType.boxed)
                {
                    sFormattedList = "BX," + sCurrentLeg;
                }
                else
                {                    
                    sFormattedList = sCurrentLeg;                    
                    for (var iIndex = 1; iIndex < arrBIs.length; iIndex++)
                    {                        
                        sCurrentLeg = arrBIs[iIndex].join();
                        if (sCurrentLeg.length > 0)
                        {
                            sFormattedList += ",WT," + sCurrentLeg;
                        }
                        else
                        {
                            sFormattedList = "";
                            break;
                        }
                    }                    
                }
            }
        }        
    }
    catch (ex)
    {
		var caller = "Caller Unknown"; try {caller = arguments.callee.caller.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		var callee = "Unknown"; try {callee = arguments.callee.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		HandleException(caller + " -> " + callee + ": " + ex.message, null, '', '');
	}
	
	return sFormattedList;
}

function GetQueryStringValue(sParamName)
{
    var sParamValue = "";

    try
    {
        var sQueryString = window.location.search.substring(1);
        var arrParameters = sQueryString.split("&");
        for (var iPrmIndex = 0; iPrmIndex < arrParameters.length; iPrmIndex++)
        {
            var arrCurrentParameter = arrParameters[iPrmIndex].split("=");
            if (arrCurrentParameter[0] == sParamName)
            {
                sParamValue = arrCurrentParameter[1];
            }
        }
    }
    catch (ex)
    {
		var caller = "Caller Unknown"; try {caller = arguments.callee.caller.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		var callee = "Unknown"; try {callee = arguments.callee.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		HandleException(caller + " -> " + callee + ": " + ex.message, null, '', '');
	}
	
	return sParamValue;
}

function DisableContainerControls(oControl)
{
    try
    {
        var sTagName = oControl.tagName;
        if (sTagName != null)
        {
            sTagName = sTagName.toLowerCase();
            if ((sTagName != "select") &&
                (sTagName != "input") &&   
                (oControl.childNodes != null) && 
                (oControl.childNodes.length > 0))
            {
                var arrChildren = oControl.childNodes;
                for (var iControlIndex = 0; iControlIndex < arrChildren.length; iControlIndex++)
                {
                    var currentCtrl = arrChildren[iControlIndex];
                    DisableContainerControls(currentCtrl);
                }
            }
            else
            {                
                switch (sTagName)
                {
                    case "input":
                        oControl.disabled = true;
                        break;
                    case "select":
                        oControl.disabled = true;
                        break;                    
                }
            }   
        }
    }
    catch (ex)
    {
		var caller = "Caller Unknown"; try {caller = arguments.callee.caller.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		var callee = "Unknown"; try {callee = arguments.callee.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		HandleException(caller + " -> " + callee + ": " + ex.message, null, '', '');
	}
}

// Returns string to display to customer if ticket not valid
function ValidateBetTicket(oTrack, oRace, oWagerType, oAmount, BIs)
{
    var sError = "";
    try
    {
        if (!(oTrack instanceof Track)) 
        {
			sError = "Please select a track.";
		} 
		else if (!(oRace instanceof Race))
		{
		    sError = "Please select a race.";
		}
		else if (!(oAmount instanceof Amount))
		{
		    sError = "Please select an amount.";
		}
		else if (!(oWagerType instanceof WagerType)) 
		{
		    sError = "Please select a wager type.";
		}		
			
		if (sError == '') 
		{
			var BiList = "";
			if (BIs != null && BIs.length>0)
			{
				BiList = BIs[0].join();
				if (BiList.length > 0) 
				{
					if (oWagerType.boxed) 
						BiList = "BX," + BiList
					else
					{
						// for each subsequent column/step ...
						for(var sIndex=1; sIndex<BIs.length; sIndex++) {
							var stepBIs = BIs[sIndex].join();
							if (stepBIs.length > 0)
								BiList += ",WT," + stepBIs;
							else {
								BiList = "";
								break;
							}
						}
					}
				}
			}
			if (BiList.length == 0) 
			{
				sError = GetErrorMsg(oWagerType.GetAbbr(), oWagerType.GetName());
			} 
			else
			{
				var oBetTotal = CalculateBetTotal(oAmount, oWagerType, BIs);
				sError = oBetTotal.ErrorResultsStr;
			}
		}
    }
    catch (ex)
    {
		var caller = "Caller Unknown"; try {caller = arguments.callee.caller.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		var callee = "Unknown"; try {callee = arguments.callee.toString().match(/^function (\w+)/)[1];} catch (ex) {}
		HandleException(caller + " -> " + callee + ": " + ex.message, null, '', '');
	}
	
	return sError;
}

function GetFormattedBIString(arrBIs, oWagerType)
{
    var sFormattedList = "";
    var sCurrentLeg = "";

    try
    {
        if (arrBIs != null && arrBIs.length > 0)
        {
            sCurrentLeg = arrBIs[0].join();
            if (sCurrentLeg.length > 0)
            {
                if (oWagerType.boxed)
                {
                    sFormattedList = "BX," + sCurrentLeg;
                }
                else
                {
                    sFormattedList = sCurrentLeg;
                    for (var iIndex = 1; iIndex < arrBIs.length; iIndex++)
                    {
                        sCurrentLeg = arrBIs[iIndex].join();
                        if (sCurrentLeg.length > 0)
                        {
                            sFormattedList += ",WT," + sCurrentLeg;
                        }
                        else
                        {
                            sFormattedList = "";
                            break;
                        }
                    }
                }
            }
        }
    }
    catch (ex)
    {
        var caller = "Caller Unknown"; try { caller = arguments.callee.caller.toString().match(/^function (\w+)/)[1]; } catch (ex) { }
        var callee = "Unknown"; try { callee = arguments.callee.toString().match(/^function (\w+)/)[1]; } catch (ex) { }
        HandleException(caller + " -> " + callee + ": " + ex.message, null, '', '');
    }

    return sFormattedList;
}