﻿/*
------------------------------------------------------------------------------------------
© Digital Industry - 2008
Autor:		Rafael Cronemberger de Assis
Cliente: 	Klabin
------------------------------------------------------------------------------------------
*/

// Global Variables
var nmOpacity = 100;
var fgNs4 = (navigator.appName == 'Netscape') ? 1 : 0;

function showModal(stPage) {
    var args = new Object;
    args.window = window;
    showModalDialog(stPage, args);
}

function dynamicSimpleValidate(objForm) {
    var objElements = objForm.elements
    var nmElements = objForm.elements.length
    var objField;

    for (var nmInc = 0; nmInc < nmElements; nmInc++) {
        try {
            var objField = objElements[nmInc]

            var boValidate = new Boolean(objField.getAttribute('boValidate'))
            var stValidate = new String(objField.getAttribute('boValidate'))
            var stMsgError = new String(objField.getAttribute('stMsgError'))
            var stFieldType = new String(objField.getAttribute('stFieldType'))
            var stNome = new String(objField.name)
            var stValue = new String(objField.value)
        }

        catch (stError) {
            //alert(stError)
        }

        /* Validação Simples */
        if (stFieldType == 'null' || stFieldType == '') {
            if (stValidate == 'true' && stValue == '') {
                alert(stMsgError);
                objField.focus();
                return false;
            }

            /* Date */
        } else if (stFieldType == 'date') {
            if (CheckDate(stValue) == false) {
                alert(stMsgError);
                objField.focus();
                return false;
            }

            /* E-mail */
        } else if (stFieldType == 'email') {
            if (validateRegexEmail(stValue) == false) {
                alert(stMsgError);
                objField.focus();
                return false;
            }

            /* Numbers */
        } else if (stFieldType == 'number') {
            if (isNaN(stValue) || stValue == '') {
                alert(stMsgError);
                objField.focus();
                return false;
            }

            /* Select Multiple (Only for PHP) */
        } else if (stFieldType == 'select_multiple') {
            /* Check all fields. */
            selectElements(objField)

            /* CPF */
        } else if (stFieldType == 'cpf') {
            if (validaCPF(stValue) == false) {
                alert(stMsgError);
                objField.focus();
                return false;
            }
        }
        /* Hora */
        else if (stFieldType == 'time') {
            if (validaHora(stValue) == false) {
                alert(stMsgError);
                objField.focus();
                return false;
            }
        }
        else if (stFieldType == 'radio') {
            if (verificaRadio(objForm, stNome) == false) {
                alert(stMsgError);
                objField.focus();
                return false;
            }
        }

        else if (stFieldType == 'drop') {
            if (stValue == 'Selecione' || stValue == 'Nenhum Grupo Cadastrado') {
                alert(stMsgError);
                return false; 
            }

        }
    }
}

function selectElements(objElement) {
    var nnInc = 0;
    var nmCount = objElement.length;
    for (nmInc = 0; nmInc < nmCount; nmInc++) {
        objElement[nmInc].selected = true
    }
}

function redirectUser(stDestino) {
    document.location.href = (stDestino)
}

function openCenterPopup(stUrl, stWindowName, stParameters, nmWidth, nmHeight) {
    stWindowParameters = ', width=' + nmWidth + ', height=' + nmHeight + '';
    stParameters = stParameters += stWindowParameters;
    objPopUp = window.open(stUrl, stWindowName, stParameters)

    try {
        centerObject(objPopUp, nmWidth, nmHeight)
    } catch (ex) { }

    objPopUp.focus();
}

function centerObject(objElement, nmWidth, nmHeight) {
    try {
        /* Popups */
        var nmX = (screen.width - nmWidth) / 2;
        var nmY = (screen.height - nmHeight) / 2;

        objElement.moveTo(nmX, nmY)
    }
    catch (ex) {
        /* Elements */
        var nmLeft = (screen.width - nmWidth) / 2;
        var nmTop = ((screen.height - nmHeight) / 2) + (parseInt(document.documentElement.scrollTop) / 2);
        //var	nmTop 	= (	parseInt(document.body.scrollTop)	+	parseInt(document.body.offsetHeight / 2) );
        objElement.style.left = nmLeft;
        objElement.style.top = nmTop;
    }
}

