// initialiser les variables
var isFullScreen = false;
var couleur =new Array('rouge','orange','bleu','turquoise','bleumarine','vert','ombre');
var icons = {};
var m_Map;
var m_MarkerManager;
var currentZoom=null;
var currentPosition=null;
var last_criteres_recherche;
var last_latitude=false;
var last_longitude=false;
var last_zoom=false;
var m_Mode = 'small'; //other possibilities : large, full
//les X seront déclarés dans le document.ready de la page
var m_maxLat = {'villes': {
							'small': {move:0.1,search:0.65},
							'large': {move:0.1,search:0.65},
							'full': {move:0.1,search:'X'}
						  },
				'habitations': {
							'small': {move:0.2,search:0.2},
							'large': {move:0.2,search:0.12},
							'full': {move:0.2,search:'X'}
						  }	
				}
var m_maxLng = {'villes': {
							'small': {move:0.1,search:0.65},
							'large': {move:0.1,search:0.65},
							'full': {move:0.1,search:'X'}
						  },
				'habitations': {
							'small': {move:0.2,search:0.12},
							'large': {move:0.2,search:0.20},
							'full': {move:0.2,search:'X'}
						  }	
				}
				
var isLoaded = {
	'provinces': false,
	'regions':false
};
var loadedVilles = new GPoint(0,0);
var loadedHabitations = new GPoint(0,0);
var tooltip;
var iconData = {
	"rond_rougeA":         { width: 65, height: 65, anchorLeft: 20, anchorRight: 21 },
	"rond_rougeB":		   { width: 45, height: 45, anchorLeft: 22, anchorRight: 22 },
	"rond_rougeC":         { width: 25, height: 25, anchorLeft: 10, anchorRight: 10 },
	"residentiel": 		   { width: 31, height: 24, anchorLeft: 14, anchorRight: 22 },
	"residentiel_inactive":{ width: 31, height: 24, anchorLeft: 14, anchorRight: 22 },
	"commercial": 		   { width: 29, height: 16, anchorLeft: 14, anchorRight: 12 },
	"commercial_inactive": { width: 29, height: 16, anchorLeft: 14, anchorRight: 12 },
	"touristique": 		   { width: 34, height: 24, anchorLeft: 14, anchorRight: 22 },
	"touristique_inactive":{ width: 34, height: 24, anchorLeft: 14, anchorRight: 22 }
};

$(document).ready(function(){
	
	//on set les latitude et longitude pour le déplacement
	m_maxLat['villes']['full'].search = parseFloat((m_maxLat['villes']['small'].search*$(window).width())/535);
	m_maxLng['villes']['full'].search = parseFloat((m_maxLng['villes']['small'].search*$(window).height())/300);
	m_maxLat['villes']['full'].search = parseFloat((m_maxLat['villes']['small'].search*$(window).width())/535);
	m_maxLng['villes']['full'].search = parseFloat((m_maxLng['villes']['small'].search*$(window).height())/300);
	m_maxLat['habitations']['full'].search = parseFloat((m_maxLat['habitations']['small'].search*$(window).width())/535);
	m_maxLng['habitations']['full'].search = parseFloat((m_maxLng['habitations']['small'].search*$(window).height())/300);
	m_maxLat['habitations']['full'].search = parseFloat((m_maxLat['habitations']['small'].search*$(window).width())/535);
	m_maxLng['habitations']['full'].search = parseFloat((m_maxLng['habitations']['small'].search*$(window).height())/300);
	
	
	if($('#overmap').length == 0){
		if($('#mymap').attr('rel')=='session'){
			$('#onmap').trigger('click',{session:true});
		}else{
			$('#onmap').trigger('click');
		}
		
	}
	
	if($('#overmap').length==1){
		lang = $('body').attr('id').split('-')[1];
		var so = new SWFObject("/medias/flash/overmap_"+lang+".swf", "overmap", "535", "300", "8", "#f6f6f6");
		so.write("overmap");
	}
	
	// pour redimentionner la carte sur l'événement click
	$('.resize').click(function(){
		
		var mode = $(this).attr('rel');
		//alert(mode)
		if(mode!='full'){
			var size = mode + 'px';
			$('#mymap').animate({'height': size})
				.queue(function(){
					m_Map.checkResize();
					m_Map.panTo(new GLatLng(last_longitude,last_latitude))
					$(this).dequeue()
					})						
		}else{
			showFullScreen();
		}
		if(mode=='300'){
			m_Mode = 'small';
		}else if(mode=='full'){
			m_Mode = 'full';
		}else{
			m_Mode = 'large';
		}
		
		$('.resize').parent().removeClass('currentTab');
		$(this).parent().addClass('currentTab');
		return false;
	});
	
});

