/* Minification failed. Returning unminified contents.
(1340,5-6): run-time warning JS1004: Expected ';': a
 */
function popup_help_full(helpid, x, y, width, height) {
    if (x == 0) x = 50;
    if (y == 0) y = 50;
    if (width == 0) width = 585;
    if (height == 0) height = 520;
    winOptions = "location=no,toolbar=yes,menubar=no,resizable=yes,scrollbars=yes,height=" + height + ",width=" + width;

    if (navigator.appName == "Netscape")
        winOptions += ",screenX=" + x + ",screenY=" + y;
    else
        winOptions += ",left=" + x + ",top=" + y;

    window.open("/Help/PopUp.aspx?help_id=" + helpid, "pop", winOptions);
}


/*	Scrolly stuff	*/
function autoScrollY() {
    var currentY = currentYOffSet();

    //	only scroll if currenty == 0 to stop refresh bug
    if (currentY == 0 && window.scrollBy) {

        var strQs = '';
        var intScrollY = 0;
        if (window.location && window.location.search) {
            strQS = window.location.search;
            intScrollY = extractQueryTerm(strQS, 'Y');
        }
        if (intScrollY > 0) {
            window.scrollBy(0, intScrollY);
        }
    }
}

function extractQueryTerm(strQS, strName) {
    var intStart;
    var intEnd;
    var intHashEnd;
    var intAmpEnd;
    var intQstnEnd;
    var strSearch;
    var strValue;

    strQS += "#";
    strSearch = strName + "=";
    intStart = (strQS.indexOf(strSearch)) + strSearch.length;

    intHashEnd = strQS.indexOf("#", intStart);
    intAmpEnd = strQS.indexOf("&", intStart);
    intQstnEnd = strQS.indexOf("?", intStart);

    intEnd = intHashEnd;

    if ((intQstnEnd != -1) && (intQstnEnd < intEnd)) {
        intEnd = intQstnEnd;
    }
    if ((intAmpEnd != -1) && (intAmpEnd < intEnd)) {
        intEnd = intAmpEnd;
    }

    strValue = strQS.substr(intStart, (intEnd - intStart));
    return strValue;
}

function currentYOffSet() {
    var pxY;
    if (document.documentElement && document.documentElement.scrollTop) {
        pxY = document.documentElement.scrollTop;
    } else if (window.pageYOffset) {
        pxY = window.pageYOffset;
    } else if (document.body) {
        pxY = document.body.scrollTop;
    }
    else {
        pxY = 0;
    }
    return pxY;
}

function persistYOffSet(link) {
    var pxY = currentYOffSet();
    return link.href + '&Y=' + pxY;
}

function redirectY(link) {

    if (window.location && this && link) {

        window.location = persistYOffSet(this);

        //	stop normal link action
        link.returnValue = false;
        if (link.preventDefault) {
            link.preventDefault();
        }
        return false;
    }
}

function hookUpLinks(linksToHookUp) {
    var links = linksToHookUp.split(",");
    for (var i = 0; i < links.length; i++) {
        if (document.getElementById(links[i])) {
            jQuery("#" + links[i]).click(redirectY);
        }
    }
}
/* Reset attribute search fields */
function resetSearch() {
    resetSearch("sidebarSearch")
}
/* Reset attribute search fields */

function resetSearch(nameOfFormToReset) {
    var myForm = document.getElementById(nameOfFormToReset);
    if (!myForm || !myForm.reset || !myForm.elements)
        return;

    myForm.reset();

    var arrElems = myForm.elements;
    if (!arrElems)
        return;

    var firstRadioElement = true;

    //  Reset Autocomplete dropdown lists
    $(".chosen-select").val('').trigger("chosen:updated");

    var removeSumoSelectedClass = function (arrElem, ulElement, isMultiSelect) {
        for (var k = 0; k < ulElement.children.length; k++) {
            ulElement.children[k].classList.remove('selected');
            ulElement.children[k].removeAttribute("selected");

            if (arrElem.sumo.selAll === undefined) {
                arrElem.parentElement.children[1].firstChild.innerText = 'Any ' + arrElem.getAttribute("data-attributename");
            }
        }

        if (!isMultiSelect) {

            if (ulElement.children[0] !== undefined) {
                ulElement.children[0].classList.add('selected');
                arrElem.parentElement.children[1].firstChild.innerText = arrElem.options[0].innerText;
            }
            else {
                arrElem.parentElement.children[1].firstChild.innerText = arrElem.options[0].innerText;
            }
        }
    };

    // Reset all input fields    
    for (var i = 0; i < arrElems.length; i++) {
        var arrElem = arrElems[i];

        switch (arrElem.type.toLowerCase()) {
        case "text":
        case "password":
        case "textarea":
            arrElem.value = "";
            break;
        case "radio":
            // Set the first radio button to be selected.
            if (firstRadioElement) {
                arrElem.selected = true;
                arrElem.checked = true;
                firstRadioElement = false;
            } else {
                arrElem.selected = false;
                arrElem.checked = false;
            }
            break;
        case "checkbox":
            arrElem.selected = false;
            arrElem.checked = false;
            break;
        case "select-multiple":
                //  To reset sumoselect controller
                if (arrElem.sumo !== undefined) {
                    arrElem.sumo.unSelectAll();

                    var options = arrElem.parentElement.lastChild.children[1];
                    if (!options.outerHTML.includes("ul")) {
                        options = arrElem.parentElement.firstChild;
                    }
                    removeSumoSelectedClass(arrElem, options, true);
                    
                }
                arrElem.selectedIndex = -1;
                break;
        case "select-one":
                //  To reset sumoselect controller
                if (arrElem.sumo !== undefined) {
                    arrElem.sumo.selectItem(0);

                    var childElement = arrElem.parentElement.lastChild.firstChild;
                    removeSumoSelectedClass(arrElem, childElement, false);
                }
                arrElem.selectedIndex = 0;
            break;
        default:
                arrElem.selectedIndex = 0;
            break;
        }

        $(arrElem).change();
    }
}

