/**
*Common declarations of global variables
*/
var months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); 
var timeOfDay = new Array("Morning", "Afternoon", "Evening"); 
    	

/**
 * Common javascript functions.
 */

function callPopup(myLocation, nWidth, nHeight)
{
  var sOptions = "menubar=1,toolbar=1,location=1,directories=0,status=1,scrollbars=1,resizable=1,width=" + nWidth + ",height=" + nHeight;
  window.open(myLocation, 'popupWndow', sOptions);
}

/**
 * A light representation of the Dealer java object.
 */
function Dealer(strPACode, strName, strPostalCode, strFax, strSubdomain, strSourceOfData, strCountry, strState) {
  this.paCode = strPACode;
  this.name = strName;
  this.postalCode = strPostalCode;
  this.fax = strFax;
  this.subdomain = strSubdomain;
  this.sourceOfData = strSourceOfData;
  this.country = strCountry;
  this.state = strState;
}

/**
 * Object to hold some relevant information about a model
 */
function ModelInfo(strId, strModelName, strYear, strLocateId, strMake, strBasePrice) 
{
  this.id = strId;
  this.name = strModelName;
  this.year = strYear;
  this.locateId = strLocateId;
  this.make = strMake;
  this.basePrice = strBasePrice;
}

/*
 * Object to hold some relevant information about the vehicle details
 * obtained from locate service.
 */
function LocateVehicleDetails(modelName, price, bodyDesc, vin, trimCode, autoTrans, engineCode, mileage, make, year) 
{
  this.modelName = modelName;
  this.price = price;
  this.bodyDesc = bodyDesc;
  this.vin = vin;
  this.trimCode = trimCode;
  this.autoTrans = autoTrans;
  this.engineCode = engineCode;
  this.mileage = mileage;
  this.make = make;
  this.year = year;
}

/**
 * Format a number of any type to a style like XX,XXX
 */
function currencyFormat(strValue) {
  // Force to an int
  var intVal = Math.round(strValue);
  var strCopy = new String(intVal);
  var arrChunks = [];
  while(strCopy.length > 3)
  {
          var chunk = strCopy.substr(strCopy.length-3);
          arrChunks.unshift(chunk);
          strCopy = strCopy.substr(0,strCopy.length-3);
  }
  if(strCopy.length > 0) { arrChunks.unshift(strCopy); }
  strCopy = arrChunks.join(",");
  return strCopy;
}

/**
 * Show a iframe mask layer behind a floater div.  This is 
 * required because in IE elements like select boxes will show
 * above absolutely positioned floater divs.
 *
 * Make sure there is no padding on the div containing the IFrame
 * or else not everything will get masked.
 *
 * @param strMaskId - ID of the div containing the iframe
 * @param strDivId - ID of the content div, used to copy it's position
 *  and size
 * @param intZIndex - zIndex of the mask div, should be less than the content.
 */
function showIFrameMask(strMaskId, strDivId) {
  var layer = document.getElementById(strDivId);
  layer.style.display = 'block';

  // show iframe
  var iframe = document.getElementById(strMaskId);
  iframe.style.visibility = 'visible';
  iframe.style.width = layer.offsetWidth;
  iframe.style.height = layer.offsetHeight;
  iframe.style.left = layer.offsetLeft;
  iframe.style.top = layer.offsetTop;  
}

function hideIFrameMask(strMaskId) {
  var iframe = document.getElementById(strMaskId);
  iframe.style.visibility = 'hidden';
}

/**
 * A function to build an associative array of request parameters.
 */
function getRequestParams() {
  var params = new Array();
  if (window.location.search.length < 2) {
    return params;
  }

  // Split the string by & and then =
  var pairs = window.location.search.substring(1).split("&");
  for (var i = 0; i < pairs.length; i++) {
    var arrPair = pairs[i].split("=");
    if (arrPair.length == 1) {
      params[arrPair[0]] = null;
    } else {
      params[arrPair[0]] = arrPair[1];
    }
  }
  return params;
}

/**
 * To launch the payment estimator.
 * @param finURL the external base service url we use.
 * @param newOrUsed 'N' if a new vehicle, 'U' otherwise.  
 * @param vehicleDetails the vehicle details obtained from locate service.
 * @param modelInfo the model information.
 */
function openPaymentEstimator(finURL, newOrUsed, vehicleDetails, modelInfo) 
{
  var zipCode = getUserZipCode();  
  var stateCode = getUserState();
  
  // if both are null, then cancel was pressed in popup
  if (zipCode == null && stateCode == null) {
    return;
  }
  
  var strURL = 'https://' + finURL + '/aaui?ATD_SERVLET_ACTION=PE&ATD_SERVLET_PAGE_CLASS=AAExternal&AirCond=Y&CountryCode=' + getFMCCCountryCode(dealer) + '&LanguageCode=' + userLanguage + '&InterfaceHomeURL=http://' + dealer.subdomain + '.dealerconnection.com&SourceOfData=' + dealer.sourceOfData;
  strURL = createURL(strURL, newOrUsed, vehicleDetails, modelInfo, zipCode, stateCode);
  callPopup(strURL, 800, 600);
}
 