function maskCurrency(objTextBox, stSeparadorMilesimo, stSeparadorDecimal, e) {
    var nmSep = 0;
    var stKey = '';
    var i = j = 0;
    var nmLen = nmLen2 = 0;
    var stCheck = '0123456789';
    var stAuxiliar = stAuxiliar2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;

    if (whichCode == 13) return true;
    stKey = String.fromCharCode(whichCode);

    if (stCheck.indexOf(stKey) == -1) return false;
    nmLen = objTextBox.value.length;

    for (i = 0; i < nmLen; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != stSeparadorDecimal)) break;

    stAuxiliar = '';

    for (; i < nmLen; i++)
        if (stCheck.indexOf(objTextBox.value.charAt(i)) != -1) stAuxiliar += objTextBox.value.charAt(i);

    stAuxiliar += stKey;
    nmLen = stAuxiliar.length;

    if (nmLen == 0) objTextBox.value = '';
    if (nmLen == 1) objTextBox.value = '0' + stSeparadorDecimal + '0' + stAuxiliar;
    if (nmLen == 2) objTextBox.value = '0' + stSeparadorDecimal + stAuxiliar;
    if (nmLen > 2) {
        stAuxiliar2 = '';

        for (j = 0, i = nmLen - 3; i >= 0; i--) {
            if (j == 3) {
                stAuxiliar2 += stSeparadorMilesimo;
                j = 0;
            }
            stAuxiliar2 += stAuxiliar.charAt(i);
            j++;
        }

        objTextBox.value = '';

        nmLen2 = stAuxiliar2.length;

        for (i = nmLen2 - 1; i >= 0; i--)
            objTextBox.value += stAuxiliar2.charAt(i);
        objTextBox.value += stSeparadorDecimal + stAuxiliar.substr(nmLen - 2, nmLen);
    }
    return false;
}

function resetDropDown(objDropDown) {
    objDropDown.options.length = 0;
}

function timeOut(nmSeconds, stAction) {
    window.setTimeout(stAction, nmSeconds);
}

function showHideElement(objElement, fgDisplay) {
    if (fgDisplay == 1)
        objElement.style.display = ''
    else
        objElement.style.display = 'none'
}

function BlockUnblockElement(objElement, fgBlock) {
    if (fgBlock == 1)
        objElement.disabled = false
    else
        objElement.disabled = true
}

function validateRegexEmail(stEmail) {
    if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(stEmail)) {
        return false;
    }
}

function displayFlash(nmWidth, nmHeight, stSwf) {
    document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="' + nmWidth + '" height="' + nmHeight + '" id="objFlash" align="middle">');
    document.write('<param name="allowScriptAccess" value="sameDomain" /><param name="wmode" value="transparent" />');
    document.write('<param name="movie" value="' + stSwf + '" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><embed src="' + stSwf + '" wmode="transparent" quality="best" width="' + nmWidth + '" height="' + nmHeight + '" name="div" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash"/>');
    document.write('</object>');
}

function FieldOnFocus(objForm, stFieldValue) {
    if (eval(objForm).value == stFieldValue) {
        eval(objForm).value = '';
    }
}

function FieldOnBlur(objForm, stFieldValue) {
    if (eval(objForm).value == '') {
        eval(objForm).value = stFieldValue;
    }
}

function Ltrim(stValue) {
    var re = /\s*((\S+\s*)*)/;
    return stValue.replace(re, '$1');
}

function Rtrim(stValue) {
    var re = /((\s*\S+)*)\s*/;
    return stValue.replace(re, '$1');
}

function Trim(stValue) {
    stValue = Ltrim(Rtrim(stValue));
    return stValue.replace(/^\s+|\s+$/g, '');
}

