(function($){
	$(function(){
		
		//alert(ajaxurl);
		var $wm_ap_public_do_ajax = "wm_ap_public_do_ajax"; //nome da função PHP chamada em wm-ap-admin.php
		var $php_ajax_data = {}; //objecto para agregar dados a enviar por ajax

    if (window.navigator.appName == "Microsoft Internet Explorer") {
      //no modo IE8 as imagens redimensionadas por css (max-width) não ficam com a altura proporcional
      if(document.documentMode == 8) {
      //recalcular a altura
        $('img.alignnone, img.aligncenter').each( function() {
          //str = "css.width: "+$(this).css("width")+"; attr.width: "+$(this).attr("width")+"; css.height: "+$(this).css("height")+"; attr.height: "+$(this).attr("height")+"; this.height: "+this.height+"; document.documentMode: "+document.documentMode;
          if( parseInt($(this).css("width")) > parseInt($(this).attr("width")) ) {
            $(this).css("height", (parseInt($(this).attr("height")) * parseInt($(this).attr("width")) / parseInt($(this).css("width"))) + "px");
          }
          //alert(str+"\ncss.width: "+$(this).css("width")+"; attr.width: "+$(this).attr("width")+"; css.height: "+$(this).css("height")+"; attr.height: "+$(this).attr("height"));

        });
      }
    }

    /*
    $hide_submenu = false;
    $('a.submenu').mouseenter(function() {      
      $submenu = $("ul#"+$(this).attr('data-menu'));
      if($submenu.is(':visible')) clearTimeout($hide_submenu);
      else $submenu.show();
    });
    $('a.submenu').mouseleave(function() {
      $hide_submenu = setTimeout(function() {$submenu.hide();}, 1000);
    });
    $('ul.submenu').mouseenter(function() {
      clearTimeout($hide_submenu);
    });
    $('ul.submenu').mouseleave(function() {
      $hide_submenu = setTimeout(function() {$submenu.hide();}, 1000);
    });
    $(window).scroll(function() { $('ul.submenu').hide(); });
    */


    if($('div.projectos_em_destaque').length == 1) {
      $wait = false;
      $scroll_timer = setInterval(function() {highlight_projecto(false);}, 4000);
      
      $('div.projectos_em_destaque div.tabs a').mouseover(function() {
        clearInterval($scroll_timer);
        $scroll_timer = false;
        if($wait) {
          _this = $(this);
          $scroll_timer = setTimeout(function() {highlight_projecto(_this);}, 300);
        }
        else highlight_projecto($(this));
      });

      $('div.projectos_em_destaque').mouseleave(function() {
        if(!$scroll_timer) $scroll_timer = setInterval(function() {highlight_projecto(false);}, 4000);
      });

      function highlight_projecto($link) {
        $wait = true;
        $active_link = $('div.projectos_em_destaque div.tabs a.active');
        $active_link.removeClass("active");
        if(!$link) {
          $link = $active_link.next();
          if(!$link.length) {$link = $active_link.parent().find(':first-child');}
        }
        //$('div.projectos_em_destaque #img_'+$active_link.attr("data-id")).hide();
        $('div.projectos_em_destaque > div.imagens > div').hide();
        $link.addClass("active");
        $('div.projectos_em_destaque #img_'+$link.attr("data-id")).fadeIn(200, function() {$wait = false;});
      }
    }


		$('#login_email').focus(function() {
			if($(this).val() == '< - - Email - - >') $(this).val('');
		});
		$('#login_pass').focus(function() {
			if($(this).val() == '--------') $(this).val('');
		});

		$('#login_form').submit(function() {
			//if(!isValidEmail($('#login_email').val())) {
			if($.trim($('#login_email').val()).length == 0) {
				alert("Endereço de Email inválido ("+$('#login_email').val()+")\n\nPor favor, corrija.");
				return false;
			}
			if($.trim($('#login_pass').val()).length == 0) {
				alert("O campo Senha não pode estar vazio.\n\nPor favor, corrija.");
				return false;
			}
			toggleMyButtonStatus($('#login_button'));
			return true;
		});

		$('input.TogglePesquisaAvancada').click(function() {
			$('#ActivarPesquisaAvancada').slideToggle();
			$('#DivPesquisaAvancada').slideToggle();
		});

    $('#ResetPesquisa').click(function() {
			window.location.href = $('#ResetPesquisaURL').attr("value");
		});


		$("select#dom_id").change(function(){populate_select_field("especialidade_id", $especialidades, $(this).val());});
		$("select#cat_id").change(function(){populate_select_field("sub_cat_id", $sub_categorias, $(this).val());});
		$("select#distrito_id").change(function(){populate_select_field("concelho_id", $concelhos, $(this).val());});

		$("a.toggle").click(function() {
			$target = $('#'+$(this).attr('data-target'));
			if($(this).text() == 'mostrar') {
				$target.show();
        $(this).text("esconder");
			}
			else if($(this).text() == 'esconder') {
				$target.hide();
        $(this).text("mostrar");
			}
			return false;
		});

    $("a.toggle_options").click(function() {
			$target = $('#'+$(this).attr('target'));
			if($(this).attr('href') == 'Mostrar') {
				$target.find('label').show();
				$("a.toggle_options[target='"+$(this).attr('target')+"']").attr('href','Esconder').html($(this).html().replace('mostrar','esconder'));
			}
			else if($(this).attr('href') == 'Esconder') {
				$target.find('input:checkbox:not(:checked)').parent().hide();
				$target.find('label b,a').parent().hide();
				$("a.toggle_options[target='"+$(this).attr('target')+"']").attr('href','Mostrar').html($(this).html().replace('esconder','mostrar'));
			}
			return false;
		});

    $("a.toggle_textfields").click(function() {
			$target = $('#'+$(this).attr('target'));
			if($(this).attr('href') == 'Mostrar') {
				$target.children(':hidden').show();
        $(this).attr('href','Esconder').html('esconder');
			}
			else if($(this).attr('href') == 'Esconder') {
				$target.find('input:text[value=""]').parent().parent().hide();
        $(this).attr('href','Mostrar').html('mostrar');
			}
			return false;
		});

		$('#registerform').submit(function() {
						
			//verificar se existem campos not_null por preencher
      $php_ajax_data = {};
      $php_ajax_data = complete_ajax_data($(this));
			if(!$php_ajax_data) return false;

			if(!isValidEmail($php_ajax_data["user_email"])) {
				alert("Endereço de Email inválido ("+$php_ajax_data["user_email"]+")\n\nPor favor, corrija.");
				return false;
			}
			$msg_confirm = "Por favor, confirme se todos os dados estão correctos.\n\n"+
										 "A sua senha de acesso será enviada para o Email \""+$php_ajax_data["user_email"]+"\"\n\n"+
										 "Clique em \"Cancelar\" para corrigir algum campo.\n\n"+
										 "Clique em \"OK\" para completar o registo";
			if(!confirm($msg_confirm)) return false;
			toggleMyButtonStatus($('#SubmitRegisto'));
			return true;
		});

    $('#updateuserform').submit(function() {

			//verificar se existem campos not_null por preencher
      $php_ajax_data = {};
      $php_ajax_data = complete_ajax_data($(this));
      if(!$php_ajax_data) return false;

			if(!isValidEmail($php_ajax_data["user_email"])) {
				alert("Endereço de Email inválido ("+$php_ajax_data["user_email"]+")\n\nPor favor, corrija.");
				return false;
			}
			$msg_confirm = "Por favor, confirme se todos os dados estão correctos.\n\n"+
										 "Clique em \"Cancelar\" para corrigir algum campo.\n\n"+
										 "Clique em \"OK\" para submeter a alteração de dados.";
			if(!confirm($msg_confirm)) return false;
			toggleMyButtonStatus($('#UpdateUser'));
			return true;
		});

    $('a.RenovarAssinatura').click(function() {

			$('div#buton_RenovarAssinatura').hide();
      $('div#ap_loading').show();
      $php_ajax_data["action"] = "wm_ap_renovar_assinatura";
      $.ajax({
        type: "GET",
        dataType: 'json',
        url: ajaxurl, //ajaxurl é definido no próprio wordpress (admin-ajax.php)
        data: $php_ajax_data, //definido no trigger que chamou esta função
        success: function($json){
          // on success do something
          $('div#ap_loading').hide();
          if($json.status != 1) $('div#buton_RenovarAssinatura').show();
          $('div#resposta_RenovarAssinatura').html($json.html);
          $('div#resposta_RenovarAssinatura').show();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          // on error do something
          $('div#ap_loading').hide();
          $('div#buton_RenovarAssinatura').show();
          $('div#resposta_RenovarAssinatura').html(textStatus+': '+errorThrown);
          $('div#resposta_RenovarAssinatura').show();
        }
      });
			return false;
		});

    $('input#NewsletterReconfirmar').click(function() {
      $button = $(this);
      toggleMyButtonStatus($button);
			$php_ajax_data["action"] = "wm_ap_reconfirmar_newsletter";
      $.ajax({
        type: "GET",
        dataType: 'json',
        url: ajaxurl, //ajaxurl é definido no próprio wordpress (admin-ajax.php)
        data: $php_ajax_data, //definido no trigger que chamou esta função
        success: function($json){
          // on success do something
          if($json.status == 1) { $button.hide(); }
          else { toggleMyButtonStatus($button); }
          $('div#resposta_NewsletterReconfirmar').html($json.html);
          $('div#resposta_NewsletterReconfirmar').show();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          // on error do something
          toggleMyButtonStatus($button);
          $('div#resposta_NewsletterReconfirmar').html(textStatus+': '+errorThrown);
          $('div#resposta_NewsletterReconfirmar').show();
        }
      });
			return false;
		});

		/*
		 * Esta função aceita como parametro "$form_id", que pode ser uma string com o ID do Form ou o próprio objecto Form.
		 * Percorre todos os campos do Form e guarda-os no objecto $php_ajax_data.
		 * Se um campo tiver a class "not_null" retorna falso e muda a cor de fundo desse campo.
		 */
		function complete_ajax_data($form_id) {
			var $missing_fields = false;
      if(typeof $form_id == 'string') $form_id = $('#'+$form_id);
			$form_id.find(':input').each(function(){

				//ver se o campo é not_null
				if($(this).hasClass("not_null") && $(this).val() == '') {
					$(this).css("background-color", "#ffffc0");
					if(!$missing_fields) $(this).focus();
					$missing_fields = true;
					//alert($(this).attr('name'))
					//return false; //continuar para o próximo each()
				}				
				switch($(this).attr('type')) {
					case 'submit':
						break;
					case 'button':
						break;
					case 'checkbox':
						if($(this).attr("checked")) $php_ajax_data[$(this).attr('name')] = $(this).val();
						break;
					case 'radio':
						if($(this).attr("checked")) $php_ajax_data[$(this).attr('name')] = $(this).val();
						break;
					default:
						$php_ajax_data[$(this).attr('name')] = $(this).val();
						break;
				}
			});
			if($missing_fields == true) {
				alert('Por favor, preencha todos os campos obrigatórios assinalados.');
				return false;
			}
			return $php_ajax_data;
		}

		var $default_button_value = "";
		function toggleMyButtonStatus($button) {
			if($button.hasClass("disabled") == false) {
				$default_button_value = $button.attr("value");
				$button.attr("value","Aguarde...");
				$button.addClass("disabled");
				$button.attr("disabled","disabled");
				//alert("1: "+$default_button_value);
			}
			else if($button.hasClass("disabled") == true) {
				$button.attr("value", $default_button_value);
				$button.removeClass("disabled");
				$button.removeAttr("disabled");
				//alert("2: "+$default_button_value);
			}
		}

		function isValidEmail(str) {
			var chAt  = '@';
			var chDot = '.';
			var strEmailAddr = $.trim(str);
			if (strEmailAddr.length == 0) return false;
			if (strEmailAddr.indexOf(" ") == -1) {
				 var iFirstAtPos = strEmailAddr.indexOf(chAt);
				 var iLastAtPos = strEmailAddr.lastIndexOf(chAt);
				 if (iFirstAtPos > 0 && iFirstAtPos < (strEmailAddr.length - 1) &&iFirstAtPos == iLastAtPos) {
					 // look for '.' there must be at least one char between '@' and '.'
					 var iDotPos = strEmailAddr.indexOf(chDot, iFirstAtPos + 1);
					 if (iDotPos > (iFirstAtPos + 1) && iDotPos < (strEmailAddr.length -1)) return true;
				 }
			}
			return false;
		}

		var $select_default_html = {};
		function populate_select_field($field_id, $json, $i) {
			//alert($i);
			if(!$select_default_html[$field_id]) $select_default_html[$field_id] = $("select#"+$field_id).html();
			if(!$i) {
				$("select#"+$field_id).html($select_default_html[$field_id]);
				return;
			}
			var options = '<option value="">-- escolha --</option>';
			for(var $j in $json[$i]) {
				options += '<option value="' + $j + '">' + $json[$i][$j] + '</option>';
			}
			$("select#"+$field_id).html(options);
			return;
		}

	});
})(jQuery);



