Event.observe(window, 'load',function(){
	/* if($('tombe_virtuelle')){ */
	if($('tombe_virtuelle')||$('home_cimetiere')){
		initialize();
		toutAfficher();
		creerTheme();
	}
	if($('creation_tombe')){
		initializeGeoLoc();
		Event.observe('animal', 'change', function(){
			if($F('animal')!=''){
				new Ajax.Request('./_ajax.php?ACT=choixRace2',{
					parameters : {animal : $F('animal')},
					onComplete: function(transport){
						$('race').update(transport.responseText);
						$('race').disabled = '';
						$('race').removeClassName('disabled');
					}
				});
			}else{
				$('race').disabled = 'disabled';
				$('race').selectedIndex = 0;
				$('race').addClassName('disabled');
			}
		});
		makeItCount('description_tombe', 250 );
		Event.observe('bt_recherche_promenade','click',function(){
			if($F('adresse')!='' && $F('pays')!=''){
				$('adresse').removeClassName('inputError');
				$('pays').removeClassName('inputError');
				adresseTombe($F('adresse'), $('pays').options[$('pays').selectedIndex].text);
			}else{
				if($F('adresse')==''){
					$('adresse').addClassName('inputError');
				}else{
					$('adresse').removeClassName('inputError');
				}
				if($F('pays')==''){
					$('pays').addClassName('inputError');
				}else{
					$('pays').removeClassName('inputError');
				}
			}
		});
		var bulle1 = new infoBulle('apercu1',{
			iB_contenu : '<img src="images/commun/cimetiere/apercu1.jpg" alt="" />',
			iB_ancrage : 'LM',
			iB_offset : {x:15,y:15}
		});
		var bulle2 = new infoBulle('apercu2',{
			iB_contenu : '<img src="images/commun/cimetiere/apercu2.jpg" alt="" />',
			iB_ancrage : 'LM',
			iB_offset : {x:15,y:15}
		});
		var bulle3 = new infoBulle('apercu3',{
			iB_contenu : '<img src="images/commun/cimetiere/apercu3.jpg" alt="" />',
			iB_ancrage : 'LM',
			iB_offset : {x:15,y:15}
		});
		var bulle4 = new infoBulle('apercu4',{
			iB_contenu : '<img src="images/commun/cimetiere/apercu4.jpg" alt="" />',
			iB_ancrage : 'LM',
			iB_offset : {x:15,y:15}
		});
		if($('bt_ajout_photo')){
			Event.observe('bt_ajout_photo','click',function(){
				var nb = $$('.upload_photo').size()+1;
				if(nb<=10){
					var tpl = '<div class="ligne"><label for="photo'+nb+'">Photo '+nb+'</label><input type="file" name="photo'+nb+'" id="photo'+nb+'" size="38" class="upload_photo" /></div>';
					$('bt_ajout_photo').up().insert({before:tpl});
					$('bt_ajout_photo').blur();
					if(nb==10){
						$('bt_ajout_photo').up().update('<div class="info">Le nombre maximum de photos est atteint.</div>');	
					}
				}
			});
		}
		if($('bt_ajout_video')){
			Event.observe('bt_ajout_video','click',function(){
				var nb = $$('.upload_video').size()+1;
				if(nb<=10){
					var tpl = '<div class="ligne"><label for="video'+nb+'">Vid&eacute;o '+nb+'</label><textarea name="video'+nb+'" id="video'+nb+'" class="upload_video" rows="3" cols="30"></textarea></div>';
					$('bt_ajout_video').up().insert({before:tpl});
					$('bt_ajout_video').blur();
					if(nb==10){
						$('bt_ajout_video').up().update('<div class="info">Le nombre maximum de vid&eacute;o est atteint.</div>');	
					}
				}
			});
		}
	}
});
Event.observe(window,'unload',function(){
	GUnload();								   
});

var map = null;
tab_marker = new Array();
/* CREATION DES POINTS */

