

/// SERVICE PANORAMIO ///
function PanoramioLayerCallback(json, panoLayer) {
  this.panoLayer = panoLayer;

  var batch = [];
  for (var i = 0; i < json.photos.length; i++) {
    var photo = json.photos[i];
    if (!panoLayer.ids[photo.photo_id]) {
      var marker = this.createMarker(photo, panoLayer.markerIcon);
      panoLayer.mgr.addMarker(marker, 0);
      panoLayer.ids[photo.photo_id] = "exists";
    }
  }
//  panoLayer.mgr.addMarkers(batch, 0);
  panoLayer.mgr.addMarkers(batch, panoLayer.map.getZoom());
  panoLayer.mgr.refresh();
}

PanoramioLayerCallback.prototype.formImgUrl = function(photoId, imgType) {
  return 'http://www.panoramio.com/photos/' + imgType + '/' + photoId + '.jpg';
}
 
PanoramioLayerCallback.prototype.formPageUrl = function(photoId) {
  return 'http://www.panoramio.com/photo/' + photoId;
}

PanoramioLayerCallback.prototype.createMarker = function(photo, baseIcon) {
  var me = this;
  var markerIcon = new GIcon(baseIcon);
  markerIcon.image = this.formImgUrl(photo.photo_id, "mini_square");
  var marker = new GMarker(new GLatLng(photo.latitude, photo.longitude), {icon: markerIcon, title: photo.photo_title});

  if (photo.photo_title.length > 33) {
    photo.photo_title = photo.photo_title.substring(0, 33) + "&#8230;";
  }
  var html = "<div id='infowin' style='height:320px; width:240px;'>" +
            "<p><a href='http://www.panoramio.com/' target='_blank'>" + 
             "<img src='http://www.panoramio.com/img/logo-small.gif' border='0' width='119px' height='25px' alt='Panoramio logo' /><\/a></p>" +
             "<a id='photo_infowin' target='_blank' href='" + photo.photo_url + "'>" +                
             "<img border='0' width='" + photo.width + "' height='" + photo.height + "' src='" + photo.photo_file_url + "'/><\/a>" +
             "<div style='overflow: hidden; width: 240px;'>" +
             "<p><a target='_blank' class='photo_title' href='" + photo.photo_url +
             "'><strong>" + photo.photo_title + "<\/strong><\/a></p>" +
             "<p>Posted by <a target='_blank' href='" + photo.owner_url + "'>" +
             photo.owner_name + "<\/a></p><\/div>" +
             "<\/div>";

  marker.html = html;

  GEvent.addListener(marker, "click", function() {
    me.panoLayer.map.openInfoWindow(marker.getLatLng(), marker.html, {noCloseOnClick: true});
  });
 
  return marker;
}


function PanoramioLayer(map, opt_opts) {
  var me = this;
  me.map = map;
  me.ids = {};
  me.mgr = new MarkerManager(map, {maxZoom: 19});

  var icon = new GIcon();
  icon.image = "http://www.panoramio.com/img/panoramio-marker.png"; 
  icon.shadow = "";  
  icon.iconSize = new GSize(24, 24); 
  icon.shadowSize = new GSize(22, 22); 
  icon.iconAnchor = new GPoint(9, 9);  
  icon.infoWindowAnchor = new GPoint(9, 0); 

  me.markerIcon = icon;
  me.enabled = false;

  GEvent.addListener(map, "moveend", function() {
    if (me.enabled) {
      var bounds = map.getBounds();
      var southWest = bounds.getSouthWest();
      var northEast = bounds.getNorthEast();
      me.load(me, {maxy: northEast.lat(), miny: southWest.lat(), maxx: northEast.lng(), minx: southWest.lng()});
    }
  });
}

PanoramioLayer.prototype.enable = function() {
  this.enabled = true;
  GEvent.trigger(map, "moveend");
}

PanoramioLayer.prototype.disable = function() {
  this.enabled = false;
  this.mgr.clearMarkers();
  this.ids = {};
}

PanoramioLayer.prototype.getEnabled = function() {
  return this.enabled;
}

