﻿/*!
*  motorsinit.js
*/
var defaultKeyword = "Keyword, e.g. GTI";

var firstSearch = true;

$(document).ready(function () {

    if (!$("#searchbar-outer").length) {
        if (typeof (motors) == 'object' && typeof (motors.filter) == 'object') {
            if (typeof (motors.filter.checkbox_change_old) == 'function') {
                $('input:checkbox').change(motors.filter.checkbox_change_old);
            }
            if (typeof (motors.filter.radio_change) == 'function') {
                $('input:radio').change(motors.filter.radio_change);    //There is no way to get back from here is the radio is changed
            }
            if (typeof (motors.filter.keyword_search_old) == 'function') {
                $('div.more-opts-panel #btnnav-freesearch').click(motors.filter.keyword_search_old);
                $('#nav-freesearch')
                            .unbind('keydown')
                            .keydown(function (event) {
                                if (event.keyCode == 13) {
                                    motors.filter.keyword_search_old(event);
                                }
                            });
            }
        }

        //Load filter values
        var tmpObj = eval('(' + unescape($(motors.constants.hiddenjson).attr('value')) + ')');
        if (tmpObj) {
            motors.constants.jsonfilter = tmpObj;
        }
        if ((typeof motors.constants.jsonfilter == 'undefined') || (motors.constants.jsonfilter == null)) {
            motors.constants.jsonfilter = {};
        }
        if ((typeof motors.constants.jsonfilter.document == 'undefined') || (motors.constants.jsonfilter.document == null)) {
            motors.constants.jsonfilter.document = {};
        }
        if ((typeof motors.constants.jsonfilter.document.data == 'undefined') || (motors.constants.jsonfilter.document.data == null)) {
            motors.constants.jsonfilter.document.data = {};
        }

        motors.getLocationCookie();

        /* search field binds */

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

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

        /* end search field binds */


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

        //This fancution will set all navigators to update when open 
        motors.handleUpdates();
        //This fancution will set all navigators to update when open
        if (typeof (motors) == 'object' && typeof (motors.filter) == 'object' && typeof (motors.navigators.init) == 'function') {
            motors.navigators.init();
        }
        motors.startPagination();

        $('.pop-close').click(function () {
            $(this).parent('.popinWindow').hide();
            //  motors.curtain.raise();
        });


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

        $('#btnnav-postcode').click(function () {
            if ($('#nav-postcode').val() != '') {
                motors.constants.jsonfilter.document.LocationUniqueId = null;
                motors.setLocationCookie();
            }
            motors.triggerDataRequest()
        });

        // Set up default text for keyword field. 
        $('#nav-freesearch').val(defaultKeyword);
        $('#nav-freesearch').focus(function () {

            if ($('#nav-freesearch').val() == defaultKeyword) {
                $('#nav-freesearch').val('');
            }

        });
        $('#nav-freesearch').blur(function () {

            if (this.value == '') {
                this.value = defaultKeyword;
            }

        });
    }

    $('#compareShow').click(function () {

        if (motors.carscompare.carsdata.item.length == 0) {

            alert("There are no cars to compare. Please add some.");
            return false;

        } else {

            if ($('.carcompare:visible').length == 0) {
                $('.carcompare').show();
            } else {
                $('.carcompare').hide();
            }
        }
    });
    if ($('div.more-opts-panel .nav-manufacturers li a, div.more-opts-panel .nav-popularmanufacturers li a')) {
        $('div.more-opts-panel .nav-manufacturers li a, div.more-opts-panel .nav-popularmanufacturers li a').not('.makeBlack').click(motors.ajax.getModels);
    }
    if (typeof (motors) == 'object' && typeof (motors.filter) == 'object' && typeof (motors.structure) == 'object') {
        $('.toggleManufacturers').click(motors.structure.toggleManufacturers);
        $('.toggleManufacturersStock').click(motors.structure.toggleManufacturersStock);

        $('.give-feedback').click(motors.structure.displaySurvey);
    }

    //.attr("href", document.location.href);
    $('.reset-search').attr("href", location.protocol + "//" + location.host + document.location.pathname); // .attr("href", location.protocol + "//" + location.host)

    // Remove turdlets
    //    if ($('#homepage-panel').length == 0) {
    //        if ($('[id$=hid_vehicleId]').val() != "") {
    //            //added by Mat F to accomodate car-{id} only on thisis sites
    //            if (document.body.className.indexOf('thisis') < 0 && window.location.pathname.indexOf('car-') < 0 && window.location.pathname.indexOf('cotw-') < 0) {

    //                if ((typeof motors.curtain != 'undefined')) {
    //                    motors.curtain.drop();
    //                }
    //                motors.curtain.setCurtainIndex();
    //                motors.curtain.wait(true);
    //                $selector = $('[id$=vehicleDetailsHolder]');
    //                $selector.find('.ajax-close, .close-text, .close, .closetext, .closebottom').each(function () {
    //                    $(this).bind('click', function () {
    //                        motors.ajax.close($selector.attr('id'));
    //                    });
    //                });
    //            }
    //        }
    //        //invalidUI(validateForm('#nav-postcode')); // show postcode validation
    //    }

    if (typeof (motors) == 'object' && typeof (motors.filter) == 'object' && typeof (motors.search.updateNavigatorCounts) == 'function') {
        motors.search.updateNavigatorCounts();
    }

});

/* Autocomplete call */
function completeMe(sel) {
    //makesure element exists
    if (sel.length) {
        //call autocomplete plugin using postcode/address service service
        $(sel).autocomplete('/completion', {
            //width
            width: 190,
            //keep cache minimum
            cacheLength: 1,
            //search within results
            matchContains: true,
            //add 'motloc' param to get string plus first letter of input value
            extraParams: {
                'c': function () { return 'motlocsimple' + $(sel).val().substring(0, 1).toLowerCase() }
            },
            //parse returned data into a usable object
            parse: function (data) {
                var dtArr = [];
                for (i = 2; i < data.length; i = i + 2) {
                    //push first item and individual location id into array
                    dtArr.push(data[i].split('|')[1] + '|' + data[i].split('|')[2]);
                }
                //use map function to process arr into object
                return $.map(dtArr, function (row) {
                    //return object
                    return {
                        //entire array item
                        data: row,
                        //only firt part of the item
                        value: row.split('|')[0],
                        result: row.split('|')[0]
                    };
                });
            },
            //place uid(2nd part of array item) in a span around the first item of arrray item
            formatItem: function (item) {
                return '<span id="' + item.split('|')[1] + '">' + item.split('|')[0] + '</span>';
            }
        })
        //when selected add extra uid attr to input
        .result(function (event, data) {
            //only on seo page
            if (sel.indexOf('location') > -1) {
                $(sel).attr('locid', data.split('|')[1]);
            }
        })
        //auto select content on focus
        .bind('click', function () {            
            $(this).select();
        });
    }
}
/* end ac */
//$(document).ready(function () {
//    //list each field that needs autocomplete
//    var acArr = ['#nav-postcode', '#location', '#location2', '#used-postcode', '#dealer-postcode'];
//    //for each field if it exists apply autocomplete
//    for (var i = 0; i < acArr.length; i++) {
//        if (acArr[i].length) {
//            completeMe(acArr[i]);
//        }
//    }
//});
