/*
 +-------------------------------------+
 Number.prototype.nombreFormate
 +-------------------------------------+
 Params (facultatifs):
 - Int decimales: nombre de decimales (exemple: 2)
 - String signe: le signe precedent les decimales (exemple: "," ou ".")
 - String separateurMilliers: comme son nom l'indique
 Returns:
 - String chaine formatee
*/
Number.prototype.nombreFormate = function (decimales, signe, separateurMilliers) {
     var _sNombre = String(this), i, _sRetour = "", _sDecimales = "";
     if (decimales == undefined) decimales = 2;
     if (signe == undefined) signe = '.';
     if (separateurMilliers == undefined) separateurMilliers = ' ';
     
     //-- Fonction qui fait la separation des milliers
     function separeMilliers (sNombre) {
        var sRetour = "";
          while (sNombre.length % 3 != 0) {
            sNombre = "0"+sNombre;
          }
          for (i = 0; i < sNombre.length; i += 3) {
            if (i == sNombre.length-1) separateurMilliers = '';
            sRetour += sNombre.substr(i, 3)+separateurMilliers;
          }
          while (sRetour.substr(0, 1) == "0") {
            sRetour = sRetour.substr(1);
          }
          return sRetour.substr(0, sRetour.lastIndexOf(separateurMilliers));
     }
     //-- S'il n'y a pas de decimales
     if (_sNombre.indexOf('.') == -1) {
         for (i = 0; i < decimales; i++) {
            _sDecimales += "0";
         }
         _sRetour = separeMilliers(_sNombre); //+signe+_sDecimales;
         if (parseInt(_sDecimales) > 0){
            _sRetour = _sRetour+signe+_sDecimales;
         }
     } else {
     //-- Il y a des decimales
        var sDecimalesTmp = (_sNombre.substr(_sNombre.indexOf('.')+1));
        if (sDecimalesTmp.length > decimales) {
            var nDecimalesManquantes = sDecimalesTmp.length - decimales;
            var nDiv = 1;
            for (i = 0; i < nDecimalesManquantes; i++) {
              nDiv *= 10;
            }
            _sDecimales = Math.round(Number(sDecimalesTmp) / nDiv);
        }
        _sRetour = separeMilliers(_sNombre.substr(0, _sNombre.indexOf('.')));
        if (parseInt(_sDecimales) > 0){
            _sRetour = _sRetour+String(signe)+_sDecimales;
        }
     }
     return _sRetour;
}

var map = null;
var geocoder = null;
var adrTest = null;
var tbAdr = new Array();
var pointCollection = new Array();
var AddressCollection = new Array();

function search(){
    //-- Paramètres
	var param = "";
    //-- Operation
    /*
	if (document.getElementById('raNatbien').value > 0){
        param += "operation="+document.getElementById('raNatbien').value+"&"; 
    }
    //-- Surf Mini
    if (document.getElementById('raSurfacemini').value > 0){
        param += "surf_min="+document.getElementById('raSurfacemini').value+"&"; 
    }
    //-- Prix Max
    if (document.getElementById('raBudgetmaxi').value > 0){
        param += "prix_max="+document.getElementById('raBudgetmaxi').value+"&"; 
    }
    //-- Situation geo
    if (document.getElementById('raVille').value > 0){
        param += "situation="+document.getElementById('raVille').value+"&"; 
    }
    //-- Formattage
    if (param.substr((param.length - 1),1) == "&"){
        param = param.substring(0,(param.length-1));
    }
	*/
    //--------------
    //alert(param);
    new xhr("GET","api.php",param,function(p){ /*alert(p);*/DisplayMarkers(p); }); //oTV //
}

