﻿var base_url = "..";
if (window.name == "") window.name = "hpi";

function OpenHPIPopup(theURL, winName, features, winWidth, winHight, centerOnScreen) {
    if (winWidth > 0 && winHight > 0) {
        if (features) features = features + ",";
        features = features + 'width=' + winWidth + ',height=' + winHight;
        if (centerOnScreen) {
            var winLeft = (screen.availWidth - winWidth) / 2;
            var winTop = (screen.availHeight - winHight) / 2;
            features = features + ',top=' + winTop + ',left=' + winLeft;
        }
    }

    var wnd = window.open(theURL, winName, features);
    wnd.opener = window;
    if (window.focus) wnd.focus();

    return wnd;
}
function OpenHPIBetPopup(url) {
    var wnd = OpenHPIPopup(url, 'hpibet', '', 0, 0);
}
function OpenHPIFundPopup(url) {
    var wnd = OpenHPIPopup(url, 'hpifund', '', 0, 0);
}
function OpenFullOddsPopup(url) {
    var wnd = OpenHPIPopup(url, 'hpifov', 'directories=0,location=0,menubar=0,status=0,titlebar=0,toolbar=0,resizable=1,scrollbars=1', 925, 600, true);
}
function OpenReplayPopup(url) {
    var wnd = OpenHPIPopup(url, 'hpirelays', 'directories=0,location=0,menubar=0,status=0,titlebar=0,toolbar=0,resizable=1', 540, 520, true);
}
function RedirectParent(url) {
    if (window.opener) try { window.opener.location.href = url; } catch (e) { }
    return false;
}
function OpenOnlineAccountPopup(url) {
    var wnd = OpenHPIPopup(url, 'hpiOA', 'directories=0,location=0,menubar=0,status=0,titlebar=0,toolbar=0,resizable=1,scrollbars=1', 800, 660, true);
}

function setIndicatorPos(indicator, panel) {
    var posInd = Sys.UI.DomElement.getBounds(indicator);
    var posPanel = Sys.UI.DomElement.getBounds(panel);
    if (posInd.width == 0) posInd.width = 100;
    posInd.x = posPanel.x + Math.round((posPanel.width - posInd.width) / 2);
    posInd.y = posPanel.y + 20;
    Sys.UI.DomElement.setLocation(indicator, posInd.x, posInd.y);
}

function OpenVideoPlayer(theURL) {
    var w = 560, h = 600;
    var left = (screen.availWidth - 560) / 2;
    var top = (screen.availHeight - 600) / 2;
    var wnd = window.open(theURL, '_vplayer', 'directories=0,location=0,menubar=0,status=0,titlebar=0,toolbar=0,resizable=1,scrollbars=1,width=' + w + ',height=' + h + '' + ',top=' + top + ',left=' + left);
    wnd.opener = window;
    if (window.focus) wnd.focus();
}

function OpenLiveVideoPlayer(theURL) {
    var videoPosition = getLiveVideoPositon();
    var w = videoPosition.width;
    var h = videoPosition.height;
    var left = videoPosition.left;
    var top = videoPosition.top;
    var wnd = window.open(theURL, '_lrplayer', 'directories=0,location=0,menubar=0,status=0,titlebar=0,toolbar=0,resizable=1,scrollbars=1,width=' + w + ',height=' + h + '' + ',top=' + top + ',left=' + left);
    wnd.opener = window;
    if (window.focus) wnd.focus();
}

function OpenReplaysVideoPlayer(theURL) {
    var videoPosition = getReplayVideoPositon();
    var w = videoPosition.width;
    var h = videoPosition.height;
    var left = videoPosition.left;
    var top = videoPosition.top;
    var wnd = window.open(theURL, '_lrplayer', 'directories=0,location=0,menubar=0,status=0,titlebar=0,toolbar=0,resizable=1,scrollbars=1,width=' + w + ',height=' + h + '' + ',top=' + top + ',left=' + left);
    wnd.opener = window;
    if (window.focus) wnd.focus();
}

function getLiveVideoPositon() {
    return getVideoWindowPositon("lvideoc");
}

function getReplayVideoPositon() {
    return getVideoWindowPositon("rvideoc");
}

