function setTimeZoneOffSet()
{
    prefs.TimeZoneOffSet = timeZoneOffset;
    prefs.SavePreferences(false);
}


function createAFFCookie(name,value,days)
{
    var expires = '';
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
	
	if(name == "AID")
	{  
	    document.cookie = "AID-PPC="+ value;	    
	}
}

function prepareForClose()
{
    try
    {
        if (top.masterChildWindow != null && !top.masterChildWindow.closed)    
        {
            if (top.masterChildWindow.prepareForClose)
                top.masterChildWindow.prepareForClose();
            top.masterChildWindow.close();
        }
    }
    catch(e){}
    
}

function onCloseMainWin()
{
    /*close popups*/    
	if(top.LogonWin) {top.LogonWin.close();}
    if (top.global.popUpWindowInfo) top.global.popUpWindowInfo.close();
    if (top.EventPnLWindows != null)
    {    
        for (var win in top.EventPnLWindows)
           top.EventPnLWindows[win].close();
    }
    prepareForClose();
       
	if ((top.global.uniqueLabel == "BETMATE") ||(top.global.uniqueLabel == "BETMATEUK"))
		OpenExitPage();
}

function ClosePopupWindow(win, evt)
{
    /*win.close();*/
    /*top.global.popUpWindowInfo = null;    */
    /*GBE_header.CallHeaderTab(false, 'account');*/
}



function getOddsSystem(){
	if(top.global.oddsSystem.isDecimalOdds)
		return 0;
	else if(top.global.oddsSystem.isFractionalOdds)
		return 1;
	else if(top.global.oddsSystem.isAmericanOdds)
		return 2;
	else return 0;	
}


function getDatesForDayLightSavings()
{
	var dateRange1 = new Date();
	var dateRange2 =  new Date();
	var timeNow = new Date();
	var adjustedDateTime= new Date();
	var adjustedTimeOffset;
	var range1Set = false;
	 
	var storedOffset = top.timeZoneOffset;
	/*alert(storedOffset);*/
	for(var i = 0; i < 600; i++){
		adjustedDateTime.setDate(adjustedDateTime.getDate() + 1);
		adjustedTimeOffset = adjustedDateTime.getTimezoneOffset();
	
		if(storedOffset != adjustedTimeOffset){
			if(range1Set){
				dateRange2 = adjustedDateTime;
				var dateRange2Formatted = new Date();
				top.timeZoneDateRange2 = dateRange2.getFullYear()+"/"+((dateRange2.getMonth()*1)+1)+"/"+dateRange2.getDate()+" 00:00:00";
				break;
			}
			else{
				dateRange1 = adjustedDateTime;
				var dateRange1Formatted = new Date();
				top.timeZoneDateRange1 = dateRange1.getFullYear()+"/"+((dateRange1.getMonth()*1)+1)+"/"+dateRange1.getDate()+" 00:00:00";
				storedOffset = adjustedTimeOffset;
				range1Set = true;
				
			}
		}
	}
	/*alert(top.timeZoneDateRange1);*/
}

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;
  return unescape(dc.substring(begin + prefix.length, end));
}

function setCookie(name, value) 
{ 
    var today = new Date();
    var expiry = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000); 
    if (value != null &&  value != "")
        document.cookie = name + "=" + escape(value)+ "; path=/; expires=" + expiry.toGMTString();
}



function changeLanguage(val)
{
	prefs.Language = val;
	if (top.GBE_masterAccount != null)
	{
	    //when master, save and refresh directly
        top.prefs.SavePreferences(false);
        reloadWholePage();
	}
	else top.prefs.SavePreferences(false, top.reloadWholePage);
}

function ForceSubmitForm(submittedForm)
{
    if (submittedForm != null)
    {        
        if (submittedForm.onsubmit)
        {
            submittedForm.onsubmit();
        }
        submittedForm.submit();
    }
}


function callFunctionAfterPreferencesUpdated()
{
    var updatePunterPreferencesImage = top.GBE_header.document.getElementById('updatePunterPreferencesImage');
    if (updatePunterPreferencesImage != null)
    {
        if (top.global.isLoggedIn == false || isImageOk(updatePunterPreferencesImage))
        {
            if (updatePunterPreferencesImage.calledFunction != null)
            {
                updatePunterPreferencesImage.calledFunction();            
            }
        }
        else 
        {
            window.setTimeout(function(){callFunctionAfterPreferencesUpdated();}, 100);
        }
    }
}

