var kenticoPage = null,
    navigatorCache,
    gaTracker = null,
    firstSearch = null;

//// fix array.indexOf in IE
if (!Array.indexOf) {
    Array.prototype.indexOf = function (obj, start) {
        for (var i = (start || 0); i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    };
}

// setup local tracking (global tracking handled in site.master)
function gaSetup() {
    var gaArr;
    gaTracker = document.getElementById('gaLocal');
    if (gaTracker && gaTracker.value) {
        gaArr = gaTracker.value.split(';');
        if (gaArr.length === 2) {
            gaTracker = {
                "name": gaArr[0],
                "acc": gaArr[1],
                "host": window.location.host
            }
            _gaq.push(
                [gaTracker.name + '._setAccount', gaTracker.acc],
                [gaTracker.name + '._setDomainName', gaTracker.host],
                [gaTracker.name + '._trackPageview'],
                ['_trackPageLoadTime']
            );
        }
    } else {
        gaTracker = null;
    }
}

function trackSearchCriteria() {
    var searchObj = motors.constants.jsonfilter.document,
        data = searchObj.data,
        currentItem,
        searchType = "UsedCarSearch",
        bodyClass = document.body.className,
        make,
        models,
        multiMakeArray,
        multiModelArray,
        nav = navigatorCache,
        navEvents = [],
        navValue,
        navVehicleType;

    //we don't just split the string and pass it as the param because we can't guarenteed the body class' structure.
    if (bodyClass.indexOf('usedcarpage') === -1) {
        if (bodyClass.indexOf('newcarpage') > -1) {
            searchType = "NewCarSearch";
        } else if (bodyClass.indexOf('dealerspage') > -1) {
            if (bodyClass.indexOf('vandealers') > -1) {
                searchType = "DealerVanSearch";
            } else {
                searchType = "DealerSearch";
            }
        } else if (kenticoPage) {
            searchType = "KenticoPageSearch";
        } else {
            searchType = "SeoPageSearch";
        }
    } else if (bodyClass.indexOf('vans') > -1) {
        searchType = "UsedVanSearch";
    }

    // GA does not like arrays.

    function gaLog(ga) {
        //set tracker
        var tracker = (ga === undefined) ? '_trackEvent' : ga.name + '._trackEvent';

        // log make/model info
        if (data && data.manufacturer) {
            multiMakeArray = [];    // lol ryan is retarded
            multiModelArray = [];   // lol ryan is retarded
            // track search events for every make selected
            for (var i = 0; i < data.manufacturer.item.length; i++) {
                make = data.manufacturer.item[i].name;
                models = (data.manufacturer.item[i].models.item === undefined || data.manufacturer.item[i].models.item.length === 0) ? "Any " + make : data.manufacturer.item[i].models.item;
                multiMakeArray.push(make);
                multiModelArray.push(models);                
                _gaq.push([tracker, searchType, make, models]); // new test GA behaviour
            }
            // track an event showing showing which makes and models went into a multiple make/model selection
            if (multiMakeArray.length > 1) {                
                _gaq.push([tracker, "multipleMakes", multiMakeArray.join(',')]);                
            }

            //  track all models searched for using the existing functionality
            if (multiModelArray.length > 0)
                _gaq.push([tracker, "Models", multiModelArray.join(',')]);
        }

        // log navigators
        if (tracker === '_trackEvent' && nav && nav.constructor === Array) {
            for (var n = 0; n < nav.length; n++) {
                if (nav[n].htmlClass === "slider") {
                    var sEl = $(nav[n].obj),
                        sVal = sEl.slider('values'),
                        sBound = [sEl.slider("option", "min"), sEl.slider("option", "max")];
                    if (sVal[0] > sBound[0] || sVal[1] > sBound[1])
                        navValue = sVal.join(','); // slider
                } else if (nav[n].obj.tagName === 'select') {
                    navValue = nav[n].obj.options[nav[n].obj.selectedIndex].value; //select
                } else {
                    navValue = $("input:checked", nav[n].obj).map(function () { // checkbox/radio
                        return ($.trim($(this).next('label').text().replace(/\(\d+\)/gi, '')));
                    }).get().join(',');
                }
                if (nav[n].name && navValue && navValue.toLowerCase() !== "any") {
                    _gaq.push(['_trackEvent', "Navigator", nav[n].name, navValue]);
                }
                navValue = null;
            }
            // log keywords navigator properly
            if (searchObj.keywordsearch && searchObj.keywordsearch.length > 0)
                navEvents.push(['_trackEvent', 'Keyword', searchObj.keywordsearch.join(',')]);
        }
    } // end gaLog(tracker);

    gaLog(); // default GA

    if (gaTracker) {
        setTimeout(function () {
            gaLog(gaTracker);
        }, 9000)                   
        //gaLog(gaTracker); // secondary GA
    }
}

// remove an item from array by name (bit slow tbh)
function removeValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === val) {
            arr.splice(i, 1);
            break;
        }
    }
}

// tab hilighting
var tabHilight = (function () {

    // TODO: the .update() function resetting everything with the 'reset' param and .reset(<DOMelement>) only resetting a specified slider, 
    // and there being no general purpose slider/checkbox/radio identification function. i will fix this at a later date, or more likely, 
    // completely forget about it when the Bubonic Plague & Flu capulets ware off.

    // Syntax:
    //   tabHilight.init()              bind events on pageload
    //   tabhilight.update()            refresh tab hilights from metadata
    //   tabhilight.update('reset')     clear all tab hilights and modified fields
    //   tabhilight.reset(<DOMElement>) reset a specific slider (this function is easily expanded upon later, but for now it's just for sliders);

    function getTabId(el) {
        while (el.className !== 'extended-options-wrapper') {
            if (el.id === 'searchbar-outer') {
                return false;
            }
            el = el.parentNode;
        }
        return el.id.substring(0, el.id.length - 3);
    }

    function resetSlider(el) {
        //TODO: have a look at this later. its a bit clunky but the sliders + inputs both need updating.
        var $this = $(el),
            sliderId = $this[0].id.split('-')[0],
            min = $this.slider('option', 'min'),
            max = $this.slider('option', 'max');
        $this.slider('values', 0, min);
        $this.slider('values', 1, max);
        document.getElementById(sliderId + '-min').value = min; // '<' + min;
        document.getElementById(sliderId + '-max').value = max; // max + '+';
    }

    function resetModified(tab) {
        var modifiedArr = $.data(tab, 'modified'),
            i = 0;
        if (modifiedArr !== undefined && modifiedArr.constructor === Array) {
            for (; i < modifiedArr.length; i++) {
                var el = document.getElementById(modifiedArr[i]);
                if (el.className.indexOf('slider') > -1) {
                    resetSlider(el);
                } else {
                    el.checked = false;
                }
            }
        }
        tab.className = tab.className.replace("modified", "");
        $.data(tab, 'modified', []);
        // reset radio buttons - 
        var radioArr = ['rdo-any', 'rdo-ncap-any'], any;
        for (var x = 0; x < radioArr.length; x++) {
            any = document.getElementById(radioArr[x]);
            if (any) any.checked = true;
            any = null;
        }
    }

    function hilightModified(tab) {
        var tabClass = tab.className,
            modifiedArr = $.data(tab, 'modified');
        if (modifiedArr !== undefined && modifiedArr.constructor === Array) {
            if (modifiedArr.length > 0) {
                if (tab.className.indexOf('modified') === -1) {
                    tabClass = tabClass + ' modified';
                }
                tab.className = tabClass;
            } else {
                $(tab).removeClass('modified');
            }
        }
    }

    function updateData(el, modified) {
        var tabId = getTabId(el), $tab, modifiedArr;
        if (tabId) {
            $tab = $(document.getElementById(tabId));
            modifiedArr = $tab.data('modified');
            if (el.type === 'radio' || typeof modifiedArr !== 'object') {
                modifiedArr = [];
            }
            if (modified) {
                if (modifiedArr.indexOf(el.id) === -1 && el.id !== "rdo-any") {
                    modifiedArr.push(el.id);
                }
            } else {
                removeValue(modifiedArr, el.id);
            }
            $tab.data('modified', modifiedArr);
        }
        tabHandler('hilight');
    }

    var tabHandler = function (mode) {
        var tabWrapper = document.getElementById('search-extended-options');
        if (tabWrapper != null) {
            var tabs = tabWrapper.getElementsByTagName('li'),
            i = 0;
            for (; i < tabs.length; i++) {
                if (mode === 'reset') {
                    resetModified(tabs[i]);
                } else {
                    hilightModified(tabs[i]);
                }
            }
        }
    };

    var bindEvents = function () {
        var searchPanel = document.getElementById('search-extended-options-container'), uiInputs, $uiSliders;
        if (searchPanel) {
            uiInputs = searchPanel.getElementsByTagName('input');
            $uiSliders = $('div.slider', searchPanel);
            $btnFreeSearch = $('#btnnav-freesearch');
            $(uiInputs).bind({
                click: function (event) {
                    var tagType = this.type,
                        modified = false;
                    if (tagType === 'radio' || tagType === 'checkbox') {
                        if (this.checked) {
                            modified = true;
                        }
                        //clear hidden field so new GUID will be generated
                        clearSearchGuid();
                        updateData(this, modified);
                    }
                },
                change: function (event) {
                    // this was hacked in at the last moment to handle the text entry fields. needs tidying and stuff.
                    if (this.className == "slider-text") {
                        var idArr = this.id.split('-'),
                            $slider = $('#' + idArr[0] + "-slider-div"),
                            modified = false;
                        if ((idArr[1] === "min") && (parseInt(this.value, 10) > $slider.slider('values', 0)) || (idArr[1] === "max") && (parseInt(this.value, 10) < $slider.slider('values', 1))) {  // nasty logic, sorry.
                            modified = true;
                        }
                    }
                }
            });
            $btnFreeSearch.bind("click", function (event) {
                var modified = false;
                if ($('div#keywords-list ul li.keyWordItem').length) {
                    modified = true;
                    //clear hidden field so new GUID will be generated
                    clearSearchGuid();
                }
                updateData($('#btnnav-freesearch'), modified);
            });
            $uiSliders.bind("slidestop", function (event, ui) {
                var $el = $(this),
                range = [$el.slider('option', 'min'), $el.slider('option', 'max')],
                modified = false;
                if ((ui.values[0] !== range[0]) || (ui.values[1] !== range[1])) {
                    modified = true;
                    //clear hidden field so new GUID will be generated
                    clearSearchGuid();
                }
                updateData(this, modified);
            });
        }
    };

    return {
        init: bindEvents,
        update: tabHandler,
        reset: resetSlider
    };

} ());


function clearSearchGuid() {

    //clear hidden field so new GUID will be generated
    var elemGUID = document.getElementById('SearchGuid');
    if (elemGUID != null) {
        elemGUID.value = "";
    }

 }


// creates the slider with the appropriate parameters. 
function CreateSlider(div, min, max, step, slideFunction) {

    $("#" + div + "-slider-div").slider({
        range: true,
        min: min,
        max: max,
        values: [min, max],
        step: step,
        slide: function (event, ui) {
            // Adjust the text box values as we slide.
            slideFunction(min, max, ui.values[0], ui.values[1], div, false);
        },
        stop: function (event, ui) {
            clearSearchGuid();
            // on stop we need to update the data, using the contents of the textboxes. 
            slideFunction(min, max, ui.values[0], ui.values[1], div, true);
        }
    })
    .find('a.ui-slider-handle:first')
            .addClass('ui-handle-left')
            .attr('title', 'Minimum ' + div)
        .end()
        .find('a.ui-slider-handle:last')
            .addClass('ui-handle-right')
            .attr('title', 'Maximum ' + div);


    // Set blur to update the slider from the textbox if possible.
    $("#" + div + "-min").blur(function () {
        clearSearchGuid();
        var minVal = this.value,
            minText = ParseSliderText(minVal, div, "min"),
            minInt = parseInt(minVal, 10),
            $slider = $("#" + div + "-slider-div"),
            sliderMax = $slider.slider("values", 1),
            sliderMin = $slider.slider("values", 0),
            boundMax = $slider.slider("option", "max"),
            boundMin = $slider.slider("option", "min"),
            dataItem;
        if (minVal === undefined || minVal === "") {
            minVal = sliderMin; // value is crap
        } else if (minInt <= boundMin) {
            minVal = boundMin;  // value is < lower bound
        } else if (minInt >= sliderMax) {
            minVal = sliderMax;  // value is > max value
        }
        $slider.slider("values", 0, minVal);
        //if (minVal <= boundMin) // we don't manipulate lower bound values atm
        if (minVal >= 100000) {
            minVal = (minVal / 1000 + "K");
        }
        // if the value is at the bound remove the json value 
        // (take this bit out if you want to actually use the value in the text box)
        if (minInt <= boundMin) {
            dataItem = motors.constants.jsonfilter.document.sliders['nav-' + this.id.split('-')[0]];
            if (dataItem) {
                dataItem.posStart = null;
            }
        }
        this.value = minVal;        
        FilterSearch();
    });

    // Set blur to update the slider from the textbox if possible.
    $("#" + div + "-max").blur(function () {
        var maxVal = this.value,
            maxText = ParseSliderText(maxVal, div, "max"),
            maxInt = parseInt(maxVal, 10),
            $slider = $("#" + div + "-slider-div"),
            sliderMax = $slider.slider("values", 1),
            sliderMin = $slider.slider("values", 0),
            boundMax = $slider.slider("option", "max"),
            boundMin = $slider.slider("option", "min"),
            dataItem;
        if (maxVal === undefined || maxVal === "") {
            maxVal = sliderMax; // value is crap
        } else if (maxInt >= boundMax) {
            maxVal = boundMax;  // value is > upper bound
        } else if (maxInt <= sliderMin) {
            maxVal = sliderMin;  // value is < min value
        }
        // udate slider (triggers search)
        $slider.slider("values", 1, maxVal);
        // update inputs
        if (maxVal >= 100000) {
            maxVal = (maxVal / 1000 + "K");
        }
        // if the value is at the bound, att a + and remove the json value
        // (take this bit out if you want to actually use the value in the text box)
        if (maxInt >= boundMax) {
            maxVal = maxVal + "+";
            dataItem = motors.constants.jsonfilter.document.sliders['nav-' + this.id.split('-')[0]];
            if (dataItem) {
                dataItem.posEnd = null;
            }
        }
        this.value = maxVal;        
        FilterSearch();
    });

    $("#" + div + "-slider-div").addTouch();
}

