// Generics variables
var newWinUpload;
var newWinImport;

// Generics functions
function go(url){
	if (document.images)
		location.replace(url);
	else
		location.href = url;
}

function openerGo(url){
	// Check that an opener exists and is not closed
	if (window.opener && !window.opener.closed) {
		window.close();
		window.opener.location.href = url;
	}
}

function closeImport(){
	if (newWinImport && !newWinImport.closed) {
		newWinImport.close();
	}
}

function strEmpty(string){
        if ( (string==null) || (string=="") ) return true;
        for (var numAux=0; numAux < string.length; numAux++){
                sTemp = string.substring(numAux, numAux+1);
                if (sTemp != ' ' && sTemp != '\n' && sTemp != '\f' && sTemp != '\r' && sTemp != '\t') {
                        return false;
                }
        }
        return true;
}

function isNumeric(str){
        for (var count = 0; count < str.length; count++){
                num = str.substring(count, count + 1);
                if (!(num >= '0' && num <= '9'))
                        return false;
        }
        return true;
}

function isAValidEmail(strEmail) {
        var arr_email;
        var substr;

        // exist @ ?
        if (strEmail.indexOf("@") < 0) {
                return false;
        }

        arr_email = strEmail.split("@");
        if (arr_email.length < 2 || arr_email.length > 2 || arr_email[0] == "" || arr_email[1] == "") {
                return false;
        }
        // check 4 .
        if ((arr_email[1].indexOf(".") < 0)) {
                return false;
        }
        // check 4 "@."
        if (strEmail.indexOf("@.") >= 0) {
                return false;
        }
        // check 4 ".@"
        if (strEmail.indexOf(".@") >= 0) {
                return false;
        }
        // check 4 " "
        if (strEmail.indexOf(" ") >= 0) {
                return false;
        }
        // check 4 ".."
        if (strEmail.indexOf("..") >= 0) {
                return false;
        }
        // check 4 ".xxx@xxx.xx" or "xxx@xxx.xx."
        substr = arr_email[0].substring(0, 1);
        if (substr == '.'){
                return false;
        }
        else{
                substr = arr_email[1].substring((arr_email[1].length)-1, arr_email[1].length);
                if (substr == '.'){
                        return false;
                }
        }
        return true;
}

function isAValidURL(strURL) {
        var arr_URL;
        var substr;

        // exist // ?
        if (strURL.indexOf("//") < 0) {
            return false;
        }

        arr_URL = strURL.split("//");
        if (arr_URL.length < 2 || arr_URL.length > 2 || arr_URL[0] == "" || arr_URL[1] == "") {
            return false;
        }
        // check 4 .
        if ((arr_URL[1].indexOf(".") < 0)) {
            return false;
        }
        // check 4 "http:" or "https:"
        if ((arr_URL[0] != "http:") && (arr_URL[0] != "https:")){
			return false;
        }

        // check 4 "//."
        if (strURL.indexOf("//.") >= 0) {
            return false;
        }
        // check 4 " "
        if (strURL.indexOf(" ") >= 0) {
            return false;
        }
        // check 4 ".."
        if (strURL.indexOf("..") >= 0) {
            return false;
        }
        // check 4 ".xxx//xxx.xx" or "xxx//xxx.xx."
        substr = arr_URL[1].substring((arr_URL[1].length)-1, arr_URL[1].length);
        if (substr == '.'){
            return false;
        }
        return true;
}

function isValidText(str){
		while (str.search('\r') != -1){
			str = str.replace('\r', " ");
		}
		while (str.search("  ") != -1){
			str = str.replace("  ", " ");
		}
        return str;
}

function isValidDate(string){
	if (string.length != 10) return false
	else{
		if ( (string.charAt(4) != "/") || (string.charAt(7) != "/")) return false
		else return true;
	}
}

function isValidNum(num, min, max){
	if ((num < min) || (num > max)) return false
	else return true;
}

function hasXcludedChar(string){
    if (string.search(/\\/) != -1){
		alert("O caracter \\ não é válido.");
		return true;
	}
    else return false;
}

function newUpload(){
//	var newWinUpload;
	url = 'fotoUpload.asp';
	opt = 'width=270,height=190,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=yes';
	newWinUpload = window.open(url, "", opt);
	newWinUpload.focus();
}

