// JavaScript Document
/* Para las tildes y enie ENIE
\u00e1 -> a
\u00e9 -> e
\u00ed -> i
\u00f3 -> o
\u00fa -> u

\u00c1 -> A
\u00c9 -> E
\u00cd -> I
\u00d3 -> O
\u00da -> U

\u00f1 -> enie
\u00d1 -> ENIE */

var pestania = 0;

function error(data, ioArgs){
	alert(data);
}

function abrirPestaniaUrl(id,url,title){
	if(!id){
		id = pestania;	
	}
	if (dijit.byId(id)){
		tabs.selectChild(dijit.byId(id));
		dijit.byId(dijit.byId(id)).setHref(url);
	}else{
		var newChild = new dijit.layout.ContentPane({ id: id, href:url, title:title, closable: true, style:"overflow: auto;"});
		tabs.addChild(newChild);
		tabs.selectChild(newChild);
		pestania++;
	}
}

// Funcion que crea una ventana de dialogo y la abre
// id = el nombre de la ventana que tendria
function fnAbrirDialogo(id, url, title,cerrado, ancho, alto){
	var nomVen = '';
	if(id == ''){
		nomVen = "dDialogoGeneral";
	}
	else{
		nomVen = id;
	}
	if(!ancho){
		ancho = '700px';
	}
	if(!alto){
		alto = '500px;';
	}
	
	if(dijit.byId(nomVen)){
		dijit.byId(nomVen).destroyDescendants();
		dijit.byId(nomVen).destroy();
	}
	//var newWindow = new dijit.Dialog ({id: "boardNodeDialog",url: url ,title: title,refreshOnShow: true,refocus:false});
	var newWindow = new dijit.Dialog ({id: nomVen, href: url ,title: title, refocus:false, style:"background-color:#FFFFFF;width:" + ancho +";height:"+ alto +";overflow: auto;" });
	if(cerrado == true){
		dijit.byId(nomVen).closeButtonNode.style.display = "none";
	}
	
	// Si la ventana oculta el boton de cerrar se bloquea la tecla de escape para que el usuario no pueda cerrarla sino a traves de algun boton o proceso propio de la ventana
	if(cerrado == true){
		dojo.connect(dijit.byId(nomVen).domNode, 'onkeypress', function (evt) {
			var key = evt.keyCode;
			// Si tecla ESC
			if(key == 27) {
				dojo.stopEvent(evt);
			}
		  });
	}
	newWindow.startup();
	newWindow.show();
}

// Funcion que recive dos parametros
// url = carga el contenido de una url especifica
// mensaje = envia un mensaje de texto para cargar en el cuadro de dialogo
function abrirDialogojQuery(div_contenedor,titulo,url,mensaje,boton,ancho,alto,modal,redimensionar,movible,escape_cerrar){
	var contenedor = "#"+div_contenedor;
	// Valores por default
	if(!titulo){
		titulo = "Mensaje";
	}
	if(!ancho){
		ancho = 400;
	}
	if(!alto){
		alto = 250;
	}
	if(modal == ""){
		modal = true;
	}
	if(modal == "true"){
		modal = true;
	}
	if(modal == "false"){
		modal = false;
	}
	if(redimensionar == ""){
		redimensionar = false;
	}
	else if(redimensionar == "true"){
		redimensionar = true;
	}
	else if(redimensionar == "false"){
		redimensionar = false;
	}
	if(movible == ""){
		movible = true;
	}
	else if(movible == "true"){
		movible = true;
	}
	else if(movible == "false"){
		movible = true;
	}
	if(escape_cerrar == ""){
		escape_cerrar = false;
	}
	else if(escape_cerrar == "true"){
		escape_cerrar = true;
	}
	else if(escape_cerrar == "false"){
		escape_cerrar = false;
	}
	if(boton){
		// Definicion del dialogo
		$(contenedor).dialog({
			modal: modal,
			title: titulo,
			width: ancho, 
			height: alto,
			closeOnEscape: escape_cerrar,
			draggable: movible,
			resizable: redimensionar,
			buttons: { "CERRAR" : function() { $(contenedor).dialog('close') } }
		});
	}
	else{
		// Definicion del dialogo
		$(contenedor).dialog({
			modal: modal,
			title: titulo,
			width: ancho, 
			height: alto,
			closeOnEscape: escape_cerrar,
			draggable: movible,
			resizable: redimensionar
		});

	}
	if(url){
		// Si manda la url hay que separara la url de los parametros
		var url1;
		var params;
		pivote = url.indexOf("?");
		if(pivote == -1){
			url1 = url;
			params = "";
		}
		else{
			url1 = url.substring(0,eval(pivote));
			params = url.substring(eval(pivote+1));
		}
		$.ajax({
			url: url1,
			data: params,
			dataType: "text",
			type: "post",
			success: function(data){
				$(contenedor).html(data);
				$(contenedor).dialog('open');
			} 	
		});				
	}
	else if(mensaje){
		$(contenedor).html(mensaje);
		$(contenedor).dialog('open');
	}
}

