// JavaScript Document
var from_loc='',to_loc='';

//For Google Map
var geocoder;
var map;
var marker;

//Setting up For POPUP
var popupStatus = 0;//0 means disabled; 1 means enabled;

$(document).ready(function(){
	$("#from_type_id").change(function(){									   
		if($(this).val()=='8'){
			$("#from_loc_id").hide();
			$("#txt_from_address").hide();
			$("#from_postcode").show();
			$("#from_door_no_tr").show();
			$("#from_map_icon").hide();
			$("#from_details_tr").hide();
		}else if($(this).val()=='7'){
			$("#from_loc_id").hide();
			$("#txt_from_address").show();
			$("#from_postcode").hide();
			$("#from_door_no_tr").hide();
			$("#from_map_icon").show();
			$("#from_details_tr").hide();
		}else{
			if($(this).val()=='1'){
				$("#from_details_tr").show();
			}else{
				$("#from_details_tr").hide();
			}
			$("#from_loc_id").show();
			$("#txt_from_address").hide();
			$("#from_postcode").hide();			
			get_location($(this).val(),"#from_loc_id");
			$("#from_door_no_tr").hide();			
			$("#from_map_icon").hide();
		}
		$("#standerd_rate_error").hide();
	});
	
	$("#to_type_id").change(function(){							 
		if($(this).val()=='8'){
			$("#to_loc_id").hide();
			$("#txt_to_address").hide();
			$("#to_postcode").show();
			$("#to_door_no_tr").show();
			$("#to_map_icon").hide();
		}else if($(this).val()=='7'){
			$("#to_loc_id").hide();
			$("#txt_to_address").show();
			$("#to_postcode").hide();
			$("#to_door_no_tr").hide();
			$("#to_map_icon").show();
		}else{
			$("#to_loc_id").show();
			$("#txt_to_address").hide();
			$("#to_postcode").hide();			
			get_location($(this).val(),"#to_loc_id");
			$("#to_door_no_tr").hide();
			$("#to_map_icon").hide();
		}	
		$("#standerd_rate_error").hide();
	});
	
	$("#show_fare").click(function(){
		if(validateSaloon()){
			get_fare();
		}
	});
	
	
	function validateSaloon(){
	/*
		if( $('#no_of_passangers').val()>4  && $('input:radio[name=vehicle_type]:checked').val() == 1){
			$("#validation_message").html("If no of passengers are more than 4 then cannot select saloon");
			$("#validation_message").show();
			$("#standerd_rate_error").hide();
			return false;
		}else{
			return true;
		}
		*/
		if(($("#from_type_id").val() == '1')&&($("#to_type_id").val() == '1') &&($("#from_loc_id").val() == $("#to_loc_id").val())){
			$("#validation_message").html("From address and to address can not be same");
			$("#validation_message").show();
			$("#standerd_rate_error").hide();
		return false;
		}
		if(($("#from_type_id").val() == '8')&&($("#to_type_id").val() == '8') &&($("#from_postcode").val() == $("#to_postcode").val())){
			$("#validation_message").html("Please enter full post code");
			$("#validation_message").show();
			$("#standerd_rate_error").hide();
		return false;
		}
		
		return true;
	}
	
	function get_fare(){									  
		if($("#from_type_id").val() != '7' && $("#from_type_id").val() != '8' && $("#to_type_id").val() != '7' && $("#to_type_id").val() != '8'){
			new_calculate_fare_for_one_location("#from_loc_id","#to_loc_id");
			
			/*
				$.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ to_loc_id:""+$("#to_loc_id").val(), from_loc_id:""+$("#from_loc_id").val(), vehicle_type:""+$('input:radio[name="vehicle_type"]:checked').val(), journy_type:""+$('input[name="journy_type"]:checked').val() }, function(json){			
					if(json.status =='true'){
						$("#journy_fare").val(json.fare);
						showcarsprice(json.fare);
						$("#standerd_rate_error").html("<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td>\u00A3 " +json.fare +"</td><td><input name='save_booking' class='button' id='save_booking' type='submit' value='Book Now' /></td></tr></table>");
					}else if(json.status =='postcode'){
						getdistance(json['from_postcode'+vehicle_number],json['to_postcode'+vehicle_number],json);
						$("#standerd_rate_error").show();
						$("#validation_message").hide();
					}else{						
						$("#standerd_rate_error").html("<p class='error'>Cant Calculate Automatically <input name='save_booking' class='button' id='save_booking' type='submit' value='Book Now' /></p>");
					}
				});
		$("#standerd_rate_error").show();
			*/	
		//Both are Addresses
		}else if($("#from_type_id").val() == '7' && $("#to_type_id").val() == '7' ){	
			if($("#txt_from_address").val() =='' || $("#txt_to_address").val() =='' ){	
				$("#validation_message").html("Enter Address First");
				$("#validation_message").show();
				$("#standerd_rate_error").hide();
			}else{
				calculate_fare_for_two_location("#txt_from_address","#txt_to_address");
				//calculate_fare("#txt_from_address","#txt_to_address");
				//$("#standerd_rate_error").show();
				//$("#validation_message").hide();
			}
				
		}
		
		//Both are PostalCode	
		else if($("#from_type_id").val() == '8' && $("#to_type_id").val() == '8' ){	
			if($("#from_postcode").val() =='' || $("#to_postcode").val() =='' ){				
				$("#validation_message").html("Enter Postcode First");
				$("#validation_message").show();
				$("#standerd_rate_error").hide();
			}
			else{
				calculate_fare_for_two_location("#from_postcode","#to_postcode");
				//calculate_fare("#from_postcode","#to_postcode");
				//$("#standerd_rate_error").show();
				//$("#validation_message").hide();
			}
		}
		
		//From-PostalCode To - Address/DDL
		else if($("#from_type_id").val() == '8'){
			//To - DDL
			if($("#to_type_id").val() != '7'){
					if(checking_for_empty("#from_postcode","Enter Postcode First","#to_loc_id","Select Location Second")){
						//calculate_fare_for_one_location("#from_postcode","#to_loc_id");					
						//----This modification done for station car as they enter postal code as KT4 format---
						if( $('#from_postcode').val().length < 6 ){
							new_calculate_fare_for_one_location_onepostcode("#from_postcode","#to_loc_id","frompostcode");	
							//calculate_fare_for_two_location("#from_postcode","#to_loc_id");	
						}else{
							new_calculate_fare_for_one_location_onepostcode("#from_postcode","#to_loc_id","frompostcode");	
							//calculate_fare_for_one_location("#from_postcode","#to_loc_id");		
						}
					}
			//To - Address
			}else{
					if(checking_for_empty("#from_postcode","Enter Postcode First","#txt_to_address","Enter Address Second")){
					calculate_fare_for_two_location("#from_postcode","#txt_to_address");
						//calculate_fare("#from_postcode","#txt_to_address");
					}
			}	
		}
		//From - Address  To - PostalCode/DDL
		else if($("#from_type_id").val() == '7'){
			if($("#to_type_id").val() != '8'){	
				if(checking_for_empty("#txt_from_address","Enter Address First","#to_loc_id","Select Location Second")){
					//calculate_fare_for_one_location("#txt_from_address","#to_loc_id");
					new_calculate_fare_for_one_location("#txt_from_address","#to_loc_id");	
				}
			}else{
				if(checking_for_empty("#txt_from_address","Enter Address First","#to_postcode","Enter Postcode Second")){
					//calculate_fare("#txt_from_address","#to_postcode");
					//----This modification done for station car as they enter postal code as KT4 format---
					if( $('#to_postcode').val().length < 6 ){
						calculate_fare_for_two_location("#txt_from_address","#to_postcode");
						//calculate_fare_for_two_location("#txt_from_address","#to_postcode");	
					}else{
						calculate_fare_for_two_location("#txt_from_address","#to_postcode");
						//calculate_fare("#txt_from_address","#to_postcode");		
					}
				}
			}
		}
		//To-PostalCode From - Address/DDL
		else if($("#to_type_id").val() == '8'){
			if($("#from_type_id").val() != '7'){
				if(checking_for_empty("#from_loc_id","Select Location First","#to_postcode","Enter Postcode Second")){
					//calculate_fare_for_one_location("#to_postcode","#from_loc_id");
					//----This modification done for station car as they enter postal code as KT4 format---
					if( $('#to_postcode').val().length < 6 ){
						new_calculate_fare_for_one_location_onepostcode("#from_loc_id","#to_postcode","topostcode");	
						//calculate_fare_for_two_location("#to_postcode","#from_loc_id");	
					}else{
						new_calculate_fare_for_one_location_onepostcode("#from_loc_id","#to_postcode","topostcode");	
						//calculate_fare_for_one_location("#to_postcode","#from_loc_id");		
					}
				}
			}else{
				if(checking_for_empty("#txt_from_address","Enter Address First","#to_postcode","Enter Postcode Second")){
					//calculate_fare("#txt_from_address","#to_postcode");
					//----This modification done for station car as they enter postal code as KT4 format---
					if( $('#to_postcode').val().length < 6 ){
						calculate_fare_for_two_location("#txt_from_address","#to_postcode");	
						//calculate_fare_for_two_location("#txt_from_address","#to_postcode");	
					}else{
						calculate_fare_for_two_location("#txt_from_address","#to_postcode");	
						//calculate_fare("#txt_from_address","#to_postcode");		
					}
				}
			}
		}
		//To-Address From - PostalCode/DDL
		else if($("#to_type_id").val() == '7'){
			if($("#from_type_id").val() != '8'){
				if(checking_for_empty("#from_loc_id","Select Location First","#txt_to_address","Enter Address Second")){
						new_calculate_fare_for_one_location("#from_loc_id","#txt_to_address");	
					//calculate_fare_for_one_location("#txt_to_address","#from_loc_id");
				}
			}else{
					if(checking_for_empty("#from_postcode","Enter Postcode First","#txt_to_address","Enter Address Second")){
					calculate_fare_for_two_location("#from_postcode","#txt_to_address");	
						//calculate_fare("#from_postcode","#txt_to_address");
					}
			}
		}
	}	
	
	
	function calculate_fare(from,to){
		$.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ loc_id:"1", vehicle_type: "all"}, function(json){			
			if(json['vc_status'+vehicle_number] =='true'){
				getdistance($(from).val(),$(to).val(),json);
			}
		});		
	}
	//loc1: user enterd location, lic2: location that should retrive by DB
	function calculate_fare_for_one_location(loc1,loc2){	
	 $.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ loc_id:""+$(loc2).val(), vehicle_type: "all"}, function(json){			
			if(json.status =='true'){
				getdistance($(loc1).val(),json.postcode,json);
			}else{			
				$("#standerd_rate_error").html("<p class='error'>Cant Calculate Automatically <input name='save_booking' class='button' id='save_booking' type='submit' value='Book Now' /></p>");	
			}
		});
	}
	
	// loc1: location that should retrive by DB, loc2: location that should retrive by DB
	function calculate_fare_for_two_location(loc1,loc2){
		//alert('2location');
		show_progress();
		$.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ to_loc_id:""+$(loc2).val(), from_loc_id:""+$(loc1).val(), vehicle_type:"all", journy_type:"1"}, function(json){
			hide_progress();			
					//alert($(loc2).val());
					//alert($(loc1).val());
					//alert('from_found_id '+json['from_loc_id']);
					//alert('to_found_id '+json['to_loc_id']);
			for(vehicle_number =1;vehicle_number<=3;vehicle_number++){
				
				if(json['status'+vehicle_number] =='true'){
					//-- add minimu fare 20 if from is airport--//
					if(($("#from_type_id").val()==1)&&(json['fare'+vehicle_number]<20)){
						json['fare'+vehicle_number] = 20;
					}
					
					//-- add 5 if from is airport(airport charge=5) --//
					if($("#from_type_id").val()==1){
						json['fare'+vehicle_number] = json['fare'+vehicle_number]+5;
					}
					
					showpriceincarbox(json['fare'+vehicle_number],vehicle_number);	
					//$("#journy_fare").val(json['fare'+vehicle_number]+".00");
					$("#standerd_rate_error").hide();	
					$("#from_to_tr").hide();			
					//$("#book_from_td").html(response.routes[0].legs[0].start_address);
					//$("#book_to_td").html(response.routes[0].legs[0].end_address);			
					//$("#from_to_tr").show();	
				}else if(json['status'+vehicle_number] =='postcode'){
					//alert(json['status'+vehicle_number]);
					//alert(json['from_postcode'+vehicle_number]);
					//alert(json['to_postcode'+vehicle_number]);
						getdistance(json['from_postcode'+vehicle_number],json['to_postcode'+vehicle_number],json,vehicle_number);
						$("#standerd_rate_error").show();
						$("#validation_message").hide();
				}
				else if(json['vc_status'+vehicle_number] =='true'){ 
				//alert(json['vc_status'+vehicle_number]);
					from_value = $(loc1).val();
					to_value = $(loc2).val();
				if(json['from_postcode_new'+vehicle_number]){
				//alert('found1 '+json['from_postcode_new'+vehicle_number]);
					from_value = json['from_postcode_new'+vehicle_number];
				}
				if(json['to_postcode_new'+vehicle_number]){
				//alert('found2 '+json['to_postcode_new'+vehicle_number]);
					to_value = json['to_postcode_new'+vehicle_number];
				}
				//alert(from_value);
				//alert(to_value);
				getdistance(from_value,to_value,json,vehicle_number);
						$("#standerd_rate_error").show();
						$("#validation_message").hide();
				}

				else{
					
					$("#standerd_rate_error").html("No related data in the Database");
					$("#standerd_rate_error").show();
				}
				}
			});	
	}
	
	// loc1: location that should retrive by DB, loc2: location that should retrive by DB
	function new_calculate_fare_for_one_location(loc1,loc2){
		//alert('same');
		show_progress();
		$.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ onelocationid:"true", to_loc_id:""+$(loc2).val(), from_loc_id:""+$(loc1).val(), vehicle_type:"all", journy_type:"1"}, function(json){
			hide_progress();	
			
			for(vehicle_number =1;vehicle_number<=3;vehicle_number++){
			//alert('forloop '+vehicle_number);
				
					//alert($(loc2).val());
					//alert($(loc1).val());
					//alert('from_found_id '+json['from_loc_id']);
					//alert('to_found_id '+json['to_loc_id']);
				//alert(json['status'+vehicle_number]);	
				if(json['status'+vehicle_number] =='true'){
					//-- add minimu fare 20 if from is airport--//
					if(($("#from_type_id").val()==1)&&(json['fare'+vehicle_number]<20)){
						json['fare'+vehicle_number] = 20;
					}
					//-- add 5 if from is airport(airport charge=5) --//
					if($("#from_type_id").val()==1){
						json['fare'+vehicle_number] = json['fare'+vehicle_number]+5;
					}
					
					showpriceincarbox(json['fare'+vehicle_number],vehicle_number);	
					//$("#journy_fare").val(json['fare'+vehicle_number]+".00");
					//$("#standerd_rate_error").hide();	
					//$("#from_to_tr").hide();			
					//$("#book_from_td").html(response.routes[0].legs[0].start_address);
					//$("#book_to_td").html(response.routes[0].legs[0].end_address);			
					//$("#from_to_tr").show();	
				}else if(json['status'+vehicle_number] =='postcode'){
					//alert(json['status'+vehicle_number]);
					//alert(json['from_postcode'+vehicle_number]);
					//alert(json['to_postcode'+vehicle_number]);
						getdistance(json['from_postcode'+vehicle_number],json['to_postcode'+vehicle_number],json,vehicle_number);
						$("#standerd_rate_error").show();
						$("#validation_message").hide();
				}
				else if(json['vc_status'+vehicle_number] =='true'){ 
				//alert(json['vc_status'+vehicle_number]);
					from_value = $(loc1).val();
					to_value = $(loc2).val();
				if(json['from_postcode_new'+vehicle_number]){
				//alert('found1 '+json['from_postcode_new'+vehicle_number);
					from_value = json['from_postcode_new'+vehicle_number];
				}
				if(json['to_postcode_new'+vehicle_number]){
				//alert('found2 '+json['to_postcode_new'+vehicle_number]);
					to_value = json['to_postcode_new'+vehicle_number];
				}
				//alert(from_value);
				//alert(to_value);
				getdistance(from_value,to_value,json,vehicle_number);
						$("#standerd_rate_error").show();
						$("#validation_message").hide();
				}
				else{
					
					$("#standerd_rate_error").html("No related data in the Database");
					$("#standerd_rate_error").show();
				}
				//alert('end loop'+vehicle_number);
			//--end for loop--//	
				}
			});	
		
	}
	
	///--- this is new function for if postcode text pass -//
	function new_calculate_fare_for_one_location_onepostcode(loc1,loc2,postcodetype){
		//alert('onepostcode');
		show_progress();
		$.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ onelocationid:"true", postcodetype:""+postcodetype, to_loc_id:""+$(loc2).val(), from_loc_id:""+$(loc1).val(), vehicle_type:"all", journy_type:"1"}, function(json){
			hide_progress();	
			//alert("postcodetype"+json['postcodetype']);		
					//alert($(loc2).val());
					//alert($(loc1).val());
					//alert('from_found_id '+json['from_loc_id']);
					//alert('to_found_id '+json['to_loc_id']);
		for(vehicle_number =1;vehicle_number<=3;vehicle_number++){
		
				if(json['status'+vehicle_number] =='true'){
					//alert(json['status'+vehicle_number]);		
					//alert(json['from_loc_id'+vehicle_number]);		
					//alert(json['to_loc_id'+vehicle_number]);		
					//alert(json['fare'+vehicle_number]+".00");
					//-- add minimu fare 20 if from is airport--//
					if(($("#from_type_id").val()==1)&&(json['fare'+vehicle_number]<20)){
						json['fare'+vehicle_number] = 20;
					}
					//-- add 5 if from is airport(airport charge=5) --//
					if($("#from_type_id").val()==1){
						json['fare'+vehicle_number] = json['fare'+vehicle_number]+5;
					}
					showpriceincarbox(json['fare'+vehicle_number],vehicle_number);	
					//$("#journy_fare").val(json['fare'+vehicle_number]+".00");
					$("#standerd_rate_error").hide();	
					$("#from_to_tr").hide();			
					//$("#book_from_td").html(response.routes[0].legs[0].start_address);
					//$("#book_to_td").html(response.routes[0].legs[0].end_address);			
					//$("#from_to_tr").show();	
				}else if(json['status'+vehicle_number] =='postcode'){
					//alert(json['status'+vehicle_number]);
					//alert(json['from_postcode'+vehicle_number]);
					//alert(json['to_postcode'+vehicle_number]);
						getdistance(json['from_postcode'+vehicle_number],json['to_postcode'+vehicle_number],json,vehicle_number);
						$("#standerd_rate_error").show();
						$("#validation_message").hide();
				}
				else if(json['vc_status'+vehicle_number] =='true'){ 
				//alert(json['vc_status'+vehicle_number]);
					from_value = $(loc1).val();
					to_value = $(loc2).val();
				if(json['from_postcode_new'+vehicle_number]){
				//alert('found1 '+json['from_postcode_new'+vehicle_number]);
					from_value = json['from_postcode_new'+vehicle_number];
				}
				if(json['to_postcode_new'+vehicle_number]){
				//alert('found2 '+json['to_postcode_new'+vehicle_number]);
					to_value = json['to_postcode_new'+vehicle_number];
				}
				//alert(from_value);
				//alert(to_value);
				getdistance(from_value,to_value,json,vehicle_number);
						$("#standerd_rate_error").show();
						$("#validation_message").hide();
				}

				else{
					
					$("#standerd_rate_error").html("No related data in the Database");
					$("#standerd_rate_error").show();
				}
				}
			});	
	}
	
	function checking_for_empty(field1,msg1,field2,msg2){
		if( (($(field1).val() !='') && ($(field1).val() !=null)) && (($(field2).val() !='') && ($(field2).val() !=null)) ) {
			$("#validation_message").hide();
			$("#standerd_rate_error").show();
			$(field1).css("background","#DAB2F8");
			$(field2).css("background","#DAB2F8");
			return true;
		}else{
			$("#validation_message").html("");

			if($(field1).val() =='' || $(field1).val() ==null){
				$("#validation_message").html(msg1);
				$(field1).css("background","#FA8080");
			}else{
				$(field1).css("background","#DAB2F8");
			}
			
			if($(field2).val() =='' || $(field2).val() ==null){
				$("#validation_message").html($("#validation_message").html()+'<BR/>'+msg2);
				$(field2).css("background","#FA8080");
			}
			else{
				$(field2).css("background","#DAB2F8");
			}
			
			$("#validation_message").show();
			$("#standerd_rate_error").hide();
			return false;
		}
	}
	
	function get_location(loc_id,select_id){		
		var option = '';
		$.getJSON("../controller/select_controller.php",{ id:""+loc_id }, function(json){			
			for (var i = 0; i < json.length; i++) {
				option += '<option value="' + json[i].optionValue + '">' + json[i].optionDisplay + '</option>';
			}		
			$(select_id).html(option);			
		});		
	}
