﻿//--------------------------------------------------------
// Serve para abrir páginas numa nova janela
// Se o link na DropDown da master page for de outro site
//--------------------------------------------------------
function UpdateURL(objS) {
    var selected = objS.options[objS.selectedIndex].value
    if (selected.indexOf("http") != -1) {
        var selectedUrl = selected.substring(0, selected.indexOf("/", selected.indexOf("//") + 2));
        if (selectedUrl == "")
            selectedUrl = selected;

        var siteUrl = document.location.hostname;
        var siteUrl = siteUrl.substring(0, siteUrl.indexOf("/", siteUrl.indexOf("//") + 2));
        if (siteUrl == "")
            siteUrl = document.location.hostname;

        if (selectedUrl.indexOf(siteUrl) == -1)
            document.getElementById('link').target = "_blank";
    }
    document.getElementById('link').href = objS.options[objS.selectedIndex].value;
}

//------------------------------------
//forms framework functions
//-----------------------------------

function validatorNIF(source, arguments) {
    var valid = true;
    var nif = arguments.Value;

    if (isNaN(nif) || (nif.length < 9) || (nif == "000000000"))
        valid = false;
    else {
        var caracter = nif.substr(0, 1);
        if ((caracter == 1) || (caracter == 2) || (caracter == 5) || (caracter == 6) || (caracter == 8) || (caracter == 9)) {
            var checkDigit = caracter * 9;
            var i;
            for (i = 2; i <= 8; i++)
                checkDigit += nif.charAt(i - 1) * (10 - i);

            checkDigit = 11 - (checkDigit % 11);
            if (checkDigit >= 10)
                checkDigit = 0;

            if (checkDigit != nif.charAt(8))
                valid = false;
        }
    }
    arguments.IsValid = valid;
}

function ValidatorGetValue(id) {
    var control;
    control = document.getElementById(id);
    if (typeof (control.value) == "string") {
        return control.value;
    }
    if (typeof (control.tagName) == "undefined" && typeof (control.length) == "number") {
        var j;
        for (j = 0; j < control.length; j++) {
            var inner = control[j];
            if (typeof (inner.value) == "string" && (inner.type != "radio" || inner.status == true)) {
                return inner.value;
            }
        }
    }
    return "";
}


//custom validator function

function validarCIL(val) {





    var erro = false;
    var cil = new Array(9);
    var Wi = new Array(9);
    var cilaux;



    //cilaux = getControlo(val.controltovalidate);
    cilaux = ValidatorGetValue(val.attributes["controltovalidate"].nodeValue);


    if (val.MasterField) {
        if (val.AllowEmptyField && cilaux == "" && getControlo(val.MasterField).selectedIndex == 1)
            return true;
    }



    nZeros = 10 - cilaux.length;  //estava 10 - cilaux.length;

    zeroEsquerda = "";

    for (k = 0; k < nZeros; k++)
        zeroEsquerda += "0";

    cilaux = zeroEsquerda + cilaux;


    if (isNaN(cilaux)) //|| (cilaux.length != 10))
    {
        erro = true;
    } else {

        //Carregar array cil

        for (c = 0; c <= cilaux.length - 1; c++)
            cil[c] = cilaux.charAt(c);

        //Pesos de cada digito 
        Wi[0] = 9;
        Wi[1] = 8;
        Wi[2] = 7;
        Wi[3] = 6;
        Wi[4] = 5;
        Wi[5] = 4;
        Wi[6] = 3;
        Wi[7] = 2;
        Wi[8] = 1;

        total = 0;
        for (i = 0; i < 9; i++) {

            total += cil[i] * Wi[i];
        }

        total += parseInt(cil[0]);

        result = total / 9;   //DIVISAO
        resto = total % 9;  //divisao inteira

        if (resto == 0) {

            checkdigito = 9;
        }
        else {
            checkdigito = resto;
        }

        cilCK = cil[9];

        //esta função não interessa
        if (checkdigito != cilCK) {
            erro = false;
        } else {
            erro = true;
        }
    }
    return erro;
}

