// Expects a list of arrModels (ModelInfo) in included ftl
var locateVehicles = [];
var VEHICLE_FILTER_ORDERING = ["model", "trans", "color", "engine", "stockId", "pageSize", "sortBy", "reverse", "pageNo"];
var DEFAULT_FILTER_VALUES = "All/All/All/All//10/BodyDesc/1/0";
// Whether the page accessed is vehicles-details type or new-vehicles-inventory type.
var isDetailsPage = false;
// Variable inventoryType is used in emailFiltered.ftl
var inventoryType = "new";

  /**
   * set the sorted order
   * @param container
   * @param countDiv
   * @param pageDivName
   */
var VehicleRenderer = function(container, countDiv, pageDivName)
{
  this.objListDiv = YAHOO.util.Dom.get(container);
  this.objCountDiv = YAHOO.util.Dom.get(countDiv);
  this.objPageDiv = pageDivName;
  this.currentPage = 0;
  this.pageSize = 10;
  this.ordering = 1;
  this.sortVehicles = null;
  this.currentVehicleSelection = [];
  this.reverseOrder = function(){
    this.ordering = this.ordering * -1;
    document.getElementById("reverseOrderSpan").className = (this.ordering == 1 ? "inventoryOrderUpImage" : "inventoryOrderDownImage");
  };

  /**
   * set the sorted order
   * @param ordering
   */
  this.setOrdering = function(ordering)
  {
    var order = parseInt(ordering, 10);
    if (isNaN(order))return;
    this.sortVehicles.setSortOrder(order);
    this.ordering = order;
    this.gotoPage(0);
  };

  /**
   * assign sorted vehicles
   * @param objSorter
   */
  this.setSorter = function(objSorter)
  {
    this.sortVehicles = objSorter;
    this.gotoPage(0);
  };

  /**
   * get the page size
   * @param pageSize
   */
  this.setPageSize = function(pageSize)
  {
    if (pageSize > 0){
      this.pageSize = pageSize;
    }
    this.gotoPage(0);
  };

  /**
   * go to the particular page
   * @param page
   */
  this.gotoPage = function(page)
  {
    page = Math.max(0, page);
    page = Math.min(page, Math.floor(this.currentVehicleSelection.length / this.pageSize));
    this.currentPage = page;
    this.renderPageDivs();
    if (this.currentVehicleSelection && this.currentVehicleSelection.length === 0){
      displayErrorMessage(errorMessages['nomodelforcombination']);
      return;
    }
    if (this.sortVehicles != null){
      this.currentVehicleSelection = this.sortVehicles.sort(this.currentVehicleSelection);
    }
    this.renderCurrentPage(this.currentVehicleSelection);
  };

  /**
   * render the page divs
   */
  this.renderPageDivs = function()
  {
    var strHTML = "";
    var pagesToLeft = 2;
    var numPages = Math.ceil(this.currentVehicleSelection.length / this.pageSize);
    if ((numPages - (this.currentPage + 1)) < 2){
      var diff = numPages - (this.currentPage + 1);
      pagesToLeft = pagesToLeft + (2 - diff);
    }
    var intMinPage = Math.max(0, this.currentPage - pagesToLeft);
    var intMaxPage = Math.min(numPages, intMinPage + 5);
    if (intMinPage > 1){
      strHTML += "... ";
    }
    for (var i = intMinPage; i < intMaxPage; i++){
      strHTML+= (i != this.currentPage)? "<a class='bodyTextLink' href='javascript:vehicleRenderer.gotoPage(" + i + ");navigateState();'>" + (i + 1) + "</a> " : (i + 1) + " ";
    }
    if (intMaxPage < numPages){
      strHTML += " ...";
    }
    YAHOO.util.Dom.get(this.objPageDiv + 'Top').innerHTML = strHTML;
    YAHOO.util.Dom.get(this.objPageDiv + 'Bottom').innerHTML = strHTML;
  };

  /**
   * go to the next page
   */
  this.nextPage = function()
  {
    this.gotoPage(this.currentPage + 1);
  };

  /**
   * go to the previous page
   */
  this.prevPage = function()
  {
    this.gotoPage(this.currentPage - 1);
  };

  /**
   * refresh the vehicle list
   * @param arrVehicleList
   */
  this.refreshVehicleList = function(arrVehicleList,isRequired)
  {
    this.currentVehicleSelection = arrVehicleList;
    this.renderCountDiv(isRequired);
    this.gotoPage(0);
  };

  /**
   * render the page
   * @param arrVehicleList
   */
  this.renderCurrentPage = function(arrVehicleList)
  {
    //if there is no vehicle then return
    if (!arrVehicleList || arrVehicleList.length == 0){
      return;
    }
    var strHTML = "";
    var startIndex = Math.max(0, this.currentPage * this.pageSize);
    var maxVehicleIndexForPage = Number(startIndex) + Number(this.pageSize);
    var endIndex = Math.min(maxVehicleIndexForPage, arrVehicleList.length);
    var vehicleTemplate = YAHOO.util.Dom.get("vehicleBlockTemplate").innerHTML;
    var noSwatch = '<span style="border: 1px solid #000000;"><img src="' + vfsBase + '/apps/img/color-na-new.gif" width="32" height="14"/></span>';
    var selectedYear = YAHOO.util.Dom.get("yearSelect").value;  // the year selected from the drop down.
    for (var i = startIndex; i < endIndex; i++){
      var cVehicle = arrVehicleList[i];
      var extSwatch = noSwatch;
      var intSwatch = noSwatch;
      if (cVehicle.ExteriorColorHex != null){
        extSwatch = '<span style="background-color: #' + cVehicle.ExteriorColorHex + ';"><img style="border: 1px solid #000000;" src="' + vfsBase + '/apps/img/null.gif" width="32" height="14"/></span>';
      }
      if (cVehicle.InteriorColorHex != null){
        intSwatch = '<span style="background-color: #' + cVehicle.InteriorColorHex + ';"><img style="border: 1px solid #000000;" src="' + vfsBase + '/apps/img/null.gif" width="32" height="14"/></span>';
      }
      //get the cookie
      var planTypeCookie = getCookie("PlanType");
      var planPrice = "";
      // set AXZ-plan divs to hidden initially
      var AXZPlanTypeDisplay = "Hidden";
      var XPlanTypeDisplay = "Hidden";
      var AXZDivDisplay = "Hidden";
      var AXZDisclaimerDiv = "";
      // checking the plan type is belongs to A/Z-plan
      if(planTypeCookie=="A" || planTypeCookie=="Z" || planTypeCookie=="AZ" || planTypeCookie=="AXZ" || planTypeCookie=="A/Z-PLAN"){
        planPrice = cVehicle.APlanPrice;
        //if planPrice is less than zero no need to visible
        if(planPrice > 0){
          AXZPlanTypeDisplay = "Visible";
          AXZDivDisplay = "Visible";
        }
        //set a/z-plan text
        AXZDisclaimerDiv = YAHOO.util.Dom.get('AZDisclaimerDiv');
        AXZDisclaimerDiv.innerHTML = arrStrings['apps.inventory.filter.AZPlanDisclaimer'];
        AXZDisclaimerDiv.style.display = "";
      }
      else if(planTypeCookie=="X" || planTypeCookie=="X-PLAN"){
        // checking the plan type is belongs to X-plan
        planPrice = cVehicle.XPlanPrice;
        //if planPrice is less than zero no need to visible
        if(planPrice > 0){
          XPlanTypeDisplay = "Visible";
          AXZDivDisplay = "Visible";
        }
        //set x-plan text
        AXZDisclaimerDiv = YAHOO.util.Dom.get('AZDisclaimerDiv');
        AXZDisclaimerDiv.innerHTML = arrStrings['apps.inventory.filter.XPlanDisclaimer'];
        AXZDisclaimerDiv.style.display = "";
      }
      var selectedModelInfo = getSelectedModel();
      var selectedYear = "";
      if (selectedModelInfo != null){
        selectedYear = selectedModelInfo.year;
      }
      /**
       *  function to render vehicles
       *  while rendeering AXZPRICE assign the axz values to renderer object
       *  arrange the price in the format
       */
      var renderObject =
      {
        "BODYDESC": cVehicle.BodyDesc,
        "DEALER_PA_CODE": cVehicle.DealerPaCode,
        "INV_LOCATION_TEXT": currentDealerPACode == cVehicle.DealerPaCode ? arrStrings['apps.inventory.info.location.instock'] : arrStrings['apps.inventory.info.location.extendedinv'],
        "EXTERIOR_COLOR_SWATCH": extSwatch,
        "INTERIOR_COLOR_SWATCH": intSwatch,
        "VIN": cVehicle.VIN,
        "MODEL_IMAGE_TAG": getImageTag(cVehicle.ThumbnailImage),
        "MODEL_NAME": cVehicle.Year + " " + cVehicle.FullModelDisplayName,
        "STOCK_ID": cVehicle.DealerStockId,
        "MODEL_ID": strModelInfoId + "",
        "EXTERIOR_COLOR": cVehicle.ExteriorColor,
        "INTERIOR_COLOR": cVehicle.InteriorColor,
        "ENGINE_DESC": cVehicle.EngineDesc,
        "TRANSMISSION": cVehicle.Transmission,
        "VEHICLE_ID": i + "",
        "PRICE": (userLanguage === "fr") ? currencyFormat(cVehicle.Price).replace(",", " ").replace(".", ",") : currencyFormat(cVehicle.Price),
        "AXZPRICE": currencyFormat(planPrice),
        "AXZPLAN": AXZPlanTypeDisplay,
        "XPLAN": XPlanTypeDisplay,
        "AXZDIVDISPLAY": AXZDivDisplay,
        "INLINE_INCENTIVE": "hidden-div",
        "CAMPAIGN": "hidden-div",
        "INV_LOCATION_TEXT_FIELD_ID": "inv-location-text-field-" + i,
        "VIN_FIELD_ID": "vin-field-" + i,
        "MAKE": typeof(cVehicle.Make) == "undefined" ? "Ford" : cVehicle.Make,
        "MODELNAME": cVehicle.ModelName,
        "YEAR": cVehicle.Year == "" ? selectedYear : cVehicle.Year
      };
      var pricingOverride = false;
      if (cVehicle.inlinePricing && cVehicle.inlinePricing.campaigns && cVehicle.inlinePricing.campaigns.length){
        var disclaimerDiv = YAHOO.util.Dom.get("campaign-disclaimer");
        var strCampaigns = "";
        for (var j in cVehicle.inlinePricing.campaigns)
        {
          var campaign = cVehicle.inlinePricing.campaigns[j];
          var strCampaign = "";
          switch (campaign.type)
          {
            case "PRICE_OVERRIDE":
              //Exclude Mustang Shelby from "Ford Family Price - FOC Summer Campaign"
              //Checked dealer for FOC dealer, the selected vehicle name for "MUSTANG" and returned body description for "SHELBY"
              if(dealer.country == "CA" || dealer.country == "ca" && !(isVehicleExcluded(selectedYear, getSelectedModel().name, cVehicle.BodyDesc) && campaign.name.search(/Foc Summer Campaign/i)>=0) )
              {
                strCampaign = "<b class='fep-text'>" + campaign.description + ":</b><b class='fep-value'>$" + currencyFormat(cVehicle.inlinePricing.adjustedPriceCampaign) + "**" + "</b><br/>";
                pricingOverride = true;
              }
              break;
            // We don't know how to display these yet. Leaving it as a placeholder - anshu 07/04/07
            case "PRICE_DISCOUNT":
            case "INFORMATIONAL":
          }
          strCampaigns += strCampaign;
        }
        if (strCampaigns != ""){
          renderObject["CAMPAIGN"] = "campaign-div";
          renderObject["CAMPAIGN_INFO"] = strCampaigns;
        }
      }
      if (cVehicle.inlinePricing && cVehicle.inlinePricing != null && !pricingOverride && cVehicle.inlinePricing.adjustedPriceOffers && cVehicle.inlinePricing.adjustedPriceOffers != cVehicle.inlinePricing.originalPrice)
      {
        renderObject["INLINE_INCENTIVE"] = "";
        var adjustedPrice = cVehicle.inlinePricing.adjustedPriceOffers;
        //for getting total discount, subtracted cVehicle.Price(MSRP)from adjusted price
        //and added total discount to AXZ-plan price
        //plantype price is greater than zero the calculate adjusted price
        if(planPrice > 0) {
          adjustedPrice = parseFloat(planPrice) + parseFloat(adjustedPrice) - parseFloat(cVehicle.Price);
        }
        //arrange the price in the format
        renderObject["ADJUSTED_PRICE"] = currencyFormat(adjustedPrice);
        renderObject["ADJUSTMENTS"] = getPricingAdjustmentTable(cVehicle.inlinePricing);
      }
      var thisObject = processTemplate(vehicleTemplate, renderObject);
      strHTML += thisObject;
    }
    this.objListDiv.innerHTML = strHTML;
    checkButtonComponentsWidth();
  };

  /**
   * To get the image
   * @param thumbnailImage image
   */
  function getImageTag(thumbnailImage)
  {
    var prefix = "<img src='" + vfsBase + "/apps/vimg/exterior/133x55/";
    var postfix = "' height=55 width=133>";
    var image = thumbnailImage ? thumbnailImage : "/apps/img/vehicleimage.jpg";
    return prefix + image + postfix;
  }

  /**
   * @param vIndex
   * @param positionID
   */
  this.openPE = function(vIndex, positionID)
  {
    var clickedObj = YAHOO.util.Dom.get(positionID);
    var coordinates = findPosition(clickedObj);
    //Get the new co-ordinates.
    var popUp = YAHOO.util.Dom.get("popUp");
    popUp.style.top = coordinates[1] + "px";
    popUp.style.left = (coordinates[0] - 391) + "px";
    var locateVehicle = this.currentVehicleSelection[vIndex];
    openPEorCAforVehicle(locateVehicle, positionID, "PE");
  };

  /**
   * @param vIndex
   * @param positionID
   */
   this.openCA = function(vIndex, positionID)
  {
    var clickedObj = YAHOO.util.Dom.get(positionID);
    var coordinates = findPosition(clickedObj);
    //Get the new co-ordinates.
    var popUp = YAHOO.util.Dom.get("popUp");
    popUp.style.top = (coordinates[1] - 100) + "px";
    popUp.style.left = (coordinates[0] - 391) + "px";
    var locateVehicle = this.currentVehicleSelection[vIndex];
    openPEorCAforVehicle(locateVehicle, positionID, "CA");
  };

/**
 * show or hide the no.of matching vehicles information
 * @param isRequired boolean 
 */  
  this.renderCountDiv = function(isRequired)
  {
    this.objCountDiv.innerHTML = (!isRequired)? "<span id='countNumberDiv' class='header2'>" + this.currentVehicleSelection.length + "</span><b class='vechilescountMessage'> " + arrStrings["apps.inventory.filter.matchingvehicles"] + "</b>": this.objCountDiv.innerHTML = "";
  }
};

