var base_url_graphics07 = '/site/graphics07/';
var initial_products = [];

function CartItem(defaults) {
  this.cart_id = (defaults.cart_id ? defaults.cart_id : null);
  this.category = (defaults.category ? defaults.category : 'Custom');
  this.product_id = defaults.product_id;
  this.item_name = defaults.item_name;
  this.tons = parseFloat(defaults.tons);
  this.tons = this.tons.toFixed(2);
  // standard, but with a few exceptions
  this.cost_per_ton = (defaults.cost_per_ton ? defaults.cost_per_ton : 10.00);
  // calculate automatically unless explicitly told otherwise (round to 2 decimal places)
  this.cost = (defaults.cost ? defaults.cost : Math.round(parseFloat(defaults.tons) * this.cost_per_ton * 100) / 100);
  this.cost = this.cost.toFixed(2);
  this.deleted = false;
}

function setCalculator(pageID) {
  var page = panes[pageID];

  if ($('#frame' + page.name).html() === '') {
    $('#frame' + page.name).load('/calculators/' + page.url, function() {
      if (page.calc) {
        page.calc.init();
      }
    });
  }
  
  $('.calcFrame').hide();
  $('#frame' + page.name).show();
  
  Calc.currentTab = pageID;
  setNavPanes();
}

function setPreset(divID, itemID) {
  var item = panes[divID].presets[itemID];
  Calc.addToCart(item);
  
  return false;
}

function setNavPanes() {
  $.each(panes, function(i, item) {
    if ((item.name == Calc.currentTab) || (item.num_items > 0)) {
      $(item.nav).addClass('active');
    } else {
      $(item.nav).removeClass('active');
    }
  });
}

function setDonationQty() {
  var donationValue = parseFloat($("#donation-Price").val());
  if (donationValue > 0) { $("#donation-Qty").val('1'); }
  else if (donationValue == 0) {$("#donation-Qty").val('0'); }
}

function makeSelectOptionsHTML(opts) {
  var s = '';
  for (var i = 0; i < opts.length; i++) {
    s += '<option value="' + opts[i].value + '">' + opts[i].name + '</option>';
  }
  return s;
}

function addCommas(nStr) {
  nStr += '';
  var x = nStr.split('.');
  var x1 = x[0];
  var x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function round2d(n) {
  var tem = new String(Math.round(100*n)/100);
  var pos = tem.lastIndexOf(".");
  if (pos >= 0) {
    var tem1 = tem.substring(0, pos);
    var tem2 = tem.substring(pos+1, tem.length);
    if (tem2.length == 0) {
      tem2 = "00";
    }
    else if (tem2.length == 1) {
      tem2  += "0";
    }
    tem = tem1 + "." + tem2;
  } else {
    tem = tem + ".00";
  }
  return(tem);
}

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);
}

// convert degrees to radians
Number.prototype.toRad = function() {
  return this * Math.PI / 180;
};


$(document).ready(function() {
  var hostname = window.location.hostname;
  switch(hostname) {
    case 'carbonfund.org':
    case 'www.carbonfund.org':
      base_url_graphics07 = 'http://static.carbonfund.org/graphics07/';
      break;
    default:
      base_url_graphics07 = '/site/graphics07/';
  }
  
  // grab the initial zip if we have it
  var qs = new Querystring();
  calcOffice.initial_zip_code = qs.get("zip_code", "");
  if (initial_options['zip_code'] != '') {
    calcOffice.initial_zip_code = initial_options['zip_code'];
  }
  
  $.each(initial_products, function(i, item) {
    Calc.cart.push(item);
  });
  Calc.displayCart();
  
  // check hash and "ucfirst" it
  var hash = window.location.hash.substring(1);
  if (initial_options['hash'] != '') {
    hash = initial_options['hash'];
  }
  hash = hash.toLowerCase();
  if (hash.length > 0) {
    hash = hash.charAt(0).toUpperCase() + hash.substr(1);
  }
  switch(hash) {
    case 'Office':
    case 'Fleet':
    case 'Travel':
    case 'Commute':
    case 'Events':
    case 'Paper':
    case 'Shipping':
    case 'Small':
    case 'Final':
      setCalculator(hash);
      break;
    default:
      setCalculator('Office');
      break;
  }
  
  $('.biznav').click(function() {
    var href = $(this).children('A').attr('href');
    setCalculator(href.substring(1));
    return false;
  });
  
  // handler for submission form
  $('#frmShop').submit(function() {
    $.each(Calc.cart, function(i, item) {
      var productid = '<input type="hidden" name="atc[item_' + i + '][productid]" value="' + item.product_id + '" />';
      var el_amount = '<input type="hidden" name="atc[item_' + i + '][amount]" value="1" />';
      var el_price = '<input type="hidden" name="atc[item_' + i + '][price]" value="' + item.cost + '" />';
      var el_cart_id = '<input type="hidden" name="atc[item_' + i + '][cartid]" value="' + (item.cart_id === null ? '' : item.cart_id) + '" />';
      var el_deleted = '<input type="hidden" name="atc[item_' + i + '][deleted]" value="' + (item.deleted ? 1 : 0) + '" />';
      $('#items_to_submit').append(productid + el_amount + el_price + el_cart_id + el_deleted);
    });
    return true;
  });
});


