﻿/*
 * TODO:
 * 	1/ Cambiar de lugar la carga de los componentes combobox de forma que hagan render antes que el viewport.
 * 	2/ Una vez visto eso y funcione ok, hay que comprobar que "afterrender" del viewport es tiempo suficiente
 * 	para que se hayan cargado todos los componentes y existan todos los elementos e ids requeridos.
 * 	3/ Cargar myAccessia en el callback de afterrender a ser posible.
 */

var debug = false;
if(debug){
    if(typeof(console)=="undefined"){
        try{
            window['console'] = { log: function(t){ alert(t); } }
        }catch(e){}
    }
}else{
    try{
          window['console'] = { log : function(){} }
        }catch(e){}
}


/*
	DEFINICIÓN DEL ALERT DE EXT
*/
var old_alert = alert;
try {
	alert = function(text){
		Ext.Msg.alert("", text);
	}
}catch(e){

}


var myAccessia = null;

var _directoryWidth = 250;
var _directoryHeight = 600;
var _SYMPOSIUM = "http://sym2.posium.com/";
var _BASE_EVENT_SEARCH = "search/doAccessiaSearch/<PARTNER>/EMPTY_PARAMETER/EMPTY_PARAMETER/EMPTY_PARAMETER/EMPTY_PARAMETER/<DATE>/EMPTY_PARAMETER.html";
var fixedMarkers = [];

var fc = 0;
var flashmapJSON = {
		id : "flashmappanel",
		border : false,
		url : '/assets/plano_entrada1.swf',
		swliveconnect : true
	}

var lastplace = null;

