var scroll_t;
var scroll_div;
var direction;
var t = 0;
var cur = 1;
var i = false;
var cur_cat = 1;
var data_importante = new Array();
var data_desc = new Array();
var main_width = 1024;

function getWidth() {
  var myWidth = 0, myHeight = 0;
  if(typeof(window.innerWidth) == 'number') {
    //Non-IE
    myWidth = window.innerWidth; }
  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth; }
  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth; }
  return myWidth; }

function getHeight() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight; }
  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight; }
  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight; }
  return myHeight; }

function set_dyn() {
  var w_window = getWidth();
  var h_window = getHeight();
  if(w_window < 950) {
    if(w_window < 450) {
      main_width = 256; }
    else {
      main_width = 512; }
    document.getElementById("main").style.width = main_width + 'px';
    document.getElementById("main").style.marginLeft = -(main_width/2) + 'px'; }
  else if(main_width < 1024) {
    main_width = 1024;
    document.getElementById("main").style.width = main_width + 'px';
    document.getElementById("main").style.marginLeft = -(main_width/2) + 'px'; }
  var action_obj = document.getElementById("action");
  var plugs_obj = document.getElementById("plugs");
  var submenu_obj = document.getElementById("submenu");
  var vot_obj = document.getElementById("vot");
  var chat_obj = document.getElementById("chat");
  var cal_obj = document.getElementById("cal");
  var h_action_plugs_submenu = h_window - 188;
  var t_vot = h_action_plugs_submenu*0.225+21;
  var t_chat = h_action_plugs_submenu*0.45+21;
  var h_vot = h_action_plugs_submenu*0.215-21;
  var h_cal = h_action_plugs_submenu*0.225-21;
  var h_chat = h_action_plugs_submenu*0.55-21;
  vot_obj.style.top = t_vot;
  vot_obj.style.height = h_vot;
  cal_obj.style.height = h_cal;
  chat_obj.style.top = t_chat;
  chat_obj.style.height = h_chat;
  action_obj.style.height = plugs_obj.style.height = submenu_obj.style.height = h_action_plugs_submenu + 'px';
  if(i)
    set_chatsub(); }

function ajaxFunction() {
  var xmlhttp;
  if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest(); }
  else if (window.ActiveXObject) {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
  else {
    return 0; }
  return xmlhttp; } // Not my code --- property of w3schools.com; small modifications.

function set_div(url, divid) {
  var div_obj = document.getElementById(divid);
  var ajax = ajaxFunction();
  if(!ajax) {
    div_obj.innerHTML = "<h1>O seu browser é demasiado antigo para visualizar este site. Por favor actualize o seu browser para um que suporte AJAX.</h1>";
    return 0; }
  ajax.onreadystatechange = function() {
    if(ajax.readyState == 4) { div_obj.innerHTML = ajax.responseText; } }
  // This should be considered as code that isn't general to all sites.
  if(divid == 'action') {
    if((cur == "forum.htm" && url != "forum.htm") || (cur == "register.htm" && url != "register.htm") || (cur == 'phps/pag.php?id=39' && url != "phps/pag.php?id=39")) {
      document.getElementById("action").style.width = 0.67*main_width;
      document.getElementById("submenu").style.width = 0.155*main_width;
      document.getElementById("plugs").style.width = 0.155*main_width;
      document.getElementById("action").style.right = 0.165*main_width; }
    cur = url; }
  if(divid == 'submenu')
    cur_cat = url;
  ajax.open("GET", url, true);
  ajax.send(null); }

