// JavaScript Document
// VARS GLOBAIS

var TABS;
// FIM VARS GLOBAIS

/* ------------ */
function me2home(){setHomePage('http://www.hoteis.pt');return false;}
function me2favo(){ var url = window.location;var title = document.title;if (window.sidebar) window.sidebar.addPanel(title, url,"");else if(window.opera && window.print){var mbm = document.createElement('a'); mbm.setAttribute('rel','sidebar');mbm.setAttribute('href',url); mbm.setAttribute('title',title);mbm.click();}else if(document.all){window.external.AddFavorite(url, title);}else{alert("Adcionar aos favoritos manualmente!")}}

function onMouseOverPause(){
	var topmsg_obj = document.getElementById("rotator");
	var pause = topmsg_obj.getElementsByTagName('marquee');
	pause[0].stop();
}
function onMouseOutPause(){
	var topmsg_obj = document.getElementById("rotator");
	var pause = topmsg_obj.getElementsByTagName('marquee');
	pause[0].start();
}

/* ------------ */

/* INsTALL MAP */
function instalarMapaGif(){
	
	var mapa = document.getElementById('mapa_flash');
	
	var div_select = document.createElement("div");
		div_select.style.zIndex=14;
		div_select.style.position='absolute';
		div_select.id = 'div_select';

	var div_over = document.createElement("div");
		div_over.style.zIndex=15;
		div_over.style.position='absolute';
		div_over.id = 'div_over';
		
	
	mapa.insertBefore(div_select,mapa.firstChild);
	mapa.insertBefore(div_over,mapa.firstChild);
	
	for(var t = mapa.firstChild; t != null; t=t.nextSibling){
		
		if (t.id == 'map'){
			for(var shape = t.firstChild; shape != null; shape=shape.nextSibling){ 
				shape.onmouseover=mapGif_over;
			}
			t.onmouseout=mapGif_out; // retirar
		}
	}
}

function mapGif_over(){
	var nome = this.id;
	var div_over=document.getElementById('div_over');
		div_over.innerHTML='';
		
	var img = document.createElement("img");
		img.src=dir+'images/mapa/'+nome+'_over.gif';
	
	div_over.appendChild(img);
}

function mapGif_out(){
		
	var div_over=document.getElementById('div_over');
		div_over.innerHTML='';
}


/********************************************************************/
function changeLanguage( LG ){
	$j("input#lng").val(LG);
	document.getElementById('changeLang').submit();
}

function lastMinit(){
	$j.PeriodicalUpdater({
		url : dir + 'template/pub/pub.php',
		method: 'post',
		maxTimeout: 15000,
		minTimeout: 10000
	},
	function(data){
		 $j("span#lastMinit").html(data);	
	});		
}
function installClock(){
  $j('span.jclock').jclock({
		fontFamily: '"Trebuchet MS", Arial, Helvetica, sans-serif',
		fontSize: '11px',
		foreground: 'white'
	});
}

function tbs( tb ){
	TABS = new ddtabcontent(tb);
	TABS.setpersist(false);
	TABS.setselectedClassTarget("link"); //"link" or "linkparent"
	TABS.init();
}
/* JQUERY */
function buscaDistrito(tp){
	$j.ajax({
	   type: "POST",
	   url: dir + "template/componentes/pesquisaAvancada/ajax/buscaDistrito.php",
	   data: "tipo="+ tp +
			 "&lng="+ LNG,
	   success: function(html){
		 $j("form#pesquisaAv div#select_distrito").html(html);		 
	   }
	});
}

function buscaConcelho(tp,dt){
	$j.ajax({
	   type: "POST",
	   url: dir + "template/componentes/pesquisaAvancada/ajax/buscaConcelho.php",
	   data: "tipo="+ tp +
	   		 "&distrito="+ dt+
			 "&lng="+ LNG,
	   success: function(html){
		 $j("form#pesquisaAv div#select_concelho").html(html);		 
	   }
	});
}

