// Google maps array
var ardMaps=[];
// number of googlemaps.
var ardmap_i=0;
// current google map
var m;
// google Maps

var ardColors=[];
ardColors[0]='#00CC00';
ardColors[1]='#CC0000';
ardColors[2]='#0000CC';
ardColors[3]='#99FF99';
var ardCi=0; //colorindex

function ardMap(name) {
	this.name=name;
}

function ardInitMaps() {
	for (var i=0; i<ardMaps.length; i++) {
		ardInitMap(ardMaps[i].name,1);
	}
}

function ardInitMap(mapId,forceinit) {
	if (GBrowserIsCompatible()) {
		found=0;
		for (var i=0; i<ardMaps.length; i++) {
			n=ardMaps[i].name;
			if (n==mapId) {
				found=1;
				m=ardMaps[i];
				if (forceinit==1) {
					m.map = new GMap2(document.getElementById(mapId));
					m.map.removeMapType(G_SATELLITE_MAP);
					m.map.addMapType(G_PHYSICAL_MAP);					

					m.map.addControl(new GMapTypeControl()); 
					m.map.addControl(new GLargeMapControl3D());					
					m.map.addControl(new GOverviewMapControl);

					m.map.setMapType(G_PHYSICAL_MAP);
				}
			}
		}
		if (found==0) {
			ardMaps[ardmap_i]=new ardMap(mapId);
			m=ardMaps[ardmap_i];
			m.map = new GMap2(document.getElementById(mapId));
			m.map.removeMapType(G_SATELLITE_MAP);
			m.map.addMapType(G_PHYSICAL_MAP);					

			m.map.addControl(new GMapTypeControl()); 
			m.map.addControl(new GLargeMapControl3D());
			m.map.addControl(new GOverviewMapControl);

			m.map.setMapType(G_PHYSICAL_MAP);

			ardmap_i++;
		}
		
	}
	return m;
}

function ardSel(selId,valArray) {
	var sel=document.getElementById(selId);
	for (var j=0; j<sel.options.length; j++) { 
		sel.options[j].selected = "";	
		for (var i=0; i<valArray.length; i++) {
			if (sel.options[j].value==valArray[i]) {
				sel.options[j].selected = "1";
			} 
		}
	}
}

function ardSetValue(fieldId,val)
{
	document.getElementById(fieldId).value=val;
}


function ardEnableAll(selId,deb) {
	var sel=document.getElementById(selId);
	for (var j=deb; j<sel.options.length; j++) { 
		sel.options[j].disabled = false;	
	}
}

function ardEnable(selId,valArray,deb) {
	var sel=document.getElementById(selId);
	for (var j=deb; j<sel.options.length; j++) { 
		sel.options[j].disabled = true;	

		var i=0;
		while ((i<valArray.length)&&(sel.options[j].value!=valArray[i]))
		{
			i++;
		}
		if (i<valArray.length)
		{
			sel.options[j].disabled = false;
		}

	}
}


function ardPolyLineClick(latlng) {
	ardSel('lineslist',[this.ardSrc]);
	ardActionForm('infolignes','POST','4.0.html?&no_cache=1&tx_ardcrictravelinfo_pi1[action]=lineclick&tx_ardcrictravelinfo_pi1[controller]=Info&cHash=427aacc65e&eID=tx_ardviewhelpers_ajx&tx_ardviewhelpers_ajx[pid]=4&tx_ardviewhelpers_ajx[extensionName]=ArdCricTravelInfo&tx_ardviewhelpers_ajx[pluginName]=Pi1','');
}

function ardOnGDirectionsLoad() {
	m=this.ardMap;
	if (this.getBounds()!=null) {
		m.bounds.extend(this.getBounds().getNorthEast());
		m.bounds.extend(this.getBounds().getSouthWest());
	}
	var polyline = this.getPolyline();
	ardCi=this.ardCi;
	if (polyline!=undefined) {
		polyline.color=ardColors[ardCi];
		polyline.opacity=0.6;	
		polyline.clickable=true;
		polyline.ardRoute=this.ardRoute;
		polyline.ardSrc=this.ardSrc;
		m.map.addOverlay(polyline);
		GEvent.addListener(polyline,"click",ardPolyLineClick);
	}
	m.map.setCenter(m.bounds.getCenter(),m.map.getBoundsZoomLevel(m.bounds));

}