(function ($) {

    //code for numbers on key pad and keyboard tab backspace and delete
    var numberKeyCodesList = [46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8, 9, 39, 37, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];

    $('input.positive-numbers-only').live("keydown",function(event){
        var code = event.keyCode ? event.keyCode :event.which;
        if($.inArray(code, numberKeyCodesList) === -1)
        {
            event.preventDefault();
        }
    });
    
    //More thorough check than the above - filters out the shift-values for number keys.
    $('input.positive-whole-numbers-only-no-symbols').live("keydown", function (e) {
        // Allow: backspace, delete, tab, escape, and enter
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
            // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
            // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });

    // Using the classes below, allowed keys can be additive. e.g. class='positive-numbers-ok decimal-point-ok do-key-check'
    // The 'do-check' is always required.
    var okKeyCodesList = [];
    var okKeyCodesWithShiftList = [];
    var keyCode = -1;

    // number keys, keypad numbers
    var numberKeyCodes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
    // backspace, tab, delete, arrow keys x 4, escape and enter, home, end.
    var navigationKeyCodes = [8, 9, 46, 37, 38, 39, 40, 27, 13, 35, 36];

    $('input.positive-numbers-ok').live("keydown", function (event) {
        $.merge(okKeyCodesList, numberKeyCodes);
    });

    $('input.decimal-point-ok').live("keydown", function (event) {
        okKeyCodesList.push(110);
    });

    $('input.plus-symbol-ok').live("keydown", function (event) {
        okKeyCodesList.push(107);
        okKeyCodesWithShiftList.push(187);
    });

    $('input.do-key-check').live("keydown", function (event) {
        keyCode = event.keyCode ? event.keyCode : event.which;
        checkKey(keyCode);
    });

    var checkKey = function(code) {
        // Always allow the navigation keys.
        $.merge(okKeyCodesList, navigationKeyCodes);

        var okKey = false;

        if (!event.shiftKey) {
            if ($.inArray(code, okKeyCodesList) >= 0) {
                okKey = true;
            }
        } else {
            if ($.inArray(code, okKeyCodesWithShiftList) >= 0) {
                okKey = true;
            }
        }

        // Allow: Ctrl+A
        if (keyCode == 65 && event.ctrlKey === true) okKey = true;

        // Allow: Ctrl+Z
        if (keyCode == 90 && event.ctrlKey === true) okKey = true;

        if (!okKey) {
            event.preventDefault();
        }

        okKeyCodesList = [];
        okKeyCodesWithShiftList = [];
        keyCode = -1;
    };

})(jQuery);;
/* Some convenience functions for adding dates and times. */

/* Date extensions 
**********************/

Date.prototype.add = function(milliseconds) {
    var newdate = new Date();
    newdate.setTime(this.getTime() + milliseconds);
    return newdate;
}

Date.prototype.subtract = function(milliseconds) {
    var newdate = new Date();
    newdate.setTime(this.getTime() - milliseconds);
    return newdate;
}

// 12am midnight
Date.prototype.startOfDay = function() {
    return new Date(this.getFullYear(), this.getMonth(), this.getDate());
}

// 1 millisecond before midnight.
Date.prototype.endOfDay = function() {
    var sod = this.startOfDay();
    return sod.add((1).day()).subtract(1);
}

Date.shortMonthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
Date.shortDayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

/* Number extensions
**********************/

Number.prototype.seconds = function() { return this * 1000 }
Number.prototype.second = function() { return this.seconds() }

Number.prototype.minutes = function() { return this * (60).seconds() }
Number.prototype.minute = function() { return this.minutes() }

Number.prototype.hours = function() { return this * (60).minutes() }
Number.prototype.hour = function() { return this.hours() }

Number.prototype.days = function() { return this * (24).hours() }
Number.prototype.day = function() { return this.days() }

Number.prototype.weeks = function() { return this * (7).days() }
Number.prototype.week = function() { return this.weeks() }

Number.prototype.fortnights = function() { return this * (2).weeks() }
Number.prototype.fortnight = function() { return this.fortnites() }

Number.prototype.months = function() { return this * (30).days() }
Number.prototype.month = function() { return this.months() }

Number.prototype.years = function() { return this * (365.25).days() }
Number.prototype.year = function() { return this.years() }

Number.prototype.from = function(date) { return date.add(this) }
Number.prototype.fromNow = function() { return this.from(new Date()) }

Number.prototype.before = function(date) { return date.subtract(this) }
Number.prototype.ago = function() { return this.before(new Date()) }

var currentWidth = 0;
TradeMe.init = function () {

    //set up global region arrays
    niRegions = new Array(0);
    siRegions = new Array(0);

    //global indicator about regions
    use_gs_regions = false;


    //  lower region chooser link
    var otherRegionChooser = document.getElementById("browseRegionLink");
    if (otherRegionChooser) {
        otherRegionChooser.onclick = function (e) {
            return TradeMe.toggleLowerRegionChooser(e, otherRegionChooser);
        };
    }

    //  att region chooser link
    $('a[name=attRegionLink]').each(function() {
        $(this).click(function (e) {
            return TradeMe.toggleAttRegionChooser(e, $(this));
        });
    });

    //	some browser checks - we need all these methods to work or else ka-blam
    if (!document.getElementById || !document.getElementsByName || !document.createElement || !TradeMe.init.apply) {
        return;
    }

};

 ;
// Determine the API URL ASAP so other parts of the page can use it

var TradeMeApi;
TradeMe.initApi = function (callback) {
    document.domain = "trademe.co.nz";
    var scheme = location.protocol;

    var $iframe = $("<iframe id='tmApiHookFrame' width='0' height='0' />");
    $iframe.appendTo("body");
    $iframe.load(function() { callback(this); });
    $iframe.attr("src", scheme + "//" + location.host + "/API/Hook.aspx");

    TradeMeApi = $iframe[0].contentWindow;
};

//	default focus to search box. could improve this to only focus if no other form element already has focus
TradeMe.setSearchFocus = function() {
    jQuery("#searchString").focus();
};

TradeMe.regionChooserBuild = function () {
    var rptpathInputs;
    var rptpath;

    rptpathInputs = $('input[name=rptpath]');
    if (rptpathInputs.length > 0) rptpath = rptpathInputs[0];

    //the region list for Services and BFS needs to be from gs_region
    if (rptpath != null && rptpath.value.length >= 5) {
        if (rptpath.value.substring(0, 5) === '9334-' || (rptpath.value.length >= 6 && rptpath.value.substring(0, 6) === '10-36-')) {
            //set the gs region indicator
            use_gs_regions = true;
            //disable the link on the change region button
            var browseRegionLink = document.getElementById("browseRegionLink");
            if (browseRegionLink != null) {
                document.getElementById("browseRegionLink").href = "javascript:void(0);";
            };
        };
    };

    //	create the div if not done
    var regionChooser = document.createElement("div");
    regionChooser.id = "RegionChooser";
    regionChooser.className = "region-chooser";

    //change some attributes depending on whether or not we're using user or GS regions
    if (!use_gs_regions) {
        regionChooser.style.background = "transparent url(/Images/3/Common/RegionBox.png) no-repeat bottom right";
    }
    else {

        regionChooser.style.background = "transparent url(/Images/3/Common/RegionBox3.png) no-repeat bottom right";
        regionChooser.style.top = "237px";
        regionChooser.style.height = "249px";
    }

    var closeLink = document.createElement("a");
    closeLink.id = "RegionChooserCloseButton";
    closeLink.href = "#";
    closeLink.className = 'region-chooser-close-button spriteButton'

    closeLink.innerHTML = "Close";

    jQuery(closeLink).click(function(e) { return TradeMe.regionChooserToggle(e); });

    var topDiv = document.createElement("div");
    topDiv.appendChild(closeLink);

    var label = document.createElement("strong");

    var regionTogglerLabel = "Change my region:";

    if (use_gs_regions) {
        regionTogglerLabel = "Change region:";
    }

    label.appendChild(document.createTextNode(regionTogglerLabel));

    topDiv.appendChild(label);

    var innerDiv = document.createElement("div");
    innerDiv.className = "regionInner";

    innerDiv.appendChild(topDiv);

    //build the list of appropriate regions
    TradeMe.buildRegionArrays();

    // get the base URI
    var baseUri = jQuery(".search-bar .ChangeRegionLink").attr("href");
    baseUri = baseUri.substr(baseUri.indexOf("=") + 1);

    var niList = document.createElement("ul");
    niList.id = "NorthIslandRegions";

    TradeMe.createRegions(niRegions, niList, baseUri);

    var siList = document.createElement("ul");
    siList.id = "SouthIslandRegions";

    TradeMe.createRegions(siRegions, siList, baseUri);

    innerDiv.appendChild(niList);
    innerDiv.appendChild(siList);

    regionChooser.appendChild(innerDiv);

    //  need an iframe to stop drop down boxes displaying in front in IE
    if (document.body.filters) {

        var ieIFrame = document.createElement("iframe");
        ieIFrame.id = "RegionChooserIFrame";

        //  needed for secure sites.
        ieIFrame.src = "javascript:'<html></html>'";
        document.body.appendChild(ieIFrame);

        if (use_gs_regions) {
            document.getElementById("RegionChooserIFrame").style.height = "224px";
        }

    }

    document.body.appendChild(regionChooser);

    return true;

};

TradeMe.buildRegionArrays = function() {


    if (use_gs_regions) {


        niRegions = new Array(
    	    9, 1, 14, 2, 4, 5, 12, 6, 15
	    );

        siRegions = new Array(
	        8, 7, 16, 3, 10, 11
	    );

        return true;

    }

    niRegions = new Array(
	    50, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12
	);

    siRegions = new Array(
	    60, 13, 14, 15, 16, 17, 18, 19
	);

    return true;

};

TradeMe.createRegions = function(regions, parentList, base) {

    var validationTokenCookie = new cookieManager.Instance().getCookie("validationToken");

    if (validationTokenCookie) {
        base += "&validationToken=" + validationTokenCookie;
    }

    var baseUrl = "/MyTradeMe/SelectRegionDone.aspx?user_region={0}&url=" + base;

    if (use_gs_regions) {
        baseUrl = "/MyTradeMe/SelectRegionDone.aspx?gsregion={0}&url=" + base;
    };

    for (var i = 0; i < regions.length; i++) {

        var regionLink = document.createElement("a");

        regionLink.href = baseUrl.replace("{0}", regions[i]);
        regionLink.id = "RegionLink" + regions[i];
        regionLink.className = "region";

        if (!use_gs_regions) {
            regionLink.appendChild(
		    document.createTextNode(
			    TradeMe.regionNameById(regions[i])
		    )
		);
        }
        else {
            regionLink.appendChild(
		    document.createTextNode(
			    TradeMe.gsRegionNameById(regions[i])
		    )
		);
        }

        if (regions[i] == 50 || regions[i] == 60) {
            regionLink.style.fontWeight = 'bold';
        }

        var listItem = document.createElement("li");

        listItem.appendChild(regionLink);

        parentList.appendChild(listItem);
    }

};

TradeMe.changeSearchRegion = function(sender, regionChooserClass, regionChooserLabelClass) {

    var newRegionId = sender.id.replace("RegionLink", "");

    $('.' + regionChooserClass).each(function () {
        $(this)
            .val(newRegionId)
            .attr('checked', true);

    });

    $('.' + regionChooserLabelClass).each(function () {
        $(this).html(TradeMe.regionNameById(parseInt(newRegionId)));

    });

    TradeMe.regionChooserToggle();

    return false;
};

TradeMe.toggleAdvRegionChooser = function(e, target) {
    // - creates the magical region chooser and displays it.
    e = e || window.event;
    TradeMe.regionChooserToggle(e, target);

    var urls = jQuery('#RegionChooser a.region');

    for (var i = 0; i < urls.length; i++) {
        urls[i].onclick = function() { try { return TradeMe.changeSearchRegion(this, "search-region-local", "search-region-local-label"); } catch (Error) { } };
    }

    // - stop the link from linking!
    this.preventDefault(e);
    this.stopPropagation(e);
    return false;

};

TradeMe.changeAttSearchRegionHandler = function(e) {
    e = e || window.event;
    var o = e.srcElement || e.target;
    if (o != this) return;

    return TradeMe.changeSearchRegion(o, "searchRegionAttLocal", "searchRegionAttLocalLabel");
};

TradeMe.toggleAttRegionChooser = function(e, target) {

    TradeMe.regionChooserToggle(e, target);

    //  need to post back off of links
    //  so remove this stuff.
    var urls = jQuery('#RegionChooser a.region');

    for (var i = 0; i < urls.length; i++) {
        urls[i].onclick = TradeMe.changeAttSearchRegionHandler;
    }

    return false;

};

TradeMe.toggleLowerRegionChooser = function (e, target) {

    target.blur();

    TradeMe.regionChooserToggle(e, target);

    //  need to post back off of links
    //  so remove this stuff.
    var urls = jQuery('#RegionChooser a.region');

    for (var i = 0; i < urls.length; i++) {
        urls[i].onclick = null;
    }

    return false;
};

TradeMe.stopPropagation = function(L) {
    if (L.stopPropagation) {
        L.stopPropagation();
    } else {
        L.cancelBubble = true;
    }
};

TradeMe.preventDefault = function(L) {
    if (L.preventDefault) {
        L.preventDefault();
    } else {
        L.returnValue = false;
    }
};

TradeMe.regionChooserToggle = function (e, target) {

    if (e && e.type) {
        TradeMe.stopPropagation(e);
        TradeMe.preventDefault(e);
    }

    //	old browser, quit
    if (!document.getElementById || !document.createElement)
        return true;

    var eleId = "RegionChooser";
    var iId = "RegionChooserIFrame";
    var regionChooser = document.getElementById(eleId);
    var regionChooserIFrame = document.getElementById(iId);

    if (!regionChooser) {

        //	first time , try build - fail and quit
        try {
            if (!TradeMe.regionChooserBuild()) {
                return true;
            }
            //	add event to hide region chooser on blur
            jQuery(document).click(function (e) { TradeMe.blurRegionChooserHandler(e); });
        } catch (e) {
            return true;
        }

        regionChooser = document.getElementById(eleId);
        regionChooserIFrame = document.getElementById(iId);

    } else {
        jQuery(regionChooser).toggle();
        if (regionChooserIFrame) {
            jQuery(regionChooserIFrame).toggle();
        }
    }

    //  add some region change handling
    var urls = jQuery('a.region', regionChooser);

    for (var i = 0; i < urls.length; i++) {
        urls[i].onclick = TradeMe.changeRegionHandler;
    }

    if (typeof (target) != 'undefined') {
        var offset = jQuery(target).offset();

        if (regionChooserIFrame) {
            regionChooser.style.left = (offset.left - 10) + "px";
            regionChooser.style.top = (offset.top - 10) + "px";
            regionChooserIFrame.style.left = (offset.left - 10) + "px";
            regionChooserIFrame.style.top = (offset.top - 10) + "px";
        } else {
            regionChooser.style.left = (offset.left - 9) + "px";
            regionChooser.style.top = (offset.top - 9) + "px";
        }
    }
    return false;

};

TradeMe.changeRegionHandler = function(e) {
    e = e || window.event;
    var o = e.srcElement || e.target;
    if (o != this) return;

    return TradeMe.changeRegion(o);
};

TradeMe.changeRegion = function(o) {
    var regions = document.getElementById("regions");
    if (!regions) return false;
    var inputs = regions.getElementsByTagName("input");
    if (!inputs || inputs.length < 2) return false;
    var oldRegionValue = inputs[1].value;
    var newRegionValue = o.id.replace("RegionLink", "");
    if (!newRegionValue || newRegionValue == 0) {
        TradeMe.regionChooserToggle();
        return false;
    }
    if (!oldRegionValue || !oldRegionValue.indexOf) oldRegionValue = 2; //	default to auckland
    if (oldRegionValue.indexOf("&") != -1) {
        //	new cookie with split value.
        var vals = oldRegionValue.split("&");
        var key = "Current=";
        for (var i = 0; i < vals.length; i++) {
            if (vals[i].substr(0, key.length) == key) {
                oldRegionValue = vals[i].substr(key.length, vals[i].length - key.length);
                break;
            }
        }
    }

    TradeMe.setRegion(newRegionValue, oldRegionValue);
    return false;
};

//	called when user clicks link on regionChooser "dropdown"
TradeMe.setRegion = function(regionId, oldRegionId) {
    //	update label
    var regionLabel = document.getElementById("userSearchRegion");
    regionLabel.removeChild(regionLabel.childNodes[0]);
    regionLabel.appendChild(
		document.createTextNode(TradeMe.regionNameById(parseInt(regionId)))
	);
    regionLabel.setAttribute("for", "searchRegion" + regionId);
    //	update the radio box
    var regionValue = document.getElementById("searchRegion" + oldRegionId);
    if (regionValue) {
        regionValue.value = regionId;
        regionValue.checked = true;
        regionValue.id = "searchRegion" + regionId;
    }

    //	closeizzle
    TradeMe.regionChooserToggle();
};

//	translates a regionId to a regionName
TradeMe.regionNameById = function(regionId) {

    switch (regionId) {
        case 1:
            return "Northland";
        case 2:
            return "Auckland";
        case 3:
            return "Waikato";
        case 4:
            return "Bay of Plenty";
        case 5:
            return "Gisborne";
        case 6:
            return "Hawke's Bay";
        case 7:
            return "Taranaki";
        case 8:
            return "Whanganui";
        case 9:
            return "Manawatu";
        case 11:
            return "Wairarapa";
        case 12:
            return "Wellington";
        case 13:
            return "Nelson Bays";
        case 14:
            return "Marlborough";
        case 15:
            return "West Coast";
        case 16:
            return "Canterbury";
        case 17:
            return "Timaru/Oamaru";
        case 18:
            return "Otago";
        case 19:
            return "Southland";
        case 50:
            return "North Island";
        case 60:
            return "South Island";
    }

    //	oh dear
    return "";
};

TradeMe.gsRegionNameById = function(regionId) {

    switch (regionId) {
        case 1:
            return "Auckland";
        case 2:
            return "Bay of Plenty";
        case 3:
            return "Canterbury";
        case 4:
            return "Gisborne";
        case 5:
            return "Hawke's Bay";
        case 6:
            return "Manawatu / Wanganui";
        case 7:
            return "Marlborough";
        case 8:
            return "Nelson / Tasman";
        case 9:
            return "Northland";
        case 10:
            return "Otago";
        case 11:
            return "Southland";
        case 12:
            return "Taranaki";
        case 14:
            return "Waikato";
        case 15:
            return "Wellington";
        case 16:
            return "West Coast";
        case 50:
            return "North Island";
        case 60:
            return "South Island";
    }

    //	oh dear
    return "";
};

TradeMe.blurRegionChooserHandler = function(e) {
    e = e || window.event;

    var o = e.srcElement || e.target;
    if (o)
        return TradeMe.blurRegionChooser(o);
};

//	will hide region chooser if clicked outside of
TradeMe.blurRegionChooser = function(o) {

    var regionChooser = document.getElementById("RegionChooser");

    if (o
	    && o.id != "browseRegionLink"
	    && o.name != "attRegionLink"
	    && o.id != "changeRegionLink"
	    && !TradeMe.isParentOf(regionChooser, o)
	    && regionChooser.style.display != 'none') {

        //	hide
        TradeMe.regionChooserToggle();

    }

    var locationChooser = document.getElementById("LocationChooser");
    if (locationChooser) {

        if (o
	        && o.id != "locationModalLink"
	        && !TradeMe.isParentOf(locationChooser, o)
	        && locationChooser.style.display != 'none') {

            //	hide
            if (typeof TradeMe.Jobs != "undefined")
                TradeMe.Jobs.LocationToggler.locationChooserToggle();
            else if (typeof TradeMe.MotorsLocationFilter != "undefined")
                TradeMe.MotorsLocationFilter.LocationToggler.locationChooserToggle();
        }

    }

    return true;

};

//	returns true if parentToFind contains element childToCheck
TradeMe.isParentOf = function(parentToFind, childToCheck) {

    if (childToCheck.parentNode == parentToFind)
        return true;

    if (childToCheck.parentNode)
        return TradeMe.isParentOf(parentToFind, childToCheck.parentNode);

    return false;
};

// Get a watchlist pixel from DFP for watchlist targeting.
TradeMe.ads = TradeMe.ads || {};
TradeMe.ads.getWatchlistPixel = function (pixelUrl) {
    var pixel = new Image();
    pixel.src = pixelUrl;
};

TradeMe.getParameterByName = function (name) {
    var query = window.location.search.substring(1);
    var params = query.length ? query.split('&') : [];

    var foundKeyValuePair = params
        .map(function (param) {
            var keyValPair = param
                .split('=')
                .map(decodeURIComponent);

            return keyValPair;
        })
        .find(function (keyValPair) {
            var key = keyValPair[0];
            return key === name;
        });

    if (!foundKeyValuePair)
        return '';

    if (!foundKeyValuePair[1])
        return '';

    return foundKeyValuePair[1].replace(/\+/g, ' ');
};;
TradeMe.namespace("favourites", "photos");

/*
*	Favourites AJAX adding stuff.
*/
TradeMe.favourites.Initialize = function() {
    // Asign events to various clicks
    var ab = jQuery(".favButton");
    if (ab.length > 0) {
        ab.click(TradeMe.favourites.AjaxButtonClick)
    }
};

// Save as favourite button clicked
TradeMe.favourites.AjaxButtonClick = function() {
    // Don't click twice
    if (isSaved) {
         return false;
    }
    // Change the style to saving
    var saveButton = $(".favButton");
    if (saveButton.length) {
        saveButton.addClass("loading");
        saveButton.removeClass("btn-yellow");
    }

    // Call the AJAX functions
    return TradeMe.favourites.AjaxCall();
};

// AJAX call
TradeMe.favourites.AjaxCall = function() {
    // If we're not signed in default to to postback
    if (!isSignedIn) {
        TradeMe.favourites.LogIn();
        return false;
    }

    // Set the Querystring parameters
    var saveParamter1 = "";
    if (isDefault1)
        saveParamter1 = "1";

    requestSentTime = new Date();

    // Execute the AJAX statement
    jQuery.ajax({
        type: "GET",
        url: "/API/Ajax/Favourites.aspx",
        data: "ajaxSubmit=true" + queryParameters,
        success: FavouriteSaveSuccess,
        error: FavoriteSaveFail,
        dataType: "json"
    });

    return false;

};

// Change the button to the 'Saved' state
TradeMe.favourites.UpdateButtonToSaved = function () {
    var saveButton = $(".favButton");
    if (saveButton.length) {
        saveButton.hide();
        $("#saved").css('display', 'inline-block');
        $('.saved-message').css('display', 'inline-block');
    }
    isSaved = true;
};

TradeMe.favourites.LogIn = function() {
    // There's an ampersand appended to the end to deal with buggy httpd.ini
    location.href = "/Members/Login.aspx?url=" + escape(TradeMe.favourites.GetDegradedUrl());
};

TradeMe.favourites.GetDegradedUrl = function() {
    var saveParamter1 = "";
    if (isDefault1)
        saveParamter1 = "1";

    return nonAjaxUrl + queryParameters;
};

// Call back function
//	AJAX return method doesn't seem to like this living in a namespace
//	so it isn't there.
function FavouriteSaveSuccess(msg) {
    if (msg.type == 'FavouritesSaveInvalidAttempt') {
        jQuery(".saving").removeClass("saving").addClass("favButton");
        jQuery(".favButton").blur();
        jQuery("#MessageInvalidAttempt").html("&nbsp;&nbsp;" + msg.description).show();
        isSaved = false;

        // Reset button from loading to default
        var saveButton = $(".favButton");
        if (saveButton.length) {
            saveButton.removeClass("loading");
            saveButton.addClass("btn-yellow");
        }

    }
    else {

        var delay = 0;

        // If already saved, then this is a change, and no ui changes need to be applied
        if (isSaved)
            return;

        // Fake a delay if the request comes back to quickly
        if (requestSentTime) {
            delay = new Date().getMilliseconds() - requestSentTime.getMilliseconds() - 1000;

            if (delay < 0)
                delay = delay * -1;
            else
                delay = 0;
        }

        // Wait till at least one second has passed then update UI
        setTimeout(TradeMe.favourites.UpdateButtonToSaved, delay);

        if (msg.option) {
            if (msg.option === '1') {
                if (msg.gtm) {
                    PushSaveCategoryToDataLayer(msg.gtm);
                }
            }
            else if (msg.option === '3' || msg.option === '4') {
                if (msg.gtm) {
                    PushSaveSearchToDataLayer(msg.gtm);
                }
            }
            else if (msg.option == '6') {
                if (msg.gtm) {
                    PushSaveMemberToDataLayer(msg.gtm);
                }
            }
        }
    }
};

function FavoriteSaveFail(XMLHttpRequest, textStatus, errorThrown) {
    location.href = TradeMe.favourites.GetDegradedUrl()
}

function PushSaveSearchToDataLayer(gtm) {
    dataLayer.push({
        'event': gtm.event,
        'ssSearchTerm': gtm.ssSearchTerm,
        'ssCategoryLevel1': gtm.ssCategoryLevel1,
        'ssCategoryLevel2': gtm.ssCategoryLevel2,
        'ssCategoryLevel3': gtm.ssCategoryLevel3,
        'ssCategoryLevel4': gtm.ssCategoryLevel4,
        'ssCategoryLevel5': gtm.ssCategoryLevel5
    });
}

function PushSaveCategoryToDataLayer(gtm) {
    dataLayer.push({
        'event': gtm.event,
        'scSearchTerm': gtm.scSearchTerm,
        'scCategoryLevel1': gtm.scCategoryLevel1,
        'scCategoryLevel2': gtm.scCategoryLevel2,
        'scCategoryLevel3': gtm.scCategoryLevel3,
        'scCategoryLevel4': gtm.scCategoryLevel4,
        'scCategoryLevel5': gtm.scCategoryLevel5
    });
}

function PushSaveMemberToDataLayer(gtm) {
    dataLayer.push({
        'event': gtm.event,
        'memberId': gtm.memberId
    });
}

TradeMe.namespace("Dom");
TradeMe.Dom = {
    getViewportWidth: function() {
        return 1024;
    }
};;


(function($) {
    function FixIE(activeOnly) {
        var offset = 0;

        if (!activeOnly) {
            $("#container button.spriteButton").mouseover(function() {
                $(this).addClass("ieHover");
                offset = $(this).css("height").substring(0, 2);
                $(this).css({ "background-position": "0px -" + offset + "px" });
            });

            $("#container button.spriteButton").mouseout(function() {
                $(this).removeClass("ieHover");
                $(this).removeClass("ieActive");
                $(this).css({ "background-position": "0px 0" })
            });
        }
        $("#container button.spriteButton").mousedown(function() {
            $(this).addClass("mouseDown");
            offset = $(this).css("height").substring(0, 2) * 2;
            $(this).css({ "background-position": "0px -" + offset + "px" });
        });

        $("#container button.spriteButton").mouseup(function() {
            $(this).removeClass("ieHover");
            $(this).removeClass("ieActive");
            $(this).css({ "background-position": "0px 0" });
        });

    }

    function SetupPopupLinks() {
        var wideWindowWith = 650;

        function openPopupWindow(link, windowWidth) {

            var href = link.attr("href");

            link.click(function() {
                var x = 50;
                var y = 50;
                var width = windowWidth;
                var height = 520;
                var winOptions = "location=no,toolbar=yes,menubar=no,resizable=yes,scrollbars=yes,height=" + height + ",width=" + width;
                winOptions += ",left=" + x + ",top=" + y;
                window.open(href, "pop", winOptions);
                return false;
            });
        }


        $("#container a.js-help-popup-wide").each(function () {
            openPopupWindow($(this), wideWindowWith);
        });

        $("#container a.js-help-popup").each(function() {
            var link = $(this);
            var href = link.attr("href");

            link.click(function() {
                var x = 50;
                var y = 50;
                var width = 585;
                var height = 520;
                var winOptions = "location=no,toolbar=yes,menubar=no,resizable=yes,scrollbars=yes,height=" + height + ",width=" + width;
                winOptions += ",left=" + x + ",top=" + y;
                window.open(href, "pop", winOptions);
                return false;
            });
        });

        $("#container a.js-help-popup-small").each(function() {
            var link = $(this);
            var href = link.attr("href");

            link.click(function() {
                var x = 380;
                var y = 230;
                var winOptions = "location=no,toolbar=no,menubar=no,resizeable=no,scrollbars=no,height=230,width=380";
                winOptions += ",left=" + x + ",top=" + y;
                window.open(href, "pop", winOptions);
                return false;
            });
        });
    }

   function fixNavbarStates() {

   }

    $(document).ready(function() {

        if ($.browser.msie && $.browser.version == 6) {
            FixIE(false);
            try {
                // this will help prevent flicker, but is only supported in IE6 SP1+
                // it's undocumented, but used a lot around the place
                document.execCommand("BackgroundImageCache", false, true);
            } catch (err) { }
        } else if ($.browser.msie && $.browser.version == 7) {
            FixIE(true);
        }
        SetupPopupLinks();

        attachTrackingHandler();

    });

    function attachTrackingHandler() {
        $.each(
            $(".tracking-link"),
            function(index, value) {
                var meta = $(value).metadata();
                if (meta != null) {
                    // build up a link
                    var link = "/Link.aspx?";
                    for (var key in meta) {
                        if (meta.hasOwnProperty(key)) {
                            link += key + "=" + meta[key] + "&";
                        }
                    }
                    $(value).mousedown(
                        function(e) {
                            if (e.which == 1 || e.which == 2) {
                                $(this).attr("href", link);
                            }
                        }
                    );
                }
            }
        );
    }

})(jQuery);

function AjaxLoadScript(url) {

    jQuery.ajax({
        type: 'GET',
        url: url,
        cache: true,
        dataType: 'script',
        data: null
    });

}

let ajaxErrorHandlerQuotaLeft = 100;

function AjaxErrorHandler(msg, url, ln) {
    if (msg != 'Error loading script' && ajaxErrorHandlerQuotaLeft > 0) {
        ajaxErrorHandlerQuotaLeft -= 1;

        var data = {
            URI: TradeMe.ServerUri,
            referrer: document.location.pathname,
            error: msg,
            line: ln
        };

        jQuery.ajax({url: '/API/Ajax/LogJavaScriptError.ashx', data: data, cache: false});

    }
}

window.onerror = AjaxErrorHandler;;
TradeMe.namespace("Supports");
TradeMe.Supports.BoxShadow = function() {
    var s = document.body.style;
    return s.WebkitBoxShadow !== undefined || s.MozBoxShadow !== undefined || s.BoxShadow !== undefined;
}
TradeMe.Supports.BorderRadius = function() {
    var s = document.body.style;
    return s.WebkitBorderRadius !== undefined || s.MozBorderRadius !== undefined || s.BorderRadius !== undefined;
}
TradeMe.Supports.RgbaColor = function() {
    if (!('result' in arguments.callee)) {
        var scriptElement = document.getElementsByTagName('script')[0];
        var prevColor = scriptElement.style.color;
        var testColor = 'rgba(0, 0, 0, 0.5)';
        if (prevColor == testColor) {
            arguments.callee.result = true;
        }
        else {
            try {
                scriptElement.style.color = testColor;
            } catch (e) { }
            arguments.callee.result = scriptElement.style.color != prevColor;
            scriptElement.style.color = prevColor;
        }
    }
    return arguments.callee.result;
}
 ;
/** JAvascript for header BEGIN **/


/** General Modal Activate Method Begin **/
function setActive(container) {
    //this method activates the drop down and binds the function to deactivate it when you click somewhere else

    var isActive = false;
    if (container.hasClass('modal-active')) {
        isActive = true;
    }
    $('.activities-buying li').removeClass('modal-active');
    $('.sat-nav li').removeClass('modal-active');
    $('.header-links li').removeClass('modal-active');
    $('.listingCard .titleCol div').removeClass('modal-active');

    if (!isActive) {
        //open the container
        container.addClass('modal-active');
        //if theres a tracking id then track away!
        $(document).click(function test(e) {
            //function to close the dropdown when you click somewhere not in the drop down
            if (container.has(e.target).length === 0) {
                container.removeClass('modal-active');
                $(document).unbind("click", test);
            }
        });
        return true;
    } else {
        container.removeClass('modal-active');
    }

    return false;
}

/** General Modal Activate Method End **/


/** Watchlist and Favourites stuff BEGIN **/

function watchlistFavouriteToggle(id, trackingId) {
    getInfoForWatchlistFavouriteToggle(id, '', false, trackingId);
    return false;
}

function favouriteMiniToggle(id, section, trackingId) {
    $('#FavouritesToggle .toggle-favourites').removeClass('btn-active');
    $('#SiteHeader_SiteTabs_BarOfSearch_' + section + 'FavouritesToggle').addClass('btn-active');
    getInfoForWatchlistFavouriteToggle(id, "favType=" + section, true, trackingId);
}

function watchlistCategoryFilter(id, categoryId, trackingId) {

    if (categoryId != '') {
        categoryId = "cId=" + categoryId;
    }

    getInfoForWatchlistFavouriteToggle(id, categoryId, false, trackingId);
}

function watchlistMiniToggle(id, categoryId) {
    $('#SiteHeader_SiteTabs_BarOfSearch_watchlistDropdownToggleDiv .toggle-watchlist, #SiteTabs_BarOfSearch_watchlistDropdownToggleDiv .toggle-watchlist').removeClass('btn-active');

    if (categoryId != '') {
        categoryId = "cId=" + categoryId;
        $('#SiteHeader_SiteTabs_BarOfSearch_WatchlistDropDownCategoryFilter, #SiteTabs_BarOfSearch_WatchlistDropDownCategoryFilter').addClass('btn-active');
    } else {
        $('#SiteHeader_SiteTabs_BarOfSearch_WatchlistDropDownCategoryAllFilter, #SiteTabs_BarOfSearch_WatchlistDropDownCategoryAllFilter').addClass('btn-active');
    }


    getInfoForWatchlistFavouriteToggle(id, categoryId, true, '');
}




function getInfoForWatchlistFavouriteToggle(id, extraData, isFromMiniToggle, trackingId) {

    var outer = $('#' + id + '-extension-line');
    var urlAddress = "/API/Ajax/WatchlistInfo.aspx";

    if (id.indexOf("Fav") > -1) {
        urlAddress = "/API/Ajax/FavouritesInfo.aspx";
        //favourite loading

        outer.html('<div class="separated-action">' +
                   '<span class="card-counter"><img class="loading-gif" src="/Images/Common/spinner-small.gif" alt="" /></span>' +
                   '<a href="/MyTradeMe/Favourites.aspx" class="nav-action-link">View Favourites<span class="action-link-arrow"></span></a>' +
                   '</div>');

        if (!isFromMiniToggle) {
            $('#FavouritesToggle .toggle-favourites').removeClass('btn-active');
            $('#SiteHeader_SiteTabs_BarOfSearch_searchesFavouritesToggle').addClass('btn-active');
        }

    } else {
        //watchlist loading
        outer.html('<div class="separated-action">' +
                   '<span class="card-counter"><img class="loading-gif" src="/Images/Common/spinner-small.gif" alt="" /></span>' +
                   '<a href="/MyTradeMe/Buy/Watchlist.aspx" class="nav-action-link">View Watchlist<span class="action-link-arrow"></span></a>' +
                   '</div>');


    }

    if (extraData != '') {
        extraData += "&";
    }
    extraData += 'trackingId=' + trackingId;
    //if its already active and from mini-toggle we don't want to do this
    var isAlreadyActive = false;
    var container = $('#' + id);
    if (container.hasClass('modal-active')) {
        isAlreadyActive = true;
    }

    if (!isFromMiniToggle) {
        setActive(container);
    }

    if (!isAlreadyActive || isFromMiniToggle) {
        if (extraData != '') {
            extraData += "&";
        }

        if (trackingId != '') {
            trackNavigateClick(trackingId, true);
        }

        $.ajax({
            type: "GET",
            url: urlAddress,
            data: extraData + "overrideReturnUrl=" + encodeURIComponent(window.location.href),
            dataType: "html",
            cache: false,

            //The function that fires on success of the ajax request
            success: function (data) {

                outer.html(data);
                $('input', outer).placeholder();

                var loginEmail = $('#' + id + '-extension-line .input-large');
                if (loginEmail.length > 0) {

                    loginEmail.focus();
                }


            },
            error: function (msg) {

                //and we didn't get a success status back from the ajax get request :( laaammmmee!
            }
        });
    }

}

/** Watchlist and Favourites stuff END **/

/**Site Tabs Begin**/
function myTradeMeClick(container, trackingId) {

    var changedToActive = setActive(container);

    //just opened the MyTradeMe drop down so lets update the info
    if (changedToActive) {

        // hide while we fetch data - doing here while the AB test is setting initial visibility in page_load
        if ($('#SiteHeader_SiteTabs_BookACourierDropdownPromo').length > 0) {
            $('#SiteHeader_SiteTabs_BookACourierDropdownPromo').hide();
        }

        trackNavigateClick(trackingId);

        //get the mytrade me info...
        $.ajax({
            type: "GET",
            url: "/API/Ajax/MyTradeMeInfo.aspx",
            data: "",
            dataType: "json",
            cache: false,

            //The function that fires on success of the ajax request
            success: function (data) {
                if (data != null) {

                    if (data.success) {

                        //lets set some data
                        $('#watchlistCount').html(data.watchlist);
                        $('#wonCount').html(data.won);
                        $('#lostCount').html(data.lost);
                        $('#sellCurrentCount').html(data.current);
                        $('#soldCount').html(data.sold);
                        $('#unsoldCount').html(data.unsold);

                        $('#username').html(data.memberName);
                        $('#balance').html(data.balance);
                        if (data.advertiseMyProducts) {
                            $('.tradevine-promotion').show();
                        } else {
                            $('.tradevine-promotion').hide();
                        }
                        if (data.hasPayNow) {
                            $('#payNowBalance').html(data.payNowBalance);
                            $('#mytrademe-paynow-wrapper').show();
                        }
                        if (data.isAgent) {

                            //lets set some agent data
                            $('#agentCurrentCount').html(data.liveListings);
                            $('#agentExpiredCount').html(data.unsold);
                            $('#agentListingsThisMonthCount').html(data.listingsThisMonth);
                            $('#agentJobPlanCount').html(data.monthlyPlan);
                            if (data.freeListings > 0) {
                                $('#agentFreeListingsThisMonthCount').html("<br/>&nbsp;(" + data.freeListings + " free listing" + (data.freeListings !== "1" ? "s)" : ")"));
                            };
                            if (data.freeFeatures > 0) {
                                $('#agentFreeFeaturesThisMonthCount').html("<br/>&nbsp;(" + data.freeFeatures + " free feature" + (data.freeFeatures !== "1" ? "s)" : ")"));
                            };
                            $('#agentPropertySubscriptionCount').html = data.currentSubscriptionListings;
                            $('#agentClosingTodayCount').html = data.closingToday;

                            var currentLinkAgent = $("#SiteHeader_SiteTabs_mtmCurrentLinkAgent");
                            var unsoldLinkAgent = $("#SiteHeader_SiteTabs_mtmUnsoldLinkAgent");

                            //both types of agents need this to show
                            $('#agentListingsThisMonth').show();

                            if (data.agentType == 'Job') {
                                //job agent!
                                $('#agent-reporting').show();
                                $('#agent-listings').show();
                                $('.job-agent-info').show();
                                $('#mtm-account-info').show();
                                if (currentLinkAgent != null) {
                                    currentLinkAgent.html("Current Jobs");
                                }

                                if (unsoldLinkAgent != null) {
                                    unsoldLinkAgent.html("Expired Jobs");
                                }

                                $('#mtm-buying').hide();
                                $('#mtm-selling').hide();
                                $('.property-agent-info').hide();

                                //prepaid job agents have special data and showey/hidey-ness
                                if (data.prepaidAgent) {
                                    if (data.hasTierJobPack) {
                                        $('.tier-job-pack').show();
                                        $('.prepaid-agent-info').hide();
                                        $('#goldPrepaidListingsRemaining').html(data.goldPrepaidListingsRemaining);
                                        $('#silverPrepaidListingsRemaining').html(data.silverPrepaidListingsRemaining);
                                        $('#bronzePrepaidListingsRemaining').html(data.bronzePrepaidListingsRemaining);
                                    } else {
                                        $('.tier-job-pack').hide();
                                        $('.prepaid-agent-info').show();
                                        $('#prepaidAgentCount').html(data.prepaidListingsRemaining);
                                        $('#prepaidBrandingAgentCount').html(data.prepaidBrandingRemaining);
                                        $('#prepaidFeaturesAgentCount').html(data.prepaidFeaturesRemaining);
                                        $('#prepaidPromotedListingsAgentCount').text(data.prepaidPromotedListingsRemaining);
                                    }
                                    //mtmCurrentLinkAgent
                                    $('#agentListingsThisMonth').hide();
                                    $('#currentSubscriptions').hide();
                                    $('#monthlyPlan').hide();
                                } else {
                                    $('.tier-job-pack').hide();
                                    $('.prepaid-agent-info').hide();
                                }
                            } else {
                                //property agent!
                                $('#agent-reporting').show();
                                $('#agent-listings').show();
                                $('.property-agent-info').show();
                                $('#mtm-account-info').show();
                                if (currentLinkAgent != null) {
                                    currentLinkAgent.html("Current");
                                }

                                if (unsoldLinkAgent != null) {
                                    unsoldLinkAgent.html("Expired");
                                }

                                $('#mtm-buying').hide();
                                $('#mtm-selling').hide();
                                $('.job-agent-info').hide();

                            }

                        } else {
                            //not an agent!
                            $('#mtm-account-info').show();
                            $('#mtm-buying').show();
                            $('#mtm-selling').show();

                            $('.job-agent-info').hide();
                            $('#agent-reporting').hide();
                            $('#agent-listings').hide();
                            $('.property-agent-info').hide();

                        }

                        if ($('#SiteHeader_SiteTabs_BookACourierDropdownPromo').length > 0) {
                            $('#SiteHeader_SiteTabs_BookACourierDropdownPromo').show();
                        }

                    } else {

                        if (!data.login) {
                            //we're not logged in so lets wipe all the data and show the login myTradeMe drop down state
                            myTradeMeWipeDataAndShowNotLoggedInState(container);
                        } else {

                            //..some kind of error occurred... ?
                            myTradeMeWipeDataAndShowNotLoggedInState(container);
                        }

                    }
                }

            },

            //Define the function that fires on the failure of the ajax request
            error: function (msg) {
                //and we didn't get a success status back from the ajax get request :( laaammmmee!
                myTradeMeWipeDataAndShowNotLoggedInState(container);
            }

        });


        //get the ping info...
        $.ajax({
            type: "GET",
            url: "/API/Ajax/MyPingBalance.aspx",
            data: "",
            dataType: "json",
            cache: false,

            //The function that fires on success of the ajax request
            success: function (data) {
                if (data != null) {

                    if (data.success) {

                        //lets set some data
                        if (data.hasBlueFish) {
                            $('#BlueFishCss').show();

                            if (data.bluefishBalance.charAt(0) === "-") {
                                $('#blueFishBalance').addClass("negative");
                            }
                            $('#blueFishBalance').html(data.bluefishBalance);
                            if (data.bluefishStatusCode === "Unavailable") {
                                $('#bluefishBalanceUrl').attr("src", "/Images/Payments/ping-balance-error.svg");
                                $('#managePing').hide();
                            } else {
                                $('#managePing').addClass("manage-ping-link");
                            }
                            $('#mytrademe-bluefish-wrapper').show();
                        }

                    }
                }
            }
        });
    }
}

function myTradeMeWipeDataAndShowNotLoggedInState(container) {
    container.addClass('logged-out-modal');

    $('#watchlistCount').html('');
    $('#wonCount').html('');
    $('#lostCount').html('');
    $('#sellCurrentCount').html('');
    $('#soldCount').html('');
    $('#unsoldCount').html('');
    $('#username').html('');
    $('#balance').html('');

    $('#agentCurrentCount').html('');
    $('#agentExpiredCount').html('');
    $('#agentListingsThisMonthCount').html('');
    $('#agentJobPlanCount').html('');
    $('#agentPropertySubscriptionCount').html('');
    $('#agentClosingTodayCount').html('');

    $('#mtm-buying').removeClass("size1of3");
    $('#mtm-buying').addClass("size1of2");

    $('#mtm-selling').removeClass("size1of3");
    $('#mtm-selling').addClass("size1of2");

    $('#mtm-buying').removeClass("unit-30-percent");
    $('#mtm-selling').removeClass("unit-33-percent");

    $('#mtm-buying').show();
    $('#mtm-selling').show();

    $('#mtm-account-info').hide();
    $('.job-agent-info').hide();
    $('#agent-reporting').hide();
    $('#agent-listings').hide();
    $('.property-agent-info').hide();

    $('#SiteHeader_SiteTabs_BookACourierDropdownPromo').show();
    $('#SiteHeader_SiteTabs_BookACourierPopup').hide();
}

/** Site Tabs End**/
$(document).ready(function () {

    $('.modal-open').click(function (e) {
        e.preventDefault();
        var link = $(this);
        var container;
        if (link.data().container) {
            container = $('#' + link.data().container);
        } else {
            container = $(this).closest('li');
        }

        if (setActive(container)) {
            //only want to track if we just set it to active
            if (link.data().trackingid) {

                if (typeof (link.data().currentcid) != "undefined" && typeof (link.data().memberid) != "undefined") {

                    trackNavigateClick(link.data().trackingid, true, link.data().currentcid, link.data().memberid);
                } else {

                    trackNavigateClick(link.data().trackingid, true);
                }
            }
        }

    });
    $('.mytrademe-open').click(function (e) {
        e.preventDefault();
        var container = $(this).closest('li');
        var trackingId = '';
        if ($(this).data().trackingid) {
            trackingId = $(this).data().trackingid;
        }
        myTradeMeClick(container, trackingId);
    });

    $('.sell-open').click(function (e) {
        e.preventDefault();

        //Avoid ajax call when closing sell drop down modal
        if ($(".sell.modal-active").length === 0) {
            return true;
        }

        var originalDescription = $('#successFeeDescription');
        var discountDescription = $('#successFeeDiscountDescription');
        var discountContainer = $('.success-fee-discount-message');

        if (originalDescription.length === 0 ||
            discountDescription.length === 0 ||
            discountContainer.length === 0) {
            return true;
        }

        showLoyaltyListingSellingBanner();

        $.ajax({
            type: "GET",
            url: "/API/Ajax/Discounts/GetSuccessFeeDiscountBanner.ashx",
            dataType: "json",
            cache: false,
            timeout: 1000,

            success: function (json, textStatus, xhr) {

                if (xhr.status === 200 && json &&
                    json.discountDescription &&
                    json.discountDescription.length > 0) {

                    originalDescription.hide();
                    discountDescription.html(json.discountDescription);
                    discountContainer.css('display', 'inline-block');
                    return;
                }

                discountContainer.hide();
                discountDescription.html("");
                originalDescription.css('display', 'inline-block');
            },
            error: function () {
                //Timeout: Don't show banner when it takes longer than 2 seconds to load
                discountContainer.hide();
                discountDescription.html("");
                originalDescription.css('display', 'inline-block');
            }
        });
    });

    $('#FavouritesToggle a').click(function (e) {

        if (window.TradeMe.MemberID === '0') {
            return true;
        }

        e.preventDefault();

        var trackingId = '';
        if ($(this).data().trackingid) {
            trackingId = $(this).data().trackingid;
        }
        watchlistFavouriteToggle('FavouritesToggle', trackingId);
    });

    $('#watchlist-toggle a').click(function (e) {

        if (window.TradeMe.MemberID === '0') {
            return true;
        }

        e.preventDefault();
        var category = $(this).data().category;
        category = category || '';
        var trackingId = '';
        if ($(this).data().trackingid) {
            trackingId = $(this).data().trackingid;
        }
        watchlistCategoryFilter('watchlist-toggle', category, trackingId);
    });

});

//used to track the links that don't go anywhere e.g jobs, property and motors search tabs etc.
function trackNavigateClick(linkTrackId, shouldTrack, currentCategory, memberId) {
    //just adding in this check cuz we've been asked to turn off the majority of tracking
    if (shouldTrack) {
        $.ajax({
            type: "GET",
            url: "/link.aspx",
            data: {
                "i": linkTrackId,
                "currentCid": currentCategory,
                "memberId": memberId,
                "FollowLinkRedirect": false
            },

            success: function () {
            },

            error: function () {
            }
        }); //end .ajax
    }


}

function checkBoxSliderUpdateClass(id) {

    var ie7Or8 = ($.browser.msie && $.browser.version.substr(0, 1) < 9) ? true : false;
    if (ie7Or8) {
        if ($('#' + id).hasClass('old-ie-checked')) {
            $('#' + id).removeClass('old-ie-checked');
        } else {
            $('#' + id).addClass('old-ie-checked');
        }
    }

}

function showLoyaltyListingSellingBanner() {
    $('.loyalty-selling-banner').hide();

    $.ajax({
        type: "GET",
        url: "/API/Ajax/Choice/GetListingSellingBanner.ashx",
        dataType: "json",
        cache: false,
        timeout: 1000,

        success: function(json, textStatus, xhr) {
            if (xhr.status === 200 && json && json.ShowFreeSuccessFeeBanner) {
                $('#SellDropDown').addClass('loyalty-banner-active');
                $('#loyalty-selling-benefit-available-quota').html(json.FreeSuccessFeeRemainingQuota);
                $('.loyalty-selling-banner').show();
            } else {
                $('#SellDropDown').removeClass('loyalty-banner-active');
            }
        }
    });
}
;
/*
* Dropdowns done right
* Depends:
*   jquery
*
* Note: You may notice a bug where if you select the option that is already selected, the button still looks pressed down.  
* This looks trivial to fix, but it really isn't because browsers can handle select element events differently (different actions on the select can swallow different events).  
*
* To enable the dropdown, include the following, replacing "drop-select" with the class of the select element.
*
* $('.drop-select').dropdown();
*
*/

(function ($) {

    var template = '<span class="drop-container">' +
                        '<span class="drop-label">All</span>' +
                        '<span class="drop-arrow"></span>' +
                    '</span>';

    var setLabelTextForSearchSelect = function (label, labelText) {
        if (labelText.toLowerCase().indexOf("categories") >= 0 && labelText.toLowerCase().indexOf("all marketplace categories") === -1) {
            label.html('in ' + labelText.toLowerCase().replace(/\xa0|(\&nbsp;)/g, ' '));
        } else {
            label.html('in <strong>' + labelText.toLowerCase().replace(/\xa0|(\&nbsp;)/g, ' ') + '</strong>');
        }
    };

    var methods = {
        init: function () {
            
            return this.each(function () {

                var self = this,
                    html,
                    width,
                    option,
                    labelText;

                // If the plugin hasn't been initialized yet
                if (!self.initialized) {

                    self.initialized = true;
                    self.select = $(self);
                    self.container = self.select.closest('.drop-container');

                    //Check if we need to add in the label/container html
                    if (self.container.length === 0) {
                        html = $(template);
                        self.select.before(html);
                        self.select.detach().appendTo(html);
                        self.container = self.select.closest('.drop-container');
                    }

                    self.isSearchSelect = self.select.data().searchBar;

                    self.label = $('.drop-label', self.container);
                    self.arrow = $('.drop-arrow', self.container);


                    width = self.select.data().selectWidth;
                    if (width) {
                        self.select.width(width - 1);
                        self.container.width(width - 22);
                    }

                    //set label to first element
                    option = $(':selected', self.select);
                    labelText = '';
                    if (option.length > 0) {
                        labelText = option.html();
                    } else {
                        labelText = $(':first-child', self.select).html();
                    }

                    if (self.isSearchSelect) {
                        if (labelText != undefined) {
                            if (labelText != '' && labelText != ' ') {
                                setLabelTextForSearchSelect(self.label, labelText);
                            } else {
                                self.label.html(labelText.toLowerCase());
                            }
                        }
                    } else {
                        self.label.html(labelText);
                    }

                    methods.bindEvents.call(self);

                }

            });
        },

        reset: function () {
            var self = this;
            self.container = self.closest('.drop-container');
            self.label = $('.drop-label', self.container);
            self.arrow = $('.drop-arrow', self.container);
            self.label.html($(':first-child', self).html());
        },

        bindEvents: function () {

            var self = this;

            self.select.change(function (e) {
                e.stopPropagation();            
                setTimeout(function () {
                    var option = $(':selected', self);
                    methods.removeFocus.call(self);
                    if (self.isSearchSelect) {
                        if (option.html() != '' && option.html() != ' ') {
                            setLabelTextForSearchSelect(self.label, option.html());
                        } else {
                            self.label.html(option.html());
                        }
                    } else {
                        self.label.html(option.html());
                    }

                }, 20);

            });

            self.select.click(function (e) {
                e.stopPropagation();
                methods.addFocus.call(self);
            });

            self.select.focus(function (e) {
                methods.addFocus.call(self);
            });

            self.select.blur(function (e) {
                methods.removeFocus.call(self);
            });
        },

        addFocus: function () {
            var self = this;
            self.container.addClass('focus');
            $(document.body).bind("click.dropdown", function (e) {
                methods.removeFocus.call(self);

            });
        },

        removeFocus: function () {
            var self = this;
            self.container.removeClass('focus');
            $(document.body).unbind("click.dropdown");
        },

        destroy: function () {

            return this.each(function () {

                var $this = $(this);
                $(window).unbind('.dropdown');
                $this.removeData('dropdown');

            });

        }
    };


    $.fn.dropdown = function (method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.dropdown');
        }

    };

})(jQuery); ;
/*
* Placeholder polyfill
* Depends:
*   jquery
*/



(function ($) {
    var i = document.createElement('input');
    var supportsPlaceholders = 'placeholder' in i;
    var placeholderLabel = '<span class="placeholder-label"></span>';
    var placeholderWrapper = '<span class="placeholder-wrapper"></span>';

    var methods = {
        init: function (options) {

            return this.each(function () {

                var self = this;
                var placeholder = $(this).attr('placeholder');
                var hasPlaceholder = $(this).is("[placeholder]");

                // If the plugin hasn't been initialized yet
                if (!self.placeholderInitialized && !supportsPlaceholders && hasPlaceholder) {

                    self.placeholderInitialized = true;
                    //Variables local to the plugin go here
                    var input = $(self);

                    //wrap input and add in placeholder span
                    input.wrap(placeholderWrapper);
                    var wrapper = input.parent();
                    var label = $(placeholderLabel).text(placeholder);
                    wrapper.append(label);
                    label.addClass('hide-placeholder');

                    label.click(function () {
                        input.focus();
                    });

                    //check input isnt already filled then add in the label
                    if (input.val() == "") {
                        label.removeClass('hide-placeholder');
                        input.addClass('placeholdered');
                    }

                    //This is to pickup when a browser has autofilled an input just after pageload
                    setTimeout(function () {
                        if (input.val() != "") {
                            label.addClass('hide-placeholder');
                            input.removeClass('placeholdered');
                        }
                    }, 100);

                    //This is to pickup when the browser has autofilled on user direction
                    if (input.attr('type') == "password") {
                        setInterval(function () {
                            if (input.val() != "") {
                                label.addClass('hide-placeholder');
                                input.removeClass('placeholdered');
                            }
                        }, 250);
                    }


                    input.bind('keydown', function (event) {

                        if (input.hasClass('placeholdered')) {
                            label.addClass('hide-placeholder');
                            input.removeClass('placeholdered');
                        }

                        input.one("keyup", function () {
                            if (input.val() == "" || input.val() == placeholder) {
                                label.removeClass('hide-placeholder');
                                input.addClass('placeholdered');
                            }
                        });

                    });

                    input.bind('focusout blur', function (event) {
                        if (input.val() == "") {
                            label.removeClass('hide-placeholder');
                            input.addClass('placeholdered');
                        }
                    });

                }

            });
        },

        destroy: function () {

            return this.each(function () {

                var $this = $(this);
                $(window).unbind('.placeholder');
                $this.removeData('placeholder');

            });

        }
    };


    $.fn.placeholder = function (method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.placeholder');
        }

    };

})(jQuery);

 ;