//recibe como par�metro la url de la p�gina mas los parametros mas el alto y el ancho de la ventana a abrir el top  y left de la ventana */
function openPopUp(url,w,h,t,l){ 
	var windowprops ="top="+t+",left="+l+",toolbar=no,location=no,status=no, menubar=no,scrollbars=yes, resizable=no,width=" + w + ",height=" + h;
	window.open(url,"",windowprops);
}

function ltrim(s) { 
    return s.replace(/^\s+/, ""); 
} 
 
function rtrim(s) { 
    return s.replace(/\s+$/, ""); 
} 

// Elimina espacios en blanco de una cadena
function trim(s) { 
    return rtrim(ltrim(s)); 
}

function esNumero(fieldValue,decallowed){
	if(!decallowed){
		decallowed = 0;  // how many decimals are allowed?
	}
	if (isNaN(fieldValue) || fieldValue == ""){
		return false;
	}
	else{
		if (fieldValue.indexOf('.') == -1) fieldValue += ".";
		dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);
		if (dectext.length > decallowed){
			return false;
		}
		else{
			return true;
		}
   }
}

// Despliega un DIV en una ventana PopUp y presenta la venatana de impresión
function imprimirDiv(nombre){
	var params;
	params='width=700,height=700,top=100,left=300,scrollbars=YES,titlebar=NO';
	params=params+',menubar=NO,toolbar=NO,location=NO,status=NO';
	var ficha = document.getElementById(nombre);
	var ventimp = window.open(' ', 'popimpr',params);
	//ventimp.document.write('<link href="../css/tablas.css" rel=stylesheet type=text/css media="all" />');
	ventimp.document.write('<link href="css/tablas.css" rel=stylesheet type=text/css media="all" />');
	//ventimp.document.write('<link href="../css/estilo.css" rel=stylesheet type=text/css media="all" />');
	ventimp.document.write('<link href="css/estilo.css" rel=stylesheet type=text/css media="all" />');
	ventimp.document.write('<style type="text/css">body{font-size: 10px;} table{font-size: 10px;}</style>');
	ventimp.document.write('<img src="images/gui/cntlogo.gif" alt="c.n.t. s.a." />');
	ventimp.document.write( ficha.innerHTML );
	ventimp.document.close();
	ventimp.print();
	ventimp.close();
}

// Despliega en un DIV en una ventana PopUp pero no lo imprime
function desplegarDiv(nombre){
	var params;
	params='width=700,height=700,top=100,left=300,scrollbars=YES,titlebar=NO';
	params=params+',menubar=NO,toolbar=NO,location=NO,status=NO';
	var ficha = document.getElementById(nombre);
	var ventimp = window.open(' ', 'popimpr',params);
	//ventimp.document.write('<link href="../css/tablas.css" rel=stylesheet type=text/css media="all" />');
	//ventimp.document.write('<link href="css/tablas.css" rel=stylesheet type=text/css media="all" />');
	//ventimp.document.write('<link href="../css/estilo.css" rel=stylesheet type=text/css media="all" />');
	//ventimp.document.write('<link href="css/estilo.css" rel=stylesheet type=text/css media="all" />');
	ventimp.document.write('<style type="text/css">body{font-size: 10px;} table{font-size: 10px;}</style>');
	//ventimp.document.write('<img src="images/gui/cntlogo.gif" alt="c.n.t. s.a." />');
	ventimp.document.write( ficha.innerHTML );
	ventimp.document.close();
}