function importData(module){
	switch (module){
		case 'protocols':
			url = 'importProtocol.asp';
			opt = 'width=370,height=190,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no';
			newWinImport = window.open(url, "", opt);
			newWinImport.focus();
			break
		default:
			url = 'importProtocol.asp';
			opt = 'width=370,height=190,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=yes';
			newWinImport = window.open(url, "", opt);
			newWinImport.focus();
	}
}

function newPopUp(url, x, y){
	opt = 'width='+x+',height='+y+',resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no'
	nPU=window.open(url, "", opt)
	nPU.focus()
}

// Especifics functions

function login_valid(form){
	if (strEmpty(form.username.value)){
		alert("É necessário preencher o campo: Utilizador")
		form.username.focus();
		return false
	}
	if (form.username.value.search("\"|\'") != -1){
		alert("Os caracteres \" e \' não são válidos.")
		form.username.focus();
		return false;
	}

	if (strEmpty(form.password.value)){
		alert("É necessário preencher o campo: Palavra-passe")
		form.password.focus();
		return false
	}
	if (form.password.value.search("\"|\'") != -1){
		alert("Os caracteres \" e \' não são válidos.")
		form.password.focus();
		return false;
	}
	return true
}

function highlight_valid(theForm, maxLength) {
    // 1º, TEST IF THERE ARE ALREADY HIGHLIGHTS.
    // IF DON'T, ONLY TEST THE NEW HIGHLIGHT.
	var error="";
	var j=0;
	
    if (theForm.numDestaques.value > 0){
		// Cálculo do número de linhas
		boundry = theForm.elements.length;
		// Tira-se 5 por causa dos inputs do "acrescentar destaque"
		boundry = boundry - 5;
		// Tira-se 5 por causa dos inputs "numDestaques" e "mode", e dos botoes "cmdCancel, cmdRepor", cmdSave e cmdUpdate" 
		boundry = boundry - 6;
		//divide-se por 5 porque cada destaque tem 5 campos
		numLinha = boundry/5;

		for(i = 0;i < numLinha;i++) {
			var valNum = theForm.elements[j].value;
			j=j+1;
			var valTit = theForm.elements[j].value;
			j=j+1;
			var valTexto = theForm.elements[j].value;
			j=j+1;
			var valLink = theForm.elements[j].value;
			j=j+1;
			//var valNJ = theForm.elements[j].value;
			j=j+1;

			// primeiro, vê se é para eliminar
			if (strEmpty(valNum)){
				if (!window.confirm('Vai eliminar o destaque \'' +  valTit + '\'.\nDesejar continuar?')){
					return false;
				}
			}
			else{
			// não é para eliminar, então faz os testes
				// Verifica se o número é valido!!!
				if (isNaN(valNum) || valNum<=0){
					error = "número '" + valNum + "' não é válido!\nCorrija por favor.";
					break;
				}
				else{
					if(valNum>200){
						error = "número '" + valNum + "' não é válido. O máximo é 200.\nCorrija por favor.";
						break;
					}
				}

				// Verifica se está tudo preenchido!
				if (strEmpty(valTit) || strEmpty(valTexto)){
					error = "tanto o título como o texto são de preenchimento obrigatório (destaque n. " + valNum + ")!\nCorrija por favor.";
					break;
				}
				
				if (valTexto.length>maxLength){
					error = "o texto pode ter no máximo " + maxLength + " caracteres. Neste momento tem " + valTexto.length + " (destaque n. " + valNum + ")!\nCorrija por favor.";
					break;
				}
				if (!strEmpty(valLink)) {
						if (valLink.search("\"|\'") != -1){
							error = "os caracteres \" e \' não são válidos (destaque n. " + valNum + ")!\nCorrija por favor.";
							break;
						}
						if (isAValidURL(valLink) == false){
							error = "o link introduzido não é válido (destaque n. " + valNum + ")!\nCorrija por favor.\n\n(nota: tem que começar por http:// ou https://)";
							break;
						}
						if (valLink.search("\/easup\/") != -1){
							error = "O link introduzido não está correcto (destaque n. " + valNum + ").\nRefere uma página apenas acessível ao administrador do site. Para corrigir, terá que abrir clicar em 'ver o sítio' no menu principal, ir à página que pretende referênciar e copiar o endereço para este campo. Se precisar de ajuda, por favor, contacte a Nostri.\n";
							break;
						}
				}
			}
		}
	}
	
	// VERIFICA VALIDADE DE NOVO DESTAQUE...
	if (strEmpty(theForm.novoTexto.value) != strEmpty(theForm.novoTit.value)){
		error = "tanto o título como o texto são de preenchimento obrigatório (novo destaque)!\nCorrija por favor.";
	}
	else{
		if (!strEmpty(theForm.novoTit.value)){
			if (isNaN(theForm.novoNum.value) || theForm.novoNum.value<=0){
				error = "número '" + theForm.novoNum.value + "' não é válido (novo destaque)!\nCorrija por favor.";
			}
			else{
				if(theForm.novoNum.value>200){
					error = "número '" + theForm.novoNum.value + "' não é válido (novo destaque). O máximo é 200.\nCorrija por favor.";
				}
			}
			if (theForm.novoTexto.value.length>maxLength){
				error = "o texto pode ter no máximo " + maxLength + " caracteres (novo destaque). Neste momento tem " + theForm.novoTexto.value.length + "!\nCorrija por favor.";
			}
			if (!strEmpty(theForm.novoLink.value)) {
					if (theForm.novoLink.value.search("\"|\'") != -1){
						error = "os caracteres \" e \' não são válidos (novo destaque)!\nCorrija por favor.";
					}
					if (isAValidURL(theForm.novoLink.value) == false){
						error = "o link introduzido não é válido (novo destaque)!\nCorrija por favor.\n\n(nota: tem que começar por http:// ou https://)";
					}
			}
		}
	}

	if (error == ""){
		return true;
	}
	else{
		window.alert("Operação abortada!\nMotivo: " + error);
		return false;
	}
}