/*
* safeSubmit stops double clicking submit buttons possible
* Depends:
*   jquery
*/

(function ($) {

    var methods = {
        init: function (options) {

            return this.each(function () {

                var self = $(this);

                self.form = self.closest('form');

                self.bind('click', function (e) {

                    self.prop("disabled", true);
                    self.html("Submitting...");
                    e.preventDefault();
                    setTimeout(function () {
                        self.form.submit();
                    }, 200);

                });


            });
        },

        destroy: function () {

            return this.each(function () {

                var $this = $(this);
                $(window).unbind('.safeSubmit');
                $this.removeData('safeSubmit');

            });

        }
    };
    
    $.fn.safeSubmit = function (method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.safeSubmit');
        }

    };

})(jQuery);;
/*
* Ubersuggest - combines recent searches, autosuggestions and category suggestions
* Depends:
*   jquery
*
* PLD-799:
*   Introduced html special chars encoding and decoding to prevent js injection.
*/

(function ($) {

    var KEY = {
        UP: 38,
        DOWN: 40,
        DEL: 46,
        TAB: 9,
        RETURN: 13,
        ESC: 27,
        COMMA: 188,
        PAGEUP: 33,
        PAGEDOWN: 34,
        BACKSPACE: 8
    };

    var insuranceSuggestionTerms = [
        "insurance", "health", "life",
        "baby", "house", "income",
        "family", "car", "cover",
        "medical", "contents", "cars for sale",
        "funeral", "mortgage", "emergency",
        "hilux", "jobs", "4wd",
        "property for sale", "trailer", "falcon",
        "corolla", "ranger", "land cruiser",
        "mortgage"
    ];

    var holidayHousesSuggestionTerms = [
        "holi", "bach", "houses", "accom", "short term r", "short term ac"
    ];

    var holidayHousesSuggestionMatchTerms = ["event", "events", "event ", "events ", "trav", "trave", "travel", "travel "];

    var methods = {
        init: function (options) {

            return this.each(function () {

                var self = this;

                // If the plugin hasn't been initialized yet
                if (!self.suggestInitialized) {

                    self.suggestInitialized = true;
                    self.options = $.extend({}, defaults, options);
                    // if highlight is set to false, replace it with a do-nothing function
                    self.options.highlight = self.options.highlight || function (value) { return value; };

                    self.input = $(self);
                    self.theForm = self.input.closest('form');
                    self.formId = $(self.theForm).attr("id");

                    self.hasFocus = 0;

                    methods.setupHiddenInputs.call(self);
                    methods.setupBindings.call(self);

                    self.cache = new Cache(self.options);
                    self.select = new Select(
                        self.options,
                        self.input,
                        function () {
                            methods.selectCurrent.call(self);
                        },
                        {
                            mouseDownOnSelect: false
                        },
                        function () {
                            self.cache.flush();
                        },
                        function () {
                            methods.onChange.call(self, 0, true);
                        }
                    );

                    self.currentAutoSuggestEvenId = 0;
                }
            });
        },

        //Grab the currently selected item from the select object and stick it in the input
        selectCurrent: function () {
            var self = this;

            var selected = self.select.selected();

            if (!selected || selected.length == 0)
                return true;

            var value = decodeEntities(selected.data("ac_data"));
            var categoryLink = selected.data("categoryLink");
            var thirdPartyLink = selected.data("thirdPartyLink");

            trackSuggestionClick(selected);

            if (typeof categoryLink !== 'undefined') {
                self.select.hide();
                methods.stopLoading.call(self);
                // Track the store click in GTM
                var storeMemberId = selected.data("storeMemberId");
                var storeName = selected.data("storeName");
                if (!!storeMemberId) {
                    dataLayer.push({
                        'event': 'storeAutoSuggestClick',
                        'storeMemberId': storeMemberId,
                        'storeName': storeName,
                        'referenceEventId': self.currentAutoSuggestEvenId
                    });
                }
                window.location = categoryLink;
                return false;
            } else if (typeof thirdPartyLink !== 'undefined') {
                self.select.hide();
                methods.stopLoading.call(self);
                window.open(thirdPartyLink, '_blank');
                return false;
            } else {

                // if this is an autosuggestion with a category, set up so right things go into the querystring
                if (selected.data("categoryId")) {

                    var $searchTypeSelect = $('#SearchType');
                    var categoryId = selected.data("categoryId");
                    var categoryName = selected.data("categoryName");
                    var rptpath = selected.data("rptpath");

                    // if the category is different, record the suggested category
                    if ($searchTypeSelect.val() !== categoryId) {
                        self.suggestedCategory.val(categoryId);
                    }

                    // set the categoryId in the SearchType select
                    $searchTypeSelect[0].add(new Option(categoryName, categoryId));
                    $searchTypeSelect.val(categoryId);
                    $searchTypeSelect.change();

                    //set the correct rptPath in hidden field
                    $('#topBarRptPath').val(rptpath);

                }

                self.previousValue = value;

                //ensure caret position is set properly in IE
                if (document.selection) {
                    self.input.val('');
                    self.input.focus();
                    var sel = document.selection.createRange();
                    sel.text = value;
                } else {
                    self.input.val(value);
                }

                self.select.hide();
                methods.stopLoading.call(self);
                return true;
            }

        },


        //Handler for when a keypress happens in the text box, responsible for:
        //hiding the suggestion box when the input is empty or requesting new suggestions
        //when the user has entered new characters
        onChange: function () {
            var self = this;

            var currentValue = self.input.val();
            self.input.data("currentValue", currentValue);

            self.select.toTop();
            self.previousValue = currentValue;

            if (currentValue.length == 0) {
                self.suggested.val("0");
            }

            if (currentValue.length >= self.options.minChars) {
                self.input.addClass(self.options.loadingClass);
                methods.makeRequest.call(self, currentValue);
            } else {
                methods.stopLoading.call(self);
                self.select.hide();
            }
        },

        hideResults: function (waitTime) {
            var self = this;
            clearTimeout(self.timeout);
            self.timeout = setTimeout(function () {
                self.select.hide();
                methods.stopLoading.call(self);
            }, waitTime ? waitTime : 200);
        },

        receiveData: function (q, data) {
            var self = this;
            if ((data.autoSuggestions && data.autoSuggestions.length)
                || (data.recentSearches && data.recentSearches.length)
                || (data.categorySuggestions && data.categorySuggestions.length)
                || (data.storeSuggestions && data.storeSuggestions.length)
                && self.hasFocus) {
                methods.stopLoading.call(self);
                self.select.display(q, data);
                self.select.show();
            } else {
                self.select.hide();
                methods.stopLoading.call(self);
            }
        },

        mapData: function (data) {

            encodeReceivedData(data);

            var self = this;
            var mapped = {
                recentSearches: data.RecentSearches,
                autoSuggestions: data.AutoSuggestions,
                categorySuggestions: data.CategorySuggestions,
                storeSuggestions: data.StoreSuggestions
            };
            return mapped;
        },

        makeRequest: function (term) {
            var self = this;

            term = term.toLowerCase();
            var data = self.cache.load(term);

            // recieve the cached data
            if (data) {
                methods.receiveData.call(self, term, data);

                // Set current auto suggestions event ID
                self.currentAutoSuggestEvenId = getEventIdBySearchTerm(term, data);
            } else {

                var extraParams = {
                    timestamp: +new Date()
                };

                $.each(self.options.extraParams, function (key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                if (typeof extraParams.cid !== 'undefined' && isNaN(extraParams.cid) && extraParams.cid != 'all') {
                    //Cant get sensible suggestions when we don't know the category
                } else {
                    $.ajax({
                        // try to leverage ajaxQueue plugin to abort previous requests
                        mode: "abort",
                        // limit abortion to this input
                        port: "ubersuggest" + self.input[0].name,
                        dataType: self.options.dataType,
                        url: self.options.url,
                        data: $.extend({
                            q: term,
                            limit: self.options.max
                        }, extraParams),
                        success: function (suggestData) {
                            var mappedData = methods.mapData.call(self, suggestData.data);
                            var searchTerm = term.toLowerCase();

                            // check if any matches for an insurance related search term
                            var isSearchTermInsurance = false;
                            for (var i = 0; i < insuranceSuggestionTerms.length; i++) {
                                if (term.indexOf(insuranceSuggestionTerms[i]) >= 0) {
                                    isSearchTermInsurance = true;
                                    break;
                                }
                            }

                            // check to see if it matches a result in auto-suggestions
                            var isInsuranceInAutoSuggestionResult = false;
                            if (!isSearchTermInsurance && mappedData.autoSuggestions !== undefined) {
                                for (var i = 0; i < mappedData.autoSuggestions.length; i++) {
                                    if (mappedData.autoSuggestions[i].SearchTerm.toLowerCase() === "insurance") {
                                        isInsuranceInAutoSuggestionResult = true;
                                        break;
                                    }
                                }
                            }

                            var isSearchTermHolidayHouses = false;
                            for (var z = 0; z < holidayHousesSuggestionTerms.length; z++) {
                                if (searchTerm.indexOf(holidayHousesSuggestionTerms[z]) !== -1) {
                                    isSearchTermHolidayHouses = true;
                                    break;
                                }
                            }

                            if (!isSearchTermHolidayHouses) {
                                for (var k = 0; k < holidayHousesSuggestionMatchTerms.length; k++) {
                                    if (searchTerm === holidayHousesSuggestionMatchTerms[k]) {
                                        isSearchTermHolidayHouses = true;
                                        break;
                                    }
                                }
                            }

                            if (isSearchTermHolidayHouses) {
                                mappedData["holidayHousesSuggestions"] = [
                                    { Name: "Holiday Houses", Url: "https://www.holidayhouses.co.nz/", Term: term }
                                ];
                            }

                            var memberId = 0;
                            if (typeof window.TradeMe !== 'undefined' && typeof window.TradeMe.MemberID !== 'undefined') {
                                memberId = window.TradeMe.MemberID;
                            }

                            // add insurance suggestions
                            if (isInsuranceInAutoSuggestionResult || isSearchTermInsurance) {
                                mappedData["lifedirectSuggestions"] = [
                                    { Name: "Life Insurance", Url: "https://www.lifedirect.co.nz/life-insurance?utm_source=trademe&utm_campaign=search&utm_medium=suggestions&utm_content=life&utm_term=" + term },
                                    { Name: "Health Insurance", Url: "https://www.lifedirect.co.nz/health-insurance?utm_source=trademe&utm_campaign=search&utm_medium=suggestions&utm_content=health&utm_term=" + term },
                                    { Name: "Income Protection", Url: "https://www.lifedirect.co.nz/income-protection?utm_source=trademe&utm_campaign=search&utm_medium=suggestions&utm_content=income&utm_term=" + term }
                                ];
                                mappedData["tmiSuggestions"] = [
                                    { Name: "Car Insurance", Url: "https://www.trademeinsurance.co.nz/car-insurance?utm_source=trademe&utm_campaign=search&utm_medium=suggestions&utm_content=car&utm_term=" + term + (memberId > 0 ? "&tm_mid=" + memberId : "") },
                                    { Name: "House Insurance", Url: "https://www.trademeinsurance.co.nz/house-insurance?utm_source=trademe&utm_campaign=search&utm_medium=suggestions&utm_content=house&utm_term=" + term + (memberId > 0 ? "&tm_mid=" + memberId : "") },
                                    { Name: "Contents Insurance", Url: "https://www.trademeinsurance.co.nz/contents-insurance?utm_source=trademe&utm_campaign=search&utm_medium=suggestions&utm_content=contents&utm_term=" + term + (memberId > 0 ? "&tm_mid=" + memberId : "") }
                                ];
                            }

                            self.cache.add(term, mappedData, suggestData.gtm);
                            methods.receiveData.call(self, term, mappedData);

                            // Push search suggestions to GTM data layer
                            if (term.length >= 1) {
                                pushSearchSuggestionsToDataLayer(suggestData.gtm,
                                    isInsuranceInAutoSuggestionResult || isSearchTermInsurance,
                                    isSearchTermHolidayHouses);

                                // Set current auto suggestions event ID
                                self.currentAutoSuggestEvenId = getEventIdBySearchTerm(term);
                            }
                        }
                    });
                }
            }
        },

        stopLoading: function () {
            var self = this;
            self.input.removeClass(self.options.loadingClass);
        },

        //Creates the hidden inputs that let us track how many characters in the submitted
        //Search term were suggested by us rather than typed by the user, also lets us track
        //What type of help was provided i.e. recent search suggestion vs autosuggest suggestion vs autosuggest category suggestion
        setupHiddenInputs: function () {
            var self = this;

            self.input.data("keypressesId", self.formId + '_keypresses');
            self.input.data("suggestedId", self.formId + '_suggested');
            self.input.data("suggestedCategoryId", self.formId + '_suggestedCategory');

            self.theForm.append('<input id="' + self.formId + '_keypresses" name="' + self.formId + '_keypresses" type="hidden" value="0" />');
            self.theForm.append('<input id="' + self.formId + '_suggested" name="' + self.formId + '_suggested" type="hidden" value="0" />');
            self.theForm.append('<input id="' + self.formId + '_suggestedCategory" name="' + self.formId + '_suggestedCategory" type="hidden" value="" />');

            self.keypresses = $('#' + self.input.data("keypressesId"));
            self.suggested = $('#' + self.input.data("suggestedId"));
            self.suggestedCategory = $('#' + self.input.data("suggestedCategoryId"));
        },


        setupBindings: function () {
            var self = this;

            // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
            self.input.bind(($.browser.opera ? "keypress" : "keydown") + ".ubersuggest", function (event) {
                // track last key pressed
                self.lastKeyPressCode = event.keyCode;
                if (self.hasFocus < 1) {
                    self.hasFocus = 1;
                }
                switch (event.keyCode) {

                    case KEY.UP:
                        event.preventDefault();
                        //if suggest box is already visible, move the selection up a row
                        //otherwise show the suggestion box using whatever term is in the input
                        if (self.select.visible()) {
                            self.select.prev();
                        } else {
                            methods.onChange.call(self, 0, true);
                        }
                        break;

                    case KEY.DOWN:
                        event.preventDefault();

                        //If the suggest box is visible , move selection down a row
                        //otherwise show the suggestion box using whatever term is in the input
                        if (self.select.visible()) {
                            self.select.next();
                        } else {
                            methods.onChange.call(self, 0, true);
                        }
                        break;

                    case KEY.TAB:
                    case KEY.RETURN:
                        //TAB or return populate the input with whatever term is currently highlighted
                        //If preventEnterSubmit is true we don't automatically submit the form
                        //this only makes sense when this is true: self.select.visible().
                        //When select dropdown is invisible, the input textbox should have default behavior
                        if (self.select.visible()) {
                            if (!methods.selectCurrent.call(self) || self.options.preventEnterSubmit) {
                                // stop default to prevent a form submit, Opera needs special handling
                                event.preventDefault();
                                self.blockSubmit = true;
                                return false;
                            }
                        }

                        break;

                    case KEY.ESC:
                        //Escape closes the suggest box
                        self.select.hide();
                        break;

                    default:

                        //This is the case that handles general keypresses, to prevent lots of redundant requests being
                        //fired when someone is typing fast we set a timeout so that keypresses that are close together
                        //will only generate requests on the last press
                        var presses = parseInt(self.keypresses.val());
                        clearTimeout(self.timeout);

                        self.timeout = setTimeout(function () {
                            methods.onChange.call(self);
                        }, self.options.delay);

                        self.keypresses.val(presses + 1);

                        break;
                }
            }).focus(function () {
                // track whether the field has focus, we shouldn't process any
                // results if the field no longer has focus
                self.hasFocus++;
            }).blur(function () {
                self.hasFocus = 0;
                //We need to wait 200ms here to make sure that we haven't just momentarily lost focus
                //for example when someone clicks to delete a recent search suggestion
                setTimeout(function () {
                    if (self.hasFocus == 0 && self.input.data('stopHideOnBlur') !== 'true') {
                        methods.hideResults.call(self, 1);
                    }
                }, 200);

            }).click(function () {
                // show select when clicking in a focused field
                if (self.hasFocus++ > 1 && !self.select.visible()) {
                    methods.onChange.call(self, 0, true);
                }
            }).bind("flushCache", function () {
                self.cache.flush();
            });

        },


        destroy: function () {
            return this.each(function () {
                var $this = $(this);
                $(window).unbind('.ubersuggest');
                $this.removeData('ubersuggest');
            });
        }
    };

    var CLASSES = {
        ACTIVE: "ac_over"
    };

    //Object that handles all interaction with the suggestion box
    function Select(options, input, select, config, flushCache, reload) {

        var self = this,
        listItems,
		active = -1,
		term = "",
        suggestions,
        searches,
        categories,
		needsInit = true,
		element,
		list,
		currentTerm,
        elementTwo,
        elementKeywords,
        settingsHtml,
        stores;

        // Create results
        function init() {
            if (!needsInit) {
                return;
            }

            element = $("<div/>")
		    .hide()
		    .addClass(options.resultsClass)
		    .css("position", "absolute")
		    .appendTo(document.body);

            elementTwo = $("<div/>")
                .addClass("search-prompts")
                .appendTo(element);

            elementKeywords = $("<div/>")
                .addClass("filter-keyword")
                .appendTo(elementTwo);

            list = $("<ul/>").appendTo(elementKeywords).mouseover(function (event) {

                if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {

                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    if (!$(target(event)).hasClass('ac_title')) {
                        $(target(event)).addClass(CLASSES.ACTIVE);
                    }

                }

            }).click(function (event) {

                $(target(event)).addClass(CLASSES.ACTIVE);

                select();

                if ($(target(event)).hasClass('ac_category') || $(target(event)).hasClass('ac_title') || $(target(event)).hasClass('ac_thirdparty'))
                    return false;

                input.focus();

                $('#' + $(input).data("suggestedId")).val($(input).val().length);

                if (options.clickToSubmit) {


                    $(input).closest("form").submit();
                }

                return false;
            }).mousedown(function () {
                config.mouseDownOnSelect = true;
            }).mouseup(function () {
                config.mouseDownOnSelect = false;
            });
            if (options.width > 0) {
                element.css("width", options.width - 2);
            } else {
                element.css("width", input.outerWidth() - 2);
            }

            $(window).resize(function () {
                var suggestBox = $('.ac_results');
                var suggestList = $('.filter-keyword ul');
                var offset = options.offsetElement ? options.offsetElement.offset() : $(input).offset();
                if (!!offset && !!input) {
                    var maxHeight = $(window).height() - (offset.top + input[0].offsetHeight + 18);
                    suggestList.css({ maxHeight: maxHeight });
                    suggestBox.css({ left: offset.left });
                }
            });

            needsInit = false;
        }

        function target(event) {
            var ele = event.target;
            while (ele && ele.tagName != "LI") {
                ele = ele.parentNode;
            }
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!ele)
                return [];
            return ele;
        }

        function moveSelect(step) {

            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);

            if (active > -1) {

                var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
                var selectedTerm = activeItem[0];

                //Need to skip over the header items in the suggestions list
                if (activeItem.hasClass('ac_title')) {
                    moveSelect(step);
                    return false;
                }

                if (activeItem.hasClass('ac_category')) {
                    input.val(decodeEntities(input.data("currentValue")));
                } else {
                    input.val(decodeEntities($(selectedTerm).data("untruncated")));
                }

                // set the suggested input with the length of the selected term
                $('#' + input.data("suggestedId")).val($(selectedTerm).data("untruncated").length);

                if (options.scroll) {
                    var offset = 0;
                    listItems.slice(0, active).each(function () {
                        offset += this.offsetHeight;
                    });
                    if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                        list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                    } else if (offset < list.scrollTop()) {
                        list.scrollTop(offset);
                    }
                }
            } else {
                input.val(input.data("currentValue"));
            }

        };

        function movePosition(step) {
            active += step;
            if (active < 0 || active >= listItems.size()) {
                active = -1;
                input.focus();
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
			? options.max
			: available;
        }

        function addListItems(items, isRemovable, sectionName) {
            var maxItems = limitNumberOfItems(items.length);
            for (var i = 0; i < maxItems; i++) {
                if (!items[i])
                    continue;

                var searchTerm = items[i].SearchTerm != null ? items[i].SearchTerm : items[i];
                var formatted = options.formatItem(searchTerm);
                if (formatted === false)
                    continue;
                var highlighted = options.highlight(formatted, encodeEntities(term));

                var li = $("<li/>")
                    .html(highlighted)
                    .addClass(i % 2 == 0 ? "ac_even" : "ac_odd")
                    .data("sectionName", sectionName)
                    .appendTo(list)[0];

                // if this is the first suggestion, also add category suggestions for this term
                if (i == 0 && items[i].SuggestedCategories) {
                    for (var j = 0; j < items[i].SuggestedCategories.length; j++) {
                        var suggestedCategory = items[i].SuggestedCategories[j];

                        var categorysuggest = highlighted + " in " + '<b>' + suggestedCategory.CategoryName + '</b> ';
                        var liCategory = $("<li/>")
                            .html(categorysuggest)
                            .addClass("ac_even")
                            .appendTo(list)[0];

                        var $liCategory = $(liCategory);
                        // change the section name for when we also have the combined keyword and category suggestion
                        var $sectionName = "suggestionsWithCategory";

                        $liCategory.data("untruncated", items[i].SearchTerm);
                        $liCategory.data("ac_data", items[i].SearchTerm);
                        $liCategory.data("categoryName", suggestedCategory.CategoryName);
                        $liCategory.data("categoryId", suggestedCategory.CategoryId);
                        $liCategory.data("rptpath", suggestedCategory.RptPath);
                        $liCategory.data("sectionName", $sectionName);

                        maxItems--;
                    }
                }

                if (isRemovable) {
                    var removeLink = $('<a href="javascript:void(0);" class="ac_remove"><i class="remove-icon"></i></a>');
                    removeLink.click(function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var elementToRemove = $(this).parent();
                        input.focus();
                        $.ajax({
                            dataType: 'json',
                            url: options.actionUrl,
                            data: {
                                action: 'remove',
                                term: elementToRemove.data("ac_data")
                            },
                            success: function (data) {
                                elementToRemove.addClass('ac_removing');
                                setTimeout(function () {
                                    flushCache();
                                    reload();
                                }, 200);
                            }
                        });
                    });
                    $(li).append(removeLink);
                }
                $(li).data("untruncated", searchTerm);
                $(li).data("ac_data", searchTerm);
            }
        }

        function addStoreItems(items) {
            for (var i = 0; i < items.length; i++) {
                if (!items[i])
                    continue;

                var title = '<div><b>' + items[i].StoreName + '</b></div>';
                var description = '<div class="store-description">' + items[i].Description + '</div>';
                var image = '<div class="store-logo"><img src="' + items[i].LogoImageUri + '"></div>';
                var link = items[i].Destination;
                var text = '<div>' + title + description + image + '</div>';
                var li = $("<li/>")
                    .html(text)
                    .addClass("ac_odd")
                    .appendTo(list)[0];

                $(li).addClass('ac_thirdparty stores');
                $(li).data("categoryLink", link);
                $(li).data("storeMemberId", items[i].MemberId);
                $(li).data("storeName", items[i].StoreName);
                $(li).data("untruncated", description);
                $(li).data("ac_data", description);
                $(li).data("sectionName", "stores");
                $(li).addClass('ac_category');
            }
        }

        function addCategoryItems(items) {
            var sessionRegion = null;
            var sessionDistrict = null;

            if (sessionStorage) {
                sessionRegion = window.sessionStorage.getItem("region");
                sessionDistrict = window.sessionStorage.getItem("district");
            }

            var maxItems = limitNumberOfItems(items.length);
            for (var i = 0; i < maxItems; i++) {
                if (!items[i])
                    continue;

                var link = '/Browse/CategoryListings.aspx?cid=' + items[i].Id;

                if (sessionRegion && !isNaN(sessionRegion)) {
                    link += "&user_region=" + sessionRegion;
                    if (sessionDistrict && !isNaN(sessionDistrict)) {
                        link += "&user_district=" + sessionDistrict;
                    }
                }

                var name = '<b>' + items[i].Name + '</b> <br>' + items[i].AncestorsNames.join(' > ');
                var li = $("<li/>")
                    .html(name)
                    .addClass(i % 2 == 0 ? "ac_even" : "ac_odd")
                    .appendTo(list)[0];

                $(li).data("untruncated", name);
                $(li).data("ac_data", name);
                $(li).data("categoryLink", link);
                $(li).data("sectionName", "categorySuggestions");
                $(li).addClass('ac_category');
            }
        }

        function addHolidayhousesItems(items) {

            for (var i = 0; i < items.length; i++) {
                if (!items[i])
                    continue;

                var link = items[i].Url;
                var utm = '?utm_source=trademe&utm_medium=suggestions&utm_term=' + items[i].Term;

                var description = '<b>' + items[i].Name + '</b>';
                var name = description + '<span class="site-link">holidayhouses.co.nz</span>';
                var li = $("<li/>")
                    .html(name)
                    .addClass("ac_odd")
                    .appendTo(list)[0];

                $(li).addClass('ac_thirdparty holidayhouses');
                $(li).data("thirdPartyLink", link + utm);

                $(li).data("untruncated", description);
                $(li).data("ac_data", description);
                $(li).data("sectionName", "holidayhouses");
                $(li).addClass('ac_category');
            }
        }

        function addLifeDirectItems(items) {
            for (var i = 0; i < items.length; i++) {
                if (!items[i])
                    continue;

                var link = items[i].Url;

                var name = '<b>' + items[i].Name + '</b><span class="site-link">lifedirect.co.nz</span><span class="expand-icon"></span>';
                var li = $("<li/>")
                    .html(name)
                    .addClass(i % 2 == 0 ? "ac_even" : "ac_odd")
                    .appendTo(list)[0];

                $(li).addClass('ac_thirdparty');
                $(li).data("thirdPartyLink", link);

                if (i === items.length - 1) {
                    $(li).addClass('last');
                }

                $(li).data("untruncated", items[i].Name);
                $(li).data("ac_data", items[i].Name);
                $(li).data("sectionName", "lifeDirect");
                $(li).addClass('ac_category');
            }
        }

        function addTMIItems(items) {
            for (var i = 0; i < items.length; i++) {
                if (!items[i])
                    continue;

                var link = items[i].Url;

                var name = '<b>' + items[i].Name + '</b><span class="site-link">trademeinsurance.co.nz</span><span class="expand-icon"></span>';
                var li = $("<li/>")
                    .html(name)
                    .addClass(i % 2 == 0 ? "ac_even" : "ac_odd")
                    .appendTo(list)[0];

                $(li).addClass('ac_thirdparty');
                $(li).data("thirdPartyLink", link);

                if (i === items.length - 1) {
                    $(li).addClass('last');
                }

                $(li).data("untruncated", items[i].Name);
                $(li).data("ac_data", items[i].Name);
                $(li).data("sectionName", "insurance");
                $(li).addClass('ac_category');
            }
        }

        function reset() {
            flushCache();
            element && element.hide();
            listItems && listItems.removeClass(CLASSES.ACTIVE);
            active = -1;
            needsInit = true;
            element.remove();
            init();
            input.focus();
        }


        function switchToSettings() {
            input.data('stopHideOnBlur', 'true');

            $(document).one('click', function (e) {
                reset();
                input.data('stopHideOnBlur', 'false');
            });

            elementKeywords.html(settingsHtml);

            //Stop clicks bubbling up and causing ghte settings screen to be closed
            elementKeywords.click(function (e) {
                e.stopPropagation();
            });

            var doneButton = $('.search-settings-done', elementKeywords);
            doneButton.click(function () {
                reset();
                input.data('stopHideOnBlur', 'false');
            });

            var clearButton = $('.search-settings-clear-history', elementKeywords);
            clearButton.one('click', function (e) {
                e.preventDefault();
                e.stopPropagation();
                clearButton.addClass('clearing').addClass('btn-disabled').html('<i></i>');
                var startTime = new Date().getMilliseconds();
                $.ajax({
                    dataType: 'json',
                    url: options.actionUrl,
                    data: {
                        action: 'removeall'
                    },
                    success: function (data) {
                        var endTime = delay = new Date().getMilliseconds();
                        if (endTime - startTime < 100) {
                            setTimeout(function () {
                                clearButton.removeClass('clearing').removeClass('btn-disabled').addClass('cleared').html('<i></i> Cleared').addClass('btn-disabled');
                            }, 200);
                        } else {
                            clearButton.removeClass('clearing').removeClass('btn-disabled').addClass('cleared').html('<i></i> Cleared').addClass('btn-disabled');
                        }
                    }
                });
            });

            var displaySearches = $('#show-searches-input', elementKeywords);
            displaySearches.change(function (e) {

                var isChecked = ($(this).is(':checked'));
                var action = isChecked ? 'turnon' : 'turnoff';

                $.ajax({
                    dataType: 'json',
                    url: options.actionUrl,
                    data: {
                        action: action
                    },
                    success: function () {
                        $.get(options.settingsUrl, function (data) {
                            settingsHtml = data;
                        });
                    }
                });

                var trackingId = isChecked ? 59091 : 59090;
                var memberId = 0;
                if (typeof window.TradeMe !== 'undefined' && typeof window.TradeMe.MemberID !== 'undefined') {
                    memberId = window.TradeMe.MemberID;
                }

                //Track the change
                $.ajax({
                    type: "GET",
                    url: "/link.aspx",
                    data: {
                        i: trackingId,
                        '-memberId': memberId
                    },
                    success: function () {
                    }
                });


            });


        }

        function fillList() {
            list.empty();
            list.parent().find('.ac_settings').remove();
            currentTerm = input.val();
            var firstClass = 'first';
            if (options.showSettings && window.TradeMe.MemberID > 0) {
                var settingsLink = $('<a href="javascript:void(0);" class="ac_settings">Settings<i class="settings-cog"></i></a>');
                settingsLink.click(function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    switchToSettings();
                });
                list.parent().append(settingsLink);
            }

            var hasExactStoreSuggestion = false;
            if (stores && stores.length > 0 && stores.map(function(s) { return s.StoreName.toLowerCase(); }).indexOf(term) !== -1) {
                hasExactStoreSuggestion = true;
            }

            if (hasExactStoreSuggestion) {
                addStoreListItems(true);
                firstClass = '';
            }
            if (searches && searches.length > 0) {
                $("<li/>").html("Recent").appendTo(list)
                    .addClass("ac_title")
                    .addClass(firstClass)
                    .click(function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        input.focus();
                    });
                firstClass = '';
                addListItems(searches, true, "recentSearches");

            }
            if (suggestions && suggestions.length > 0) {
                $("<li/>").html("Suggestions").appendTo(list)
                    .addClass("ac_title")
                    .addClass(firstClass)
                    .click(function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        input.focus();
                    });
                firstClass = '';
                addListItems(suggestions, false, "suggestions");
            }
            if (!hasExactStoreSuggestion) {
                addStoreListItems(false);
            }
            if (categories && categories.length > 0) {
                $("<li/>").html("Categories").appendTo(list)
                    .addClass("ac_title")
                    .addClass(firstClass)
                    .click(function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        input.focus();
                    });
                addCategoryItems(categories);
            }
            if (holidayhouses && holidayhouses.length > 0) {
                $("<li/>").html("Book your next holiday rental <span class='holidayhouses-logo' title='For better places to stay'></span>").appendTo(list)
                    .addClass("ac_title")
                    .addClass(firstClass)
                    .addClass("ac_thirdparty")
                    .click(function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        input.focus();
                    });
                addHolidayhousesItems(holidayhouses);
            }
            if (lifedirect && lifedirect.length > 0) {
                $("<li/>").html("Protect your family <span class='lifedirect-logo' title='Quote, Compare and Apply for insurance on LifeDirect'></span>").appendTo(list)
                    .addClass("ac_title")
                    .addClass(firstClass)
                    .addClass("ac_thirdparty")
                    .click(function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        input.focus();
                    });
                addLifeDirectItems(lifedirect);
            }
            if (tmi && tmi.length > 0) {
                $("<li/>").html("Protect your stuff <span class='tmi-logo' title='Car, House and Contents on Trade Me Insurance'></span>").appendTo(list)
                    .addClass("ac_title")
                    .addClass(firstClass)
                    .addClass("ac_thirdparty")
                    .click(function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        input.focus();
                    });
                addTMIItems(tmi);
            }

            listItems = list.find("li");
            if (options.selectFirst) {
                listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                active = 0;
            }

            // apply bgiframe if available
            if ($.fn.bgiframe)
                element.bgiframe();
        }

        function addStoreListItems(isOnTop) {
            var firstClass = '';
            if (isOnTop) {
                firstClass = 'first';
            }
            if (stores && stores.length > 0) {
                $("<li/>").html("Trade Me Stores").appendTo(list)
                    .addClass("ac_title")
                    .addClass(firstClass)
                    .click(function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        input.focus();
                    });
                addStoreItems(stores);
            }
        }

        return {
            display: function (q, data) {
                init();
                suggestions = data.autoSuggestions;
                term = q;
                searches = data.recentSearches;
                categories = data.categorySuggestions;
                lifedirect = data.lifedirectSuggestions;
                holidayhouses = data.holidayHousesSuggestions;
                tmi = data.tmiSuggestions;
                stores = data.storeSuggestions;
                fillList();
            },
            next: function () {
                moveSelect(1);
            },
            prev: function () {
                if (active == -1) {
                    moveSelect(listItems.size());
                } else {
                    moveSelect(-1);
                }
            },
            hide: function () {
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible: function () {
                return element && element.is(":visible");
            },
            current: function () {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            toTop: function () {
                if (active > -1) {
                    moveSelect(-(active + 1));
                }
            },
            show: function () {
                var offset = options.offsetElement ? options.offsetElement.offset() : $(input).offset();
                element.css({
                    top: offset.top + input[0].offsetHeight + 4,
                    left: offset.left
                }).show();

                if (options.scroll) {
                    list.scrollTop(0);
                    list.css({
                        maxHeight: $(window).height() - (offset.top + input[0].offsetHeight + 18),
                        overflow: 'auto'
                    });
                }
                if (!settingsHtml && options.showSettings) {
                    $.get(options.settingsUrl, function (data) {
                        settingsHtml = data;
                    });
                }
                ellipsizeStoreDescription();
            },
            selected: function () {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected;
                //return selected && selected.length && $(selected[0]).data("ac_data");
            },
            emptyList: function () {
                list && list.empty();
            },
            unbind: function () {
                element && element.remove();
            }
        };
    };

    var defaults = {
        url: "/API/Ajax/Ubersuggestions/Ubersuggestions.ashx",
        actionUrl: "/API/Ajax/Ubersuggestions/UbersuggestionActions.ashx",
        settingsUrl: "/API/Ajax/Ubersuggestions/Settings.aspx",
        extraParams: {
            cid: function () { return $("#SearchType").val(); }
        },
        inputClass: "ac_input",
        resultsClass: "ac_results modal-active-ext",
        loadingClass: "ac_loading",
        minChars: 1,
        delay: 100,
        cacheLength: 100,
        selectFirst: false,
        formatItem: function (term) {
            var formatted = term;
            if (formatted.length > 35) {
                formatted = formatted.substring(0, 35);
                formatted = formatted + "&#8230;";
            }
            return formatted;
        },
        width: 442,
        highlight: function (value, searchTerm) {
            //remove leading spaces
            searchTerm = decodeEntities(searchTerm.replace(/^[\s]{1,}/, ""));
            var escapedTerm = searchTerm.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1");
            // wrap the searched term between <strong/> tags.
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + escapedTerm + ")(?![^<>]*>)(?![^&;]+;)", "i"), "<span class=\"search-term\"><strong>$1</strong></span>");
        },
        scroll: true,
        scrollHeight: 400,
        conditionalElementId: 'SearchType',
        clickToSubmit: true,
        max: 16,
        preventEnterSubmit: false,
        offsetElement: false,
        //whether on the dropdown list, show "settings" link to the right of "suggestions".
        showSettings: true
    };

    function Cache(options) {

        var data = {};
        var length = 0;
        var lastConditional = "";
        if (options.conditionalElementId != '') {
            lastConditional = $("#" + options.conditionalElementId).val();
        }

        function add(q, dataToAdd, gtmData) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = {
                autoSuggestions: dataToAdd.autoSuggestions,
                recentSearches: dataToAdd.recentSearches,
                categorySuggestions: dataToAdd.categorySuggestions,
                lifedirectSuggestions: dataToAdd.lifedirectSuggestions,
                holidayHousesSuggestions: dataToAdd.holidayHousesSuggestions,
                tmiSuggestions: dataToAdd.tmiSuggestions,
                storeSuggestions: dataToAdd.storeSuggestions,
                gtm: gtmData
            };
        };

        function flush() {
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            load: function (q) {
                if (!options.cacheLength || !length)
                    return null;

                if ((options.conditionalElementId == '') || (lastConditional != $("#" + options.conditionalElementId).val())) {
                    flush();
                }
                if (options.conditionalElementId != '') {
                    lastConditional = $("#" + options.conditionalElementId).val();
                }

                if (data[q]) {
                    // if the exact item exists, use it
                    return data[q];
                }
                return null;
            }
        };
    };

    function decodeEntities(encodedString) {
        var textArea = document.createElement('textarea');
        textArea.innerHTML = encodedString;
        return textArea.value;
    }

    function encodeEntities(html) {
        return document.createElement('a').appendChild(
            document.createTextNode(html)).parentNode.innerHTML;
    };

    function encodeReceivedData(data) {

        if (data === undefined)
            return;

        if (data.RecentSearches !== undefined) {
            for (i = 0; i < data.RecentSearches.length; i++) {
                data.RecentSearches[i] = encodeEntities(data.RecentSearches[i]);
            }
        }

        if (data.AutoSuggestions !== undefined) {
            for (i = 0; i < data.AutoSuggestions.length; i++) {
                data.AutoSuggestions[i].SearchTerm = encodeEntities(data.AutoSuggestions[i].SearchTerm);
            }
        }
    }

    function ellipsizeStoreDescription() {
        var storeDescriptions = $(".store-description");
        if (storeDescriptions.length > 0) {
            for (var i = 0; i < storeDescriptions.length; i++) {
                var storeDescription = storeDescriptions[i];
                if (!!storeDescriptions[i]) {
                    var wordArray = storeDescription.innerHTML.split(' ');
                    // 1 pixel deduceted from scrollheight to handle IE rounding issue
                    while (storeDescription.scrollHeight - 1 > storeDescription.offsetHeight) {
                        wordArray.pop();
                        storeDescription.innerHTML = wordArray.join(' ') + '...';
                    }
                }
            }
        }
    }

    // Push the search suggestions event to GTM
    function pushSearchSuggestionsToDataLayer(gtm, insuranceInSearch, holidayHouseInSearch) {
        if (!!gtm) {
            // Clear up previous store suggestions
            resetStoreSuggestions();

            // Build and push new search suggestion event
            var storeSuggestions = [];
            gtm.StoreSuggestions.map(function(x) {
                storeSuggestions.push({
                    'storeMemberId': x.MemberId,
                    'storeName': x.StoreName
                });
            });

            dataLayer.push({
                'event': gtm.EventName,
                'eventId': gtm.EventId,
                'searchTerm': gtm.SearchTerm,
                'hasSearchSuggestions': gtm.HasSearchSuggestions,
                'recentSearchesCount': gtm.RecentSearchesCount,
                'autoSuggestionsCount': gtm.AutoSuggestionsCount,
                'storesSuggestionsCount': gtm.StoresSuggestionsCount,
                'categorySuggestionsCount': gtm.CategorySuggestionsCount,
                'hasHolidayHouses': holidayHouseInSearch,
                'hasLifeDirect': insuranceInSearch,
                'hasTmInsurance': insuranceInSearch,
                'storeSuggestions': storeSuggestions,
                'hasSuggestionsWithCategory': gtm.HasSuggestionsWithCategory,
                'abTestName': gtm.AbTestName,
                'abTestVariant': gtm.AbTestVariant
            });
        }
    }

    function getEventIdBySearchTerm(searchTerm, cacheData) {
        // If its from cached data, reset store suggestions and load from cached gtm data
        if (!!cacheData && !!cacheData.gtm && cacheData.gtm.EventName === 'searchAutoSuggestions' && cacheData.gtm.SearchTerm === searchTerm) {
            var storeSuggestions = [];
            cacheData.gtm.StoreSuggestions.map(function (x) {
                storeSuggestions.push({
                    'storeMemberId': x.MemberId,
                    'storeName': x.StoreName
                });
            });
            resetStoreSuggestions(searchTerm, storeSuggestions);
            return cacheData.gtm.EventId;
        }

        // Otherwise, read it from current event in datalayer
        for (var i = 0; i < dataLayer.length; i++) {
            if (dataLayer[i].hasOwnProperty('event') && dataLayer[i]['event'] === 'searchAutoSuggestions'
                && dataLayer[i].hasOwnProperty('searchTerm') && dataLayer[i]['searchTerm'] === searchTerm) {
                return dataLayer[i]['eventId'];
            }
        }

        return null;
    }

    function resetStoreSuggestions(searchTerm, storeSuggestions) {
        // Clear up previous store suggestions
        // and set correct store suggestions from cache if applicable
        for (var i = 0; i < dataLayer.length; i++) {
            if (dataLayer[i].hasOwnProperty('event') && dataLayer[i]['event'] === 'searchAutoSuggestions') {
                if (dataLayer[i].hasOwnProperty('searchTerm') && dataLayer[i]['searchTerm'] === searchTerm) {
                    dataLayer[i].storeSuggestions = storeSuggestions;
                } else {
                    dataLayer[i].storeSuggestions = [];
                }
            }
        }
    }

    function trackSuggestionClick(selected) {
        var selectedElement = $(selected);

        var index = selectedElement.index();
        var section = selectedElement.data("sectionName");

        // A more general search event
        dataLayer.push({
            'event': 'searchSuggestionClick',
            'searchSuggestionSectionName': section,
            'searchSuggestionPosition': index === -1 ? null : index
        });
    }

    $.fn.ubersuggest = function (method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jquery.ubersuggest');
            return false;
        }
    };

})(jQuery);

