/*----- Call Autocomplete plugin -----*/
$(document).ready(function(){
	apply_autocomplete("#from_location", "#from_type_id_fk");
	apply_autocomplete("#to_location", "#to_type_id_fk");
});

function apply_autocomplete(target_address, target_address_type){
	$( target_address ).autocomplete({
		source: function(request, response) {
			$.ajax({ 
				url: "ajax_get_address.php",
				data: { 
					keyword: $(target_address).val() ,
					search_from: $(target_address_type).val()
				},
				dataType: "json",
				type: "POST",
				success: function(data){
					response(data);
				}
			})
		},
		minLength: 3
	});
}

function submit_locations(){
	var from_location=$("#from_location").val();
	var from_location_type=$("#from_type_id_fk").val();
	
	var to_location=$("#to_location").val();
	var to_location_type=$("#to_type_id_fk").val();
	
	if(from_location!="" && to_location!=""){
		//store locations to session values
		$.ajax({ 
			url: "ajax_store_locations_session.php",
			data: { 
				from_location_type: from_location_type,
				from_location: from_location,
				to_location_type: to_location_type,
				to_location: to_location
			},
			dataType: "html",
			type: "POST",
			success: function(data){
				if(data=='done')
					redirect("booking_details.php");
			}
		});
	}
}

function toggle_location_selection(container_id, location_control_id, selected_value){
	if(selected_value==0){
		//display textbox
		$("#"+container_id).html('<input type="text" name="' + location_control_id + '" id="' + location_control_id + '" value="" class="booking_text2" />');
		apply_autocomplete("#from_location", "#from_type_id_fk");
		apply_autocomplete("#to_location", "#to_type_id_fk");
	}
	else{
		//display selectbox
		$("#"+container_id).html('<span style="padding:8px 3px;float:left;font-size:12px;width:240px;">Loading...</span>');
		$.ajax({ 
			url: "ajax_get_address_selector.php",
			data: { 
				location_control_id: location_control_id,
				selected_value: selected_value
			},
			dataType: "html",
			type: "POST",
			success: function(data){
				$("#"+container_id).html(data);
			}
		});
	}
}

function toggle_return(checked_value){
	if(checked_value=="yes"){
		$('.return_element').show();
		if($("#to_location_type").val()=='1'){
			$("#flight_details_container").show();
		}
	}
	else{
		$('.return_element').hide();
		if($("#to_location_type").val()=='1'){
			$("#flight_details_container").hide();
		}
	}
	update_booking_total();
}
