/**
 * Javascript to support the usedvehiclesFilter.ftl page. Include this AFTER vehicleFilter.js.
 * 
 * @author Neil Thier (c) Versata 2006
 */

// Constant to store one more than the number of characters of
//  Marketing Text (Dealer Comments) to be shown in preview
var MARKETING_TEXT_PREVIEW_CHARS = 280;
// Constant to store one more than the number of characters of
//  Marketing Text (Dealer Comments) to be shown in preview applicable to FLM
var FLM_MARKETING_TEXT_PREVIEW_CHARS = 325;

// Variable to cache the MarketingTexts of each of the vehicles
// To be used in global methods
var arrMarketingText = [];
// Variable inventoryType is used in emailFiltered.ftl
var inventoryType = "used";
var arrImgList = [];
var selectedImgNo = 0;
var arrVehicleListFinal = [];
var isNN = document.layers ? true : false;
var isIE = document.all ? true : false;
var posX = 0;
var posY = 0;
// The set of vehicle fields to use in the filters
arrFilterFields = new Array(
  new FilterField("Year", false, yearMinMatcher),
  new FilterField("YearTo", true, yearMaxMatcher),
  new FilterField("VehicleType", false, propertyMatcher),
  new FilterField("Make", false, propertyMatcher),
  new FilterField("ModelName", false, propertyMatcher),
  new FilterField("Mileage", true, numericalRangeMatcher),
  new FilterField("Price", true, numericalRangeMatcher),
  new FilterField("Certified", true, checkboxMatcher)
);
if (!strMileageUnits){
  strMileageUnits = 'mi';
}
var  modelYear;
var  make;
var  model;
var  modelPkg;
var  mnfBodyDesc;
var  bodyStyle;
/**
 * Render a list of vehicles.
 * 
 * @param arrVehicles
 * @param intStartIndex
 * @param intEndIndex
 * @param objListDiv
 * @param objCountDiv
 */