function getVideoWindowPositon(sCookieName) {
    var videoPosition = {
        width: 530,
        height: 430,
        top: (screen.availHeight - 430) / 2,
        left: (screen.availWidth - 530) / 2
    };

    try {
        //var sCookieName = "videoc";
        var cookieValue = getCookie(sCookieName);
        if (cookieValue) {
            var arr = cookieValue.split("|");
            var arrWH = arr[0].split(":");
            var arrTL = arr[1].split(":");
            videoPosition.width = parseFloat(arrWH[0]);
            videoPosition.height = parseFloat(arrWH[1]);
            videoPosition.top = parseFloat(arrTL[0]);
            videoPosition.left = parseFloat(arrTL[1]);
        }
    }
    catch (err) {
        videoPosition = {
            width: 530,
            height: 430,
            top: (screen.availHeight - 430) / 2,
            left: (screen.availWidth - 530) / 2
        };
    }
    return videoPosition;
}


/**
* Sets a Cookie with the given name and value.
*
* name       Name of the cookie
* value      Value of the cookie
* [expires]  Expiration date of the cookie (default: end of current session)
* [path]     Path where the cookie is valid (default: path of calling document)
* [domain]   Domain where the cookie is valid
*              (default: domain of calling document)
* [secure]   Boolean value indicating if the cookie transmission requires a
*              secure transmission
*/
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
        "; expires=Thu, 30-Dec-10 00:00:01 GMT" +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
* Gets the value of the specified cookie.
*
* name  Name of the desired cookie.
*
* Returns a string containing value of specified cookie,
*   or null if cookie does not exist.
*/
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    //alert('get cookie: '+name+' >> '+unescape(dc.substring(begin + prefix.length, end)));
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
* Deletes the specified cookie.
*
* name      name of the cookie
* [path]    path of the cookie (must be same as path used to create cookie)
* [domain]  domain of the cookie (must be same as domain used to create cookie)
*/
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestErrorHandler);

function EndRequestErrorHandler(sender, args) {
    if (args.get_error() != undefined) {
        /* suppress any client-side callback errors */
        args.set_errorHandled(true);
    }
}

