/*
*  Motors SEO page Javascript
*/

/* tiggered when you click the search button */

function doSearch(obj) {
    var $this = $(obj),
        panelID = $this.attr('id').split('-')[0],
        imgFormat = 'png',
        url, location, make, model, distance, price;
    if ($this.hasClass('inactive')) {
        if (!document.getElementById('validation-alert')) {
            if ($(document.body).hasClass('lte7')) {
                imgFormat = 'gif';
            }
            $('#' + panelID + '-postcode')
                .after('<div id="validation-alert">Please enter a postcode first<img src="http://cdn2.motors.co.uk/v2live/images/validation-alert-arrow-left-e16702.' + imgFormat + '"></div>')
                .focus();
            $('#validation-alert').click(function () {
                $(this).fadeTo('slow', 0, function () {
                    $(this).remove();
                });
            });
        }
        return false;
    } else {
        make = document.getElementById('make-value').value.toLowerCase();
        model = document.getElementById('model-value').value.toLowerCase();
        refinements = document.getElementById('searchcriteria').value.toLowerCase();
        location = document.getElementById(panelID + '-postcode').value.toLowerCase();
        distance = document.getElementById(panelID + '-distance-value').value;
        price = document.getElementById(panelID + '-price-value').value;
        if (make == 'car' || make == 'man') {
            make = '';
        }
        function addPrefix(url) {
            return ((url.indexOf('?') + 1) == url.length) ? '' : '&';
        }
        if (panelID == "dealer") {
            url = '/search/dealer/?';
            if (location.length > 0)
                url += addPrefix(url) + 'location=' + location;
            if (distance.length > 0)
                url += addPrefix(url) + 'distance=' + distance;
            if (make.length > 0)
                url += addPrefix(url) + 'makeModel=' + make;
        } else {
            //url = '/search/?';
            url = obj.pathname + '?';
            if ($(document.body).hasClass('ie')) {
                url = "/" + obj.pathname + '?';
            }
            if (location.length > 0)
                url += addPrefix(url) + 'location=' + location;
            if (distance.length > 0)
                url += addPrefix(url) + 'distance=' + distance;
            if (make.length > 0)
                url += addPrefix(url) + 'makeModel=' + make;
            if (model.length > 0)
                url += ',' + model;
            if (price.length > 0)
                url += addPrefix(url) + 'price=' + price;
            url += refinements;
        }
        url = url.replace(/50000+/g, '');
        document.location = url;
    }
}

/* validate location field */

function checkSeoLocation(obj) {
    var $this = $(obj),
        panelID,
        $submit;
    if ($this.attr('id')) {
        panelID = $this.attr('id');
        $submit = $('#' + panelID.split('-')[0] + '-search-submit');

        var result = (($this.val() == "") || ($this.val() == defaultLocation)) ? false : true;
        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);
            // also check postcode validity. 
            result = (motors.isValidPostcode(newVal)) ? true : false;
        }
        if (!result) {
            $this.addClass('empty');
            $submit.addClass('inactive');
            if (!document.getElementById('validation-alert')) {
                $this
                .after('<div id="validation-alert">Please enter a postcode first<img src="http://cdn2.motors.co.uk/v2live/images/validation-alert-arrow-left-e16702.gif"></div>')
                .focus();
                $('#validation-alert').click(function () {
                    $(this).fadeTo('slow', 0, function () {
                        $(this).remove();
                    });
                });
            }
        } else {
            $('#validation-alert')
        .fadeTo('slow', 0, function () {
            $(this)
                .unbind('click')
                .remove();
        });
            $this.removeClass('empty');
            $submit.removeClass('inactive');
        }
        $("div[id$='slider']").slider("option", "disabled", !result);
    }
}