/**
 *
 * @param modelId id for the model
 * @param isGetOffersCall boolean value for the offers
 * @return
 */
function getLocateVehicles(modelId, isGetOffersCall)
{
  strModelInfoId = modelId;
  var currentModelIdState = YAHOO.util.History.getCurrentState("modelid");
  var newModelIdState = modelId;
  if (newModelIdState != currentModelIdState){
    YAHOO.util.History.navigate("modelid", newModelIdState);
  }
  else{
    (isGetOffersCall)? showStatusMessage(arrStrings["apps.inventory.details.lookingforoffers"]) : showStatusMessage(arrStrings["apps.inventory.filter.gettingvehicles"] + "...");
    getFliterImage();
    var request = YAHOO.util.Connect.asyncRequest('GET', "../../services/getNewInventoryList?pacode=" + dealer.paCode + "&modelid=" + modelId + "&lang=" + userLanguage + (zipCode != '' ? "&zipcode=" + zipCode : ""), callback);
  }
}

/**
 *
 * @param modelId if for the model
 */
function requestThisQuote(modelId)
{
  location.href = "quickquote?_eventId=selectModel&modelId=" + modelId;
}

/**
 * Function for the Yahoo AJAX toolkit.  This gets called when the AJAX call returns
 * with success.
 */
