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

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 renderPane(pane) {
  var target = '#panel' + pane.name;
  if ($.inArray(pane.name, calc_preset_panes_render) !== -1) {
    target = '#frame' + pane.name;
  }
  if ($(target).html() === '') {
    var lc = pane.name.toLowerCase();
    var s = '<div class="calcSubPanelA ' + pane.subPanelExtraClass + '">';
    s += '<div class="calcSubPanelB">';
    s += '<div class="calcSubPanelC"></div>';
    for (var j = 0; j < pane.presets.length; j++) {
      s+= '<div class="presetListing" style="left: 0px;">';
      s+= '<a href="#" class="indiv-preset-' + lc + (j+1) + '" onClick="setPreset(\'' + pane.name + '\', \'' + j + '\'); return false;"></a>';
      s+= '</div>';
    }
    s += '</div></div>';
    $(target).html(s);
  }
}

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

  if ($('#frame' + page.name).html() === '') {
    if ($.inArray(page.name, calc_preset_panes_render) !== -1) {
      $('#frame' + page.name).addClass('presetContainer');
    } else {
      $('#frame' + page.name).load('/calculators/' + page.url, function() {
        if (page.calc) {
          page.calc.init();
        }
      });
    }
  }
  $('#main_frame').height(page.height);
  
  $('.calcFrame').hide();
  $('#frame' + page.name).show();
  
  $('.calcPanel').hide();
  renderPane(page);
  $('#panel' + page.name).show();

  $('#step2Div').css('visibility', 'visible');
  $('#tagImage2').html('<img src="' + base_url_graphics07 + page.image2 + '">');
  
  Calc.currentTab = pageID;
  setNavPanes();
}

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

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/';
  }
  
  var calc_preset_panes = ($('#calc_preset_panes').length ? $('#calc_preset_panes').val() : '');
  calc_preset_panes_render = calc_preset_panes.split(',');
  
  // grab the initial zip if we have it
  var qs = new Querystring();
  calcHome.initial_zip_code = qs.get("zip_code", "");
  if (initial_options['zip_code'] != '') {
    calcHome.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 'Home':
    case 'Car':
    case 'Flight':
    case 'Trainbus':
    case 'Zero':
    case 'Gift':
    case 'Events':
      setCalculator(hash);
      break;
    default:
      break;
  }
  
  // handler for button sprites
  $('.indivcalc-buttons A').click(function() {
    var href = $(this).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) {
    if (item.cost > 0 && typeof panes[item.category] != 'undefined') {
      panes[item.category].num_items++;
    }
    if (isNaN(item.tons)) {
      item.tons = '0.00';
    }
    this.cart.push(item);
    this.displayCart();
    
    // advance to the next calculator
    if (typeof panes[item.category] != 'undefined') {
      setCalculator(panes[item.category].nextCalc);
    }
  },

  removeFromCart: function(idx) {
    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;
    
    setNavPanes();
  }

};




/* Home */

