
// 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 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);
}


/* 
*
* NOTA: Apagar tudo daqui para baixo, caso exista algo.
*
*/
				
function escolherRegalojamentos(id){
	
	td = "td_" + id;

	//CAMPO id_alojamento					
	frmOperacoes.txtid_alojamento.value = getAttrib( td,"id_alojamento");
	//CAMPO descricao					
	frmOperacoes.txtdescricao.value = getAttrib( td,"descricao");
	//CAMPO informacoes					
	frmOperacoes.tArinformacoes.value = replaceBR(getAttrib( td, "informacoes"));
}
				
function escolherRegoperadores(id){
	
	td = "td_" + id;

	//CAMPO id_operador					
	frmOperacoes.txtid_operador.value = getAttrib( td,"id_operador");
	//CAMPO descricao					
	frmOperacoes.txtdescricao.value = getAttrib( td,"descricao");
}
				
function escolherRegpacotes_alojamentos(id){
	
	td = "td_" + id;

						
	//CAMPO '.id_pacote.'						
	setOption('cmbid_pacote', getAttrib( td, 'id_pacote'));
						
	//CAMPO '.id_alojamento.'						
	setOption('cmbid_alojamento', getAttrib( td, 'id_alojamento'));
}
				
function escolherRegpacotes_tipos(id){
	
	td = "td_" + id;

						
	//CAMPO '.id_pacote.'						
	setOption('cmbid_pacote', getAttrib( td, 'id_pacote'));
						
	//CAMPO '.id_tipo.'						
	setOption('cmbid_tipo', getAttrib( td, 'id_tipo'));
}
				
function escolherRegtipologia_eventos(id){
	
	td = "td_" + id;

	//CAMPO id_tipologia_eventos					
	frmOperacoes.txtid_tipologia_eventos.value = getAttrib( td,"id_tipologia_eventos");
	//CAMPO descricao					
	frmOperacoes.txtdescricao.value = getAttrib( td,"descricao");
}
				
function escolherRegtipologia_pacotes(id){
	
	td = "td_" + id;

	//CAMPO id_tipologia_pacotes					
	frmOperacoes.txtid_tipologia_pacotes.value = getAttrib( td,"id_tipologia_pacotes");
	//CAMPO descricao					
	frmOperacoes.txtdescricao.value = getAttrib( td,"descricao");

	//CAMPO destaque_1n
	araddestaque_1n = frmOperacoes.raddestaque_1n;
	for (i=0; i<araddestaque_1n.length; i++){	
		if (araddestaque_1n[i].value == getAttrib( td, 'destaque_1n')){
			araddestaque_1n[i].checked = true;
		} else {
				araddestaque_1n[i].checked = false;	
			}
	}		
	

	//CAMPO destaque_2n
	araddestaque_2n = frmOperacoes.raddestaque_2n;
	for (i=0; i<araddestaque_2n.length; i++){	
		if (araddestaque_2n[i].value == getAttrib( td, 'destaque_2n')){
			araddestaque_2n[i].checked = true;
		} else {
				araddestaque_2n[i].checked = false;	
			}
	}		
	

	//CAMPO destaque_3n
	araddestaque_3n = frmOperacoes.raddestaque_3n;
	for (i=0; i<araddestaque_3n.length; i++){	
		if (araddestaque_3n[i].value == getAttrib( td, 'destaque_3n')){
			araddestaque_3n[i].checked = true;
		} else {
				araddestaque_3n[i].checked = false;	
			}
	}		
	

	//CAMPO destaque_4n
	araddestaque_4n = frmOperacoes.raddestaque_4n;
	for (i=0; i<araddestaque_4n.length; i++){	
		if (araddestaque_4n[i].value == getAttrib( td, 'destaque_4n')){
			araddestaque_4n[i].checked = true;
		} else {
				araddestaque_4n[i].checked = false;	
			}
	}		
	
	
	//CAMPO foto
	imagem = '';
	if (getAttrib( td, 'foto') == ''){
		imagem = 'sem_imagem.jpg';
	} else {
			imagem = getAttrib( td, 'foto');
		}
	
	document.all.imgThumb.src = 'uploads/thumbs/' + imagem;
						
}


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

	//CAMPO id_pacote					
	frmOperacoes.txtid_pacote.value = getAttrib( td,"id_pacote");
	//CAMPO descricao					
	frmOperacoes.txtdescricao.value = getAttrib( td,"descricao");
	//CAMPO frase_chave					
	frmOperacoes.txtfrase_chave.value = getAttrib( td,"frase_chave");
	
	//CAMPO foto
	imagem = '';
	if (getAttrib( td, 'foto') == ''){
		imagem = 'sem_imagem.jpg';
	} else {
			imagem = getAttrib( td, 'foto');
		}
	
	document.all.imgThumb.src = 'uploads/thumbs/' + imagem;
						
						
	//CAMPO '.operadores.'						
	setOption('cmboperadores', getAttrib( td, 'operador'));
	//CAMPO preco					
	frmOperacoes.txtpreco.value = getAttrib( td,"preco");
	
	
	// MUDAR NO CRIAR_MODULO
	//CAMPO inicio	
	//CAMPO HIDDEN txtinicio
	frmOperacoes.txtinicio.value = getAttrib( td, "inicio");
	//arrDataTotal 	= (getAttrib( td, "inicio")).split(" ");
	//arrData 		= arrDataTotal[0];
	arrDiv = (getAttrib( td, "inicio")).split("-");
	setOption("cmbDiainicio", arrDiv[0] );
	setOption("cmbMesinicio", arrDiv[1] );
	setOption("cmbAnoinicio", arrDiv[2] );					
	
	//CAMPO fim					
	//CAMPO HIDDEN txtinicio
	frmOperacoes.txtfim.value = getAttrib( td,"fim");
	//arrDataTotal 	= (getAttrib( td, "inicio")).split(" ");
	//arrData 		= arrDataTotal[0];
	arrDiv = (getAttrib( td, "fim")).split("-");
	setOption("cmbDiafim", arrDiv[0] );
	setOption("cmbMesfim", arrDiv[1] );
	setOption("cmbAnofim", arrDiv[2] );
	//CAMPO dia_inicio
	frmOperacoes.txtdia_inicio.value = getAttrib( td,"dia_inicio");
	
	//CAMPO destaque_site
	araddestaque_site = frmOperacoes.raddestaque_site;
	for (i=0; i<araddestaque_site.length; i++){	
		if (araddestaque_site[i].value == getAttrib( td, 'destaque_site')){
			araddestaque_site[i].checked = true;
		} else {
				araddestaque_site[i].checked = false;	
			}
	}
	
	//CAMPO destaque_tipo
	araddestaque_tipo = frmOperacoes.raddestaque_tipo;
	for (i=0; i<araddestaque_tipo.length; i++){	
		if (araddestaque_tipo[i].value == getAttrib( td, 'destaque_tipo')){
			araddestaque_tipo[i].checked = true;
		} else {
				araddestaque_tipo[i].checked = false;	
			}
	}
	
	//CAMPO valido
	aradvalido = frmOperacoes.radvalido;
	for (i=0; i<aradvalido.length; i++){	
		if (aradvalido[i].value == getAttrib( td, 'valido')){
			aradvalido[i].checked = true;
		} else {
				aradvalido[i].checked = false;	
			}
	}
	
	
	//CAMPO ult_act					
	frmOperacoes.txtult_act.value = getAttrib( td,"ult_act");
}
