// Configuración WMS
function loadServices(parent, groupName, servicios, customizable) {
	var ns = parent?parent.grafcan:grafcan;
	var flag = false;
	for (var i=0; i<servicios.length; i++) {
		// comprobamos que sea un servicio activo
		var forBrowse = true;
		try {forBrowse = eval($attrValue(servicios[i].attributes, "forBrowse"))} catch(e){}
		var forError = false;
		try {forError = eval($attrValue(servicios[i].attributes, "forError"))} catch(e){}
		if ($isElementNode(servicios[i]) && forBrowse) {
			var capas = $getNode(servicios[i].childNodes, "layers").childNodes; // elementos <layer>
			// atributo onlyOneFixedLayer
			var oneFixedLayer = false;
			try {						
				oneFixedLayer = eval($attrValue(servicios[i].attributes, "onlyOneFixedLayer"));
			} catch(e) {
				oneFixedLayer = false;
			}
			// atributo highlight
			var highlight = false;
			try {						
				highlight = eval($attrValue(servicios[i].attributes, "highlight"));
			} catch(e) {
				highlight = false;
			}
			// href
			var hrefNode = $getNode(servicios[i].childNodes, "href"); // elemento <href>
			var href = {title:'',url:''};
			if (hrefNode) {
				href.title = $attrValue(hrefNode.attributes, "title");
				href.url = $nodeValue(hrefNode);
			}
			// creamos el servicio
			var serviceName = '';
			serviceName = $attrValue(servicios[i].attributes, "name");
			var svc = ns.cfg.createService({name:serviceName,
										    shortName:$attrValue(servicios[i].attributes, "shortName"),
											desc:$attrValue(servicios[i].attributes, "desc"),
											defaultService:eval($attrValue(servicios[i].attributes, "default")),
											forBrowse:forBrowse,
											forError:forError,
											customizable:customizable,
											onlyOneFixedLayer:oneFixedLayer,
											highlight:highlight,
											href:{title:href.title,url:href.url}});
			// designamos el servicio inicial al arrancar la aplicación
			if (!customizable && svc.defaultService) ns.curService = serviceName;
			with (svc) {
				legend = $getNodeValue(servicios[i].childNodes, "legend");
				visibility.minResolution = parseInt($attrValue($getNode(servicios[i].childNodes, "visibility").attributes, "min"));
				visibility.maxResolution = parseInt($attrValue($getNode(servicios[i].childNodes, "visibility").attributes, "max"));
				copyrightCollection = $getNodeValue(servicios[i].childNodes, "copyrightCollection");						
				try {
					baseUrl3D = $getNodeValue(servicios[i].childNodes, "baseUrl3D");
				} catch(e) {
					baseUrl3D = "";
				}
				var queryEl = $getNode(servicios[i].childNodes, "query"); // elementos <queryUrl> y <queryLayers>
				if (queryEl.childNodes.length>0) {
					query.queryUrl = $getNodeValue(queryEl.childNodes, "queryUrl");
					query.queryUrl3D = $getNodeValue(queryEl.childNodes, "queryUrl3D");
					query.queryLayers = $getNodeValue(queryEl.childNodes, "queryLayers");
					query.format = $getNodeValue(queryEl.childNodes, "format");
					try{query.imageFormat = $attrValue($getNode(queryEl.childNodes, "format").attributes, "image");}catch(e){query.imageFormat='';}
				}
			}
			// añadimos el servicio al grupo
			try {
				if (!ns.cfg.groups[groupName]) ns.cfg.createGroup(groupName,ns.customGroupDesc);
				ns.cfg.groups[groupName].addService(svc);
			} catch (e) {
				alert(e.message);
				break;
			}
			// designamos el grupo como inicial si el servicio lo es
			if (!customizable && svc.defaultService && !ns.cfg.groups[groupName].defaultGroup)
				ns.cfg.groups[groupName].setDefault(true);
			// añadimos las capas al servicio
			for (var j=0; j<capas.length; j++) {
				if ($isElementNode(capas[j])) {
					// creamos la capa
					var layerName = $attrValue(capas[j].attributes, "name");
					var opacity = $getNodeValue(capas[j].childNodes, "opacity");
					var visibility = $getNode(capas[j].childNodes, "visibility");
					var minResolution = 7, maxResolution = 19;
					var baseUrlToPrint = $getNodeValue(capas[j].childNodes, "baseUrlToPrint");
					var folder = null;
					try {folder = $attrValue(capas[j].attributes, "folder")} catch(e) {}
					var queryable = false;
					try {queryable = $attrValue(capas[j].attributes, "queryable")} catch(e) {}
					var hidden = false;
					try {hidden = eval($attrValue(capas[j].attributes, "hidden"))} catch(e) {}
					if (visibility) {
						minResolution = $attrValue(visibility.attributes, "min");
						maxResolution = $attrValue(visibility.attributes, "max");
					}
					try {
						opacity = parseFloat(opacity);
					} catch(e) {
						opacity = 1.0;
					}
					var singleTile = null;
					try {
						singleTile = $getNodeValue(capas[j].childNodes, "singleTile");
					} catch(e) {
						singleTile = null;
					}
					var lyr = ns.cfg.createLayer(
									layerName,
									$attrValue(capas[j].attributes, "desc"),
									{visible:eval($attrValue(capas[j].attributes, "visible")),
									fixedLayer:eval($attrValue(capas[j].attributes, "fixed")),
									visibility: {minResolution:minResolution,maxResolution:maxResolution},
									type:$getNodeValue(capas[j].childNodes, "type"),
									format:$getNodeValue(capas[j].childNodes, "format"),
									baseUrl:$getNodeValue(capas[j].childNodes, "baseUrl"),
									baseUrlToPrint:baseUrlToPrint,
									tileFunction:(customizable?(j>0?parent.getTileUrl_transparent:parent.getTileUrl_opaque):$getNodeValue(capas[j].childNodes, "tileUrl")),
									layers:$getNodeValue(capas[j].childNodes, "layers"),
									opacity:opacity,
									singleTile:singleTile,
									folder:folder,
									queryable:queryable,
									hidden:hidden
									});
					// añadimos la capa al servicio
					try {						
						svc.addLayer(lyr);
					} catch (e) {
						alert(e.message);
						break;
					}
					flag = true;
				}
			}
		}
	}
	return (flag?svc:false);
}
function loadConf(xml) {
	var doc = GXml.parse(xml);
	var servicios = doc.getElementsByTagName('service');
	var groupName = grafcan.customGroupName;
	var gblConfig = grafcan.cfg;
	var svc = loadServices(self, groupName, servicios, true);
	if (svc) {
		// configuramos el nuevo GMapType
		grafcan.addService2Tree(svc);
		// establecemos el servicio recién creado
		var nodoServicio = grafcan.tree.getNodeById(svc.name);		
		if (nodoServicio) {			
			nodoServicio.select();
			grafcan.tree.getNodeById(groupName).expand();
		}
		grafcan.browseWMS.hide();
		return true;
	}
	return false;
}
function WMS_function(type, event) {
	switch(type) {
		case 'menu':
			var flag = (grafcan.cfg.countOfCustomizableServices()==0);
			if (flag) {
				grafcan.customMenu.items.map['wms_edit'].disable();
				grafcan.customMenu.items.map['wms_del'].disable();
				grafcan.customMenu.items.map['wms_save'].disable();
			} else {
				grafcan.customMenu.items.map['wms_edit'].enable();
				grafcan.customMenu.items.map['wms_del'].enable();
				grafcan.customMenu.items.map['wms_save'].enable();
			}
			if (grafcan.enableLoadKML) {
				if (grafcan.kmlUser)
					grafcan.customMenu.items.map['wms_unloadKML'].enable();
				else
					grafcan.customMenu.items.map['wms_unloadKML'].disable();
			}
			grafcan.customMenu.show($id('customize'));
			break;
		case 'new':
			WMS_new();
			break;
		case 'edit':
			WMS_list(event, type);
			break;
		case 'del':
			WMS_list(event, type);
			break;
		case 'save':
			WMS_list(event, type);
			break;
		case 'load':
			WMS_load();
			break;
		case 'loadKML':
			WMS_loadKML(event);
			break;
		case 'unloadKML':
			WMS_unloadKML();
			break;
	}
}
function WMS_new(svcName) {
	//grafcan.listWMSPanel.hide();
	grafcan.serviceToCustomize = svcName;
	//
	var left = window.screenX || window.screenLeft;
	var top = window.screenY || window.screenTop;
	var width = 525;
	var height = 610;
	var win = window.open('pages/wms/newWMS.htm', 'customizeWMS', 'left='+left+',top='+top+',scrollbars=no,status=no,toolbar=no,location=no,menubar=no,directories=no,height='+height+',width='+width+',scrollbars=yes');
	win.focus();
}
function WMS_edit() {
	var svcName = '';	
	for (var s in grafcan.listWMS.items.map) {
		var itemMenu = grafcan.listWMS.items.map[s]
		if (itemMenu.checked) {
			if (svcName=='') {
				svcName = itemMenu.serviceName;
			} else {
				alert(_('Seleccione sólo un servicio'));
				return;
			}
		}
	}
	if (svcName=='') {
		alert(_('Seleccione un servicio'));
		return;
	}
	WMS_new(svcName);
}
function WMS_del() {
	var curSvcDeleted = false;
	for (var s in grafcan.listWMS.items.map) {
		var itemMenu = grafcan.listWMS.items.map[s];
		if (itemMenu.checked) {
			if (!curSvcDeleted) curSvcDeleted = (itemMenu.serviceName==grafcan.curService);
			if (!grafcan.cfg.groups[grafcan.customGroupName].removeService(itemMenu.serviceName))
				//alert('No se pudo eliminar el servicio "' + itemMenu.text + '"');
				alert(Gettext.strargs(_("No se pudo eliminar el servicio '%1'"),itemMenu.text));
			else
				//alert('Se eliminó el servicio "' + itemMenu.text + '"');
				alert(Gettext.strargs(_("Se eliminó el servicio '%1'"),itemMenu.text));
			grafcan.tree.getNodeById(grafcan.customGroupName).removeChild(grafcan.tree.getNodeById(itemMenu.serviceName));
		}
	}	
	if (curSvcDeleted) {
		// establecemos el maptype por defecto
		grafcan.tree.getNodeById(grafcan.cfg.getDefaultService().name).select();
	}
}
function WMS_save() {
	var sXML = '';
	for (var s in grafcan.listWMS.items.map) {
		var itemMenu = grafcan.listWMS.items.map[s];
		if (itemMenu.checked)
			sXML += grafcan.cfg.getService(itemMenu.serviceName).getConfig();
	}
	if (sXML!='') {
		sXML = '<?xml version="1.0" encoding="iso-8859-1"?><services>' + sXML + '</services>';
		with($id('frmConfig')) {
			thing.value = sXML;
			action = 'pages/saveConfig.php';
			submit();
		}
	} else
		alert(_('Seleccione al menos un servicio'));
}
function WMS_load(event) {
	if (grafcan.browseWMS) {
		if (!grafcan.browseWMS.isVisible()) {
			grafcan.browseWMS.items.get(0).form.reset();
			grafcan.browseWMS.show();
		}
		return;
	}
    var form = new Ext.FormPanel({
        fileUpload: true,
        frame: false,
		bodyStyle: 'padding:10px 10px 10px 10px;',
		autoHeight:true,
        defaults: {
            anchor: '95%',
            allowBlank: false,
            msgTarget: 'side'
        },
        items: [{
            xtype: 'fileuploadfield',
            id: 'confFile',
			name: 'confFile',
			fieldLabel:'',
            buttonText: _('Examinar'),
			hideLabel:true
        },{
            xtype: 'hidden',
            id: 'domain',
            name: 'domain',
			value: documentDomain
        }],
		buttons: [{
            text: _('Cargar'),
            handler: function(){
				var frm = this.ownerCt.ownerCt.getForm();
                if (frm.isValid()) {
	                frm.submit({url:'pages/loadConfig.php',method:'POST',
							    success:function(form, action){
									if (!loadConf(action.result.data)) alert(_('Error cargando el servicio'));
								},
								failure:function(form, action){
									alert(_('Error cargando el servicio'))
								},
								waitTitle:_('Espere'),waitMsg:_('Cargando servicio')+'...'}
					);
                }
            }
        }]
	});
	grafcan.browseWMS = new Ext.Window({title:_('Cargar configuración'),closeAction:'hide',constrain:true,border:false,resizable:false,width:440,autoHeight:true,items:[form]});
	grafcan.browseWMS.show();
}
function WMS_loadKML(event) {
	if (grafcan.browseKML) {
		if (!grafcan.browseKML.isVisible()) {
			grafcan.browseKML.items.get(0).form.reset();
			grafcan.browseKML.show();
		}
		return;
	}
    var kmlForm = new Ext.FormPanel({
        fileUpload: true,
        frame: false,
		bodyStyle: 'padding:10px 10px 10px 10px;',
		autoHeight:true,
        defaults: {
            anchor: '95%',
            allowBlank: false,
            msgTarget: 'side'
        },
        items: [{
            xtype: 'fileuploadfield',
            id: 'kmlFile',
			name: 'kmlFile',
			fieldLabel:'',
            buttonText: _('Examinar'),
			hideLabel:true
        },{
            xtype: 'hidden',
            id: 'domain',
            name: 'domain',
			value: documentDomain
        }],
		reader: new Ext.data.JsonReader({
				root: 'data',
				fields: [{name:'url'},{name:'error'}]
		}),
		buttons: [{
            text: _('Cargar'),
            handler: function(){
				var frm = this.ownerCt.ownerCt.getForm();
                if (frm.isValid()) {
	                frm.submit({url:grafcan.urlLoadKML,method:'POST',
							    success:function(form, action){
									var geoxml = loadKML(action.result.data.url, 
									   function() { // success_callback
											try {map.removeOverlay(grafcan.kmlUser);}catch(e){}
											grafcan.kmlUser = geoxml;
											if (grafcan.kmlUser.loadedCorrectly()) {
												grafcan.kmlUser.gotoDefaultViewport(map);
											}
											setMapCursor('default');
									   },
									   function() { // error_callback
										   alert(_('Error en la carga')+':\n\n'+action.result.data.error);
									   });
									map.addOverlay(geoxml);
									setMapCursor('wait');
								},
								failure:function(form, action){
									alert(action.result.data.error)
								},
								waitTitle:_('Espere'),waitMsg:_('Cargando')+' KML...'}
					);
                }
            }
        }]
	});
	grafcan.browseKML = new Ext.Window({title:_('Cargar KML'),closeAction:'hide',constrain:true,border:false,resizable:false,width:440,autoHeight:true,items:[kmlForm]});
	grafcan.browseKML.show();
}
function WMS_unloadKML() {
	if (grafcan.kmlUser) map.removeOverlay(grafcan.kmlUser);
	grafcan.kmlUser = null;
}
function WMS_list(event, type) {
	try{grafcan.listWMS.destroy();}catch(e){}
	grafcan.listWMS = new Ext.menu.Menu({id:'listWMS'});
	var html = '';
	var sep = '';
	var n = 0;
	var list = grafcan.cfg.getCustomizableServices();
	var lengthList = grafcan.cfg.countOfCustomizableServices();
	var bChecked = (lengthList==1&&type=='edit'?true:false);
	for (var s in list) {
		var itemMenu = grafcan.listWMS.add({id:'listWMS_'+(++n),text:list[s],checked:bChecked,hideOnClick:false});
		itemMenu.serviceName = s;
	}
	grafcan.listWMS.add('-',
						{text:_('Continuar'),hideOnClick:true,
						 listeners:{'click': function(baseItem, evt) {
												switch(type) {
													case 'edit':
														WMS_edit();
														break;
													case 'del':
														WMS_del();
														break;
													case 'save':
														WMS_save();
														break;
												}
									}}
	});
	grafcan.listWMS.show($id('customize'));
}
//
function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight; 
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}
function windowWidth() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerWidth)
		return self.innerWidth;
	// IE 6
	if (document.documentElement && document.documentElement.clientWidth)
		return document.documentElement.clientWidth;
	// IE 5
	if (document.body)
		return document.body.clientWidth;
	// Just in case.
	return 0;
}
function activateBusquedas(flag, html) {
	if (flag) {
		$set_innerHTML('busquedas-resultados-div', html);
		$id('busquedas-resultados-panel').style.display = 'block';
		$id('tblCoordenadas').style.display = 'none';
		handleResize();
	} else {
		$set_innerHTML('busquedas-resultados-div', '');
		$id('busquedas-resultados-panel').style.display = 'none';
		$id('tblCoordenadas').style.display = ($ie())?'block':'table';
	}
}
function activateAyudaBusquedas() {
	switch ($id('divAyuda').style.display) {
		case 'none':
			$id('divAyuda').style.display='block';
			$set_innerText('hrefAyuda',_('Ocultar ayuda'));
			break;
		default:
			$id('divAyuda').style.display='none';
			$set_innerText('hrefAyuda',_('Ayuda'));
			break;
	}
	handleResize();
}
function activateResultados(flag, gdir) {
	if (flag && !grafcan.tabviewSidebar.get('tabRutas')) {
		var html = '<table style="margin:3px;height:50px" cellspacing="2" cellpadding="2">'
				 + '	<tr><td width="25">'+_('Desde')+'</td><td colspan="2"><input type="text" name="txtOrigen" id="txtOrigen" size="42" onChange="$id(\'cmdRoute\').disabled=(this.value==\'\')"/></td></tr>'
				 + '	<tr><td>'+_('A')+'</td><td colspan="2"><input type="text" name="txtDestino" id="txtDestino" size="42" onChange="$id(\'cmdRoute\').disabled=(this.value==\'\')"/></td></tr>'
				 + '	<tr><td>&nbsp;</td><td><button id="cmdRoute" disabled="disabled" onClick="queryRoute($id(\'txtOrigen\').value, $id(\'txtDestino\').value)">'+_('Calcular')+'</button></td>'
				 + '    	<td align="right"><button id="cmdPrintRoute" style="display:none" onClick="printRoute()">'+_('Imprimir')+'</button></td>'
				 + '	</tr>'
				 + '</table>'
				 + '<div id="resultados-div" style="height:'+(getHeight()-101)+'px;width:'+(grafcan.tabviewSidebar.getWidth()-($ie()?0:10))+'px;margin:0px;overflow:auto"></div>';
		grafcan.tabviewSidebar.add({id:'tabRutas',title:_('Ruta'),closable:true,autoHeight:true,html:html,listeners:{'beforeclose':function(){activateResultados(false)}}});
		grafcan.tabviewSidebar.doLayout();
		grafcan.tabviewSidebar.activate('tabRutas');
		$id('txtOrigen').focus();
	}
	if (flag) {
		$id('cmdPrintRoute').style.display = 'none';
	} else {
		$id('cmdPrintRoute').style.display = 'none';
		if (grafcan.gdir) grafcan.gdir.clear();
	}
}
function addCosa(desc, cosa, url) {
	if (!grafcan.overlayRepository) return;
	var contador = 1;
	if (Ext.getCmp('gridCosas'))
		contador = Ext.getCmp('gridCosas').getStore().getCount()+1;		
	var id = 'cosa_'+contador;
	while (grafcan.cosas[id]) id='cosa_'+(++contador);
	grafcan.cosas[id] = cosa;
	grafcan.cosas[id].url = url;
	grafcan.queryOverlay = cosa;
	grafcan.queryOverlayURL = url;
	if (!grafcan.tabviewSidebar.get('tabCosas')) {
		var checkColumn = new Ext.grid.CheckColumn({
		   dataIndex: 'visible',
		   width: 20
		});
		var sm = new Ext.grid.CheckboxSelectionModel();
		var grid = new Ext.grid.GridPanel({
			id: 'gridCosas',
			hideHeaders:true,
			plugins: checkColumn,
			tbar:[{
				id:'cmdEliminarCosa',
				text:_('Eliminar'),
				handler: function() {
					var s = grid.getSelectionModel().getSelections();
					var store = grid.getStore();
					for(var i=0,r;r=s[i];i++) store.remove(r);
					if (store.getCount()==0) grafcan.tabviewSidebar.remove('tabCosas');
				}
			}],
			store: new Ext.data.SimpleStore({
						fields:[{name:'id',type:'string'},{name:'desc',type:'string'},{name:'visible',type:'boolean'},{name:'url',type:'string'}],
						idIndex:0,
						listeners:{
							'update': function(me, record, operation) {
								if (record.modified.visible) {
									if (record.data.visible)
										grafcan.cosas[record.data.id].show();
									else
										grafcan.cosas[record.data.id].hide();
								}
							},
							'remove': function(me, record, index) {
								map.removeOverlay(grafcan.cosas[record.data.id]);
								delete(grafcan.cosas[record.data.id]);								
							}
						}
			}),
			listeners: {
				'rowcontextmenu': function(me, rowIndex, e) {
					var contextMenu = new Ext.menu.Menu();
					contextMenu.add({text:_('Ir a')+'...',
									 handler:function(){
										 var cosa = grafcan.cosas[grid.getStore().getAt(rowIndex).data.id];
										 if (cosa instanceof GMarker)
										 	map1.setCenter(cosa.getLatLng());
										 else
										 	cosa.gotoDefaultViewport(map);
									}
					});
					contextMenu.add({text:_('Exportar a KML'),handler:function(){cosa2KML(grid.getStore().getAt(rowIndex).data.id)}});
					e.stopEvent();  // no muestra el menú de contexto del navegador
					contextMenu.showAt(e.xy);
				}
			},
			colModel: new Ext.grid.ColumnModel({
				columns: [
					checkColumn,
					{hidden:true,dataIndex:'id'},
					{dataIndex:'desc',width:'auto'},
					{hidden:true,dataIndex:'url'}
				]
			}),
			enableColumnHide:false,enableColumnMove:false,enableColumnResize:false,enableHdMenu:false,
			height: 200,
			frame: false
		});
		grafcan.tabviewSidebar.add({id:'tabCosas',
								    title:_('Cosas'),
									closable:true,
									autoHeight:true,
									items:grid,
									listeners: {
										'beforeclose':function(p){
											if (p.id=='tabCosas') {
												var store = grid.getStore();
												while(store.getCount()) store.removeAt(store.getCount()-1);
											}
										}
									}
		});
		grafcan.tabviewSidebar.doLayout();
	}
	var store = Ext.getCmp('gridCosas').getStore();
	store.loadData([[id,desc,true,url]], true);
	//grafcan.tabviewSidebar.activate('tabCosas');
	if (grafcan.enableKMLExporting) $id('exportToKML').style.display='inline';
}
function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	map1.setCenter(map.getCenter());
	map1.checkResize();
	handleResize();
	if (grafcan.syncMode) {
		map2.checkResize();
		grafcan.synchronizeMap2();
	}
	return false;
}
function geo2utm(point) {
	var ll = new LatLng(point.lat(), point.lng());
	var utm = ll.toUTMRef();
	ll=null;
	this.x = utm.easting;
	this.y = utm.northing;
	this.latZone = utm.latZone;
	this.huso = utm.lngZone;
}
function DegreesFormat(degrees, isLatitude, prec) {
	if (!prec) prec = 0;
	var desc = '';
	if (isLatitude) {
		var letter = (degrees>=0)?'N':'S';
	} else {
		var letter = (degrees>=0)?'E':'O';
		degrees = -degrees;
	}
	var deg = parseInt(degrees);
	var mts = (degrees-deg)*60;
	var sgs = (mts-parseInt(mts))*60;
	mts = parseInt(mts);
	this.degrees = deg;
	this.minutes = mts;
	this.seconds = sgs;
	this.formatted = formatNumber(deg,0,2)+"°"+formatNumber(mts,0,2)+"'"+formatNumber(sgs,prec,2)+'" '+letter;
}
function formatNumber(number, decimal_places, leading_zero) {
	var num = new NumberFormat(number);
	num.setPlaces(decimal_places?decimal_places:0);
	num.setSeparators(true, ".", ",");
	var fmtnum = num.toFormatted();
	if (leading_zero) {
		num.truncate = true;
		var ent = String(num.getRounded(fmtnum));
		for (var i=leading_zero;i>ent.length;i--) {
			fmtnum = '0' + fmtnum;
		}
	}
	return fmtnum;
}
// mredkj.com (formateo de números)
function NumberFormat(num, inputDecimal)
{
	this.VERSION = 'Number Format v1.5.4';
	this.COMMA = ',';
	this.PERIOD = '.';
	this.DASH = '-'; 
	this.LEFT_PAREN = '('; 
	this.RIGHT_PAREN = ')'; 
	this.LEFT_OUTSIDE = 0; 
	this.LEFT_INSIDE = 1;  
	this.RIGHT_INSIDE = 2;  
	this.RIGHT_OUTSIDE = 3;  
	this.LEFT_DASH = 0; 
	this.RIGHT_DASH = 1; 
	this.PARENTHESIS = 2; 
	this.NO_ROUNDING = -1;
	this.num;
	this.numOriginal;
	this.hasSeparators = false;  
	this.separatorValue;  
	this.inputDecimalValue; 
	this.decimalValue;  
	this.negativeFormat; 
	this.negativeRed; 
	this.hasCurrency;  
	this.currencyPosition;  
	this.currencyValue;  
	this.places;
	this.roundToPlaces; 
	this.truncate; 
	this.setNumber = setNumberNF;
	this.toUnformatted = toUnformattedNF;
	this.setInputDecimal = setInputDecimalNF; 
	this.setSeparators = setSeparatorsNF; 
	this.setCommas = setCommasNF;
	this.setNegativeFormat = setNegativeFormatNF; 
	this.setNegativeRed = setNegativeRedNF; 
	this.setCurrency = setCurrencyNF;
	this.setCurrencyPrefix = setCurrencyPrefixNF;
	this.setCurrencyValue = setCurrencyValueNF; 
	this.setCurrencyPosition = setCurrencyPositionNF; 
	this.setPlaces = setPlacesNF;
	this.toFormatted = toFormattedNF;
	this.toPercentage = toPercentageNF;
	this.getOriginal = getOriginalNF;
	this.moveDecimalRight = moveDecimalRightNF;
	this.moveDecimalLeft = moveDecimalLeftNF;
	this.getRounded = getRoundedNF;
	this.preserveZeros = preserveZerosNF;
	this.justNumber = justNumberNF;
	this.expandExponential = expandExponentialNF;
	this.getZeros = getZerosNF;
	this.moveDecimalAsString = moveDecimalAsStringNF;
	this.moveDecimal = moveDecimalNF;
	this.addSeparators = addSeparatorsNF;
	if (inputDecimal == null) {
		this.setNumber(num, this.PERIOD);
	} else {
		this.setNumber(num, inputDecimal); 
	}
	this.setCommas(true);
	this.setNegativeFormat(this.LEFT_DASH); 
	this.setNegativeRed(false); 
	this.setCurrency(false); 
	this.setCurrencyPrefix('$');
	this.setPlaces(2);
}
function setInputDecimalNF(val) {
	this.inputDecimalValue = val;
}
function setNumberNF(num, inputDecimal) {
	if (inputDecimal != null) {
		this.setInputDecimal(inputDecimal); 
	}
	this.numOriginal = num;
	this.num = this.justNumber(num);
}
function toUnformattedNF() {
	return (this.num);
}
function getOriginalNF() {
	return (this.numOriginal);
}
function setNegativeFormatNF(format) {
	this.negativeFormat = format;
}
function setNegativeRedNF(isRed) {
	this.negativeRed = isRed;
}
function setSeparatorsNF(isC, separator, decimal) {
	this.hasSeparators = isC;
	if (separator == null) separator = this.COMMA;
	if (decimal == null) decimal = this.PERIOD;
	if (separator == decimal) {
		this.decimalValue = (decimal == this.PERIOD) ? this.COMMA : this.PERIOD;
	} else {
		this.decimalValue = decimal;
	}
	this.separatorValue = separator;
}
function setCommasNF(isC) {
	this.setSeparators(isC, this.COMMA, this.PERIOD);
}
function setCurrencyNF(isC) {
	this.hasCurrency = isC;
}
function setCurrencyValueNF(val) {
	this.currencyValue = val;
}
function setCurrencyPrefixNF(cp) {
	this.setCurrencyValue(cp);
	this.setCurrencyPosition(this.LEFT_OUTSIDE);
}
function setCurrencyPositionNF(cp) {
	this.currencyPosition = cp
}
function setPlacesNF(p, tr) {
	this.roundToPlaces = !(p == this.NO_ROUNDING); 
	this.truncate = (tr != null && tr); 
	this.places = (p < 0) ? 0 : p; 
}
function addSeparatorsNF(nStr, inD, outD, sep) {
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}
function toFormattedNF() {	
	var pos;
	var nNum = this.num; 
	var nStr;            
	//var splitString = new Array(2);   
	if (this.roundToPlaces) {
		nNum = this.getRounded(nNum);
		nStr = this.preserveZeros(Math.abs(nNum)); 
	} else {
		nStr = this.expandExponential(Math.abs(nNum)); 
	}
	if (this.hasSeparators) {
		nStr = this.addSeparators(nStr, this.PERIOD, this.decimalValue, this.separatorValue);
	} else {
		nStr = nStr.replace(new RegExp('\\' + this.PERIOD), this.decimalValue); 
	}
	var c0 = '';
	var n0 = '';
	var c1 = '';
	var n1 = '';
	var n2 = '';
	var c2 = '';
	var n3 = '';
	var c3 = '';
	var negSignL = (this.negativeFormat == this.PARENTHESIS) ? this.LEFT_PAREN : this.DASH;
	var negSignR = (this.negativeFormat == this.PARENTHESIS) ? this.RIGHT_PAREN : this.DASH;
	if (this.currencyPosition == this.LEFT_OUTSIDE) {
		if (nNum < 0) {
		if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
		if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
		}
		if (this.hasCurrency) c0 = this.currencyValue;
	} else if (this.currencyPosition == this.LEFT_INSIDE) {
		if (nNum < 0) {
			if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
			if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
		}
		if (this.hasCurrency) c1 = this.currencyValue;
	}
	else if (this.currencyPosition == this.RIGHT_INSIDE) {
		if (nNum < 0) {
		if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
		if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
		}
		if (this.hasCurrency) c2 = this.currencyValue;
	}
	else if (this.currencyPosition == this.RIGHT_OUTSIDE) {
		if (nNum < 0) {
		if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
		if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
		}
		if (this.hasCurrency) c3 = this.currencyValue;
	}
	nStr = c0 + n0 + c1 + n1 + nStr + n2 + c2 + n3 + c3;
	if (this.negativeRed && nNum < 0) {
		nStr = '<font color="red">' + nStr + '</font>';
	}
	return (nStr);
}
function toPercentageNF() {
	nNum = this.num * 100;
	nNum = this.getRounded(nNum);
	return nNum + '%';
}
function getZerosNF(places) {
	var extraZ = '';
	var i;
	for (i=0; i<places; i++) {
		extraZ += '0';
	}
	return extraZ;
}
function expandExponentialNF(origVal) {
	if (isNaN(origVal)) return origVal;
	var newVal = parseFloat(origVal) + ''; 
	var eLoc = newVal.toLowerCase().indexOf('e');
	if (eLoc != -1) {
		var plusLoc = newVal.toLowerCase().indexOf('+');
		var negLoc = newVal.toLowerCase().indexOf('-', eLoc); 
		var justNumber = newVal.substring(0, eLoc);
		if (negLoc != -1) {
		var places = newVal.substring(negLoc + 1, newVal.length);
		justNumber = this.moveDecimalAsString(justNumber, true, parseInt(places));
		} else {
			if (plusLoc == -1) plusLoc = eLoc;
			var places = newVal.substring(plusLoc + 1, newVal.length);
			justNumber = this.moveDecimalAsString(justNumber, false, parseInt(places));
		}
		newVal = justNumber;
	}
	return newVal;
} 
function moveDecimalRightNF(val, places) {
	var newVal = '';
	if (places == null) {
 		newVal = this.moveDecimal(val, false);
	} else {
		newVal = this.moveDecimal(val, false, places);
	}
return newVal;
}
function moveDecimalLeftNF(val, places) {
	var newVal = '';
	if (places == null) {
		newVal = this.moveDecimal(val, true);
	} else {
		newVal = this.moveDecimal(val, true, places);
	}
	return newVal;
}
function moveDecimalAsStringNF(val, left, places) {
	var spaces = (arguments.length < 3) ? this.places : places;
	if (spaces <= 0) return val; 
	var newVal = val + '';
	var extraZ = this.getZeros(spaces);
	var re1 = new RegExp('([0-9.]+)');
	if (left) {
		newVal = newVal.replace(re1, extraZ + '$1');
		var re2 = new RegExp('(-?)([0-9]*)([0-9]{' + spaces + '})(\\.?)');		
		newVal = newVal.replace(re2, '$1$2.$3');
	} else {
		var reArray = re1.exec(newVal); 
		if (reArray != null) {
			newVal = newVal.substring(0,reArray.index) + reArray[1] + extraZ + newVal.substring(reArray.index + reArray[0].length); 
		}
		var re2 = new RegExp('(-?)([0-9]*)(\\.?)([0-9]{' + spaces + '})');
		newVal = newVal.replace(re2, '$1$2$4.');
	}
	newVal = newVal.replace(/\.$/, ''); 
	return newVal;
}
function moveDecimalNF(val, left, places) {
	var newVal = '';
	if (places == null) {
		newVal = this.moveDecimalAsString(val, left);
	} else {
		newVal = this.moveDecimalAsString(val, left, places);
	}
	return parseFloat(newVal);
}
function getRoundedNF(val) {
	val = this.moveDecimalRight(val);
	if (this.truncate) {
		val = val >= 0 ? Math.floor(val) : Math.ceil(val); 
	} else {
		val = Math.round(val);
	}
	val = this.moveDecimalLeft(val);
	return val;
}
function preserveZerosNF(val) {
	var i;
	val = this.expandExponential(val);
	if (this.places <= 0) return val; 
	var decimalPos = val.indexOf('.');
	if (decimalPos == -1) {
		val += '.';
		for (i=0; i<this.places; i++) {
			val += '0';
		}
	} else {
		var actualDecimals = (val.length - 1) - decimalPos;
		var difference = this.places - actualDecimals;
		for (i=0; i<difference; i++) {
			val += '0';
		}
	}
	return val;
}
function justNumberNF(val) {
	newVal = val + '';
	var isPercentage = false;
	if (newVal.indexOf('%') != -1) {
		newVal = newVal.replace(/\%/g, '');
		isPercentage = true; 
	}
	var re = new RegExp('[^\\' + this.inputDecimalValue + '\\d\\-\\+\\(\\)eE]', 'g');	
	newVal = newVal.replace(re, '');
	var tempRe = new RegExp('[' + this.inputDecimalValue + ']', 'g');
	var treArray = tempRe.exec(newVal); 
	if (treArray != null) {
		var tempRight = newVal.substring(treArray.index + treArray[0].length); 
		newVal = newVal.substring(0,treArray.index) + this.PERIOD + tempRight.replace(tempRe, ''); 
	}
	if (newVal.charAt(newVal.length - 1) == this.DASH ) {
		newVal = newVal.substring(0, newVal.length - 1);
		newVal = '-' + newVal;
	}
	else if (newVal.charAt(0) == this.LEFT_PAREN
		&& newVal.charAt(newVal.length - 1) == this.RIGHT_PAREN) {
		newVal = newVal.substring(1, newVal.length - 1);
		newVal = '-' + newVal;
	}
	newVal = parseFloat(newVal);
	if (!isFinite(newVal)) {
		newVal = 0;
	}
	if (isPercentage) {
		newVal = this.moveDecimalLeft(newVal, 2);
	}
	return newVal;
}
//
/*
 * añade ? o &
 */