function load()
{
var niveauZoom;

if (GBrowserIsCompatible()){

	   	  map = new GMap2(document.getElementById("map"));
		  map.addControl(new GSmallMapControl());
		  map.addControl(new GMapTypeControl());
		  		  
		  //Centrer sur la france
   	  	  map.setCenter(new GLatLng(47.010225655683485, 3.14208984375), 6);
		  geocoder = new GClientGeocoder();
		  
		  G_PHYSICAL_MAP.getMaximumResolution = function () { return 10 };
		  G_NORMAL_MAP.getMaximumResolution = function () { return 10 };
		  G_SATELLITE_MAP.getMaximumResolution = function () { return 10 };
		  G_HYBRID_MAP.getMaximumResolution = function () { return 10 }; 
		  
		  GEvent.addListener(map, "zoomend", function(){
			niveauZoom = map.getZoom();
		  	if(niveauZoom>10){map.disableDoubleClickZoom();}
		  });

		  //resizeMap();
      		  
	 }
}

function DisplayMarkers(adr)
{
  	//pour debug --> Affichage à droite des annonces renvoyées
	//document.getElementById("debug").innerHTML = adr;
	
	//alert(adr);
	//-- On récup les données du champ, et transforme en tableau
  	tbAdr = eval(adr); //eval(document.getElementById('A2').value);
  	//--tbAdr = eval(opener.document.getElementById('A2').value);
  	var x = 0;
  	map.clearOverlays();
  	//-- Parcours du tableau
  	for (i=0;i<tbAdr.length;i++){
  	    //alert(tbAdr[i][2]);
  	    if (tbAdr[i][2] != null){
        		
				var latitude =  tbAdr[i][2];
				var longitude =  tbAdr[i][3];
        		//alert(obj.Status.code);
    		    
    			
                 var icon = getIcone(tbAdr[i][4]);
    			
    	           var point = new GLatLng(latitude,longitude);
    		     	   var marker = new GMarker(point,icon);
    		     	   marker.nb = i;
    		     	   marker.cod = tbAdr[i][0];
    		     	   //alert(marker.cod);
    		     	   marker.txt = tbAdr[i][1];
    		     	   //marker.ph = tbAdr[i][3];
    		     	   marker.prx = (tbAdr[i][5] * 1);
    		     	   marker.rep = tbAdr[i][6];
    		     	   map.addOverlay(marker);
    		     	   GEvent.addListener(marker, "click", function() {
//     		     	      var phHTML = "";
//     		     	      if (this.ph != ""){
//                         phHTML = "<td style='margin-right: 5px;'><img src='"+this.ph+"' border='0'></td><td width='10px'>&nbsp;</td>";
//                     }
//     		     	      var txtHtml = "";
//                     txtHtml += "<table cellspacing='0' cellpadding='0' border='0' width='100%'>";
//                     txtHtml += "<tbody><tr><td colspan='3'>";
//                     txtHtml += "<div align='left' style='float: left;'><b>R&eacute;f : </b>"+this.cod+"&nbsp;&nbsp;&nbsp;<b>Prix : </b>"+this.prx.nombreFormate(0)+"&euro;</div>";
//                     txtHtml += "<div align='right' style='width: 100px;float: right;'><a href='#' style='margin-right: 15px;' onclick=\"MapToFiche('"+this.cod+"');\">Ouvrir ce bien</a></div>";
//                     txtHtml += "</td></tr>";
//     		     	      txtHtml += "<tr><td colspan='3'><hr></td></tr>";
//                     txtHtml += "<tr>" + phHTML + "<td style='font-family: Arial,Times New Roman, Verdana;font-size: 14px;'><span>" + this.txt + "</span></td></tr>";
//                     txtHtml += "<tr><td colspan='3'>&nbsp;</td></tr></tbody>";
//                     txtHtml += "</table><br>";
//    	    			    this.openInfoWindowHtml(txtHtml);

                      //-- PIge Batiments
//                       if (prv == "IM"){
//                           this.openInfoWindowHtml(getBulleBatiments(this.cod,this.prx,this.txt,this.rep));
//                       }
//                       //-- Biens
//                       else if (prv == "BI") {
                          this.openInfoWindowHtml(getBulleBiens(this.cod,this.prx,this.txt), {maxWidth: 300});
//                       }
//                       else if (prv == "AQ") {
//                           this.openInfoWindowHtml(getBulleBiens(this.ph,this.cod,this.prx,this.txt));
//                       }
    	  		     });
    	  		     
    			       if (x == 0){
    				        map.setCenter(point, 8);
                 }
                 x++;
    		    
		    }
  	}
}

