var map ;
var Hybrid ;
var Standard ;
var markers ;
var icon_size ;
var offset ;
var icon ;
var test ;

map = new OpenLayers.Map('map', {controls: []});

//on dclare les diffrents controles
map.addControl(new OpenLayers.Control.MouseToolbar());
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.addControl(new OpenLayers.Control.PanZoomBar());
map.addControl(new OpenLayers.Control.MouseDefaults());

//on dclare les layers
Hybrid = new OpenLayers.Layer.Google("Satellite", { 'type': G_HYBRID_MAP });
Standard = new OpenLayers.Layer.Google("Standard");

//var Satellite = new OpenLayers.Layer.Google("Satel", { 'type': G_SATELLITE_MAP });			
markers = new OpenLayers.Layer.Markers("Markers");

//on dclare notre icone personnalis
icon_size = new OpenLayers.Size(16,16);
offset = new OpenLayers.Pixel(-(icon_size.w/2), -icon_size.h);
icon = new OpenLayers.Icon('images/spin.png',icon_size,offset);

//on ajoute les layers  la map
map.addLayers([Hybrid,Standard,markers]);//

//on situe le centre de la map
map.setCenter(new OpenLayers.LonLat(-31,32), 2);

// Marker class
//
OpenLayers.ProductMarker = OpenLayers.Class.create();
OpenLayers.ProductMarker.prototype = 
    OpenLayers.Class.inherit( OpenLayers.Marker, {
	
	tMap		: null,
	szName		: null,
	
	iCount		: 0,
	iLastClickX     : 0,
	iLastClickY     : 0,
	
	oQlDiv    	: null,
	oInfosDiv 	: null,
	oCloseDiv 	: null,
	oListDiv  	: null,
	oProductsDiv    : null,
	oPopDiv		: null,
	
	aCities  	: null,
	
	oPreviousSelectedTarget : null,
	
	bShowDetails : false ,
	bIsVisible : false,
	
	pointerX: function(event) {
	    return event.pageX || (event.clientX +
				   (document.documentElement.scrollLeft || document.body.scrollLeft));
	},
	
	pointerY: function(event) {
	    return event.pageY || (event.clientY +
				   (document.documentElement.scrollTop || document.body.scrollTop));
	},
	
	browserAgent: function () {
	    var agt=navigator.userAgent.toLowerCase();
	    if (agt.indexOf("msie") != -1) return 'Internet Explorer';
	    if (agt.indexOf("firefox") != -1) return 'Firefox';
	    if (agt.indexOf("opera") != -1) return 'Opera';
	    if (agt.indexOf("staroffice") != -1) return 'Star Office';
	    if (agt.indexOf("chrome") != -1) return 'Chrome';
	    if (agt.indexOf("webtv") != -1) return 'WebTV';
	    if (agt.indexOf("beonex") != -1) return 'Beonex';
	    if (agt.indexOf("chimera") != -1) return 'Chimera';
	    if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	    if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	    if (agt.indexOf("safari") != -1) return 'Safari';
	    if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	    if (agt.indexOf("netscape") != -1) return 'Netscape';
	    if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	    if (agt.indexOf('\/') != -1) {
		if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
		    return navigator.userAgent.substr(0,agt.indexOf('\/'));}
		else return 'Netscape';
	    } else if (agt.indexOf(' ') != -1)
		return navigator.userAgent.substr(0,agt.indexOf(' '));
	    else 
		return navigator.userAgent;
	},	
	
	//--------------------------------------------------------------------------------------
	//		Constructeur
	//--------------------------------------------------------------------------------------
	
	initialize: function( lonlat, icon, name, iCount, szInfosDiv, bShowDetails, tCurrentMap ) {
            //alert( "productmarjer:init" ) ;
            OpenLayers.Marker.prototype.initialize.apply(this, arguments);
            this.tMap = tCurrentMap;
            this.szName = name;
	    this.iCount = iCount;
	    this.bShowDetails = bShowDetails ;
	    this.events.register("mouseover", this, this.InflateMarker );
	    this.events.register("mouseout"	, this, this.DeflateMarker );
	    this.events.register("click"	, this, this.GetCountryProducts );
	    this.oPopDiv = $(szInfosDiv) ;
	    //creation de la popup principale
	    this.oProductsDiv  			= document.createElement( 'div' ) ; 
	    this.oProductsDiv.id 		= 'productsDiv' ;  
	    document.getElementsByTagName('body')[0].appendChild(this.oProductsDiv); 
            //alert( "productmarjer:init" ) ;
	    
	},
	
	destroy: function() {
	},
	
	//--------------------------------------------------------------------------------------
	//		Info-bulle overlib affichee au hover du marker
	//--------------------------------------------------------------------------------------
	
	show : function (szText, ix, iy) {
	    // Si il est cache on le rend visible
	    if(this.bIsVisible==false) {
		this.bIsVisible=true;
		//on positionne la div par rapport au curseur
		this.oPopDiv.style.left = ix + "px";
		this.oPopDiv.style.top = iy + "px";
		//on change de classe pour passer le parametre visibility a "visible"
		this.oPopDiv.className="visibleInfobulle"; 
		// on insere le flux html passe en parametre dans l'infobulle
		this.oPopDiv.innerHTML = szText; 
	    }
	},
	
	hide : function () {
	    // Si la bulle etais visible on la cache
	    if(this.bIsVisible==true) {
		this.bIsVisible=false;
		//on change de classe pour passer le parametre visibility a "hidden"
		this.oPopDiv.className="hiddenInfobulle"; 
	    }
	},
	
	//fait grossir le marker au hover
	InflateMarker: function (event){
	    this.inflate(2) ;
	    //afficher l'infobulle au hover
	    
	    var pixelPosition = this.tMap.getPixelFromLonLat( this.lonlat ) ;	
	    var iX = pixelPosition.x + 10;
	    var iY = pixelPosition.y;	   
	    
	    if (this.iCount > 1) {
		this.show("<div id='country' style='background-color: #89a9cf; color: black';position:absolute;><center><b>"
			  +this.szName+"</b></center></div><br/><b>There are " 
			  +this.iCount+ " products available for this country.</b>",iX, iY);
	    } else {
		this.show("<div id='country' style='background-color: #89a9cf; color: black';position:absolute;><center><b>"
			  +this.szName+"</b></center></div><br/><b>There is " 
			  +this.iCount+ " product available for this country.</b>",iX, iY);
	    }
	},
	
	//ramene le marker a sa taille initiale
	DeflateMarker: function (event){
	    this.inflate(.5) ;
	    //cacher l'infobulle à la sortie du hover
	    this.hide();
	},
	
	//--------------------------------------------------------------------------------------
	//		OpenRico, creation et remplissage des div
	//--------------------------------------------------------------------------------------
	
	//creation de la popup, des differentes div à linterieur de celle-ci
	showProductPopup: function ( oProductTable, aCities ) {	
	    
	    //positionnement de la div
	    this.oProductsDiv.style.left       = "50px" ;
	    this.oProductsDiv.style.top        = "80px" ;
	    this.oProductsDiv.style.width      = "800px" ;
	    this.oProductsDiv.style.height     = "355px" ;
	    this.oProductsDiv.style.visibility = 'visible';
	    this.oProductsDiv.style.opacity    = '1.0' ;
	    
	    //sauvegarde du tableau cities dans le this
	    this.aCities = aCities ;
	    
	    //creation des div
	    this.oQlDiv    		= document.createElement( 'div' ) ; 
	    this.oQlDiv.id 		= 'divQl' ;
	    this.oInfosDiv 		= document.createElement( 'div' ) ; 
	    this.oInfosDiv.id 	= 'divInfos' ;
	    this.oCloseDiv 		= document.createElement( 'div' ) ; 
	    this.oCloseDiv.id 	= 'divClose' ;
	    this.oListDiv  		= document.createElement( 'div' ) ; 
	    this.oListDiv.id 	= 'divList' ;
	    this.oCountryDiv 	= document.createElement( 'div' ) ;
	    this.oCountryDiv.id = 'divCountry' ;
	    this.oTitle 		= document.createElement( 'p' ) ;
	    this.oTitle.id 		= 'listTitle' ;
	    this.oCoordMDiv		= document.createElement( 'div' ) ; 
	    this.oCoordMDiv.id 	= 'divCoordM' ;
	    this.oCoordULDiv	= document.createElement( 'div' ) ; 
	    this.oCoordULDiv.id = 'divCoordUL' ;
	    this.oCoordURDiv	= document.createElement( 'div' ) ; 
	    this.oCoordURDiv.id = 'divCoordUR' ;
	    this.oCoordLLDiv	= document.createElement( 'div' ) ; 
	    this.oCoordLLDiv.id = 'divCoordLL' ;
	    this.oCoordLRDiv	= document.createElement( 'div' ) ; 
	    this.oCoordLRDiv.id = 'divCoordLR' ;
	    
	    //rajout des div sur la popup
	    this.oProductsDiv.appendChild(this.oListDiv);	
	    this.oProductsDiv.appendChild(this.oQlDiv);	
	    this.oProductsDiv.appendChild(this.oInfosDiv);	
	    this.oProductsDiv.appendChild(this.oCloseDiv);
	    this.oProductsDiv.appendChild(this.oCountryDiv) ;			
	    this.oProductsDiv.appendChild(this.oTitle) ;	
	    this.oProductsDiv.appendChild(this.oCoordULDiv);	
	    this.oProductsDiv.appendChild(this.oCoordURDiv);	
	    this.oProductsDiv.appendChild(this.oCoordLLDiv);	
	    this.oProductsDiv.appendChild(this.oCoordLRDiv);			
	    
	    //creation du titre de la liste de produits
	    this.oTitle.innerHTML = 'Available products : ';
	    
	    //ajout de la table des produits dans la div contenant la ListDiv
	    this.oListDiv.appendChild( oProductTable ) ;			
	    
	    //creation du (bouton) close
	    this.oCloseDiv.innerHTML = '<img src="images/close.png">' ;
	    this.oCloseDiv.onclick = function() { this.hideProductPopup() ; }.bind(this) ;
	},
	
	//creation de la fonction close
	hideProductPopup: function ()
	{
	    document.getElementsByTagName('body')[0].removeChild( this.oOpacityDiv );		
	    
	    while( this.oProductsDiv.hasChildNodes() ) {
		this.oProductsDiv.removeChild( this.oProductsDiv.firstChild );	
	    }
	    
	    // Close the popup
	    //
	    if( this.browserAgent() == 'Firefox' || this.browserAgent() == 'Chrome' ) {
		oEffect = new Rico.Effect.SizeAndPosition( this.oProductsDiv, this.iLastClickX, this.iLastClickY, 1, 1 ) ;
		oAnim = new Rico.Effect.Animator( oEffect ) ;
		oAnim.play( oEffect, {step:20, duration:100} ) ;
	    } else
		this.oProductsDiv.style.visibility = 'hidden';
	},
	
	//creation du onclick sur un produit
	productClicked: function ( e )
	{
	    //recuperation du DOM element
	    if (!e)    // IE
		oTarget = window.event.srcElement
	    else
		oTarget = e.target ;
	    
	    iProductIndex = parseInt(oTarget.id) ;
	    this.SelectProduct(iProductIndex, oTarget);
	},
	
	//affiche les infos sur le produit selectionne si l'utilisateur est logge
	SelectProduct: function(iProductIndex, oTd)
	{
	    if ( this.bShowDetails ) {		
		
		this.oProductsDiv.appendChild(this.oCoordMDiv);
		//recuperation de l'id du produit qui est clique
		iId = this.aCities[iProductIndex].getAttribute('id') ; 
		
		// si le produit est clique, changement de la class CSS
		if ( this.oPreviousSelectedTarget != null )
		    this.oPreviousSelectedTarget.className = "unselectedProduct" ;
		oTd.className  = "selectedProduct" ;
		this.oPreviousSelectedTarget = oTd ;
		
		//affichage du contenu de la InfosDiv
		this.GetProductDetail(iId);
		
		//affichage du contenu de la QlDiv
		oImg = document.createElement( 'img' ) ;
		oImg.id = 'imgQl' ;
		oImg.src = 'preview.php?max=300&id='+iId ;
		
		//nettoyage de la Qldiv pour l'affichage suivant
		if ( this.oQlDiv.hasChildNodes() ) 
		{
		    this.oQlDiv.removeChild( this.oQlDiv.firstChild );	
		}
		this.oQlDiv.appendChild( oImg ) ;
	    }
	    else alert ("Log in to access database");
	},
	
	// Remplissage de la InfosDiv
	showProductInfos : function (oInfosTable,aProducts)
	{
	    //sauvegarde du tableau cities dans le this
	    this.aProducts = aProducts ;
	    
	    //nettoyage de la div pour l'affichage suivant
	    if ( this.oInfosDiv.hasChildNodes() ) 
	    {
		this.oInfosDiv.removeChild( this.oInfosDiv.firstChild );	
	    }
	    
	    //ajout du detail des produits dans la div
	    this.oInfosDiv.appendChild( oInfosTable ) ;			
	},
	
	//--------------------------------------------------------------------------------------
	//		Ajax Request : recuperation de la liste des produits
	//-------------------------------------------------------------------------------------	
	
	GetCountryProducts: function (event){
	    
	    // Create background div to hide partially the map
	    this.oOpacityDiv	= document.createElement( 'div' ) ; 
	    this.oOpacityDiv.id = 'divOpacity' ;
	    document.getElementsByTagName( 'body' )[0].appendChild( this.oOpacityDiv ) ;		
	    
	    Rico.Effect.setOpacity(this.oOpacityDiv, 0.5);
	    this.oOpacityDiv.style.visibility = 'visible';	
	    
	    // Keep last click
	    this.iLastClickX = this.pointerX( event ) ;
	    this.iLastClickY = this.pointerY( event ) ;
	    
	    var poAjax = new Ajax.Request( "get_country_products.php", 
					   {
					       method: 'get', 
					       parameters: "country="+this.szName,
					       onSuccess:this.updateProductSuccess.bind(this), 
					       onFailure:this.updateProductFailure   
					   }
					 );
	    
	},	
	
	//Succes de la Requete Ajax 
	updateProductSuccess: function ( oHttpRequest ) {
	    if (oHttpRequest.readyState == 4) { 
		if (oHttpRequest.status == 200) {
		    
		    // get response as XML DOM and fetch Root Node.
		    var oXmlResponse = 	oHttpRequest.responseXML ;
		    var oRootNode 	 = 	oXmlResponse.documentElement;
		    var aCities 	 =	oRootNode.getElementsByTagName("city");
		    
		    // cree un element <table> et un element <tbody>
		    var mytable       = document.createElement("table");
		    var mytablebody   = document.createElement("tbody");
		    
	 	    for( iCityIndex = 0 ; iCityIndex < aCities.length ; iCityIndex++ ){
			
		        var szCName 	  =	aCities[iCityIndex].getAttribute('CName') ;					
			var mycurrent_row = document.createElement("tr");
			
			mycurrent_row.id  = "" + iCityIndex ;
			mycurrent_row.onclick = function(e) { this.productClicked(e) ; }.bind(this) ;
			
			// cree un element <td>
			var mycurrent_cell = document.createElement("td");
			
			if(iCityIndex==0)
			    oFirstTd = mycurrent_cell;
			
			mycurrent_cell.id  = "" + iCityIndex ;
			//on met le row par defaut sur unselected
			mycurrent_cell.className  = "unselectedProduct" ;
			// cree un nÂœud texte
			var currenttext = document.createTextNode(szCName);
			// ajoute le nÂœud texte cree à la cellule <td>
			mycurrent_cell.appendChild(currenttext);
			// ajoute la cellule <td> à la ligne <tr>
			mycurrent_row.appendChild(mycurrent_cell);					
			// ajoute la ligne <tr> à l'element <tbody>
			mytablebody.appendChild(mycurrent_row);	
		    }
		    
		    // ajoute <tbody> à l'element <table>
		    mytable.appendChild(mytablebody);				
		    this.showProductPopup( mytable, aCities ) ;
		    this.SelectProduct(0, oFirstTd);
		    
		} else {
		    this.oOpacityDiv.style.visibility = 'hidden';	
		    alert("Unable to access catalog database\nPlease retry later.") ;
		}
		
	    } else {
		this.oOpacityDiv.style.visibility = 'hidden';	
		alert("Unable to access catalog database\nPlease retry later.") ;
	    }
	},
	
	//Echec de la requete Ajax
	updateProductFailure: function ( oHttpRequest ) {
	    this.oOpacityDiv.style.visibility = 'hidden';	
	    alert("Unable to access catalog database\nPlease retry later.") ;
	},	
	
	//creation du tableau de la liste des pays
	createArray : function ( szProperty_title, szProperty_content, oTable ) {
	    // cree un element <tr>
	    var mycurrent_row 		 = document.createElement("tr");
	    // cree un element <td>
	    var mycurrent_cell 		 = document.createElement("td");
	    // rempli l'innerHTML
	    mycurrent_cell.innerHTML = '<span class=property_title>' 
		+ szProperty_title + '</span> : <span class=property_content>' 
		+ szProperty_content + '</span>';
	    // ajoute la cellule <td> à la ligne <tr>
	    mycurrent_row.appendChild(mycurrent_cell);
	    // ajoute la ligne <tr> à l'element <tbody>
	    oTable.appendChild(mycurrent_row);	
	},
	
	//--------------------------------------------------------------------------------------
	//		Ajax Request : recuperation des informations des produits et de ses coordonnees
	//--------------------------------------------------------------------------------------
	
	GetProductDetail: function (iId){
	    var poAjax2 = new Ajax.Request( "get_city_infos.php", 
					    {
						method: 'get', 
						parameters: "id="+iId,
						onSuccess:this.updateDetailSuccess.bind(this), 
						onFailure:this.updateDetailFailure   
					    }
					  );		
	},	
	
	//Succes de la requete Ajax
	updateDetailSuccess: function ( oHttpRequest ) {
	    if (oHttpRequest.readyState == 4) { 
		if (oHttpRequest.status == 200) {
		    
		    // get response as XML DOM and fetch Root Node.
		    var oXmlResponse = 	oHttpRequest.responseXML ;
		    var oRootNode 	 = 	oXmlResponse.documentElement;
		    var aProducts 	 =	oRootNode.getElementsByTagName("product");
		    
		    // cree un element <table> et un element <tbody>
		    var mytable       = document.createElement("table");
		    var mytablebody   = document.createElement("tbody");
		    var iProductIndex = 0;
		    
		    var szCountryName   	 =	aProducts[0].getAttribute('countryName') ;
		    // insere le nom du pays dans le innerHTML de la div
		    this.oCountryDiv.innerHTML = szCountryName;
		    
		    var szCityName 	  		 =	aProducts[0].getAttribute('cityName') ;
		    
		    if( szCityName.toLowerCase().indexOf("whole") >= 0 ) {
			this.createArray ( 'Area', szCityName, mytablebody );
		    } else {
			this.createArray ( 'City Name', szCityName, mytablebody );
		    }
		    
		    var szType 	  	  	     =	aProducts[0].getAttribute('type') ;	
		    this.createArray ( 'Type', szType, mytablebody );
		    
		    var szR_D 	 			 =	aProducts[0].getAttribute('release_date') ;
		    this.createArray ( 'Release Date', szR_D, mytablebody );
		    
		    var szResolution  		 =	aProducts[0].getAttribute('resolution') + " meters" ;
		    this.createArray ( 'Resolution', szResolution, mytablebody );
		    
		    var szSize	 		     =	aProducts[0].getAttribute('size') + " km&sup2;" ;
		    this.createArray ( 'Size', szSize, mytablebody );
		    
		    // ajoute <tbody> à l'element <table>
		    mytable.appendChild(mytablebody);				
		    
		    //envoi la table dans Infosdiv
		    this.showProductInfos( mytable, aProducts ) ;
		    
		    var szULC_lon 	  	  	     =	aProducts[0].getAttribute('ULC_lon') ;	
		    var szULC_lat 			  	 =	aProducts[0].getAttribute('ULC_lat') ;
		    this.createArrayCoord ( 'Lon', 'Lat', szULC_lon, szULC_lat, this.oCoordULDiv );
		    
		    var szURC_lon	  	  	  =	aProducts[0].getAttribute('URC_lon') ;
		    var szURC_lat	  	  	 =	aProducts[0].getAttribute('URC_lat') ;
		    this.createArrayCoord ( 'Lon', 'Lat', szURC_lon, szURC_lat, this.oCoordURDiv );
		    
		    var szLLC_lon 	  	  	  = aProducts[0].getAttribute('LLC_lon') ;
		    var szLLC_lat 	  	  	  = aProducts[0].getAttribute('LLC_lat') ;
		    this.createArrayCoord ( 'Lon', 'Lat', szLLC_lon, szLLC_lat, this.oCoordLLDiv );
		    
		    var szLRC_lon 	  	  	  =	aProducts[0].getAttribute('LRC_lon') ;
		    var szLRC_lat 	  	  	  =	aProducts[0].getAttribute('LRC_lat') ;
		    this.createArrayCoord ( 'Lon', 'Lat', szLRC_lon, szLRC_lat, this.oCoordLRDiv );
		    
		} else {
		    alert( 'Internal Error : unable to update infos' );
		}
		
	    } else {
		alert( 'Internal Error : unable to update infos' );
	    }
	},
	
	//Echec de la requete Ajax
	updateDetailFailure: function ( oHttpRequest ) {
	    alert("ERROR") ;
	},	
	
	//cretion du tableau des coord des emprises des quicklook
	createArrayCoord : function ( szProperty_title1, szProperty_title2, 
				      szProperty_content1, szProperty_content2, 
				      oDiv_coord) {
	    
	    oDiv_coord.innerHTML = '<span class=property_title>' 
		+ szProperty_title1 + '</span> : <span class=property_content>' 
		+ szProperty_content1 + '</span><br/><span class=property_title>'
		+ szProperty_title2 + '</span> : <span class=property_content>' 
		+ szProperty_content2 + '</span>';
	},
	
	//--------------------------------------------------------------------------------------
	//--------------------------------------------------------------------------------------
	
	CLASS_NAME: "OpenLayers.ProductMarker"
    }
);