function getPrint(print_area, track, race, date, urlBase, title, skipRaceInfo) {
    //Creating new pagevar 
    var areas = print_area.split(";");
    var pp = window.open();
    //debugger;
    //Adding HTML opening tag with <HEAD> … </HEAD> portion
    pp.document.writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
    pp.document.writeln('<html><head>');
    if (title)
        pp.document.writeln('<title>' + title + '</title>');
    else
        pp.document.writeln('<title>Print Race Information</title>');
    pp.document.writeln('<link href="' + urlBase + '/App_Themes/default/hpi.css" type="text/css" rel="stylesheet">')
    pp.document.writeln('<link href="' + urlBase + '/App_Themes/default/hpicontent.css" type="text/css" rel="stylesheet">')
    pp.document.writeln('<base target="_self"></head>');
    //Adding Body Tag
    pp.document.writeln('<body>');
    //Adding header    
    var hdrnum = Math.floor(Math.random()*1) + 1;
    
    pp.document.writeln('<table width="85%" style="text-align:center"><tr><td>'); 
    pp.document.writeln('<div style="width: 840px;">');
	pp.document.writeln('<div id="pphdr">');
	pp.document.writeln('	<img src="' + urlBase + '/Images/Pub/Header/lgo-hpi-sml.gif" width="77" height="70" alt="HorsePlayer Interactive" class="ppfloatLeft">');
	pp.document.writeln('	<div class="pphdrBnr'+ hdrnum + '">');
    pp.document.writeln('		<div class="pphdrRight">');
    pp.document.writeln('			<img src="' + urlBase + '/Images/Pub/Header/pp-lgo-hpifund.gif" width="57" height="47" alt="HPIFund" class="pplgoHpifund">');
    pp.document.writeln('			<img src="' + urlBase + '/Images/Pub/Header/pp-hdr-title.gif" width="215" height="47" alt="HorsePlayer Interactive Online Account Funding" class="floatLeft">');	
	//pp.document.writeln('			<div class="links">');
	//pp.document.writeln('				<a href="javascript:void(null);" onclick="javascript:window.open(\'http://www.horseplayerinteractive.com/Content/ContactUs.aspx\');">Contact Us</a> | ');
	//pp.document.writeln('				<a href="javascript:void(null);" onclick="javascript:window.open(\'http://www.horseplayerinteractive.com/Discover/HPIFaqDeposits.aspx\');">Help</a>');
	//pp.document.writeln('			</div>');	
	//pp.document.writeln('			<input type="submit" name="_ctl0:_ctl0:ucHeader:btnExit" value="Sign Out" id="_ctl0__ctl0_ucHeader_btnExit" tabindex="-10" class="btnSmall btnHdr" />');
	pp.document.writeln('		</div>');
	pp.document.writeln('	</div>');
	pp.document.writeln('</div></div></td></tr></table><br />');

	if (!skipRaceInfo) {
	    //Adding race info
	    pp.document.writeln('<table width="85%" style="text-align:center"><tr><td><b>Track: </b>' + track + '</td><td><b>Race: </b>' + race + '</td>');
	    pp.document.writeln('<td><b>Date:</b> ' + date + '</td></tr></table><br>');
	}
    
    //Writing print area of the calling page
    pp.document.writeln("<table width='85%'><tr><td>");    
    for (i = 0; i < areas.length; i++) {
        pp.document.writeln(document.getElementById(areas[i]).innerHTML);
    }
    pp.document.writeln("</td></tr><tr><td colspan='2' class='hsep5'></td></tr>");
    pp.document.writeln("<tr>");
    pp.document.writeln("<td colspan='2'>");
    //Adding footer    
    pp.document.writeln("<div class='ftr'>");
    //pp.document.writeln("<div class='ftrright'><a href='http://www.whitecapcanada.com' target='_blank'><img src='../Images/Pub/Footer/ftr_wclogo.gif' alt='e-Business by Whitecap' /></a></div>");
    var d = new Date();
	pp.document.writeln("<div class='ftrleft'><div class='ftrtxt'>© 2007-" + d.getFullYear() + " Woodbine Entertainment Group.");
    //pp.document.writeln("<a id='ctl00_Footer_lnkPP' href='/Discover/PrivacyPolicy.aspx'>Privacy Policy</a> | ");
    //pp.document.writeln("<a id='ctl00_Footer_lnkRG' href='/Content/ResponsibleGaming.aspx'>Responsible Gaming</a> | ");
    pp.document.writeln(" | 1-888-675-8886");
    pp.document.writeln("</div></div></div>");
    pp.document.writeln("      </td>");
    pp.document.writeln("    </tr></table>");
    //Ending Tag of </form>, </body> and </html>
	pp.document.writeln('</body></html>');
    pp.document.close();
    pp.focus();
    pp.print();
    pp.close();
}

function FixMenuFocus(sender, eventArgs) {
    try {
        var link = eventArgs.Item.LinkElement.href;
        if (link.lastIndexOf("#") == link.length - 1) {
            var isFocused = false;
            for (i = 0; i < eventArgs.Item.Items.length; i++) {
                if (eventArgs.Item.Items[i].CssClass == 'focused') {
                    isFocused = true;
                    break;
                }
            }
            if (!isFocused) {
                eventArgs.Item.CssClass = "";
                eventArgs.Item.FocusedCssClass = "";
                eventArgs.Item.Blur();
            }
        }
    }
    catch (e) { }
}

// Fix FF modal popup flicker problem on refresh/postback
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(fixModalPopups);
Sys.Application.add_load(fixModalPopups);

function fixModalPopups(sender, args)
{
    // Loop through all objects registered by the AjaxControlToolkit.
    for (var i = 0; i < Sys.Application._disposableObjects.length; i++)
    {
        // If it's a modal popup
        if (Sys.Application._disposableObjects[i].constructor.__typeName == "AjaxControlToolkit.ModalPopupBehavior")
        {
            var popUp = Sys.Application._disposableObjects[i];

            // Verify it exists so the script won't fail
            if (popUp)
            {
                //Add the function below as the event
                popUp.add_hidden(HidePopupPanel);
            }
        }
    }
}