/*	
	function getdistance(from,to,vehicle){
		from_loc=from;
		to_loc=to;
		var distance=0;
		var directionsService = new google.maps.DirectionsService();
		var request = {
			origin: ''+from, 
			destination: ''+to,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		
		directionsService.route(request, function(response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
			distance=response.routes[0].legs[0].distance.value;
			distance = distance/1.609344;
			distance=(Math.round(distance/100))/10;
			var temp_distance = Math.round(distance/0.5)*0.5;
			if(distance > temp_distance){
				temp_distance = temp_distance+ 0.5;
			}
			distance = temp_distance;*/
 /*			var fare=0;
			if(distance > 2){
				distance = distance - 2;
				fare = parseFloat(vehicle.start_rate) + parseFloat(distance * parseFloat(parseFloat(vehicle.increment_rate)/parseFloat(vehicle.increment_distance)));
			}else{
				fare = parseFloat(vehicle.start_rate);
			}
			if($('input[name="journy_type"]:checked').val() =='2'){
				fare = fare*2*90/100;
			}
			fare = parseFloat(Math.round(parseFloat(fare)*100))/100;*/
/*			var fare=0;
			if(distance <= 1){
				fare = 5;
			}else if(distance > 1 ){
				fare = Math.round(2.60 * distance);
			}
			if($('input[name="journy_type"]:checked').val() =='2'){
				fare = fare*2*90/100;
			}
			fare = parseFloat(Math.round(parseFloat(fare)*100))/100;
			
			$("#journy_fare").val(fare);
			showcarsprice(fare);
			$("#standerd_rate_error").html("<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td>\u00A3 " +fare +"</td><td><input name='save_booking' class='button' id='save_booking' type='submit' value='Book Now' /></td></tr></table>");						
		}else{			
			$("#standerd_rate_error").html("<p class='error'>Cant Calculate Automatically <input name='save_booking' class='button' id='save_booking' type='submit' value='Book Now' /></p>");			
		}
		});
	}*/
	//--new function --//
	function getdistance(from,to,vehicle,vno){
		var geocoder = new google.maps.Geocoder();
	   	var results;
	   	geocoder.geocode( { 'address': ''+from+''}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				from_loc = results[0].geometry.location; 
				geocoder.geocode( { 'address': ''+to+''}, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						to_loc = results[0].geometry.location;										
						var distance=0;
						var directionsService = new google.maps.DirectionsService();
						var request = {
							origin: from_loc, 
							destination: to_loc,
							travelMode: google.maps.DirectionsTravelMode.DRIVING
						};
						
						directionsService.route(request, function(response, status) {
							if (status == google.maps.DirectionsStatus.OK) {
							distance=response.routes[0].legs[0].distance.value;
							distance = distance/1.609344;
							distance=(Math.round(distance/100))/10;							
							var temp_distance = Math.round(distance/0.5)*0.5;
							if(distance > temp_distance){
								temp_distance = temp_distance+ 0.5;
							}
							distance = temp_distance;
							//distance = 14;
							//alert('distance '+distance);
							var fare=0;
							//alert(vehicle['startrate_miles'+vno]);
							if(distance > parseFloat(vehicle['startrate_miles'+vno])){
								//distance = distance - parseFloat(vehicle.startrate_miles);
								/*-- new code for fare calculate based on the millage from price metrix table */
								
								//alert(vehicle.frommiles_array);
								frommiles_array2 = vehicle['frommiles_array'+vno].split("##");
								tomiles_array2 = vehicle['tomiles_array'+vno].split("##");
								rates_array2 = vehicle['rates_array'+vno].split("##");
								tot_price = 0;
								sub_price =0;
								sub_miles =0;
								diduct_startmiles ='false';
								for(i=0;i<frommiles_array2.length;i++){
									
									if((frommiles_array2[i] < distance )  &&  (tomiles_array2[i] <= distance)){
										if(diduct_startmiles == 'false'){
										diduct_startmiles = 'true';
										sub_miles = (tomiles_array2[i] - frommiles_array2[i]) - parseFloat(vehicle['startrate_miles'+vno]);
										}else{
										sub_miles = tomiles_array2[i] - frommiles_array2[i];
										}
									sub_price = parseFloat(rates_array2[i]);
									tot_price += sub_price*sub_miles;
									
											
									}else if((frommiles_array2[i] < distance ) && (tomiles_array2[i] > distance )){
										if(diduct_startmiles == 'false'){
										diduct_startmiles = 'true';
										sub_miles = (distance - frommiles_array2[i]) - parseFloat(vehicle['startrate_miles'+vno]);
										}else{
										sub_miles = distance - frommiles_array2[i];
										}
									sub_price = parseFloat(rates_array2[i]);
									tot_price += sub_price*sub_miles;
									}
								
								}
								fare = parseFloat(vehicle['start_rate'+vno]) + tot_price;
								//alert('tot_price '+tot_price);
								//alert('vehicle_price '+parseFloat(vehicle.start_rate));
								//alert(fare);
								//-- old function --//
								//fare = parseFloat(vehicle.start_rate) + parseFloat(distance * parseFloat(parseFloat(vehicle.increment_rate)/parseFloat(vehicle.increment_distance)));
							}else{
								fare = parseFloat(vehicle['start_rate'+vno]);
							}
							//-- add minimu fare 20 if from is airport--//
							if(($("#from_type_id").val()==1)&&(fare<20)){
								fare = 20;
							}
							//-- add 5 if from is airport(airport charge=5) 22-02-2010--//
							if($("#from_type_id").val()==1){
								fare = parseFloat(fare)+parseFloat(5);
							}
							
							fare = Math.ceil(fare);
							//alert('final fare '+fare);
							//if($('input[name="journy_type"]:checked').val() =='2'){
							//	fare = fare*2;
							//}
							//fare = parseFloat(Math.round(parseFloat(fare)*100))/100;
							$("#journy_fare").val(fare);			
							$("#from_to_tr").show();	
							$("#standerd_rate_error").hide();
			//$("#journy_fare").val(fare);
			//showcarsprice(fare);
			showpriceincarbox(fare,vno);
			//$("#standerd_rate_error").html("<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td>\u00A3 " +fare +"</td><td><input name='save_booking' class='button' id='save_booking' type='submit' value='Book Now' /></td></tr></table>");						

						}else{
			showpriceincarbox("NA",vno);
						//	$("#standerd_rate_error").html("Can't Calculate the Standerd Rate");
						//	$("#standerd_rate_error").show();
						//	$("#from_to_tr").hide();
						}
						});
					}
				});
			}
		});
	}	
	
	
	
	$("#show_map").click(function(){								 
		var map_status = true;
		var map_from = '';
		var map_to = '';
		
		if($("#from_type_id").val() == '7'){
			if($("#txt_from_address").val() == '' || $("#txt_from_address").val() == null ){						 
				map_status = false;
			}else{
				map_from = $("#txt_from_address").val() ;
			}
		}else if($("#from_type_id").val() == '8'){
			if($("#from_postcode").val() == '' || $("#from_postcode").val() == null ){
				map_status = false;
			}else{
				map_from = $("#from_postcode").val() ;
			}
		}

		if($("#to_type_id").val() == '7'){			
			if($("#txt_to_address").val() == '' || $("#txt_to_address").val() == null ){
				map_status = false;
			}else{
				map_to = $("#txt_to_address").val() ;
			}
		}else if($("#to_type_id").val() == '8'){
			if($("#to_postcode").val() == '' || $("#to_postcode").val() == null ){
				map_status = false;
			}
			else{
				map_to = $("#to_postcode").val() ;
			}
		}
		
		
		if(  (($("#from_type_id").val() == '7') || ($("#from_type_id").val() == '8')) &&  (($("#to_type_id").val() == '7') || ($("#to_type_id").val() == '8')) ){
			showMap(map_status,map_from,map_to);
		}
		
		
		if(($("#from_type_id").val() != '7') && ($("#from_type_id").val() != '8') && ($("#to_type_id").val() != '7') && ($("#to_type_id").val() != '8')){	
			$.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ loc_id:""+$("#from_loc_id").val(), vehicle_type: ""+$('input:radio[name="vehicle_type"]:checked').val()}, function(json){			
				if(json.status =='true'){
					if(json.postcode != '' && json.postcode != null){						
						map_from =json.postcode;
					}else{
						map_status = false;
					}
				}else{
					map_status = false;
				}
				
				$.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ loc_id:""+$("#to_loc_id").val(), vehicle_type: ""+$('input:radio[name="vehicle_type"]:checked').val()}, function(json){			
				if(json.status =='true'){
					if(json.postcode != '' && json.postcode != null){						
						map_to =json.postcode;
					}else{
						map_status = false;
					}
				}else{
					map_status = false;
				}	
				
				showMap(map_status,map_from,map_to);
			});

			});
		}else if(($("#from_type_id").val() != '7') && ($("#from_type_id").val() != '8')){
			$.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ loc_id:""+$("#from_loc_id").val(), vehicle_type: ""+$('input:radio[name="vehicle_type"]:checked').val()}, function(json){			
				if(json.status =='true'){
					if(json.postcode != '' && json.postcode != null){						
						map_from =json.postcode;
					}else{
						map_status = false;
					}
				}else{
					map_status = false;
				}
				
				showMap(map_status,map_from,map_to);
			});
		}else if(($("#to_type_id").val() != '7') && ($("#to_type_id").val() != '8')){	
			$.getJSON("../controller/calculate_fare_controller_forstationcars.php",{ loc_id:""+$("#to_loc_id").val(), vehicle_type: ""+$('input:radio[name="vehicle_type"]:checked').val()}, function(json){			
				if(json.status =='true'){
					if(json.postcode != '' && json.postcode != null){						
						map_to =json.postcode;
					}else{
						map_status = false;
					}
				}else{
					map_status = false;
				}
				
				showMap(map_status,map_from,map_to);
			});
		}
		
	});
	
	
	function showMap(map_status,map_from,map_to){
		if(map_status == false){
			$("#standerd_rate_error").html("<p class='error'>Map Showing Error</p>");
			$("#standerd_rate_error").show();
		}else{
			window.open('map.php?from='+map_from+'&to='+map_to+'','Mapwindow','width=1020,height=700,scrollbars=yes');
		}
	}
	
	
	
