MSG_SELECCIONAR = "You must select a register of list";
MSG_ABANDONAR = "¿You sure to exit the application?";
MSG_TERMINADO = "Process finished!";
MSG_ELIMINAR = "You sure to remove this item?";
MSG_ELIMINADO = "Register has been removed!";
MSG_PROBLEMAS = "Some problems with the process.";
/*
 * Function validarAcceso
 * Este bloque de código es utilizado para habilitar el keyup {ENTER}
 */
Element.Events.keyenter = {
    base: 'keyup',
    condition: function(e){
        // We can basically put any logic here.
        // In this example we return true, when the pressed key is the
        // Enter-Button so the keyenter event gets fired.
        return e.key=='enter';
    }
};

$create = function(tag){
    return document.createElement(tag);
}

/*
 * Function validarAcceso
 * Esta función es utilizada para realizar la validación de los datos de acceso enviados
 * desde la sección de ingreso restringido.
 */
function validarAcceso(){
    $('notificacion').innerHTML = "";
    if($('usuario').value == ''){
        $('notificacion').innerHTML = "Insert username";
        $('usuario').focus();
    }
    else if($('clave').value == ''){
        $('notificacion').innerHTML = "Insert password";
        $('clave').focus();
    }else{
        $('notificacion').innerHTML = "Sending access data...";
        requestLogin = new Request({
            url:"inc/sesiones.php",
            onSuccess: function(txt){
                eval(txt);
                if(responseAJAX){
                    if(responseAJAX['ACCESO'] == 'OK'){
                        $('notificacion').innerHTML = "Access ok!";
                        tb_show();
                        setTimeout("window.location.href = 'product-list.php';",500);
                    }else{
                        $('notificacion').innerHTML = "Access denied!";    
                    }
                }
            },
            onFailure: function(){
                $('notificacion').innerHTML = "Requested error, retry";
            }
        });
        requestLogin.send({method:'post',data:'accion=login&usuario='+$('usuario').value+"&clave="+$('clave').value});
    }
}

function abandonar(){
    onComplete = {onComplete:function(ret){ if(ret){
        requestLogin.send({method:'post',data:'accion=logout'});
    } }}
    CONFIRM("<h1>Control system</h1><em>Validation to exit the application</em><br/><p>¿You sure to exit the application?</p>",onComplete)
    requestLogin = new Request({
        url:"inc/sesiones.php",
        onSuccess: function(txt){
            eval(txt);
            if(responseAJAX){
                if(responseAJAX['LOGOUT'] == 'OK')
                    window.location.href = 'store.php';
            }
        },
        onFailure: function(){
            $('notificacion').innerHTML = "Request error, retry";
        }
    });
}

/***** Función para utilizar el filtrado desde la cabecera de las grillas ******/
/*
    Recibe en la instancia el objeto de la grilla
    function cargaFiltros es para setear los ids de los campos a filtrar y las columnas relacionadas
    function filtrar es para aplicar el filtrado a la grilla
*/
function filterBy(objGrilla){
    this.idsFiltros = false; this.cantFiltros = 0;
    this.idsColumnsas  = false; this.numColumna = false;
    this.objetoGrilla = objGrilla; this.vecFiltros = new Array();
    
    this.cargaFiltros = function(filtros,columnas){
        this.idsFiltros = filtros.split(",");
        this.idsColumnsas = columnas.split(",");
        this.cantFiltros = this.idsColumnsas.length;
        for(i=0; i<this.cantFiltros; i++){
            this.objetoGrilla.makeFilter(this.idsFiltros[i],this.idsColumnsas[i]);
        }
    }
    
    this.filtrar = function(objetoEvento){
        divPadre = objetoEvento.parentNode;
        idDiv = divPadre.id;
        tVal = divPadre.childNodes[0].value.toLowerCase();
        
        for(i=0; i<this.cantFiltros; i++){
            if(this.idsFiltros[i] == idDiv){
                this.numColumna = this.idsColumnsas[i];
                this.vecFiltros[this.numColumna] = tVal;
                break;
            }
        }
        for (var i = 0; i < this.objetoGrilla.getRowsNum(); i++) {
            this.objetoGrilla.setRowHidden(this.objetoGrilla.getRowId(i), false);
            for(j=0; j<this.vecFiltros.length; j++){
                if(this.vecFiltros[j] && this.vecFiltros[j] != ""){
                    tStr = this.objetoGrilla.cells2(i, j).getValue().toString().toLowerCase();
                    if (tStr.indexOf(this.vecFiltros[j]) != 0){
                        this.objetoGrilla.setRowHidden(this.objetoGrilla.getRowId(i), true);
                        break;
                    }
                }
            }
        }
    }
}

