/**
 * @author Shea Frederick
 */

Ext.namespace('Ext.ux');
 
/**
 *
 * @class GMapPanel
 * @extends Ext.Panel
 */
 
 
 /* Bouton full screen */
 
function FullScreenControl() {
}
FullScreenControl.prototype = new GControl();

var full = false;

FullScreenControl.prototype.initialize = function(map) {
  var container = document.createElement('div');
  var switchDiv = document.createElement('div');
  this.setButtonStyle_(switchDiv);
  container.appendChild(switchDiv);
  switchDiv.appendChild(document.createTextNode('Plein écran'));
  GEvent.addDomListener(switchDiv, 'click', function() {
	  var divMap = document.getElementById('mobi-mt-full-map-center-panel');	
	  var centre = map.getCenter();
		if (full == false) {
			classesMap = divMap.className;
			var divDestFull = document.body;
			
			document.getElementById('container').style.display = 'none';
			document.getElementById('footer').style.display = 'none';
			bgBody = document.body.style.background;
			document.body.style.background = 'none';
			
			divMap.parentNode.removeChild(divMap);	
			divDestFull.appendChild(divMap);
			divMap.className += ' mobi-mt-full-map-center-panel-fullscreen';	
			
			switchDiv.removeChild(switchDiv.firstChild);
			switchDiv.appendChild(document.createTextNode('Revenir à la page'));
			full = true;
		}				
		else {
			var divDestInt = document.getElementById('mobi-mt-full-map');	
			divMap.parentNode.removeChild(divMap);	
			divDestInt.insertBefore(divMap, document.getElementById('mobi-mt-full-map-west-panel'));
			divMap.className = classesMap;		
			
			document.body.style.background = bgBody;
			document.getElementById('container').style.display = 'block';
			document.getElementById('footer').style.display = 'block';
		
			switchDiv.removeChild(switchDiv.firstChild);
			switchDiv.appendChild(document.createTextNode('Plein écran'));
			full = false;
		}
		  map.checkResize();
		  map.setCenter(centre);
	});
	

	GEvent.addDomListener(document, 'keydown', function(e) {
		if (e.which == 27){
			if (full == true){
				var divMap = document.getElementById('mobi-mt-full-map-center-panel');	
				var centre = map.getCenter();
				var divDestInt = document.getElementById('mobi-mt-full-map');	
				divMap.parentNode.removeChild(divMap);	
				divDestInt.insertBefore(divMap, document.getElementById('mobi-mt-full-map-west-panel'));
				divMap.className = classesMap;		
				
				document.body.style.background = bgBody;
				document.getElementById('container').style.display = 'block';
				document.getElementById('footer').style.display = 'block';
			
				switchDiv.removeChild(switchDiv.firstChild);
				switchDiv.appendChild(document.createTextNode('Plein écran'));
				full = false;		
				map.checkResize();
			  map.setCenter(centre);			
			}
		}		  
	});

  map.getContainer().appendChild(container);
  
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
FullScreenControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 40));
}

FullScreenControl.prototype.setButtonStyle_ = function(button) {
  button.style.color = "#000000";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "2px outset black";
  button.style.padding = "0px";
  button.style.textAlign = "center";
  button.style.width = "5em";
  button.style.cursor = "pointer";
}

 /* Fin Bouton full screen */
 

var lang_no_directions = "La carte ne peut pas tracer l'itinéraire."
 