function getNewSubmitForm()
{
    var submitForm = document.createElement("FORM");
    document.body.appendChild(submitForm);
    submitForm.method = "POST";
    return submitForm;
}

/*helper function to add elements to the form*/
function createNewFormElement(inputForm, elementName, elementValue)
{
    var newElement = document.createElement("INPUT");
    newElement.type = "hidden";
    newElement.name = elementName;
    newElement.value = elementValue;
    inputForm.appendChild(newElement);
    return newElement;
}

function reloadWholePage(showAlert)
{

     /*var submitForm = getNewSubmitForm();*/
     /*createNewFormElement(submitForm, "currentPreferences", top.GetPreferencesURLPostfix());*/
     /*var tempDate = new Date();*/
     /*createNewFormElement(submitForm, "timeDummy", tempDate.getTime());*/
     /*var newLocation = window.top.location.href;*/
     /*if (newLocation.indexOf('.aspx') == -1)*/
     /*{*/
     /*   queryStart = newLocation.indexOf('?');*/
     /*   if(queryStart == -1)*/
     /*       newLocation += 'Default.aspx';*/
     /*   else*/
     /*       newLocation = newLocation.substr(0, queryStart)+"/Default.aspx";*/
     /*}*/
     /*submitForm.action= newLocation;*/
     /*document.body.appendChild(submitForm);*/
     /*submitForm.submit();*/
     
     var postFix = '';
     
     /*0017034: remove url parameters when user clicks on betdaq logo or logs out. */
     var url = top.location.href;
     var index = url.indexOf('?');
     if(index > -1)
        url = url.substring(0, index);
     if (top.GetPreferencesURLPostfix() != '' && url.indexOf('currentPreferences') == -1)
     {
        postFix = '?currentPreferences=' + top.GetPreferencesURLPostfix();
     }
     
     if (typeof(top.GBE_masterAccount) != "undefined" && top.GBE_masterAccount != null)
     {
        var agentIndex = top.location.href.indexOf('agentId');        
        if (agentIndex > -1)
        {
            var agentIndexTo = top.location.href.indexOf('&', agentIndex + 1);
            if (agentIndexTo == -1)
                agentIndexTo = top.location.href.length;
            postFix += '&agentId=' + top.location.href.substring(agentIndex + 8, agentIndexTo);              
        }
        
        var masterAccountIndex = top.location.href.indexOf('masterAccount');        
        if (masterAccountIndex > -1)
        {
            var masterAccountIndexTo = top.location.href.indexOf('&', masterAccountIndex + 1);
            if (masterAccountIndexTo == -1)
                masterAccountIndexTo = top.location.href.length;
            postFix += '&masterAccount=' + top.location.href.substring(masterAccountIndex + 14, masterAccountIndexTo);              
        }
     }          
     
     if (showAlert == true)
        postFix += "&showAlert=true"
     
    var alreadyReloaded = false;
    if (top.masterChildWindow != null && !top.masterChildWindow.closed)    
    {
        reloadPageAndChild();
        alreadyReloaded = true;
    }
    
    if(top.opener != null)
    {
        reloadPageAndParent();
        alreadyReloaded = true;
    }
    if (!alreadyReloaded)
        top.location.href = url + postFix;
}

function reloadPageAndParent()
{
    try    
    {
        if (top.opener != null && !top.opener.top.closed && typeof(top.opener.top.reloadPageAndParent) != "undefined")
        {
            top.opener.top.reloadPageAndParent();
        }
    }catch(e){}    
    
    top.location.reload();
}

function reloadPageAndChild()
{   
    try    
    {
        if (top.masterChildWindow != null && !top.masterChildWindow.top.closed && typeof(top.masterChildWindow.top.reloadPageAndChild) != "undefined")
        {
            top.masterChildWindow.top.reloadPageAndChild();
        }
    }catch(e){}
    top.location.reload();
}


