//******************************************************************************************************************
// USUARIOS PORTAL
//******************************************************************************************************************
function GrabarUsuario(form)
{
    theForm.txtNombre.value=trim(theForm.txtNombre.value);
    if (noVacio(theForm.txtNombre) == false) {
	    alert('Por favor, ingresar el/los nombre(s).');
	    theForm.txtNombre.focus();
	    return false;
	}
    theForm.txtApellidoPaterno.value=trim(theForm.txtApellidoPaterno.value);
    if (noVacio(theForm.txtApellidoPaterno) == false) {
	    alert('Por favor, ingresar el apellido paterno.');
	    theForm.txtApellidoPaterno.focus();
	    return false;
	}
    theForm.txtApellidoMaterno.value=trim(theForm.txtApellidoMaterno.value);
    if (noVacio(theForm.txtApellidoMaterno) == false) {
	    alert('Por favor, ingresar el apellido materno.');
	    theForm.txtApellidoMaterno.focus();
	    return false;
	}
    if(!theForm.rdoSexo[0].checked && !theForm.rdoSexo[1].checked)
    {
	    alert('Por favor, seleccionar el sexo.');
	    return false;
    }
    theForm.txtEmail.value=trim(theForm.txtEmail.value);
	if (noVacio(theForm.txtEmail) == false || esEmail(theForm.txtEmail)==false) {
		alert('Por favor, verificar la dirección de correo electrónico.');
		theForm.txtEmail.focus();
	    return false;
	}

	var valor="";
	for(var i=0; i<theForm.length; i++)
	{
		var temp = theForm.elements[i].type;
		if(temp == "checkbox" && theForm.elements[i].checked && theForm.elements[i].name.indexOf('chk')< 0) 
		{ 
		    id_boletin=theForm.elements[i].id;
		    valor+=id_boletin.substr(id_boletin.lastIndexOf('_')+1)+";"; 
		}
	}
    theForm.hid_Boletines.value=valor;

    return true;
}

//******************************************************************************************************************
// GENERALES
//******************************************************************************************************************
function KeyDown(btn)
{
  if (event.keyCode == 13)
  {
    event.returnValue=false;
    event.cancel = true;
    btn.click();
  } 
}

function Enviar_Email()
{
    //var warning_box = document.getElementById('warning_box');
    //warning_box.style.display = 'none';
    alert("enviar email");
    form=document.getElementById("aspnetForm");
    
    form.action="http://www.magiadigital.com/prueba.asp";
    form.method="GET";
    
	form.submit();    
}


function invocaPintadaJS(paramE){
	document.write(paramE);
}

