$(document).ready(function(){

  // Zebra stripe our tables
  $("table.table_list tr:odd").addClass("odd");
  $("table.table_list tr:even").addClass("even");

  // Highlight active tab
  $("#nav a[href $='" + location.pathname + "']").parents("li").addClass('selected');

  // Highlight the active tab, even if we're on a subpage (as long we're not on the home page! -- that would highlight everything)
  location.pathname.split('/')[1] && !$("#nav li.selected").length ? $("#nav a[href ^='/" + location.pathname.split('/')[1] + "']:first").parents("li").addClass('selected') : null;

  // Hightlight the active submenu link
  $("#submenu a[href $='" + location.pathname + location.search + "']").not('.delete').addClass('selected');

  // Load Google map if applicable
  loadGoogleMap();

  // Storage Unit Tooltips
  $(".storage-unit").hover(function() {
      if ($(".tooltip", this).css("display") == "block") { return false; }
      $(".tooltip", this).show();
  },
  function() {
      $(".tooltip", this).hide();
  });

  // Add classes to certain form input types
  $('input[type="text"],input[type="password"]').addClass('text-input');
  $('input[type="checkbox"]').addClass('checkbox');

  // Hide special instructions for people without javascript
  $('.nojs').hide();


  // Unit Type form
  function summarizeDiscount(i) {
    var n = i.id.match(/\d+$/)[0];
    var p = $('#unit_type_price').val();
    var d = $(i).val();
    if (d == '' || p == '') {
      $('#discount' + n + '-summary').empty();
    } else {
      var m = p - parseInt(p * d) / 100;
      var f = m * n;
      $('#discount' + n + '-summary').html('(' + numberToCurrency(m) + ' per month, ' + numberToCurrency(f) + ' total)');
    }
  };
  $('.discount').keyup(function () {summarizeDiscount(this);}).each(function () {summarizeDiscount(this);});

  // Site setup/settings
  function toggleGateKeyText() {
    if ($('#site_gate_key_enabled').length > 0) {
      var gks = $('#site_gate_key_sent').add('#site_gate_key_text').parent();
      ($('#site_gate_key_enabled').attr('checked')) ? gks.show() : gks.hide();
    }
  }
  $('#site_gate_key_enabled').change(toggleGateKeyText);
  toggleGateKeyText();

  // line_items/pay
  $('#payment_method').change(function () {
    $('.payment-method-fields').hide();
    if ($('#payment_method').val() == 'one_time_card') {
      $('.one-time-card').show();
    } else if ($('#payment_method').val() == 'cash') {
      $('.cash').show();
    } else if ($('#payment_method').val() == 'check') {
      $('.check').show();
    }
  }).trigger('change');

  function togglePayFields() {
    if ($('#payment_method').val() == 'cash' || $('#payment_method').val() == 'check') {
      $('#transaction-message').show();
    } else {
      $('#transaction-message').hide();
    }
    if ($('#payment_method').val() == 'one_time_card') {
      $('#one-time-card').show();
    } else {
      $('#one-time-card').hide();
    }
  }
  $('#payment_method').change(togglePayFields);
  togglePayFields();

  // Add some markup to our link buttons
  $('a.button').each(function(){
    $(this).append("<span class='corners'><span class='c1'></span><span class='c2'></span><span class='c3'></span><span class='c4'></span></span>");
  });

  // Custom pricing for admins
  $('select#site_contract_length').change(function (){
    if($(this).val() == "0"){
      $('#custom-pricing').slideDown();
      $('#custom-pricing :input').removeAttr('disabled');
    }else{
      $('#custom-pricing').hide();
      $('#custom-pricing :input').attr('disabled', true);
    }
  });

  $('input#line_item_amount, input#line_item_taxable').bind('click keyup', function () {updateFeeTaxSummary();});
  if ($('input#line_item_amount').length > 0) {updateFeeTaxSummary()};

  // AJAX manager rental form
  var unit_type_field = $('form#manager-rental-form select#rental_unit_type_id');
  if (unit_type_field.length > 0) {
    loadRentalFieldsForUnitType(unit_type_field.val());
    $(unit_type_field).change(function(){
      loadRentalFieldsForUnitType($(this).val());
    });
  }

  $('form#manager-rental-form select#rental_billing_cycle').change(function (){
    if($('option:selected', this).text().match(/Custom/)){
      $('#custom-pricing :input').removeAttr('disabled');
      $('#custom-pricing').slideDown();
    }else{
      $('#custom-pricing :input').attr('disabled', true);
      $('#custom-pricing').hide();
    }
  });

  $('form#manager-rental-form select, form#manager-rental-form input').bind('click keyup', function (){updateSummaryChargeForManagerRentalForm();});
  $('form#manager-rental-form select#rental_rented_on_2i')
    .add($('form#manager-rental-form select#rental_rented_on_3i'))
    .add($('form#manager-rental-form select#rental_rented_on_1i'))
    .add($('form#manager-rental-form select#rental_billing_cycle'))
    .change(function (){updateSummaryNextChargeOnForManagerRentalForm();});
  if ($('form#manager-rental-form').length > 0) {updateSummaryNextChargeOnForManagerRentalForm();}


  // Site payment gateway form
  $('select#site_gateway_name').change(function (){
    $('.gateway-form').hide();  // Hide all of the gateway forms.
    $('.gateway-form :input').attr('disabled', true);  // Disable all of the gateway form inputs.

    selected_gateway_css_id = '#' + $(this).val() + '-gateway';
    $(selected_gateway_css_id).show();   // Show the select gateway form.
    $(selected_gateway_css_id + ' :input').attr('disabled', false); // And enable its inputs.
    //$(selected_gateway_css_id + ' textarea').css('width', '600px'); // And fix a webkit textarea reactivation bug (http://code.google.com/p/chromium/issues/detail?id=2033)
  });

  // Payment gateway toggle form
  $('a#change-payment-gateway').click( function(){
    $('#payment-gatway-show-form').hide();
    $('#payment-gateway-form').show();
    return false;
  });

  // Lockout notice toggle auction date
  $("#auction_toggle").attr("checked", "checked");
  $("#auction_toggle").change(function(){
    if($(this).is(":checked")){
      $("#auction-fields").children("select").attr("disabled", false);
    }else{
      $("#auction-fields").children("select").attr("disabled", true);
    }
  });

  // autosubmit dropdowns
  $("select.autosubmit").siblings('input[type="submit"]').hide();
  $("select.autosubmit").change(function(){
    this.form.submit();
  });

  // Add check/uncheck all to checkbox lists
  $('ul#checkbox-list').prepend("<li class='check-uncheck-all'>Select: <a href='#' class='check-all' onclick='javascript:$(\"ul#checkbox-list input.checkbox\").attr(\"checked\", true); return false;'>All</a>, <a href='#' class='uncheck-all' onclick='javascript:$(\"ul#checkbox-list input.checkbox\").attr(\"checked\", false); return false;'>None</a></li>");

  // Template letter bulk print
  $('table#template-letter-customers').before("<p class='check-uncheck-all'>Select: <a href='#' class='check-all' onclick='javascript:$(\"table#template-letter-customers input.checkbox\").attr(\"checked\", true); return false;'>All</a>, <a href='#' class='uncheck-all' onclick='javascript:$(\"table#template-letter-customers input.checkbox\").attr(\"checked\", false); return false;'>None</a></p>");
  $("table#template-letter-customers").tablesorter({headers: { 0: { sorter: false } }});

  // Add check/uncheck all to checkbox tables
  $('table#checkbox-table').before("<p class='check-uncheck-all'>Select: <a href='#' class='check-all' onclick='javascript:$(\"table#checkbox-table input.checkbox\").attr(\"checked\", true); return false;'>All</a>, <a href='#' class='uncheck-all' onclick='javascript:$(\"table#checkbox-table input.checkbox\").attr(\"checked\", false); return false;'>None</a></p>");

  // Billing history
  $('#check-all').click(function() {
    $("input[type='checkbox']").attr('checked', true);
    return false;
  });
  $('#check-none').click(function() {
    $("input[type='checkbox']").attr('checked', false);
    return false;
  });

});

