var map;

var directionsArray = new Array(); //an array to hold all the directions/routes
var colors = ["#FF00FF","#333333","#00ff00","#0000ff","63B8FF","FF4FC4"];
var colorArrIndex=0;
var geocoder = null;
var addressMarker;
var i=0;
var secondmapcounter=0;
var errorOccurred=0;

var usepolyline=1;

var hasLoaded=0;
var setIntervalId;


function loadMaps() {
  google.load("maps", "2.x", {"callback" : initialize2});
  
  //alert('ok');


  
}


function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    geocoder = new GClientGeocoder();

    map.addControl(new GMapTypeControl());
    map.addControl(new GLargeMapControl());
    map.addControl(new GOverviewMapControl());
	
  }
}

function initialize2() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    geocoder = new GClientGeocoder();

    map.addControl(new GMapTypeControl());
    map.addControl(new GLargeMapControl());
    map.addControl(new GOverviewMapControl());
	

  }
}

//function setDirections(fromAddress, toAddress, locale) {
//  gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": locale });
//}

function setDirections(id)
{
/*
    var map_canvas = document.getElementById("map_canvas");
  if(map_canvas.style.display=="none")
  {
      //alert("true");
      map_canvas.style.display="block";
  }

  */
    //alert("id = "+id);
    var newid = id-1;


    //alert("newid = "+newid);


   /* remove the previous route
   if(newid>0)
        directionsArray[newid-1].clear();
   */

    currentId = id;
    directionsArray[newid] = new GDirections(map);
    GEvent.addListener(directionsArray[newid], "load",onGDirectionsLoad);
    GEvent.addListener(directionsArray[newid], "error", handleErrors);

    var route = "from:"+document.getElementById('from_'+id).value+" to:"+document.getElementById('to_'+id).value;
    //alert(route);

    //directionsArray[id-1].load(route,{getPolyline:true});
    directionsArray[newid].load(route);

    showAddress(document.getElementById('from_'+id).value);
	showAddress(document.getElementById('to_'+id).value);


	
    //disabled the fields unless there is error
    document.getElementById("from_"+currentId).readOnly =true;
    document.getElementById("to_"+currentId).readOnly =true;
    document.getElementById("submit_"+currentId).readOnly =true;
	
}


function setDirections3(id)
{
/*
    var map_canvas = document.getElementById("map_canvas");
  if(map_canvas.style.display=="none")
  {
      //alert("true");
      map_canvas.style.display="block";
  }

  */
    //alert("id = "+id);
    var newid = id;


    //alert("newid = "+newid);


   /* remove the previous route
   if(newid>0)
        directionsArray[newid-1].clear();
   */

    currentId = id;
    directionsArray[newid] = new GDirections(map);
    GEvent.addListener(directionsArray[newid], "load",onGDirectionsLoad);
    GEvent.addListener(directionsArray[newid], "error", handleErrors);

    var route = "from:"+document.getElementById('from_'+id).value+" to:"+document.getElementById('to_'+id).value;
    //alert(route);

    //directionsArray[id-1].load(route,{getPolyline:true});
    directionsArray[newid].load(route);

/*
    showAddress(document.getElementById('from_'+id).value);
	showAddress(document.getElementById('to_'+id).value);


	
    //disabled the fields unless there is error
    document.getElementById("from_"+currentId).readOnly =true;
    document.getElementById("to_"+currentId).readOnly =true;
    document.getElementById("submit_"+currentId).readOnly =true;
*/
	
}
var secondFrom="";
var secondTo="";
function testHasLoaded()
{
	//alert('ok');
	if(document.getElementById('map_canvas_overview'))
	{
		//alert("removeInterval");
		hasLoaded=1;
		clearInterval(setIntervalId);
		setDirection2(secondFrom,secondTo);
		//showDirection(thedirectionid);
	}
	else
	{
		setIntervalId = setTimeout("testHasLoaded()",5000);
	}
}

function testHasLoaded2(from,to,id1,id2)
{
    if(document.getElementById('map_canvas_overview'))
	{
		//alert("removeInterval");
		hasLoaded=1;
		clearInterval(setIntervalId);
		setDirection4(from,to,id1,id2);
		//showDirection(thedirectionid);
	}
	else
	{
		setIntervalId = setTimeout(function(){testHasLoaded2(from,to,id1,id2)},1000);
	}

}

