// TRATAMENTO DE DATAS
function y2k(number) { return (number < 1000) ? number + 1900 : number; }
function isDate (day,month,year) {
/*
 checks if date passed is valid
 will accept dates in following format:
 isDate(dd,mm,ccyy), or
 isDate(dd,mm) - which defaults to the current year, or
 isDate(dd) - which defaults to the current month and year.
 Note, if passed the month must be between 1 and 12, and the
 year in ccyy format.
*/
    var today = new Date();
    year = ((!year) ? y2k(today.getYear()):year);
    month = ((!month) ? today.getMonth():month-1);
    if (!day) return false
    var test = new Date(year,month,day);
    if ( (y2k(test.getYear()) == year) &&
         (month == test.getMonth()) &&
         (day == test.getDate()) )
        return true;
    else
        return false
}

function prepararData(obj, i){
	
	objDia = "";
	objMes = "";
	objAno = "";
	
	if (obj.substr(3,3)=="Dia"){
		objDia = obj;
		objMes = obj.replace('Dia', 'Mes');
		objAno = obj.replace('Dia', 'Ano');
	
	} else if (obj.substr(3,3)=="Mes"){			
			objMes = obj;
			objDia = obj.replace('Mes', 'Dia');
			objAno = obj.replace('Mes', 'Ano');
			
		} else if (obj.substr(3,3)=="Ano"){
				objAno = obj;
				objDia = obj.replace('Ano', 'Dia');
				objMes = obj.replace('Ano', 'Mes');
								
			}
		
	strDia = "frmGestao." + objDia + ".value;"
	strMes = "frmGestao." + objMes + ".value;"
	strAno = "frmGestao." + objAno + ".value;"
	
	dia = eval(strDia);
	mes = eval(strMes);
	ano = eval(strAno);
	
	data = ano + "-" + mes + "-" + dia;
	
	if (!isDate(dia, mes, ano)){
		alert("Data inválida");
	}
	
	//Colocar a data no campo escondido
	strTemp = obj.substring(0,6);
	strCampoData = obj.replace(strTemp, "txt");	
	strData = "frmGestao." + strCampoData + ".value = data;"
	eval(strData);
}



function setOption(nomeCmb, opcao) {
	
  var obj = document.getElementById(nomeCmb);		
	
	for (i=0; i<obj.options.length; i++){
		
		if (obj.options[i].value == opcao){
			obj.options[i].selected = true;	
		}	
	}
}




function setDataOption( nome ){
	  
  data = getAttrib( td, nome);
	getElem('txt' + nome).value = data;
  //alert(data);
  arrDataTotal = data.split(" ");
	arrData 		= arrDataTotal[0];
	arrDiv 		= arrData.split("-");
  
  if (arrDiv[0].length < 4){
  	arrDiv = arrDiv.reverse(); 
  }
  
  
	setOption("cmbAno" + nome, arrDiv[0] );
	setOption("cmbMes" + nome, arrDiv[1] );
	setOption("cmbDia" + nome, arrDiv[2] );
}



function preencherTxt(campo, data ){

	eval("frmOperacoes." + campo + ".value ='" + data + "';");
	
}



//Actualizar a string resultante das comboboxes seleccionadas
function actGroupVal(id, estado, valor){

	strChk = 'txt'+ id;
	
	txtChk = document.getElementById(strChk);
	
	if (estado==true){
		
		//ADICIONAR
		
		if (txtChk.value!=''){
			arrVal = (txtChk.value).split('|§|');
			
			arrVal.push(valor);
						
			arrVal = arrVal.sort();
			
			txtChk.value = arrVal.join('|§|');
		} else {
				txtChk.value = valor;
			}
		
	} else {
			
			//REMOVER	
			arrVal = (txtChk.value).split('|§|');
			
			for (i=0; i<arrVal.length; i++){
				
				if (arrVal[i]==valor){
					
					s1 = arrVal.splice(i, 1);
					
					arrVal = arrVal.sort();
					txtChk.value = arrVal.join('|§|');
				}
			}
			
		}
}





//Contar objectos
function contarObj(tipo, nome){

	var ckCnt = 0;
	var objCount = 0;
	//TAG é em MAIÚSCULAS
	var obj = document.getElementsByTagName('INPUT');
	
	for (var i=0; i<obj.length; i++) {
		//tipo é em minúsculas
		if ((obj[i].type == tipo) && (obj[i].id == nome)) {
			objCount++;
		}
	}
	
	return objCount;
}


//Adicionar a funçao in_array ao objecto array
Array.prototype.in_array = function(valor){
	
	if (this.length>0){
	
		for (var i=0; i<this.length; i++){
		
			if (this[i] == valor){
				return true;
			}
		}
	}
	return false;
}




//Seleccionar as checkboxes de acordo com as opçoes da BD
function preSel(obj, numObjs, txt){

	//alert(obj +'---'+ numObjs +'---'+ txt);
	
	if (txt!=''){
	
		var arr = txt.split('|§|');
		
		if (i>1){
			for (var i=0; i<numObjs; i++){
				obj[i].checked=false;
				if (arr.in_array(obj[i].value)){
					
					obj[i].checked=true;
				}		
			}
		} else {
				obj.checked=false;
				if (arr.in_array(obj.value)){
					obj.checked=true;
				}
			}
		
	}
}



//Validar que uma das opções (RADIO BUTTON) foi escolhida
function validateRB(frm, btnName)
{
	//var btn = frm[btnName]
	
	var bth = document.getElementById(btnName);
	var valid
	
	for (var x = 0;x < btn.length; x++)
	{
		valid = btn[x].checked
		if (valid) {break}
	}
	if(!valid)
	{
		alert("Please select an answer.")
	}
}