function set_chat() {
  var div_obj = document.getElementById("chat");
  var ajax = ajaxFunction();
  if(!ajax) {
    div_obj.innerHTML = "<h1>O seu browser é demasiado antigo para visualizar este site. Por favor actualize o seu browser para um que suporte AJAX.</h1>";
    return 0; }
  ajax.onreadystatechange = function() {
    if(ajax.readyState == 4) {
      div_obj.innerHTML = ajax.responseText;
      if(document.getElementById("l").value == "1") {
        if(!i) set_chatsub();
        div_obj.scrollTop = 0;
        t = document.getElementById("lmsg_t").value;
        ajax.open("GET", "phps/chat.php?t=" + t, true);
        ajax.send(null); }
      else {
        if(i) {
          i = false;
          document.getElementById("logout").innerHTML = "";
          document.getElementById("chat").style.height = (((getHeight() - 188)*0.55)-21) + 'px';
          document.getElementById("chat_sub").style.height = 0;
          document.getElementById("chat_sub").style.display = "none"; } } } }
  ajax.open("GET", "phps/chat.php?t=" + t, true);
  ajax.send(null); }

function set_chatsub() {
  var h_window = getHeight();
  var h_plugs = h_window - 188;
  var chat_obj = document.getElementById("chat");
  var chat_sub_obj = document.getElementById("chat_sub");
  var h_chat = (h_plugs*0.55) - 91;
  chat_sub_obj.style.height = '70px';
  chat_sub_obj.style.display = "block";
  chat_obj.style.height = h_chat + 'px';
  // Since calling this functions means the user logged in, we also use it to add the logout link and reffresh some divs.
  document.getElementById("logout").innerHTML = "<a href=\"javascript:logout()\">Logout</a>"; 
  set_div('phps/admin.php', 'admin');
  set_div('phps/vot.php', 'vot');
  set_div(cur, 'action');
  set_div(cur_cat, 'submenu');
  document.getElementById("chat_sub").innerHTML = "<input type=\"text\" id=\"msg\" onKeyPress=\"submitonEnter('n=1&msg=' + encodeURIComponent(document.getElementById('msg').value), 'phps/chat.php?t=0', 'chat', event); eraseonEnter(this, event);\" /><br /><a href=\"javascript:;\" onclick=\"post_submit('n=1&msg=' + encodeURIComponent(document.getElementById('msg').value), 'phps/chat.php?t=0', 'chat'); document.getElementById('msg').value = '';\"><img src=\"./img_dec/enviar.jpg\" class=\"menu\" /></a>";
  i = true; }

function login_chat() {
  var div_obj = document.getElementById("chat");
  var pass, user, rem = 0;
  user = document.getElementById("user").value;
  pass = document.getElementById("pass").value;
  params = 'l=1&user=' + user + '&pass=' + pass + '&rem=' + rem;
  var ajax = ajaxFunction();
  ajax.open("POST", "phps/chat.php", true);
  ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  ajax.setRequestHeader("Content-length", params.length);
  ajax.setRequestHeader("Connection", "close");
  ajax.onreadystatechange = function() {
    if(ajax.readyState == 4) {
      div_obj.innerHTML = ajax.responseText;
      if(document.getElementById("l").value == "1") {
        set_chatsub();
        set_chat(); } } }
  ajax.send(params); }

function login_onEnter_chat(e) {
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  if (keycode == 13) {
    login_chat();
    return false; }
  else
     return true; }

function post_submit(params, url, divid) {
  var div_obj = document.getElementById(divid);
  var ajax = ajaxFunction();
  ajax.open("POST", url, true);
  ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  ajax.setRequestHeader("Content-length", params.length);
  ajax.setRequestHeader("Connection", "close");
  ajax.onreadystatechange = function() {
    if(ajax.readyState == 4) {
      div_obj.innerHTML = ajax.responseText; } }
  ajax.send(params); }

function scroll() {
  var div = document.getElementById(scroll_div);
  switch(direction) {
    case 1: //scroll left
      if(div.scrollLeft) { div.scrollLeft--; }
      break;
    case 2: // scroll right
      if(div.scrollLeft != div.scrollWidth) { div.scrollLeft++; }
      break;
    case 3: // scroll up
      if(div.scrollTop) { div.scrollTop--; }
      break;
    default: // scroll down
      if(div.scrollTop != div.scrollHeight) { div.scrollTop++; } }
  scroll_t = setTimeout("scroll()", 10); }

function stop_scroll() {
  clearTimeout(scroll_t); }