function renderVehicleList(arrVehicleList, intStartIndex, intEndIndex, objListDiv, objCountDiv) {
  arrVehicleListFinal = arrVehicleList;
  objListDiv.innerHTML = "";
  /******* Pre Owned Vehicle Inventory Search Part-I-Start NEW******/
  // On selection of the filters
  if(arrVehicleList.length === 0 && vehicleFlag == 1){
    noVehiclesDiv.innerHTML = '<font face="verdana" size=2>' + arrStrings['apps.inventory.filter.noMatchingVehiclesMsg'] + '</font>';
  }
  // On form load
  else if(arrVehicleList.length === 0 ){
    noVehiclesDiv.innerHTML = '<font face="verdana" size=2>' + arrStrings['apps.inventory.filter.noMatchingVehiclesMsgOnLoad'] + '</font>';
  }
  else{
    noVehiclesDiv.innerHTML = "";
    var strHTML = '<table cellspacing="0" cellpadding="0" class="usedVehicleTable"><tr><td style="padding:0px;">';
    strHTML += '<div class="poiSubheaderHolder"><div class="poiSubheaderMain"><div class="poiHeaderBlank"></div>'
          + '<div class="poiSubheaderMileage"><span class="poiHeaderTxt header6C">' + arrStrings['apps.inventory.filter.mileage'] + '</span></div>'
          + '<div class="poiSubheaderEngine"><span class="poiHeaderTxt header6C">' + arrStrings['apps.inventory.filter.eng'] + '</span></div>'
          + '<div class="poiSubheaderTrans"><span class="poiHeaderTxt header6C">' + arrStrings['apps.newinventory.filter.trans'] + '</span></div>'
    //Show the certified column header for Jaguar dealers and for non jaguar dealers do not showfor others dealers
    if (isJaguarDealer == 'true')
    {
      strHTML +='<div class="poiSubheaderCertified"><span class="poiHeaderTxt header6C">' + arrStrings['apps.inventory.filter.certified'] + '</span></div>';
    }
    strHTML += '<div class="poiSubheaderPrice"><span class="poiHeaderTxt header6C">' + arrStrings['apps.inventory.filter.price']
          + '</span></div></div></div>';
    for (i = intStartIndex; i < arrVehicleList.length && i < intEndIndex; i++) {
      var imageURLs = '';
      var thumbnailURL = '';
      if (arrVehicleList[i].NumImages > 0) {
        thumbnailURL = 'http://invassets.dealerconnection.com/vimages/' + arrVehicleList[i].DealerId + '/' + arrVehicleList[i].DealerStockId
                   + '_1.jpg';
        for (var imgIndex = 1; imgIndex <= arrVehicleList[i].NumImages; imgIndex++ ){
          imageURLs += 'http://invassets.dealerconnection.com/vimages/' + arrVehicleList[i].DealerId + '/' + arrVehicleList[i].DealerStockId + '_'
            + imgIndex + '.jpg' + (imgIndex == arrVehicleList[i].NumImages ? '' : '|');
        }
      } else {
        thumbnailURL = vfsBase + '/apps/img/vehicleimage.jpg';
      }
      mnfBodyDesc = arrVehicleList[i].FullModelDisplayName;
      modelPkg = arrVehicleList[i].ModelPackage;
      bodyStyle = arrVehicleList[i].BodyDesc;
      modelYear= arrVehicleList[i].Year;
      make = arrVehicleList[i].Make;
      model = arrVehicleList[i].ModelName;
      evps.push(modelYear);
      evps.push(make);
      evps.push(model);
      evps.push(modelPkg);
      evps.push(bodyStyle);
      generateVehicleNames('Year',evps,modelYear,mnfBodyDesc);
      generateVehicleNames('Make',evps,make,mnfBodyDesc);
      generateVehicleNames('Model',evps,model,mnfBodyDesc);
      generateVehicleNames('Pkg',evps,modelPkg,mnfBodyDesc);
      generateVehicleNames('Style',evps,bodyStyle,mnfBodyDesc);
      mnfBodyDesc = Trim(mnfBodyDesc).length===0?'':Trim(mnfBodyDesc)+' ';
      var certifiedPreowned = ((!((isCertifiedPreOwned != 'true') || (isLandRoverDealer == 'true'))) && arrVehicleList[i].Certified) ? "true":"false";
      strHTML += '<div class="poiMain" ><div class="poiTspacer"></div><div class="poiImage">'
            + '<a href="?_flowExecutionKey=' + flowExecutionId + '&_eventId_vehicledetails=true&vin=' + arrVehicleList[i].VIN
            + '&dealerPACode=' + arrVehicleList[i].DealerPaCode + '&certifiedPreownedImg=' + certifiedPreowned + '">' + '<img id="vehThubnailImg_' + i + '" src="' + thumbnailURL
            + '" width="130" height="97" border="0" /></a></div>' + '<div style="float: left;"><div class="poiDetailsContainer">'
            + '<div class="poiVehicleDetails"><div id = "poi-vehicle-details-' + i + '" class="poiCarpropertiesBoldTxt header8">' + parseInt(modelYear)+" "+make+'<div class="poiCarpropertiesBoldTxt1 header8">'+model+' '+modelPkg+'</div>'
            + '<div class="poiCarpropertiesBoldTxt2 header5b">'+mnfBodyDesc+bodyStyle+'</div></div><div class="poiCarpropertiesTxt header8" style="color:#000000">'
            + arrStrings['apps.inventory.filter.color'] + '<span id = "poi-vehicle-color-' + i + '" class="poiCarpropertiesBoldTxt bodyText" style="font-weight: bold;"> ' + arrVehicleList[i].ExteriorColor
            + ' </span></div>';
      strHTML += '<div id = "poi-vehicle-stock-' + i + '" class="poiStockTxt header8" style="color:#000000">' + arrStrings['apps.inventory.filter.stockid'] + '<span class="bodyText">' + arrVehicleList[i].DealerStockId
            + '</span></div><div class="poiLinksTxt">';
      if (imageURLs !== '')
      {
        strHTML += '<a class="poiLinksTxt bodyTextLink poiLinksOverrite" style="cursor: pointer;" href="javascript:showVehicleParts(\'' + imageURLs + '\');setOmnitureTag(\''+arrVehicleList[i].Make+'\',\''+arrVehicleList[i].ModelName+'\',\''+arrVehicleList[i].Year+'\')">'
            + arrStrings['apps.inventory.filter.enlarge'] + '</a> | ';
      }
      strHTML += '<a class="poiLinksTxt bodyTextLink poiLinksOverrite" id="poiVehicleDetailsLink' + i + '" href="?_flowExecutionKey=' + flowExecutionId
            + '&_eventId_vehicledetails=true&vin=' + arrVehicleList[i].VIN + '&dealerPACode=' + arrVehicleList[i].DealerPaCode + '&certifiedPreownedImg=' + certifiedPreowned + '">'
            + arrStrings['apps.inventory.filter.seedetails'] + '</a></div></div>';
      strHTML += '<div class="poiGroup"><div class="poiGroupDiv">'
            + '<div class="poiMileage bodyText">'
            + (arrVehicleList[i].Mileage > 0
              ?currencyFormat(arrVehicleList[i].Mileage) + ' ' + strMileageUnits
               :
               '<div style="text-align:center;">-</div>'
              )
            + '</div>'
            + '<div class="poiEngine bodyText">' + arrVehicleList[i].EngineDesc + '</div>'
            + '<div class="poiTrans bodyText">' + arrVehicleList[i].Transmission + '</div>'
        // Show the certified field for all Jaguar dealers
        if (isJaguarDealer == 'true')
        {
            strHTML += '<div class="poiCertified">' + (arrVehicleList[i].Certified
                  ?
                  '<img src="' + vfsBase + '/themes/chromesteel/images/tickmark.gif" width="15" height="14" />'
                  :
                  '-')
                  + '</div>';
        }
        strHTML  += '<div id = "poi-vehicle-price-' + i + '" class="poiPrice header5D">';
      if (arrVehicleList[i].Price !== null && arrVehicleList[i].Price > 0) {
       if(userLanguage == 'en' || userLanguage == 'es'){
        strHTML += '$' + currencyFormat(arrVehicleList[i].Price);
       }else if(userLanguage == 'fr'){
        strHTML += currencyFormat(arrVehicleList[i].Price).replace(",", " ").replace(".", ",") + ' $';
       }
      } else {
        strHTML += arrStrings['apps.inventory.filter.pricenotavailable'];
      }
      strHTML += '</div></div>';
      if (isLandRoverDealer == 'true' || isJaguarDealer == 'true') {
          strHTML += getGetInternetPriceButton(arrVehicleList, i, certifiedPreowned);
      } else {
          strHTML += getFLMGetInernetButtonContainer(i);
       }
      
      strHTML += '<div class="poiLinkdiv" style="clear: both;"><div class="poiSchedule"></div><div class="poiScheduletxt">'
            + '<a class="testDriveText bodyTextLink poiLinksOverrite" href="?_flowExecutionKey=' + flowExecutionId + '&_eventId_testdrive=true&requestType=testDrive&vin='
            + arrVehicleList[i].VIN + '&dealerPACode=' + arrVehicleList[i].DealerPaCode + '&certifiedPreownedImg=' + certifiedPreowned + '">' + arrStrings['apps.inventory.filter.testdrive']
            + '</a></div></div>';
      strHTML += '<div class="poiLinkdiv" style="clear: both;"><div class="poiSchedule"></div><div class="poiScheduletxt">'
            +  '<a class="testDriveText bodyTextLink poiLinksOverrite" href="javascript:createEMailPopup(' + i + ", null, '" + arrVehicleList[i].DealerPaCode
            + "', 'poiFiltersDiv'" + ')">' + arrStrings['apps.inventory.sendEmail.title'] + '</a></div></div></div></div>'
            + '<div class="poiLocTextContainer"><p id = "poi-vehicle-location-' + i + '" style="padding: 0px; margin: 0px;" class="instructionalText">';
      if (strPACode == arrVehicleList[i].DealerPaCode) {
        strHTML += arrStrings['apps.inventory.info.location.instock'];
      } else {
        strHTML += arrStrings['apps.inventory.info.location.extendedinv'];
      }
      strHTML += '</p></div>';
        // Show the certified field for all FLM certified dealers
        if ((!((isCertifiedPreOwned != 'true') || (isLandRoverDealer == 'true'))) && arrVehicleList[i].Certified)
        {
        var vechBrand = "";
        if (arrVehicleList[i].Make == "Ford") {
            vechBrand = "Certified_Ford_logo.gif";
        } else if (arrVehicleList[i].Make == "Lincoln") {
            vechBrand = "Certified_Lincoln_logo.gif";
        } else if (arrVehicleList[i].Make == "Mercury") {
            vechBrand = "Certified_Mercury_logo.gif"
        }
        
        if (vechBrand != "") {
            strHTML += '<div class="poiCertified">' +
            (arrVehicleList[i].Certified ? '<img src="' + vfsBase + '/common/images/' + vechBrand + '" width="126" height="28" />' : '-') +
            '</div>';
        }
        }
     strHTML += '</div></div>';
      strHTML += '<div class="poiBottomContainer">';
      if (arrVehicleList[i].MarketingText !== null && arrVehicleList[i].MarketingText !== '') {
           if (isLandRoverDealer == 'true' || isJaguarDealer == 'true'){
             strHTML += getCommentString(arrVehicleList, i);
           } else {
               strHTML += getFLMCommentString(arrVehicleList, i);
           }
        // Saving the MarketingText of the vehicle in the cache
        arrMarketingText[i] = arrVehicleList[i].MarketingText;
      }
      strHTML += '</div>';
      strHTML += '</div>';
    }
    strHTML += '</td</tr></table>';
    objListDiv.innerHTML = strHTML;
  } //ELSE closes here
  objCountDiv.innerHTML = '<span class="header2">' + arrVehicleList.length + '</span>' + ' ' + arrStrings['apps.inventory.filter.matchingvehicles'];
  // Update the number of pages
  updatePageNumbers(YAHOO.util.Dom.get('pageNumbers'), YAHOO.util.Dom.get('pageNumbersBottom'));
  //Any of component js actions.
  if (typeof(initializePageUI) == "function"){
    initializePageUI();
    for (i = intStartIndex; i < arrVehicleList.length && i < intEndIndex; i++) {
        var giCrtifiedPreowned = ((!((isCertifiedPreOwned != 'true') || (isLandRoverDealer == 'true'))) && arrVehicleList[i].Certified) ? "true":"false";
        cloneButton(i , arrVehicleList, giCrtifiedPreowned);
    }
  }
}

