google.load("maps", "2.x");

var map = null;
var geocoder = null;
var bounds = null;
var adresses = null;
var points = null;
var pointsCpt = null;

/*
* Initialisation de googleMap et StreetView
*/
function initializeGoogleMap() {
  if (GBrowserIsCompatible()) {	  	
	init();
  }
}

/*
init
*/
function init(){
	
	/** Google Map **/
	map = new google.maps.Map2(document.getElementById("googleMap")); // 721x530
	map.setCenter(new GLatLng(45.545447,-73.639076), 11);
	
	geocoder = new google.maps.ClientGeocoder();
	
	showControl();
	newSearch();	
}
/*
Affiche les controles de la carte
*/
function showControl(){
	//http://code.google.com/intl/fr/apis/maps/documentation/reference.html#GMapUIOptions
	var customUI = map.getDefaultUI();
    map.setUI(customUI);
}

/*
Nouvelle recherche, appelée en premier lors d'une recherche
*/
function newSearch() {
	
	bounds = new GLatLngBounds();
	
	adresses = new Array();
	points = new Array();	
	map.clearOverlays();
	
	pointsCpt = 0;
	toggleForm(false);
	loadAddresses();
}

/*
Load les adresses en AJAX, selon les critères de recherche
*/
function loadAddresses(){
	
	
	// Récupère les filtres  
	var quartier = $("select#parQuartier").val();
	var type = $("select#typePropriete").val();
	var prix = $("select#prixDemande").val();
	
	// Options services
	var servicesOptions = $("input.inCheck:checked");
	var services = new Array;
	servicesOptions.each(function(){
		if ( $(this).is(":checked") ) 
			services.push($(this).val());		
	});
	
	//alert("Quartier: "+quartier+"\nType: "+type+"\nPrix: "+prix);
	// Ajax
	$.ajax({
		   type: "GET",
		   url: "lib/ajax/carteInteractive.ajax.php",
		   cache:false,
		   dataType:"json",
		   data: "quartier="+quartier+"&type="+type+"&prix="+prix+"&services="+services.join(","),
		   success: function(json_response){
				 if (json_response["code"] == "noresult") {
					noResult();
				 } else {
					adresses = formatJsonAddresses(json_response);
				 	loadPoints();
				 }
		   	}
		   });
}
/*
Load les points un par un, de façon récusrsive
*/
function loadPoints() {
	for (var i = 0; i < adresses.length; i++) {
		var coordinates = adresses[i].ll.split(",");
		var point = new GLatLng(coordinates[0], coordinates[1]);
		if (point) {
			points[i] = point;
			if(adresses[i].type=="PROP") bounds.extend(points[i]); // Ajoute le point aux limites
		}
	}
	showPoints();
}
/*function loadPoints() {
	
	var address = adresses[pointsCpt].address;
	
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					$("#googleLog").html($("#googleLog").html()+address+" pas trouvée.<br />");
				} else {	
					//alert(address + " found!");
					points[pointsCpt] = point; // on enregistre le point
				}
				pointsCpt++;
				if (pointsCpt < adresses.length) waitandLoadPoint(); //loadPoints(); // Load le point suivant
				else showPoints(); // Load des points complété
			});
		
	}
}

function waitandLoadPoint() {
	var timeout = 225;
	window.setTimeout("loadPoints()", timeout);
}*/

/*
Affiche les points propriétés
*/
function showPoints(){
	
	setMapZoomAndCenter();
	
	for (var i = 0; i < adresses.length; i++){
		if (points[i] != undefined) {
			createIcon(i, adresses[i].type);
		}
	}
	
	toggleForm(true);
}
/*
Zoom/center selon les bounds
*/
function setMapZoomAndCenter(){
	var zoom = Math.min(17, map.getBoundsZoomLevel(bounds))
	map.setZoom(zoom);
    map.setCenter(bounds.getCenter());
}

/*
* Création d'un icone
*/
function createIcon(index, type){
	
	if (type=="PROP") {
		createProprieteIcon(index);
	} else {
		createServiceIcon(index, type);
	}
}