/* Funcion utilizada para reemplazar la anticuada forma de alerts de los navegadores */
ALERT = function(texto,propiedades){
    Sexy.alert(texto,propiedades);
}

/* Funcion utilizada para reemplazar la anticuada forma de alerts de los navegadores */
INFO = function(texto,propiedades){
    Sexy.info(texto,propiedades);
}

/* Funcion utilizada para reemplazar la anticuada forma de alerts de los navegadores */
CONFIRM = function(texto,propiedades){
    Sexy.confirm(texto,propiedades);
}

PROMPT = function(texto,propiedades){
    Sexy.prompt(texto,'' , propiedades );
}

// NUMERIC DATA VALIDATION INCLUDING FLOAT OR INTEGER DETECTION
function onlyNumbers(evt,campo,dec,textoMostrar,sinsigno){
    var b1=0;
    var cont=0;
    var m1=-1;
    if(!dec){  dec=0; }
    var  field = document.getElementById(campo).value;
    evt = (evt) ? evt : event;
    //Desabilita el pegado con el uso de ( Control ) o ( shift + insert )
    if (evt.shiftKey) {if (evt.keyCode==45)return false;}else if (evt.ctrlKey) {return false;}
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
    if (charCode > 31  && (charCode < 48 || charCode > 57) && charCode!= 46  && charCode!= 45 ) {
        ALERT("<h1>"+textoMostrar+"</h1><p><em>This field must be numeric</em></p>");
        return false;
    }
    b1= field.indexOf(".",0); //UBICACION DEL "." EN EL STRING
    m1=field.indexOf("-",0); //UBICACION DEL "-" EN EL STRING
    if(charCode == 45){
        if(sinsigno){
            ALERT("<h1>"+textoMostrar+"</h1><p><em>This field must be positive</em></p>");
            return false;
        }else{
            if(m1!=-1){
                ALERT("<h1>"+textoMostrar+"</h1><p><em>No se acepta otro signo</em></p>");
                return false;
            }else{
                if(field.length != 0){
                    ALERT("<h1>"+textoMostrar+"</h1><p><em>El lugar del signo es incorrecto</em></p>");
                    return false;
                }
            }
        }
    }
    var entero=0;
    if(dec != 0){ // CONTROL DEL PRIMER
        if(b1 != -1){ // CONTROL PARA EVITAR UN SEGUNDO . INCORRECTO.
            if(charCode==46){
                ALERT("<h1>"+textoMostrar+"</h1><p><em>No se acepta otro punto</em></p>");
                return false;
            }else{
                // CONTADOR DE DECIMALES
                cont=field.length-b1;
                // CONTROL DE DECIMALES, NO PUEDE SUPERAR LA CANTIDAD ESPECIFICADA EN DEC.
                if(cont > dec){
                    if (charCode!=8){
                        ALERT("<h1>"+textoMostrar+"</h1><p><em>Sobrepasa la cantidad de los decimales</em></p>");
                        return false;
                    }
                }
            }
        }
    }else{ // CONTROL PARA CAMPOS SIN DECIMALES
        if(charCode==46){  //arreglo por Odaimar Carrillo
            // Developer Colombia - julio 2007
            ALERT("<h1>"+textoMostrar+"</h1><p><em>El campo debe ser entero</em></p>");
            //end
            return false;
        }
    }
    return true;
} //end onlyNumbers

function compareD(a, b){
	/** 
	* Validate that both dates have data
	*/
	d1 = a.split("/");
	d2 = b.split("/");
	var y1=parseInt(d1[2],10);
	var m1=parseInt(d1[1],10);
	var d1=parseInt(d1[0],10);
	var y2=parseInt(d2[2],10);
	var m2=parseInt(d2[1],10);
	var d2=parseInt(d2[0],10);
	if ((y1 < y2) || ((y1 == y2)&&((m1<m2) || ((m1==m2)&&(d1 < d2))))) return -1; //simplified version of above code
	if ((y1 == y2)&&(m1 == m2)&&(d1 == d2)) return 0;
	if ((y1 > y2) || ((y1 == y2)&&((m1 > m2)) || ((m1 == m2)&&(d1 > d2))))  return 1; //simplified version of above code
}

//FUNCION: quitNumericFormat
//Quita los separadores a un valor dado
//PARAMETROS:
//value   : valor a convertir
//SALIDA:
//        Si es un valor con separadores, lo retorna como
//        una cadena del valor con representaciï¿½ estï¿½dar
//        de javascript. Si no tenï¿½ el formato, devuelve cero.
function quitNumericFormat(value) { //Retorna el valor que se le pasa sin marcadores de miles (como string, hay que convertirlo con parseFloat)
	value = value.replace(/\./g,'');
	value = value.replace(/\,/g,'.');
	return value;
} //END quitNumericFormat