function setDirection4(from, to,id1,id2)
{
	secondFrom= from;
	secondTo = to;

	//alert("to:"+to);
	if(hasLoaded==1)
	{
        //alert("ok");
		hasLoaded=0;
    	directionsArray[secondmapcounter] = new GDirections(map);

	    GEvent.addListener(directionsArray[secondmapcounter], "load",onGDirectionsLoad);
	    GEvent.addListener(directionsArray[secondmapcounter], "error", handleErrors);

    	var route = "from:"+from+" to:"+to;

		//alert(route);

		//alert(secondmapcounter);

		directionsArray[secondmapcounter].load(route);

		//alert(directionsArray[secondmapcounter]);

		secondmapcounter++;

		usepolyline=0;

        addressToLat4(from,id1);
        addressToLat4(to,id2);

	}
	else
	{
		setIntervalId = setTimeout(function(){testHasLoaded2(from,to,id1,id2)},1000);

	}
}

function addressToLat4(address,id) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        //alert(address + " not found");
      } else {

        /*map.setCenter(point, 13);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(address);
        */

       // alert(point); //get the lat and long
        updatelatlong(point,id);


      }
    }
  );
}

function updatelatlong(p,id)
  {
   //alert(currentcat.value);
           if (document.getElementById) {
   var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

 }
 if (x) {
   x.onreadystatechange = function() {
     if (x.readyState == 4 && x.status == 200) {

       var response =x.responseText;
       //alert(response);



     }
   }
   var url = "updatelatlong.php?p="+p+"&id="+id;
   //alert(url);
   x.open("GET", url, true);
   x.send(null);


   return false;
 }

 return false;

  }

var thedirectionid="";
function showDirection(id)
{
	thedirectionid=id;
	
	//alert("the id="+thedirectionid);
	if(hasLoaded==1)
	{
		for(var i=0;i<=thedirectionid;i++)
		{	
			setDirections3(i);
		}
	}

	else
	{
		setIntervalId = setTimeout("testHasLoaded()",1000);

	}

}
function noaccent(chaine) {
  temp = chaine.replace(/[àâä]/gi,"a")
  temp = temp.replace(/[éèêë]/gi,"e")
  temp = temp.replace(/[îï]/gi,"i")
  temp = temp.replace(/[ôö]/gi,"o")
  temp = temp.replace(/[ùûü]/gi,"u")
  return temp
}

function setDirection2(from, to)
{
	secondFrom= from;
	secondTo = to;
	hasLoaded =1;
	//alert("to:"+to);
	if(hasLoaded==1)
	{
		hasLoaded=0;
    	directionsArray[secondmapcounter] = new GDirections(map);

	    GEvent.addListener(directionsArray[secondmapcounter], "load",onGDirectionsLoad);
	    GEvent.addListener(directionsArray[secondmapcounter], "error", handleErrors);

    	var route = "from:"+noaccent(from)+" to:"+noaccent(to);

		//alert(route);

		//alert(secondmapcounter);

		directionsArray[secondmapcounter].load(route);
	
		//alert(directionsArray[secondmapcounter]);

		secondmapcounter++;

		usepolyline=0;

	}
	else
	{
		setIntervalId = setTimeout("testHasLoaded()",1000);

	}


}

var directionsArray2 = new Array(); //an array to hold all the directions/routes
function setDirectionForMatching(from, to,theid)
{
	secondFrom= from;
	secondTo = to;


		hasLoaded=0;
    	directionsArray2[theid] = new GDirections(map);

	    GEvent.addListener(directionsArray2[theid], "load",onGDirectionsLoad);
	    GEvent.addListener(directionsArray2[theid], "error", handleErrors);

    	var route = "from:"+from+" to:"+to;

		//alert(route);

		//alert(secondmapcounter);

		directionsArray2[theid].load(route);

		//alert(directionsArray[secondmapcounter]);


		usepolyline=1;



}

function clear2(theid)
{
     directionsArray2[theid].clear();
}
function setDirection2WithId(from, to,id)
{
	secondFrom= from;
	secondTo = to;
	
	//alert("to:"+to);
	if(hasLoaded==1 && id>0 && document.getElementById(id-1))
	{
		hasLoaded=0;
    	directionsArray[secondmapcounter] = new GDirections(map);
	
	    GEvent.addListener(directionsArray[secondmapcounter], "load",onGDirectionsLoad);
	    GEvent.addListener(directionsArray[secondmapcounter], "error", handleErrors);

    	var route = "from:"+from+" to:"+to;
		
		//alert(route);
		
		//alert(secondmapcounter);
	
		directionsArray[secondmapcounter].load(route);
	
		//alert(directionsArray[secondmapcounter]);
	
		secondmapcounter++;
	
		usepolyline=0;
		
	}
	else
	{
		setIntervalId = setTimeout("testHasLoaded()",5000);	
		
	}

	
}