Ext.ux.GMapPanel = Ext.extend(Ext.Panel, {
    initComponent : function(){
        
        var defConfig = {
        	plain: true,
        	zoomLevel: 3,
        	yaw: 180,
        	pitch: 0,
        	zoom: 0,
        	gmapType: 'map',
            border: false
        }
        
        Ext.applyIf(this,defConfig);
        
		Ext.ux.GMapPanel.superclass.initComponent.call(this);        

    },
    afterRender : function(){
        
        var wh = this.ownerCt.getSize();
        Ext.applyIf(this, wh);
        
		Ext.ux.GMapPanel.superclass.afterRender.call(this);	
        
		if (this.gmapType === 'map'){
			this.gmap = new GMap2(this.body.dom);
		}
		
		if (this.gmapType === 'panorama'){
			this.gmap = new GStreetviewPanorama(this.body.dom);
		}
		//Predy
		this.gmap.addMapType(G_SATELLITE_3D_MAP);
		/*
		if (typeof this.addControl === 'object' && this.gmapType === 'map') {
			this.gmap.addControl(this.addControl);
		}
		*/
		if (typeof this.addControl === 'object' && this.gmapType === 'map') {
			var i = 0;
			while (i < this.addControl.length){
				this.gmap.addControl(this.addControl[i]);
				i++;
			}
			this.gmap.addControl(new FullScreenControl());
		}
		
		if (typeof this.setCenter === 'object') {
			if (typeof this.setCenter.geoCodeAddr === 'string'){
				this.geoCodeLookup(this.setCenter.geoCodeAddr);
			}else{
				if (this.gmapType === 'map'){
					var point = new GLatLng(this.setCenter.lat,this.setCenter['long']);
					this.gmap.setCenter(point, this.zoomLevel);	
				}
				if (typeof this.setCenter.marker === 'object' && typeof point === 'object'){
					this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear);
				}
			}
			if (this.gmapType === 'panorama'){
				this.gmap.setLocationAndPOV(new GLatLng(this.setCenter.lat,this.setCenter['long']), {yaw: this.yaw, pitch: this.pitch, zoom: this.zoom});
			}
		}
		
        var dt = new Ext.util.DelayedTask();
        dt.delay(300, function(){
            this.addMarkers(this.markers);
        }, this);

	},
    onResize : function(w, h){
        if (typeof this.gmap == 'object') {
            this.gmap.checkResize();
        }

		Ext.ux.GMapPanel.superclass.onResize.call(this, w, h);

    },
    setSize : function(width, height, animate){
        
        if (typeof this.gmap == 'object') {
            this.gmap.checkResize();
        }
		
		Ext.ux.GMapPanel.superclass.setSize.call(this, width, height, animate);
        
    },
	getMap: function(){
		
		return this.gmap;
		
	},
	addMarkers: function(markers) {
		
		if (Ext.isArray(markers)){
			for (var i = 0; i < markers.length; i++) {
				var mkr_point = new GLatLng(markers[i].lat,markers[i]['long']);
				this.addMarker(mkr_point,markers[i].marker,false,markers[i].setCenter);
			}
		}
		
	},
	addMarker: function(point, marker, clear, center){
		
		Ext.applyIf(marker,G_DEFAULT_ICON);

		if (clear === true){
			this.gmap.clearOverlays();
		}
        if (center === true) {
            this.gmap.setCenter(point, this.zoomLevel);
        }

		var mark = new GMarker(point,marker);
		//Predy
		GEvent.addListener(mark, "mouseover", function() {
			// console.log(mark);
			mark.openInfoWindowHtml(mark.ha.infowindowhtml);
		});
   		this.gmap.addOverlay(mark);
	},
	geoCodeLookup : function(addr) {
		
		this.geocoder = new GClientGeocoder();
		this.geocoder.getLocations(addr, this.addAddressToMap.createDelegate(this));
		
	},
    addAddressToMap : function(response) {
		
		if (!response || response.Status.code != 200) {
			Ext.MessageBox.Ext.Msg.alert('ERR', 'Error', 'Code '+response.Status.code+' Error Returned');
  		} else {
    		place = response.Placemark[0];
			addressinfo = place.AddressDetails;
			accuracy = addressinfo.Accuracy;
			if (accuracy === 0) {
				Ext.MessageBox.Ext.Msg.alert('ERR', 'Unable to Locate Address', 'Unable to Locate the Address you provided');
			}else{
				if (accuracy < 7) {
					Ext.MessageBox.Ext.Msg.alert('ERR', 'Address Accuracy', 'The address provided has a low accuracy.<br><br>Level '+accuracy+' Accuracy (8 = Exact Match, 1 = Vague Match)');
				}else{
	        		point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
					if (typeof this.setCenter.marker === 'object' && typeof point === 'object'){
						this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear,true);
					}
				}
			}
	  	}
		
	},
	//Predy
	initDirections : function(id) {
		this.directionsPanel = document.getElementById(id);
		//this.directions = new GDirections(this.gmap, this.directionsPanel);
		this.directions = new GDirections(null, this.directionsPanel);
	},
	clearDirections : function() {
		if (this.directions.getPolyline() != null && this.directions.getPolyline() !== undefined){
			this.gmap.removeOverlay(this.directions.getPolyline());
		}		
	},
	
	getDirections : function(fromAddress, toAddresses) {
		var me = this;
		var lang = 'fr';
		var to = '';
		var i = 0;
		while (i < toAddresses.length){
			to += " to: "+toAddresses[i];
			i++;
		}
		this.directions.load("from: "+fromAddress+to,
					{ "locale": lang, getPolyline: true });
		GEvent.addListener(this.directions, "load", function() {
			me.gmap.addOverlay(me.directions.getPolyline());
		});	
		GEvent.addListener(me.directions, "error", me.handleErrors(me.directions));
	},
	fixCenter : function(){
		if (typeof this.setCenter === 'object') {
			if (typeof this.setCenter.geoCodeAddr === 'string'){
				this.geoCodeLookup(this.setCenter.geoCodeAddr);
			}else{
				if (this.gmapType === 'map'){
					var point = new GLatLng(this.setCenter.lat,this.setCenter['long']);
					// console.log('lat: '+this.setCenter.lat);
					// console.log('long: '+this.setCenter['long']);
					this.gmap.setCenter(point, this.zoomLevel);	
				}
				if (typeof this.setCenter.marker === 'object' && typeof point === 'object'){
					this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear);
				}
			}
			if (this.gmapType === 'panorama'){
				this.gmap.setLocationAndPOV(new GLatLng(this.setCenter.lat,this.setCenter['long']), {yaw: this.yaw, pitch: this.pitch, zoom: this.zoom});
			}
		}
	},
	addGeoXML : function(kmlURL){
		// var gx = new GGeoXml("http://maps.cga.harvard.edu/kml/hospitals.kml");
		// var gx = new GGeoXml("http://peyrefitte3.mtourisme.mobi/fileadmin/ressources_mob/mt_map/import_obts.php?actionMobi=dkml&idLang=37&idObject=6479&pid=442");
		var gx = new GGeoXml(kmlURL);
		this.gmap.addOverlay(gx);
		
	},
	addTracing: function(tracing){
		var me = this;
		var points = Ext.util.JSON.decode(tracing);
		var i = 1; 
		while (i < points.length){
			var glatlng1 = new GLatLng(points[i-1]['y'],points[i-1]['x']);
			var glatlng2 = new GLatLng(points[i]['y'],points[i]['x']);
			var arr = new Array();
			arr.push(glatlng1);
			arr.push(glatlng2);
			var poly = new GPolyline(arr, "#000000", 2, 1);
			me.gmap.addOverlay(poly);
			++i;
		}
	},
	//<!> ExtJS has to be loaded
	handleErrors: function(directions){
		if (directions.getStatus() !== undefined){
			//if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
			//	Ext.Msg.alert('ERR', "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code);
			if (directions.getStatus().code == G_GEO_SERVER_ERROR){
				// Ext.Msg.alert('ERR', "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);
			}
			else if (directions.getStatus().code == G_GEO_MISSING_QUERY){
				// Ext.Msg.alert('ERR', "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);
			}
			//   else if (directions.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
			//     Ext.Msg.alert('ERR', "The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + directions.getStatus().code);

			else if (directions.getStatus().code == G_GEO_BAD_KEY){
				// Ext.Msg.alert('ERR', "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);
			}
			else if (directions.getStatus().code == G_GEO_BAD_REQUEST){
				// Ext.Msg.alert('ERR', "A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
			}
			//else Ext.Msg.alert('ERR', "An unknown error occurred.");
		}
	}

 
});

Ext.reg('gmappanel',Ext.ux.GMapPanel);