/*--Start Google Map with autocompletion textbox --*/
initialize();
  
$(function() { 
    $("#address").autocomplete({
      //This bit uses the geocoder to fetch address values
      source: function(request, response) {
        geocoder.geocode( {'address' : request.term+' UK'
 }, function(results, status) {
          response($.map(results, function(item) {
            return {
              label:  item.formatted_address,
              value: item.formatted_address,
              latitude: item.geometry.location.lat(),
              longitude: item.geometry.location.lng()
            }
          }));
        })
      },
      //This bit is executed upon selection of an address
      select: function(event, ui) {
        $("#latitude").val(ui.item.latitude);
        $("#longitude").val(ui.item.longitude);
        var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
        marker.setPosition(location);
        map.setCenter(location);
      }
    });
  });
	
  //Add listener to marker for reverse geocoding
  google.maps.event.addListener(marker, 'drag', function() {
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
          $('#address').val(results[0].formatted_address);
          $('#latitude').val(marker.getPosition().lat());
          $('#longitude').val(marker.getPosition().lng());
        }
      }
    });
  });
  

$(function() { 
    $("#txt_from_address").autocomplete({
      //This bit uses the geocoder to fetch address values
      source: function(request, response) {
        geocoder.geocode( {'address' : request.term+' UK'
 }, function(results, status) {
          response($.map(results, function(item) {
            return {
              label:  item.formatted_address,
              value: item.formatted_address,
              latitude: item.geometry.location.lat(),
              longitude: item.geometry.location.lng()
            }
          }));
        })
      },
      //This bit is executed upon selection of an address
      select: function(event, ui) {
        $("#latitude").val(ui.item.latitude);
        $("#longitude").val(ui.item.longitude);
        var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
        marker.setPosition(location);
        map.setCenter(location);
      }
    });
  });
	
  //Add listener to marker for reverse geocoding
  google.maps.event.addListener(marker, 'drag', function() {
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
          $('#txt_from_address').val(results[0].formatted_address);
          $('#latitude').val(marker.getPosition().lat());
          $('#longitude').val(marker.getPosition().lng());
        }
      }
    });
  });
  
  
