// Whether the page accessed is vehicle-details type or new-vehicles-inventory type.
var isDetailsPage = true;
var overObj = null;
var coordinates = null;

/**
 * @param strName
 */
 function showEquipmentTab(strName) {
  // First hide all the other tabs
  for (var i = 0; i < arrEquipmentTabs.length; i++) {
    var objContentDiv = document.getElementById("ndEquipment" + arrEquipmentTabs[i]);
    objContentDiv.style.display = "none";
    var objTabDiv = document.getElementById("ndEquipmentTab" + arrEquipmentTabs[i]);
    objTabDiv.className = "contact-background";
    if (strName == arrEquipmentTabs[i]) {
      curTabIndex = i;
    }
  }
  // Now show the correct one
  var objContentDiv = document.getElementById("ndEquipment" + strName);
  objContentDiv.style.display = "block";
  var objTabDiv = document.getElementById("ndEquipmentTab" + strName);
  objTabDiv.className = "selected-tab";
  // Update the next/prev buttons
  var objPrevTab = document.getElementById("ndPreviousTab");
  var objNextTab = document.getElementById("ndNextTab");
  objPrevTab.innerHTML = "&lt; " + getPreviousTab();
  objNextTab.innerHTML = getNextTab() + " &gt;";
}

/**
 * Returns the name of the next tab
 */
function getNextTab() {
  return (curTabIndex < arrEquipmentTabs.length - 1) ? arrEquipmentTabs[curTabIndex + 1] : arrEquipmentTabs[0];
}

/**
 * Returns the name of the previous tab
 */
function getPreviousTab() {
  return (curTabIndex > 0) ? arrEquipmentTabs[curTabIndex - 1] : arrEquipmentTabs[arrEquipmentTabs.length - 1];
}

/**
 * show the name of the next tab
 */
function showNextTab() {
  showEquipmentTab(getNextTab());
}

/**
 * show the name of the previous tab
 */
function showPreviousTab() {
  showEquipmentTab(getPreviousTab());
}

/**
 * To hide the status message
 */
function hideStatusMessage()
{
  var status = document.getElementById("statusDiv");
  status.style.visibility = "hidden";
  hideIFrameMask("belowStatusDiv");
}

/**
 * Function for the Yahoo AJAX toolkit.  This gets called when the AJAX call returns
 * with failure.
 */
var handleFailure = function(o)
{
  hideStatusMessage();
};

var handleSuccess = function(o)
{
  hideStatusMessage();
  if(o.responseText == null || o.responseText == 'null')
  {
    displayInlinePrice(null);
    return;
  }
  var inlinePrice = JSON.parse(o.responseText);
  //if zipcode is defined invalid by the admin.
  if(inlinePrice.invalidZipCode)
  {
    showHideZipCodeErrorMessage(userInputBaseId, true);
    return;
  }
  displayInlinePrice(inlinePrice);
  document.getElementById("zipCodeEntered").innerHTML = zipCode + '.';
  changeDisplayStatus("ViewSpecialOffer", false);
  changeDisplayStatus("zipCodeMessageDiv", false);
  changeDisplayStatus("zipCodeDiv", true);
  setZipCodeCookie(zipCode);
  showHideZipCodeErrorMessage('zipCodeDiv' ,false);
};

/**
 * An object for the Yahoo AJAX toolkit.
 */
var specialOfferCallback =
{
  success: handleSuccess,
  failure: handleFailure,
  argument: [""]
};

/**
 * @param objInlinePrice
 */
function displayInlinePrice(objInlinePrice)
{
  var inlinePricingTable = document.getElementById("inlinePricingTable");
  var strHtml = '';
  if(objInlinePrice.adjustedPriceOffers && objInlinePrice.adjustedPriceOffers != objInlinePrice.originalPrice && objInlinePrice.adjustments && objInlinePrice.adjustments.length) {
    strHtml += getPricingAdjustmentTable(objInlinePrice.adjustments);
    if(objInlinePrice.expiryDate && objInlinePrice.expiryDate != null) {
      strHtml += '<div class="ndSpecialOfferRow instructionalText"><i style="padding-left:15px;">' + arrStrings['apps.incentives.offersexpiry'] + ' ' + objInlinePrice.expiryDate + '</i></div>';
    }
    var adjustedPrice = objInlinePrice.adjustedPriceOffers;
    //plantype price is greater than zero the calculate adjusted price
    if(planTypePrice > 0) {
    /**
     * for getting total discount, subtracted objInlinePrice.originalPrice(MSRP)from adjusted price
     * and added total discount to AXZ-plan price
     */
      adjustedPrice = parseFloat(planTypePrice) + parseFloat(adjustedPrice) - parseFloat(objInlinePrice.originalPrice);
    }
    strHtml += '<div class="ndSpecialOfferLine"></div>'
    strHtml += '<div class="ndSpecialOfferRow"><div class="ndSpecialOfferLeft header6D">'+ arrStrings['apps.inventory.filter.adjustedprice'] + ":</div><div class='ndSpecialOfferRight header6D'>$" + currencyFormat(adjustedPrice) + '&nbsp;&nbsp;&nbsp;&nbsp;</div></div>'
  }
  strHtml += getCampaignsHTML(objInlinePrice);
  inlinePricingTable.innerHTML =  strHtml;
  var zipCodeDiv = document.getElementById("zipCodeMessage");
  var zipCodeMessageDiv = document.getElementById("zipCodeMessageDiv");
  if(zipCodeDiv != null && zipCodeMessageDiv != null) {
    zipCodeDiv.innerHTML = arrStrings['apps.inventory.filter.zipinfo'];
    zipCodeMessageDiv.style.display = 'block';
  }
  displayCampaignDisclaimers(objInlinePrice.campaignDisclaimers);
}