function handleErrors(){

 if (this.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + this.getStatus().code);
 else if (this.getStatus().code == G_GEO_SERVER_ERROR)
   alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + this.getStatus().code);

 else if (this.getStatus().code == G_GEO_MISSING_QUERY)
   alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + this.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

 else if (this.getStatus().code == G_GEO_BAD_KEY)
   alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + this.getStatus().code);

 else if (this.getStatus().code == G_GEO_BAD_REQUEST)
   alert("A directions request could not be successfully parsed.\n Error code: " + this.getStatus().code);

 else alert("An unknown error occurred.");

 //alert("status="+this.getStatus().code);
 if(this.getStatus().code!=200)//if there is error, then let the fields ENBALED
 {

    document.getElementById("from"+currentId).disabled=false;
    document.getElementById("to"+currentId).disabled=false;
    document.getElementById("submit"+currentId).disabled=false;
  }
}


var initialColor=true;//to make the first run red in every map; ONLY for first run
function onGDirectionsLoad(){
    // Use this function to access information about the latest load()
    // results.

    // e.g.
    // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...




  //alert(gdir.getDistance().html);
  //alert(gdir.getDuration().html);
  //alert(gdir.getSummaryHtml());

    /*
	if(true)//(usepolyline==1)
	{
  		var polyline = this.getPolyline();
  		polyline.setStrokeStyle({color:colors[colorArrIndex],weight:3,opacity:0.7});
  		map.addOverlay(polyline);
  		colorArrIndex++;

        if(colorArrIndex>colors.length)
            colorArrIndex=0;

	}
    */


  		var polyline = this.getPolyline();
        if(initialColor==true)
        {
            polyline.setStrokeStyle({color:"#8F30A1",weight:3,opacity:0.7});
            initialColor=false;
        }
        else
        {
  		    //polyline.setStrokeStyle({color:genRandomColor(),weight:3,opacity:0.7});
            polyline.setStrokeStyle({color:colors[colorArrIndex],weight:3,opacity:0.7});
            colorArrIndex++;

            if(colorArrIndex>colors.length)
                colorArrIndex=0;
        }

  		map.addOverlay(polyline);






	//alert('done');
  //alert("i="+i);

}

function genRandomColor(){
colors = new Array(14)
colors[0]="0"
colors[1]="1"
colors[2]="2"
colors[3]="3"
colors[4]="4"
colors[5]="5"
colors[5]="6"
colors[6]="7"
colors[7]="8"
colors[8]="9"
colors[9]="a"
colors[10]="b"
colors[11]="c"
colors[12]="d"
colors[13]="e"
colors[14]="f"

digit = new Array(5)
color=""
for (i=0;i<6;i++){
digit[i]=colors[Math.round(Math.random()*14)]
color = color+digit[i]
}
return color;
}

function showAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        //alert(address + " not found");
      } else {

        /*//map.setCenter(point, 13);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(address);
        */

        //alert(point); //get the lat and long
		addAddress(address,point);
		addressToLat(address);
      }
    }
  );
}

var counter=0;
function addressToLat(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        //alert(address + " not found");
      } else {

        /*//map.setCenter(point, 13);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(address);
        */

        //alert(point); //get the lat and long
		//addAddress(address,point);
		if(counter==0)
		{
			document.getElementById("pointfrom_"+(numberOfRows-1)).value=point;
			//alert(document.getElementById("pointfrom_"+(numberOfRows-1)).value);
			counter=1;
		}
		else if(counter==1)
		{
			document.getElementById("pointto_"+(numberOfRows-1)).value=point;
			//alert(document.getElementById("pointto_"+(numberOfRows-1)).value);
			counter=0;
			
		}

      }
    }
  );
}