function init_map(){
	
	if(!GBrowserIsCompatible){
		return;
	}
	
	// initialise la map et le marker manager
	m_Map = new GMap2(document.getElementById('mymap'));
	m_Map.addControl(new GMapTypeControl());
	m_Map.addControl(new GLargeMapControl());
	m_Map.setCenter(new GLatLng(50, -98), 3);
	m_Map.continuousZoomEnabled();
	//m_Map.enableScrollWheelZoom();
	m_Map.getInfoWindow().hide();
	m_MarkerManager = new MarkerManager(m_Map);
	currentPosition = new GLatLng(0, 0);
	currentZoom     = 3;
	
	// set up marker tooltip div 
    tooltip = document.createElement("div");
    document.getElementById("mymap").appendChild(tooltip);
    tooltip.style.visibility="hidden";
	
	// appelle la fonction updateMap a chaque modification dans la map (au changement de position, au zoom)
	GEvent.addListener(m_Map, "dragend", moveEndCallback)
	GEvent.addListener(m_Map, "zoomend",moveEndCallback);
	
	
	$('#btn_positionner').click(function(){
		rechercherVille()
		return false;
	});
 	
	$('#fermer_fullScreen').click(hideFullScreen);
}
function getSection(zoom){
	if(zoom < 5){
		currentsection = 'provinces';
	}else if(zoom < 9){
		currentsection = 'regions';
	}else if(zoom < 11){
		currentsection = 'villes';
	}else{
		currentsection = 'habitations';
	}
	return currentsection;
}
function moveEndCallback(typeUpdate,moveInfo){
	//validation pour déterminer si la carte a été zoomé ou non
	currentSection = getSection(m_Map.getZoom());
	currentPosition = m_Map.getCenter();
	newZoom = m_Map.getZoom();

	if(typeof(moveInfo)=='undefined'){
		var moveInfo=new Object;
	}
	
	var m_updatemap = false; 
	//alert(typeof(typeUpdate))
	if(typeof(typeUpdate)!='string' || typeof(typeUpdate)=='number'){
		
		// vérifie si les provinces et/ou les régions ont été loader qu'une seule fois
		if (currentsection != false) {
			if (!isLoaded[currentsection]) {
				if (currentsection == 'provinces' || currentsection == 'regions') {
					isLoaded[currentsection] = true;
					switch (currentsection) {
						case "provinces":
							m_MarkerManager.DuProprio_clearMarkersOnLayer(0, 4);
							$("loading").show();
							$("#loadingProvinces").show();
							m_updatemap=true;
							break;
						case "regions":
							m_MarkerManager.DuProprio_clearMarkersOnLayer(5, 8);
							$("#loading").show();
							$("#loadingRegions").show();
							m_updatemap=true;
							break;
					}
				}
			}
		}
		
		//on vérifie si on charge les villes ou habitation pour effacer les marqueurs
		if (currentSection == "villes") {
			//alert(currentsection)
			var nouveauCentre = m_Map.getCenter();
			// pour les villes
			diffVillesX = Math.abs(Math.abs(nouveauCentre.x) - Math.abs(loadedVilles.x));
			diffVillesY = Math.abs(Math.abs(nouveauCentre.y) - Math.abs(loadedVilles.y));
			//alert(Math.abs(nouveauCentre.y)+' '+Math.abs(loadedVilles.y));
			//alert(diffVillesX+' > '+m_maxLat[currentsection][m_Mode].move+' || '+diffVillesY+' > '+m_maxLng[currentsection][m_Mode].move)
			if(diffVillesX > m_maxLat[currentsection][m_Mode].move || diffVillesY > m_maxLng[currentsection][m_Mode].move) {
				//alert('reload city')
				m_MarkerManager.DuProprio_clearMarkersOnLayer(9, 10);
				loadedVilles = m_Map.getCenter();
				$("#loading").show();
				$("#loadingVilles").show();
				moveInfo.maxLat = m_maxLat[currentsection][m_Mode].search;
				moveInfo.maxLng = m_maxLng[currentsection][m_Mode].search;
				m_updatemap=true;
			}
		} else if (currentsection == "habitations") {
			var nouveauCentre = m_Map.getCenter();
			// pour les habitations
			diffHabitationsX = Math.abs(Math.abs(nouveauCentre.x) - Math.abs(loadedHabitations.x));
			diffHabitationsY = Math.abs(Math.abs(nouveauCentre.y) - Math.abs(loadedHabitations.y));
			if (diffHabitationsX > 0.10 || diffHabitationsY > 0.10) {
				m_MarkerManager.DuProprio_clearMarkersOnLayer(11, 20);
				loadedHabitations = m_Map.getCenter();
				$("#loading").show();
				$("#loadingHabitations").show();
				moveInfo.maxLat = m_maxLat[currentsection][m_Mode].search;
				moveInfo.maxLng = m_maxLng[currentsection][m_Mode].search;
				m_updatemap=true;
			}
		}
	}else{
		m_updatemap=true;
		m_MarkerManager.DuProprio_clearMarkersOnLayer(0, 20);
		isLoaded['regions']=false;
		isLoaded['provinces']=false;
	}
	
	if(m_updatemap){
		//alert('lets go update me '+typeof(typeUpdate)+' '+currentZoom+' '+newZoom)
		if(currentZoom!=newZoom && typeof(typeUpdate)!='string'){ 
			//alert('zoom')
			//le typeof sert à valider si on demande d'Afficher par les 
			//critères de session ou un refresh complet par le formulaire
			//it's a zoom
			moveInfo.latitude  = currentPosition.lng();
			moveInfo.longitude = currentPosition.lat();
			moveInfo.zoom      = newZoom;
			updateMap(currentZoom,moveInfo);
			currentZoom=newZoom;
		}else{
			//it's a move, drag or anything but not a zoom
			updateMap(typeUpdate,moveInfo);
		}
	}
	//call ajax pour updater les dernieres modifs sur la carte
	if(typeUpdate!='session'){
		toUpdate = {
			latitude:currentPosition.lng(),
			longitude:currentPosition.lat(),
			zoom:currentZoom
		};
		update_position(toUpdate);
	}
}
function update_position(toUpdate){
	$.ajax({
		type: "POST",
			url: "/pages/ajax/ajax.maps.updateposition.php",
			data: toUpdate
	});
}