function HidePopupPanel(source, args)
{
    //find the panel associated with the extender
    objPanel = document.getElementById(source._PopupControlID);

    //check the panel exists
    if (objPanel)
    {
        //set the display attribute, so it remains hidden on postback
        objPanel.style.display = 'none';
    }
}

// =============
// Popup Alerts
// =============
var PAMessageQueue = new Array();
var PAPageURLBase = "";
var PADisplayTime = "10s";
var PAInterval = "30s";

function ShowAlert(ID, title, content, URL, pageURLBase)
{
    if (PAPageURLBase == "") PAPageURLBase = pageURLBase;
    
    var obj = $("<div class=\"alert-box\"><div class=\"title-bar\"><div class=\"title\">" + title + "</div><div class=\"x-button\"><img src=\"" + PAPageURLBase + "/Images/Pub/x.jpg\" alt=\"Close\" style=\"cursor: pointer;\" /></div><div style=\"clear: both;\"></div></div><div class=\"contents\">" + content + "</div></div>");
    $(obj).attr("ID", ID);
    $(obj).find(".title-bar > .x-button").click(function() { var box = $(this).closest(".alert-box"); MarkAlertAsViewed($(box).attr("ID")); $(box).stopTime().remove(); });

    if (URL != "")
    {
        $(obj).find(".contents").css("cursor", "pointer").click(function() { var box = $(this).closest(".alert-box"); MarkAlertAsViewed($(box).attr("ID")); $(box).stopTime().remove(); window.location = URL.replace("[!BASEURL]", PAPageURLBase); });
    }
  
    $(obj).hover(
				function() // Over
				{
				    $(this).stopTime().stop().fadeTo("fast", 1.0);
				}
				,
				function() // Out
				{
				    $(this).oneTime(PADisplayTime, function() { $(this).fadeOut("slow", function() { MarkAlertAsViewed($(this).attr("ID")); $(this).remove(); }); });
				}
		);
    $(obj).appendTo("#alertArea");
    $(obj).fadeIn("fast", function() { $(this).oneTime(PADisplayTime, function() { $(this).fadeOut("slow", function() { MarkAlertAsViewed($(this).attr("ID")); $(this).remove(); }); }); });
}

// Creates the timer required to periodically check for popup alerts
// To disable the timer call $(document).stopTime("PopupAlertTimer")
function StartPopupAlertTimer(interval, displayTime, pageURLBase)
{
    PAInterval = interval;
    PADisplayTime = displayTime;
    PAPageURLBase = pageURLBase;
    
    // Call it once for first page visit
    GetPopupAlerts();
    
    // Set timer to call it every [PAInterval] seconds from now
    $(document).everyTime(PAInterval, "PopupAlertTimer", function() { GetPopupAlerts(); });
}

// Retrieve popup alerts
function GetPopupAlerts()
{
    $.ajax({
        type: "POST",
        url: PAPageURLBase + "/Racing/PortalServices.asmx/GetPendingAlertRequests",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msgs) { HandlePopupAlertResponse(msgs, PAPageURLBase); }
    });
}

// Mark alert as viewed
function MarkAlertAsViewed(ID)
{
    $.ajax({
        type: "POST",
        url: PAPageURLBase + "/Racing/PortalServices.asmx/MarkAlertAsViewed",
        data: '{"alertID": "' + ID + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
    
    ShowNextMessage()
}

// Handle a popup alert response
function HandlePopupAlertResponse(msgs)
{
    if (msgs == null) return;

    // Pause timer while viewing messages
    $(document).stopTime("PopupAlertTimer");

    PAMessageQueue = PAMessageQueue.concat(msgs);

    ShowNextMessage();
}

// Show the next available message
function ShowNextMessage()
{
    // If there are no more messages in the queue, restart alert timer to poll for more.
    if (PAMessageQueue.length == 0)
    {
        $(document).everyTime(PAInterval, "PopupAlertTimer", function() { GetPopupAlerts(); });

        return;
    }

    var msg = PAMessageQueue.shift();

    ShowAlert(msg.ID, msg.Title, msg.Message, msg.URL, PAPageURLBase);
}
// ==================
//  End Popup Alerts
// ==================