/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

/**
 * @author Shea Frederick
 */
 
/*
 * SPOT Simple Viewer
 * 
 * contact@apem.asso.fr
 * http://www.apem.asso.fr
 * last update : 16/03/2009
 */

Ext.namespace('Ext.ux');
 
/**
 *
 * @class GMapPanel
 * @extends Ext.Panel
 */
Ext.ux.GMapPanel = Ext.extend(Ext.Panel, {
    initComponent : function(){
		
		/*// variable pour GDirections
		var directions1;
		var directions2;
		var directions3;*/
		
        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'){
			// update : default layers
			if (Ext.isArray(this.layersDefault) && this.layersDefault.length != 0) {
				this.gmap = new GMap2(this.body.dom,{mapTypes: this.layersDefault});
			}
			// end update
			else{
				this.gmap = new GMap2(this.body.dom);
			}
        }
        
        if (this.gmapType === 'panorama'){
            this.gmap = new GStreetviewPanorama(this.body.dom);
        }
        
        if (typeof this.addControl == 'object' && this.gmapType === 'map') {
            this.gmap.addControl(this.addControl);
        }
        
		// update : load method before calling setCenter
		GEvent.bind(this.gmap, 'load', this, function(){
            this.onMapReady();
        });
		// end update
		
        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.lng);
                    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.lng), {yaw: this.yaw, pitch: this.pitch, zoom: this.zoom});
            }
        }
		
		//fonction permettant de faire le choix entre le camping-car et la voiture - ne fonctionne pas
		this.addDirections();
		
		// add GDirections
		/*directions1 = new GDirections();
		directions2 = new GDirections(null, document.getElementById("dirnPanel"));
		directions3 = new GDirections();*/

		//kmlroute = new GGeoXml("http://www.sig-pyrenees.net/confede/rdcv2/data/kml/rdc_final8.kmz");
		
		/*waypoints1 = ['43.37133946471833,-1.786199424151103','43.30640835943079,-1.499076411761766','43.1767129164744,-1.400008192991724','43.01850769417413,-0.9546240660765704','43.09667503612968,-0.6709821245432646','43.04942524366999,-0.6684046842354419'];
		waypoints2 = ['43.04942524366999,-0.6684046842354419','43.07483274230459,-0.5474003391361182','43.04639172975173,-0.4264221365740195'];
		waypoints3 = ['43.04639172975173,-0.4264221365740195','42.89600320701081,0.06275518882999709','42.93613119116377,0.344458830078247','42.81204641931292,0.3171932017693213','42.80864892176351,0.4014592514103899','42.78266944405227,0.691626462645949','42.92157351218037,0.7225069347492918','42.85966134965857,1.114966489487106','42.80653242572469,1.270952429877172','42.83369897576876,1.607617846181753','42.8083378278486,1.940661238284946','42.87720518105333,2.183725167013251','42.50827242293062,2.046062352039626','42.50143754581259,2.041923781243682','42.48972049657861,2.038914142388149','42.56568325078333,2.645088946400946','42.47642116740757,2.673947064096012','42.49004863516548,2.805710149355671','42.54381775034842,3.025383127753596','42.52445429642262,3.082255291569491','42.44024350928351,3.175393734259213'];
		
		
		directions1.loadFromWaypoints(waypoints1, {getPolyline: true});
		directions2.loadFromWaypoints(waypoints2, {getPolyline: true, travelMode: G_TRAVEL_MODE_WALKING});
		directions3.loadFromWaypoints(waypoints3, {getPolyline: true});
	
		
		GEvent.addListener(directions1,"load",handleDirectionsLoad1);
		GEvent.addListener(directions2,"load",handleDirectionsLoad2);
		GEvent.addListener(directions3,"load",handleDirectionsLoad3);*/
		
		//Ajout du KMZ de la route des cols
		//this.getMap().addOverlay(kmlroute);
		//Ext.getCmp('carto').addKMLOverlay("http://www.sig-pyrenees.net/confede/rdcv2/data/kml/rdc_final8.kmz");
		
		// listener on map - zoomend and moveend - reload map
		
		var extendPercent = this.extendPercent / 100;
		var mapTemp = this.getMap();
		
		GEvent.addListener(mapTemp, 'zoomend', function() {
		
			var centerLat = mapTemp.getCenter().lat();
			var centerLng = mapTemp.getCenter().lng();
			var north = mapTemp.getBounds().getNorthEast().lat();
			var south = mapTemp.getBounds().getSouthWest().lat();
			var west = mapTemp.getBounds().getNorthEast().lng();
			var east = mapTemp.getBounds().getSouthWest().lng();

			Ext.getCmp('carto').addTreeLayers(Ext.getCmp('tree-panel').getChecked());
		});
		
		var centerLat = this.getMap().getCenter().lat();
		var centerLng = this.getMap().getCenter().lng();
		
		var north = this.getMap().getBounds().getNorthEast().lat();
		var south = this.getMap().getBounds().getSouthWest().lat();
		var west = this.getMap().getBounds().getNorthEast().lng();
		var east = this.getMap().getBounds().getSouthWest().lng();
		
		/*function handleDirectionsLoad1(){
			mapTemp.addOverlay(directions1.getPolyline());
		}
		function handleDirectionsLoad2(){
			mapTemp.addOverlay(directions2.getPolyline());
		}
		function handleDirectionsLoad3(){
			mapTemp.addOverlay(directions3.getPolyline());
		}*/
		
		// init progress bar -> doesn't work, it may be because the div is created as a map container ?
		function waiting(){};
		waiting.prototype = new GControl();
		waiting.prototype.initialize = function(mapTemp) {
			var waiting_div = document.createElement("div");
			var progress_div = document.createElement("div");
			progress_div.id = "id_progress_div";
			progress_div.innerHTML = "";

			mapTemp.getContainer(mapTemp).appendChild(waiting_div);
			waiting_div.appendChild(progress_div);
   
			mapTemp.getContainer().appendChild(waiting_div);
			return waiting_div;
			
		}
		
		var centre = new GSize((mapTemp.getSize().width / 2) - 100, (mapTemp.getSize().height / 2) - 35);
		waiting.prototype.getDefaultPosition = function() {
			return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, centre);
		}
		var waitingControl = new waiting();
		this.getMap().addControl(waitingControl);
		document.getElementById("id_progress_div").style.visibility="visible";
		// end of init bar
		

    },
    onMapReady : function(){
        this.addMarkers(this.markers);
        this.addMapControls();
        this.addOptions();
		
    },
    onResize : function(w, h){

        if (typeof this.getMap() == 'object') {
            this.gmap.checkResize();
        }
        
        Ext.ux.GMapPanel.superclass.onResize.call(this, w, h);

    },
    setSize : function(width, height, animate){
        
        if (typeof this.getMap() == 'object') {
            this.gmap.checkResize();
        }
        
        Ext.ux.GMapPanel.superclass.setSize.call(this, width, height, animate);
        
    },
    getMap : function(){
        
        return this.gmap;
        
    },
    getCenter : function(){
        
        return this.getMap().getCenter();
        
    },
    getCenterLatLng : function(){
        
        var ll = this.getCenter();
        return {lat: ll.lat(), lng: ll.lng()};
        
    },
    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].lng);
                this.addMarker(mkr_point,markers[i].marker,false,markers[i].setCenter, markers[i].listeners);
            }
        }
        
    },
    addMarker : function(point, marker, clear, center, listeners){
        
        Ext.applyIf(marker,G_DEFAULT_ICON);

        if (clear === true){
            this.getMap().clearOverlays();
        }
        if (center === true) {
            this.getMap().setCenter(point, this.zoomLevel);
        }

        var mark = new GMarker(point,marker);
        if (typeof listeners === 'object'){
            for (evt in listeners) {
                GEvent.bind(mark, evt, this, listeners[evt]);
            }
        }
        this.getMap().addOverlay(mark);

    },
    addMapControls : function(){
        
        if (this.gmapType === 'map') {
            if (Ext.isArray(this.mapControls)) {
                for(i=0;i<this.mapControls.length;i++){
                    this.addMapControl(this.mapControls[i]);
                }
            }else if(typeof this.mapControls === 'string'){
                this.addMapControl(this.mapControls);
            }else if(typeof this.mapControls === 'object'){
                this.getMap().addControl(this.mapControls);
            }
        }
        
    },
    addMapControl : function(mc){
        
        var mcf = window[mc];
        if (typeof mcf === 'function') {
            this.getMap().addControl(new mcf());
        }    
        
    },
    addOptions : function(){
        
        if (Ext.isArray(this.mapConfOpts)) {
            var mc;
            for(i=0;i<this.mapConfOpts.length;i++){
                this.addOption(this.mapConfOpts[i]);
            }
        }else if(typeof this.mapConfOpts === 'string'){
            this.addOption(this.mapConfOpts);
        }        
        
    },
    addOption : function(mc){
        
        var mcf = this.getMap()[mc];
        if (typeof mcf === 'function') {
            this.getMap()[mc]();
        }    
        
    },
    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.alert('Error', 'Code '+response.Status.code+' Error Returned');
        }else{
            place = response.Placemark[0];
            addressinfo = place.AddressDetails;
            accuracy = addressinfo.Accuracy;
            if (accuracy === 0) {
                Ext.MessageBox.alert('Unable to Locate Address', 'Unable to Locate the Address you provided');
            }else{
                if (accuracy < 7) {
                    Ext.MessageBox.alert('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, this.setCenter.listeners);
                    }
                }
            }
        }
        
    },
	
	// update SPOT Simple Viewer
	addTreeLayers : function(nodeArray){
		
		if (nodeArray.length == 0){
			this.getMap().clearOverlays();
			addStartStopPoi();
			/*this.getMap().addOverlay(directions1.getPolyline());
			this.getMap().addOverlay(directions2.getPolyline());
			this.getMap().addOverlay(directions3.getPolyline());*/
			//this.getMap().addOverlay(kmlroute);
			displayRoute();
		}
		else{
			this.getMap().clearOverlays();
			addStartStopPoi();
			/*this.getMap().addOverlay(directions1.getPolyline());
			this.getMap().addOverlay(directions2.getPolyline());
			this.getMap().addOverlay(directions3.getPolyline());*/
			//this.getMap().addOverlay(kmlroute);
			displayRoute();
			var listType = new Array();
			for(i=0;i<nodeArray.length;i++){
				var temp = nodeArray[i].id;
				listType.push(temp);
			}
			
			// url php file to get markers
			var urlstr = "./function/getObj.php?maxY="+this.getMap().getBounds().getNorthEast().lat()+"&minY="+this.getMap().getBounds().getSouthWest().lat()+"&maxX="+this.getMap().getBounds().getNorthEast().lng()+"&minX="+this.getMap().getBounds().getSouthWest().lng()+"&zoomLevel="+this.getMap().getZoom()+"&listType="+listType;
			GDownloadUrl(urlstr, function(data, responseCode) {
				if (responseCode == 200) {
					//alert(data);
					var xmlDoc = GXml.parse(data);
					var markers = xmlDoc.documentElement.getElementsByTagName("marker");
					
					// display loading.gif -> doesn't work
					document.getElementById("id_progress_div").style.visibility="visible";
					document.getElementById("id_progress_div").innerHTML = '<img src="../images/loading.gif">';
					
					// display markers on map
					for (var i=0;i<markers.length;i++){
						
						if (markers[i].getAttribute("url_kml") == ''){
						
							// latitude and longitude marker
							var lat_marker = parseFloat(markers[i].getAttribute("lat_object"));
							var lng_marker = parseFloat(markers[i].getAttribute("lng_object"));
							
							// GIcon definition
							var icon = new GIcon();
							icon.iconSize = new GSize(24.0, 38.0);
							icon.shadowSize = new GSize(44.0, 38.0);
							icon.iconAnchor = new GPoint(12.0, 38);
							icon.infoWindowAnchor = new GPoint(12.0, 19.0);
							
							if (markers[i].getAttribute("cluster") == 0){
								// image and shadow icon
								icon.image = "./icon/marker/"+markers[i].getAttribute("id_type")+".png";
								icon.shadow = "./icon/marker/shadow.png";
								
								var point = new GLatLng(lat_marker,lng_marker);
								var mark = new GMarker(point,{icon: icon,title: markers[i].getAttribute("title_object")});
								var infowindow = markers[i].getAttribute("title_object");
								Ext.getCmp('carto').addClusteringMarker(mark,infowindow,false);
								
							}
							else{
								// image and shadow icon
								icon.image = "./icon/marker/cluster_marker.png";
								icon.shadow = "./icon/marker/shadow.png";
								
								var point = new GLatLng(lat_marker,lng_marker);
								var title = markers[i].getAttribute("nb_marker")+' items - zoom to view (click on marker)';
								var mark = new GMarker(point,{icon: icon,title: title});
								var infowindow = '';
								Ext.getCmp('carto').addClusteringMarker(mark,infowindow,true);
								
							}
							
							// display loading.gif
							Ext.getCmp('carto').progressBar(i,markers.length);
						}
						else{
							Ext.getCmp('carto').addKMLOverlay(markers[i].getAttribute('url_kml'));
							
						}
						
						// display loading.gif -> doesn't work
						Ext.getCmp('carto').progressBar(i,markers.length);
						
					}
					
					// hide loading.gif -> doesn't work
					Ext.getCmp('carto').progressBar(markers.length,markers.length);
					
				}

			});
			
		}
		
	},
	addClusteringMarker : function(marker,infowindow,bool_cluster){
		if (!bool_cluster){
			GEvent.addListener(marker, 'click', function() {
				marker.openInfoWindowHtml(infowindow);
			});
			this.getMap().addOverlay(marker);
		}
		else{
			var mapTemp = this.getMap();
			GEvent.addListener(marker, 'click', function() {
				mapTemp.setCenter(marker.getLatLng(),mapTemp.getZoom()+1);
			});
			this.getMap().addOverlay(marker);
		}
		
	},
	addDirections : function(){
		sel = document.getElementById('mode_transport');
		transport = sel.options[sel.selectedIndex].value;
		/*if (transport == 'camping')
			alert('camping-car');
		else
			alert('auto');
		*/
	},
	// doesn't work
	progressBar : function(progress,nb_object){
		if (progress != nb_object){
			document.getElementById("id_progress_div").style.visibility="visible";
			document.getElementById("id_progress_div").style.width = "32px";
			document.getElementById("id_progress_div").innerHTML='<img src="../images/loading.gif">';
		}
		else{
			document.getElementById("id_progress_div").style.visibility="hidden";
			//setTimeout('document.getElementById("id_progress_div").style.visibility="hidden";',200);
		}
	},
	addKMLOverlay : function(kmlfile){
		if (typeof kmlfile === 'string' && kmlfile !== ''){
			var geoXml = new GGeoXml(kmlfile);
			this.getMap().addOverlay(geoXml);
		}
		
	}
	
	// end update SPOT Simple Viewer
 
});

Ext.reg('gmappanel',Ext.ux.GMapPanel); 
