// Mensaje de carga de las paginas
var pg_loading = "Loading ...";
var pg_form_loading="Procesando los datos, por favor espere ...";
var app_name = "Aplicacion:";

//----------------------------------------------------------------
// Funciones para manejar el Stack
//----------------------------------------------------------------
var stackHistory = new Array();
var stackPointer = -1;

function stackPrint() {
    var text = "";
    for (var i = 0; i <= stackPointer; i++)
        text += stackHistory[stackPointer]+", ";
    alert(text);
}

function stackPush(value) {
    stackPointer++;
    stackHistory[stackPointer] = value;
//    stackPrint();
}

function stackPop() {
    --stackPointer;
//    stackPrint();
    return stackPointer >= 0 ? stackHistory[stackPointer] : null;
}

function stackBack() {
    $(".divcontent").hide();
    var divname = stackPop();
    if (divname == null)
        $("#dBody").show();
    else
        $("#"+divname).show();
}

function stackReset() {
    $("#dBody").show();
    $(".divcontent").hide();
    stackPointer = -1;
}

//----------------------------------------------------------------
// Navegacion con stack
//----------------------------------------------------------------
function stackAjaxNav(url, args, dst) {
    $("#dBody").hide();
    $(".divcontent").hide();
    stackPush(dst);
    $("#"+dst).html('<p align="center"><br><img src="skins/spinner.gif"> '+pg_loading+'</p>');
    $("#"+dst).show();
    ajaxNavNotHistory(url, args, dst);
}

//----------------------------------------------------------------
// Remplaza los $n por cambios de línea
//----------------------------------------------------------------
function replaceReturn(msg) {
    while (msg.indexOf("$n") > -1)
        msg = msg.replace("$n", "\n");
    return msg;
}

//----------------------------------------------------------------
// Remplaza en "msg" los "oldChar" por "newChar"
//----------------------------------------------------------------
function replaceAll(msg, oldChar, newChar) {
    while (msg.indexOf(oldChar) > -1)
        msg = msg.replace(oldChar, newChar);
    return msg;
}

//----------------------------------------------------------------
// Obtiene un formulario por el nombre
//----------------------------------------------------------------
function getFormByName(name) {
    for (var i = 0; i < document.forms.length; i++)
        if (document.forms[i].name == name)
            return document.forms[i];
    return null;
}

//----------------------------------------------------------------
// Obtiene el indice del un formulario por el nombre
//----------------------------------------------------------------
function getFormIndexByName(name) {
    for (var i = 0; i < document.forms.length; i++)
        if (document.forms[i].name == name)
            return i;
    return -1;
}

//----------------------------------------------------------------
// Obtiene el elemento de un formulario por el "id"
//----------------------------------------------------------------
function getFormElementById(form, id) {
    for (var i = 0; i < form.length; i++)
        if (form[i].id == id)
            return form[i];
    return null;
}

//----------------------------------------------------------------
// Muestra los datos de un formulario en formato name(type) = value
//----------------------------------------------------------------
function showFormByIndex(indx) {
    if (document.forms[indx] != null)
        showForm(document.forms[indx]);
    else
        alert("No existe el formulario: "+indx);
}

function showForm(form) {
    var text = "Formularios: "+document.forms.length+"\n";
    for (var i = 0; i < document.forms.length; i++)
        text = text + document.forms[i].name + " (" + document.forms[i].id + ")\n";
    text = text + "\n"+form.name + "\n";
    for (i = 0; i < form.length; i++)
        text = text + form.elements[i].name + " (" + form.elements[i].type + ") = "+form.elements[i].value + "\n";
    alert(text);
}

//----------------------------------------------------------------
// Retorna los datos de un formulario
//----------------------------------------------------------------
function  getFormData(form, dynCheck) {
    if (dynCheck == "undefined")
        dynCheck = false;
    var netscape = navigator.userAgent.indexOf("Firefox")!=-1;
    var data = '';
    var item;
    for (var i = 0; i < form.length; i++) {
        if (!dynCheck && form.elements[i].type == "checkbox")
            data = data + '&' + form.elements[i].name + '=' + (form.elements[i].checked ? "true" : "false");
        else if (form.elements[i].value != null && form.elements[i].name != null) {
            item = escape(form.elements[i].value);
            // Escape del + y &
            while (item.indexOf('+') >= 0) 
                item = item.replace('+', '%2B');
            while (item.indexOf('&') >= 0)
                item = item.replace('&', '%26');
            data = data + '&' + form.elements[i].name + '=' + item;
        }
    }
    return data.substring(1);
}