/* 
* Création d'un icone particulier pour les propriétées
*/
function createProprieteIcon(index){
	
	var html;
	var point = points[index];
	//adresses[i].html
	
	// Création d'un marqueur
	var myIcon = new GIcon(G_DEFAULT_ICON);
	myIcon.image = "images/marker.png";
	myIcon.iconSize = new GSize(15, 16);
	myIcon.iconAnchor = new GPoint(8, 16);
	myIcon.shadow = "";
	/*myIcon.iconSize = new GSize(22, 31);
	myIcon.shadow = "my_custom_icon_shadow.png";
	myIcon.shadowSize = new GSize(42, 31);
	
	myIcon.infoWindowAnchor = new GPoint(10, 14);
	myIcon.printImage = "my_custom_icon_print.gif";
	myIcon.mozPrintImage = "my_custom_icon_mozPrint.gif";
	myIcon.printShadow = "my_custom_icon_printShadow.gif";
	myIcon.transparent = "my_custom_icon_transparent.png";
	myIcon.imageMap = [ 10,29, 1,16, 0,5, 5,0, 12,4, 18,2, 21,12, 21,16 ]; */		  		  
	var markerOptions = { icon:myIcon };		  
	var marker = new GMarker(point, markerOptions);
	map.addOverlay(marker);
	
	html = '<div id="GMapInfoWindow">';
	if (adresses[index].image!= "") html+= '<div class="photo"><a href="proprietes-resultats.php?reset=true&id_quartier=0&id_typePropriete=0&prixDemande=0&MLSSIA='+adresses[index].sia+'"><img src="'+adresses[index].image+'"></a></div>';
	html+= '<ul class="noBullet details">';
	html+= '<li class="adresse">'+adresses[index].adresse+'</li>';
	html+= '<li class="sia">'+textes["MLS_SIA"]+' : <span>'+adresses[index].sia+'</span></li>';
	html+= '<li class="prix">'+textes["PRIX"]+' : <span>'+adresses[index].prix+adresses[index].prixExtra+'</span></li>';
	//html+= '<li class="lien"><a href="proprietes-'+adresses[index].sia+'.html">'+textes["VOIR_LES_DETAILS"]+'</a></li>';
	html+= '<li class="lien"><a href="proprietes-resultats.php?reset=true&id_quartier=0&id_typePropriete=0&prixDemande=0&MLSSIA='+adresses[index].sia+'">'+textes["VOIR_LES_DETAILS"]+'</a></li>';
	html+= '</ul></div>';
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});	
}
/* 
* Création d'un icone particulier pour les services
*/
function createServiceIcon(index, type) {
	var html;
	var point = points[index];
	
	//if (!bounds.containsLatLng(point)) return;
	
	// Création d'un marqueur
	var myIcon = new GIcon(G_DEFAULT_ICON);
	switch(type) {
		case "ECOL" :
			myIcon.image = "images/ecole.png";
			myIcon.iconSize = new GSize(15, 15);
			myIcon.iconAnchor = new GPoint(8, 15);
			break;
		case "GARD" :
			myIcon.image = "images/garderie.png";
			myIcon.iconSize = new GSize(16, 13);
			myIcon.iconAnchor = new GPoint(8, 13);
			break;
		case "CINE" :
			myIcon.image = "images/cinema.png";
			myIcon.iconSize = new GSize(15, 13);
			myIcon.iconAnchor = new GPoint(8, 13);
			break;
		case "THEA" :
			myIcon.image = "images/theatre.png";
			myIcon.iconSize = new GSize(20, 13);
			myIcon.iconAnchor = new GPoint(10, 13);
			break;
	}
	myIcon.shadow = "";
	
	var markerOptions = { icon:myIcon };	
	var marker = new GMarker(point, markerOptions);
	map.addOverlay(marker);
	
	html = '<div id="GMapInfoWindow">';
	html+= '<ul class="noBullet details">';
	html+= '<li class="adresse">'+adresses[index].label+'</li>';
	html+= '<li>'+adresses[index].adresse+'</li>';
	html+= '</ul></div>';
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});	
}

/*
Formatte un résultat AJAX envoyé en JSON
*/
function formatJsonAddresses(json)
{
	var addressesArr = new Array();
	for(var i=0; i < json.length; i++) {
		addressesArr[i] = {
							sia	:	json[i].sia, 
							ll :	json[i].ll, 
							prix :	json[i].prix,
							prixExtra :	json[i].prixExtra, 
							label :	json[i].label,
							adresse:json[i].adresse, 
							image :	json[i].image,
							type :	json[i].type
							};
	}
	return addressesArr;
}

/*
aucun résultat apres la recherche
*/
function noResult() {
	toggleForm(true);
}

/*
active/désactive le formulaire de recherche
*/
function toggleForm(flag)
{
	if (flag) {
		$("#btnActualiser, select#parQuartier, select#typePropriete, select#prixDemande").attr("disabled", "").fadeTo("fast", 1);
		$("fieldset.services label").fadeTo("fast", 1);
		$("fieldset.services label input:radio").attr("disabled", "");
		//loadingScreen(false);
	} else {
		
		$("#btnActualiser, select#parQuartier, select#typePropriete, select#prixDemande").attr("disabled", "disabled").fadeTo("fast", 0.5);
		$("fieldset.services label").fadeTo("fast", 0.5);
		$("fieldset.services label input:radio").attr("disabled", "disabled");
		//loadingScreen(true);
	}
}

/*
affiche/cache l'écran de loading sur la carte
*/
function loadingScreen(flag) {
	if (flag) {
		var screen = $("<div id=\"loadingScreen\"></div>");
		var bar = $("<div id=\"loadingScreenBar\"></div>");
		/*var position = $("#googleMap").position();
		screen.css({
				   "width" : $("#googleMap").width()+"px",
				   "height" : $("#googleMap").height()+"px",
				   "top" : 0,
				   "left" : 0,
				   "opacity" : 0.5
				   }).appendTo("#googleMap");*/	
		bar.css({
				   "top" : (($("#googleMap").height()/2)-10)+"px",
				   "left" : (($("#googleMap").width()/2)-110)+"px"
				   }).appendTo("#googleMap");	
	} else {
		$("div#loadingScreen").fadeTo("fast", 0, function(){ 
			$("div#loadingScreen, div#loadingScreenBar").remove();
		});
	}
}

$(document).ready(function(){		   
	initializeGoogleMap();
	
	$("#btnActualiser").click(newSearch);
	// Annulation du form submit
	$("form#formMenuRechercheCarte").submit(function(){
											 return false;
									});
});

