// 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_map_icon").hide();
	$("#to_map_icon").hide();
	
	$('input:radio[name="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();
		}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();
		}else{
			$("#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();
	});
	
	$('input:radio[name="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(){
		get_fare();
	});
	
	
	function get_fare(){									  
		if($('input:radio[name="from_type_id"]:checked').val() != '7' && $('input:radio[name="from_type_id"]:checked').val() != '8' && $('input:radio[name="to_type_id"]:checked').val() != '7' && $('input:radio[name="to_type_id"]:checked').val() != '8'){
				$.getJSON("../controller/calculate_fare_controller.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);
						$("#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,json.to_postcode,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($('input:radio[name="from_type_id"]:checked').val() == '7' && $('input:radio[name="to_type_id"]:checked').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("#txt_from_address","#txt_to_address");
				$("#standerd_rate_error").show();
				$("#validation_message").hide();
			}
				
		}
		
		//Both are PostalCode	
		else if($('input:radio[name="from_type_id"]:checked').val() == '8' && $('input:radio[name="to_type_id"]:checked').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("#from_postcode","#to_postcode");
				$("#standerd_rate_error").show();
				$("#validation_message").hide();
			}
		}
		
		//From-PostalCode To - Address/DDL
		else if($('input:radio[name="from_type_id"]:checked').val() == '8'){
			//To - DDL
			if($('input:radio[name="to_type_id"]:checked').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");
				}
			//To - Address
			}else{
				if(checking_for_empty("#from_postcode","Enter Postcode First","#txt_to_address","Enter Address Second")){
					calculate_fare("#from_postcode","#txt_to_address");
				}
			}	
		}
		//From - Address  To - PostalCode/DDL
		else if($('input:radio[name="from_type_id"]:checked').val() == '7'){
			if($('input:radio[name="to_type_id"]:checked').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");
				}
			}else{
				if(checking_for_empty("#txt_from_address","Enter Address First","#to_postcode","Enter Postcode Second")){
					calculate_fare("#txt_from_address","#to_postcode");
				}
			}
		}
		//To-PostalCode From - Address/DDL
		else if($('input:radio[name="to_type_id"]:checked').val() == '8'){
			if($('input:radio[name="from_type_id"]:checked').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");
				}
			}else{
				if(checking_for_empty("#txt_from_address","Enter Address First","#to_postcode","Enter Postcode Second")){
					calculate_fare("#txt_from_address","#to_postcode");
				}
			}
		}
		//To-Address From - PostalCode/DDL
		else if($('input:radio[name="to_type_id"]:checked').val() == '7'){
			if($('input:radio[name="from_type_id"]:checked').val() != '8'){
				if(checking_for_empty("#from_loc_id","Select Location First","#txt_to_address","Enter Address Second")){
					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("#from_postcode","#txt_to_address");
				}
			}
		}
	}	
	
	
	function calculate_fare(from,to){
		$.getJSON("../controller/calculate_fare_controller.php",{ loc_id:"1", vehicle_type: ""+$('input:radio[name="vehicle_type"]:checked').val()}, function(json){			
			if(json.vc_status =='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.php",{ loc_id:""+$(loc2).val(), vehicle_type: ""+$('input:radio[name="vehicle_type"]:checked').val()}, 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>");	
			}
		});
	}
	
	
	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",'');
			$(field2).css("background",'');
			return true;
		}else{
			$("#validation_message").html("");

			if($(field1).val() =='' || $(field1).val() ==null){
				$("#validation_message").html(msg1);
				$(field1).css("background","#FA8080");
			}else{
				$(field1).css("background",'');
			}
			
			if($(field2).val() =='' || $(field2).val() ==null){
				$("#validation_message").html($("#validation_message").html()+'<BR/>'+msg2);
				$(field2).css("background","#FA8080");
			}
			else{
				$(field2).css("background",'');
			}
			
			$("#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;
			$("#journy_fare").val(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>");			
		}
		});
	}
	
	$("#show_map").click(function(){								 
		var map_status = true;
		var map_from = '';
		var map_to = '';
		
		if($('input:radio[name="from_type_id"]:checked').val() == '7'){
			if($("#txt_from_address").val() == '' || $("#txt_from_address").val() == null ){						 
				map_status = false;
			}else{
				map_from = $("#txt_from_address").val() ;
			}
		}else if($('input:radio[name="from_type_id"]:checked').val() == '8'){
			if($("#from_postcode").val() == '' || $("#from_postcode").val() == null ){
				map_status = false;
			}else{
				map_from = $("#from_postcode").val() ;
			}
		}

		if($('input:radio[name="to_type_id"]:checked').val() == '7'){			
			if($("#txt_to_address").val() == '' || $("#txt_to_address").val() == null ){
				map_status = false;
			}else{
				map_to = $("#txt_to_address").val() ;
			}
		}else if($('input:radio[name="to_type_id"]:checked').val() == '8'){
			if($("#to_postcode").val() == '' || $("#to_postcode").val() == null ){
				map_status = false;
			}
			else{
				map_to = $("#to_postcode").val() ;
			}
		}
		
		
		if(  (($('input:radio[name="from_type_id"]:checked').val() == '7') || ($('input:radio[name="from_type_id"]:checked').val() == '8')) &&  (($('input:radio[name="to_type_id"]:checked').val() == '7') || ($('input:radio[name="to_type_id"]:checked').val() == '8')) ){
			showMap(map_status,map_from,map_to);
		}
		
		
		if(($('input:radio[name="from_type_id"]:checked').val() != '7') && ($('input:radio[name="from_type_id"]:checked').val() != '8') && ($('input:radio[name="to_type_id"]:checked').val() != '7') && ($('input:radio[name="to_type_id"]:checked').val() != '8')){	
			$.getJSON("../controller/calculate_fare_controller.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.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(($('input:radio[name="from_type_id"]:checked').val() != '7') && ($('input:radio[name="from_type_id"]:checked').val() != '8')){
			$.getJSON("../controller/calculate_fare_controller.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(($('input:radio[name="to_type_id"]:checked').val() != '7') && ($('input:radio[name="to_type_id"]:checked').val() != '8')){	
			$.getJSON("../controller/calculate_fare_controller.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
	});
}