function get_products_per_country(){
    //alert( "get_products_per_country called !!!" ) ;
    
    var poAjax = new Ajax.Request( "get_products.php", 
				   {
				       method: 'get', 
				       onSuccess:updateMarkersSuccess, 
				       onFailure:updateMarkersFailure                         			
				   }
				 );
}

function updateMarkersSuccess( oHttpRequest ) { 
    
    //alert( "updateMarkersSuccess called !!!" ) ;
    
    if (oHttpRequest.readyState == 4) { 
	if (oHttpRequest.status == 200) {
	    
	    // get response as XML DOM and fetch Root Node.
	    var oXmlResponse = oHttpRequest.responseXML ;	
	    var oRootNode = oXmlResponse.documentElement;
	    var aCountries = oRootNode.getElementsByTagName("country");
	    
	    for( iCountryIndex = 0 ; iCountryIndex < aCountries.length ; iCountryIndex++ ){
		
		szName = aCountries[iCountryIndex].getAttribute('name') ;
		szLon  = aCountries[iCountryIndex].getAttribute('lon') ;
		szLat  = aCountries[iCountryIndex].getAttribute('lat') ;
		szCount  = aCountries[iCountryIndex].getAttribute('count') ;
		iCount = parseInt( szCount );
		fLon = parseFloat( szLon ) ;
		fLat = parseFloat( szLat ) ;
		
		var lonlat = new OpenLayers.LonLat(fLon,fLat);
		var icon2 = icon.clone();
		
		var marker = new OpenLayers.ProductMarker(lonlat,icon2,szName,iCount,'tooltip',true,map) ;
		markers.addMarker(marker);
	    }
	} else {
	    alert( 'Error(status) : unable create product markers; please retry later' );
	}
    } else {
	alert( 'Error(readyState) : unable create product markers; please retry later' );
    }
}

function updateMarkersFailure( oHttpRequest ) {
    alert( 'Error(get) : unable create product markers; please retry later' ) ;
}	

