var sSTD_WIN_OPEN_SETTINGS = "toolbar=no,menubar=no,width=650px,height=380px,left=100px,top=100px,scrollbars=yes,resizable=yes";
var sFOOTO_WIN_OPEN_SETTINGS = "toolbar=no,menubar=no,width=640px,height=436px,left=100px,top=100px,scrollbars=yes,resizable=yes";
var sBETCOST_WIN_OPEN_SETTINGS = "toolbar=no,menubar=no,width=460px,height=200px,left=100px,top=100px,scrollbars=no,resizable=yes";
var sTOTE_WIN_OPEN_SETTINGS = "toolbar=no,menubar=no,width=640px,height=436px,left=100px,top=100px,scrollbars=yes,resizable=yes";
var sCC_WIN_OPEN_SETTINGS = "toolbar=no,menubar=no,width=540px,height=300px,left=100px,top=100px,scrollbars=yes,resizable=yes";
var sFOB_TRANS_WIN_OPEN_SETTINGS = "toolbar=no,menubar=no,width=1035px,height=436px,left=100px,top=100px,scrollbars=yes,resizable=yes";
var sVBET_WIN_OPEN_SETTINGS = "toolbar=no,menubar=no,width=1020px,height=436px,left=100px,top=100px,scrollbars=yes,resizable=yes";
var sVBET_LIVE_STREAM_WIN_OPEN_SETTINGS = "toolbar=no,menubar=no,width=700px,height=700px,left=100px,top=100px,scrollbars=yes,resizable=no";

// login window setrtings - std size, with resizable=no
var sLOGIN_WIN_OPEN_SETTINGS = "toolbar=no,menubar=no,width=650px,height=380px,left=100px,top=100px,scrollbars=yes,resizable=no"; 
//----------------------------------------------------------------------------
function openLoginWin(sURL, sName) {
  openWin(sURL, sName, sLOGIN_WIN_OPEN_SETTINGS);
}
//----------------------------------------------------------------------------
function openFootoWin(sURL, sName) {
  openWin(sURL, sName,sFOOTO_WIN_OPEN_SETTINGS);
}
//----------------------------------------------------------------------------
function openToteWin(sURL, sName) {
  openWin(sURL, sName,sTOTE_WIN_OPEN_SETTINGS);
}
//----------------------------------------------------------------------------
function openBetCostWin(sURL, sName) {
  openWin(sURL, sName,sBETCOST_WIN_OPEN_SETTINGS);
}
//----------------------------------------------------------------------------
function openCCWin(sURL, sName) {
    openWin(sURL, sName, sCC_WIN_OPEN_SETTINGS);
}
//----------------------------------------------------------------------------
function openFOBTransDetailsWin(sURL, sName) {
    openWin(sURL, sName, sFOB_TRANS_WIN_OPEN_SETTINGS);
}
//----------------------------------------------------------------------------
function openVBetWin(sURL, sName) {
    openWin(sURL, sName, sVBET_WIN_OPEN_SETTINGS);
}
//----------------------------------------------------------------------------
function openVBetLiveVisionWin(sURL, sName) {
    openWin(sURL, sName, sVBET_LIVE_STREAM_WIN_OPEN_SETTINGS);
}
//----------------------------------------------------------------------------
function openWin(sURL, sName, sWinSettings) {
  var sOpenSettings = "";
  if ((sWinSettings == undefined) || (sWinSettings == ""))
  { sOpenSettings = sSTD_WIN_OPEN_SETTINGS;  }
  else
  { sOpenSettings = sWinSettings; }
  
  var oWin = window.open( getOpenWindowUrl(sURL), sName, sOpenSettings);
  if (oWin) oWin.focus();
  return oWin;
}
//----------------------------------------------------------------------------
function openWinFromAnchor(sURL, sName) {
  var oWin = openWin(sURL, sName);
}
//----------------------------------------------------------------------------  
function openStdWin(sURL, sName) {
  var oWin = window.open( getOpenWindowUrl(sURL), sName);
  if (oWin) oWin.focus();
  return oWin;
}
//----------------------------------------------------------------------------
function getOpenWindowUrl(sURL) {

  var sResult;
  sResult = sURL;
  if( sResult.indexOf('?') >= 0 ) {
    sResult = sResult + '&';
  }
  else {
    sResult = sResult + '?';
  }
  
  sResult = sResult + "IsInWindow=Y";

  if( window.location.protocol != "https:" ) {
    sResult = sResult + "&ParentIsNotSecure=Y";
  }
  
  return sResult;
}
//----------------------------------------------------------------------------
function setFocus(sID) {
  if (document.getElementById(sID)) document.getElementById(sID).focus();
}
//----------------------------------------------------------------------------
function closeDlg() { window.top.close(); }
//----------------------------------------------------------------------------
function jumpToUrl(sUrl) {
  document.location = sUrl;
}
//----------------------------------------------------------------------------
function doPostBack(eventTarget, eventArgument, aControl)
{
  var input;
  var itemsAdded;

  itemsAdded = false;

  try {
    if ( window.__doPostBack )
    {
      __doPostBack(eventTarget,eventArgument);
    }
    else
    {
      if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1)
      {
			  theform = document.forms(0);
		  }
		  else
		  {
			  theform = document.forms[0];
		  }
      
      input = document.createElement('INPUT');
      input.type = "hidden";
      input.name = "__EVENTTARGET";
      input.id = "__EVENTTARGET";
      input.value = eventTarget.split("$").join(":");
      theform.appendChild(input);

      input = document.createElement('INPUT');
      input.type = "hidden";
      input.name = "__EVENTARGUMENT";
      input.id = "__EVENTARGUMENT";
      input.value = eventArgument;
      theform.appendChild(input);
      
      itemsAdded = true;
      theform.submit();
    }
  }
  catch(err) {
    if( itemsAdded == true ) {
      removeDocumentItemsById("__EVENTTARGET");
      removeDocumentItemsById("__EVENTARGUMENT");
    }
    
    if( window.handlePostError != null ) {
      handlePostError(eventTarget, eventArgument, aControl);
    }
    else {
      alert("An error has occured trying to submit this form");
    }
  }
}