/**
 * @param objInlinePricing
 */
function getCampaignsHTML(objInlinePricing)
{
  var strHTML = '';
  if(!objInlinePricing.adjustedPriceCampaign || objInlinePricing.adjustedPriceCampaign == objInlinePricing.originalPrice) {
    return strHTML;
  }
  var campaignList = objInlinePricing.campaigns;
  if(campaignList && campaignList != null && campaignList.length) {
    for(var i in campaignList) {
      //Exclude MUSTANG SHELBY models from Foc Summer Campaign
      if(campaignList[i].type == 'PRICE_OVERRIDE' && !(isVehicleExcluded(modelInfoObject.year, vehicleDetailsObject.modelName, vehicleDetailsObject.bodyDesc) && campaignList[i].name.search(/Foc Summer Campaign/i)>=0 )) {
        strHTML += '<div class="ndSpecialOfferLine"><div class="ndStar"></div>';
        if(userLanguage == 'en' || userLanguage == 'es'){
          strHTML += '<div class="ndSpecialOfferLeft fep-text header5D">' + campaignList[i].description + ':</div><div class="ndSpecialOfferRight fep-value header5D">$' + currencyFormat(objInlinePricing.adjustedPriceCampaign) + "**</div>"
        }
        else{
          strHTML += '<div class="ndSpecialOfferLeft fep-text header5D">' + campaignList[i].description + ':</div><div class="ndSpecialOfferRight fep-value header5D">' + currencyFormat(objInlinePricing.adjustedPriceCampaign) + "$**</div>"
        }
        strHTML += '</div>';
        YAHOO.util.Dom.replaceClass("focMsrpText","header5D", "header6");
        YAHOO.util.Dom.replaceClass("focMsrpValue","header5D", "header6");
      }
    }
  }
  return strHTML;
}

/**
 * Makes an Ajax Call to refresh inline incentives
 * @param userZipCode
 */
function refreshZipCode(userZipCode)
{
  if(userZipCode && !validateUSZipCode(userZipCode)){
    alert(arrStrings['apps.inputvalidation.invalidzipus']);
    return;
  }
  if(userZipCode == zipCode){
    return;
  }
  zipCode = userZipCode;
  setCookie("zipCodeCookie",zipCode,7);
  getInlinePricing(zipCode);
}

/**
 * To show the status message
 * @param strMessage
 */
function showStatusMessage(strMessage)
{
  var status = document.getElementById("statusDiv");
  var statusMessage = document.getElementById("statusDivMessage");
  statusMessage.innerHTML = strMessage;
  status.style.visibility = "visible";
  showIFrameMask("belowStatusDiv", "statusDiv");
}

/**
 * @param zipCode
 */
function getInlinePricing(zipCode)
{
  showStatusMessage(arrStrings["apps.inventory.details.lookingforoffers"]);
  var request = YAHOO.util.Connect.asyncRequest('GET', "../../services/getVehicleInlinePrice?pacode=" + dealer.paCode + "&modelid=" + modelInfoObject.id + "&vin=" + vehicleDetailsObject.vin + "&lang=" + userLanguage + "&zipcode=" + zipCode, specialOfferCallback);
}

/**
 * @param arrAdjustments
 */
function getPricingAdjustmentTable(arrAdjustments)
{
  var strAdjustmentTable = "";
  for(var i in arrAdjustments) {
    var strHTML = '<div class="ndSpecialOfferRow"><div class="ndSpecialOfferLeft header9"><div class="ndStar"></div>' + arrAdjustments[i].name + '</div>';
    strHTML += '<div class="ndSpecialOfferRight header9">-$' + currencyFormat(-arrAdjustments[i].amount) + '&nbsp;&nbsp;&nbsp;&nbsp;</div></div>';
    strAdjustmentTable += strHTML;
  }
  return strAdjustmentTable;
}

/**
 * @param objDisclaimerMap
 */