PanoramioLayer.prototype.load = function(panoLayer, userOptions) {
  var options = {
    order: "popularity",
    set: "public",
    from: "0",
    to: "10",
    minx: "-180",
    miny: "-90",
    maxx: "180",
    maxy: "90",
    size: "small"
  };
 
  for (optionName in userOptions) {
    if (userOptions.hasOwnProperty(optionName)) {
      options[optionName] = userOptions[optionName];
    }
  }
 
  var url = "http://www.panoramio.com/map/get_panoramas.php?";
  var uniqueID = "";
 
  for (optionName in options) {
    if (options.hasOwnProperty(optionName)) {
      var optionVal = "" + options[optionName] + "";
      url += optionName + "=" + optionVal + "&";
      uniqueID += optionVal.replace(/[^\w]+/g,"");
    }
  }
  var callbackName = "PanoramioLayerCallback.loader" + uniqueID; //ask dion
  eval(callbackName + " = function(json) { var pa = new PanoramioLayerCallback(json, panoLayer);}");
 
  var script = document.createElement('script');
  script.setAttribute('src', url + 'callback=' + callbackName);
  script.setAttribute('id', 'jsonScript');
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
}

/// SERVICE PANORAMIO ///


		function ZOOMBoutonControl() {}
		ZOOMBoutonControl.prototype = new GControl();
		ZOOMBoutonControl.prototype.initialize = function(MaCarte) {
			var containerZOOM = document.createElement('div');
			containerZOOM.style.backgroundImage = 'url("http://www.pelimmo.com/images/supportgmap.png")';
			containerZOOM.style.backgroundRepeat = 'no-repeat';
			containerZOOM.style.backgroundPosition = 'left';	
			containerZOOM.style.paddingTop = '5px';	
			containerZOOM.style.paddingBottom = '5px';	
			containerZOOM.style.paddingRight = '1px';	
			containerZOOM.style.paddingLeft = '30px';	
			containerZOOM.style.width = '40px';
			
			
			// Cr&eacute;ation du bouton [ Zoom + ]
			var boutonZoomPlus = document.createElement('div');
			this.setButtonStyle_Zoom_(boutonZoomPlus);
			containerZOOM.appendChild(boutonZoomPlus);
			boutonZoomPlus.style.backgroundImage = 'url("http://www.pelimmo.com/images/zoom_in.png")';
			GEvent.addDomListener(boutonZoomPlus, 'click', function() {

					MaCarte.zoomIn();
			});
			GEvent.addDomListener(boutonZoomPlus, 'mouseover', function() {
			});
			GEvent.addDomListener(boutonZoomPlus, 'mouseout', function() {
			});
			
			// Cr&eacute;ation du bouton [ Zoom - ]
			var boutonZoomMoins = document.createElement('div');
			this.setButtonStyle_Zoom_(boutonZoomMoins);
			containerZOOM.appendChild(boutonZoomMoins);
			boutonZoomMoins.style.backgroundImage = 'url("http://www.pelimmo.com/images/zoom_out.png")';
			GEvent.addDomListener(boutonZoomMoins, 'click', function() {
				MaCarte.zoomOut();
			});
			GEvent.addDomListener(boutonZoomMoins, 'mouseover', function() {
			});
			GEvent.addDomListener(boutonZoomMoins, 'mouseout', function() {
			});
			
		
			  MaCarte.getContainer().appendChild(containerZOOM);
			  return containerZOOM;
		}




		// Style des boutons [ Zoom ] de la carte
		ZOOMBoutonControl.prototype.setButtonStyle_Zoom_ = function(button) {
		button.style.textAlign = 'center';
		button.style.display = 'block';
		button.style.width = '32px';
		button.style.height = '32px';
		button.style.cursor = 'pointer';
		}

		// Position des boutons [ Zoom ] de la carte : en haut à droite avec une marge de 0 pixels
		ZOOMBoutonControl.prototype.getDefaultPosition = function() {
			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 7));
		}

		// Création des boutons [ PLAN ] - [ SATELLITE ] - [ MIXTE ] - [ RELIEF ] - [ PANORAMIO ]
		function PSMBoutonControl() {}
		PSMBoutonControl.prototype = new GControl();
		PSMBoutonControl.prototype.initialize = function(MaCarte) {
			var containerPSM = document.createElement('div');
			
			// Cr&eacute;ation du bouton [ Plan ]
			var boutonPlan = document.createElement('div');
			this.setButtonStyle_PSM(boutonPlan);
			containerPSM.appendChild(boutonPlan);
			boutonPlan.appendChild(document.createTextNode('Plan'));
			GEvent.addDomListener(boutonPlan, 'click', function() {
				MaCarte.setMapType(G_NORMAL_MAP);
			});
			GEvent.addDomListener(boutonPlan, 'mouseover', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn_hover.png")';
			});
			GEvent.addDomListener(boutonPlan, 'mouseout', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn.png")';
			});
			
			// Cr&eacute;ation du bouton [ Satellite ]
			var boutonSatellite = document.createElement('div');
			this.setButtonStyle_PSM(boutonSatellite);
			containerPSM.appendChild(boutonSatellite);
			boutonSatellite.appendChild(document.createTextNode('Satellite'));
			GEvent.addDomListener(boutonSatellite, 'click', function() {
				MaCarte.setMapType(G_SATELLITE_MAP);
			});
			GEvent.addDomListener(boutonSatellite, 'mouseover', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn_hover.png")';
			});
			GEvent.addDomListener(boutonSatellite, 'mouseout', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn.png")';
			});
			
			// Cr&eacute;ation du bouton [ Mixte ]
			var boutonMixte = document.createElement('div');
			this.setButtonStyle_PSM(boutonMixte);
			containerPSM.appendChild(boutonMixte);
			boutonMixte.appendChild(document.createTextNode('Mixte'));
			GEvent.addDomListener(boutonMixte, 'click', function() {
				MaCarte.setMapType(G_HYBRID_MAP);
			});
			GEvent.addDomListener(boutonMixte, 'mouseover', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn_hover.png")';
			});
			GEvent.addDomListener(boutonMixte, 'mouseout', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn.png")';
			});
			

			// Cr&eacute;ation du bouton [ Relief ]
			var boutonRelief = document.createElement('div');
			this.setButtonStyle_PSM(boutonRelief);
			containerPSM.appendChild(boutonRelief);
			boutonRelief.appendChild(document.createTextNode('Relief'));
			GEvent.addDomListener(boutonRelief, 'click', function() {
				MaCarte.setMapType(G_PHYSICAL_MAP);
			});
			GEvent.addDomListener(boutonRelief, 'mouseover', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn_hover.png")';
			});
			GEvent.addDomListener(boutonRelief, 'mouseout', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn.png")';
			});
			

			// Cr&eacute;ation du bouton [ Panoramio ]
			var boutonMixte = document.createElement('div');
			this.setButtonStyle_PSM(boutonMixte);
			containerPSM.appendChild(boutonMixte);
			boutonMixte.appendChild(document.createTextNode('Panoramio'));
			GEvent.addDomListener(boutonMixte, 'click', function() {
			    if (this.panoLayer) {
			      if (this.panoLayer.getEnabled()) {
			        this.panoLayer.disable();
			      } else {
			        this.panoLayer.enable();
			      }
			    } else {
			      this.panoLayer = new PanoramioLayer(map);
			      this.panoLayer.enable();
			    }
			});
			GEvent.addDomListener(boutonMixte, 'mouseover', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn_hover.png")';
			});
			GEvent.addDomListener(boutonMixte, 'mouseout', function() {
				this.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn.png")';
			});


			  MaCarte.getContainer().appendChild(containerPSM);
			  return containerPSM;
		}

		// Style des boutons [ Plan ] - [ Satellite ] - [ Mixte ] de la carte
		PSMBoutonControl.prototype.setButtonStyle_PSM = function(button) {
		  button.style.textDecoration = 'none';
		  button.style.color = '#ffffff';
		  button.style.font = '13px Arial';
		  button.style.padding = '0px';
		  button.style.marginBottom = '0px';
		  button.style.lineHeight = '24px';
		  button.style.textAlign = 'center';
		  button.style.width = '100px';
		  button.style.height = '24px';
		  button.style.cursor = 'pointer';
		  button.style.backgroundImage = 'url("http://www.pelimmo.com/images/fondgmap_btn.png")';
		  button.style.backgroundRepeat = 'no-repeat';
		  button.style.backgroundPosition = 'center';
		}
		
		// Position des boutons [ Plan ] - [ Satellite ] - [ Mixte ] de la carte : en haut à gauche avec une marge de 7 pixels
		PSMBoutonControl.prototype.getDefaultPosition = function() {
		  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
		}