var Calc = {
  cart: [],
  totalCO2: 0,
  totalCost: 0,
  currentTab: null,
  
  init: function() {
    $('#detailform').submit(function() { return false; }); // form for details doesn't actually DO anything
    this.displayCart();
  },
  
  addToCart: function(item) {
    // only "light up" the nav pane for non-zero items
    if (item.cost > 0) {
      panes[item.category].num_items++;
    }
    if (isNaN(item.tons)) {
      item.tons = '0.00';
    }
    this.cart.push(item);
    this.displayCart();
  },

  removeFromCart: function(idx) {
    if (this.cart[idx].cost > 0) {
      if (panes[this.cart[idx].category]) {
        panes[this.cart[idx].category].num_items--;
      }
    }
    if (this.cart[idx].cart_id) {
      this.cart[idx].deleted = true;
    } else {
      this.cart.splice(idx, 1);
    }
    this.displayCart();
  },

  displayCart: function() {
    var nTotalCO2 = 0.0;
    var nTotalCost = 0.0;

    $("#listResultsTbody").html('');

    for (i = 0; i < this.cart.length; i++) {
      var newRow = document.createElement("tr");
      newRow.id = "cart_row_" + i;

      var ItemCell = document.createElement("td");
      ItemCell.className="categoryResultDiv";         
      var CO2Cell = document.createElement("td");          
      CO2Cell.className="categoryResultDiv";
      CO2Cell.style.textAlign = "right";
      var CostCell = document.createElement("td");
      CostCell.className="categoryResultDiv";
      CostCell.style.textAlign = "right";
      var RemoveCell = document.createElement("td");
      RemoveCell.className="categoryResultDiv";
      RemoveCell.style.textAlign = "right";

      if(this.cart[i].item_name.length > 25) {
         ItemCell.innerHTML = this.cart[i].item_name.substring(0, 25) + "...";
      } else {
         ItemCell.innerHTML = this.cart[i].item_name;
      }
      CO2Cell.innerHTML = this.cart[i].tons;
      CostCell.innerHTML = formatCurrency(this.cart[i].cost);
      RemoveCell.innerHTML = "<img src=\"" + base_url_graphics07 + "trashcan.jpg\" class=\"cBtns\" alt=\"X\" onclick=\"Calc.removeFromCart(" + i + ")\" />";

      newRow.appendChild(ItemCell);
      newRow.appendChild(CO2Cell);
      newRow.appendChild(CostCell);
      newRow.appendChild(RemoveCell);

      if (! this.cart[i].deleted) {
        $("#listResultsTbody").append(newRow);
        nTotalCost += parseFloat(this.cart[i].cost);
        nTotalCO2 += parseFloat(this.cart[i].tons);
      }
    }
    
    $('#hideList').show();
    $('#chooserDiv').show();
    
    $('#grandTotalCellPrice').html('<strong>' + formatCurrency(nTotalCost) + '</strong>');
    $('#grandTotalCellCO2').html('<strong>' + round2d(nTotalCO2.toFixed(2)) + '</strong>');
    
    this.totalCO2 = nTotalCO2;
    this.totalCost = nTotalCost;
    
    showEquiv();
    setNavPanes();
    checkCarbonFreePartner();
  }

};


/* Office */