;
$(function () {
    $('.SelectAutoSubmit').change(function () {
        $(this).siblings('.SelectLoadingText').show();
        this.form.submit();
    });
});;
/// <minify />

/*
* Autocomplete - jQuery plugin 1.0.2
*
* Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, JÃ¶rn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
* - Further modifications have been made to fit into the trademe codebase by William Berger
*/
; (function ($) {

    $.fn.extend({
        autocomplete: function (urlOrData, options) {
            var isUrl = typeof urlOrData == "string";
            options = $.extend({}, $.Autocompleter.defaults, {
                url: isUrl ? urlOrData : null,
                data: isUrl ? null : urlOrData,
                delay: isUrl ? $.Autocompleter.defaults.delay : 10,
                max: options && !options.scroll ? options.limit : 150
            }, options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function (value) { return value; };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            return this.each(function () {
                new $.Autocompleter(this, options);
            });
        },
        result: function (handler) {
            return this.bind("result", handler);
        },
        search: function (handler) {
            return this.trigger("search", [handler]);
        },
        flushCache: function () {
            return this.trigger("flushCache");
        },
        setOptions: function (options) {
            return this.trigger("setOptions", [options]);
        },
        unautocomplete: function () {
            return this.trigger("unautocomplete");
        }
    });

    $.Autocompleter = function (input, options) {

        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).addClass(options.inputClass);
        var $form = $(input.form);
        var $keypresses;
        var $suggested;
        var timeout;
        var previousValue = "";
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
            mouseDownOnSelect: false
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);

        var blockSubmit;

        if (options.turnOffAuto) {
            $input.attr("autocomplete", "off");
        }

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function () {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        //setup hidden inputs to track number of user keypresses vs suggested
        $(input).data("keypressesId", $form.attr("id") + '_keypresses');
        $(input).data("suggestedId", $form.attr("id") + '_suggested');
        $form.append('<input id="' + $form.attr("id") + '_keypresses" name="' + $form.attr("id") + '_keypresses" type="hidden" value="0" />');
        $form.append('<input id="' + $form.attr("id") + '_suggested" name="' + $form.attr("id") + '_suggested" type="hidden" value="0" />');
        $keypresses = $('#' + $(input).data("keypressesId"));
        $suggested = $('#' + $(input).data("suggestedId"));

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function (event) {
            // track last key pressed
            lastKeyPressCode = event.keyCode;
            if (hasFocus < 1) {
                hasFocus = 1;
            }
            switch (event.keyCode) {

                case KEY.UP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.prev();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.DOWN:
                    event.preventDefault();
                    $(input).data("userClosed", false);
                    if (select.visible()) {
                        select.next();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEUP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageUp();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEDOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageDown();
                    } else {
                        onChange(0, true);
                    }
                    break;

                    // matches also semicolon                                                                                                                                   
                case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
                case KEY.TAB:
                case KEY.RETURN:
                    if (selectCurrent() && options.preventEnterSubmit) {
                        // stop default to prevent a form submit, Opera needs special handling
                        event.preventDefault();
                        blockSubmit = true;
                        if (options.itemSelectedHandler) {
                            options.itemSelectedHandler();
                        }
                        return false;
                    }
                    break;

                case KEY.ESC:
                    select.hide();
                    break;

                default:

                    var presses = parseInt($keypresses.val());
                    clearTimeout(timeout);
                    timeout = setTimeout(function () { onChange(); }, options.delay);
                    $keypresses.val(presses + 1);

                    break;
            }
        }).focus(function () {
            // track whether the field has focus, we shouldn't process any
            // results if the field no longer has focus
            hasFocus++;
        }).blur(function () {
            hasFocus = 0;
            if (!config.mouseDownOnSelect) {
                hideResults();
            }
        }).click(function () {
            // show select when clicking in a focused field
            if (hasFocus++ > 1 && !select.visible()) {
                onChange(0, true);
            }
        }).bind("search", function () {
            // TODO why not just specifying both arguments?
            var fn = (arguments.length > 1) ? arguments[1] : null;
            function findValueCallback(q, data) {
                var result;
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].result.toLowerCase() == q.toLowerCase()) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if (typeof fn == "function") fn(result);
                else $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()), function (i, value) {
                request(value, findValueCallback, findValueCallback);
            });
        }).bind("flushCache", function () {
            cache.flush();
        }).bind("setOptions", function () {
            $.extend(options, arguments[1]);
            // if we've updated the data, repopulate
            if ("data" in arguments[1])
                cache.populate();
        }).bind("unautocomplete", function () {
            select.unbind();
            $input.unbind();
            $(input.form).unbind(".autocomplete");
        });


        function selectCurrent() {
            var selected = select.selected();
            if (!selected)
                return false;

            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var words = trimWords($input.val());
                if (words.length > 1) {
                    v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
                }
                v += options.multipleSeparator;
            }

            //ensure caret position is set properly in IE               
            if (document.selection) {
                $input.val('');
                $input.focus();
                var sel = document.selection.createRange();
                sel.text = v;
            } else {
                $input.val(v);
            }
            hideResultsNow();

            $input.trigger("result", [selected.data, selected.value]);
            $input.trigger("blur");
            return true;
        }

        function onChange(crap, skipPrevCheck) {

            var currentValue = $input.val();
            $(input).data("currentValue", currentValue);

            select.toTop();
            previousValue = currentValue;
            currentValue = lastWord(currentValue);

            if (currentValue.length == 0) {
                $(input).data("userClosed", false);
                $suggested.val("0");
            }

            if (currentValue.length >= options.minChars && !$(input).data("userClosed")) {
                $input.addClass(options.loadingClass);
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value) {
                return [""];
            }
            var words = value.split(options.multipleSeparator);
            var result = [];
            $.each(words, function (i, value) {
                if ($.trim(value))
                    result[i] = $.trim(value);
            });
            return result;
        }

        function lastWord(value) {
            if (!options.multiple)
                return value;
            var words = trimWords(value);
            return words[words.length - 1];
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue) {
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
                // fill in the value (keep the case the user has typed)
                $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                // select the portion of the value not typed by the user (so the next character will erase)
                $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults() {
            clearTimeout(timeout);
            timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
            select.hide();
            clearTimeout(timeout);
            stopLoading();
            if (options.mustMatch) {
                // call search and run callback
                $input.search(
				function (result) {
				    // if no value found, clear the input box
				    if (!result) {
				        if (options.multiple) {
				            var words = trimWords($input.val()).slice(0, -1);
				            $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
				        }
				        else
				            $input.val("");
				    }
				}
			    );
            }
        };

        function receiveData(q, data) {
            if (data && data.length && hasFocus) {
                stopLoading();
                select.display(data, q);
                autoFill(q, data[0].value);
                select.show();

                //resize if needed (except on IE6)
                var $results = $('.ac_results:visible');

            } else {
                hideResultsNow();
            }
        };

        function request(term, success, failure) {
            if (!options.matchCase)
                term = term.toLowerCase();
            var data = cache.load(term);

            // recieve the cached data
            if (data && data.length) {
                success(term, data);
                // if an AJAX url has been supplied, try loading the data now
            } else if ((typeof options.url == "string") && (options.url.length > 0)) {

                var extraParams = {
                    timestamp: +new Date()
                };

                $.each(options.extraParams, function (key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                $.ajax({
                    // try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    // limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    url: options.url,
                    data: $.extend({
                        q: lastWord(term),
                        limit: options.max
                    }, extraParams),
                    success: function (data) {
                        var parsed = options.parse && options.parse(data) || parse(data);
                        cache.add(term, parsed);
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure(term);
            }
        };

        function parse(data) {
            var parsed = [];
            var rows = data.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var row = $.trim(rows[i]);
                if (row) {
                    row = row.split("|");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: options.formatResult && options.formatResult(row, row[0]) || row[0]
                    };
                }
            }
            return parsed;
        };

        function stopLoading() {
            $input.removeClass(options.loadingClass);
        };

    };

    $.Autocompleter.defaults = {
        inputClass: "ac_input",
        resultsClass: "ac_results modal-active-ext",
        loadingClass: "ac_loading",
        minChars: 1,
        delay: 400,
        matchContains: false,
        matchSubset: false,
        matchContains: false,
        cacheLength: 100,
        max: 100,
        mustMatch: false,
        extraParams: {},
        selectFirst: false,
        formatItem: function (row) {
            var formatted = row[0];
            if (formatted.length > 20) {
                formatted = formatted.substring(0, 20);
                formatted = formatted + "&#8230;";
            }
            return formatted;
        },
        formatMatch: null,
        autoFill: false,
        width: 0,
        multiple: false,
        multipleSeparator: ", ",
        highlight: function (value, term) {
            //remove leading spaces
            term = term.replace(/^[\s]{1,}/, "");
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "i"), "<span class=\"search-term\"><strong>$1</strong></span>");

        },
        scroll: true,
        scrollHeight: 280,
        closeElement: '<div class="CloseSuggestions" id="CloseSuggestions"><span>Close suggestions</span></div>',
        conditionalElementId: '',
        preventEnterSubmit: true,
        clickToSubmit: true,
        turnOffAuto: true,
        itemSelectedHandler: null
    };

    $.Autocompleter.Cache = function (options) {

        var data = {};
        var length = 0;
        var lastConditional = "";
        if (options.conditionalElementId != '') {
            lastConditional = $("#" + options.conditionalElementId).val();
        }

        function matchSubset(s, sub) {
            if (!options.matchCase)
                s = s.toLowerCase();
            var i = s.indexOf(sub);
            if (i == -1) return false;
            return i == 0 || options.matchContains;
        };

        function add(q, value) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = value;
        }

        function populate() {
            if (!options.data) return false;
            // track the matches
            var stMatchSets = {},
			nullData = 0;

            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if (!options.url) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];

            // loop through the array and create a lookup structure
            for (var i = 0, ol = options.data.length; i < ol; i++) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

                var value = options.formatMatch(rawValue, i + 1, options.data.length);
                if (value === false)
                    continue;

                var firstChar = value.charAt(0).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[firstChar])
                    stMatchSets[firstChar] = [];

                // if the match is a string
                var row = {
                    value: value,
                    data: rawValue,
                    result: options.formatResult && options.formatResult(rawValue) || value
                };

                // push the current match into the set list
                stMatchSets[firstChar].push(row);

                // keep track of minChars zero items
                if (nullData++ < options.max) {
                    stMatchSets[""].push(row);
                }
            };

            // add the data items to the cache
            $.each(stMatchSets, function (i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush() {
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            load: function (q) {
                if (!options.cacheLength || !length)
                    return null;

                if ((options.conditionalElementId == '') || (lastConditional != $("#" + options.conditionalElementId).val())) {
                    flush();
                }
                if (options.conditionalElementId != '') {
                    lastConditional = $("#" + options.conditionalElementId).val();
                }

                /* 
                * if dealing w/local data and matchContains than we must make sure
                * to loop through all the data collections looking for matches
                */
                if (!options.url && options.matchContains) {
                    // track all matches
                    var csub = [];
                    // loop through all the data grids for matches
                    for (var k in data) {
                        // don't search through the stMatchSets[""] (minChars: 0) cache
                        // this prevents duplicates
                        if (k.length > 0) {
                            var c = data[k];
                            $.each(c, function (i, x) {
                                // if we've got a match, add it to the array
                                if (matchSubset(x.value, q)) {
                                    csub.push(x);
                                }
                            });
                        }
                    }
                    return csub;
                } else if (data[q]) {
                    // if the exact item exists, use it
                    return data[q];

                } else if (options.matchSubset) {
                    for (var i = q.length - 1; i >= options.minChars; i--) {
                        var c = data[q.substr(0, i)];
                        if (c) {
                            var csub = [];
                            $.each(c, function (i, x) {
                                if (matchSubset(x.value, q)) {
                                    csub[csub.length] = x;
                                }
                            });
                            return csub;
                        }
                    }
                }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function (options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list,
		currentTerm;

        // Create results
        function init() {
            if (!needsInit) {
                return;
            }
            element = $("<div/>")
		    .hide()
		    .addClass(options.resultsClass)
		    .css("position", "absolute")
		    .appendTo(document.body);


            elementTwo = $("<div/>")
                .addClass("search-prompts")
                .appendTo(element);



            elementKeywords = $("<div/>")
                .addClass("filter-keyword")
                .appendTo(elementTwo);



            list = $("<ul/>").appendTo(elementKeywords).mouseover(function (event) {

                if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    $(target(event)).addClass(CLASSES.ACTIVE);
                }
            }).click(function (event) {
                $(target(event)).addClass(CLASSES.ACTIVE);
                select();
                // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                input.focus();
                $('#' + $(input).data("suggestedId")).val($(input).val().length);
                if (options.clickToSubmit) {
                    $(input).closest("form").submit();
                } else if (options.itemSelectedHandler) {
                    options.itemSelectedHandler();
                }
                return false;
            }).mousedown(function () {
                config.mouseDownOnSelect = true;
            }).mouseup(function () {
                config.mouseDownOnSelect = false;
            });

            element.append(options.closeElement);

            $closeElement = $('#' + $(options.closeElement).attr('id'));

            $closeElement.click(function () {
                $(input).data("userClosed", true);
            });

            if (options.input) {
                element.css("width", options.input.outerWidth() - 2);
            }

            needsInit = false;
        }

        function target(event) {
            var element = event.target;
            while (element && element.tagName != "LI")
                element = element.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!element)
                return [];
            return element;
        }

        function moveSelect(step) {

            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            if (active > -1) {
                var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
                var selectedTerm = activeItem[0];
                var $selectedTerm = $(selectedTerm);

                $(input).val($(selectedTerm).data("untruncated"));
                // set the suggested input with the length of the selected term
                $('#' + $(input).data("suggestedId")).val($(selectedTerm).data("untruncated")[0].length);

                if (options.scroll) {
                    var offset = 0;
                    listItems.slice(0, active).each(function () {
                        offset += this.offsetHeight;
                    });
                    if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                        list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                    } else if (offset < list.scrollTop()) {
                        list.scrollTop(offset);
                    }
                }
            } else {
                $(input).val($(input).data("currentValue"));
            }

        };

        function movePosition(step) {
            active += step;
            if (active < 0 || active >= listItems.size()) {
                active = -1
                $(input).focus();
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
			? options.max
			: available;
        }

        function fillList() {
            list.empty();
            currentTerm = $(input).val();

            var max = limitNumberOfItems(data.length);

            //console.log("max = " + max);
            // var formatted = options.formatItem("Keywords",  8, max, "Keywords", "Keywords");
            //   var hi = $("<li/>").html("Keywords").addClass("ac_even").appendTo(list)[0];
            //   $(hi).data("untruncated", "Keywords");
            //   $(hi).data("ac_data", "hey");


            for (var i = 0; i < max; i++) {
                if (!data[i])
                    continue;
                var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
                if (formatted === false)
                    continue;
                var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
                $(li).data("untruncated", data[i].data);
                $(li).data("ac_data", data[i]);


            }
            listItems = list.find("li");
            if (options.selectFirst) {
                listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                active = 0;
            }

            // apply bgiframe if available
            if ($.fn.bgiframe)
                element.bgiframe();
        }

        return {
            display: function (d, q) {
                init();
                data = d;
                term = q;
                fillList();
            },
            next: function () {
                moveSelect(1);
            },
            prev: function () {
                if (active == -1) {
                    moveSelect(listItems.size());
                } else {
                    moveSelect(-1);
                }

            },
            pageUp: function () {
                if (active != 0 && active - 8 < 0) {
                    moveSelect(-active);
                } else {
                    moveSelect(-8);
                }
            },
            pageDown: function () {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect(listItems.size() - 1 - active);
                } else {
                    moveSelect(8);
                }
            },
            hide: function () {
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible: function () {
                return element && element.is(":visible");
            },
            current: function () {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            toTop: function () {
                if (active > -1) {
                    moveSelect(-(active + 1));
                }
            },
            show: function () {
                var offset = $(input).offset();
                element.css({
                    top: offset.top + input.offsetHeight,
                    left: offset.left
                }).show();
                if (options.scroll) {
                    list.scrollTop(0);
                    list.css({
                        maxHeight: options.scrollHeight,
                        overflow: 'auto'
                    });

                    if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                        var listHeight = 0;
                        listItems.each(function () {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
                        }
                    }

                }
            },
            selected: function () {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected && selected.length && $(selected[0]).data("ac_data");
            },
            emptyList: function () {
                list && list.empty();
            },
            unbind: function () {
                element && element.remove();
            }
        };
    };

    $.Autocompleter.Selection = function (field, start, end) {
        if (field.createTextRange) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart("character", start);
            selRange.moveEnd("character", end);
            selRange.select();
        } else if (field.setSelectionRange) {
            field.setSelectionRange(start, end);
        } else {
            if (field.selectionStart) {
                field.selectionStart = start;
                field.selectionEnd = end;
            }
        }
        field.focus();
    };

})(jQuery);