var calcHome = {
  dom_prefix: '#calc_home',
  indvCost: null, // individual cost per year
  cartPrice: null, // price for shopping cart form
  num_people_old: 1,
  custom_product_id: 16223,
  
  initial_zip_code: '',
  electricityRegionalCO2PerKWHDefault: 1.336, // default CO2 per KWH
  electricityRegionalCO2PerKWH: 1.336, // default CO2 per KWH
  
  init: function() {
    calcHome.calcForm();
    
    $(calcHome.dom_prefix + ' .reset').click(calcHome.resetForm);
    $(calcHome.dom_prefix + ' .addToCart').click(calcHome.addToCart);
    
    $(calcHome.dom_prefix + ' .num_people .selecttext').focus(calcHome.oldNumPersons);
    $(calcHome.dom_prefix + ' .num_people .selecttext').change(calcHome.multForm).keyup(calcHome.multForm);

    $(calcHome.dom_prefix + ' .zip_code .selecttext').change(calcHome.getRegionalFactors).keyup(calcHome.getRegionalFactors);
    
    $(calcHome.dom_prefix + ' .electricity .selecttext').change(calcHome.calcForm).keyup(calcHome.calcForm);
    $(calcHome.dom_prefix + ' .gas .selecttext').change(calcHome.calcForm).keyup(calcHome.calcForm);
    $(calcHome.dom_prefix + ' .oil .selecttext').change(calcHome.calcForm).keyup(calcHome.calcForm);
    
    $(calcHome.dom_prefix + ' .num_people .selecttext').focus();
    
    calcHome.resetForm();
  },
  
  resetForm: function() {
    $(calcHome.dom_prefix + ' .num_people .selecttext').val(1);
    $(calcHome.dom_prefix + ' .zip_code .selecttext').val(calcHome.initial_zip_code);
    $(calcHome.dom_prefix + ' .electricity .selecttext').val(4401);
    $(calcHome.dom_prefix + ' .oil .selecttext').val(0);
    $(calcHome.dom_prefix + ' .gas .selecttext').val(311);
    $(calcHome.dom_prefix + ' .lpg .selecttext').val(0);
    $(calcHome.dom_prefix + ' .co2_py .selecttextTotal').val("");
    $(calcHome.dom_prefix + ' .dol_py .selecttextTotal').val("");
    $(calcHome.dom_prefix + ' .z_co2 .selecttext').val("");
    $(calcHome.dom_prefix + ' .z_py .selecttext').val("");
    
    calcHome.electricityRegionalCO2PerKWH = calcHome.electricityRegionalCO2PerKWHDefault;
    calcHome.getRegionalFactors();
    return false;
  },
  
  getRegionalFactors: function() {
    var zip_code = $(calcHome.dom_prefix + ' .zip_code .selecttext').val();
    
    if (zip_code.length >= 5) {
      var data = { "zip_code": zip_code };
      $.get('/calculators/aj_individual-home.php', data, function(resp) {
        if (resp.status == 'OK') {
          calcHome.electricityRegionalCO2PerKWH = resp.electricityRegionalCO2PerKWH;
          calcHome.calcForm();
        }
      }, 'json');
    }
    
    return true;
  },
  
  calcForm: function () {
    var el_mul, gas_mul, oil_mul, ton_mul, co2_tpy, persons, energy;
    
    el_mul = calcHome.electricityRegionalCO2PerKWH / 2204.6;        // 1.336/2204.6 (lbs per KWH / lbs per ton)
    gas_mul = 0.0054700626;    // 120.593/2204.6 (lbs per 1000 cf / lbs per ton) * 100 cf/therm (so really /10)
    oil_mul = 0.0101533158;   // 22.384/2204.6 (lbs per gal / lbs in ton)
    ton_mul = 10.0;

    $(calcHome.dom_prefix + " .co2_py .selecttextTotal").html("");
    $(calcHome.dom_prefix + " .dol_py .selecttextTotal").html("");

    persons = parseFloat($(calcHome.dom_prefix + " .num_people .selecttext").val());

    var el = ($(calcHome.dom_prefix + " .electricity .selecttext").val() > 0) ? parseFloat($(calcHome.dom_prefix + " .electricity .selecttext").val()) : 0;
    var gas = ($(calcHome.dom_prefix + " .gas .selecttext").val() > 0) ? parseFloat($(calcHome.dom_prefix + " .gas .selecttext").val()) : 0;
    var oil = ($(calcHome.dom_prefix + " .oil .selecttext").val() > 0) ? parseFloat($(calcHome.dom_prefix + " .oil .selecttext").val()) : 0;
    
    energy = el*el_mul + gas*gas_mul + oil*oil_mul;
    co2_tpy = energy;
    
    $(calcHome.dom_prefix + " .co2_py .selecttextTotal").html(round2d(co2_tpy)); // individual CO2  per year
    $(calcHome.dom_prefix + " .dol_py .selecttextTotal").html('$' + round2d(co2_tpy * ton_mul)); // individual cost per year
    
    calcHome.indvCO2 = co2_tpy; // individual CO2  per year
    calcHome.indvCost = '$' + round2d(co2_tpy*ton_mul); // individual cost per year
    calcHome.cartPrice = round2d(co2_tpy*ton_mul); // price for shopping cart form
    
    return false;
  },
  
  oldNumPersons: function() {
    calcHome.num_people_old = parseFloat($(calcHome.dom_prefix + " .num_people .selecttext").val());
    if (isNaN(calcHome.num_people_old) || (calcHome.num_people_old <= 0)) {
      calcHome.num_people_old = 1;
    }
  },
  
  multForm: function() {
    var num_people = parseFloat($(calcHome.dom_prefix + " .num_people .selecttext").val());
    if (isNaN(num_people) || (num_people <= 0)) {
      num_people = 1;
    }

    var electricity_per_1 = $(calcHome.dom_prefix + " .electricity .selecttext").val() / calcHome.num_people_old;
    var oil_per_1 = $(calcHome.dom_prefix + " .oil .selecttext").val() / calcHome.num_people_old;
    var gas_per_1 = $(calcHome.dom_prefix + " .gas .selecttext").val() / calcHome.num_people_old;

    $(calcHome.dom_prefix + " .electricity .selecttext").val(electricity_per_1 * num_people);
    $(calcHome.dom_prefix + " .oil .selecttext").val(oil_per_1 * num_people);
    $(calcHome.dom_prefix + " .gas .selecttext").val(gas_per_1 * num_people);

    calcHome.oldNumPersons();
    calcHome.calcForm();
    
    return true;
  },
  
  addToCart: function() {
    var new_item = new CartItem({
      category: 'Home',
      product_id: calcHome.custom_product_id,
      item_name: 'Custom Home',
      tons: calcHome.indvCO2,
      price: calcHome.cartPrice
    });
    Calc.addToCart(new_item);
    
    return false;
  }

};


/* Car */