$(function() { 
    $("#txt_to_address").autocomplete({
      //This bit uses the geocoder to fetch address values
      source: function(request, response) {
        geocoder.geocode( {'address' : request.term+' UK'
 }, function(results, status) {
          response($.map(results, function(item) {
            return {
              label:  item.formatted_address,
              value: item.formatted_address,
              latitude: item.geometry.location.lat(),
              longitude: item.geometry.location.lng()
            }
          }));
        })
      },
      //This bit is executed upon selection of an address
      select: function(event, ui) {
        $("#latitude").val(ui.item.latitude);
        $("#longitude").val(ui.item.longitude);
        var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
        marker.setPosition(location);
        map.setCenter(location);
      }
    });
  });
	
  //Add listener to marker for reverse geocoding
  google.maps.event.addListener(marker, 'drag', function() {
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
          $('#txt_to_address').val(results[0].formatted_address);
          $('#latitude').val(marker.getPosition().lat());
          $('#longitude').val(marker.getPosition().lng());
        }
      }
    });
  });
/*--End Google Map with autocompletion textbox --*/
	


/*--Start Popup with jquery --*/

//CONTROLLING EVENTS IN jQuery
$("#from_map_icon").click(function(){
	centerPopup();
	loadPopup();
	textbox_to_write = 'from';
	initialize();
});
		
