﻿function replaceString(StringToCheck, StringToSearchFor, StringToReplaceWith) {
    var returnValue = StringToCheck;

    if (StringToSearchFor != StringToReplaceWith) {
        while (returnValue.indexOf(StringToSearchFor) != -1) {
            returnValue = returnValue.replace(StringToSearchFor, StringToReplaceWith);
        }
    }

    return returnValue;
}
function OpenForum(URL) {
    var n = SiteName.replace('.', '_');
    n = n.replace(' ', '_');
    var x = window.open(URL, n);
    
}
function OpenConsole(URL) {
    window.open(URL, 'RaceConsole', 'resizable=no,scrollbars=no,menubar=no,location=no,toolbar=no,status=yes,top=40,left=40,width=1000,height=680');
}
function ShowFlash(FlashFile,FlashSize,ID,FlashVars) 
{
	if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) {
		document.write('<'+'script language=\"VBScript\"\>\n');
		document.write('On Error Resume Next\n');
		document.write('Sub '+ID+'_FSCommand(ByVal command, ByVal args)\n');
		document.write('	Call '+ID+'_DoFSCommand(command, args)\n');
		document.write('End Sub\n');
		document.write('</script\>\n');
	}
    document.write ('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase='+document.location.protocol+'"//fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" id="'+ID+'" '+FlashSize+' align="middle" style="position:relative; left:0; top:0">');
    document.write ('<param name="allowScriptAccess" value="sameDomain" />');
    document.write ('<param name="movie" value="'+FlashFile+'" />');
    document.write ('<param name="quality" value="high" />');
    if (FlashVars) document.write ('<param name="flashvars" value="'+ FlashVars +'" />');
    document.write ('<param name="wmode" value="transparent" />');
    document.write ('<param name="bgcolor" value="#ffffff" />');
    document.write ('<embed src="'+FlashFile+'" quality="high" '+FlashSize+' wmode="transparent" swLiveConnect=true id="'+ID+'" name="'+ID+'"');
    if (FlashVars) document.write (' flashvars="'+ FlashVars +'"');
    document.write (' align="middle" allowScriptAccess="samedomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
    document.write ('</object>');
    isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
}

function getDropdownValue(aDropdown)
{
    return (aDropdown.options[aDropdown.selectedIndex].value);
}

function getCheckboxValue(aCheckbox)
{
    return (aCheckbox.checked) ? aCheckbox.value : "";
}

function SwapNavImage(aImage,URL)
{
    var CurrentLoc = aImage.src;
    var i = CurrentLoc.lastIndexOf('/');
    aImage.src = CurrentLoc.substr(0,i +1 ) + URL;
}

// Community Icon
function changeCommunityIcon(num) {
    var path = document.getElementById('communitynav').src.slice(0, document.getElementById('communitynav').src.lastIndexOf('/') + 1);
    
    if((num > 0) && (document.getElementById('communitynav').src==path+"Community_icon-o.png")) {
        document.getElementById('communitynav').src=path+"Community_icon_mail-o.png";
        document.getElementById('unreadMessages').innerHTML=num;
    } else if((num <= 0) && (document.getElementById('communitynav').src==path+"Community_icon-o.png")) {
        document.getElementById('communitynav').src=path+"Community_icon-o.png";
        document.getElementById('unreadMessages').innerHTML='';
    } else if((num > 0) && (document.getElementById('communitynav').src==path+"Community_icon.png")) {        
        document.getElementById('communitynav').src=path+"Community_icon_mail.png";
        document.getElementById('unreadMessages').innerHTML=num;
    } else {
        document.getElementById('communitynav').src=path+"Community_icon.png";
        document.getElementById('unreadMessages').innerHTML='';
    }
}

function SwapNavImageCommunity() {
    var path=document.getElementById('communitynav').src.slice(0,document.getElementById('communitynav').src.lastIndexOf('/')+1);
    var fileName=document.getElementById('communitynav').src.slice(document.getElementById('communitynav').src.lastIndexOf('/')+1);
    if(fileName == 'Community_icon.png') {
        document.getElementById('communitynav').src=path+"Community_icon-o.png";
    } else if (fileName == 'Community_icon-o.png') {
        document.getElementById('communitynav').src=path+"Community_icon.png";
    } else if (fileName == 'Community_icon_mail-o.png') {
        document.getElementById('communitynav').src=path+"Community_icon_mail.png";
    } else if (fileName == 'Community_icon_mail.png') {
        document.getElementById('communitynav').src=path+"Community_icon_mail-o.png";
    }
}

