var rootcapas;
var Arbol;
var pMinimapa;
var pTpGisLeft;

var refrescar = false;
var divCoordenadas;
var barraActiva = "";

/************************************ Arbol de Capas **************************************************/


//-----------------------------------------------------------------------------------
Ext.onReady(function(){

/** * Imagen por defecto ** */
	Ext.BLANK_IMAGE_URL = 'images/azul/s.gif';
/** * Funcion para los Tips ** */
	Ext.QuickTips.init();
/** * Cartel Cargando ** */
	myMask = new Ext.LoadMask(document.body, {msg:"Procesando..."});
	
/**
* ************************************ ARBOL DE CAPAS ******************************************
*/

rootcapas = new Ext.tree.TreeNode({
	text:'Capas',
	id:'idroot',
	expanded: true
});

bArbol = new Ext.Toolbar({
	border: false,
	autoHeight: true,
	items: [
		{xtype:'tbseparator'},
			// plugins por defecto
			{id:'ba1', iconCls: 'reload', text: 'Actualizar', handler:function(){CartoWeb.trigger("Layers.LayerShowHide");}},
		{xtype:'tbseparator'},
			// boton configurar mapa
			{id:'ba3', iconCls: 'ba3', handler:function(){Arbol.getRootNode().expand();}},
		{xtype:'tbseparator'},
			// plugins por defecto
			{id:'ba4', iconCls: 'ba4', handler:function(){Arbol.getRootNode().collapse();}},					
		{xtype:'tbseparator'}
	]
});

load_arbol(elementos, rootcapas);

Arbol = new Ext.tree.TreePanel({
	tbar: bArbol,
	id : 'panelarbol',
	style:'margin:0 0 0 2;',
	width:200,
	//enableDD:true,
	autoScroll: true,
	containerScroll: true,
	region:'center',
	root: rootcapas,
	listeners:
	{
		"nodedrop":function(obj)
		{
			CartoWeb.trigger("Layers.LayerShowHide");
		}
	}
});

/**
 * ************************************ BARRA DE MENU ******************************************
 */

	 var bMEnu = new Ext.Toolbar();
	 bMEnu.render('barraMenu');	
	// Funcion al dar click en una opcion del menu horizontal
	function onClickMenu(item){ 
	  	// document.getElementById("ifMarco").src = item.src;
	}

//*************************************  Funcion para cambiar de tema *******************************
    function cambiartema(ptema)
	{
		document.getElementById("tema").value=ptema;
		doSubmit();
	}	
//*************************************  Funcion para la ayuda **************************************

    function ayuda()
    {
    
	var nav = new Array('Microsoft Internet Explorer','Netscape');

	if(window.navigator.appName == nav[1])
	{
        var ancho = document.width - 50; 
        var alto = document.height - 50; 
    }
		var ayudaS = new Ext.Window({
			title : 'Ayuda',
			renderTo : document.body,
			autoScroll:true,
			border: true,
			layout:'fit',
			resizable: false,
			html:'<iframe src="geoweb/ayuda" width="'+ancho+'" height="'+alto+'"></iframe>'	
		});
		ayudaS.show();		
    }

//*************************************  Funcion para la Catalogo **************************************

    function catalogo()
    {
    
	var nav = new Array('Microsoft Internet Explorer','Netscape');

	if(window.navigator.appName == nav[1])
	{
        var ancho = document.width - 30; 
        var alto = document.height - 50; 
    }
		var catalg = new Ext.Window({
			title : 'Catalogo de Mapas',
			renderTo : document.body,
			autoScroll:true,
			border: true,
			modal: true,
            draggable: false,
			layout:'fit',
			resizable: false,
			html:'<iframe src="geoweb/catalogo/web" width="'+ancho+'" height="'+alto+'"></iframe>'	
		});
		catalg.show();		
    }
	
/**
 * *************************************** Barra de Herramientas 1 **********************************
 */

	bTools1 = new Ext.Toolbar({
		border: false,
		autoHeight: true,
		items: [
				{xtype:'tbseparator'},					
			    // tb2
						// zoom +
						{id:'zoomin_icon', iconCls: 'tb2a',handler:function(){enableTool('zoomin');}},
						// zoom -
						{id:'zoomout_icon',iconCls: 'tb2b',handler:function(){enableTool('zoomout');}},
						// boton configurar mapa
						{id:'recentrar_icon', iconCls: 'tb2c',handler:function(){enableTool('recentrar',1);}},
						// boton configurar mapa
						{id:'fullextent_icon', iconCls: 'tb2d',handler:function(){enableTool('fullextent');}/*,xtype: 'splitbutton',
							menu : {items: [
								{id:'fullextent', iconCls: 'tb2d', text: 'Zoom extenso por Capas',handler:function(){CapaZoomExtenso();}},  
							]}*/
						},
						
						// Boton Zoom Previo
						{id:'tb2e', iconCls: 'tb2e',handler:function(){
							return CartoWeb.trigger('BboxHistory.moveTo', null, {steps: -1})}
	
						},
						// Boton Zoom Siguinte
						{id:'tb2f',iconCls: 'tb2f',handler:function(){
							return CartoWeb.trigger('BboxHistory.moveTo', null, {steps: +1})}
						},
						// boton configurar mapa
						{id:'pan_icon', iconCls: 'tb2h',handler:function(){enableTool('pan');}},
				{xtype:'tbseparator'},			 
				/*// tb1
						// plugins por defecto
						{id:'select_by_point_icon', iconCls: 'tb1a',handler:function(){SeleccionQuery('select_by_point', 'Debe escoger la capa que desea seleccionar&nbsp');}},
						// boton configurar mapa
						{id:'select_by_bbox_icon',iconCls: 'tb1b',handler:function(){SeleccionQuery('select_by_bbox', 'Debe escoger la capa que desea seleccionar&nbsp');}},
						// boton configurar mapa
						{id:'select_by_circle_icon', iconCls: 'tb1c',handler:function(){SeleccionQuery('select_by_circle', 'Debe escoger la capa que desea seleccionar&nbsp');}},
						// boton configurar mapa
						{id:'select_by_polygon_icon', iconCls: 'tb1d',handler:function(){SeleccionQuery('select_by_polygon', 'Debe escoger la capa que desea seleccionar&nbsp');}},
						// boton configurar mapa
						{id:'select_by_clear_icon', iconCls: 'tb1e',handler:function(){enableTool('select_by_clear', true);}},					
			    {xtype:'tbseparator'},*/					
			    // tb3
						// plugins por defecto
						{id:'query_by_point_icon', iconCls: 'tb3a',handler:function(){SeleccionQuery('query_by_point', 'Debe escoger la capa que desea consultar');}},
						// boton configurar mapa
						{id:'query_by_bbox_icon',iconCls: 'tb3b',handler:function(){SeleccionQuery('query_by_bbox', 'Debe escoger la capa que desea consultar');}},
						// boton configurar mapa
						{id:'query_by_circle_icon', iconCls: 'tb3c',handler:function(){SeleccionQuery('query_by_circle', 'Debe escoger la capa que desea consultar');}},
						// boton configurar mapa
						{id:'query_by_polygon_icon', iconCls: 'tb3k',handler:function(){SeleccionQuery('query_by_polygon', 'Debe escoger la capa que desea consultar');}},									
				{xtype:'tbseparator'},					
			    // tb4
						{id:'tb3d', iconCls: 'tb3d',handler:function(){fLocalizadorPC();}},
						// boton para el calculo de distancia
						{id:'distance_icon', iconCls: 'tb3e',handler:function(){enableTool('distance');fCalcDistancia();}},
						// boton para el calculo de area
						{id:'surface_icon',iconCls: 'tb3f',handler:function(){enableTool('surface');fCalculoArea();}},
						{id:'azimuth_icon', iconCls: 'tb3h',handler:function(){enableTool('azimuth');fCalculoAzimute();}},
						{id:'azimuth1_icon', iconCls: 'tb3z',handler:function(){this.initialConfig.srcMenu='azimuth'; enableTool(this.initialConfig.srcMenu);enableTool('azimuth1');}},
						// boton configurar mapa
						//{id:'tb3m', iconCls: 'tb3m' , handler:function(){DeterminarRuta();}},
						// boton configurar mapa
						//{id:'locT_icon', iconCls: 'tb3n', handler:function(){enableTool('locT');}},
						// boton configurar mapa
						//{id:'perfil_icon',iconCls: 'tb3o', handler:function(){enableTool('perfil');}},
				{xtype:'tbseparator'},					
			    // tb5
						//{id:'tb3g',iconCls: 'tb3g'},
						// boton configurar mapa
						//{id:'bwinCMapa',iconCls: 'tb3i',handler:function(){fConfigurarMapa();}},
						// boton configurar mapa
						{id:'tb3j',iconCls: 'tb3j',handler:function(){ControlSeleccion();}},
			    {xtype:'tbseparator'},
			    // tb6
						// plugins por defecto
						{id:'tb4a', iconCls: 'tb4a', handler:function(){fEscalaGrafica();}},
						// boton configurar mapa
						{id:'tb4b',iconCls: 'tb4b', handler:function(){fVentanaReferencia();}},
						// boton configurar mapa
						// {id:'tb4c',iconCls: 'tb4c'},
						// boton configurar mapa
						//{id:'tb4d', iconCls: 'tb4d',handler:function(){fNavegadorVirtual();}},		      
				{xtype:'tbseparator'},										
				// tb7
						// boton configurar mapa
						//{id:'btnAgregarCapaVect', iconCls: 'tb6b' ,handler:function(){LoadFile();}},
						// boton configurar mapa
						//{id:'tb6c', iconCls: 'tb6c' ,handler:function(){PGLayer();}},
						// boton configurar mapa
					     /*{id:'tb6d', iconCls: 'tb6d'},
						// boton configurar mapa
						{id:'tb6e', iconCls: 'tb6e'},*/
						// boton configurar mapa
						{id:'tb6f', iconCls: 'tb6f'},		
				{xtype:'tbseparator'},					
						//{id:'pdfrotate_icon', iconCls: 'tb7c',handler:function(){enableTool('pdfrotate');fExportarPDF();}},      
				//{xtype:'tbseparator'},					
						//{id:'edit_icon', iconCls: 'edit',handler:function(){enableTool('edit');}},      
				//{xtype:'tbseparator'}
 				          /*{id:'btnBuscarPersona', iconCls: 'tb9a' ,handler:function(){Buscar_Persona();}},
 				          {id:'locT_icon', iconCls: 'tb9b' ,handler:function(){enableTool('locT');}},
 				          {id:'tb9c', iconCls: 'tb9c' ,handler:function(){}},*/
						// boton configurar mapa
						//{id:'btnAgregarCapaVect', iconCls: 'tb6b' ,handler:function(){LoadFile();}},
						// boton configurar mapa
				       
			]
	});
	
	function SeleccionQuery(herramienta, cartel)
	{
		if(document.getElementById('capas_select').value == "")
		{
			ControlSeleccion();
			enableTool(herramienta);	
			/*Ext.MessageBox.alert('Advertencia', cartel +
			';&nbsp;<img src="images/azul/icon-azul/tb3j.png">&nbsp;&nbsp;');
			AjaxHandler.doAction.actionName = "";*/
		}
		else
			enableTool(herramienta);			
    }


/**
 * **************************************** Panel Barras ***************************************
 */

 
pBarras = new Ext.Panel({
			id: 'titulo',
			title:'<img src="images/bg_banner.gif" height="50" style=margin:0 0 0 0>',			
			region:'north',
			style:'margin:0 0 0 0;',
			items: bTools1,
			height: 79
	}); 


    /** ********** variables del miniMapa *************** */
	miniMapa = document.getElementById('keymap_p').value;
        miniMapaw = document.getElementById('keymap_w').value;
        miniMapah = document.getElementById('keymap_h').value;
    /** ********** variables de la escala *************** */
    escala = document.getElementById('currentScale_value').value;
    
mapaRef = new Ext.Panel({
	height:150,
  	id : 'mapaR',
  	frame: true,
  	collapsible: true,
  	html: '<div id="keymapContainer" style="visibility: visible;margin:0 0 0 15;">'+
				'<div id="floatkeymap" style=" width:'+miniMapaw+'px; height:'+miniMapah+'px; ">'+
				'<input id="keymap" type="image" style=" width:'+ 
				+miniMapaw+'px; height:'+miniMapah+'px; " alt="keymap_alt" src="'+miniMapa+'"' + 'name="keymap"/>'+
				'</div>'+'</div>'
})
    
	


pMinimapa = new Ext.Panel({
    title:"Mapa de Referencia",
    region:'south',
    id:'west-panel',
    region:'south',
    height:177,
    collapsible: true,
    items: mapaRef
   
});

/**
 * ***************************************** Panel Informacion *************************************
 */
 
 divCoordenadas = document.createElement('div');
 divCoordenadas.setAttribute('id','floatGeo');
 divCoordenadas.setAttribute('class','locationInfo');
 divCoordenadas.innerHTML = 'Coordenadas(degree): %s / %s';
 
 /******************************  Panel Estandar de Navegacion  **********************************/
	
	comboEscala = new Ext.form.ComboBox({
	id: 'escala',
	mode:'remote',
	valueField:'id_escala',
	displayField:'factor',
	triggerAction: 'all',
	editable : false,
	value: document.getElementById("currentScale_value").value,
	width : 110,
	store:  new Ext.data.Store({
		autoLoad:true,
		baseParams:{
			accion:'cargarComboEscala',
			opcion:1,
		},
		proxy: new Ext.data.HttpProxy({ url:"geoweb/configurar/sConfigurar.php" }),
		reader: new Ext.data.JsonReader({root: 'filas', totalProperty:'cant_filas'},[{name:'id_escala'},{name:'factor'}])
	}),
	listeners: {
		select: function(comboEscala){
			scaleTemp = comboEscala.getRawValue();
			document.getElementById("recenter_scale").value = parseInt(scaleTemp);
			setCustomScale("select");
		}
	}
	});
	
	barraEstandar = new Ext.Panel({
	layout:'column',
	items:	[{
				columnWidth: 0.30,
				style:'margin:5 0 0 0;',
				html: divCoordenadas,
			},{	
				columnWidth: 0.05,
				style:'margin:5 0 0 0;',
				html: 'Escala 1:'
			},{
				columnWidth: 0.15,
				style:'margin:0 0 0 5;',
				items: comboEscala,
			},{	
				columnWidth: 0.20,
				style:'margin:5 0 0 0;',
				html: '<div id="pintada">'+'Capa Seleccionada: Ninguna'+'</div>'
			},{
				columnWidth: 0.15,
				style:'margin:5 0 0 20;',
				html:'<div id="geozoom">'+'Zoom: '+'</div>',
			}]
	});
		
	pInf = new Ext.Panel({
			region:'south',
			height: 35,
			frame : true,
			items: barraEstandar,
	});
	


/**
 * ********************************** Panel Mapa ******************************************************
 */
	pMapa = new Ext.Panel({
			region:'center',
			contentEl: 'mapBorder',
			id: "divImgGis",
			layout:'fit'
			    
	});

/**
 * ********************************* Funcion para cuando se rezise el mapa ****************************
 */

pMapa.on('resize',function(){
	if(refrescar)
		Enviar();
})

window.onresize = function(){
	refrescar = true;
}

});