$("#to_map_icon").click(function(){
	centerPopup();
	loadPopup();
	textbox_to_write = 'to';
	initialize();
});

//CLOSING POPUP
//Click the x event!
$("#popupContactClose").click(function(){
	disablePopup();
});

//Click out event!
$("#backgroundPopup").click(function(){
	disablePopup();
});

//Press Escape event!
$(document).keypress(function(e){
	if(e.keyCode==27 && popupStatus==1){
		disablePopup();
	}
});
	
/*--End Popup with jquery--*/	
	
	
	
});



/*--Google Map--*/
function initialize(){
  var latlng = new google.maps.LatLng(41.659,-4.714);
  var options = {
    zoom: 16,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };
        
  map = new google.maps.Map(document.getElementById("map_canvas"), options);
  geocoder = new google.maps.Geocoder();
  marker = new google.maps.Marker({
    map: map,
    draggable: true
  });			
}

/* POPUP  */

//loading popup with jQuery magic!
function loadPopup(){
	//loads popup only if it is disabled
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("slow");
		$("#popupContact").fadeIn("slow");
		popupStatus = 1;

		//selectAddress();
	}
}

function selectAddress(){
	if(textbox_to_write=='from'){
		document.getElementById('txt_from_address').innerHTML = document.getElementById('address').value;
	}else if (textbox_to_write=='to'){
		document.getElementById('txt_to_address').innerHTML = document.getElementById('address').value;
	}else{
		//document.getElementById('lbladdress').innerHTML = document.getElementById('address').value;
	}
	disablePopup();
}

