// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

$.datePicker.setDateFormat('mdy','/');

$(document).ready(function() {
  $(".container").wrap("<div class='border'></div>");
  $(".costs fieldset").vjustify();
  $(".airports fieldset").vjustify();
  $('#trips').tableSorter({
		sortColumn: 3,			// Integer or String of the name of the column to sort by.
		sortClassAsc: 'headerSortUp',		// Class name for ascending sorting action to header
		sortClassDesc: 'headerSortDown',	// Class name for descending sorting action to header
		headerClass: 'header',			// Class name for headers (th's)
		stripingRowClass: ['even','odd'],	// Class names for striping supplyed as a array.
		stripRowsOnStartUp: true,		// Strip rows on tableSorter init.
    dateFormat: 'mm/dd/yyyy'
	});
  setupPlannerCosts();
  setupNavigation();
  setupFAQ();
  $('.date').datePicker();
  $("form :input:visible:enabled:first").focus();
});

function setupNavigation() {
  path = location.pathname.split('/');
  if (path) {
    $('#navigation a[@href$="' + [path[0], path[1]].join('/') + '"]').parent().attr('class', 'selected');
  }
}

function setupFAQ() {
  $('#faq dd').hide();
  $('#faq dt').click(function() {
    question = $(this);
    answer = question.next('dd')
    if (answer.css('display') == 'none') {
      answer.show();
      question.addClass('open');
    } else {
      answer.hide();
      question.removeClass('open');
    }
  });
}

function disable(id) {
  $(id).attr('disabled','disabled');
}

function enable(id) {
  $(id).removeAttr('disabled');
}

function setupPlannerCosts() {
  setupCarCosts();
  setupPrivateAircraftCosts();
  setupCommercialAirlineCosts();
}

function setupCarCosts() {
  if ($('#car_cost_pricing_method_id_1').attr('checked')) {
    disableCustomCarCosts();
  }
  $('#car_cost_pricing_method_id_1').click( function() {
    disableCustomCarCosts();
  });
  $('#car_cost_pricing_method_id_2').click( function() {
    enableCustomCarCosts();
  });
}

function disableCustomCarCosts() {
    disable('#car_cost_car_name');
    disable('#car_cost_price_per_mile');
}

function enableCustomCarCosts() {
    enable('#car_cost_car_name');
    enable('#car_cost_price_per_mile');
}

function setupPrivateAircraftCosts() {
  if ($('#private_aircraft_cost_pricing_method_id_1').attr('checked')) {
    disableCustomPrivateAircraftCosts();
  } else {
    disableDefaultPrivateAircraftCosts();
  }
  $('#private_aircraft_cost_pricing_method_id_1').click( function() {
    enableDefaultPrivateAircraftCosts();
    disableCustomPrivateAircraftCosts();
  });
  $('#private_aircraft_cost_pricing_method_id_2').click( function() {
    enableCustomPrivateAircraftCosts();
    disableDefaultPrivateAircraftCosts();
  });
  $('#private_aircraft_cost_charge_method_per_hour').click( function() {
    enable('#private_aircraft_cost_price_per_hour');
    disable('#private_aircraft_cost_price_per_mile');
  });
  $('#private_aircraft_cost_charge_method_per_mile').click( function() {
    disable('#private_aircraft_cost_price_per_hour');
    enable('#private_aircraft_cost_price_per_mile');
  });

  $("#private_aircraft_cost_aircraft_type_id").change(function(){
    $.getJSON("/aircraft_types/filter_models/" + $(this).val(), function(j){
      var options = '<option value=""></option>';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].attributes.id + '">' + j[i].attributes.name + '</option>';
      }
      $("#private_aircraft_cost_aircraft_model_id").html(options);
      $("#private_aircraft_cost_aircraft_model_id").val("");
    });
  });
}

function disableDefaultPrivateAircraftCosts() {
  disable('#private_aircraft_cost_aircraft_type_id');
  disable('#private_aircraft_cost_aircraft_model_id');
  disable('#private_aircraft_cost_default_price_per_hour');
}

