/*
Script: googlemap.js
		
License:
        MIT-style license.

About:
		googlemap.js for mootools framework <http://www.mootools.net/> (c) 2007 Valerio Proietti, MIT-style license.
		Class created by Sylvain Barraud, Yvan Cottet and Gregory Paccaud, Luca Pillonel <http://www.esl.ch/>.
		Last modification, 9 novembre 2009.

Version: 1.0

Note:
		XHTML doctype is required.
		
*/

/*
Class: GoogleMap
		
Arguments:

		map_container		A dom element ID
		street_container	A dom element ID
		data				Data origin (DB or XML)
		auto_center			true / false (calculate where to center on)
		streetview			true / false
		cache				false or new Cache()
		customized_icon		true / false (use a customized icon)
		icon_image			path (customized icon)
		icon_shadow			path (customized icon)
		

Example:

		(start code)
		myZebra = new Zebra({
			'list' : $$('#menu a'),
			'class' : 'zebred',
			'onfirst' : true
		});
		(end)
		
Note:
		Don't forget to insert "<script language="Javascript" type="text/javascript" src="js/mootools.js"></script>" 
		and "<script language="Javascript" type="text/javascript" src="http://www.google.com/jsapi?key=ABCDE"></script>" into the head page before this js file.
*/
var GoogleMap = new Class({
	
	Implements : Options,

	options: {
		'map_container' : 'map',
		'street_container' : 'street',
		'data' : 'DB',
		'auto_center' : false,
		'streetview' : true,
		'cache' : false,
		'customized_icon' : false,
		'icon_image' : '/img/googlemap/gmarker_esl.png',
		'icon_shadow' : '/img/googlemap/gmarker_esl_shadow.png',
		'xmlPath' : '/xml/towns.xml',
		'server' : 'eslagency'
	},
	
	initialize : function(options) {
		this.setOptions(options);
		this._createMap();
	},
	
	//Function to create google map instance
	_createMap : function() {
		if (GBrowserIsCompatible()) {
	        
		    this.map = new GMap2($(this.options.map_container));
		    
		    this.map.addControl(new GMapTypeControl());		
		    this.map.addControl(new GLargeMapControl3D());	
		    
			if(this.options.customized_icon) this._createIcon();
			this._getData(this.options.data);
		}
	},
	
	//Function to get data form the DB or XML
	_getData : function(method) {
		if(method == 'DB'){
			var yMax = xMax = -1000;
			var yMin = xMin = 1000;
			// for each point from the coordinates array
			$A(coordinates).each(function(spot){
				if(spot.coord_long != 0 && spot.coord_lat != 0){
					// add marker
					this.map.addOverlay(this._createMarker(new GLatLng(spot.coord_lat, spot.coord_long), spot.text));
					// if auto_center then store extrem coordinates
					if(this.options.auto_center){
						if (spot.coord_long > xMax) xMax = spot.coord_long.toFloat();
						if (spot.coord_long < xMin) xMin = spot.coord_long.toFloat();
						if (spot.coord_lat > yMax) yMax = spot.coord_lat.toFloat();
						if (spot.coord_lat < yMin) yMin = spot.coord_lat.toFloat();
					}
				}
			},this);
			
			if(this.options.auto_center)
				this._setCenter(xMax,yMax,xMin,yMin);
			else this.map.setCenter(new GLatLng(coordinates[0].coord_lat, coordinates[0].coord_long), coordinates[0].zoom);
			
			if(this.options.streetview) this.showStreetView(coordinates[0].streetlat, coordinates[0].streetlong, coordinates[0].streetyaw, coordinates[0].streetpitch, coordinates[0].streetzoom);
		}
		// XML for our use
		else if(method == 'XML') {
			var streetlat ;
			var streetlong ; 
			var streetyaw ;
			var streetpitch ;
			var streetzoom ;
			
			//load xml file code for IE
			if (window.ActiveXObject) {
				var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
						
				xmlDoc.async = false;
				xmlDoc.load(this.options.xmlPath);
				
				//if file is loaded
				if (xmlDoc.getElementsByTagName('town')[0]) {
					
					//for each town from XML
					for(i=0; i<xmlDoc.getElementsByTagName('town').length; i++){
						//get google map coordinates
						var point = new GLatLng(
						xmlDoc.getElementsByTagName('town')[i].getElementsByTagName('map')[0].getElementsByTagName('lat')[0].text, 
						xmlDoc.getElementsByTagName('town')[i].getElementsByTagName('map')[0].getElementsByTagName('long')[0].text
						);
						if (xmlDoc.getElementsByTagName('town')[i].getAttribute('name') == center) {
							//get street view coordinates
							streetlat = xmlDoc.getElementsByTagName('town')[i].getElementsByTagName('street')[0].getElementsByTagName('lat')[0].text;
							streetlong = xmlDoc.getElementsByTagName('town')[i].getElementsByTagName('street')[0].getElementsByTagName('long')[0].text; 
							streetyaw = xmlDoc.getElementsByTagName('town')[i].getElementsByTagName('street')[0].getElementsByTagName('yaw')[0].text;
							streetpitch = xmlDoc.getElementsByTagName('town')[i].getElementsByTagName('street')[0].getElementsByTagName('pitch')[0].text;
							streetzoom = xmlDoc.getElementsByTagName('town')[i].getElementsByTagName('street')[0].getElementsByTagName('zoom')[0].text;
							
							//google map center on
							this.map.setCenter(point,15);
						}
						
						//create marker with a link on the its page
						this.map.addOverlay(
							this._createMarker(
								point, 
								"<a href='/floor/cs?server="+srv+"&lang="+defaultLanguage+"&item_categoryID="+
								xmlDoc.getElementsByTagName('town')[i].getElementsByTagName('link')[0].getAttribute('cid')+"'>"+officesLanguages.ouroffice+" "+
								officesLanguages[xmlDoc.getElementsByTagName('town')[i].getAttribute('name')]+"</a>",
								xmlDoc.getElementsByTagName('town')[i].getAttribute('la')
							)
						);
					}
					
					this.showStreetView(streetlat, streetlong, streetyaw, streetpitch, streetzoom);
					
				}
			}
			
			// code for Mozilla, Firefox, Opera, etc.
			else {
				new Request({
					url: this.options.xmlPath,
					onSuccess: function(responseTxt, responseXML){
						var coordinate;
						//for each town from XML 
						responseXML.getElements('town').each(function(town){
							//get google map coordinates
							var point = new GLatLng(town.getElement('map lat').get('text'),town.getElement('map long').get('text'));
							if(town.get('name') == center){
								//get street view coordinates
								streetlat = town.getElement('street lat').get('text');
								streetlong = town.getElement('street long').get('text'); 
								streetyaw = town.getElement('street yaw').get('text');
								streetpitch = town.getElement('street pitch').get('text');
								streetzoom = town.getElement('street zoom').get('text');
								
								//google map center on
								this.map.setCenter(point,15);
							}
							
							//get cid
							var cid = town.getElement(this.options.server).get('text');
							this.map.addOverlay(
								this._createMarker(
									point, 
									"<a href='/floor/cs?server="+srv+
									"&lang="+defaultLanguage+
									"&item_categoryID="+cid+"'>"+
									officesLanguages.ouroffice+" "+officesLanguages[town.get('name')]+"</a>",
									town.get('lang')
								)
							);
							
						}, this);
						
						this.showStreetView(streetlat, streetlong, streetyaw, streetpitch, streetzoom);
						
					}.bind(this)
				}).send();
			}
		}
	},
	
	//Function to create an customized icon
	_createIcon : function() {
		this.icon = new GIcon();
		this.icon.image = this.options.icon_image;
		this.icon.shadow = this.options.icon_shadow;
		this.icon.iconSize = new GSize(91, 46);
		this.icon.shadowSize = new GSize(113, 52);
		this.icon.iconAnchor = new GPoint(29, 46);
		this.icon.infoWindowAnchor = new GPoint(29, 46);
	},
	
	//Function to create a marker at the given point with the given number label
	_createMarker : function(point, text, lang) {
		var marker = new GMarker(point, this.icon);
		
		if(this.testLang(lang)) {
			GEvent.addListener(marker, "click", function() {
	        	marker.openInfoWindowHtml(text);
	        });
		}
		return marker;
	},
	
	//test the lang
	testLang : function(lang) {
		if(!lang) return true;
		if(defaultLanguage.contains(lang.split('_')[0]))
			return true;
		else
			return false;
	},
	
	//Function to calculate where center on
	_setCenter : function(xmax,ymax,xmin,ymin) {
		var mybounds = new GLatLngBounds(new GLatLng(ymin, xmin), new GLatLng(ymax, xmax));
		var x = (xmin.toFloat()+(xmax-xmin)/2);
		var y = (ymin.toFloat()+(ymax-ymin)/2);
		var zoom = this.map.getBoundsZoomLevel(mybounds)-1;
		this.map.setCenter(new GLatLng(y,x),zoom);
	},
	
	//Function for the street view
	showStreetView : function(streetlat, streetlong, streetyaw, streetpitch, streetzoom) {	
		if (streetlat != 0 && streetlong != 0) {
            var options = {
                latlng: new GLatLng(streetlat, streetlong),
                pov: {
                    yaw: streetyaw.toInt(),
                    pitch: streetpitch.toInt(),
                    zoom: streetzoom.toInt()
                }
            };
            
            this.streetView = new GStreetviewPanorama($(this.options.street_container), options);
            
            GEvent.addListener(this.streetView, "error", this._manageError.bind(this));
            
        }
        else {
            $(this.options.street_container).destroy();
        }
		
		//add a cache
		if(this.options.cache) eval(this.options.cache);
			
	},
	
	//Function to manage street view errors
	_manageError : function(error){
		if(error == 600) {
			//switch pano to black
			this.streetView.remove();
			$(this.options.street_container).destroy();
		} else {
			//
			alert('you need the Flash pluggin to see the street view');
		}
	}

});