var calcCar = {
  dom_prefix: '#calc_car',
  mpg: null,
  mileage: null,
  co2: null,
  cost: null,
  custom_product_id: 16224,
  
  init: function() {
    $(calcCar.dom_prefix + ' .makeselect').attr('disabled', true);
    $(calcCar.dom_prefix + ' .modelselect').attr('disabled', true);
    $(calcCar.dom_prefix + ' .specselect').attr('disabled', true);
    $(calcCar.dom_prefix + ' .mileageselect').attr('disabled', true);
    
    $(calcCar.dom_prefix + ' .yearselect').change(calcCar.yearChange);
    $(calcCar.dom_prefix + ' .makeselect').change(calcCar.makeChange);
    $(calcCar.dom_prefix + ' .modelselect').change(calcCar.modelChange);
    $(calcCar.dom_prefix + ' .specselect').change(calcCar.specChange);
    $(calcCar.dom_prefix + ' .mileageselect').change(calcCar.mileageChange);
    
    $(calcCar.dom_prefix + ' .addcar').click(calcCar.addToCart);
    
    $(calcCar.dom_prefix + ' .yearselect').focus();
  },
  
  yearChange: function() {
    calcCar.clearTotals();
    var year = $(calcCar.dom_prefix + ' .yearselect').val();

    $(calcCar.dom_prefix + ' .makeselect').val('');
    $(calcCar.dom_prefix + ' .modelselect').val('');
    $(calcCar.dom_prefix + ' .specselect').val('');

    $(calcCar.dom_prefix + ' .makeselect').attr('disabled', true);
    $(calcCar.dom_prefix + ' .modelselect').attr('disabled', true);
    $(calcCar.dom_prefix + ' .specselect').attr('disabled', true);
    $(calcCar.dom_prefix + ' .mileageselect').attr('disabled', true);

    if (year !== '') {
      $.getJSON('/calculators/aj_individual-car.php', {mode: 'make', year: year}, function(data) {
        $(calcCar.dom_prefix + ' .makeselect').html('<option value="">Choose a make...</option>' + makeSelectOptionsHTML(data));
        $(calcCar.dom_prefix + ' .makeselect').attr('disabled', false);
        $(calcCar.dom_prefix + ' .makeselect').focus();
      });
    }
    
    return false;
  },
  
  makeChange: function() {
    calcCar.clearTotals();
    var year = $(calcCar.dom_prefix + ' .yearselect').val();
    var make = $(calcCar.dom_prefix + ' .makeselect').val();

    $(calcCar.dom_prefix + ' .modelselect').val('');
    $(calcCar.dom_prefix + ' .specselect').val('');

    $(calcCar.dom_prefix + ' .modelselect').attr('disabled', true);
    $(calcCar.dom_prefix + ' .specselect').attr('disabled', true);
    $(calcCar.dom_prefix + ' .mileageselect').attr('disabled', true);

    if (year !== '') {
      $.getJSON('/calculators/aj_individual-car.php', {mode: 'model', year: year, make: make}, function(data) {
        $(calcCar.dom_prefix + ' .modelselect').html('<option value="">Choose a model...</option>' + makeSelectOptionsHTML(data));
        $(calcCar.dom_prefix + ' .modelselect').attr('disabled', false);
        $(calcCar.dom_prefix + ' .modelselect').focus();
      });
    }
  },
  
  modelChange: function() {
    calcCar.clearTotals();
    var year = $(calcCar.dom_prefix + ' .yearselect').val();
    var make = $(calcCar.dom_prefix + ' .makeselect').val();
    var model = $(calcCar.dom_prefix + ' .modelselect').val();

    $(calcCar.dom_prefix + ' .specselect').val('');

    $(calcCar.dom_prefix + ' .specselect').attr('disabled', true);
    $(calcCar.dom_prefix + ' .mileageselect').attr('disabled', true);

    if (year !== '') {
      $.getJSON('/calculators/aj_individual-car.php', {mode: 'spec', year: year, make: make, model: model}, function(data) {
        $(calcCar.dom_prefix + ' .specselect').html('<option value="">Choose a spec...</option>' + makeSelectOptionsHTML(data));
        $(calcCar.dom_prefix + ' .specselect').attr('disabled', false);
        $(calcCar.dom_prefix + ' .specselect').focus();
      });
    }
  },
  
  specChange: function() {
    calcCar.clearTotals();
    $(calcCar.dom_prefix + ' .mileageselect').attr('disabled', false);
    $(calcCar.dom_prefix + ' .mileageselect').focus();
    calcCar.calcForm();
  },
  
  mileageChange: function() {
    calcCar.calcForm();
  },
  
  clearTotals: function() {
    calcCar.mpg = null;
    calcCar.co2 = null;
    calcCar.cost = null;
    
    $(calcCar.dom_prefix + ' .mpg .selecttextTotal').html("0");
    $(calcCar.dom_prefix + ' .co2 .selecttextTotal').html("0.00");
    $(calcCar.dom_prefix + ' .cost .selecttextTotal').html("$0.00");
    
    return false;
  },
  
  calcForm: function () {
    if ($(calcCar.dom_prefix + " .yearselect").val() === '') {
      $(calcCar.dom_prefix + " .yearselect").focus();
      return false;
    }
    
    if ($(calcCar.dom_prefix + " .makeselect").val() === '') {
      $(calcCar.dom_prefix + " .makeselect").focus();
      return false;
    }
    
    if ($(calcCar.dom_prefix + " .modelselect").val() === '') {
      $(calcCar.dom_prefix + " .modelselect").focus();
      return false;
    }
    
    if ($(calcCar.dom_prefix + " .specselect").val() === '') {
      $(calcCar.dom_prefix + " .specselect").focus();
      return false;
    }
    
    calcCar.mpg = parseFloat($(calcCar.dom_prefix + " .specselect").val());
    calcCar.mileage = parseFloat($(calcCar.dom_prefix + " .mileageselect").val());
    calcCar.co2 = calcCar.mileage / calcCar.mpg * 0.00887;
    calcCar.cost = calcCar.co2 * 10.0;
    
    $(calcCar.dom_prefix + " .mpg .selecttextTotal").html(addCommas(calcCar.mpg));
    $(calcCar.dom_prefix + " .co2 .selecttextTotal").html(calcCar.co2.toFixed(2));
    $(calcCar.dom_prefix + " .cost .selecttextTotal").html('$' + calcCar.cost.toFixed(2));
    
    return false;
  },
  

  addToCart: function() {
    if (calcCar.mpg === null) {
      alert("Please complete vehicle selection");
      return false;
    }
    
    var new_item = new CartItem({
      category: 'Car',
      product_id: calcCar.custom_product_id,
      item_name: $(calcCar.dom_prefix + " .makeselect").val() + ' ' + $(calcCar.dom_prefix + " .modelselect").val(),
      tons: calcCar.co2,
      price: calcCar.cost
    });
    Calc.addToCart(new_item);
    
    return false;
  }

};