var calcOffice = {
  dom_prefix: '#calc_office',
  totalCO2: null,
  totalPrice: null,
  custom_product_id: 16216,
  
  initial_zip_code: '',
  
  init: function() {
    $(calcOffice.dom_prefix + ' .howSite').click(calcOffice.changeSiteHow);
    $(calcOffice.dom_prefix + ' .locationServers').click(calcOffice.changeServers);
    
    $(calcOffice.dom_prefix + ' INPUT[type=text]').change(calcOffice.calcForm).keyup(calcOffice.calcForm);
    $(calcOffice.dom_prefix + ' INPUT[type=radio]').change(calcOffice.calcForm);
    $(calcOffice.dom_prefix + ' SELECT').change(calcOffice.calcForm).keyup(calcOffice.calcForm);
    $(calcOffice.dom_prefix + ' .add').click(calcOffice.addToCart);
    
    calcOffice.resetForm();
  },

  changeSiteHow: function() {
    var sel = $('#howDiv_' + $('.howSite:checked').val());
    $('.howDiv').not(sel).hide();
    sel.show();
  },
  
  changeServers: function() {
    var val = $('.locationServers:checked').val();
    if (val == 'onsite') {
      $('#serversDiv').show();
    } else {
      $('#serversDiv').hide();
    }
  },
  
  resetForm: function() {
    $(calcOffice.dom_prefix + ' INPUT[TYPE=text]').val("");
    $(calcOffice.dom_prefix + ' INPUT[TYPE=radio]').attr("checked", "");
    $(calcOffice.dom_prefix + ' INPUT[TYPE=checkbox]').attr("checked", "");
    $(calcOffice.dom_prefix + ' .howDiv').hide();
    $(calcOffice.dom_prefix + ' #serversDiv').hide();
    $(calcOffice.dom_prefix + ' #tonsCO2Site').html("0.00");
    $(calcOffice.dom_prefix + ' #totalSite').html("$0.00");
    
    $(calcOffice.dom_prefix + ' #stateZipSite').val(calcOffice.initial_zip_code);
    
    return false;
  },
  
  calcForm: function () {
    var data = {"stateZipSite":   $('#stateZipSite').val(),
                "businessNameSite":   $('#businessNameSite').val(),
                "howSite":   $('.howSite:checked').val(),
                "siteTimeMult": $('#siteTimeMult').val(),
                "naturalGasBSite":   $('#naturalGasBSite').val(),
                "naturalGasUSite":   $('#naturalGasUSite').val(),
                "electricityBSite":   $('#electricityBSite').val(),
                "electricityUSite":   $('#electricityUSite').val(),
                "oilBSite":   $('#oilBSite').val(),
                "oilUSite":   $('#oilUSite').val(),
                "propaneBSite":   $('#propaneBSite').val(),
                "propaneUSite":   $('#propaneUSite').val(),
                "employeesSite":   $('#employeesSite').val(),
                "buildingTypeSite":   $('#buildingTypeSite').val(),
                "businessSqFtSite":   $('#businessSqFtSite').val(),
                "numberServers":   $('#numberServers').val(),
                "locationServers":   $('.locationServers:checked').val()
              };

    $.get('/calculators/aj_business-office.php', data, function(resp) {
      if (resp.status == 'OK') {
        $('#errorsDivSite').hide();
        
        calcOffice.totalCO2 = resp.co2;
        calcOffice.totalPrice = resp.price;
        
        $('#tonsCO2Site').html(round2d(calcOffice.totalCO2));
        $('#totalSite').html(formatCurrency(calcOffice.totalPrice));
      } else {
        $('#errorsDivSite').html('<strong>' + resp.msg + '</strong>');
        $('#errorsDivSite').show();
      }
    }, 'json');
    
    return true;
  },
  
  addToCart: function() {
    var new_item = new CartItem({
      category: 'Office',
      product_id: calcOffice.custom_product_id,
      item_name: 'Office - ' + $('#businessNameSite').val(),
      tons: calcOffice.totalCO2,
      cost: calcOffice.totalPrice
    });
    Calc.addToCart(new_item);
    
    setCalculator('Fleet');
    calcOffice.resetForm();
    
    return false;
  }

};


/* Fleet */