/**
 * 
 * Function to get FLM or FoC dealer comment string as html
 * 
 * @param {Object}
 *          i Index of current Vechicle
 * 
 */
function getFLMGetInernetButtonContainer(i){
  return '<div class="get-button-container" style="float: right;">'
            + '<div id="getInternetPriceButton-container-'+ i + '"' +'class="button-container" style="clear: both; margin: 0px;"></div>';
}

/**
 * 
 * Function to get 'Get Internet Button'
 * 
 * @param {Object}
 *          i Index of current Vechicle
 * @param {Object}
 *          arrVehicleList List of Vechicles
 * 
 */
function getGetInternetPriceButton(arrVehicleList, i, certifiedPreowned) {
  return '<div class="get-button-container" style="float: right;">'
           + '<div class="button-container" style="clear: both; margin: 0px;"><div class="button-left"></div><div class="button">'
           + '<a href="?_flowExecutionKey=' + flowExecutionId + '&_eventId_requestquote=true&requestType=quote&vin='
           + arrVehicleList[i].VIN + '&dealerPACode=' + arrVehicleList[i].DealerPaCode + '&certifiedPreownedImg=' + certifiedPreowned + '"><span class="button-label">'
           + arrStrings['apps.inventory.filter.getinternetprice'] + '</span></a></div><div class="button-right"></div></div>';
}

