var inforum = false;
$(document).ready(function(){
$('#main-nav > li').hover
	(
			
			function() { 
				$('#main-nav ul').hide();
				$('#main-nav2 ul').hide();
				
				$(this).children('ul').show(); 
				$('a:first-child', this).addClass("hover"); 
			},
			function() { 
				$(this).children('ul').hide(); 
				$('a:first-child', this).removeClass("hover"); 
				$('#main-nav > li').children('ul.default').show(); 
				$('#main-nav2 > li').children('ul.default').show(); 

		}
	);
	
	$('#main-nav2 > li').hover
	(
			
			function() { 
				$('#main-nav ul').hide();
				$('#main-nav2 ul').hide();
				
				$(this).children('ul').show(); 
				$('a:first-child', this).addClass("hover"); 
			},
			function() { 
				$(this).children('ul').hide(); 
				$('a:first-child', this).removeClass("hover"); 
				$('#main-nav > li').children('ul.default').show(); 
				$('#main-nav2 > li').children('ul.default').show(); 

		}
	);
	
	//make all links with rel external open in new window
	$("a[@rel='external']").click(function(){return !window.open($(this).attr("href"));});
	$("#user-submit").removeAttr("disabled");
	
	init_sidebar_de();

});

function init_sidebar_de()
{
	$("#btn_mais_vistos").click ( function(){
        $("#mais_vistos").show();
        $("#mais_comentados").hide();
        $("#btn_mais_vistos").addClass('active');
        $("#btn_mais_comentados").removeClass("active");
		return false;
   });
   
   
   $("#btn_mais_comentados").click ( function(){
        $("#mais_comentados").show();
        $("#mais_vistos").hide();
        $("#btn_mais_comentados").addClass('active');
        $("#btn_mais_vistos").removeClass("active");
		return false;
   });

}

///////////////////////////////////////////  USERS //////////////////////////////////////////////////////////////////////////////

function login()
{
	
	$("#user-login-feedback").html('A enviar...');
		
	var user = $("#user").val();
    var pass = $("#password").val();
    
    if(user == '' || pass == '')
    {
    	$("#user-login-feedback").html('<span class="error">Por favor introduza o login e a password.</span>');
    	return false;
    }
    
    $("#user-submit").attr("disabled","disabled");
    
    $.ajax({
              type:"POST",
              url: "users/login",
              data: "user="+user+"&password="+pass+"&ajx=1",
              success: function(msg){
                
                 $("#user-panel").html(msg); 
                 
                  if(inforum == true){
					//hack for when we're in the forum
					window.parent.document.location.reload();
					//if (top.frames.length>0)
        			//	setTimeout("top.location = window.location;",100);

     			  }
                
              },
              error: function(msg){
                 $("#user-panel").html(msg);
              }

              
     });
     

    

     return false;
}

function logout()
{
	$("#feedback").html('A enviar...');
		
	    
    $.ajax({
              type:"GET",
              url: "users/logout/?xhr=1",
              success: function(msg){
                
                 $("#user-panel").html(msg); 
                 
                 if(inforum == true){
					//hack for when we're in the forum
					window.parent.document.location.reload();
					//if (top.frames.length>0)
        			//	setTimeout("top.location = window.location;",100);

     			  }
                
              },
              error: function(msg){
                 $("#user-panel").html(msg);
              }

              
     });

     return false;
}


///////////////////////////////////////////  \USERS //////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////  EMPRESAS //////////////////////////////////////////////////////////////////////////////

function init_empresas_de()
{  
    $(".lettersheader").unbind( 'click' );
    $(".empresatitle").unbind( 'click' );

    $(".lettersheader").bind('click', function () { 
      $("#empresas").html('A carregar..');
      var letter = $(this).attr('title');
      get_empresas(letter);
      return false;
    });

    $(".empresatitle").bind('click', function () { 
      $("#empresas").html('A carregar..');
      var id = $(this).attr('title');
      get_empresa_by_id(id); 
      return false;
    });
}


function get_empresa_by_id(id)
{
	var url = 'empresas/empresa_ajax/' + id;
  $.get(url, function(data){
      if(data == '') {
        data = 'Registo n&atilde;o encontrado.';
      }
      $("#empresas").html(data);
      init_empresas_de();
  });
}


