var selectionSize = 5; //size of result for addresses combo box - provided by google
var minim_chars_addr = 1; //minimum letters in google box for the map to start search
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var currency_symbole = '';
var price = 0;
var Addr_town = '';
var Addr_coun = '';
var mile_km = '2';//km as default
var car_rate_1 = 0;
var car_rate_2 = 0;
var car_rate_3 = 0;
var car_rate_4 = 0;
var minimum_charge =0;
var minimum_distance =0;
var minimum_unit = 'm';
var every_charge =0;
var every_distance =0;
var every_unit = 'km';
var SelectOption = '';
var coverage_area = 0;
var coverage_not_msg = '';
var coverage_not_sure_msg = '';
var office_location = '';
var search_city_restriction = '1';
var area_covered_check = '0';
document.onclick=check; 
function initialize() {
    geocoder = new google.maps.Geocoder();    
    directionsService = new google.maps.DirectionsService();
    
    var heathrow  = new google.maps.LatLng(51.470280, -0.397757);
	var officeii  = new google.maps.LatLng(51.470280, -0.397757);

    var myOptions = {
      zoom: 10,
      controls: true,
      streetViewControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: officeii
    }  
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    // Create a renderer for directions and bind it to the map.
    var rendererOptions = {
      map: map
    }
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
 
    /* journey details ; create a div with id="directionsPanel" 
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    */
   
    // Instantiate an info window to hold step text.
    stepDisplay = new google.maps.InfoWindow();

}
     
function calcRoute(start,end){
    document.getElementById("loading").style.display='block';     
    for (i = 0; i < markerArray.length; i++){
      markerArray[i].setMap(null);
    }
    markerArray = [];
    // a DirectionsRequest using DRIVING directions.
    if(start == ""){ 
        start = document.getElementById("map_from").value
        if(search_city_restriction == '1')
            start = atart + ","+Addr_town;
        start = start +","+Addr_coun;
    }
    if(end == ""){
        end = document.getElementById("map_to").value 
        if(search_city_restriction == '1')        
            end = end + ","+Addr_town;
        end = end+","+Addr_coun;  
    } 

    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    // Route the directions and pass the response to a
    // function to create markers for each step.
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            //  var warnings = document.getElementById("warnings_panel");
            //  warnings.innerHTML = "<b>" + response.routes[0].warnings + "</b>";
            directionsDisplay.setDirections(response);
        	var myRoute = response.routes[0].legs[0];
        	var distance = 0;
        	var duration = 0;    
        	for (i = 0; i < myRoute.steps.length; i++){
                     distance = distance + myRoute.steps[i].distance.value;
                     duration = duration + myRoute.steps[i].duration.value;                
                }              
            price = getPrice(distance);  
            duration = duration / 60;
            if (mile_km == '1')
                distance = (((distance * 100/2.5) / 12) / 3 )/ 1760;
            else
                distance = distance / 1000;
            try{                 
               if (mile_km == '1')
                    document.getElementById("distance").innerHTML="Distance: "+distance.toFixed(2)+" miles";
                else
                    document.getElementById("distance").innerHTML="Distance: "+distance.toFixed(2)+" km";                   
				document.getElementById("duration").innerHTML="Duration: "+duration.toFixed(0)+" minutes";
                document.getElementById("g_price").innerHTML = currency_symbole + price.toFixed(2);
            } 
            catch(ex)
            {
                if (mile_km == '1')
                    document.getElementById("distance").innerHTML="Distance: "+ Math.round(distance * 100)/100+" miles";
                else
                    document.getElementById("distance").innerHTML="Distance: "+Math.round(distance * 100)/100+" km";          
                document.getElementById("duration").innerHTML="Duration: "+Math.round(duration) + "minutes";	
                document.getElementById("g_price").innerHTML = currency_symbole + " "+ Math.round(price * 100) / 100 +" ";                               
            }
            
			var res = 'true';
            if(area_covered_check == '1')
                res = withinPicUpArea(start);
			if(res == 'true'){
				document.getElementById("div_reserve_g").style.display='block';
				document.getElementById("distance").style.display = 'block';
				document.getElementById("duration").style.display = 'block';
				document.getElementById("g_price").style.display = 'block'; 
			}                    
                                          
    	   //Show marker in each step
    	   //showSteps(response);
        }
    });
    document.getElementById("loading").style.display='none';  
 }

function showSteps(directionResult) {
    // For each step, place a marker, and add the text to the marker's
    // info window. Also attach the marker to an array so we
    // can keep track of it and remove it when calculating new routes.
    var myRoute = directionResult.routes[0].legs[0];
 
    for (var i = 0; i < myRoute.steps.length; i++) {
        var marker = new google.maps.Marker({
            position: myRoute.steps[i].start_point, 
            map: map
        });
    attachInstructionText(marker, myRoute.steps[i].instructions);
    markerArray[i] = marker;
    }
}