/**
 * 
 * Function to get FLM or FoC 'Get Internet Button Container'
 * 
 * @param {Object}
 *          i Index of current Vechicle
 * @param {Object}
 *          arrVehicleList List of Vechicles
 * 
 */
function getFLMCommentString(arrVehicleList, i) {
  return '<div class="poiCommentDiv"><div class="poiCommentHeader poiFLMCommentHeader"></div>'
    + '<div class="poiCommentMoreBtnHolder" style=" border: 0px solid #ff0000;">'
    + '<table style="width: 100%; margin: 0px;"><tr><td><div class="poiCommentText instructionalText" id="infoMain' + i + '">'
    + '\u0022' + arrVehicleList[i].MarketingText.substring(0, FLM_MARKETING_TEXT_PREVIEW_CHARS)
    + (arrVehicleList[i].MarketingText.length < FLM_MARKETING_TEXT_PREVIEW_CHARS ? '' : ' ......') + '\u0022' + '</div></td>'
    + '<td style="vertical-align: bottom;">'
    + (arrVehicleList[i].MarketingText.length < FLM_MARKETING_TEXT_PREVIEW_CHARS ?
       ''
       :
         '<div class="poiMoreHideBtnHolder" style=" border: 0px solid #ff00ff;">'
         + '<a id="moreButton' + i + '" href="javascript:showHideInfo(' + i + ',true)" style="text-decoration: none; display: block;">'
         + '<div class="poiMoreHideButtonContainer">'
         + '<div class="poiMoreButtonArrow poiFLMMoreButtonArrow"></div></div></a>'
         + '<a id="hideButton' + i + '" href="javascript:showHideInfo(' + i + ', true)" style="text-decoration: none; display: none;">'
         + '<div class="poiMoreHideButtonContainer">'
         + '<div class="poiHideButtonArrow poiFLMHideButtonArrow"></div></div></a></div>')
         + '</td></tr></table></div></div>';
}

