/**
 *Declaracion de la ventana modificar mapa
 *@author Romanuel Ramon Antunez
**/

/*****************************************************************************/

var radio1 = new Ext.form.Radio({
	    xtype:'radio',
	    id: 'gd',
	    checked: true,
	    hideLabel :true,
	    boxLabel: 'Grados Decimales',
	    anchor:'95%',
	    name: 'fcoor',
	    disabled: true
})

var radio2 = new Ext.form.Radio({
	    xtype:'radio',
	    id: 'gm',
	    hideLabel :true,
	    boxLabel: 'Grados Minutos',
	    anchor:'95%',
	    name: 'fcoor',
	    disabled: true
})

var radio3 = new Ext.form.Radio({
	    xtype:'radio',
	    id: 'gms',
	    hideLabel :true,
	    boxLabel: 'Grados Minutos Segundos',
	    anchor:'95%',
	    name: 'fcoor',
            disabled: true
})

var radio4 = new Ext.form.Radio({
	    id: 'cartesiana',
	    hideLabel :true,
	    boxLabel: 'Cartesiana',
	    anchor:'95%',
	    name: 'tdistancia',
	    disabled: true
})

var radio5 = new Ext.form.Radio({
	    id: 'esf&eacute;rica',
	    checked: true,
	    hideLabel :true,
	    boxLabel: 'Esf&eacute;ricas',
	    anchor:'95%',
	    name: 'tdistancia',
	    disabled: true	    
})

var comboDist = new Ext.form.ComboBox({
	    //xtype:'combo',
	    fieldLabel: 'Distancia',
	    id: 'dista',
	    //value: 'Metros',
	    anchor:'95%',
	    name: 'dista',
	    mode:'remote',
	    valueField:'id_unidmed',
	    displayField:'nombre',
	    triggerAction: 'all',
	    store:  new Ext.data.Store({
	      //autoLoad:true,
	      baseParams:{
		accion:'cargarComboUMedDist',
		opcion:1,
		filtro: 4
	      },
	      proxy: new Ext.data.HttpProxy({ url:"geoweb/configurar/sConfigurar.php" }),
	      reader: new Ext.data.JsonReader({root: 'filas', totalProperty:'cant_filas'},[{name:'id_unidmed'},{name:'nombre'}])
	     })
});
var comboSup = new Ext.form.ComboBox({
	      //xtype:'combo',
	      fieldLabel: 'Superficie',
	      id: 'superf',
	      value: 'Metros cuadrados',
	      anchor:'95%',
	      name: 'superf',
	      mode:'remote',
	      valueField:'id_unidmed',
	      displayField:'nombre',
	      triggerAction: 'all',
	      store:  new Ext.data.Store({
		//autoLoad:true,
		baseParams:{
		  accion:'cargarComboUMedSuperf',
		  opcion:1,
		  filtro: 2
		},
		proxy: new Ext.data.HttpProxy({ url:"geoweb/configurar/sConfigurar.php" }),
		reader: new Ext.data.JsonReader({root: 'filas', totalProperty:'cant_filas'},[{name:'id_unidmed'},{name:'nombre'}])
	      })
});
var comboAci = new Ext.form.ComboBox({
	    //xtype:'combo',
	    fieldLabel: '&Aacute;ngulos',
	    id: 'ang',
	    value: 'Grados decimales',
	    anchor:'95%',
	    name: 'ang',
	    mode:'remote',
	    valueField:'id_unidmed',
	    displayField:'nombre',
	    triggerAction: 'all',
	    store:  new Ext.data.Store({
	      //autoLoad:true,
	      baseParams:{
		accion:'cargarComboUMedAngulo',
		opcion:1,
		filtro: 3
	      },
	      proxy: new Ext.data.HttpProxy({ url:"geoweb/configurar/sConfigurar.php" }),
	      reader: new Ext.data.JsonReader({root: 'filas', totalProperty:'cant_filas'},[{name:'id_unidmed'},{name:'nombre'}])
	     })
});