/* Flight */

var calcFlight = {
  dom_prefix: '#calc_flight',
  airport1: null,
  airport2: null,
  distance: null,
  co2: null,
  cost: null,
  custom_product_id: 16225,
  
  init: function() {
    tb_init('a.thickbox');
    
    $(calcFlight.dom_prefix + ' .airport .selecttext').attr('disabled', true);
    $(calcFlight.dom_prefix + ' .airport2 .selecttext').attr('disabled', true);
    
    $.get('/calculators/aj_individual-flight-airports.php', {}, function(resp) {
      $(calcFlight.dom_prefix + " .airport .selecttext").autocomplete(resp.airport_list, {width: 150, matchContains: true, scrollHeight: 250, mustMatch: true, selectFirst: false, formatResult: calcFlight.formatACResult});
      $(calcFlight.dom_prefix + " .airport2 .selecttext").autocomplete(resp.airport_list, {width: 150, matchContains: true, scrollHeight: 250, mustMatch: true, selectFirst: false, formatResult: calcFlight.formatACResult});
      
      $(calcFlight.dom_prefix + ' .airport .selecttext').attr('disabled', false);
      $(calcFlight.dom_prefix + ' .airport2 .selecttext').attr('disabled', false);
      
      $(calcFlight.dom_prefix + ' .airport .selecttext').focus();
    }, 'json');
    
    $(calcFlight.dom_prefix + ' .addflight').click(calcFlight.addToCart);
    $(calcFlight.dom_prefix + ' .reset').click(calcFlight.resetForm);
    
    $(calcFlight.dom_prefix + ' SELECT').change(calcFlight.airportChange).keyup(calcFlight.airportChange);
    $(calcFlight.dom_prefix + ' INPUT[type=checkbox]').click(calcFlight.airportChange);

    $(calcFlight.dom_prefix + ' .airport .selecttext').change(calcFlight.airportChange);
    $(calcFlight.dom_prefix + ' .airport2 .selecttext').change(calcFlight.airportChange);
    
    $(calcFlight.dom_prefix + ' .airport .selecttext').result(function(e, data, formatted) {
     calcFlight.airportChange(e);
    });
    $(calcFlight.dom_prefix + ' .airport2 .selecttext').result(function(e, data, formatted) {
     calcFlight.airportChange(e);
    });
    
  },
  
  resetForm: function() {
    $(calcFlight.dom_prefix + ' .selecttext').val("");
    $(calcFlight.dom_prefix + ' .PassengerNum').val("1");
    $(calcFlight.dom_prefix + ' .isroundtrip').attr("checked", true);
    $(calcFlight.dom_prefix + ' #cb_radiative').attr("checked", false);
    calcFlight.co2 = null;
    calcFlight.cost = null;

    $(calcFlight.dom_prefix + " .distance .selecttextTotal").html("0");
    $(calcFlight.dom_prefix + " .co2 .selecttextTotal").html("0.00");
    $(calcFlight.dom_prefix + " .cost .selecttextTotal").html("$0.00");
    
    return false;
  },
  
  formatACResult: function(row) {
    return row.toString().substr(0, 3);
  },
  
  airportChange: function(e, add_to_cart) {
    if (typeof add_to_cart == 'undefined') {
      add_to_cart = false;
    }
    
    var airport1 = $(calcFlight.dom_prefix + ' .airport .selecttext').val();
    var airport2 = $(calcFlight.dom_prefix + ' .airport2 .selecttext').val();
    
    if ((airport1.length == 3) && (airport2.length == 3)) {
      $.getJSON('/calculators/aj_individual-flight.php', {airport1: airport1, airport2: airport2}, function(data) {
        calcFlight.airport1 = data.airport1;
        calcFlight.airport2 = data.airport2;
        calcFlight.calcForm(add_to_cart);
      });
    }
    
    return true;
  },
  
  calcForm: function(add_to_cart) {
    if ((calcFlight.airport1 === null) || (calcFlight.airport2 === null)) {
      return;
    }
    var lat1 = calcFlight.airport1.lat;
    var lat2 = calcFlight.airport2.lat;
    var lng1 = calcFlight.airport1.lng;
    var lng2 = calcFlight.airport2.lng;
    
    var R = 6371; // constant (in km)
    var dLat = (lat2-lat1).toRad();
    var dLng = (lng2-lng1).toRad(); 
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLng/2) * Math.sin(dLng/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var distance = R * c;
    
    // if it's a round trip, double it
    if ($(calcFlight.dom_prefix + ' #cb_RoundTripFlight:checked').length) {
      distance *= 2;
    }
    distance /= 1.6; // km => mi (slightly incorrect - should be 1.609344)
    distance = Math.round(distance);
    
    if (distance < 301) {
      nTon = distance * 0.00024;
    } else if (distance < 1001) {
      nTon = distance * 0.00019;
    } else {
      nTon = distance * 0.00018;
    }
    
    if ($(calcFlight.dom_prefix + ' #cb_radiative:checked').length) {
      nTon = nTon * 2.7;
    }
    
    // multiply by the number of passengers
    var num_passengers = $(calcFlight.dom_prefix + ' .PassengerNum').val();
    nTon = nTon * num_passengers;
    
    calcFlight.distance = distance;
    calcFlight.co2 = nTon;
    calcFlight.cost = calcFlight.co2 * 10.0;  // constant price per ton
    
    $(calcFlight.dom_prefix + " .distance .selecttextTotal").html(addCommas(calcFlight.distance));
    $(calcFlight.dom_prefix + " .co2 .selecttextTotal").html(calcFlight.co2.toFixed(2));
    $(calcFlight.dom_prefix + " .cost .selecttextTotal").html('$' + calcFlight.cost.toFixed(2));
    
    if (add_to_cart) {
      calcFlight.addToCart();
    }
    
    return false;
  },
  
  addToCart: function() {
    if (calcFlight.cost === null) {
      var airport1 = $(calcFlight.dom_prefix + ' .airport .selecttext').val();
      var airport2 = $(calcFlight.dom_prefix + ' .airport2 .selecttext').val();

      if ((airport1.length == 3) && (airport2.length == 3)) {
        calcFlight.airportChange(null, true);
        return;
      }
      alert("Please select your airports.");
      $(calcFlight.dom_prefix + ' .airport .selecttext').focus();
      return false;
    }
    
    var new_item = new CartItem({
      category: 'Flight',
      product_id: calcFlight.custom_product_id,
      item_name: calcFlight.airport1.code + '-' + calcFlight.airport2.code,
      tons: calcFlight.co2,
      price: calcFlight.cost
    });
    Calc.addToCart(new_item);
    
    return false;
  }

};


