//RigaTaxi Api Key
//http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAif6n_myOal6C0wShHBisJBQQvVNWmxT9_8jCzYL2dmWpsj_XfRRX2FYnAVemMHwuoLbewup8ncl2Vw

	var map;
    var gdir;
	var pointsArray = new Array(); 
	var countPoint = 1;
	var bool=true;
	var geo;
	var nameCode="LV";

    function initialize() {
      if (GBrowserIsCompatible()) { 
		
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
		geo = new GClientGeocoder(); 
		
        GEvent.addListener(gdir, "load", function(){
			var distance = gdir.getDistance().meters/1000;	//distance in KM
			var time = gdir.getDuration().seconds;
			getPrices(distance,time);
		});
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl3D());	//Zoom Menu
		map.addControl(new GMapTypeControl());	//Creates a standard map type control for selecting and switching between supported map types via buttons.
		GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay);
		GEvent.addListener(gdir, "error", handleErrors);
		
		GEvent.addListener(map,"singlerightclick", function(point,b,overlay) { 
        if (overlay) { 
          if (overlay instanceof GMarker) { 
			for (var i=1; i<countPoint; i++){
      			if (overlay.getTitle()==varExtraPoint + " "+String.fromCharCode(i+65) && bool==true){
					map.removeOverlay(overlay);
					pointsArray.splice(i,1);
					countPoint--;
					gdir.loadFromWaypoints(pointsArray);
				}
      		}
          } 
        } 
		else {
			var latlng = map.fromContainerPixelToLatLng(point); 
			addDirection(latlng);
		}
      }); 

        setDirections("1 Dzirnavu iela, Rīga 1010, Latvija", "350 Brīvības gatve, Rīga 1006, Latvija");
      }
    }
    
    function setDirections(fromAddress, toAddress) {	//From -> to direction markers
		pointsArray[0] = fromAddress;
		pointsArray[countPoint] = toAddress;
		gdir.loadFromWaypoints(pointsArray); 
    }
	
	function addDirection(newDirection){	//Add new Marker for direction
		pointsArray[countPoint+1] = pointsArray[countPoint];
		pointsArray[countPoint] = newDirection;
		countPoint++;
		gdir.loadFromWaypoints(pointsArray); 
	}
	
	function backDirection() {
		temp = pointsArray[0];	//temp var
		pointsArray[0] = pointsArray[countPoint];
		pointsArray[countPoint] = temp;
		gdir.loadFromWaypoints(pointsArray); 
    }
	
	function price2ways(){
		if (bool==false){	//If price 2 ways href not pressed
			countPoint--;
			pointsArray.splice(countPoint+1,1);	
			document.getElementById("fromAddress").disabled=false;
			document.getElementById("toAddress").disabled=false;
			document.getElementById("submit1").disabled=false;
			document.getElementById('backDirection').style.visibility = 'visible'; 
			document.getElementById('removeExtraPoints').style.visibility = 'visible'; 
			document.getElementById('hint').style.visibility = 'visible';
			document.getElementById('menuBackDirection').disabled = false; 
			document.getElementById('menuRemoveExtraPoints').disabled = false; 
		}
		if (bool==true){	//If price 2 ways is pressed
			countPoint++;
			pointsArray[countPoint] = pointsArray[0];
			document.getElementById("fromAddress").disabled=true;
			document.getElementById("toAddress").disabled=true;
			document.getElementById("submit1").disabled=true;
			document.getElementById('backDirection').style.visibility = 'hidden'; 
			document.getElementById('removeExtraPoints').style.visibility = 'hidden'; 
			document.getElementById('hint').style.visibility = 'hidden'; 
			document.getElementById('menuBackDirection').disabled = true; 
			document.getElementById('menuRemoveExtraPoints').disabled = true; 
		}
		gdir.loadFromWaypoints(pointsArray); 
		bool = !bool;
	}
	
	function removeExtraPoints(){//Remove all points except start point and end point
		if (countPoint>1){
			pointsArray[1]=pointsArray[countPoint];
			for (var i=countPoint; i>=2; i--)
				pointsArray.splice(i,1);	
			countPoint=1;
			gdir.loadFromWaypoints(pointsArray); 
		}
	}
	
	function getPrices(distance,time){
		distance=distance+(distance * distance_percents / 100);
		var normalTimePrice = (time*normal_price_per_hour/3600) + ((time*normal_price_per_hour/3600)*normal_percents_per_hour/100);			// (time * ls/h) + %
		var koorporativeTimePrice = (time*koorporative_price_per_hour/3600) + ((time*koorporative_price_per_hour/3600)*koorporative_percents_per_hour/100);	// (time * ls/h) + %
		
		var normalPrice = normal_seat_cost_price + normalTimePrice + (normal_price_per_km * distance);
		var koorporativePrice = koorporative_seat_cost_price + koorporativeTimePrice + (koorporative_price_per_km * distance);
		var timeShow, timeName;
		
		if (time>0 && time<60){
			timeShow = time;
			timeName = varSec;
		}
		else if (time>60 && time<3600){
			timeShow = time/60;
			timeName = varMin;
		}
		else if (time>3600){
			timeShow = time/3600;
			timeName = varHours;
		}
		timeShow=timeShow+(timeShow*10/100);
		
		document.getElementById("Distance").innerHTML = (varDistance + distance.toFixed(2) + " Km ("+ timeShow.toFixed(2) +" "+ timeName +")");
		document.getElementById("KoorpPrice").innerHTML = ("<nobr>" + varKoorpText + koorporativePrice.toFixed(2) + " Ls</nobr>");
		document.getElementById("NormalPrice").innerHTML = (varNormalText + normalPrice.toFixed(2) + " Ls");
	}
	
    function addressHints(search,where) {//-------------------------------------------------adress hints----------------------------------------------------
        // ====== Perform the Geocoding ======   
        geo.getLocations(search, function (result)
          {
            if (result.Status.code == G_GEO_SUCCESS) {
              // ===== If there was more than one result, "ask did you mean" on them all =====
              if (result.Placemark.length > 1) { 
                // Loop through the results
				var empty=0;
				
				document.getElementById("hint").innerHTML = "[<a onclick='changeLocation(\""+search+"\",\""+where+"\")' title=\""+varAllHintTitle+"\" onmouseover=\"this.style.cursor='pointer'\">"+varAllHintText+"</a>]";
				
				document.getElementById("menuHint").innerHTML = "<button id='menuHintButton' style='width:150px' onclick='changeLocation(\""+search+"\",\""+where+"\")' title=\""+varAllHintTitle+"\">"+varAllHintText+"</a>";
				
                for (var i=0; i<result.Placemark.length; i++) {
				  var address = result.Placemark[i].address;  
				  var addressLat = result.Placemark[i].Point.coordinates[1];
                  var addressLon = result.Placemark[i].Point.coordinates[0];
				  var addressLatLon = addressLat+","+addressLon;
				  
				  if (addressLat == 56.9221227 & addressLon == 23.9793629)
					  address = "Rīgas Lidosta";
				  
				  if (nameCode=="LV"){
					  if (result.Placemark[i].AddressDetails.Country.CountryNameCode=='LV'){
						  empty++;
						  if (empty==1) 
	document.getElementById("hint").innerHTML = varRecAddress+" [<a onclick='changeLocation(\""+search+"\",\""+where+"\")' title=\""+varAllHintTitle+"\" onmouseover=\"this.style.cursor='pointer'\">"+varAllHintText+"</a>]:";
	document.getElementById("menuHint").innerHTML = "<button id='menuHintButton' style='width:150px' onclick='changeLocation(\""+search+"\",\""+where+"\")' title=\""+varAllHintTitle+"\">"+varAllHintText+"</a>";
	document.getElementById("hint").innerHTML += "<br><a onclick='hintClick(\""+addressLatLon+"\",\""+address+"\",\""+where+"\")' onmouseover=\"this.style.cursor='pointer'\">"+address+"</a>";
					  }
				  }
				  else {
						  empty++;
						  if (empty==1)
	document.getElementById("hint").innerHTML = varRecAddress+" [<a onclick='changeLocation(\""+search+"\",\""+where+"\")' title=\""+varLvHintTitle+"\" onmouseover=\"this.style.cursor='pointer'\">"+varLvHintText+"</a>]:";
	document.getElementById("menuHint").innerHTML = "<button id='menuHintButton' style='width:150px' onclick='changeLocation(\""+search+"\",\""+where+"\")' title=\""+varLvHintTitle+"\">"+varLvHintText+"</a>";
	document.getElementById("hint").innerHTML += "<br><a onclick='hintClick(\""+addressLatLon+"\",\""+address+"\",\""+where+"\")' onmouseover=\"this.style.cursor='pointer'\">"+address+"</a>";  
				  }
                }
              }
            }
          }
        );
    }
	
	function changeLocation(search,where){
		changeNameCode(); 
		document.getElementById("hint").innerHTML = "";
		addressHints(search,where);
	}
	
	function changeNameCode(){
		if (nameCode=="LV") nameCode="";
		else nameCode="LV";
	}
	
	function hintClick(point,address,where){
		addressToForm(address,where);
		if (where=='fromAddress')
		setDirections(point,pointsArray[countPoint]);
		else setDirections(pointsArray[0],point);
	}
	
	function addressToForm(address,where){
 
		document.getElementById(where).value=address; 
		document.getElementById("hintMenu").removeChild(document.getElementById("hint"));
		
		var div = document.createElement("div");
	  	div.id ="hint";
	  	document.getElementById("hintMenu").appendChild(div);
	}
					//--------------------------------------------------------adress hints End-------------------------------------------------------------