/**
 * 
 * Function to get dealer comment string as html
 * 
 * @param {Object}
 *          i Index of current Vechicle
 * @param {Object}
 *          arrVehicleList List of Vechicles
 * 
 */
function getCommentString(arrVehicleList, i){
  return '<div class="poiCommentHeader">' + arrStrings['apps.inventory.filter.dealerComment'] + '</div>'
              + '<div class="poiCommentMoreBtnHolder" style=" border: 0px solid #ff0000;">'
              + '<table style="width: 100%; margin: 0px;"><tr><td><div class="poiCommentText" id="infoMain' + i + '">'
              + arrVehicleList[i].MarketingText.substring(0, MARKETING_TEXT_PREVIEW_CHARS)
              + (arrVehicleList[i].MarketingText.length < MARKETING_TEXT_PREVIEW_CHARS ? '' : ' ...')+ '</div></td>'
              + '<td style="vertical-align: bottom;">'
              + (arrVehicleList[i].MarketingText.length < MARKETING_TEXT_PREVIEW_CHARS ?
                   ''
                   :
                   '<div class="poiMoreHideBtnHolder" style=" border: 0px solid #ff00ff;">'
                     + '<a id="moreButton' + i + '" href="javascript:showHideInfo(' + i + ',false)" style="text-decoration: none; display: block;">'
                     + '<div class="poiMoreHideButtonContainer"><div class="poiMoreHideButton">' + arrStrings['apps.inventory.filter.more']
                     + '</div><div class="poiMoreButtonArrow"></div></div></a>'
                     + '<a id="hideButton' + i + '" href="javascript:showHideInfo(' + i + ',false)" style="text-decoration: none; display: none;">'
                     + '<div class="poiMoreHideButtonContainer"><div class="poiMoreHideButton">' + arrStrings['apps.inventory.filter.hide']
                     + '</div><div class="poiHideButtonArrow"></div></div></a></div>')
                     + '</td></tr></table></div>';
}

/**
 * 
 * Function to add 'Get Our Internet Price' buttons
 * 
 * @param {Object}
 *          i Index of current Vechicle
 * @param {Object}
 *          arrVehicleList List of Vechicles
 * 
 */
function cloneButton(i , arrVehicleList, giCrtifiedPreowned) {
  $D = YAHOO.util.Dom;
  var button = $D.get("getInternetPriceButton");
  var buttonContainer = $D.get('getInternetPriceButton-container-'+i);
  var newButton = button.cloneNode(true);
  $D.setStyle(newButton, 'display', 'block');
  $D.setStyle(newButton, 'visibility', 'visible');
  buttonContainer.appendChild(newButton);
  var el = $D.getElementsByClassName('btnContainer', 'div','getInternetPriceButton-container-' + i)[0];
  el.removeAttribute('onclick');
  addClickListener(el, arrVehicleList[i], giCrtifiedPreowned);
  checkButtonWidth('btn','-getInternetPrice','170');
}

/**
 * 
 * Function to add Listener to element
 * 
 * @param {Object}
 *          el element
 * @param {Object}
 *          currentVehicle currentVehicle
 * 
 */
function addClickListener(el, currentVehicle, giCrtifiedPreowned) {
  YAHOO.util.Event.addListener(el, "click", function(){
    window.open('?_flowExecutionKey=' + flowExecutionId + '&_eventId_requestquote=true&requestType=quote&vin='
      + currentVehicle.VIN + '&dealerPACode=' + currentVehicle.DealerPaCode+'&certifiedPreownedImg=' + giCrtifiedPreowned , target='_self');
            });
}
/**
 * Retuns the Vehicle List
 * 
 * @return
 */
function getVehicleList() {
  showStatusMessage(arrStrings['apps.inventory.filter.gettingvehicles'] + '...');
  var request = YAHOO.util.Connect.asyncRequest('GET', '../../services/getUsedInventoryList?pacode=' + strPACode + '&lang=' + userLanguage, callback);
}

/**
 * Called when the used-vehicle-make-filter changes. Currenlty controls the
 * values in the model filter upon changes in the make filter.
 */