function reloadPageAfterPreferencesUpdated()
{           
    var updatePunterPreferencesImage = top.GBE_header.document.getElementById('updatePunterPreferencesImage');
    if (updatePunterPreferencesImage != null)
    {
        if (top.global.isLoggedIn == false || isImageOk(updatePunterPreferencesImage))
        {
            reloadWholePage();
        }
        else 
        {
            window.setTimeout(function(){reloadPageAfterPreferencesUpdated();}, 100);
        }
    }
    else if(top.global.isLoggedIn == false)
    {
        reloadWholePage();
    }
}

function isImageOk(img) 
{
    if (!img.complete) 
    {
        return false;
    }

    if (typeof(img.naturalWidth) != "undefined" && img.naturalWidth == 0) 
    {
        return false;
    }
    return true;
}

function GetPreferencesURLPostfix()
{
    return top.preferencePostFix;
}

function AddPreferencesToActionURL(formObj)
{
    if (formObj == null || typeof(formObj.action) == "undefined" || formObj.action == null) return true;
       
    if (formObj.action.indexOf('currentPreferences') > -1)
    {
        return true;
    }
    else
    {
        if (formObj.action.indexOf('?') > -1)
        {
            formObj.action += "&";
        }
        else
        {
            formObj.action += "?";
        }
    }
    
    formObj.action += "currentPreferences=" + GetPreferencesURLPostfix();
    
    return true;
}


function marketObject()
{
	this.mT;
	this.relatedMarketId;
	this.pF;
	this.sEWO;

	this.isEachWayMarket =
	function isEachWayMarket()
	{
		if ((this.mT < 22 ) && (this.mT > 18))
			return true;
		else return false;
	}
}

var tempCopyOfMarketGrid = "";   /* Holder for copy of contents of the event card market grid, so we can replace it after a reload*/

function HideNotifications()
{
    var mainInnerFrame = top.GBE_FrameSet.document.getElementById("mainInnerFrame");
    mainInnerFrame.rows = NOTIFICATION_ROWS_HIDDEN;

    var notif = top.GBE_FrameSet.document.getElementById("GBE_Notification");
    notif.style.display = 'none';     
}


function ReloadFrames(isNotificationRefreshed, isMainPanelRefreshed)
{   
    var isNotificationPanelRefreshed = false;
    
    if (isNotificationRefreshed)
    {
        var notif = top.document.getElementById("GBE_Notification");
        var mainInnerFrame = top.GBE_FrameSet.document.getElementById("mainInnerFrame");
        if (prefs.DisplayNotifications)
        {
            mainInnerFrame.rows = NOTIFICATION_ROWS_LOGGED_EXPANDED;
            notif.style.display = 'block';      
        }
        else 
        {
            mainInnerFrame.rows = NOTIFICATION_ROWS_HIDDEN;
            notif.style.display = 'none';
        }
        
        if (prefs.DisplayNotifications && notif.innerHTML == "") isNotificationPanelRefreshed = true;
    }
    
    if (isMainPanelRefreshed)
    {
        isNotificationPanelRefreshed = true;

        /* Copy contents of the event card market grid, so we can replace it after the reload     */
        if (top.GBE_main != null && top.GBE_main.GBE_evCard && top.GBE_main.GBE_evCard.document.getElementById("marketGridDivRow"))   
            tempCopyOfMarketGrid = top.GBE_main.GBE_evCard.document.getElementById("marketGridDivRow").innerHTML;
        
        if (top.global != null && top.global.baseURL != null && top.GBE_main != null && top.GBE_main.GBE_evCard != null && top.GBE_main.GBE_evCard.currentQueryString != null && top.GBE_main.GBE_evCard.currentQueryString != '')
        {
            var reloadedUrl =  top.global.baseURL + "Common/twoiframe.aspx" + top.GBE_main.GBE_evCard.currentQueryString;

            // On reload of event card, make sure that any selection/odds passed into it on initial load
            // (e.g. by clicking on search results) are NOT passed in this time
            // (e.g. odds format may have changed, so odds could be in wrong format!)
            reloadedUrl = reloadedUrl.replace("odds=", "oddsDONTUSE=").replace("sId=", "sIdDONTUSE=").replace("type=", "typeDONTUSE=");

            if (reloadedUrl.indexOf('currentPreferences') == -1)
                reloadedUrl += "&currentPreferences=" + top.GetPreferencesURLPostfix();
            top.GBE_main.location.href = reloadedUrl;
        }
        else
        {
            if (is_ie)
            {
                top.GBE_main.history.go(0);  
            }
            else
            {
                top.GBE_main.location.href = top.GBE_main.location.href;
            }
        }
    }
    
    if (isNotificationPanelRefreshed == true)
    {
        var notificationLocation = siteRoot + '/common/loadNotification.aspx?currentPreferences=' + top.GetPreferencesURLPostfix();
        if (is_ie)
        {
            top.frames['GBE_Notification'].location.href = notificationLocation;
        }
        else
        {
            top.GBE_Notification.location = notificationLocation;
        }
    }
}

