$(document).ready(function() {
  window.cntRes = 0;
  window.cntBus = 0;

  // if the calculator exists
  if ($(".dpl-calculator").length) {

    // format the input on blur
    $(".dpl-calculator input[type!='button']").bind("blur", calcBlurInput);

    // re-draw the calculator if they change the target
    $("#target-select").bind("change", drawCalculator);

    // re-draw the calculator if they change the offer
    $(".offer-select").bind("change", drawCalculator);

    // show or hide the calculate vs compare screens
    $(".calc-function li").bind("click", clickCalcFunction);

    // run the calculation if they click the calculate button
    $(".dpl-calculator .button-calculate").bind("click", clickCalculate);

    buildCalculator(offers);
    
    $(".dpl-calculator").fadeIn();
    
    drawCalculator();

    $('.dpl-calculator .help-kwh-usage').qtip({
       content: '<img class="calc-tooltip" src="/i/tip-kwh.jpg" />',
       show: 'mouseover',
       hide: 'mouseout',
       position: {
         corner: {
           target: 'rightMiddle',
           tooltip: 'leftMiddle'
         }
       },
       style: {
         tip: 'leftMiddle',
         padding: 0,
         width: 275
       }
    });

    $('.dpl-calculator .help-dpl-generation').qtip({
       content: '<img class="calc-tooltip" src="/i/tip-generation.jpg" />',
       show: 'mouseover',
       hide: 'mouseout',
       position: {
         corner: {
           target: 'rightMiddle',
           tooltip: 'leftMiddle'
         }
       },
       style: {
         tip: 'leftMiddle',
         padding: 0,
         width: 275
       }
    });

    $('.dpl-calculator .help-dpl-transmission').qtip({
       content: '<img class="calc-tooltip" src="/i/tip-transmission.jpg" />',
       show: 'mouseover',
       hide: 'mouseout',
       position: {
         corner: {
           target: 'rightMiddle',
           tooltip: 'leftMiddle'
         }
       },
       style: {
         tip: 'leftMiddle',
         padding: 0,
         width: 275
       }
    });

  }

});


function clickCalculate(e) {

  // loop through all the selects in the visible offers section
  $(".offers:visible select").each(function() {
    var theEntryID;

    // if there's only 1 option, clone to work around jquery bug
    //   val() doesn't work on display:none selects
    if ($(this).find("option").length == 1) {
      theEntryID = stripFront($(this).clone().val());
    } else {
      theEntryID = stripFront($(this).val());
    }

    // get the index of this offer
    var offerIndex = getOfferIndexFromID(theEntryID);
    
    if (offers[offerIndex].offer_type == "Percentage Discount") {
      calc_percDiscount(offerIndex, $(this).attr("title"));
    }
    
    if (offers[offerIndex].offer_type == "Per kWh Discount") {
      calc_kwhDiscount(offerIndex, $(this).attr("title"));
    }
    
    // check to see which savings were better and add "best" class
  });
}


function calc_percDiscount(offerIndex, resultsClass) {
  var percentageOff = parseFloat(offers[offerIndex].percentage_discount);
  var additionalFee = parseFloat(offers[offerIndex].additional_fee);
  var kwhUse = $(".data-kwh-usage:visible").asNumber();
  var dplGen = $(".data-dpl-generation:visible").asNumber();
  var dplTra = $(".data-dpl-transmission:visible").asNumber();

  var savingsGeneration   = dplGen * percentageOff;
  var savingsTransmission = dplTra * percentageOff;
  var savingsTotal        = (savingsGeneration + savingsTransmission) - additionalFee;
  
  var newGen = dplGen - savingsGeneration;
  var newTra = dplTra - savingsTransmission;
  var newkWh = parseFloat((newGen + newTra + additionalFee) / kwhUse) * 100;
  if (isNaN(newkWh)) { newkWh = 0; }

  if ($(".savings-dpl-generation:visible").length) {
    $(".savings-dpl-generation:visible").text(-savingsGeneration);
    $(".savings-dpl-generation:visible").formatCurrency({negativeFormat: "-%s%n"});
  }

  if ($(".savings-dpl-transmission:visible").length) {
    $(".savings-dpl-transmission:visible").text(-savingsTransmission);
    $(".savings-dpl-transmission:visible").formatCurrency({negativeFormat: "-%s%n"});
  }

  $("." + resultsClass + " .you-save:visible em").text(savingsTotal);
  $("." + resultsClass + " .you-save:visible em").formatCurrency({negativeFormat: "-%s%n"});
  
  $("." + resultsClass + " .equal-to:visible").html("(equal to <strong>" + newkWh.toFixed(2) + "</strong> cents per kWh)");
}


function calc_kwhDiscount(offerIndex, resultsClass) {
  var newkWh = parseFloat(offers[offerIndex].fixed_price_discount / 100);
  var additionalFee = parseFloat(offers[offerIndex].additional_fee);
  var kwhUse = $(".data-kwh-usage:visible").asNumber();
  var dplGen = $(".data-dpl-generation:visible").asNumber();
  var dplTra = $(".data-dpl-transmission:visible").asNumber();

  var originalCost        = dplGen + dplTra;
  var newCost             = (kwhUse * newkWh) + additionalFee;
  
  if (originalCost == 0) {
    var percentageOff    = 0;
  } else {
    var percentageOff    = 1 - (newCost / originalCost);
  }
  
  var savingsGeneration   = dplGen * percentageOff;
  var savingsTransmission = dplTra * percentageOff;
  var savingsTotal        = savingsGeneration + savingsTransmission;
  
  var newGen = dplGen - savingsGeneration;
  var newTra = dplTra - savingsTransmission;

  if ($(".savings-dpl-generation:visible").length) {
    $(".savings-dpl-generation:visible").text(-savingsGeneration);
    $(".savings-dpl-generation:visible").formatCurrency({negativeFormat: "-%s%n"});
  }

  if ($(".savings-dpl-transmission:visible").length) {
    $(".savings-dpl-transmission:visible").text(-savingsTransmission);
    $(".savings-dpl-transmission:visible").formatCurrency({negativeFormat: "-%s%n"});
  }

  $("." + resultsClass + " .you-save:visible em").text(savingsTotal);
  $("." + resultsClass + " .you-save:visible em").formatCurrency({negativeFormat: "-%s%n"});
  
  $("." + resultsClass + " .equal-to:visible").html("(equal to <strong>" + parseInt(percentageOff * 100) + "%</strong> discount)");
}