/**
 * Opens up the credit application in a popup.
 * @param finURL the external base service url we use.
 * @param newOrUsed 'N' if a new vehicle, 'U' otherwise.  
 * @param vehicleDetails the vehicle details obtained from locate service.
 * @param modelInfo the model information.
 */
function openCreditApplication(finURL, newOrUsed, vehicleDetails, modelInfo) 
{
  var zipCode = getUserZipCode();  
  var stateCode = getUserState();
  
  // if both are null, then cancel was pressed in popup
  if (zipCode == null && stateCode == null) {
    return;
  }
  
  var strURL = "https://" + finURL + "/aaui?ATD_SERVLET_ACTION=CA&ATD_SERVLET_PAGE_CLASS=AAExternal&AirCond=Y&CountryCode=" + getFMCCCountryCode(dealer) + "&LanguageCode=" + userLanguage + "&InterfaceHomeURL=http://" + dealer.subdomain + ".dealerconnection.com&SourceOfData=" + dealer.sourceOfData; 
  strURL = createURL(strURL, newOrUsed, vehicleDetails, modelInfo, zipCode, stateCode);  
  callPopup(strURL, 800, 600);
}

/**
 * Prompts the Applicant for his ZipCode.
 * @return the user's zipcode if entered, else, returns null
 */
function getUserZipCode() 
{

  var zipCode = null;
  
  if (dealer.country == 'us') 
  {
    var isValidZipCode = false;
    
    while (!isValidZipCode) 
    {
      zipCode = prompt (arrStrings['apps.inventory.zipCode.prompt'],'');
    
      // return if the user preses cancel
      if (zipCode == null) 
      {
        return null;
      }
      
      isValidZipCode = validateUSZipCode(zipCode);
      
      if (!isValidZipCode) 
      {
        alert(arrStrings['apps.inventory.zipCode.invalid']);
      }
    } 
  }
  return zipCode;
}

/**
 * Checks for a valid US Zip code
 * @param zipCode the zipCode to validate
 * @return true if its a valid US Zip Code
 */
function validateUSZipCode(zipCode) {
  var usZipCode = /^\d{5}$/;
  return usZipCode.test(zipCode);
}

/**
 * Prompts the Applicant for his State.
 * @return the user's state if entered, else, returns null
 */
function getUserState() 
{

  var state = null;
  
  if (dealer.country == 'ca') 
  {  
    var isValidState = false;

    while (!isValidState) 
    {
      state = prompt (arrStrings['apps.inventory.state.prompt'],'');
    
      // return if the user preses cancel
      if (state == null) 
      {
        return null;
      }
    
      isValidState = validateCAState(state);
      
      if (!isValidState) 
      {
        alert(arrStrings['apps.inventory.state.invalid']);
      }
    }    
  }
  
  return (null == state)?null : state.toUpperCase();  
}

/**
 * Checks for a valid Canada State code
 * @param state the state to validate
 * @return true if its a valid Canada State Code
 */
function validateCAState(state) {
  var canStateCode = /^[a-zA-Z]{2}$/;
  return canStateCode.test(state);
}

/**
 * Get the country code to pass to FMCC.
 */
function getFMCCCountryCode(objDealer) {
  var countryCode = "USA";
  if (objDealer.country == "ca") {
    countryCode = "CAN";
  }
  return countryCode;
}

/**
 * Attaches vehicle & model parameters to the finance url.
 * @param finURL the external base service url we use.
 * @param newOrUsed 'N' if a new vehicle, 'U' otherwise.  
 * @param vehicleDetails the vehicle details obtained from locate service.
 * @param modelInfo the model information.
 * @param zipCode the applicant's postal code
 */
function createURL(finURL, newOrUsed, vehicleDetails, modelInfo, zipCode, stateCode)
 {
 
   // attach common parameters
   strURL = attachCommonParameters(finURL, newOrUsed);
   
   // attach regional parameters
   if (dealer.country == 'us') 
   {
     strURL += attachUSRegionalParameters(zipCode);
   } 
   else if (dealer.country == 'ca') 
   {
     strURL += attachCARegionalParameters(stateCode);
   }
   
   // attach model/vehicle parameters
   if (null == vehicleDetails)
   {
     if (null != modelInfo) 
     {
       return attachModelParameters(strURL, newOrUsed, modelInfo);
     } 
     //Since we dont have both vehicle & model details we send back the base url with just dealer data.
     return strURL;
   }
   else 
   {
     return attachModelVehicleParameters(strURL, newOrUsed, modelInfo, vehicleDetails);
   }
 }

