/*-----------------------------------------------------------------------------------------------*/
//
// Copyright (c) 2008 Agence Clark (http://www.agence-clark.com)
//
/*-----------------------------------------------------------------------------------------------*/

/*-----------------------------------------------------------------------------------------------*/
// Variables
/*-----------------------------------------------------------------------------------------------*/
var map = null;
var baseIcon = new GIcon(G_DEFAULT_ICON);
/*-----------------------------------------------------------------------------------------------*/
// Init Page
/*-----------------------------------------------------------------------------------------------*/
Event.observe(window, 'load',function(){
	if($('mod_implantations') && $('map')){		
		// Variable
		map = new GMap2($("map"));
		map.addControl(new GMapTypeControl());
		map.addControl(new GSmallMapControl());
		
		baseIcon.shadow = "images/commun/gmap/ombre.png";
		baseIcon.iconSize = new GSize(14,23);
		baseIcon.shadowSize = new GSize(16,26);
		baseIcon.iconAnchor = new GPoint(12,29);
	
		initialize();
		AfficheType();
		FiltreLieu();		
	}
});
Event.observe(window,'unload',function(){
	if($('mod_implantations') && $('map')) GUnload();
});

/*-----------------------------------------------------------------------------------------------*/
// Fonctions
/*-----------------------------------------------------------------------------------------------*/
// Google Maps //
function tri_nombres(a,b){
	return a-b;
}

var getCoord = function(coord){
	var tab_lat = new Array();
	var tab_lng = new Array();
	tab_point.each( function(e){
		tab_lat.push(e.latitude);
		tab_lng.push(e.longitude);
	});
	var lat_min = parseFloat(tab_lat.sort(tri_nombres).first());
	var lat_max = parseFloat(tab_lat.sort(tri_nombres).last());
	var lng_min = parseFloat(tab_lng.sort(tri_nombres).first());
	var lng_max = parseFloat(tab_lng.sort(tri_nombres).last());
	switch(coord){
		case 'lat_min' : return lat_min; break;
		case 'lat_moy' : return (lat_min+lat_max)/2; break;
		case 'lat_max' : return lat_max; break;
		case 'lng_min' : return lng_min; break;
		case 'lng_moy' : return (lng_min+lng_max)/2; break;
		case 'lng_max' : return lng_max; break;
	}
}

var initialize = function() {
	// Recherche des filtres
	IDDept = $('ImpDept').value;
	IDVille = $('ImpVille').value;
	ActType1 = $('type1').className;
	ActType2 = $('type2').className;
	ActType3 = $('type3').className;
	ActType4 = $('type4').className;
	
	
	$('f_liste').update('<p class="loading"><img src="./images/commun/loading.gif" alt="" /></p>');
	new Ajax.Request('./plugins/mod_implantations/_ajax.php?ACT=gmap_implantations',{
		parameters : {IDDept : IDDept, IDVille : IDVille, ActType1 : ActType1, ActType2 :ActType2, ActType3 : ActType3, ActType4 : ActType4},
		onComplete: function(transport){
			map.clearOverlays();
			tab_point = transport.responseText.evalJSON();
			// INIT
			var sw = new GLatLng(getCoord('lat_min'), getCoord('lng_min'));
			var ne = new GLatLng(getCoord('lat_max'), getCoord('lng_max'));
			var bounds = new GLatLngBounds(sw, ne);
			level  = map.getBoundsZoomLevel(bounds);
			map.setCenter(new GLatLng(getCoord('lat_moy'), getCoord('lng_moy')), level);
			creerPoint();
			creerListe();
		}
	});	
};

var creerPoint = function(){
	tab_point.each( function(e,i){
		var point = new GLatLng(e.latitude,e.longitude);
		map.addOverlay(createMarker(point, i));
	});
};