/* Train/Bus */

var calcTrainbus = {
  dom_prefix: '#calc_trainbus',

  tripfrom: null,
  tripto: null,

  directions: null,

  distance: null,
  co2: null,
  cost: null,
  custom_product_id: 16226,
  
  init: function() {
    $(calcTrainbus.dom_prefix + ' .method').change(calcTrainbus.calcForm).click(calcTrainbus.calcForm);
    $(calcTrainbus.dom_prefix + ' .PassengerNum').change(calcTrainbus.calcForm).keyup(calcTrainbus.calcForm);
    $(calcTrainbus.dom_prefix + ' .isroundtrip').change(calcTrainbus.calcForm).click(calcTrainbus.calcForm);

    $(calcTrainbus.dom_prefix + ' .tripfrom').typeWatch({ wait: 500, captureLength: 2, callback: calcTrainbus.getDistance });
    $(calcTrainbus.dom_prefix + ' .tripto').typeWatch({ wait: 500, captureLength: 2, callback: calcTrainbus.getDistance });

    $(calcTrainbus.dom_prefix + ' .addtrainbus').click(calcTrainbus.addToCart);
    $(calcTrainbus.dom_prefix + ' .cBtnsReset').click(calcTrainbus.clearForm);
    
    calcTrainbus.directions = new GDirections();
    GEvent.addListener(calcTrainbus.directions, 'load', calcTrainbus.calcForm);
  },
  
  clearForm: function() {
    calcTrainbus.distance = null;
    calcTrainbus.co2 = null;
    calcTrainbus.cost = null;
    
    $(calcTrainbus.dom_prefix + ' #method_train').attr("checked", true);
    $(calcTrainbus.dom_prefix + ' .PassengerNum').val("1");
    $(calcTrainbus.dom_prefix + ' .isroundtrip').attr("checked", true);
    
    $(calcTrainbus.dom_prefix + ' .tripfrom').val("");
    $(calcTrainbus.dom_prefix + ' .tripto').val("");
    
    $(calcTrainbus.dom_prefix + ' .distance .selecttextTotal').html("0");
    $(calcTrainbus.dom_prefix + ' .co2 .selecttextTotal').html("0.00");
    $(calcTrainbus.dom_prefix + ' .cost .selecttextTotal').html("$0.00");
    
    return false;
  },
  
  getDistance: function() {
    calcTrainbus.tripfrom = $(calcTrainbus.dom_prefix + ' .tripfrom').val();
    calcTrainbus.tripto = $(calcTrainbus.dom_prefix + ' .tripto').val();
    if ((calcTrainbus.tripfrom === '') || (calcTrainbus.tripto === '')) {
      return true;
    }
    
    calcTrainbus.directions.load('from: ' + calcTrainbus.tripfrom + ' to: ' + calcTrainbus.tripto);
  },
  
  calcForm: function () {
    if (calcTrainbus.directions === null) {
      return true;
    }
    
    var gdistance = calcTrainbus.directions.getDistance();
    if (gdistance === null) {
      return true;
    }
    var CurrentMileage = parseFloat(gdistance.html.replace("&nbsp;mi", "").replace(",", ""));
    
    if ($(calcTrainbus.dom_prefix + ' .isroundtrip:checked').length > 0) {
      CurrentMileage *= 2; // round trip - double the distance
    }
    
    var PassengerNumber = parseInt($(calcTrainbus.dom_prefix + ' .PassengerNum').val(), 10);
    var CurCost = 0;
    var CurCO2 = 0;
    var MultNum; // multiplier

    switch($(calcTrainbus.dom_prefix + ' INPUT[name="trainbus_method"]:checked').val()) {
      case 'train':
        CurrentMileage = CurrentMileage + CurrentMileage * 0.1; //nature of railroad tracks
        if (CurrentMileage > 20) {
          MultNum = 0.42;
        } else {
          MultNum = 0.35;
        }
        CurCO2 = PassengerNumber * CurrentMileage * MultNum;
        break;
      case 'bus':
        CurrentMileage = CurrentMileage + CurrentMileage * 0.1; // non-linear roads
        if (CurrentMileage > 20) {
          MultNum = 0.18;
        } else {
          MultNum = 0.66;
        }
        CurCO2 = PassengerNumber * CurrentMileage * MultNum;
        break;
    }

    CurCO2 = CurCO2 * 0.00045359237; //convert to tons
    CurCost = CurCO2 * 10.0; // price per ton
    CurCost = round2d(CurCost);
    
    calcTrainbus.distance = parseFloat(round2d(CurrentMileage));
    calcTrainbus.co2 = parseFloat(CurCO2);
    calcTrainbus.cost = parseFloat(round2d(CurCost));
    
    $(calcTrainbus.dom_prefix + " .distance .selecttextTotal").html(addCommas(calcTrainbus.distance));
    $(calcTrainbus.dom_prefix + " .co2 .selecttextTotal").html(round2d(calcTrainbus.co2));
    $(calcTrainbus.dom_prefix + " .cost .selecttextTotal").html(formatCurrency(calcTrainbus.cost));
    
    return true;
  },

  addToCart: function() {
    if (calcTrainbus.distance === null) {
      alert("Please set your trip options.");
      return false;
    }
    
    var new_item = new CartItem({
      category: 'Trainbus',
      product_id: calcTrainbus.custom_product_id,
      item_name: calcTrainbus.tripfrom + '-' + calcTrainbus.tripto,
      tons: calcTrainbus.co2,
      price: calcTrainbus.cost
    });
    Calc.addToCart(new_item);
    
    return false;
  }

};