function ButtonMouseOver(but,style)
{
	if (but.className=="ButtonOff") return;
	if (style!=null){
		but.className = style;
	}else {
		but.className = 'ButtonOver';
	}
}
function ButtonMouseOut(but,style)
{
	if (but.className=="ButtonOff") return;
	if (style!=null){
		but.className = style;
	}else {
		but.className = 'Button';
	}
}
function ButtonMouseDown(but,style)
{
	if (but.className=="ButtonOff") return;
	if (style!=null){
		but.className = style;
	}else {
		but.className = 'ButtonDown';
	}
}
function ButtonMouseUp(but,style)
{
	if (but.className=="ButtonOff") return;
	if (style!=null){
		but.className = style;
	}else {
		but.className = 'ButtonOver';
	}
}
function ButtonDisable(but) {
    ButtonMouseOut(but, "SlvrButtonDisabled");
    but.className = "SlvrButtonDisabled";
    but.childNodes[0].onclick = returnFalse;
}
function returnFalse() {
    return false;
}
function GotoPage(Page)
{
	document.forms[0].Command.value="Goto";
	document.forms[0].Data.value=Page;
	document.forms[0].submit();
}
function calendarButtonStyle(oObject,classNameText)
{
    oObject.className = classNameText;
}
//from SalesRing.asp
function ValidateDefaultHorseName()
{
	if (document.BuyMultipleHorses.DefaultHorseName.value.replace(" ","").length==0){
		alert("Please specify a default horse name. This will be used as the base name given to each horse, but may be changed in the next step.");
		return false;
	}
	return true;
}

//from NSA
function submitForm(submit)
{
    if (formValid) {
    //popup validation check: clear the popupcheck on submit so that popup does not occur.
      if (document.forms[0] != null) {
          if (document.forms[0].popupcheck != null) {
              document.forms[0].popupcheck.value = '';
          }
      }
      if(submit==null) document.aspnetForm.submit();
      return true;
  }
}
function validateFormField() {
    var isValid = validateForm();

    if (isValid != formValid) {
        formValid = isValid;
        nb = document.getElementById('NextButton');
        if (nb != null) nb.className = (formValid) ? 'NextButton' : 'NextButtonDis';
    }
}
function inputKeyUp(nextButton) 
{
  var isValid = validateForm();

  if (isValid != formValid) 
  {
    formValid = isValid;
    nb = document.getElementById('NextButton');
    if (nb != null) nb.className = (formValid) ? 'NextButton' : 'NextButtonDis';
  }

  if (event.keyCode == 13)
  {
    if (nextButton) 
    {
      document.forms[0][nextButton].focus();
    } 
    else 
    {
      submitForm();
    }
  }
}

function ShowRaceSnapshots(RaceID) {
	var x = window.open(SiteURL+"/Betting/ViewRaceSnapshots.aspx?RacID="+RaceID,'ShowRaceSnapshots','resizable=no,scrollbars=no,menubar=no,location=no,toolbar=no,status=yes,top=40,left=40,width=420,height=350');
}
function GetCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}
function IsWebstartInstalled()
{
	var WebstartInstalled=false;
	var isIE = "false";
	if (navigator.mimeTypes && navigator.mimeTypes.length)
	{
		x = navigator.mimeTypes['application/x-java-jnlp-file'];
		if (x) {
			javawsInstalled = 1;
			javaws12Installed=1;
		}
	} else { 
		isIE = "true";
	}
	var javawsInstalled = 0;
	var javaws12Installed = 0;

	if (navigator.mimeTypes && navigator.mimeTypes.length)
	{
		x = navigator.mimeTypes['application/x-java-jnlp-file']; 
		if (x) WebstartInstalled=true;
	} else { 
		isIE = "true"; 
	} 
	if (isIE == "true"){
		try{
			var obj=new ActiveXObject("JavaWebStart.isInstalled");
			WebstartInstalled=true;
		}catch(e){
		}
		try{
			var obj=new ActiveXObject("JavaWebStart.isInstalled.2");
			WebstartInstalled=true;
		}catch(e){
		}
	}
	return WebstartInstalled;
}
function ShowHorseTrainHist(HorseID, IsAuction) {
    open('../Owner/TrainingHistory.aspx?HorseID=' + HorseID + ((IsAuction != null) ? IsAuction : ''), 'PopUpWindow', 'width=800,height=650,scrollbars=yes,resizable=yes').focus();
}
function ShowHorseForm(HorseID) 
{
    open('../Owner/HorseForm.aspx?HorseID=' + HorseID ,'PopUpWindow','width=720,height=800,scrollbars=yes,resizable=yes').focus();
}