function populateVehicleFilter(objMatcher) {
  var selectedModelsSet = new Array();
  //Iterate through each vehicle to collect the matching model names.
  for ( var v = 0 ; v < arrVehicles.length ; v++ ) {
    if(objMatcher.matches(arrVehicles[v])){
      selectedModelsSet[arrVehicles[v]['ModelName']] = arrVehicles[v]['ModelName'];
    }
  }
  //Copy the contents from the set to an array so that we can sort them.
  var selectedModels = new Array();
  for (var model in selectedModelsSet) {
     selectedModels[selectedModels.length] = model;
  }
  //Sort the new model array in alphabetical order;
  var sortedSelectedModels = selectedModels.sort();
  modelFilter = document.forms['filtersForm'].elements['ModelName']; //Update the drop-down.
  modelFilter.length = 1;
  for (var v = 0; v < sortedSelectedModels.length; v++) {
    var value = sortedSelectedModels[v];
    modelFilter.options[modelFilter.options.length] = new Option(value, value);
  }
}
/**
 * Sorts a dropdown.options
 */
function sortDropDownOptions(sorter, options) {
   //Ignore the first 'All' option.
   var optionsToSort = new Array();
   for (var v = 1; v < options.length; v++) {
     optionsToSort[v - 1] = new Option(options[v].text, options[v].value);
   }
   var sortedOptions = sorter.sort(optionsToSort);
   options.length = 1;
   for (var v = 0; v < sortedOptions.length; v++) {
     options[options.length] = sortedOptions[v];
   }
}
/**
 * 
 * @param sorter
 * @param options
 * @return
 */
function sortYearDropDownOptions(sorter, options) {
  var optionsToSort = new Array();
  for (var v = 0; v < options.length; v++) {
    optionsToSort[v] = new Option(options[v].text, options[v].value);
  }
  var sortedOptions = sorter.sort(optionsToSort);
  options.length = 0;
  for (var v = 0; v < sortedOptions.length; v++) {
    options[options.length] = sortedOptions[v];
  }
}
/**
 * This method reset the fields of Mileage and Price
 */
function resetFields()
{
  document.forms['filtersForm'].elements['Mileage'].selectedIndex = 0;
  document.forms['filtersForm'].elements['Price'].selectedIndex = 0;
}
/**
 * Sorts the contents of the filters below;
 *  year: chronological - newest to oldest
 *  vehicle type: alphabetical
 *  make: alphabetical
 *  model: alphabetical (should be filtered if "make" is selected, look at populateVehicleFilter)
 */
function sortUsedVehicleFilters() {
  var optionSorter = new ObjectSorter('text',simpleComparator);
  sortDropDownOptions(optionSorter, document.forms['filtersForm'].elements['VehicleType'].options);
  sortDropDownOptions(optionSorter, document.forms['filtersForm'].elements['Make'].options);
  sortDropDownOptions(optionSorter, document.forms['filtersForm'].elements['ModelName'].options);
  // Sorting Years in reverse order
  optionSorter.reverseSortOrder();
  sortYearDropDownOptions(optionSorter, document.forms['filtersForm'].elements['Year'].options);
  sortYearDropDownOptions(optionSorter, document.forms['filtersForm'].elements['YearTo'].options);
  //To restore the state of previous selection if any.
  var year = document.forms['filtersForm'].elements['Year'].selected;
  var yearTo = document.forms['filtersForm'].elements['YearTo'].selected;
  var vehicleType = document.forms['filtersForm'].elements['VehicleType'].selected;
  var make = document.forms['filtersForm'].elements['Make'].selected;
  var model = document.forms['filtersForm'].elements['ModelName'].selected;
  // Restore previous selection.
  document.forms['filtersForm'].elements['Year'].selectedIndex = document.forms['filtersForm'].elements['Year'].length - 1;
  document.forms['filtersForm'].elements['YearTo'].selectedIndex = 0;
  document.forms['filtersForm'].elements['VehicleType'].selected = vehicleType;
  document.forms['filtersForm'].elements['Make'].selected = make;
  document.forms['filtersForm'].elements['ModelName'].selected = model;
  resetFields();
}
/**
 * 
 * @return
 */
