/*--------------------------------------------------------------------------
 *
 *  Funciones comunes PagoConfiable
 *
 *  funciones utilizadas recurrentemente
 *
 *--------------------------------------------------------------------------*/

function validarFormulario(nombreForm, mensaje) {
	mensaje = 'Los campos marcados son obligatorios y deben ser introducidos correctamente';
	if (dijit.byId(nombreForm).validate()) {
		return true;
	} else {
		//escribirMensaje(mensaje, '', 'ocultarVentanaMensajes()', '','1');
		return false;
	}

}
/* Carga mensajes de sistema en ventana emergente
	iconoMensaje:
	1=>Advertencia, 2=>Item Agregado, 3=>Item Eliminado, 4=>Item Restinguido,
	5=>Error, 6=>Información, 7=>Ok, 8=>No permitido
*/
function escribirMensaje(textoMensaje, tiempo, botonAceptar, botonCancelar, iconoMensaje) {

	if (textoMensaje) {
		//Ajustando la posicion en que se mostrara
		avanceY = 100 + getViewportScrollY();
		document.getElementById('mensajesSistema').style.marginTop = avanceY + "px";

		codigoBotonAceptar = "<input id=\"butonMsgSistemAceptar\" type=\"button\" value=\"Aceptar\" onclick=\""+botonAceptar+"\" />";
		codigoBotonCancelar = "<input id=\"butonMsgSistemCancelar\" type=\"button\" value=\"Cancelar\" onclick=\""+botonCancelar+"\" />";
		if (textoMensaje){
			cargarMsg (textoMensaje);
		}
		//Seleccionando botones y/o tiempo a mostrar en la ventana
		codigoBotones = "";
		if ( (botonAceptar) && (botonCancelar) ) {
			codigoBotones = codigoBotonAceptar + " " + codigoBotonCancelar;
		} else if ( (botonAceptar) && (!botonCancelar) ) {
			codigoBotones = codigoBotonAceptar;
		} else if ( (!botonAceptar) && (botonCancelar) ) {
			codigoBotones = codigoBotonCancelar;
		}
		else {
			window.setTimeout(ocultar, tiempo);
		}
		//Seleccionando la imagen junto al mensaje
		imagen = '';
			switch(iconoMensaje) {
				case '1': //Advertencia
					imagen = 'ico_advertencia.gif';
					break;
				case '2': //Item Agregado
					imagen = 'ico_agregar.gif';
					break;
				case '3': //Item Eliminado
					imagen = 'ico_borrar.gif';
					break;
				case '4': //Item Restinguido
					imagen = 'ico_candado.gif';
					break;
				case '5': //Error
					imagen = 'ico_error.gif';
					break;
				case '6': //Información
					imagen = 'ico_informacion.gif';
					break;
				case '7': //Ok
					imagen = 'ico_ok.gif';
					break;
				case '8': //No permitido
					imagen = 'ico_nopermitido.gif';
					break;
				default: document.getElementById('mensajeImagen').style.display = 'none';
			}

		if (imagen) {
			document.getElementById('mensajeImagen').src = '/images/' + imagen;
			document.getElementById('mensajeImagen').style.display = 'block';
		}

		document.getElementById('mensajeBotones').innerHTML = codigoBotones;
		document.getElementById('mensajesSistema').style.display = 'block';
		if (botonAceptar){
			document.getElementById('butonMsgSistemAceptar').focus();
		}
	}
}

//Oculta la ventana de mensajes del sistema
function ocultarVentanaMensajes() {
	document.getElementById('mensajesSistema').style.display = 'none';
}

function escribirMensajeIframe(textoMensaje, tiempo, botonAceptar, botonCancelar, iconoMensaje) {
	if (textoMensaje) {

		//Ajustando la posicion en que se mostrara
		avanceY = 100 + getViewportScrollY();
		window.top.document.getElementById('mensajesSistema').style.marginTop = avanceY + "px";

		codigoBotonAceptar = "<input id=\"butonMsgSistemAceptar\" type=\"button\" value=\"Aceptar\" onclick=\""+botonAceptar+"\" />";
		codigoBotonCancelar = "<input id=\"butonMsgSistemCancelar\" type=\"button\" value=\"Cancelar\" onclick=\""+botonCancelar+"\" />";
		if (textoMensaje){
			window.top.document.getElementById('mensajeTexto').innerHTML = textoMensaje;
		}
		//Seleccionando botones y/o tiempo a mostrar en la ventana
		codigoBotones = "";
		if ( (botonAceptar) && (botonCancelar) ) {
			codigoBotones = codigoBotonAceptar + " " + codigoBotonCancelar;
		} else if ( (botonAceptar) && (!botonCancelar) ) {
			codigoBotones = codigoBotonAceptar;
		} else if ( (!botonAceptar) && (botonCancelar) ) {
			codigoBotones = codigoBotonCancelar;
		}
		else {
			window.setTimeout(ocultar, tiempo);
		}
		//Seleccionando la imagen junto al mensaje
		imagen = '';
			switch(iconoMensaje) {
				case '1': //Advertencia
					imagen = 'ico_advertencia.gif';
					break;
				case '2': //Item Agregado
					imagen = 'ico_agregar.gif';
					break;
				case '3': //Item Eliminado
					imagen = 'ico_borrar.gif';
					break;
				case '4': //Item Restinguido
					imagen = 'ico_candado.gif';
					break;
				case '5': //Error
					imagen = 'ico_error.gif';
					break;
				case '6': //Información
					imagen = 'ico_informacion.gif';
					break;
				case '7': //Ok
					imagen = 'ico_ok.gif';
					break;
				case '8': //No permitido
					imagen = 'ico_nopermitido.gif';
					break;
				default: window.top.getElementById('mensajeImagen').style.display = 'none';
			}

		if (imagen) {
			window.top.document.getElementById('mensajeImagen').src = '/images/' + imagen;
			window.top.document.getElementById('mensajeImagen').style.display = 'block';
		}

		window.top.document.getElementById('mensajeBotones').innerHTML = codigoBotones;
		window.top.document.getElementById('mensajesSistema').style.display = 'block';
		if (botonAceptar){
			window.top.document.getElementById('butonMsgSistemAceptar').focus();
		}
	}
}