var createMarker = function(point,i) {
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "images/commun/gmap/ombre.png";
	baseIcon.iconSize = new GSize(24, 29);
	baseIcon.shadowSize = new GSize(39, 29);
	baseIcon.iconAnchor = new GPoint(19, 14);
	baseIcon.infoWindowAnchor = new GPoint(0, 0);
	var IconType = new GIcon(baseIcon);
	IconType.image = "images/commun/gmap/animal"+tab_point[i].type+".png";
	
	markerOptions = {
		title : tab_point[i].nom,
		icon:IconType,
		clickable : true
	};
	var marker = new GMarker(point, markerOptions);

	GEvent.addListener(marker, "click", function() {
		m = marker;
		m_i = i;
		var infoOptions = {
			onOpenFn : 	openInfo,
			onCloseFn : closeInfo
		}
		var url_page = 'tombe-animal_150_b'+tab_point[i].id+'.php';
		var myHtml = '<div class="visuel"><img src="'+tab_point[i].visuel+'" alt=""></div>';
		myHtml+= '<div class="info">';
		myHtml+= '	<a href="'+url_page+'" class="nom">'+tab_point[i].nom+'</a><br/>';
		myHtml+= '	<strong>race : </strong>'+tab_point[i].race1+' - '+tab_point[i].race2+'<br/>';
		myHtml+= '	<strong>Sexe : </strong>'+tab_point[i].sexe+'<br/>';
		myHtml+= '	<strong>Tombe cr&eacute;e le : </strong>'+tab_point[i].creation+'<br/>';
		myHtml+= '	<a href="'+url_page+'" class="recueillir">Se recueillir</a>';
		myHtml+= '	</div>';
    	map.openInfoWindowHtml(point,'<div style="width:300px; height:90px;" class="etiquette">'+myHtml+'</div>', infoOptions);
		map.panTo(point);
	});
	tab_marker.push(marker);
	return marker;
};

var openInfo = function(){
	tab_marker.each( function(a,b){
		a.setImage("images/commun/gmap/animal"+tab_point[b].type+".png");
	});
	m.setImage("images/commun/gmap/animal"+tab_point[m_i].type+"on.png");
};

var closeInfo = function(){
	tab_marker.each( function(a,b){
		a.setImage("images/commun/gmap/animal"+tab_point[b].type+".png");
	});
};

var creerPoint = function(){
	tab_point.each( function(e,i){
		var point = new GLatLng(e.latitude,e.longitude);
		map.addOverlay(createMarker(point, i));
	});
};

function tri_nombres(a,b){
	return a-b;
}

var calculCoord = function(calcul){
	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());
	if(calcul=='lat_moy'){return (lat_min+lat_max)/2;}
	if(calcul=='lng_moy'){return (lng_min+lng_max)/2;}
	if(calcul=='lat_min'){return lat_min;}
	if(calcul=='lat_max'){return lat_max;}
	if(calcul=='lng_min'){return lng_min;}
	if(calcul=='lng_max'){return lng_max;}
}

var initialize = function() {
	map = new GMap2($("map"));
	map.addControl(new GMapTypeControl());
	map.addControl(new GSmallMapControl());
	// INIT
	/*
	var sw = new GLatLng(calculCoord('lat_min'), calculCoord('lng_min'));
	var ne = new GLatLng(calculCoord('lat_max'), calculCoord('lng_max'));
	var bounds = new GLatLngBounds(sw, ne);
	level  = map.getBoundsZoomLevel(bounds);
	*/
	map.setCenter(new GLatLng(46.5, 2.5), 5); // CENTRAGE FRANCE
	creerPoint();
};

var resetTheme = function(){
	map.clearOverlays();
	$$('.filtres li a').each( function(bt){
		bt.removeClassName('on');	
	});
};

var toutTheme = function(){
	$$('.filtres li a').each( function(bt){
		bt.addClassName('on');	
	});
};

var toutAfficher = function(){
	Event.observe('tous_theme', 'click', function(){
		if($('tous_theme').hasClassName('on') == false){
			$('tous_theme').addClassName('on');
			creerPoint();
			toutTheme();
			tab_theme = tab_theme_sav;
		}else{
			$('tous_theme').removeClassName('on');
			resetTheme();
			tab_theme=new Array();
		}
	});
};

var creerTheme = function(){
	tab_original = tab_point;
	tab_theme = new Array();
	tab_theme_sav = new Array();
	tab_original.each( function(e,i){
		tab_theme.push(e.type);					
	});
	tab_theme_sav = tab_theme.uniq();
	tab_theme = tab_theme.uniq().toJSON();

	$$('.filtres li').each( function(bt, i){
		if(!tab_theme.include(bt.className.substr(5))){
			bt.update('<span>'+bt.down(0).innerHTML+'</span>');
		}
	});
	tab_theme = tab_theme_sav;
	choixTheme();
};

