var googlemapclass = Class.create();
googlemapclass.prototype = {
	initialize: function(div) {		
		this.div=$(div);
		this.templateFiche  = 	new Template('<div class="bg"/>'+
								'<a class="close" title="Fermer" onclick="Hidelayer(\'layer-infos\');" href="javascript:void(0);">Fermer</a>'+
								'<div class="row1">'+
								'	<div>'+
								'		<h3>#{nomparcour}</h3>'+
								'		<em>#{dateajout}</em>'+
								'	</div>'+
								'	<p>'+
								'		<strong>Spot :</strong> #{mode}<br/>'+
								'		<strong>Parcours :</strong> #{parcours}<br/>'+
								'		<strong>Dénivelé :</strong> #{denivele}<br/>'+
								'		<strong>Distance :</strong> #{distance}<br/>'+
								'	</p>'+
								'	<div style="background: transparent url(#{photo}) no-repeat scroll 2px 2px; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" class="pic"><div class="masklayer"/><img src="#{photo}" alt="" class="print"></div>'+
								'</div>'+
								'</div>'+
								'<div class="row2">'+
								'	<p>'+
								'		<span>Accès</span><br/>'+
								'		#{acces}'+
								'		<br/><br/> '+
								'		<span>Commentaire</span><br/>'+
								'		#{info}'+
								'	</p>'+
								'	<a class="print" title="Imprimer" href="javascript:_googlemap.printFiche();">Imprimer</a>'+
								'</div>');
								
								
								
		this.templateInfoBulle  = new Template('<div id="infosbulle">'+
								'	<h4>#{nomparcour}</h4>'+
								'	<div class="content">'+
								'		<div class="pic" style="background:url(#{vig}) 2px 2px no-repeat;"><div class="mask"></div></div>'+
								'		<p class="txt">#{info}</p>'+
								'		<p>'+
								'			<strong>Spot :</strong> #{mode}<br />'+
								'			<strong>Parcours :</strong> #{parcours}<br />'+
								'			<strong>D&eacute;nivel&eacute; :</strong> #{denivele}<br />'+
								'			<strong>Distance :</strong> #{distance}<br />'+
								'		</p>'+
								'		<a href="javascript:void(0);" onclick="Showlayer(\'layer-infos\');" title="Voir la fiche">Voir la fiche</a>'+
								'	</div>'+
								'</div>');
								
								
								
		this.placeMarks=new Array();
		this.map = new GMap2(this.div);
		this.geocoder = new GClientGeocoder();
		this.map.addControl(new GMapTypeControl());
	    this.centerdefault=new GLatLng(46.9502622421856, 2.6806640625);
	    this.zoomdefault=5;
	    this.map.setCenter(this.centerdefault, this.zoomdefault);
		this.zoommaxi=16;
		this.zoommini=5;
		this.map.addControl(new GSmallMapControl());
		this.map.enableScrollWheelZoom();
		this.page=1;
		this.nbpage=1;
		this.polygones=null;
		this.selectedplaceMark =null;
 	    this.Cluster=new Array();
	    GEvent.addListener(this.map, 'zoomend', this.zoomend.bind(this));
	    GEvent.addListener(this.map, 'moveend', this.moveend.bind(this));
 		Event.observe(window, 'unload', function(){ GUnload();     });
 		this.params = null;
 		
 		this.initAllBtn();
 		
 		this.getSpots();
	},
	search:function (address) {
		if (this.geocoder) {
        	this.geocoder.getLatLng(address,this.setCenter.bind(this));
		}
    },
    setCenter:function(point){
		this.map.setCenter(point, 8);   
    },
	printFiche:function(){
		//console.debug(this);
		var _html  = $('layer-infos').innerHTML;
		//Correction IE et code pour imprimer
		_html = _html.gsub('_googlemap.printFiche','window.print');
		
		var html = '<html>\n<head>\n';
		html += '\t<style type="text/css" media="screen"> @import url("skins/css/print.css"); </style>\n\n';
		html += '\t<style type="text/css" media="print"> @import url("skins/css/print.css"); </style>\n\n';
		html += '\n</head>\n\n';
		html += '\n<body>\n\n';
		html += '<div id="layer-infos">';
		html += _html;
		html += '</div>';
		html += '\n</body>\n</HTML>';
		
		var printWin = window.open("","printSpecial", "width=775,height=335,scrollbars=no");
		printWin.document.open();
		printWin.document.write(html);
		printWin.print();
		//window.print();
	},
	initAllBtn:function(){
		$('all-type').checked=true;
 		$('all-deniv').checked=true;
 		$('all-distance').checked=true;
	 	_mCheck1.setAllBtnState({currentTarget:$('all-type')});
	 	_mCheck2.setAllBtnState({currentTarget:$('all-deniv')});
	 	_mCheck3.setAllBtnState({currentTarget:$('all-distance')});
	},
	closeInfoHtmlZoomed:function(){
		this.map.closeInfoWindow();
	},
	zoomend:function(){
		if(this.map.getZoom()<this.zoommini) 
			this.map.setZoom(this.zoommini);
		
		this.updateVisualSpot();
	},
	moveend:function(){
	},
	gotoPointAndDisplayParcour:function(e,o){
		this.map.clearOverlays();
		this.map.closeInfoWindow();
		this.selectedplaceMark.full = eval(e.responseText)[0];
		//this.selectedplaceMark.full.photo = 'data/spot/'+this.selectedplaceMark.id+'/2.jpg';
		this.selectedplaceMark.full.photo = this.selectedplaceMark.vigb;
		this.polygones = eval(this.selectedplaceMark.full.polygone);
		var centerPoint = new GLatLng(this.polygones[1][0][0],this.polygones[1][0][1]);
		this.map.setCenter(centerPoint, this.polygones[0][0]);
		this.map.setZoom(this.polygones[0]);
		this.polygonize();
		
		var v = this.selectedplaceMark.full;
		v.mode = (v.mode=="les2") ? "Running et VTT" : v.mode;
		v.parcours=[];
		
		if(v.trajet_bord_de_mer==1)
			v.parcours.push("bord de mer");
		if(v.trajet_foret==1)
			v.parcours.push("foret");
		if(v.trajet_montagne==1)
			v.parcours.push("montagne");
		if(v.trajet_plaine==1)
			v.parcours.push("plaine");
		if(v.trajet_ville==1)
			v.parcours.push("ville");
		if(v.trajet_autre==1)
			v.parcours.push("autre");
				
		v.parcours = v.parcours.join(", ");
		
		var html = this.templateFiche.evaluate(this.selectedplaceMark.full);
		$('layer-infos').update(html);
		if(this.displayFiche==true){
			Showlayer('layer-infos');
		}else{
			setTimeout(this.displayInfobulle.bind(this),500);
		}
	},	
	displayInfobulle:function(){
		var fiche = this.templateInfoBulle.evaluate(this.selectedplaceMark.full);
		this.selectedplaceMark.marker.openInfoWindowHtml(fiche, {maxWidth:224,maxHeight:208,autoScroll:false});
	},
	polygonize:function(){
		var polylines=new Array();
		var allPost = this.polygones[1];
		for(x=0;x<allPost.length;x++){
			polylines.push(new GLatLng(allPost[x][0],allPost[x][1]));
		}
			
		this.map.addOverlay(this.selectedplaceMark.marker);
		var polyline = new GPolyline(polylines, "#0000ff", 5,0.5);
		this.map.addOverlay(polyline);
		var bound = polyline.getBounds();
		
	},
	
	updateVisualSpot:function(){
		this.map.clearOverlays();
		for (i=0;i<this.placeMarks.length;i++) {
			this.map.addOverlay(this.placeMarks[i].marker);
		}
		this._filterIntersectingMapMarkers();
	},
	//----------------------------------------------------------------
	// Cluster 
	//--
	
	_filterIntersectingMapMarkers:function(){
		for (i=0;i<this.Cluster.length;i++)
			this.map.removeOverlay(this.Cluster[i]);
		var notToShow=new Array();
		var count=0,i, j, _isActive, mapMarkers, Bounds = this.map.getBounds();
		for (i=0;i<this.placeMarks.length;i++) {
			mapMarkers = this.placeMarks[i].marker;
			var savedMarkers = new Array();
			var _isActive  = Bounds.containsLatLng(mapMarkers.getLatLng()) ? true : false;
			if(_isActive && this.in_array(notToShow,this.placeMarks[i].marker)==false){
				for (j=0;j<this.placeMarks.length;j++){
					_mapMarkers = this.placeMarks[j].marker;
					if (mapMarkers!=_mapMarkers && this.in_array(notToShow,this.placeMarks[j].marker)==false){
						_distance = Math.round(this.calculateRadius(mapMarkers.getLatLng(),_mapMarkers.getLatLng()));
						 if(_distance<30) { 
							notToShow.push(_mapMarkers);
							this.placeMarks[j].marker.hide(); 
							savedMarkers.push(this.placeMarks[j]);
	 						count++;
	 					}
 					}
				}
 				if(savedMarkers.length>0){
	 				this.placeMarks[i].marker.hide(); 
					savedMarkers.push(this.placeMarks[i]);
					var info={
						markers:savedMarkers,
						latlong:this.placeMarks[i].marker.getLatLng()
					};
					markerInCluster = this.createGroupMarker(info);
					this.Cluster.push(markerInCluster);
					this.map.addOverlay(markerInCluster);
 				}
		    }
		}
	},
	createGroupMarker:function(info){
		var allshort 			= "";
		
		var Icon 				= new GIcon();
		Icon.iconSize 			= new GSize(22,32);
		Icon.iconAnchor 		= new GPoint(11, 32);
		Icon.infoWindowAnchor 	= new GPoint(11, 1);
		Icon.image				= "skins/img/push_pin_group.png";
		
		
		for (i=0;i<info.markers.length;i++) {
			_marker = info.markers[i];
			allshort+='<a href="javascript:void(0);" onclick="_googlemap.getParcourHtml('+_marker.i+');" title="D&eacute;couvrez ce spot">'+_marker.nomparcour+'</a><br/>';
			_marker.marker.hide(); 
		}
		var _marker = new GMarker(info.latlong, {icon:Icon});
		_marker.importance=200;
		_marker.allshort=allshort;
		
		GEvent.addListener(_marker, "click", this.openWindowGrouped.bindAsEventListener(this,_marker));
		
		return _marker;
	},
	openWindowGrouped:function(e,m){
		this.map.closeInfoWindow();
		m.openInfoWindowHtml(m.allshort, {maxWidth:400,maxHeight:300,autoScroll:true});
	},	
	in_array:function(array,item){
		for(xx=0;xx<array.length;xx++){
			if(array[xx]==item){
				return true;
			}
		}
		return false;
	},
	calculateRadius:function(point1, point2) {
	    var point1 = this.map.fromLatLngToDivPixel(point1);
	    var point2 = this.map.fromLatLngToDivPixel(point2);
	    var radius = this.distanceFrom(point1,point2);
	    return radius;
	
	},
	distanceFrom:function(a2,a){
        var b=a2.x-a.x;
        var c=a2.y-a.y;
        return Math.sqrt(b*b+c*c)
	},
	
	//------------------------------------------------------------------------
	// Recherche
	//-----------------------------------------------------------------------
	
	getSpots:function(){
		this.params = $('SearchForm').serialize(true);
		if(this.params.dept==""){
			this.map.setCenter(this.centerdefault, this.zoomdefault);
		}else{
			this.search(this.params.dept+", France");
		}
		new Ajax.Request(
			'includes/php/get.json.spot.php',{
				method: 'post',
				parameters:this.params,
				onSuccess:this.updateContent.bind(this)
			}
		);	
	},
	updateContent:function(e){
		this.map.clearOverlays();
		this.placeMarks = eval(e.responseText);
		var nbspots = (this.placeMarks.length>1) ? this.placeMarks.length+" s&eacute;lections" : this.placeMarks.length+" s&eacute;lection";
		$('nbSpots').update(nbspots);
		var Icon 				= new GIcon();
		Icon.iconSize 			= new GSize(15,22);
		Icon.iconAnchor 		= new GPoint(8, 22);
		Icon.infoWindowAnchor 	= new GPoint(8, 1);
		Icon.image				= "skins/img/push_pin.png";
		for (i=0;i<this.placeMarks.length;i++) {
			var marker = new GMarker( new GLatLng(this.placeMarks[i].map_lat,this.placeMarks[i].map_long),{icon:Icon});
			GEvent.addListener(marker, "click", this.getParcour.bindAsEventListener(this,this.placeMarks[i]));
			this.placeMarks[i].marker=marker;
			this.placeMarks[i].i=i;
		}
		this.updateVisualSpot();
		this.page=0;
		this.nbpage = this.placeMarks.length/4;
		this.nbpage = (Math.round(this.nbpage)<this.nbpage) ? Math.round(this.nbpage)+1 : Math.round(this.nbpage);
		this.pagination();
		this.updateVignette();
	},
	
	pagination:function(){
		
		var maxV		= 3;
		
		var html 		= '';
		var prev 		= (this.page==0) ? 0 : this.page-1;
		var next 		= ((this.page+1)==this.nbpage) ? this.nbpage-1 : this.page+1;
		var classprev 	= (this.page==0) ? 'class="disabled"' : '';
		var classnext 	= ((this.page+1)==this.nbpage) ? 'class="disabled"' : '';
		
		html = '<li id="pagination_previous" '+classprev+'><a href="#" onclick="_googlemap.setPage('+prev+');" title="Precedent"></a></li>';
		
		var firstPage 	= 1;
		var endPage		= this.nbpage;
		
		html+=(this.page == (firstPage-1)) ? '<li class="current"><span>'+firstPage+'</span></li>' : '<li class="current"><span><a href="javascript:void(0);" onclick="_googlemap.setPage('+(firstPage-1)+');">'+firstPage+'</a></span></li>';
		
		if(this.page<=3){
			for(t=1;t<this.nbpage-1;t++){
				if(t<5)
					html+=(this.page == t) ? '<li class="current"><span>'+(t+1)+'</span></li>' : '<li class="current"><span><a href="#" onclick="_googlemap.setPage('+t+');">'+(t+1)+'</a></span></li>';
			}
			html+='<li class="truncate">...</li>';
			html+='<li class="current"><span><a href="javascript:void(0);" onclick="_googlemap.setPage('+(endPage-1)+');">'+(endPage)+'</a></span></li>';
		}else if(this.page>3 && this.page<this.nbpage-4){
			html+='<li class="truncate">...</li>';
 			var t	= this.page;
 			var tp	= t-1;
 			var tn	= t+1;
 			html+='<li class="current"><span><a href="javascript:void(0);" onclick="_googlemap.setPage('+(tp)+');">'+(tp+1)+'</a></span></li>';
 			html+='<li class="current"><span>'+(t+1)+'</span></li>'
			html+='<li class="current"><span><a href="javascript:void(0);" onclick="_googlemap.setPage('+(tn)+');">'+(tn+1)+'</a></span></li>';
			html+='<li class="truncate">...</li>';
			html+='<li class="current"><span><a href="javascript:void(0);" onclick="_googlemap.setPage('+(endPage-1)+');">'+(endPage)+'</a></span></li>';
		}else if(this.page>=this.nbpage-4){
			html+='<li class="truncate">...</li>';
 			for(t=this.nbpage-4;t<this.nbpage;t++){
				html+=(this.page == t) ? '<li class="current"><span>'+(t+1)+'</span></li>' : '<li class="current"><span><a href="#" onclick="_googlemap.setPage('+t+');">'+(t+1)+'</a></span></li>';
			}
		}
		html+='<li id="pagination_next" '+classnext+'><a href="#" onclick="_googlemap.setPage('+next+');" title="Suivant"></a></li>';
		
		$('_pagination').update(html);
	},
	updateVignette:function(){
		var html='', i=1, start = (this.page*4), end = start+4;
		for(x=start;x<end;x++){
			if(this.placeMarks[x])
				html+='<div class="mask'+i+'" style="background:url('+this.placeMarks[x].vig+');"><a href="javascript:void(0);" onclick="_googlemap.getParcourHtml('+x+');" title="D&eacute;couvrez ce spot">D&eacute;couvrez ce spot</a></div>';
				//html+='<div class="mask'+i+'" style="background:url(data/spot/'+this.placeMarks[x].id+'/221.jpg);"><a href="javascript:void(0);" onclick="_googlemap.getParcourHtml('+x+');" title="D&eacute;couvrez ce spot">D&eacute;couvrez ce spot</a></div>';
			i++;
		}
		$('ListImages').update(html);
	},
	
	setPage:function(p){
		this.page=p;
		this.pagination();
		this.updateVignette();
	},
	
	getParcourHtml:function(offset){
		this.selectedplaceMark = this.placeMarks[offset];
		this.displayFiche=true;
		new Ajax.Request(
			'includes/php/get.json.parcour.php',
			{
				method: 'post',
				parameters:{id:this.selectedplaceMark.id},
				onSuccess:this.gotoPointAndDisplayParcour.bind(this)
			}
		);	
	},	
	
	getParcour:function(e,placeMark){
		this.selectedplaceMark = placeMark;
		this.displayFiche=false;
		new Ajax.Request(
			'includes/php/get.json.parcour.php',
			{
				method: 'post',
				parameters:{id:placeMark.id},
				onSuccess:this.gotoPointAndDisplayParcour.bind(this)
			}
		);	
	}
	
	
};