function ocultarVentanaMensajesIframe() {
	window.top.document.getElementById('mensajesSistema').style.display = 'none';
}



//Muestra y Oculta la imagen cargando para las operaciones ajax
function cargando(visible) {
	if (visible == 'true') {
		//Ajustando la posicion en que se mostrara
		//avanceY = getViewportScrollY() + 3;
		//document.getElementById('sistemaCargando').style.marginTop = avanceY + "px";
		//alert(document.getElementById('sistemaCargando').style.display);
		document.getElementById('sistemaCargando').style.display = 'block';		
		console.log('Mostrando Mensaje');
	}
	else {
		document.getElementById('sistemaCargando').style.display = 'none';
		console.log('Ocultando Mensaje');
	}
}

//Escribe el contenido del mensaje
function cargarMsg (textoMensaje){
	document.getElementById('mensajeTexto').innerHTML = textoMensaje;
}

//Entrega la posicion avanzada en el eje y al hacer scroll
function getViewportScrollY() {
    var scrollY = 0;
    if( document.documentElement && document.documentElement.scrollTop ) {
        scrollY = document.documentElement.scrollTop;
    }
    else if( document.body && document.body.scrollTop ) {
        scrollY = document.body.scrollTop;
    }
    else if( window.pageYOffset ) {
        scrollY = window.pageYOffset;
    }
    else if( window.scrollY ) {
        scrollY = window.scrollY;
    }
    return scrollY;
}

function ingresaMensaje(texto) {
	if (texto == 'Ingrese su mensaje...') {
		document.frmSugerencia8.sugerenciaMensaje.value = '';
		document.frmSugerencia9.sugerenciaMensaje.value = '';
	}
}

//Muestra/Oculta un div
function visibilidad(id, estado) {
	visible = 'none';
	if (estado) {
		visible = 'block';
	}
	document.getElementById(id).style.display = visible;
}

// formatea una cadena dejando la primera letra en mayuscula
// idImput = Cadena
// todo = Boolean
//			true =>cambiar la primera letra a cada palabra de la frase
//			false=>cambia letra a primera letra de la frase
function PrimeraLetraMayuscula(idImput, todo)
{
	var inicial;
	var cadenafinal='';
 	cadena = document.getElementById(idImput).value;
 	if(todo){
  		arrayNombre = cadena.split(" ");
  		for(i=0; i<arrayNombre.length ; i++)
 			{
     		nombre = arrayNombre[i].toLowerCase();
  			inicial = arrayNombre[i].substring(0, 1);
  			inicial = inicial.toUpperCase();
		 	nombres = inicial + nombre.substring(1, nombre.length);
		 	cadenafinal = cadenafinal + nombres;
		 	if (i!=arrayNombre.length-1){
		 	    cadenafinal = cadenafinal + ' ';
		 		}
 			}
 	}
	else{
		cadena = cadena.toLowerCase();
	   	inicial = cadena.substring(0, 1);
	   	inicial = inicial.toUpperCase();
	   	cadenafinal = inicial + cadena.substring(1, cadena.length);
		}
	document.getElementById(idImput).value=cadenafinal;
}


// *******************  funciones javascrit que validan un rut  **************************
// funcion Valida rut
// idImput = Cadena  => id del imput que contiene el rut