fConfMapa = new Ext.FormPanel
(
  {
    labelAlign: 'top',
    buttonAlign: 'right',
    frame:true,   	
    items:[
    {
      layout:'column',
      items:[
      {
	//primera columna
	columnWidth:.5,
	style:'margin:0 15 0 5;',
	layout:'form',
	items:[
	{
	    xtype:'fieldset',
	    title: 'Unidades del Mapa',
	    layout:'form',
	    autoHeight:true,
	    items :[
	      {
		/*xtype:'combo',
		fieldLabel: 'Coordenadas',
		id: 'coorde',
		value: 'Grados',
		anchor:'95%',
		name: 'coorde',
		mode:'remote',
		valueField:'id_unidmed',
		displayField:'nombre',
		triggerAction: 'all',
		store:  new Ext.data.Store({
		  autoLoad:true,
		  baseParams:{
		    accion:'cargarComboUMedCoord',
		    opcion:1,
		    filtro: 1
		  },
		  proxy: new Ext.data.HttpProxy({ url:"geoweb/configurar/sConfigurar.php" }),
		  reader: new Ext.data.JsonReader({root: 'filas', totalProperty:'cant_filas'},[{name:'id_unidmed'},{name:'nombre'}])
		 }),
		 listeners: {  select: function(){
							if(Ext.get('coorde').getValue() == 'Grados'){
							    radio1.enable();
							    radio2.enable();
							    radio3.enable();
							  }
							  else
							  {
							    radio1.disable();
							    radio2.disable();
							    radio3.disable();
							    
							  }
						}}*/
			style:'margin:0 0 15 0;',
			//xtype:'box',
			id:'srcoord', 
			//autoEl: {tag:'blockquote', html:'Descipci&oacute;n:'}
			html: '<div id="coord">Coordenadas: </div>'
		},
	  comboDist,comboSup,comboAci]
	},
	{
	  xtype:'fieldset',
	  title: 'Formato de Coord. Geogr&aacute;ficas',
	  layout:'form',
	  autoHeight:true,
	  items :[radio1, radio2, radio3]
	}]
	},
	{
	  //primera columna
	  columnWidth:.5,
	  style:'margin:0 5 15 5;',
	  layout:'form',
	  items:[
	  {
	    xtype:'fieldset',
	    height: '300',
	    width: '200',
	    title: 'Tipo de Distancia',
	    items:[
	    {
	      layout: 'column',
	      items: [{columnWidth: .5,items:[radio4]}, {columnWidth: .5,items:[radio5]}] 
	     }]
	    },
	    {
	      xtype:'fieldset',
	      title: 'Sistemas de Referencia',
	      layout:'form',
	      autoHeight:true,
	      items :[
	      {
		xtype:'box',
		autoEl: {tag:'blockquote', html:'<center>Proyecci&oacute;n Actual </center>'}
	      },
	     /* {
	      style:'margin:20 5 5 5;',
		xtype:'box',
		id:'sregps', 
		autoEl: {tag:'blockquote', html:'EGPS:'}
		//html: '<div id:"idProj">EPSG: </div>'
	      },
	      {
		xtype:'box',
		id:'sp2', 
		autoEl: {tag:'blockquote', html:'&nbsp;'}
	      },*/
	      {
	      style:'margin:0 5 15 5;',
		//xtype:'box',
		id:'srdesc', 
		//autoEl: {tag:'blockquote', html:'Descipci&oacute;n:'}
		html: '<div id="descrip">Descripci&oacute;n: </div>'
	      },
	      {
		xtype:'button',
		id:'camproy',
		text: 'Cambiar Proyecci&oacute;n',
		listeners: {  click: function()
			{
				mm();
			}
		}
	      }]
	    }]
	  }]
	}]
  });

  var ConfigurarM;
  var proyeccionini = "";
 
   function fConfigurarMapa(){
    // la ventana se crea cuando se hace clic sobre el boton
    if(!ConfigurarM){
      ConfigurarM = new Ext.Window({
	title : 'Configurar Mapa',
	renderTo : document.body,
	layout : 'fit',
	width : 500,
	height : 500,
	closeAction :'hide',
	modal : true, 
	resizable :false,
	plain : true,
	items : fConfMapa,
	buttons: [{
	  text : 'Aceptar',
	  handler : function(){
	    Configurar();// llamada a la funcion para cargar config
	  }					
	},
	{
	  text : 'Cancelar',
	  handler  : function(){
	    ConfigurarM.hide();
	  }
	}]
      });
    }
 
document.getElementById('coord').innerHTML = '<span>Coordenadas: </span>'+BuscarNom(mapconfig.coord);
comboDist.setValue(BuscarNom(mapconfig.dist));
comboSup.setValue(BuscarNom(mapconfig.supf));
comboAci.setValue(BuscarNom(mapconfig.azim));
if(mapconfig.coord == "degree"){
	radio1.enable();
	radio2.enable();
	radio3.enable();
	
}else{
	radio1.disable();
	radio2.disable();
	radio3.disable();		
}
if(mapconfig.tDist == 1){
	radio4.disable();
	radio5.enable();
	radio4.setValue(false);
	radio5.setValue(true);
}else{
	radio4.enable();
	radio5.disable();
	radio4.setValue(true);
	radio5.setValue(false);
}
document.getElementById('descrip').innerHTML = '<span>Descripci&oacute;n:</span>'+mapconfig.Proj;
ConfigurarM.show();


function Configurar()
{
	//mapconfig = new MapConfig();
	//mapconfig.coord = BuscarAcro(Ext.get('coorde').getValue());
	mapconfig.dist = BuscarAcro(Ext.get('dista').getValue());
	mapconfig.supf = BuscarAcro(Ext.get('superf').getValue());
	mapconfig.azim = BuscarAcro(Ext.get('ang').getValue());
  
	if(radio1.checked == true)
	{
	  mapconfig.fCoord = 0;
	}
	else if(radio2.checked == true)
	{
	  mapconfig.fCoord = 1;
	}
	else
	{
	  mapconfig.fCoord = 2;
	}  
	
	if(radio4.checked == true)
	{
	  mapconfig.tDist = 0; 
	}
	else
	{
	  mapconfig.tDist = 1;
	}

	mapconfig.printZoom();
		  
	ConfigurarM.hide();
}

};

	Ext.data.JsonStore = function(c){
    		Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(c, {
        	proxy: !c.data ? new Ext.data.HttpProxy(new Ext.data.Connection({url: c.url, timeout: c.timeout})) : undefined,
        	reader: new Ext.data.JsonReader(c, c.fields)
	    }));
	};
	Ext.extend(Ext.data.JsonStore, Ext.data.Store);
	
	var BigTimeoutcon = 120000; 		
	var storeproj = new Ext.data.JsonStore({
		root: 'filas',
        	totalProperty: 'cant_filas',
        	//idProperty: 'id',
		url: 'geoweb/configurar/sConfigurar.php',
        	//remoteSort: true,
		//autoLoad: true,
        	fields: [
            	'name','id', 'val'
        	],
		baseParams:{
			accion:'cargarProyeccion',
			opcion:1,
		},
	      	proxy: new Ext.data.HttpProxy({ url:"geoweb/configurar/sConfigurar.php", timeout: BigTimeoutcon }),
		//reader: new Ext.data.JsonReader({root: 'filas', totalProperty:'cant_filas'},[{name:'name'},{name:'id'},{name:'val'}])
	});


	 var pagingBar = new Ext.PagingToolbar({
		pageSize: 20,
		store: storeproj,
		displayInfo: true,
		doLoad : function(start){
			var o = {}, pn = this.paramNames;
		    	o[pn.start] = start;
		    	o[pn.limit] = this.pageSize;
		    	if(this.fireEvent('beforechange', this, o) !== false){
		        	this.store.load({params:o});
		    	}
		},
		changePage: function(page){
        		this.doLoad(((page-1) * this.pageSize).constrain(0, this.store.getTotalCount()));  
   		},
		getPageData : function(){
			var total = this.store.getTotalCount();
		    	return {
		        	total : total,
		        	activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
		        	pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
		    	}},					
	});
	
	// create the Grid
    	var gridProject = new Ext.grid.GridPanel({
        	store: storeproj,
		ds : storeproj,
        	columns: [
            		{id:'name',header: "Name", width: 300, sortable: true, dataIndex: 'name'},
            		{header: "Identificador", width: 100, sortable: true, dataIndex: 'id'}, 
			//{header: "Valor", width: 500, sortable: false, dataIndex: 'val'}           		
        	],
        	stripeRows: true,
        	autoExpandColumn: 'name',
        	height:350,
        	width:400,
        	title:'Lista de Proyecciones',
		sm: new Ext.grid.RowSelectionModel({singleSelect: true}),
		viewConfig: {
			forceFit: true
		},
		split: true,
		region: 'north',

		// paging bar on the bottom
        	bbar: pagingBar

    	});

	
	var ct = new Ext.Panel({
		renderTo: document.body,
		frame: true,
		//title: 'Book List',
		width: 800,
		height: 600,
		layout: 'border',
		items: [
			gridProject,
			{
				id: 'detailPanel',
				region: 'center',
				bodyStyle: {
					background: '#ffffff',
					padding: '7px'
				},
				html: 'Seleccione una proyeccion...'
			}
		]
	})
	
	var ValTplMarkup = [
		'Identificador: {id}<br/>',
		'Nombre: {name}<br/>',
		'Valor: {val}<br/>',
	];

	var valtpl = new Ext.Template(ValTplMarkup);
	var proj = new Array();
	var selec = false;
	gridProject.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
		selec = true;		
		var detailPanel = Ext.getCmp('detailPanel');
		valtpl.overwrite(detailPanel.body, r.data);
		proj['name'] = r.data['name'];
		proj['id'] = r.data['id'];
		proj['val'] = r.data['val'];
	});

	//Aqui mandar a cargar el arreglo del fichero	
	storeproj.load({params:{start:0, limit:20}});

    var win;
    function mm(){
	
        // create the window on the first click and reuse on subsequent clicks
        if(!win){
            win = new Ext.Window({
		title       : 'Cambiar Proyecci&oacute;n',
                renderTo    : document.body,
                layout      : 'fit',
                width       : 500,
                height      : 500,
                closeAction :'hide',
                plain       : true,
		items       : ct,
		modal       :true,
                buttons: [{
                    text     : 'Submit',
		    handler  : function(){
                        St_Proyeccion();
                    }
		    },{
                    text     : 'Close',
                    handler  : function(){
                        win.hide();
                    }
                }]
            });
        }
	
        win.show();
};

