var myCom = {
	markers: [], 
	popup: {}, 
	info: {},
	apiUrl : "/include/map-json.php",
	apiInfo: "/include/map-info.php",
	mc : {},
	map : {}
};

window.addEvent('domready', function() {	

	// Execution automatique
	(function () {

		// Lancement de la bannière défilante
		if ($('slider') != null && $('slider').hasClass('noscroll') == false) {
			var slider = new Fx.Scroll.Carousel('slider',{
				mode: 'horizontal'
			});
	
			var show = function () { slider.toNext(); };
			show.periodical(4000);
		}

		if ($('launchDiaporama')) {
			var diapo = [];
			$$('.album a[rel=lightbox-slideshow-page]').each(function(e,i) { diapo.push([e.get('href')]) });
			$('launchDiaporama').addEvent('click', function(e) { e.stop(); Slimbox.open(diapo, 0, {loop: true}); });
		}
		
		if ($('menuActive') != null) {
			$$('#menuNav > li').each(function(elt, i) {
				if (elt.hasClass($('menuActive').get('value'))) {
					elt.set('class', elt.get('class')+'_over');
				}
			});
		}
		
		$$('#content > p.visuel').each(function(elt, i) {  
			if (elt.get('html') == "") 
				elt.destroy();
		});
		
		if (Browser.Engine.name == 'trident' && Browser.Engine.version == 4) {
			$$('#menuNav > li').each(function(i, e) {
				i.addEvents({
					'mouseenter': function () {
						this.set('class', this.get('class')+'_over over');
					},
					'mouseleave' : function () {
						this.set('class', this.get('class').replace(/^(.*)_over\sover$/,'$1'));
					}
				});
			});
		}
		
		
		String.prototype.getRoot = function () {
			return this.replace(/^.*\/([^\/]+)$/g,"$1");
		}
		
		var urlRef = document.URL.getRoot();
		if (urlRef == "http://www.digitaleen.com/domia/") {
			$('navigation').setStyle('display', 'none');
		}else {
			if ($('partenaire') != null)
			$('partenaire').setStyle('display', 'none');
		}
		
		
		var lstPage = ["nos-engagements.php"];
		lstPage.each(function(elt,i) { 
			if (document.URL.getRoot() == elt)  {
				$('slider').destroy();
			}
		});
		
		
		if ($('content-form') != null) {
			var myForm = new Forms('content-form');
		}
		
		
		if ($('map') != null) {
			window.onload = function() {
				var ll0;
				if ($('latlng') != null && $('latlng').get('value') != "") {
					ll0 = $('latlng').get('value').split(';');
				}else ll0 = [45.79152069,3.11483619];

			var myOptions = {
    	  		zoom: 15,
				center: new google.maps.LatLng(ll0[0],ll0[1]),
      			mapTypeId: google.maps.MapTypeId.ROADMAP,
				mapTypeControl: true,
				mapTypeControlOptions : {
					style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
				},
				navigationControl: true,
				navigationControlOptions : {
					position: google.maps.ControlPosition.TOP_LEFT,
					style : google.maps.NavigationControlStyle.DEFAULT
				},
				scaleControl: true,
				keyboardShortcuts: true,
				scrollwheel: false,
				streetViewControl: true,
				draggableCursor: 'move',
				draggingCursor: 'move'
	    	}
			myCom.map = new google.maps.Map($('map'),myOptions);
			
			var reqInit = new Request.JSON({
				method : 'get', 
				url : myCom.apiUrl,
				onSuccess: function (obj, txt) { 
					initMarkers(obj);
				}
			}).send(null);
			
			
			marker = new google.maps.Marker({
									position: myCom.map.getCenter(), 
									title: "Domia, 13 boulevard Leon Jouheaux, 63100 Clermont-Ferrand", 
									map: myCom.map});
			
			var markerTram = new google.maps.Marker({
									position: new google.maps.LatLng(45.79116161,3.11376330), 
									title: "Station de Tram : Montferrand - Lafontaine", 
									map: myCom.map,
									icon: '/domia/templates/01/images/map-train.png'});
			
			var bounds = new google.maps.LatLngBounds (new google.maps.LatLng(45.84175717,2.94057915),new google.maps.LatLng(45.68128034,3.25986931));
			
			var initMarkers = function (jsonData) {
				var currentItem = {}, latlng = {}, marker = {}, info;
				var mk = []; 
		
				var urlRef = document.URL.getRoot();
		
				for (i in jsonData) {
					currentItem = jsonData[i];
			
					for (j in currentItem) {
						if (currentItem[j].hasOwnProperty('lat') && currentItem[j]['lat'] != "") {
						latlng = new google.maps.LatLng(currentItem[j]['lat'],currentItem[j]['lng']);

						bounds.extend(latlng);
						
						marker = new google.maps.Marker({
									position: latlng, 
									title: currentItem[j]['libelle'], 
									map: myCom.map,
									icon: (currentItem[j]["type"] == "realisation")?"/templates/01/images/icon-home.png":"/templates/01/images/icon-realestate.png"});


						mk.push(marker);

						info = '<p class="info">'+currentItem[j]['libelle']+'<br/><br/></p>';
						myCom.markers.push({info: info, marker: marker, url: 'comm', id: (currentItem[j].hasOwnProperty('id'))?currentItem[j]["id"]:null});

						setInfo(myCom.markers[myCom.markers.length-1]);
						}
				
					}
				}
		
		
				myCom.mc = new MarkerClusterer(myCom.map, mk, {gridSize: 50, maxZoom: 17});
				
				if (urlRef.match(/^.*\?id=([0-9]+).*$/) != false) {
					launchInfoWindow(urlRef.replace(/^.*\?id=([0-9]+).*$/, '$1'));
				}
			};
			
			myCom.map.fitBounds(bounds);
			
			
			
			var setInfo = function (obj) {
			// Utilise une variable globale pour infowindow pour eviter d'utiliser plusieurs fenetres
			// Utiliser une variable locale pour utiliser plusieurs fenetres
				myCom.info = new google.maps.InfoWindow(
			      { content: obj.info,
    			    size: new google.maps.Size(200,50)
      			  });
			
				google.maps.event.addListener(obj.marker, 'click', function() {
				// Se positionne sur le marker
					myCom.map.panTo(obj.marker.getPosition());
			
					(function (m, id) {
						var hx = new XMLHttpRequest();
						hx.open( "GET", myCom.apiInfo+"?q="+id, true );
						hx.onreadystatechange = function () {
							if (hx.readyState == 4 && hx.status == 200){
								myCom.info.setContent(hx.responseText);
								myCom.info.open(myCom.map,m);
  							}	
						}
						hx.send(null);
					})(obj.marker,obj.id);
				});
			
			// Si accès direct à une fiche
/*				if (document.URL.getRoot() == obj.url) {
					// Lancer plutot le triger "click" du marker plutot que d'ouvrir l'infowindow	
					infowindow.open(myCom.map,obj.marker);
					myCom.map.panTo(obj.marker.getPosition());
				}*/
  			};
			
			
			
			}
		}

	})();
	
	
	
});

