/*
*	BEGIN Fonctions pour les cartes
*/
// nombre de marqueur maximum affiché
var nbMaxMarker=800000;//80
// Minimum de marqueur pouvant être contenus dans un cluster
var nbMinMarker=1;
// nb minimum de point affichés dans l'infobulle
var nbMinMarkerInfo=1;
var json='';
var htmlPoints = new Object();
var var_zoom = 14;
var mapId;

$(document).ready(function() {
	if (mapId) {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById(mapId));
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			map.addControl(new GScaleControl());
	
			GDownloadUrl(SITE_ROOT+"markers.php", setup_json);
			GDownloadUrl(SITE_ROOT+"markersStructure.php", setup_json);
				
			// centre par défaut : ici lat/lng de la manif définis dans le fichier php
			var center = new GLatLng(lat, lng);
			
			// centrage de la carte sur paris
			var zoom = var_zoom;
			
			map.setCenter(center,zoom);
			set_corner(center);
		}
	}
	
	if (!$.browser.msie || ($.browser.msie && $.browser.version.substr(0, 1) >= 7)) {
		$('.dk').dropkick({
			width: '180px'
		});
		
		$('.dk_contact').dropkick({
			theme:'orange'
		});
	}


});
function createMarker(point, html, iconimg) { 
	var iconFinal = new GIcon(); 
	iconFinal.image = iconimg; // image du curseur
	iconFinal.iconSize = new GSize(32, 32); 
	iconFinal.iconAnchor = new GPoint(15, 32);
	iconFinal.infoWindowAnchor = new GPoint(15, 9);
	
	var marker = new GMarker(point,iconFinal);
	GEvent.addListener(marker, "click", function() {
	
		//console.log(marker.getLatLng().lat(), marker.getLatLng().lng());
		marker.openInfoWindowHtml("<div style='display:block;padding:0 0 20px 0;height:110%;'>"+htmlPoints["lat"+marker.getLatLng().lat()+"lng"+marker.getLatLng().lng()]+"</div>");
	});
	
	return marker;
}
function setup_json(json) { 
	var data = eval('('+json+')');
	for (var i=0; i<data["markers"].length; i++) {
		//console.log(data["markers"][i]["lat"], data["markers"][i]["lng"]);
		if (htmlPoints["lat"+data["markers"][i]["lat"]+"lng"+data["markers"][i]["lng"]] == undefined) {
			htmlPoints["lat"+data["markers"][i]["lat"]+"lng"+data["markers"][i]["lng"]] = data["markers"][i]["html"];
		} else {
			htmlPoints["lat"+data["markers"][i]["lat"]+"lng"+data["markers"][i]["lng"]] += "<hr style='margin:5px 0'/>"+data["markers"][i]["html"];
		}
		var point = new GLatLng(data["markers"][i]["lat"], data["markers"][i]["lng"]);
		var marker_point = createMarker(point, data["markers"][i]["html"], data["markers"][i]["iconimg"]);
		//clusterer.AddMarker(marker_point, data["markers"][i]["titre"]);
		map.addOverlay(marker_point);
	}
};
// créer un point sur la carte a partir d'une adresse , nom de ville pays etc ...
function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					document.getElementById("error_msg").innerHTML= " \"" + address + "\" est introuvable ";			
					
					// centre par défaut : ici lat/lng de la manif définis dans le php
					var point = new GLatLng(lat, lng);
					var zoom = var_zoom;		
					//map.clearOverlays();
					map.setCenter(point, zoom);
				} else {
					document.getElementById("error_msg").innerHTML="";
					document.getElementById("lat").value = point.lat().toFixed(5);
					document.getElementById("lng").value = point.lng().toFixed(5);
				}	
				set_corner(point);
			}
		);
	}
}
// set_corner est toujours appelé lorsqu'on a determiné le centre de la carte . Elle permet de déterminer les coordonnées géo de la zone d'affichage en fct du zoom utilisé
// zoom possible 16/13/7/5
function set_corner(point){
	var array_zoom=new Array(13,10,8,6);
	boucle=0;
	zoom=array_zoom[array_zoom.length-1];
	var currentProjection = G_NORMAL_MAP.getProjection();
	var centre=point;
	var array_coord=new Array();
	while (boucle<array_zoom.length ) {
		centre_xy = currentProjection.fromLatLngToPixel(centre, array_zoom[boucle]);
		
		A_point=new GPoint(centre_xy.x-250,centre_xy.y-250);	
		tilePointA = currentProjection.fromPixelToLatLng(A_point,  array_zoom[boucle]);
		B_point=new GPoint(centre_xy.x+250,centre_xy.y+250);	
		tilePointB = currentProjection.fromPixelToLatLng(B_point,  array_zoom[boucle]);
		
		array_coord[boucle]=array_zoom[boucle]+"/"+tilePointA.lat()+"/"+tilePointA.lng()+"/"+tilePointB.lat()+"/"+tilePointB.lng();
		
		boucle=boucle+1;
	}
	
	$.get(SITE_ROOT+'inc/get_nb_manif_perim.php', 
		{ zoom_1:array_coord[0] , zoom_2:array_coord[1] , zoom_3:array_coord[2] , zoom_4:array_coord[3] } ,
		function (data){
			$("#zoom").val(data);
			map.setCenter(point, var_zoom);			
			centre_xy = currentProjection.fromLatLngToPixel(centre, data);
	
			A_point=new GPoint(centre_xy.x-250,centre_xy.y-250);	
			tilePointA = currentProjection.fromPixelToLatLng(A_point,  data);
			B_point=new GPoint(centre_xy.x+250,centre_xy.y+250);	
			tilePointB = currentProjection.fromPixelToLatLng(B_point,  data);
			
			affiche_manif(tilePointA.lat(),tilePointA.lng(),tilePointB.lat(),tilePointB.lng());
		}	
	);
}
function affiche_manif(lata,lnga,latb,lngb){
	$.get(SITE_ROOT+'inc/get_manifs_geoloc2.php', 
		{lat_a:lata,lng_a:lnga,lat_b:latb,lng_b:lngb},
		function(data){
			$("#result").html(data);
		}
	);
}