function OpenRaceViewerDownloadPopup() {
    var x = window.open("../RaceViewer/RaceViewer.aspx", 'DownloadRaceViewer', 'resizable=no,scrollbars=no,menubar=no,location=no,toolbar=no,status=yes,top=40,left=40,width=800,height=600');
}
function ShowHorseTransfer(HorseID) {
    open('../Betting/TransferHistory.aspx?HorseID=' + HorseID, 'PopUpWindow', 'width=800,height=650,scrollbars=yes,resizable=yes').focus();
}
function ShowHorseStats(HorseID) {
    open('../Owner/HorseStats.aspx?HorseID=' + HorseID, 'PopUpWindow', 'width=720,height=650,scrollbars=yes,resizable=yes').focus();
}

function CommLinkClick(aEvent) {
    if (window.event) {
        // IE
        if ((window.event.srcElement.tagName == 'A' || window.event.srcElement.parentNode.tagName == 'A') && window.event.srcElement.href) {
            if (window.event.srcElement.parentNode.tagName == 'A') {
                Forum_OpenParent(window.event.srcElement.parentNode.href);
            }
            else {
                Forum_OpenParent(window.event.srcElement.href);
            }
        }

    }
    else {
        if (aEvent.target) {
            // FF
            s = new String(aEvent.target);
            if (s.indexOf('object') == -1) {
                Forum_OpenParent(aEvent.target);
            }
            else {
                if (aEvent.target.parentNode.tagName == 'A') {
                    Forum_OpenParent(aEvent.target.parentNode);
                }
            }
        }
    }
    return false;
}

function Forum_OpenParent(URL) {
    if (window.opener == null) {
        NewWin = window.open(URL, 'Parent');
        NewWin.focus();
    }
    else {
        try {
            window.opener.location = URL;
            window.opener.focus();
        }
        catch (err) {
            window.open(URL, 'Parent').focus();
        }
    }
}
function OpenBetting() {
    window.open(BettingURL, 'Betting');
}
function OpenWhyJoinPopup() {
    var x = window.open(SiteURL + '/Templates/ViewTemplate.aspx?Template=WhyJoin', 'WhyJoin', 'resizable=no,scrollbars=no,menubar=no,location=no,toolbar=no,status=no,width=560,height=500');
}
function OpenComparisonTablePopup() {
    var x = window.open(SiteURL + "/Templates/ViewTemplate.aspx?Template=ComparisonTable", 'ComparisonTable', 'resizable=no,scrollbars=no,menubar=no,location=no,toolbar=no,status=yes,top=40,left=40,width=630,height=500');
}
function OpenWindow(PageName) {
    window.open(PageName, 'tour', 'width=930,height=400,scrollbars=no,noresize=true');
}
function OpenCredits() {
    var x = window.open("../RaceViewer/Credits.asp", 'DownloadRaceViewer', 'resizable=no,scrollbars=no,menubar=no,location=no,toolbar=no,status=yes,top=40,left=40,width=450,height=325');
}
function OpenRAFTerms() {
    var x = window.open("/Templates/ViewTemplate.aspx?Template=RAFTerms", 'RAFTerms', 'resizable=no,scrollbars=no,menubar=no,location=no,toolbar=no,status=yes,top=40,left=40,width=560,height=500');
}
function TwoYODiagramPopup() {
    window.open('../Templates/ImageView.aspx?width=750&height=550&iscommon=false&isglobal=false&image=2YODiagram.gif', 'tour', 'width=750,height=550,scrollbars=no,noresize=true');
}
function ThreeYODiagramPopup() {
    window.open('../Templates/ImageView.aspx?width=750&height=550&iscommon=false&isglobal=false&image=3YODiagram.gif', 'tour', 'width=750,height=550,scrollbars=no,noresize=true');
}
function FourToSevenYODiagramPopup() {
    window.open('../Templates/ImageView.aspx?width=750&height=550&iscommon=false&isglobal=false&image=4to7YODiagram.gif', 'tour', 'width=750,height=550,scrollbars=no,noresize=true');
}

function viewRaceByID(raceID) {
    if (window.viewRace) {
        viewRace();
    }
    else {
        window.location.href = '../Betting/RaceDetails.aspx?RacID=' + raceID;
    }
}


