﻿// PageStudio uses some libraries that conflict with the $ factory method.
// To avoid eh.js causing errors when used on a page that also uses PageStudio, we'll refer to jQuery via a different variable.

var $jq = jQuery;


//Returns true if the enter key was pressed for all browsers, need to test on MAC's
function submitForm(e, obj) {
    //To cope with different browsers
    evt = e || window.event;
    var keyPressed = evt.which || evt.keyCode;
    if (keyPressed == 13)
        return true;
    else
        return false;
}

function getParamFromQueryString(parameter) {
    var qs;
    if ($jq.address) {
        qs = $jq.address.value();
    }
    else {
        qs = location.search;
    }
    var loc = qs.substring(1, qs.length);
    var param_value = null;

    var params = loc.split("&");
    for (i = 0; i < params.length; i++) {
        param_name = params[i].substring(0, params[i].indexOf('='));
        if (param_name == parameter) {
            param_value = params[i].substring(params[i].indexOf('=') + 1)
        }
    }
    return param_value;
}

var searchBoxText = "Search site";
var searchBoxText2 = "Keyword or phrase";

function termsAreValid(termsToCheck) {
    return termsToCheck && (termsToCheck != searchBoxText) && (termsToCheck != searchBoxText2)
}

function cleanTerms(schTerms) {
    schTerms = schTerms.replace(/[!#]*/g, "");
    schTerms = schTerms.replace(/  /g, " ");
    schTerms = encodeURIComponent(schTerms);
    return schTerms;
}

$jq(document).ready(function () {

    $jq("#keyField").click(function () {
        var kfv = $jq("#keyField").val();
        if (kfv == searchBoxText || kfv == searchBoxText2) {
            $jq("#keyField").val("");
        }
    });

    // Find all anchors with rel="popup" and attach popup behaviour.
    $jq("a.hasAttribute(rel:popup)").click(function () {
        doPopUp(this);
    });
});

// Start popups.

var newWindow = null;

function closeWin() {
    if (newWindow != null) {
        if (!newWindow.closed)
            newWindow.close();
    }
}

function popUpWin(url, type, strWidth, strHeight) {

    closeWin();

    type = type.toLowerCase();

    if (type == "fullscreen") {
        strWidth = screen.availWidth;
        strHeight = screen.availHeight;
    }
    var tools = "";
    if (type == "standard") tools = "resizable,toolbar=yes,location=yes,scrollbars=yes,menubar=yes,width=" + strWidth + ",height=" + strHeight + ",top=0,left=0";
    if (type == "console" || type == "fullscreen") tools = "resizable,toolbar=no,location=no,scrollbars=no,width=" + strWidth + ",height=" + strHeight + ",left=0,top=0";
    newWindow = window.open(url, 'newWin', tools);
    newWindow.focus();
}

function doPopUp(e) {
    //set defaults - if nothing in rel attrib, these will be used
    var t = "standard";
    var w = "400";
    var h = "400";
    //look for parameters
    attribs = this.rel.split(" ");
    if (attribs[1] != null) { t = attribs[1]; }
    if (attribs[2] != null) { w = attribs[2]; }
    if (attribs[3] != null) { h = attribs[3]; }
    //call the popup script
    popUpWin(this.href, t, w, h);
    //cancel the default link action if pop-up activated
    if (window.event) {
        window.event.returnValue = false;
        window.event.cancelBubble = true;
    }
    else if (e) {
        e.stopPropagation();
        e.preventDefault();
    }
}

function findPopUps() {
    var popups = document.getElementsByTagName("a");
    for (i = 0; i < popups.length; i++) {
        if (popups[i].rel.indexOf("popup") != -1) {
            // attach popup behaviour
            popups[i].onclick = doPopUp;
            // add popup indicator
            if (popups[i].rel.indexOf("noicon") == -1) {
                //popups[i].style.backgroundImage = "url(pop-up.gif)";
                popups[i].style.backgroundPosition = "0 center";
                popups[i].style.backgroundRepeat = "no-repeat";
                //popups[i].style.paddingLeft = "15px";
            }
            // add info to title attribute to alert fact that it's a pop-up window
            popups[i].title = popups[i].title + " [Opens in pop-up window]";
        }
    }
}

addEvent(window, 'load', findPopUps, false);

function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true; } else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r; } else { elm['on' + evType] = fn; } }