function buscaCategoria(tp,dt,cs){
	$j.ajax({
	   type: "POST",
	   url: dir + "template/componentes/pesquisaAvancada/ajax/buscaCategoria.php",
	   data: "tipo="+ tp +
	   		 "&distrito="+ dt +
			 "&concelho="+ cs +
			 "&lng="+ LNG,
	   success: function(html){
		 $j("form#pesquisaAv div#select_categoria").html(html);		 
	   }
	});
}

function limpa_pav(){
	window.location.href=dir;
}
/**/
//function installAutoSugestao(){
$j(function() {
           
    function format(hot) {var output = hot.value+' <br> <small>'+ hot.info + '</small>';return output;}
    function format2(hot) {return hot.id;}
    
    $j("#pesquisaAv #nome").autocomplete(dir + 'template/componentes/pesquisaAvancada/ajax/getAutoName.php', {
        minChars: 3,
        width: 392,
        scroll: true,
        scrollHeight: 240,
        max: 30,
        dataType: "json",
        parse: function(data) {
            return $j.map(data, function(row) {
                return {
                    data: row,
                    id: row.id,
                    value: row.value,
                    info: row.info,
                    result: row.value 
                }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    }).result(function(e, item) {
        $j("#sid").val( format2(item) );
    });
    
    $j("#PesquisaSimples #nome").autocomplete(dir + 'template/componentes/pesquisaAvancada/ajax/getAutoName.php', {
        minChars: 3,
        width: 260,
        scroll: true,
        scrollHeight: 240,
        max: 30,
        dataType: "json",
        parse: function(data) {
            return $j.map(data, function(row) {
                return {
                    data: row,
                    value: row.value,
                    info: row.info,
                    result: row.value 
                }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    }).result(function(e, item) {
        $j("#PesquisaSimples #sid").val( format2(item) );
    });
    
    
    
    $j("#pesquisaAv #morada").autocomplete(dir + 'template/componentes/pesquisaAvancada/ajax/getAutoAdresse.php', {
        minChars: 3,
        width: 392,
        scroll: true,
        scrollHeight: 240,
        max: 30,
        dataType: "json",
        parse: function(data) {
            return $j.map(data, function(row) {
                return {
                    data: row,
                    value: row.value,
                    info: row.info,
                    loc: row.loc,
                    con: row.con,
                    dis: row.dis,
                    cp4: row.cp4,
                    cp3: row.cp3,
                    result: row.value 
                    
                }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    }).result(function(e, item) {
        $j("#pesquisaAv #localidade, #cplocalidade").val( item.loc );
        $j("#pesquisaAv #concelho").val( item.con );
        $j("#pesquisaAv #distrito").val( item.dis );
        $j("#pesquisaAv #codigoPostal4").val( item.cp4 );
        $j("#pesquisaAv #codigoPostal3").val( item.cp3 );			
    });
    $j("#pesquisaAv #localidade").autocomplete(dir + 'template/componentes/pesquisaAvancada/ajax/getAutoLocal.php', {
        minChars: 3,
        width: 320,
        scroll: true,
        scrollHeight: 240,
        max: 30,
        dataType: "json",
        parse: function(data) {
            return $j.map(data, function(row) {
                return {
                    data: row,
                    value: row.value,
                    info: row.info,
                    con: row.con,
                    dis: row.dis,
                    result: row.value 
                    
                }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    }).result(function(e, item) {
        $j("#pesquisaAv #concelho").val( item.con );
        $j("#pesquisaAv #distrito").val( item.dis );
    });
    
    $j("#pesquisaAv #cplocalidade").autocomplete(dir + 'template/componentes/pesquisaAvancada/ajax/getAutoLocal.php', {
        minChars: 3,
        width: 344,
        scroll: true,
        scrollHeight: 200,
        max: 30,
        dataType: "json",
        parse: function(data) {
            return $j.map(data, function(row) {
                return {
                    data: row,
                    value: row.value,
                    info: row.info,
                    con: row.con,
                    dis: row.dis,
                    result: row.value 
                    
                }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    }).result(function(e, item) {
    	$j("#pesquisaAv #localidade").val( item.value );
        $j("#pesquisaAv #concelho").val( item.con );
        $j("#pesquisaAv #distrito").val( item.dis );
    });
    
    $j("#pesquisaAv #concelho").autocomplete(dir + 'template/componentes/pesquisaAvancada/ajax/getAutoConcelho.php', {
        minChars: 3,
        width: 205,
        scroll: true,
        scrollHeight: 200,
        max: 30,
        dataType: "json",
        parse: function(data) {
            return $j.map(data, function(row) {
                return {
                    data: row,
                    value: row.value,
                    info: row.info,
                    dis: row.dis,
                    result: row.value 
                    
                }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    }).result(function(e, item) {
        $j("#pesquisaAv #distrito").val( item.dis );
    });
    
    $j("#pesquisaAv #distrito").autocomplete(dir + 'template/componentes/pesquisaAvancada/ajax/getAutoConcelho.php', {
        minChars: 3,
        width: 205,
        scroll: true,
        scrollHeight: 200,
        max: 30,
        dataType: "json",
        parse: function(data) {
            return $j.map(data, function(row) {
                return {
                    data: row,
                    value: row.value,
                    result: row.value 
                    
                }
            });
        },
        formatItem: function(item) {
            return item.value;
        }
    });
    
    $j("#soliciteMail #unidade").autocomplete(dir + 'template/customer_care/ajax/getDateHotel.php', {
        minChars: 3,
        width: 412,
        scroll: true,
        scrollHeight: 240,
        max: 30,
        dataType: "json",
        parse: function(data) {
            return $j.map(data, function(row) {
                return {
                    data: row,
                    value: row.value,
                    info: row.info,
                    id:row.id,
                    id_tipo:row.id_tipo,
                    categoria:row.categoria,
                    prefixo_morada:row.prefixo_morada,
                    morada:row.morada,
                    localidade:row.localidade,
                    concelho:row.concelho,
                    cod4:row.cod4,
                    cod3:row.cod3,
                    id_distrito:row.id_distrito,
                    pais:row.pais,
                    telefone:row.telefone,
                    telemovel:row.telemovel,
                    fax:row.fax,
                    email:row.email,
                    website:row.website,
                    result: row.value                     
                }
            });
        },
        formatItem: function(item) {
            return format(item);
        }
    }).result(function(e, item) {
    	$j("#soliciteMail #id_unidade").val( item.id );
        $j("#soliciteMail #id_tipo option[value="+item.id_tipo+"]").attr("selected",true);
        $j("#soliciteMail #categoria").val( item.categoria );
        $j("#soliciteMail #h_cp4").val( item.cod4 );
        $j("#soliciteMail #h_cp3").val( item.cod3 );
        $j("#soliciteMail #prefixo_morada option[value="+item.prefixo_morada+"]").attr("selected",true);
        $j("#soliciteMail #morada").val( item.morada );
        $j("#soliciteMail #localidade").val( item.localidade );
        $j("#soliciteMail #concelho").val( item.concelho );
        $j("#soliciteMail #id_distrito option[value="+item.id_distrito+"]").attr("selected",true);
        $j("#soliciteMail #pais").val( item.pais );
        $j("#soliciteMail #telefone").val( item.telefone );
        $j("#soliciteMail #fax").val( item.fax );
        $j("#soliciteMail #telemovel").val( item.telemovel );
        $j("#soliciteMail #email").val( item.email );
        $j("#soliciteMail #url").val( item.website );
        
    });
    
});
	
//}
function installAutoTab(){
	$j('#codigoPostal4').autotab({ target: 'codigoPostal3', format: 'numeric', maxlength: 4 });
}

function getcp(){

	lerCodigoPostal($j("input[name=codigoPostal4]").val(),$j("input[name=codigoPostal3]").val());
	
}
function lerCodigoPostal(T4,T3){
	
	switch(validarCp(T4,T3)){
		//case -1:modalMsg(Dicionario['cpinvalido'],Dicionario['codpostal'],'stop','Ok')/*'Este código postal não é válido!'*/; break;
		//case 0: modalMsg(Dicionario['escrevacp'],Dicionario['codpostal'],'question','Ok'); break;
		case 0:
		case -1:
		case 7: openDialog(T4,T3);break;
		case 4: openDialog(T4,'');break;
	}	
	
}

function validarCp(cp4,cp3){
	var v4 = cp4.match(/^\d{4}$/);
	var v3 = cp3.match(/^\d{3}$/);
	//
	if(cp4=='' && cp3=='')return 0; //nenhum
	if(v4 && v3)return 7; // completo
	if(v4) return 4; // incial
	
	return -1; // invalido
}

function openDialog(cp4, cp3){
	
	/*$j.ajax({
	   type: "POST",
	   url: dir + "template/componentes/pesquisaAvancada/ajax/getAutoCodPostal.php",
	   data: "T4="+ cp4 +
	   		 "&T3="+cp3 ,
	   success: function(html){
		 $j("#listaCodPostal").html( html );
		 $j('#openCodPostal').dialog('open');
	   }
	 });	*/
     
	//Event.stop();
	Lightview.show({
		href: dir + 'template/componentes/pesquisaAvancada/ajax/getAutoCodPostal.php',
		rel: 'ajax',
		options: {
			menubar: false,
			autosize: true,
			topclose: true,
			keyboard: false, 
			overlayClose: false,
			ajax: {
				method: 'post',
				evalScripts: true,
				parameters:{'T4':cp4,'T3':cp3}
			}
		}
	});
}

function montarMorada(m,l,d){
	 $j("#morada").val( m );
	 $j("#localidade, #cplocalidade").val( l );
	 $j("#distrito").val( d );
	 //$j('#openCodPostal').dialog('close');
     Lightview.hide();
}

function getInsCp(cp4, cp3){
	switch(validarCp(cp4,cp3)){
		case 0:
		case -1:
		case 7: openInsDialog(cp4,cp3);break;
		case 4: openInsDialog(cp4,'');break;
    }
}

function openInsDialog( cp4, cp3 ){
	Lightview.show({
		href: dir + 'template/customer_care/ajax/getCodPostal.php',
		rel: 'ajax',
		options: {
			menubar: false,
			autosize: true,
			topclose: true,
			keyboard: false, 
			overlayClose: false,
			ajax: {
				method: 'post',
				evalScripts: true,
				parameters:{'T4':cp4,'T3':cp3}
			}
		}
	});
}

function customerCareMorada(m, l , d , cd, pr, cc){
	$j("#prefixo_morada option[value="+pr+"]").attr("selected",true);
    $j("#morada").val( m );
	$j("#localidade").val( l );
    $j("#concelho").val( cc );

    $j("#id_distrito option[value="+cd+"]").attr("selected",true);
  
    
	Lightview.hide();
}

function copiaCima(){
	var c4 = $j("#h_cp4").val();
    var c3 = $j("#h_cp3").val();
    
	var pr = $j("#prefixo_morada").val();
    var mr = $j("#morada").val();
    var lc = $j("#localidade").val();
    var cc = $j("#concelho").val();
    var di = $j("#id_distrito").val();
    var pa = $j("#pais").val();
    var te = $j("#telefone").val();
    var fa = $j("#fax").val();
    var tm = $j("#telemovel").val();
    

	$j("#em_cp4").val(c4);
    $j("#em_cp3").val(c3);

	$j("#em_prefixo_morada option[value="+pr+"]").attr("selected",true);
    $j("#em_morada").val(mr);
    $j("#em_localidade").val(lc);
    $j("#em_concelho").val(cc);
    $j("#em_id_distrito option[value="+di+"]").attr("selected",true);
    $j("#em_pais").val(pa);
    $j("#em_telefone").val(te);
    $j("#em_fax").val(fa);
    $j("#em_telemovel").val(tm);

}

function simplePreload()
{ 
  var args = simplePreload.arguments;
  document.imageArray = new Array(args.length);
  for(var i=0; i < args.length; i++)
  {
    document.imageArray[i] = new Image;
    document.imageArray[i].src = args[i];
  }
}

function advertising(){
    $j.ajax({
      url: "/template/pub/advertising.php",
      data: {mod:MOD},
      dataType: "json",
      success: function(html) {
        
        switch(html.type){
        	case 'img': $j("#pub300x250").html(html.link).css({height:html.height,width:html.width}); break;
        	case 'script': 
                $j("#pub300x250").html('<iframe class="iframeadvertising" scrolling="no" allowtransparency="1" src="'+unescape(html.link)+'" width="'+html.width+'" height="'+html.height+'" frameborder="0"></iframe>').css("margin-bottom","20px");
                break;
        }
        
      }
    });
}

function pestana(){
	$j.post(dir + "template/componentes/ajax/pestana.php", function(data){ $j("div#pestana").html(data).fadeIn("slow"); writeObjects();});
}

function hiddenPub(){
	$j(".smartPub").css("display","none");
}
function showPub(){
	$j(".smartPub").css("display","block");
}

/**/
function inicio(){
	if(HTTPS == 'OFF'){
		lastMinit();
     	advertising();
             }
    
    
	installClock();
	//installAutoSugestao();
	//installAutoTab();
	//simplePreload(dir + "/images/mapa/acores_over.gif", dir + "/images/mapa/aveiro_over.gif", dir + "/images/mapa/beja_over.gif", dir + "/images/mapa/braganca_over.gif", dir + "/images/mapa/castelo_over.gif", dir + "/images/mapa/coimbra_over.gif", dir + "/images/mapa/evora_over.gif", dir + "/images/mapa/faro_over.gif", dir + "/images/mapa/guarda_over.gif", dir + "/images/mapa/leiria_over.gif",dir + "/images/mapa/lisboa_over.gif",dir + "/images/mapa/madeira_over.gif", dir + "/images/mapa/portalegre_over.gif", dir + "/images/mapa/porto_over.gif", dir + "/images/mapa/santarem_over.gif",dir + "/images/mapa/setubal_over.gif", dir + "/images/mapa/viana_over.gif", dir + "/images/mapa/vilareal_over.gif", dir + "/images/mapa/viseu_over.gif");

	
    document.oncontextmenu = function (){return false;}
}	

$j(window).bind('load',function(){
		inicio();
});

$j(function(){
	/*$j("a#TABMAPA").click(function(){
		$j("div#rotaMapa").css({"display":"block"});
	});
	
	$j("a#TABLISTA").click(function(){
		$j("div#rotaMapa").css({"display":"none"});
	});*/
	
    $j(".tabMenu a").click(function(){
        if($j("a#TABMAPA").hasClass("selected")){
            $j("div#rotaMapa").css({"display":"block"});
            $j("div#staticMap").css({"display":"none"});
        }else{
            $j("div#rotaMapa").css({"display":"none"});
            
            if($j("a#TABLISTA").hasClass("selected")){
            	$j("div#staticMap").css({"display":"block"});
            }
        }
    });
    if($j("a#TABMAPA").hasClass("selected")){
            $j("div#rotaMapa").css({"display":"block"});
             $j("div#staticMap").css({"display":"none"});
        }
});
function rightMap(){
	$j("div#rotaMapa").css({"display":"block"});
    $j("div#staticMap").css({"display":"none"});
}



$j(function(){

	//PHONE
    $j("span.textPhone[id]").one("click", function(){
    	var ID = $j(this).attr("id");
        $j.post(dir+"template/componentes/ajax/count.php", { id: $j(this).attr("id"), tipo:"1", object:"8", local:"1" } );
        
        $j(this).css({"display":"none"});
        $j("span#numberPhone_"+ID).css({"display":"block"});
    });
    
	//FAX
    $j("span.textFax[id]").one("click", function(){
    	var ID = $j(this).attr("id");
        $j.post(dir+"template/componentes/ajax/count.php", { id: $j(this).attr("id"), tipo:"1", object:"9", local:"1" } );
        
        $j(this).css({"display":"none"});
        $j("span#numberFax_"+ID).css({"display":"block"});
    });
	//MOBILE
    $j("span.textTelm[id]").one("click", function(){
    	var ID = $j(this).attr("id");
        $j.post(dir+"template/componentes/ajax/count.php", { id: $j(this).attr("id"), tipo:"1", object:"10", local:"1" } );
        
        $j(this).css({"display":"none"});
        $j("span#numberTelm_"+ID).css({"display":"block"});
    });



	//Abre Aba	
	$j(".botaoContactos[id]").one("click", function(){
    	var ID = $j(this).attr("id");
        
    	$j.post(dir+"template/componentes/ajax/count.php", { id: $j(this).attr("id"), tipo:"1", object:"1", local:"1" } );
    	$j.post(dir+"template/componentes/ajax/getFotos.php", { id: $j(this).attr("id")},
    		function(html){            	
        		$j(".divFotos"+ID).html(html);
         });
    });
    
	

	//MAIL
	$j(".sendMail[id]").one("click", function(){$j.post(dir+"template/componentes/ajax/count.php", { id: $j(this).attr("id"), tipo:"1", object:"2", local:"1" } );});
	
	//Recomenda
	$j(".sendRecomendar[id]").one("click", function(){$j.post(dir+"template/componentes/ajax/count.php", { id: $j(this).attr("id"), tipo:"1", object:"3", local:"1" } );});
	
	//Gps
	$j(".sendGps[id]").one("click", function(){$j.post(dir+"template/componentes/ajax/count.php", { id: $j(this).attr("id"), tipo:"1", object:"4", local:"1" } );});
	
	//Url
	$j(".sendUrl[id]").one("click", function(){$j.post(dir+"template/componentes/ajax/count.php", { id: $j(this).attr("id"), tipo:"1", object:"6", local:"1" } );});
	
	//Info
	$j("#btInfo[class]").one("click", function(){$j.post(dir+"template/componentes/ajax/count.php", { id: $j(this).attr("class"), tipo:"1", object:"7", local:"1" } );});

});

/* Lightview */
document.observe('lightview:opened', function(event) {
	$j("#pub300x250").hide();
});

document.observe('lightview:hidden', function(event) {
  $j("#pub300x250").show();
});


function showAjaxLogin(){
	//Event.stop();	
	Lightview.show({
		href: dir + 'template/componentes/ajax/login.php',
		rel: 'ajax',
		title: 'Login',
		caption: 'Enter your username and password to login',
		options: {
			autosize: true,
			topclose: true,
			keyboard: false, 
			overlayClose: false,
			ajax: {
				method: 'post',
				evalScripts: true,
				onComplete: function(){
					$('username').focus();
					//$('ajaxForm').observe('submit', submitAjaxFormDemonstration);
				}
			}
		}
	});
	
}

function showSMS(id) {
	//Event.stop();
 	Lightview.show({
		href: dir + 'template/componentes/ajax/SMS.php',
		rel: 'ajax',
		options: {
			menubar: false,
			autosize: true,
			topclose: true,
			keyboard: false, 
			overlayClose: false,
			ajax: {
				method: 'post',
				evalScripts: false,
				parameters:{'id':id},
				onComplete: function(){
				// once the request is complete we observe the form for a submit
				$('sendSMSform').observe('submit', submitAjaxSMS);
				}
			}
		}
	});	
}


function verifica_tel()
{
	var num_caract =  document.getElementById('telemovel').value.length;
    
    if( num_caract == '9')
    {
	    return true;
    } else if(num_caract != '9'){
    	alert("Insira um número de telemóvel válido.");
        return false;
    }
}

function calcula_total_caracteres(){
	var total = 0;
 
 		if (document.getElementById('nome_').checked == true)
        	{
       			var nome = parseInt($('val_nome').value.strip());      
            }else if (document.getElementById("nome_").checked == false){
            	var nome = '';
            }
            total += +nome;
     
		if (document.getElementById('morada').checked == true)
        	{
       			var morada = parseInt($('val_morada').value.strip());      
            }else if (document.getElementById("morada").checked == false){
            	var morada = '';
            }
            total += +morada;
    
		if (document.getElementById('cod_postal').checked == true)
        	{
       			var cod_postal = parseInt($('val_cod_postal').value.strip());
            }else if (document.getElementById("cod_postal").checked == false){
            	var cod_postal = '';
            }
            total += +cod_postal;

		if (document.getElementById('localidade').checked == true)
        	{
       			var localidade = parseInt($('val_localidade').value.strip());
            }else if (document.getElementById("localidade").checked == false){
            	var localidade = '';
            }
            total += +localidade;

		if (document.getElementById('concelho').checked == true)
        	{
       			var concelho = parseInt($('val_concelho').value.strip());
            }else if (document.getElementById("concelho").checked == false){
            	var concelho = '';
            }
    		total += +concelho;        

		if (document.getElementById('distrito').checked == true)
        	{
       			var distrito = parseInt($('val_distrito').value.strip());
            }else if (document.getElementById("distrito").checked == false){
            	var distrito = '';
            }
            total += +distrito;

		if (document.getElementById('telefone_').checked == true)
        	{
       			var telefone_ = parseInt($('val_telefone').value.strip());
            }else if (document.getElementById("telefone_").checked == false){
            	var telefone_ = '';
            }
            total += +telefone_;

    	if (document.getElementById('fax_').checked == true)
        	{
       			var fax_ = parseInt($('val_fax').value.strip());
            }else if (document.getElementById("fax_").checked == false){
            	var fax_ = '';
            }
            total += +fax_;

    	if (document.getElementById('email_').checked == true)
        	{
       			var email_ = parseInt($('val_email').value.strip());
            }else if (document.getElementById("email_").checked == false){
            	var email_ = '';
            }
            total += +email_;

    	if (document.getElementById('gps_').checked == true)
        	{
       			var gps_ = parseInt($('val_gps').value.strip());
            }else if (document.getElementById("gps_").checked == false){
            	var gps_ = '';
            }
            total += +gps_;
      
     //  var total = +nome + +morada + +cod_postal + +localidade + +concelho + +distrito + +telefone_ + +email_ + +gps_ + +fax_;
		if(total>160){
        	alert("A mensagem tem mais de 160 caracteres e não pode ser enviada!");
            return false;
        }
        document.getElementById("totais").innerHTML = 'Tem ' + total + ' caracteres de 160';
}

function submitAjaxSMS(event) {
  // block default form submit
  Event.stop(event);
  
	var valida =  verifica_tel();
    if(!valida)
    return;
    
  Lightview.show({
    href: dir + 'template/componentes/ajax/sendSMS.php',
    rel: 'ajax',
    options: {
	  menubar: false,
	  topclose: false,
	  autosize: true,
	  overlayClose: false,
      ajax: {
        parameters: Form.serialize('sendSMSform') // the parameters from the form
      }
    }
  });
}

function showAjaxRecomendar(id) {
	//Event.stop();
	Lightview.show({
		href: dir + 'template/componentes/ajax/recomend.php',
		rel: 'ajax',
		options: {
			menubar: false,
			autosize: true,
			topclose: true,
			keyboard: false, 
			overlayClose: false,
			ajax: {
				method: 'post',
				evalScripts: true,
				parameters:{'id':id},
				onComplete: function(){
				// once the request is complete we observe the form for a submit
				$('ajaxFormRecomend').observe('submit', submitAjaxRecomendar);
				}
			}
		}
	});
	
}
function submitAjaxRecomendar(event) {
  // block default form submit
  Event.stop(event);
  
  // if there's no text in the box, don't do anything
  var text = $('Rec_Nome').value.strip();
  if (!text) return;
  
  var text = $('Rec_amigo').value.strip();
  if (!text) return;

  var text = $('Rec_email').value.strip();
  if (!text) return;

  var text = $('Rec_mensagem').value.strip();
  if (!text) return;

  Lightview.show({
    href: dir + 'template/componentes/ajax/sendRecomendMail.php',
    rel: 'ajax',
    options: {
	  menubar: false,
	  topclose: false,
	  autosize: true,
	  overlayClose: false,
      ajax: {
        parameters: Form.serialize('ajaxFormRecomend') // the parameters from the form
      }
    }
  });
}


function showAjaxFormDemonstration(id, ti) {
	//Event.stop();
	
	Lightview.show({
		href: dir + 'template/componentes/ajax/contact.php',
		rel: 'ajax',
		//title: 'Pedido de Informaçao',
		//caption: '<nobr>Enter your username and password to login</nobr>',
		options: {
			menubar: false,
			autosize: true,
			topclose: true,
			keyboard: false, 
			overlayClose: false,
			ajax: {
				method: 'post',
				evalScripts: true,
				parameters:{'id':id},
				onComplete: function(){
				// once the request is complete we observe the form for a submit
				$('ajaxForm').observe('submit', submitAjaxFormDemonstration);
				}
			}
		}
	});
	
}

function submitAjaxFormDemonstration(event) {
  // block default form submit
  Event.stop(event);
  
  // if there's no text in the box, don't do anything
 // var text = $('nome').value.strip();
 // if (!text) return;
  
  //var text = $('email').value.strip();
  //if (!text) return;

//  var text = $('assunto').value.strip();
 // if (!text) return;

  //var text = $('mensagem').value.strip();
  //if (!text) return;
	  
  Lightview.show({
    href: dir + 'template/componentes/ajax/sendContactMail.php',
    rel: 'ajax',
    options: {
	  menubar: false,
	  topclose: false,
	  autosize: true,
	  overlayClose: false,
      ajax: {
        parameters: Form.serialize('ajaxForm') // the parameters from the form
      }
    }
  });
}

function checkFieldAjaxFrom() {
	missinginfo = "";
	mail = true;
	tel = true;

	if (document.ajaxForm.nome.value == "") {
		missinginfo = 'true';
		document.ajaxForm.nome.style.border="1px solid #FF0000";
	}else{
		document.ajaxForm.nome.style.border="1px solid #00FF00";
	}
	
	if(document.ajaxForm.email.value == ""){mail = false;}
	if(document.ajaxForm.telefone.value == ""){tel = false;}
	
	if(mail){
		if(document.ajaxForm.email.value.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)==null){
			missinginfo = 'true';
			document.ajaxForm.email.style.border="1px solid #FF0000";
			mail = false;;
		}else{
			mail = true;
			document.ajaxForm.email.style.border="1px solid #00FF00";
		}
	}
	
	if(!mail && !tel){
		document.ajaxForm.email.style.border="1px solid #FF0000";
		mail=false;
	}else{
		if(mail){document.ajaxForm.email.style.border="1px solid #00FF00";}
		if(tel){document.ajaxForm.telefone.style.border="1px solid #00FF00";}	
	}
	
	
	

	if (document.ajaxForm.assunto.value == "") {
		missinginfo = 'true';
		document.ajaxForm.assunto.style.border="1px solid #FF0000";
	}else{
		document.ajaxForm.assunto.style.border="1px solid #00FF00";
	}
	
	if (document.ajaxForm.mensagem.value == "") {
		missinginfo = 'true';
		document.ajaxForm.mensagem.style.border="1px solid #FF0000";
	}else{
		document.ajaxForm.mensagem.style.border="1px solid #00FF00";
	}

	if (missinginfo != "") {
		return false;
	}
	else {
		return true;
	}
}
/* VALID CREDIT CARD */
/*============================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from a variety of sources on 
the web, although the best is probably on Wikepedia ("Credit card number"):

  http://en.wikipedia.org/wiki/Credit_card_number

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003
Updated:    26th Feb. 2005      Additional cards added by request
Updated:    27th Nov. 2006      Additional cards added from Wikipedia
Updated:    18th Jan. 2008      Additional cards added from Wikipedia
Updated:    26th Nov. 2008      Maestro cards extended
Updated:    19th Jun. 2009      Laser cards extended from Wikipedia

*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard (cardnumber, cardname) {
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "VisaCard", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "305, 36, 38, 54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "12,13,14,15,16,18,19", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844",
               checkdigit: true};
  cards [12] = {name: "LaserCard", 
               length: "16,17,18,19", 
               prefixes: "6304,6706,6771,6709",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i < cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}

/*============================================================================*/