function getFilterSelections(){
  vehicleFlag = 1;
  var year = document.forms['filtersForm'].elements['Year'].value;
  var yearTo = document.forms['filtersForm'].elements['YearTo'].value;
  // Swap the values of year and  yearTo, if (year > yearTo)
  if (year > yearTo) { var temp = year; year = yearTo; yearTo = temp; }
  var type = document.forms['filtersForm'].elements['VehicleType'].value;
  var make = document.forms['filtersForm'].elements['Make'].value;
  var modelName = document.forms['filtersForm'].elements['ModelName'].value;
  var mileage = document.forms['filtersForm'].elements['Mileage'].value;
  var price = document.forms['filtersForm'].elements['Price'].value;
  var cert = document.forms['filtersForm'].elements['Certified'].checked;
  var sortSelect = document.forms['sortForm'].elements['sortSelect'].value;
  var vehiclesPerPage = YAHOO.util.Dom.get('vehiclesPerPage').options[YAHOO.util.Dom.get('vehiclesPerPage').selectedIndex].value;
  var pageNo = YAHOO.util.Dom.get('pageNo').value;
  var strSelections = '{"year":"' + year + '", "yearTo":"' + yearTo + '", "type":"' + type + '", "make":"' + make + '", "model":"' + modelName
        + '", "mileage":"' + mileage + '", "price":"' + price + '", "cert":"' + cert + '", "sortOrder":"' + sortOrder + '", "sortSelect":"'
        + sortSelect + '", "vehiclesPerPage":"' + vehiclesPerPage + '", "pageNo":"' + pageNo + '"}';
  return strSelections;
}
/**
 * 
 * @param objFilterForm
 * @return
 */
function setFilterSelections(objFilterForm) {
  if(!objFilterForm) { return; }
  selectValue('filtersForm', 'Year', objFilterForm.year, 'value', relaxedCompare);
  selectValue('filtersForm', 'YearTo', objFilterForm.yearTo, 'value', relaxedCompare);
  selectValue('filtersForm', 'VehicleType', objFilterForm.type, 'value', relaxedCompare);
  selectValue('filtersForm', 'Make', objFilterForm.make, 'value', relaxedCompare);
  populateVehicleFilter({ 'matches' : function(objModel) {
    return (objFilterForm.make == 'All' || objModel.Make == objFilterForm.make)
        && (objFilterForm.type == 'All' || objModel.VehicleType == objFilterForm.type)? true:false;
  } });
  selectValue('filtersForm', 'ModelName', objFilterForm.model, 'value');
  selectValue('filtersForm', 'Mileage', objFilterForm.mileage, 'value');
  selectValue('filtersForm', 'Price', objFilterForm.price, 'value');
  document.forms['filtersForm']['Certified'].checked = ('true' == objFilterForm.cert);
  sortOrder = ((objFilterForm.sortOrder == '1')? 1 : -1);
  selectValue('sortForm', 'sortSelect', objFilterForm.sortSelect, 'value');
  selectValue('sortForm', 'vehiclesPerPage', objFilterForm.vehiclesPerPage, 'value');
  setSortOrderImage();
  filterCurrentVehicles();
}
/**
 * 
 * @param imgUrls
 * @return
 */
function showVehicleParts(imgUrls)
{
  if(imgUrls.length > 1){
    arrImgList = new Array();
    var arrImgs = imgUrls.split('|');
    for(var j = 0; j < arrImgs.length; j++){
      arrImgList[j] = arrImgs[j];
    }
    imageState(selectedImgNo);
    var loadedImage = new Image();
    loadedImage.onload = function() {
      var imageHolder = YAHOO.util.Dom.get('imageData');
      imageHolder.src = arrImgList[selectedImgNo];
      imageHolder.style.width = (loadedImage.width > 600 ? 600 : loadedImage.width) + 'px';
      var largeImg = YAHOO.util.Dom.get('largeImage');
      largeImg.style.visibility = 'visible';
      largeImg.style.display = 'block';
      largeImg.style.width = imageHolder.width + 'px';
      centerElement(largeImg,largeImg.offsetWidth,largeImg.offsetHeight);
    }
    loadedImage.src = arrImgList[selectedImgNo]; //This causes the loading of the image.
    showDimLayer();
  }
}
/**
 * 
 * @return
 */
function showDimLayer ( ) {
  var obj = YAHOO.util.Dom.get('dimmedLayer');
  var opacity = 50;
  obj.style.filter = 'alpha(opacity:' + opacity + ')';
  obj.style.KHTMLOpacity = opacity / 100;
  obj.style.MozOpacity = opacity / 100;
  obj.style.opacity = opacity / 100;
  obj.style.visibility = 'visible';
  obj.style.height = getPageDimensions().height + 'px';
  obj.style.display = 'block';
}
/**
 * 
 * @return
 */
function hideLargeImage () {
  YAHOO.util.Dom.get('largeImage').style.visibility = 'hidden';
  YAHOO.util.Dom.get('dimmedLayer').style.visibility = 'hidden';
  YAHOO.util.Dom.get('largeImage').style.display = 'none';
  YAHOO.util.Dom.get('dimmedLayer').style.display = 'none';
  selectedImgNo = 0;  // Reseting the selected image index
}