//create as global so the property search bar can call this when it switches from for sale to rentals
var setupOtherSearchSuggest = function () { };

(function ($) {

    $(document).ready(function () {

        //for sell process
        function setupDvdSuggest() {
            var $keywordInput = $('#searchTitle');
            if ($keywordInput.length > 0) {
                var url = "/API/Ajax/Suggest.aspx";
                var options = {
                    extraParams: {
                        cid: function () { return $("#cid").val(); }
                    },
                    delay: 100,
                    max: 15,
                    input: $keywordInput,
                    conditionalElementId: 'cid',
                    closeElement: '', //'<div class="HideSuggestions" id="DvdHideSuggestions"><a href="javascript:void(0);">Hide suggestions<\/a><\/div>',
                    formatItem: function (row) {
                        var formatted = row[0];
                        if (formatted.length > 100) {
                            formatted = formatted.substring(0, 100);
                            formatted = formatted + "&#8230;";
                        }
                        return formatted;
                    },
                    scroll: false,
                    preventEnterSubmit: false
                }
                $keywordInput.autocomplete(url, options);
            }
        }
        /* setup auto suggest for all sidebar searches*/
        setupOtherSearchSuggest = function () {
            //Check that the searchbar exists
            var $cidInput = $('#sidebarSearch input[name=cid], #PropertySearchForm input[name=cid], .jobs-advanced #JobsCat');

            if ($cidInput.length <= 0) {
                return;
            }
            // keyword search will be one of these
            var $keywordInput = $('#sidebar-15,#sidebar-153,#sidebar-54, .jobs-advanced #Keyword');

            if ($keywordInput.length > 0) {
                var url = "/API/Ajax/GeneralSuggest.aspx";
                var options = {
                    extraParams: {
                        cid: function () {
                            var topBarCid = $("#SearchType").val();
                            var sideBarCid = $cidInput.val();
                            //if top bar and sidebar match, use the top bar cid for both searches
                            return topBarCid.indexOf(sideBarCid) >= 0 ? topBarCid : sideBarCid;
                        },
                        make: function () {
                            // finds make when on motors sidebar search
                            return $('#sidebar-Make').val();
                        }
                    },
                    delay: 100,
                    conditionalElementId: 'SearchType',
                    input: $keywordInput,
                    closeElement: '', //'<div class="HideSuggestions" id="GeneralHideSuggestions"><a href="javascript:void(0);">Hide suggestions<\/a><\/div>',
                    formatItem: function (row) {
                        var formatted = row[0];
                        if (formatted.length > 35) {
                            formatted = formatted.substring(0, 35);
                            formatted = formatted + "&#8230;";
                        }
                        return formatted;
                    },
                    max: 10,
                    preventEnterSubmit: false,
                    turnOffAuto: true,
                    clickToSubmit: false
                }
                // clear the autocomplete first, incase the search form has been displayed with js
                $keywordInput.unautocomplete();
                $keywordInput.autocomplete(url, options);

            }
        }

        /* setup auto suggest for all sidebar searches*/
        setupHomepageSearchSuggest = function (tabBoxId) {
            var $cidInput = '';
            if (!tabBoxId) {
                return;
            } else {

                if (tabBoxId == 'main-box-jobs') {
                    //manually putting these category id's in because on the sidebar search its done based on what page you're on.. which doesnt really work on the homepage
                    $cidInput = '5000'
                } else if (tabBoxId == 'main-box-motors') {
                    $cidInput = '268'

                } else if (tabBoxId == 'main-box-property') {
                    $cidInput = '5748'

                } else if (tabBoxId == 'main-box-services') {
                    $cidInput = '9334'

                }

            }

            if ($cidInput.length <= 0) {
                return;
            }
            // keyword search will be one of these
            var $keywordInput = $('#' + tabBoxId + ' .default-input');

            var $selectedTab = $('#verticals-feature .verticals-nav-switcher .modal-active');

            if ($keywordInput.length > 0) {
                var url = "/API/Ajax/GeneralSuggest.aspx";
                var options = {
                    extraParams: {
                        cid: function () {
                            return $cidInput;
                        },
                        make: function () {
                            // finds make when on motors sidebar search
                            return $('#SearchTabs1_MotorsSearchFormControl_MotorsUsedCarMakeSelect').val();
                        }
                    },
                    delay: 100,
                    conditionalElementId: 'SearchType',
                    input: $keywordInput,
                    closeElement: '',
                    formatItem: function (row) {
                        var formatted = row[0];
                        if (formatted.length > 35) {
                            formatted = formatted.substring(0, 35);
                            formatted = formatted + "&#8230;";
                        }
                        return formatted;
                    },
                    max: 10,
                    preventEnterSubmit: false,
                    turnOffAuto: true,
                    clickToSubmit: false
                }
                // clear the autocomplete first, incase the search form has been displayed with js
                $keywordInput.unautocomplete();
                $keywordInput.autocomplete(url, options);

            }
        }

        setupDvdSuggest();
        setupOtherSearchSuggest();
        setupHomepageSearchSuggest();


    });

})(jQuery);