function Enviar(){
	document.getElementById('divImgGis').style.width = document.getElementById('ext-gen17').style.width;
	document.getElementById('divImgGis').style.height = document.getElementById('ext-gen17').style.height;
        document.cookie = "ancho" + "=" + parseInt(document.getElementById('divImgGis').style.width.split('px')); 
        document.cookie = "alto" + "=" + parseInt(document.getElementById('divImgGis').style.height.split('px'));
	doSubmit();
}



/**
 * ****************************** Marco de la Pagina *******************************************
 */
var collapsed = false;
Ext.onReady(function(){
	
	
	if(document.getElementById("collapse_keymap").value == 1)
		collapsed = true;
		
	var pleftCapas = new Ext.Panel({
		id:'leftCapas',
		autoWidth: true,
		layout:'border',
		border:false,
		//title:'Capas',
		items:[Arbol ,pMinimapa]
	});	
	
	pTpGisLeft = new Ext.Panel({
		id:'pContainer',
		region:'west',
		width:205,
		title:'Control de Capas',
		collapsible:true,
            	collapsed: collapsed,
		layout:'fit',
		items:[pleftCapas],
		listeners: {  collapse: function(panel){
				  	if(document.getElementById("collapse_keymap").value != 1) // sino cae en un ciclo infinito
				  	{
				  		document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon");
						document.getElementById("collapse_keymap").value = 1;
						Enviar();
					}
				  },
				  expand: function(panel){
				  	if(mapaRef.collapsed){
						document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon");
					}
					else{
						document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon x-btn-pressed");
					}
					document.getElementById("collapse_keymap").value = 0;
					refrescar = true;	
				  }
				}			
	})

plantilla = new Ext.Viewport({
	layout:'border',
	items:[pBarras,pMapa,pInf,pTpGisLeft]
});

var button3 = Ext.get('ba3');
button3.on('click', function(){
	Arbol.expandAll();
});
    
var button4 = Ext.get('ba4');
button4.on('click', function(){
	Arbol.collapseAll();
});

if(!collapsed && !pMinimapa.collapsed)
{
	if(mapaRef.collapsed){
		document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon");
	}
	else{
		document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon x-btn-pressed");
	}
}

pMinimapa.on('collapse', function(){
	document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon");
});	

pMinimapa.on('expand', function(){
	if(mapaRef.collapsed){
		document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon");
	}
	else{
		document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon x-btn-pressed");
	}
});


mapaRef.on('collapse', function(){
	document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon");
});

mapaRef.on('expand', function(){
	document.getElementById('tb4b').setAttribute("class", "x-btn-wrap x-btn x-btn-icon x-btn-pressed");
});


Arbol.expand();

document.getElementById('Map_h').value = document.getElementById('ext-gen17').style.height;
document.getElementById('Map_w').value = document.getElementById('ext-gen17').style.width;

});