function getIframeDocument(iframe)
{
    var doc = null;
    if(iframe.contentDocument)  
       doc = iframe.contentDocument;  
    else if(iframe.contentWindow)  
       doc = iframe.contentWindow.document;  
    else if(iframe.document)  
       doc = iframe.document; 
    return doc;
}

function ReloadLanguageFrames()
{
    top.dontReloadWholeSite = true;
    top.GBE_leftnav.location.href = top.GBE_leftnav.location.href;
    top.GBE_header.location.href = top.GBE_header.location.href;
}

function isBrowserSuitable() 
{
    /*We support...
    Windows
    Internet Explorer 5.5 or greater
    Firefox
    Safari
    */

	if ( browser.isWin && browser.isIE && browser.versionMinor >= 5.5 )
		return true;
			
	if ( browser.isGecko && browser.versionMinor >= 1.7)
		return true;
	
/*
	if ( browser.isMac && browser.isSafari && browser.versionMinor >= 1.2 )
		return true;
*/	
    /*if (browser.isOpera) return true;*/
    
    if (browser.isSafari) return true; 
    
	
	document.location.href = GBE_Web_UI_Util_BrokerLangHTMLDir + "/IncompatibleBrowser.html";
}

function FocusPopupWindow()
{
    if (top.global && top.global.popUpWindowInfo && !top.global.popUpWindowInfo.closed)
    {
        top.global.popUpWindowInfo.focus();
    }
}

/*use this method to call popup pages*/
function goToPopupSection(jumpTo, tabId, otherParams)
{
    var tempDate = new Date(); 
    if (top.getTopWindow().FocusPopupWindow)
        top.getTopWindow().FocusPopupWindow();
        
    var linkPostFix = '.aspx?x=' + tempDate.getTime() + '&JumpTo=' + jumpTo + '&tabId=' + tabId + '&currentPreferences=' + top.GetPreferencesURLPostfix();;
        
    if (tabId == 'accountTab')
    {
        linkPostFix = '/Secure/Account/blankSecurePage' + linkPostFix;
    }
    else /*all other tabs*/
    {
        linkPostFix = '/Common/BlankPage' + linkPostFix;
    }
    
    top.GBE_hidden.location =  top.siteRoot + linkPostFix;
    return false;
}


function sizeIframe()
{
    $("#GBE_FrameSet").height($(window).height());
    $("#GBE_FrameSet").width($(window).width());
}