function ardGooogleMapsHandleErrors(){
 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 (this.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: " + this.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("Google n'a pas réussi a traiter la demande d'itinéraire.\n Error code: " + this.getStatus().code);
 else if (this.getStatus().code == 620)
   //servers are too loaded...
   var error=true;
 
 else alert("An unknown error occurred : "+ this.getStatus().code);
}

function ardDrawMap(mapId,pois,forceinit) {
	ardDrawMapDirections(mapId,[pois],forceinit);
}

function ardDrawMapDirections(mapId,routes,forceinit) {
		m=ardInitMap(mapId,forceinit);
		m.gdirs = new Array();
		m.bounds = new GLatLngBounds();
		m.gdirindex=0;
		m.i=0;
		m.ardCi=0;
		for (var j=0; j<routes.length; j++) {
			if (m.ardCi>ardColors.length) m.ardCi=0;
			ardDrawMapDir(m,routes[j]); 
			m.ardCi++;
		}	
}

function ardDrawMapDir(m,route) {
			if (typeof route.pois=="undefined") route.pois=null;
			if (route.pois.length>25)
			{
				/*alert('trop de points a afficher : '+route.pois.length);*/
				route1= jQuery.extend(true, {}, route);
				route1.pois=route.pois.slice(0,25);
				ardDrawMapDir(m,route1);
				route2=jQuery.extend(true, {}, route);
				route2.pois=route.pois.slice(24);
				ardDrawMapDir(m,route2);
			} else {
				m.gdirs[m.i]=new GDirections(m.map);
				m.gdirs[m.i].ardMap=m;
				m.gdirs[m.i].ardRoute=route.pois;
				m.gdirs[m.i].ardSrc=route.src;
				m.gdirs[m.i].ardIndex=m.i;
				m.gdirs[m.i].ardCi=m.ardCi;
				GEvent.addListener(m.gdirs[m.i],"load",ardOnGDirectionsLoad);
				GEvent.addListener(m.gdirs[m.i], "error", ardGooogleMapsHandleErrors);
				m.gdirs[m.i].loadFromWaypoints(route.pois,{preserveViewport:true});
				m.i=m.i+1;
			}

}




/***************************************************************/


var fillColors=[];
var polys=[];
var polyNames=[];


function ardDrawMapPolygons(mapId,polygones,names,colors,forceinit) {
	m = ardInitMap(mapId,forceinit);

	if (forceinit==1)
		m.bounds = new GLatLngBounds();

	this.polyNames = names;
	this.fillColors = colors;
	for (var j=0; j<polygones.length; j++) {	
		ardDrawMapPoly(m,polygones[j],j,forceinit);
	}


}


function ardDrawMapPoly(m,poly,j,forceinit) {

	var lineOpacity = .8;
	var fillOpacity = .2;

	var lineColor = "#000000"; // black line
	var lineOpacity = .2;
	var fillOpacity = .2;
	var lineWeight = 2;
	var polyPoints=[];

	for (var i=0; i<(poly.length); i++)
	{
	    var coors=poly[i];
	    var coor=coors.split(new RegExp("[,]+", "g"));
	    polyPoints.push(new GLatLng(coor[0], coor[1]));
	    if (forceinit==1) m.bounds.extend(new GLatLng(coor[0], coor[1]));
	}

	polyShape = new GPolygon(polyPoints,lineColor,lineWeight,lineOpacity,fillColors[j], fillOpacity);
	polys.push(polyShape);
	//m.map.clearOverlays();
	m.map.addOverlay(polyShape);

/*
  	GEvent.addListener(polyShape, 'click', function(point) {
         for (var i=0; i<polys.length; i++) {
            if (polys[i].Contains(point)) {
              m.map.openInfoWindowHtml(point,polyNames[i]);
            }
          }

	}); 
*/

	if (forceinit==1)
		m.map.setCenter(m.bounds.getCenter(),m.map.getBoundsZoomLevel(m.bounds));
}


      // === A method for testing if a point is inside a polygon
      // === Returns true if poly contains point
/*      GPolygon.prototype.Contains = function(point) {
        var j=0;
        var oddNodes = false;
        var x = point.lng();
        var y = point.lat();
        for (var i=0; i < this.getVertexCount(); i++) {
          j++;
          if (j == this.getVertexCount()) {j = 0;}
          if (((this.getVertex(i).lat() < y) && (this.getVertex(j).lat() >= y))
          || ((this.getVertex(j).lat() < y) && (this.getVertex(i).lat() >= y))) {
            if ( this.getVertex(i).lng() + (y - this.getVertex(i).lat())
            /  (this.getVertex(j).lat()-this.getVertex(i).lat())
            *  (this.getVertex(j).lng() - this.getVertex(i).lng())<x ) {
              oddNodes = !oddNodes
            }
          }
        }
        return oddNodes;
      };
*/


/***************************************************************/







function ardGmZIndexProcess() {
	return 9999999999;
}
// Creates a marker whose info window displays the letter corresponding
// to the given index.
function ardCreateMarker(point,title,html) {
  // Create a lettered icon for this point using our icon class
  //var letter = String.fromCharCode("A".charCodeAt(0) + index);
  //var letteredIcon = new GIcon(baseIcon);
  //letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
  // Set up our GMarkerOptions object
  //markerOptions = { icon:letteredIcon };
  //var marker = new GMarker(point, markerOptions);
 
  var marker = new GMarker(point,{'title':title,'zIndexProcess':ardGmZIndexProcess});
  GEvent.addListener(marker, "click", function() {
	marker.openInfoWindowHtml(html);
  });
  return marker;
}

function ardPanTo(mapId,lat,long,html) {
	m=ardInitMap(mapId,0);
	var pt=new GLatLng(lat, long)
	m.map.panTo(pt);
	if (html.length>0) m.map.openInfoWindowHtml(pt,html);
}

function ardDrawMarkers(mapId,json,forceinit) {
		pois=eval(json);
		m=ardInitMap(mapId,forceinit);
		m.bounds = new GLatLngBounds();
		for (var j=0; j<pois.length; j++) {
		    var point=new GLatLng( pois[j].lat,pois[j].long);
			m.map.addOverlay(ardCreateMarker(point,pois[j].title,pois[j].html));
			m.bounds.extend(point);
		}
		m.map.setCenter(m.bounds.getCenter(),m.map.getBoundsZoomLevel(m.bounds));
}