var createMarker = function(point,i) {
	// Create a lettered icon for this point using our icon class
	var IconType = new GIcon(baseIcon);
	IconType.image = "images/commun/gmap/picto"+tab_point[i].type+".png";
	markerOptions = {
		icon:IconType
	};
	var marker = new GMarker(point, markerOptions);

	GEvent.addListener(marker, "click", function() {
		etiquette(point,i);
		deplaceListe(i);
	});
	return marker;
};

var etiquette = function(point,i){
	$('map').setStyle({visibility:'visible'});
	var infoOptions = {
		pixelOffset : new GSize(-5,-8),
		onOpenFn : 	openInfo,
		onCloseFn : closeInfo
	}
	var myHtml = '';
	myHtml += '<h3 class="type'+tab_point[i].type+'">'+tab_point[i].rue_court+'<br/>'+tab_point[i].cp_ville_court+'</h3><div class="ensemble">';
	if(tab_point[i].visuel != "") myHtml += '<div class="visuel"><img src="../data/imgs/implantations/medium/'+tab_point[i].visuel+'" alt=""></div>';
	myHtml += '<div class="txt '+(tab_point[i].visuel != ""?'':'double')+'">';
	if(tab_point[i].nb != "") myHtml += '<p>'+tab_point[i].nb+' logements</p>';
	myHtml += '<a href="'+tab_point[i].lien_detail+'" class="lien"><img src="./images/fr/boutons/bt_voir.gif" alt="Voir la fiche" /></a></div></div>';
	map.openInfoWindowHtml(point,'<div class="etiquette" style="width:300px; height:130px; overflow:hidden;zoom:1;">'+myHtml+'</div>', infoOptions);
}

var openInfo = function(){};
var closeInfo = function(){
	$$('.ligne').each(function(e){
		e.removeClassName('in');
	});
};

var creerListe = function(){
	$('f_liste').update();
	tab_point.each( function(e,i){
		var tpl = '<div class="ligne #{last}" id="ligne_#{id}"><h3 class="type#{type}"><a href="javascript:void(0);" class="nom">#{rue} - #{cp_ville}</a></h3>';
		tpl += '<div class="ensemble">';
		if(tab_point[i].visuel != "")  tpl += '<div class="visuel"><img src="../data/imgs/implantations/small/#{visuel}" alt="" /></div>';
		tpl += '<div class="txt">';
		if(tab_point[i].nb != "")  tpl += '<p>#{nb} logements</p>';
		tpl += '<ul><li><a href="javascript:void(0);" class="infos">Plus d\'infos</a></li>';
		if(tab_point[i].lien_demande != '') tpl += '<li><a href="#{lien_demande}">Déposer votre dossier</a></li>';
		tpl += '</ul></div></div></div>';

		var valeur_template = {id:tab_point[i].id, last:tab_point[i].last, type:tab_point[i].type, rue:tab_point[i].rue, cp_ville:tab_point[i].cp_ville, visuel:tab_point[i].visuel, nb:tab_point[i].nb, lien_demande:tab_point[i].lien_demande};
		var template = new Template(tpl);
		var nouveau = template.evaluate(valeur_template);	
		$('f_liste').insert({bottom:nouveau});
	});
	
	$$('.ligne').each(function(e,i){
		var lien = $$('#'+e.id+' h3 a')[0];
		Event.observe(lien, 'click', function(){
			var point = new GLatLng(tab_point[i].latitude,tab_point[i].longitude);											 
			etiquette(point,i);
			deplaceListe(i);
		});
		lien = $$('#'+e.id+' .infos')[0];
		Event.observe(lien, 'click', function(){
			var point = new GLatLng(tab_point[i].latitude,tab_point[i].longitude);											 
			etiquette(point,i);
			deplaceListe(i);
		});
	});
};

var deplaceListe = function(i){
	var id = tab_point[i].id;
	var hauteur = 0;
	$('ligne_'+id).previousSiblings().each( function(e){
		hauteur = hauteur + e.offsetHeight;
	});
	$('f_liste').scrollTop = hauteur;
	$$('.ligne').each(function(e){
		e.removeClassName('in');
	});
	$('ligne_'+id).addClassName('in');
};