//add new row to insert a new route
var numberOfRows=1;
var currentId=0;
function addNewRow(tableRef)
{

    var myTable = document.getElementById(tableRef);
    var tBody = myTable.getElementsByTagName('tbody')[0];
    var newTR = document.createElement('tr');
    newTR.id = "tr"+numberOfRows;

    var newTD1 = document.createElement('td');
    var newTD2 = document.createElement('td');
    var newTD3 = document.createElement('td');
    var newTD4 = document.createElement('td');

    //newTD1.className="";
    //newTD1.innerHTML = "Code";
    //newTD1.style.width="25px";


	var newfield7 = document.createElement('input');
    newfield7.type = 'hidden';
    newfield7.name = "pointfrom_"+numberOfRows;
    newfield7.id = "pointfrom_"+numberOfRows;
	
	var newfield8 = document.createElement('input');
    newfield8.type = 'hidden';
    newfield8.name = "pointto_"+numberOfRows;
    newfield8.id = "pointto_"+numberOfRows;
	
    var newfield1 = document.createElement('input');
    newfield1.className="wickEnabled";
    newfield1.type = 'text';
    newfield1.name = "from_"+numberOfRows;
    newfield1.id = "from_"+numberOfRows;
    //newfield1.value=code;
    newTD1.appendChild(newfield1);
    newTD1.className = "mytdtextfield";


    var newfield2 = document.createElement('input');
    newfield2.className="wickEnabled";
    newfield2.type = 'text';
    newfield2.id = "to_"+numberOfRows;
    newfield2.name = "to_"+numberOfRows;
    //newfield2.value=exp;
    newTD2.appendChild(newfield2);
    newTD2.className = "mytdtextfield";
    newTD2.id = "td"+numberOfRows;
    //newTD2.style.width="95px";
    newTD2.className="txt";

    var newfield3 = document.createElement('input');
    //newfield2.className="mytextfield";
    newfield3.type = 'button';
    newfield3.id = "submit_"+numberOfRows;
    newfield3.name = "submit_"+numberOfRows;
    newfield3.value="Add To Map";
    newTD3.appendChild(newfield3);
    newTD3.className = "mytdtextfield";
    newTD3.id = "td"+numberOfRows;
	
    //newTD3.style.width="95px";
    newTD3.className="txt";

    //var theid =numberOfRows-1;
	var fieldname = newfield3.id;
	var ex = fieldname.split("_");
	
	var theid = ex[1];
    newfield3.onclick=function(evt)
    {
        //alert(evt);
		
		
        setDirections(theid,newfield1,newfield2,newfield3);
		
		return false;

    };


    /*
	var anchorTagPlus = document.createElement('a');
    anchorTagPlus.appendChild(document.createTextNode("+"));
    anchorTagPlus.style.textDecoration="none";
    anchorTagPlus.href = "#";
    anchorTagPlus.onclick = function()
    {
        addNewRow('routetable');
    }
	newTD3.appendChild(anchorTagPlus);
	*/
	
    var anchorTagMinus = document.createElement('a');
    anchorTagMinus.appendChild(document.createTextNode("-"));
    anchorTagMinus.style.textDecoration="none";
    anchorTagMinus.href = "#";
    anchorTagMinus.onclick = function()
    {
        //clear the route and delete the row
        clear(theid,newTR);
    }

    
    newTD3.appendChild(document.createTextNode("      "));
    newTD3.appendChild(anchorTagMinus);
	newTD3.appendChild(newfield7);
	newTD3.appendChild(newfield8);

    newTR.appendChild(newTD1);
    newTR.appendChild(newTD2);
    newTR.appendChild(newTD3);
    newTR.appendChild(newTD4);

    tBody.appendChild(newTR);

    numberOfRows++;
}

function clear(theid,rows)
{
    alert("clear ="+theid);
    removeRow(rows,theid);
    if(theid-1>=0 && theid<=numberOfRows)
    {
        directionsArray[theid-1].clear();
    }

}


function removeRow(rows,theid)
{
	/*
    if(numberOfRows>2)
    {
        document.getElementById('routetable').deleteRow(rows.rowIndex);


    }
    else
    {
        document.getElementById('from_'+theid).disabled=false;
        document.getElementById('to_'+theid).disabled=false;
        document.getElementById('submit_'+theid).disabled=false;
    }

    //numberOfRows--;
    if(numberOfRows<2)
            numberOfRows=1;
	*/
	document.getElementById('routetable').deleteRow(rows.rowIndex);
	numberOfRows--;
	

}

//add address to table
function addAddress(theadd,pt)
{
	
  if (document.getElementById) {
    var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

  }
  if (x) {
    x.onreadystatechange = function() 
	{
      	if (x.readyState == 4 && x.status == 200) 
		{
			
		}
        
    }
	
	var url = "addAddress.php?add="+theadd+"&pt="+pt;
	//window.open(url);
    x.open("GET", url, true);
    x.send(null);

    return false;
  }

  return false;
}

function sleep(naptime){
      naptime = naptime * 1000;
      var sleeping = true;
      var now = new Date();
      var alarm;
      var startingMSeconds = now.getTime();
      //alert("starting nap at timestamp: " + startingMSeconds + "\nWill sleep for: " + naptime + " ms");
      while(sleeping){
         alarm = new Date();
         alarmMSeconds = alarm.getTime();
         if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
      }      
     // alert("Wakeup!");
   }