var handleSuccess = function(o)
{
  hideStatusMessage();
  var error = null;
  if (o.responseText == null){
    locateVehicles = null;
  }else{
    //get he responce to the json object
    var responseJSON = JSON.parse(o.responseText);
    locateVehicles = responseJSON['vehicles'];
    displayCampaignDisclaimers(responseJSON.campaignDisclaimers);
  }
  //if zipcode is defined invalid by the admin.
  if(responseJSON["invalidZipCode"] != null && responseJSON["invalidZipCode"] != ""){
    changeDisplayStatus("zipCodeDiv", (userInputBaseId == "zipCodeDiv"));
    showHideZipCodeErrorMessage(userInputBaseId, true);
    return;
  }
  if (locateVehicles == null){
    error = 'error';
    locateVehicles = [];
  }
  else if (locateVehicles.length === 0){
      vehicleRenderer.refreshVehicleList(locateVehicles);
      if ( vehicleParaValue != undefined && vehicleParaValue != 'undefined'){
        var yearBox = document.forms["newInvFilter"]["Year"];
        if( yearBox.value == yearBox[yearBox.length-1].value ) return;
        var currentYear = yearBox.value-1;
        selectValue('newInvFilter','Year',currentYear,'value');
        vehicleYearChanged();
      } else {
        error = 'novehicleformodel';
      }
    }
  locateVehicleSearch = new ModelSearch('newInvFilter', [bodySelect, colorSelect, transSelect, engineSelect, stockIdField], locateVehicles, true);
  locateVehicleSearch.init();
  vehicleRenderer.setSorter(new ObjectSorter(document.sortForm['sortSelect'].value, simpleComparator));
  vehicleRenderer.refreshVehicleList(locateVehicles);
  setSearchFilters(decodeFilters(filterValues, VEHICLE_FILTER_ORDERING));
  if (error != null){
    displayErrorMessage(errorMessages[error]);
    changeDisplayStatus("sortingPrefsDiv", false);
    changeDisplayStatus("zipCodeDiv", false);
    changeDisplayStatus("pagingDivBottom", false);
    return;
  }
  if(locateVehicles.length == 0){
    clearErrorDiv();
    changeDisplayStatus("vehicleListDiv", false);
    changeDisplayStatus("letUsFindItP", false);
    changeDisplayStatus("pagingDivBottomContainer", false);
    changeDisplayStatus("sortingPrefsDiv", false);
    changeDisplayStatus("zipCodeDiv", false);
    changeDisplayStatus("pagingDivBottom", false);
    return;
  }
  changeDisplayStatus("vehicleListDiv", true);
  changeDisplayStatus("letUsFindItP", true);
  changeDisplayStatus("pagingDivBottomContainer", true);
  changeDisplayStatus("sortingPrefsDiv", true);
  changeDisplayStatus("zipCodeDiv", true);
  changeDisplayStatus("pagingDivBottom", true);
  setZipCodeCookie(zipCode);
  hideViewSpecialOfferLink();
};

