

﻿function prepareGallery(){
	if (document.getElementById && document.getElementsByTagName){
		if (gallery = document.getElementById("multipleImg")){
			var links = gallery.getElementsByTagName("a");
			for( var i=0; i < links.length; i++ ){
				links[i].onclick = function(){
					return !showPic(this);
				};
			}
		}
	}
}


function disp_alert()
{
	alert("VUE PAR CARTE" + '\n' + "Pour une meilleure lisibilité, le nombre d'offres affichées sur la carte est au maximum 10." + '\n' + "Pour visualiser les autres offres, cliquez sur les onglets numérotés");
}



function showPic (link) {
	var linkHref = link.href;
	if(images = link.getElementsByTagName('img')){
		if(image = images[0]){
			r = new RegExp('/dynamic/image/([0-9]+)\?.*', 'g');
			if(match = r.exec(image.src)){
				if(image_id = match[1]){
					if(largerImgLink = document.getElementById("largerImg")){
						if(largerImgs = largerImgLink.getElementsByTagName('img')){
							var largerImg = new Image();
							if(largerImg = largerImgs[0]){
								largerImg.src = '/dynamic/image/'+match[1]+'?x=186&y=151&mode=c';
								largerImgHref = largerImgLink.href;
								if(-1!=largerImgHref.indexOf('?')){
									largerImgHref = largerImgHref.substring(0,largerImgHref.indexOf('?'));
								}
								largerImgHref += '?img='+match[1]+'&amp;hide_template=true&amp;KeepThis=true&amp;TB_iframe=true&amp;height=540&amp;width=670';
								largerImgLink.href = largerImgHref;

								return true;
							}
						}
					}
				}
			}
		}
	}
	return false;
}
	
window.onload = function(){
	if(document.getElementById('googleMap')){
		loadGoogleApi();
	}
	prepareGallery();
	checkPrintLinks();
	setupOrderButton();
	setupAlertButton();
}

function checkPrintLinks(){

	links = document.getElementsByTagName('a');
	for(var i=0; i<links.length; i++) {
		if(links[i].rel=='print-link') {
			links[i].onclick = function() {

				window.iFrame = document.createElement('IFRAME');

				window.iFrame.style.width = '1px';
				window.iFrame.style.height = '1px';
				window.iFrame.style.position = 'absolute';
				window.iFrame.style.top = '-1000px';

				window.iFrame.setAttribute('src', this.href+'#triggerPrint');

				document.body.appendChild(window.iFrame);

				return false;

			}
		}
	}


	if(window.location.hash=='#triggerPrint') {
		window.focus();
		window.print();
	}

}

function loadGoogleApi(){
	var metas = document.getElementsByTagName('meta');
	var googleKey = false;
	for(var i=0; i<metas.length; i++){
		var meta = metas[i];
		if(meta.name == 'google-api'){
			googleKey = meta.content;
		}
	}

	if(googleKey){
		var script = document.createElement("script");
		script.src = "http://www.google.com/jsapi?key="+googleKey+"&callback=loadGoogleMapsApi";
		script.type = "text/javascript";
		document.getElementsByTagName("head")[0].appendChild(script);
	}
}



function loadGoogleMapsApi(){
	google.load('maps','2', {'callback':mapsApiLoaded});
}