var choixTheme = function(){
	$$('.filtres li a').each( function(bt){
		Event.observe(bt, 'click', function(){
			map.clearOverlays();
			if(bt.className == 'on'){
				bt.removeClassName('on');
				tab_theme = tab_theme.without(bt.up(0).className.substr(5));
			}else{
				bt.addClassName('on');	
				tab_theme.push(bt.up(0).className.substr(5));
			}
			tab_original.each( function(e,i){
				tab_theme.each( function(e2,j){
					if(e.type == e2){
						var point = new GLatLng(e.latitude,e.longitude);
						map.addOverlay(createMarker(point, i));	
					}
				});
			});	
		});
	});
};

var centrerMap = function(){
	var cg = new GClientGeocoder();
	cg.getLatLng($F('ville_gmap'), function(point){
		if(!point){
			if(!$('erreur_frm_centrer')){
				$('frm_centrer').insert({top:'<div id="erreur_frm_centrer" class="erreur">D&eacute;sol&eacute;, mais votre recherche n\'a donn&eacute; aucun r&eacute;sultat.</div>'});
			}
		}else{
			if($('erreur_frm_centrer')){
				$('erreur_frm_centrer').remove();
			}
			map.setCenter(point, 12);
		}
	});
	return false;
}

var initializeGeoLoc = function() {
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "images/commun/gmap/ombre.png";
	baseIcon.iconSize = new GSize(24,29);
	baseIcon.shadowSize = new GSize(39,29);
	baseIcon.iconAnchor = new GPoint(12,29);
	var IconType = new GIcon(baseIcon);
	IconType.image = "images/commun/gmap/animal6.png";
	markerOptions = {
		icon:IconType
	};
	map = new GMap2($("map_ajout_tombe"));
	map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl());
	GEvent.addListener(map, "click", function(marker, point) {
		$('latitude').value = point.lat();
		$('longitude').value = point.lng();
		map.clearOverlays();
		map.addOverlay(new GMarker(point, markerOptions));
	});
	map.setCenter(new GLatLng(48.862004474432936, 2.350902557373047), 6); // Tour Eiffel, Paris
	geocoder = new GClientGeocoder();
};

function adresseTombe(adresse,pays){
	if(geocoder){
		geocoder.getLatLng(
			pays+", "+adresse,
			function(point){
				if(!point){
					if(!$('erreur_promenade')){
						$('map_ajout_tombe').insert({before:'<div class="erreur" id="erreur_promenade">Aucune adresse ne semble correspondre &agrave; "'+adresse+' ,'+pays+'"</div>'});
					}else{
						$('erreur_promenade').update('Aucune adresse ne semble correspondre &agrave; "'+adresse+' ,'+pays+'"');
					}
				}else{
					if($('erreur_promenade')){
						$('erreur_promenade').remove();
					}
					$('latitude').value = point.lat();
					$('longitude').value = point.lng();
					map.setCenter(point, 15);
					var marker = new GMarker(point, markerOptions);
					map.clearOverlays();
					map.addOverlay(marker);
				}
			}
		)
	}
}

/* FORMULAIRE */
var frmTombe = function() {
	param_form = { mep: 'msg_global', autoScroll: true, action: 'submit'};
	if( $('existing_animal').value == "" ) {
		champs_form = {
			latitude: {alerte:'Vous devez localiser votre tombe'},	
			nom_animal: {alerte:'Le nom de votre animal est obligatoire'},	
			animal: {alerte:'Le type d\'animal est obligatoire'},
			naissance: {alerte:'La date de naissance de votre animal est obligatoire'},
			deces: {alerte:'La date de d&eacute;c&egrave; de votre animal est obligatoire'},
			description_tombe: {alerte:'Le message de la tombe est obligatoire'}
		};
	} else {
		champs_form = {
			latitude: {alerte:'Vous devez localiser votre tombe'},	
			deces: {alerte:'La date de d&eacute;c&egrave; de votre animal est obligatoire'},
			description_tombe: {alerte:'Le message de la tombe est obligatoire'}
		};
	}
	return formVerif('frm_tombe', champs_form, param_form, {idMsgGlobal:'msgGlobalTombe'});
};