// return the index in the offers array for the given entry id
function getOfferIndexFromID(offerID) {
  for (var i in offers) {
    if (offers[i].id == offerID) {
      return(i);
    }
  }
}


function getCurrOfferTitle() {
  var currOffer = $(".offer-select:visible").val();

  if (currOffer == undefined) {
    currOffer = safenize("offer " + $(".dpl-calculator .offers label:visible").text());
  }
  
  return currOffer;
}


function calcBlurInput(e) {
  $(this).toNumber();
  
  if (!$(this).hasClass("data-kwh-usage")) {
    $(this).formatCurrency();
  }

  if ($(this).val() == "") {
    if (!$(this).hasClass("data-kwh-usage")) {
      $(this).val("$0.00");
    } else {
      $(this).val("0");
    }
  }
  
  if ($(this).hasClass("data-kwh-usage")) {
    $(".data-kwh-usage").val($(this).val());
  }

  if ($(this).hasClass("data-dpl-generation")) {
    $(".data-dpl-generation").val($(this).val());
  }

  if ($(this).hasClass("data-dpl-transmission")) {
    $(".data-dpl-transmission").val($(this).val());
  }

  clickCalculate();
}


function drawCalculator() {

  // hide all the targets
  $(".target").hide();
  
  // show the currently selected target
  $(".target." + $("#target-select").val()).show();
  
  // show the compare nav item
  $(".nav-compare").show();

  // if it's business and there are less than 2 offers
  if (($("#target-select").val() == "business") && (window.cntBus < 2)) {
    // hide the campare nav item
    $(".nav-compare").hide().removeClass("current");

    // select the calculate nav item
    $(".nav-calculate").addClass("current");
  }

  // if it's residential and there are less than 2 offers
  if (($("#target-select").val() == "residential") && (window.cntRes < 2)) {
    // hide the compare nav item
    $(".nav-compare").hide().removeClass("current");
    
    // select the calculate nav item
    $(".nav-calculate").addClass("current");
  }
  
  // hide all the descriptions
  $(".description").hide();
  
  // show the currently selected target's currently selected offer's description
  $("." + $("#target-select").val() + " .description." + $("." + $("#target-select").val() + " .offer-select").val()).show();
  
  // hide all forms
  $(".form").hide();
  
  // show the current form
  $(".form." + $(".calc-function li.current").text().toLowerCase()).show();

  $(".dpl-calculator input:visible").trigger("blur");

  clickCalculate();
}

function clickCalcFunction(e) {
  // remove the current class from the calc-function tabs
  $(".calc-function li").removeClass("current");

  // add the current class to the one they just clicked
  $(this).addClass("current");
  
  // re-draw the calculator
  drawCalculator();
}


// converts a string into string safe to use as a class name
function safenize(theString) {
  if (theString) {
    return(theString.toLowerCase().split(' ').join('-'));
  }
}

function stripFront(theString) {
  return(theString.split('-')[1]);
}


// builds out the calculator DOM
function buildCalculator(theJSON) {

  // remove extra stuff from the DOM
  $(".offer-select option").remove();
  $(".calculate .description").remove();

  // loop through the JSON offers (from EE)
  for(i in theJSON) {
    // build the select option for this offer
    var theOption = '<option class="offer-' + safenize(theJSON[i].title) + '" value="offer-' + safenize(theJSON[i].id) + '">' + theJSON[i].title + '</option>';

    // build the description for this offer
    var theDescription = '<p class="description offer-' + safenize(theJSON[i].id) + '">' + theJSON[i].description + '</p>';

    // put the option in the DOM
    $("." + safenize(theJSON[i].offer_target) + " .offer-select").append(theOption);
    
    // if it's the second select, select the second option
    $("." + safenize(theJSON[i].offer_target) + " .offer-select-2 option:selected").removeAttr('selected').next('option').attr('selected', 'selected');

    // put the description in the DOM
    $("." + safenize(theJSON[i].offer_target) + " .calculate .offers").append(theDescription);

    // increment the counters
    if (safenize(theJSON[i].offer_target) == 'residential') { window.cntRes++; }
    if (safenize(theJSON[i].offer_target) == 'business') { window.cntBus++; }
  }

  // make some adjustments to the DOM based on the counters
  if (window.cntRes < 1) {
    $(".dpl-calculator .residential .form").remove();
    $(".dpl-calculator .residential").append("<p class='calc-message'>No residential offers at this time.");
  }
  if (window.cntBus < 1) {
    $(".dpl-calculator .business .form").remove();
    $(".dpl-calculator .business").append("<p class='calc-message'>No business offers at this time.");
  }
  if (window.cntRes == 1) {
    $(".residential .calculate .offers label").text($("#offer-select-residential option").first().text());
    $("#offer-select-residential").hide();
  }
  if (window.cntBus == 1) {
    $(".business .calculate .offers label").text($("#offer-select-business option").first().text());
    $("#offer-select-business").hide();
  }

}