function mapsApiLoaded(){
		if(mapDiv=document.getElementById('googleMap')){
			
			if('areaMap'==mapDiv.className) {
				var bounds = new google.maps.LatLngBounds();
				var divs = mapDiv.getElementsByTagName('div');
				var mapLinks = mapDiv.getElementsByTagName('a');
				for(var i=0; i<divs.length; i++) {
					if(divs[i].className='geo'){
						var loc = (divs[i].innerHTML.split(';'));
						bounds.extend(new google.maps.LatLng(loc[0], loc[1]));
					}
				}
				if(!bounds.isEmpty()){
					var mapLink=false;
					if(mapLinks.length>0){ mapLink=mapLinks[0].href; }
					var map = new google.maps.Map2(mapDiv);
					map.getContainer().style.overflow='hidden';
					map.setCenter(bounds.getCenter());
					map.setZoom(map.getBoundsZoomLevel(bounds));
					if(mapLink) {
						google.maps.Event.addListener(map, 'click', function(){ window.location.href=mapLink; });
					}
				}
			}
			else if('largeMap'==mapDiv.className) {
				var map = new google.maps.Map2(mapDiv);
				map.getContainer().style.overflow='hidden';
				var latLngArray = mapDiv.title.split(';');
				mapDiv.title = '';
				var latLng = new google.maps.LatLng(latLngArray[0], latLngArray[1]);
				map.setCenter(latLng, 12);
				map.addOverlay(new google.maps.Marker(latLng));
				map.addControl(new google.maps.MapTypeControl());
				map.addControl(new google.maps.LargeMapControl());
				map.addControl(new google.maps.ScaleControl());
				map.getContainer().style.overflow='hidden';
			}
			else if('listMap'==mapDiv.className) {
				var bounds = new google.maps.LatLngBounds();
				var divs = mapDiv.getElementsByTagName('div');
				var points = new Array();
				for(var i=0; i<divs.length; i++) {
					if(divs[i].className=='property'){
						var loc = (divs[i].title.split(';'));
						var point = new google.maps.LatLng(loc[0], loc[1]);
						var custom_icon=new GIcon(G_DEFAULT_ICON, '/assets/DTZ/img/france/gmap-icons/red_Marker'+loc[2]+'.png');
						bounds.extend(point);
						point = new google.maps.Marker(point,{icon: custom_icon});
						points.push(point);
						point.bindInfoWindowHtml(divs[i].innerHTML);
					}
				}
				var map = new google.maps.Map2(mapDiv);
				map.setCenter(bounds.getCenter());
				map.setZoom(map.getBoundsZoomLevel(bounds));
				map.addControl(new GMapTypeControl());
				map.addControl(new GLargeMapControl());
				map.addControl(new GScaleControl());
				for(var i=0; i<points.length; i++){
					map.addOverlay(points[i]);
				}
			}
			else if('searchMap'==mapDiv.className) {

				var loc = mapDiv.title.split(';');
				mapDiv.title='';
				
				var map = new google.maps.Map2(mapDiv);
				
				google.maps.Map2.prototype.handleMove = function(){
					this.getPoints();
				}

				google.maps.Map2.prototype.handleMoveStart = function(){
					this.oldZoom = map.getZoom();
				}

				google.maps.Map2.prototype.initialiseMap = function(){
					var map = this;
					GEvent.addListener(this, 'moveend', function(){ map.handleMove(); });
					GEvent.addListener(this, 'movestart', function(){ map.handleMoveStart(); });
					map.handleMove();
				}

				google.maps.Map2.prototype.getPoints = function(){
					if(response = this.getCachedResponse()){
						return this.handlePointsResponse(response);
					}
					var map = this;
					mapBounds = this.getBounds();
					zoom = this.getZoom();
					
					map.req = new AjaxObj();
                	qs = this.queryString;
               		 	if(!qs){qs='?'; }
               			 qs += '&output=json';
                		 qs += '&submit_search=1';
                		 qs += '&map_bounds='+mapBounds;
                		 qs += '&zoom='+zoom;
                	map.req.doRequest('/property/searchmap'+qs,function(response){  map.handleJsonResponse(response); });
					
				}

				google.maps.Map2.prototype.getCachedResponse = function(){
					if(this.storedResponses && this.storedResponses[this.getZoom()]){
						for(var i=0; i<this.storedResponses[this.getZoom()].length; i++){
							respBounds = new GLatLngBounds(
							new GLatLng(
							this.storedResponses[this.getZoom()][i].bounds[0][0],
							this.storedResponses[this.getZoom()][i].bounds[0][1]
							),
							new GLatLng(
							this.storedResponses[this.getZoom()][i].bounds[1][0],
							this.storedResponses[this.getZoom()][i].bounds[1][1]
							)
							);
							if(respBounds.containsBounds(this.getBounds())){
								return this.storedResponses[this.getZoom()][i];
							}
						}
					}

					return false;
				}

				google.maps.Map2.prototype.handleJsonResponse = function(response){
                	if(response.points){
                    	this.storeResponse(response);
                	}
                	this.handlePointsResponse(response);

				}

				google.maps.Map2.prototype.clearRedundantPoints = function(){

					this.singleMarkerIds = new Array();

					// if zoom changes, clear everything
					if(map.oldZoom!=map.getZoom()){
						this.markers = new Array();
						return this.clearOverlays();
					}

					for(var i=0; i<this.markers.length; i++){
						var m = this.markers[i];
						if(m.propertycount==1){
							this.singleMarkerIds.push(m.propertyid);
						}
						else{
							this.removeOverlay(m);
							this.markers.splice(i,1);
							i--;
						}
					}
				}

				Array.prototype.contains = function(value){
					for(var i=0;i<this.length; i++){
						if(value==this[i]){ return true; }
					}
					return false;
				}

				// Handles the response from the server
				google.maps.Map2.prototype.handlePointsResponse = function(response){


					if(pointsData = response.points){

						if(!this.markers){
							this.markers= new Array();
						}
						this.clearRedundantPoints();
						for(var i=0; i<pointsData.length; i++){
							var icon=G_DEFAULT_ICON;
							count = (pointsData[i].count);
							if(count==1){
								icon = custom_icon[1];
							}
							if(count>1 && count<10){
								icon = custom_icon[pointsData[i]['count']];
							}
							if(count>=10 && count<20){
								icon = custom_icon[10];
							}
							if(count>=20 && count<50){
								icon = custom_icon[20];
							}
							if(count>=50 && count<100){
								icon = custom_icon[50];
							}
							if(count>=100 && count<200){
								icon = custom_icon[100];
							}
							if(count>=200 && count<500){
								icon = custom_icon[200];
							}
							if(count>=500 && count<1000){
								icon = custom_icon[500];
							}
							if(count>=1000 && count<2000){
								icon = custom_icon[1000];
							}
							if(count>=2000){
								icon = custom_icon[2000];
							}
							var marker = new GMarker(new GLatLng(pointsData[i].lat, pointsData[i].lng) ,{icon: icon});

							marker.propertycount = count;
							marker.propertyid=pointsData[i].id;

							if(count!=1 || !this.singleMarkerIds.contains(marker.propertyid)){

								this.addOverlay(marker);
								this.markers.push(marker);

								var map = this;
								if(count==1){
									GEvent.addListener(marker, "click", function() {
										map.getPointDetails(this);
									});
								}
								else{
									GEvent.addListener(marker, "click", function() {
										newZoom = (map.getZoom()<15)?(map.getZoom()+2):map.getZoom();
										map.setCenter(this.getLatLng(), newZoom);
									});
								}
							}

						}

					}


				}

				google.maps.Map2.prototype.getPointDetails = function(point){
					this.fetchPointDetails(point);
				}

				google.maps.Map2.prototype.fetchPointDetails = function(point){
					if(!this.pointsDetails){
						this.pointsDetails = new Array();
					}
					if(this.pointsDetails[point.propertyid]){
						return this.displayPointDetails(point, point.propertyid, this.pointsDetails[point.propertyid]);
					}
					map = this;
					map.req = new AjaxObj();
					
					path = location.pathname.split('/');
					
					regex = new RegExp('^[a-z]{2}$');
					lang=false;
					if(match=(regex.exec(path[1]))) {
						lang = match[0];
					}
					
					
                	qs = this.queryString;
               		 	if(!qs){qs='?'; }
               			 qs += '&output=json';
               		url = '/';
               		if(lang) {
               			url += lang + '/';
               		}
               		url += 'property/display/'+point.propertyid+qs;
                	map.req.doRequest(url,
                	function(t){
							map.displayPointDetails(point,t.id, t.details);
							map.pointsDetails[t.id] = t.details;
						});
				}

				google.maps.Map2.prototype.displayPointDetails = function(point,id, details){
					point.openInfoWindowHtml(details, {'maxWidth':'300'});
					point.infoWindowIsOpen=true;
					GEvent.addListener(point, "infowindowclose", function() {
						this.infoWindowIsOpen=false;
					});
				}

				google.maps.Map2.prototype.storeResponse = function(response){

					if(!this.storedResponses){
						this.storedResponses = new Array();
					}

					if(!this.storedResponses[response.zoom]){
						this.storedResponses[response.zoom] = new Array();
					}

					this.storedResponses[response.zoom].push(response);

				}

				var custom_icon = [];
				var iconFolder = '/assets/DTZ/img/map-icons/';
				var iconPops = [1,2,3,4,5,6,7,8,9,10,20,50,100,200,500,1000,2000];
				var iconImages = ['1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png',
				'10+.png','20+.png','50+.png','100+.png','200+.png','500+.png',
				'1000+.png','2000+.png'];
				for(var i=0; i<iconPops.length; i++){

					custom_icon[iconPops[i]]=new GIcon(G_DEFAULT_ICON, iconFolder+iconImages[i]);

					if(iconPops[i]==1) {					
						custom_icon[iconPops[i]].iconSize = new GSize(24,33);
						custom_icon[iconPops[i]].iconAnchor = new GPoint(12,33);
						custom_icon[iconPops[i]].infoWindowAnchor = new GPoint(12,5);
						custom_icon[iconPops[i]].imageMap = [12,1,18,2,22,6,22,11,21,17,18,22,11,31,5,22,2,17,1,11,1,7,5,2];
						custom_icon[iconPops[i]].shadowSize = new GSize(37,33);
						custom_icon[iconPops[i]].shadow =  iconFolder+'marker_shadow.png';
					}
					else if(iconPops[i]>=2 && iconPops[i]<=9){
						custom_icon[iconPops[i]].iconSize = new GSize(28,39);
						custom_icon[iconPops[i]].iconAnchor = new GPoint(14,39);
						custom_icon[iconPops[i]].infoWindowAnchor = new GPoint(14,5);
						custom_icon[iconPops[i]].imageMap = [15,1,22,2,26,6,26,12,25,19,22,25,13,35,6,25,3,19,2,12,2,8,6,2];
						custom_icon[iconPops[i]].shadowSize = new GSize(44,39);
						custom_icon[iconPops[i]].shadow =  iconFolder+'marker_shadow10.png';
					}
					else if(iconPops[i]>=10 && iconPops[i]<=50){
						custom_icon[iconPops[i]].iconSize = new GSize(32,45);
						custom_icon[iconPops[i]].iconAnchor = new GPoint(16,45);
						custom_icon[iconPops[i]].infoWindowAnchor = new GPoint(16,5);
						custom_icon[iconPops[i]].imageMap = [18,2,26,3,30,7,30,14,29,22,26,29,15,41,7,29,4,22,3,14,3,10,7,3];
						custom_icon[iconPops[i]].shadowSize = new GSize(51,45);
						custom_icon[iconPops[i]].shadow =  iconFolder+'marker_shadow50.png';
					}
					else if(iconPops[i]>=100){
						custom_icon[iconPops[i]].iconSize = new GSize(36,51);
						custom_icon[iconPops[i]].iconAnchor = new GPoint(18,51);
						custom_icon[iconPops[i]].infoWindowAnchor = new GPoint(18,5);
						custom_icon[iconPops[i]].imageMap = [20,3,29,4,33,8,33,16,32,25,29,33,16,47,7,33,4,25,3,16,3,12,7,4];
						custom_icon[iconPops[i]].shadowSize = new GSize(57,51);
						custom_icon[iconPops[i]].shadow =  iconFolder+'marker_shadow100.png';
					}
					
					custom_icon[iconPops[i]].transparent = iconFolder+'1_percent.png';

				}

				if(loc.length==3) {
					map.setCenter(new google.maps.LatLng(loc[0], loc[1]), loc[3]*1);
				}
				else {
					if(loc.length==4) {
						bounds = new google.maps.LatLngBounds(							
							new google.maps.LatLng(loc[2], loc[3]), // sw
							new google.maps.LatLng(loc[0], loc[1]) //ne
						);
						map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
					}
					else {
						return false;
					}
				}
				
				map.addControl(new GLargeMapControl());
				map.addControl(new GMapTypeControl());
				map.addControl(new GScaleControl());
				map.queryString = location.search;

				map.initialiseMap();

			}

			else {
				var map = new google.maps.Map2(mapDiv);
				map.getContainer().style.overflow='hidden';
				var latLngArray = mapDiv.title.split(';');
				mapDiv.title = '';
				var latLng = new google.maps.LatLng(latLngArray[0], latLngArray[1]);
				map.setCenter(latLng, 12);
				var marker = new google.maps.Marker(latLng);
				map.addOverlay(marker);
				map.addControl(new google.maps.SmallZoomControl);
				map.getContainer().style.overflow='hidden';

				if(lnk = document.getElementById('largeMapLink')){
					google.maps.Event.addListener(map, 'click',
					function(){ window.location.href=lnk.href; });
				}

			}
	}
}