// Affiche type //
var AfficheType = function(){
	$$('#mod_implantations .filtres li a').each( function(e,i){
		Event.observe(e,'click', function(){			
			// Affichage bouton
			if(e.hasClassName('on')){
				var src = e.down().src;
				e.down().src = src.split('_on')[0]+'_off.gif';
				e.removeClassName('on');
				e.addClassName('off');
			} else {
				var src = e.down().src;
				e.down().src = src.split('_off')[0]+'_on.gif';
				e.removeClassName('off');
				e.addClassName('on');
			}
			initialize();
		});
	});
};

// Filtre lieu //
var FiltreLieu = function(){
	// Select
	Event.observe($('ImpDept'), 'change', function(){
		new Ajax.Request('./plugins/mod_implantations/_ajax.php?ACT=gmap_dept',{
			parameters : {ImpDept : $('ImpDept').value},
			onComplete: function(transport){
				if(transport.responseText != "false"){
					// Select
					$('ImpVille').update(transport.responseText);
					initialize();
					// Cartes
					if($('ImpDept').value == "") $('map').setStyle({visibility:'hidden'});
					else $('map').setStyle({visibility:'visible'});
				}
			}
		});	
	});
	Event.observe($('ImpVille'), 'change', function(){ 
		initialize();
		// Cartes
		if($('ImpVille').value == "") $('map').setStyle({visibility:'hidden'});
		else $('map').setStyle({visibility:'visible'});
	});
	
	// Carte image
	$$('#map_carte area').each(function(e){
		var Dept = (e.id).split('_')[1];		
		Event.observe(e, 'click', function(){
			// Select
			var Index = 0;
			$$('#ImpDept option').each(function(f,i){ if(f.value == Dept) $('ImpDept').selectedIndex = i; });
			new Ajax.Request('./plugins/mod_implantations/_ajax.php?ACT=gmap_dept',{				
				parameters : {ImpDept : Dept},
				onComplete: function(transport){
					if(transport.responseText != "false"){																								
						$('ImpVille').update(transport.responseText);
						initialize();
						$('map').setStyle({visibility:'visible'});
					}
				}
			});	
		});	
	});
};

/*-----------------------------------------------------------------------------------------------*/
// Verification de formulaire
/*-----------------------------------------------------------------------------------------------*/
var frmDemandeLocal = function() {
	param_form = { mep: 'msg_champ', autoScroll: false, action: 'submit'};
	champs_form = {
		DLLocal: {alerte:'Votre local commercial est obligatoire'},
		DLNom: {alerte:'Votre nom est obligatoire'},	
		DLPrenom: {alerte:'Votre prénom est obligatoire'},
		DLAdresse: {alerte:'Votre adresse est obligatoire'},
		DLTel: {alerte:'Votre numéro de téléphone est obligatoire'},
		DLProfession: {alerte:'Votre profession est obligatoire'},
		DLActivite: {alerte:'Votre activité commerciale est obligatoire'}
		//DLImmatriculation: {alerte:'Votre numéro d\'immatriculation au registre du commerce est obligatoire'}
	};
	return formVerif('frm_demande_local', champs_form, param_form);
};

var frmDemandeParking = function() {
	param_form = { mep: 'msg_champ', autoScroll: false, action: 'submit'};
	champs_form = {
		DPParking: {alerte:'Votre parking est obligatoire'},
		DPType: {alerte:'Vous devez préciser votre situation'},
		DPNom: {alerte:'Votre nom est obligatoire'},	
		DPPrenom: {alerte:'Votre prénom est obligatoire'},
		DPAdresse: {alerte:'Votre adresse est obligatoire'},
		DPTel: {alerte:'Votre numéro de téléphone est obligatoire'},
		DPMarque: {alerte:'Votre marque de voiture est obligatoire'},
		DPImmatriculation: {alerte:'Votre numéro d\'immatriculation de voiture est obligatoire'}
	};
	return formVerif('frm_demande_parking', champs_form, param_form);
};