//FUNCION: applyNumericFormat
//Aplica el fomato de separadores a un valor dado
//PARAMETROS:
//value   : valor a aplicar separadores
//dig     : longitud mï¿½ima para la parte entera del nmero (opcional)
//dec     : longitud mï¿½ima para la parte decimal de la cantidad (opcional)
//positive: el valor debe ser estrictamente positivo (true)
//          o puede ser positivo y negativo (por defecto)
//SALIDA:
//        Retorna el valor con los separadores incluidos
function applyNumericFormat(value, dig, dec, positive){
	var temp;
	var result;
	var sign;
	//if (isNumericFormat(value, dig, dec, positive)) { return value; }
	if (isNaN(value) || value==undefined) { return value; }
	temp = value.toString().split('.'); //Separar parte entera y parte decimal
	//Si es un nmero negativo quitar el signo para formatear el valor y volver a ponerlo al final
	if (temp[0].charAt(0) == '-'){
		if (!positive) { sign = '-'; } else { sign = ''; }
		temp[0] = temp[0].substr(1,temp[0].length-1)
	} else { sign = ''; }
	//Si una parte es vacï¿½ asigna por defecto, si supera la longitud indicada se trunca o redondea en caso de decimales
	if (!temp[0]) { temp[0] = '0'; }
	if (dig && temp[0].length > dig) { temp[0] = temp[0].substring(0, dig); }
	if (dec){
		if (!temp[1]) { temp[1] = ''; }
		if (temp[1].length > dec){
			var quitDec = temp[1].length - dec;
			var tmp = Math.round(parseInt(temp[1], 10)/Math.pow(10, quitDec));
			temp[1] = tmp.toString();
		}else{
			var addZeros = dec - temp[1].length;
			for (var i=0; i<addZeros; i++) { temp[1] += '0'; }
		}
	}
	//Poner los separadores de la manera correcta en el campo
	result = '';
	for (var i = temp[0].length-3; i > 0; i-=3){ result = '.' + temp[0].substr(i,3) + result; }
	result = temp[0].substr(0, (temp[0].length % 3 != 0)? temp[0].length % 3: 3) + result; //Unir ltimo segmento del nmero
	result = (temp[1])? sign + result + ',' + temp[1] : sign + result;
	return result;
} //END applyNumericFormat

/////////////////////////////////////////////////////////////////////////////////////////////////////
//FUNCIONES PARA TRABAJAR CON PUNTOS COMO SEPARADORES DE MILES Y COMAS COMO SEPARADORES DE DECIMALES
//            Control de cualquier longitud de decimales y mejora del control
//            para la parte entera.
//            Posibilidad de restringir las cantidades a sï¿½o positivas
//            Optimización de funciones
//            Corrección de errores menores
//FUNCION: setNumericMask
//Esta función configura un campo referenciado por el id, como un campo
//numérico con separadores de miles (.) y decimales (,)
//asigna lo necesario en sus eventos onKeyPress, onKeyUp y onBlur
//PARAMETROS:
//id      : identificador del input a configurar con la máscara
//digits  : longitud máxima para la parte entera del nmero
//dec     : longitud máxima para la parte decimal de la cantidad
//label   : etiqueta con que se identificará el campo en mensajes al usuario
//positive: si (true) la cantidad sí puede ser positiva
//          en caso contrario (false) puede ser positiva y negativa
function setNumericMask(id, digits, dec, label, positive){
	//Si no se proporciona el nmero de dígitos pero los demás parámetros si, se asume infinito
	if (typeof(dec) == 'string' && !label){
		positive = label;
		label    = dec;
		dec      = digits;
		digits   = 10;
	}
	if (!digits)   { dec      = 10;    }
	if (!dec)      { dec      = 2;     }
	if (!label)    { label    = id;    }
	if (!positive) { positive = false; }
	var obj = document.getElementById(id);
		obj.numericMask = true;
		obj.digits = digits;
	obj.decimals = dec;
		obj.label = label;
		obj.positive = positive;
	obj.onkeypress = function(event){
			if (this.oldonkeypress && this.oldonkeypress!='') { this.oldonkeypress(event) }
			return NumericMask(event, this.id, this.digits, this.decimals, this.label, this.positive);
	}
	obj.oldonblur = obj.onblur;
	obj.onblur = function(event){
		if (this.oldonblur && this.oldonblur!='') { this.oldonblur(event) }
		this.value = quitNumericFormat(this.value);
		this.value = applyNumericFormat(this.value, this.digits, this.decimals, this.positive);
	}
	obj.oldonkeyup = obj.onkeyup;
	obj.onkeyup = function(event){
		if (this.oldonkeyup && this.oldonkeyup!=''){ this.oldonkeyup(event); }
		applyNumericMask(this.id, this.digits, this.decimals, this.label, this.positive);
	}
}