/*function initFormContact() {
	if ($("#formContact")) {
		$("#formContact").validate();
	}
}*/

function initFormAutour() {
	if ($("#autour")) {
		var autour = $("#autour");
		var defaultVal = "Adresse, code postal ou ville";
		autour.val(defaultVal);
		autour.focus(function() {
			if (autour.val() == defaultVal) {
				autour.val("");
			}
		});
		autour.focusout(function() {
			if (autour.val() == "") {
				autour.val(defaultVal);
			}
		});
	}
}

function initFormAutour2() {
	if ($("#autour2")) {
		var autour = $("#autour2");
		var defaultVal = "...saisissez votre adresse";
		//var defaultVal = "perpignan";
		autour.val(defaultVal);
		autour.focus(function() {
			if (autour.val() == defaultVal) {
				autour.val("");
			}
		});
		autour.focusout(function() {
			if (autour.val() == "") {
				autour.val(defaultVal);
			}
		});
		
		$("#filterAutour2").submit(function(e) {
			if($("#autour2").val() != "" && $("#autour2").val() != defaultVal) {
				$.get("inc/get_dpt_pred_de_chez_vous.php", {
					q:$("#autour2").val(),
					idBaseDpt:$("#idBaseDpt").val()},
					function(data) {
						$("#departement").hide();
						$("#presDeChezVous").show();
						if (data != "") {
							
							var parts = data.split("***");
							
							// lieux de remise
							$("#listeVillesPresDeChezVous").html(parts[0]);
							var nbResult = $("#countLieuxResult").html();
							if (nbResult == 1) {
								var msg = nbResult+" lieu de remise près de chez vous";
							} else {
								var msg = nbResult+" lieux de remise près de chez vous";
							}
							$("#countLieuxPresDeChezVous").html(msg);
							$("#listeVillesPresDeChezVous>li").tsort({attr:"rel"});
							
							// events à venir
							$("#departement2").hide();
							$("#presDeChezVous2").show();
							$(".ajaxResults").html(parts[1]);
							$(".ajaxResults .hiddenresult>li").tsort({attr:"rel"});							
							dptPagination("#presDeChezVous2 .ajaxResults");
							
						} else {
							$("#listeVillesPresDeChezVous").html("");
							$("#countLieuxPresDeChezVous").html("Aucun résultat");
						}
					}
				);
  			}
			e.preventDefault();
		});
	}
}