// Affichage des services dans la zone indiquée
var chargeServices = function (lat,lng,prox,checktab,zoom){
	var script = document.createElement('script');
	script.src = 'http://www.keltoa.com/testg/sites_template_data_cat.php?prox='+prox+'&lat='+lat+'&lng='+lng+'&checktab='+checktab;
  script.type = 'text/javascript';
	document.body.appendChild(script);
	cm_getJSON(lat,lng,prox);
};

var gestionRetour = function (str){
   document.getElementById('sidebarDIV').innerHTML = str;
};

var gestionErreur = function (){
    document.getElementById('sidebarDIV').innerHTML = 'Service indisponible ou défaillant';
};




// Gestion Map
var map, checktab = ',', toggleState = new Array(), marker = null, mapMarkers = [], mapMeservices = new Array(), mapHTMLS = [], bounds = new GLatLngBounds(), togglePano = 0;


function toggleMyPano() {
  if (togglePano == 1) {
	var pano_layer = new PanoramioLayer(map);
	pano_layer.enable(false);
	togglePano = 0;
  } else {
	var pano_layer = new PanoramioLayer(map);
	pano_layer.enable();
	togglePano = 1;
  }
}
	  


var cm_baseIcon = new GIcon();
cm_baseIcon.iconSize = new GSize(34, 34);
cm_baseIcon.iconAnchor = new GPoint(9, 34);
cm_baseIcon.infoWindowAnchor = new GPoint(9, 2);