/* Events */

var calcEvents = {
  dom_prefix: '#calc_events',
  co2: null,
  cost: null,
  custom_product_id: 16227,
  
  init: function() {
    $(calcEvents.dom_prefix + ' .secHead').click(function() {
      var el = $(this).next('DIV').toggle();
      if ($(el).filter(':visible').length > 0) {
        $(this).children('IMG').attr('src', '/calculators/images/closeDiv.gif');
      } else {
        $(this).children('IMG').attr('src', '/calculators/images/openDiv.gif');
      }
    });
    
    tb_init('a.thickbox');
    
    $(calcEvents.dom_prefix + ' .reset').click(calcEvents.resetForm);
    $(calcEvents.dom_prefix + ' INPUT').change(calcEvents.calcForm).keyup(calcEvents.calcForm);
    $(calcEvents.dom_prefix + ' .addEventBtn').click(calcEvents.addToCart);
    
    calcEvents.resetForm();
    $(calcEvents.dom_prefix + ' #eventName').focus();
  },
  
  resetForm: function() {
    $(calcEvents.dom_prefix + ' .selecttext').val("");
    $(calcEvents.dom_prefix + ' #eventName').val("Custom Event");
    $(calcEvents.dom_prefix + ' #eventDays').val("1");
    $(calcEvents.dom_prefix + ' #eventPeople').val("10");
    calcEvents.co2 = null;
    calcEvents.cost = null;

    $(calcEvents.dom_prefix + " .co2 .selecttextTotal").html("0.00");
    $(calcEvents.dom_prefix + " .cost .selecttextTotal").html("$0.00");
    
    return false;
  },
  
  calcForm: function () {
    var autoKG, venueKG, hotelKG, hotelKGUp, mealKG, transitKG, trainKG, shortFlightKG, medFlightKG, longFlightKG, extraLongFlightKG;
    autoKG = 0.35;
    venueKG = 0.520;
    hotelKG = 14.61;
    hotelKGUp = 29.53;
    mealKG = 1.25;
    transitKG = 0.17;
    trainKG = 0.34;
    shortFlightKG = 0.29;
    medFlightKG = 0.20;
    longFlightKG = 0.18;
    extraLongFlightKG = 0.18; /* same as above */

    var eventName = $("#eventName").val();
    if (eventName === '')  {
      return true;
    }

    var eventDays = parseFloat($("#eventDays").val());
    if (eventDays == 0 || isNaN(eventDays)) {
      return true;
    }

    var eventPeople = parseFloat($("#eventPeople").val());
    if (eventPeople == 0 || isNaN(eventPeople)) {
      return true;
    }

    var eventCars = parseFloat($("#eventCars").val());
    var eventCarDist = parseFloat($("#eventCarDist").val());
    var eventFltShort = parseFloat($("#eventFltShort").val());
    var eventFltMed = parseFloat($("#eventFltMed").val());
    var eventFltLong = parseFloat($("#eventFltLong").val());
    var eventFltExtLong = parseFloat($("#eventFltExtLong").val());
    var eventTrain = parseFloat($("#eventTrain").val());
    var eventTrainDist = parseFloat($("#eventTrainDist").val());
    var eventTransit = parseFloat($("#eventTransit").val());
    var eventBikeFoot = parseFloat($("#eventBikeFoot").val());
    var eventHotelNights = parseFloat($("#eventHotelNights").val());
    var eventMeals = parseFloat($("#eventMeals").val());
    var eventUpscale = $('#eventUpscale:checked').length;

    var carTotal;
    var hotelMultiplier;
    var hotelTotal;
    var mealTotal;
    var trainTotal;
    var transitTotal;
    var fltShortTotal;
    var fltMedTotal;
    var fltLongTotal;
    var fltExtLongTotal;
    
    // calculate subtotals
    var venueTotal = eventDays * eventPeople * venueKG;
    
    if (eventCars > 0) {
      carTotal = eventCars * (eventCarDist*2)*autoKG;
    } else {
      carTotal = 0;
    }

    if (eventCars>0&&(eventCarDist==0||isNaN(eventCarDist))) {
      return true;
    }

    if(eventHotelNights>0)  {
      if (eventUpscale==1) {
        hotelMultiplier = hotelKGUp;
      } else {
        hotelMultiplier = hotelKG;
      }
      hotelTotal = eventHotelNights*hotelMultiplier;
    } else {
      hotelTotal=0;
    }

    if (eventMeals>=3) {
      mealTotal= eventMeals*eventPeople*(mealKG/3);
    } else if (eventMeals==2) {
      mealTotal= eventMeals*eventPeople*(mealKG/2);
    } else {
      mealTotal= 0;
    }
    
    if (eventTrain>0) {
      trainTotal = eventTrain*(eventTrainDist*2)*trainKG;
    } else {
      trainTotal=0;
    }

    if(eventTrain>0&&(eventTrainDist==0||isNaN(eventTrainDist))) {
      return true;
    }
    
    if(eventTransit>0)  { transitTotal = eventTransit*16*transitKG; } else { transitTotal=0; }
    if(eventFltShort>0)  { fltShortTotal = (eventFltShort*500)*shortFlightKG; } else { fltShortTotal=0; }
    if(eventFltMed>0) { fltMedTotal = (eventFltMed*1300)*medFlightKG; } else { fltMedTotal=0; }
    if(eventFltLong>0)  { fltLongTotal = (eventFltLong*2250)*longFlightKG; } else { fltLongTotal=0; }
    if(eventFltExtLong>0)  { fltExtLongTotal = (eventFltExtLong*4750)*extraLongFlightKG; } else { fltExtLongTotal=0; }

    // calculate totals
    var totalFootprintKG = carTotal + hotelTotal + mealTotal + trainTotal + transitTotal + fltShortTotal + fltMedTotal + fltLongTotal + fltExtLongTotal + venueTotal;
    var totalFootprintT = totalFootprintKG/1000;
    var totalFootprintTOveraged = totalFootprintT*1.1;
    var varPrice = totalFootprintTOveraged*10; 
    var finalTons = totalFootprintTOveraged.toFixed(2);
    var finalPrice = varPrice.toFixed(2);

    calcEvents.co2 = totalFootprintTOveraged;
    calcEvents.cost = (calcEvents.co2 * 10.0).toFixed(2);

    $(calcEvents.dom_prefix + " .co2 .selecttextTotal").html(calcEvents.co2.toFixed(2));
    $(calcEvents.dom_prefix + " .cost .selecttextTotal").html('$' + calcEvents.cost);
    
    return true;
  },
  
  addToCart: function() {
    calcEvents.calcForm();
    if (calcEvents.co2 === null) {
      return;
    }
    var new_item = new CartItem({
      category: 'Events',
      product_id: calcEvents.custom_product_id,
      item_name: $("#eventName").val(),
      tons: calcEvents.co2,
      price: calcEvents.cost
    });
    Calc.addToCart(new_item);
    
    return false;
  }

};