//----------------------------------------------------------------
// Envia un formulario y carga el resultado
//----------------------------------------------------------------
function submitForm(url, form, area, check, clear, async) {
    if (check == "undefined")
        check = false;
    if (clear == "undefined")
        clear = false;
    if (async == "undefined")
        async = true;
    if (check) {
        if (!checkForm(form))
            return false;
    }
    var data = getFormData(form);
    if (clear)
        $("#"+area).html('<p align="center"><br><img src="images/spinner.gif"> '+pg_form_loading+'</p>');
    $.ajax({async: async, type: 'POST', url: getAjaxURL(url, null), data: data,
            success: function(html) { $("#"+area).html(html); },
            error: function(XMLHttpRequest, textStatus, errorThrown) { alert('ERROR\nPage:'+url+';dst='+area+'\ninfo = '+XMLHttpRequest.statusText+'\ntextStatus = '+textStatus+'\nerrorThrown = '+errorThrown); }
    });
    return true;
}

//----------------------------------------------------------------
// Envia un formulario y carga el resultado
//----------------------------------------------------------------
function submitFormBlockUI(url, form, area, check, top) {
    if (check) {
        if (!checkForm(form))
            return false;
    }
    if (top == "undefined")
        $.blockUI({ css: {border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .5, color: '#fff', zIndex:999999},
                    message: '<b>'+pg_form_loading+'</b>' });
    else
        $.blockUI({ css: {top: top, border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .5, color: '#fff'},
                    message: '<b>'+pg_form_loading+'</b>' });
    $.ajax({type: 'POST', url: getAjaxURL(url, null), data: getFormData(form, false),
            success: function(html) {
                $("#"+area).html(html);
                $.unblockUI();
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { alert('ERROR\nPage:'+url+';dst='+area+'\ninfo = '+XMLHttpRequest.statusText+'\ntextStatus = '+textStatus+'\nerrorThrown = '+errorThrown); }
    });
    return true;
}

//----------------------------------------------------------------
// Hace un preproseso de los checkbox generados dinamicamente.
// Adiciona ;S o ;N indicando si esta seleccionado o no
//----------------------------------------------------------------
function submitDynamicCheckboxesBlockUI(url, form, area) {
    for (var i = 0; i < form.length; i++) {
        if (form.elements[i].type == "checkbox") {
            form.elements[i].value = form.elements[i].value + ";"+(form.elements[i].checked ? "S" : "N");
        }
    }
    $.blockUI({ css: {border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .5, color: '#fff'},
                message: '<b>'+pg_form_loading+'</b>' });
    $.ajax({type: 'POST', url: getAjaxURL(url, null), data: getFormData(form, true),
            success: function(html) {
                $("#"+area).html(html);
                $.unblockUI();
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { alert('ERROR\nPage:'+url+';dst='+area+'\ninfo = '+XMLHttpRequest.statusText+'\ntextStatus = '+textStatus+'\nerrorThrown = '+errorThrown); }
    });
    return true;
}

//----------------------------------------------------------------
// Hace submit de un dialogo
//----------------------------------------------------------------
function submitDialog(url, form, area, check) {
    if (check == "undefined")
        check = null;
    if (check != null) {
        if (!check(form))
            return false;
    }
    $.ajax({type: 'POST', url: getAjaxURL(url, null), data: getFormData(form),
            success: function(html) { $("#"+area).html(html); },
            error: function(XMLHttpRequest, textStatus, errorThrown) { alert('ERROR\nPage:'+url+';dst='+area+'\ninfo = '+XMLHttpRequest.statusText+'\ntextStatus = '+textStatus+'\nerrorThrown = '+errorThrown); }
    });
    return true;
}

//----------------------------------------------------------------
// Muestra un dialogo con el contenido de un "Action"
//----------------------------------------------------------------
function openDialog(url, arg, dst) {
    ajaxNavSyncNotHistory(url, arg, dst);
    $('#'+dst).dialog('open');
}

//----------------------------------------------------------------
// Valida un entero
//----------------------------------------------------------------
function restoreEditStyle(val) {
    $("#"+val.id).css({backgroundColor:clEdit, color:clFontColor});
}

//----------------------------------------------------------------
// Valida un entero
//----------------------------------------------------------------
function validateInt(val, msg, dst, validNull) {
    if (validNull && val.value == '') {
        $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
        return true;
    }
    if (val.value.match(/^\d+$/) == null || isNaN(parseInt(val.value))) {
        $("#"+val.id).css( {backgroundColor:clEditError, color:clFontErrColor } );
        addErrorInfo(msg, dst);
        return false;
    }
    $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
    val.value = parseInt(val.value);
    return true;
}

//----------------------------------------------------------------
// Valida un real
//----------------------------------------------------------------
function validateFloat(val, msg, dst, validNull) {
    if (validNull && val.value == '') {
        $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
        return true;
    }
    var error = true;
    if (val.value.match(/^\d*\.{0,1}\d*$/) != null || val.value.match(/^\d*\,{0,1}\d*$/) != null) {
        val.value = val.value.replace(',', '.');
        error = false;
    }
    if (error || isNaN(parseFloat(val.value))) {
        $("#"+val.id).css( {backgroundColor:clEditError, color:clFontErrColor} );
        addErrorInfo(msg, dst);
        return false;
    }
    $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
    val.value = parseFloat(val.value);
    return true;
}

//----------------------------------------------------------------
// Valida una fecha
//----------------------------------------------------------------
function validateDate(val, msg, dst, validNull) {
    if (validNull && val.value == '') {
        $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
        return true;
    }
    var result = Date.fromString(val.value);
    if (!result) {
        $("#"+val.id).css( {backgroundColor:clEditError, color:clFontErrColor} );
        addErrorInfo(msg, dst);
        return false;
    }
    val.value = result.asString();
    $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
    return true;
}

//----------------------------------------------------------------
// Valida una cadena
//----------------------------------------------------------------
function validateString(val, msg, dst, validNull) {
    if (validNull && val.value == '') {
        $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
        return true;
    }
    if (val.value == "") {
        $("#"+val.id).css( {backgroundColor:clEditError, color:clFontErrColor} );
        addErrorInfo(msg, dst);
        return false;
    }
    $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
    return true;
}

//----------------------------------------------------------------
// Valida una direccion de Email
//----------------------------------------------------------------
function validateEmail(val, msg, dst, validNull) {
    if (validNull && val.value == '') {
        $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
        return true;
    }
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if (pattern.test(val.value)) {
        $("#"+val.id).css( {backgroundColor:clEditOK, color:clFontColor});
        return true;
    } else {
        $("#"+val.id).css( {backgroundColor:clEditError, color:clFontErrColor} );
        addErrorInfo(msg, dst);
        return false;
    }
}

//--------------------------------------------------------------------
// Valida una cuenta bancanria
//--------------------------------------------------------------------
function validateBankAccount(i_entidad,i_oficina,i_digito,i_cuenta){
    var wtotal,wcociente, wresto;
    if (i_entidad.length != 4 || i_oficina.length != 4 || i_digito.length != 2 || i_cuenta.length != 10)
        return false;
    wtotal = i_entidad.charAt(0) * 4;
    wtotal += i_entidad.charAt(1) * 8;
    wtotal += i_entidad.charAt(2) * 5;
    wtotal += i_entidad.charAt(3) * 10;
    wtotal += i_oficina.charAt(0) * 9;
    wtotal += i_oficina.charAt(1) * 7;
    wtotal += i_oficina.charAt(2) * 3;
    wtotal += i_oficina.charAt(3) * 6;
    // busco el resto de dividir wtotal entre 11
    wcociente = Math.floor(wtotal / 11);
    wresto = wtotal - (wcociente * 11);
    wtotal = 11 - wresto;
    if (wtotal == 11)
        wtotal = 0;
    if (wtotal == 10)
        wtotal = 1;
    if (wtotal != i_digito.charAt(0))
        return false;
    //hemos validado la entidad y oficina
    //-----------------------------------
    wtotal = i_cuenta.charAt(0) * 1;
    wtotal += i_cuenta.charAt(1) * 2;
    wtotal += i_cuenta.charAt(2) * 4;
    wtotal += i_cuenta.charAt(3) * 8;
    wtotal += i_cuenta.charAt(4) * 5;
    wtotal += i_cuenta.charAt(5) * 10;
    wtotal += i_cuenta.charAt(6) * 9;
    wtotal += i_cuenta.charAt(7) * 7;
    wtotal += i_cuenta.charAt(8) * 3;
    wtotal += i_cuenta.charAt(9) * 6;

    // busco el resto de dividir wtotal entre 11
    wcociente = Math.floor(wtotal / 11);
    wresto = wtotal - (wcociente * 11);
    wtotal = 11 - wresto;
    if (wtotal == 11){wtotal=0;}
    if (wtotal == 10){wtotal=1;}

    if (wtotal != i_digito.charAt(1))
        return false;
    // hemos validado la cuenta corriente
    return true;
}

//----------------------------------------------------------------
// Adiciona informacion a los errores
//----------------------------------------------------------------
function addErrorInfo(msg, dst) {
    if (msg != "") {
        var text = $("#"+dst).html();
        $("#"+dst).html(text+'<img src="images/bullet.gif" border="0">&nbsp;'+msg+'<br>');
    }
}

//----------------------------------------------------------------
// Carga una pagina desde el servidor
//----------------------------------------------------------------
function ajaxNav(pag, args, dst) {
    if (dst == null || dst == '' || dst == 'null')
        redirect(getAjaxURL(pag, args));
    else {
        $("#"+dst).html('<p align="center"><br><img src="images/spinner.gif"> '+pg_loading+'</p>');
        $.historyLoad('ajPg='+getAjaxURL(pag, args)+';dst='+dst);
    }
}

//----------------------------------------------------------------
// Carga una pagina (sin incluirla en history)
//----------------------------------------------------------------
function ajaxNavNotHistory(pag, args, dst, clear, callback) {
    //alert("pag = "+pag+", args = "+args+", dst = "+dst);
    if (clear)
        $("#"+dst).html('<p align="center"><br><img src="images/spinner.gif"> '+pg_loading+'</p>');
        $.ajax({ url: getAjaxURL(pag, args), cache: false,
             success: function(html){
                $("#"+dst).html(html);
                if (callback != null)
                    callback();
             },
            error: function(XMLHttpRequest, textStatus, errorThrown) { alert('ERROR\nPage:'+getAjaxURL(pag, args)+';dst='+dst+'\ninfo = '+XMLHttpRequest.statusText+'\ntextStatus = '+textStatus+'\nerrorThrown = '+errorThrown); }
    });
}

function ajaxNavSyncNotHistory(pag, args, dst, clear, callback) {
    //alert("pag = "+pag+", args = "+args+", dst = "+dst);
    if (clear)
        $("#"+dst).html('<p align="center"><br><img src="images/spinner.gif"> '+pg_loading+'</p>');
    $.ajax({ url: getAjaxURL(pag, args), cache: false, async : false,
             success: function(html){
                $("#"+dst).html(html);
                if (callback != null)
                    callback();
             },
            error: function(XMLHttpRequest, textStatus, errorThrown) { alert('ERROR\nPage:'+getAjaxURL(pag, args)+';dst='+dst+'\ninfo = '+XMLHttpRequest.statusText+'\ntextStatus = '+textStatus+'\nerrorThrown = '+errorThrown); }
    });
}

//----------------------------------------------------------------
// Carga las paginas (utilizando el history)
//----------------------------------------------------------------
var ajaxLoad = function (hash) {
    var args = hash.split(';');
    var url = null;
    var dst = null;
    for (i = 0; i < args.length; i++) {
        if (args[i].indexOf('ajPg=') == 0)
            url = args[i].substring(5);
        if (args[i].indexOf('dst=') == 0)
            dst = args[i].substring(4);
    }
    if (url != null && dst != null) {
        $.ajax({ url: url, cache: false,
                 success: function(html){ $("#"+dst).html(html); },
                 error: function(XMLHttpRequest, textStatus, errorThrown) { alert('ERROR\nPage:'+url+';dst='+dst+'\ninfo = '+XMLHttpRequest.statusText+'\ntextStatus = '+textStatus+'\nerrorThrown = '+errorThrown); }
        });
    }
};

//----------------------------------------------------------------
// Algoritmo criptografico SHA1
//----------------------------------------------------------------
function SHA1(msg) {

	function rotate_left(n,s) {
		var t4 = ( n<<s ) | (n>>>(32-s));
		return t4;
	}

	function lsb_hex(val) {
		var str="";
		var i;
		var vh;
		var vl;

		for( i=0; i<=6; i+=2 ) {
			vh = (val>>>(i*4+4))&0x0f;
			vl = (val>>>(i*4))&0x0f;
			str += vh.toString(16) + vl.toString(16);
		}
		return str;
	}

	function cvt_hex(val) {
		var str="";
		var i;
		var v;

		for( i=7; i>=0; i-- ) {
			v = (val>>>(i*4))&0x0f;
			str += v.toString(16);
		}
		return str;
	}


	function Utf8Encode(string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	}

	var blockstart;
	var i, j;
	var W = new Array(80);
	var H0 = 0x67452301;
	var H1 = 0xEFCDAB89;
	var H2 = 0x98BADCFE;
	var H3 = 0x10325476;
	var H4 = 0xC3D2E1F0;
	var A, B, C, D, E;
	var temp;

	msg = Utf8Encode(msg);

	var msg_len = msg.length;

	var word_array = new Array();
	for( i=0; i<msg_len-3; i+=4 ) {
		j = msg.charCodeAt(i)<<24 | msg.charCodeAt(i+1)<<16 |
		msg.charCodeAt(i+2)<<8 | msg.charCodeAt(i+3);
		word_array.push( j );
	}

	switch( msg_len % 4 ) {
		case 0:
			i = 0x080000000;
		break;
		case 1:
			i = msg.charCodeAt(msg_len-1)<<24 | 0x0800000;
		break;

		case 2:
			i = msg.charCodeAt(msg_len-2)<<24 | msg.charCodeAt(msg_len-1)<<16 | 0x08000;
		break;

		case 3:
			i = msg.charCodeAt(msg_len-3)<<24 | msg.charCodeAt(msg_len-2)<<16 | msg.charCodeAt(msg_len-1)<<8	| 0x80;
		break;
	}

	word_array.push( i );

	while( (word_array.length % 16) != 14 ) word_array.push( 0 );

	word_array.push( msg_len>>>29 );
	word_array.push( (msg_len<<3)&0x0ffffffff );


	for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {

		for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
		for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);

		A = H0;
		B = H1;
		C = H2;
		D = H3;
		E = H4;

		for( i= 0; i<=19; i++ ) {
			temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}

		for( i=20; i<=39; i++ ) {
			temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}

		for( i=40; i<=59; i++ ) {
			temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}

		for( i=60; i<=79; i++ ) {
			temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}

		H0 = (H0 + A) & 0x0ffffffff;
		H1 = (H1 + B) & 0x0ffffffff;
		H2 = (H2 + C) & 0x0ffffffff;
		H3 = (H3 + D) & 0x0ffffffff;
		H4 = (H4 + E) & 0x0ffffffff;

	}

	temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

	return temp.toLowerCase();

}

//---------------------------------------------------------------------
// Muestra el dialogo de captura de un texto
//---------------------------------------------------------------------
var dlgOkButton = null;
function dlgGetText(title, msg, buttonOk) {
    dlgOkButton = buttonOk;
    $('#tdDlgGetTextLabel').html(msg);
    $('#dlgGetText').dialog("option", "title", title);
    $('#dlgGetText').dialog('open');
}

function dlgGetMemo(title, msg, buttonOk) {
    dlgOkButton = buttonOk;
    $('#tdDlgGetMemoLabel').html(msg);
    $('#dlgGetMemo').dialog("option", "title", title);
    $('#dlgGetMemo').dialog('open');
}

//----------------------------------------------------------------
// Redirecciona a una URL
//----------------------------------------------------------------
function redirect(url) {
    window.location.href = url;
}

function redirectAction(pag, args) {
    window.location.href = getAjaxURL(pag, args);
}

//----------------------------------------------------------------
// Abre una ventana para hacer las traducciones                                                                 
//----------------------------------------------------------------
function openTranslation(table, id, dst, size, mode) {
    if (size == null)
        size = '30';
    if (mode == null)
        mode = 'text';
    $("#"+dst).html('<p align="center"><br><img src="images/spinner.gif"> Cargando ...</p>');
    $("#"+dst).slideDown("slow");
    ajaxNavNotHistory('/Traducciones.action?action=load', 'table='+table+'&id='+id+'&size='+size+'&mode='+mode+'&dst='+dst, dst);
}

//----------------------------------------------------------------
// Envia el fichero al servidor
//----------------------------------------------------------------
function sendFileToServer(form, msg, dstInfo, msgConfirm) {
    if (msgConfirm != null) {
        var asw = confirm(msgConfirm);
        if (!asw)
            return;
    }
    $("#"+dstInfo).html('<img src="images/spinner.gif"> '+msg);
    form.op.value = 'load';
    form.submit();
}

//--------------------------------------------------------------------
// Muestra el mensaje de respuesta del servidor
//--------------------------------------------------------------------
function setFileuploadResult(dlg, msg, dstInfo) {
    if (msg == null || msg == '')
        $("#"+dlg).dialog('close');
    else
        $("#"+dstInfo).html(msg);
}

//--------------------------------------------------------------------
// Escribe informacion de LOG (Consola de errores)
//--------------------------------------------------------------------
function writeDebug(text, level) {
    try {
        switch (level) {
            case "warn" :
                console.warn(app_name, text);
                break;
            case "error" :
                console.error(app_name, text);
                break;
            default:
                console.log(app_name, text);
        }
    } catch(e) {
    }
}

//----------------------------------------------------------------
// Abre una ventana de overlay
//----------------------------------------------------------------
var currentOverlayApi = null;
function openOverlay(url, args, dOverlay, x, y) {
    if (x == null) {
        x = $(window).width() - $(window).width() / 2 - $('#'+dOverlay).width() / 2;
        y = $(window).height() - $(window).height() / 2 - $('#'+dOverlay).height() / 2;
    }
    if (url != null)
        ajaxNavSyncNotHistory(url, args, dOverlay);
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        $(".overlay_p").css({width:"650px"});
        $(".overlay").css({width:"650px"});
        $(".overlay_big").css({width:"650px"});
        $(".overlay_top").css({width:"650px", height:"270px"});
        $(".overlay_cuad").css({width:"380px", height:"270px"});
    }
    currentOverlayApi = $('#'+dOverlay).overlay({
        //effect: 'apple',
        top: y,
        left: x,
        expose: { color: '#000000', loadSpeed: 200, opacity: 0.5},
        closeOnClick: false,
        api: true }).load();
}