var param_useSidebar = true;
var param_titleColumn = "title";
var param_descriptionColumn = "description";
var param_latColumn = "latitude";
var param_lngColumn = "longitude";
var param_idserviceColumn = "idservice";


// GALERIE PANORAMIO
    function jsonpanoramio(url)
    {
      var jstag=document.createElement("script");
      jstag.setAttribute("type", "text/javascript");
      jstag.setAttribute("src", url);
      document.getElementsByTagName("head")[0].appendChild(jstag);
    }

    function traitephotos(datos)
    {
      var fotos = datos['photos'];
      for(var i=0;i<20;i++)
      {
        var url = fotos[i]['photo_file_url'];
        var miimagen = new Image();
        miimagen.src = url;
        $('jsonphotospanoramio').appendChild(miimagen);
      }
    }
//


function load(lat,lng,zoom,prox){
	if (GBrowserIsCompatible()){
	
		var LargeurInitiale = 400 ;    
    map = new GMap2($("map"), { size: new GSize(LargeurInitiale,400) } );
    map.setCenter(new GLatLng(lat, lng, parseInt(zoom)));
    $("map").style.width = "100%";

		//bounds = new GLatLngBounds();

		checktab= ",";

		var f = $("sidebarDIV");
		var inputs = f.getElementsByTagName("input");
		for(var t = 0;t < inputs.length;t++){
			if(inputs[t].type == "checkbox" && inputs[t].checked == true){
				checktab+=inputs[t].id+',';
			}
		}

		//map = new GMap2(document.getElementById("map"));

		mapMarkers = new Array();
		for (var s = 0; s < 500; s++) {
			mapMeservices[s] = new Array();
		}
		for (var s = 0; s < 500; s++) {
			if(checktab.indexOf(",idservice"+s)<0){
				toggleState[s] = 0;
			}
			else{
				toggleState[s] = 1;
			}
		}
		
		map.addControl(new GLargeMapControl());
    map.addControl(new GMenuMapTypeControl(true,false));
    map.addMapType(G_PHYSICAL_MAP);

/*
		map.addMapType(G_PHYSICAL_MAP);
		map.setMapType(G_PHYSICAL_MAP);
		map.addControl(new GScaleControl());                     
		map.addControl(new ZOOMBoutonControl());
		map.addControl(new PSMBoutonControl());

		//map.setCenter(new GLatLng(lat, lng), zoom);
*/
		chargeServices(lat,lng,prox,checktab);

	} else {
		alert("Désolé, les cartes Google ne sont pas compatibles avec votre navigateur");
	} 
}