//----------------------------------------------------------------------------
function removeDocumentItemsById(anId) {
  var theForm;
  var itemToRemove;

  if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1)
  {
		theForm = document.forms(0);
	}
	else
	{
		theForm = document.forms[0];
	}

  itemToRemove = document.getElementById(anId);
  
  if( itemToRemove != null ) {
    theForm.removeChild(itemToRemove);
  }
}

//----------------------------------------------------------------------------
var clockId;
var clockDate;
var clockRefresh;
//----------------------------------------------------------------------------
function startClock(aId, aYear, aMonth, aDay, aHour, aMinute, aSecond, aMilliSecond, aRefresh)
{
  clockId = aId;
  clockDate = new Date(aYear, aMonth-1, aDay, aHour, aMinute, aSecond, aMilliSecond);
  clockRefresh = aRefresh;
  setClockText();
  window.setTimeout( "setClockDate()", aRefresh);
}
//----------------------------------------------------------------------------
function showAlert(msg)
{
  alert(msg);
}
//----------------------------------------------------------------------------
function setClockDate()
{
  clockDate.setTime( clockDate.getTime() + clockRefresh );
  setClockText();
  window.setTimeout( "setClockDate()", clockRefresh);
}
//----------------------------------------------------------------------------
function setClockText()
{
  var clock = document.getElementById(clockId);
  clock.innerHTML = formatClockDate(clockDate);
}
//----------------------------------------------------------------------------
function formatClockDate(aDate)
{
  var txt = pad(aDate.getDate(),2,"0",true);
  txt += "/";
  txt += pad(aDate.getMonth()+1,2,"0",true);
  txt += "/";
  txt += aDate.getFullYear();
  txt += "&nbsp;";
  txt += pad(aDate.getHours(),2,"0",true);
  txt += ":";
  txt += pad(aDate.getMinutes(),2,"0",true);
  //txt += ":";
  //txt += pad(aDate.getSeconds(),2,"0",true);
  txt += "&nbsp;(WST)";
  return txt;
}
//----------------------------------------------------------------------------
function pad(str, len, chr, left) {
  var newStr = str + "";
    if (newStr.length < len) {
      for (var i = newStr.length; i < len; i++) {
        if (left) {
          newStr = chr + newStr;
        } else {
        newStr += chr;
      }
    }
  }
  return newStr;
}
//----------------------------------------------------------------------------
// Below is temp function for the DateNavigationController.cs  
// Still waiting on the outcome of the meeting of Back Button issues.
function hopTo(aIdexVal,e)
{
  e.selectedIndex = 0;
  //alert (e.options[e.selectedIndex].value + " Jump To" + aIdexVal);
  location='/RWWA.TabOzbet.Website/UI/RacingUI/RaceMeetings.aspx?fixtureDate=' + aIdexVal;
}
//----------------------------------------------------------------------------
function resetSelect()
{
  var adrop = document.getElementById("raceMeetingListControl_dateNavigationControl_navigationDropDownList");
  adrop.selectedIndex = 0;
}
//----------------------------------------------------------------------------
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);
}

