﻿//GLOBAL JQUERY
$(function(){

	//INPUTS CLEAR
	$.fn.defaultValue = function(){
		return $(this).each(function(){
			$(this).focus(function(){
				if($(this).val()==$(this).attr("title")) $(this).val("");
			});
			$(this).blur(function(){
				if(!$(this).val()) $(this).val($(this).attr("title"));
			});
		}); 
	};


	//WORKAROUND FOR DEPRECATED BROWSER.VERSION
	jQuery.browser.msie6 = jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && typeof window['XMLHttpRequest'] != "object";

	/* PNG fix */
	if ($.browser.msie && $.browser.version == '6.0' && typeof($.ifixpng) == "function") {
		$.ifixpng('/_layouts/1033/edp/images/global/transparent.gif');
		$("img[src$='.png'], .residenciais,, .pme, .empresariais, .spaceli, .bgtop, .bgbottom").ifixpng();
	};



	
	//MENU
	if ($(".sections").length) {
		$(".submenu_container").hide();
		$(".sections .submenu .submenu_item").hoverIntent({
			sensitivity: 5,
			interval: 150,
			over: function(){
				$(this).find(".submenu_container").slideDown();
				$(this).find(".submenu_item_off").hide();
				$(this).find(".submenu_item_on").show();
			},
			timeout: 300, 
			out: function(){
				$(this).find(".submenu_container").slideUp();
				$(this).find(".submenu_item_on").hide();
				$(this).find(".submenu_item_off").show();
			}
		});
		//alternative keyboard methods
		$(".sections .submenu .submenu_item").find("a:first").focus(function(){
			//close
			$(this).parent().find("a:last").blur(function(){
				$(this).parents(".submenu_item").find(".submenu_container").slideUp();
				$(this).parents(".submenu_item").find(".submenu_item_on").hide();
				$(this).parents(".submenu_item").find(".submenu_item_off").show();
			});
			//open
			$(this).parent().find(".submenu_container").slideDown();
			$(this).parent().find(".submenu_item_off").hide();
			$(this).parent().find(".submenu_item_on").show();
		});
	
	};



	
	//SEARCH
	$("input.defaultValue").defaultValue();
    $("a.search-btn").hover(
		function(){
			$(this).find('.search-btn_off').hide();
			$(this).find('.search-btn_on').show();
		},
		function(){
			$(this).find('.search-btn_on').hide();
			$(this).find('.search-btn_off').show();
		}
	);



	
	//LATERAL SUB-MENU
	if ($(".lateralNavigationContainer").length) {
		$(".lateralNavigation li ul").hide();
		$(".lateralNavigation li ul li ul").hide();
		$(".lateralNavigation li ul").parent().addClass("plus");
		$(".lateralNavigation li ul").parent().hoverIntent({
			sensitivity: 5,
			interval: ($.browser.msie)  ?  75 : 150, //tempo em ms para o ie e restantes browsers
			over: function(){
				$(this).removeClass("plus").addClass("minus");
				$(this).find("ul:eq(0)").slideDown();
			},
			timeout: 300, 
			out: function(){
				$(this).removeClass("minus").addClass("plus");
				$(this).find("ul:eq(0)").slideUp();
			}
		});
		//alternative keyboard methods
		$(".lateralNavigation li ul").parent().find("a:first").focus(function(){
			$(this).parent().removeClass("plus").addClass("minus");
			$(this).parent().find("ul:eq(0)").slideDown();
		});
		$(".lateralNavigation li ul").find("a:last").blur(function(){
			$(this).parent().parent("ul").parent().removeClass("minus").addClass("plus");
			$(this).parent().parent("ul").slideUp();
		});
	};

	
	


	
	//HIGHLIGHT TABLES
	if ($(".highlight, .highlightWithoutCell, .highlightMoreInfo, .highlightMoreInfo2").length) {
		
		$(".highlight, .highlightWithoutCell, .highlightMoreInfo, .highlightMoreInfo2").each(function(){
			$(this).find("tr:odd").addClass("alternate");
		});
		$(".highlightMoreInfo2 td:not(.allowAlternate), .highlightMoreInfo2 th:not(.allowAlternate), .highlightMoreInfo td:not(.allowAlternate), .highlightMoreInfo th:not(.allowAlternate), .highlight tr:not(.allowAlternate), .highlight th:not(.allowAlternate), .highlightWithoutCell td:not(.allowAlternate), .highlightWithoutCell th:not(.allowAlternate)").each(function() {
			$(this).hover(function(){
				$(this).closest("table").find(".alternate").removeClass("alternate");
			}, function(){
				$(this).closest("table").find("tr:odd").addClass("alternate");
			});
		});
		
		$(".highlightMoreInfo td.highlightThis, .highlightMoreInfo2 td.highlightThis").live("mouseover",function(){
			$(this).parent().find(".goLink").addClass("remoteHover");
		});
		$(".highlightMoreInfo td, .highlightMoreInfo2 td").mouseout(function(){
			$(this).parent().find(".goLink").removeClass("remoteHover");
		});
		
		//if($.browser.msie && $.browser.version=='6.0') { } else {
		if($.browser.msie) { } else {
			$(".highlight").each(function() {
				$(this).tableHover({
					rowClass: 'highlightBG',
					colClass: 'highlightBG',
					cellClass: 'highlightThis',
					headCols: true,
					ignoreRowClass: 'thead'
				});
			});
			$(".highlightMoreInfo").each(function() {
				$(this).tableHover({
					rowClass: 'highlightBG',
					colClass: 'highlightBG',
					cellClass: 'highlightThis',
					headCols: true,
					ignoreRowClass: 'thead',
					ignoreCols: [6]
				});
			});
			$(".highlightMoreInfo2").each(function() {
				$(this).tableHover({
					rowClass: 'highlightBG',
					colClass: 'highlightBG',
					cellClass: 'highlightThis',
					headCols: true,
					ignoreRowClass: 'thead',
					ignoreCols: [4]
				});
			});
			$(".highlightWithoutCell").each(function() {
				$(this).tableHover({
					rowClass: 'highlightBG',
					colClass: 'highlightBG',
					headCols: true,
					ignoreRowClass: 'thead'
				});
			});
		}
		
	};
	
	$("a.closeTable").parent().next(".tableContainer").toggle();
	$(".tableTitle").click(function(event){
		event.preventDefault();
		if ($(this).next(".tableContainer").next(".relativeDescription").length) {
			$(this).next(".tableContainer").slideToggle();
			$(this).next(".tableContainer").next(".relativeDescription").slideToggle();
			$(this).children("a").toggleClass("closeTable");
		} else {
			$(this).next(".tableContainer").slideToggle();
			$(this).children("a").toggleClass("closeTable");
		}
	});
	//alternative keyboard methods
	$(".tableTitle").keypress(function(e){
		//toggles the table on "enter" key pressed
		if(e.wich == 13){ $(this).click(); }
	});



	
	//TABLE SORTER
	if($(".tableSorter").length) {
		$(".tableSorter").tablesorter();
	}

	//TABLE SORTER
	$(".alternateLongTable").each(function(){
		$(this).find("tr:odd").addClass("alternate");
	});



	
	//SLIDE CONTENT
	$(".slideContent:not('.open') .titleExpand a").toggleClass("closed");
	$(".slideContent:not('.open') .content").hide();
	$(".slideContent .titleExpand a").click(function(event){
		event.preventDefault();
		$(this).toggleClass("closed").parent().parent().find(".content").slideToggle();
	});
	//alternative keyboard methods
	$(".slideContent .titleExpand a").keypress(function(e){
		//expand content when "enter" key is pressed
		if(e.wich == 13){ $(this).click(); }
	});
	
	if($(".itemToValue").length) {
		$(".itemToValue").each(function() {
			$(".slideContent:not('.open')").hide();
			$(this).find(".item a").click(function(event) {
				event.preventDefault();
				$(this).parents(".itemToValue").find(".slideContent").slideToggle();
			});
			//alternative keyboard methods
			$(this).find(".item a").keypress(function(e){
				//toggles on "enter" key pressed
				if(e.wich == 13){ $(this).click(); }
			});
		});
	}



	
	//GOOGLE MAPS
	if($(".gMaps").length) {
		$(".gMaps").jmap('init', {
			'mapType': 'hybrid',
			'mapCenter': [38.726057, -9.149238],
			'mapZoom': 17
		});
		$(".gMaps").jmap('AddMarker', {
			'pointLatLng': [38.726057, -9.149238],
			'pointHTML': '<strong>EDP Sede</strong><br><u>Descri�o:</u> Lorem ipsum dolor site nonummy'
		});
	};
	//Parceiros
	if($(".partnerMap").length) {
		$(".partnerMap").jmap('init', {
			'mapType': 'hybrid',
			'mapCenter': [38.726057, -9.149238],
			'mapZoom': 17
		});
		$(".partnerMap").jmap('AddMarker', {
			'pointLatLng': [38.726057, -9.149238],
			'pointHTML': '<strong>EDP Sede</strong><br><u>Descri��o:</u> Lorem ipsum dolor site nonummy'
		});
	};
	//STORE AND AGENTS LOCATION MAP
	if($(".storesAgentsLocationMap").length) {
		initialize();
	};


	
	//INPUT'S HOVER AND OUT
	if($("input, select, textarea").length) {
		$("input[type='text'], input[type='password'], select, textarea").focus(function() {
			$(this).addClass("inputFocus");
		});
		$("input[type='text'], input[type='password'], select, textarea").blur(function() {
			$(this).removeClass("inputFocus");
		});
	};



	
	//FORM HELP
	$(".helpContent").hide();
	$(".help").hover(function(){
		$($(this).attr("href")).slideDown("slow");
	});
	$('.help').click(function(event){
		event.preventDefault();
		$($(this).attr("href")).slideUp("slow");
	});
	//alternative keyboard methods
	$(".help").focus(function(){
		$($(this).attr("href")).slideDown("slow");
	});
	$('.help').keypress(function(e){
		//triggers help when "enter" key is pressed
		if(e.wich == 13){ $(this).click(); }
	});



	
	//SIMULATOR TABS
	if($(".simulatorContentContainer").length){
		//a mesma verificacao e feita para os restante simuladores ou step atraves do ID de cada container
		$(".simulatorInfoContainer").hide();
		//Passo 1
		$("form[name='step1'] .submit").submit(function(event){
			event.preventDefault();
			$(".simulatorContentContainer li:eq(0) a").addClass("ui-tabs-done");
			$(".simulatorContentContainer").tabs('option','selected', 1);
			//alert($("form[name='step1']").serialize());
			
			//mostra resultados do passo1 na barra lateral de suporte
			$(".simulatorInfoContainer").show();
			$(".simulatorInfoContainer div#passo2_results").hide();
			$(".simulatorInfoContainer p#tipo_local_consumo_result").html($("select[name='tipo_local_consumo'] option:selected").text());
			$(".simulatorInfoContainer p#potencia_contratada_result").html($("select[name='potencia_contratada'] option:selected").text());
			$(".simulatorInfoContainer p#tarifa_result").html($("select[name='tarifa'] option:selected").text());
			$(".simulatorInfoContainer p#tipo_simulacao_result").html($("input[name='tipo_simulacao']:checked").val());
		});
		//alternative keyboard methods
		$("form[name='step1'] .submit").keypress(function(e){
			//submit when "enter" key is pressed
			if(e.wich == 13){ $(this).submit(); }
		});
		//Passo 2
		$("form[name='step2'] input[name='consumo_vazio']").defaultValue();
		$("form[name='step2'] input[name='consumo_cheia']").defaultValue();
		$("form[name='step2'] input[name='consumo_fora_vazio']").defaultValue();
		$("form[name='step2'] .submit").submit(function(event){
			event.preventDefault();
			$(".simulatorContentContainer li:eq(1) a").addClass("ui-tabs-done");
			$(".simulatorContentContainer").tabs('option','selected', 2);
			//alert($("form[name='step2']").serialize());
			
			//mostra resultados do passo2 na barra lateral de suporte
			$(".simulatorInfoContainer div#passo2_results").show();
			$(".simulatorInfoContainer p#data_leitura1_result").html($("input[name='data_leitura1']").val());
			$(".simulatorInfoContainer p#data_leitura2_result").html($("input[name='data_leitura2']").val());
			$(".simulatorInfoContainer p#consumos_periodo_result").html($("input[name='consumo_vazio']'").val()+" - "+$("input[name='consumo_cheia']'").val()+" - "+$("input[name='consumo_fora_vazio']'").val());
		});
		//alternative keyboard methods
		$("form[name='step2'] .submit").keypress(function(e){
			//submit when "enter" key is pressed
			if(e.wich == 13){ $(this).submit(); }
		});
		$("form[name='step2'] .goBack").click(function(event){
			event.preventDefault();
			$(".simulatorContentContainer").tabs('option','selected', 0);
			$(".simulatorContentContainer li:eq(0) a").removeClass("ui-tabs-done");
			$(".simulatorInfoContainer").hide();
		});
		//alternative keyboard methods
		$("form[name='step2'] .goBack").keypress(function(e){
			//go back when "enter" key is pressed
			if(e.wich == 13){ $(this).click(); }
		});

		$(".simulatorContentContainer").tabs();
	};



	
	//SERVICO DE ALERTAS TABS
	if($(".simulatorContentContainer").length){
		//a mesma verificacao e feita para os restante simuladores ou step atraves do ID de cada container
		$(".simulatorInfoContainer").hide();
		//Passo 1
		$("form[name='step1'] .submit").submit(function(event){
			event.preventDefault();
			$(".simulatorContentContainer li:eq(0) a").addClass("ui-tabs-done");
			$(".simulatorContentContainer").tabs('option','selected', 1);
			//alert($("form[name='step1']").serialize());
			
			//mostra resultados do passo1 na barra lateral de suporte
			$(".simulatorInfoContainer").show();
			$(".simulatorInfoContainer div#passo2_results").hide();
			$(".simulatorInfoContainer p#email_result").html($("input[name='email']").val());
		});
		//alternative keyboard methods
		$("form[name='step1'] .submit").keypress(function(e){
			//submit when "enter" key is pressed
			if(e.wich == 13){ $(this).submit(); }
		});
		//Passo 2
		$("form[name='step2'] .submit").submit(function(event){
			event.preventDefault();
			$(".simulatorContentContainer li:eq(1) a").addClass("ui-tabs-done");
			$(".simulatorContentContainer").tabs('option','selected', 2);
			//alert($("form[name='step2']").serialize());
			
			//mostra resultados do passo2 na barra lateral de suporte
			$(".simulatorInfoContainer div#passo2_results").show();
			$(".simulatorInfoContainer p#eu_sou_result").html($("select[name='eu_sou'] option:selected").text());
			$(".simulatorInfoContainer p#empresa_result").html($("input[name='empresa']").val());
			$(".simulatorInfoContainer p#nome_apelido_result").html($("input[name='nome']").val()+" "+$("input[name='apelido']").val());
			var newHTMLInteresses = "";
			$("input[name^='interesse']:checked'").each(function(){ newHTMLInteresses += $(this).next("label").text()+'<br />'; });
			$(".simulatorInfoContainer p#subscricoes_result").html(newHTMLInteresses);
			var newHTMLIdiomas = "";
			$("input[name^='lang']:checked'").each(function(){ newHTMLIdiomas += $(this).next("label").text()+'<br />'; });
			$(".simulatorInfoContainer p#idiomas_result").html(newHTMLIdiomas);
		});
		//alternative keyboard methods
		$("form[name='step2'] .submit").keypress(function(e){
			//submit when "enter" key is pressed
			if(e.wich == 13){ $(this).submit(); }
		});
		$("form[name='step2'] .goBack").click(function(event){
			event.preventDefault();
			$(".simulatorContentContainer").tabs('option','selected', 0);
			$(".simulatorContentContainer li:eq(0) a").removeClass("ui-tabs-done");
			$(".simulatorInfoContainer").hide();
		});
		//alternative keyboard methods
		$("form[name='step2'] .goBack").keypress(function(e){
			//go back when "enter" key is pressed
			if(e.wich == 13){ $(this).click(); }
		});

		$(".simulatorContentContainer").tabs();
	};



	
	//DATE PICKER INVESTIDORES
	if($(".datePicker").length) {
		$(".datePicker").datepicker({
			maxDate: '0',
            minDate: new Date(1997, 1 - 1, 1),
			showOn: "both", 
			buttonImage: "/_layouts/1033/edp/images/global/calendar_datepick_icon.gif", 
			buttonImageOnly: true,
			changeMonth: true,
            changeYear: true,
            dateFormat: 'dd-mm-yy'
        });
    };

    //DATE PICKER INTERRUPCOES PROGRAMADAS
    if ($(".datePickerIP").length) {
        $(".datePickerIP").datepicker({
            maxDate: '2w',
            minDate: '-2m',
            showOn: "both",
            buttonImage: "/_layouts/1033/edp/images/global/calendar_datepick_icon.gif",
            buttonImageOnly: true,
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd-mm-yy'
		});
	};



	
	//GENERAL FORM VALIDATOR
	if($("form.validate").length) {
		$("form.validate").each(function(){
			$(this).validate({
				errorElement: "span",
				errorClass: "errorMsg",
				errorPlacement: function(error, element, errorClass) {
					error.appendTo(element.parents("fieldset").find(".errorContainer"));
					/*switch (element.attr('type')){
						case 'radio':
						case 'checkbox':
							error.appendTo( element.parent().parent().parent().prev("label") );
							element.removeClass(errorClass);
							break;
						default:
							error.appendTo( element.parent().parent().prev("legend").find(".errorMsg") );
							break;
					}*/
				},
				highlight: function(element) {
					$(element).addClass("errorInput");
					$(element).prev("label").addClass("necessary");
				},
				unhighlight: function(element) {
					$(element).removeClass("errorInput");
					$(element).prev("label").removeClass("necessary");
				},
				rules: {
					nome: { required: true },
					apelido: { required: true },
					assunto: { required: true },
					morada: { required: true },
					codigo_postal: { required: true, number: true },
					localidade: { required: true },
					data_nascimento: { required: true, datePT: true },
					sexo: { required: true },
					telefone: { number: true },
					telemovel: { number: true },
					username: { required: true, minlength: 3 },
					email: { required: true, email: true },
					email_confirm: { equalTo: "#email" },
					password: { required: true, minlength: 6 },
					password_confirm: { equalTo: "#password" },
					aceita_termos: { required: true },
					num_accoes: { required: true, number: true },
					data_cotacao: { required: true, datePT: true },
					montante_investido:{ required: true, number: true },
					data_investimento: { required: true, datePT: true }
				},
				messages: {
					aceita_termos: {
						required: function(value, element){
							$(element).parents("fieldset").find(".errorRequired").html("&Eacute; obrigat&oacute;rio aceitar os Termos e Condi&ccedil;&otilde;es!").addClass("errorMsg").show();
						}
					}
				}
			});			
		});
	};



	
	//GENERAL FORM PLUGINS
	//slider
	if($(".slider").length) {
		$(".slider").each(function(){
			var options = $(this).parent().find("input[type='radio']");
			options.hide();
			$(this).parent().find("label").width($(this).parent().width()/options.length);
			$(this).slider({
				min: 0,
				max: options.length-1,
				step: 1,
				stop: function(event, ui){
					options.eq(ui.value).attr("checked", "checked");
				}
			});
			$(this).parent().find("label.inline").css({"margin-top":"5px", "text-align":"center", "padding":"0px"});
			$(this).parent().find("label:eq(1)").css({"text-align":"left"});
			$(this).parent().find("label:last").css({"text-align": "right"});
		});
	};
	//dependencias
	if ($("select.dependencia").length) {
	    $("select.dependencia_result optgroup").hide();
	    $("select.dependencia").change(function() {
			$("select.dependencia_result option[value='initialValue']").remove();
			$("select.dependencia_result optgroup").hide();
			$("#"+$(this).val()).show().find("option:eq(0)").attr("selected","selected");
	    });
	};



	
	//GLOSSARIO
	/*
	if($(".alfabeto").length){
		var hash = location.hash;
		hash = hash.substr(1, hash.length).toUpperCase();
		
		if(hash){
			$(".alfabeto a").removeClass("on");
			$(".alfabeto a[title='"+hash+"']").addClass("on")
			$(".glossario").load($(".alfabeto a[title='"+hash+"']").attr("href")+" .glossario")
		}
		$(".alfabeto a").click(function(event){
			event.preventDefault();
			if(!$(this).is(".disabled")){
				$(".alfabeto a.on").removeClass("on");
				$(this).addClass("on");
				var url = $(this).attr("href");
				$(".glossario").fadeTo("fast", 0, function(){
					$(this).load(url + " .glossario", function(){
						$(".glossario").fadeTo("fast", 1);
					});
				});
			}
		});
	}
	*/



	
	//ADVANCED SEARCH
    if ($(".advancedSearch").length) { 
        $(".contentButtonOpen").toggle(
			function(event) {
			    event.preventDefault();
			    $(".advancedSearch").slideDown(function() {
			        $(this).fadeTo("fast", 1);
			        $(".contentButtonOpen").addClass("contentButtonClose");
					var closeText = $(".contentButtonClose").attr("rel");
					var openText = $(".contentButtonClose").attr("title");
			        $(".contentButtonClose").attr({"title": closeText, "rel": openText}).html(closeText);
			    });
			    ($.browser.msie && $.browser.version == '6.0') ? distanceBottom = "-28px" : distanceBottom = "-27px";
			    $(this).animate({ "bottom": distanceBottom });
			}, function() {
			    $(".advancedSearch").fadeTo("fast", 0, function() {
			        $(".advancedSearch").slideUp(function() {
			            $(".contentButtonOpen").removeClass("contentButtonClose");
						var openText = $(".contentButtonOpen").attr("rel");
						var closeText = $(".contentButtonOpen").attr("title");
			            $(".contentButtonOpen").attr({"title": openText, "rel": closeText}).html(openText);
			        });
			    });
			    ($.browser.msie && $.browser.version == '6.0') ? distanceBottom = "-1px" : distanceBottom = "0px";
			    $(this).animate({ "bottom": distanceBottom });
			}
		);
		 if ($(".openAdvancedSearch").length) {
            $(".contentButtonOpen").addClass("contentButtonClose");
            ($.browser.msie && $.browser.version == '6.0') ? distanceBottom = "-28px" : distanceBottom = "-27px";
            var closeText = $(".contentButtonClose").attr("rel");
			var openText = $(".contentButtonClose").attr("title");
			$(".contentButtonClose").attr({"title": closeText, "rel": openText}).html(closeText).css({ "bottom": distanceBottom });
			$(".contentButtonOpen").click();
        } else {
			$(".advancedSearch").hide().fadeTo("fast", 0);
        }
    }



	
	//LINKS HOVER'S
	//documentos legais
	if($("dl.documentList").length){
		$("dl.documentList dd.image").each(function(){
			if($(this).find("img").length){
				$(this).hover(
					function() {
						$(this).parent().find("dt a").addClass("hover");
					},
					function() {
						$(this).parent().find("dt a").removeClass("hover");
					}
				);
			}
		});
	};



	
	//SITEMAP
	if($("#siteMap").length){
		$("ul#siteMap li").each(function(){
			if($(this).find("ul").length){
				$(this).find("ul").hide();
				$(this).find("a:first").addClass("open").click(function(event) {
					event.preventDefault();
					$(this).next("ul").slideToggle();
					$(this).toggleClass("close");
				});
				//alternative keyboard methods
				$(this).find("a:first").addClass("open").keypress(function(e){
					//toggles on "enter" key pressed
					if(e.wich == 13){ $(this).click(); }
				});
			}
		});
	}



	
	//CHANGE MOOD
	if(typeof bgObject == 'object'){

	    function showObject(object) {
	        if (object.indexOf('.jpg') > -1) {
	            $("#flashContainer").css({ "background-image": "url('" + object + "')", "background-repeat": "no-repeat", "background-position": "center top" });
	        } else if (object.indexOf('.swf') > -1) {
	            swfobject.embedSWF(object, "flashContainer", "100%", "670", "9.0.0", "/_layouts/1033/edp/flash/expressInstall.swf", false, { menu: "false", wmode: "transparent", allowfullscreen: "true", bgcolor: "#ffffff" });
	        }
	    };
		var hoje = new Date();
		var mes = hoje.getMonth();
		var hora = hoje.getHours();
	
		for(var i=0;i<horario[mes].length;i++){
			if(horario[mes][i].inicio>horario[mes][i].fim){
				if((hora>=horario[mes][i].inicio && hora<=23) || (hora>=0 && hora<horario[mes][i].fim)){
					//alert(bgObject[horario[mes][i].imagem]);
					showObject(bgObject[horario[mes][i].imagem]);
				}
			} else {
				if(hora>=horario[mes][i].inicio && hora<horario[mes][i].fim){
					//alert(bgObject[horario[mes][i].imagem]);
					showObject(bgObject[horario[mes][i].imagem]);
				}
			}
		}
	}

	
	//MEDIA PLAYER
	//if($("#extendedMediaPlayer").length) {
	//	var flashvars = {dataSource: "/_layouts/1033/edp/xml/videosMediaPlayer.xml"};
	//	var params = {menu:"false", wmode:"transparent", allowfullscreen:"true"};
	//	swfobject.embedSWF("/_layouts/1033/edp/flash/videoPlayerEDP_extended.swf", "extendedMediaPlayer", "875", "248", "8.0.0", false, flashvars, params, false);
	//}
	//if($("#extendedMediaPlayer_4x3").length) {
	//	var flashvars = {dataSource: "/_layouts/1033/edp/xml/videosMediaPlayer_4x3.xml"};
	//	var params = {menu:"false", wmode:"transparent", allowfullscreen:"true"};
	//	swfobject.embedSWF("/_layouts/1033/edp/flash/videoPlayerEDP_extended_4x3.swf", "extendedMediaPlayer_4x3", "875", "248", "8.0.0", false, flashvars, params, false);
	//}

	// JORGE OLD
	if ($(".videoListed").length) {
	    var qs = window.location.search.substring(1);
	    qs = qs.split("&");
			
	    var pageName = "";

	    for (i = 0; i < qs.length; i++) {
	        var aux = qs[i].split("=");
	        if (aux[0] == "n") {
	            pageName = aux[1];
	        }
	    }

	    if (pageName != "")
	        document.getElementById(pageName).className += " videoListedActive";
	}

	// END JORGE OLD

	$(".filterVideosBar a").click(function(event) {
	    //TECRUZ
		//event.preventDefault();
		if($(".filterVideosBar li:not(.selected)")) {
			$(".filterVideosBar li.selected").removeClass("selected");
			$(this).parent().addClass("selected");
		}
	});

// DELETED BY CALEJO
//	$(".videoListed").click(function(event) {
//		event.preventDefault();
//	$(".videoListedActive").removeClass("videoListedActive");
//		$(this).addClass("videoListedActive", 500);
//	});
// END DELETED BY CALEJO
	//alternative keyboard methods
	$(".videoListed").keypress(function(e){
		if(e.wich == 13){ $(this).click(); }
	});
	
	//if($(".playingVideo").length) {
	//	var flashvars = {file: "/_layouts/1033/edp/videos/video3.flv"}; //video default
	//	var params = {menu:"false", wmode:"opaque", allowfullscreen:"true", allowScriptAccess:"always"};
	//	swfobject.embedSWF("/_layouts/1033/edp/flash/videoPlayerEDP.swf", "videoPlayer", "400", "225", "9.0.0", "/_layouts/1033/edp/flash/expressInstall.swf", flashvars, params, false);
	//}
//	if($(".playingVideo_4x3").length) {
//		var flashvars = {file: "/_layouts/1033/edp/videos/video3.flv"}; //video default
//		var params = {menu:"false", wmode:"opaque", allowfullscreen:"true", allowScriptAccess:"always"};
//		swfobject.embedSWF("/_layouts/1033/edp/flash/videoPlayerEDP_4x3.swf", "videoPlayer", "400", "300", //"9.0.0", "/_layouts/1033/edp/flash/expressInstall.swf", flashvars, params, false);
//	}

// DELETED BY CALEJO
//	if($(".videoListed").length) {
//		function selectVideo(videoSelected) {
//			document.getElementById("videoPlayer").playVideo(videoSelected);
//		}
//		$(".videoListed a").click(function() { 
//			selectVideo($(this).attr('href'));
//		});
//	}
// END DELETED BY CALEJO

	
	//CAPTCHA
	$("#refreshimg").click(function(){
	$.post('newsession.php');
	$("#captchaimage").load('image_req.php');
	return false;
	});
	
	$("#captchaform").validate({
		rules: {
			captcha: {
				required: true,
				remote: "process.php"
			}
		},
		messages: {
			captcha: "Correct captcha is required. Click the captcha to generate a new one"	
		},
		submitHandler: function() {
			alert("Correct captcha!");
		},
		success: function(label) {
			label.addClass("valid").text("Valid captcha!")
		},
		onkeyup: false
	});


// FLASH CANNOT BE USED - CALEJO
	
	
//	//MAPA �REA DE REDE
//	if($("#mapAreaRede").length) {
//		var flashvars = {xmlPath: "/_layouts/1033/edp/xml/mapaPortugal_area_rede.xml"};
//		var params = {menu:"false", wmode:"transparent", allowScriptAccess:"always"};
//		swfobject.embedSWF("/_layouts/1033/edp/flash/mapaPortugal_area_rede.swf", "mapAreaRede", "289", "433", "9.0.0", "/_layouts/1033/edp/flash/expressInstall.swf", flashvars, params, false);
//		
//		$.fn.selectAreaRede = function(link) {
//			window.location = link;
//		}
//	}
//	

//	
//	//MAPA DISTRITO
//	if($("#mapDistritos").length) {
//		var flashvars = {xmlPath: "/_layouts/1033/edp/xml/mapaPortugal_mapa_distritos.xml"};
//		var params = {menu:"false", wmode:"transparent", allowScriptAccess:"always"};
//		swfobject.embedSWF("/_layouts/1033/edp/flash/mapaPortugal_mapa_distritos.swf", "mapDistritos", "289", "433", "9.0.0", "/_layouts/1033/edp/flash/expressInstall.swf", flashvars, params, false);
//		
//		$.fn.selectDistrito = function(link) {
//			$(".fldDistrito").val(link);
//		}
//	}
//	
//	
//	//MAPA DIREC��O DE REDE E CLIENTES
//	if($("#mapRedeClientes").length) {
//		var flashvars = {xmlPath: "/_layouts/1033/edp/xml/mapaPortugal_rede_clientes.xml"};
//		var params = {menu:"false", wmode:"transparent", allowScriptAccess:"always"};
//		swfobject.embedSWF("/_layouts/1033/edp/flash/mapaPortugal_rede_clientes.swf", "mapRedeClientes", "289", "433", "9.0.0", "/_layouts/1033/edp/flash/expressInstall.swf", flashvars, params, false);
//		
//		$.fn.selectRedeClientes = function(link) {
//			$(".fldRedeClientes").val(link);
//		}
//	}
	
	//MAPA ÁREA DE REDE
    $("#mapAreaRede area").hover(function() {
        eval('var coords = ' + this.className);
        $(".mapBgAreaRede").css({ 'background-position': coords.xMap + ' ' + coords.yMap });
        $(".mapLabel").html($(this).attr('alt'));
        $(".mapLabel").css({ 'top': coords.yLabel, 'left': coords.xLabel });
    }, function() {
        $(".mapLabel").html('&nbsp;');
        $(".mapBgAreaRede").css('background-position', '0 0');
    });


    //MAPA DISTRITO
    $("#mapDistritos area").hover(function() {
        eval('var coords = ' + this.className);
        $(".mapBgDistritos .mapLabel").html($(this).attr('alt')).css({ 'top': coords.yLabel, 'left': coords.xLabel });
        $(".mapBgDistritos").css({ 'background-position': coords.xMap + ' ' + coords.yMap });
        lastLabel = $(this).attr('alt');
        lastxLabel = coords.xLabel;
        lastyLabel = coords.yLabel;
        lastxMap = coords.xMap;
        lastyMap = coords.yMap;
    }, function() {
        $(".mapBgDistritos .mapLabel").html('&nbsp;');
        $(".mapBgDistritos").css('background-position', '0 0');
    });
    $("#mapDistritos area").click(function(event) {
        event.preventDefault();
        $(".fldDistrito").val($(this).attr('alt'));
        DoPostBackDistritos();
    });


    //MAPA DIRECÇÃO DE REDE E CLIENTES
    $("#mapRedeClientes area").hover(function() {
        eval('var coords = ' + this.className);
        $(".mapBgRedeClientes").css({ 'background-position': coords.xMap + ' ' + coords.yMap });
        $(".mapBgRedeClientes .mapLabel").html($(this).attr('alt')).css({ 'top': coords.yLabel, 'left': coords.xLabel });
    }, function() {
        $(".mapBgRedeClientes .mapLabel").html('&nbsp;');
        $(".mapBgRedeClientes").css('background-position', '0 0');
    });
    $("#mapRedeClientes area").click(function(event) {
        event.preventDefault();
        $(".fldRedeClientes").val($(this).attr('alt'));
        DoPostBackDRC();
    });

	
	
	
	// START ---------- TABS SIMULATOR
	if($(".simulatorContentContainer").length) {
		//PASSO 1
		$("form[name='step1'] select, form[name='step1'] input[type='text']").val("");
		$("form[name='step1'] input[name='tipo_simulacao']").each(function(){this.checked = false;});
		$("form[name='step1'] select:not([name='tipo_local_consumo']), form[name='step1'] input, form[name='step1'] textarea").attr("disabled", "disabled");
		$("form[name='step1'] select[name='tipo_local_consumo']").change(function() {
			if($(this).val())	{
				$("form[name='step1'] select[name='potencia_contratada']").removeAttr("disabled");
			} else {
				$("form[name='step1'] select[name='potencia_contratada'], select[name='tarifa']").attr("disabled", "disabled").val("");
				$("form[name='step1'] input[name='tipo_simulacao']").attr("disabled", "disabled").each(function(){this.checked = false;});
				$("form[name='step1'] input[type='submit']").attr("disabled", "disabled");
			}
		});
			$("form[name='step1'] select[name='potencia_contratada']").change(function() {
			if($(this).val())	{
				$("form[name='step1'] select[name='tarifa']").removeAttr("disabled");
			} else {
				$("form[name='step1'] select[name='tarifa']").attr("disabled", "disabled").val("");
				$("form[name='step1'] input[name='tipo_simulacao']").attr("disabled", "disabled").each(function(){this.checked = false;});
				$("form[name='step1'] input[type='submit']").attr("disabled", "disabled");
			}
		});
		$("form[name='step1'] select[name='tarifa']").change(function() {
			if($(this).val())	{
				$("form[name='step1'] input[name='tipo_simulacao']").removeAttr("disabled");
			} else {
				$("form[name='step1'] input[name='tipo_simulacao']").attr("disabled", "disabled").each(function(){this.checked = false;});
				$("form[name='step1'] input[type='submit']").attr("disabled", "disabled");
			}
		});
		$("form[name='step1'] input[name='tipo_simulacao'] ").click(function() {
			$("form[name='step1'] input[type='submit']").removeAttr("disabled");
		});
		//alternative keyboard methods
		$("form[name='step1'] input[name='tipo_simulacao'] ").keypress(function(e){
			if(e.wich == 13){ $(this).click(); }
		});

		var isValid = false;
		$("form[name='step1']").submit(function(event){
			event.preventDefault();
			isValid = true;
			//copia valores do passo anterior
			$("form[name='step2'] select[name='tipo_local_consumo_result'] option:eq(0)")
				.val($("form[name='step1'] select[name='tipo_local_consumo'] option:selected").val())
				.append(" "+$("form[name='step1'] select[name='tipo_local_consumo'] option:selected").text());
			$("form[name='step2'] select[name='potencia_contratada_result'] option:eq(0)")
				.val($("form[name='step1'] select[name='potencia_contratada'] option:selected").val())
				.append(" "+$("form[name='step1'] select[name='potencia_contratada'] option:selected").text());
			$("form[name='step2'] select[name='tarifa_result'] option:eq(0)")
				.val($("form[name='step1'] select[name='tarifa'] option:selected").val())
				.append(" "+$("form[name='step1'] select[name='tarifa'] option:selected").text());
			$("form[name='step2'] label input[value='"+$("form[name='step1'] label input[name='tipo_simulacao']:checked").val()+"']").attr("checked","checked");
			
			//novos campos
			$("form[name='step2'] input[name='consumo_vazio']").defaultValue();
			$("form[name='step2'] input[name='consumo_fora_vazio']").defaultValue();
			
			$(".simulatorContentContainer > ul").tabs('select', 1);
			isValid = false;
			//alert($("form[name='step1']").serialize());
			
		});
		//alternative keyboard methods
		$("form[name='step1']").keypress(function(e){
			//submit when "enter" key is pressed
			if(e.wich == 13){ $(this).submit(); }
		});
		//PASSO 2
		$("form[name='step2']").submit(function(event){
			event.preventDefault();
			isValid = true;
			
			$(".simulatorContentContainer > ul").tabs('select', 2);
			isValid = false;
			//alert($("form[name='step2']").serialize());
		});
		//alternative keyboard methods
		$("form[name='step2']").keypress(function(e){
			//submit when "enter" key is pressed
			if(e.wich == 13){ $(this).submit(); }
		});
		$("form[name='step2'] .goBack").click(function(event){
			event.preventDefault();
			isValid = true;
			
			$(".simulatorContentContainer > ul").tabs('select', 0);
			isValid = false;
		});
		//alternative keyboard methods
		$("form[name='step2'] .goBack").keypress(function(e){
			//go back when "enter" key is pressed
			if(e.wich == 13){ $(this).submit(); }
		});
			
		$(".simulatorContentContainer > ul").tabs({
			select: function(e, ui) {
				return isValid;
			}
		});
	};
	// END ---------- TABS SIMULATOR

	
});


