(function(jQuery, global) {

    global.SearchManager = {
        SEARCH_FORM_ID: "search",
        _errorComponents: [],
        _markupProgress: 0,
        _sandbox : null,
        
        setSandBox : function(sandbox)
        {
            this._sandbox = sandbox;
        },
        getSandBox : function()
        {
            return this._sandbox;
        },
        setErrorComponents: function(compId, action) {

            if(action == "add") {
                this._errorComponents.push(compId);
                return true;
            } else if(action == "remove") {
                for(var i=0; i<this._errorComponents.length; i++){
                    if(this._errorComponents[i] == compId){
                        this._errorComponents.splice(i,1);
                        return true;
                    }
                }
            }
            return false;
        },
        isErrorComponents: function() {
            return this._errorComponents.length > 0;
        },
        getCheckboxEvent : function()
        {
            //hack, if lower than jQUery 1.4, liveQuery kicks in and it doesn't work right with change
            // and when jQuery 1.4.2 jquery().live() kicks in and it doesn't work right with click on checkbox
            return (jQuery().jquery.indexOf("1.4.2") < 0) ? "click" : "change";
        },
        initializeEvents : function() {
        
            //hack, if lower than jQUery 1.4, liveQuery kicks in and it doesn't work right with change
            // and when jQuery 1.4.2 jquery().live() kicks in and it doesn't work right with click on checkbox
            var checkboxClickEvent = SearchManager.getCheckboxEvent();

            /* click event for category checkbox / radio buttons in the search page */
            jQuery("div#standardSearchCategory input:checkbox").livequery(checkboxClickEvent, function() {
                SearchManager.getMarkup(jQuery(this).attr('id'));
            }, "div#standardSearchCategory");
           
            jQuery("div#standardSearchCategory input:radio").livequery(checkboxClickEvent, function() {
                SearchManager.getMarkup(jQuery(this).attr('id'));
            }, "div#standardSearchCategory");

            /* click event for custom search entries (checkbox / radio buttons) in the search page */
            jQuery("div#customSearchCategory input:checkbox").livequery(checkboxClickEvent, function() {
                SearchManager.getMarkup(jQuery(this).attr('id'));
            }, "div#customSearchCategory");

            jQuery("div#customSearchCategory input:radio").livequery(checkboxClickEvent, function() {
                SearchManager.getMarkup(jQuery(this).attr('id'));
            }, "div#customSearchCategory");

            
            //Due to JQuery 1.4.2 .live() bug :check click events for IE must happen before all
            //other event registration or it won't fire in IE.
            SearchManager.searchSecondaryFiltersEvents();
            
            var searchForm =  jQuery("form#" + this.SEARCH_FORM_ID);
            var oThis = this;
            var _progress;

            function getMarkupProgress(item) {
                if(SearchManager._markupProgress == 1) {
                    clearInterval(eval(item));
                    SearchManager._markupProgress = 0;
                    searchFormSubmit();
                }
            }

            function searchFormSubmit() {
                var proceed = !(SearchManager.isErrorComponents());
                if(proceed) {
                    searchForm.submit();
                    return true;
                } else {
                    return false;
                }
            }

            jQuery("a.searchButton").click(function() {
                if(SearchManager._markupProgress == 0) {
                    searchFormSubmit();
                    return false;
                } else {
                    //Wait for the response before submitting to check for errors
                    _progress = setInterval(function(){getMarkupProgress("_progress")}, 300);
                }
                return false;
            });

            /* Change event for all the dropdowns in the search page */
            jQuery("select.searchdropdown").livequery('change', function() {
                SearchManager.getMarkup(jQuery(this).attr('id'));
            });

            jQuery("select.rangeDropdown").live('change', function() {
                if (jQuery(this).hasClass("min")) {
                    SearchManager.limitMaxToMin(this, SearchManager.getMarkup);
                } else {
                    SearchManager.getMarkup(jQuery(this).attr('id'));
                }
            });



            /* click event for clear all link */
            jQuery(".inv_search_clearAll").livequery('click', function() {
                SearchManager.getMarkup(jQuery(this).attr('id'));
                //Below code is to collapse the open filtets in the show me filter section
                jQuery("div.filterItem").removeClass("openFilterItem");
            });

            /* blur event for vin/stock# */
            jQuery("#inv_search_stockOrVIN").livequery('change', function() {
                removeErrorDisplay(jQuery(this));
                if (SearchManager.validateStockOrVIN() && !SearchManager.isErrorComponents()) {
                    SearchManager.getMarkup(jQuery(this).attr('id'));
                }
            });

            /* ENTER key event for  vin/stock#  */
            jQuery("#inv_search_stockOrVIN").livequery('keydown', function(event) {
                if (event.keyCode == 13) {
                    removeErrorDisplay(jQuery(this));
                    if (SearchManager.validateStockOrVIN() && !SearchManager.isErrorComponents()) {
                        SearchManager.getMarkup(jQuery(this).attr('id'));
                    }
                }
            });

            /* Focus event for  vin/stock#  */
            jQuery("#inv_search_stockOrVIN").livequery('focus', function() {
                removeErrorDisplay(jQuery(this));
            });

            /* Click event for  vin/stock#  */
            jQuery("#inv_search_stockOrVIN").livequery('click', function() {
                removeErrorDisplay(jQuery(this));
            });
            
            function removeErrorDisplay(obj) {
                SearchManager.removeErrorDisplay(obj);
            }

            /* blur event for zip code text */
            jQuery("#inv_search_zipCode").livequery('change', function() {
                removeErrorDisplay(jQuery(this));
                if(SearchManager.validateZip() && !SearchManager.isErrorComponents()) {
                    SearchManager.getMarkup(jQuery(this).attr('id'));
                }
            });

            /* ENTER key event for zip code text */
            jQuery("#inv_search_zipCode").livequery('keydown', function(event) {
                if (event.keyCode == 13) {
                    removeErrorDisplay(jQuery(this));
                    if(SearchManager.validateZip() && !SearchManager.isErrorComponents()) {
                        SearchManager.getMarkup(jQuery(this).attr('id'));
                    }
                }
            });

            jQuery("#inv_search_zipCode").livequery('click', function() {
                removeErrorDisplay(jQuery(this));
            });
            jQuery("#inv_search_zipCode").livequery('focus', function() {
                removeErrorDisplay(jQuery(this));
            });

            /* change event for within radius dropdown */
            jQuery("#inv_search_radius").livequery('change', function() {
                SearchManager.getMarkup(jQuery(this).attr('id'));
            });

            jQuery("#inv_search_priceToggle").livequery('change', function() {
                SearchManager.getMarkup(jQuery(this).attr('id'));
            });

            jQuery("#inv_search_monthlyPaymentToggle").livequery('change', function() {
                SearchManager.getMarkup(jQuery(this).attr('id'));
            });



            /* Method to tweak IE for the select width issue */
            //TODO: this is a hack that needs a better solution
            if (jQuery.browser.msie && jQuery.browser.version  < 9.0) {
                if (document.compatMode === "CSS1Compat") //standard strict rendering
                {
                    SearchManager.selectWidthSizeForCIR2_VSR2_UnderStrictMode();
                }
                else
                {
                    SearchManager.selectWidthSize();
                }
            }



            jQuery("select.min").livequery("change", function () {
                SearchManager.limitMaxToMin(this, null);
            });

            if (jQuery.browser.msie) {
                jQuery("select.max").livequery("change", function() {
                    var thisSelect = jQuery(this);
                    var optionLen = Number(thisSelect.find('option').length);
                    if (optionLen > 1) {
                        var minSelect = jQuery(thisSelect.prev("select.min"));
                        var minIndex = Number(minSelect.attr('selectedIndex'));
                        var maxIndex = thisSelect.attr('selectedIndex');
                        if (maxIndex < minIndex) {
                            thisSelect.attr('selectedIndex', minIndex - 1);
                        }
                    }
                });
            }

            jQuery(".min").livequery(jQuery.browser.msie ? "click" : "change", function () {
                SearchManager.limitMaxToMin(this, null);
            });
        },

        removeErrorDisplay : function(obj)
        {
            var newObj = "#"+obj.attr('id')+"_errorMsg_container";
            jQuery(newObj).remove();
            obj.removeClass("error_highlight");
        },

        limitMaxToMin: function(select, callBack) {
            var jqSelect = jQuery(select);
            var optionLen = Number(jqSelect.find('option').length);
            if (optionLen > 1) {
                var minIndex = select.selectedIndex;
                var jqMaxSelect = jqSelect.next("select.max");
                var maxSelect = jqMaxSelect[0];
                var maxIndex = maxSelect.selectedIndex;
                if(maxIndex < minIndex -1) {
                    maxSelect.selectedIndex = minIndex-1;
                }
                jqMaxSelect.children().each(function () {
                    var me = jQuery(this);
                    var thisIndex = me.index() + 1;
                    me.removeAttr("disabled");
                    me.removeClass("optDisabled");
                    if (thisIndex < minIndex)
                    {
                        me.attr("disabled", "disabled");
                        me.addClass("optDisabled")
                    }
                });
            }
            if (callBack instanceof Function) {
                callBack(jqSelect.attr('id'));
            }
        },

        renderMarkupInIEBrowser: function(msg) {
            jQuery("Markup", msg).children().each( function() {
                var $ele = jQuery(this);
                var id = $ele.attr('id');

                if (id === 'inv_results_container') {
                    var t = jQuery(this).text();
                    jQuery("#" + id).html(t);
                } else {
                    jQuery("#" + id).replaceWith(this.xml);
                }
            });
        },

        renderMarkupInOtherBrowsers: function(msg) {
            jQuery("Markup", msg).children().each( function() {
                var $ele = jQuery(this);
                var id = $ele.attr('id');
                if (id == 'inv_results_container' || id == 'inv_search_count_container') {
                    var t = jQuery(this).text();
                    jQuery("#" + id).html(t);
                } else {
                    var target = jQuery('#' + id);
                    var html = '';
                    var serializer = new XMLSerializer();
                    jQuery(this).children().each(function() {
                        html += serializer.serializeToString(this);
                    });
                    target.empty();
                    target.append(html);
                    //Perserve space between text & checkbox
                    if (id == 'inv_search_new_container' || id == 'inv_search_used_container' || id == 'inv_search_certified_container') {
                        target.children('label').prepend('&nbsp;');
                    }

                }
            });
        },

        updateSortByColoum: function(value) {
        	jQuery('#sortCol').attr('value', value);
        },

        updateSelectedIndex: function(value) {
            jQuery('#selectIndex').attr('value', value);
        },

        updateSortDir: function(value) {
        	        	jQuery('#sortDir').attr('value', value);
        },

        updateRange: function(){
            SearchSliders.updateSliders();
        },

        getMarkup: function(componentId) {
                    	SearchManager._markupProgress = 2;            	
            SearchManager.updateSortByColoum('');
            SearchManager.updateSelectedIndex('');
            SearchManager.updateSortDir('');
            // Remove component from error field if found
            SearchManager.setErrorComponents(componentId,'remove');
            var postParameters = jQuery("form#" + SearchManager.SEARCH_FORM_ID).serialize();
            var url = "searchVehicles.ajax?componentId=" + componentId;
            var hiddenValue = jQuery("input[name='pageContext']");            jQuery.ajax({
                type: "POST",
                url: url,
                data: postParameters,
                dataType: "xml",
                success: function(data) {
                    var isError = SearchManager.getErrorMarkup(data);
                    if (isError) {
                        // Mark as error field
                        SearchManager.setErrorComponents(componentId,'add');
                        SearchManager._markupProgress = 1;
                        return false;
                    }

                    SearchManager._markupProgress = 1;
                    // Proceed with search only if all the fields are valid
                    var proceed = !(SearchManager.isErrorComponents());
                    if(proceed) {
                        if (jQuery(hiddenValue).val() === "VehicleSearchResults") {
                            SearchManager.fadeInResults();
                        }                                                
                        if (jQuery.browser.msie) {
                            SearchManager.renderMarkupInIEBrowser(data);
                        } else {
                            SearchManager.renderMarkupInOtherBrowsers(data);
                        }
                        SearchManager.raiseRenderingCompletedEvent();
                        //Below code is to fire the pixe tag
                        if (jQuery(hiddenValue).val() === "VehicleSearchResults") {
                            // update the page context:
                            var params = jQuery("form#" + SearchManager.SEARCH_FORM_ID).serialize();
                            // If there is no search param in postParameters, then set search=All
                            var st = (params.indexOf('search=') === -1) ? 'search=new&search=preowned&search=certified&' + params : params;
                            ContextManager.updateProperties(st);
                            SearchManager.firePixelTag();
                        }
                        SearchManager.updateRange();
                    }
                    SearchManager._markupProgress = 0;
                    SearchManager.registerZIndex();                                        if(getParameter("saved") =="true") {                    	jQuery("#search").submit();                    }                    
                },
                error: function(request, status, error)
                {
                }
            });
        },
        /**
         * raise Cobalt.Website.Common.Events.RenderingCompleted event so modules framework on Results page has a chance to
         * perform necessary actions
         */
        raiseRenderingCompletedEvent: function()
        {
            var sandbox = this.getSandBox();
            if (!sandbox) { return; }
            sandbox.raise(null, Cobalt.Website.Common.Events.RenderingCompleted, {sourceModule:"Legacy_SearchManager", componentId:"Legacy_SearchManager"});
        },

        firePixelTag: function() {
            EventManager.publish({
                eventName:'com.cobaltgroup.ws.view.results.inventory'
            });
        },

        fadeInResults: function() {
            jQuery("#resultsContainer,#inv_results_container").hide().fadeIn(3000);
        },

        getErrorMarkup: function(data) {
            var errorFlag = false;
            jQuery(data).find('Errors').each(function() {
                var id = jQuery(this).find('div').attr('id');
                var errorMsg = jQuery(this).find('div').text();
                SearchManager.createErrorDisplay(id, errorMsg);
                errorFlag = true;
            });
            return errorFlag;
        },
        createErrorDisplay: function(id, errorMsg) {
            var errorMsg_container = id+'_errorMsg_container';
            if(jQuery("#" + errorMsg_container)){
                jQuery("#" + errorMsg_container).remove()
            }
            jQuery("#" + id).after('<span id="'+errorMsg_container+'" class="inv_search_errorMsg_container"></span>');
            jQuery(("#"+errorMsg_container)).html(errorMsg + '<span id="leftarrow"></span>');
            jQuery("#" + id).addClass("error_highlight");
        },

        selectWidthSize: function() {
            jQuery("div#vehSearchPrimaryCriteria select.searchdropdown").livequery('mouseover', function() {

                SearchManager.restoreSelectWidth(jQuery(this));

                var currentWidth = jQuery(this).width();
                var currentCSSWidth = jQuery(this).css('width');
                jQuery(this).attr("defaultWidth", currentCSSWidth);

                //-------ie quirks mode compatible only--------
                jQuery(this).css({"width":"auto","position":"absolute"});
                var autoWidth = jQuery(this).width();
                if (autoWidth < currentWidth)
                {
                    jQuery(this).css({"width":currentCSSWidth,"position":"relative"});
                }
            });

            jQuery("div#vehSearchPrimaryCriteria select.searchdropdown").livequery('mouseout', function() {

                /*In IE mouseout will be triggered on two occassion in the select component.
                 //1. When we mouse out of the the select component
                 //2. When we go and select any of the options in the select component.:-)
                 //The second options shouldn't happen, because of this we are not able to select any of
                 // of the options. To fix this issue we can detect whether the onmouseout event being fired
                 //is accurate or not.You can do this by checking for window.event.toElement which is this case
                 //is null.
                 */
                if (window.event.toElement) {
                    SearchManager.restoreSelectWidth(jQuery(this));
                }
            });

            jQuery("div#vehSearchPrimaryCriteria select.searchdropdown").livequery('change', function() {
                SearchManager.restoreSelectWidth(jQuery(this));
            });

            jQuery("div#vehSearchPrimaryCriteria select.searchdropdown").livequery('blur', function() {
                SearchManager.restoreSelectWidth(jQuery(this));
            });
        },

        restoreSelectWidth: function(thisComponent) {
            var defaultCssWidth = jQuery(thisComponent).attr("defaultWidth");

            //--- ie quirks mode compatible only
            thisComponent.css({"width":defaultCssWidth,"position":"relative"});
            thisComponent.css("z-index", "10");
        },

        validateStockOrVIN: function () {
            var id = "inv_search_stockOrVIN";
            var obj = jQuery('#'+id);
            var stockOrVIN = jQuery.trim(obj.val());
            SearchManager.setErrorComponents(id, 'remove');
            if (stockOrVIN == '') {
                obj.attr('value', '');
                return true;
            }
            if(SearchManager.checkInvalidField(id)) {
                SearchManager.createErrorDisplay(id, ERRORMESSAGE_ENTER_REQUIRED_DATA);
                SearchManager.setErrorComponents(id, 'add');
                return false;
            }
            return !SearchManager.isErrorComponents();

        },
        validateZip: function () {
            var id = "inv_search_zipCode";
            var obj = jQuery('#'+id);
            var zip = jQuery.trim(obj.val());
            SearchManager.setErrorComponents(id, 'remove');
            if (zip === '') {
                obj.attr('value', '');
                return true;
            }
            try {
                var errorMsg = zip + " " + INVALID_ZIP_CODE;
                if(SearchManager.checkInvalidField(id)) {

                    SearchManager.createErrorDisplay(id, errorMsg);
                    SearchManager.setErrorComponents(id, 'add');
                    return false;
                }
                return true;
            }
            catch (err) {
                if (typeof(handleException) !== "undefined") {
                    handleException(err);
                }
                return false;
            }
        },
        checkInvalidField: function(id) {
            try {
                FormUtility.resetErrors();
                var someForm = document.forms["search"];
                var badFields = FormUtility.getBadlyFormatted(someForm);
                for(var i=0; i < badFields.length; i++) {
                    if(badFields[i].id == id) {
                        return true;
                    }

                }
                return false;
            } catch(err) {
                handleException(err);
                return false;
            }
        },

        getSelectedText: function (element) {
            var jqElement = jQuery(element);
            var sibInputs = jqElement.parents(".subFiltersContainer").find("input:checked");
            var selectedStr = "";
            if (sibInputs.length > 0) {
                var sibInpLen = sibInputs.length;
                selectedStr = "<span>" + SELECTED + ":&nbsp;";
                for (var i = 0; i < sibInpLen; i++) {
                    var sibId = jQuery(sibInputs[i]).attr("id");
                    if (i > 0) {
                        selectedStr += ", "
                    }
                    selectedStr += jQuery("label[for=" + sibId + "]").html();
                }
                selectedStr += "</span>";
            }
            var selectedTextElem = jqElement.parents("div.filterItem").find("div.selectedText");
            jQuery(selectedTextElem).html(selectedStr);
        },

        BadFormatError: function(id) {
            jQuery("#" + id).addClass("error_highlight");
            jQuery("#" + id).after('<span id="inv_search_errorMsg_container"></span>');
            jQuery("#inv_search_errorMsg_container").html(ERRORMESSAGE_ENTER_REQUIRED_DATA + '<span id="leftarrow"></span>');
        },

        searchSecondaryFiltersEvents: function() {
            SearchManager.registerZIndex();
            jQuery("div.filterItem").livequery("click", function(e)
            {
                var srcElement = e.target;

                if (SearchManager.isCustomDropdownControl(srcElement)) {
                    SearchManager.doCustomDropdownControlEvent(srcElement);
                }

                else if (SearchManager.isCheckboxControl(srcElement)) {
                    SearchManager.doCheckboxEvent(srcElement);
                }
            },"form#search");
        },

        registerZIndex: function() {
            var filterItems = jQuery("div.filterItem");
            var zIndex = filterItems.length;
            jQuery(filterItems).each(function(index){
                jQuery(this).css("z-index", zIndex);
                zIndex--;
            });
        },

        /**
         * find whether we clicked within a custom dropdown
         * @param element
         */
        isCustomDropdownControl:function(element)
        {
            var toggleImgClassName = ".filterToggleImage";
            var contextContainer = jQuery("#secondaryFilters");

            return jQuery(element).closest(toggleImgClassName, contextContainer).length > 0;
        },

        isCheckboxControl:function(element)
        {
            return (jQuery(element).is("#secondaryFilters input:checkbox"));
        },

        doCheckboxEvent: function(checkbox)
        {
            if (!checkbox || !checkbox.id)
            {
                throw new Error("doCheckboxEvent: illegal arg");
            }

            SearchManager.getSelectedText(checkbox);
            SearchManager.getMarkup(checkbox.id);
        },

        doCustomDropdownControlEvent: function(element)
        {
            //if dropdown is open
            if (jQuery(element).hasClass("sprite-filterArrowOpen"))
            {
                jQuery(element).removeClass("openFilterItem sprite-filterArrowOpen");
                jQuery(element).children(".handleFilterLabel").removeClass("sprite-filterArrowOpen");

                SearchManager.turnOffContentLayer(element);
            }
            else
            {
                jQuery(element).addClass("openFilterItem sprite-filterArrowOpen");
                SearchManager.turnOnContentLayer(element);
            }
        },

        turnOffContentLayer:function(srcElement)
        {
            SearchManager.setContentLayerAttr(srcElement, "absolute", "none");
        },

        turnOnContentLayer:function(srcElement)
        {
            SearchManager.setContentLayerAttr(srcElement, "absolute", "block");
        },

        setContentLayerAttr:function(srcElement, position, display)
        {
            var parent = SearchManager.findFilterItemParent(srcElement);

            if (parent && parent.length > 0)
            {
                var contentLayer = jQuery(".subFiltersContainer", parent);
                contentLayer.css({position:position, display:display, top:"20px"});
            }
        },

        findFilterItemParent: function(element)
        {
            var jElement = jQuery(element);
            var filterItemClass = "filterItem";

            if (jElement.hasClass(filterItemClass))
            {
                return jElement;
            }

            return jQuery(jElement).parent("." + filterItemClass);
        },

        selectWidthSizeForCIR2_VSR2_UnderStrictMode: function()
        {
            jQuery("div#vehSearchPrimaryCriteria select.searchdropdown").livequery('mouseenter', function() {
                SearchManager.restoreSelectWidthForCIR2_VSR2_UnderStrictMode(jQuery(this));
                var currentWidth = jQuery(this).width();
                var currentCSSWidth = jQuery(this).outerWidth();

                jQuery(this).attr("defaultWidth", currentCSSWidth);

                //-------ie standard mode compatible only--------
                var offsetTop = jQuery(this).position().top;
                var offsetLeft = jQuery(this).position().left;
                jQuery(this).css({width:"auto",position:"absolute",top: offsetTop + "px", left: offsetLeft+"px"});
                var autoWidth = jQuery(this).width();
                if (autoWidth < currentWidth)
                {
                    jQuery(this).css({"width":currentCSSWidth,"position":"absolute"});
                }
            });
            jQuery("div#vehSearchPrimaryCriteria select.searchdropdown").livequery('mouseleave', function() {
                if (window.event.toElement) {
                    SearchManager.restoreSelectWidthForCIR2_VSR2_UnderStrictMode(jQuery(this));
                }
            });
            jQuery("div#vehSearchPrimaryCriteria select.searchdropdown").livequery('change', function() {
                SearchManager.restoreSelectWidthForCIR2_VSR2_UnderStrictMode(jQuery(this));
            });
            jQuery("div#vehSearchPrimaryCriteria select.searchdropdown").livequery('blur', function() {
                SearchManager.restoreSelectWidthForCIR2_VSR2_UnderStrictMode(jQuery(this));
            });
        },
        restoreSelectWidthForCIR2_VSR2_UnderStrictMode:function(thisComponent)
        {
                var defaultCssWidth = jQuery(thisComponent).attr("defaultWidth");
            //-------ie standard mode compatible only--------
            thisComponent.css({"width":defaultCssWidth,"position":"static"});
            thisComponent.css("z-index", "10");
        }
    };

    global.SearchSliders = {
        createSliders: function() {
            try {
                var sliderSelects = [];
                sliderSelects.push({selects:jQuery('select#inv_search_minPrice, select#inv_search_maxPrice'),values:[]});
                sliderSelects.push({selects:jQuery('select#inv_search_minMonthlyPayment, select#inv_search_maxMonthlyPayment'),values:[]});
                sliderSelects.push({selects:jQuery('select#inv_search_minYear, select#inv_search_maxYear'),values:[]});
                sliderSelects.push({selects:jQuery('select#inv_search_minMPG, select#inv_search_maxMPG'),values:[]});
                sliderSelects.push({selects:jQuery('select#inv_search_minMileage, select#inv_search_maxMileage'),values:[]});

                var numSelects = sliderSelects.length;
                function createSlider(elem, selects){
                    var me = jQuery(elem);
                      me.slider({
                        min: 0,
                        max: optionSize,
                        range: true,
                        values: [select.selects[0].selectedIndex, select.selects[1].selectedIndex+1],
                        slide: function(event, ui) {
                            if(ui.values[0]==optionSize||ui.values[1]==0){
                                return false;
                            }
                            var minUiValue = ui.values[0];
                            var maxUiValue = ui.values[1];
                            selects[0].selectedIndex = minUiValue;
                            selects[1].selectedIndex = maxUiValue-1;
                        },
                        stop: function(event, ui) {
                            if(ui.value == ui.values[0]) {
                                jQuery(selects[0]).change();
                            } else {
                                jQuery(selects[1]).change();
                            }
                        }
                      });
                    me.addClass("spriteContainer sprite-slider_back");
                    me.addClass("spriteContainer sprite-slider_back");
                    me.children("a.ui-slider-handle").addClass("spriteContainer sprite-indicator1 indicator");
                }
                for(var i=0;i<numSelects;i++) {
                    var select = sliderSelects[i];
                    if(select.selects.length <= 0) {
                        continue;
                    }

                    var minSelect = jQuery(select.selects[0]);
                    var minOptions=minSelect.children("option");
                    var optionSize = minOptions.length;
                    createSlider(minSelect.parent('.range-selectors').prev('.searchSlider'), select.selects);

                }
            } catch (err) {
                if (typeof(handleException) !== "undefined") {
                    handleException(err);
                }
                else
                    throw err;

            }
        },

        updateSliders: function() {
            jQuery("#inv_search_priceRange_slider").slider('destroy');
            jQuery("#inv_search_monthlyPaymentRange_slider").slider('destroy');
            jQuery("#inv_search_yearRange_slider").slider('destroy');
            jQuery("#inv_search_mpgRange_slider").slider('destroy');
            jQuery("#inv_search_mileageRange_slider").slider('destroy');
            this.createSliders();
        },

        getMarkupSliderChange: function(elements) {
            var selects = jQuery(elements);
            if (selects.length > 0) {
                SearchManager.getMarkup(selects.eq(0).attr("id"));
            }
        }
    };

    jQuery(document).ready(function() {

        SearchManager.initializeEvents();
        SearchSliders.createSliders();

        /* Initiate the payment calculator events only if the payment div is available */
        if (jQuery("#inv_search_paymentTypeSelector").length > 0) {
            SearchPaymentCalculator.paymentCalculatorEvents();
        }

        var searchForm = document.getElementById("search");
        if(searchForm !== null && searchForm !== undefined && searchForm.nodeName == "FORM"){
            searchForm.reset();
        }
    });
    function getParameter(paramName) {  	  var searchString = window.location.search.substring(1),  	      i, val, params = searchString.split("&");  	  for (i=0;i<params.length;i++) {  	    val = params[i].split("=");  	    if (val[0] == paramName) {  	      return unescape(val[1]);  	    }  	  }  	  return null;  	}    
})(Cobalt.Core.JQueryFactory.getLatest(), window);