var calcFleet = {
  dom_prefix: '#calc_fleet',
  totalCO2: null,
  totalPrice: null,
  custom_product_id: 16217,
  
  init: function() {
    $(calcFleet.dom_prefix + ' INPUT').change(calcFleet.calcForm).keyup(calcFleet.calcForm);
    $(calcFleet.dom_prefix + ' .add').click(calcFleet.addToCart);
  },

  resetForm: function() {
    $(calcFleet.dom_prefix + ' INPUT[TYPE=text]').val("");
    
    $(calcOffice.dom_prefix + ' #tonsCO2Fleet').html("0.00");
    $(calcOffice.dom_prefix + ' #totalFleet').html("$0.00");
    
    $(calcFleet.dom_prefix + ' #errorsDivFleet').hide();
    
    return false;
  },
  
  calcForm: function () {
    var data = {"carsFleet":   $('#carsFleet').val(),
                "carsMilesFleet":   $('#carsMilesFleet').val(),
                "greenCarsFleet":   $('#greenCarsFleet').val(),
                "greenCarsMilesFleet":   $('#greenCarsMilesFleet').val(),
                "vanstrucksFleet":   $('#vanstrucksFleet').val(),
                "vanstrucksMilesFleet":   $('#vanstrucksMilesFleet').val(),
                "bigrigsFleet":   $('#bigrigsFleet').val(),
                "bigrigsMilesFleet":   $('#bigrigsMilesFleet').val()
              };

    $.get('/calculators/aj_business-fleet.php', data, function(resp) {
      if (resp.status == 'OK') {
        $('#errorsDivFleet').hide();
        
        calcFleet.totalCO2 = resp.co2;
        calcFleet.totalPrice = resp.price;
        
        $('#tonsCO2Fleet').html(round2d(calcFleet.totalCO2));
        $('#totalFleet').html(formatCurrency(calcFleet.totalPrice));
      } else {
        $('#errorsDivFleet').html('<strong>' + resp.msg + '</strong>');
        $('#errorsDivFleet').show();
      }
    }, 'json');
    
    return true;
  },
  
  addToCart: function() {
    var new_item = new CartItem({
      category: 'Fleet',
      product_id: calcFleet.custom_product_id,
      item_name: 'Fleet',
      tons: calcFleet.totalCO2,
      cost: calcFleet.totalPrice
    });
    Calc.addToCart(new_item);
    
    setCalculator('Travel');
    calcFleet.resetForm();
    
    return false;
  }

};


/* Travel */

var calcTravel = {
  dom_prefix: '#calc_travel',
  totalCO2: null,
  totalPrice: null,
  custom_product_id: 16218,
  
  init: function() {
    $(calcTravel.dom_prefix + ' INPUT').change(calcTravel.calcForm).keyup(calcTravel.calcForm);
    $(calcTravel.dom_prefix + ' .add').click(calcTravel.addToCart);
    
    calcTravel.resetForm();
    
    $(calcTravel.dom_prefix + ' .secHeadToggle').click(function() {
      $(this).nextAll('DIV.secToggle:first').toggle();
      $(this).toggleClass('open');
    });
  },

  resetForm: function() {
    $(calcTravel.dom_prefix + ' INPUT').val("0");
    $(calcTravel.dom_prefix + ' #errorsDivTravel').hide();
    
    $(calcOffice.dom_prefix + ' #tonsCO2Travel').html("0.00");
    $(calcOffice.dom_prefix + ' #totalTravel').html("$0.00");
    
    return false;
  },
  
  calcForm: function () {
    var data = {"shortFlightTravel":   $('#shortFlightTravel').val(),
                "mediumFlightTravel":   $('#mediumFlightTravel').val(),
                "longFlightTravel":   $('#longFlightTravel').val(),
                "trainTravel":   $('#trainTravel').val(),
                "busTravel":   $('#busTravel').val(),
                "hotelTravel":   $('#hotelTravel').val()
              };

    $.get('/calculators/aj_business-travel.php', data, function(resp) {
      if (resp.status == 'OK') {
        $('#errorsDivTravel').hide();
        
        calcTravel.totalCO2 = resp.co2;
        calcTravel.totalPrice = resp.price;
        
        $('#tonsCO2Travel').html(round2d(calcTravel.totalCO2));
        $('#totalTravel').html(formatCurrency(calcTravel.totalPrice));
      } else {
        $('#errorsDivTravel').html('<strong>' + resp.msg + '</strong>');
        $('#errorsDivTravel').show();
      }
    }, 'json');
    
    return true;
  },
  
  addToCart: function() {
    var new_item = new CartItem({
      category: 'Travel',
      product_id: calcTravel.custom_product_id,
      item_name: 'Travel',
      tons: calcTravel.totalCO2,
      cost: calcTravel.totalPrice
    });
    Calc.addToCart(new_item);
    
    setCalculator('Commute');
    calcTravel.resetForm();
    
    return false;
  }

};


/* Commute */