function attachInstructionText(marker, text){
    google.maps.event.addListener(marker, 'click', function() {
        // Open an info window when the marker is clicked on,
        // containing the text of the step.
        stepDisplay.setContent(text);
        stepDisplay.open(map, marker);
    });
}

function withinPicUpArea(address_f){
    //- If covers all town -//
    if(coverage_area == 0 || office_location == "")    
        return 'true';   

    var off_distance = -1;

    for (i = 0; i < markerArray.length; i++){
      markerArray[i].setMap(null);
    }
    markerArray = []; 

    var request = {
        origin: address_f,
        destination: office_location,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {    
        	var myRoute = response.routes[0].legs[0];
                off_distance = 0;
        	for (i = 0; i < myRoute.steps.length; i++)
                    off_distance = off_distance + myRoute.steps[i].distance.value;
                if( off_distance > coverage_area || off_distance == -1){
                    document.getElementById("distance").style.display = 'none';
                    document.getElementById("duration").style.display = 'none';
                    document.getElementById("g_price").style.display = 'none';                                         
                    if(document.getElementById("suggestions_from_div").style.display == 'none')
                        alert(coverage_not_msg);                    
                    document.getElementById("div_reserve_g").style.display='none';       
                    return 'false';
                }
        }
    });
    return 'true';    
}

function getOptions(){
//    getMapSuggestion(0);
//    getMapSuggestion(1); 

    var address_f = document.getElementById("map_from");
    var address_t = document.getElementById("map_to");

    if(address_f.value.length < minim_chars_addr || address_t.value.length < minim_chars_addr) 
        return; 
    calcRoute(address_f.value,address_t.value); 
}

function selectSuggest(from_to){
	var elSel;
	var address;
    googleFromFound = false;
    googleToFound = false;
	if(from_to == 'from'){
		elSel = document.getElementById('suggest_from');
		document.getElementById('suggestions_from_div').style.display = 'none'; 
		address = document.getElementById("map_from");
	}
	if(from_to == 'to'){
		elSel = document.getElementById('suggest_to');
		document.getElementById('suggestions_to_div').style.display = 'none';
		address = document.getElementById("map_to");
	}
    var elOptOld = elSel.options[elSel.selectedIndex];
    
    if(from_to == 'from')
        document.getElementById("map_from").value = elOptOld.value; 
    if(from_to == 'to')
        document.getElementById("map_to").value = elOptOld.value; 
}

function getPrice(d){
    var extra_dis = 0;
    var minimum_dis = minimum_distance;
    var every_dis = every_distance;
    price = minimum_charge;  
    if(mile_km == '2'){//metric
        if(minimum_unit == 'km')
           minimum_dis = minimum_dis * 1000;
        if(d <= minimum_dis)
            return price;
       if(every_unit == 'km')
            every_dis = every_dis * 1000; 
			
        extra_dis = d - minimum_dis;
		price += (extra_dis / every_dis) * every_charge;
    }
    if(mile_km == '1'){//imperial
        //convert it from m to yard
        d = ((d * 100/2.5) / 12) / 3 ;
        if(minimum_unit == 'mi'){
           minimum_dis = minimum_dis * 1760;
        }
        if(d <= minimum_dis){
            price = minimum_charge;
            return price;
        }
        if(every_unit == 'mi')
            every_dis = every_dis * 1760;  
        extra_dis = d - minimum_dis;
        price = price + (extra_dis / every_dis) * every_charge;        
    }  
    var ctype = 1;
    for (i=0; i<document.form_show_booking.cartype.length ; i ++) 
        if (document.form_show_booking.cartype[i].checked) {
           ctype = document.form_show_booking.cartype[i].value; break;
        }
    if(ctype == '1')price = price + (price * car_rate_1)/100;
    if(ctype == '2')price = price + (price * car_rate_2)/100;
    if(ctype == '3')price = price + (price * car_rate_3)/100;
    if(ctype == '4')price = price + (price * car_rate_4)/100;    
    return Math.round(price * 100) / 100 ;
}

function form_changed(f)
{
    if(f == 'form_from'){
        document.form_from.gto.value = document.form_to.gto.value;
        document.form_from.lto.value = document.form_to.lto.value;
        document.form_from.submit();     
    }
    if(f == 'form_to'){
        document.form_to.gfrom.value = document.form_from.gfrom.value;
        document.form_to.lfrom.value = document.form_from.lfrom.value;  
        document.form_to.submit();                 
    }
}