function submitonEnter(params, url, divid, e) {
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;
  if (keycode == 13) {
    post_submit(params, url, divid);
    return false; }
  else
     return true; }

function eraseonEnter(obj, e) {
  var keycode;
  if(window.event) keycode = window.event.keyCode;
  else if(e) keycode = e.which;
  else return true;
  if(keycode == 13) {
    obj.value = "";
    return false; }
  else
    return true; }

function logout() {
  stop_scroll();
  var ajax = ajaxFunction();
  ajax.onreadystatechange = function() {
    document.getElementById("logout").innerHTML = "";
    set_div(cur, 'action');
    set_div('phps/vot.php', 'vot');
    set_div('phps/chat.php', 'chat');
    set_div(cur_cat, 'submenu');
    document.getElementById("admin").innerHTML = "";
    i = false;
    document.getElementById("chat").style.height = (((getHeight() - 188)*0.55) -21) + 'px';
    document.getElementById("chat_sub").style.height = 0;
    document.getElementById("chat_sub").style.display = "none"; }
  ajax.open("GET", "phps/logout.php", true);
  ajax.send(null); }

function getRadioChecked_value(radioObj) {
  var i;
  for(i = 0; i < radioObj.length; i++) {
    if(radioObj[i].checked) {
      return radioObj[i].value; } }
  return radioObj.length+1; }

function sugestoes() {
  set_div('phps/sugestoes.php','action');
  cur='phps/sugestoes.php'; }

function setimg(gal, i) {
  set_div('phps/gal.php?gal=' + gal + '&img=' + i, 'action');
  cur = 'phps/gal.php?gal=' + gal + '&img=' + i; }

function delimg(gal, id, i) {
  var delf;
  if(document.getElementById('delfile' + i).checked) {
    delf = 1; }
  else {
    delf = 0; }
  post_submit('del=' + id + '&f=' + delf, 'phps/gal.php?gal=' + gal, 'action');
  cur = 'phps/gal.php?gal=' + gal; }

function delvot(id) {
  post_submit("del=1&id=" + id, 'phps/vot.php', 'vot'); }

function del_menu(id, cat) {
  if(confirm("Tem a certeza que quer eliminar esta opção?\nNão se esqueça, que ao fazê-lo, eliminará também a página correspondente!!!"))
    post_submit("del=1&id=" + id, 'phps/menu.php?cat=' + cat, 'submenu'); }

function del_gal(gal) {
  post_submit("del=1&gal=" + gal, 'phps/menu_gal.php', 'submenu'); }

function set_activ() {
  set_div('phps/pag.php?id=28', 'action');
  set_div('phps/menu.php?cat=activ', 'submenu'); }

function set_qs() {
  set_div('phps/pag.php?id=1', 'action');
  set_div('phps/menu.php?cat=qs', 'submenu'); }

function set_proj() {
  set_div('phps/pag.php?id=27', 'action');
  set_div('phps/menu.php?cat=proj', 'submenu'); }

function wrflash(id) {
  document.write("<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" id=\"" + id + "\">\n<param name=\"movie\" value=\"flash/" + id + ".swf\">\n<embed src=\"flash/" + id + ".swf\" type=\"application/x-shockwave-flash\" width=\"100%\" height=\"100%\" />\n</object>\n"); }

function set_loja() {
  set_div('phps/loja.php', 'action');
  set_div('menu_loja.htm', 'submenu'); }

function set_cart() {
  set_div('phps/cart.php', 'action');
  set_div('menu_loja.htm', 'submenu'); }

function set_forum() {
  set_div('forum.htm', 'action');
  set_div('c.htm', 'submenu');
  document.getElementById("submenu").style.width = 0;
  document.getElementById("plugs").style.width = 0;
  document.getElementById("action").style.width = main_width;
  document.getElementById("action").style.right = 0; }

function set_register() {
  set_div('register.htm', 'action');
  set_div('c.htm', 'submenu');
  document.getElementById("submenu").style.width = 0;
  document.getElementById("action").style.width = 0.835*main_width; }