var calcCommute = {
  dom_prefix: '#calc_commute',
  totalCO2: null,
  totalPrice: null,
  custom_product_id: 16219,
  
  init: function() {
    $(calcCommute.dom_prefix + ' INPUT').change(calcCommute.calcForm).keyup(calcCommute.calcForm);
    $(calcCommute.dom_prefix + ' .add').click(calcCommute.addToCart);
    
    calcCommute.resetForm();
  },

  resetForm: function() {
    $(calcCommute.dom_prefix + ' INPUT').val("0");
    $(calcCommute.dom_prefix + ' #errorsDivCommute').hide();
    
    $('#tonsCO2Commute').html('0.00');
    $('#totalCommute').html('$0.00');
    
    return false;
  },
  
  calcForm: function () {
    var data = {"carsCommute":   $('#carsCommute').val(),
                "carsMilesCommute":   $('#carsMilesCommute').val(),
                "transitCommute":   $('#transitCommute').val(),
                "transitMilesCommute":   $('#transitMilesCommute').val()
              };

    $.get('/calculators/aj_business-commute.php', data, function(resp) {
      if (resp.status == 'OK') {
        $('#errorsDivCommute').hide();
        
        calcCommute.totalCO2 = resp.co2;
        calcCommute.totalPrice = resp.price;
        
        $('#tonsCO2Commute').html(round2d(calcCommute.totalCO2));
        $('#totalCommute').html(formatCurrency(calcCommute.totalPrice));
      } else {
        $('#errorsDivCommute').html('<strong>' + resp.msg + '</strong>');
        $('#errorsDivCommute').show();
      }
    }, 'json');
    
    return true;
  },
  
  addToCart: function() {
    var new_item = new CartItem({
      category: 'Commute',
      product_id: calcCommute.custom_product_id,
      item_name: 'Employee Commute',
      tons: calcCommute.totalCO2,
      cost: calcCommute.totalPrice
    });
    Calc.addToCart(new_item);
    
    setCalculator('Events');
    calcCommute.resetForm();
    
    return false;
  }

};


/* Events */

var calcEvents = {
  dom_prefix: '#calc_events',
  totalCO2: null,
  totalPrice: null,
  custom_product_id: 16220,
  
  init: function() {
    $(calcEvents.dom_prefix + ' INPUT').change(calcEvents.calcForm).keyup(calcEvents.calcForm);
    $(calcEvents.dom_prefix + ' .add').click(calcEvents.addToCart);

    calcEvents.resetForm();
    
    $(calcEvents.dom_prefix + ' .secHeadToggle').click(function() {
      $(this).nextAll('DIV.secToggle:first').toggle();
      $(this).toggleClass('open');
    });
    
    $(calcEvents.dom_prefix + ' .singleMultiple').click(function() {
      var sel = $('.singleMultiple:checked').val();
      $('#eventsDiv_' + sel).show();
      $('.eventsDiv').not('#eventsDiv_' + sel).hide();
      $('#eventsDetails').show();
    });
    
    tb_init('a.thickbox');
  },

  resetForm: function() {
    $(calcEvents.dom_prefix + ' INPUT[TYPE=text]').val("");
    $(calcEvents.dom_prefix + ' INPUT[TYPE=radio]').attr("checked", "");
    $(calcEvents.dom_prefix + ' INPUT[TYPE=checkbox]').attr("checked", "");
    $(calcEvents.dom_prefix + ' .eventsDiv').hide();
    $(calcEvents.dom_prefix + ' #eventsDetails').hide();
    $(calcEvents.dom_prefix + ' #errorsDivEvents').hide();
    
    $('#tonsCO2Events').html('0.00');
    $('#totalEvents').html('$0.00');
    
    return false;
  },
  
  calcForm: function () {
    var data = {"singleMultiple":   $('.singleMultiple:checked').val(),
                "eventName":   $('#eventName').val(),
                "numberEvents":   $('#numberEvents').val(),
                "numberDaysEvents":   $('#numberDaysEvents').val(),
                "numberAttendeesEvents":   $('#numberAttendeesEvents').val(),
                "carsEvents":   $('#carsEvents').val(),
                "carsMilesEvents":   $('#carsMilesEvents').val(),
                "flights1Events":   $('#flights1Events').val(),
                "flights2Events":   $('#flights2Events').val(),
                "flights3Events":   $('#flights3Events').val(),
                "flights4Events":   $('#flights4Events').val(),
                "flights5Events":   $('#flights5Events').val(),
                "flights6Events":   $('#flights6Events').val(),
                "trainEvents":   $('#trainEvents').val(),
                "trainMilesEvents":   $('#trainMilesEvents').val(),
                "transitEvents":   $('#transitEvents').val(),
                "transitMilesEvents":   $('#transitMilesEvents').val(),
                "mealsEvents":   $('#mealsEvents').val(),
                "hotelEvents":   $('#hotelEvents').val(),
                "upscaleEvents":   $('#upscaleEvents:checked').length
              };

    $.get('/calculators/aj_business-events.php', data, function(resp) {
      if (resp.status == 'OK') {
        $('#errorsDivEvents').hide();
        
        calcEvents.totalCO2 = resp.co2;
        calcEvents.totalPrice = resp.price;
        
        $('#tonsCO2Events').html(round2d(calcEvents.totalCO2));
        $('#totalEvents').html(formatCurrency(calcEvents.totalPrice));
      } else {
        $('#errorsDivEvents').html('<strong>' + resp.msg + '</strong>');
        $('#errorsDivEvents').show();
      }
    }, 'json');
    
    return true;
  },
  
  addToCart: function() {
    var new_item = new CartItem({
      category: 'Events',
      product_id: calcEvents.custom_product_id,
      item_name: 'Events',
      tons: calcEvents.totalCO2,
      cost: calcEvents.totalPrice
    });
    Calc.addToCart(new_item);
    
    setCalculator('Paper');
    calcEvents.resetForm();
    
    return false;
  }

};