/**
 * 
 * @return
 */
function prevImage () {
  imageState(selectedImgNo - 1);
  var bigImg = YAHOO.util.Dom.get('imageData');
  selectedImgNo = (selectedImgNo == 0)? selectedImgNo: --selectedImgNo;
  bigImg.src = arrImgList[selectedImgNo];
}

/**
 * 
 * @return
 */
function nextImage () {
  var bigImg = YAHOO.util.Dom.get('imageData');
  imageState(selectedImgNo + 1);
  selectedImgNo = (selectedImgNo == arrImgList.length - 1)?selectedImgNo: ++selectedImgNo;
  bigImg.src = arrImgList[selectedImgNo];
}
/**
 * 
 * @param count
 * @return
 */
function imageState (count) {
  var prevImg = YAHOO.util.Dom.get('prevImageId');
  var nextImg = YAHOO.util.Dom.get('nextImgId');
  nextImg.style.display='block';
  prevImg.style.display='block';
  if (count == arrImgList.length - 1) { nextImg.style.display = 'none'; }
  if (count == 0) { prevImg.style.display = 'none'; }
}
/**
 * 
 * @param index
 * @return
 */
function showHideInfo(index, isFLM)
{
  var f1 = YAHOO.util.Dom.get('infoMain' + index);
  var f2 = YAHOO.util.Dom.get('moreButton' + index);
  var f3 = YAHOO.util.Dom.get('hideButton' + index);
  // If "More" button is visible, show the full MarketingText and "Hide" button and remove "More" button
  if ( f2.style.display == "block" ) {
    f1.innerHTML = arrMarketingText[index];
    f2.style.display = 'none';
    f3.style.display = 'block';
  }
  // If "Hide" button is visible, show the preview MarketingText and "More" button and remove "Hide" button
  else if ( f3.style.display == "block" ) {
      if (isFLM){
          f1.innerHTML = '\u0022' + arrMarketingText[index].substring(0, FLM_MARKETING_TEXT_PREVIEW_CHARS)
               + (arrMarketingText[index].length < FLM_MARKETING_TEXT_PREVIEW_CHARS ? '' : ' ......') + '\u0022';
      } else {
          f1.innerHTML = arrMarketingText[index].substring(0, MARKETING_TEXT_PREVIEW_CHARS)
               + (arrMarketingText[index].length < MARKETING_TEXT_PREVIEW_CHARS ? '' : ' ...');
      }

    /* TODO: The following two lines of commented code may be required if MarketingText exceeds more than 5 lines (450+ characters).
     *       At present, MarketingText in the locate is of only 256 characters max.
     *
     * f1.innerHTML += ' <a class="poiLinksTxt" href="' + YAHOO.util.Dom.get('poiVehicleDetailsLink' + index).href + '">'
     *            + arrStrings['apps.inventory.filter.details'] + ' ></a>';
     */
    f2.style.display = 'block';
    f3.style.display = 'none';
  }
}
/**
 * Call the Ominiture Event for Used Inventory
 * 
 * @param channel
 * @param prop5
 * @param make
 * @param model
 * @param year
 * @param bodydesc
 * @param selIndex
 * @param intEndIndex
 * @return
 */
function ominitureEventForUsedInventory ( channel , prop5 , make , model , year , bodydesc , selIndex , intEndIndex ) {
  setTempVariables();
  if (s !== null) 
  {
    s.templtv = s.linkTrackVars;
    s.linkTrackVars = 'channel,eVar1,eVar2,eVar3,eVar4,eVar5,eVar12,eVar14,eVar15,eVar16,eVar18,eVar35,prop1,prop2,prop3,prop4,prop5,prop12,prop14,prop15,prop16,prop21';
    s.pageName = prop5;
    s.channel = channel;
    s.eVar3 = s.prop3;
    s.prop5 = prop5;
    s.prop12 = s.eVar12 = year;
    s.eVar18 = bodydesc;
    s.eVar5 = "used";
    s.prop16 = s.eVar16 = make.toLowerCase() + " " + model.toLowerCase();
    s.prop21 = s.eVar35 = parseInt(selIndex) + 1 + ':' + intEndIndex;
    fireOmnitureEventToS1();
    if(s.templtv){s.linkTrackVars=s.templtv;}
  }
  resetVariables();   
}
