// JavaScript Document
var map = "";
var TousMesMarqueurs = [];
var i = 0;
var nbMarkers = 0;
var minusMarkers = 0;
var infoW=0;


/*function esasZoomOut(){
	var paragraphs = map.getContainer().getElementsByTagName('p').length;
	if(paragraphs > 6){
		map.zoomOut();
	}
};
interval = setInterval("esasZoomOut()",200);*/

function go(url, titre, heightwidth){
	MOOdalBox.open(url, unescape(decodeURIComponent(titre)), heightwidth);
}

function myclick(i){
    GEvent.trigger(TousMesMarqueurs[i], "click");
};

function rollover(i){
    GEvent.trigger(TousMesMarqueurs[i], "mouseover");
};

function rollout(i){
    GEvent.trigger(TousMesMarqueurs[i], "mouseout");
};

function initialize(){

	if (GBrowserIsCompatible()) {		
		document.searchForm.textA.value="";
		var ToutesLesBalisesInput = document.getElementsByTagName('input');
		
		map = new GMap2(document.getElementById("map"), {mapTypes:[G_PHYSICAL_MAP,G_SATELLITE_MAP,G_NORMAL_MAP]});
		
		var center = new GLatLng(46.5,2);
		map.setCenter(center,6);
		map.setUIToDefault();
		map.addControl(new GLargeMapControl());
		var ov = new GOverviewMapControl();
      	map.addControl(ov,new GControlPosition(G_ANCHOR_BOTTOM_RIGHT));
      	ov.hide(true); 
		map.enableDoubleClickZoom(function() {infoW=1;});
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		map.addControl(new GMapTypeControl());
		var bounds = map.getBounds();
		var bminX = bounds.minX;
		var bminY = bounds.minY;
		var bmaxX = bounds.maxX;
		var bmaxY = bounds.maxY;
		
		function reloadMyMap(etat){	
			bounds = map.getBoundsLatLng();
			bminX = bounds.minX;
			bminY = bounds.minY;
			bmaxX = bounds.maxX;
			bmaxY = bounds.maxY;
			if(etat==true){
				Inito(true, 0);
			}
		};
		
		GEvent.addListener(map, 'infowindowclose', function() {
			infoW=0;
			/*reloadMyMap(true);*/
		});
		
		/*fonction qui permet d'afficher les markers uniquement s'ils sont présents sur la map*/
		GEvent.addListener(map,'moveend', function() {
			if (infoW==1){
				reloadMyMap(false);
			}
			else{
				reloadMyMap(true);
			}
		});
		
		var baseIcon = new GIcon();
		baseIcon.iconSize=new GSize(27,36);
		baseIcon.shadowSize=new GSize(40,40);
		baseIcon.iconAnchor=new GPoint(12,36);
		baseIcon.infoWindowAnchor=new GPoint(12,0);
		var vvac = new GIcon(baseIcon, 'images/pictos/vvac.png', null, 'images/pictos/shadow.png');
		var camp = new GIcon(baseIcon, 'images/pictos/camp.png', null, 'images/pictos/shadow.png');
		var chat = new GIcon(baseIcon, 'images/pictos/chat.png', null, 'images/pictos/shadow.png');
		var site = new GIcon(baseIcon, 'images/pictos/site.png', null, 'images/pictos/shadow.png');
		var special = new GIcon(baseIcon, 'images/pictos/special.png', null, 'images/pictos/shadow.png');

		function Init(val, init, nolimit, searchTA, bminX, bminY, bmaxX, bmaxY){
			//alert(bminX+' '+bminY+' '+bmaxX+' '+bmaxY);
			if(val == null){return;}
			var typeselec=val.value;
			if(val.checked==true){
				window['side_bar_html_' + typeselec]="";
				window['present_'+typeselec] = 0;
				GDownloadUrl('xml/data.xml', function(data) {
					var xml = GXml.parse(data);
					var markers = xml.documentElement.getElementsByTagName('marker');
					/*alert(markers[0].getAttribute('nom'));*/
					for (var i = 0; i < markers.length; i++) {
						var type = markers[i].getAttribute('type');
						if(type == typeselec){
							var lat = parseFloat(markers[i].getAttribute('lat'));
							var lng = parseFloat(markers[i].getAttribute('lng'));
							var point = new GLatLng(lat,lng);
							var marque = markers[i].getAttribute('marque').toString();
							var logo = markers[i].getAttribute('logo');
							var nom = markers[i].getAttribute('nom');
							var adresse = markers[i].getAttribute('adresse');
							var codepostal = markers[i].getAttribute('codepostal');
							var ville = markers[i].getAttribute('ville');
							var type = markers[i].getAttribute('type');
							var urlvisite = markers[i].getAttribute('urlvisite');
							var paramlg = markers[i].getAttribute('paramlg');
							var paramvisite = markers[i].getAttribute('paramvisite');
							var urlresa = markers[i].getAttribute('urlresa');
							var tailleW = markers[i].getAttribute('tailleW');
							var tailleH = markers[i].getAttribute('tailleH');
							var searchTAtest = new RegExp(searchTA, "gi");
							if(marque !==""){
								marque=" :: "+marque;
							}
							
							function ajout(){
								visibiliteOn('side_bar_'+typeselec);
								var marker = CreateMarker(point, nom, marque, logo, adresse, codepostal, ville, type, urlvisite, paramlg, paramvisite, urlresa, tailleW, tailleH, i);
								map.addOverlay(marker);
								window['present_'+typeselec] = window['present_'+typeselec] + 1;
								nbMarkers=nbMarkers+1;
								document.getElementById('nbresults').innerHTML = '('+nbMarkers+')';
								window['side_bar_html_' + typeselec] +='<li><a href="javascript:myclick(' + i + ')" onmouseover="rollover(' + i + ')" onmouseout="rollout(' + i + ')"><div id="picto"><img src="images/' + typeselec + '.gif" border="0" width="25" height="25"/></div><div id="row"><span id="sbNom_' + typeselec +'">' + nom + '</span><br /><span id="sbVille">' + ville + '</span><span id="sbMarque">' + marque + '</span></div></a></li>';
							}
							
							if (nolimit==0){
								if (bminX<lng && lng<bmaxX && bminY<lat && lat<bmaxY && (nom.match(searchTAtest) || marque.match(searchTAtest) || ville.match(searchTAtest))){
									ajout();
								}
							}
							if (nolimit==1){
								if (nom.match(searchTAtest) || marque.match(searchTAtest) || ville.match(searchTAtest)){
									ajout();
								}
							}
						}
					}
					document.getElementById('side_bar_' + typeselec).innerHTML = window['side_bar_html_' + typeselec];
				});	
			}
			
			if(val.checked==false){
				visibiliteOff('side_bar_'+typeselec);
				GDownloadUrl('xml/data.xml', function(data) {
					var xml = GXml.parse(data);
					var markers = xml.documentElement.getElementsByTagName('marker');
					for (var i = 0; i < markers.length; i++) {
						var type = markers[i].getAttribute('type');
						if(type == typeselec){
							if(TousMesMarqueurs[i]){
								map.removeOverlay(TousMesMarqueurs[i]);
							}
						}	
					}
				nbMarkers=nbMarkers-window['present_'+typeselec];
				document.getElementById('nbresults').innerHTML = '('+nbMarkers+')';
				window['present_'+typeselec]=0;
				});
			}
		};
		
		function visibiliteOn(thingId){
			var targetElement = document.getElementById(thingId);
				targetElement.style.display = "";
		};
		
		function visibiliteOff(thingId){
			var targetElement = document.getElementById(thingId);
				targetElement.style.display = "none";
		};
		
		function Inito(rech, nolimit){
			//alert("ok");
			if(rech){
				GDownloadUrl('xml/data.xml', function(data) {
					var xml = GXml.parse(data);
					var markers = xml.documentElement.getElementsByTagName('marker');
					for (var i = 0; i < markers.length; i++) {
						if(TousMesMarqueurs[i]){
							map.removeOverlay(TousMesMarqueurs[i]);
						}
					}
				});
			}
			if(ToutesLesBalisesInput != null){
				nbMarkers=0;
				for(var i = 0; i < ToutesLesBalisesInput.length; i++){
					if (rech==false){
						ToutesLesBalisesInput[i].checked=true;	
					}
					if(ToutesLesBalisesInput[i].type == 'checkbox'){
						ToutesLesBalisesInput[i].onclick=function(){Init(this,1,nolimit,document.searchForm.textA.value, bminX, bminY, bmaxX, bmaxY);}
						visibiliteOff('side_bar_' + ToutesLesBalisesInput[i].value);
						Init(ToutesLesBalisesInput[i],1,nolimit,document.searchForm.textA.value, bminX, bminY, bmaxX, bmaxY);
					}	
				}
			};
		document.getElementById('nbresults').innerHTML = '('+nbMarkers+')';
		};
		
		Inito(false, 0);
		document.searchForm.textA.onkeyup=function(e){
			var keycode;
			if (window.event) keycode = window.event.keyCode;
			else if (e) keycode = e.which;
			if (keycode !== "13"){
				Inito(true, 1);
			}
		}
		
		function addslashes(ch) {
			ch = ch.replace(/\\/g,"\\\\")
			ch = ch.replace(/\'/g,"\\'")
			ch = ch.replace(/\"/g,"\\\"")
			return ch
		}
		
		function CreateMarker(point, nom, marque, logo, adresse, codepostal, ville, type, urlvisite, paramlg, paramvisite, urlresa, tailleW, tailleH, i) { 
			if(type=='vvac'){var icone = vvac;} 
			if(type=='camp'){var icone = camp;} 
			if(type=='chat'){var icone = chat;}
			if(type=='site'){var icone = site;}
			if(type=='special'){var icone = special;}
			var marker = new GMarker(point,icone); 
			TousMesMarqueurs[i]=marker;
			
			// Switch icon on marker mouseover and mouseout
			GEvent.addListener(marker, "mouseover", function() {
			  marker.setImage("images/pictos/select.png");
			});
			GEvent.addListener(marker, "mouseout", function() {
			  marker.setImage("images/pictos/"+type+".png");
			});
			
			GEvent.addListener(marker, 'click', function() {
				<!--map.setCenter(point,9);-->
				<!--marker.openInfoWindowHtml('<div><table width="300" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="2"><div id="iframeContent"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="300" height="150" title="aperçu de &quot;'+ nom +'&quot;"><param name="movie" value="viewer.swf?lg=' + paramlg + '&amp;visite=' + paramvisite + '" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><embed src="viewer.swf?lg=' + paramlg + '&amp;visite=' + paramvisite + '" quality="high" wmode="transparent" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="300" height="150"></embed></object></div><div id="visitLink"><a href="iframe.php?_url=' + urlvisite + '&_width=' + tailleW + '&_height=' + tailleH + '" rel="moodalbox ' + tailleW + ' ' + tailleH + '" title="' + nom + '"><img src="images/acceder.png" title="accéder à la visite virtuelle rich-média &quot;' + nom +'&quot;" /></a></div></td></tr><tr><td><div id="ibNom">' + nom + '</div><div id="ibAdresse">' + codepostal + ' ' + ville + '</div></td><td height="50"><div align="right"><img src="images/logos/' + logo + '" alt="logo_' + marque + '" /></div></td></tr></table></div>');-->
				
				marker.openInfoWindowHtml('<div><table width="300" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="2"><div id="iframeContent"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="300" height="150" title="aperçu de &quot;'+ nom +'&quot;"><param name="movie" value="viewer.swf?lg=' + paramlg + '&amp;visite=' + paramvisite + '" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><embed src="viewer.swf?lg=' + paramlg + '&amp;visite=' + paramvisite + '" quality="high" wmode="transparent" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="300" height="150"></embed></object></div><div id="visitLink"><a href=\'javascript:go(\"iframe.php?_url='+ urlvisite +'&_width=' + tailleW + '&_height=' + tailleH + '\", \"'+ escape(encodeURIComponent(nom)) +'\", \"'+ tailleW +' '+ tailleH +'\");\'><img src="images/acceder.png" title="accéder à la visite virtuelle rich-média &quot;' + nom +'&quot;" /></a></div></td></tr><tr><td><div id="ibNom">' + nom + '</div><div id="ibAdresse">' + codepostal + ' ' + ville + '</div></td><td height="50"><div align="right"><img src="images/logos/' + logo + '" alt="logo_' + marque + '" /></div></td></tr></table></div>');
				
				Window.onDomReady(MOOdalBox.init.bind(MOOdalBox));
				infoW=1;
			});
			
			
			
			return marker; 
		};
	
		/*var interprod = CreateMarker(new GLatLng(48.858905, 2.380151), "Interaview Production", "", "", "4 avenue Parmentier", "75011", "PARIS", "special", "http://www.interaview.com", "fr", "interaview", "", "800", "600", 30000);
		map.addOverlay(interprod);*/
	}
	
	else {
		alert("Désolé, votre navigateur n'est pas compatible avec les Google Maps API.");
    }
	
};

function onlyZone(){
	initialize;
}

//MOODALBOX SCRIPT

var _ERROR_MESSAGE = "Oops.. there was a problem with your request.<br /><br />" +
					"Please try again.<br /><br />" +
					"<em>Click anywhere to close.</em>"; // the error message displayed when the request has a problem
var _RESIZE_DURATION 		= 400; 		// Duration of height and width resizing (ms)
var _INITIAL_WIDTH			= 250;		// Initial width of the box (px)
var _INITIAL_HEIGHT			= 250;		// Initial height of the box (px)
var _CONTENTS_WIDTH 		= 500;		// Actual width of the box (px)
var _CONTENTS_HEIGHT		= 400;		// Actual height of the box (px)
var _DEF_CONTENTS_WIDTH		= 500;		// Default width of the box (px) - used for resetting when a different setting was used
var _DEF_CONTENTS_HEIGHT	= 400;		// Default height of the box (px) - used for resetting when a different setting was used
var _ANIMATE_CAPTION		= true;		// Enable/Disable caption animation
var _EVAL_SCRIPTS			= false;	// Option to evaluate scripts in the response text
var _EVAL_RESPONSE			= false;	// Option to evaluate the whole response text

// The MOOdalBox object in its beauty
var MOOdalBox = {
	
	// init the MOOdalBox
	init: function (options) {
		
		// init default options
		this.options = Object.extend({
			resizeDuration: 	_RESIZE_DURATION,
			initialWidth: 		_INITIAL_WIDTH,	
			initialHeight: 		_INITIAL_HEIGHT,
			contentsWidth: 		_CONTENTS_WIDTH,
			contentsHeight: 	_CONTENTS_HEIGHT,
			defContentsWidth: 	_DEF_CONTENTS_WIDTH,
			defContentsHeight: 	_DEF_CONTENTS_HEIGHT,
			animateCaption: 	_ANIMATE_CAPTION,
			evalScripts: 		_EVAL_SCRIPTS,
			evalResponse: 		_EVAL_RESPONSE
		}, options || {});
		
		// scan anchors for those opening a MOOdalBox
		this.anchors = [];
		$A($$('a')).each(function(el){
			// we use a regexp to check for links that 
			// have a rel attribute starting with "moodalbox"
			if(el.rel && el.href && el.rel.test('^moodalbox', 'i')) {
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);
		
		// add event listeners
		this.eventKeyDown = this.keyboardListener.bindWithEvent(this);
		this.eventPosition = this.position.bind(this);
		
		// init the HTML elements
		// the overlay (clickable to close)
		this.overlay = new Element('div').setProperty('id', 'mb_overlay').injectInside(document.body);
		// the center element
		this.center = new Element('div').setProperty('id', 'mb_center').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);
		// the actual page contents
		this.contents = new Element('div').setProperty('id', 'mb_contents').injectInside(this.center);

		// the bottom part (caption / close)
		this.bottom = new Element('div').setProperty('id', 'mb_bottom').setStyle('display', 'none').injectInside(document.body);
		this.closelink = new Element('a').setProperties({id: 'mb_close_link', href: '#'}).injectInside(this.bottom);
		this.caption = new Element('div').setProperty('id', 'mb_caption').injectInside(this.bottom);
		new Element('div').setStyle('clear', 'both').injectInside(this.bottom);
		
		this.error = new Element('div').setProperty('id', 'mb_error').setHTML(_ERROR_MESSAGE);
		
		// attach the close event to the close button / the overlay
		this.closelink.onclick = this.overlay.onclick = this.close.bind(this);
		
		// init the effects
		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: 	this.overlay.effect('opacity', { duration: 500 }).hide(),
			resize: 	this.center.effects({ duration: this.options.resizeDuration, onComplete: nextEffect }),
			contents: 	this.contents.effect('opacity', { duration: 500, onComplete: nextEffect }),
			bottom: 	this.bottom.effects({ duration: 400, onComplete: nextEffect })
		};
		
		this.ajaxRequest = Class.empty;

	},
	
	click: function(link) {
		return this.open (link.href, link.title, link.rel);
	},

	open: function(sLinkHref, sLinkTitle, sLinkRel) {
		this.href = sLinkHref;
		this.title = sLinkTitle;
		this.rel = sLinkRel;
		this.position();
		this.setup(true);
		this.top = Window.getScrollTop() + (Window.getHeight() / 15);
		this.center.setStyles({top: this.top+'px', display: ''});
		this.fx.overlay.custom(0.8);
		return this.loadContents(sLinkHref);
		//alert();
	},

	position: function() {
		this.overlay.setStyles({top: Window.getScrollTop()+'px', height: Window.getHeight()+'px'});
	},

	setup: function(open) {
		var elements = $A($$('object'));
		elements.extend($$(window.ActiveXObject ? 'select' : 'embed'));
		elements.each(function(el){ el.style.visibility = open ? 'hidden' : ''; });
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		this.step = 0;
	},
	
	loadContents: function() {		
		if(this.step) return false;
		this.step = 1;
		
		// check to see if there are specified dimensions
		// if not, fall back to default values
		var aDim = this.rel.match(/[0-9]+/g);
		this.options.contentsWidth = (aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defContentsWidth;
		this.options.contentsHeight = (aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defContentsHeight;
						
		this.bottom.setStyles({opacity: '0', height: '0px', display: 'none'});
		this.center.className = 'mb_loading';
		
		this.fx.contents.hide();
		
		// AJAX call here
		var nextEffect = this.nextEffect.bind(this);
		var ajaxFailure = this.ajaxFailure.bind(this);
		var ajaxOptions = {
			method: 		'get',
			update: 		this.contents, 
			evalScripts: 	this.options.evalScripts,
			evalResponse: 	this.options.evalResponse,
			onComplete: 	nextEffect, 
			onFailure: 		ajaxFailure
			};
		this.ajaxRequest = new Ajax(this.href, ajaxOptions).request();
				
		return false;
	},
	
	ajaxFailure: function (){
		this.contents.setHTML('');
		this.error.clone().injectInside(this.contents);
		this.nextEffect();
		this.center.setStyle('cursor', 'pointer');
		this.bottom.setStyle('cursor', 'pointer');
		this.center.onclick = this.bottom.onclick = this.close.bind(this);		
	},
	
	nextEffect: function() {
		switch(this.step++) {
		case 1:
			// remove previous styling from the elements 
			// (e.g. styling applied in case of an error)
			this.center.className = '';
			this.center.setStyle('cursor', 'default');
			this.bottom.setStyle('cursor', 'default');
			this.center.onclick = this.bottom.onclick = '';
			this.caption.setHTML(this.title);
			
			this.contents.setStyles ({width: this.options.contentsWidth + "px", height: this.options.contentsHeight + "px"});

			if(this.center.clientHeight != this.contents.offsetHeight) {
				this.fx.resize.custom({height: [this.center.clientHeight, this.contents.offsetHeight]});
				break;
			}
			this.step++;
					
		case 2:
			if(this.center.clientWidth != this.contents.offsetWidth) {
				this.fx.resize.custom({width: [this.center.clientWidth, this.contents.offsetWidth], marginLeft: [-this.center.clientWidth/2, -this.contents.offsetWidth/2]});
				break;
			}
			this.step++;
		
		case 3:
			this.bottom.setStyles({top: (this.top + this.center.clientHeight)+'px', width: this.contents.style.width, marginLeft: this.center.style.marginLeft, display: ''});
			this.fx.contents.custom(0,1);
			break;
		
		case 4:
			if(this.options.animateCaption) {
				this.fx.bottom.custom({opacity: [0, 1], height: [0, this.bottom.scrollHeight]});
				break;
			}
			this.bottom.setStyles({opacity: '1', height: this.bottom.scrollHeight+'px'});

		case 5:
			this.step = 0;
		}
	},
	
	
	keyboardListener: function(event) {
		// close the MOOdalBox when the user presses CTRL + W, CTRL + X, ESC
		if ((event.control && event.key == 'w') || (event.control && event.key == 'x') || (event.key == 'esc')) {
			this.close();
			event.stop();
		}		
	},
	
	close: function() {
		this.open ("iframe.php?_url=http://www.france-visites.com/blank.html", "blank", "moodalbox");
		if(this.step < 0) return;
		this.step = -1;
		for(var f in this.fx) this.fx[f].clearTimer();
		this.center.style.display = this.bottom.style.display = 'none';
		this.center.className = 'mb_loading';
		this.fx.overlay.chain(this.setup.pass(false, this)).custom(0);		
		return false;
	}
		
};
// startup
Window.onDomReady(MOOdalBox.init.bind(MOOdalBox));