function Marcar(container_id){
	var subvalor = 0;
	var rows = document.getElementById(container_id).getElementsByTagName('tr');
	var checkbox;
	for(var j = 0 ; j <5 ; j++){
		for ( var i = 0; i < rows.length; i++ )	{
			checkbox = rows[i].getElementsByTagName( 'input' )[j];
			if ( checkbox && checkbox.type == 'checkbox' ){
				if ( checkbox.disabled == false ){
					checkbox.checked = true;
				}
			}
		}
	}
}

function Desmarcar(container_id){
	var rows = document.getElementById(container_id).getElementsByTagName('tr');
	var checkbox;
	for(var j = 0 ; j <5 ; j++){
		for ( var i = 0; i < rows.length; i++ ){
			checkbox = rows[i].getElementsByTagName( 'input' )[j];
			if ( checkbox && checkbox.type == 'checkbox' ){
				if ( checkbox.disabled == false ){
					checkbox.checked = false;
				}
			}
		}
	}
}

function contarMarcados(container_id,columna){
	
	var rows = document.getElementById(container_id).getElementsByTagName('tr');
	var cont=0;
	var checkbox;
	for ( var i = 0; i < rows.length; i++ ){
		checkbox = rows[i].getElementsByTagName( 'input' )[columna];
		if ( checkbox && checkbox.type == 'checkbox' ){
			if ( checkbox.checked == true ){
				cont = cont + 1;
			}
		}
	}
	return cont;
}

function marcarCambiado(control,valor,container_id){
	var rows = document.getElementById(container_id).getElementsByTagName('tr');
	var marcador = document.getElementsByName(control);
	for(i = 0; i < marcador.length; i++){
		//console.dir(marcador[i]);
		if(marcador[i].id == valor){
			marcador[i].checked = true;
			return;
		}
	}
	return;
}

function cerrarSistema(){
	try{
		window.close();
	}
	catch(e){}
}

function parametrosBusquedaCalles(opcion){
	leftAccordion.selectChild(acMapas);
	_$('searchForm').findlist.options[opcion].selected=true;
	setSearchInput();
}

