﻿/**
 * @author Andrés Gustavo Soto Vidal
 * @email a.gustavo.soto@gmail.com
 */
var ACCESSIA_LIVEMAPS_KEY = "AorcS9P5PwWKEaYyvehEGptrxwWODT2DiCURPqMytxoXI0_mufJsvci_zcR36S1q";


Ext.namespace('Ext.ux.panel');
 
/**
 * @class Ext.ux.panel.LiveMapPanel
 * @extends Ext.Panel
 * <p>A simple component that adds Live maps functionality to any panel or panel based component
 * <p>Sample usage:</p>
 */
Ext.ux.LiveMapPanel = Ext.extend(Ext.Panel, {
    /**
     * @cfg {Boolean} border
     * Defaults to <tt>false</tt>.  See {@link Ext.Panel}.<code>{@link Ext.Panel#border border}</code>.
     */
    border: false,

    /**
     * @cfg {Array} respErrors
     * An array of msg/code pairs.
     */
    respErrors: [],
    /**
     * @cfg {String} respErrorTitle
     * Defaults to <tt>'Error'</tt>.
     */
    respErrorTitle : 'Error',

    /**
     * @cfg {String} livemapType
     */
    livemapType : 'map',
    /**
     * @cfg {Object} setCenter
	setCenter: {
		geoCodeAddr: '4 Yawkey Way, Boston, MA, 02215-3409, USA',
		marker: {title: 'Fenway Park'}
	},
	setCenter: {
		lat: 42.345573,
		lng: -71.098326
	}
    /**
     * @cfg {Number} zoomLevel
     * The zoom level to initialize the map at, generally between 1 (whole planet) and 40 (street).
     * Also used as the zoom level for panoramas, zero specifies no zoom at all.
     * Defaults to <tt>3</tt>.
     */
    zoomLevel: 3,
    /**
     * @cfg {Number} yaw
     * The Yaw, or rotational direction of the users perspective in degrees. Only applies to livemap birdview.
     * Defaults to <tt>180</tt>.
     */
    yaw: 180,
    /**
     * @cfg {Array} livemapConfOpts
     */
    /**
     * @cfg {Array} livemapControls
     */
    /**
     * @cfg {Array} markers
     * Markers may be added to the map. Instead of specifying <code>lat</code>/<code>lng</code>,
	 */
    mapDefined: false,
    // private
    mapDefinedLiveMap: false,
	//private
	resizeChapuza : false,
    // private
    initComponent : function(){
        
        this.addEvents(
            /**
             * @event mapready
             * Fires when the map is ready for interaction
             * @param {LiveMapPanel} this
             * @param {LiveMap} map
             */
            'mapready'
        );
        Ext.ux.GMapPanel.superclass.initComponent.call(this);        

    },
    // private
    afterRender : function(){
		if (typeof(VEMap)=='function'){
	        var wh = this.ownerCt.getSize();
	        Ext.applyIf(this, wh);
	        
	        Ext.ux.GMapPanel.superclass.afterRender.call(this);
			$('#'+this.body.dom.id).append('<div id="livemap" style=" width:100px; height:100px; display:block; border:2px solid #000000; overflow:hidden; background:#000000;"></div>');
			
			this.livemap = new VEMap('livemap');
			this.livemap.SetCredentials(ACCESSIA_LIVEMAPS_KEY);
			if (typeof this.initLoadOpts != 'undefined') this.livemap.LoadMap(
				(( typeof this.initLoadOpts.center != 'undefined') ? new VELatLong(this.initLoadOpts.center.lat, this.initLoadOpts.center.lng) : null ),
				(( typeof this.initLoadOpts.zoom != 'undefined') ? this.initLoadOpts.zoom : 14 ),
				(( typeof this.initLoadOpts.mapStyle != 'undefined') ? VEMapStyle[this.initLoadOpts.mapStyle] : null ),
				(( typeof this.initLoadOpts.fixed != 'undefined') ? this.initLoadOpts.fixed : null ),
				null, // mode 2D 3D
				null, // show Switch (mode switch)
				(( typeof this.initLoadOpts.tileBuffer != 'undefined') ? this.initLoadOpts.tileBuffer : null ),
				null // Extra options
			);
			else this.livemap.LoadMap();
			this.mapDefined = true;
			this.mapDefinedLiveMap = true;
			
	        this.onMapReady();
		}
		else{
			this.livemap = null;
			$('#'+this.body.dom.id).html('<p>No ha sido posible cargar el mapa de vista aérea; rogamos nos disculpen por las molestias que esto les pueda ocasionar.</p>');
		} 
    },
    // private
    onMapReady : function(){
		/* Este set size arregla los problemas de los tab panel cuando no saben el alto inicialmente */
        //this.setSize(this.ownerCt.getWidth(), this.ownerCt.getHeight());
		/*
		if (typeof this.center === 'object') {
			console.log('['+this.center.lat+','+this.center.lng+','+( (typeof this.zoom != 'undefined') ? this.zoom : 3 )+']');
			this.getMap().SetCenterAndZoom(new VELatLong(this.center.lat, this.center.lng), ( (typeof this.zoom != 'undefined') ? this.zoom : 3 ));
			console.log('center changed');
		}*/
		
        this.addOptions();
        
        this.fireEvent('mapready', this, this.getMap());
    },
    // private
    onResize : function(w, h){
        Ext.ux.LiveMapPanel.superclass.onResize.call(this, w, h);
		
        $("#livemap").width(w).height(h);
		// A ver si con esto se arregla el tamaño del mapa
		if (typeof this.livemap != 'undefined' && this.livemap != null) {
			this.livemap.LoadMap(
				this.livemap.GetCenter(),
				this.livemap.GetZoomLevel(),
				this.livemap.GetMapStyle()
			);
		}
    },
    // private
    setSize : function(width, height, animate){
		if (typeof width != 'object'){
			Ext.ux.LiveMapPanel.superclass.setSize.call(this, width, height, animate);
			$("#livemap").width(width).height(height);
		}
		else{
			Ext.ux.LiveMapPanel.superclass.setSize.call(this, width.width, width.height, animate);
			$("#livemap").width(width.width).height(width.height);
		}
		if (typeof this.livemap != 'undefined' && this.livemap != null) {
			this.livemap.LoadMap(
				this.livemap.GetCenter(),
				this.livemap.GetZoomLevel(),
				this.livemap.GetMapStyle()
			);
		}
    },
    /**
     * Returns the current google map which can be used to call Google Maps API specific handlers.
     * @return {GMap} this
     */
    getMap : function(){
        
        return this.livemap;
        
    },
    // private
    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);
        }        
        
    },
    /**
     * Adds a GMap option to the map.
     * @param {String} mo a string representation of the option to be instantiated.
     */
    addOption : function(mo){
        
        var mof = this.getMap()[mo];
        if (typeof mof === 'function') {
            this.getMap()[mo]();
        }    
        
    },
	
	/**
	 * cambiarDestino
	 */
	cambiarDestino : function(o){
		if (typeof(this.getMap()) != 'undefined' && this.getMap()!=null){
			//this.livemap = new VEMap('livemap');
			SpaceNeedle = new VELatLong(o.lat, o.lng); 
			this.livemap.LoadMap(SpaceNeedle, 14);
			this.livemap.AttachEvent("onobliqueenter", OnObliqueEnterHandler);		
		}
	},
	/**
	 * ObliqueHandler
	 */
	onObliqueEnterHandler : function(){
		if (typeof(this.getMap()!='undefined' && this.getMap()!=null)){
			if(this.getMap().IsBirdseyeAvailable()){
			   this.getMap().SetBirdseyeScene(this.getMap().GetCenter());
			}else{
				alert("esta zona no tiene birdview");
			}
		}
	}
});



Ext.reg('livemappanel',Ext.ux.LiveMapPanel); 

function OnObliqueEnterHandler(){
	var map = (Ext.getCmp('livemappanel')).getMap();
	if (typeof(map)!='undefined' && map != null){
		if(map.IsBirdseyeAvailable()){
		   map.SetBirdseyeScene(map.GetCenter());
		   
		}else{
			alert("esta zona no tiene birdview");
		}
	}
}