/**
 *
 * @param strMessage status meaage to show
 * @return
 */
function showStatusMessage(strMessage)
{
  var status = YAHOO.util.Dom.get("statusDiv");
  var statusMessage = YAHOO.util.Dom.get("statusDivMessage");
  statusMessage.innerHTML = strMessage;
  status.style.visibility = "visible";
  showIFrameMask("belowStatusDiv", "statusDiv");
  changeDisplayStatus("letUsFindItDiv", false);
}

/**
 * change/hide the status message
 */
function hideStatusMessage()
{
  var status = YAHOO.util.Dom.get("statusDiv");
  status.style.visibility = "hidden";
  hideIFrameMask("belowStatusDiv");
  changeDisplayStatus("letUsFindItDiv", true);
}

/**
 * Function for the Yahoo AJAX toolkit.  This gets called when the AJAX call returns
 * with failure.
 */
var handleFailure = function(o)
{
  hideStatusMessage();
  displayErrorMessage(errorMessages['error']);
};

/**
 * An object for the Yahoo AJAX toolkit.
 */
var callback =
{
  success: handleSuccess,
  failure: handleFailure
};

/**
 * Clears StockId. And then shows vehicles according to current values
 */
function filterVehicles(stateChange)
{
  if (locateVehicleSearch){
    var currentFilterState = YAHOO.util.History.getCurrentState("filters");
    var newFilterState = encodeFilters(getCurrentFilterState(), VEHICLE_FILTER_ORDERING);
    (currentFilterState != newFilterState && (typeof(stateChange) == "undefined" || stateChange)) ? YAHOO.util.History.navigate("filters", newFilterState): vehicleRenderer.refreshVehicleList(locateVehicleSearch.currentSelection);
  }
  else{
    displayErrorMessage(errorMessages['selectamodel']);
  }
}