// End popups.

/*************************************************/
/*** Search behaviour for specialist searches ****/
/*** override by setting this variable in pages **/
var searchResultsCallbackSelector = "#searchResultsAjaxWrapper";
var ajaxSearchResultPagingLoadsNewPage = false;
/************************************************/

function cleanTopSearchSubmit() {
    var searchTerms = $jq("#searchInput").val();
    if (termsAreValid(searchTerms)) {
        searchTerms = cleanTerms(searchTerms);
        var showTotals = $jq("#showTotals").val();
        // This should match the format in the appsetting simpleSiteSearchQueryString
        location.href = '/siteSearch?showTotals=' + showTotals + '&terms=' + searchTerms + '&mode=Site';
    }
}

function cleanSectionSearchSubmit() {
    var searchTerms = $jq("#ctl00_cpMain_txtSectionSearch").val();
    if (termsAreValid(searchTerms)) {
        searchTerms = cleanTerms(searchTerms);
        var showTotals = $jq("#showTotals").val();
        var branch = $jq("#ctl00_cpMain_hdnBranch").val();
        // This should match the format in the appsetting simpleSiteSearchQueryString
        location.href = '/siteSearch?showTotals=' + showTotals + '&terms=' + searchTerms + '&mode=Site&branch=' + branch;
    }
}

function cleanProfSearchSubmit() {
    var searchTerms = $jq("#keyField").val();
    if (termsAreValid(searchTerms)) {
        searchTerms = cleanTerms(searchTerms);
        var showTotals = $jq("#showTotals").val();
        //var vals = getProfIndexVals();
        //var types = getProfSearchTypes();
        var branches = getProfSearchBranches();
        var stMode = getSearchTermMode();
        var searchLocation = '/siteSearch?showTotals=' + showTotals + '&terms=' + searchTerms + '&mode=Site&stmode=' + stMode;
        if (branches.length > 0) {
            searchLocation += "&profbranches=" + branches.join(",");
        }
        /*
        if (vals.length > 0) {
        searchLocation += "&index=Subject|" + vals.join(",");
        }
        if (types.length > 0) {
        searchLocation += "&type=" + types.join(",");
        }*/
        location.href = searchLocation;
    }
}

function cleanNewsFilterSubmit() {
    var topic = $jq("#TopicSelect").val();
    var region = $jq("#RegionSelect").val();
    if (topic || region) {
        var newNewsUrl = location.pathname;//Added to fix 278 issue
        if (newNewsUrl.charAt(newNewsUrl.length - 1) != "/")
            newNewsUrl = newNewsUrl + "/";        
        var qsChar = "?";
        if (topic) {
            newNewsUrl += "?topic=" + topic;
            qsChar = "&";
        }
        if (region) {
            newNewsUrl += (qsChar + "region=" + region);
        }
        location.href = newNewsUrl;
    }
}

function getBattlefieldsSearchLocationQueryString() {

    var searchTerms = $jq("#keyField").val();
    var county = $jq("#County").val();
    var region = $jq("#Region").val();
    var period = $jq("#Period").val();
    var dateRange = $jq("#DateRange").val();
    var from = $jq("FromDate").val();
    var to = $jq("ToDate").val();

    if (termsAreValid(searchTerms) || county.length > 0 || region.length > 0 || dateRange.length > 0 || period.length > 0) {
        searchTerms = cleanTerms(searchTerms);
        var showTotals = $jq("#showTotals").val();

        var searchLocation = 'showTotals=' + showTotals + '&terms=' + searchTerms + "&mode=Battlefields";
        if (county != undefined) { searchLocation += "&county=" + county }
        if (region != undefined) { searchLocation += "&region=" + region }
        if (period != undefined) { searchLocation += "&period=" + period }
        if (dateRange != undefined) { searchLocation += "&dateRange=" + dateRange }
        if (from != undefined) { searchLocation += "&from=" + from }
        if (to != undefined) { searchLocation += "&to=" + to }
        searchLocation += "&type=Battlefield";
        return searchLocation;
    }
    return null;
}


var eventSearchTermsDefaultText = "Enter Text...";
var eventLocationDefaultText = "Enter Location...";