//custom validator function
function validaCamposObrigatoriosDiv(val) {
    if (!valida)
        return true;
    var vCtrl = document.getElementById(val.controltovalidate)
    var aux = val.CamposObrigatorios.split(';');
    var campos = aux[vCtrl.selectedIndex].split(',');

    if (campos == "") {
        return false;
    }
    for (c = 0; c <= campos.length - 1; c++) {
        if (val.ValidaValoresNumericos) {
            if (getControlo(campos[c]).value == "" || isNaN(getControlo(campos[c]).value))
                return false;
        }

        else {
            if (getControlo(campos[c]).value == "")
                return false;
        }

    }
    return true;
}



//set style in controls
function SetResto(campos, vCtrl, set) {
    if (!valida)
        return;
    var aux = campos.split(';');
    var campos = aux[vCtrl.selectedIndex].split(',');
    if (campos == "") {
        return false;
    }
    for (c = 0; c <= campos.length - 1; c++) {
        var controlo = getControlo(campos[c])
        if (controlo.value == "") {
            WebForm_AppendToClassName(controlo, 'errorInput');
            WebForm_AppendToClassName(GetLabel(controlo), 'necessary');
        }
        else {
            if (campos[c] != "dummy") {
                WebForm_RemoveClassName(controlo, 'errorInput');
                WebForm_RemoveClassName(GetLabel(controlo), 'necessary');
            }
        }

        if (vCtrl.selectedIndex != 0) {
            if (c == 0 && controlo.value == "") {
                WebForm_AppendToClassName(getControlo("opcao" + vCtrl.selectedIndex), 'necessary')
            }
            if (c == 0 && controlo.value != "") {
                WebForm_RemoveClassName(getControlo("opcao" + vCtrl.selectedIndex), 'necessary')
            }
        }
        else {
            if (c == 0 && controlo.value == "") {
                WebForm_AppendToClassName(controlo.previousSibling.previousSibling, 'necessary')
            }
            if (c == 0 && controlo.value != "") {
                WebForm_RemoveClassName(controlo.previousSibling.previousSibling, 'necessary')
            }
        }
    }
    //remove style from validator control parent
    if (campos != "") {
        WebForm_RemoveClassName(GetLabel(vCtrl), 'necessary');
        WebForm_RemoveClassName(vCtrl, 'errorInput');
    }

}



function ValidatorUpdateIsValid() {
    Page_IsValid = AllValidatorsValid(Page_Validators);
    SetValidatorStyles();
}

//set  jquery validator style
function SetValidatorStyles() {
    var i;

    // clear all  
    for (i = 0; i < Page_Validators.length; i++) {
        var inputControl = document.getElementById(Page_Validators[i].controltovalidate);
        WebForm_RemoveClassName(inputControl, 'errorInput');
        WebForm_RemoveClassName(GetLabel(inputControl), 'necessary');

        //custom validator
        if (Page_Validators[i].attributes["CamposObrigatorios"]) {
            SetResto(Page_Validators[i].attributes["CamposObrigatorios"].nodeValue, inputControl, false);
        }
    }
    // set invalid
    for (i = 0; i < Page_Validators.length; i++) {
        inputControl = document.getElementById(Page_Validators[i].controltovalidate);
        if (!Page_Validators[i].isvalid) {
            if ((inputControl.value == "" && valida == true) || inputControl.value != "") {
                WebForm_AppendToClassName(inputControl, 'errorInput');
                WebForm_AppendToClassName(GetLabel(inputControl), 'necessary');
            }
            //custom validator
            if (Page_Validators[i].attributes["CamposObrigatorios"]) {
                SetResto(Page_Validators[i].attributes["CamposObrigatorios"].nodeValue, inputControl, true);
            }

        }
    }
    valida = false;
}