function St_Proyeccion(){
	if(selec){
		/*mapconfig.Proj['name'] = proj['name'];
		mapconfig.Proj['id'] = proj['id'];*/
		mapconfig.Proj = proj['val'];
		
		//document.getElementById('descrip').innerHTML = '<span>Descripci&oacute;n:</span>'+mapconfig.Proj['val'];
		document.getElementById("valProjNew").value = mapconfig.Proj;
		//document.getElementById("idProjNew").value = proj['id'];
		document.getElementById("valProjNew").value = document.getElementById("valProjNew").value.replace('+','');
		document.getElementById("valProjNew").value = Replace(document.getElementById("valProjNew").value,'+',',');
		document.getElementById("valProjNew").value = Replace(document.getElementById("valProjNew").value," ","");
		mapconfig.Configurar();		
		document.getElementById("valCoord").value = mapconfig.coord;

		CartoWeb.trigger('setProjection.doIt');
		ConfigurarM.hide();
						
		//document.getElementById("statusProj").value = changePro;
		//alert(document.getElementById("valProyeccion").value);
		
		win.hide();
	}else{
		Ext.MessageBox.show({
			title: 'Error',
			msg: 'No ha seleccionado una proyecci&oacute;n',
			buttons: Ext.MessageBox.OK,
			icon: Ext.MessageBox.ERROR
		});
	}
	
}

function Replace(texto,s1,s2){
	return texto.split(s1).join(s2);
}