function getEventSearchQueryString() {

    //var rand = new Date();
    var eventsSearchTerms = getEscapedInputVal("terms");
    if (eventsSearchTerms == escape(eventSearchTermsDefaultText)) {
        eventsSearchTerms = "";
    }
    var eventLocation = getEscapedInputVal("eventLocation");
    if (eventLocation == escape(eventLocationDefaultText)) {
        eventLocation = "";
    }
    //alert(eventsSearchTerms);
    //alert(eventLocation);
    var eventsStart = getEscapedInputVal("eventsStart");
    var eventsEnd = getEscapedInputVal("eventsEnd");
    var eventsFilter = getEventSearchFilter();
    eventsSearchTerms = cleanTerms(eventsSearchTerms);
    if (eventsSearchTerms || eventLocation || eventsStart || eventsEnd || eventsFilter) {
        var qs = "terms=" + eventsSearchTerms
                + "&mode=Events"
                + "&eventLocation=" + eventLocation
                + "&eventsStart=" + eventsStart
                + "&eventsEnd=" + eventsEnd
                + "&eventsFilter=" + eventsFilter;
        //        + "&rand=" + rand.getTime(); // TODO: remove for live
        return qs;
    }
    return null;
}

function getDiscoveryVisitSearchQueryString() {
    var keyStage = escape(getSelectedOption("keyStage"));
    var subject = escape(getSelectedOption("subject"));
    var region = escape(getSelectedOption("region"));
    var property = escape(getSelectedOption("property"));

    if (keyStage || subject) {
        var qs = "keyStage=" + keyStage
                + "&subject=" + subject
                + "&region=" + region
                + "&property=" + property
                + "&mode=DiscoveryVisits"
        return qs;
    }
    return null;
}

function getSelectedOption(dropDownName) {
    var selection = $jq(".masterForm select[name='" + dropDownName + "']");
    return selection.val();
}

function getEscapedInputVal(inputName) {
    var selection = $jq(".masterForm input[name='" + inputName + "']");
    if (selection.length > 0) {
        return escape(selection.attr("value"));
    }
    return "";
}

/*
function cleanEventSearchSubmit() {

var searchTerms = $jq("#eventSearch").val();
if (termsAreValid(searchTerms)) {
location.href = "/daysout/events/?terms=" + searchTerms;
}
}*/



function getPubSearchLocationQueryString() {
    // This should match the behaviour in CleanPubSearch.ashx
    var searchTerms = $jq("#keyField").val();
    if (searchTerms == searchBoxText || searchTerms == searchBoxText2) {
        $jq("#keyField").val("");
        searchTerms = "";
    }
    //if (termsAreValid(searchTerms)) { // allow empty terms

    searchTerms = cleanTerms(searchTerms);
    var showTotals = $jq("#showTotals").val();
    var qs = 'showTotals=' + showTotals + '&terms=' + searchTerms + '&mode=Publications';
    qs += "&stmode=" + getSearchTermMode();
    qs += "&searchTitles=" + (($jq("#searchTitles").is(':checked')) ? "true" : "false");
    qs += "&searchKeywords=" + (($jq("#searchKeywords").is(':checked')) ? "true" : "false");
    qs += "&series=" + $jq("#series").val();
    qs += "&nonEhOnly=" + (($jq("#nonEhOnly").is(':checked')) ? "true" : "false");
    qs += "&downloadsOnly=" + (($jq("#downloadsOnly").is(':checked')) ? "true" : "false");
    qs += "&forthcomingTitles=" + (($jq("#forthcomingTitles").is(':checked')) ? "true" : "false");
    qs += "&periodPublished=" + $jq("#periodPublished").val();
    return qs;
    //}
    //return null;
}


function getBluePlaqueSearchLocationQueryString() {
    var searchTerms = $jq("#keyField").val();
    var searchBorough = $jq("#keyBorough").val();
    var searchErectedBy = $jq("#keyErectedBy").val();
    var searchYearErected = $jq("#keyYearErected").val();
    var searchLocation = $jq("#keyLocation").val();

    if (!termsAreValid(searchTerms)) {
        searchTerms = "";
    }

    searchTerms = cleanTerms(searchTerms);

    var showTotals = $jq("#showTotals").val();

    var vals = getBluePlaquesIndexVals();
    var qs = 'showTotals=' + showTotals + '&terms=' + searchTerms + '&mode=BluePlaques';

    if (searchLocation != "") {
        qs += '&location=' + searchLocation;
    }

    if (searchBorough != "") {
        qs += '&borough=' + searchBorough;
    }

    if (searchErectedBy != "") {
        qs += '&erectedBy=' + searchErectedBy;
    }

    if (searchYearErected != "") {
        qs += '&erectedYear=' + searchYearErected;
    }


    if (vals.length > 0) {
        qs += "&index=Subject|" + vals.join(",");
    }
    return qs;

    return null;
}