//disabling popup with jQuery magic!
function disablePopup(){
	//disables popup only if it is enabled
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("slow");
		$("#popupContact").fadeOut("slow");
		popupStatus = 0;
	}
}

//centering popup
function centerPopup(){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupContact").height();
	var popupWidth = $("#popupContact").width();
	//centering
	$("#popupContact").css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	
	$("#backgroundPopup").css({
		"height": windowHeight
	});
}

function load_from_boxes(obj){
	
		if(obj=='8'){
			$("#from_loc_id").hide();
			$("#txt_from_address").hide();
			$("#from_postcode").show();
			$("#from_door_no_tr").show();
			$("#from_map_icon").hide();
			$("#from_details_tr").hide();
		}else if(obj=='7'){
			$("#from_loc_id").hide();
			$("#txt_from_address").show();
			$("#from_postcode").hide();
			$("#from_door_no_tr").hide();
			$("#from_map_icon").show();
			$("#from_details_tr").hide();
		}else{
			if(obj=='1'){
				$("#from_details_tr").show();
			}else{
				$("#from_details_tr").hide();
			}
			$("#from_loc_id").show();
			$("#txt_from_address").hide();
			$("#from_postcode").hide();			
			//get_location(obj,"#from_loc_id");
			$("#from_door_no_tr").hide();			
			$("#from_map_icon").hide();
		}

		$("#standerd_rate_error").hide();
}
function load_to_boxes(obj){
	
		if(obj=='8'){
			$("#to_loc_id").hide();
			$("#txt_to_address").hide();
			$("#to_postcode").show();
			$("#to_door_no_tr").show();
			$("#to_map_icon").hide();
		}else if(obj=='7'){
			$("#to_loc_id").hide();
			$("#txt_to_address").show();
			$("#to_postcode").hide();
			$("#to_door_no_tr").hide();
			$("#to_map_icon").show();
		}else{
			$("#to_loc_id").show();
			$("#txt_to_address").hide();
			$("#to_postcode").hide();	
			//get_location2(obj,"#to_loc_id");
			$("#to_door_no_tr").hide();
			$("#to_map_icon").hide();
		}	
		$("#standerd_rate_error").hide();
}