/* Paper */

var calcPaper = {
  dom_prefix: '#calc_paper',
  totalCO2: null,
  totalPrice: null,
  custom_product_id: 16221,
  
  init: function() {
    $(calcPaper.dom_prefix + ' INPUT').change(calcPaper.calcForm).keyup(calcPaper.calcForm);
    $(calcPaper.dom_prefix + ' SELECT').change(calcPaper.calcForm).keyup(calcPaper.calcForm);
    
    $(calcPaper.dom_prefix + ' .add').click(calcPaper.addToCart);

    calcPaper.resetForm();

    $(calcPaper.dom_prefix + ' .add_paper_type').click(function() {
      var new_el = $(calcPaper.dom_prefix + ' .paperDiv:last').clone(true);
      $(calcPaper.dom_prefix + ' .paperDiv:last').append('<hr /');
      new_el.insertAfter(calcPaper.dom_prefix + ' HR:last');
      
      $(calcPaper.dom_prefix + ' .paperDiv:last INPUT').val("");
      $(calcPaper.dom_prefix + ' .paperDiv:last SELECT').val(0);
      $(calcPaper.dom_prefix + ' .paperDiv:last INPUT').change(calcPaper.calcForm).keyup(calcPaper.calcForm);
      $(calcPaper.dom_prefix + ' .paperDiv:last SELECT').change(calcPaper.calcForm).keyup(calcPaper.calcForm);
      return false;
    });
  },

  resetForm: function() {
    $(calcPaper.dom_prefix + ' .paperType').val("1");
    $(calcPaper.dom_prefix + ' .paperRecycledContent').val("0");
    $(calcPaper.dom_prefix + ' .paperNumber').val("");
    $(calcPaper.dom_prefix + ' .paperDiv').not(calcPaper.dom_prefix + ' .paperDiv:first').remove();
    $(calcPaper.dom_prefix + ' .paperDiv HR').remove();

    $(calcPaper.dom_prefix + ' #errorsDivPaper').hide();
    
    $('#tonsCO2Paper').html('0.00');
    $('#totalPaper').html('$0.00');
    
    return false;
  },
  
  calcForm: function () {
    var rows = [];
    $(calcPaper.dom_prefix + ' .paperDiv').each(function(index, domElement) {
      rows.push( {"paperType": $(this).contents().find('.paperType').val(),
                  "paperRecycledContent": $(this).contents().find('.paperRecycledContent').val(),
                  "paperNumber": $(this).contents().find('.paperNumber').val()
                });
    });
    var data = { "paper_rows": JSON.stringify(rows) };

    $.get('/calculators/aj_business-paper.php', data, function(resp) {
      if (resp.status == 'OK') {
        $('#errorsDivPaper').hide();
        
        calcPaper.totalCO2 = resp.co2;
        calcPaper.totalPrice = resp.price;
        
        $('#tonsCO2Paper').html(round2d(calcPaper.totalCO2));
        $('#totalPaper').html(formatCurrency(calcPaper.totalPrice));
      } else {
        $('#errorsDivPaper').html('<strong>' + resp.msg + '</strong>');
        $('#errorsDivPaper').show();
      }
    }, 'json');
    
    return true;
  },
  
  addToCart: function() {
    var new_item = new CartItem({
      category: 'Paper',
      product_id: calcPaper.custom_product_id,
      item_name: 'Paper',
      tons: calcPaper.totalCO2,
      cost: calcPaper.totalPrice
    });
    Calc.addToCart(new_item);
    
    setCalculator('Shipping');
    calcPaper.resetForm();
    
    return false;
  }

};


