// portal.js

// anula o voltar do navegador
history.forward(1);

function beginRequest(sender, args) {
    $.blockUI();
}

function pageLoading(sender, args) {

}

function pageLoaded(sender, args) {
}

function endRequest(sender, args) {
    $.unblockUI();
    if (args.get_error() != undefined) {
        var errorMessage;
        if (args.get_response().get_statusCode() == '200') {

            if (args.get_response().get_responseData().indexOf('SessaoEncerrada') > -1) {
                errorMessage = "A sua sessao com o servidor foi reiniciada e esta janela sera fechada !\n\nPor favor, faca seu login novamente na tela inicial do portal.";
            }
            else
                errorMessage = args.get_error().message;
        }
        else {
            errorMessage = '### Um erro inesperado aconteceu ###';
        }
        
        args.set_errorHandled(true);
        alert(errorMessage);

        if (args.get_response().get_responseData().indexOf('SessaoEncerrada') > -1)
            FechaJanela();

        return;
    }
}

void function redimensiona() {
    var descwidth = 10; 				// Desconto
    var availwidth = parseInt(document.body.offsetWidth); //janela
    var dimwidth = 800 - descwidth; 	// Desejado

    var lwidth = ((availwidth - dimwidth) / 2) - 1;
    var rwidth = ((availwidth - dimwidth) / 2) + 1;

    if (lwidth < 0)
        lwidth = 0;

    if (rwidth < 0)
        rwidth = 0;

    var availheight = parseInt(screen.availHeight - 2);
    var dimheight = 598;

    document.getElementById("fgeral").style.width = dimwidth + lwidth + rwidth;
    document.getElementById("fleft").style.width = lwidth;
    document.getElementById("fright").style.width = rwidth;
    document.getElementById("fmiddle").style.width = dimwidth;
    if (document.getElementById("imgtopo")) document.getElementById("imgtopo").style.width = dimwidth;
    menuleft = lwidth;
}

function RetornaFormCaller(ctrls, vlrs) {
    // os vlrs chegam em escape pois alguns contem "'" e são unescaped somente no form destino
    var i, retval, expr = "";

    for (i = 0; i < ctrls.length; i++) {
        if (vlrs[i].substr(0, 1) != '.')
            expr += "document.all['" + ctrls[i] + "'].value=unescape('" + vlrs[i] + "'); ";
        else
            expr += "document.all['" + ctrls[i] + "']" + unescape(vlrs[i]);
    }
    self.opener.setTimeout(expr, 0);
    self.close();
    return false;
}

function Maximiza() {
    moveTo(0, 0);
    resizeTo(screen.width, screen.height - 27);
}

function AbreFramePrincipal(url, fecharjanelaatual) {
    var janelas = [window, window.opener, window.parent, window.top];

    var frame = null;

    for (var i = 0; i < 4; i++)
        if (janelas[i] != null) {
        if (janelas[i].name == "SWAgafarmaFrame")
            frame = janelas[i];
        else if (janelas[i].SWAgafarmaFrame != null)
            frame = janelas[i].SWAgafarmaFrame;

        if (frame != null) {
            frame.location = url;

            if (fecharjanelaatual) {
                window.opener = null;
                window.close();
            }
            return;
        }
    }
    alert('A janela principal do sistema não foi localizada e por isso esta página não será redirecionada automaticamente.\n\nPor favor, saia e entre novamente neste portal !');
}

function isEMailValido(email) {
    return email.search(/^[^@]+@[^@]+\.[a-z]{2,}$/) != -1 || email == "";
}

function ContaErro(val, cond) {
    val.style.visibility = cond ? "visible" : "hidden";
    return cond ? 1 : 0;
}

function GeraErro(cond, mens) {
    return cond ? (mens + '\n') : '';
}

function AcertaCampoData(oText) {
    if (isDataVazia(oText.value))
        oText.value = "";
}

function EliminaBrancos(fld) {
    var result = "";
    for (i = 0; i < fld.length; i++)
        if (fld.charAt(i) != " ")
        result += fld.charAt(i);
    return result;
}

function isDataVazia(sDate) {
    str = EliminaBrancos(sDate);
    return (str == "" || str == "//" || str == "//::" || str == "//:")
}

