//fix cursor position in inpur box
function setCaretTo(obj, pos) {
	if(obj.createTextRange) {
		/* Create a TextRange, set the internal pointer to
		   a specified position and show the cursor at this
		   position
		*/
		var range = obj.createTextRange();
		range.move("character", pos);
		range.select();
	} else if(obj.selectionStart) {
		/* Gecko is a little bit shorter on that. Simply
		   focus the element and set the selection to a
		   specified position
		*/
		obj.focus();
		obj.setSelectionRange(pos, pos);
	}
}


//set the minimum purchase date
var min_purchase_date = "+2d";

var getMinDate = function(date_input){	

	return min_purchase_date;
}

var mtValidateOneWay = function(){
	var has_errors = 0;
	//check departure
	if($j("#mtDepartureCity").val() == ""){
		alert("Departure City can't be blank");
		var has_errors = 1;
	}
	
	if($j("#mtDepartureCity").val().length < 3){
		alert("Departure City must be at least 3 characters");
		var has_errors = 1;
	}
	//check destination city
	if($j("#mtDestinationCity").val()== "" ){
		alert("Destination City can't be blank");
		var has_errors = 1;
	}
	
	if($j("#mtDestinationCity").val().length < 3){
		alert("Destination City must be at least 3 characters");
		var has_errors = 1;
	}
	
	//check departure date
	if($j("#mtDepartureDateInput").val() == ""){
		alert("Departure Date can't be blank");
		var has_errors = 1;	
	}	
	
	var departure_date = $j("#mtDepartureDateInput").val();
	var departure_date = departure_date.split("/");
	if(isNaN(departure_date[0]) || isNaN(departure_date[1]) || isNaN(departure_date[2])){
		alert("Please select a departure date");
		var has_errors = 1;
	}
	
	//check the number of adults
	var number_of_adults = $j("#mtNumberOfAdultsInput").val();
	var number_of_seniors =  $j("#mtNumberOfSeniorsInput").val();
	if(parseInt(number_of_adults + number_of_seniors)< 1){
		alert("At least 1 adult must be traveling");
		var has_errors = 1;
	}
	
	if(has_errors){
		return false
	} else {
		progress_update();
		return true;	
	}
}

var mtValidateRoundTrip = function(){
	var has_errors = 0;
	//validate the common elements
	var x = mtValidateOneWay();
	if(!x){
		var has_errors = 1;	
	}
	
	//check destination date
	if($j("#mtReturnDateInput").val() == ""){
		alert("Destination Date can't be blank");
		var has_errors = 1;	
	}	
	
	var destination_date = $j("#mtReturnDateInput").val();
	var destination_date = destination_date.split("/");
	if(isNaN(destination_date[0]) || isNaN(destination_date[1]) || isNaN(destination_date[2])){
		alert("Please select a destination date");
		var has_errors = 1;
	}
	
	if(has_errors){
		return false
	} else {
		progress_update();		
		return true;	
	}
}

var mtValidateMultiCity = function(){
	var has_errors = 0;
	var number_legs = $j(".mtAirport_input:visible").length / 2;
	//set the multi city number of legs
	$j("#multi_leg_select").val(number_legs);
	//check the first leg
	mtValidateOneWay();
	
	//check the rest of the legs
	for(i=1;i<number_legs;i++){
		//check departure
		if($j("#mtDepartureCity" + i).val() == ""){
			alert("Departure City for flight " + (i + 1) + " can't be blank");
			var has_errors = 1;
		}
		
		if($j("#mtDepartureCity" + i).val().length < 3){
			alert("Departure City for flight " + (i + 1) + " must be at least 3 characters");
			var has_errors = 1;
		}
		
		//check destination city
		if($j("#mtDestinationCity" + i).val()== "" ){
			alert("Destination City for flight " + (i + 1) + " can't be blank");
			var has_errors = 1;
		}
		
		if($j("#mtDestinationCity" + i).val().length < 3){
			alert("Destination City for flight " + (i + 1) + " must be at least 3 characters");
			var has_errors = 1;
		}
		
		//check departure date
		if($j("#mtDepartureDateInput" + i).val() == ""){
			alert("Departure Date for flight " + (i + 1) + " can't be blank");
			var has_errors = 1;	
		}	
	}	
	
	if(has_errors){
		return false
	} else {
		progress_update();		
		return true;	
	}
}

//validate the form
var mtValidate = function(){
	//check the type of search
	var search_type = $j("input[@name='flight_type']:checked").val();
	
	switch(search_type) {
		case "OW":
			var x = mtValidateOneWay();
			if(!x){
				return false;	
			}
		break;
		case "RT":
			var x = mtValidateRoundTrip();
			if(!x){
				return false;	
			}
		break;
		case "MC":
			var x = mtValidateMultiCity();
			if(!x){
				return false;	
			}
		break;
		
	}

	//check for destination date
	$j("#air_form").submit();	
}

//auto complete helper function to set hidden field value and set input to empty if empty result
function set_target_val(target, data) {
	target.val('');
	if (data && data.length > 1){
		target.val(data[1]);
	}
}

