﻿YAHOO.namespace("CSSearch");
YAHOO.CSSearch.AdvSearch = function() {
    /*********************** Private Properties ***********************/
    var g_oRespSchema = { resultsList: "d.Results" },
        g_sMnuCssClass = null,
        g_sBtnCssClass = null,
        g_iRange = 150,
        g_oSiteSearchColsData = null,
        g_HaveCarList = false,              //True indicates the carlist is available       
        g_IsInitiatedByPaginator = false,   //True=> Webservice hit is initialized by paginator buttons, avoids recreating the paginator
        g_BlockPaginationHndlr = false,     //True=>The pagination buttons are changed by clicking back or forward buttons, avoids the execution of hndlrHandlePagination
        g_IsSliderInitialized = false,      //True=>Slider is initialized for the first time and avoids rebinding the datatable
        g_IsQuickSearch = false,            //Avoids executing the code related to datatable
        g_AvoidBackPreviousHndlr = false,   //True =>One of the search buttons are clicked, avoids the execution of BackPreviousPage function
        g_SliderBtnsCreated = false,        //True indicates that the slider buttons are created
        g_SliderValuesSet = false,          //True indicates that the sliders max and min values are set
        g_IsTableFilteredBySlider = false,
        g_SetLabels4Btns = false,
        g_oDataTable = null,
        g_sCarListQryParamFromQryStr = null,
        g_oCarList = null,
        g_iTotalCount = null,
        g_oPaginator = null,
        g_iPageNum = null,
        g_oCarListDSCallback = null,
        g_onButtonsAvailable = null,
        g_iStockType = null,
        g_IsStockTypeRestricted = false,     //Avoids creating radio buttons in quick search
        g_bookmarkedSection = null,
        g_sSortItem = null,
        g_sUsedText = null,
        g_iRowsPerpage = 30,
        g_iStartPage = 1,
        g_onDataTblCreated = null,
        g_onDataTblFiltered = null,
        g_LogSearch = true;

    var g_oColumnDefs = [], g_SortFlags = [];

    var g_oSiteSearchCols = [
        { key: "DeptTypeID" },
        { key: "HeaderText" },
        { key: "Fields" },
        { key: "FormatString" }
    ];

    var g_oButtonList = {
        Year: { Type: "MenuButton", Label: "Year", DType: "int", Visible: false, CompareAsEQ: { 0: true }, SelectedValue: null, DSKey: "year", QSKey: "yr", DataSource: "/Services/Inventory.asmx/GetYears", ResponseSchema: { resultsList: "d.Results" }, ContainerID: "Select_Your_Vehicle", Callback: null },
        Make: { Type: "MenuButton", Label: "Make", DType: "string", Visible: false, CompareAsEQ: { 0: true }, SelectedValue: null, DSKey: "make", QSKey: "mk", DataSource: "/Services/Inventory.asmx/GetMakes", ResponseSchema: { resultsList: "d.Results" }, ContainerID: "Select_Your_Vehicle", Callback: null },
        Model: { Type: "MenuButton", Label: "Model", DType: "string", Visible: false, CompareAsEQ: { 0: true }, SelectedValue: null, DSKey: "model", QSKey: "mdl", DataSource: "/Services/Inventory.asmx/GetModels", ResponseSchema: { resultsList: "d.Results" }, ContainerID: "Select_Your_Vehicle", Callback: null },
        //SubModel: { Type: "MenuButton", Label: "SubModel", DType: "string", Visible: false, CompareAsEQ: { 0: true }, SelectedValue: null, DSKey: "subModel",QSKey: "smdl", DataSource: "/Services/Inventory.asmx/GetSubModels", ResponseSchema: { resultsList: "d.Results" }, ContainerID: "Select_Your_Vehicle", Callback: null },
        MinDFList: { Type: "SliderButton", Label: "Min Price", DType: "int", Visible: false, CompareAsEQ: { 0: true, 1: true }, SelectedValue: 0, DSKey: "minDFList", QSKey: "lsMn", MinValue: 0, MaxValue: 200000, ContainerID: "Price_Range", SliderObj: null, ScalingFactor: null },
        MaxDFList: { Type: "SliderButton", Label: "Max Price", DType: "int", Visible: false, CompareAsEQ: { 0: true, 2: true }, SelectedValue: 200000, DSKey: "maxDFList", QSKey: "lsMx", MinValue: 0, MaxValue: 200000, ContainerID: "Price_Range", SliderObj: null, ScalingFactor: null }
        //        MinMileage: { Type: "SliderButton", Label: "Min Mileage", DType: "int", CompareAsEQ: { 0: true, 1: true }, SelectedValue: 0, DSKey: "minMileage",QSKey: "yr", MinValue: 0, MaxValue: 300, ContainerID: "Mileage_Range", SliderObj: null, ScalingFactor: null },
        //        MaxMileage: { Type: "SliderButton", Label: "Max Mileage", DType: "int", CompareAsEQ: { 0: true, 2: true }, SelectedValue: 0, DSKey: "maxMileage",QSKey: "yr", MinValue: 0, MaxValue: 300, ContainerID: "Mileage_Range", SliderObj: null, ScalingFactor: null }
    };

    var g_sCarListDataSource = "/Services/Inventory.asmx/SearchCars",
        g_sSiteSearchColsDataSource = "/Services/Inventory.asmx/GetSiteSearchCols";

    var g_oCarListResponseSchema = {
        resultsList: "d.Results",
        fields: [
            { key: "CarID" }, { key: "CustomerID" }, { key: "SiteDefID" }, { key: "DealerStockID" }, { key: "VIN" }, { key: "StockType" }
            , { key: "Year" }, { key: "Make" }, { key: "Model" }, { key: "SubModel" }
            , { key: "DFList" }, { key: "DisplayDFList" }, { key: "DisplayListPrice" }, { key: "DisplayMSRP" }, { key: "DisplayInternetPrice" }
            , { key: "ExtColor" }, { key: "IntColor" }, { key: "Mileage" }
            , { key: "First80w60h" }, { key: "Certified" }, { key: "IsSpecial" }, { key: "SiteDetailURL" }, { key: "SiteURL" }
            , { key: "Engine" }, { key: "EngineSize" }, { key: "ModelNum" }
        ],
        metaFields: { totalCount: "d.TotalCount", iMinPrice: "d.iMinPrice", iMaxPrice: "d.iMaxPrice", PageNum: "d.PageNum", CarsPerPage: "d.CarsPerPage" }
    },

      g_oSiteSearchColsResponseSchema = {
          resultsList: "d.Results",
          fields: g_oSiteSearchCols
      };

    /*         
    * Called from MasterInit and CBProcessGrdConfigData functions which sends a request
    *       to fetch data
    *  
    *  @param {object} oCallback - Contains the functions to be executed on success and failure of data request
    *  @param {string} sParameter - A parameter which will be sent along with the request
    *  @param {string} sDataSource - Contains the web service method which acts as a data source for requests
    *  @param {object} oResponseSchema - Holds the response schema fields 
    */
    var RequestData = function(oCallback, sParameter, sDataSource, oResponseSchema) {
        var oDataSource = new YAHOO.util.DataSource(sDataSource);
        oDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; //  set the content-type to JSON

        //This line is required to establish JSON Communincation between YUI Datasource and Asp.net WebService
        oDataSource.connMgr.initHeader("Content-Type", "application/json; charset=utf-8", true);
        oDataSource.responseSchema = oResponseSchema;
        oDataSource.sendRequest(sParameter, oCallback, null);
        oDataSource = null;
    },

    /*         
    * It creates querystring for datasource call to get MenuItems based on Button Menu Type
    */
    CreateReqParam4MenuDSQuery = function(sButton) {
        var sMenuRequestParams = "?stockType=" + g_iStockType + "&year=null&make=null&model=null&subModel=null&minDFList=null&maxDFList=null&minMileage=null&maxMileage=null";
        for (sBtnIndex in g_oButtonList) {
            if (sButton == sBtnIndex) {
                sMenuRequestParams = sMenuRequestParams.replace(g_oButtonList[sBtnIndex].DSKey + "=null&", "");
                continue;
            }
            if (g_oButtonList[sBtnIndex].SelectedValue != null) {
                if (YAHOO.lang.isNumber(g_oButtonList[sBtnIndex].SelectedValue))
                    sMenuRequestParams = sMenuRequestParams.replace(g_oButtonList[sBtnIndex].DSKey + "=null", g_oButtonList[sBtnIndex].DSKey + "=" + g_oButtonList[sBtnIndex].SelectedValue);
                else
                    sMenuRequestParams = sMenuRequestParams.replace(g_oButtonList[sBtnIndex].DSKey + "=null", g_oButtonList[sBtnIndex].DSKey + "=\"" + EncodeString(g_oButtonList[sBtnIndex].SelectedValue) + "\"");
            }
        }
        return sMenuRequestParams;
    },

    /*         
    * It creates querystring for Datasource call to get Carlist data
    */
    CreateReqParam4CarListFromBtns = function(SortCol, SortType, pageNum) {
        var oQS = new Querystring();
        var sMenuRequestParams = "?logSearch=" + g_LogSearch + "&stockType=" + g_iStockType
                 + "&year=null&make=null&model=null&subModel=null&VIN=null&dealerStockID=null&minDFList=null&maxDFList=null&minMileage=null&maxMileage=null&numOfDoors=null&" + GetParam(oQS, "certified", "cert", false, false) + "onLotAfter=null&onLotBefore=null&";
        for (var sBtnIndex in g_oButtonList) {
            if (g_oButtonList[sBtnIndex].SelectedValue != null) {
                if (YAHOO.lang.isNumber(g_oButtonList[sBtnIndex].SelectedValue))
                    sMenuRequestParams = sMenuRequestParams.replace(g_oButtonList[sBtnIndex].DSKey + "=null", g_oButtonList[sBtnIndex].DSKey + "=" + g_oButtonList[sBtnIndex].SelectedValue);
                else
                    sMenuRequestParams = sMenuRequestParams.replace(g_oButtonList[sBtnIndex].DSKey + "=null", g_oButtonList[sBtnIndex].DSKey + "=\"" + EncodeString(g_oButtonList[sBtnIndex].SelectedValue) + "\"");
            }
        }
        sMenuRequestParams += "&sortCol=";
        sMenuRequestParams += SortCol == null ? null : ("\"" + SortCol + "\"");
        sMenuRequestParams += "&sortType=";
        sMenuRequestParams += SortType == null ? null : ("\"" + SortType + "\"");
        sMenuRequestParams += "&pageNum=" + pageNum;
        sMenuRequestParams += "&carsPerPage=" + g_iRowsPerpage + "&mpghmn=null&output=json\"";
        return sMenuRequestParams;
    },

    /*         
    * Called by the functions BackPreviousPage, MasterInit. Creates datasource request parameter by decoding the querystring
    *   parameters.    
    */
    CreateReqParam4CarListFromQueryString = function() {
        var oQS = new Querystring();
        var sParams = "?logSearch=" + g_LogSearch + "&" + GetParam(oQS, "sortCol", "sortCol", false, false);
        sParams += GetParam(oQS, "sortType", "sortType", false, false);
        sParams += GetParam(oQS, "VIN", "vin", false, false);
        sParams += GetParam(oQS, "dealerStockID", "stk", false, false);
        sParams += GetParam(oQS, "stockType", "dpt", true, true);
        sParams += GetParam(oQS, "year", "yr", true, true);
        if (g_oButtonList["Year"] != null)
            g_oButtonList["Year"].SelectedValue = QSVal(oQS, "yr", true, true);
        sParams += GetParam(oQS, "make", "mk", false, false);
        if (g_oButtonList["Make"] != null)
            g_oButtonList["Make"].SelectedValue = QSVal(oQS, "mk", false, true);
        sParams += GetParam(oQS, "model", "mdl", false, false);
        if (g_oButtonList["Model"] != null)
            g_oButtonList["Model"].SelectedValue = QSVal(oQS, "mdl", false, true);
        sParams += GetParam(oQS, "subModel", "smdl", false, false);
        sParams += GetParam(oQS, "minMileage", "miMn", true, true);
        sParams += GetParam(oQS, "maxMileage", "miMx", true, true);
        sParams += GetParam(oQS, "numOfDoors", "nmDrs", true, true);
        sParams += GetParam(oQS, "certified", "cert", false, false);
        sParams += GetParam(oQS, "minDFList", "lsMn", true, true);
        g_oButtonList["MinDFList"].SelectedValue = QSVal(oQS, "lsMn", true, true);
        sParams += GetParam(oQS, "maxDFList", "lsMx", true, true);
        g_oButtonList["MaxDFList"].SelectedValue = QSVal(oQS, "lsMx", true, true);
        sParams += GetParam(oQS, "onLotAfter", "dtAft", false, false);
        sParams += GetParam(oQS, "onLotBefore", "dtBef", false, false);
        sParams += "pageNum=1&carsPerPage=" + g_iRowsPerpage + "&";
        sParams += GetParam(oQS, "mpghmn", "mpghmn", true, true);
        sParams += "&output=json\"";
        return sParams;
    },

    /*         
    * Sets the selected values for the buttons from the query string.
    */
    SetBtnValuesFromQryString = function(sQry) {
        var sParams = null, oQryStrValue = null, oQS = new Querystring();

        if (sQry != null) {
            //sQry contains the previous search parameters list
            sParams = sQry.split('&');
            for (var i in sParams) {
                if (sParams[i].indexOf("pageNum") > -1) {
                    g_iPageNum = Number(sParams[i].split('=')[1]);
                    break;
                }
            }
        }
        for (sBtnType in g_oButtonList) {
            if (!sQry || sQry == "") {
                //Try to fetch the value from querystring
                if (g_oButtonList[sBtnType] != null && !g_IsQuickSearch) {
                    g_oButtonList[sBtnType].SelectedValue = QSVal(oQS, g_oButtonList[sBtnType].QSKey, false, true);
                }
                continue;
            }

            //Otherwise, we have to rely on the anchor (sQry)
            for (var i in sParams) {
                if (sParams[i].toLowerCase().indexOf(g_oButtonList[sBtnType].DSKey.toLowerCase()) < 0) continue;
                if (sParams[i].indexOf("null") > -1) continue;
                oQryStrValue = sParams[i].split('=')[1];
                break;
            } //var i in sParams

            oBtn = YAHOO.widget.Button.getButton('Btn' + sBtnType);
            if (oQryStrValue != null) {
                var sValue = unescape(oQryStrValue.replace(/["]/g, ""));
                if (g_SetLabels4Btns)
                    oBtn.set("label", sValue);

                if (g_oButtonList[sBtnType].Type == 'SliderButton') {
                    g_oButtonList[sBtnType].SelectedValue = Number(sValue);
                }
                else {
                    g_oButtonList[sBtnType].SelectedValue = sValue;
                }
            }
            else {
                g_oButtonList[sBtnType].SelectedValue = null;
                if (g_SetLabels4Btns)
                    oBtn.set("label", g_oButtonList[sBtnType].Label);
            }
            oQryStrValue = null;

        } //sBtnType in g_oButtonList
    },

    InitializeHistory = function() {
        g_bookmarkedSection = YAHOO.util.History.getBookmarkedState("QryString");
        var initialSection = g_bookmarkedSection || 'N/A';
        YAHOO.util.History.register("QryString", initialSection, BackPreviousPage);
        // Initialize the browser history management library.
        try {
            YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
        } catch (e) {
        };
    },

    BackPreviousPage = function(sQry) {
        if (!g_AvoidBackPreviousHndlr) {
            g_BlockPaginationHndlr = true;
            g_IsInitiatedByPaginator = false;
            g_LogSearch = false;
            if (sQry.indexOf('N/A') > -1) {
                sQry = CreateReqParam4CarListFromQueryString();
            }
            g_SetLabels4Btns = true;
            SetBtnValuesFromQryString(sQry);
            RequestData(g_oCarListDSCallback, sQry, g_sCarListDataSource, g_oCarListResponseSchema);
        }
        g_AvoidBackPreviousHndlr = false;
    },

    /*         
    * Called by the function CreateCustomColumns and creates a hyperlink using the data and fields that
    *   are passed as parameters.
    *  
    *  @param {object} Data - Contains the Car record  
    *  @param {object} Fields - Contains the Fields  
    *  @param {string} FormatString - Contains the format of the link  
    */
    CreateLink = function(Data, Fields, FormatString) {
        var cols = Fields.split(",");
        //Do not try FormatString.replace(new RegExp(sRegExp, "g"), Data[cols[i]]) for it always say Invalid quanititier;
        // It is expensive to use sRegExp =eval("/\\{"+i+''+ "\\}/g");FormatString = FormatString.replace(sRegExp, Data[cols[i]] ? Data[cols[i]] : "")
        for (var i in cols) {
            FormatString = FormatString.replace('{' + i + '}', Data[cols[i]] ? Data[cols[i]] : "").replace('{' + i + '}', Data[cols[i]] ? Data[cols[i]] : "");
        }
        return FormatString;
    },

     CreateCustomColumns = function() {
         var sField;
         for (var i in g_oCarList) {
             for (var j in g_oColumnDefs) {
                 sField = g_oColumnDefs[j]["key"];
                 g_oCarList[i][sField] = CreateLink(g_oCarList[i], g_oSiteSearchColsData[j].Fields, g_oSiteSearchColsData[j].FormatString);
             }
         }
     },

     CreateMenu = function(btn, menuItems) {
         if (YAHOO.lang.isNumber(menuItems[0])) {
             for (var idx in menuItems)
                 menuItems[idx] = String(menuItems[idx]);
         }
         var oMenu = btn.getMenu();
         oMenu.clearContent();
         oMenu.addItems(menuItems);
         oMenu.render(btn);
     },

    /*         
    * Called by the functions hndlrOnMenuItemSelected, hndlrOnSliderEnd, hndlrOnResetClick, hndlrRowsPerPageChange.
    *    Sends request to get filtered car data   
    */
     GetFilteredCarList = function(pageNum) {
         var sReqParam = CreateReqParam4CarListFromBtns(null, null, pageNum);
         g_AvoidBackPreviousHndlr = true;
         g_HaveCarList = false;
         YAHOO.util.History.navigate("QryString", sReqParam);
         //Hit webservice to get car records
         RequestData(g_oCarListDSCallback, sReqParam, g_sCarListDataSource, g_oCarListResponseSchema);
     },

    /*         
    * Called by the functions CBProcessGrdConfigData,CBProcessCarData.
    *    Destroys the existing datatable and creates a new table with passed data records.   
    */
     CreateDataTable = function() {
         if (g_oDataTable != null)
             g_oDataTable.destroy();

         var oDsRecords = new YAHOO.util.DataSource(g_oCarList);
         oDsRecords.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
         oDsRecords.responseSchema = {
             fields: g_oColumnDefs
         };
         g_oDataTable = new YAHOO.widget.DataTable("CSData", g_oColumnDefs, oDsRecords);
         g_oDataTable.subscribe("cellClickEvent", hndlrRegisterHistoryForCellClick);

         //Do not recreate the paginator when the datatable is being created by paginator buttons
         if (!g_IsInitiatedByPaginator) {
             if (g_oPaginator != null)
                 g_oPaginator.destroy();
             g_oPaginator = new YAHOO.widget.Paginator({
                 rowsPerPage: g_iRowsPerpage,
                 totalRecords: g_iTotalCount,
                 template: "{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}",
                 alwaysVisible: true,
                 updateOnChange: true,
                 pageLinks: 5,
                 //rowsPerPageOptions: g_rowsPerPageOptions,
                 containers: ["CSPagingTop", "CSPagingBtm"]
             });
             g_oPaginator.subscribe("pageChange", hndlrHandlePagination);
             g_oPaginator.render();
         }
         //YAHOO.util.Event.addListener(YAHOO.util.Dom.getElementsByClassName("yui-pg-rpp-options"), "change", hndlrRowsPerPageChange);
         g_oPaginator.setPage(g_iPageNum, false);

         if (g_onDataTblCreated)
             g_onDataTblCreated.fire(g_oDataTable);

         if (g_onDataTblFiltered && g_LogSearch)
             g_onDataTblFiltered.fire();
     },

     CreateContainerDiv = function(containerID) {
         //If the container does not exist, create
         var oBtnContainer = YAHOO.util.Dom.get(containerID);
         if (!oBtnContainer) {
             oBtnContainer = AddSepCloseElem(YAHOO.util.Dom.get("CSBtnMaster"), "div", containerID, "ETInlineBlock", null);
             AddSepCloseElem(oBtnContainer, "h2", null, null, null).innerHTML = containerID.replace(/_/g, " ");
         }
     },

    /*         
    *  Creates Menu Buttons and adds event handlers to them
    */
    CreateMenuBtns = function(type, args) {
        for (var sBtnIndex in g_oButtonList) {
            if ((g_IsQuickSearch && g_oButtonList[sBtnIndex].Visible == false) || g_oButtonList[sBtnIndex].Type == "SliderButton")
                continue;
            if (!g_IsQuickSearch)
                CreateContainerDiv(g_oButtonList[sBtnIndex].ContainerID); //Create the containerDiv

            //Create Button
            oButton = new YAHOO.widget.Button({
                type: "menu",
                label: g_oButtonList[sBtnIndex].SelectedValue == null ? g_oButtonList[sBtnIndex].Label : g_oButtonList[sBtnIndex].SelectedValue,
                lazyloadmenu: false,
                id: "Btn" + sBtnIndex,
                menu: ["No Items"],
                container: g_oButtonList[sBtnIndex].ContainerID,
                menuminscrollheight: 100,
                menumaxheight: 215
            });
            YAHOO.util.Dom.addClass(oButton, g_sBtnCssClass);

            //Subscribe to menu click events
            oMenu = oButton.getMenu();
            oMenu.subscribe("click", hndlrOnMenuItemSelected, oButton);

            var oBtnMenuCallback =
                {
                    success: CBMenuItemsAvailable,
                    failure: CBProcessError,
                    argument: oButton
                };
            g_oButtonList[sBtnIndex].Callback = oBtnMenuCallback;
            if (g_oButtonList[sBtnIndex].SelectedValue == null)
                RequestData(oBtnMenuCallback, CreateReqParam4MenuDSQuery(sBtnIndex), g_oButtonList[sBtnIndex].DataSource, g_oRespSchema);
            else
                CreateMenu(oButton, [g_oButtonList[sBtnIndex].SelectedValue]);
            //CSS Hooks
            if (!YAHOO.util.Config.alreadySubscribed(oMenu.showEvent, MenuCSHdrFtr, oMenu)) {
                oMenu.showEvent.subscribe(MenuCSHdrFtr, oMenu, true);
            }
        }
    },

    /*         
    *  Creates Slider Buttons and adds event handlers to them
    */
    CreateSliderBtns = function(type, args) {
        if (g_IsQuickSearch) return;
        for (var sBtnIndex in g_oButtonList) {
            if (g_oButtonList[sBtnIndex].Type == "MenuButton")
                continue;
            CreateContainerDiv(g_oButtonList[sBtnIndex].ContainerID); //Create the containerDiv
            var sLabel = null;
            //Set the min or max price if it is passed through querystring
            if (g_oButtonList[sBtnIndex].SelectedValue == 0
              || g_oButtonList[sBtnIndex].SelectedValue == 200000
              || g_oButtonList[sBtnIndex].SelectedValue == null)
                sLabel = g_oButtonList[sBtnIndex].Label;
            else
                sLabel = sBtnIndex.indexOf("DFList") > -1 ? Convert2PrettyString(g_oButtonList[sBtnIndex].SelectedValue + "") : g_oButtonList[sBtnIndex].SelectedValue + " MPG";

            //Menu instance body element will house a slider instance
            // Menu width = Thumb Width + g_iRange
            var oSliderMenu = new YAHOO.widget.Menu("menu" + sBtnIndex, { width: "170px" });

            oButton = new YAHOO.widget.Button({
                type: "menu",
                label: sLabel,
                lazyloadmenu: false,
                id: "Btn" + sBtnIndex,
                menu: oSliderMenu,
                container: g_oButtonList[sBtnIndex].ContainerID
            });

            //Once the new Button is created, "appendTo" event will be used 
            //  to render its Menu instance into the same DOM element specified as the containing element
            //  for the Button.
            oButton.on("appendTo", hndlrAppendSlider2Btn, oButton);

            //"beforeShow" event handler to the Menu instance 
            //  will instantiate the Slider.
            oSliderMenu.subscribe("beforeShow", hndlrOnMenuBeforeShow, oButton);
        }
        g_SliderBtnsCreated = true;
        //Set Max and Min values for the sliders only if the carlist is available
        if (!g_SliderValuesSet && g_HaveCarList & !g_IsTableFilteredBySlider)
            SetSliderMinMaxValues();
    },

    /*         
    *  Creates Reset(Clear All) and search buttons
    */
    CreateResetSearchBtns = function() {
        if (g_IsQuickSearch) {

            //Create Radio Button Div
            var oStockTypeGrp = new YAHOO.widget.ButtonGroup({ id: "CSRadio", name: "StockType", container: "CSStockType" });
            if (!g_IsStockTypeRestricted) {
                oStockTypeGrp.addButtons([
                 { id: "btnRadNew", label: "New", value: "1", checked: true, onclick: { fn: HndlrbtnNewClick} },
                 { id: "btnRadUsed", label: g_sUsedText, value: "2", onclick: { fn: HndlrbtnUsedClick} }
               ]);
            }

            //Add Search Button
            var oSearchButton = new YAHOO.widget.Button({ type: "link", id: "CSSearch", label: "<span>Search</span>", container: "CSSrchReset", onclick: { fn: hndlrbtnQuickSearchClick} });

            //Add Reset Button
            var oResetButton = new YAHOO.widget.Button({ type: "link", id: "CSReset", label: "Reset", container: "CSSrchReset", onclick: { fn: hndlrOnResetClick} });
            return;
        }

        //Create Reset DIV
        AddSepCloseElem(YAHOO.util.Dom.get("CSBtnMaster"), "div", "CSReset", "ETInlineBlock", null);
        var oResetButton = new YAHOO.widget.Button({ type: "link", id: "btnReset", label: "Clear All", container: "CSReset", onclick: { fn: hndlrOnResetClick} });

        //Create VIN/Stock DIV and link
        oTmpDIV = AddSepCloseElem(YAHOO.util.Dom.get("CSBtnMaster"), "div", "CSBtmStockVIN", null, null);
        var oToggleStockIdVinButton = new YAHOO.widget.Button({ type: "link", label: "Stock #/VIN", id: "btnToggleStockVin", container: "CSBtmStockVIN", onclick: { fn: hndlrOnToggleStockIdVinClick} });

        //Add Search Button for VIN/Stock #
        var oSearchButton = YAHOO.util.Dom.get("btnSearch");
        YAHOO.util.Event.addListener(oSearchButton, "click", hndlrbtnSearchClick);
    },

    /*         
    *  Creates Sort Buttons and adds event handlers to them
    */
    CreateSortBtns = function() {
        var oSortList = new Array(["Year", "Year"], ["Make", "Make"], ["Model", "Model"], ["SubModel", "Trim"], ["DFList", "Price"]), ItemCtr, sSortBody = "";
        for (ItemCtr in oSortList) {
            var sElement = "<a id=\"CSSORTTEXT\" class=\"SORTTEXT\" href=\"#\">SORTTEXT</a>";
            sElement = sElement.replace(/SORTTEXT/g, oSortList[ItemCtr][1]);
            sSortBody = sSortBody.concat(sElement);
            YAHOO.util.Event.addListener("CS" + oSortList[ItemCtr][1], "click", hndlrOnSortClick, oSortList[ItemCtr][1]);
            g_SortFlags.push({ key: oSortList[ItemCtr][1], value: false });
        }
        var oDiv = YAHOO.util.Dom.get("CSSort");
        oDiv.innerHTML += sSortBody;
    },

    /*         
    *  Rebinds all buttons whose selected value is null 
    *
    *  @param {object} menuItemText - The selected menu item text. 
    *  @param {object} btn - The button object. 
    */
    RebindMenuBtns = function(menuItemText, btn) {
        g_AvoidBackPreviousHndlr = true;
        var sSelVal = null, sReqParam = null;
        for (var sBtnIndex in g_oButtonList) {
            if (g_IsQuickSearch && g_oButtonList[sBtnIndex].Visible == false)
                continue;
            //Send request only when the button does not have a selected value
            sSelVal = g_oButtonList[sBtnIndex].SelectedValue;
            if (sSelVal == null && g_oButtonList[sBtnIndex].Type == "MenuButton") {
                sReqParam = CreateReqParam4MenuDSQuery(sBtnIndex);
                RequestData(g_oButtonList[sBtnIndex].Callback, sReqParam, g_oButtonList[sBtnIndex].DataSource, g_oRespSchema);
            }
        }
    },

    /*         
    * Sets the Max and Min values on the slider buttons
    */
    SetSliderMinMaxValues = function() {
        var iMinMaxValue = null, sBtnIndex = null, oSliderBtn = null;
        for (sBtnIndex in g_oButtonList) {
            if (g_oButtonList[sBtnIndex].Type == "MenuButton")
                continue;
            iMinMaxValue = sBtnIndex.indexOf("Min") < 0 ? g_iCurrentMax : g_iCurrentMin;
            //Don't allow excluded values
            if (iMinMaxValue == -99999.99) iMinMaxValue = sBtnIndex.indexOf("Min") < 0 ? 200000 : 0;
            oSliderBtn = YAHOO.widget.Button.getButton("Btn" + sBtnIndex);
            oSliderBtn.set("label", Convert2PrettyString(iMinMaxValue.toString()));
        }
        if (g_IsTableFilteredBySlider)
            g_IsTableFilteredBySlider = false;
    },

    /*         
    *  Resets the lables and selected values of the buttons
    */
    ResetLabelsAndSelectedValuesOfBtns = function() {
        //Reset the selected values of all the buttons
        for (sBtnIndex in g_oButtonList) {
            if (g_IsQuickSearch && g_oButtonList[sBtnIndex].Visible == false)
                continue;
            oButton = YAHOO.widget.Button.getButton('Btn' + sBtnIndex);
            oButton.set("label", g_oButtonList[sBtnIndex].Label); //Reset the previous selected menuItem which is shown on the button

            if (g_oButtonList[sBtnIndex].Type === 'MenuButton') {
                g_oButtonList[sBtnIndex].SelectedValue = null; //Reset the SelectedValue property of g_oButtonList to null                       
            }
            else if (g_oButtonList[sBtnIndex].Type === 'SliderButton') {
                sBtnID = oButton._button.id, sThumbID = sBtnID.replace('Btn', "").replace('-button', 'thumb');
                var sMaxMinColumnName = sBtnID.indexOf("Min") < 0 ? "MaxValue" : "MinValue";
                g_oButtonList[sBtnIndex].SelectedValue = g_oButtonList[sBtnIndex][sMaxMinColumnName];
            }
        }
        if (!g_IsQuickSearch) {
            //Clear the contents of textboxes in StockVin Div
            YAHOO.util.Dom.get("txtStockID").value = "";
            YAHOO.util.Dom.get("txtVin").value = "";
            //Make the Vin/StockID lookup section invisible
            YAHOO.util.Dom.addClass(YAHOO.util.Dom.get("CSStockVinSearch"), "DfltHidden");
        }
    },

    SetPrettyLbl4Btn = function(btn, btnType, value2Display) {
        if (btnType.indexOf("DFList") > -1)
            btn.set("label", Convert2PrettyString(value2Display));
        else if (btnType.indexOf("Mileage") > -1)
            btn.set("label", value2Display + " MPG");
    },

    /****************************** Event Handlers *******************************/
    /*         
    *  This is handler for radio Button. It will reload Button Menu for New Cars. 
    */
    HndlrbtnNewClick = function() {
        if (g_iStockType != 1) {
            g_iStockType = 1;
            RebindMenuBtns(null, null);
        }
    },

    /*         
    *  This is handler for radio Button . It will reload Button Menu for Used Car. 
    */
    HndlrbtnUsedClick = function() {
        if (g_iStockType != 2) {
            g_iStockType = 2;
            RebindMenuBtns(null, null);
        }
    },

    /* 
    *  This function is triggered when the menuitem of the buttons is clicked or selected. 
    *    It filters datatable and rebinds other buttons
    *  
    *  @param {String} eventType - The name of the event that was fired.
    *  @param {Array} eventArgs - Collection of arguments sent when the event was fired. 
    *  @param {object} oBtn - The button object. 
    */
    hndlrOnMenuItemSelected = function(eventType, eventArgs, oBtn) {
        var oMenuItem = eventArgs[1];   //Menu Item instance that was the target of the event                
        if (oMenuItem) {
            var sMenuItemText = oMenuItem.cfg.getProperty("text");  //cfg represents MenuModule's Config object which can be used to get the properties of the object
            oBtn.set("label", sMenuItemText);
            g_oButtonList[oBtn._button.id.replace("Btn", "").replace("-button", "")].SelectedValue = sMenuItemText;
        }
        g_LogSearch = true;
        if (!g_IsQuickSearch)
            GetFilteredCarList(g_iStartPage);
        RebindMenuBtns(sMenuItemText, oBtn);
    },

    /*
    *   This function is triggered when slider button is clicked. It sets the slider constraints
    *       and initializes the slider if the button is clicked for the first time
    */
     hndlrOnMenuBeforeShow = function(eventType, eventArgs, oBtn) {
         var sBtnID = oBtn._button.id, oSlider = null, iScalingFactor = 0, iScalingFactorInverse = 0;
         var sMenuButtonType = sBtnID.replace(new RegExp("(Btn)|(-button)", "gi"), "");
         var sLabel = oBtn._configs.label.value.replace(',', '').replace('$', '') - 0;

         //The number of pixels the thumb can move on the slider
         var MinValue = g_oButtonList[sMenuButtonType].MinValue,
                    MaxValue = g_oButtonList[sMenuButtonType].MaxValue;
         g_oButtonList[sMenuButtonType].ScalingFactor = (g_iRange / (MaxValue - MinValue));
         iScalingFactor = g_oButtonList[sMenuButtonType].ScalingFactor;
         iScalingFactorInverse = (1 / iScalingFactor);

         var sBackgroundID = sMenuButtonType + 'bg', sThumbID = sMenuButtonType + 'thumb', oSlider = null;
         oSlider = g_oButtonList[sMenuButtonType].SliderObj;
         if (oSlider != null) {
             oSlider.thumb.resetConstraints();
             oSlider.setStartSliderState();
             oSlider.thumb.startOffset = [0, 0];
             oSlider.animate = false;
             oSlider.setValue(Math.round(iScalingFactor * (sLabel - MinValue)), true);
             return;
         }

         /*    
         *   Instantiate the Slider
         *     
         *   @param <String> slider-bg - the id of the slider's background element
         *   @param <String> slider-thumb - the id of the thumb element
         *   @param  <int> 0 - the number of pixels the element can move left
         *   @param  <int> g_iRange - the number of pixels the element can move right                                 
         */
         oSlider = YAHOO.widget.Slider.getHorizSlider(sBackgroundID, sThumbID, 0, g_iRange, 1);
         oSlider.animate = false;

         //oSlider.setValues(Math.round(m_iScalingFactor * MinValue), Math.round(m_iScalingFactor * MaxValue), true);
         // Set the initial value of the Slider instance. The default value for MinValue slider
         //  will be the min DFList and for MaxValue slider the value is max DFList
         if (sMenuButtonType.indexOf("Min") > -1) {
             if (YAHOO.lang.isNumber(sLabel)) {
                 oSlider.setValue(Math.round(iScalingFactor * (sLabel - MinValue - (iScalingFactorInverse))), true);
             }
             else {
                 SetPrettyLbl4Btn(oBtn, sMenuButtonType, MinValue + "");
                 oSlider.setValue(0, true);
             }
         }
         else {
             if (YAHOO.lang.isNumber(sLabel)) {
                 oSlider.setValue(Math.round(iScalingFactor * (sLabel - MinValue + (iScalingFactorInverse))), true);
             }
             else {
                 SetPrettyLbl4Btn(oBtn, sMenuButtonType, MaxValue + "");
                 oSlider.setValue(150, true);
             }
         }
         g_IsSliderInitialized = true; //Slider is initialized for the first time. 
         oSlider.subscribe("change", hndlrOnSliderChange, oBtn);
         oSlider.subscribe("slideEnd", hndlrOnSliderEnd, oBtn);
         g_oButtonList[sMenuButtonType].SliderObj = oSlider;
     },

    /*
    *  Apppends the slider to the button on the "appendTo" event of the button
    *  
    *  @param <String> e - Event Type
    *  @param {object} oBtn - Button object which fired this event.           
    */
    hndlrAppendSlider2Btn = function(e, oBtn) {
        // Add Slider markup to the Menu instance's body element
        var sBtnID = oBtn._button.id;
        var sMenuButtonType = sBtnID.replace(new RegExp("(Btn)|(-button)", "gi"), "");
        var sSliderBody = "<div id=\"XXXXXX\" title=\"Slider\" class=\"slider-bg\" height=\"15px\" tabindex=\"1\" ><div id=\"YYYYYY\" class=\"slider-thumb\" ><img src=\"/media/images/thumb-n.gif\" width =\"20px\" height=\"15px\" /></div></div>",
                        sSliderBody = sSliderBody.replace('XXXXXX', sMenuButtonType + "bg").replace('YYYYYY', sMenuButtonType + 'thumb');

        var oSliderMenu = oBtn.getMenu();
        oSliderMenu.setBody(sSliderBody);

        //Render the Menu instance into the element specified as the Button instance's container
        oSliderMenu.render(this.get("container"));
    },

    /*
    *   Event Handler for slideEnd event on the slider button. The datatable
    *       is filtered. It does not accept any parameters. 
    *   
    */
    hndlrOnSliderEnd = function() {
        //Avoids binding the datatable when the slider is first initialized   
        if (g_IsSliderInitialized) {
            g_IsSliderInitialized = false;
            return;
        }
        g_IsTableFilteredBySlider = true;
        g_LogSearch = true;
        GetFilteredCarList(g_iStartPage);
        RebindMenuBtns(null, null);
        g_IsSliderInitialized = false;
    },

    /*
    *   Event Handler for change event on the slider button. The new x offset is
    *       converted to relative DFList and is saved in g_oButtonList[sButtonType].SelectedValue. 
    *       The reason we save these values is the slideEnd event does not pass any parameters.
    * 
    *   @param <String> SelectedValue -  newOffset|x (pixel value)
    *   @param <object> oBtn - Button object
    */
    hndlrOnSliderChange = function(SelectedValue, oBtn) {
        var sButtonType = oBtn._button.id.replace(new RegExp("(Btn)|(-button)", "gi"), "");
        var sThumbID = "".concat(sButtonType, 'thumb');
        var iScalingFactorInverse = 1 / g_oButtonList[sButtonType].ScalingFactor;
        //Avoids binding the datatable when the slider is first initialized
        if (g_IsSliderInitialized) {
            return;
        }
        g_oButtonList[sButtonType].SelectedValue = String(Math.round((SelectedValue * iScalingFactorInverse) + g_oButtonList[sButtonType].MinValue));
        SetPrettyLbl4Btn(oBtn, sButtonType, g_oButtonList[sButtonType].SelectedValue);
        g_IsSliderInitialized = false;
    },

    /*         
    * Event handler for the click event on sort items. It uses g_SortFlags to store the current order
    *   of the records for a specified sSortItem. If the same sortitem is clicked again then the 
    *   records are displayed in reverse order.
    *  
    *  @param {String} sSortItem - Clicked SortItem        
    */
    hndlrOnSortClick = function(eventType, sortItem) {
        g_sSortItem = sortItem;
        var sSortType = null;
        for (var j = 0; j < g_SortFlags.length; j++) {
            if (g_SortFlags[j].key == sortItem) {
                sSortType = g_SortFlags[j].value ? "ASC" : "DESC";
                g_SortFlags[j].value = !(g_SortFlags[j].value);
            }
        }
        if (sortItem == "Trim") sortItem = "SubModel";
        if (sortItem == "Price") sortItem = "DFList";
        g_LogSearch = false;
        var sParam = CreateReqParam4CarListFromBtns(sortItem, sSortType, g_iStartPage);
        RequestData(g_oCarListDSCallback, sParam, g_sCarListDataSource, g_oCarListResponseSchema);
        g_IsInitiatedByPaginator = false;
        g_AvoidBackPreviousHndlr = true;
    },

    /*         
    * Event handler for "click" event on Reset button. It recreates the menu for the buttons
    *   and displays all the data in the datatable irrespective of the query string. 
    */
    hndlrOnResetClick = function(e) {
        //After Reset when Non_Slider Button is click we can still get the min and max value for Slide Button.       
        g_IsSliderInitialized = false;
        g_IsInitiatedByPaginator = false;
        ResetLabelsAndSelectedValuesOfBtns();
        RebindMenuBtns(null, null);
        g_LogSearch = false;
        if (!g_IsQuickSearch)
            GetFilteredCarList(g_iStartPage);
    },

    hndlrHandlePagination = function(state) {
        if (g_BlockPaginationHndlr) {
            g_BlockPaginationHndlr = false;
            return;
        }
        var sSortType = null, sSortItem = g_sSortItem;
        for (var j = 0; j < g_SortFlags.length; j++) {
            if (g_SortFlags[j].key == sSortItem) {
                sSortType = g_SortFlags[j].value ? "DESC" : "ASC";
            }
        }
        if (sSortItem == "Trim") sSortItem = "SubModel";
        if (sSortItem == "Price") sSortItem = "DFList";
        var sParam = CreateReqParam4CarListFromBtns(sSortItem, sSortType, state.newValue);
        g_iPageNum = state.newValue;
        g_LogSearch = false;
        g_IsInitiatedByPaginator = true;
        RequestData(g_oCarListDSCallback, sParam, g_sCarListDataSource, g_oCarListResponseSchema);
        g_AvoidBackPreviousHndlr = true;
        YAHOO.util.History.navigate("QryString", sParam);
    },

    hndlrOnToggleStockIdVinClick = function() {
        var oToggleDiv = YAHOO.util.Dom.get("CSStockVinSearch");
        if (oToggleDiv.className == "DfltHidden") {
            YAHOO.util.Dom.removeClass(oToggleDiv, "DfltHidden");
        }
        else {
            //Clear the contents of textboxes in StockVin Div
            YAHOO.util.Dom.get("txtStockID").value = "";
            YAHOO.util.Dom.get("txtVin").value = "";
            YAHOO.util.Dom.addClass(oToggleDiv, "DfltHidden");
        }
    },

    hndlrbtnSearchClick = function() {
        //Get the StockNumber and Vin
        var sVin = YAHOO.util.Dom.get("txtVin").value.toUpperCase(), sStockId = YAHOO.util.Dom.get("txtStockID").value.toUpperCase();
        sVin = sVin.length == 0 ? "null" : "\"" + sVin.replace(/[" "]/g, "") + "\"";
        sStockId = sStockId.length == 0 ? "null" : "\"" + sStockId.replace(/[" "]/g, "") + "\"";
        if (sVin == "null" && sStockId == "null") return false;
        //Search
        var sCarListParameter = "?logSearch=true&stockType=" + g_iStockType + "&VIN=" + sVin + "&dealerStockID=" + sStockId + "&sortCol=null&sortType=null&year=null&make=null&model=null&subModel=null&minDFList=null&maxDFList=null&&minMileage=null&maxMileage=null&numOfDoors=null&certified=null&onLotAfter=null&onLotBefore=null&pageNum=1&carsPerPage=30&mpghmn=null&output=json\"";
        RequestData(g_oCarListDSCallback, sCarListParameter, g_sCarListDataSource, g_oCarListResponseSchema);
    },

     hndlrbtnQuickSearchClick = function() {
         var sHttp = null;

         //Even with restrction g_iStockType will have a value (even if it is just the default)
         if (g_iStockType == 1) sHttp = "/New-Cars/New-Car-Search.aspx?dpt=1#QryString=";
         else sHttp = "/Used-Cars/Used-Car-Search.aspx?dpt=2#QryString=";
         sHttp = sHttp.concat(EncodeString(CreateReqParam4CarListFromBtns(null, null, g_iStartPage)));
         location.href = sHttp;
     },

     hndlrRowsPerPageChange = function(e, args) {
         g_iRowsPerpage = g_oPaginator.getRowsPerPage();
         g_IsInitiatedByPaginator = true;
         g_LogSearch = false;
         GetFilteredCarList(g_iPageNum);
     },

     hndlrRegisterHistoryForCellClick = function(e) {
         if (Event.target.innerHTML.indexOf("href") > -1) {
             g_AvoidBackPreviousHndlr = true;
             YAHOO.util.History.navigate("QryString", CreateReqParametersString(g_sSortItem, g_iStockType, g_iPageNum));
         }
     },

    /********************************* Callback functions *******************************/
    /*
    *  Call back function for button menu items. It fires an event onButtonsAvailable and creates Sort buttons
    *  
    *  @param {String} requestStr - Contains the request object that was sent.
    *  @param {object} oParsedResponse - Has the return data
    *  @param {object} oPayload - The button object which is passed as an argument
    */
    CBMenuItemsAvailable = function(requestStr, oParsedResponse, oPayload) {
        CreateMenu(oPayload, oParsedResponse.results);
    },

    /* 
    *  Call back function for button list datasource. It fires an event onButtonsAvailable and creates Sort buttons
    *  
    *  @param {String} requestStr - Contains the request object that was sent.
    *  @param {object} oParsedResponse - Has the return data
    *  @param {object} oPayload - The same value as was passed in to the argument of the oCallback object literal
    */
    CBProcessButtonsData = function(requestStr, oParsedResponse, oPayload) {
        var oBtns = oParsedResponse.results[0], sBtnIndex = null;
        if (g_IsQuickSearch) {
            for (sBtnIndex in oBtns) {
                if (g_oButtonList[sBtnIndex] == null) { continue; }
                g_oButtonList[sBtnIndex].Visible = oBtns[sBtnIndex];
                g_oButtonList[sBtnIndex].ContainerID = "CSYMMS";
            }
        }
        //Add the menu and button classes
        YAHOO.util.Dom.addClass(YAHOO.util.Dom.get("CSBtnMaster"), g_sMnuCssClass);
        g_SetLabels4Btns = false;
        SetBtnValuesFromQryString(g_bookmarkedSection);
        g_onButtonsAvailable.fire();

        //Create Sort buttons only if it is not quick search
        if (!g_IsQuickSearch) {
            CreateSortBtns();
        }
    },

    /* 
    *  Call back function for grid config datasource. It creates g_oColumnDefs array
    *       and then creates the datatable
    *  
    *  @param {String} requestStr - Contains the request object that was sent.
    *  @param {object} oParsedResponse - Has the return data
    *  @param {object} oPayload - The same value as was passed in to the argument of the oCallback object literal
    */
    CBProcessGrdConfigData = function(requestStr, oParsedResponse, oPayload) {
        g_oSiteSearchColsData = oParsedResponse.results;

        //Create a g_oColumnDefs which is required for fetching carlist data
        //Do not use g_oColumnDefs.push for it is wrong order in IE// g_oColumnDefs.push({ key: i+"Header", label: g_oSiteSearchColsData[i].HeaderText });
        for (var i in g_oSiteSearchColsData)
            g_oColumnDefs[i] = { key: i + "Header", label: g_oSiteSearchColsData[i].HeaderText };

        //Get car list from database
        g_oCarListDSCallback =
           {
               success: CBProcessCarData,
               failure: CBProcessError,
               scope: null
           };
        if (g_bookmarkedSection != null) {
            RequestData(g_oCarListDSCallback, g_bookmarkedSection, g_sCarListDataSource, g_oCarListResponseSchema);
        }
        else
            RequestData(g_oCarListDSCallback, CreateReqParam4CarListFromQueryString(), g_sCarListDataSource, g_oCarListResponseSchema);
    },

    /* 
    *  Call back function for car list datasource. It creates the datatable
    *  
    *  @param {String} requestStr - Contains the request object that was sent.
    *  @param {object} oParsedResponse - Has the return data
    *  @param {object} oPayload - The same value as was passed in to the argument of the oCallback object literal
    */
    CBProcessCarData = function(requestStr, oParsedResponse, oPayload) {
        g_oCarList = oParsedResponse.results;
        CreateCustomColumns();
        g_HaveCarList = true;
        g_iTotalCount = oParsedResponse.meta.totalCount;
        g_iPageNum = oParsedResponse.meta.PageNum;
        g_iCurrentMin = oParsedResponse.meta.iMinPrice;
        g_iCurrentMax = oParsedResponse.meta.iMaxPrice;
        CreateDataTable();
        //Set Max and Min values for the sliders only if they are created
        if (g_SliderBtnsCreated && !g_IsTableFilteredBySlider) {
            SetSliderMinMaxValues();
            g_SliderValuesSet = true;
        }
        var oDiv = YAHOO.util.Dom.get("SearchResults");
        oDiv.innerHTML = "<span>Search Results (<span class=\"TotalCount\">" + g_iTotalCount + "</span>)</span>";
    },

   CBProcessError = function(requestStr, oParsedResponse, oPayload) { };

    return {
        /*       
        *  Entry point for all code in the file     
        *   - Asynchronous requests are sent to fetch Grid Config data, Button data and Carlist from database using webservice methods
        *
        *   @param {string} deptTypeID  
        *   @param {string} mnuCssClass - CSS Class to add to menus for the menu buttons
        *   @param {string} btnCssClass - CSS Class to add to buttons
        *   @param {bool} IsQuickSearch - Avoids execution of datatable code
        *   @param {string} usedText         
        */
        MasterInit: function(deptTypeID, mnuCssClass, btnCssClass, IsQuickSearch, usedText) {
            if (deptTypeID == null || deptTypeID.length == 0) {
                var iDeptType = null;
                if (!IsQuickSearch)
                    iDeptType = YAHOO.util.History.getQueryStringParameter("dpt");
                g_iStockType = iDeptType == null ? 1 : iDeptType;
            } else {
                g_iStockType = deptTypeID;
                g_IsStockTypeRestricted = true;
            }
            g_sBtnCssClass = btnCssClass;
            g_sMnuCssClass = mnuCssClass;
            g_IsQuickSearch = IsQuickSearch;
            g_sUsedText = usedText;
            g_onButtonsAvailable = new YAHOO.util.CustomEvent("onButtonsAvailable");
            g_onButtonsAvailable.subscribe(CreateMenuBtns);
            g_onButtonsAvailable.subscribe(CreateSliderBtns);
            g_onButtonsAvailable.subscribe(CreateResetSearchBtns);

            //Get Button data from database
            var oBtnListDSCallback =
            {
                success: CBProcessButtonsData,
                failure: CBProcessError,
                scope: null
            },
            sBtnDataSource = "/Services/Inventory.asmx/GetButtons?btnListType=1";
            RequestData(oBtnListDSCallback, null, sBtnDataSource, g_oRespSchema);

            if (!IsQuickSearch) {
                InitializeHistory();
                //Get Grid Config data            
                var oSiteSearchColsCallback =
                {
                    success: CBProcessGrdConfigData,
                    failure: CBProcessError,
                    scope: null
                };
                RequestData(oSiteSearchColsCallback, "?deptTypeID=" + g_iStockType, g_sSiteSearchColsDataSource, g_oSiteSearchColsResponseSchema);
            }
        },

        DataTblCreated: function() {
            g_onDataTblCreated = new YAHOO.util.CustomEvent("onDataTblCreated");
            return (g_onDataTblCreated);
        },

        DataTblFiltered: function() {
            g_onDataTblFiltered = new YAHOO.util.CustomEvent("onDataTblFiltered");
            return (g_onDataTblFiltered);
        }
    }
} ();