// s'éxécute lorsqu'il y a un changement de position ou de zoom sur la map
function updateMap(recharger, moveInfo){
	//alert('updateMap')
	$('#loadingHabitationsNonDispo').hide();
	//alert('updateMap')
	var currentsection=false;
	var diffVillesX;
    var diffVillesY;
	var diffHabitationsX;
	var diffHabitationsY;
	
	currentSection = getSection(m_Map.getZoom());
	
	// va chercher les info a afficher
	mycenter  = m_Map.getCenter();
	
	if(typeof(recharger)!='undefined'){
		if (recharger === 'reload' || recharger==='session') {
			//recherche avec des nouveau critères
			myData = get_criteres_recherche();
			
			if (myData.vi != '0' && myData.vi != '') {
				myData.zoom = 11;
			} else if (myData.re != '0' && myData.re != '') {
				myData.zoom = 9;
			} else if (myData.pr != '0' && myData.pr != '') {
				myData.zoom = 5;
			} else {
				myData.zoom = 3;
			}
			
			last_criteres_recherche = myData;
			
			if(recharger === 'reload'){
				dataToSend = myData;
				//dataToSend.sessionLat   = currentPosition.lng();
				//dataToSend.sessionLng   = currentPosition.lat();
				//dataToSend.sessionZoom  = currentZoom;
			}else{
				dataToSend.usesession = true;
			}
	
		}else{
			//recherche avec les anciens critères ainsi qu'avec un nouveau zoom
			dataToSend = last_criteres_recherche;
			dataToSend.zoom = m_Map.getZoom();
			if(typeof(moveInfo)=='object'){
				if(typeof(moveInfo.zoom)!='undefined'){
					dataToSend.zoom      = moveInfo.zoom;
					dataToSend.longitude = moveInfo.longitude;
					dataToSend.latitude  = moveInfo.latitude;
				}
				if(typeof(moveInfo.maxLat) != 'undefined' && typeof(moveInfo.maxLng) != 'undefined'){
					//alert('with max show')
					dataToSend.maxLat = moveInfo.maxLat;
					dataToSend.maxLng = moveInfo.maxLng;
				}
			}
		}
	}else{
		dataToSend = last_criteres_recherche;
		dataToSend.zoom = m_Map.getZoom();
		dataToSend.longitude = mycenter.lat();
		dataToSend.latitude = mycenter.lng();
	}
	
	$.ajax({
	   type: "POST",
	   url: "/pages/ajax/ajax.maps.php",
	   data: dataToSend,
	   success: ajaxMapsCallback,
	   dataType: "json"
	});
}