function FadeElement(idElement, stMethod, nmVelocity) {
    var objElement = document.getElementById(idElement)
    if (objElement) {
        if (nmOpacity == 100 && stMethod == 'in') nmOpacity = 10; fgContinue = true; showHideElement(objElement, 1);

        if (nmOpacity > 0) {
            if (stMethod == 'in') {
                fgDisplay = 1;
                nmOpacity += 10;
            } else {
                fgDisplay = 0;
                nmOpacity -= 10
            }
            fgContinue = true;
        } else {
            fgContinue = false;
        }

        if (nmOpacity == 100 && stMethod == 'in') fgContinue = false;

        if (fgContinue == true) {
            objElement.style.filter = 'alpha(style=0,opacity=' + nmOpacity + ')';
            objTimer = setTimeout("FadeElement('" + idElement + "', '" + stMethod + "', " + nmVelocity + ");", nmVelocity);
        } else {
            showHideElement(objElement, fgDisplay)
            nmOpacity = 100;
            objElement.style.filter = 'alpha(style=0,opacity=' + nmOpacity + ')';
        }
    }
}

function BlockChars() {
    if (!fgNs4) {
        if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
    } else {
        if (event.which < 45 || event.which > 57) returnfalse;
    }
}

function BlockSpecialChars() {
    if (!fgNs4) {
        if ((event.keyCode > 32 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65) || (event.keyCode > 90 && event.keyCode < 97)) event.returnValue = false;
    } else {
        if ((event.which > 32 && event.which < 48) || (event.which > 57 && event.which < 65) || (event.which > 90 && event.which < 97)) return false;
    }
}

function DataChars() {
    if (!fgNs4) {
        if (event.keyCode < 48 || event.keyCode > 57) {
            event.returnValue = false;
        }
    }
}

function CheckDate(stDate) {
    var arrayDate = stDate.split("/");
    var stCheck = '0123456789';
    var stDateTemp = '';
    var stSeparator = '/';
    var nmDay = arrayDate[0];
    var nmMonth = arrayDate[1];
    var nmYear = arrayDate[2];
    var nmLoop = 0;
    var nmError = 0;
    var nmInc;
    for (nmInc = 0; nmInc < stDate.length; nmInc++) {
        if (stCheck.indexOf(stDate.substr(nmInc, 1)) >= 0) {
            stDateTemp = stDateTemp + stDate.substr(nmInc, 1);
        }
    }

    stDate = stDateTemp;
    if (stDate.substr(4, 4) != 4) nmErro = 1;
    //if (stDate.length == 6)	stDate = stDate.substr(0,4) + '20' + stDate.substr(4,2);
    //nmYear 	= stDate.substr(4,4);

    if (nmYear == 0) nmError = 1;

    if ((nmMonth < 1) || (nmMonth > 12)) nmError = 1;

    if (nmDay < 1) nmError = 1;
    if ((nmYear % 4 == 0) || (nmYear % 100 == 0) || (nmYear % 400 == 0)) nmLoop = 1;
    if ((nmMonth == 2) && (nmLoop == 1) && (nmDay > 29)) nmError = 1;
    if ((nmMonth == 2) && (nmLoop != 1) && (nmDay > 28)) nmError = 1;
    if ((nmDay > 31) && ((nmMonth == 1) || (nmMonth == 3) || (nmMonth == 5) || (nmMonth == 7) || (nmMonth == 8) || (nmMonth == 10) || (nmMonth == 12))) nmError = 1;
    if ((nmDay > 30) && ((nmMonth == 4) || (nmMonth == 6) || (nmMonth == 9) || (nmMonth == 11))) nmError = 1;
    //if ((nmDay == 0) && (nmMonth == 0) && (nmYear == 00)) nmError = 0; nmDay = ''; nmMonth = ''; nmYear = ''; stSeparator = '';

    if (stDate.length != 8 && stDate.length != 7) nmError = 1;

    if (nmError == 0) {
        return true;
    } else {
        return false;
    }
}