$j(document).ready(function(){
		
	//set start date of the Arrival city
	$j("#mtDepartureDateInput").change(function(){
		if($j("#mtReturnDateInput").val() == "mm/dd/yyyy" && $j("#mtFlightTypeRoundTrip:checked")){
			$j("#mtReturnDateInput").val($j("#mtDepartureDateInput").val());
		}
	});
	
	
	//set up autocompete	
	var autocomplete_url = (("https:" == document.location.protocol) ? "https://" : "http://") + document.domain + "/include/inc_php/flights/flightform_v2/air_list.php";
	var autocomplete_settings_obj = {
			minChars:3,
			width: 300,
			scrollHeight: 350,
			formatResult: function(data, i, total) { return (data && data.length > 1) ? data[2] : ' '; }
	};
	$j(".mtAirport_input").autocomplete(autocomplete_url, autocomplete_settings_obj);
	
	//handle results when item is selected
	$j(".mtAirport_input").result(function(event, data, formatted) {
		//var x = $j(this).val();	
		var y = $j(this).attr("title");	
		var z = $j(this).attr("id").substring(2,11);
		
		if(z == "Departure"){
			var target = $j("#legs_" + y + "_departure_airport");			
		} else {
			var target = $j("#legs_" + y + "_arrival_airport");	
		}
		var y = $j(this).attr("id");
		setCaretTo(document.getElementById(y),0);
		set_target_val(target, data);
	});


	//delete initial blank space
	$j("input[autocomplete='off']").keydown(function(evt) {
		var code = evt.keyCode;
		if ($j(this).val() == '' && code == 32)
			return false;
	});
	

	//home page additional options	
	$j("#mtAdditionalOptionsLink").click(function () {
		if($j("#mtHomeAdditionalOptions").is(":visible")){
			$j("#mtAdditionalOptionsLink").removeClass("mtAdditionalLinksImageOpen").addClass("mtAdditionalLinksImage").html("More Search Options");
			$j("#mtHomeAdditionalOptions").hide("slow");
			$j("#mtShowNumberOfConnections input").hide();
			$j("#mtClassType").hide();
		} else {
			$j("#mtClassType").show();
			$j("#mtAdditionalOptionsLink").removeClass("mtAdditionalLinksImage").addClass("mtAdditionalLinksImageOpen").html("Fewer Search Options");
			$j("#mtHomeAdditionalOptions").show("slow");
			$j("#mtShowNumberOfConnections input").show();
		}
	});
	
	//date picker options
	var date_options = 	{
		//minDate: getMinDate(),
		numberOfMonths: 2,
		duration: 'fast',
		showAnim: 'slide',
		showOptions: {direction: 'up'},
		beforeShow: function(input) {
			//get the min date value				
			$j(this).datepicker('option', 'minDate', getMinDate(this.title));
		}
	};
	
	//add the date picker
	$j('.mtDateInput').datepicker(date_options);	
	
	//home page number of connections
	$j("#mtNumberOfConnectionsCheckbox").click(function(){
		if($j("#mtShowNumberOfConnections").is(":visible")){
			$j("#mtShowNumberOfConnections").hide();
		} else {
			$j("#mtShowNumberOfConnections").show();
		}
	});
	
	//home page limit to specific airlines
	$j("#mtLimitAirlinesCheckbox").click(function(){
		$j("#mtShowSpecificAirlines:visible").hide("fast");
		$j("#mtShowSpecificAirlines:hidden").show("fast");
	});	
	
	/*
	//populate the hidden departure field
	$j('input[id^="mtDepartureCity"]').change(function(){
		var x = $j(this).val();	
		var y = $j(this).attr("title");		
		$j("#legs_" + y + "_departure_airport").val(x);								 
	});
	

	//populate the hidden destination field	
	$j('input[id^="mtDestinationCity"]').change(function(){
		var x = $j(this).val();	
		var y = $j(this).attr("title");	
		$j("#legs_" + y + "_arrival_airport").val(x);								 
	});	
	*/
	
	//populate the hidden departure date field
	//$j("#mtDepartureDateInput").change(function(){
	$j('input[id^="mtDepartureDateInput"]').change(function(){
															
		var datestring = $j(this).val().split("/");	
		//current value
		var x = $j(this).attr("title");
		//next value
		var y = parseInt($j(this).attr("title")) + 1;
		//prepopulate the next date input
		if ($j(this).attr('id') == 'mtDepartureDateInput'){
			var nextDate = $j(this).attr('id') + "1";	
			$j("#" + nextDate).val($j(this).val());
		} else {
			var nextDate = parseInt($j(this).attr('id').substring(20,21)) + 1;
			var nextDate = "mtDepartureDateInput" + nextDate;
			$j("#" + nextDate).val($j(this).val());
		}
		//hidden fields for the current date input
		$j("#legs_" + x + "_search_date_day").val(datestring[1]);			
		$j("#legs_" + x + "_search_date_month").val(datestring[0]);	
		
		//hidden fields for the next date input
		$j("#legs_" + y + "_search_date_day").val(datestring[1]);			
		$j("#legs_" + y + "_search_date_month").val(datestring[0]);		
		
	});

	//populate the hidden destination date field
	$j("#mtReturnDateInput").change(function(){
		var datestring = $j(this).val().split("/");		
		$j("#round_trip_return_date_day").val(datestring[1]);			
		$j("#round_trip_return_date_month").val(datestring[0]);	
	});	
	
	//hide one way option when one way is selected
	$j("#mtFlightTypeOneWay").click(function(){		
		if($j("#mtFlightTypeOneWay").is(":checked")){
			$j("#mtReturnDate").hide();
		}
		$j('div[id^="mtFlightSegment"]').each(function(i){
			var x = $j(this).attr("id");
			var y = x.substring(15,16);
			//hide the extra segments if their visible
			if(y > 1){
				if($j(this).is(":visible")){
					$j(this).hide();
				}
			}
		});
	});
	
	//round trip selection
	$j("#mtFlightTypeRoundTrip").click(function(){		
		if($j("#mtReturnDate").is(":hidden")){
			$j("#mtReturnDate").show();
		}
		$j('div[id^="mtFlightSegment"]').each(function(i){
			var x = $j(this).attr("id");
			var y = x.substring(15,16);
			//hide the extra segments if their visible
			if(y > 1){
				if($j(this).is(":visible")){
					$j(this).hide();
				}
			}
		});
		$j("#mtFlightSegment1 .mtAirSearchBoxSubHead").hide();
	});
	
	// multi city selection 
	$j("#mtFlightTypeMultiCity").click(function(){		
		if(!$j("#mtReturnDate").is(":hidden")){
			$j("#mtReturnDate").hide();
		}
		if($j(".mtAddFlightContainer2").is(":hidden")){
			$j(".mtAddFlightContainer2").show();	
		}
		$j("#mtFlightSegment2").show();		
		$j("#mtFlightSegment1 .mtAirSearchBoxSubHead").show();
	});
	
	//on page load check to make sure return date is hidden if one way is selected
	if($j("#mtFlightTypeOneWay").is(":checked")){
		$j("#mtReturnDate").hide();			
	}
	
	//on page load if multi city is selected make sure the segments are showing
	if($j("#mtFlightTypeMultiCity").is(":checked")){
		if(!$j("#mtReturnDate").is(":hidden")){
			$j("#mtReturnDate").hide();
		}	
		$j("#mtFlightSegment2").show();
		$j("#mtFlightSegment1 .mtAirSearchBoxSubHead").show();
	}
	
	//on page load set number of children to 0
	$j("#mtNumberOfChildrenInput").val("0");
	
	//add another flight to multi city search
	$j(".mtAddAnotherFlight").click(function(){
		var x = $j(this).attr("title");			
		$j("#mtFlightSegment" + x).show();
		$j(this).parent(".mtAddFlightContainer" + x-1).hide();
		if($j(".mtAddFlightContainer" + x).is(":hidden")){
			$j(".mtAddFlightContainer" + x).show();	
		}
		return false;
	});
	
	//remove flight to multi city search
	$j(".mtRemoveFlight").click(function(){
		var x = $j(this).attr("title");			
		$j("#mtFlightSegment" + x).hide();
		var y = x-1;
		$j(".mtAddFlightContainer" + y).show();		
		return false;
	});
	
	//show children ages when children are selected
	$j("#mtNumberOfChildrenInput").click(function(){
		var y = parseInt($j(this).val());
		
		switch(y) {
			case 0: 
				if($j("#mtChildrenAges").is(":visible")){
					$j("#mtChildrenAges").hide();
					$j('div[id^="mtChildAge"]').each(function(i){
						if($j(this).is(":visible")){
							$j(this).hide();	
						}
					});
				}
			break;
			case 1:				
				$j("#mtChildrenAges").show();
				$j("#mtChildAge1").show();
				var x = 2;				
				while(x <= 5){
					$j("#mtChildAge" + x).hide();
					x++;
				}
			break;
			case 2: 
				$j("#mtChildrenAges").show();
				var x = 1;
				var y = 2;
				while(x <= y){					
					$j("#mtChildAge" + x).show();
					x++;
				}
				var x = 3;
				var y = 5;
				while(x <= y){
					$j("#mtChildAge" + x).hide();
					x++;
				}
			break;
			case 3:
				$j("#mtChildrenAges").show();			
				var x = 1;
				var y = 3;
				while(x <= y){
					$j("#mtChildAge" + x).show();
					x++;
				}
				var x = 4;
				var y = 5;
				while(x <= y){
					$j("#mtChildAge" + x).hide();
					x++;
				}			
			break;
			case 4: 
				$j("#mtChildrenAges").show();			
				var x = 1;
				var y = 4;
				while(x <= y){
					$j("#mtChildAge" + x).show();
					x++;
				}
				var x = 5;
				var y = 5;
				while(x <= y){
					$j("#mtChildAge" + x).hide();
					x++;
				}			
			break;
			case 5: 
				$j("#mtChildrenAges").show();
				var x = 1;
				var y = 5;
				while(x <= y){
					$j("#mtChildAge" + x).show();
					x++;
				}	
			break;
		}
	});
});