function displayCampaignDisclaimers(objDisclaimerMap)
{
  if(!objDisclaimerMap && objDisclaimerMap == null) {
    return;
  }
  var strHtml = '';
  for(var key in objDisclaimerMap) {
    strHtml += "** " + objDisclaimerMap[key] + '<br>';
  }
  document.getElementById("campaign-disclaimer").innerHTML = strHtml;
}
/**
 * To check the position of mouse pointer
 * and it returns true or false
 * @param event
 */
function checkTheMousePoint(event) {
  var mousePoint_x;
  var mousePoint_y;
  if(!document.all) {
    mousePoint_x = event.pageX;
    mousePoint_y = event.pageY;
  } else {
    mousePoint_x = event.clientX+document.body.scrollLeft-document.body.clientLeft-2;
    mousePoint_y = event.clientY+document.body.scrollTop-document.body.clientTop;
  }
  var overObj_topLeftPoint_x = coordinates[0];
  var overObj_topLeftPoint_y = coordinates[1];
  var overObj_bottomRightPoint_x = overObj_topLeftPoint_x+overObj.offsetWidth;
  var overObj_bottomRightPoint_y = overObj_topLeftPoint_y+overObj.offsetHeight;
  return (mousePoint_x>overObj_topLeftPoint_x&&mousePoint_x<overObj_bottomRightPoint_x)&&(mousePoint_y>overObj_topLeftPoint_y&&mousePoint_y<overObj_bottomRightPoint_y) ? !((mousePoint_x>overObj_topLeftPoint_x&&mousePoint_x<overObj_bottomRightPoint_x)&&(mousePoint_y>overObj_topLeftPoint_y&&mousePoint_y<overObj_bottomRightPoint_y)) : !((mousePoint_x>overObj_topLeftPoint_x&&mousePoint_x<overObj_bottomRightPoint_x)&&(mousePoint_y>overObj_topLeftPoint_y&&mousePoint_y<overObj_bottomRightPoint_y));
}
/**
 * To display the tool tip 
 * @param obj
 */
function showToolTip(obj)
{
  var overObj = document.getElementById("feature_"+obj);
  var tooltip = document.getElementById("toolTip");
  var coordinates = findPosition(overObj);
  tooltip.style.left = (coordinates[0]-100) + "px";
  tooltip.style.top = coordinates[1]+"px";
  tooltip.style.visibility = 'visible';
}

/**
 * To hide the tool tip 
 * @param event
 */
function hideToolTip(event)
{
  var toHideTheDIV = checkTheMousePoint(event);
  if(toHideTheDIV) {
    var tooltip = document.getElementById("toolTip");
    tooltip.style.visibility = 'hidden';
  }
}

  /**
   * @param count
   * @param arrayLength
   */
function imageState(count, arrayLength)
{
  var prevImg = document.getElementById("prevImageId");
  var nextImg = document.getElementById("nextImgId");
  //The arrayLength <= 2 corresponds to the case where the number of images <= 1. In such a case both the prev & next are not shown.
  if (arrayLength <= 2)
  {
    nextImg.style.display="none";
    prevImg.style.display="none";
  }
  else if(count == (arrayLength-1))
  {
    nextImg.style.display="none";
    prevImg.style.display="block";
  }
  else if(count == 1)
  {
    prevImg.style.display="none";
    nextImg.style.display="block";
  }
  else
  {
    nextImg.style.display="block";
    prevImg.style.display="block";
  }
}
/**
 * To display the dim layer
 */
function showDimLayer()
{
  var obj = document.getElementById('dimmedLayer');
  obj.style.display = "block";
  var dims = getScreenCordinates();
  obj.style.height = dims[1];
  obj.style.width = dims[0];
}

/**
 * To hide the large image 
 */
function hideLargeImage()
{
  document.getElementById("largeImage").style.visibility = "hidden";
  document.getElementById('dimmedLayer').style.display = "none";
}

/**
 * To validate the form
 * @param formElement name of the form
 */
function validate(formElement)
{
  var firstName = (formElement['firstName'] || formElement['FirstName']).value;
  var lastName = (formElement['lastName'] || formElement['LastName']).value;
  var address = (formElement['street'] || formElement['Address1']).value;
  var zipCode = (formElement['postalCode'] || formElement["ZipCode"]).value;
  var phone = (formElement['phone'] || formElement['DayPhone']).value;
  var email = (formElement['email'] || formElement['Email']).value;
  return validator.checkFirstName(firstName) && validator.checkLastName(lastName)
    && validator.checkAddress(address) && validator.checkZip(zipCode) && validator.checkPhone(phone)
    && validator.checkEmail(email);
}
/**
 * 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 details page
 * @param year the year of the model
 * @param make the make of the model
 * @param model
 */
function callPopupStickerInDetails(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 details page
 * @param year the year of the model
 * @param make the make of the model
 * @param model
 */
function callSendEmailInDetails(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;
    }
  }
}