function setupOrderButton()
{
	if(el = document.getElementById('orderSelect')) {
		el.onchange = function() {
			if(this.parentNode && this.parentNode.nodeName=='FORM'){
				var frm = this.parentNode;
				location.href = frm.action+'&'+this.value+'=true';
			}
		}
	}
}

function setupAlertButton()
{
	if(el = document.getElementById('emailAlertForm')) {
		el.onsubmit = function() {
			//			alert(this.qs.value + '&subs_email=' +this.subs_email.value);
			tb_show(null, this.action + '?' + 'subs_email=' + this.subs_email.value + '&' + this.qs.value);
			return false;
		}
	}
}

function AjaxObj() {

    var self = this;
    var callback = null;

    this.getXmlHttp = function(){
        try { var xmlHttp = new XMLHttpRequest();}
        catch (e) { var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}
        return xmlHttp;
    }

    this.xmlHttp = this.getXmlHttp();

    this.doRequest = function(url, callback){
        this.callback = callback;
        this.xmlHttp.open('GET', url, true);
        this.xmlHttp.onreadystatechange = this.handleResponse;
        this.xmlHttp.send(null);
    }

    this.handleResponse = function(){
        if(4==self.xmlHttp.readyState){
            var response = eval('(' + self.xmlHttp.responseText + ')');
            if (typeof self.callback == 'function') { self.callback(response);}
        }
    }

}