function disableCustomPrivateAircraftCosts() {
  disable('#private_aircraft_cost_aircraft_name');
  disable('#private_aircraft_cost_aircraft_speed');
  disable('#private_aircraft_cost_charge_method_per_hour');
  disable('#private_aircraft_cost_price_per_hour');
  disable('#private_aircraft_cost_charge_method_per_mile');
  disable('#private_aircraft_cost_price_per_mile');
}

function enableDefaultPrivateAircraftCosts() {
  enable('#private_aircraft_cost_aircraft_type_id');
  enable('#private_aircraft_cost_aircraft_model_id');
  enable('#private_aircraft_cost_default_price_per_hour');
}

function enableCustomPrivateAircraftCosts() {
  enable('#private_aircraft_cost_aircraft_name');
  enable('#private_aircraft_cost_aircraft_speed');
  enable('#private_aircraft_cost_charge_method_per_hour');
  enable('#private_aircraft_cost_charge_method_per_mile');
  if ($('#private_aircraft_cost_charge_method_per_hour').attr('checked')) {
    enable('#private_aircraft_cost_price_per_hour');
  } else {
    enable('#private_aircraft_cost_price_per_mile');
  }
}

function setupCommercialAirlineCosts() {
  if ($('#commercial_airline_cost_pricing_method_id_1').attr('checked')) {
    disableCustomCommercialAirlineCosts();
  } else {
    disableDefaultCommercialAirlineCosts();
  }
  $('#commercial_airline_cost_pricing_method_id_1').click( function() {
    enableDefaultCommercialAirlineCosts();
    disableCustomCommercialAirlineCosts();
  });
  $('#commercial_airline_cost_pricing_method_id_2').click( function() {
    enableCustomCommercialAirlineCosts();
    disableDefaultCommercialAirlineCosts();
  });
}

function disableDefaultCommercialAirlineCosts() {
  disable('#commercial_airline_cost_default_airline_id');
}

function disableCustomCommercialAirlineCosts() {
  disable('#commercial_airline_cost_airline_id');
  disable('#commercial_airline_cost_custom_flight_cost');
  disable('#commercial_airline_cost_custom_flight_time');
  disable('#commercial_airline_cost_flight_type_oneway');
  disable('#commercial_airline_cost_flight_type_return');
}

function enableDefaultCommercialAirlineCosts() {
  enable('#commercial_airline_cost_default_airline_id');
}

function enableCustomCommercialAirlineCosts() {
  enable('#commercial_airline_cost_airline_id');
  enable('#commercial_airline_cost_custom_flight_cost');
  enable('#commercial_airline_cost_custom_flight_time');
  enable('#commercial_airline_cost_flight_type_oneway');
  enable('#commercial_airline_cost_flight_type_return');
}

function showAddress(type, mapDiv) {
  if (!mapDiv) mapDiv = type;
  address = $('#' + type + '_address').val();
  geocoder = new GClientGeocoder();
  clearAddressFields(type);
  geocoder.getLocations(
    address,
    function(response) {
      if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to find that address.");
      } else {
        populateAddressFields(type,response);
        addMapMarker(mapDiv, response);
      }
    }
  );
}

function clearAddress(type, mapDiv) {
  if(!mapDiv) mapDiv = type;
  $('#' + type + '_address').val('');
  clearAddressFields(type);
  map = resetMap(mapDiv);
  map.setCenter(new GLatLng(37.0625, -95.677068), 3);
}

function clearAddressFields(type) {
  $('#' + type + '_street1').val('');
  $('#' + type + '_street2').val('');
  $('#' + type + '_city').val('');
  $('#' + type + '_state').val('');
  $('#' + type + '_postal_code').val('');
  $('#' + type + '_latitude').val('');
  $('#' + type + '_longitude').val('');
}