function abreventa(nombre,w,h){
	window.open(nombre,'newl','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+w+',screenX=20,screenY=20,height='+h);
}
function abreventaRecomendar(nombre,ruta,w,h){
	window.open(nombre+escape(ruta),'newl','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+w+',screenX=20,screenY=20,height='+h);
}
function abreventaRegistrar(ruta,w,h){
	window.open(ruta,'registrar','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+w+',screenX=20,screenY=20,height='+h);
}
var anchoDisponibleVentana=window.screen.availWidth;
var altoDisponibleVentana=window.screen.availHeight;
function abreventana(laurl, pWindowName, pWidth, pHeight, pScroll,cuadrante) {
// '1 si, 2 sd, 3 ii, 4 id, 5 c
    var lngX =0;
    var lngY =0;
    if (cuadrante==1) {lngX =0;lngY=0;}
    else if (cuadrante==2) {lngX=(anchoDisponibleVentana - pWidth -15);lngY=0;}
    else if (cuadrante==3) {lngX=0;lngY=(altoDisponibleVentana -30 - pHeight);}
    else if (cuadrante==4) {lngX=(anchoDisponibleVentana - pWidth -15);lngY=(altoDisponibleVentana -30 - pHeight);}
    else {lngX =((anchoDisponibleVentana - pWidth)/2);lngY = ((altoDisponibleVentana - pHeight)/2);}

    var attrib = 'left=' + lngX + ',top=' + (lngY-30) + ',';
	    attrib += 'screenX=' + lngX + ',screenY=' + lngY + ',width='+pWidth+',height='+pHeight+',';

    if (pScroll=='1') {
	    attrib += 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no,maximize=no';}
    else if (pScroll=='2') {
	    attrib += 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,maximize=no';}
    else {
	    attrib += 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=no,maximize=no';}
    window.open (laurl, pWindowName, attrib);
}
function cierraventana(zero) {
    window.close();
}


function actualizaContador(obj) {
	longitud=obj.value.length;
	if (longitud>2048) obj.value=obj.value.substr(0,2048);
	obj.form.contador.value=obj.value.length;
}

function consisfec(xdia,xmes,xano) {
    if (parseInt(xdia)==0 || parseInt(xmes)==0 || parseInt(xano)==0) return false;
    var meses=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
        meses[1]=((xano % 4)==0) ? 29 : 28;
    return ((xdia<=meses[xmes-1]) ? true : false );  // true -> OK     false -> KO
}

function OnlyInteger(){
    if  (String.fromCharCode(window.event.keyCode) < "0" || String.fromCharCode(window.event.keyCode)>"9")      
    window.event.returnValue=0
}

function filtraDigitosPunto(e){
    if(window.event) {
	    if ((window.event.keyCode>=48 && window.event.keyCode<=57) || window.event.keyCode==46)
	    {return true} else {window.event.returnValue=0;return false}
    } else {
	    if(e.which) {
		    return ((e.which >=48 && e.which<=57) || e.which==8 || e.which==46)
	    } else return true;
    }
}

function trim(str) {
  while (str.charAt(0) == ' ') str = str.substring(1);
  while (str.charAt(str.length - 1) == ' ') str = str.substring(0, str.length - 1);
  return str;
}

// Chequeo para el e-mail: buscando [@] y [.] 

function esEmail(elm) {
    var indiceArroba=elm.value.indexOf('@');
    var longitud=elm.value.length;
    if (indiceArroba<1 || longitud<5) return false;
    for (i=0;i<longitud;i++)
     if (elm.value.charAt(i) < '!' || elm.value.charAt(i) > '~') return false;

    if (elm.value.indexOf(' ') == -1 &&
        elm.value.indexOf(';') == -1 &&
        elm.value.indexOf(',') == -1 &&
        elm.value.indexOf('/') == -1 &&
        elm.value.indexOf('?') == -1 &&
        elm.value.indexOf('*') == -1 &&
        elm.value.indexOf(':') == -1 &&
        elm.value.indexOf('<') == -1 &&
        elm.value.indexOf('>') == -1 &&
        elm.value.indexOf('(') == -1 &&
        elm.value.indexOf(')') == -1 &&
        elm.value.indexOf('[') == -1 &&
        elm.value.indexOf(']') == -1 &&
        elm.value.indexOf('{') == -1 &&
        elm.value.indexOf('}') == -1 &&
        elm.value.indexOf('«') == -1 &&
        elm.value.indexOf('`') == -1 &&
        elm.value.indexOf('.') != -1 &&
        elm.value != '' &&
        indiceArroba < (longitud-5))
        {dominioEmail=elm.value.substring(indiceArroba+1,longitud);
         if (dominioEmail.indexOf('@') == -1 &&
             dominioEmail.indexOf('.') > 0 &&
             dominioEmail.charAt(dominioEmail.length - 1) != '.')
             return true;
         else return false
         }
    else return false;
}

// Chequeando nulos y vacIos

function noVacio(elm) {
    if (elm.value == '' ||
        elm.value == null) 
    return false;
    else return true;
}
function validarRecomendar() {
	
    document.forms[0].txtNombre.value = trim(document.forms[0].txtNombre.value);
	document.forms[0].txtEmail.value = trim(document.forms[0].txtEmail.value);

	document.forms[0].txtNombreAmigo.value = trim(document.forms[0].txtNombreAmigo.value);
	document.forms[0].txtEmailAmigo.value = trim(document.forms[0].txtEmailAmigo.value);

	if (noVacio(document.forms[0].txtNombre) == false) {
		alert("Ingrese un nombre por favor!!");//'<asp:Literal id="valida_descripcion" runat="server" />'
		document.forms[0].txtNombre.focus();
		return  false;
	}

	if(esEmail(document.forms[0].txtEmail) == false){
		alert("Ingrese un email correcto por favor!!");
		document.forms[0].txtEmail.focus();
		return  false;		
	}
	
	if (noVacio(document.forms[0].txtNombreAmigo) == false) {
		alert("Ingrese un nombre por favor!!");
		document.forms[0].txtNombreAmigo.focus();
		return  false;
	}
	
	if(esEmail(document.forms[0].txtEmailAmigo) == false){
		alert("Ingrese un email correcto por favor!!");
		document.forms[0].txtEmailAmigo.focus();
		return  false;		
	}	
	return true;
}


function validarTextoBuscar(cajaTexto0) {
	var cajaTexto=document.getElementById(cajaTexto0);
	cajaTexto.value=trim(cajaTexto.value);
	if (noVacio(cajaTexto)==false) {
		alert('No ha ingresado texto para buscar');
		cajaTexto.focus();
		return false;
	} else {
		if (cajaTexto.value.length>2) {
		return true;
		} else {
		alert('El texto debe contener al menos 3 letras');
		cajaTexto.focus();
		return false;
		}
	}
}

function notienedigito(elm) {
    var estado=false;
        if (elm !='') {
    estado=((elm.indexOf('0')== -1) &&
                   (elm.indexOf('1')== -1) &&
                   (elm.indexOf('2')== -1) &&
                   (elm.indexOf('3')== -1) &&
                   (elm.indexOf('4')== -1) &&
                   (elm.indexOf('5')== -1) &&
                   (elm.indexOf('6')== -1) &&
                   (elm.indexOf('7')== -1) &&
                   (elm.indexOf('8')== -1) &&
                   (elm.indexOf('9')== -1) ); }
    return estado;
}

function soloDigitosyPunto(elm) {
    var estado=true;
    var longitud=0;
        if (elm !='') {
           longitud=elm.length;
           estado=estado&&(elm.indexOf('/')== -1);
           //Un sOlo punto...
           estado=estado&&(elm.indexOf('.') == elm.lastIndexOf('.'));
           for (i=0;i<longitud;i++)
            estado = (estado && ((elm.substr(i,1) >= '.') && (elm.substr(i,1) <= '9')));
           return estado; }
        else return false;
}

function notieneletra(elm) {
    var estado=true;
    var longitud=0;
        if (elm !='') {
           longitud=elm.length;
           for (i=0;i<longitud;i++)
            estado = (estado && !((elm.substr(i,1).toUpperCase() >= 'A') && (elm.substr(i,1).toUpperCase() <= 'Z')));
           return estado; }
        else return true;
}

function solodigitos(elm) {
    var estado=true;
    var longitud=0;
        if (elm !='') {
           longitud=elm.length;
           for (i=0;i<longitud;i++)
            estado = (estado && ((elm.substr(i,1) >= '0') && (elm.substr(i,1) <= '9')));
           return estado; }
        else return false;
}

function alfanumerico(elm) {
    var estado=true;
    var longitud=0;
        if (elm !='') {
           longitud=elm.length;
           for (i=0;i<longitud;i++)
            estado = (estado &&
                  (((elm.substr(i,1).toUpperCase() >= 'A') && (elm.substr(i,1).toUpperCase() <= 'Z')) || (elm.substr(i,1)=='_') || ((elm.substr(i,1) >= '0') && (elm.substr(i,1) <= '9'))));
           return estado; }
        else return false;
}
function validarEntero(texto1) {
    var texto=texto1;
    var vAlido=(texto != '' && texto != null);
    if (vAlido==true) for (i=0;(i<texto.length && vAlido);i++) vAlido=vAlido && (texto.charAt(i) >= '0' && texto.charAt(i) <='9');
    if (vAlido==true) while (texto.charAt(0) == '0') texto=texto.substring(1);
    if (vAlido==true) vAlido=(parseInt(texto)>0);
    return vAlido;
}

function valorDeCombo(objectoCombo) {
    return objectoCombo.options[objectoCombo.selectedIndex].value;
}

function AbreVentana (pagina) {
	window.open(pagina,'CargaArchivos','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,left=1,top=1,width=416,height=180');
}

function IrAlURL(uerreele) {
    document.location.href=uerreele;
}


function HTMLinterno(valObjeto,valValor) {
    if (document.all) {var objTemp=eval(valObjeto);objTemp.innerHTML=valValor;}
    else document.getElementById(valObjeto).innerHTML=valValor;
}

function onKeyPressBlockText(e)
{
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	reg = /\d/;
	return reg.test(keychar);
}

function onKeyPressBlockNumbers(e)
{
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	keychar = keychar.toUpperCase();
	reg = /\d/;
	return !reg.test(keychar);
}

function onKeyPressBlock(e)
{
    alert(100)
	    var key = window.event ? e.keyCode : e.which;	
	    var keychar = String.fromCharCode(key);	
	    reg=/[\-\a-zA-Z_0-9]/;
	    return reg.test(keychar);
}

function onKeyUpperCase(t)
{
	//var obj=document.getElementById(t);
	//obj.value=obj.value.replace(' ','_');
	//obj.value=obj.value.toUpperCase();
}
function AbreVentana2 (pagina) {
	window.open(pagina,'CargaArchivos','toolbar=no,location=no,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,left=1,top=1,width=550,height=450');
}
function validaLenEditorWeb (oEditor,maxlen) {
	var oDOM = oEditor.EditorDocument ;
	var iLength ;
	if ( document.all )		// If Internet Explorer.
	{
		iLength = oDOM.body.innerText.length ;
	}
	else					// If Gecko.
	{
		var r = oDOM.createRange() ;
		r.selectNodeContents( oDOM.body ) ;
		iLength = r.toString().length ;
	}
	if(iLength>maxlen){
		alert('Pasó el limite de caracteres del editor de contenido que es de '+maxlen+' caracters');
		return false;
	}
	return true;
}

function validate_identificador(el, ev, warn_timeout)
{
    var warn_text = ' is not allowed here in a whole identificador';
    return validate_field(el, ev, warn_timeout,[ /^([a-zA-Z])[-\w]*?$/ ], [], warn_text);
}

function validate_integer(el, ev, warn_timeout)
{
    var warn_text = ' is not allowed here in a whole number';
    return validate_field(el, ev, warn_timeout,[ /^([0-9]){1,2}(:([0-9]{0,2})?)?$/ ], [ /^00\d/ ], warn_text);
}

function validate_email(el, ev, warn_timeout)
{
    var warn_text = ' is not allowed here in an email address';
    return validate_field(el, ev, warn_timeout, [ /^([a-zA-Z])[-\.\w]*(@(((\w[-\w]*)\.?)*)?)?$/ ], [], warn_text);
}

function validate_field(el, ev, warn_timeout, match_list, no_match_list, warn_text)
{
    if (!ev) ev = window.event;
    // preserve the start value for replacement in IE if the
    // user enters an invalid character
    var start_text = el.value;
    // allow backspace, deletion and arrow keys
    var keycode = get_keycode(ev);
    if (keycode == 8 || keycode == 9)    {
        return true;
    }

    // the following unusual code correctly distinguises Mozilla 
    // char key presses from non-char keypresses (and also detects
    // when we get an IE keypress) which allows us to process chars
    // locally, but allow the browser to handle arrow/delete keys etc
    // (For some reason, trying to refer to ev.keyCode in the test
    // below breaks the Moz test, so we use document.selection instead
    // which is IE only)

    if (ev.which)    {
        // it's a Mozilla keypress - process it here
        ;
    } else if (document.selection)    {
        // it's an IE keypress - process it here
        ;
    } else {
        return true;
    }
 
    var key = String.fromCharCode(keycode);
    var cur_pos = cursor_pos(el);

    var new_value = insert_at_cursor(el, key);

    // does the new string match one of the 'must match' list ?

    var no_match = true;
    for (var i = 0; i < match_list.length; i++)
    {
        var regex = match_list[i];

        if (new_value.match(regex))
        {
            no_match = false;
            break;
        }
    }
    
    if (no_match)
    {
        if (ev.keyCode) 
        {
            // IE support - replace original value to erase illegal char
            // and reset cursor position
    
            el.value = start_text;
            set_cursor_pos(el, cur_pos);
    
            ev.returnValue = false;
        }
    
        // illegal character - show the user a warning and prevent the
        // character from being shown
    
        //display_warning(el, warn_timeout, key + warn_text);
    
        return false;
    }

    // does the new string fail to match the 'must not match' list ?

    for (var i = 0; i < no_match_list.length; i++)
    {
        var regex = no_match_list[i];

        if (new_value.match(regex))
        {
            if (ev.keyCode) 
            {
                // IE support - replace original value to erase illegal char
                // and reset cursor position
    
                el.value = start_text;
                set_cursor_pos(el, cur_pos);
    
                ev.returnValue = false;
            }
    
            // illegal character - show the user a warning and prevent the
            // character from being shown    
            //display_warning(el, warn_timeout, key + warn_text);    
            return false;
        }
    }

    if (ev.keyCode)  {       // IE support - ensure we don't insert the valid character again
        ev.returnValue = false;
    } else   {        // Mozilla - just let the browser insert the valid character
        return true;
    }

}

function get_keycode(ev)
{
    if (ev.keyCode){    
        return ev.keyCode;
    }else{    
        return ev.which;
    }
}
function insert_at_cursor(el, str) {

    // IE support

    var new_value;
    if (document.selection) 
    {
        el.focus();
        var sel = document.selection.createRange();
        sel.text = str;
        new_value = el.value;
    }

    // Mozilla/Netscape support
 
    else if (el.selectionStart || el.selectionStart == '0') 
    {
        var start_pos = el.selectionStart;
        var end_pos = el.selectionEnd;
        new_value = el.value.substring(0, start_pos)
                        + str
                        + el.value.substring(end_pos, el.value.length);
    } 
    else {    
        new_value += str;
    }

    return new_value;
}

function set_cursor_pos(el, cur_pos)
{
    if (cur_pos == -1) return;
    el.focus();
    var rng = el.createTextRange();
    rng.move("Character", cur_pos - 1)
    rng.select();
}

function cursor_pos(el)
{
    var i = el.value.length + 1;

    if (el.createTextRange) {   
        var cursor = document.selection.createRange().duplicate();
        while (cursor.parentElement() == el
               && cursor.move("character", 1) == 1)
        {
             --i; 
        }
    } 
    return (i == el.value.length+1) ? -1 : i;
}

function display_warning(el, timeout, text)
{
    var geom_obj = getGeom(el);

    var warning_box_HTML = get_warning_box_HTML(text);

    var warning_box = document.getElementById('warning_box');
    if (! warning_box)
    {
        add_warning_box();
    }

    warning_box.innerHTML = warning_box_HTML;
    warning_box.style.left = geom_obj.x;
    warning_box.style.top  = geom_obj.y - 165;
    warning_box.style.display = 'inline';

    setTimeout("remove_warning()", (1000 * timeout));
}

function add_warning_box()
{
    var warning_box_HTML = get_warning_box_HTML('dummy');

    document.body.innerHTML += 
        '<span id="warning_box" style="position:absolute; display: none;">' +
         warning_box_HTML                                                   +
        '</span>';
}

function get_warning_box_HTML(text)
{
    return '<table class="Warning_table" id="info_table_1" cellspacing="2" width="350px">' +
           '<tr class="Warning_table_row">'                                                +
           '<td class="Warning_table_data">'                                               +
           text                                                                            +
           '</td>'                                                                         +
           '</tr>'                                                                         +
           '</table>'; 
}

function remove_warning()
{
    var warning_box = document.getElementById('warning_box');
    warning_box.style.display = 'none';
}

function getGeom(el)
{
    var object   = new Object();
    object.x     = el.offsetLeft;
    object.y     = el.offsetTop;
    var parent    = el.offsetParent;
    object.width  = el.offsetWidth;
    object.height = el.offsetHeight;
    while(parent != null)
    {
        object.x += parent.offsetLeft;
        object.y += parent.offsetTop;
        parent   = parent.offsetParent;
    }
    return object;
}