function getGAPSearchLocationQueryString() {
    var searchTerms = $jq("#keyField").val();

    if (termsAreValid(searchTerms)) {
        searchTerms = cleanTerms(searchTerms);
        var showTotals = $jq("#showTotals").val();
        var searchBranch = $jq("#propertyType1").val();
        var vals = getGAPsIndexVals();
        var qs = 'showTotals=' + showTotals + '&terms=' + searchTerms + '&mode=Gap' + '&GAPType=' + searchBranch;
        return qs;
    }
    return null;
}

function getPropertyQueryString() {
    var searchTerms = $jq("#keyField").val();
    var filter = GetInterestAreaFilters();

    if (termsAreValid(searchTerms)) {
        searchTerms = cleanTerms(searchTerms);
        var showTotals = $jq("#showTotals").val();
        var qs = 'showTotals=' + showTotals + '&terms=' + searchTerms + '&filter=' + filter + '&mode=Property';
        return qs;
    }
    return null;
}

function GetInterestAreaFilters() {

    var elements = document.getElementById("propertyFilterInput").getElementsByTagName("input");

    var i = 1;
    var IAFilters = "";

    if (elements[0].title == "Everything" && elements[0].checked) {
        IAFilters = elements[0].title;
    }
    else {
        while (i < elements.length) {
            if (elements[i].checked) {
                if (IAFilters.length == 0) {
                    IAFilters = elements[i].title;
                }
                else {
                    IAFilters = IAFilters + "," + elements[i].title;
                }
            }
            i++;
        }

    }
    return IAFilters;
}

function getCaseStudySearchLocationQueryString() {
    var searchTerms = $jq("#keyField").val();

    var studyType = escape($jq("#selAssetType").val());
    var studyRegion = escape($jq("#selRegion").val());
    var studyPath = escape($jq("#path").val());
    var studyIndexName = escape($jq("#indexname").val());

    if (termsAreValid(searchTerms) || searchTerms == "") {
        searchTerms = cleanTerms(searchTerms);
        var showTotals = $jq("#showTotals").val();
        //var vals = getGAPsIndexVals();
        var qs = 'showTotals=' + showTotals + '&indexname=' + studyIndexName + '&path=' + studyPath + '&terms=' + searchTerms + '&mode=casestudy&region=' + studyRegion + '&type=' + studyType;
        return qs;
    }
    return null;
}

function getPorticoSearchQueryString() {
    var searchTerms = $jq("#keyField").val();

    var period = escape($jq("#selPeriod").val());
    var propertyType = escape($jq("#selPropertyType").val());
    var path = escape($jq("#path").val());

    if (termsAreValid(searchTerms) || searchTerms == "") {
        searchTerms = cleanTerms(searchTerms);
        var showTotals = $jq("#showTotals").val();
        var qs = 'showTotals=' + showTotals + '&path=' + path + '&terms=' + searchTerms + '&mode=portico&period=' + period + '&propertytype=' + propertyType;
        return qs;
    }
    return null;
}

function getSearchTermMode() {
    if ($jq("#all_words").is(':checked')) return "all";
    if ($jq("#any_word").is(':checked')) return "any";
    return "exact";
}

function getEventSearchFilter() {
    if ($("#radEvents").is(':checked')) {
        return "Events";
    } else {
        return "MembersEvents";
    }
}

// not currently used
function getProfIndexVals() {
    // condense subject index into single param:
    // TODO: make this more elegant
    var vals = [];
    if ($jq("#research").is(':checked')) vals.push("research");
    if ($jq("#designation").is(':checked')) vals.push("designation");
    if ($jq("#advice").is(':checked')) vals.push("advice");
    if ($jq("#funding").is(':checked')) vals.push("funding");
    if ($jq("#training_skills").is(':checked')) vals.push("training_skills");
    if ($jq("#archives_collections").is(':checked')) vals.push("archives_collections");
    return vals;
}