function mascaraData(objField) {
    var stDate = objField.value;
    if (stDate.length == 2) {
        stDate = stDate + '/';
        objField.value = stDate;
        return true;
    }
    if (stDate.length == 5) {
        stDate = stDate + '/';
        objField.value = stDate;
        return true;
    }
}

function resetForm(objForm) {
    objForm.reset();
}

function DeleteItem(stParameters) {
    if (confirm('Deseja realmente deletar o ítem selecionado?')) {
        location.href = (stParameters)
    }
}

function ConfirmaExclusao() {
    return confirm('Deseja excluir este registro?');
}

function Timer(nmSeconds, stAction) {
    window.setTimeout(stAction, nmSeconds);
}

function moveSelectItem(fbox, tbox) {
    var arrFbox = new Array();
    var arrTbox = new Array();
    var arrLookup = new Array();
    var i;
    for (i = 0; i < tbox.options.length; i++) {
        arrLookup[tbox.options[i].text] = tbox.options[i].value;
        arrTbox[i] = tbox.options[i].text;
    }

    var fLength = 0;
    var tLength = arrTbox.length;
    for (i = 0; i < fbox.options.length; i++) {
        arrLookup[fbox.options[i].text] = fbox.options[i].value;
        if (fbox.options[i].selected && fbox.options[i].value != "") {
            arrTbox[tLength] = fbox.options[i].text;
            tLength++;
        } else {
            arrFbox[fLength] = fbox.options[i].text;
            fLength++;
        }
    }

    arrFbox.sort();
    arrTbox.sort();

    fbox.length = 0;
    tbox.length = 0;

    var c;
    for (c = 0; c < arrFbox.length; c++) {
        var no = new Option();
        no.value = arrLookup[arrFbox[c]];
        no.text = arrFbox[c];
        fbox[c] = no;
    }

    for (c = 0; c < arrTbox.length; c++) {
        var no = new Option();
        no.value = arrLookup[arrTbox[c]];
        no.text = arrTbox[c];
        tbox[c] = no;
    }
}

function validaCPF(stCpf) {
    stCpf = stCpf.replace(".", "");
    stCpf = stCpf.replace(".", "");
    stCpf = stCpf.replace("-", "");
    valor = true;
    erro = new String;

    if (stCpf.length < 11) erro += "Preencha corretamente o número do seu CPF! \n\n";
    var nonNumbers = /\D/;
    if (nonNumbers.test(stCpf)) erro += "Preencha corretamente o número do seu CPF! \n\n";
    if (stCpf == "00000000000" || stCpf == "11111111111" || stCpf == "22222222222" || stCpf == "33333333333" || stCpf == "44444444444" || stCpf == "55555555555" || stCpf == "66666666666" || stCpf == "77777777777" || stCpf == "88888888888" || stCpf == "99999999999") {
        erro += "Número de CPF inválido!"
    }
    var a = [];
    var b = new Number;
    var c = 11;
    for (i = 0; i < 11; i++) {
        a[i] = stCpf.charAt(i);
        if (i < 9) b += (a[i] * --c);
    }
    if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11 - x }
    b = 0;
    c = 11;
    for (y = 0; y < 10; y++) b += (a[y] * c--);
    if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11 - x; }
    if ((stCpf.charAt(9) != a[9]) || (stCpf.charAt(10) != a[10])) {
        erro += "Número de CPF inválido!";
    }

    if (erro.length > 0) {
        return false
    }
}

function mascaraHora(objField) {
    var nmHora;
    nmHora = objField.value;
    if (nmHora.length == 2) {
        nmHora = nmHora + ':';
        objField.value = nmHora;
    }
}