function form_check_submit(){
        if(document.form_from.lfrom.value == -1 || document.form_to.lto.value == -1){
        alert(__('Choose direction please'));
        return;
    }   
    document.form_check_cost.gto.value = document.form_to.gto.value;
    document.form_check_cost.lto.value = document.form_to.lto.value;        
    document.form_check_cost.gfrom.value = document.form_from.gfrom.value;
    document.form_check_cost.lfrom.value = document.form_from.lfrom.value;              
    document.form_check_cost.submit();
}

function get_cookie(s){
    var ss = "";
    var cookies = document.cookie.split("; ");
    try{
        for(i=0;i<cookies.length;i++){
            var keyval=cookies[i].split("=");
            if(keyval[0] == s){
                ss = keyval[1];
                break;
            }   
        }
    }
    catch(ex){;        
    }
    return ss;
}

function getMapSuggestion(fromTo){ 
    document.getElementById("loading").style.display='block'; 
 
    var dir = "from";
    if(fromTo == 1)
        dir = "to";
     
    var box;
    var combo;
    var selectiondiv; 
    if(dir == "from"){
        box = document.getElementById("map_from");                      
        combo = document.getElementById("suggest_from");
        selectiondiv = document.getElementById("suggestions_from_div");        
    }     
    if(dir == "to"){
        box = document.getElementById("map_to");  
        combo = document.getElementById("suggest_to");
        selectiondiv = document.getElementById("suggestions_to_div");                
    }     
    var location = box.value;
    if(location.length < minim_chars_addr)
    {
        document.getElementById("loading").style.display='none';
        return false;
    }        
    if(location.search(Addr_town) == -1 && search_city_restriction == '1')
		location = location + " "+Addr_town;
    location = location+" "+Addr_coun;

    combo.options.length = 0; 
    if (geocoder) {
      geocoder.geocode( { 'address': location}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
//            if(results.length == 1){
//                box.value = results[0].formatted_address;            
//            }
			if(results.length > 0){
                selectiondiv.style.display='block';
				combo.options.length = 0;
   				for(i=-1;i < results.length;i++){				    
					var elOptNew = document.createElement('option');
                    var thetext;  
                    if(i==-1)
                        thetext = SelectOption;
                    else
                        thetext = results[i].formatted_address;
                    elOptNew.text = thetext;
   					elOptNew.value = thetext; 
					try {
					  combo.add(elOptNew, null);//elOptOld); // standards compliant; doesn't work in IE
					}
					catch(ex) {//alert(elOptNew.text);
					  combo.add(elOptNew);//, combo.selectedIndex); // IE only
					}
				}
			}
        }
      });
    }   
    combo.size = selectionSize;
//    combo.size = (combo.options.length > selectionSize)? selectionSize : combo.options.length ;
  
    /* set cookie */
    var expiry ="Friday, 02-Jul-10 12:00:00 GMT";
    document.cookie="map_from="+document.getElementById("map_from").value+";expires="+expiry;
    document.cookie="map_to="+document.getElementById("map_to").value+";expires="+expiry;     
    document.getElementById("loading").style.display='none';  
}

function showBooking(book){
     if(book == "goog"){
        document.form_show_booking.addr_from.value = document.getElementById("map_from").value;  
        document.form_show_booking.addr_to.value = document.getElementById("map_to").value;
        document.form_show_booking.phone.value = get_cookie('phone');    
        document.form_show_booking.door_num.value = get_cookie('door_num');    
        document.form_show_booking.price.value = price;                   
        document.form_show_booking.submit();  
    }
    if(book == "own"){    
        var own_from = document.getElementById("from_select_own");   
        var own_to = document.getElementById("to_select_own");  
        document.form_show_booking_own.addr_from.value = own_from.options[own_from.selectedIndex].text;   
        document.form_show_booking_own.addr_to.value = own_to.options[own_to.selectedIndex].text; 
        document.form_show_booking_own.phone.value = get_cookie('phone');    
        document.form_show_booking_own.door_num.value = get_cookie('door_num');    
        document.form_show_booking_own.price.value = document.getElementById("id_div_cost").innerHTML; 
        var ct=1;
        for(i=1; i<= document.form_check_cost.cartype.length;i++){
            if(document.form_check_cost.cartype[i-1].checked){
                ct = document.form_check_cost.cartype[i-1].value;
                break;
            }
        }    
        
        document.form_show_booking_own.cartype.value = ct;                     
        document.form_show_booking_own.submit();  
    }   
} 

function check(e){ 
	var target = (e && e.target) || (event && event.srcElement); 
	var obj = document.getElementById('suggestions_from_div'); 
	var obj2 = document.getElementById('suggestions_to_div'); 
	obj.style.display='none'; 
	obj2.style.display='none'; 
} 