// Calculate Total for Rental Fees
function updateFeeTaxSummary() {
  var amount = parseFloat($('input#line_item_amount').val());
  if (isNaN(amount)) {amount = 0;}
  var tax = parseFloat($('span#line-item-tax').html().replace('(', '')) / 100;
  if (isNaN(tax) || !$('#line_item_taxable').attr('checked')) {tax = 0;}
  tax
  var html = numberToCurrency(amount) + " + " + numberToCurrency(amount * tax) + " = " + numberToCurrency(amount + amount * tax) + " Total";
  $('span#tax-summary').html(html);
}

function updateSummaryChargeForManagerRentalForm() {
  var monthly_price, deposit, prorated, total;
  var tax_rate = parseFloat($('#rent-tax-rate').html());
  if (isNaN(tax_rate)) {tax_rate = 0;}
  if ($('#rental_amount_rented_for')[0].disabled) {
    monthly_price = parseFloat($('#rental_billing_cycle option:selected').html().replace('$', ''));
  } else {
    monthly_price = parseFloat($('#rental_amount_rented_for').val());
  }
  if (isNaN(monthly_price)) {monthly_price = 0;}
  monthly_price = monthly_price + monthly_price * tax_rate;
  if ($('#rental_charge_deposit').attr('checked')) {
    deposit = parseFloat($('#rental_deposit').val());
  }
  if (isNaN(deposit)) {deposit = 0;}
  if ($('#rental_charge_prorated_amount').attr('checked')) {
    prorated = parseFloat($('#rental_prorated_amount').val());
  }
  if (isNaN(prorated)) {prorated = 0;}
  prorated = prorated + prorated * tax_rate;
  var total = deposit + prorated;
  // TODO: Is there a better place to put this view stuff?
  $('form#manager-rental-form span#summary-intro').html("Clicking this button will attempt to charge the credit card on file for:<br />");
  html = "&nbsp;&nbsp;&nbsp;<strong>" + numberToCurrency(total) + "</strong> (" + numberToCurrency(deposit) + " Deposit + " + numberToCurrency(prorated) + " Prorated) immediately and<br />";
  html = html + "&nbsp;&nbsp;&nbsp;<strong>" + numberToCurrency(monthly_price) + "</strong>";
  $('form#manager-rental-form span#summary-charge').html(html);
}