function ajaxMapsCallback(data){
	if(typeof(data)!='object'){return;}	
	if(data.zoom!==false && data.gotothis!==false){
		if (typeof(data.marker)!='undefined' && data.marker.length != 0 ){
			isLoaded[getSection(data.zoom)] = true;
			last_longitude = data.longitude;
			last_latitude  = data.latitude;
			last_zoom      = data.zoom;
			currentZoom = parseInt(data.zoom);
			moveMap(data.longitude, data.latitude, data.zoom);
			
			if(getSection(data.zoom)=='habitations'){
				loadedHabitations = m_Map.getCenter();
			}else if(getSection(data.zoom)=='villes'){
				loadedVilles = m_Map.getCenter();
			}
			
			markers = new Array();
			for(var x=0;x<data.marker.length;x++){
				markers.push(creerMarker(data.marker[x]));
			}
			m_MarkerManager.addMarkers(markers, parseInt(data.marker[0].zoom_min),parseInt(data.marker[0].zoom_max));
			m_MarkerManager.refresh();
			//on assigne les classes aux markers
			/*
			for(var x=0;x<markers.length;x++){
				alert('#mtgt_'+markers[x].id)
				//alert($('#mtgt_'+markers[x].id).length)
				//$('#mtgt_'+markers[x].id).addClass(markers[x].icon.className);
			}
			*/
		}else{
			$("#loading").show();
			$("#loading div").hide();
			$('#loadingHabitationsNonDispo').show();
			return;
		}
	}
	
	$("#loading").hide();
	$('#loadingProvinces, #loadingRegions, #loadingVilles, #loadingHabitations, #loadingHabitationsNonDispo').hide();
}