var newMarkers = [];
var latLngs = [];
var icons = [];
	
function onGDirectionsAddOverlay(){ 	//--------------------------Dragable markers-------------------------------------
  // Remove the draggable markers from previous function call.
  for (var i=0; i<newMarkers.length; i++){
    map.removeOverlay(newMarkers[i]);
  }
 
  // Loop through the markers and create draggable copies
  for (var i=0; i<=countPoint; i++){
    var originalMarker = gdir.getMarker(i);
    latLngs[i] = originalMarker.getLatLng();
    icons[i] = originalMarker.getIcon();
	if (i==0){
    	newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:varStart});
	}
	if (i==gdir.getNumRoutes()){
		newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:varEnd});
	}
	if (i>0 && i<gdir.getNumRoutes()){
		newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:varExtraPoint + ' '+String.fromCharCode(i+65)});
	}
    map.addOverlay(newMarkers[i]);
 
    // Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
	if (i==0)
		GEvent.addListener(newMarkers[i], "dragend", function(){
		  for (var i=0; i<=countPoint; i++){
			pointsArray[i]= newMarkers[i].getLatLng();
		  }
		  document.getElementById("fromAddress").value = varMarkerPosChange;
		  gdir.loadFromWaypoints(pointsArray);
		});
	else if (i==gdir.getNumRoutes())
		GEvent.addListener(newMarkers[i], "dragend", function(){
		  for (var i=0; i<=countPoint; i++){
			pointsArray[i]= newMarkers[i].getLatLng();
		  }
		  document.getElementById("toAddress").value = varMarkerPosChange;
		  gdir.loadFromWaypoints(pointsArray);
		});
	else 
		GEvent.addListener(newMarkers[i], "dragend", function(){
		  for (var i=0; i<=countPoint; i++){
			pointsArray[i]= newMarkers[i].getLatLng();
		  }
		  gdir.loadFromWaypoints(pointsArray);
		});
 
    // Now we can remove the original marker safely
    map.removeOverlay(originalMarker);
  }
}		//----------------------------------------Dragable markers end-----------------------------------

	function handleErrors(){
		alert(varErrorText);
	}