$(function () {



    $('#dealer-search-submit, #used-search-submit')
        .click(function (e) {
            e.preventDefault();
            doSearch(this);
        });

    /*
    * Search Panel Tabs  
    */
    (function setupTabs(document) {
        var $search = $('#search'),
            resizedTabs = [],
            tabPadding = 13,
            baseHeight = 38,
            maxHeight = baseHeight,
            oldHeight,
            newHeight;
        // change tab
        function tabChange() {
            if (this.className.indexOf('active') == -1) {
                var newType = this.id.split('-')[1],
                    oldType = (newType == 'dealer') ? 'used' : 'dealer',
                    oldTab = document.getElementById('tab-' + oldType),
                    oldDiv = document.getElementById('content-' + oldType),
                    locObj = document.getElementById(newType + '-postcode');
                // tab class
                oldTab.className = oldTab.className.split('active')[0];
                this.className += " active";
                checkSeoLocation(locObj);
                oldDiv.className = oldDiv.className.split('active')[0];
                document.getElementById('content-' + newType).className += " active";
                // set location field on new content
                locObj.value = document.getElementById(oldType + '-postcode').value;
            }
        };
        // find maximum tab-height and push all tabs shorter than this to an array
        $search
            .find('li.tab')
            .each(function () {
                if (this.offsetHeight >= maxHeight) {
                    maxHeight = this.offsetHeight;
                } else {
                    resizedTabs.push(this);
                }
                $(this).bind('click', tabChange);
            });
        // if there are any tabs shorter than the max height fix their height and line-height
        if (resizedTabs.length >= 1) {
            $(resizedTabs)
                .each(function () {
                    $(this).css({
                        "line-height": (parseInt(this.offsetHeight / baseHeight) * baseHeight) + "px",
                        "height": (maxHeight - tabPadding) + "px"
                    });
                });
        }
    })(this);

    /* sliders */

    $('#dealer-distance-slider').slider({
        range: 'min',
        value: 50,
        min: 0,
        max: 200,
        step: 5,
        slide: function (event, ui) {
            var v;
            if (ui.value == '200') {
                v = 'Nationwide';
            } else if (ui.value <= '1') {
                v = '1 mile';
            } else {
                v = ui.value + ' miles';
            }
            $('#dealer-distance-slider-value').text(v);
            $('#dealer-distance-value').val(ui.value);
        }
    }).find('a.ui-slider-handle:first')
            .addClass('ui-handle-left')
            .attr('title', 'Minimum ' + "_test")
        .end()
        .find('a.ui-slider-handle:last')
            .addClass('ui-handle-right')
            .attr('title', 'Maximum ' + "_test");

    $('#used-distance-slider').slider({
        range: 'min',
        value: 20,
        min: 0,
        max: 200,
        step: 5,
        slide: function (event, ui) {
            var v;
            if (ui.value == '200') {
                v = 'Nationwide';
            } else if (ui.value <= '1') {
                v = '1 mile';
            } else {
                v = ui.value + ' miles';
            }
            $('#used-distance-slider-value').text(v);
            $('#used-distance-value').val(ui.value);
        }
    }).find('a.ui-slider-handle:first')
            .addClass('ui-handle-left')
            .attr('title', 'distance-slider');



    $('#used-price-slider').slider({
        range: true,
        min: 0,
        max: 50000,
        step: 500,
        values: [0, 50000],
        slide: function (event, ui) {
            var priceMin,
                priceMax,
                anyPrice = false;
            /*
            using ui.sliders to store these values breaks the min/max overlap blocking,
            throwing them at another array slows it down to a crawl. weird.

            since nobody asked for this, it's not been implemented.

            a,
            d = (ui.values[0] == ui.value) ? 0 : 1,    // get active handle's position in ui.values
            c = ui.values[d] / 500;                    // linear value of d

            // spam some numbers
            if (ui.values[d] <= 16666.6666666667) { a = toNearest(c * 100, 100); }
            else if (ui.values[d] <= 33333.3333333333) { a = toNearest(3300 + ((c - 33.333) * 500), 500); }
            else { a = toNearest(19500 + ((c - 66.666) * 1000), 1000); }
            if (a > 50000 || a == 0) { a = toNearest(a, 50000); }
            ui.values[2 + d] = a;

            // clean up first event
            if (ui.values[2] === undefined) { ui.values[2] = 0; }
            if (ui.values[3] === undefined) { ui.values[3] = 50000; }
            */

            // update display
            priceMin = ui.values[0];
            priceMax = ui.values[1];

            if (priceMin === 0 && priceMax == 50000) {
                a = "Any Price";
                anyPrice = true;
            } else if (priceMin <= 50000 && priceMax == 50000) {
                a = "Above &pound;" + priceMin;
                anyPrice = true;
            } else if (priceMin === 0 && priceMax >= 0) {
                a = "Below &pound;" + priceMax;
                anyPrice = true;
            } else if (priceMin == priceMax) {
                a = "&pound;" + priceMax;
                anyPrice = false;
            } else {
                a = "&pound;" + priceMin + " to " + "&pound;" + priceMax;
                anyPrice = false;
            }
            $('#used-price-slider-value').html(a);
            $('#used-price-value').val(priceMin + "," + priceMax);
        }
    }). find('a.ui-slider-handle:first')
            .addClass('ui-handle-left')
            .attr('title', 'price-min-slider')
        .end()
        .find('a.ui-slider-handle:last')
            .addClass('ui-handle-right')
            .attr('title', 'price-max-slider');

    $('#search li.tab')
    .click(function (e) {
        $('#dealer-postcode, #used-postcode').each(function () {
            checkSeoLocation(this);
        });
    });
    /* search buttons */
    $('#dealer-postcode, #used-postcode')
        .keyup(function (e) {
            if ($(this).val() !== "" && ((e.which) ? e.which : e.keyCode) == 13) {
                doSearch(this);
            }
        })
        .keyup(function (e) {
            checkSeoLocation(this);
        })
        .change(function (e) {
            checkSeoLocation(this);
        }).each(function () {
            checkSeoLocation(this);
        });
    /* end */
});