/**
 * ********************* Menu Clic Derecho *************************************************
 */

Ext.onReady(function()
{

	
	document.body.oncontextmenu=function(){return false;};
	mapa = document.getElementById('divImgGis');
	mapa.oncontextmenu=function(e){ 
	if (Ext.isIE) {  
		tempX = event.clientX + document.body.scrollLeft; 
		tempY = event.clientY + document.body.scrollTop; 
	} else {  // por si es NS
		tempX = e.pageX; 
		tempY = e.pageY; 
	}   
	// catch possible negative values in NS4
	if (tempX < 0){tempX = 0;} 
	if (tempY < 0){tempY = 0;}  
								 
	}
});
/** ******************************************************************************************************** */


function fEscalaGrafica(){
	if(myform['scalebarStatus'].value == 0)
		myform['scalebarStatus'].value = 1;
	else
		myform['scalebarStatus'].value = 0;
	CartoWeb.trigger('Location.Refrescar');
}


function fVentanaReferencia(){
	if(!mapaRef.collapsed)
		mapaRef.collapse();
	else
		mapaRef.expand();
	if(collapsed){
		pTpGisLeft.expand();
	}			
};



/****************  destruir panel **************************************/

function DestruirMontarPanel(panel)
{

	var leftCapas = Ext.getCmp("leftCapas");

	CerrarTab();
	
	var tabPanel = new Ext.TabPanel({
		id:'TabMenu',
		layoutOnTabChange:true,
		activeTab:0	,
		tabWidth:96,
		minTabWidth:96,
		resizeTabs:true,
		listeners: {
            remove: function(tabP, tab){
                CerrarTab();
                //enableTool('zoomin');
            }
        }
	});

	tabPanel.add(panel);

	leftCapas.setTitle('Capas');
	tabPanel.add(leftCapas);

	pTpGisLeft.setTitle('');
	pTpGisLeft.add(tabPanel);
	pTpGisLeft.doLayout(true);

}

function CerrarTab(){

	var leftCapas = Ext.getCmp("leftCapas");	
	
	var Capas = document.getElementById('leftCapas');
	Capas.setAttribute('class', 'x-panel x-panel-noborder');
	
	pTpGisLeft.add(leftCapas);
	pTpGisLeft.remove(Ext.getCmp("TabMenu"));
	pTpGisLeft.setTitle('Control de Capas');
	pTpGisLeft.doLayout(true);

}