function getProfSearchBranches() {
    var branches = [];
    if ($jq("#branch_profall").is(':checked')) {
        branches.push("profall");
        return branches;
    }
    if ($jq("#branch_research").is(':checked')) branches.push("research");
    if ($jq("#branch_archives").is(':checked')) branches.push("archives");
    if ($jq("#branch_designation").is(':checked')) branches.push("designation");
    if ($jq("#branch_advice").is(':checked')) branches.push("advice");
    if ($jq("#branch_pubs").is(':checked')) branches.push("pubs");
    if ($jq("#branch_funding").is(':checked')) branches.push("funding");
    if ($jq("#branch_training").is(':checked')) branches.push("training");

    return branches;
}

function getBluePlaquesIndexVals() {
    var vals = [];
    return vals;
}

function getGAPsIndexVals() {
    var vals = [];
    return vals;
}

// not currently used
function getProfSearchTypes() {
    // TODO: move types to config
    var types = [];
    if ($jq("#pages").is(':checked')) {
        types.push("Section");
        types.push("General Document");
        types.push("News Story");
    }
    if ($jq("#publications").is(':checked')) {
        types.push("Publication");
        types.push("Publication Cover");
        types.push("Publication Accessible Word Doc");
    }
    if ($jq("#images").is(':checked')) types.push("Gallery Image"); // TODO: more
    return types;
}

function AjaxSearch_LoadFirstPageOfResults(queryString) {
    if (queryString) {
        if (ajaxSearchResultPagingLoadsNewPage) {
            reloadSamePageWithNewQueryString(queryString);
        }
        else {
            if ($jq.address) {
                $jq.address.value("?" + queryString);
            }
            else {
                $jq("#searchResultsAjaxTargetWrapper").load("/siteSearch #searchResultsAjaxWrapper", queryString, searchResultsCallBack);
            }
        }
    }
}

function AjaxSearch_LoadFirstPageOfResultsForSimpleMarkup(queryString, selector) {

    if (queryString) {
        if (ajaxSearchResultPagingLoadsNewPage) {
            reloadSamePageWithNewQueryString(queryString);
        }
        else {
            if ($jq.address) {
                $jq.address.value("?" + queryString);
            }
            else {
                if (!selector) selector = searchResultsCallbackSelector;
                $jq("#searchResultsAjaxTargetWrapper").load("/siteSearch " + selector, queryString, simpleMarkupSearchResultsCallback);
            }
        }
    }
}

function reloadSamePageWithNewQueryString(queryString) {
    var parts = location.href.split("?");
    var newHref = parts[0] + "?" + queryString;
    location.href = newHref;

}

// If ajaxSearchResultPagingLoadsNewPage = false, we'll get a new page request when the user pages search results.
// This ensures that the result box is filled with the correct page of results.
function AjaxSearch_LoadAddtionalPageOfResults() {
    var qs = getQueryStringForCallback();
    if (qs.length > 1) {
        // this takes the paging query string from the results page pager
        $jq("#searchResultsAjaxTargetWrapper").load("/siteSearch #searchResultsAjaxWrapper", qs, searchResultsCallBack);
    }
}


function AjaxSearch_LoadAddtionalPageOfResultsForSimpleMarkup(selector) {
    if (!selector) selector = searchResultsCallbackSelector;
    var qs = getQueryStringForCallback();
    if (qs.length > 1) {
        // this takes the paging query string from the results page pager
        $jq("#searchResultsAjaxTargetWrapper").load("/siteSearch " + selector, qs, simpleMarkupSearchResultsCallback);
    }
}

function getQueryStringForCallback() {
    if ($jq.address && $jq.address.queryString()) {
        return $jq.address.queryString();
    }
    if (location.search && location.search.length > 0) {
        var rtn = location.search.substring(1);
        return rtn;
    }
}