function news_valid(form) {
    var strErr = "";
    var err = false;
    var msg = "";

    // DATA_VALID
    if (!isValidDate(form.ndate.value) && !(err)) {
            alert("A data não é válida.");
            form.ndate.focus();
            return false;
    }

    if (strEmpty(form.author.value) && !(err)) {
            strErr = "autor";
            form.author.focus();
            err = true;
    }
    if ((hasXcludedChar(form.author.value)) && !(err)){
            form.author.focus();
            return false;
    }

    if (strEmpty(form.titPT.value) && !(err)) {
            strErr = "título (PT)";
            form.titPT.focus();
            err = true;
    }
    if ((hasXcludedChar(form.titPT.value)) && !(err)){
            form.titPT.focus();
            return false;
    }
/*
		if ((strEmpty(form.text.value+form.textFCK.value)) && !(err)) {
            strErr = "texto";
            form.text.focus();
            err = true;
    }
    if ((hasXcludedChar(form.text.value)) && !(err)){
            form.text.focus();
            return false;
    }
*/
		if ((strEmpty(form.textFCK.value)) && !(err)) {
            strErr = "texto";
            form.text.focus();
            err = true;
    }
    if ((hasXcludedChar(form.textFCK.value)) && !(err)){
            form.textFCK.focus();
            return false;
    }

    if (err) {
            alert("É necessário preencher o campo: " + strErr + ".")
            return false;
    }
    else return true;
}

function courses_valid(form) {
    var strErr = "";
    var err = false;
    var msg = "";

    // DATA_VALID
    if (!isValidDate(form.ndate.value) && !(err)) {
            alert("A data não é válida.");
            form.ndate.focus();
            return false;
    }

    if (strEmpty(form.author.value) && !(err)) {
            strErr = "autor";
            form.author.focus();
            err = true;
    }
    if ((hasXcludedChar(form.author.value)) && !(err)){
            form.author.focus();
            return false;
    }

    if (strEmpty(form.titPT.value) && !(err)) {
            strErr = "título (PT)";
            form.titPT.focus();
            err = true;
    }
    if ((hasXcludedChar(form.titPT.value)) && !(err)){
            form.titPT.focus();
            return false;
    }
    if (strEmpty(form.text.value) && !(err)) {
            strErr = "texto";
            form.text.focus();
            err = true;
    }
    if ((hasXcludedChar(form.text.value)) && !(err)){
            form.text.focus();
            return false;
    }
    if (err) {
            alert("É necessário preencher o campo: " + strErr + ".")
            return false;
    }
    else return true;
}