//-- new function for station cars pass prices into car images --//
function showcarsprice(fareobject){
	$("#pricecarsdiv").css({"display": "block"});
	$("#divmaincontent").css({"display": "none"});
	$("#carpricediv1").html("<p class=''>10</p>");
	$("#carpricediv2").html("<p class=''>12</p>");
	$("#carpricediv3").html("<p class=''>13</p>");
	
}

function show_progress(){
					$("#standerd_rate_error").html("<p class='error'>Calculating fare please wait......</p>");
					$("#standerd_rate_error").show();
	$("#carpricediv"+1).html("");
	$("#carpricediv"+2).html("");
	$("#carpricediv"+3).html("");
	//-reest values --//
	for(aa=1;aa<=3;aa++){
	document.getElementById('from_type_id'+aa).value = "";
	document.getElementById('from_loc_id'+aa).value = "";
	document.getElementById('txt_from_address'+aa).value = "";
	document.getElementById('from_postcode'+aa).value = "";
	document.getElementById('to_type_id'+aa).value = "";
	document.getElementById('to_loc_id'+aa).value = "";
	document.getElementById('txt_to_address'+aa).value = "";
	document.getElementById('to_postcode'+aa).value = "";
	document.getElementById('journy_fare'+aa).value = "";
	}	
}
function hide_progress(){
					$("#standerd_rate_error").html("");
					$("#standerd_rate_error").hide();
	$("#pricecarsdiv").css({"display": "block"});
	$("#divmaincontent").css({"display": "none"});
	$("#carpricediv"+1).html("<p class=''>Call Us</p>");
	$("#carpricediv"+2).html("<p class=''>Call Us</p>");
	$("#carpricediv"+3).html("<p class=''>Call Us</p>");
	for(aa=1;aa<=3;aa++){
	document.getElementById('from_type_id'+aa).value = document.getElementById('from_type_id').value;
	document.getElementById('from_loc_id'+aa).value = document.getElementById('from_loc_id').value;
	document.getElementById('txt_from_address'+aa).value = document.getElementById('txt_from_address').value;
	document.getElementById('from_postcode'+aa).value = document.getElementById('from_postcode').value;
	document.getElementById('to_type_id'+aa).value = document.getElementById('to_type_id').value;
	document.getElementById('to_loc_id'+aa).value = document.getElementById('to_loc_id').value;
	document.getElementById('txt_to_address'+aa).value = document.getElementById('txt_to_address').value;
	document.getElementById('to_postcode'+aa).value = document.getElementById('to_postcode').value;
	}	
	
}

function showpriceincarbox(carefare,vnumber){
	//alert("#carpricediv"+vnumber);
	if(carefare=="NA"){
	$("#carpricediv"+vnumber).html("<p class=''>Call Us</p>");
	}else{
	$("#carpricediv"+vnumber).html("<p class=''>\u00A3"+carefare+"</p>");
	document.getElementById('journy_fare'+vnumber).value = carefare;
	}
}