function validarCedula (numero){
	var suma = 0;
	var residuo = 0;
	var pri = false;
	var pub = false;
	var nat = false;
	var numeroProvincias = 22;
	var modulo = 11;
	
	var ok=1;
	
	if (numero.length!=10&&numero.length!=13){
		return "C\u00e9dula incorrecta n\u00famero de d\u00edgitos";
	}
	
	/* Aqui almacenamos los digitos de la cedula en variables. */
	d1 = numero.substr(0,1);
	d2 = numero.substr(1,1);
	d3 = numero.substr(2,1);
	d4 = numero.substr(3,1);
	d5 = numero.substr(4,1);
	d6 = numero.substr(5,1);
	d7 = numero.substr(6,1);
	d8 = numero.substr(7,1);
	d9 = numero.substr(8,1);
	d10 = numero.substr(9,1);
	
	var idprovincia=d1+d2;
	if (idprovincia>numeroProvincias){
		return "C\u00e9dula Incorrecta primeros dos d\u00edgitos";
	}
	
	
	/* El tercer digito es: */
	/* 9 para sociedades privadas y extranjeros */
	/* 6 para sociedades publicas */
	/* menor que 6 (0,1,2,3,4,5) para personas naturales */
	
	if (d3==7 || d3==8){
		return 'El tercer d\u00edgito ingresado es inv\u00e1lido';
	}
	
	/* Solo para personas naturales (modulo 10) */
	if (d3 < 6){
		nat = true;
		p1 = d1 * 2; if (p1 >= 10) p1 -= 9;
		p2 = d2 * 1; if (p2 >= 10) p2 -= 9;
		p3 = d3 * 2; if (p3 >= 10) p3 -= 9;
		p4 = d4 * 1; if (p4 >= 10) p4 -= 9;
		p5 = d5 * 2; if (p5 >= 10) p5 -= 9;
		p6 = d6 * 1; if (p6 >= 10) p6 -= 9;
		p7 = d7 * 2; if (p7 >= 10) p7 -= 9;
		p8 = d8 * 1; if (p8 >= 10) p8 -= 9;
		p9 = d9 * 2; if (p9 >= 10) p9 -= 9;
		modulo = 10;
	}
	/* Solo para sociedades publicas (modulo 11) */
	/* Aqui el digito verficador esta en la posicion 9, en las otras 2 en la pos. 10 */
	else if(d3 == 6){
		pub = true;
		p1 = d1 * 3;
		p2 = d2 * 2;
		p3 = d3 * 7;
		p4 = d4 * 6;
		p5 = d5 * 5;
		p6 = d6 * 4;
		p7 = d7 * 3;
		p8 = d8 * 2;
		p9 = 0;
	}
	/* Solo para entidades privadas (modulo 11) */
	else if(d3 == 9) {
		pri = true;
		p1 = d1 * 4;
		p2 = d2 * 3;
		p3 = d3 * 2;
		p4 = d4 * 7;
		p5 = d5 * 6;
		p6 = d6 * 5;
		p7 = d7 * 4;
		p8 = d8 * 3;
		p9 = d9 * 2;
	}
	suma = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
	residuo = suma % modulo;
	
	/* Si residuo=0, dig.ver.=0, caso contrario 10 - residuo*/
	digitoVerificador = residuo==0 ? 0: modulo - residuo;
	
	/* ahora comparamos el elemento de la posicion 10 con el dig. ver.*/
	if (pub==true){
		if (digitoVerificador != d9){
			return 'El ruc de la empresa del sector p\u00fablico es incorrecto.';
		}
		/* El ruc de las empresas del sector publico terminan con 0001*/
		if ( numero.substr(9,4) != '0001' ){
			return 'El ruc de la empresa del sector p\u00fablico debe terminar con 0001';
		}
	}
	else if(pri == true){
		if (digitoVerificador != d10){
			return 'El ruc de la empresa del sector privado es incorrecto.';
		}
		if ( numero.substr(10,3) != '001' ){
			return 'El ruc de la empresa del sector privado debe terminar con 001';
		}
	}
	else if(nat == true){
		if (digitoVerificador != d10){
			return 'El n\u00famero de c\u00e9dula de la persona natural es incorrecto.';
		}
		if (numero.length >10 && numero.substr(10,3) != '001' ){
			return 'El ruc de la persona natural debe terminar con 001';
		}
	}
	return;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// Funciones Genericas AJAX

function cargarUrlDiv(url,div,metodo){
	var pagina;
	var params;
	var target = "#"+div;
	var pivote = url.indexOf("?");
	if(pivote == -1){
		pagina = url;
		params = "";
	}
	else{
		pagina = url.substring(0,eval(pivote));
		params = url.substring(eval(pivote+1));
	}
	if(metodo == ""){
		metodo = "post";
	}
	
	$.ajax({
		url: pagina,
		data: params,
		dataType: "text",
		type: metodo,
		success: function(data){
			$(target).html(data);
		}
	});
}

function centrarPuntoMapa(longitud,latitud,zoom,abrirModal){
	var rfactor = 5;
	var pxx = isNaN(longitud)?'' : roundN(longitud,rfactor);
	var pyy = isNaN(latitud)?'' : roundN(latitud,rfactor);
	var x1 = eval(pxx - 200);
	var x2 = eval(pxx + 200);
	var y1 = eval(pyy - 200);
	var y2 = eval(pyy + 200);	
	var imgxy = x1+"+"+y1+"+"+x2+"+"+y2;
	
	if(!zoom)
	{
		zoom = "14";	
	}
	
	if(!abrirModal)
	{
		zoompoint(1,imgxy);
		tabs.selectChild(dijit.byId("tabGis"));
	}
	else
	{
		var utm1 = new UTMRef(pxx, pyy, "E", 17);
		var ll3 = utm1.toLatLng();
		var ruta = "../php/googleMaps.php?latitud="+ll3.lat+"&longitud="+ll3.lng+"&zoom="+zoom;
		fnAbrirDialogo('mapGooPM',ruta,"Vista del Mapa en GoogleMaps en las coordenadas Latitud: "+ll3.lat+" Longitud: "+ll3.lng,false,'730px','560px');
	}
}

function validarDireccionMail(mail)
{  
	cadena=/^([a-zA-Z0-9\._-]+)@([a-zA-Z0-9\._-]+)\.([a-zA-Z0-9\._-]+)$/;  
	if(cadena.test(mail))
    	return 1;
    else
    	return 0;
}