function set_evento() {
  set_div('phps/pag.php?id=39', 'action');
  set_div('c.htm', 'submenu');
  document.getElementById("submenu").style.width = 0;
  document.getElementById("plugs").style.width = 0;
  document.getElementById("action").style.width = main_width;
  document.getElementById("action").style.right = 0; }

function set_home() {
  set_div('phps/news.php', 'action');
  set_div('phps/menu.php?cat=home', 'submenu'); }

/* Código para o calendário.
Autor: Brian Gosselin
Site: http://scriptasylum.com/ 
Algumas alterações minhas -- Tradução para Português, datas importantes e a adição de setas para mudar de mês/ano */
function buildCal(m, y, cM, cH, cDW, cD, brdr){
  var i;
  var mn=['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
  var dim=[31,0,31,30,31,30,31,31,30,31,30,31];

  var oD = new Date(y, m-1, 1); //DD replaced line to fix date bug when current day is 31st
  oD.od=oD.getDay()+1; //DD replaced line to fix date bug when current day is 31st

  var todaydate=new Date() //DD added
  var scanfortoday=(y==todaydate.getFullYear() && m==todaydate.getMonth()+1)? todaydate.getDate() : 0 //DD added

  dim[1]=(((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0))?29:28;
  var t='<div class="'+cM+'"><table class="'+cM+'" cols="7" cellpadding="0" border="'+brdr+'" cellspacing="0"><tr align="center">';
  t+='<td><a href=\'javascript:;\' onclick=\'change_cal(0)\'>&lt;</a></td><td colspan="5" align="center" class="'+cH+'">'+mn[m-1]+' - '+y+'</td><td><a href=\'javascript:;\' onclick=\'change_cal(1)\'>&gt;</a></td></tr><tr align="center">';
  for(s=0;s<7;s++)t+='<td class="'+cDW+'">'+"DSTQQSS".substr(s,1)+'</td>';
  t+='</tr><tr align="center">';
  for(i=1;i<=42;i++){
    var x=((i-oD.od>=0)&&(i-oD.od<dim[m-1]))? i-oD.od+1 : '&nbsp;';
    if (x==scanfortoday) //DD added
      x='<span id="today">'+x+'</span>'; //DD added
    for(a = 0; a < data_importante.length; a++) {
      if(y == data_importante[a].getFullYear() && m == data_importante[a].getMonth()+1 && x == data_importante[a].getDate()) {
        x = '<a href="javascript:;" onmouseover="ddesc_show(' + a + ');" onmouseout="ddesc_hide();" class="important">' + x + '</a>';
        if (x==scanfortoday)
          x = '<a href="javascript:;" onmouseover="ddesc_show(' + a + ');" onmouseout="ddesc_hide();" class="important_today">' + x + '</a>' } }
    t+='<td class="'+cD+'">'+x+'</td>';
    if(((i)%7==0)&&(i<36))t+='</tr><tr align="center">'; }
  return t+='</tr></table></div>'; }

var todaydate=new Date()
var curmonth=todaydate.getMonth()+1 //get current month (1-12)
var curyear=todaydate.getFullYear() //get current year

// Mais código para o calendário, desta vez da autoria de Cynary aKa Rodrigo
function change_cal(y) {
  if(y) {
    curmonth = (curmonth == 12)? 1:curmonth+1;
    curyear = (curmonth == 1)? curyear+1:curyear; }
  else {
    curmonth = (curmonth == 1)? 12:curmonth-1;
    curyear = (curmonth == 12)? curyear-1:curyear; }
  document.getElementById("cal").innerHTML = buildCal(curmonth ,curyear, "main", "month", "daysofweek", "days", 1); }

function ddesc_show(i) {
  var desc_div = document.getElementById("datadesc");
  desc_div.innerHTML = data_desc[i];
  desc_div.style.display = "block"; }

function ddesc_hide() {
  document.getElementById("datadesc").style.display = "none"; }

//Function obtained from: anyexample.com
function getElementsByClass( searchClass, domNode, tagName) {
	if (domNode == null) domNode = document;
	if (tagName == null) tagName = '*';
	var el = new Array();
	var tags = domNode.getElementsByTagName(tagName);
	var tcl = " "+searchClass+" ";
	for(i=0,j=0; i<tags.length; i++) {
		var test = " " + tags[i].className + " ";
		if (test.indexOf(tcl) != -1)
			el[j++] = tags[i];
	}
	return el;
}

function hide_subsubmenu() {
  var subsubs = getElementsByClass('subsubmenu');
  for(i = 0; i < subsubs.length; i++) {
    subsubs[i].style.display = "none"; } }

function show_subsubmenu(id) {
  hide_subsubmenu();
  document.getElementById(id).style.display = "block"; }

function ischecked(objname) {
  var radioObj = document.getElementsByName(objname);
  var i;
  for(i = 0; i < radioObj.length; i++) {
    if(radioObj[i].checked) {
      return true; } }
  return false; }

function isfilled(textid) {
  var obj = document.getElementById(textid);
  return obj.value != ""; }

// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************
//http://www.codetoad.com/forum/17_10053.asp

function isDate(dateID) {
var dateStr = document.getElementById(dateID).value;

var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?

if (matchArray == null) {
alert("Por favor entre a data nos formatos dd/mm/aaaa ou dd-mm-aaaa.");
return false;
}

month = matchArray[3]; // p@rse date into variables
day = matchArray[1];
year = matchArray[5];

if (month < 1 || month > 12) { // check month range
alert("O mês deve estar entre 1 e 12.");
return false;
}

if (day < 1 || day > 31) {
alert("O dia deve ser entre 1 e 31");
return false;
}

if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("O mês "+month+" não tem 31 days!")
return false;
}

if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day > 29 || (day==29 && !isleap)) {
alert("Fevereiro " + year + " não tem " + day + " dias!");
return false;
}
}
return true; // date is valid
}