function validaHora(stValue) {
    var nmHora = (stValue.substring(0, 2));
    var nmMin = (stValue.substring(3, 5));
    var nmErro = 0;
    if ((nmHora < 00 || nmHora > 23) || (nmMin < 00 || nmMin > 59)) {
        nmErro = 1;
    } else if (stValue.length != 5) {
        nmErro = 1;
    }
    if (nmErro == 1) {
        return false;
    }
}
function SomenteNumero(e) {
    var tecla = (window.event) ? event.keyCode : e.which;

    if ((tecla > 47 && tecla < 58))
        return true;
    else {
        if (tecla != 8)
            return false;
        else
            return true;
    }

}

function limpa_string(S) {
    // Deixa so' os digitos no número
    var Digitos = "0123456789";
    var temp = "";
    var digito = "";
    for (var i = 0; i < S.length; i++) {
        digito = S.charAt(i);
        if (Digitos.indexOf(digito) >= 0) { temp = temp + digito }
    }
    return temp
}

function verificaRadio(objForm, stNome) {
    var nmCount = 0, nmErro = 0;
    //validacao de radio buttons sem saber quantos sao
    for (nmInc = 0; nmInc < objForm.length; nmInc++) { // loop de elementos do formulário
        if (objForm.elements[nmInc].type == 'radio' && objForm.elements[nmInc].name == stNome) { // verifica se é do tipo radio e o nome é igual ao enviado
            nmCount++; // conta o número de radios com o mesmo nome
            if (objForm.elements[nmInc].checked == false) { // verifica se está checkado
                nmErro += 1;
            }
        }
    }
    if (nmCount == nmErro) {
        return false;
    } else {
        //return true;
    }
}

/* Valida itens do cadastro de usuários /cadastro/*/
function checkInformacao(objForm) {
    nmLength = objForm.length;
    var nmCount = 0; var nmInc;
    for (nmInc = 0; nmInc < nmLength; nmInc++) {
        if (objForm.elements[nmInc].type == 'checkbox') {
            if (objForm.elements[nmInc].checked == true) {
                nmCount++;
            }
        }
    }
    if (nmCount == 0) {
        return false;
    } else {
        return true;
    }
}

function validaData(objForm) {
    var nmDia, nmAno, nmMes;
    nmDia = objForm.nmDia.value;
    nmMes = objForm.nmMes.value;
    nmAno = objForm.nmAno.value;
    if (CheckDate(nmDia + "/" + nmMes + "/" + nmAno) == true) {
        if (checkInformacao(objForm) == false) {
            alert("Selecione uma opção para: \n'Onde voce busca informações sobre o festival?'");
            return false;
        } else {
            return dynamicSimpleValidate(objForm);
        }
    } else {
        alert('Favor preencher a Data de Nascimento corretamente')
        return false;
    }
}

function checkPdfLink(objForm) {
    var fgPdf = document.getElementById('fgPDF').checked;
    var fgLink = document.getElementById('fgLink').checked;
    var stPdf = document.getElementById('id_PDF').value;
    var stLink = document.getElementById('id_Link').value;
    nmErro = 0;
    if (fgPdf == true && stPdf == "") {
        alert('Nenhum PDF foi enviado');
        nmErro++
    } else if (fgLink == true && stLink == "") {
        alert('Favor preencher o campo Link');
        nmErro++
    }
    if (nmErro == 0) {
        if (dynamicSimpleValidate(objForm) != false) {
            objForm.submit();
        }
    }
}

function displayDhtmlFlash(largura, altura, arquivo, nmTime) {
    window.setTimeout("closeDhtml();", nmTime);

    document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="' + largura + '" height="' + altura + '" id="objDhtmlFlash" align="middle">');
    document.write('<param name="allowScriptAccess" value="sameDomain" /><param name="wmode" value="transparent" />');
    document.write('<param name="movie" value="' + arquivo + '" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><embed src="' + arquivo + '" wmode="transparent" quality="best" width="' + largura + '" height="' + altura + '" name="div" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash"/>');
    document.write('</object>');
}

function closeDhtml() {
    document.getElementById("objDhtmlFlash").style.display = "none";
    document.getElementById("divBannerTop").innerHTML = "";
}