//----------------------------------------------------------------------------
//This is the old checklogin to work on .net 2003
function checkLogin(e)
{
  if( readCookie("OzbetAccountUser") == null ) 
  {
    return false;
  }
  else 
  {
    return true;
  }
}

//----------------------------------------------------------------------------
//This is the old checklogin to work on .net 2003
function OriginalcheckLogin(e)
{
  if( readCookie("TABozbetAUTH") == null ) 
  {
    return false;
  }
  else 
  {
    return true;
  }
}
////----------------------------------------------------------------------------
///This is the new checkLogin to work in .net 2008 with Ajax call
function ccheckLogin(loginForm)
{
  RWWA.TabOzbet.Website.ServiceReference.Security.ScriptWebService.IsClientAuthenticated(OnAjaxSucceeded, OnAjaxFailed,loginForm);
}
function OnAjaxSucceeded(isAuthenticated,userContext)
{
     if (!isAuthenticated)
     {
        openLoginWin(userContext,'login');
        return false;
     }
     else
     {
        DisableControl(this);
        submitBet(this.name,'');
        return false;
     }
}
function OnAjaxFailed(error)
    {
        
        alert( error.get_message() );

    }



//----------------------------------------------------------------------------
function copyValues( aSourceDocument, aDestinationDocument ) {
  var loop;
  var extent;
  var sourceForm;
  var destinationForm;
  var name;

  sourceForm = aSourceDocument.forms[0];
  destinationForm = aDestinationDocument.forms[0];
  extent = aSourceDocument.forms[0].elements.length;
  
  for( loop = 0 ; loop < extent ; loop++ ) {
    if( sourceForm.elements[loop].type == "checkbox" ) {
      name = sourceForm.elements[loop].name;
      if (( name != null ) && ( name != "" ) && ( destinationForm.elements[name] != null ))
      {
        destinationForm.elements[name].checked = sourceForm.elements[loop].checked;
      }
    }
    else if( sourceForm.elements[loop].type == "radio" ) {
      name = sourceForm.elements[loop].name;
      if (( name != null ) && ( name != "" ) && ( destinationForm.elements[name] != null ))
      { 
        destinationForm.elements[loop].checked = sourceForm.elements[loop].checked;
      }
    }
    else {
      name = sourceForm.elements[loop].name;
      if (( name != null ) && ( name != "" ) && ( destinationForm.elements[name] != null ))
      {
        destinationForm.elements[name].value = sourceForm.elements[loop].value;
      }
    }
  }
}
//----------------------------------------------------------------------------
function addInWindowToAction( aForm ) {
  var url;
  url = aForm.action;
  
  if( url.indexOf("IsInWindow=") < 0 ) {
    if( url.indexOf('?') >= 0 ) {
      url = url + '&';
    }
    else {
      url = url + '?';
    }
    
    url = url + "IsInWindow=Y";
    
    aForm.action = url;
  }
}
//----------------------------------------------------------------------------
function createBetIdentifier() {
  return ;
}
//----------------------------------------------------------------------------
function clearDisplayedErrors()
{ 
  clearDiv("errDiv");
  clearDiv("customValidationSummary");
}
//----------------------------------------------------------------------------
function clearDiv(id)
{
  var childNodesCount;
  var div = document.getElementById(id);
  if( div != null )
  {
    childNodesCount = div.childNodes.length; 
    for( var i = 0; i < childNodesCount; i++ )
    {
       div.removeChild( div.childNodes[0] );
    }
  }
}
//----------------------------------------------------------------------------
function displayError( anErrorText )
{
//alert(anErrorText);
  var errDiv = document.getElementById('errDiv');
  
  if( errDiv != null )
  {
    errDiv
    var newdiv = document.createElement('div');
    newdiv.className = 'err-message';

    var oText = document.createTextNode(' ' + anErrorText);
    var newspan = document.createElement('span');

    newspan.className = 'shriek'
    newspan.innerHTML = '!';
    newdiv.appendChild(newspan);
    newdiv.appendChild(oText);  
    
    errDiv.appendChild(newdiv);
  }
}
//----------------------------------------------------------------------------
// Works similar to the .Net "String.Format" method
function StringFormat()
{
  var result;
  var args = arguments;

  if ( args.length == 0 )
  {
    result = "";
  }
  else if ( args.length == 1 )
  {
    result = args[0];
  }
  else if ( args.length > 1 )
  {
    result = args[0];
    for ( var i = 0; i < (args.length - 1); i++ )
    {
      var re = new RegExp("\\$\\{" + i + "\\}", "g");
      result = result.replace(re, args[i + 1] );       
    }
  }
  return result;
}
//----------------------------------------------------------------------------
function ToCurrency(amount)
{
  return "$" + amount;
}
//----------------------------------------------------------------------------
function ToRegExpCurrency(amount)
{
  return "$$" + amount;
}
//----------------------------------------------------------------------------
function RenderFooter(aYear, aMonth, aDay, aHour, aMinute, aSecond, aMilliSecond, aRefresh) {
  var footerDiv;
  var footerHtml;

  footerDiv = document.getElementById("footer");

  if( footerDiv != null ) {
    footerHtml = 
      "<div id='divCopyright'>" +
      "<a href='" + __httpRoot + "/UI/ContentUI/AllContent.aspx?contentCode=Important Notice&contentMenuType=No Menu' id='footerControl_copyrightLink'>Copyright &copy; " + aYear + " Racing and Wagering Western Australia</a>" +
      "</div>";
                    
      footerHtml =  
        "<div class='cleaner'>&nbsp;</div>" +
        "<div id='divFooter'>" +
        "<table class='width-100pc'>" +
        "<tbody>" +
        "<tr>" +
        "<td width='33%'>" +
        "<a href='" + __httpRoot + "/UI/ContentUI/AllContent.aspx?contentCode=Responsible%20Wagering&amp;contentMenuType=No%20Menu' class='link white'>RWWA supports Responsible Wagering</a>" +
        "</td>" +
        "<td width='33%'>" +
        "<div id='footerControl_divClock'>abc</div>" +
        "</td>" +
        "<td style='text-align: right;'>" +
        "<a href='" + __httpRoot + "/UI/ContentUI/AllContent.aspx?contentCode=Important Notice&contentMenuType=No Menu' id='footerControl_copyrightLink' class='link white'>&copy; " + aYear + " RWWA</a>" +
        "<span class='space'>&nbsp;|&nbsp;</span>" +
        "<a href='" + __httpRoot + "/UI/ContentUI/AllContent.aspx?contentCode=_About_Root&amp;contentMenuType=About%20Content%20Menu' id='footerControl_hypLegalLink' class='link white'>About Us</a>" +
        "<span class='space'>&nbsp;|&nbsp;</span>" +
        "<a href='" + __httpRoot + "/UI/ContentUI/AllContent.aspx?contentCode=Important%20Notice&amp;contentMenuType=No%20Menu' id='footerControl_hypLegalLink' class='link white'>Legal</a>" +
        "<span class='space'>&nbsp;|&nbsp;</span>" +
        "<a href='" + __httpRoot + "/UI/ContentUI/AllContent.aspx?contentCode=Contact%20the%20TAB&amp;contentMenuType=No%20Menu' id='footerControl_hypContactUsLink' class='link white'>Contact Us</a>" +
        "<span class='space'>&nbsp;&nbsp;</span>" +
        //"<a href='" + __httpRoot + "/Default.aspx' id='footerControl_hypHomeLink' title='go to TABOzbet home' class='link white'>Home</a>" +
        "</td>" +
        "</tr>" +
        "</tbody>" +
        "</table>" +
        "<div class='set-min-width'>&nbsp;</div>" +
        "</div>";

      footerDiv.innerHTML = footerHtml;                         
      
      startClock("footerControl_divClock", aYear, aMonth, aDay, aHour, aMinute, aSecond, aMilliSecond, aRefresh);
  }
}
//----------------------------------------------------------------------------
function RenderHeaderLinks()
{
  var table;
  var row;
  var cell;
  var index = 0;
  var machineNameSpan;
  var helpLink;
  var findLink;
  var refreshLink;
  var rowHtml;
        
  table = document.getElementById("tblBannerLinks");
    
  if ( table != null )
  {
    row = AppendRowToTable(table);
    machineNameSpan = "<span class='txt-med clr-white'>[" + __machineName + "]</span>";
    helpLink = "<a href='" + __helpUrl + "' id='headerControl_HelpHyperlink' class='help white-bold' title='TABozbet v" + __appVersion + "'></a>";
    findLink = "<a href='" + __findUrl+ "' id='headerControl_FindHyperlink' class='find white-bold' title='find items in this site'></a>";
    
    if( window.PerformRefresh ) {
      refreshLink = "<a id='headerControl_refreshButton' class='refresh white' href='javascript:PerformRefresh()'></a>";
    }
    else {
      refreshLink = "<a id='headerControl_refreshButton' class='refresh white' href='javascript:doPostBack(\"headerControl$refreshButton\",\"\")'></a>";
    }
  
    if( isBrowserSafari() )
    {
      rowHtml = "";
      if ( __showWebServerNameInHeader )
      {
        rowHtml = "<td>" + machineNameSpan + "</td>";
      }

      rowHtml += "<td>" + helpLink + "</td>" +
        "<td>" + findLink + "</td>" +
        "<td>" + refreshLink + "</td>";
        
      row.innerHTML = rowHtml;
    }
    else
    {
      if ( __showWebServerNameInHeader )
      {
        cell = row.insertCell(index++);
        cell.innerHTML = machineNameSpan;
      }
      
      cell = row.insertCell(index++);
      cell.innerHTML = helpLink;
      cell = row.insertCell(index++);
      cell.innerHTML = findLink;
      cell = row.insertCell(index++);
      cell.innerHTML = refreshLink;
    }  
  }
}
//----------------------------------------------------------------------------
function DateNavOnChange(element, calendarUrl, navUrl)
{
  var selectedValue = element.options[element.selectedIndex].value;
  
  element.selectedIndex = 0;
  
  if( selectedValue == 'Calendar' )
  {
    location=calendarUrl;
  }
  else if( selectedValue != null )
  {
    location=navUrl + selectedValue;
  }
}
//----------------------------------------------------------------------------
function jumpToCalendar(e,oldMonthVal,oldYearVal,sURL)
{
  var sMonthList = document.forms[0]["monthDropDownList"];
  var sYearList = document.forms[0]["yearDropDownList"];
  var sMonthVal;
  var sYearVal;

  sMonthVal=(sMonthList.selectedIndex < 9)?'0'+(sMonthList.selectedIndex+1):sMonthList.selectedIndex+1;
  sYearVal = sYearList.value;
  sMonthList.options[oldMonthVal].selected = true;
  sYearList.options[oldYearVal].selected = true;
  window.location = sURL + "&calendarDate=01"+sMonthVal+sYearVal;
}