/**
 * Used to clear error message div
 */
function clearErrorDiv()
{
  var listDiv = YAHOO.util.Dom.get("vehicleListDiv");
  listDiv.innerHTML = " ";
}

/*
 * Used to navigate history states
 */
function navigateState()
{
  var bookmarkedState = YAHOO.util.History.getCurrentState("filters");
  var newFilterState = encodeFilters(getCurrentFilterState(), VEHICLE_FILTER_ORDERING);
  if (bookmarkedState != newFilterState){
    YAHOO.util.History.navigate("filters", newFilterState);
  }
}

/**
 * Displays the error message
 */
function displayErrorMessage(msg)
{
  var listDiv = YAHOO.util.Dom.get("vehicleListDiv");
  listDiv.innerHTML = "<p class='inventoryMessage'>" + msg + "</div>";
}

/**
 * Resets stock id and other filter values
 */
function clearStockId()
{
  document.forms['newInvFilter']['StockId'].value = "";
  if (locateVehicleSearch){
    locateVehicleSearch.selectionChanged(4);
  }
}

/**
 * Selects a Model based on strModelInfoId. It gets the model from the list of models, matches Make, year and Model Id
 * to select the model. If not found, resets the selections.
 */
function selectModel()
{
  var selectedModel = getSelectedModel();
  if (selectedModel == null){
    return;
  }
  if (!selectValue('newInvFilter', 'Make', selectedModel.make, 'value')){
    return;
  }
  newInvSearch.selectionChanged(0);
  if (!selectValue('newInvFilter', 'Year', selectedModel.year, 'value')){
    return;
  }
  newInvSearch.selectionChanged(1);
  if (!selectValue('newInvFilter', 'Model', strModelInfoId, 'value')){
    document.forms['newInvFilter']['Year'].selectedIndex = 0;
    return;
  }
  getLocateVehicles(document.forms['newInvFilter']['Model'].value);
}

/**
 * It checks whether the zip is blank or not
 * If it is null or blank then populate it using getCookie method 
 */
function checkCookie()
{
  var codeCookie = null;
  if (dealer.country == 'us'){
    codeCookie = getCookie('zipCodeCookie');
  }
  else if (dealer.country == 'ca'){
    codeCookie = getCookie('provinceCodeCookie');
  }
  codeCookie == null? document.getElementById('promptText').value = "" : document.getElementById('promptText').value = codeCookie;
}

/**
 * Opens payment estimator or the Credit application URL for a selected objVehicle, which is a JSON vehicle returned by Ajax service
 * Note that there is a JS representation of locatevehicle object as well but it is different from the
 * JSON notation in which we get it from Ajax. TODO We need to converge the two notations into one
 */