var panes = {
  'Zero':
  { name: 'Zero',
    url: 'individual-zero.php',
    nav: '#calc-button-zero',
    nextCalc: 'Gift',
    num_items: 0,
    height: 20,
    image2: 'Tensas.jpg',
    autoRenderPanel: true,
    subPanelExtraClass: '',
    presets: [new CartItem({category: 'Zero', 'product_id': 16179, item_name: 'DirectCarbon-Indv', tons: 10}),
              new CartItem({category: 'Zero', 'product_id': 16180, item_name: 'ZeroCarbon-Indv', tons: 24}),
              new CartItem({category: 'Zero', 'product_id': 16181, item_name: 'DirectCarbon-Fam', tons: 40}),
              new CartItem({category: 'Zero', 'product_id': 16182, item_name: 'ZeroCarbon-Fam', tons: 96})
            ],
    calc: null
  },
  
  'Home':
  { name: 'Home',
    url: 'individual-home.php',
    nav: '#calc-button-home',
    nextCalc: 'Car',
    num_items: 0,
    height: 320,
    image2: 'Inland.jpg',
    autoRenderPanel: true,
    subPanelExtraClass: '',
    presets: [new CartItem({category: 'Home', 'product_id': 16137, item_name: 'Apartment', tons: 4.98, cost: 49.88}),
              new CartItem({category: 'Home', 'product_id': 16164, item_name: 'Small House', tons: 7.48, cost: 74.82}),
              new CartItem({category: 'Home', 'product_id': 16165, item_name: 'Medium House', tons: 12.47, cost: 124.71}),
              new CartItem({category: 'Home', 'product_id': 16166, item_name: 'Large House', tons: 20, cost: 200.00})
            ],
    calc: calcHome
  },
  
  'Car':
  { name: 'Car',
    url: 'individual-car.php',
    nav: '#calc-button-car',
    nextCalc: 'Flight',
    num_items: 0,
    height: 320,
    image2: 'Idleaire.jpg',
    autoRenderPanel: true,
    subPanelExtraClass: '',
    presets: [new CartItem({category: 'Car', 'product_id': 16167, item_name: 'Car-Green (41+ mpg)', tons: 2.72, cost: 27.21}),
              new CartItem({category: 'Car', 'product_id': 16168, item_name: 'Car-Efficient (29-40 mpg)', tons: 3.63, cost: 36.28}),
              new CartItem({category: 'Car', 'product_id': 16169, item_name: 'Car-Full Size (19-28 mpg)', tons: 5.44, cost: 54.42}),
              new CartItem({category: 'Car', 'product_id': 16170, item_name: 'Car-SUV (10-18 mpg)', tons: 9.07, cost: 90.70})
            ],
    calc: calcCar
  },
  
  'Flight':
  { name: 'Flight',
    url: 'individual-flight.php',
    nav: '#calc-button-flight',
    nextCalc: 'Trainbus',
    num_items: 0,
    height: 320,
    image2: 'Tensas.jpg',
    autoRenderPanel: true,
    subPanelExtraClass: '',
    presets: [new CartItem({category: 'Flight', 'product_id': 16171, item_name: 'Flight-6,000 Miles', tons: 1.13, cost: 11.33}),
              new CartItem({category: 'Flight', 'product_id': 16172, item_name: 'Flight-20,000 Miles', tons: 3.78, cost: 37.86}),
              new CartItem({category: 'Flight', 'product_id': 16173, item_name: 'Flight-40,000 Miles', tons: 7.57, cost: 75.73 }),
              new CartItem({category: 'Flight', 'product_id': 16174, item_name: 'Flight-100,000 Miles', tons: 18.94, cost: 189.43})
            ],
    calc: calcFlight
  },
  
  'Gift':
  { name: 'Gift',
    url: 'individual-blank.html',
    nav: '#calc-button-gift',
    nextCalc: 'Events',
    num_items: 0,
    height: 490,
    image2: 'ForestRivas.jpg',
    autoRenderPanel: true,
    subPanelExtraClass: 'calcSubPanelAGift',
    presets: [new CartItem({category: 'Gift', 'product_id': 16183, item_name: '1 Ton Gift Offset', tons: 1}),
              new CartItem({category: 'Gift', 'product_id': 16147, item_name: '2 Ton Gift Offset', tons: 2}),
              new CartItem({category: 'Gift', 'product_id': 16184, item_name: '5 Ton Gift Offset', tons: 5}),
              new CartItem({category: 'Gift', 'product_id': 16151, item_name: '10 Ton Gift Offset', tons: 10}),
              new CartItem({category: 'Gift', 'product_id': 16185, item_name: '50 Ton Gift Offset', tons: 50}),
              new CartItem({category: 'Gift', 'product_id': 16232, item_name: '100 Ton Gift Offset', tons: 100})
            ],
    calc: null
  },
  
  'Trainbus':
  { name: 'Trainbus',
    url: 'individual-trainbus.php',
    nav: '#calc-button-trainbus',
    nextCalc: 'Zero',
    num_items: 0,
    height: 320,
    image2: 'Inland.jpg',
    autoRenderPanel: true,
    subPanelExtraClass: '',
    presets: [new CartItem({category: 'Trainbus', 'product_id': 16175, item_name: 'Rail-5,000 miles', tons: 1}),
              new CartItem({category: 'Trainbus', 'product_id': 16176, item_name: 'Rail-50,000 miles', tons: 10}),
              new CartItem({category: 'Trainbus', 'product_id': 16177, item_name: 'Bus-12,000 miles', tons: 1}),
              new CartItem({category: 'Trainbus', 'product_id': 16178, item_name: 'Bus-36,000 miles', tons: 3})
            ],
    calc: calcTrainbus
  },
  
  'Events':
  { name: 'Events',
    url: 'individual-events.php',
    nav: '#calc-button-events',
    nextCalc: 'Events',
    num_items: 0,
    height: 800,
    image2: 'Idleaire.jpg',
    autoRenderPanel: false,
    subPanelExtraClass: '',
    presets: [new CartItem({category: 'Events', 'product_id': 16187, item_name: '1 Day Event (<250 attendees)', tons: 7.5}),
              new CartItem({category: 'Events', 'product_id': 16188, item_name: '1 Day Event (251-500 attendees)', tons: 15})
            ],
    calc: calcEvents
  }
};


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