;
var BaseRepository = function (targetUrl) {
    var target = targetUrl;
    var dataType = {
        json: 'json',
        xml: 'xml',
        html: 'html'
    };
    var type = {
        post: 'POST',
        get: 'GET'
    };

    var self = this;
    self.post = function (handler, data, successCallback, errorCallback) {
        jQuery.ajax({
            type: type.post,
            url: target + handler,
            data: data,
            success: successCallback,
            error: errorCallback,
            dataType: dataType.json,
            cache: false
        });
    };
    self.get = function (handler, data, successCallback, errorCallback) {
        jQuery.ajax({
            type: type.get,
            url: target + handler,
            data: data,
            success: successCallback,
            error: errorCallback,
            dataType: dataType.json
        });
    };

    self.getHTML = function (handler, data, successCallback, errorCallback) {
        jQuery.ajax({
            type: type.get,
            url: handler,
            data: data,
            success: function (html) {
                var parser = new DOMParser();
                successCallback(parser.parseFromString(html, "text/html"));
            },
            error: errorCallback,
            dataType: dataType.html
        });
    };

    self.getCache = function (handler, cache, successCallback) {
        jQuery.ajax({
            type: type.get,
            url: target + handler,
            cache: cache,
            success: successCallback,
            dataType: dataType.json
        });
    };
};
var GtmShoppingCartRepository = function() {
    var self = this;

    self.pushRemoveFromCartToDataLayer = function(item) {
        if (item && item.gtmShoppingCartViewModel) {
            var removeFromCartEvent = {
                'event': 'removeFromCart',
                'ecommerce': {
                    'remove': {
                        'products': [
                            {
                                'name': item.listingTitle(),
                                'id': item.listingId(),
                                'price': item.price(),
                                'brand': item.gtmShoppingCartViewModel.brand(),
                                'category': item.gtmShoppingCartViewModel.category(),
                                'quantity': item.quantity(),
                                'dimension41': item.gtmShoppingCartViewModel.mCat(),
                                'dimension42': item.gtmShoppingCartViewModel.newOrUsed(),
                                'dimension43': item.gtmShoppingCartViewModel.storeName(),
                                'dimension44': item.gtmShoppingCartViewModel.subtitle(),
                                'dimension45': item.gtmShoppingCartViewModel.sellerId(),
                                'dimension46': item.gtmShoppingCartViewModel.mustPickUp(),
                                'dimension48': item.gtmShoppingCartViewModel.sellerLocation(),
                                'dimension49': item.gtmShoppingCartViewModel.freeShipping(),
                            }]
                    }
                }
            };
            if (item.cartId() > 0) {
                removeFromCartEvent.cartId = item.cartId();
            }
            dataLayer.push(removeFromCartEvent);
        }
    }

    self.pushAddToCartToDataLayer = function(data) {
        if (data && data.gtmShoppingCartViewModel) {
            var addToCartEvent = {
                'event': 'addToCart',
                'ecommerce': {
                    'add': {
                        'products': [
                            {
                                'name': data.listingTitle,
                                'id': data.listingId,
                                'price': data.price,
                                'brand': data.gtmShoppingCartViewModel.brand,
                                'category': data.gtmShoppingCartViewModel.category,
                                'quantity': data.quantity,
                                'dimension41': data.gtmShoppingCartViewModel.mCat,
                                'dimension42': data.gtmShoppingCartViewModel.newOrUsed,
                                'dimension43': data.gtmShoppingCartViewModel.storeName,
                                'dimension44': data.gtmShoppingCartViewModel.subtitle,
                                'dimension45': data.gtmShoppingCartViewModel.sellerId,
                                'dimension46': data.gtmShoppingCartViewModel.mustPickUp,
                                'dimension48': data.gtmShoppingCartViewModel.sellerLocation,
                                'dimension49': data.gtmShoppingCartViewModel.freeShipping,
                            }]
                    }
                }
            };
            if (data.cartId > 0) {
                addToCartEvent.cartId = data.cartId;
            }
            dataLayer.push(addToCartEvent);
        }
    }
};;
var ShoppingCartItemRepository = function () {
    var self = this;
    var gtmRepository = new GtmShoppingCartRepository();
    self.prototype = new BaseRepository('/API/Ajax/ShoppingCart/');
    self.handlers = {
        add: 'AddToShoppingCart.ashx',
        update: 'UpdateShoppingCartItemQuantity.ashx',
        remove: 'RemoveFromShoppingCart.ashx',
        getDetails: 'GetCartDetails.ashx',
        updateShipping: 'UpdateShoppingCartItemShipping.ashx',
        updatePromotionalShipping: 'UpdatePromotionalShipping.ashx'
    };

    self.removeItemFromCart = function (itemToRemove, successCallback, errorCallback) {
        self.prototype.post(
            self.handlers.remove,
            {
                'cartItemId': itemToRemove.cartItemId(),
                'listingId': itemToRemove.listingId()
            },
             function (data) {
                 successCallback(data, itemToRemove);
                 gtmRepository.pushRemoveFromCartToDataLayer(itemToRemove);
             },
            function (error) {
                errorCallback(error);
            }
        );
    };

    self.updateItemQuantityInCart = function (itemToUpdate, successCallback, errorCallback) {
        self.prototype.post(
            self.handlers.update,
            {
                'cartItemId': itemToUpdate.cartItemId(),
                'listingId': itemToUpdate.listingId(),
                'quantity': itemToUpdate.quantity()
            },
            function (data) {
                successCallback(data);
            },
            function (error) {
                errorCallback(error);
            });
    };

    self.updateShoppingCartItemShipping = function (itemToUpdate,shippingOption, successCallback, errorCallback) {
        self.prototype.post(
            self.handlers.updateShipping,
            {
                'cartItemId': itemToUpdate.cartItemId(),
                'listingId': itemToUpdate.listingId(),
                'quantity': itemToUpdate.quantity(),
                'shippingPrice': shippingOption.value.price(),
                'shippingDetails': shippingOption.value.description()
            },
            function (data) {
                successCallback(data, itemToUpdate);
            },
            function (error) {
                errorCallback(error, itemToUpdate);
            });
    };

    self.updatePromotionalShipping = function (sellerId, shippingOption, successCallback, errorCallback) {
        self.prototype.post(
            self.handlers.updatePromotionalShipping,
            {
                'sellerId': sellerId,
                'shippingPrice': shippingOption.value.price(),
                'shippingDetails': shippingOption.value.description()
            },
            function (data) {
                successCallback(data, shippingOption);
            },
            function (error) {
                errorCallback(error);
            });
    };

    self.addItemToCart = function (listingId, quantity, successCallback, errorCallback) {
        var referringSqid = TradeMe.getParameterByName("rsqid")
        self.prototype.post(
            self.handlers.add,
            {
                'id': listingId,
                'quantity': quantity,
                'referringSqid': referringSqid
            },
            function(data) {
                successCallback(data);
                gtmRepository.pushAddToCartToDataLayer(data);
            },
            function(error) { errorCallback(error); }
        );
    };

    self.undoRemoveItemFromCart = function (listingId, quantity, successCallback, errorCallback) {
        self.prototype.post(
            self.handlers.add,
            {
                'id': listingId,
                'quantity': quantity,
                'returnItem':true
            },
            function(data) {
                successCallback(data);
                gtmRepository.pushAddToCartToDataLayer(data);
            },
            function (error) { errorCallback(error); }
        );
    };
    self.getDetails = function (successCallback) {
        self.prototype.getCache(
           self.handlers.getDetails,
           false,
           function (data) { successCallback(data); }
       );
    };

};;