function ParseSliderText(inputText, type, minOrMax) {
    if (inputText.indexOf("K", inputText.length - 1) !== -1) {
        // if K is appended, assume they're using it as a suffix for x1000. If 
        // it's not valid the slider won't move anyway until they put in something valid. 
        inputText = inputText.substring(0, inputText.length - 1);
        inputText = inputText * 1000;
    }
    if (type == "enginesize") {
        // Users' could type in 1.6 or 1.6L rather than 1600cc
        if (inputText.indexOf("L", inputText.length - 1) !== -1) {
            // if K is appended, assume they're using it as a suffix for x1000. If 
            // it's not valid the slider won't move anyway until they put in something valid. 
            inputText = inputText.substring(0, inputText.length - 1);
            inputText = inputText * 1000;
        }
        if (inputText.indexOf(".") !== -1) {
            // If a decimal point is included, try and multiply by 1000 to get the cc.
            inputText = inputText * 1000;
        }
    }
    if (/[0-9]+/.test(inputText)) {
        var data = motors.constants.jsonfilter.document.sliders;
        if (!data['nav-' + type]) {
            data['nav-' + type] = {};
        }
        var dataItem = data['nav-' + type];
        if (minOrMax == "min") {
            dataItem.posStart = inputText;
        }
        else {
            dataItem.posEnd = inputText;
        }
        //FilterSearch();
    }
    return inputText;
}

// touch support
$.extend($.support, {
    touch: "ontouchend" in document
});


var lastTap = null;

//
// Hook up touch events
$.fn.addTouch = function () {
    if ($.support.touch) {
        this.each(function (i, el) {
//            el.addEventListener("touchstart", iPadTouchHandler, false);
//            el.addEventListener("touchmove", iPadTouchHandler, false);
//            el.addEventListener("touchend", iPadTouchHandler, false);
//            el.addEventListener("touchcancel", iPadTouchHandler, false);
        });
    }
};

// defines slider behaviour. 
function SlideFunction(min, max, minslidervalue, maxslidervalue, div, updateData) {
    var minvalue = minslidervalue,
        maxvalue = maxslidervalue,
        minInput = document.getElementById(div + '-min'),
        maxInput = document.getElementById(div + '-max');
    
    if (minInput) {
        if (minslidervalue == min) {
            minInput.value = min;
            minvalue = null;
        }
        else {
            minInput.value = minslidervalue;
        }
    }

    if (maxInput) {
        if (maxslidervalue == max) {
            maxInput.value = max + "+";
            maxvalue = null;
            if (div == 'mileage') {
                maxInput.value = (max / 1000 + "K+");
            }
        }
        else {
            maxInput.value = maxslidervalue;
        }
    }

    if (updateData) {
        var data = motors.constants.jsonfilter.document.sliders;
        if ((div == 'price') && $('body.newcarpage').length) {
            div = 'minprice';
        }

        if (typeof (data['nav-' + div]) == 'undefined') {
            data['nav-' + div] = {};
        }
        var dataItem = data['nav-' + div];
        dataItem.posStart = minvalue;
        dataItem.posEnd = maxvalue;        
        
        FilterSearch();
    }
}

// TODO: move all these recursive functions into one place and handle them in a tidier way

function buildSearchURL(el) {
    // construct URL and redirect
    if (validateSearchNew() == true) {

        var searchBox = document.getElementById('nav-postcode'),
            distanceSlider = document.getElementById('search-distance'),
            priceMin = document.getElementById('price-min'),
            priceMax = document.getElementById('price-max'),
            searchstring = '/search/',
            priceParam = 'price',
            data = motors.constants.jsonfilter.document.data,
            minPriceValue = parseInt(priceMin.value.replace(/,/g, ''), 10),
            maxPriceValue = parseInt(priceMax.value.replace(/,/g, ''), 10),
            tabId = (function getTabId(el) { // TODO: similar to function for getting id in tab handler. refactor into one place later.
                while (el.tagName !== 'LI') {
                    if ((el.id === 'search') || (el.id === 'vanSearch')) {
                        return false;
                    }
                    el = el.parentNode;
                }
                return el.id;
            } (el));
        searchstring = $('#search-main-tabs a.current').attr('href');
        searchstring += '?location=' + searchBox.value;

        if (distanceSlider && distanceSlider.value && (parseInt(distanceSlider.value, 10) < 1000))
            searchstring += '&distance=' + distanceSlider.value;

        if (minPriceValue || maxPriceValue)
            searchstring += '&' + priceParam + '=' + ((minPriceValue <= 100) ? '' : minPriceValue) + ',' + ((maxPriceValue >= 50000) ? '' : maxPriceValue);

        if (data['manufacturer']) {
            for (i = 0; i < data['manufacturer'].item.length; i++) {
                if (i >= 1) {
                    searchstring += ';' + data['manufacturer'].item[i].name;
                }
                if (i == 0) {
                    searchstring += '&makeModel=' + data['manufacturer'].item[i].name;
                }
                if (data['manufacturer'].item[i].models && data['manufacturer'].item[i].models.item) {
                    searchstring += ',' + data['manufacturer'].item[i].models.item.join(',');
                }
            }
        }

        // append tab id if they clicked a tab
        if (tabId)
            searchstring += '&tab=' + tabId;

        trackSearchCriteria();

        window.location.href = encodeURI(searchstring);
    }
    else {
        //        tabId = (function getTabId(el) { // TODO: similar to function for getting id in tab handler. refactor into one place later.
        //            while (el.tagName !== 'LI') {
        //                if (el.id === 'search') {
        //                    return false;
        //                }
        //                el = el.parentNode;
        //            }
        //            return el.id;
        //        } (el));

        //        var searchs = '/search/';
        //        if (tabId) {
        //            searchs += '?tab=' + tabId;
        //        }
        //        window.location.href = encodeURI(searchs);
    }

    return false;
}