function openPEorCAforVehicle(objVehicle, positionID, isPEorCA)
{
  var selectedModel = getSelectedModel();
  checkCookie();
  if (selectedModel){
    var autoTrans = objVehicle.TransmissionCode.substring(objVehicle.TransmissionCode.length - 3);
    var engineCode = objVehicle.EngineCode.substring(objVehicle.EngineCode.length - 3);
    var vehicleDetails = new LocateVehicleDetails(objVehicle.ModelName, objVehicle.Price, objVehicle.BodyDesc, objVehicle.VIN, objVehicle.PEPCode, autoTrans, engineCode, '0', selectedModel.make, objVehicle.YEAR);
    if (isPEorCA == "PE"){
      openPaymentEstimator(financeURL, "N", vehicleDetails, selectedModel, positionID);
    }
    else if (isPEorCA == "CA"){
      openCreditApplication(financeURL, "N", vehicleDetails, selectedModel, positionID);
    }
  }
}

/**
 * Gets the currently selected Model object. Returns a null if not found
 */
function getSelectedModel()
{
  if (strModelInfoId){
    for (var i in arrModels){
      if (arrModels[i].id == strModelInfoId){
        return arrModels[i];
      }
    }
  }
  return null;
}

/**
 * Clears the model list and displays "Select A Model" message
 */
function clearModelList(isRequired)
{
  locateVehicles = [];
  locateVehicleSearch = new ModelSearch('newInvFilter', [bodySelect, colorSelect, transSelect, engineSelect, stockIdField], locateVehicles, true);
  locateVehicleSearch.init();
  locateVehicleSearch = null;
  vehicleRenderer.refreshVehicleList([],isRequired);
  displayErrorMessage(errorMessages['selectamodel']);
}

/**
 * Invoked when search button is clicked
 */
function searchByStockId(stateChange)
{
  if (locateVehicles && locateVehicles.length > 0 && locateVehicleSearch && Trim(document.forms['newInvFilter']['StockId'].value) != "")
  {
    locateVehicleSearch.init();
    locateVehicleSearch.selectionChanged(4);
    filterVehicles(stateChange);
  }
}

/**
 * Invoked when the year dropdown changes.
 */
function vehicleYearChanged()
{
  newInvSearch.isCheckUrlReqPara = false;
  newInvSearch.selectionChanged(1);
  var selectedModel = getSelectedModel();
  var year = document.forms['newInvFilter']['Year'].value;
  var defaultObj = getDefaultYearAndVehicle();
  if (selectedModel)
  {
    selectValue('newInvFilter', 'Model', selectedModel.name, 'text');
  }
  if (year == defaultObj.year)
  {
    selectValue('newInvFilter', 'Model', defaultObj.name, 'text');
  }
  getLocateVehicles(document.forms['newInvFilter']['Model'].value);
}

/**
 * Returns Default year and make as a JS object
 */
function getDefaultYearAndVehicle()
{
  var make = document.forms['newInvFilter']['Make'].value;
  return invDefaultsArr[make];
}

/**
 * Called When Make Dropdown changes
 */
function vehicleMakeChanged()
{
  newInvSearch.isCheckUrlReqPara = false;
  newInvSearch.selectionChanged(0);
  var make = document.forms['newInvFilter']['Make'].value;
  var defaultObj = getDefaultYearAndVehicle();
  if (defaultObj.year)
  {
    selectValue('newInvFilter', 'Year', defaultObj.year, 'value');
  }
  newInvSearch.selectionChanged(1);
  if (defaultObj.name)
  {
    selectValue('newInvFilter', 'Model', defaultObj.name, 'text');
  }
  getLocateVehicles(document.forms['newInvFilter']['Model'].value);
}

/**
 * Sets the search filters to values specified in filterObj and filters the vehicles
 */
function setSearchFilters(filterObj)
{
  document.forms['newInvFilter']['StockId'].value = "";
  selectValue('newInvFilter', 'BodyStyle', filterObj.model, 'value');
  locateVehicleSearch.selectionChanged(0);
  selectValue('newInvFilter', 'Color', filterObj.color, 'value');
  locateVehicleSearch.selectionChanged(1);
  selectValue('newInvFilter', 'Transmission', filterObj.trans, 'value');
  locateVehicleSearch.selectionChanged(2);
  selectValue('newInvFilter', 'Engine', filterObj.engine, 'value');
  locateVehicleSearch.selectionChanged(3);
  if (filterObj.stockId && Trim(filterObj.stockId) != "")
  {
    document.forms['newInvFilter']['StockId'].value = filterObj.stockId;
    searchByStockId(false);
  }
  else
  {
    filterVehicles(false);
  }
  selectValue('sortForm', 'vehiclesPerPageSelect', filterObj.pageSize, 'value');
  vehicleRenderer.setPageSize(filterObj.pageSize);
  selectValue('sortForm', 'sortSelect', filterObj.sortBy, 'value');
  vehicleRenderer.setSorter(new ObjectSorter(filterObj.sortBy, simpleComparator));
  vehicleRenderer.setOrdering(filterObj.reverse);
  vehicleRenderer.gotoPage(filterObj.pageNo);
}