function searchResultsCallBack() {

    $jq("#searchResultsAjaxTargetWrapper .searchResultsBlock").hide();

    if (!ajaxSearchResultPagingLoadsNewPage) {
        $jq(".searchBottom a, #topPagerContainer a").each(function (i) {
            if (this.href) {
                var qpos = this.href.indexOf("?");
                this.href = "#?" + this.href.substring(qpos + 1);
            }
        });
    }

    //var resultsText = $jq(".jqResultCount").text();
    // TODO: need Google Analytics page tracking event here to record how many 
    // results came back for this search - we have the number of results, in
    // resultsText, but we don't have the search query string
    //if (resultsText) document.title = resultsText + " " + document.title;

    /*
    if (!ajaxSearchResultPagingLoadsNewPage) {
    $jq(".searchBottom a").click(function(e) {
    e.preventDefault();
    if (this.href) {
    var qpos = this.href.indexOf("?");
    $jq("#searchResultsAjaxTargetWrapper").load("/siteSearch #searchResultsAjaxWrapper", this.href.substring(qpos + 1), searchResultsCallBack);
    }
    });
    }*/
    scroll(0, 0);


    //this is to maitain state of radio buttons in FF as JQuery was removing the checked option when rendering the HTML
    var paramMode = getParamFromQueryString("stmode");

    switch (paramMode) {
        case "all":
            {
                $jq("#all_words").attr("checked", "true");
                break;
            }
        case "any":
            {
                $jq("#any_word").attr("checked", "true");
                break;
            }
        case "exact":
            {
                $jq("#exact_words").attr("checked", "true");
                break;
            }
    }

    //document.getElementById("searchResultsAjaxTargetWrapper").scrollIntoView();
}

function simpleMarkupSearchResultsCallback() {

    // rewrite the links to point to deep link address

    if (!ajaxSearchResultPagingLoadsNewPage) {
        $jq("#simpleMarkupPagingContainer a").each(function (i) {
            if (this.href) {
                var qpos = this.href.indexOf("?");
                var href = this.href.substring(0, qpos);
                //                if(href.lastIndexOf("/") == href.length -1) {
                //                    href = href.substring(0, href.length -1);
                //                }
                //this.href = href + "/#/?" + this.href.substring(qpos + 1);
                this.href = href + "#?" + this.href.substring(qpos + 1);
            }
        });
    }

    /*if (!ajaxSearchResultPagingLoadsNewPage) {
    $jq("#simpleMarkupPagingContainer a").click(function(e) {
    e.preventDefault();
    if (this.href) {
    var qpos = this.href.indexOf("?");
    $jq("#searchResultsAjaxTargetWrapper").load("/siteSearch " + searchResultsCallbackSelector, this.href.substring(qpos + 1), simpleMarkupSearchResultsCallback);
    }
    });
    }*/

    scroll(0, 0);
    //document.getElementById("searchResultsAjaxTargetWrapper").scrollIntoView();
}


function makeElementsAllTheSameHeight(jqSelector) {
    var maxCallOutHeight = 0;
    var isMembershipNewsPresent = false;
    $jq(jqSelector).each(function (index) {
        // don't do the resize if one of them is a membershipNews callout
        //if (!($jq(this).hasClass("membershipNews"))) {
        var computedHeight = $jq(this).height();
        //alert(computedHeight);
        if (computedHeight > maxCallOutHeight) {
            maxCallOutHeight = computedHeight;
        }
        //}
        //else {
        //    isMembershipNewsPresent = true;
        //}
    });
    if (maxCallOutHeight > 0 && !isMembershipNewsPresent) {
        $jq(jqSelector).css("height", maxCallOutHeight + 30);
    }
}


function StringBuffer() {
    this.__strings__ = new Array;
}

StringBuffer.prototype.append = function (str) {
    //this.__strings__.push(str);
    this.__strings__[this.__strings__.length] = str;
};

StringBuffer.prototype.toString = function () {
    return this.__strings__.join("");
};




// This script prevents the x and y coords of the submit button being submitted on the query string.
// For those without script the form submits to a handler that does the same thing, but on the server.

var hostname;
//var link;