function protocolsCategories_valid(form) {
    var strErr = "";
    var err = false;
    var msg = "";

    if (strEmpty(form.descricao.value) && !(err)) {
            strErr = "Nome";
            form.descricao.focus();
            err = true;
    }
    if ((hasXcludedChar(form.descricao.value)) && !(err)){
            form.descricao.focus();
            return false;
    }
    if (err) {
            alert("É necessário preencher o campo: " + strErr + ".")
            return false;
    }
    else return true;
}


function protocols_valid(form) {
    var strErr = "";
    var err = false;
    var error = "";
    var maxLength = 250;
    

    if (strEmpty(form.descricao.value) && !(err)) {
            strErr = "Nome";
            form.descricao.focus();
            err = true;
    }
    if ((hasXcludedChar(form.descricao.value)) && !(err)){
            form.descricao.focus();
            return false;
    }
    
    if (err) {
            alert("É necessário preencher o campo: " + strErr + ".")
            return false;
    }
    
    if (form.descontos.value.length>maxLength){
		error = "o texto pode ter no máximo " + maxLength + " caracteres (novo destaque). Neste momento tem " + form.descontos.value.length + "!\nCorrija por favor.";
        alert(error);
        form.descontos.focus();
        return false;
	}

    if (form.morada.value.length>maxLength){
		error = "o texto pode ter no máximo " + maxLength + " caracteres (novo destaque). Neste momento tem " + form.morada.value.length + "!\nCorrija por favor.";
        alert(error);
        form.descontos.focus();
        return false;
	}
    
    return true;
}

function agenda_valid(form) {
    var strErr = "";
    var err = false;
    var msg = "";

    // DATA_VALID
    if (!isValidDate(form.ndateStart.value) && !(err)) {
            alert("A data de início não é válida.");
            form.ndateStart.focus();
            return false;
    }
    if (!strEmpty(form.ndateFinish.value) && !(err)) {
		if (form.ndateFinish.value < form.ndateStart.value){
			alert('A data de fim não é válida');
            form.ndateFinish.focus();
            return false;
		}
    }

    if (strEmpty(form.titPT.value) && !(err)) {
            strErr = "título";
            form.titPT.focus();
            err = true;
    }
    if ((hasXcludedChar(form.titPT.value)) && !(err)){
            form.titPT.focus();
            return false;
    }
    
    if ((form.cboCategory.value==0) && !(err)) {
            strErr = "categoria";
            form.titPT.focus();
            err = true;
    }
    
    if (strEmpty(form.text.value) && !(err)) {
            strErr = "texto";
            form.text.focus();
            err = true;
    }
    if ((hasXcludedChar(form.text.value)) && !(err)){
            form.text.focus();
            return false;
    }
    if (err) {
            alert("É necessário preencher o campo: " + strErr + ".")
            return false;
    }
    else return true;
}

function setMode(str){
	document.dados.mode.value=str;
}

function previewImgNews(name, imgPath){
	if (name != 'semFoto.gif'){
		document.images['imgPreview'].src = imgPath + name;
	}
	else{
		document.imgPreview.src = semFoto.src;
	}
}