function clearAirports(type) {
  var options = '<option value=""></option>';
  if (type == 'origin') {
    $('#private_aircraft_cost_departure_airport_id').html(options);
    $('#commercial_airline_cost_departure_airport_id').html(options);
  } else {
    $('#private_aircraft_cost_arrival_airport_id').html(options);
    $('#commercial_airline_cost_arrival_airport_id').html(options);
  }
}

function populateAirports(type, response) {
  var lat = place.Point.coordinates[1];
  var lng = place.Point.coordinates[0];

  if (type == 'origin') {
    if ($('#private_aircraft_cost_departure_airport_id')) {
      $.getJSON("/airport_selection/general_aviation?lat=" + lat + '&lng=' + lng, function(j){
        var options = '<option value=""></option>';
        for (var i = 0; i < j.length; i++) {
          options += '<option value="' + j[i].attributes.id + '">' + j[i].attributes.name + '</option>';
        }
        $("#private_aircraft_cost_departure_airport_id").html(options);
        $("#private_aircraft_cost_departure_airport_id").val("");
      });
    }
    if ($('#commercial_airline_cost_departure_airport_id')) {
      $.getJSON("/airport_selection/commercial?lat=" + lat + '&lng=' + lng, function(j){
        var options = '<option value=""></option>';
        for (var i = 0; i < j.length; i++) {
          options += '<option value="' + j[i].attributes.id + '">' + j[i].attributes.name + '</option>';
        }
        $("#commercial_airline_cost_departure_airport_id").html(options);
        $("#commercial_airline_cost_departure_airport_id").val("");
      });
    }
  } else {
    if ($('#private_aircraft_cost_arrival_airport_id')) {
      $.getJSON("/airport_selection/general_aviation?lat=" + lat + '&lng=' + lng, function(j){
        var options = '<option value=""></option>';
        for (var i = 0; i < j.length; i++) {
          options += '<option value="' + j[i].attributes.id + '">' + j[i].attributes.name + '</option>';
        }
        $("#private_aircraft_cost_arrival_airport_id").html(options);
        $("#private_aircraft_cost_arrival_airport_id").val("");
      });
    }
    if ($('#commercial_airline_cost_arrival_airport_id')) {
      $.getJSON("/airport_selection/commercial?lat=" + lat + '&lng=' + lng, function(j){
        var options = '<option value=""></option>';
        for (var i = 0; i < j.length; i++) {
          options += '<option value="' + j[i].attributes.id + '">' + j[i].attributes.name + '</option>';
        }
        $("#commercial_airline_cost_arrival_airport_id").html(options);
        $("#commercial_airline_cost_arrival_airport_id").val("");
      });
    }
  }
}

function populateAddressFields(type, response){
  place = response.Placemark[0];
  if (place) {
    adminArea = place.AddressDetails.Country.AdministrativeArea;
    if (adminArea) {
      $('#' + type + '_state').val(adminArea.AdministrativeAreaName);
      subadminArea = adminArea.SubAdministrativeArea;
      if (subadminArea) {
        local = subadminArea.Locality;
        if (local) {
          $('#' + type + '_city').val(local.LocalityName);
          street = local.Thoroughfare;
          if (street) {
            $('#' + type + '_street1').val(street.ThoroughfareName);
          }
          postal = local.PostalCode;
          if (postal) {
            $('#' + type + '_postal_code').val(postal.PostalCodeNumber);
          }
        }
      }
    }
    $('#' + type + '_lat').val(place.Point.coordinates[1]);
    $('#' + type + '_lng').val(place.Point.coordinates[0]);
  }
}

function resetMap(type) {
  map = new GMap2(document.getElementById(type + "_map"));
  map.addControl(new GSmallMapControl());

  return map;
}

function addMapMarker(type, response) {
  map = resetMap(type);
  place = response.Placemark[0];
  point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
  map.setCenter(point, 10);
  var marker = new GMarker(point);
  map.addOverlay(marker);
}