//FUNCION: applyNumericMask
//Aplica la máscara de separadores de miles a un input
//que está siendo digitado por el usuario. Corrige la
//posición del cursor si es necesario
//PARAMETROS:
//id      : identificador del input a enmascarar
//digits  : longitud máxima para la parte entera del nmero
//dec     : longitud máxima para la parte decimal de la cantidad
function applyNumericMask(id, digits, dec){
	var value;
	var result;
	var temp;
	var hasComma;
	var caretPos;
	var sign;
	var fixPos;
	fixPos = 0;
	value = result = $(id).value;
	if (result == '' || result == '-') { return true; }
	hasComma = (result.indexOf(',')!=-1);
	temp     = result.split(',');
	caretPos = doGetCaretPosition(document.getElementById(id));
	//Si es un nmero negativo quitar el signo para formatear el valor y volver a ponerlo al final
	if (temp[0].charAt(0) == '-') { sign = '-';  temp[0] = temp[0].substr(1,temp[0].length-1)} else { sign = ''; }
	//Limipiar los viejos separadores que no aplican
	if (temp[0]){ temp[0] = temp[0].replace(   /\./g, ''); } else { temp[0] = '0'; }
	if (temp[1]){ temp[1] = temp[1].replace(/[^\d]/g, ''); } else { temp[1] =  ''; }
	//Validar los tamaños de dígitos y decimales
	if (temp[0].length > digits) { temp[0] = temp[0].substr(0, digits); fixPos = 1;  }
	if (temp[1].length > dec   ) { temp[1] = temp[1].substr(0, dec); }
	//Poner los separadores de la manera correcta en el campo
	result = '';
	for (var i = temp[0].length-3; i > 0; i-=3){ result = '.' + temp[0].substr(i,3) + result; }
	if (temp[0].length % 3 != 0) { result = temp[0].substr(0, temp[0].length % 3) + result; //join last segment length != 3
	}else{ result = temp[0].substr(0, 3) + result; } //join last segment length == 3
	result = (hasComma)? sign + result + ',' + temp[1] : sign + result;
	$(id).value = result;
	//Saber si será necesario aplicar corrección a posición del cursor luego de reformatear
	if (!((caretPos == 1 && sign == '') || (caretPos == 2 && sign == '-'))){
		if (result.length > value.length) { caretPos++; } //si se incremento la longitud al formatear
		else if (result.length < value.length) { caretPos--; } //si se redujo la longitud al formatear
	}
	caretPos += fixPos;
	setCaretToPos(id,caretPos);
}

//VALIDA DUPLICIDAD DE PUNTOS EN LOS CAMPOS CON DECIMAL
function doGetCaretPosition(oField) {
	// Initialize
	var iCaretPos = 0;
	// IE Support
	if (document.selection) {
		// Set focus on the element
		//oField.focus ();
		// To get cursor position, get empty selection range
		var oSel = document.selection.createRange();
		// Move selection start to 0 position
		oSel.moveStart ('character', -oField.value.length);
		// The caret position is selection length
		iCaretPos = oSel.text.length;
	}else if (oField.selectionStart || oField.selectionStart == '0'){iCaretPos = oField.selectionStart;}
	// Return results
	return (iCaretPos);
}

//FUNCION: setCaretToPos
// Ubica el cursor dentro de un input en la posición indicada
//PARAMETROS:
//id : input sobre el que se quiere posicionar el cursor
//pos: posición en la que debe ubicarse el cursor, por defecto toma 0 (inicio),
//     puede suministrarse los valores especiales 'begin' y 'end'
function setCaretToPos(id,pos){
	if (typeof(pos) =='string'){
		if (pos == 'end') { pos = $(id).value.length;
		} else { pos = 0; }
	} else if (pos == undefined || pos == null) { pos = 0; }
	setSelectionRange(id, pos, pos);
} //END

//FUNCION: setSelectionRange
//Funcion para seleccionar un rango de texto dentro de un input mediante código
//PARAMETROS:
//id            : input sobre el cual hacer la selección de texto
//selectionStart: posición de inicio de la selección
//selectionEnd  : posición de fin de la selección
function setSelectionRange(id, selectionStart, selectionEnd){
	var input = document.getElementById(id);
	if (input.setSelectionRange) {
		input.focus();
		input.setSelectionRange(selectionStart, selectionEnd);
	}else if (input.createTextRange) {
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
} //END setSelectionRange

/* ::::::::::::::::::::::::::::::::::: END ::::::::::::::::::::::::::::::::::: */