function initFormAlert() {
	if ($("#alertEmail")) {
		var alertEmail = $("#alertEmail");
		var alertEmailDefaultVal = "Adresse e-mail";
		alertEmail.val(alertEmailDefaultVal);
		alertEmail.focus(function() {
			if (alertEmail.val() == alertEmailDefaultVal) {
				alertEmail.val("");
			}
		});
		alertEmail.focusout(function() {
			if (alertEmail.val() == "") {
				alertEmail.val(alertEmailDefaultVal);
			}
		});
	}
	if ($("#alertAdresse")) {
		var alertAdresse = $("#alertAdresse");
		var alertAdresseDefaultVal = "Votre adresse";
		alertAdresse.val(alertAdresseDefaultVal);
		alertAdresse.focus(function() {
			if (alertAdresse.val() == alertAdresseDefaultVal) {
				alertAdresse.val("");
			}
		});
		alertAdresse.focusout(function() {
			if (alertAdresse.val() == "") {
				alertAdresse.val(alertAdresseDefaultVal);
			}
		});
	}
	if ($(".alerteOpener")) {
		$(".alerteOpener").colorbox({width:500, height:400, iframe:true});
	}
}


function checkFormAlert() {
	var adresse= $("#Alertadresse").val();
	var email=$("#Alertemail").val();
	var delai=$("#Alertdelai").val();
	var distance=$("#Alertdistance").val();
	var errorString="";
	mymatch = email.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]{2,}[.][a-zA-Z]{2,5}$/);	
	if (adresse=="" || delai=="" || distance=="") errorString+="Tous les champs doivent être renseignés<br/>";
	if (mymatch === null) errorString+="Email erroné<br/>";
	if (errorString!="") {
		//alert(errorString);
		$("#formAlerte").prepend("<div id='ErrorAlert' style='position:absolute;top:160px;left:30px;width: 150px;background:#cc0000;color:#fff;text-align:center;padding:5px;z-index:10000'>"+errorString+"<br/><a href='' onClick='$(\"#ErrorAlert\").detach();return false;' style='color:#fff;margin-top:20px'>Fermer</a></div>");
		
		return false;
	} else $("#formAlerte").submit();
	

}

function repriseFormAlerte() {
	var adresse= $("#Alerte2Adresse").val();
	var email=$("#Alerte2Email").val();
	var delai=$("#Alerte2Delai").val();
	var distance=$("#Alerte2Distance").val();
	var errorString="";
	mymatch = email.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]{2,}[.][a-zA-Z]{2,5}$/);	
	if (adresse=="" || delai=="" || distance=="") errorString+="Tous les champs doivent être renseignés<br/>";
	if (mymatch === null) errorString+="Email erroné<br/>";
	if (errorString!="") {
		//alert(errorString);
		$("#repriseFormAlerte").prepend("<div id='ErrorAlert' style='position:absolute;top:850px;left:0px;width: 400px;background:#cc0000;color:#fff;text-align:center;padding:5px;z-index:10000'>"+errorString+"<br/><a href='' onClick='$(\"#ErrorAlert\").detach();return false;' style='color:#fff;margin-top:20px'>Fermer</a></div>");
		
		return false;
	} else $("#repriseFormAlerte").submit();
	

}


function dptPagination(containerId) {
	var items_per_page = 3;
	var num_entries;
	
	function pageselectCallback(page_index, jq){
		var start = page_index*items_per_page;
		var end = Math.min(num_entries, start+items_per_page);
		$(containerId+" .Searchresult").empty();
		for(var i=start; i < end; i++)
		{
			
			var new_content = jQuery(containerId+" .hiddenresult li.result:eq("+i+")").clone();
			$(containerId+" .Searchresult").append(new_content);
		}
		return false;
	}
	
	function initPagination() {
		// count entries inside the hidden content
		num_entries = jQuery(containerId+" .hiddenresult li.result").length;
		// Create content inside pagination element
		$(containerId+" .Pagination").pagination(num_entries, {
			items_per_page: items_per_page,
			num_display_entries:8,
			callback: pageselectCallback
		});
	}
	
	initPagination();
}

function empty (mixed_var) {
	var key;    
    if (mixed_var === "" ||  mixed_var === 0 ||  mixed_var === "0" ||   mixed_var === null ||   mixed_var === false || typeof mixed_var === 'undefined'){ return true;} 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }        return true;
    }
    return false;
}