function updateSummaryNextChargeOnForManagerRentalForm() {
  if ($('form#manager-rental-form').length == 0) {return;}
  var d = $('select#rental_rented_on_1i').val() + '-' + $('select#rental_rented_on_2i').val() + '-' +$('select#rental_rented_on_3i').val();
  var b = $('#rental_billing_cycle').val();
  if (null == b) {b = 1;}
  $.get('/rentals/next_charge_on_ajax?rented_on=' + d + '&billing_cycle=' + b, function(data){
    $('span#summary-billing-cycle').html(data);
  });
}

function loadRentalFieldsForUnitType(unit_type_id){
  $.get('/unit_types/' + unit_type_id + '/available_units_ajax', function(data){
    $('select#rental_unit_id').html(data);
  });
  $.get('/unit_types/' + unit_type_id + '/billing_cycle_ajax', function(data){
    $('select#rental_billing_cycle').html(data);
    $('#custom-pricing :input').attr('disabled', true);
    $('#custom-pricing').hide();
    updateSummaryChargeForManagerRentalForm();
  });
  $.get('/unit_types/' + unit_type_id + '/deposit_ajax', function(data){
    $('input#rental_deposit').val(data);
    updateSummaryChargeForManagerRentalForm();
  });
}

function loadGoogleMap(){
  if ($("#map").length > 0 && GBrowserIsCompatible()) {
    var business = $("#map-name").text();
    var address = $("#map-address").text();
    var map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(address,
      function(point) {
        if (!point) {
          alert(address + " not found");
        } else {
          map.setCenter(point, 13);
          var marker = new GMarker(point);
          map.addOverlay(marker);
          marker.openInfoWindowHtml("<div id='map-info'><h3>" + business + "</h3><p>" + address + "</p></div>");
        }
      }
    );
  }
}

// http://www.web-source.net/web_development/currency_formatting.htm
function numberToCurrency(amount) {
  var i = parseFloat(amount);
  if (isNaN(i)) {i = 0.00;}
  var minus = '';
  if (i < 0) {minus = '-';}
  i = Math.abs(i);
  i = parseInt(i * 100);
  i = i / 100;
  s = new String(i);
  if(s.indexOf('.') < 0) {s += '.00';}
  if(s.indexOf('.') == (s.length - 2)) {s += '0';}
  s = minus + s;
  return '$' + s;
}