// Validator classes in order to not use control.js
function WebForm_AppendToClassName(element, className) {
    var currentClassName;
    if (!element) {
        return;
    }
    else {
        currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';

        className = WebForm_TrimString(className);
        var index = currentClassName.indexOf(' ' + className + ' ');
        if (index === -1) {
            element.className = (element.className === '') ? className : element.className + ' ' + className;
        }
    }
}
function WebForm_RemoveClassName(element, className) {
    if (!element) {
        return;
    }
    else {
        var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
        className = WebForm_TrimString(className);
        var index = currentClassName.indexOf(' ' + className + ' ');
        if (index >= 0) {
            element.className = WebForm_TrimString(currentClassName.substring(0, index) + ' ' +
                currentClassName.substring(index + className.length + 1, currentClassName.length));
        }
    }

}

function WebForm_TrimString(value) {
    return value.replace(/^\s+|\s+$/g, '')
}



function GetLabel(inputControl1) {
    while (inputControl1.nodeName != "LABEL") {
        inputControl1 = inputControl1.previousSibling;
    }
    return inputControl1;

}

function validaTelefone(val) {

    var vCtrlTel = document.getElementById(val.controltovalidate)
    var vCtrlInd = document.getElementById(getControlo(val.attributes["Indicativo"].nodeValue).id)

    var erro = true;

    if (vCtrlInd.value == "+351") {
        if (vCtrlTel.value.length != 9) {
            erro = false;

        }
        else {
            primeiroDigito = vCtrlTel.value.substr(0, 1);
            doisPrimeirosDigitos = vCtrlTel.value.substr(0, 2);

            if ((primeiroDigito != "2") && (doisPrimeirosDigitos != "91") && (doisPrimeirosDigitos != "92") && (doisPrimeirosDigitos != "93") && (doisPrimeirosDigitos != "96") && (doisPrimeirosDigitos != "30")) {
                erro = false;

            }
        }
    }
    return erro;
}

//função copiada do init.js do moss

var g_updateFormDigestPageLoaded = new Date();
function UpdateFormDigest(serverRelativeWebUrl, updateInterval) {
    try {
        if ((g_updateFormDigestPageLoaded == null) || (typeof (g_updateFormDigestPageLoaded) != "object")) {
            return;
        }
        var now = new Date();
        if (now.getTime() - g_updateFormDigestPageLoaded.getTime() < updateInterval) {
            return;
        }
        if ((serverRelativeWebUrl == null) || (serverRelativeWebUrl.length <= 0)) {
            return;
        }
        var formDigestElement = document.getElementsByName("__REQUESTDIGEST")[0];
        if ((formDigestElement == null) || (formDigestElement.tagName.toLowerCase() != "input") || (formDigestElement.type.toLowerCase() != "hidden") ||
			(formDigestElement.value == null) || (formDigestElement.value.length <= 0)) {
            return;
        }
        var request = null;
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (ex) {
            request = null;
        }
        if (request == null) {
            try {
                request = new XMLHttpRequest();
            }
            catch (ex) {
                request = null;
            }
        }
        if (request == null) {
            return;
        }
        request.open("POST", GetUrlFromWebUrlAndWebRelativeUrl(serverRelativeWebUrl, "_vti_bin/sites.asmx"), false);
        request.setRequestHeader("Content-Type", "text/xml");
        request.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetUpdatedFormDigest");
        request.send("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "  <soap:Body>" + "    <GetUpdatedFormDigest xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\" />" + "  </soap:Body>" + "</soap:Envelope>");
        var responseText = request.responseText;
        if ((responseText == null) || (responseText.length <= 0)) {
            return;
        }
        var startTag = '<GetUpdatedFormDigestResult>';
        var endTag = '</GetUpdatedFormDigestResult>';
        var startTagIndex = responseText.indexOf(startTag);
        var endTagIndex = responseText.indexOf(endTag, startTagIndex + startTag.length);
        var newFormDigest = null;
        if ((startTagIndex >= 0) && (endTagIndex > startTagIndex)) {
            var newFormDigest = responseText.substring(startTagIndex + startTag.length, endTagIndex);
        }
        if ((newFormDigest == null) || (newFormDigest.length <= 0)) {
            return;
        }
        var oldValue = formDigestElement.value;
        formDigestElement.value = newFormDigest;
    }
    catch (ex) {
    }
}