$jq(document).ready(function () {

    hostname = location.hostname;
    hostname = "http://" + hostname;


    $jq("#searchInput").autocomplete('/ehAjax/AutoComplete.ashx', {
        width: 145,
        max: 10,
        scroll: true,
        scrollHeight: 300,
        minChars: 3,
        matchSubset: false,
        cacheLength: 10,
        matchSubset: true,
        extraParams: { 's': 'all' },
        selectFirst: false
    }).result(cleanTopSearchSubmit);

    $jq("#searchInput").click(function (e) {
        if ($jq("#searchInput").val() == 'Search site') {
            $jq("#searchInput").val("");
        }
    });

    // Fixes broken tracking on the new Publications Cover - DIVs renamed and added on Template
    $jq(".download a,.priceBox a,.openTop a,.paleGreenBox furtherInfo a,#midCol a,#rightCol a,#bigColLeft a").click(function (ev) {


        this.rel ? link = this.rel : link = $jq(this).attr("href");

        if (link != null && $jq(this).attr("class").indexOf("DoNotTrack") == -1) {
            lowerLink = link.toLowerCase();
            if ($jq(this).attr("class") == "liteboxa") {
                _gaq.push(['_trackPageview', "/Lightbox" + lowerLink]);
            }
            else {
                if (lowerLink.indexOf("http://") != -1) {
                    if (!(lowerLink.indexOf("http://" + eh_base_url) == 0 ||
                          lowerLink.indexOf("https://" + eh_base_url) == 0)) {
                        _gaq.push(['_trackPageview', "/External_Link" + lowerLink]);
                        if ($jq(this).attr("target").length == 0) {
                            ev.preventDefault();
                            setTimeout('document.location = "' + link + '"', 500);
                        }
                    }
                }
                else {
                    if ((link.indexOf("/content/") != -1) && (lowerLink.substring(0, 9) == "/content/")) {
                        _gaq.push(['_trackPageview', "/download" + lowerLink]);
                        if ($jq(this).attr("target").length == 0) {
                            ev.preventDefault();
                            setTimeout('document.location = "' + link + '"', 500);
                        }
                    }
                }
            }
        }

    });

    $jq("#searchForm").submit(function (e) {
        e.preventDefault();
        cleanTopSearchSubmit();
    });

    $jq("#othersearchBtn").click(function (e) {
        if ($jq("#othersitelist").val() != '') {
            window.open($jq("#othersitelist").val());
        }
        return false;
    });

    $jq("div #links ul li:last-child").addClass("noborder");
    $jq(".rchev:not( .topImage .rchev, .rchevDisabled, .norchev, .jqRchevIgnore), .mor_rightChevron").after("<img class='deFloat' src='/static/images/rchev.gif' alt=''/>");

});

var REGISTERED_USER_LOGGED_IN = false;

$jq(function () {
    var dispName = getEhCookieSubValue("dispname");
    if (dispName) {
        $jq("#loginLink").replaceWith("<a href='/myaccount/'>Welcome, " + dispName + "</a> | <a href='/login/logged-out/'>Sign out</a>");
        REGISTERED_USER_LOGGED_IN = true;
    }
    else {
        $jq("#loginLink").attr("href", "/login/?ReturnUrl=" + window.location.pathname);
    }

    var persRegion = getEhCookieSubValue("region");
    if (persRegion) {
        var regionalDaysOutPath = "/daysout/";
        switch (persRegion) {
            case "East Midlands":
                regionalDaysOutPath = "/daysout/eastmidlands/";
                break;
            case "East of England":
                regionalDaysOutPath = "/daysout/eastofengland/";
                break;
            case "London":
                regionalDaysOutPath = "/daysout/london/";
                break;
            case "North East":
                regionalDaysOutPath = "/daysout/northeast/";
                break;
            case "North West":
                regionalDaysOutPath = "/daysout/northwest/";
                break;
            case "South East":
                regionalDaysOutPath = "/daysout/southeast/";
                break;
            case "South West":
                regionalDaysOutPath = "/daysout/southwest/";
                break;
            case "West Midlands":
                regionalDaysOutPath = "/daysout/westmidlands/";
                break;
            case "Yorkhshire":
                regionalDaysOutPath = "/daysout/yorkshire/";
                break;
        }
        $jq(".nav .parent a.daysout").attr("href", regionalDaysOutPath);
    }
});

function getEhCookieSubValue(subkey) {
    var ehCookie = $jq.cookie("eh_clear");
    if (ehCookie) {
        var splt = ehCookie.split('&');
        var ehClear = {};
        $jq.each(splt, function (x, y) {
            var temp = y.split('=');
            ehClear[temp[0]] = temp[1];
        });
        return ehClear[subkey];
    }
    return null;
}

String.prototype.endsWith = function (str) {
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex != -1) && (lastIndex + str.length == this.length);
}

var firstTrack = true;
function callPageTracker() {
    if (firstTrack == false) {
        _gaq.push(['_trackPageview']);
    }
    firstTrack = false;
}

function recordVirtualLink(link, virtual) {
    _gaq.push(['_trackPageview', virtual]);
    setTimeout('document.location = "' + link.href + '"', 500)
}