function config_valid(form, oldUserName) {
	// emptiness validation
	var strErr = "";
	var err = false;

	if (strEmpty(form.username.value)) {
		strErr = "utilizador";
		form.username.focus();
		err = true;
	}

	if ((form.username.value.length < 3) && !(err)){
		alert("O nome de utilizador que ter pelo menos 3 caracteres.")
		form.username.focus();
		return false;
	}
	
	if ((form.username.value.search("\"|\'| ") != -1) && !(err)){
		alert("Espaços e os caracteres \" e \' não são válidos.")
		form.username.focus();
		return false;
	}

	if ((form.password1.value != form.password2.value) && !(err)) {
		alert("A palavra-passe e sua confirmação não são iguais.")
		form.password1.focus();
		return false;
	}
	if (form.password1.value.search("\"|\'") != -1){
		alert("Os caracteres \" e \' não são válidos.")
		form.password1.focus();
		return false;
	}
	if (form.password2.value.search("\"|\'") != -1){
		alert("Os caracteres \" e \' não são válidos.")
		form.password2.focus();
		return false;
	}

	if (strEmpty(form.nNews.value) && !(err)) {
		strErr = "nº de notícias";
		form.nNews.focus();
		err = true;
	}
	if ((form.nNews.value.search("\"|\'") != -1) && !(err)){
		alert("Os caracteres \" e \' não são válidos.")
		form.nNews.focus();
		return false;
	}
	if ((isNumeric(form.nNews.value) == false) && !(err)) {
		alert("O nº de notícias introduzido não é válido.")
		form.nNews.focus();
		return false
	}

	if ((isValidNum(form.nNews.value, 1, 40) == false) && !(err)) {
		alert("O nº de notícias tem que ser entre 1 e 40.")
		form.nNews.focus();
		return false
	}

	if (strEmpty(form.nCourses.value) && !(err)) {
		strErr = "nº de notícias";
		form.nCourses.focus();
		err = true;
	}
	if ((form.nCourses.value.search("\"|\'") != -1) && !(err)){
		alert("Os caracteres \" e \' não são válidos.")
		form.nCourses.focus();
		return false;
	}
	if ((isNumeric(form.nCourses.value) == false) && !(err)) {
		alert("O nº introduzido não é válido.")
		form.nCourses.focus();
		return false
	}

	if ((isValidNum(form.nCourses.value, 1, 40) == false) && !(err)) {
		alert("O nº tem que ser entre 1 e 40.")
		form.nCourses.focus();
		return false
	}

	if (strEmpty(form.nInitiatives.value) && !(err)) {
		strErr = "nº de iniciativas";
		form.nInitiatives.focus();
		err = true;
	}
	if ((form.nInitiatives.value.search("\"|\'") != -1) && !(err)){
		alert("Os caracteres \" e \' não são válidos.")
		form.nInitiatives.focus();
		return false;
	}
	if ((isNumeric(form.nInitiatives.value) == false) && !(err)) {
		alert("O nº de iniciativas introduzido não é válido.")
		form.nInitiatives.focus();
		return false
	}

	if ((isValidNum(form.nInitiatives.value, 1, 40) == false) && !(err)) {
		alert("O nº de iniciativas tem que ser entre 1 e 40.")
		form.nInitiatives.focus();
		return false
	}

	if (err) {
		alert("É necessário preencher o campo: " + strErr + ".")
		return false;
	}
	
	if (form.username.value != oldUserName){
		if (window.confirm("Vai alterar o seu nome de utilizador para \'" + form.username.value + "\'!\n Desejar continuar?\n(o nome de utilizador actual passará a ser obsoleto)")){
		}
		else return false;
	}

	if (form.password1.value.length > 0){
		if (window.confirm("Vai alterar a sua palavra-passe!\n Desejar continuar?\n(a palavra-passe actual passará a ser obsoleta)")){
		}
		else return false;
	}

	return true;
}


function galleryAlbuns_valid(form) {
    var strErr = "";
    var err = false;
    var msg = "";

    if (strEmpty(form.descricao.value) && !(err)) {
            strErr = "Nome";
            form.descricao.focus();
            err = true;
    }
    if ((hasXcludedChar(form.descricao.value)) && !(err)){
            form.descricao.focus();
            return false;
    }
    if (err) {
            alert("É necessário preencher o campo: " + strErr + ".")
            return false;
    }
    else return true;
}


function guestbook_valid(form) {
    var strErr = "";
    var err = false;
    var msg = "";

    if (strEmpty(form.title.value) && !(err)) {
            strErr = "O seu nome";
            form.title.focus();
            err = true;
    }
    if ((hasXcludedChar(form.title.value)) && !(err)){
            form.title.focus();
            return false;
    }

	if ((strEmpty(form.text.value)) && !(err)) {
            strErr = "O seu comentário";
            form.text.focus();
            err = true;
    }
    if ((hasXcludedChar(form.text.value)) && !(err)){
            form.text.focus();
            return false;
    }

    if (err) {
            alert("É necessário preencher o campo: " + strErr + ".")
            return false;
    }
    else return true;
}

function RefreshAntiBot(valImageId) {
	var objImage = document.images[valImageId];
	if (objImage == undefined) {
		return;
	}
	var now = new Date();
	objImage.src = objImage.src.split('?')[0] + '?x=' + now.toUTCString();
}