function SearchFacility()
{
    var currentlyHighlightedResult = -1;
    var currentKeyword = "";
    var currentSearchRequest = null;
    var currentPriceRequest = null;

    // Constants
    var SELECTIONSTATUS_ACTIVE = 2;
    var SELECTIONSTATUS_SUSPENDED = 3;
    var SELECTIONSTATUS_WITHDRAWN = 4;


    // As user types each additional letter of the search term, we may repeatedly do the same search
    // so we cache the prices for the existing searchs, just so the prices don't go blank while the new search is being done
    var cachedBackPrices = new Object();
    var cachedLayPrices = new Object();
    var cachedSelectionStatuses = new Object();

    this.centreOnPage = function ()
    {
        var leftPos = ($(document).width() - $("#searchBox").width()) / 2;

        $("#searchBox").css("left", leftPos);
        $("#searchBoxBackground").css("left", leftPos - 13);
        $("#searchBoxBackgroundResultsShown").css("left", leftPos - 13);
        $("#searchBoxCloseResultsIcon").css("left", leftPos + 218);
        $("#searchResultsOverlay").css("left", leftPos - 11);
    }

    // Get key pressed (from event object)
    function getKeyCode(e)
    {
        var kCode;

        if (e.keyCode)
            kCode = e.keyCode;
        else
            kCode = e.charCode;

        return kCode;
    }

    // Scroll the specified element into view (in "container")
    function scrollIntoView(element, container)
    {
        var containerTop = $(container).scrollTop();
        var containerBottom = containerTop + $(container).height();
        var elemTop = element.offsetTop;
        var elemBottom = elemTop + $(element).height();
        if (elemTop < containerTop)
        {
            $(container).scrollTop(elemTop);
        }
        else if (elemBottom > containerBottom)
        {
            $(container).scrollTop(elemBottom + 19 - $(container).height());
        }
    }

    // Show the search facility
    this.show = function ()
    {
        $("#searchFacility").show();
        this.centreOnPage();
        this.hideResults();
    }

    // Hide the search facility
    this.hide = function ()
    {
        $("#searchFacility").hide();
        this.hideResults();
    }

    // Called when the search box loses focus
    this.onSearchBoxInputBlur = function ()
    {
        if ($("#searchBoxInput").val() == "")
            this.resetSearchBoxInput();

        //setTimeout("searchFacility.hideResults();", 200);
    }

    // Reset the search input box to "Search Markets" in grey
    this.resetSearchBoxInput = function ()
    {
        $("#searchBoxInput").val(GBE_Web_UI_Search_SearchMarkets).css("color", "#BBBBBB");
        $("#searchBoxInput").blur();
    }

    // Pad left with "0" or any other char
    function padLeft(nr, n, str)
    {
        return Array(n - String(nr).length + 1).join(str || '0') + nr;
    }

    function getIMEI()
    {
        // IMEI string format we will use is "BBBBTPPPPPP"
        // BBBB is broker number (e.g. "0001" for brk1)
        // T is 1 of Exchange Tab, 2 for 1Bet Tab
        // PPPPPP is punter ID, or blank if not logged in
        return padLeft(top.global.brokerHandle, 4)
            + (top.prefs.LastViewedTab == "ibroker_tab" ? "2" : "1")
            + top.global.punterId;
    }

    // Response to a key press (e.g. do a new search, or browse up/down through results)
    this.onKeyUp = function (keyword, e)
    {
        // If "Search Markets" was in search textbox, clear it and change colour to black
        if ($("#searchBoxInput").val() == GBE_Web_UI_Search_SearchMarkets)
        {
            $("#searchBoxInput").val("").css("color", "#000000");
            keyword = "";
        }

        // Check key pressed
        var kCode = getKeyCode(e);

        if (kCode == 27)    // ESC key
        {
            // Hide search results
            this.hideResults();
            $("#searchBoxInput").blur();
        }
        else if (kCode == 13)   // ENTER key
        {
            // Simulate click on currently highlighted search result
            if (currentlyHighlightedResult > -1)
            {
                $("#resultLink_" + currentlyHighlightedResult).click();
                $("#searchBoxInput").blur();
            }
        }
        else if (kCode == 37 || kCode == 39 || kCode == 35 || kCode == 36 || kCode == 16)     // LEFT OR RIGHT ARROW, OR HOME, OR END, OR SHIFT
        {
            // Do nothing, search term has not changed
        }
        else if (kCode == 40)    // DOWN ARROW
        {
            // If next result exists
            if ($("#result_" + (currentlyHighlightedResult + 1)).length > 0)
            {
                $("#result_" + currentlyHighlightedResult).removeClass("searchResultSelected").addClass("searchResult");
                currentlyHighlightedResult++;
                $("#result_" + currentlyHighlightedResult).removeClass("searchResult").addClass("searchResultSelected");

                scrollIntoView(document.getElementById("result_" + currentlyHighlightedResult), "#searchResults");
            }
        }
        else if (kCode == 38)    // UP ARROW
        {
            if (currentlyHighlightedResult > -1)
            {
                $("#result_" + currentlyHighlightedResult).removeClass("searchResultSelected").addClass("searchResult");
                currentlyHighlightedResult--;
            }

            if (currentlyHighlightedResult > -1)
            {
                $("#result_" + currentlyHighlightedResult).removeClass("searchResult").addClass("searchResultSelected");

                scrollIntoView(document.getElementById("result_" + currentlyHighlightedResult), "#searchResults");
            }

        }
        else
        {
            // If search term has changed, or search results not currently visible
            if (keyword != currentKeyword || !$("#searchResultsOverlay").is(":visible"))
            {
                // Do a search
                currentKeyword = keyword;

                if (keyword.length < 3)
                {
                    // Reset caches so we don't show stale prices
                    this.clearCaches();
                }

                if (keyword.length > 2)
                {
                    if (currentSearchRequest != null)
                        currentSearchRequest.abort();

                    // Handle special chars: " + \ < >
                    keyword = keyword.replace(/"/g, "").replace(/\+/g, "%2B").replace(/\\/g, "").replace(/</g, "").replace(/>/g, "");

                    var request = '{ ' +
                                ' "searchText": "' + keyword + '", ' +
                                ' "imei": "' + getIMEI() + '", ' +
                                ' "isSportsbook" : ' + (top.prefs.IsIBrokerSite ? "true" : "false") + ' }';

                    currentSearchRequest = $.ajax({
                        type: 'POST',
                        url: "Search/MobileCloudAPICall.aspx?API=Search",
                        data: request,
                        success: searchFacility.handleSearchResponse,
                        error: searchFacility.handleSearchError,
                        dataType: "json",
                        timeout: 5000
                    });

                }
                else
                {
                    // Blank out search results
                    $("#searchResults").html("");
                    this.hideResults();
                }
            }
        }
    }

    function showResultsOverlay()
    {
        // Show results overlay
        $("#searchResultsOverlay").show();
        $("#searchBoxCloseResultsIcon").show();

        $("#searchResultsNoMatches").hide();
        $("#searchResultsNoResponse").hide();
        $("#searchResults").hide();

        $("#searchBoxBackground").hide();
        $("#searchBoxBackgroundResultsShown").show();
    }

    // Handle error in getting search results
    this.handleSearchError = function (jqXHR, textStatus, errorThrown)
    {
        // If error due to explicitly aborting previous request, don't display any error
        if (textStatus == "abort")
            return;

        showResultsOverlay();

        $("#searchResultsNoResponse").show();
        $("#searchResultsOverlay").height($("#searchResultsNoResponse").height() + 24)

        $("#searchOverlayBackgroundBottom").css("top", $("#searchResultsNoResponse").height() + 15);
        $("#searchOverlayBackgroundSides").height($("#searchResultsNoResponse").height() + 15);
    }

    var searchResponse = null;

    // Handle response received for a search request
    this.handleSearchResponse = function (response)
    {
        searchResponse = response;

        // Request latest prices for top selections returned
        getSearchPrices(true);

        showResultsOverlay();

        if (response.rc == 0)
        {
            if (response.searchHits.length == 0)
            {
                $("#searchResultsNoMatches").show();
                $("#searchResultsOverlay").height($("#searchResultsNoMatches").height() + 20)

                $("#searchOverlayBackgroundBottom").css("top", $("#searchResultsNoMatches").height() + 11);
                $("#searchOverlayBackgroundSides").height($("#searchResultsNoMatches").height() + 11);
            }
            else
            {
                // Set height to auto, otherwise height will not change from previous height
                $("#searchResults").height("auto");

                // Display search results
                $("#searchResults").html($("#searchResultsTemplate").tmpl(response));
                $("#searchResults").show();

                // Display any cached prices while we wait for latest prices to be returned
                displayCachedPrices();

                // Reset result that is selected using up/down arrow keys
                currentlyHighlightedResult = -1;

                // Scroll to top of search results
                $("#searchResults").scrollTop(0);
                setTimeout('$("#searchResults").scrollTop(1);', 10);
                setTimeout('$("#searchResults").scrollTop(0);', 20);

                setSearchResultsOverlayHeight();

            }
        }
        else
            $("#searchResults").html("Error: " + response.rc);
    }

    function setSearchResultsOverlayHeight()
    {
        // Limit height of search results
        if ($("#searchResults").height() > 400)
            $("#searchResults").height(400);

        // Position drop shadows
        $("#searchOverlayBackgroundBottom").css("top", $("#searchResults").height() - 9);
        $("#searchOverlayBackgroundSides").height($("#searchResults").height() - 9);

        // Search results overlay height to same as seatch results
        $("#searchResultsOverlay").height($("#searchResults").height());
    }

    // Clear caches of back and lay prices
    this.clearCaches = function ()
    {
        cachedBackPrices = new Object();
        cachedLayPrices = new Object();
        cachedSelectionStatuses = new Object();
    }

    // Request prices for the selections which has "sp=true"
    function getSearchPrices(topResults)
    {
        // Kill any outstanding price request
        if (currentPriceRequest != null)
            currentPriceRequest.abort();

        var selectionIds = "";

        var fromIndex = 0;
        var toIndex = 0;
        if (topResults)
        {
            // Get prices for first 5 events
            fromIndex = 0;
            toIndex = 4;
        }
        else
        {
            // Get prices for remaining events
            fromIndex = 5;
            toIndex = 999999;
        }

        // For each event
        for (var i = fromIndex; i <= toIndex && i < searchResponse.searchHits.length; i++)
        {
            // For each matching selection in event
            for (var j = 0; j < searchResponse.searchHits[i].his.length; j++)
            {
                var selectionId = searchResponse.searchHits[i].his[j].si;

                // Check we don't already have prices for this selection, if not then add it to list to get
                var cachedBackPrice = cachedBackPrices["'" + selectionId + "'"];
                if (typeof cachedBackPrice == "undefined")
                {
                    if (selectionIds != "")
                        selectionIds = selectionIds + ",";
                    selectionIds = selectionIds + selectionId;
                }
            }
        }

        if (selectionIds != "")
        {
            currentPriceRequest = $.ajax({
                type: 'GET',
                url: "Search/GetPrices.aspx?selectionIds=" + selectionIds + "&currentPreferences=" + top.GetPreferencesURLPostfix(),
                success: topResults ? searchFacility.handleGetPricesForTopResultsResponse : searchFacility.handleGetPricesResponse,
                error: searchFacility.handleGetPricesError,
                dataType: "json",
                timeout: 5000
            });

        }
        else
        {
            if (topResults)
            {
                // No prices to get for top results, so get prices for remaining selections
                getSearchPrices(false);
            }
        }
    }

    this.handleGetPricesError = function (jqXHR, textStatus, errorThrown)
    {
    }

    // Handle response to get prices
    this.handleGetPricesResponse = function (response)
    {
        for (var i = 0; i < response.prices.length; i++)
        {
            // Show prices
            $("#backPrice_" + response.prices[i].si).html(response.prices[i].bp);
            $("#layPrice_" + response.prices[i].si).html(response.prices[i].lp);
            cachedBackPrices["'" + response.prices[i].si + "'"] = response.prices[i].bp;
            cachedLayPrices["'" + response.prices[i].si + "'"] = response.prices[i].lp;

            // Save selection status to cache
            cachedSelectionStatuses["'" + response.prices[i].si + "'"] = response.prices[i].ss;

            // If selection is withdrawn or suspended, mark it as such
            markWithdrawnOrSuspendedSelection(response.prices[i].si, response.prices[i].ss);
        }

        // We may need to adjust heights after market selections as withdrawn or suspended
        setSearchResultsOverlayHeight();
    }

    // If selection is withdrawn or suspended, mark it as such
    function markWithdrawnOrSuspendedSelection(selectionId, selectionStatus)
    {
        if (selectionStatus == SELECTIONSTATUS_SUSPENDED
            || selectionStatus == SELECTIONSTATUS_WITHDRAWN)
        {
            // Hide prices
            $("#prices_" + selectionId).hide();

            // Style selection name
            $("#selName_" + selectionId).addClass("wSel");

            // Display "Withdrawn" or "Suspended"
            if (selectionStatus == SELECTIONSTATUS_WITHDRAWN)
                $("#withdrawn_" + selectionId).show();
            if (selectionStatus == SELECTIONSTATUS_SUSPENDED)
                $("#suspended_" + selectionId).show();
        }
    }

    this.handleGetPricesForTopResultsResponse = function (response)
    {
        // Display prices returned
        searchFacility.handleGetPricesResponse(response);

        // Get prices for remaining selections
        getSearchPrices(false);
    }

    // Display cached prices (while we wait for the live prices to arrive)
    function displayCachedPrices()
    {
        // For each back/lay box pair
        $("[id^=selName_]").each(function ()
        {
            // Get the selectionId
            var selId = $(this).attr('id').replace("selName_", "");

            // Display cached back price
            var cachedBackPrice = cachedBackPrices["'" + selId + "'"];
            if (typeof cachedBackPrice != "undefined")
                $("#backPrice_" + selId).html(cachedBackPrice);

            // Display cached lay price
            var cachedLayPrice = cachedLayPrices["'" + selId + "'"];
            if (typeof cachedLayPrice != "undefined")
                $("#layPrice_" + selId).html(cachedLayPrice);

            // If selection is withdrawn or suspended, mark it as such
            var cacheSelectionStatus = cachedSelectionStatuses["'" + selId + "'"];
            if (typeof cacheSelectionStatus != "undefined")
                markWithdrawnOrSuspendedSelection(selId, cacheSelectionStatus);
        });
    }



    // Hide the search results
    this.hideResults = function ()
    {
        $("#searchResultsOverlay").hide();
        $("#searchBoxCloseResultsIcon").hide();

        $("#searchBoxBackground").show();
        $("#searchBoxBackgroundResultsShown").hide();
    }

    // Select a search result
    this.selectResult = function (event, eventId, eventName, marketId, marketName, selectionId, selectionName, polarity)
    {
        // Blur input box in case result was selected using keyboard
        $("#searchBoxInput").blur();

        if (eventId)
        {
            // Drill down to event on left nav
            top.GBE_leftnav.ServerJumpAndOpen('ec:' + eventId, null, null, true);
        }
        else if (selectionId)
        {
            // Load market and put selection on bet slip
            var odds = null;
            if (selectionId != null)
                odds = (polarity == "F" ? cachedBackPrices["'" + selectionId + "'"] : cachedLayPrices["'" + selectionId + "'"]);

            if (top.GBE_main
                && top.GBE_main.GBE_evCard
                && top.GBE_main.GBE_evCard.mId
                && top.GBE_main.GBE_evCard.mId == marketId
                && !top.GBE_main.GBE_evCard.marketIsSuspended(marketId))
            {
                // Market is already loaded, and not suspended, so add bet to bet slip
                top.GBE_main.GBE_evCard.goOrder(null, marketId, selectionId, polarity, false, 0, false, odds)
            }
            else
            {
                // Load market passing through selectionId, polarity and odds
                var destinationString = 'mkt:' + marketId + ':' + selectionId + ':' + polarity;
                if (odds != null && typeof (odds) != "undefined")
                    destinationString += ":" + odds;

                top.GBE_leftnav.ServerJumpAndOpen(destinationString, null);
            }
        }
        else
        {
            // Load market

            if (top.GBE_main
                && top.GBE_main.GBE_evCard
                && top.GBE_main.GBE_evCard.mId
                && top.GBE_main.GBE_evCard.mId == marketId)
            {
                // market already loaded, do nothing!
            }
            else
            {
                top.GBE_leftnav.ServerJumpAndOpen('mkt:' + marketId, null);
            }
        }

        this.hideResults();

        // If selectionId specified, forget marketId as we don't need it from now on
        if (selectionId)
            marketId = null;

        // Send request to webservice indicating which result was selected

        var handle = -1;
        var name = "";
        if (eventId)
        {
            handle = eventId;
            name = eventName;
        }
        else if (marketId)
        {
            handle = marketId;
            name = marketName;
        }
        else
        {
            handle = selectionId;
            name = selectionName;
        }

        var request = '{ ' +
                        ' "imei": "' + getIMEI() + '", ' +
                        ' "isMarket" : ' + (marketId != null ? "true" : "false") + ',' +
                        ' "isEventClassifier" : ' + (eventId != null ? "true" : "false") + ',' +
                        ' "isSelection" : ' + (selectionId != null ? "true" : "false") + ',' +
                        ' "handle" : ' + handle + ',' +
                        ' "name" : "' + name + '" }';

        currentSearchRequest = $.ajax({
            type: 'POST',
            url: "Search/MobileCloudAPICall.aspx?API=SetSelected",
            data: request,
            dataType: "json",
            timeout: 5000
        });

        // Stop this function from being called multiple times for the same mouse click
        event.cancelBubble = true; // for IE
        if (event.stopPropagation)
            event.stopPropagation(); // for other browsers
    }

}

var searchFacility = new SearchFacility();

$(document).ready(function ()
{
    searchFacility.resetSearchBoxInput();
});