/*
 * Removes characters from the number string which are not digits. Is used to remove extra formats in a number string.
 * @param number formatted number string. ex : '312(1121)+22'
 * @return the digit sequence after removing the formatting. ex: 312112122
 */
function extractNumber(number) 
{
   return number.replace(/[^0-9]/g, '');
}

/*
 * Removes all extra formattings from a zip code. Zip code can have alphabets in them. ex : canada zipcodes.
 * @param zip formatted zip string. ex : 'aaa 1223' 
 * @return the digit sequence after removing the formatting. ex: aaa1223
 */
function extractZip(zip)
{
   return zip.replace(/[^0-9a-zA-Z]/g, '');
}

/*
 * To extract the bodystyle code from vin. Currently characters 5-7 of the VIN code
 * form the bodystyle code.
 * @param vin the complete vin of the vehicle.
 *
 * @return the bodystyle code of the vehicle.
 */
function extractBodyStyleCodeFromVIN(vin)
{
  if(null != vin && 7 <= vin.length)
  {
    return vin.substr(4,3);
  }
  return '';
}

/*
 * Appends to the base url, the common parameters for a finance request.
 */
function attachCommonParameters(strURL, newOrUsed)
{

  strURL += '&DealerPACode=' + dealer.paCode;
  strURL += '&DealerName=' + escape(dealer.name);
  strURL += '&DealerFullFax=' + extractNumber(dealer.fax);
  strURL += '&DealerFullPhone=';
  strURL += '&DealerEmailAddr=';
  strURL += '&ePrice=N';
  strURL += '&PEPDiscount=0';
  strURL += '&NewUsedIndicator=' + newOrUsed;
  return strURL;
}

/*
 * Appends to the base url, the regional US specific parameters for a finance request.
 */
function attachUSRegionalParameters(zipCode)
{
  return '&paFullZipCode=' + zipCode;
}

/*
 * Appends to the base url, the regional Canada specific parameters for a finance request.
 */
function attachCARegionalParameters(stateCode)
{
  return '&paCurResState=' + stateCode;
}

/*
 * Appends to the base url various model parameters involved in a finance request.
 * @param strURL the external base service url we use.
 * @param newOrUsed 'N' if a new vehicle, 'U' otherwise.  
 * @param modelInfo the model information.
 */
function attachModelParameters(strURL, newOrUsed, modelInfo) 
{

  strURL += '&ModelName=' + modelInfo.name;
  strURL += '&ModelKey=' + modelInfo.year + '|' + modelInfo.make + '|999';
  strURL += '&ModelPrice=' + modelInfo.basePrice;
  strURL += '&SellingPrice=' + modelInfo.basePrice;
  return strURL;
}

/*
 * Appends some vehicle details params onto the url.
 *
 * @param strURL the external base service url we use.
 * @param vehicleDetails the vehicle details obtained from locate service.
 *
 * @return the modified url. 
 */
function attachVehicleParameters(strURL, vehicleDetails)
{
  strURL += '&ModelName=' + vehicleDetails.modelName;
  strURL += '&ModelPrice=' + vehicleDetails.price;
  strURL += '&SellingPrice=' + vehicleDetails.price;
  strURL += '&EngineCode=' + vehicleDetails.engineCode;
  strURL += '&AutoTrans=' + vehicleDetails.autoTrans; 
  strURL += '&TrimCode=' + vehicleDetails.trimCode;
  strURL += '&TrimDesc=' + escape(vehicleDetails.bodyDesc);
  return strURL;
}

/*
 * Appends to the base url various model & vehicle parameters involved in a finance request.
 * @param strURL the external base service url we use.
 * @param newOrUsed 'N' if a new vehicle, 'U' otherwise.  
 * @param modelInfo the model information.
 * @param vehicleDetails the vehicle details obtained from locate service.
 *
 * @return the modified url. 
 */
function attachModelVehicleParameters(strURL, newOrUsed, modelInfo, vehicleDetails) 
{

  var bodyStyleCode = extractBodyStyleCodeFromVIN(vehicleDetails.vin);
  
  //For old vehicles we use the locate service data.
  if ('U' == newOrUsed)
  {
    strURL += '&Mileage=' + vehicleDetails.mileage;  
    strURL += '&ModelKey=' + vehicleDetails.year + '|' + vehicleDetails.make + '|' + bodyStyleCode;
  }
  else 
  {  
    strURL += '&ModelKey=' + modelInfo.year + '|' + modelInfo.make + '|' + bodyStyleCode;
    strURL += '&Mileage=0'
  }
  return attachVehicleParameters(strURL, vehicleDetails)
}