//Verificar se um campo está vazio
function isEmpty(aTextField) {
   if ((aTextField.value.length==0) ||
   (aTextField.value==null)) {
      return true;
   }
   else { return false; }
}	


function replaceBR(str){

	//alert(str);
	n = (str.split("<br>")).length;
	for (i=0; i<n; i++ ){
		str = str.replace('<br>', "\r\n");
	}
	
	return str;
}


function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function isEmail(string) {
    if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
        return true;
    else
        return false;
}

function validarCampo(tipoCampo, numC, obj, nomeCampo){

	ret = false;
  
  id = obj.id;
  valor = document.getElementById(id).value
  
  switch (tipoCampo){
  
  	case 'telefone':
     		if (valor.length!=numC){
           	alert('Número de '+ nomeCampo +' incorrecto.');
              obj.focus();
              return false;
           } else {
						if (!isInteger(valor)){
							alert('Número de '+ nomeCampo +' incorrecto.');
              		obj.focus();
              		return false;			
                 }
           	}
     	break;
     case 'mail':
     		
           if (!isEmail(valor)){
							alert('E-Mail incorrecto.');
              		obj.focus();
              		return false;			
                 }
     	break;
     case 'numerico':
     		
				if (!isInteger(valor)){
					alert('Número de '+ nomeCampo +' incorrecto.');
          		obj.focus();
          		return false;			
         }
     	break;
  }

  return true;
}


function getAttrib (obj, attribute){

	//alert(obj +" -- "+attribute);
	return document.getElementById(obj).getAttribute(attribute);
}


function getElem(strId){
	return document.getElementById(strId);
}

/*
numbers = new Array("one","two","three","four","five");
alert(numbers.in_array("three")) // should evaluate to true
*/
Array.prototype.in_array = function ( obj ) {
	var len = this.length;
	for ( var x = 0 ; x <= len ; x++ ) {
		if ( this[x] == obj ) return true;
	}
	return false;
}

/* 
*
* NOTA: Apagar tudo daqui para baixo, caso exista algo.
*
*/
		

				
function escolherRegsites(id){
	
	td = "td_" + id;

   //CAMPO id_sites					
   getElem('txtid_sites').value = getAttrib( td,"id_sites");
   //CAMPO nome					
   getElem('txtnome').value = getAttrib( td,"nome");
	//CAMPO descricao					
	getElem('tArdescricao').value = replaceBR(getAttrib( td, "descricao"));
   //CAMPO url					
   getElem('txturl').value = getAttrib( td,"url");

	//CAMPO logotipo
	imagem = '';
	if (getAttrib( td, 'logotipo') == ''){
		imagem = 'sem_imagem.jpg';
	} else {
			imagem = getAttrib( td, 'logotipo');
		}
	
	getElem('imgThumbimglogotipo').src = 'uploads/thumbs/' + imagem;
	
  //CAMPO num_ordem					
	getElem('txtnum_ordem').value = getAttrib( td,"num_ordem");					

	//CAMPO estado						
	getElem('txtchkestado').value = getAttrib( td,'estado');
	var o 	= getElem('chkestado');
	var n = contarObj('checkbox', 'chkestado');
	var t 	= getElem('txtchkestado').value;
	preSel(o, n, t);
	//alert(getAttrib( td,"num_ordem"));
	
}

				
function escolherRegutilizadores(id){
	
   td = "td_" + id;
   
   //CAMPO id_utilizadores					
   getElem('txtid_utilizadores').value = getAttrib( td,"id_utilizadores");
   //CAMPO nome					
   getElem('txtnome').value = getAttrib( td,"nome");
   //CAMPO username					
   getElem('txtusername').value = getAttrib( td,"username");
   //CAMPO password					
   getElem('txtpassword').value = getAttrib( td,"password");
}

function escolherReganuncios(id){
	
	td = "td_" + id;

	//CAMPO id_anuncios					
	getElem('txtid_anuncios').value = getAttrib( td,"id_anuncios");
	//CAMPO titulo					
	getElem('txttitulo').value = getAttrib( td,"titulo");
	//CAMPO descricao					
	getElem('tArdescricao').value = replaceBR(getAttrib( td, "descricao"));
	//CAMPO mail					
	getElem('txtmail').value = getAttrib( td,"mail");
	//CAMPO telefone					
	getElem('txttelefone').value = getAttrib( td,"telefone");
	//CAMPO localidade					
	getElem('txtlocalidade').value = getAttrib( td,"localidade");
	if (getAttrib( td,"destaque")=='s'){
		getElem('chkDestaque').checked=true;
	} else {
		getElem('chkDestaque').checked=false;
	}
	if (getAttrib( td,"estado")=='activo'){
		getElem('chkEstado').checked=true;
	} else {
		getElem('chkEstado').checked=false;
	}
}

function escolherRegfotos(id){
	
	td = "td_" + id;

	//CAMPO id_fotos					
	getElem('txtid_fotos').value = getAttrib( td,"id_fotos");
	//CAMPO id_anuncios					
	getElem('txtid_anuncios').value = getAttrib( td,"id_anuncios");

	//CAMPO foto
	imagem = '';
	if (getAttrib( td, 'foto') == ''){
		imagem = 'sem_imagem.jpg';
	} else {
			imagem = getAttrib( td, 'foto');
		}
	
	getElem('imgThumbimgfoto').src = 'uploads/anuncios/thumbs/' + imagem;
						
}

function abrirGestaoFotos(){
	
	id_anuncios = getElem('txtid_anuncios').value;
	
	//alert(id_anuncios);
	if (id_anuncios!=''){
		window.open('gestao_fotos.php?id_anuncios='+id_anuncios, 'win1');
		
	} else alert('Tem que escolher um anúncio.');
	
	
}