//----------------------------------------------------------------------------
function submitBet(eventTarget, eventArgument)
{
  makeFormTargetUnique();
  updateUniqueBetId();
  doPostBack(eventTarget, eventArgument);
}

//----------------------------------------------------------------------------
function updateUniqueBetId()
{
  var separatorIndex;
  var thisDate = new Date();
  var uid;
  
  if( uniqueIdentiferElementId != null ) 
  {
    uid = document.getElementById(uniqueIdentiferElementId);
    
    if ( uid != null )
    {
      separatorIndex = uid.value.indexOf("~~~");
      
      if( separatorIndex >= 0 ) 
      {
        uid.value = uid.value.substring(0, separatorIndex);
      }
      
      uid.value = uid.value + "~~~" + thisDate.getTime();
    }
  }
}

//----------------------------------------------------------------------------
function DisableSubmitOnEnterKey() 
{
  document.body.onkeydown = DisableSubmitCheckKeyDown;
}

//----------------------------------------------------------------------------
function DisableSubmitCheckKeyDown(e) 
{
   
  if (navigator.appName == "Netscape")
  {
    if (e.which == 13)
    {
      return false;
    }
  }
  else
  {
	  if (event.keyCode == 13)
    {
      event.returnValue=false;
      event.cancel = true;
    }
  }
}