var CartDetailsViewModel = function (cartDetailsJson) {
    var self = this;
    var shoppingCartItemRepository = new ShoppingCartItemRepository();
    var populateCartDetails = function (data) {
        if (data.totalListings) {
            $('.cart-total-listings').text(data.totalListings);
            $('.cart-total-listings').show();
        } else {
            $('.cart-total-listings').hide();
        }
    };
    
    populateCartDetails(cartDetailsJson);
    
    self.getCartDetails = function () {
        shoppingCartItemRepository.getDetails(populateCartDetails); 
    };
}

var cartDetailsViewModel = new CartDetailsViewModel(globalCartDetailsJson);;
$(function ($) {
    $("#LocationFilter_regionSelect").change(function() {

        var newRegionString = 'user_region=' + $(this).val();
        var url = window.location.href;

        if (url.indexOf("user_region") > -1) {
            url = url.replace(/user_region=\d*/i, newRegionString);
        }else{
            if (url.indexOf('?') > -1) {
                url += '&' + newRegionString;
            } else {
                url += '?' + newRegionString;
            }
        }

        url = url.replace(/&user_district=[\d,]*/i, "");
        url = url.replace(/&?page=\d*/i, "");
        window.location.href = url;

    });

    var changeDistrictInUrlAndReload = function (newDistrict) {
        var newDistrictString = 'user_district=' + (newDistrict || "");
        var url = decodeURIComponent(window.location.href);

        if (url.indexOf("user_district") > -1) {
            url = url.replace(/user_district=[\d,]*/i, newDistrictString);
        } else {
            if (url.indexOf('?') > -1) {
                url += '&' + newDistrictString;
            } else {
                url += '?' + newDistrictString;
            }
        }

        url = url.replace(/&?page=\d*/i, "");
        window.location.href = url;
    };

    var $districtSelectMulti = $('#LocationFilter_districtSelectMulti');
    if ($districtSelectMulti.length) {
        var placeholder = 'All districts';
        $districtSelectMulti.multipleSelect({
            placeholder: placeholder,
            selectAll: true,
            selectAllText: placeholder,
            selectAllDelimiter: ['', ''],
            allSelected: placeholder,
            width: 200,
            minimumCountSelected: 100,
            onCheckAll: function() {
                $districtSelectMulti.multipleSelect('uncheckAll');
            },
            onUncheckAll: function() {
                changeDistrictInUrlAndReload($districtSelectMulti.val());
            },
            onClick: function() {
                changeDistrictInUrlAndReload($districtSelectMulti.val());
            }
        });

        if ($districtSelectMulti.find('option').length) {            
            var $districtSelectMultiHidden = $('#LocationFilter_districtSelectMultiHidden');
            var selectedDistricts = $districtSelectMultiHidden.val().split(',');
            $districtSelectMulti.multipleSelect('setSelects', selectedDistricts);
            $districtSelectMulti.multipleSelect('enable');
        } else {
            $districtSelectMulti.multipleSelect('disable');
        }
    }

    var $districtSelect = $('#LocationFilter_districtSelect');
    if ($districtSelect.length) {
        $districtSelect.change(function () {
            changeDistrictInUrlAndReload($districtSelect.val());
        });
    }
    
    if (sessionStorage) {
        var clearLocation = qs('clear_location');
        
        if (clearLocation == "1") {
            clearLocationSession();
        } else {
            setLocationSession();
        }
        getLocationSession();
    }
    
    function clearLocationSession() {
        window.sessionStorage.removeItem("region");
        window.sessionStorage.removeItem("district");
    }

    function setLocationSession() {
        //Check to see if there are region or district values in the querystring
        var regionId = qs('user_region');
        var districtId = (qs('user_district') || "").match(/[\d]+/g) || 0;

        if (regionId && !isNaN(regionId)) {
            window.sessionStorage.setItem("region", regionId);
            $('#sessionRegion').attr("value", regionId);
            if (districtId && districtId.length) {
                window.sessionStorage.setItem("district", districtId);
                $('#sessionDistrict').attr("value", districtId);
            } else {
                window.sessionStorage.setItem("district", 0);
                $('#sessionDistrict').attr("value", 0);
            }
        }
    }
    
    function getLocationSession() {
        //check to see if we have any location details stored
        var sessionRegion = (!isNaN(window.sessionStorage.getItem("region")) ? window.sessionStorage.getItem("region") : 100);
        var sessionDistrict = (window.sessionStorage.getItem("district") || "").match(/[\d]+/g) || 0;

        if (sessionRegion) {
            //any stored location filters to all browse links
            $(".categories-list a," +
                ".category-directory," +
                ".category-listings-breadcrumbs a," +
                ".breadCrumbs a," +
                "#fullCat a," +
                ".related a," +
                ".recent-search-term a").each(function () {
                    var href = $(this).attr("href");
                    if (href && href.indexOf("?") == -1) {
                        $(this).attr("href", $(this).attr("href") + '?user_region=' + sessionRegion + '&user_district=' + sessionDistrict);
                    } else {
                        if (href && href.indexOf("user_region") == -1) {
                            $(this).attr("href", $(this).attr("href") + '&user_region=' + sessionRegion);
                        }
                        if (href && href.indexOf("user_district") == -1) {
                            $(this).attr("href", $(this).attr("href") + '&user_district=' + sessionDistrict);
                        }
                    }
                });

            //add stored location to search bar form
            $('#sessionRegion').attr("value", sessionRegion);
            if (sessionDistrict) {
                $('#sessionDistrict').attr("value", sessionDistrict);
            }
        }
    }

    function qs(key) {
        key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
        var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
        return match && decodeURIComponent(match[1].replace(/\+/g, " "));
    }

});;
$(function ($) {
    $("a .trial-information-close").click(function (e) {
        e.preventDefault();
        $(".member-trial-message").slideUp();
        $(".member-trial-footnote").slideUp();
        var today = new Date();
        today.setTime(today.getTime());
        var expiresDate = new Date(today.getTime() + Number(30).days());
        document.cookie = "hideMemberTrialInitialInfo=1;expires=" + expiresDate.toGMTString() + ";path=/;";
    });
});;