function launchInfoWindow (id) {
	for (e in myCom.markers) {
		if ((myCom.markers[e]).id == id)	{
			myCom.map.panTo(myCom.markers[e].marker.getPosition());
			google.maps.event.trigger(myCom.markers[e].marker, 'click');
			myCom.map.setZoom(12);
		}
	}
	
}

function displayMarker (id) {
		for (e in myCom.markers) {
			if (myCom.markers[e]["id"] == 4) {
				google.maps.event.trigger(myCom.markers[e].marker,"click");
				break;
			}
		}
		
	}

var Forms = new Class ({
		Implements: Options,
		
		options : {
			formValidInput : 'valid-form',
			errorClass : 'error'
		},

		initialize : function (container, options) {
			this.setOptions(options);
			this.validForm = $(this.options.formValidInput);
			
			
			this.container = $(container);

			this.obl = [];
			this.initUrl();
			this.initPopup();

			$('valid-form').addEvent('click', function(event) {
				event.stop();
				this.obl.empty();
				this.parseInput(this.container); 
				if (this.obl.length > 0) {
					event.preventDefault(); 
					this.displayObl();
				}else $('content-form').submit();
			}.bind(this));
		},
		
		initUrl : function () {
			this.action = this.container.get('action');
		},
		
		initPopup : function () {
			this.popup = new Element ('div', {'id' : 'popup'});
			this.popup.inject(document.body, 'top');
			
			this.popup.addEvents({
				'show' : function () { this.toggleClass('show'); },
				'hide' : function () { this.toggleClass('show'); }
			});
		},
		
		parseInput : function (container) {
			var bool = true;
			(container.getElements('input, textarea, select')).each(function (elt, i) {
				if (elt.hasClass('obligatoire') && this.testInput(elt) == false) {
					elt.addClass(this.options.errorClass);
					this.obl.push(elt);
				}else if (elt.hasClass('error')) elt.removeClass('error');
			}, this);
		},
		
		testInput : function (tag) {
			var result =  true;

			switch (tag.get('tag')) {
				case 'input'	:	if (tag.get('type') == 'text') {
										if (tag.get('value').trim() == '')
											result = false;
										tag.addEvent('click', function() { this.select(); });
									}
									else if (tag.get('type') == 'checkbox' && tag.checked == false) result = false;
									else if (tag.get('type') == 'radio' && tag.checked == false) result = false
									break;

				case "textarea"	:	if (tag.get('value').trim() == '') result = false;
									break;

				case "select"	:	if (tag.get('value') == 0) result = false;
									break
			}
			
			return result;
		},

		displayObl : function () {
			this.popup.empty();
			
			var background = new Element('div', {'class': 'background'});
			background.inject(this.popup);
			
			var message = new Element('div', {'class': 'message'});
			message.addEvent('click', function () { this.popup.fireEvent('hide'); }.bind(this));

			if (this.obl.length > 0) {
				(new Element('p', {'html' : 'Les champs du formulaire <span class="rouge">en rose</span> contiennent des erreurs ou ne sont pas remplis correctement'})).inject(message);
				(new Element('p', {'html' : '&gt;&gt; Revenir sur le formulaire &lt;&lt;', 'class' : 'link'})).inject(message);
				(new Element('p', {'class' : 'footer'})).inject(message);
	
				message.inject(this.popup);
				
				this.popup.fireEvent('show');
			}
		}
	});