/**
 *
 * @param objInlinePrice
 * @return
 */
function getPricingAdjustmentTable(objInlinePrice)
{
  var arrAdjustments = objInlinePrice.adjustments;
  var strAdjustmentTable = "";
  for (var i in arrAdjustments)
  {
    var strHTML = (i == 0) ? "" : "<tr><td class='vehicle-price-adjustments'>";
    strHTML += arrAdjustments[i].name;
    //arrange the price in the format
    strHTML += '</td><td class="vehicle-amount-adjustments">-$' + currencyFormat(-arrAdjustments[i].amount);
    strHTML += (i == (arrAdjustments.length - 1)) ? "" : '</td></tr>';
    strAdjustmentTable += strHTML;
  }
  if (objInlinePrice.expiryDate && objInlinePrice.expiryDate !== null)
  {
    strAdjustmentTable += '<tr><td class="vehicle-price-adjustments"><i>' + arrStrings['apps.incentives.offersexpiry'] + ' ' + objInlinePrice.expiryDate + '</i></td><td>';
  }
  return strAdjustmentTable;
}


/**
 * Returns the current filter values as a JSON object
 */
function getCurrentFilterState()
{
  var modelVal = document.forms['newInvFilter']['BodyStyle'].value;
  var transmissionVal = document.forms['newInvFilter']['Transmission'].value;
  var colorVal = document.forms['newInvFilter']['Color'].value;
  var engiveVal = document.forms['newInvFilter']['Engine'].value;
  var stockIdVal = document.forms['newInvFilter']['StockId'].value;
  var pageSizeVal = YAHOO.util.Dom.get('vehiclesPerPageSelect').options[YAHOO.util.Dom.get('vehiclesPerPageSelect').selectedIndex].value;
  var sortByVal = YAHOO.util.Dom.get('sortSelect').options[YAHOO.util.Dom.get('sortSelect').selectedIndex].value;
  var reverseVal = vehicleRenderer.ordering;
  var pageNoVal = vehicleRenderer.currentPage;
  var filterState =
  {
    "model": modelVal,
    "trans": transmissionVal,
    "color": colorVal,
    "engine": engiveVal,
    "stockId": stockIdVal,
    "pageSize": pageSizeVal,
    "sortBy": sortByVal,
    "reverse": reverseVal,
    "pageNo": pageNoVal
  };
  return filterState;
}

/**
 * Makes an Ajax Call to refresh inline incentives
 * @param userZipCode
 */
function refreshZipCode(userZipCode)
{
  if (!userZipCode || userZipCode == '' || !validateUSZipCode(userZipCode))
  {
    alert(errorMessages['InvalidZip']);
    return;
  }
  if (userZipCode == zipCode)
  {
    return;
  }
  zipCode = userZipCode;
  YAHOO.util.Dom.get("zipCodeMessage").innerHTML = arrStrings['apps.inventory.filter.changezip'];
  getLocateVehicles(strModelInfoId, true);
}

/**
 * Displays the camapign disclaimers, for the Disclaimer-Map object passed to it.
 * @param {Object} objDisclaimerMap
 */
function displayCampaignDisclaimers(objDisclaimerMap)
{
  if (!objDisclaimerMap && objDisclaimerMap == null)
  {
    return;
  }
  var strHtml = '';
  for (var key in objDisclaimerMap)
  {
    strHtml += "** " + objDisclaimerMap[key] + '<br>';
  }
  YAHOO.util.Dom.get("campaign-disclaimer").innerHTML = strHtml;
}

/**
 * Decodes Filter Values as a JSON Object from the String
 * @param {Object} strFilters String with filter values
 * @param {Object} keyOrderingArr Keys and their ordering to be stored in JSON Object
 */
function decodeFilters(strFilters, keyOrderingArr)
{
  var jsonObject = new Object();
  var strEncodedArr = strFilters.split("/");
  for (var i = 0; i < keyOrderingArr.length; i++)
  {
    jsonObject[keyOrderingArr[i]] = decodeStringFromReadableURI(strEncodedArr[i]);
  }
  return jsonObject;
}

/**
 * Encodes JSON Object into a String according to key ordering
 * @param {Object} objFilters Filter values reresented as JSON Objects
 * @param {Object} keyOrderingArr  Keys and their ordering
 */
function encodeFilters(objFilters, keyOrderingArr)
{
  var strEncoded = "";
  for (var i in keyOrderingArr)
  {
    strEncoded += encodeStringAsReadableURI(objFilters[keyOrderingArr[i]]);
    if (i < keyOrderingArr.length - 1)
    {
      strEncoded += "/";
    }
  }
  return strEncoded;
}

/**
 * Encodes a String as a readable URI. Replaces spaces with '+'. Also encodes '/' as '%2F'
 * @param {Object} strValue String value to encode
 */