// crée les markeur sur la map
function creerMarker(arrPlace){
	var marker;
	var icon = getIcon(arrPlace["icon"]);
	var posn = new GLatLng(arrPlace["longitude"], arrPlace["latitude"]);
  	marker = new GMarker(posn, { title: arrPlace["label"], icon: icon });
	
    marker.tooltip = arrPlace['tooltip'];
    marker.icon = icon;
	marker.icon.className = arrPlace["class"];
	marker.title = arrPlace["label"];
	marker.vue = false;
	marker.id=arrPlace["id"];
	GEvent.addListener(marker, 'click', function() {
		hideTooltip();
		if (typeof(arrPlace["prix"])!='undefined'){
			gPointInfoTabs = marker.getPoint();
			dataToSend = {
				'idHab':arrPlace["id"]
			}
			$.ajax({
			   type: "GET",
			   url: "/pages/ajax/ajax.infoTabs.php",
			   data: dataToSend,
	   		   dataType: "json",
			   success: afficherInfoTabs

			});
			//m_Map.openInfoWindowTabsHtml(gPointInfoTabs, data);
		}else{
			loadedVilles = new GPoint(0,0);
			loadedHabitations = new GPoint(0,0);
			if(arrPlace.type=='pr'){
				//last_criteres_recherche.pr = arrPlace.id;
				//$('#recherche-provinces').jcSelect(arrPlace.id);
				//$('#recherche-regions').jcEnable();
			}else if(arrPlace.type=='re'){
				/*last_criteres_recherche.re = arrPlace.id;
				$('#recherche-regions').jcEnable();
				$('#recherche-regions').jcSelect(arrPlace.id);
				$('#recherche-villes').jcEnable();*/
				//loadedVilles = new GLatLng(arrPlace["longitude"],arrPlace["latitude"]);
			}else if(arrPlace.type=='vi'){
				//loadedHabitations = new GLatLng(arrPlace["longitude"],arrPlace["latitude"]);
			}
			currentZoom = parseInt(arrPlace["zoom"]);	
			moveMap(arrPlace["longitude"], arrPlace["latitude"], arrPlace["zoom"]);
			//on appelle manuellement updateMap car la fonction moveMap désactive le listener zoomend
			moveInfo = {
				longitude : arrPlace["longitude"],
				latitude  : arrPlace["latitude"],
				zoom      : arrPlace["zoom"]
			}
			moveEndCallback(false,moveInfo);
		}
		
		});
	GEvent.addListener(marker,"mouseover", function() {
		monTimer = setTimeout(function(){showTooltip(marker)},250);
		//showTooltip(marker);
		});
	GEvent.addListener(marker,"mouseout", function() {
		hideTooltip(marker);
		clearTimeout(monTimer);
		});

	return marker;
}

function afficherInfoTabs(data){

	var infoTabs = new Array();
	
	for(var x=0; x < data.length; x++)
	{		
		infoTabs.push(new GInfoWindowTab(data[x].type,data[x].html));
	
	}
	
	m_Map.openInfoWindowTabsHtml(gPointInfoTabs, infoTabs);
}

// défini l'icone à afficher sur la carte
function getIcon(images) {
	var icon = null;
	if (images) {
		if (icons[images]) {
		  icon = icons[images];
		} else {
		  icon = new GIcon();
		  icon.image = "/medias/images/maps/marker_" + images + ".png";
		  icon.name = images;
		  var size = iconData[images];
		  icon.iconSize = new GSize(size.width, size.height);
		  icon.iconAnchor = new GPoint(size.anchorLeft, size.anchorRight);
		  icons[images] = icon;
		}
	}
	return icon;
}

//ferme le Tooltip ouvert sur la carte 
function hideTooltip(marker){
	tooltip.style.visibility="hidden";
	flagTooltipOuvert=false;
}