function validate_insc(e, i) {
  var resultado = "";
  var tipo;
  var i;
  var params;
  var keycode;
  if(i) {
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if(keycode != 13) return false; }
  if(!ischecked("tipo")) {
    alert("Não disse se era individual ou em grupo.");
    return false; }
  else {
    tipo = getRadioChecked_value(document.getElementsByName("tipo"));
    if(tipo == "individual") {
      if(!isfilled("nome_ind")) resultado += "Não preencheu o seu nome.\n";
      if(!isfilled("bi_ind") || !isDate("bi_ind")) resultado += "Não preencheu a sua data de nascimento.\n";
      if(resultado == "") post_submit("tipo=individual&nome=" + encodeURIComponent(document.getElementById("nome_ind").value) + "&bi=" + encodeURIComponent(document.getElementById("bi_ind").value), "phps/inscricao.php", "action");
      else { alert(resultado); return false; } }
    else {
      if(!isfilled("nome_equipa0")) resultado += "Não preencheu o nome do responsável pelo grupo.\n";
      if(!isfilled("bi_equipa0") || !isDate("bi_equipa0")) resultado += "Não preencheu a data de nascimento do capitão da equipa.\n";
      for(i = 1; i < 8; ++i) {
        if(!isfilled("nome_equipa" + i)) resultado += "Não preencheu o nome do " + i + "º jogador da equipa.\n";
        if(!isfilled("bi_equipa" + i) || !isDate("bi_equipa" + i)) resultado += "Não preencheu a data de nascimento do " + i + "º jogador do grupo.\n"; }
      if(resultado == "") {
        params = "tipo=equipa&nome_equipa=" + encodeURIComponent(document.getElementById("nome_equipa").value);
        for(i = 0; i < 8; ++i) {
          params += "&nome" + i + "=" + encodeURIComponent(document.getElementById("nome_equipa" + i).value) + "&bi" + i + "=" + encodeURIComponent(document.getElementById("bi_equipa" + i).value); }
        post_submit(params, "phps/inscricao.php", "action"); }
      else { alert(resultado); return false; } } }
    return true; }