// Object for handling Ajax Calls
function ajaxObject(url, callbackFunction) {
    var that = this;
    this.updating = false;
    this.abort = function() {
        if (that.updating) {
            that.updating = false;
            that.AJAX.abort();
            that.AJAX = null;
        }
    }
    this.update = function(passData, postMethod) {
        if (that.updating) { return false; }
        that.AJAX = null;
        if (window.XMLHttpRequest) {
            that.AJAX = new XMLHttpRequest();
        } else {
            that.AJAX = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (that.AJAX == null) {
            return false;
        } else {
            that.AJAX.onreadystatechange = function() {
                if (that.AJAX.readyState == 4) {
                    that.updating = false;
                    that.callback(that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML);
                    that.AJAX = null;
                }
            }
            that.updating = new Date();
            if (/post/i.test(postMethod)) {
                var uri = urlCall + '?' + that.updating.getTime();
                that.AJAX.open("POST", uri, true);
                that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                that.AJAX.setRequestHeader("Content-Length", passData.length);
                that.AJAX.send(passData);
            } else {
                var uri = urlCall + '?' + passData + '&timestamp=' + (that.updating.getTime());
                that.AJAX.open("GET", uri, true);
                that.AJAX.send(null);
            }
            return true;
        }
    }
    var urlCall = url;
    this.callback = callbackFunction || function() { };
}

function SetUnreadMessages(turfmasterID) {
    if (turfmasterID != "") {
        var num;
        if (GetCookie('UnreadMessages') == null) {
            //JR added this condition cannot call http from https
            if (location.href.indexOf('https://') == -1) {
                var myRequest = new ajaxObject(SiteURL + "/Owner/UnreadMessages.aspx");
                myRequest.update('command=getUnreadMessages&tmid=' + turfmasterID);
                myRequest.callback = function(responseText, responseStatus, responseXML) {
                    var ExpireDate = new Date();
                    ExpireDate.setMinutes(ExpireDate.getMinutes() + 1);
                    var a = SiteURL.split('.');
                    document.cookie = "UnreadMessages=" + responseXML.getElementsByTagName('mail')[0].getElementsByTagName('unreadMessages')[0].firstChild.nodeValue + "; expires=" + ExpireDate.toGMTString() + "; path=/; domain=" + a[a.length - 2] + "." + a[a.length - 1] + ";";
                    num = parseInt(responseXML.getElementsByTagName('mail')[0].getElementsByTagName('unreadMessages')[0].firstChild.nodeValue);
                    changeCommunityIcon(num);
                }
            }
        } else {
            var num = parseInt(GetCookie('UnreadMessages'));
            changeCommunityIcon(num);
        }
    }
}

function chkAll(allChk, objInput, name) {
    var toCheck = allChk.checked;
    if (document.getElementById(objInput)) {
        document.getElementById(objInput).value = (toCheck) ? generateAllValue(name) : '0';
    }
    for (var x = 0; x < document.forms[0].length; x++) {
        if (document.forms[0][x].getAttribute('clientName') == name) {
            document.forms[0][x].checked = toCheck;
        }
    }
}
function generateAllValue(name) {
    var finalValue = 0;
    for (var x = 0; x < document.forms[0].length; x++) {
        if (document.forms[0][x].getAttribute('clientName') == name) finalValue = finalValue + parseInt(document.forms[0][x].value);
    }
    return finalValue;
}

function generateValue(chk, objInput) {
    objInput = document.getElementById(objInput);
    if (objInput != null) {
        var itemValue = objInput.value;
        objInput.value = (chk.checked) ? parseInt(itemValue) | parseInt(chk.value) : parseInt(itemValue) - parseInt(chk.value);
    }
}

function checkBoxFromText(clientId, inputName) {
    for (var x = 0; x < document.forms[0].length; x++) {
        if (document.forms[0][x].getAttribute('clientId') == clientId) {
            document.forms[0][x].checked = document.forms[0][x].checked ? false : true;
            generateValue(document.forms[0][x], document.getElementById(inputName).value);
        } 
    }
}

function checkSelectedCountry(ddl, divToHide, divToShow) {
    var selectedOption = ddl.options[ddl.selectedIndex].value;
    document.getElementById(divToHide).style.display = (selectedOption.toUpperCase() == 'UNITED STATES') ? 'none' : '';
    document.getElementById(divToShow).style.display = (selectedOption.toUpperCase() == 'UNITED STATES') ? '' : 'none';
}