function encodeStringAsReadableURI(strValue)
{
  if (typeof(strValue) != "string")
  {
    return strValue;
  }
  return strValue.replace(/\+/g, '%2B').replace(/ /g, '+').replace(/\//g, "%2F");
}

/**
 * Decodes String encoded by encodeStringAsReadableURI
 * @param {Object} strValue Value to be decoded
 */
function decodeStringFromReadableURI(strValue)
{
  if (typeof(strValue) != "string")
  {
    return strValue;
  }
  return strValue.replace(/%2F/g, "/").replace(/\+/g, ' ').replace(/%2B/g, '+');
}

/**
 *  Checks the button components width and adjusts according to max width
 */
function checkButtonComponentsWidth(){
  var buttonClass = YAHOO.util.Dom.getElementsByClassName('btnContainerLeft');
  for(var i=0; i < buttonClass.length; i++){
    var buttonId = buttonClass[i].id;
    var buttonSplit = buttonId.split('-');
    checkButtonWidth('btn','-'+buttonSplit[1],'200');
  }
}

/**
 *  Adds the image content based on the selected year/ brand/ model in the search filter *
 */
function getFliterImage(){
  var model = getSelectedModel();
  var vehicleContent = '<img src="'+ vfsBase +'/apps/vimg/exterior/165x148/'+ model.defaultImage +'" >';
  vehicleContent += '<div class="modelNameTxt header5C">'+ model.name+'</div>';
  fileterImageEl = YAHOO.util.Dom.getElementsByClassName('filterImage');
  fileterImageEl[0].innerHTML = (fileterImageEl[0]!= null) ? vehicleContent : '';
}

/**
 * Assign eVars to props
 * @return
 */
function assignValues()
{
  //Assign the eVars to props
  s.prop14 = s.eVar14;
  s.eVar15 = s.prop15;
  s.prop1 = s.eVar1;
  s.prop2 = s.eVar2;
  if(s.prop3 !== ""){
    s.eVar3 = s.prop3;
  }
  s.prop4 = s.eVar4;
  s.prop7;
}

/**
 * @return
 */
function assignNewInvetoryValues()
{
  //Assign new in new inventory
  s.eVar5 = 'new';
  //Assign channel for new inventory
  s.channel = 'inventory-new';
  s.eVar14 = 'dealerconnection';
}

/**
 * Call omniture in new inventory page
 * @param year the year of the model
 * @param make the make of the model
 * @param model
 */
function callPopupStickerInNewInventory(year, make, model)
{
  setTempVariables();
  if (s !== null) 
  {
    s.templtv= s.linkTrackVars;
    s.linkTrackVars='eVar1,prop1,eVar2,prop2,eVar3,prop3,eVar5,eVar14,prop14,eVar15,prop15,eVar4,prop4,prop7,channel,eVar12,prop12,prop5,eVar16,prop16';
    //Assign params
    s.prop5 = 'window sticker';
    s.prop12 = s.eVar12 = year;
    //Assign eVars to props
    assignValues();
    assignNewInvetoryValues();
    //add param 
    s.eVar16 = s.prop16 = make + ' ' + model;
    s.pageName = 'dc: window sticker';
    //call fire omnitur event
    fireOmnitureEventSites('dc: window sticker');
    if(s.templtv)
    {
      s.linkTrackVars=s.templtv;
    }
  }
  resetVariables();
}

/**
 * Call omniture in new inventory page
 * @param year the year of the model
 * @param make the make of the model
 * @param model
 */
function callSendEmailInNewInventory(year, make, model)
{
  setTempVariables();
  if (s !== null) 
  {
    s.templtv= s.linkTrackVars;
    s.linkTrackVars='eVar1,prop1,eVar2,prop2,eVar3,prop3,eVar5,eVar14,prop14,eVar15,prop15,eVar4,prop4,prop7,channel,eVar12,prop12,prop5,eVar16,prop16';
    //Assign params
    s.prop5 = 'window sticker email';
    //Assign eVars to props
    assignValues();
    assignNewInvetoryValues();
    s.prop12 = s.eVar12 = year;
    //add param 
    s.eVar16 = s.prop16 = make + ' ' + model;
    s.pageName = 'window sticker email';
    //call fire omnitur event
    fireOmnitureEventSites('window sticker email');
    if(s.templtv)
    {
      s.linkTrackVars=s.templtv;
    }
  }
}

/** 
 * To hide the view special offers link, if zipcode cookie is available
 */
function hideViewSpecialOfferLink(){
  cookiedZipCode = getCookie("zipCodeCookie");
  if(cookiedZipCode != null && cookiedZipCode != "")
  {
    // To get all the view special offers link elements in the page
    var viewSpecialOffersArray = YAHOO.util.Dom.getElementsByClassName("view-special-offer","div");
    // To hide the view special offers links 
    YAHOO.util.Dom.setStyle(viewSpecialOffersArray,"display", "none");
  }
}