/* Shipping */

var calcShipping = {
  dom_prefix: '#calc_shipping',
  totalCO2: null,
  totalPrice: null,
  custom_product_id: 16222,
  
  init: function() {
    $(calcShipping.dom_prefix + ' INPUT').change(calcShipping.calcForm).keyup(calcShipping.calcForm);
    $(calcShipping.dom_prefix + ' SELECT').change(calcShipping.calcForm).keyup(calcShipping.calcForm)
    $(calcShipping.dom_prefix + ' .add').click(calcShipping.addToCart);

    calcShipping.resetForm();
    
    $(calcShipping.dom_prefix + ' .add_shipping_type').click(function() {
      var new_el = $(calcShipping.dom_prefix + ' .shippingDiv:last').clone(true);
      $(calcShipping.dom_prefix + ' .shippingDiv:last').append('<hr /');
      new_el.insertAfter(calcShipping.dom_prefix + ' HR:last');

      $(calcShipping.dom_prefix + ' .shippingDiv:last INPUT').change(calcShipping.calcForm).keyup(calcShipping.calcForm);
      $(calcShipping.dom_prefix + ' .shippingDiv:last SELECT').change(calcShipping.calcForm).keyup(calcShipping.calcForm);
      $(calcShipping.dom_prefix + ' .shippingDiv:last INPUT').val("");
      $(calcShipping.dom_prefix + ' .shippingDiv:last SELECT').val(0);
      return false;
    });
  },

  resetForm: function() {
    $(calcShipping.dom_prefix + ' .shippingType').val("1");
    $(calcShipping.dom_prefix + ' .shippingNumber').val("");
    $(calcShipping.dom_prefix + ' .shippingLbs').val("");
    $(calcShipping.dom_prefix + ' .shippingMiles').val("");
    $(calcShipping.dom_prefix + ' .shippingDiv').not(calcShipping.dom_prefix + ' .shippingDiv:first').remove();
    $(calcShipping.dom_prefix + ' HR').remove();

    $('#tonsCO2Shipping').html('0.00');
    $('#totalShipping').html('$0.00');

    $(calcShipping.dom_prefix + ' #errorsDivShipping').hide();
    
    return false;
  },
  
  calcForm: function () {
    var rows = [];
    $(calcShipping.dom_prefix + ' .shippingDiv').each(function(index, domElement) {
      rows.push( {"shippingType": $(this).contents().find('.shippingType').val(),
                  "shippingNumber": $(this).contents().find('.shippingNumber').val(),
                  "shippingLbs": $(this).contents().find('.shippingLbs').val(),
                  "shippingMiles": $(this).contents().find('.shippingMiles').val()
                });
    });
    var data = { "shipping_rows": JSON.stringify(rows) };

    $.get('/calculators/aj_business-shipping.php', data, function(resp) {
      if (resp.status == 'OK') {
        $('#errorsDivShipping').hide();
        
        calcShipping.totalCO2 = resp.co2;
        calcShipping.totalPrice = resp.price;
        
        $('#tonsCO2Shipping').html(round2d(calcShipping.totalCO2));
        $('#totalShipping').html(formatCurrency(calcShipping.totalPrice));
      } else {
        $('#errorsDivShipping').html('<strong>' + resp.msg + '</strong>');
        $('#errorsDivShipping').show();
      }
    }, 'json');
    
    return true;
  },
  
  addToCart: function() {
    var new_item = new CartItem({
      category: 'Shipping',
      product_id: calcShipping.custom_product_id,
      item_name: 'Shipping',
      tons: calcShipping.totalCO2,
      cost: calcShipping.totalPrice
    });
    Calc.addToCart(new_item);
    
    setCalculator('Final');
    calcShipping.resetForm();
    
    return false;
  }

};


/* Final */

var calcFinal = {
  dom_prefix: '#calc_final',
  
  init: function() {
    // if they haven't completed one of the other calcs, go to that;
    // otherwise, show the finalize message
    var showfinal = true;
    // $.each(panes, function(i, item) {
    //   if ((item.name != 'Final') || (item.num_items == 0)) {
    //     setCalculator(item.name);
    //     showfinal = false;
    //     return false;
    //   }
    // });
    
    if (showfinal) {
      $('#customdonationDiv').show();
    }
  }

};