function getBulleBiens(code,prix,texte){

    	var phHTML = "";
    	
		var smallcode = code.substr(6);
		
    	var txtHtml = "";
      txtHtml += "<table cellspacing='0' cellpadding='0' border='0' width='100%'>";
      txtHtml += "<tbody><tr><td colspan='3'>";
      txtHtml += "<div align='left' style='float: left; color:#000;'><b>R&eacute;f : </b>"+smallcode+"&nbsp;&nbsp;&nbsp;<b>Prix : </b>"+prix.nombreFormate(0)+"&euro;</div>";
      txtHtml += "<div align='right' style='width: 100px;float: right; color:#000;'><a href='annonce-"+code+".html' class='web' style='margin-right: 15px;'>Fiche du bien</a></div>";
      txtHtml += "</td></tr>";
    	txtHtml += "<tr><td colspan='3'><hr></td></tr>";
      txtHtml += "<tr>" + phHTML + "<td style='font-family: Arial,Times New Roman, Verdana;font-size: 14px; color:#000;'><span>" + texte + "</span></td></tr>";
      txtHtml += "<tr><td colspan='3'>&nbsp;</td></tr></tbody>";
      txtHtml += "</table><br>";
      
      return txtHtml;
      
}

function getBulleBatiments(code,nbAppart,adresse,rep){
      
      var pluriel = "";
      var txtHtml = "";
      var dont = "";
      txtHtml += "<table cellspacing='0' cellpadding='0' border='0' width='100%'>";
      txtHtml += "<tbody><tr><td colspan='3'>";
      txtHtml += "<div align='left' style='float: left;'><b>R&eacute;f : </b>"+code+"</div>";
      txtHtml += "<div align='right' style='width: 100px;float: right;'><a href='#' style='margin-right: 15px;' onclick=\"ImMapToFiche('"+code+"');\">Descriptif</a></div>";
      txtHtml += "</td></tr>";
    	txtHtml += "<tr><td colspan='3'><hr></td></tr>";
      txtHtml += "<tr><td style='font-family: Arial,Times New Roman, Verdana;font-size: 14px;'><span><b>Adresse: </b><br />&nbsp;&nbsp;&nbsp;" + adresse + "</span></td></tr>";
      if (parseInt(nbAppart)>0){
          if (parseInt(nbAppart) > 1){
              pluriel = "s";
          }else{
              pluriel = "";
          }
          if (rep != ""){
              dont = "dont:";
          }
          txtHtml += "<tr><td colspan='3'>&nbsp;</td></tr></tbody>";
          txtHtml += "<tr><td style='font-family: Arial,Times New Roman, Verdana;font-size: 14px;'><span><b>R&eacute;partition:</b><br />&nbsp;&nbsp;&nbsp;" + nbAppart + " habitation"+pluriel+" "+dont+"</span></td></tr>";
          if (rep != ""){
              txtHtml += "<tr><td style='font-family: Arial,Times New Roman, Verdana;font-size: 14px;'><span>" + rep + "</span></td></tr>";
          }
      }
      txtHtml += "<tr><td colspan='3'>&nbsp;</td></tr></tbody>";
      txtHtml += "</table><br>";            
      return txtHtml;
      
}