function Rut(idImput){

  texto = document.getElementById(idImput).value;
  if (texto !=""){
	var tmpstr = "";
	for ( i=0; i < texto.length ; i++ ){
		if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' ){
			tmpstr = tmpstr + texto.charAt(i);
			}
		}
	texto = tmpstr;
	largo = texto.length;



	if ( largo != 9){
		//document.getElementById(idImput).value='';
	    //dijit.byId(idImput).invalidMessage='EL rut es incorrectos';
	    //validarFormulario('UpdateForm','');
	   // document.getElementById(idImput).value='';
	    if(!dijit.byId(idImput).validate()){
		    dijit.byId(idImput).invalidMessage='EL rut ingresado es incorrecto';
			//dijit.byId(idImput).focus();

			return false;
		}
	}

	for (i=0; i < largo ; i++ )	{
		if ( texto.charAt(i) !="0" && texto.charAt(i) != "1" && texto.charAt(i) !="2" && texto.charAt(i) != "3" && texto.charAt(i) != "4" && texto.charAt(i) !="5" && texto.charAt(i) != "6" && texto.charAt(i) != "7" && texto.charAt(i) !="8" && texto.charAt(i) != "9" && texto.charAt(i) !="k" && texto.charAt(i) != "K" ){
			//document.getElementById(idImput).value='';
		    if(!dijit.byId(idImput).validate()){
			    dijit.byId(idImput).invalidMessage='EL rut ingresado es incorrecto';
				//dijit.byId(idImput).focus();
				return false;
			}
		}
	}

	var invertido = "";
	for ( i=(largo-1),j=0; i>=0; i--,j++ ){
		invertido = invertido + texto.charAt(i);
		}
	var dtexto = "";
	dtexto = dtexto + invertido.charAt(0);
	dtexto = dtexto + '-';
	cnt = 0;

	for ( i=1,j=2; i<largo; i++,j++ ){
		if ( cnt == 3 ){
			dtexto = dtexto + '.';
			j++;
			dtexto = dtexto + invertido.charAt(i);
			cnt = 1;
		}
		else {
			dtexto = dtexto + invertido.charAt(i);
			cnt++;
		}
	}
	invertido = "";
	for ( i=(dtexto.length-1),j=0; i>=0; i--,j++ ){
		invertido = invertido + dtexto.charAt(i);
	}
    document.getElementById(idImput).value = invertido.toUpperCase();
	if ( revisarDigito2(texto, idImput)){
		if(dijit.byId(idImput).validate()){
			return true;
			}
		else{
			return false;
		}

		}
	}
	return false;
}

function revisarDigito(dvr, idImput)
{
	dv = dvr + ""
	if ( dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k'  && dv != 'K')
	{
		//document.getElementById(idImput).value='';
	    if(!dijit.byId(idImput).validate()){
		    dijit.byId(idImput).invalidMessage='EL rut ingresado es incorrecto';
			//dijit.byId(idImput).focus();
			return false;
		}
	}
	return true;
}

function revisarDigito2(crut, idImput){
	texto = document.getElementById(idImput).value;
	largo = crut.length;
	if ( largo < 2 ){
		//document.getElementById(idImput).value='';
	    if(!dijit.byId(idImput).validate()){
		    dijit.byId(idImput).invalidMessage='EL rut ingresado es incorrecto';
			//dijit.byId(idImput).focus();
			return false;
		}
	}
	if ( largo > 2 ){
		rut = crut.substring(0, largo - 1);
		}
	else{
		rut = crut.charAt(0);
		}
	dv = crut.charAt(largo-1);
	revisarDigito(dv, idImput);

	if ( rut == null || dv == null ){
		return 0;
		}

	var dvr = '0'
	suma = 0;
	mul  = 2;

	for (i= rut.length -1 ; i >= 0; i--){
		suma = suma + rut.charAt(i) * mul;
		if (mul == 7){
			mul = 2;
			}
		else{
			mul++;
			}
	}
	res = suma % 11;
	if (res==1){
		dvr = 'k';
		}
	else if (res==0){
		dvr = '0';
		}
	else{
		dvi = 11-res
		dvr = dvi + "";
	}
	if ( dvr != dv.toLowerCase() ){
		document.getElementById(idImput).value = texto+' ';
		//alert(dijit.byId(idImput).regExpGen);
	    if(!dijit.byId(idImput).validate()){
		    dijit.byId(idImput).invalidMessage='EL rut ingresado es incorrecto';
			//dijit.byId(idImput).focus();
			return false;
		}
	}

	return true
}
// ***************************** Fin validacion de rut ***********************************

function strip_tags(str, allowed_tags) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i>,<b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'

    var key = '', tag = '', allowed = false;
    var matches = allowed_array = [];
    var allowed_keys = {};

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_tags  = allowed_tags.replace(/[^a-zA-Z,]+/g, '');;
        allowed_array = allowed_tags.split(',');
    }

    str += '';

    // Match tags
    matches = str.match(/(<\/?[^>]+>)/gi);

    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }

        // Save HTML tag
        html = matches[key].toString();

        // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }

        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }

    return str;
}

function divVisibilidad(id) {
	if (document.getElementById(id).style.display == 'none') {
		document.getElementById(id).style.display = 'block';
	} else {
		document.getElementById(id).style.display = 'none';
	}
}

function divOcultar(id) {
	if (document.getElementById(id).style.display == 'block') {
		document.getElementById(id).style.display = 'none';
	}
}

function EnviarSugerencias() {
	var urlAccion = '/admin/index/guardarsugerencia';
	var queryString = $('formSugerencia').serialize(true);
	AuxFrmG = new llamadaAjax(queryString, urlAccion, 'get', 'divFormularioSurgerencias');
}

function trim (str, charlist) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
 
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}