/* Small */

var calcSmall = {
  dom_prefix: '#calc_small',
  
  init: function() {
    $('#customdonationDiv').show();
  }

};


var panes = {
  'Office':
  { name: 'Office',
    nav: '#biznav1',
    url: 'business-office.php',
    height: 370,
    num_items: 0,
    calc: calcOffice
  },
  
  'Fleet':
  { name: 'Fleet',
    nav: '#biznav3',
    url: 'business-fleet.php',
    height: 370,
    num_items: 0,
    calc: calcFleet
  },
  
  'Travel':
  { name: 'Travel',
    nav: '#biznav4',
    url: 'business-travel.php',
    height: 370,
    num_items: 0,
    calc: calcTravel
  },
  
  'Commute':
  { name: 'Commute',
    nav: '#biznav5',
    url: 'business-commute.php',
    height: 370,
    num_items: 0,
    calc: calcCommute
  },
  
  'Events':
  { name: 'Events',
    nav: '#biznav6',
    url: 'business-events.php',
    height: 370,
    num_items: 0,
    calc: calcEvents
  },
  
  'Paper':
  { name: 'Paper',
    nav: '#biznav7',
    url: 'business-paper.php',
    height: 370,
    num_items: 0,
    calc: calcPaper
  },
  
  'Shipping':
  { name: 'Shipping',
    nav: '#biznav8',
    url: 'business-shipping.php',
    height: 370,
    num_items: 0,
    calc: calcShipping
  },
  
  'Small':
  { name: 'Small',
    nav: '#biznavsmall',
    url: 'business-small.php',
    height: 370,
    num_items: 0,
    presets: [new CartItem({category: 'Small', 'product_id': 16189, item_name: 'Small Business, 1-5 Employees', tons: 35, cost: 350}),
              new CartItem({category: 'Small', 'product_id': 16190, item_name: 'Small Business, 6-10 Employees', tons: 70, cost: 700}),
              new CartItem({category: 'Small', 'product_id': 16191, item_name: 'Small Business, 11-20 Employees', tons: 140, cost: 1400})
            ],
    calc: calcSmall
  },
  
  'Final':
  { name: 'Final',
    nav: '#biznavfinal',
    url: 'business-final.php',
    height: 370,
    num_items: 0,
    calc: calcFinal
  }
};


var Equivalencies = [
  { 'text': 'the annual greenhouse gas emissions from XXXX passenger vehicles',
    'div': 5.5,
    'class': 'vehicles'
  },
  { 'text': 'the CO<sub>2</sub> emissions from XXXX gallons of gas consumed',
    'div': .0088,
    'class': 'gas'
  },
  { 'text': 'the CO<sub>2</sub> emissions from XXXX barrels of oil consumed',
    'div': .4265,
    'class': 'oil'
  },
  { 'text': 'the carbon sequestered annually by XXXX acres of pine forest',
    'div': 4.405,
    'class': 'pine'
  },
  { 'text': 'the carbon sequestered by XXXX seedlings growing for 10 years',
    'div': .039,
    'class': 'seedlings'
  },
  { 'text': 'the carbon emissions of XXXX propane cylinders',
    'div': .024,
    'class': 'propane'
  },
  { 'text': 'the energy use of XXXX homes for 1 year',
    'div': 10.99,
    'class': 'homes'
  },
  { 'text': 'the CO<sub>2</sub> offset by a 2 MW wind turbine spinning for XXXX hours',
    'div': .606 * 2,
    'class': 'turbines'
  }
];


function showEquiv() {
  if (Calc.totalCO2 == 0) {
    $('#equivalenciesContainer').hide();
    return;
  }
  
  var rnd = Math.floor(Math.random() * Equivalencies.length);
  var total_equiv = Calc.totalCO2 / Equivalencies[rnd]['div'];
  var h = '<strong>Your carbon footprint of ' + addCommas(Calc.totalCO2.toFixed(2)) + ' tons is equivalent to ' + Equivalencies[rnd]['text'].replace("XXXX", addCommas(total_equiv.toFixed(2))) + '</strong>';
  
  $('#equivalenciesText').html(h);
  $('#equivalenciesContainer').attr('class', Equivalencies[rnd]['class']).show();
}

function checkCarbonFreePartner() {
  if (Calc.totalCost >= 350) {
    $('#partnerOffDiv').hide();
    $('#partnerDiv').show();
  } else {
    $('#partnerDiv').hide();
    $('#partnerOffDiv').show();
  }
}


/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008
	
	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}