function MapToFiche(bicod)
{
    if (opener.document.getElementById("BISELEC")){
      opener.document.getElementById("BISELEC").value = "MAPFFS";
      opener.document.getElementById("BISELECMAP").value = bicod;
      opener.goFiche();
      return false;
    }else{ 
        //-- 5 premiers pour les descriptifs, les autres pour chaque autre page des biens
        var tbAlias = ['M21','A184','A105','A80','M27','A197','A203','A224','INFOBICOD','A119','M26','A221','A2','A211'];
        var inputs = opener.document.getElementsByTagName("INPUT");
        for (x=0;x<inputs.length;x++){
            for (i=0;i<tbAlias.length;i++){
                if (inputs[x].id == tbAlias[i])
                {
                    inputs[x].value = bicod;
                    opener.goFiche();
                    return false;
                }
            }
        }
    }
}

function ImMapToFiche(imcod){
    //-- La liste
    if (opener.document.getElementById("REFFROMMAP")){
      opener.document.getElementById("REFFROMMAP").value = imcod;
      //--opener.document.getElementById("BISELECMAP").value = bicod;
//       alert("JS : " + opener.document.getElementById("REFFROMMAP").value);
      opener.DescFromMap();
      return false;
    }
    //-- Les autres pages
    else{ 
        //-- 5 premiers pour les descriptifs, les autres pour chaque autre page des biens
        var tbAlias = ['A59','REFFROMMAP','A71'];
        var inputs = opener.document.getElementsByTagName("INPUT");
        for (x=0;x<inputs.length;x++){
            for (i=0;i<tbAlias.length;i++){
                if (inputs[x].id == tbAlias[i])
                {
                    inputs[x].value = imcod;
                    opener.DescFromMap();
                    return false;
                }
            }
        }
    }
}

function getIcone(operation)
{
    var im = "";
    //-- Maison + Viager
    if (operation == 2 || operation == 7 || operation == 5){
        im = "http://srvlinux2.technolog.fr/vitrinesV4/img/marker.png";
    		var icon = new GIcon();
    		icon.image = im;
    		icon.iconSize = new GSize(22, 22);
    		icon.iconAnchor = new GPoint(6, 20);
    		icon.infoWindowAnchor = new GPoint(5, 1);
    }
    //-- Appart + Immeuble
    if (operation == 1 || operation == 6 || operation == 12 || operation == 0){
        im = "http://srvlinux2.technolog.fr/vitrinesV4/img/markerAppart.png";
    		var icon = new GIcon();
    		icon.image = im;
    		icon.iconSize = new GSize(22, 31);
    		icon.iconAnchor = new GPoint(6, 20);
    		icon.infoWindowAnchor = new GPoint(5, 1);
    }
    //-- Terrain
    if (operation == 3 || operation == 8){
        im = "http://srvlinux2.technolog.fr/vitrinesV4/img/markerTerrain.png";
    		var icon = new GIcon();
    		icon.image = im;
    		icon.iconSize = new GSize(22, 22);
    		icon.iconAnchor = new GPoint(6, 20);
    		icon.infoWindowAnchor = new GPoint(5, 1);
    }
    //-- Commerce
    if (operation == 4 || operation == 9 || operation == 13){
        im = "http://srvlinux2.technolog.fr/vitrinesV4/img/marker.png";
    		var icon = new GIcon();
    		icon.image = im;
    		icon.iconSize = new GSize(22, 22);
    		icon.iconAnchor = new GPoint(6, 20);
    		icon.infoWindowAnchor = new GPoint(5, 1);
    }
    //-- Parking
    if (operation == 10 || operation == 11){
        im = "http://srvlinux2.technolog.fr/vitrinesV4/img/marker.png";
    		var icon = new GIcon();
    		icon.image = im;
    		icon.iconSize = new GSize(22, 22);
    		icon.iconAnchor = new GPoint(6, 20);
    		icon.infoWindowAnchor = new GPoint(5, 1);
    }
		
		return icon;		
}

function resizeMap()
{
	dv = document.getElementById("map");
	dv.style.height = document.body.clientHeight - 10;
	dv.style.width = document.body.clientWidth - 10;
}

function init()
{
	load();
	DisplayMarkers();
}

function redim()
{
	window.resizeTo(800,600);
}

//window.onresize = resizeMap;