function detail_service(markerNum) {
	mapMarkers[markerNum].openInfoWindowHtml(mapHTMLS[markerNum]);
}

function close_detail_service(markerNum) {
	mapMarkers[markerNum].closeInfoWindow(mapHTMLS[markerNum]);
}


function togglemarkers(idservice) {
  if (toggleState[idservice] == 1) {
    for (var i=mapMeservices[idservice][0]; i<mapMeservices[idservice][0]+mapMeservices[idservice].length; i++) {
      mapMarkers[i].hide();
    }
    toggleState[idservice] = 0;
  } else {
    for (var i=mapMeservices[idservice][0]; i<mapMeservices[idservice][0]+mapMeservices[idservice].length; i++) {
      mapMarkers[i].show();
    }
    toggleState[idservice] = 1;
  }
} 


function cm_loadMapJSON(json) {

	for (var i = 0; i < json.feed.entry.length; i++) {
	var entry = json.feed.entry[i];
		if(entry["gsx$" + param_latColumn]) {

			var lat = parseFloat(entry["gsx$" + param_latColumn].$t);
			var lng = parseFloat(entry["gsx$" + param_lngColumn].$t);
			var point = new GLatLng(lat,lng);
			var html = "<div style='font-size:12px;'>";
			html += "<strong>" + entry["gsx$"+param_titleColumn].$t + "</strong>";
			var label = entry["gsx$"+param_titleColumn].$t;

			var idservice = parseFloat(entry["gsx$idservice"].$t);

			if(entry["gsx$" + param_descriptionColumn]) {
				html += "<br/>" + entry["gsx$"+param_descriptionColumn].$t;
			}
			html += "</div>";
			
			var marker = cm_createMarker(point,label,html,idservice);
			map.addOverlay(marker);
      			mapMarkers[i] = marker;
			mapHTMLS[i] = html;

			bounds.extend(point);

			mapMeservices[idservice].push(i);
			
      			if(toggleState[idservice]=="0"){
      				mapMarkers[i].hide();
      			}
		}
	}

	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());

	var bounds2 = map.getBounds();
	var southWest = bounds2.getSouthWest();
	var northEast = bounds2.getNorthEast();
	
	var maxy = northEast.lat();
	var miny = southWest.lat();
	var maxx = northEast.lng();
	var minx = southWest.lng();
	
	//jsonpanoramio("http://www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=20&minx="+minx+"&miny="+miny+"&maxx="+maxx+"&maxy="+maxy+"&size=small&callback=traitephotos");
}



function cm_createMarker(point, title, html, idservice) {

	var label1 = 'D&eacute;tail';

	var markerOpts = {};
	var nIcon = new GIcon(cm_baseIcon);
	
	nIcon.image = "http://www.keltoa.com/testg/markers/"+idservice+".png";
	
	markerOpts.icon = nIcon;
	markerOpts.title = title;		 
	var marker = new GMarker(point, markerOpts);
	
	marker.idservice = idservice;
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,html)]);
	});
	return marker;
}



function createMarker_client(point, title, html ) {

	var label1 = 'D&eacute;tail';

	var markerOpts = {};
	var nIcon = new GIcon(cm_baseIcon);
	
	nIcon.image = "arebat.png";
	
	markerOpts.icon = nIcon;
	markerOpts.title = title;		 
	var marker = new GMarker(point, markerOpts);
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,html)]);
	});
	return marker;
}





function cm_getJSON(lat,lng,prox) {
	var scriptjson = document.createElement('script');
	scriptjson.setAttribute('src', 'http://www.keltoa.com/testg/sites_clients_data_json.php?lat='+lat+'&lng='+lng+'&prox='+prox);
	scriptjson.setAttribute('id', 'jsonScript');
	scriptjson.setAttribute('type', 'text/javascript');
	document.documentElement.firstChild.appendChild(scriptjson);
}