//----------------------------------------------------------------------------
var _disabledControls =  new Array();

function DisableControl(aControl)
{
  aControl.disabled = true;
  _disabledControls[_disabledControls.length] = aControl;
}

//----------------------------------------------------------------------------
function PerformPageUnload()
{
  for( loop = 0 ; loop < _disabledControls.length ; loop++ ) 
  {
    _disabledControls[loop].disabled = false;
  }
}

//----------------------------------------------------------------------------
function makeFormTargetUnique()
{
  var formAction;
  var itemIndex;
  var itemEndIndex;
  var thisDate = new Date();
    
  formAction = document.forms[0].action;
    
  itemIndex = formAction.indexOf("&zipfix=");
  
  if( itemIndex < 0 ) 
  {
    itemIndex = formAction.indexOf("?zipfix=");
  }
  
  if( itemIndex >= 0 ) 
  {
    itemEndIndex = formAction.indexOf("&",itemIndex + 1);
    
    if( itemEndIndex < 0 ) 
    {
      formAction = formAction.substring( 0, itemIndex );
    }
    else 
    {
      formAction = formAction.substring( 0, itemIndex  + 1 ) + formAction.substring( itemEndIndex + 1, formAction.length );
    }
  }
    
  if( formAction.indexOf("?") >= 0 ) 
  {
    formAction = formAction + "&zipfix=" + thisDate.getTime();
  }
  else 
  {
    formAction = formAction + "?zipfix=" + thisDate.getTime();
  }
    
  document.forms[0].action = formAction;
}