function load_place_from_url(){
	try{
		var URLHASH = window.location.hash.replace(/#/g, '');
		URLHASH = URLHASH.replace(/_/g, ' ');
		
		if ($.browser.mozilla){
			URLHASH = unescape(URLHASH);   // para firefox
		} else {
			URLHASH = unescape(decodeURIComponent(URLHASH));  // para los demas
		}

		//window.location.hash = URLHASH;
		//URLHASH = unscape(URLHASH);
		if (URLHASH!=''){
			$(Ext.getCmp("lugaresAccordion")).each(function(){
			    $(this.items.items).each(function(){
			        for(var i in this.nodeHash){
			            if(typeof(this.nodeHash[i].fullInfo)!="undefined" && this.nodeHash[i].fullInfo.name==URLHASH){
			                this.nodeHash[i].fireEvent('click', this.nodeHash[i]);
			                return false;
			            }
			        }
			    });
			});
		}
	}catch(e){
		setTimeout(function(){load_place_from_url() }, 1000);
	}
}

function do_my_homedrop(position, address){
	if (typeof(address) != 'undefined') {
		Ext.getCmp('comborutaobj').setRawValue(address);
		Ext.getCmp('comborutaobj').removeClass('x-form-empty-field');
	}else {
		myAccessia.Gmap._geocoder.getLocations(position, function(result){
			if (result.Status.code == 200) {
				if (typeof(result.Placemark) != 'undefined') {
					if (result.Placemark.length > 0) {
						Ext.getCmp('comborutaobj').setRawValue(result.Placemark[0].address);
						Ext.getCmp('comborutaobj').removeClass('x-form-empty-field');
					}
				}
			}
			else 
				Ext.getCmp('comborutaobj').setRawValue(' ?? ');
		});
	}
}
function MY_onHomeDrop(position, address){
	if (Ext.getCmp('comborutaobj')) do_my_homedrop(position, address);
	else setTimeout(function(){
		MY_onHomeDrop(position, address);
	}, 500);
	return false;
}


function pirulaTimeoutFlash(){doPlaceAction(lastplace);}

var directionsWindow = null;
var enVistaDeImpresion = false;
var vistaDireccionesSimplesHtml = "";
var _print_map_zoom = null;

	function mydirectionsload(){
		$(".ruta-btn-borrar").css("display", "block");
		if (!directionsWindow){
			directionsWindow = new Ext.Window({
				x : 0, 
				y : 230,
				
				layout : 'border',
				width : 300,
				height : 490,
				closeAction : 'hide',
				cls : 'noprint',
				ctCls : 'noprint',
				defaults : {
					cls : 'noprint'
				},
				items : [
					new Ext.Panel({
						region : 'center',
						layout : 'card',
						border : false,
						id : 'ventana_impresion',
						activeItem : 0,
						items : [
							new Ext.Panel({
								border : false,
								region : 'center',
								xtype: 'panel',
								id : 'dirwin',
								contentEl : 'GMAP_DIRECTIONS',
								autoScroll : true
							}),
							new Ext.Panel({
								border : false,
								id : 'printwin',
								contentEl : 'PRINT_DIRECTIONS'
							})
						]
					}),
					new Ext.Toolbar({
						region : 'north',
						height : 30,
						border : false,
						items : [{
							id : 'botonImprimirDirecciones',
							xtype: 'button',
							cls:'x-btn-text-icon',
							overCls:'x-btn-over',
							//icon: 'js/ext-3.0/resources/images/accessia-blue/directions/print.gif',
							iconCls : 'my_print_button',
							text: 'Vista de Impresión',
							handler: function(b, e){
								if (enVistaDeImpresion){
									this.setText('Vista de Impresión');
									enVistaDeImpresion = false;
									Ext.getCmp('ventana_impresion').getLayout().setActiveItem(0);
								}else{
									var button = this;
									_print_map_zoom = myAccessia.Gmap._map.getZoom();
									button.setIconClass('my_print_loading_button');
									button.setText('... Cargando la vista, espere por favor ... ');
									enVistaDeImpresion = true;
									Ext.getCmp('ventana_impresion').getLayout().setActiveItem(1);
									var url = myAccessia.Gmap.printWithGoogle({
										from : Ext.getCmp('comborutaobj').getValue(),
										zoom : _print_map_zoom
									});
									if ($("#PRINT_DIRECTIONS").html() === '') {
										$('#PRINT_DIRECTIONS').load(url, function(){
											button.setText('Direcciones simples');
											button.setIconClass('my_print_button');
											$("iframe", "#PRINT_DIRECTIONS").css("height", $("#PRINT_DIRECTIONS").parent().css("height"));
											$("iframe", "#PRINT_DIRECTIONS").css("width", $("#PRINT_DIRECTIONS").parent().css("width"));
										});
									}else{
										button.setText('Direcciones Simples');
										button.setIconClass('my_print_button');
										$("iframe", "#PRINT_DIRECTIONS").css("height", $("#PRINT_DIRECTIONS").parent().css("height"));
										$("iframe", "#PRINT_DIRECTIONS").css("width", $("#PRINT_DIRECTIONS").parent().css("width"));
									}
								}
							}
						}]
					})
					
				],
				maximizable : true
			});
			directionsWindow.addListener('resize', function(w, width, height){
				if (enVistaDeImpresion){
					$("iframe","#PRINT_DIRECTIONS").css("height", $("#PRINT_DIRECTIONS").parent().css("height"));
					$("iframe","#PRINT_DIRECTIONS").css("width", $("#PRINT_DIRECTIONS").parent().css("width"));
				}
			});
			directionsWindow.addListener('hide', function(w){
				enVistaDeImpresion = false;
				Ext.getCmp('ventana_impresion').getLayout().setActiveItem(0);
			});
		}else{
			Ext.getCmp('ventana_impresion').getLayout().setActiveItem(0);
			Ext.getCmp('botonImprimirDirecciones').setText('Vista de Impresión');
			$('#PRINT_DIRECTIONS').html('');
			enVistaDeImpresion = false;
		}
		
		if (lastplace) {
			directionsWindow.setTitle("Direcciones para:  "+Ext.getCmp('comborutaobj').getRawValue()+"    >>>   "+lastplace.name);
			Ext.getCmp('gmappanel').getMap().setCenter(new GLatLng(parseFloat(lastplace.lat), parseFloat(lastplace.lng)), 16);
		}
		else directionsWindow.setTitle("Direcciones para:  "+Ext.getCmp('comborutaobj').getRawValue()+"    >>>   Campus de Espinardo");
		directionsWindow.show(this);
		//Ext.getCmp('gmappanel').getMap().setCenter(parseFloat(lastplace.lat), parseFloat(lastplace.lng), 16);
	}


var street_window = null;
var panoramaObject = null;
function MY_onStreetDrop(latlng, pov, address){
	if (!street_window){
		panoramaObject = new Ext.ux.GMapPanel({
			id : "panorama_panel",
		    gmapType: 'panorama',
			zoomLevel : pov.zoom,
			yaw : pov.yaw,
			pitch : pov.pitch,
		    setCenter: {
		        lat: latlng.lat(),
		        lng: latlng.lng()
		    }
		});
		street_window = new Ext.Window({
			width : 500,
			height : 300,
			x : 200,
			y : 200,
			title : address,
			closeAction : 'hide',
			layout : 'fit',
			title : 'Street View',
			items : [panoramaObject]
		});
	}
	else panoramaObject.setPanoramaCenter({
		lat : latlng.lat(),
		lng : latlng.lng(),
		zoom : pov.zom,
		yaw : pov.yaw,
		pitch : pov.pitch
	});
	street_window.setTitle(address);
	street_window.show();	
}

	/*EVENTS*/
	function find_city(){
		if ($("#city_field").attr("value") != ""){

			var geocoder = new GClientGeocoder();

			geocoder.getLocations($("#city_field").attr("value"),function(geo_results){
				if (geo_results.Status.code == 200){
					var locations_panel = $("#locations_panel");
					locations_panel.html("");
					$(geo_results.Placemark).each(function(){
						if($(geo_results.Placemark).index(this) == 0){
							var center = new GLatLng(parseFloat(this.Point.coordinates[1]), parseFloat(this.Point.coordinates[0]));
							//Accessia.Gmap.initLocation(center);
							myAccessia.Gmap.initLocation(center);
							$("#location").val(
								"{'lat':'"+this.Point.coordinates[1]+"','lng':'"+this.Point.coordinates[0]+"'}"
							);
						}
						$('<img class="img_selection_address" src="/imgs/a_inicio.gif" />'+'<a class="anchor_selection_address"></a><br/>').
							html(this.address).
							attr({
								"href": "#",
								"rel": "{'lat':'"+this.Point.coordinates[1]+"','lng':'"+this.Point.coordinates[0]+"'}"
							}).
							click(function(){
								select_place = true;
								var lat = eval("("+$(this).attr("rel")+")").lat;
								var lng = eval("("+$(this).attr("rel")+")").lng;
								var center = new GLatLng(parseFloat(lat), parseFloat(lng));
								//Accessia.Gmap.initLocation(center);
								myAccessia.Gmap.initLocation(center);
								$("#city_field").val($(this).html());
								locations_panel.html("");
								return false;
							}).appendTo(locations_panel);
					});
				}
			});

		}
	}


	function findComboCity(){
		var c = Ext.getCmp('comborutaobj');
		if (c.getRawValue() != ""){
			var geo = new GClientGeocoder();
			geo.getLocations( c.getRawValue() , function(results){
				if (results.Status.code == 200){
					var arrayBlock = new Array();
					$(results.Placemark).each(function(i){
						arrayBlock.push([i, this.address, this.Point.coordinates[1], this.Point.coordinates[0] ]);
					});
					(c.getStore()).loadData(arrayBlock, false);
					c.expand();
				}
			});
		}
	}

function ocultar(b,e) {
	var left = Ext.getCmp('izquierda');

	if (left.collapsed) {
		left.expand();
	} else {
		left.collapse();
	}
}

function activarTab(id) {
	var tabsc = Ext.getCmp('tabs');
	if (tabsc.rendered) {
	  tabsc.layout.setActiveItem(id);
	  $('.tab').each(function(){
			switch(parseInt($(this).parent().attr('id'))) {
				case 0: $(this).css('background-position','0px -108px'); break;
				case 1: $(this).css('background-position','0px -144px'); break;
				case 2: $(this).css('background-position','0px -180px'); break;
			}
			$(this).parent().removeClass("ulselected");
	  });
	  switch(id) {
			case 0: $('#navigator ul li[id=0]').find('div.tab').css('background-position','0px 0px'); break;
			case 1: $('#navigator ul li[id=1]').find('div.tab').css('background-position','0px -36px'); break;
			case 2: $('#navigator ul li[id=2]').find('div.tab').css('background-position','0px -72px'); break;
	 }	
		
	  $('#'+id).addClass("ulselected");
	} else {
	  tabsc.activeItem = 0
	}

	doPlaceAction(lastplace);
/*	if (id != 0) doPlaceAction(lastplace);
	else{
		tabsc.doLayout(false, true);
	}*/
}

function flashCambiarDestino(info){
	if (typeof (info) != 'undefined' && info){
		if (typeof (info.place) != 'undefined') {
			$("#flashmappanel")[0].cambiarDestino(info.place);
		}else {
			$("#flashmappanel")[0].cambiarDestino("0");
		}
	}
}

function doPlaceAction(place){
	if (typeof(place)!='undefined' && place){
		switch (Ext.getCmp('tabs').layout.activeItem.id){
			case "livemappanel" : Ext.getCmp('livemappanel').cambiarDestino(place); break;
			case "gmappanel" : {
				Ext.getCmp('gmappanel').getMap().setCenter(new GLatLng(parseFloat(place.lat), parseFloat(place.lng)), 16);
				//Accessia.Gmap.cambiarDestino(place); break;
				if (myAccessia != null) myAccessia.Gmap.cambiarDestino(place); break;
			}
			case "flashmappanel" : flashCambiarDestino(place); break;
			case "helppanel" : break;
			default : break;
		}
	}
}

function placeClickedHandler(placeObj, eventObj){
	placeObj.fullInfo.type='place';
	/* Esto añade la url de la imagen del icono que se va a usar para el marcador del place. al pasarle esto la API ya tiene la función que hace falta para que si existe lo cree de nuevo 
	 * Se creará un icono de tipo Accessia.Gmaps._littleIcon que mide creo 16x16 o 22x22, no recuerdo. Si hace falta otra medida se lo podemos poner en la API o meter una función en el API que
	 * cree el icono que no haga falta y pasar el icono creado como parte del objeto en lugar de la URL.
	*/
	placeObj.fullInfo.myIconUrl = '/imgs/places/place-'+((typeof(placeObj.fullInfo.place)!='undefined')?placeObj.fullInfo.place:placeObj.fullInfo.fake_place)+'.png';

	lastplace = placeObj.fullInfo;

	doPlaceAction(lastplace);

	Ext.getCmp('combodestino').setRawValue(lastplace.name);
	
	// añadir a la url lo sellecionado
	var URLHASH = lastplace.name.replace(/ /g, '_');
	
	//window.location.hash = encodeURI(escape(URLHASH));
	
	if ($.browser.safari){
		window.location.hash = encodeURI(escape(URLHASH)); // para safari
	} else {
		window.location.hash = URLHASH;  // para los demas
	}
	
	
	Ext.getCmp('combodestino').removeClass('x-form-empty-field');
	
}

function createCampusBlock(campus){
	var container = new Ext.tree.TreePanel({
		 // tree
		 title : campus.name,
		 border : false,
		 animate:true,
		 enableDD:true,
		 collapsed:true,
		 containerScroll: true,
		 rootVisible:false,
		 // panel
		 autoScroll:true,
		 margins: '5 0 5 5'
		 
	});
	var _root_node = new Ext.tree.TreeNode({
		text: campus.name,
		allowDrag:false,
		allowDrop:false,
		leaf : false
	});
	container.setRootNode(_root_node);
	
	if (campus.edificios != 'undefined'){
		if (campus.edificios.edificio != 'undefined'){
			for (var i=0; i < campus.edificios.edificio.length; i++) {
				var node = new Ext.tree.TreeNode({
					text: (
						( typeof campus.edificios.edificio[i].place != 'undefined' &&
							campus.edificios.edificio[i].place != ''
						) ? campus.edificios.edificio[i].place+'. ' : (i+1)+'. '
					)+campus.edificios.edificio[i].name,
					allowDrag:false,
					cls: 'edificio',
					qtip : campus.edificios.edificio[i].name,
					leaf:true
				});

				node.fullInfo = campus.edificios.edificio[i];
				/* Esto añade el place ficticio a los uqe no lo tienen en la carga del XML en base a la posición de lectura */

				if (typeof(node.fullInfo.place)==='undefined') node.fullInfo.fake_place = (i+1);
				node.on('click', placeClickedHandler);
				_root_node.appendChild(node);
				
				if (typeof(campus.edificios.edificio[i].place)==='undefined' || campus.edificios.edificio[i].place === "") node.fullInfo.fake_place = campus.edificios.edificio[i].id;
				campus.edificios.edificio[i].myIconUrl = '/imgs/places/place-'+((typeof(campus.edificios.edificio[i].place)!='undefined')?campus.edificios.edificio[i].place:campus.edificios.edificio[i].fake_place)+'.png';
				campus.edificios.edificio[i].type = "place";
				fixedMarkers.push(campus.edificios.edificio[i]);
			}
		}
	}
	
	return (container);
}



function iefix(){
//Elimina un div que provocaba un error en IE8.
	var bwrap = Ext.getCmp('foot').bwrap;

	if (Ext.isIE8||Ext.isIE7||Ext.isIE6||Ext.isIE5) Ext.removeNode(bwrap.dom.children[0]);

}

var planearrutaform = '<div id="planruta"><img class="AB" src="js/ext-3.0/resources/images/default/como/A.png"/><img class="AB" src="js/ext-3.0/resources/images/default/como/B.png"/></div>';
planearrutaform += '<div id="dataruta"><div id="comboruta"></div><span class="locations_panel">Ejemplo: Calle del Sol, Madrid</span><div id="destino-name" class=""></div><span class="locations_panel">O selecci&oacute;nelo en los cuadros inferiores</span><div class="ruta-btn"><a class="rutaplan" href=#>C&oacute;mo llegar</a></div><div class="ruta-btn-borrar"><a class="rutaborrar" href=#>Borrar ruta</a></div></div>';

var buscadorform = '<div id="searcher"></div>';
// Override del template de la cabecera de un grid. En caso de añadir más grids, van a sufrir el override tambien, ojo
/*Ext.override(Ext.grid.GridView, {
		templates: {
			header: new Ext.Template(
				'<div class="grid-header-search-tool">',
				'<a class="search-tool-button" href="#">',
	            '<img class="search-tool-button-img" title="Buscador" src="js/ext-3.0/resources/images/accessia-blue/lupa.png"/>',
	            '</a></div>',
				
				'<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
			 	'<thead><tr class="x-grid3-hd-row">',
				'{cells}</tr></thead>',
			  	'</table>')
		}
}); */

Ext.onReady(function() {
	Ext.QuickTips.init();
	var rutas = new Ext.Panel({
		title: 'COMO LLEGAR',
		border : false,
		id: 'rutas',
		region:'north',
		height: 150,
		html: planearrutaform,
		cls:'empty',
		autoScroll : true
	});
	rutas.addListener('afterrender', function(){
		$("#city_field").keyup(find_city);
		$(".rutaplan").click(function(){
			myAccessia.Gmap.doDirections();
			return false;
		});
	});
	
	var eventos = new Ext.grid.GridPanel({

		title: 'EVENTOS <span class="small">(seleccione evento de destino)</span>',
		id : 'eventospanel',
		border : false,
		layout:'fit',
		fill: false,
		cls: 'eventos',
		titleCollapse: true,
		store: new Ext.data.JsonStore({
				autoLoad : true,
				autoDestroy: true,
				storeId: 'myEvents',
				sortInfo: { field: "date_ini", direction: "DSC" },
				//url: '/proxy/sym_events',
				data: symposium_events,
				record: 'Placemark',

				fields: [
					'id', 'title', 'date_ini', 'date_end', 'description', {name:'lat', type: 'float'}, {name:'lng', type: 'float'}
				]
			}),
		colModel: new Ext.grid.ColumnModel({
			defaults: {
				sortable: true
			},
			columns: [
				{id: 'Titulo',
				header: 'Titulo',
				width: 70,
				dataIndex: 'title',
				renderer: function(value, metaData, record, rowIndex, colIndex, store) {
							
							var name = record.get('title').replace(/"/g,'&quot;');
							metaData.attr = 'ext:qtip="'+ String.escape(name) +'"';
							return value;
						}
				},
				{header: 'Fecha',
				width: 30,
				dataIndex: 'date_ini'}
			]
		}),
		viewConfig:{forceFit: true},
		tbar: [new Ext.form.TextField({
			id: 'eventsearcher',
			enableKeyEvents: true,
			width: '200',
			emptyText: 'Filtre por título, descripción o fecha',
			listeners: {'keyup': function() { Ext.getCmp('eventospanel').getStore().filterBy(function (record, id) {
						var cadena = Ext.getCmp('eventsearcher').getRawValue();
						var matcher = this.data.createValueMatcher(cadena, true, false); //anyMatch, caseSensitive
						return (matcher.test(String(record.data.title)) || matcher.test(String(record.data.description)) || matcher.test(String(record.data.date_ini)));				
					}); } 
			}
		}), {
			icon: 'js/ext-3.0/resources/images/accessia-blue/filter.png'
		}]
	});

	eventos.on('rowclick', function(grid,rowIndex,e) {
		var record = grid.getStore().getAt(rowIndex);
		var lat = record.get('lat');
		var lng = record.get('lng');
		var panelMapa = Ext.getCmp('gmappanel');
		var mapaG = panelMapa.getMap();

		var tabsc = Ext.getCmp('tabs');

		if (tabsc.rendered) {
			activarTab(0);  // Necesario para cambiar estilos de la navigation bar

			var place = {
				name : record.get('title'),
				description : '<p>Del '+record.get('date_ini')+' al '+record.get('date_end')+'</p><p><a href="http://sym.posium.com/event_detail/'+record.get('id')+'.html'+'">Visite la web del evento</a></p><p>&nbsp;</p>'+record.get('description'),
				lat : record.get('lat'),
				lng : record.get('lng'),
				lat_parking : record.get('lat_parking'),
				lng_parking : record.get('lng_parking'),
				type : 'partnerevent',
				/* Estos tabs están de prueba */
				tabs : [
					{
						title : 'Información extra',
						content : '<iframe style="text-align:center; border:1px #ccc solid; width:99%; height:99%;" src="http://sym.posium.com/event_detail/simple/190.html">Tu navegador es demasiado antíguo</iframe>'
					}
				]
			}

			lastplace = place;
			doPlaceAction(lastplace);

			Ext.getCmp('combodestino').setRawValue(lastplace.name);
			
			// añadir a la url lo sellecionado
			window.location.hash = '';
		
			
			Ext.getCmp('combodestino').removeClass('x-form-empty-field');
		}

	});

	var lugares = new Ext.Panel({
		  //title: 'Lugares o eventos <span class="small">(Seleccione lugar de destino)</span>',
		  id : 'lugaresAccordion',
		  border : false,
		  layout: 'accordion',
		  titleCollapse: true,
		  bodyStyle: 'padding:5px;',
		  layoutConfig: {
            autoWidth: true
          },
		  region: 'center',
		  //cls:'empty',
		  items: []
	});
	
	var buscador = new Ext.Panel({
		id: 'Search',
		title: '<div class="x-tool x-tool-toggle" id="myxtool"> </div> <span class="x-panel-header-text">LUGARES <span class="small">(seleccione lugar de destino)</span></span>',
		bodyBorder : false,
		region: 'center',
		layout: 'border',
		items: [{ html:buscadorform, bodyBorder:false, border: false, xtype: 'panel', bodyStyle: 'padding:5px;', region: 'north', height: 30}, lugares]
	});
	
	function loadLugares(){
		var lugares = Ext.getCmp('lugaresAccordion');
	
		var data = new JKL.ParseXML("/service/camps_places");
		/* Esto es para solucionar el problema con el generador del controal ActiveX de la libreria */
		if (Ext.isIE8||Ext.isIE7) data.http.textmode = true;
		var xml = data.parse();
	
		if (typeof xml.camps != 'undefined'){
			if (typeof xml.camps.campus != 'undefined'){
				for (var i=0; i < xml.camps.campus.length; i++){
					var lugar = createCampusBlock(xml.camps.campus[i]);
					lugares.add(lugar);
					//Listener para mostrar Eventos cuando todos los lugares están collapsed 
					//Es independiente del número de campus
					lugar.addListener('collapse', function(){
						var elementos = lugares.layout.container.items.items;
						var replegados = true;
						$(elementos).each(function() {
							replegados = (replegados && this.collapsed);
						});
						lugares.layout.setActiveItem('eventospanel');
					});
				}
			}
		}
		lugares.add(eventos);
		lugares.doLayout();
		
	}
	
	loadLugares();
	
/*	var accordion = new Ext.Panel({
		id: 'accordion',
		margins:'0 0 0 0',
		region: 'center',
		layout:'accordion',
		items: [lugares, eventos]
	}); */
	var izquierda = new Ext.Panel({
		border : false,
		region:'west',
		layout:'border',
		id: 'izquierda',
		collapsible : true,
		hideCollapseTool : true,
		hideLabel : true,
		cls:'empty',
		split: 'true',
		cmargins: '0 0 0 0',
		floatable: false,
		collapseMode: 'mini',
		collapsibleSplitTip: 'Arrastra para ampliar',
		useSplitTips: true,
		minSize: 250,
		maxSize: 600,
		width: 300,
		margin: '0 0 0 0',

		items: [rutas,buscador]
	});


	var footer = new Ext.Panel({
		border : false,
		id: 'foot',
		region:'south',
		cls: 'pie',
		height: 25,

		bbar:
		[{
			text: 'Mostrar / Ocultar Directorio',
			id: 'toggleBtn',
			cls: 'hideshow',
			handler: ocultar
			},'->',{
			text: '2009&copy; Accessia',
			cls: 'copy'
			}
		]

	});

	var gmapObject = new Ext.ux.GMapPanel({
				border : false,
				id : 'gmappanel',
				xtype: 'gmappanel',
				zoomLevel: 15,
				gmapType: 'map',

				mapControls: [
					"GMenuMapTypeControl",
					new ExtLargeMapControl({
						  zoomInBtnTitle : "Aumentar",
						  zoomOutBtnTitle : "Reducir",
						  moveNorthBtnTitle : "Vista panorámica hacia arriba",
						  moveSouthBtnTitle : "Vista panorámica hacia abajo",
						  moveEastBtnTitle : "Vista panorámica a la derecha",
						  moveWestBtnTitle : "Vista panorámica a la izquierda",
						  homeBtnTitle : "Volver al último resultado"
					})
				],
				setCenter: {
					lat : 38.016665,
					lng : -1.170087
				}
	});
	gmapObject.on('mapready', function(t,m){
		setTimeout(function(){
			m.setCenter(new GLatLng(38.016665,-1.170087));
		},500);
	});

	gmapObject.addListener('mapready', function(){
		myAccessia = new Accessia_v2({
			Gmap : {
				map : Ext.getCmp('gmappanel').getMap(),
				active_layers : true,
				active_map_types : true,
				active_location : true,
				directions_div : "GMAP_DIRECTIONS",
				onDirectionsLoad : mydirectionsload,
				onHomeDrop : MY_onHomeDrop,
				streetDrop : MY_onStreetDrop
				/*load_overlays : {
					ground_overlays : [
						{
							url : 'http://accessia.es/jqmaps/nivel_17_overlay_transparente.png',
							bounds : {
								ne : {lat:38.026943, lng:-1.164188 },
								sw : {lat:38.010213, lng:-1.175678 }
							}
						}
					]
				}*/
			}
		});
		myAccessia.addPlugins({	
			Gmap : ['ControlLugares', 'MoreControl', 'StreetDoll', 'ContextMenuManager']
		});
		myAccessia.Gmap.addFixedMarkers(
			fixedMarkers, {
			click : function(o, ll){
				Ext.getCmp('combodestino').setRawValue(this.getTitle());
				Ext.getCmp('combodestino').setValue(this.getTitle());
				
				// añadir a la url lo sellecionado
				
				var URLHASH = this.getTitle().replace(/ /g, '_');
				if ($.browser.safari){
					window.location.hash = encodeURI(escape(URLHASH)); // para safari
				} else {
					window.location.hash = URLHASH;  // para los demas
				}
	
				

				Ext.getCmp('combodestino').removeClass('x-form-empty-field');
				/*
				 * Hay que actualizar el last place como se haría en el select del combo.
				 */
				lastplace = {
					name : this.getTitle(),
					lat : this.getLatLng().lat(),
					lng : this.getLatLng().lng()
				}
			}
		});
		myAccessia.Gmap.active_hide_fixed_markers(14);

		var zoomHere = $('\
		<div><p class="_zoom_click">Zoom aquí</p><div class="_zoom_div" style="display:none;"><input class="_new_zoom_level" type="text" value="nivel de zoom..." /><input class="_go_to_zoom" type="button" value="go" /></div></div>\
		');
		myAccessia.Gmap._contextMenu.addMenuElement([
			{
				element : "Colocar Inicio Aquí",
				callbacks : [{
					event : 'click',
					callback : function(){
						myAccessia.Gmap.home_change(myAccessia.Gmap._contextMenu._context_latlng);
					}
				}]
			},{
				element : "Ver street view",
				callbacks : [{
					event : 'click',
					callback : function(){
						myAccessia.Gmap._streetDoll.goToStreet(myAccessia.Gmap._contextMenu._context_latlng);
					}
				}]
			},{
				element : zoomHere[0],
				callbacks : [{
					event : 'click',
					callback : function(){
						$(this).next("._zoom_div").show();
					},
					ids_classes : "._zoom_click"
				},{
					event : 'focus',
					callback : function(){
						this.selectionStart = 0;
						this.selectionEnd = (this.textLength);
					},
					ids_classes : "._new_zoom_level"
				},{
					event : 'click',
					callback : function(){
						this.selectionStart = 0;
						this.selectionEnd = (this.textLength);
					},
					ids_classes : "._new_zoom_level"
				},{
					event : 'click',
					callback : function (){
						var zoom = parseInt($(this).prev("input").val(),10); 
						if (zoom != 'NaN' && zoom >=6 && zoom <= 17) myAccessia.Gmap._map.setCenter(myAccessia.Gmap._contextMenu._context_latlng, zoom);
						else alert("el zoom debe ser un entero entre 6 y 17");
						$(this).prev("input").val("");
						$(this).parent("div").hide();
					},
					ids_classes : "._go_to_zoom"
				}]
			}
		]);
		
	});
	
	gmapObject.addListener('mapresized', function(){
		if (typeof (myAccessia) != 'undefined' && myAccessia) myAccessia.Gmap.infoWindowResize();
	});


	var livemapObject = new Ext.ux.LiveMapPanel({
				//title : 'BirdView', //Titulo para el tabpanl
				border : false,
				id : 'livemappanel',
				xtype : 'livemappanel',

				initLoadOpts : {
					center : { lat : 38.017138, lng : -1.169665 },
					zoom : 14,
					mapStyle : 'Birdseye'
				}
	});


	var help = new Ext.Panel({
		border : false,
		//title : 'Ayuda',

		html : "<strong>Aqu&iacute; ir&aacute; la ayuda</strong>",
		id : "helppanel"
		//contentEl : 'plano_'
	});

	var flashmap = new Ext.FlashComponent(flashmapJSON);
	flashmap.addListener('show', function(o){
		setTimeout("pirulaTimeoutFlash()", 500);
		//doPlaceAction(lastplace);
	});
/*	flashmap.addListener('render', function(o){
		doPlaceAction(lastplace);
	});*/

	var tabpanelgroup = new Ext.Panel({
		border : false,
		region: 'center',
		id: 'tabs',
		layout:'card',
		activeItem: 0,
		autoDestroy : false,
		items : [gmapObject, livemapObject, flashmap]
		//items : [flashmap, help]
	});

	var header = new Ext.Panel({
		id: 'header',
		region:'north',
		border : false,
		cls:'empty accessia_header',
		height: 75,
		html: '<div id="accessia-img">&nbsp;</div>' /* +'<div id="accessia-header-menu"><div id="accessia-header-menu-content"><ul><li><a href=#>SOBRE ACCESSIA</a> | </li><li><a href=#>AYUDA</a> | </li><li><a href=#>CONTACTO</a> | </li><li id="accessia-header-menu-universidades"><a href=#>UNIVERSIDADES&nbsp;&#9661;</a></li></ul></div></div>'+'<div id="universia">&nbsp;</div>' */ 
	});

	var center = new Ext.Panel({
		border : false,
		id: 'center',
		layout:'border',
		region:'center',
		margins:'0 0 0 0',
		cls:'empty',
		bodyStyle:'background:#f1f1f1',
		items: [tabpanelgroup]
	});
	
	var viewport = new Ext.Viewport({
		id: 'viewport',
		border : false,
		layout:'border',
		items:[
			header, footer, izquierda, center
			]
	});
	viewport.on('afterrender', function(e){
		
	});

	iefix();





	var resultTpl = new Ext.XTemplate(
        '<tpl for="."><div class="search-item">',
            '{name}',
        '</div></tpl>'
    );
	var search = new Ext.form.ComboBox({
        store: new Ext.data.Store({
            autoLoad : true,
			autoDestroy: true,
			idProperty : 'name',
			storeId: 'lugSearch',
			url: '/service/camps_places',
			filter : function(property, value, anyMatch, caseSensitive){  // Busca en nombre y en descripcion, cualquier resultado y no sensible a mayusculas
				var matcher = this.data.createValueMatcher(value, true, false); //anyMatch, caseSensitive
				return this.filterBy(function(r){
					return (matcher.test(String(r.data['name'])) || matcher.test(String(r.data['description'])));
				});
			},

            reader: new Ext.data.XmlReader({
                record: 'edificio',
                id: 'id'
            }, Ext.data.Record.create([
                {name: 'id', mapping: 'id'},
				{name: 'name', mapping: 'name'},
				{name: 'lat', mapping: 'lat'},
				{name: 'lng', mapping: 'lng'},
				{name: 'description', mapping: 'description'},
				{name: 'place', mapping: 'place'},
				{name: 'lat_parking', mapping: 'lat_parking'},
				{name: 'lng_parking', mapping: 'lng_parking'},
				{name: 'plantas', mapping: 'plantas'}
            ])
			)
		}),
		displayField:'name',
		emptyText: 'Busqueda rápida',
		forceSelection : true,
		hideTrigger : true,
		id: 'searchbox',
		itemSelector: 'div.search-item',
		lazyInit: false,
		listWidth: 295,	
		mode: 'local',
		renderTo: 'searcher',
		selectOnFocus : false,
        tpl: resultTpl,
		triggerAction: 'all',
        typeAhead: false,
        mode: 'local',
        triggerAction: 'all',
		forceSelection : true,
		listWidth: 295,
		width: 180,
		listEmptyText: 'No hay resultados',
        lazyInit: false,

        onSelect: function(record){ // override default onSelect to do redirect
			record.data.type='place';

			if (typeof(record.data.place)==='undefined') record.data.fake_place = record.data.id;
			record.data.myIconUrl = '/imgs/places/place-'+((typeof(record.data.place)!='undefined')?record.data.place:record.data.fake_place)+'.png';

			lastplace = record.data;
			doPlaceAction(lastplace);
			this.setRawValue(lastplace.name);
			this.collapse();
			Ext.getCmp('combodestino').setRawValue(lastplace.name);
			Ext.getCmp('combodestino').removeClass('x-form-empty-field');
			
			var URLHASH = lastplace.name.replace(/ /g, '_');
			if ($.browser.safari){
				window.location.hash = encodeURI(escape(URLHASH)); // para safari
			} else {
				window.location.hash = URLHASH;  // para los demas
			}
	
        }
    });
	
	search.on('focus', function(){
		this.doQuery('',true);
		
	});

	var comboruta = new Ext.form.ComboBox({
		id : 'comborutaobj',
		renderTo : 'comboruta',
		mode : 'local',
		typeAhead : false,
		emptyText : 'Escriba su lugar de origen...',
		triggerAction : 'all',
		hideTrigger:true,
		width: 180,
		selectOnFocus : true,
		displayField : 'address',
		tpl : '<tpl for="."><div ext:qtip="{address}. ({lat},{lng})" class="x-combo-list-item">{address}</div></tpl>',
		store : new Ext.data.ArrayStore({ fields : [ 'id', 'address', {name:'lat', type:'float'} , {name:'lng',type:'float'} ] }),
		onSelect : function(record){
			myAccessia.Gmap.initLocation(new GLatLng(record.data.lat, record.data.lng));
			this.setRawValue(record.data.address);
			this.collapse();
		}
	});
	comboruta.on({
		'keyup' : {
			fn : findComboCity,
			scope : this
		}
	});
//	comboruta.addListener('keyup', findComboCity);
	comboruta.render();

	
	var combodestino = new Ext.form.ComboBox({
		displayField : 'name',
		emptyText : 'Escriba su destino...',
		forceSelection : true,
		hideTrigger:true,
		id : 'combodestino',
		mode : 'local',
		renderTo : 'destino-name',
		selectOnFocus : true,
		tpl : '<tpl for="."><div ext:qtip="{name}" class="x-combo-list-item">{name}</div></tpl>',
		triggerAction : 'all',
		typeAhead : false,
		width: 180,

		store : new Ext.data.JsonStore({
			url : '/service/symevents_places',
			storeId : 'combodestinostore',
			idProperty : 'name',
			autoDestroy : true,
			autoLoad : true,
			filter : function(property, value, anyMatch, caseSensitive){  // Busca en nombre y en descripcion, cualquier resultado y no sensible a mayusculas
				var matcher = this.data.createValueMatcher(value, true, false); //anyMatch, caseSensitive
				return this.filterBy(function(r){
					return matcher.test(String(r.data['name']));
				});
			},
			fields : [ 'id', 'type', 'name', 'description', 'place', {name:'lat', type:'float'}, {name:'lng', type:'float'}, {name:'lat_parking',type:'float'}, {name:'lng_parking', type:'float'}]
		}),
		onSelect : function(record){
			var place = {
				name : record.data.name,
				description : record.data.description,
				lat : record.data.lat,
				lng : record.data.lng,
				lat_parking : record.data.lat_parking,
				lng_parking : record.data.lng_parking,
				type : record.data.type,
				plantas : "[]",
				place : record.data.place
			}

			if (record.data.type === "place"){
				if (typeof(record.data.place)==='undefined' || record.data.place === "") place.fake_place = record.data.id;
				place.myIconUrl = '/imgs/places/place-'+((typeof(record.data.place)!='undefined')?record.data.place:record.data.fake_place)+'.png';
			}
			lastplace = place;
			doPlaceAction(lastplace);
			this.setValue(record.data.name);
			this.collapse();	
		}
	});
	
	combodestino.render();
	setTimeout(function(){ load_place_from_url(); },1000);
	
	combodestino.on('focus', function(o){
		o.doQuery('',true);
	});
	
	//JS para el comportamiento especial del acordeon
	var invisible = true;
	$('#Search div.x-panel-header:first').click(function(){
		if (invisible) { //Posicion del sprite
			$('#myxtool').css('background-position', '0px -255px');
		} else {
			$('#myxtool').css('background-position', '0px -240px');			
		}
		invisible = (!(invisible));
		$('#lugaresAccordion > div > div > div').filter(':not(#eventospanel)').toggle();
		Ext.getCmp('eventospanel').expand();
		buscador.doLayout();
	});
	// Acordeon empieza escondido
	$('#lugaresAccordion > div > div > div').filter(':not(#eventospanel)').toggle();
	
	/* Menú de pestañas (para que este situado sobre el mapa)(eventos necesita dos por el toggle del toolbar)*/
	$(document.body).append('<div id="navigator"><ul><li id="0" class="ulselected"><div class="tab">&nbsp;</div></li><li id="1"><div class="tab">&nbsp;</div></li><li id="2"><div class="tab">&nbsp;</div></li></div>');
	/* Detalle del estilo, picos sobre cada panel */
	$('div#rutas .x-panel-body:first').append('<img style="position:absolute;left:275px;top:-1px;" src="/js/ext-3.0/resources/images/accessia-blue/acordeon/pico.gif">');
	$('div#Search .x-panel-body.x-panel-body-noheader.x-panel-body-noborder:first').append('<img style="position:absolute;left:275px;top:-1px;" src="/js/ext-3.0/resources/images/accessia-blue/acordeon/pico.gif">');
	$("#eventospanel div.x-toolbar").append('<img style="position:absolute;left:275px;top:-1px;" src="/js/ext-3.0/resources/images/accessia-blue/acordeon/pico.gif">');
	//$('div#eventospanel .x-grid3-header-inner').append('<img id="picoeventos" style="position:absolute;left:275px;top:-1px;" src="/js/ext-3.0/resources/images/accessia-blue/acordeon/pico.gif">');
	//JS para las pestañas
	//Defino la posicion del background, segun ID de pestaña. Lo hago aqui porque via CSS no seria validable
	 $('.tab').each(function(){
	 	if (($(this).parent().filter(':not(.ulselected)')).size() > 0) {
			switch (parseInt($(this).parent().attr('id'))) {
				case 0:
					$(this).css('background-position', '0px -108px');
					break;
				case 1:
					$(this).css('background-position', '0px -144px');
					break;
				case 2:
					$(this).css('background-position', '0px -180px');
					break;
			}
		} else {
			switch (parseInt($(this).parent().attr('id'))) {
				case 0:
					$(this).css('background-position', '0px 0px');
					break;
				case 1:
					$(this).css('background-position', '0px -36px');
					break;
				case 2:
					$(this).css('background-position', '0px -72px');
					break;
			}
		}
	 });
	 //On click cambiar pestaña
	 $('.tab').click(function(){
	 	activarTab(parseInt($(this).parent().attr('id')));
	 });
	 //Hover mover el background sprite
	 $('.tab').hover(function(){
			if (($(this).parent().filter(':not(.ulselected)')).size()>0) 
			switch(parseInt($(this).parent().attr('id'))) {
				case 0: $(this).css('background-position','0px 0px'); break;
				case 1: $(this).css('background-position','0px -36px'); break;
				case 2: $(this).css('background-position','0px -72px'); break;
			}
	},function(){
			if (($(this).parent().filter(':not(.ulselected)')).size()>0) 
			switch(parseInt($(this).parent().attr('id'))) {
				case 0: $(this).css('background-position','0px -108px'); break;
				case 1: $(this).css('background-position','0px -144px'); break;
				case 2: $(this).css('background-position','0px -180px'); break;
			}
	});
	// LiveMap Panel captura el click aunque sea sobre gmappanel. Lo liberamos si el click no es en su div
	$("#gmappanel").click(function() {
		$("#livemap")[0].releaseCapture();
	});
	
	/* Menú para que salga por encima de todo. 
	$(document.body).append('\
<div id="accessia-header-menu-universidades-content">\
	<ul>\
		<li class="header">España</li>\
		<li>\
			<ul class="universidad-content">\
				<li><a href="#">Universidad de Murcia</a></li>\
				<li><a href="#">Universidad de Alicante</a></li>\
				<li><a href="#">Universidad Politécnica de Madrid</a></li>\
			</ul>\
		</li>\
		<li class="header">Portugal</li>\
		<li>\
			<ul class="universidad-content">\
				<li><a href="#">Universidad de Lisboa</a></li>\
				<li><a href="#">Universidad de Minho</a></li>\
				<li><a href="#">Instituto Politécnico de Porto</a></li>\
			</ul>\
		</li>\
		<li class="header">Latinoamérica</li>\
		<li>\
			<ul class="universidad-content">\
				<li><a href="#">Universidad Austral</a></li>\
				<li><a href="#">Universiadad Alberto Hurtado</a></li>\
				<li><a href="#">Centro de Estudios Universitarios - Nuevo León</a></li>\
				<li><a href="#">Universidad Católica de Chile</a></li>\
			</ul>\
		</li>\
	</ul>\
</div>');
	$("#accessia-header-menu-content a").click(function(){ 
		if(!$(this).parent().hasClass('over-universidades') && $(this).parent().attr('id')==='accessia-header-menu-universidades') {
			$(this).parent().addClass('over-universidades'); 
			$("#accessia-header-menu-universidades-content").css("display","block");
		}else {
			$("#accessia-header-menu-universidades").removeClass('over-universidades'); 
			$("#accessia-header-menu-universidades-content").css("display","none");
		}
	});
	$("#accessia-header-menu-universidades-content a").click(function(){$("#accessia-header-menu-universidades").removeClass('over-universidades'); $("#accessia-header-menu-universidades-content").css("display","none"); return false; });
*/
	$(".ruta-btn-borrar").click(function(){
		if (directionsWindow){
			directionsWindow.hide();
			myAccessia.Gmap.clearDirections();
			$(this).css("display", "none");
		}
	});
	
	/** Lupa Buscador de Eventos
	$(".search-tool-button").click(function() {
		var desplazamiento = parseInt($("#eventospanel div.x-panel-tbar").height());
		if ($("#eventospanel div.x-panel-tbar").css("display")=="none") 
			desplazamiento = -desplazamiento;
		desplazamiento = parseInt($("#picoeventos").css("top")) + desplazamiento;
		$("#picoeventos").css("top", desplazamiento+"px");
		$("#eventospanel div.x-panel-tbar").toggle();
	}); */

});