function isDataValida(sDate) {
    return validateDate(sDate, "W", "A") || isDataVazia(sDate);
}

function AbreDialogo(sDialogo, oArgs, sHeight, sWidth) {
    sHeight = (parseInt(sHeight) + 20) + "px"; ;
    sWidth = (parseInt(sWidth) + 20) + "px"; ;
    return window.showModalDialog(sDialogo, oArgs, "dialogHeight:" + sHeight + "; dialogWidth:" + sWidth + "; " +
				"edge: Raised; center: Yes; help: No; resizable: No; status: No;");
}

function ChecaValor(txt) {
    cVirg = 0;
    for (i = 0; i < txt.value.length; i++) {
        ch = txt.value.charAt(i);
        if (ch == ',')
            cVirg++;
        if (cVirg > 1 || !((ch >= '0' && ch <= '9') || ch == ',')) {
            alert('Valor Invalido !');
            txt.focus();
            return false;
        }
    }
    return true;
}

function Status(mens, tempo) {
    oInterval = null;
    function LimpaStatus() {
        window.status = '';
        clearInterval(oInterval);
    }

    window.status = mens;
    if (tempo != null)
        oInterval = setInterval(LimpaStatus, tempo);
}

function CloseForm() {
    window.open('blank.aspx', 'SWAgafarmaFrame')
}

function EnterKeyDown() {
    if (event.keyCode == 13)
        if ((event.srcElement.tagName.toUpperCase() == "SELECT") ||
			(event.srcElement.tagName.toUpperCase() == "INPUT") &&
			((event.srcElement.type.toUpperCase() == "TEXT") ||
				(event.srcElement.type.toUpperCase() == "PASSWORD") ||
				(event.srcElement.type.toUpperCase() == "RADIO") ||
				(event.srcElement.type.toUpperCase() == "CHECKBOX")
			))
        event.keyCode = 9;

    if (event.ctrlKey && event.keyCode == 78) {
        alert("Teclas CTRL+N bloqueadas !");
        event.keyCode = 0;
        event.returnValue = false;
    }
}

function KeyPress() {
    if ((event.srcElement.tagName.toUpperCase() == "INPUT" && event.srcElement.type.toUpperCase() != "FILE") ||
		 event.srcElement.tagName.toUpperCase() == "TEXTAREA") {
        // minusculo em campo normal ?
        if ((event.keyCode >= 97) &&
			(event.keyCode <= 122) &&
			(event.srcElement.id.toUpperCase().indexOf("EMAIL") == -1) &&
			(event.srcElement.id.toUpperCase().indexOf("_LWR") == -1))
            event.keyCode = event.keyCode - 32;
        // maiusculo em email ?
        else if ((event.keyCode >= 65) &&
				(event.keyCode <= 90) &&
				(event.srcElement.id.toUpperCase().indexOf("EMAIL") != -1))
            event.keyCode = event.keyCode + 32;

        if (event.keyCode >= 127 && (event.srcElement.id.toUpperCase().indexOf("_LWR") == -1))
            event.keyCode = 0;
    }
}

function FechaJanela() {
    javascript: window.opener = '';
    window.close();
}

function AbreJanela(Url, Janela, ScrollBars, Resizable, Topo, Esquerda, Larg, Alt) {
    feat = "status=yes, channelmode=no, directories=no, fullscreeen=no, location=no, menubar=no,";

    if (Topo != null)
        feat += "top=" + Topo.toString();

    if (Esquerda != null)
        feat += "left=" + Esquerda.toString();

    if (Larg != null)
        feat += "width=" + Larg.toString();

    if (Alt != null)
        feat += "height=" + Alt.toString();

    feat += ",scrollbars=" + (ScrollBars == false ? "no" : "yes");

    feat += ",resizable=" + (Resizable == false ? "no" : "yes");

    return window.open(Url, Janela, feat, true);
}

function AbreJanelaMax(Url, Janela, ScrollBars, Resizable) {
    return AbreJanela(Url, Janela, ScrollBars, Resizable, 0, 0, screen.width, screen.height);
}

function ZeroTrim(value) {
    var re = /0*(\d*)/;
    return value.replace(re, "$1");
}

function LTrim(value) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}

function RTrim(value) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}

function trim(value) {
    return LTrim(RTrim(value));
}