function addURLChars(url) {
	if (url.indexOf("?")==-1) url += "?";
	else if (url.substring(url.length-1)!='?' && url.substring(url.length-1)!='&') url += "&";
	return url;
}
//
function goto3D() {
	if (!grafcan.cfg.getService(grafcan.curService).baseUrl3D) {
		alert(_('Este servicio no está disponible en 3D'));
		return;
	}
	var url = "http://visor.grafcan.es/visor3D/default.php";
	var c = 104226048;
	var rango = c * 1/Math.pow(2, map.getZoom());
	url += "?svc="+grafcan.curService+"&lat="+map.getCenter().lat()+"&lng="+map.getCenter().lng()+"&range="+rango;
	document.location.href = url;
}
//
function viewSidebar() {
	if (document.body.className.match('sidebar-right'))
		changeBodyClass('sidebar-right', 'nosidebar');
	else
		changeBodyClass('nosidebar', 'sidebar-right');
}
// Escala aproximada
function EscalaAproximada(oMap) {
	var ScreenRes = ($ie())?screen.deviceXDPI:screen.pixelDepth*3;
	var bounds = oMap.getBounds();
	return Math.abs(ScreenRes * 39.37 * 156543.04 * Math.cos(bounds.getNorthEast().lat()*Math.PI/180) / Math.pow(2,oMap.getZoom()));
}
// Cargar KMLs
function loadKML(url, callback_success, callback_error) {
	var geoxml = new GGeoXml(url);
	GEvent.addListener(geoxml, 'load', function(){
									if (geoxml.loadedCorrectly()) {
										if (callback_success) {callback_success(geoxml);}
									} else {
										if (callback_error) {callback_error();}
									}});
	return geoxml;
}
// Nueva impresión
function print_success() {
	// data:[<MIME-type>][;charset="<encoding>"][;base64],<data>
	//window.open('data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAwAAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFzByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSpa/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJlZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uisF81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PHhhx4dbgYKAAA7','_blank','height=300,width=400');
	aler(9);
	var data='';
	for (var i=0;arguments[0][i];i++) data+=arguments[0][i];
	window.open('data:application/x-pdf;base64,'+c,'_blank');
}
function print_error() {
	alert(_('Error en la impresión')+'\n\n'+arguments[0]);
}
function printMap2() {
	var prn = new PrintObj(grafcan.urlPrintServer, print_success, print_error);
	// Cálculo del alto para las dimensiones: 533 x 633
	var width = 1024;
	var height = 1216;
	var ratio = height/width;
	var meta = new Array();
	//
	var bounds = map.getBounds();
	// Coordenadas ventana
	var coord1 = new geo2utm(bounds.getNorthEast());
	var coord2 = new geo2utm(bounds.getSouthWest());
	var utmcentro = new geo2utm(map.getCenter());
	var mitad = (coord1.x-coord2.x)/2*ratio;
	// nuevo bbox width x height
	var minx = coord2.x;
	var maxx = coord1.x;
	var miny = utmcentro.y-mitad;
	var maxy = utmcentro.y+mitad;
	//if (minx<grafcan.visibleBounds.minx || minx>grafcan.visibleBounds.maxx) minx = grafcan.visibleBounds.minx;
	//if (maxx>grafcan.visibleBounds.maxx || maxx<minx) maxx = grafcan.visibleBounds.maxx;
	//if (miny<grafcan.visibleBounds.miny || miny>grafcan.visibleBounds.maxy) miny = grafcan.visibleBounds.miny;
	//if (maxy>grafcan.visibleBounds.maxy || maxy<miny) maxy = grafcan.visibleBounds.maxy;
	var nw = UTMRefToLatLng(minx, maxy, grafcan.Huso.Numero, grafcan.Huso.Letra);
	var ne = UTMRefToLatLng(maxx, maxy, grafcan.Huso.Numero, grafcan.Huso.Letra);
	var se = UTMRefToLatLng(maxx, miny, grafcan.Huso.Numero, grafcan.Huso.Letra);
	var sw = UTMRefToLatLng(minx, miny, grafcan.Huso.Numero, grafcan.Huso.Letra);	
	nw = new GLatLng(nw.lat, nw.lng);
	ne = new GLatLng(ne.lat, ne.lng);
	se = new GLatLng(se.lat, se.lng);
	sw = new GLatLng(sw.lat, sw.lng);
		
	var bbox_geo = sw.lng()+","+sw.lat()+","+ne.lng()+","+ne.lat();
	var bbox_utm = minx+","+miny+","+maxx+","+maxy;

	meta.push(new DegreesFormat(nw.lat(),true,2).formatted + '  ' + new DegreesFormat(nw.lng(),false,2).formatted); // META00: nw geo
	meta.push(formatNumber(minx,2) + '  ' + formatNumber(maxy,2)); // META01: nw utm
	meta.push(new DegreesFormat(ne.lat(),true,2).formatted + '  ' + new DegreesFormat(ne.lng(),false,2).formatted); // META02: ne geo
	meta.push(formatNumber(maxx,2) + '  ' + formatNumber(maxy,2)); // META03: ne utm
	meta.push(new DegreesFormat(sw.lat(),true,2).formatted + '  ' + new DegreesFormat(sw.lng(),false,2).formatted); // META04: sw geo
	meta.push(formatNumber(minx,2) + '  ' + formatNumber(miny,2)); // META05: sw utm
	meta.push(new DegreesFormat(se.lat(),true,2).formatted + '  ' + new DegreesFormat(se.lng(),false,2).formatted); // META06: se geo
	meta.push(formatNumber(maxx,2) + '  ' + formatNumber(miny,2)); // META07: se utm
	var svc = grafcan.currentMapCfg();
	var url_fusiona = '';
	var sep = '';
	var idParam = 0;
	for (var s in svc.layers) {
		var url = '';
		var layer = svc.layers[s];
		if (layer.visible) {
			if (!layer.type && layer.name!='ghost') {
				if (layer.singleTile)
					url = getSingleTileUrl({layerName:layer.name,
										    bbox:bbox_utm,
											srs:'EPSG:'+grafcan.EPSG_utm,
											width:width,height:height});
				else
					url = getTileUrl_single({baseUrl:((layer.baseUrlToPrint)?layer.baseUrlToPrint:layer.baseUrl),
											 layers:layer.layers,
											 bounds:bounds,
											 width:width,height:height,format:layer.format,
											 bbox:bbox_utm,
											 srs:'EPSG:'+grafcan.EPSG_utm});																	
				// temporal
				/*var url2 = url.replace(/idecan1.grafcan.es/g, '192.168.90.11');
				url2 = url2.replace(/idecan2.grafcan.es/g, '192.168.90.10');*/
				var url2 = url;
				// eliminamos posibles espacios en blanco o similares antes del comienzo de la URL
				var re = /[\t\n ]*(?=http)/i;
				url2 = url2.replace(re, "");
				//
				url_fusiona += sep + 'param'+(++idParam)+'='+encodeURIComponent(url2)+((layer.opacity)?'&param'+idParam+'opacity='+layer.opacity*100:'');
				sep = '&';
			}
		}
	}
	if (idParam>1)
		url_fusiona = grafcan.urlFusiona+'?'+url_fusiona;
	else
		url_fusiona = url2;
	meta.push(url_fusiona); // META08: imagen
	meta.push(svc.desc); // META09: servicio
	//var escala = EscalaAproximada(map);
	var escala = (maxx-minx)/0.188;
	meta.push(_('Escala aprox.')+': 1:'+formatNumber(escala, 0)); // META10: escala aproximada
	meta.push(null); // META11: uso futuro
	//
	window.open('pages/espere_'+grafcan.lang+'.htm','printTarget','width=800,height=600,directories=no,location=no,menubar=no,resizable=yes,status=no,titlebar=no');
	if (grafcan.queryOverlay || grafcan.measureOverlay.length) {
		// max bbox
		var minx=9999999, miny=9999999, maxx=-9999999, maxy=-9999999;
		var pSRS='&SRS=EPSG:'+grafcan.EPSG_utm;
		var pSIZE='&SIZE='+width+','+height;
		var pURLKML='';
		var pURLGML = '';
		var pKML='';
		if (grafcan.queryOverlay) {
			if (grafcan.queryOverlay instanceof GMarker) {
				var b = grafcan.queryOverlay.getLatLng();
				minx = maxx = b.lng();
				miny = maxy = b.lat();
			} else {
				var b = grafcan.queryOverlay.getDefaultBounds();
				minx = b.getSouthWest().lng();
				miny = b.getSouthWest().lat();
				maxx = b.getNorthEast().lng();
				maxy = b.getNorthEast().lat();
			}
			if (grafcan.queryOverlayURL instanceof GLatLng) {
				// Point resultado de búsqueda UTM/Geo
				/*pKML = '&KML=<?xml version="1.0" encoding="UTF-8"?>'
					 + '<kml xmlns="http://earth.google.com/kml/2.1">'
					 + '<Document>'
					 + '<Placemark>'
				     + '<Point>'
				     + '<coordinates>'+(minx+','+miny+',0')+'</coordinates>'
				     + '</Point>'
				     + '</Placemark>'
				     + '</Document>'
				     + '</kml>';*/
			} else {
				//pURLKML = '&URLKML='+grafcan.queryOverlayURL;
				pURLGML = '&URLGML='+grafcan.queryOverlayURL;
				pURLGML = pURLGML.replace('toponimiakml','toponimiagml');
			}
		}
		if (grafcan.measureOverlay.length) {
			if (grafcan.measureOverlay.polygon)
				var b = grafcan.measureOverlay.polygon.getBounds();
			else
				var b = grafcan.measureOverlay.polyline.getBounds();
			if (minx>b.getSouthWest().lng()) minx = b.getSouthWest().lng();
			if (miny>b.getSouthWest().lat()) miny = b.getSouthWest().lat();
			if (maxx<b.getNorthEast().lng()) maxx = b.getNorthEast().lng();
			if (maxy<b.getNorthEast().lat()) maxy = b.getNorthEast().lat();
			pKML = '&KML=<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://earth.google.com/kml/2.1"><Document><Placemark>';
			for (var i=0; i<grafcan.measureOverlayName.length; i++) {
				if (grafcan.measureOverlay[grafcan.measureOverlayName[i]]) {
					var copia = grafcan.measureOverlay[grafcan.measureOverlayName[i]];
					var coords = '';
					var sep = '';
					for (var j=0; j<copia.getVertexCount(); j++) {
						var p = copia.getVertex(j);
						coords += sep + p.lng()+','+p.lat()+',0';
						sep = ' ';
					}
					if (grafcan.measureOverlayName[i]=='polygon')
						pKML += ('<Polygon><outerBoundaryIs><LinearRing><coordinates>'+coords+'</coordinates></LinearRing></outerBoundaryIs></Polygon>');
					else if (grafcan.measureOverlayName[i]=='polyline')
						pKML += '<LineString><coordinates>'+coords+'</coordinates></LineString>';
					else
						pKML += '<Point><coordinates>'+coords+'</coordinates></Point>';					
				}
			}
			pKML += '</Placemark></Document></kml>';
		}
		var pBBOX = '&BBOX='+bbox_utm;
		var params = pBBOX+pSRS+pSIZE+pURLKML+pURLGML+pKML;		
		var url = grafcan.urlRasterKML;
		GDownloadUrl(url, function(data, responseCode) {
							   if (responseCode==200) {
								   var vdata = data.split('\n');
								   if (vdata.length==1) {
									   meta.push(data);
								   } else {
									   for(var i=0;i<vdata.length;i++) {
										   if (vdata[i].indexOf('http://')==0) {
											   meta.push(vdata[i]);
										   } else if (vdata[i].indexOf('error')==0) {
											   alert(data);
										   }
									   }
								   }
								   prn.printByForm('report013',meta,'printTarget');
							   } else {
								   alert(data);
							   }},
							   params, 'application/x-www-form-urlencoded');
	} else {		
		prn.printByForm('report013',meta,'printTarget');
	}
}
// objeto waiting
var woWait = null;
function waiting(container) {
	this.div = null;
	if (!container)
		this.container = document.body;	
	else
		this.container = container;
}
waiting.prototype.show = function() {
	if (!this.container) return;
	var ancho = 126;
	var alto = 25;
	this.div = document.createElement('div');
	var span = document.createElement('span');
	span.innerHTML = '<div style="position:absolute;z-Index:1;left:1px;top:1px;color:#003366;width:'+ancho+'px;font-family:Verdana, Arial, Helvetica, sans-serif;font-size:9px;text-align:center;">'+_('Espere')+'...</div>';
	this.div.appendChild(span);
	span = document.createElement('span');
	span.innerHTML = '<div style="position:absolute;z-Index:0;left:2px;top:2px;color:#6699CC;width:'+ancho+'px;font-family:Verdana, Arial, Helvetica, sans-serif;font-size:9px;text-align:center;">'+_('Espere')+'...</div>';
	this.div.appendChild(span);
	var img = document.createElement('img');
	img.src = 'img/inProcess.gif';
	img.border = 0;
	img.vspace = 0;
	with (img.style) {
		position = 'absolute';
		left = '1px';
		top = '15px';
	}
	var anchoCliente = (window.innerWidth)?window.innerWidth:parseInt(document.documentElement.clientWidth);
	var altoCliente = (window.innerHeight)?window.innerHeight:parseInt(document.documentElement.clientHeight);
	if (anchoCliente<=0) anchoCliente = 426;
	this.div.appendChild(img);
	this.div.style.position = 'absolute';
	this.div.style.left = (anchoCliente/2-ancho/2)+'px';
	this.div.style.top = parseInt(altoCliente/2)+'px';
	this.div.style.width = ancho+'px';
	this.div.style.height = alto+'px';
	this.container.appendChild(this.div);
}
waiting.prototype.hide = function() {
	if (this.div) this.container.removeChild(this.div);
}
//