// affiche le tooltip sur la carte au survol
function showTooltip(leMarker) {
	
	tooltip.innerHTML = leMarker.tooltip;
    var point=m_Map.getCurrentMapType().getProjection().fromLatLngToPixel(m_Map.getBounds().getSouthWest(),m_Map.getZoom());
    var offset=m_Map.getCurrentMapType().getProjection().fromLatLngToPixel(leMarker.getPoint(),m_Map.getZoom());
    var anchor=leMarker.icon.iconAnchor;
	var width=leMarker.icon.iconSize.width;
	var height=leMarker.icon.iconSize.height;
	
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width - width/2,- offset.y + point.y +anchor.y -height/8));
	//var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x ,- offset.y + point.y));
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
	//flagTooltipOuvert = idHabitation;
	
	//if(idHabitation>0)  window.setTimeout("loadIncrementerRollOver("+idHabitation+")",1000);
	
	// vérifié si le marqueur est déja vue
	if ( m_Map.getZoom() >= 11 && leMarker.vue != true){
		
		dataToSend = {
			'cookie_name':'maisonvue', //on crée aussi une variable session avec ce nom
			'cookie_value':leMarker.title
		}
		//success: ajaxMapsCallback,
		$.ajax({
		   type: "GET",
		   url: "/pages/ajax/ajax.cookie.php",
		   data: dataToSend
		});
		
		leMarker.setImage('/medias/images/maps/marker_' + leMarker.icon.name + '_inactive.png')
		//leMarker.getIcon().image = '/medias/images/maps/marker_' + leMarker.icon.name + '_inactive.png';
		leMarker.vue = true;
	}
}

// repossitionne la map
function moveMapX(lati,longi,zoom){
	// repositionner
	m_Map.setCenter(new GLatLng(lati, longi), parseInt(zoom));
}


// fonction pour la gestion du mode plein écran
function adjustFullScreenSize(){
	$('#mymap').css('width', $(window).width() + 'px')
	$('#mymap').css('height', $(window).height() + 'px')
}
function adjustFullScreenPosition(){
	$(document).scrollTop(0)
	$(document).scrollLeft(0)
}
function showFullScreen(){
	isFullScreen=true;
	
	$(window).bind('resize',adjustFullScreenSize)
	//$(window).bind('scroll',adjustFullScreenPosition)
	
	adjustFullScreenPosition();
	
	$('#boxMap').after('<div id="keepMapPos"></div>');
	$('#keepMapPos').css('width', $('#mymap').width() + 'px')
	$('#keepMapPos').css('height', $('#mymap').height() + 'px')
	
	$('#fullscreen').css('display','block');
	
	$('body').css('overflow-y','hidden');
	$('body').css('overflow','hidden');
	
	if($.browser.msie==true && $.browser.version==6){
		$('#fullscreen').css('width',$(window).width() + 'px');
		$('#fullscreen').css('height','63px');
	}
	
	cssObject = {
		position: 'absolute'
	}
	
	$('#fullscreen').css(cssObject)
		.animate({'top': '0px'})
	
	
	$('#boxMap').css(cssObject)
			.animate({'left': '0px'})
			.animate({'top': '50px'})
			.queue(function(){
				$('#mymap')
					.animate({'width': $(window).width() + 'px'})
					.animate({'height': $(window).height() + 'px'})
					.queue(function(){
						m_Map.checkResize()
						m_Map.panTo(new GLatLng(last_longitude,last_latitude))
						//moveMap(last_longitude,last_latitude,last_zoom);
						$(this).dequeue()
					})
				$(this).dequeue()
			});
	$('#leaderboard-top, .ads-bigbox').hide();
}		 		 

function hideFullScreen(){
	
	$(window).unbind('resize')
	$(window).unbind('scroll')
	
	$('#fullscreen').css('display','none');
	$('#boxMap').css('top','auto');
	$('#boxMap').css('left','auto');
	$('#boxMap').css('position','static');
	$('#mymap').css('width',$('#keepMapPos').css('width'))
	$('#mymap').css('height',$('#keepMapPos').css('height'))
	$('body').css('overflow','auto');
	$('#keepMapPos').remove();
	$('.resize').parent().removeClass('currentTab')
	$('.resize[rel='+$('#mymap').height()+']').parent().addClass('currentTab');
	
	m_Map.checkResize()
	m_Map.panTo(new GLatLng(last_longitude,last_latitude));
	$('#leaderboard-top, .ads-bigbox').show();
}