function get_empresas(letter)
{
	var url = 'empresas/letter_ajax/' + letter;
  $.get(url, function(data){
      if(data == '') {
        data = 'N&atilde;o foram encontradas empresas a come&ccedil;ar pela letra ' + letter;
      }
      $("#empresas").html(data);
      init_empresas_de();
  });
}

/////////////////////////////////////////// \ EMPRESAS //////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////ARTICLES//////////////////////////////////////////////////////////////////////////////////

function submit_comment_to_noticia()
{
		$("#submit-comment").attr("disabled","disabled");
		$("#comment-feedback").html('A enviar...');
		
		var author = $("#comment-author").val();
		var email = $("#comment-email").val();
		var message = $("#comment-message").val();
		var articles_id = $("#articles-id").val();
		var city = $("#comment-city").val();
		
        $.ajax({
              type:"POST",
              url: "noticias/comment",
              data: "author="+author+"&message="+message+"&email="+email+"&articles_id="+articles_id+"&city="+city,
              success: function(msg){
                 $("#comment-feedback").html(msg); 
              },
              error: function(msg){
                 $("#comment-feedback").html(msg);
                 
              }

              
         });
	     $("#submit-comment").attr("enabled","enabled");
         return false;
}
/////////////////////////////////////////// \ ARTICLES /////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////BANNERS//////////////////////////////////////////////////////////////////////////////////


function load_banner(banner_id, elem_id)
{
  var url = 'banners/get/' + banner_id;
  $.get(url, function(data){
      if(data == '') {
        data = '<strong>Este espa&ccedil;o pode ser seu! Contacte-nos para saber como!</strong>';
      }
      $("#"+elem_id).html(data);
  });
}

/////////////////////////////////////////// \BANNERS ///////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////POLLS////////////////////////////////////////////////////////////////////////////////////

// Global variable definitions
var JSON_ID = "id";
var JSON_ANSWER = "answer";
var JSON_VOTES = "votes";



$(document).ready(function() {

    $("#pollForm").submit(formProcess);

    if ($("#pollresults").length > 0 ) {
        animateResults();
    }
      
    $("#getResults").click(function() {
    	$("#pollcontainer").fadeOut("slow",function() {
    		$("#pollcontainer").empty();
    		$.getJSON("polls/getresults",loadResults);
    	});
    });

});



function formProcess(event) {

    event.preventDefault();

    var myPollId = $('#pollId').val();
    var myAnswerId = $('input[@name=answer]:checked').val();

    $("#pollcontainer").fadeOut("slow",function() {
    	$("#pollcontainer").empty();
    	$.post("polls", { pollId: myPollId, answerId: myAnswerId }, function(data) { loadResults(data); } , "json");
    });
}



function animateResults() {

  $("#pollresults div").each(function(){
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
  });

}



function loadResults(data) {

  var totalVotes = 0;
  var percent;

  for (id in data) {
    totalVotes = totalVotes+parseInt(data[id][JSON_VOTES]);
  }
  
  var htmlRes = "<div id='pollresults'><dl class='graph'>\n";

  for (id in data) {
    percent = Math.round((parseInt(data[id][JSON_VOTES])/parseInt(totalVotes))*100);
    htmlRes = htmlRes+"<dt class='bar-title'>"+data[id][JSON_ANSWER]+"</dt><dd class='bar-container'><div id='bar"+data[id][JSON_ID]+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd><br class='clear'/>\n";
  }
  
  htmlRes = htmlRes+"</dl></div>\n";

  
  $("#pollcontainer").append(htmlRes).fadeIn("slow",function(){
    animateResults();});
  $("#pollmodule").append("Total de votos: "+totalVotes+"");
  

}

/////////////////////////////////////////// \POLLS //////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////// \POPUP //////////////////////////////////////////////////////////////////////////////////

function PopUp(page, myWidth, myHeight) {
	newWind=window.open(page,"popUp","width="+myWidth+",height="+myHeight+",toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,directories=no,resizable=no");
	if(newWind.opener == null) {
		newWind.opener = window;
	}
	else {
		newWind.focus();
	}
}


/////////////////////////////////////////// POPUP //////////////////////////////////////////////////////////////////////////////////