var currentOverlayCallback = null;
function openOverlayDialog(url, args, dOverlay, callback) {
    currentOverlayCallback = callback;
    openOverlay(url, args, dOverlay);
}

function showOverlayMsg(msg) {
    var x = $(window).width() - $(window).width() / 2 - $('#dlgMsgInfo').width() / 2;
    var y = $(window).height() - $(window).height() / 2 - $('#dlgMsgInfo').height() / 2;
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        $(".overlay_p").css({width:"650px"});
        $(".overlay").css({width:"650px"});
        $(".overlay_big").css({width:"650px"});
        $(".overlay_top").css({width:"650px", height:"270px"});
        $(".overlay_cuad").css({width:"380px", height:"270px"});
    }
    $("#dMsgInfo").html(msg);
    currentOverlayApi = $('#dlgMsgInfo').overlay({
        //effect: 'apple',
        top: y,
        left: x,
        expose: { color: '#000000', loadSpeed: 200, opacity: 0.5},
        closeOnClick: false,
        api: true }).load();
}

$.tools.validator.fn("[type=time]", "Please supply a valid time", function(input, value) {
	return /^\d\d:\d\d$/.test(value);
});

$.tools.validator.fn("[data-equals]", "Value not equal with the $1 field", function(input) {
	var name = input.attr("data-equals"),
		 field = this.getInputs().filter("[name=" + name + "]");
	return input.val() == field.val() ? true : [name];
});

$.tools.validator.fn("[minlength]", function(input, value) {
	var min = input.attr("minlength");

	return value.length >= min ? true : {
		en: "Please provide at least " +min+ " character" + (min > 1 ? "s" : ""),
		fi: "Kentän minimipituus on " +min+ " merkkiä"
	};
});

$.tools.validator.localizeFn("[type=time]", {
	en: 'Please supply a valid time',
	fi: 'Virheellinen aika'
});


$(document).ready(function () {
    $.historyInit(ajaxLoad);
});



