var showPrice, showSub = "true";
var pagePrices = new Array();
var cashback = 0;
function formatCurrency(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num)) { num = "0"; }
  var sign = (num == (num = Math.abs(num)));
  num = Math.floor(num * 100 + 0.50000000001);
  var cents = num % 100;
  num = Math.floor(num/100).toString();
  if(cents < 10) { cents = "0" + cents; }
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
  num = num.substring(0 , num.length-(4*i+3)) + ',' +
  num.substring(num.length-(4 * i + 3));
  return (((sign)?'':'-') + '$' + num + '.' + cents);
}
function getShowPrice() { return showPrice; }
function setShowPrice(price) { showPrice = price; }
function getShowSub() { return showSub; }
function setShowSub(show) { showSub = show; }
function addPrice(id, p) { pagePrices[id] = p; }
function removePrice(id) { delete pagePrices[id]; }
function getTotalCurrPrice() {
  var test = "";
  var id;
  for(id in pagePrices) {
    test += id + ": " + pagePrices[id] + "\n";
  }
  var t = 0;
  for(id in pagePrices) {
    t += pagePrices[id];
  }
  return t;
}
function getCashback() { return cashback; }
function setCashback(cash) { cashback = cash; }
// This function will get the totals from the fields, convert to numbers, and run the totals
function updatePageTotal() {
  var fields = ["base","options","attachments","rebate","discount","cashback"];
  var fieldVals = new Array();
  var t;
  // Get all values and set to numbers
  for(var id in fields) {
    t = $("#quote-" + fields[id]).text(); 
    fieldVals[fields[id]] = Math.abs(t.replace(/\$|\,/g,''));
  }
  // Set subtotal amount
  var subTotal = fieldVals["base"] + fieldVals["options"] + fieldVals["attachments"];
  $("#quote-msrp").text(formatCurrency(subTotal));
  // Total all the fields as needed
  var total = subTotal - fieldVals["rebate"] - fieldVals["discount"] - fieldVals["cashback"];
  $("#quote-price").text(formatCurrency(total));
}
function updatePagePrice() {
  var currPage = $("#currPage").val();
  var p = getTotalCurrPrice();
  $("#quote-" + currPage).text(formatCurrency(p));
  // Update Total fields
  updatePageTotal();
}
function updateDiscountPrice(price) {
  $("#quote-discount").text(formatCurrency(price));
}
function updateBuildItemInfo(id) {
  //Remove 'active' class from unselected buttons
  $("#build-items input").parent().parent().parent().removeClass('active');
  //Add 'active' class to selected buttons
  $("#build-items input:checked").parent().parent().parent().addClass('active');

  //Make ajax call
  if (id == null) {
    updateImage(null);
    updateBuildName("");
    updateBuildDescription("");
    updateBuildPrice("");
    $("#response-area").hide();
  } else {
    buildInfoAjax(id);
  }
}
function updateSpecialOfferDesc(offer) {
  $("#build-special").text(offer);
}
function updateFinanceOption(offer) {
  var showPrice = getShowPrice();
  $("#financeOption").val(offer);
  if(offer == "CASHBACK") {
    $("#quote-cashback").html(formatCurrency(getCashback()));
    $("#cashback-row").show();
    if(showPrice) { updatePagePrice(); }
    if(!getShowSub()) {
      $("#total-row").removeClass("subtotal");
      $("#sug-row").show();
    }
  } else {
    $("#cashback-row").hide();
    $("#quote-cashback").html(formatCurrency(0));
    if(showPrice) { updatePagePrice(); }
    if(!getShowSub()) {
      $("#total-row").addClass("subtotal");
      $("#sug-row").hide();
    }
  }
}
//----------------------------------------------- AJAX Functions -----------------------------------------------------//
function buildInfoAjax(id) {
  var url = "/buildandquote/bq_ajax.html?id=" + id;
  //Ajax variables
  var ajaxData;
  var imgurl;
  var name;
  var desc;
  var price;
  var discount;
  var showPrice;
  var cashback;
  var financing;
  var other;
  var usRebate;
  var offersDetail;
  var apAttInfo;
  var c, f, o, d, r = false; // cashback/fiancing/equipment/discount/rebate bool
  var currPage = $("#currPage").val();

  //Run Ajax call to populate build item information.
  $.get(url, function(data){
    //alert(data);
    //data format
    // [imgurl, name, desc, price, discount,
    //  show price, cashback, financing, other,
    //  usRebate, special offers detail, apAttInfo]
    ajaxData      = eval(data);
    imgurl        = ajaxData[0];
    name          = ajaxData[1];
    desc          = ajaxData[2];
    price         = Math.abs(ajaxData[3]);
    discount      = Math.abs(ajaxData[4]);
    showPrice     = ajaxData[5];
    cashback      = ajaxData[6];
    financing     = ajaxData[7];
    other         = ajaxData[8];
    usRebate      = ajaxData[9];
    offersDetail  = ajaxData[10];
    apAttInfo     = ajaxData[11];

    //alert("Image Url: " + imgurl + "\nName: " + name + "\nDesc: " + desc);
    updateImage(imgurl);
    updateBuildName(name);
    // ========================== Base page totals ========================== //
    if(currPage == "base") { // Only change on basemodel page.
      if(price != 0 && price != null && showPrice) {
        updateBuildPrice(price);
        $("#response-area").show();
        addPrice(id, price);
      } else {
        $("#response-area").hide();
        updateBuildPrice("");
      }
      // Update special offer
      if(discount != 0 && discount != null && showPrice) {
        updateDiscountPrice(discount);
        d = true;
      } else {
        updateDiscountPrice("");
        d = false;
      }
      // Check if we show price or not
      if(showPrice) {
        $("#quoteBoxShowPrice").show();
      } else {
        $("#quoteBoxShowPrice").hide();
      }
      // Check for rebate
      if(usRebate != "0" && usRebate != null && showPrice) {
        $("#quote-rebate").text(formatCurrency(usRebate));
        $("#rebate-row").show();
        r = true;
      } else {
        $("#quote-rebate").text(formatCurrency(0));
        $("#rebate-row").hide();
        r = false;
      }
      // Checking if subtotal should be shown.
      if(!r && !d) {
        $("#total-row").addClass("subtotal");
        $("#sug-row").hide();
        setShowSub(false);
      } else {
        $("#total-row").removeClass("subtotal");
        $("#sug-row").show();
        setShowSub(true);
      }
      // Update choice of offers
      if(cashback != "" && cashback != null && cashback != "0" && showPrice) {
        c = true;
        setCashback(cashback);
      } else { c = false; }
      if(financing != "" && financing != null) {
        f = true;
      } else { f = false; }
      if(other != "" && other != null) {
        o = true;
      } else { o = false; }
      //$("#quote-offer").html("");
      updateFinanceOption("");
      // Show all radio then hide as needed
      $("#offer-finance-div").show();
      $("#offer-cash-div").show();
      $("#offer-other-div").show();
      // -------------- Multi Value -------------- //
      if(c && f && o) {
        $("#input-finance").text("").text(financing);
        $("#input-cash").text("").text("Cash in lieu of financing: " + formatCurrency(cashback));
        $("#input-other").text("").text(other);
        $("#offer-selectRebate").show();
        $("#offer-finance").click();
      } else if (c && !f && o) {
        $("#offer-finance-div").hide();
        $("#input-cash").text("").text("Cash in lieu of financing: " + formatCurrency(cashback));
        $("#input-other").text("").text(other);
        $("#offer-selectRebate").show();
        $("#offer-finance").click();
      } else if (!c && f && o) {
        $("#offer-cash-div").hide();
        $("#input-finance").text("").text(financing);
        $("#input-other").text("").text(other);
        $("#offer-selectRebate").show();
        $("#offer-finance").click();
      } else if (c && f && !o) {
        $("#offer-other-div").hide();
        $("#input-finance").text("").text(financing);
        $("#input-cash").text("").text("Cash in lieu of financing: " + formatCurrency(cashback));
        $("#offer-selectRebate").show();
        $("#offer-finance").click();
      // -------------- Single Value -------------- //
      } else if (!c && f && !o) {
        $("#offer-selectRebate").hide();
        $("#offer-rebate").html("");
        $("<p>" + financing + "</p>").appendTo("#offer-rebate");
        updateFinanceOption("FINANCE");
      } else if (c && !f && !o) {
        $("#offer-selectRebate").hide();
        $("#offer-rebate").html("");
        $("<p>Cash in lieu of financing: " + formatCurrency(cashback) + "</p>").appendTo("#offer-rebate");
        updateFinanceOption("CASHBACK");
      } else if (!c && !f && o) {
        $("#offer-selectRebate").hide();
        $("#offer-rebate").html("");
        $("<p>" + other + "</p>").appendTo("#offer-rebate");
        updateFinanceOption("OTHER");
      // -------------- No Value -------------- //
      } else {
        $("#offer-rebate").html("");
        $("#offer-selectRebate").hide();
      }
      // Update offers detail
      if(offersDetail != "" && offersDetail != null) {
        updateSpecialOfferDesc(offersDetail);
      } else {
        updateSpecialOfferDesc("");
      }
      updatePagePrice();
    } else {
      // Use showPrice from hidden value on page, not ajax call version
      var pageShowPrice = getShowPrice();
      if(price != 0 && price != null && pageShowPrice) {
        updateBuildPrice(price);
        $("#response-area").show();
        addPrice(id, price);
      } else {
        $("#response-area").hide();
        updateBuildPrice("");
      }
      if (pageShowPrice == "true") { updatePagePrice(); }
    }
    // ====================== END Base page totals ========================== //
    // check if desc is null, if it is set to blank so desc is updated correctly.
    if(desc == null) { desc = ""; }
    updateBuildDescription(desc);
  });
}
function updateImage(imgurl) {
  // write response variables to user interface
  var buildImg = document.getElementById('build-img');
  var buildImgUrl;
  var parentAbb = document.getElementById('parentAbb');
  if(imgurl == null) {
    if(parentAbb.value == "asl"){
      buildImgUrl = "/images/bq/build_img_asl_na.jpg";
    } else if(parentAbb.value == "e"){
      buildImgUrl = "/images/bq/build_img_e_na.jpg";
    } else if(parentAbb.value == "ctl"){
      buildImgUrl = "/images/bq/build_img_ctl_na.jpg";
    } else if(parentAbb.value == "ct"){
      buildImgUrl = "/images/bq/build_img_tr_na.jpg";
    } else if(parentAbb.value == "ml"){
      buildImgUrl = "/images/bq/build_img_ml_na.jpg";
    } else if(parentAbb.value == "sl"){
      buildImgUrl = "/images/bq/build_img_sl_na.jpg";
    } else if(parentAbb.value == "uv"){
      buildImgUrl = "/images/bq/build_img_uv_na.jpg";
    } else if(parentAbb.value == "vt"){
      buildImgUrl = "/images/bq/build_img_vt_na.jpg";
    } else if(parentAbb.value == null || parentAbb.value == ''){
      buildImgUrl = "/images/bq/build_img_att_na.jpg";
    } else { buildImgUrl = "/images/bq/build_img_default.jpg"; }
  } else {
    buildImgUrl = imgurl + "&width=350";
  }
  buildImg.src = buildImgUrl;
}
function updateBuildName(name) {
  $('#build-name').text(name);
}
function updateBuildDescription(desc) {
  $('#build-desc').text(desc);
}
function updateBuildPrice(price) {
  $('#build-price').text(formatCurrency(price));
}
//------------------------------------------- END AJAX Functions -----------------------------------------------------//
function errorChecking() {
  var error_msg_location = document.getElementById("zip.errors");
  var error_msg_div = document.getElementById("error_div");
  var error_msg_placement = document.getElementById("error_zip");
  var zipField = document.getElementById("zip_p");
  if(error_msg_location) {
    if(error_msg_div) {
      error_msg_div.style.display = "";
      error_msg_placement.innerHTML = error_msg_location.innerHTML;
      zipField.className = 'validate';
    } else {
      error_msg_div.style.display = "none";
    }
  }
}
function packageItemsUpdate(value) {
  // Remove all existing disabled properties
  $("#build-items input:disabled").removeAttr("disabled");
  $.each($("#package-" + value + "-list li"), function(){
    $("#option-" + this.value).attr("checked", true).attr("disabled", true);
    $("#option-" + this.value).parent().parent().parent().addClass("active");
  });
}
function competitiveCompare() {
  var model, url;
  var tbiFrameHeight;
  var tbiFrameWidth;
  var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;
  var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
  if (windowWidth <= 1025) {
    tbiFrameWidth = windowWidth - 60;
  } else {
    tbiFrameWidth = "1025";
  }
  if (windowHeight <= 625) {
    tbiFrameHeight = windowHeight - 60;
  } else {
    tbiFrameHeight = "625";
  }
  var thickboxVars = "?KeepThis=true&TB_iframe=true&height=" + tbiFrameHeight + "&width=" + tbiFrameWidth;
  // Get the selected basemodel
  model = $(".itemInput input:radio:checked").attr("id");
  url = $("#compare-" + model).val();
  // If link is blank, do nothing.  Should not happen, setup as a failsafe.
  if(url != null && url != "") {
    url = url + thickboxVars;
    $("#competitive_compare_link").attr("href", url);
    $("#competitive_compare_link").click();
  }
}
function disclaimer() { $("#disclaimer_link").click(); }
$(document).ready(
  function() {
    // Show or hide the price sections
    setShowPrice($("#showPrice").val());
    var showPrice = getShowPrice();

    // Update with first checked item
    var id = $("#build-items input:checked").attr("value");
    updateBuildItemInfo(id);

    // Update page price
    if(showPrice == "true") { updatePagePrice(); }

    $("#build-items li a").click(function() {
      // Get the sub ul to show and hide
      $(this).parent().find('.subCategories').slideToggle("normal");
      // Toggle the expand/collapse category icon
      $(this).find('.folderIcon').toggle();
    });

    // Hide all but the first category
    $("#build-items li:not(:first) a").parent().find('.subCategories').slideToggle();
    $("#build-items li:not(:first) a").find('.folderIcon').toggle();

    $('#build-items input').click(function() {
      var showPrice = getShowPrice();
      // Update correct selection highlight
      // Check if radio, if so, clear all prices out for that radio set
      if(this.type == "radio") {
        $("input[name='" + this.name +"']").each(function(){
          removePrice($(this).val());
        });        
      }
      // Check if checked or not
      if (this.checked) {
        updateBuildItemInfo(this.value);
      } else {
        updateBuildItemInfo();
        removePrice(this.value);
        if(showPrice == "true") { updatePagePrice(); }
      }
    });

    // Set onclick for package expanding
    $("#build-items a.packageLink").click(function() {
      $(this).find('.packageIcon').toggle();
      // Toggle the packageitems
      $(this).parent().parent().next().toggle();
    });

    // Set package item update onclick
    $(".packageItem").click(function() {
      updateBuildItemInfo(this.value);
    });

    // Load initial JSON information for alerts
    getAlertInfo(); // in bqAlerts.js
    //getPackageAlertInfo(); // in bqAlerts.js

    // Set a check on all items
    // Ignore all inputs with the 'noAlert' class
    $("#build-items li input:not(.noAlert)").click(function() {
      var optName;
      var selSet;
      // Set radio buttons to also set previous options onclick
      if($(this).is(":radio")) {
        // Pull out radio button set from name
        optName = $(this).attr("name");
        selSet = optName.split('[')[1].split(']')[0];
        setRadio(selSet);
      }
      /* Temp hiding options of a package until all errors are ironed out 07-09-2009 */
        // Check alerts -- Remove if above note is removed to allow for if check again.
        checkAlert(this.value);
      /*
      // Set packaging onclick to show items included in package
      if($(this).hasClass("pkgInput")) {
        // Pull out radio button set from name
        optName = $(this).attr("name");
        selSet = optName.split('[')[1].split(']')[0];
        $("ul[name='packageList[" + selSet + "]']").hide();
        $("#package-" + this.value + "-list").show();

        // Reset package icons to expand
        $.each($(".packageIcon"), function() {
          if($(this).hasClass("exp")) {
              $(this).show();
          } else if ($(this).hasClass("clp")) {
              $(this).hide();
          }
        });

        // Set active package icon to collapse
        $(this).parent().next().find(".exp").hide();
        $(this).parent().next().find(".clp").show();

        // Select/Deselect and Disable/Enable items based on package
        packageItemsUpdate(this.value);
        checkPackageAlert(this.value);
      } else {
        // Check alerts
        checkAlert(this.value);
      } */
    });
    // Hide Compare Competitors button on all but Compact Tractors.  Should only run on basemodel.jsp
    var currPage = $("#currPage").val();
    if(currPage == "base" && ref == "5684") {
      $("#bq-compare").show();
    }
  }
);