function toProperCase(str) {
    return str.replace(/\w\S*/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

// Validate the search and apply validation tooltip or not as required. 
function validateSearchNew(force, message) {

    var $location = document.getElementById('nav-postcode');
    result = false;

    if ($location.value == "" || force == true) {

        $($location).addClass('empty').focus();

    } else {

        $($location).removeClass('empty');
        result = true;

    }
    return result;
}

function updateJSONfromMake() {
    var makesPopup;
    var allMakes = document.getElementById('all-makes');
    // any that appear in popular makes will also appear in all makes
    makesPopup = allMakes;
    var data = motors.constants.jsonfilter.document.data,
        makesInputs,
        makesArr = [],
        i = 0,
        makeStringArr = [],
        x;

    if (makesPopup) {
        var keepInJSON = true;
        makesInputs = makesPopup.getElementsByTagName('input');
        for (; i < makesInputs.length; i++) {
            if (makesInputs[i].checked) {

                // do json
                var tempObj = {
                    "name": makesInputs[i].value,
                    "models": []
                };
                var j = 0;
                var exists = false;

                var s = "";
                var d = "";
                if (!data.manufacturer) {
                    data.manufacturer = {};
                    data.manufacturer.item = [];
                }
                for (; j < data.manufacturer.item.length; j++) {
                    s = tempObj.name.toLowerCase();
                    d = data['manufacturer'].item[j].name.toLowerCase();
                    if (s == d) {
                        exists = true;
                        makeStringArr.push(tempObj.name);
                        // exits in UI and in data. No need to add.
                    }
                    else {
                        makesArr.push(data['manufacturer'].item[j]);
                    }
                }

                if (!exists) {
                    // Exists in 
                    data.manufacturer.item.push(tempObj);
                    makesArr.push(tempObj);
                    makeStringArr.push(tempObj.name);
                }
            }

        }
    }

    // if there is at least one make selected, get the name and put it in the input field.
    var result;
    result = (!motors.isValidPostcode($('#nav-postcode').val())) ? false : true;
    var searchmake = "";
    if (makeStringArr.length === 0) {
        searchmake = "Any";
        document.getElementById('search-model').disabled = true;
        $('div.outercontainer #search-model').addClass('search-input-drop-down-disabled');
    }
    else if (makeStringArr.length <= 2) {
        searchmake = makeStringArr.sort().join(', ');
        if (result) { document.getElementById('search-model').disabled = false; }
        $('div.outercontainer #search-model').removeClass('search-input-drop-down-disabled');
    }
    else {
        searchmake = makeStringArr.length.toString() + " makes selected";
        if (result) { document.getElementById('search-model').disabled = false; }
        $('div.outercontainer #search-model').removeClass('search-input-drop-down-disabled');
    }
    //document.getElementById('search-make').value = (makeStringArr.length === 0) ? "Any" : makeStringArr.sort().join(', ');
    document.getElementById('search-make').value = searchmake;
    PopulateModelsDropdown(makeStringArr);
}

function setJSONfromParams() {

    var data = motors.constants.jsonfilter.document.data,
        sliders = motors.constants.jsonfilter.document.sliders,
        allPop,
        popPop,
        manuObj,
        priceArr,
        makeArr = [],
        makeId,
        modelArr,
        modelsOnly;

    if (motors.queryString.location) {

        // distance
        if (motors.queryString.distance) {
            var distInput = document.getElementById('search-distance');
            var options = distInput.options;
            var distanceQueryValue = parseInt(motors.queryString.distance);

            for (var i = 0; i < options.length; i++) {
                if (options[i].value >= distanceQueryValue) {
                    // Pick the nearest value, not just the next one.
                    var devforw = options[i].value - distanceQueryValue;
                    var devback = (i > 1) ? distanceQueryValue - options[i - 1].value : 999999;
                    distInput.value = (devforw <= devback) ? options[i].value : options[i - 1].value;
                    break;
                }
            }
            sliders['nav-distance'] = {
                posEnd: distInput.value
            };
        }

        // price
        if (motors.queryString.price) {
            priceArr = (motors.queryString.price.indexOf(',') > -1) ? motors.queryString.price.split(',') : [motors.queryString.price, 50000];
            $priceSlider = $('#price-slider-div');
            sliders['nav-price'] = {};
            if (priceArr[0] !== "") {
                sliders['nav-price'].posStart = priceArr[0];
                document.getElementById('price-min').value = priceArr[0];
                $priceSlider.slider('values', 0, priceArr[0]);
            }
            if (priceArr[1] !== "") {
                sliders['nav-price'].posEnd = priceArr[1];
                document.getElementById('price-max').value = priceArr[1];
                $priceSlider.slider('values', 1, priceArr[1]);
            }
        }

        // Magical function to create JSON make/model structure and check appropriate boxes
        var foo = function (make, models) {
            makeId = make.replace(/\s|%20/g, '').toLowerCase();
            manuObj = {
                "name": make.replace(/%20/g, ' '),
                "models": {
                    "item": []
                }
            }
            if (models.length > 0) {
                manuObj.models.item = models;
            }
            data.manufacturer.item.push(manuObj);

            // this bit is pretty nasty, but tbh it needs fixing fast. TODO: make it less nasty.            
            popularMakeCheckbox = document.getElementById('check-pop-' + makeId);
            if (popularMakeCheckbox) {
                popularMakeCheckbox.checked = true; // :(
                //popularMakeCheckbox.attr('class', 'modified');
                popularMakeCheckbox.className = 'modified';
            }
            allMakeCheckbox = document.getElementById('check-all-' + makeId);
            if (allMakeCheckbox) {
                allMakeCheckbox.checked = true; // :(
                //allMakeCheckbox.attr('class', 'modified');
                allMakeCheckbox.className = 'modified';
                if (!popularMakeCheckbox) {
                    var $currentMake = $("#pop-up-make #check-pop-" + make);
                    if (!$currentMake.length) {
                        // if the selected make doesn't exist in popular, alter the text
                        // in the popular makes link to give the user visibility of their extra selections.
                        var currentCount = $('#all-makes-link #all-makes-count #count').text();
                        currentCount = currentCount++;
                        $('#all-makes-link #all-makes-count #count').text(currentCount + 1);
                        $('#all-makes-link #all-makes-count').show();
                    }
                    $currentMake.attr("checked", this.checked == 1);
                }
            }
        };

        // makes and models
        data.manufacturer = {};
        data.manufacturer.item = [];
        if (motors.queryString.makeModel) {
            makeModelArr = motors.queryString.makeModel.replace(/%20/g, ' ').split(';');
            for (i = 0; i < makeModelArr.length; i++) {
                modelArr = makeModelArr[i].split(',');
                foo(modelArr[0], modelArr.slice(1));
                makeArr.push(modelArr[0]);
            }
        }
        if (document.location.href.indexOf('dealer') != -1) {
            GetSelectedDealerMakes();
        }
        if (motors.queryString.manuf) {
            var make = motors.queryString.manuf;
            var models = null;
            if (motors.queryString.model) {
                models = motors.queryString.model.replace(/%20/g, ' ').split(',');
            }
            foo(make, models);
            makeArr.push(make);
        }
        GetSelectedMakes();
        BuildAlerts(false);
        //PopulateModelsDropdown(makeArr);

    }
    else {
        // if no querystring, try and reload JSON from cookie.

        var locString = getCookie("motorsSearch");
        //if (!window.location.search.substring(1)) {
        //    Not entirely sure why this is even here, but it was causing issues with vans so i purged it.
        //    ToggleAdvancedSearchOptions();
        //}
        for (d in navigatorCache) {
            $navigatorObj = navigatorCache[d].obj;
            // if a slider, get the slider data out of the JSON object.v
            navigatorName = navigatorCache[d].name;
            if (navigatorName == 'nav-distance') {
                var sliderInJSON;
                if (sliders[navigatorName] != undefined) {
                    sliderInJSON = sliders[navigatorName];
                    if (sliderInJSON.posEnd !== "" && sliderInJSON.posEnd !== null) {
                        document.getElementById('search-distance').value = sliderInJSON.posEnd;

                    }
                }
            }
            if (navigatorCache[d].htmlClass == 'slider') {
                var sliderInJSON;
                if (sliders[navigatorName] != undefined) {
                    sliderInJSON = sliders[navigatorName];
                    if (sliderInJSON.posStart !== "" && sliderInJSON.posStart !== null && sliderInJSON.posStart != undefined) {
                        document.getElementById(navigatorName.split('-')[1] + '-min').value = sliderInJSON.posStart;
                        $("div#" + navigatorName.split('-')[1] + "-slider-div").slider('values', 0, sliderInJSON.posStart);
                    }
                    if (sliderInJSON.posEnd !== "" && sliderInJSON.posEnd !== null && sliderInJSON.posEnd != undefined) {
                        document.getElementById(navigatorName.split('-')[1] + '-max').value = sliderInJSON.posEnd;
                        $("div#" + navigatorName.split('-')[1] + "-slider-div").slider('values', 1, sliderInJSON.posEnd);
                    }
                }
            }
            else {
                // get the object and the input boxes contained within
                var $inputs = $("div#" + navigatorName.split('-')[1]).find("input");
                var dataInJSON;
                if (data[navigatorName] != undefined) {
                    dataInJSON = data[navigatorName];

                    $inputs.each(function () {
                        for (b in dataInJSON.item) {
                            var parts = this.id.split('-');
                            if (parts[parts.length - 1] == dataInJSON.item[b].toLowerCase().replace(/ /g, '')) {
                                this.checked = true;
                                //this.attr('class', 'modified');
                            }
                        }
                    });
                }
            }
        }

        if (data.manufacturer.item != undefined) {
            for (var f in data.manufacturer.item) {
                var makeId = data.manufacturer.item[f].name.toLowerCase();
                popularMakeCheckbox = document.getElementById('check-pop-' + makeId);
                if (popularMakeCheckbox) {
                    popularMakeCheckbox.checked = true; // :(
                }
                allMakeCheckbox = document.getElementById('check-all-' + makeId);
                if (allMakeCheckbox) {
                    allMakeCheckbox.checked = true; // :(
                    if (!popularMakeCheckbox) {
                        var $currentMake = $("#pop-up-make #check-pop-" + make);
                        if (!$currentMake.length) {
                            // if the selected make doesn't exist in popular, alter the text
                            // in the popular makes link to give the user visibility of their extra selections.
                            var currentCount = $('#all-makes-link #all-makes-count #count').text();
                            currentCount = currentCount++;
                            $('#all-makes-link #all-makes-count #count').text(currentCount + 1);
                            $('#all-makes-link #all-makes-count').show();
                        }
                        $currentMake.attr("checked", this.checked == 1);
                    }
                }
                PopulateModelsDropdown(makeArr);
                Search();
            }
        }
    }
    //Problem when merged from 22/23, an extra ELSE has been put in and causing errors, I have removed this for now but i don't know for sure what this area does so it could cause issues
    //    else {
    //        // if no querystring, try and reload JSON from cookie.
    //        var locString = $.cookie("motorsSearch");

    //        if (locString != null) {
    //            motors.constants.jsonfilter = eval('(' + locString + ')');
    //        }

    //        data = motors.constants.jsonfilter.document.data;
    //        sliders = motors.constants.jsonfilter.document.sliders;
    //        keywords = motors.constants.jsonfilter.document.keywordsearch;

    //        var navigatorName;
    //        var $navigatorObj;
    //        var d, a, c, b, e;

    //        for (e in keywords) {
    //            AddKeywordToListFromJSON(keywords[e]);
    //        }
    //        ToggleAdvancedSearchOptions();
    //        for (d in navigatorCache) {
    //            $navigatorObj = navigatorCache[d].obj;
    //            // if a slider, get the slider data out of the JSON object.v
    //            navigatorName = navigatorCache[d].name;
    //            if (navigatorName == 'nav-distance') {
    //                var sliderInJSON;
    //                if (sliders[navigatorName] != undefined) {
    //                    sliderInJSON = sliders[navigatorName];
    //                    if (sliderInJSON.posEnd !== "" && sliderInJSON.posEnd !== null) {
    //                        document.getElementById('search-distance').value = sliderInJSON.posEnd;

    //                    }
    //                }
    //            }
    //            if (navigatorCache[d].htmlClass == 'slider') {
    //                var sliderInJSON;
    //                if (sliders[navigatorName] != undefined) {
    //                    sliderInJSON = sliders[navigatorName];
    //                    if (sliderInJSON.posStart !== "" && sliderInJSON.posStart !== null) {
    //                        document.getElementById(navigatorName.split('-')[1] + '-min').value = sliderInJSON.posStart;
    //                        $("div#" + navigatorName.split('-')[1] + "-slider-div").slider('values', 0, sliderInJSON.posStart);
    //                    }
    //                    if (sliderInJSON.posEnd !== "" && sliderInJSON.posEnd !== null) {
    //                        document.getElementById(navigatorName.split('-')[1] + '-max').value = sliderInJSON.posEnd;
    //                        $("div#" + navigatorName.split('-')[1] + "-slider-div").slider('values', 1, sliderInJSON.posEnd);
    //                    }
    //                }
    //            }
    //            else {
    //                // get the object and the input boxes contained within
    //                var $inputs = $("div#" + navigatorName.split('-')[1]).find("input");
    //                var dataInJSON;
    //                if (data[navigatorName] != undefined) {
    //                    dataInJSON = data[navigatorName];

    //                    $inputs.each(function () {
    //                        for (b in dataInJSON.item) {
    //                            var parts = this.id.split('-');
    //                            if (parts[parts.length-1] == dataInJSON.item[b].toLowerCase().replace(/ /g, '')) {
    //                                this.checked = true;
    //                            }
    //                        }
    //                    });
    //                }
    //            }
    //        }

    //        if (data.manufacturer.item != undefined) {
    //            for (var f in data.manufacturer.item) {
    //                var makeId = data.manufacturer.item[f].name.toLowerCase();
    //                popularMakeCheckbox = document.getElementById('check-pop-' + makeId);
    //                if (popularMakeCheckbox) {
    //                    popularMakeCheckbox.checked = true; // :(
    //                }
    //                allMakeCheckbox = document.getElementById('check-all-' + makeId);
    //                if (allMakeCheckbox) {
    //                    allMakeCheckbox.checked = true; // :(
    //                    if (!popularMakeCheckbox) {
    //                        var $currentMake = $("#pop-up-make #check-pop-" + make);
    //                        if (!$currentMake.length) {
    //                            // if the selected make doesn't exist in popular, alter the text
    //                            // in the popular makes link to give the user visibility of their extra selections.
    //                            var currentCount = $('#all-makes-link #all-makes-count #count').text();
    //                            currentCount = currentCount++;
    //                            $('#all-makes-link #all-makes-count #count').text(currentCount + 1);
    //                            $('#all-makes-link #all-makes-count').show();
    //                        }
    //                        $currentMake.attr("checked", this.checked == 1);
    //                    }
    //                }
    //                PopulateModelsDropdown(makeArr);
    //            }
    //        }
    //    }
}

function setSearchParamsFromJSON() {    
    var data = motors.constants.jsonfilter.document.data,
        sliders = motors.constants.jsonfilter.document.sliders,
        $priceSlider,
        searchModel = document.getElementById('search-model'),
        makeId,
        makeEl,
        a, b,
        modelArr,
        modelChk,
        modelCount = 0,
        allMakes = [];

    //TODO: this needs tidying up. will turn it into a proper object at some point.

    // makes and models
    if (data.manufacturer) {
        //loop through manufacturers in JSON object
        for (a in data.manufacturer.item) {
            if (data.manufacturer.item.hasOwnProperty(a)) {
                if (data.manufacturer.item[a].name) {
                    // check the relevant input.
                    makeId = data.manufacturer.item[a].name.replace(/\s|%20/g, '').toLowerCase();
                    //                    makeLe = document.getElementById('chk-pop-' + makeId);
                    //                    makeEl = document.getElementById('chk-all-' + makeId);
                    makeLe = document.getElementById('input-' + makeId);
                    if (makeLe) {
                        makeLe.checked = true;
                        makeLe.checked = true;
                        // get models for each manufacturer
                        if (data.manufacturer.item[a].models && data.manufacturer.item[a].models.item) {
                            // check only selected models
                            modelArr = data.manufacturer.item[a].models.item;
                            if (modelArr.length > 0) {
                                for (b = 0; b < modelArr.length; b++) {
                                    modelChk = document.getElementById('chk-' + makeId + '-' + modelArr[b].replace(/\s|%20/g, '').toLowerCase());
                                    if (modelChk) {
                                        modelChk.checked = true;
                                        modelCount++;
                                    }
                                }
                                // expand models selection panel if there are any models selected
                                document.getElementById('input-' + makeId).checked = false;
                                document.getElementById('models-input-' + makeId).style.display = "block";
                                // if some models are checked that aren't the 'all models' checkboxes edit the 'All models' text.
                                if (modelArr.length == 1) {
                                    $("#label-input-" + makeId).text(" " + $("#models-input-" + makeId + " input:checked").attr("value"));
                                } else {
                                    $("#label-input-" + makeId).text(" " + modelArr.length + ((modelArr.length == 1) ? " model" : " models") + " selected");
                                }
                            } else {
                                // check them all
                                modelChk = document.getElementById('models-input-' + makeId)
                                modelChk = modelChk.getElementsByTagName('input');
                                for (b = 0; b < modelChk.length; b++) {
                                    modelChk[b].checked = true;
                                    modelCount++;
                                }
                            }
                        } else {
                            // check them all (again :|)
                            modelChk = document.getElementById('models-input-' + makeId)
                            modelChk = modelChk.getElementsByTagName('input');
                            for (b = 0; b < modelChk.length; b++) {
                                modelChk[b].checked = true;
                                modelCount++;
                            }
                        }
                        // track all selected makes
                        allMakes.push(data.manufacturer.item[a].name);
                    }
                }
            }
        }
    }

    // update display    
    GetSelectedModels();
    
    if (modelCount > 0) {
        searchModel.value = modelCount + ((modelCount == 1) ? " model" : " models") + " selected";
    }

    if (data.manufacturer && data.manufacturer.item && data.manufacturer.item.length > 0) {
        var result = (!motors.isValidPostcode($('#nav-postcode').val())) ? false : true;
        if (result) { searchModel.disabled = false; }
    }
    else {
        searchModel.disabled = true;
    }

    var allMakesVal;
    if (allMakes.length === 0) {
        allMakesVal = "Any";
    } else if (allMakes.length <= 2) {
        allMakesVal = allMakes.sort().join(', ');
    } else {
        allMakesVal = allMakes.length + " makes selected";
    }
    document.getElementById('search-make').value = allMakesVal;    
    firstSearch = false;
}

function radio_change(event) {

    if (!motors.validate()) { return false; }

    var input = event.target;
    var $this = $(input).siblings('label');

    var itemTableLength = -1;
    var checkboxCount = -1;

    var liText = input.value;
    var liClass = input.name;
    if (liClass.match(/^[0-9]/))
        liClass = 'c' + liClass;

    liClass = liClass.replace("/", "").replace("(", "").replace(")", "");

    var dataKey = $(input).parents('div[id*=Navigator]').attr('class');
    var data = motors.constants.jsonfilter.document.data;
    if (typeof (data[dataKey]) == 'undefined')
        data[dataKey] = {};
    if (!(data[dataKey].item instanceof Array))
        data[dataKey].item = [];

    data[dataKey].item = [];  //clear the array only one item can be there anyway

    if (liText != 'Any') {
        data[dataKey].item.push(liText);
    } //if Any ignore
    updateNavigatorCounts();

    Search();
}
// checkbox change event
function checkbox_change(event) {

    var modelData = [];
    if (!motors.validate()) { return false; }

    var input = event.target;
    var $this = $(input);

    var itemTableLength = -1;
    var checkboxCount = -1;

    var liText = $("#searchbar-outer label[for='" + input.id + "']").text();
    liText = jQuery.trim(liText);
    var liClass = input.name;
    if (liClass.match(/^[0-9]/))
        liClass = 'c' + liClass;

    liClass = liClass.replace("/", "").replace("(", "").replace(")", "");
    var dataKey = $(input).parents('div[id*=Navigator]').attr('class');

    if (dataKey == undefined) {
        dataKey = $(input).parents('table[id*=Navigator]').attr('class');
    }
    // TODO: Remove this minging kludge.
    // For manufacturer searches, not all navigators are searchable (grr), so we have to have ugly code here instead.
    switch (dataKey) {
        case 'nav-popmakesstock':
            dataKey = 'nav-allmakesstock';
            break;
        case 'nav-popmakesfranc':
            dataKey = 'nav-allmakesfranc';
            break;
    }
    if ((dataKey !== 'nav-popmakesstock') && (dataKey !== 'nav-allmakesstock') && (dataKey !== 'nav-dealertype')) {

        var data = motors.constants.jsonfilter.document.data;
        if (typeof (data[dataKey]) == 'undefined')
            data[dataKey] = {};
        if (!(data[dataKey].item instanceof Array))
            data[dataKey].item = [];

        motors.filter.lastAction = [0, dataKey, liClass];

        if (input.checked) {

            data[dataKey].item.push(liText);
            itemTableLength = data[dataKey].item.length;
            sortingOptionsCheckBox(data[dataKey].item, dataKey, false);

            //######GOOGLE EVENT TRACKING
            //we don't want this info here.
            //pageTracker._trackEvent('Navigator', 'Action', dataKey, data[dataKey].item.toString());
            //for (var z = 0; z < data[dataKey].item.length; z++) {
            //    _gaq.push(['_trackEvent', 'Navigator', dataKey, data[dataKey].item[z].toString()]);
            //}
            //######GOOGLE EVENT TRACKING

        } else {

            //SEO Case
            data[dataKey].item.splice($.inArray(liText, data[dataKey].item), 1);
            sortingOptionsCheckBox(data[dataKey].item, dataKey, false);

            itemTableLength = data[dataKey].item.length;
        }        
        FilterSearch();
    }
    else {

        // select contrasting checkbox too.
        var idArray = this.id.split("-");
        var make = "";

        if (idArray.length > 3) {

            make = idArray[2] + '-' + idArray[3];

        } else { make = idArray[2]; }

        var currentSelector = this.id.split("-")[1];

        if (currentSelector == "pop") {
            $("#pop-up-make #check-all-" + make).attr("checked", this.checked == 1);
        }
        else {
            var $currentMake = $("#pop-up-make #check-pop-" + make);
            if (!$currentMake.length) {
                // if the selected make doesn't exist in popular, alter the text
                // in the popular makes link to give the user visibility of their extra selections.
                var currentCount = $('#all-makes-link #all-makes-count #count').text();
                currentCount = currentCount++;
                $('#all-makes-link #all-makes-count #count').text(currentCount + 1);
                $('#all-makes-link #all-makes-count').show();
            }
            $currentMake.attr("checked", this.checked == 1);
        }

    }
}

function sortingOptionsCheckBox(myArray, dataKey, isSlider) {

    var addOption = false;
    var tagName = "#sortbyOptions"
    var myOption = {};

    //TO DO: Improve by replaceing asc, -des

    function addDropDownOption(myOption) {
        $(tagName).append(myOption)
        // $.jNice.SelectAdd($(tagName), 0);

    };

    function removeDropDownOption(dataKey) {

        if ($(tagName + " option[value='" + dataKey + "-asc']").attr("selected")) {
            $(tagName + " option[value='" + dataKey + "-asc']").attr("selected", false);
            $(tagName + " option[value='highestprice']").attr("selected", true);
        }

        if ($(tagName + " option[value='" + dataKey + "-des']").attr("selected")) {
            $(tagName + " option[value='" + dataKey + "-des']").attr("selected", false);
            $(tagName + " option[value='highestprice']").attr("selected", true);
        }

        $(tagName + " option[value='" + dataKey + "-asc']").remove();
        //    $.jNice.SelectUpdate($(tagName));


        $(tagName + " option[value='" + dataKey + "-des']").remove();
        //  $.jNice.SelectUpdate($(tagName));

    }

    dataKey = dataKey.replace(".slider-hold ", "");

    switch (dataKey) {

        // ******************************************************************************** //                                                                                                                                                                                                                          
        //  This should be coming from web.config, not hard coded.                          //                                                                                                                                                                                                                          
        // ******************************************************************************** //                                                                                                                                                                                                                           
        case 'nav-seats': dataText = "Number of seats"; break;

        //SLIDERS                                                                                                                                                                                                                                                                                                                      
        case 'nav-acceleration': dataText = "Acceleration"; break;
        case 'nav-age': dataText = "Age"; break;
        case 'nav-carbon': dataText = "Carbon emmision"; break;
        case 'nav-enginesize': dataText = "Engine Size"; break;
        case 'nav-mpg': dataText = "MPG"; break;
        case 'nav-insurance': dataText = "Insurance group"; break;
        case 'nav-mileage': dataText = "Mileage"; break;
        case 'nav-power': dataText = "Power"; break;
        case 'nav-tax': dataText = "Tax"; break;
        case 'nav-speed': dataText = "Speed"; break;

        default: dataText = ""; break;

    }

    //check required if the option already exist

    if (dataText != "") {

        var myOptionAsc = '<option value=' + dataKey + '-asc' + '  >' + dataText + '-ascending' + '</option>';
        var myOptionDes = '<option value=' + dataKey + '-des' + '  >' + dataText + '-descending' + '</option>';

        if (!isSlider) {

            if ((myArray.length > 1)) {

                if ($(tagName + " option[value='" + dataKey + "-asc']").length == 0) {

                    addDropDownOption(myOptionAsc);
                }

                if ($(tagName + " option[value='" + dataKey + "-des']").length == 0) {

                    addDropDownOption(myOptionDes);
                }

            } else {

                if ($(tagName + " option[value='" + dataKey + "-asc']").length > 0) {

                    removeDropDownOption(dataKey);
                }

                if ($(tagName + " option[value='" + dataKey + "-des']").length > 0) {

                    removeDropDownOption(dataKey);
                }

            }
        } else {

            //{postStart,posEnd,value1,value2}
            if ((myArray[2] > myArray[0]) || (myArray[3] < myArray[1])) {

                if ($(tagName + " option[value='" + dataKey + "-asc']").length == 0) {

                    addDropDownOption(myOptionAsc);
                }

                if ($(tagName + " option[value='" + dataKey + "-des']").length == 0) {

                    addDropDownOption(myOptionDes);
                }

            } else {

                removeDropDownOption(dataKey);
                removeDropDownOption(dataKey);

            }
        }
    }

}

// document.ready

// postbackJSON(motors.constants.jsonfilter.document.data); 
function postbackJSON(obj) {
    // this is just experimental, rewrite using actual proper JS at some point :P
    $('body').append('<form id="jsonForm" method="post" action="/search/"><input type="text" id="jsonInput" name="jsonInput" /></form>');
    $('#jsonInput').val(JSON.stringify(obj));
    $('#jsonForm').submit();
}

// ONLOAD START ------------------------------------------------------------------------------

$(document).ready(function () {

    $('a.show-dealer-location').live('click', function (e) {
        e.preventDefault();
        var res = $(this).parentsUntil('div.result-item'),
            end = res.find('p.address').html(),
            start = (($('#nav-postcode').length) ? $('#nav-postcode').val().toLowerCase() : motors.constants.jsonfilter.document.postcode.toLowerCase() || ''),
            href = ((res.find('h5 a').length) ? res.find('h5 a').attr('href') : window.location.pathname),
            dealerId = (res.find('h5 a').length) ? res.find('.result-details h5 a').attr('href') : window.location.pathname;

        dealerId = dealerId.split('/')[1];

        // do stuff
        if (end.indexOf('(') > -1) end = end.substr(0, end.lastIndexOf("("));
        end = end.replace(/<br>/gi, ', ') + ", United Kingdom";
        end = end.replace(/, ,/g, ',');
        // if a map already exists nuke it
        if ($('#dealerMap').length > 0)
            $('#dealerMap').remove();
        // show map(ish)
        motors.ajax.showDealerMap(start, end, dealerId);
        // track event in GA
        _gaq.push(['_trackEvent', 'ViewMap', href, start]);
        // track event in AuditDB
        $.post('/audit/map-view/' + dealerId);
    });

    $('#createAdHome, #createAd, #createAdSEO').click(function () {
        var currentUrl = location.href;
        var i = currentUrl.indexOf("/");
        var url = currentUrl.split('/');
        var domainSub = url[2].split('.');
        if ((domainSub[0] == 'motors') || (domainSub[0] == 'www')) {
            window.location = 'http://sellyourcar.motors.co.uk/Advert/Vehicle/' + $('#sell-your-car-home input.sell-a-car').val();
        }
        else {
            window.location = 'http://' + domainSub[0] + '.sellyourcar.motors.co.uk/Advert/Vehicle/' + $('#sell-your-car-home input.sell-a-car').val();
        }
    });

    $('#loginHome').click(function () {
        var currentUrl = location.href;
        var i = currentUrl.indexOf("/");
        var url = currentUrl.split('/');
        var domainSub = url[2].split('.');
        if ((domainSub[0] == 'motors') || (domainSub[0] == 'www')) {
            window.location = 'http://sellyourcar.motors.co.uk/';
        }
        else {
            window.location = 'http://' + domainSub[0] + '.sellyourcar.motors.co.uk/';
        }
    });

    if ($('#requestDetailsPopup').length) {
        var currentUrl = location.href;
        var i = currentUrl.indexOf("/");
        var url = currentUrl.split('/');
        var domainSub = url[2].split('.');
        if ((domainSub[0] == 'motors') || (domainSub[0] == 'www')) {
            $('#requestDetailsPopup #requestDetailsForm').attr('action', 'http://local.sellyourcar.motors.co.uk/Advert/RequestDetails/');
        }
        else {
            $('#requestDetailsPopup #requestDetailsForm').attr('action', 'http://' + domainSub[0] + '.sellyourcar.motors.co.uk/Advert/RequestDetails/');
        }

    }

    // identify CMS pages once, rather than all the time
    kenticoPage = (function (cmsVersion) {
        return (cmsVersion && cmsVersion.className === "CMS") ? true : null;
    } (document.getElementById('cmsversion')));


    if (($("#searchbar-outer").length) || ($('#searchbar-seo').length)) {

        // build a cache of the navigators as a json object so we have easy access to them later
        navigatorCache = (function (panel) {
            var i = 0, navArray = [], navName;
            $("div[id^='Navigator'], div[id$='-slider-div']", panel).not('.nav-popmakesstock, .nav-allmakesstock').each(function () {
                navArray.push({
                    "name": ((this.className === "slider") ? "nav-" + this.id.split('-')[0] : this.className),
                    "id": this.id,
                    "htmlClass": this.className,
                    "obj": this
                });
            });
            // hack in the nav-distance
            navArray.push({
                "name": "nav-distance",
                "id": "search-distance",
                "htmlClass": "search-input",
                "obj": document.getElementById('search-distance')
            });
            return navArray;
        } (document.getElementById('searchbar-outer')));

        // Set up sliders.
        CreateSlider("price", 0, 50000, 500, SlideFunction); // reduced lower bound to zero at gary's request
        CreateSlider("enginesize", 0, 3000, 500, SlideFunction);
        CreateSlider("age", 0, 10, 1, SlideFunction);
        CreateSlider("mileage", 0, 100000, 1000, SlideFunction);
        CreateSlider("insurance", 1, 20, 1, SlideFunction);
        CreateSlider("tax", 0, 500, 10, SlideFunction);
        CreateSlider("mpg", 10, 60, 5, SlideFunction);
        CreateSlider("carbon", 100, 250, 25, SlideFunction);
        CreateSlider("speed", 0, 250, 10, SlideFunction);
        CreateSlider("power", 0, 250, 10, SlideFunction);
        CreateSlider("acceleration", 0, 20, 1, SlideFunction);
        //Load filter values

        var tmpObj = eval('(' + unescape($(motors.constants.hiddenjson).attr('value')) + ')');
        if (tmpObj) {
            motors.constants.jsonfilter = tmpObj;
            // tmpObj is apparently terrible, and cannot be relied upton to create the structure properly so we do it here...
            motors.constants.jsonfilter.document.data = {
                "manufacturer": {
                    "item": []
                }
            };
        } else {
            // if the json object doesn't exist build the barebones
            motors.constants.jsonfilter = {
                "document": {
                    "data": {
                        "manufacturer": {
                            "item": []
                        }
                    },
                    "sliders": {}
                }
            };
        }

        motors.getLocationCookie();

        if (motors) {

            if (typeof (motors.queryString) === 'object' && motors.queryString.tab) {
                //tab required from URL make correct one current
                document.getElementById('search-extended-options-container').style.display = "block";
                SetActiveTab(motors.queryString.tab);
            }

            // It takes ages for document.ready to fire - we can probably get away with running this earlier...
            // moved it up a bit, should trigger a bit sooner.
            if (typeof (motors.startPagination) === 'function') {
                motors.startPagination();
            }

        }

        //$('#nav-postcode').attr('autocomplete', 'on'); // Set temporary for auto complete test

        //This fancution will set all navigators to update when open 
        motors.handleUpdates();

        if (typeof (motors) == 'object' && typeof (motors.filter) == 'object' && typeof (motors.navigators.init) == 'function') {
            motors.navigators.init();
        }

        $('#sortbyOptions').change(function () {
            if (!kenticoPage)
                motors.triggerDataRequest();
        });

        var defaultKeyword = "Keyword, e.g. GTI";

        // Set up default text for keyword field. 
        $('#nav-freesearch')
			.val(defaultKeyword)
			.focus(function () {
			    if (this.value == defaultKeyword) {
			        this.value = '';
			    }
			})
			.blur(function () {
			    if (this.value == '') {
			        this.value = defaultKeyword;
			    }
			});

        // Set up default text for min/max on price slider. bug - 2722
        $("input#price-min").val("0");
        $("input#price-max").val("50000+");

        if (typeof (motors) == 'object' && typeof (motors.filter) == 'object') {
            if (typeof (checkbox_change) == 'function') {
                $('#searchbar-outer input:checkbox').change(checkbox_change);
            }
            if (typeof (radio_change) == 'function') {
                $('#searchbar-outer input:radio').change(radio_change);    //There is no way to get back from here is the radio is changed
            }
            if (typeof (motors.filter.checkbox_change_old) == 'function') {
                $('div.more-opts-panel input:checkbox').change(motors.filter.checkbox_change_old);
            }
            if (typeof (motors.filter.radio_change_old) == 'function') {
                $('div.more-opts-panel input:radio').change(motors.filter.radio_change_old);    //There is no way to get back from here is the radio is changed
            }
        }

        $("#pop-up-make input").change(function (event) {
            if (!event.target.checked) {
                RemoveMakeFromJSON(event.target);
            }
        });

        // Detect whether or not this is a cms page and attach the appropriate event.
        if (!kenticoPage) {
            // if not a cms page hook up normal ajax search events.
            $("#search-button").live('click', function (event) {
                //run dealer name search
                if ($('#dealer-name').length) {
                    dealerNameSearch();
                }
                if (this.className.indexOf('inactive') === -1) {
                    firstSearch = false;
                    //only run this search if pop-up-make is not open - fix for bug - 2369
                    if (!$("#pop-up-make").hasClass("open")) {
                        Search();
                    }
                    return false;
                }
            });

            $("#searchbar-outer ul.tabs-list li").click(function (event) {
                SetActiveTab(this.id);
            });
        }
        else {
            // if cms, we need to redirect to a non-cms page and retain any criteria entered. 
            $("#search-button").live('click', function (event) {
                if (this.className.indexOf('inactive') === -1) {
                    buildSearchURL(event.target);
                    firstSearch = false;
                }
            });

            $("#searchbar-outer ul.tabs-list li").click(function (event) {
                buildSearchURL(event.target);
            });

            $('#advanced-search-options-anchor').remove();
            $('#advanced-search-options-links').css('color', '#fff');
        }



        $('#nav-postcode').bind('keyup', function () {
            checkLocationNew($(this));
        }).focus(); // ensure postcode field has focus onload!

        //if enter key pressed perform search if postcode is valid
        $('body')
        .bind('keyup', function (e) {
            if (e.keyCode == '13') {
                var elemSearchButton = document.getElementById('search-button');
                if (elemSearchButton != null) {
                    // Detect whether or not this is a cms page and attach the appropriate event.
                    if (!kenticoPage) {
                        //if Private seller pop then don't perform search
                        if ((e.target.id == "emailPSFord_fullName") || (e.target.id == "emailPSFord_email")) {
                            $('#emailPSDetails').trigger('click');
                        }
                        else {
                            if (elemSearchButton.className.indexOf('inactive') === -1) {
                                firstSearch = false;
                                //only run this search if pop-up-make is not open - fix for bug - 2369
                                if (!$("#pop-up-make").hasClass("open")) {
                                    Search();
                                }
                                return false;
                            }
                            $("#searchbar-outer ul.tabs-list li").click(function (event) {
                                SetActiveTab(this.id);
                            });
                        }
                    }
                    else {
                        if (elemSearchButton.className.indexOf('inactive') === -1) {
                            buildSearchURL(e.target);
                            firstSearch = false;
                        }
                    }
                }
            }
        }).focus(); // ensure postcode field has focus onload!


        if (document.getElementById('searchbar-outer')) {
            if (document.getElementById('nav-postcode')) { // do not break SEO pages
                checkLocationNew("#nav-postcode");
            }
        }

        $('#nav-postcode').bind('keyup', function () {
            checkLocationNew($(this));
        }).focus(); // ensure postcode field has focus onload!

        if (document.getElementById('searchbar-outer')) {
            if (document.getElementById('nav-postcode')) { // do not break SEO pages
                checkLocationNew("#nav-postcode");
            }
        }

        jQuery.fn.keypressFilter = function (method) {
            return this.each(function () {
                $(this).keydown(function (e) {
                    var key = e.charCode || e.keyCode || 0;
                    if (method == "numeric") {
                        // only allow backspace, tab, delete, arrows, numbers and keypad numbers
                        return (
                            key == 8 ||
                            key == 9 ||
                            key == 46 ||
                            (key >= 37 && key <= 40) ||
                            (key >= 48 && key <= 57) ||
                            (key >= 96 && key <= 105));
                    } else {
                        // only allow tab
                        return (key == 9);
                    }
                })
            })
        }
        // prevent text input in make/model boxes but allow a tab press ;)
        $('input.search-input-drop-down').keypressFilter();
        $('input.slider-text').keypressFilter('numeric');

        //Hide popups when click is triggered in the page.
        $("body").click(function (event) {
            // check whether this is the dealer page or not. 
            if (!$("#dealer-by-name").length) {
                if ($("#pop-up-make").is(":visible") && (event.target.id != "search-make")) {
                    GetSelectedMakes("true");
                    $("#pop-up-make").hide();
                }
                if ($("#pop-up-model").is(":visible") && (event.target.id != "search-model")) {
                    GetSelectedModels();
                    $("#pop-up-model").hide();
                }
            }
            else {
                if ($("#pop-up-make").is(":visible") && (event.target.id != "search-make")) {
                    GetSelectedDealerMakes();
                    $("#pop-up-make").hide();
                }
                if ($("#pop-up-vendor").is(":visible") && (event.target.id != "search-vendor")) {
                    $("#pop-up-vendor").hide();
                }
            }
        });

        // If the click occurs inside of the popup we don't 
        // want to close the window, so stop event propagating.
        $("div.popup-box").click(function (event) {
            event.stopPropagation();
        });

        $("div.make-model-navigator").click(function (event) {
            $(this).addClass("orange");
        });

        $("#search-make").live('click', function (event) {
            if (!event.target.disabled) {
                if ($('#pop-up-make').is(':visible')) {
                    $('#pop-up-make').hide();
                }
                else {
                    //add class open to fix bug 2369
                    $("#pop-up-make").show().addClass("open");
                }

            }
            return false;
        });

        $("#search-model").live('click', function (event) {
            if (!event.target.disabled) {
                if ($('#pop-up-model').is(':visible')) {
                    $('#pop-up-model').hide();
                }
                else {
                    $("#pop-up-model").show();
                }

                // show model options if nly one make selected. also, lol long strings.
                if (motors.constants.jsonfilter.document.data.manufacturer.item && motors.constants.jsonfilter.document.data.manufacturer.item.length == 1) {
                    $("#pop-up-model .model-expanding-section").show();
                }
            }
            return false;
        });

        $("#search-vendor").live('click', function (event) {
            $("#pop-up-vendor").slideFadeToggle();
            return false;
        });
    }

    // if this is the new car search page, we need to remove the colour navigator.
    if ($('body.newcarpage').length) {
        motors.constants.jsonfilter.document.sliders = {};
        //Search();
    }


    var ua = $.browser;
    if (ua.msie && ua.version.slice(0, 2) == "7.") {
        if ($('#pop-up-model').length > 0) {
            var $popupModel = $('#pop-up-model');
            $popupModel.insertBefore('#userIP');
            if ($("#search-model").parents().find("#dealerSearch").length > 0) {
                $popupModel.css('top', '282px');
            }
            else {
                $popupModel.css('top', '324px');
            }
            var position = $('#search-model').offset();
            $popupModel.css('left', position.left);
        }
        if ($('#pop-up-make').length > 0) {
            var $popupMake = $('#pop-up-make');
            $popupMake.insertBefore('#userIP');
            if ($("#search-make").parents().find("#dealerSearch").length > 0) {
                $popupMake.css('top', '282px');
            }
            else {
                $popupMake.css('top', '324px');
            }
            var position = $('#search-make').offset();
            $popupMake.css('left', position.left);
        }
        if ($("#pop-up-vendor").length > 0) {
            var $popupVendor = $('#pop-up-vendor');
            $popupMake.insertBefore('#userIP');
            if ($("#search-vendor").parents().find("#dealerSearch").length > 0) {
                $popupVendor.css('top', '282px');
            }
            else {
                $popupVendor.css('top', '324px');
            }
            var position = $('#search-vendor').offset();
            $popupVendor.css('left', position.left);
        }
    }
});

// ONLOAD END ------------------------------------------------------------------------------

// Check the location field and enable/disable search options as required. 
// This is called from motors-home.js.
var defaultLocation = "e.g. DE1 2BH or Derby";
function checkLocationNew(obj) {
    var $this = (obj) ? $(obj) : $('#nav-postcode'),
        result = (($this.val() == "") || ($this.val() == defaultLocation)) ? false : true,
        advanced = document.getElementById('advanced-search-options-anchor');

    //    if ($this.val().length < 6) {
    //        $this.addClass('search-location-empty');
    //        $this.removeAttr('disabled');
    //        $('span#postcode-guidance').removeAttr('style');
    //        $('div.outercontainer .search-input').attr('disabled', 'disabled');
    //        $('div.outercontainer #nav-postcode').removeAttr('disabled');
    //        $('div.outercontainer .search-input-drop-down').addClass('search-input-drop-down-disabled');
    //        if (advanced)
    //            DisableOnClickAnchor(advanced, true);
    //        DisableSlidersAndSelectors(true);
    //    }
    //    else {
    var newVal;

    if (result) {
        //remove bad characters that break the search, don't worry about any random non-alphanumeric characters they'll not break anything.
        newVal = $this.val().replace(/~|=/gi, '');
        $this.val(newVal);
        result = (newVal == "") ? false : true;
        // also check postcode validity. 
        result = (motors.isValidPostcode(newVal)) ? true : false;

    }

    if (result) {
        $this.removeClass('search-location-empty');
        $this.removeClass('empty');
        $('span#postcode-guidance').css('visibility', 'hidden');
        $('#search-distance').removeAttr('disabled');
        $('#search-make')
            .removeAttr('disabled')
            .removeClass('search-input-drop-down-disabled');
        if ($('#search-make').attr('value') != "Any") {
            $('#search-model')
                .removeAttr('disabled')
                .removeClass('search-input-drop-down-disabled');
        }
        // dealer search  
        if ($('#search-vendor').length > 0) {
            $('#search-vendor')
                .removeAttr('disabled')
                .removeClass('search-input-drop-down-disabled');
        }
        // car/van search  
        // TODO: no idea who wrote it but this function code is terrible.
        $('#search-vehicletype').removeAttr('disabled');
    }
    else {
        $this.addClass('search-location-empty');
        $this.removeAttr('disabled');
        $('span#postcode-guidance').removeAttr('style');
        $('div.outercontainer .search-input').attr('disabled', 'disabled');
        $('div.outercontainer #nav-postcode').removeAttr('disabled');
        $('div.outercontainer .search-input-drop-down').addClass('search-input-drop-down-disabled');
    }

    if (advanced)
        DisableOnClickAnchor(advanced, !result);
    DisableSlidersAndSelectors(!result);
    //}
    var advanced = document.getElementById('advanced-search-options-anchor');
    $this.focus();

}

// disable or enable slider functionality
function DisableSlidersAndSelectors(disable) {    
    $("div[id$='slider-div']").slider("option", "disabled", disable);

    if (disable) {
        $('input.slider-text').attr('disabled', 'disabled');
        $('div.outercontainer #search-button').removeClass('orange')
            .addClass('inactive');
        $('#keywordsearchdiv #btnnav-freesearch').removeClass('orange')
            .addClass('inactive');
        $('#search-extended-options-container input').attr('disabled', 'disabled');
        $('#dealer-name').attr('disabled', 'disabled');
        $('#dealer-name_search').addClass('button_disabled')            
    }
    else {
        $('input.slider-text').removeAttr('disabled');
        $('#search-button').addClass('orange')
            .removeClass('inactive');
        $('#keywordsearchdiv #btnnav-freesearch').addClass('orange')
            .removeClass('inactive');
        $('#search-extended-options-container input').removeAttr('disabled');
        $('#dealer-name').removeAttr('disabled');
    }
    var keywordButton = document.getElementById("search-button");
    var searchButton = document.getElementById("btnnav-freesearch");
    DisableOnClickAnchor(searchButton, disable);
    DisableOnClickAnchor(keywordButton, disable);
}

// Disable anchor functionality
function DisableOnClickAnchor(obj, disable) {
    /*
    if (obj !== null) {
    if (disable) {
    var href = obj.getAttribute("onclick");
    if (href && href != "" && href != null) {
    obj.setAttribute('onclick_bak', href);
    }
    obj.removeAttribute('onclick');
    if (obj.className.indexOf('inactive') === -1)
    obj.className += 'inactive';
    }
    else {
    if (obj.hasAttribute("onclick_bak")) {
    obj.setAttribute('onclick', obj.attributes['onclick_bak'].nodeValue);
    $(obj).removeClass('inactive');
    }
    }
    }
    */
}


// Model check function. 
function CheckModelList(id, make, selectall) {

    var data = motors.constants.jsonfilter.document.data;

    // Expand or collapse the model list based on the 'All models' checkbox status.
    if (selectall === true) {
        // check all tickboxes
        ExpandCollapseModelList(id, document.getElementById(id).checked);
        // find this model and clear down it's json object so it actually searches on all of them
        for (var i = 0; i < data.manufacturer.item.length; ++i) {
            if (data.manufacturer.item[i].name.toLowerCase() == make.toLowerCase()) {
                //delete data.manufacturer.item[i].models;
                data.manufacturer.item[i].models = {
                    "item": []
                }
            }
        }
    }
    else {
        var $inputsManu = $("#models-" + id).find("input"),
            numberOfModelsSelectedForThisMake = (function (arr) {
                var x = 0;
                arr.each(function () {
                    if (this.checked === true) ++x;
                });
                return x;
            } ($inputsManu)),
            totalNumberOfModelsForThisMake = $inputsManu.length;

        // Find whether some of the models have been selected and action.
        if (numberOfModelsSelectedForThisMake > 0) {

            if (numberOfModelsSelectedForThisMake < totalNumberOfModelsForThisMake) {

                // Deselect 'All Models' 
                $("#" + id).attr("checked", false);

                var say = $("#models-" + id + " input:checked").map(function () {
                    return this.value;
                }).get();

                // build the json object up (remove old entries and skip existing ones)
                var itemArr, alreadyThere;
                for (var i = 0; i < data.manufacturer.item.length; ++i) {
                    if (data.manufacturer.item[i].name.toLowerCase() == make.toLowerCase()) {
                        for (var j = 0; j < say.length; j++) {
                            if ((typeof (data.manufacturer.item[i].models) == 'undefined') && (say.length > 0)) {
                                data.manufacturer.item[i].models = {};
                            }
                            if ((typeof (data.manufacturer.item[i].models.item) == 'undefined') && (say.length > 0)) {
                                data.manufacturer.item[i].models.item = [];
                            }
                            itemArr = data.manufacturer.item[i].models.item;
                            alreadyThere = false;
                            //TODO: sort out this looping, it's got a lot happening and with loads and loads of models it'll get slow in crap browsers
                            for (var r = 0; r < itemArr.length; r++) {
                                if (itemArr[r] == say[j]) // item already present, don't add it again
                                    alreadyThere = true;
                                if (say.indexOf(itemArr[r]) === -1) // current item not in the list of selected models, remove it
                                    removeValue(itemArr, itemArr[r]);
                            }
                            if (!alreadyThere) // if the item isn't in the JSON already add it
                                itemArr.push(say[j]);
                        }
                    }
                }
            } else {
                // all models selected, recheck input
                document.getElementById(id).checked = true;
                // clear down json object if they're all there
                if (data.manufacturer.item) {
                    for (var i = 0; i < data.manufacturer.item.length; ++i) {
                        if (data.manufacturer.item[i].name.toLowerCase() == make.toLowerCase()) {
                            data.manufacturer.item[i].models.item = [];
                        }
                    }
                }
            }

            // set the model count (if some models are checked that aren't the 'all models' checkboxes edit the 'All models' text)
            $("#label-" + id).text(" " + ((numberOfModelsSelectedForThisMake == 1) ? $("#models-" + id + " input:checked").attr("value") : (numberOfModelsSelectedForThisMake + ((numberOfModelsSelectedForThisMake == 1) ? " model" : " models") + " selected")));

        } else {

            // zero models selected

            // show appropriate helper text with no models selected
            $("#label-" + id).text((motors.constants.jsonfilter.document.data.manufacturer.item.length == 1) ? " - no models selected, all makes will be searched" : " - select models to include this make in your search");

        }
    }
}

function ExpandCollapseModelList(id, collapse) {
    if (collapse == true) {
        $("#models-" + id + " input").attr("checked", true);
        $("#label-" + id).text(" - all models");
    }
    else {
        $("#models-" + id).show();
        $("#models-" + id + " input").attr("checked", false);

        // show appropriate helper text with no models selected
        $("#label-" + id).text((motors.constants.jsonfilter.document.data.manufacturer.item.length == 1) ? " - no models selected, all makes will be searched" : " - select models to include this make in your search");
    }
}

function ToggleMakes() {
    var popDiv = document.getElementById("popular-makes"),
        allDiv = document.getElementById("all-makes"),
        popLink = document.getElementById('all-makes-link'),
        allLink = document.getElementById('popular-makes-link'),
        allDisp, popDisp, allClass, popClass;

    if (allDiv.className !== "active") {
        allDisp = "block";
        allClass = "active";
        popDisp = "none";
        popClass = "";
    } else {
        allDisp = "none";
        allClass = "";
        popDisp = "block";
        popClass = "active";
    }

    popDiv.className = popClass;
    popDiv.style.display = popDisp;
    allLink.style.display = allDisp;

    allDiv.className = allClass;
    allDiv.style.display = allDisp;
    popLink.style.display = popDisp;

}

// SlideFadeToggle function
$.fn.slideFadeToggle = function (easing, callback) {
    // breaks the hell out of IE
    return this.animate({ opacity: 'toggle', height: 'toggle' }, "fast", easing, callback);
};

function ExpandCollapseModel(id) {
    $("#models-input-" + id).toggle();
}

// top right commands 
function ToggleAdvancedSearchOptions() {    

    var $extendedOptions = $("#search-extended-options-container"),
        anchorText = ($extendedOptions.is(':visible')) ? "More" : "Fewer",
        borderValue = ($extendedOptions.is(':visible')) ? "0" : "solid 1px #ccc";

    // Toggle visibility with animation. 
    $extendedOptions.slideFadeToggle();

    //set default active tab
    SelectCurrentTab();

    // update anchor text
    $('#advanced-search-options-anchor').text(anchorText + " options");

    $('#search-extended-options').css('border-bottom', borderValue);
}

function SelectCurrentTab() {
    var tabId = $('div.extended-options-wrapper:visible').attr('id');
    tabId = tabId.replace('div', '');    
    SetActiveTab(tabId);
}

function ResetSearchOptions() {
    CleanSearch();
    FilterSearch();    
}

function ResetMotorsDropDown(id) {
    var control = document.getElementById(id);
    if (control != null) {
        control.value = "Any";
    }
}

function ResetMotorsTextBox(id) {
    var control = document.getElementById(id);
    if (control != null) {
        control.value = "";
    }
}

function CleanSearch() {
    ResetMotorsDropDown("search-make");
    ResetMotorsDropDown("search-model");
    ResetMotorsDropDown("search-vendor");
    $("#search-distance").val("1000");
    var slider = document.getElementById('price-slider-div');
    if (slider!=null)
    {
        tabHilight.reset(slider);
    }
    $('#outercontainer select').find('option:first').attr('selected', 'selected');
    $('#search-extended-options').find('li.modified').removeClass('modified');
    $("div.popup-box input").attr("checked", false);
    $("div#keywords-list #keywords li").remove();
    tabHilight.update('reset');

    motors.constants.jsonfilter.document.data = {};
    motors.constants.jsonfilter.document.sliders = {};
    motors.filter.keyWordArray = [];

    ResetMotorsTextBox("dealer-name");

    //reset alerts to std
    elemAlertHTML = document.getElementById("alertsHTML");
    var htmlBuild = 'Make: <span>Any</span>; Model: <span>Any</span><br> Price: <span>Any</span>; within: <span>1000 miles</span> from <span class="postcode">' + document.getElementById('nav-postcode').value  + '</span>';
    
    //Change the markup in the search panel
    if (elemAlertHTML) {        
        elemAlertHTML.innerHTML = htmlBuild;
    }
}

// Enable/disable the model drop down based on the currently selected makes. 
function ToggleEnabledModelDropDown() {
    if (document.getElementById("search-make")) {
        var selectedMakes = document.getElementById("search-make").value;
        if (selectedMakes == "Any") {
            // There are no specific makes. Disable the Model textbox.
            document.getElementById("search-make").value = "Any";
            document.getElementById("search-model").disabled = true;
            $('div.outercontainer #search-model').addClass('search-input-drop-down-disabled');
        }
        else {
            document.getElementById("search-model").disabled = false;
            $('div.outercontainer #search-model').removeClass('search-input-drop-down-disabled');
        }
    }
}

// Set the active extended tab. 
function SetActiveTab(tabid) {

    //TODO: tidy this up when we have a chance to refactor - i think it's probably a bad id to use the [attrib=] selector to getElementById. 
    //  also select by id needs no inheritance chain to identify (pointless to get parent by class, then tag name, then get by id after that 
    //  since it'll just fall back to document level on the id anyway.)

    // remove active tab from all other tabs
    $("#searchbar-outer ul.tabs-list").find('li').removeClass('current-main-tab');

    // apply class
    document.getElementById('search-extended-options-container').style.display = "block";
    $("#" + tabid).addClass("current-main-tab");

    var $extendedOptions = $("#search-extended-options-container");
    // hide tabs and show only current tab div.
    $extendedOptions.find("div.extended-options-wrapper").hide();
    document.getElementById(tabid + 'div').style.display = "block";

    // update the anchor text
    $('#advanced-search-options-anchor').text("Fewer options");
    var borderValue = "solid 1px #ccc";

    $('#search-extended-options').css('border-bottom', borderValue);

    updateNavigatorCounts();
}

function updateNavigatorCounts() {

    var $openNav = $('div.extended-options-wrapper:visible, div.outercontainer'),
        $updateableNavigators = $openNav.find("div.navigator-count"),
        $popUp = $('#pop-up-model');

    if ($popUp.length > 0)
        updateSpecificNavigator($popUp, motors.constants.jsonfilter);

    $updateableNavigators.each(function () {
        updateSpecificNavigator(this, motors.constants.jsonfilter);
    });
}

function updateSpecificNavigator(nav, filter) {

    //It's Friday and I have no better idea
    if (motors.constants.jsonfilter.document.postcode == '') {
        motors.constants.jsonfilter.document.postcode = $('#nav-postcode').val();
    }

    var $nav = $(nav);
    var css = $nav.attr('class').split(' ');
    css = jQuery.grep(css, function (n, i) { return (n != 'popup-box') && (n != 'navigator-count'); });
    var identifier = css[0];

    $('.navigator-count.' + identifier).find('span.navigatorCount').addClass('updating');
    var postData = JSON.stringify(filter);

    var options = {
        type: 'POST',
        url: motors.buildUrl('/ajax/navigator.ashx?' + identifier),
        data: postData,
        timeout: 5000,
        dataType: 'json' // This is the return type, not the supplied data
    };

    // If something goes wrong, just clear all the items
    options.error = function (XMLHttpRequest, textStatus, errorThrown) {
        var navname = this.url.split('?')[1];
        $("div[id^='Navigator']." + navname).find('span.navigatorCount').text('').removeClass('updating');
    };

    // When data is returned, update the counts for all items
    options.success = function (data, textStatus) {
        var $nav = $('.' + identifier);

        // Set all counts to zero so anything not returned 
        if (identifier != 'nav-models')
            $nav.find('span.navigatorCount').text('(0)').removeClass('updating');

        if ((data != null) && (data.navigator != null)) {

            var items = data.navigator.item;
            if ((items instanceof Object) && !(items instanceof Array)) {
                items = [items];
            }

            for (var i = 0; i < items.length; ++i) {

                var liClass = items[i].value;
                if (liClass.match(/^[0-9]/))
                    liClass = 'c' + liClass;

                // TODO: What's this for, and why isn't the below used instead?
                //liClass = liClass.replace(/\/()/, '')
                liClass = liClass.replace("/", "").replace("(", "").replace(")", "");

                $nav.find('span.' + liClass + '.navigatorCount')
                            .text('(' + items[i].count + ')');
            }
        }
    };

    if (motors.search.requests == null) {
        motors.search.requests = {};
    }
    // If there is an active search request, abort it.
    if (motors.search.requests[identifier] != null) {
        motors.search.requests[identifier].abort();
    }

    motors.search.requests[identifier] = $.ajax(options);

}

function triggerDataRequest() {

    var keyWordString = '';

    if (motors.validate()) {

        //motors.filter.transitionStart()

        for (var i = 0; i < motors.filter.keyWordArray.length; i++) {
            keyWordString += motors.filter.keyWordArray[i] + ' ';
        }

        motors.constants.jsonfilter.document.keywordsearch = motors.filter.keyWordArray;

        //            var postcode = $('#nav-postcode').val();
        //            $.cookie('motorsPostcode', null);
        //            $.cookie('motorsPostcode', postcode, motors.constants.cookieOptions);
        //            motors.constants.jsonfilter.document.postcode = postcode;

        motors.setLocationCookie();
        motors.getLocationCookie();


        motors.handleUpdates();
        motors.ajax.requestData('');

        omnitureAuto('event1'); // update search results: omniture tracking trigger
    }

}
// is this still used? itll only be used in here. have a look later.
function RemoveMakeFromJSON(item) {
    var data = motors.constants.jsonfilter.document.data,
        makesPopup = document.getElementById((1 === 2) ? 'all-makes' : 'popular-makes'),
        makesInputs,
        makesArr = [],
        i = 0,
        makeStringArr = [],
        x;

    if (data.manufacturer.item) {
        for (; i < data.manufacturer.item.length; i++) {
            if (data.manufacturer.item[i].name.toLowerCase() == item.value.toLowerCase()) {
                data.manufacturer.item.splice(i, 1);
            }
        }
    }
}

// Occurs when makes have been selected. 
function GetSelectedMakes(obj) {    
    if ((obj) && (obj != undefined)) {
        firstSearch = false;
    }
    clearSearchGuid();
    updateJSONfromMake();
    //remove class open as gets confusing
    $("#pop-up-make").removeClass("open")
    $("#pop-up-make").hide();
    //move focus so user can hit enter
    $("#nav-postcode").focus();
    //No need to call this here as called indirectly from this call above: updateJSONfromMake();
    //FilterSearch();
}

// Occurs when makes have been selected. 
function GetSelectedDealerMakes() {

    var data = motors.constants.jsonfilter.document.data,
    // this is just mental code, as it will always go for popular makes
    // and wewant all makes anyway
    //makesPopup = document.getElementById((1 === 2) ? 'all-makes' : 'popular-makes'),
        makesPopup = document.getElementById('all-makes'),
        makesInputs,
        i = 0,
        makeStringArr = [],
        x;

    if (makesPopup) {
        var keepInJSON = true;
        makesInputs = makesPopup.getElementsByTagName('input');
        for (; i < makesInputs.length; i++) {
            if (makesInputs[i].checked) {

                // do json
                var tempObj = makesInputs[i].value;
                var j = 0;
                var exists = false;

                var s = "";
                var d = "";
                data['nav-allmakesstock'] = {};
                data['nav-allmakesstock'].item = [];

                data['nav-allmakesstock'].item.push(tempObj);
                makeStringArr.push(tempObj);
            }
        }
    }

    // if there is at least one make selected, get the name and put it in the input field.

    var searchmake = "";
    if (makeStringArr.length === 0) {
        searchmake = "Any";
    }
    else if (makeStringArr.length <= 2) {
        searchmake = makeStringArr.sort().join(', ');
    }
    else {
        searchmake = makeStringArr.length.toString() + " makes selected";
    }
    document.getElementById('search-make').value = searchmake;
    $("#pop-up-make").hide();
    // need to force the search now
    FilterSearch();
}

function PopulateModelsDropdown(makeArr) {

    // Send ajax request to get options
    var modelList = document.getElementById('model-list'),
        makeString = (makeArr.length > 0) ? makeArr.join(',') : $("#pop-up-make input:checked").map(function () { return this.value }).get().join(',');

    if (modelList) {
        modelList.innerHTML = '<img src="http://cdn2.motors.co.uk/v2live/images/ajax-loader.gif" style="margin:5px 0 5px 200px;" />';
        $.ajax({
            type: 'GET',
            url: motors.helper.applicationRoot + '/ajax/models.ashx?make=' + makeString + '&type=search&postCode=' + $('#nav-postcode').val() + '&distance=' + document.getElementById('search-distance').value,
            error: function (jqXHR) {

                modelList.innerHTML = "An error occured, please try again.";

            },
            success: function (data) {
                //populate select list
                if (data) {

                    if (data.toString().toLowerCase().indexOf("because your postoced is incorrect") >= 0) {
                        modelList.innerHTML = "We can't display the models for this manufacturer because we have been unable to locate your postcode - please try again with another postcode.";                                                                   
                    } else {

                        modelList.innerHTML = data;
                        setSearchParamsFromJSON();
                    }
                }
            }
        });
    }
}

// Occurs when models have been selected. 
function GetSelectedVendors() {
    // if there is at least one make selected, get the name and put it in the input field.
    if (($("#pop-up-vendor input:checked").size() == 0) || $("#pop-up-vendor input:checked").size() == $("#pop-up-vendor input").size()) {
        $("#search-vendor").val("Any");
    }
    else {
        var dealerString = $("#pop-up-vendor input:checked").map(function () {
            return this.value;
        }).get().join(',');
        dealerString = dealerString.substring(0, 15) + "...";

        $("#search-vendor").val(dealerString);
    }

    var data = motors.constants.jsonfilter.document.data;
    if ((typeof (data['nav-dealertype']) == 'undefined')) {
        data['nav-dealertype'] = {};
    }

    data['nav-dealertype'].item = $("#pop-up-vendor input:checked").map(function () {
        return this.value;
    }).get();

    $("#pop-up-vendor").slideFadeToggle();
    FilterSearch();
}


// Occurs when dealers (dealer search only) have been selected. 
// TODO: optimise this and call it instead of the counters being used elsewhere :)
function GetSelectedModels() {
    var modelLen = $("#pop-up-model input[id^='chk-']:checked").length,
        $uncheckedModels = $("#pop-up-model input[id^='input-']").not(":checked"),
        $uncheckedInner,
        makeStringArr,
        searchmake,
        id,
        allEl,
        popEl,
        data = motors.constants.jsonfilter.document.data; //        modelsToRemove = [],

    // rebuild models list if there are any unselected vehicles
    if ($uncheckedModels.length > 0) {
        $uncheckedModels.each(function (e) {

            if (this.id.split('-').length > 2) {
                id = this.id.split('-')[1] + '-' + this.id.split('-')[2];
            } else {
                id = this.id.split('-')[1];
            }
            $uncheckedInner = $('#models-input-' + id + ' input:checked');
            // check if any models are selected
            if ($uncheckedInner.length == 0) {
                allEl = document.getElementById('check-all-' + id);
                popEl = document.getElementById('check-pop-' + id);
                allEl.checked = false;
                if (popEl !== null)
                    popEl.checked = false;
                //modelsToRemove.push(allEl.value);
                //loop through and find the appropriate manu and KILL IT WITH FIRE
                if (data.manufacturer && data.manufacturer.item) {
                    for (var i = 0; i < data.manufacturer.item.length; ++i) {
                        if (data.manufacturer.item[i].name === allEl.value) {
                            data.manufacturer.item.splice(i, 1);
                        }
                    }
                }
            }
        });

        // TODO: refactor this, it's a copy paste from elsewhere. could be a function non?
        // repopulate makes input
        makeStringArr = $('#all-makes input:checked').map(function () {
            return this.value;
        }).get();
        var result = (!motors.isValidPostcode($('#nav-postcode').val())) ? false : true;
        if (makeStringArr.length === 0) {
            searchmake = "Any";
            document.getElementById('search-model').disabled = true;
            $('#search-model').addClass('search-input-drop-down-disabled');
        }
        else if (makeStringArr.length <= 2) {
            searchmake = makeStringArr.sort().join(', ');
            if (result) { document.getElementById('search-model').disabled = false; }
            $('#search-model').removeClass('search-input-drop-down-disabled');
        }
        else {
            searchmake = makeStringArr.length.toString() + " makes selected";
            if (result) { document.getElementById('search-model').disabled = false; }
            $('#search-model').removeClass('search-input-drop-down-disabled');
        }
        document.getElementById('search-make').value = searchmake;
        //GetSelectedMakes(true); <--- never ever ever call this. it's awful.
    }

    // if there is at least one make selected, get the name and put it in the input field.
    if ((modelLen == 0) || modelLen == $("#pop-up-model input[id^='chk-']").size()) {
        $("#search-model").val("Any");
    } else {
        $("#search-model").val(modelLen + ((modelLen == 1) ? " model" : " models") + " selected");
    }

    // hide models popup
    if ($("#pop-up-model").is(':visible')) {
        $("#pop-up-model").hide(); // .slideFadeToggle();
        //move focus so user can hit enter
        $("#nav-postcode").focus();
    }
    
    FilterSearch();
}

// Keywords 

// onclick function for 'add keyword' button. 
function AddKeywordToList() {

    var $keyword_input = $('#nav-freesearch');

    var _keyWord = $.trim($keyword_input.val());
    $keyword_input.val('Keyword, e.g. GTI');

    var _keyWordArray = [];

    _keyWordArray = _keyWord.split(',');


    //######GOOGLE EVENT TRACKING
    _gaq.push(['_trackEvent', 'Navigator', 'Keyword', _keyWord]);
    //######GOOGLE EVENT TRACKING


    for (var i = 0; i < _keyWordArray.length; i++) {

        _keyWord = $.trim(_keyWordArray[i].toUpperCase());

        var liClass = _keyWord;

        if (liClass.match(/^[0-9]/))
            liClass = 'c' + liClass;

        liClass = liClass.replace("/", "").replace("(", "").replace(")", "").replace(' ', '').toLowerCase();

        motors.filter.lastFilter = [2, 'keyword', liClass];

        if (_keyWord == "") { return false; } //exit loop

        if ($.inArray(_keyWord, motors.filter.keyWordArray) != -1) { alert('Keyword ' + _keyWord + ' already entered'); return false; };

        motors.filter.keyWordArray.push(_keyWord);

        $content = $('#keywordsearchdiv');

        if ($content.find('ul').length == 0) {

            var _ulKeyWord = document.createElement('ul');
            _ulKeyWord.className = 'selected keyword' //+ liClass;
            $content.append(_ulKeyWord);
        }

        var _liKeyWord = document.createElement('li');
        _liKeyWord.className = 'keyWordItem ' + liClass;                //<li class=''>

        var _spanKeyWord = document.createElement('span');
        _spanKeyWord.appendChild(document.createTextNode(_keyWord));

        var _linkKeyWordRemove = document.createElement('a');
        _linkKeyWordRemove.setAttribute('href', '#');

        _linkKeyWordRemove.className = 'linkKeyWordRemove linkRemove';   //<a href='#'>X</a>
        _linkKeyWordRemove.appendChild(document.createTextNode('x'));


        $(_linkKeyWordRemove).click(function () {

            motors.filter.keyWordArray.splice($.inArray($(this).siblings().text(), motors.filter.keyWordArray), 1);
            $(this).parent('li').remove();

            FilterSearch();
        });

        _liKeyWord.appendChild(_spanKeyWord);
        _liKeyWord.appendChild(_linkKeyWordRemove);

        $content.find('ul').append(_liKeyWord);

    }

    $keyword_input.focus();

    FilterSearch();
}

// onclick function for 'add keyword' button. 
function AddKeywordToListFromJSON(_keyWord) {

    var liClass = _keyWord;

    if (liClass.match(/^[0-9]/))
        liClass = 'c' + liClass;

    liClass = liClass.replace("/", "").replace("(", "").replace(")", "").replace(' ', '').toLowerCase();

    motors.filter.lastFilter = [2, 'keyword', liClass];

    if (_keyWord == "") { return false; } //exit loop

    if ($.inArray(_keyWord, motors.filter.keyWordArray) != -1) { alert('Keyword ' + _keyWord + ' already entered'); return false; };

    motors.filter.keyWordArray.push(_keyWord);

    $content = $('#keywordsearchdiv');

    if ($content.find('ul').length == 0) {

        var _ulKeyWord = document.createElement('ul');
        _ulKeyWord.className = 'selected keyword' //+ liClass;
        $content.append(_ulKeyWord);
    }

    var _liKeyWord = document.createElement('li');
    _liKeyWord.className = 'keyWordItem ' + liClass;                //<li class=''>

    var _spanKeyWord = document.createElement('span');
    _spanKeyWord.appendChild(document.createTextNode(_keyWord));

    var _linkKeyWordRemove = document.createElement('a');
    _linkKeyWordRemove.setAttribute('href', '#');

    _linkKeyWordRemove.className = 'linkKeyWordRemove linkRemove';   //<a href='#'>X</a>
    _linkKeyWordRemove.appendChild(document.createTextNode('x'));


    $(_linkKeyWordRemove).click(function () {

        motors.filter.keyWordArray.splice($.inArray($(this).siblings().text(), motors.filter.keyWordArray), 1);
        $(this).parent('li').remove();

        FilterSearch();
    });

    _liKeyWord.appendChild(_spanKeyWord);
    _liKeyWord.appendChild(_linkKeyWordRemove);

    $content.find('ul').append(_liKeyWord);
}

// remove duplicate keywords from array
function removeDuplicateElement(arrayName) {
    var newArray = new Array();
    label: for (var i = 0; i < arrayName.length; i++) {
        for (var j = 0; j < newArray.length; j++) {
            if (newArray[j] == arrayName[i])
                continue label;
        }
        if (arrayName[i] !== "") {
            newArray[newArray.length] = arrayName[i];
        }
    }
    return newArray;
}

// Distance select box onchange event. 
function ChangeDistance() {
    clearSearchGuid();
    var data = motors.constants.jsonfilter.document.sliders,
        targetUrl = (document.body.className.indexOf('vansdealers' > -1)) ? 'dealer/van' : 'dealer/';
    data['nav-distance'] = {posEnd: $("#search-distance").val()};    
    dataItem = data['nav-distance'];
    $('#dealerLink').attr('href', '/search/' + targetUrl + '?distance=' + dataItem.posEnd); // <-- what?!
    FilterSearch();
};

// Vehicle type select box onchange event. 
// TODO: make this suck less. make all of it suck less.
function ChangeVehicleType() {
    clearSearchGuid();
    var data = motors.constants.jsonfilter.document;
    data['nav-vehicletype'] = $("#search-vehicletype").val();
    FilterSearch();
};

// called by the search button. Only after this call can the filters activate a search without clicking the button.
function Search() {
    if ($('#searchbar-outer').is(':visible')) {
        motors.setLocationCookie();
    }
    if (!kenticoPage) {
        motors.triggerDataRequest(); // only search on non-CMS pages
        trackSearchCriteria();
    }
    firstSearch = false;
    BuildAlerts(true);
}

function WriteAlertCookie() {
    // get controls
    var makemodel = document.getElementById("makemodel"),
        distance = document.getElementById("distance"),
        pricefrom = document.getElementById("pricefrom"),
        priceto = document.getElementById("priceto"),
        postcode = document.getElementById("postcode");
    var cookiesafemakemodel = makemodel.value.replace(',', '!');
    var value = cookiesafemakemodel + '%' + distance.value + '%' + pricefrom.value + '%' + priceto.value + '%' + postcode.value;
    setCookie('motorsalertcookie', value, 1, 'motors.co.uk');
}

function WriteLogoutCookie() {
    // get controls
    var makemodel = document.getElementById("makemodel"),
        distance = document.getElementById("distance"),
        pricefrom = document.getElementById("pricefrom"),
        priceto = document.getElementById("priceto"),
        postcode = document.getElementById("postcode");
    var cookiesafemakemodel = makemodel.value.replace(',', '!');
    var value = cookiesafemakemodel + '%' + distance.value + '%' + pricefrom.value + '%' + priceto.value + '%' + postcode.value;
    setCookie('motorslogoutcookie', value, 1, 'motors.co.uk');
}

function BuildAlerts(isSearch) {    
    //Declare vaiables for data and make model specific data
    var data = motors.constants.jsonfilter,
    elemAlertHTML = document.getElementById("alertsHTML"),
    buildPriceRange = "Any",
    buildMakes = "Any",
    buildModels = "Any",
    buildDistance = "1000",
    totalMakes = 2,
    makeModelListForHandler = "Any#Any";

    //sorry about this but if a search is generated then we want to overwrite the alertSaved from querystring
    if (isSearch) {
        returnLogin = false;
    }
    else {
        returnLogin = getParameterByName('alertSaved', window.location.href);
    }

    //Show/hide info, check if it's coming back from a login and if not     
    if(!returnLogin) {
        $('#alertsMessage').addClass('hide');
        $('#alertsHTML').removeClass('hide');        
    }

    //check if make and model data exists and if so put into object
    if (motors.constants.jsonfilter != null) {
        makeModelData = motors.constants.jsonfilter.document.data
    }

    //check JSON has value
    if (data != null) {

        //build form values
        var makemodel = document.getElementById("makemodel"),
        distance = document.getElementById("distance"),
        pricefrom = document.getElementById("pricefrom"),
        priceto = document.getElementById("priceto"),
        postcode = document.getElementById("postcode");

        var navPrice = data.document.sliders['nav-price'];        

        if (navPrice) {
            //if price min has been set then add to string        
            if ((navPrice.posStart != null) && (navPrice.posStart != "")) {
                buildPriceRange = "£" + data.document.sliders['nav-price'].posStart;
                if (pricefrom != null) { pricefrom.value = data.document.sliders['nav-price'].posStart; }
            }
            //if price max has been set then add to string
            if ((navPrice.posEnd != null) && (navPrice.posEnd != "") && (navPrice.posEnd != undefined)) {
                buildPriceRange += " - £" + data.document.sliders['nav-price'].posEnd;
                if (priceto != null) { priceto.value = data.document.sliders['nav-price'].posEnd; }
            }
            else {
                //check if string is original state if so then leave it as that if not it means a price min has been set
                if (buildPriceRange != "Any") {
                    buildPriceRange += " - Any";
                }
            }
        }

        //check if make/models have data        
        if ((makeModelData != null) && (makeModelData.manufacturer.item != "")) {            
            var currentModel;
            //set builders back to empty strings
            buildMakes = "";
            buildModels = "";
            makeModelListForHandler = "";            

            //loop through JSON object until totalMakes is reached
            for (var i = 0; i < makeModelData.manufacturer.item.length; i++) {
                //put JSON data into object
                currentModel = makeModelData.manufacturer.item[i];

                //Add makes
                make = currentModel.name;
                //Add models
                models = (currentModel.models.item === undefined || currentModel.models.item.length === 0) ? "Any " + make : currentModel.models.item;
                //check if first item if not then add , seperated.
                var makeModelDivider = (i > 0) ? ", " : "";

                //object to display makes on screen
                buildMakes += makeModelDivider + make;
                //if models then the handler needs makemodel structured like this "Audi#A4, Audi#A5 etc" so we need to build this here
                if ((currentModel.models.item != undefined) && (currentModel.models.item.length != 0)) {
                    //loop through model and build # list of makes and models
                    for (var x = 0; x < currentModel.models.item.length; x++) {                            
                        makeModelListForHandler += ((i > 0) ? ", " : "") +make + '#' + currentModel.models.item[x];
                    }
                }
                else {
                    //if no models add "Any"
                    makeModelListForHandler += makeModelDivider + make + '#Any';
                }
                //object to display models on screen
                buildModels += makeModelDivider + models;
            }

            //Set makes and models to max 15 chars
            buildMakes = buildMakes.substring(0, 35) + "...";
            buildModels = buildModels.substring(0, 35) + "...";

            currentModel = null;
        }

        //build hidden form Make/Model list
        if (makemodel) {
            makemodel.value = makeModelListForHandler;
        }

        var navDistance = data.document.sliders['nav-distance'];
        if (navDistance) {
            //check if distance has been selected and if not leave as desfutl
            if ((navDistance.posEnd != null) && (navDistance.posEnd != "") && (navDistance.posEnd != undefined)) {
                buildDistance = data.document.sliders['nav-distance'].posEnd;
                if (distance != null) { distance.value = buildDistance; }
            }
        }

        //check if postcode has values
        if (postcode != null) { postcode.value = data.document.postcode.toUpperCase(); }

        //build HTML to display
        htmlBuild = 'Make: <span>' + buildMakes + '</span>; Model: <span>' + buildModels + '</span> <br />Price: <span>' + buildPriceRange + '</span>; within: <span>' + buildDistance + ' Miles</span> from <span>' + data.document.postcode.toUpperCase() + '</span>';
    }    
    
    //Change the markup in the search panel
    if (elemAlertHTML) {        
        elemAlertHTML.innerHTML = htmlBuild;
    }
   
}


// Called by filter controls, checking if the search button has been clicked
// before performing a search. 
function FilterSearch() {    
    if ($('#searchbar-outer').is(':visible')) {
        setCookie('motorsSearch', JSON.stringify(motors.constants.jsonfilter), 30);
    }
    if (firstSearch === false || (document.referrer).match("dealer")) { // fix for issues switching between tabs
        Search();
    } 
    firstSearch = false;
    updateNavigatorCounts();
}

$(function () {
    tabHilight.init();
    //TODO - think of better way of not calling this function.
    if (($('#searchbar-outer').is(':visible') &&
        (document.location.href.indexOf('?') != -1) &&
        (document.location.href.indexOf('/new') == -1)) || (document.location.href.indexOf('/vans/') != -1) && (document.location.href.indexOf('/used/vans/') == -1)) {
        setJSONfromParams();
    }
    gaSetup();
    firstSearch = (motors.constants.jsonfilter && motors.constants.jsonfilter.document && motors.constants.jsonfilter.document.totalresults) ? true : false;
});

function BackToSearchResults() {
    //var url = history.previous;
    var url = document.referrer;
    window.location.href = url.split('?')[0] + "?return=1";

}

