var obj_alerts = null;

function update_alerts() {
  var url = baseURL + '/people/' + currentUser + '/update-alerts';
  var ajax = new Ajax.Request(url, {
    method: 'post',
    onFailure: function(request) {
      setTimeout('update_alerts();', 30*1000);
    },
    onComplete: function(request) {
      if (request.responseText != '') {
          obj_alerts = eval("(" + request.responseText + ")");
          update_popup_alerts();
      }
      setTimeout('update_alerts();', 30*1000);
    }
  });
}

function update_popup_alerts() {
  if (obj_alerts.alerts.length > 0) {
    obj = obj_alerts.alerts[0];
    u_text = function() {
      var l = obj_alerts.alerts.length;
      if (l == 1) {
        $('alert-title').innerHTML = $('alert-title-one').innerHTML;
      } else {
        $('alert-title').innerHTML = $('alert-title-many').innerHTML.replace('$N', l);
      }
      $('alert-message').innerHTML = obj.message;
      $('alert-reaction').innerHTML = obj.reaction;
      if (obj.type == 'chat' && obj.popup) {
        OpenChat(obj.reaction_url);
      }
      new Effect.Appear('popup_alerts', {duration: 1});
    }
    if ($('popup_alerts').style.display == "") {
      new Effect.Fade('popup_alerts', {duration: 0.5, afterFinish: u_text});
    } else {
      u_text();
    }
  } else {
    new Effect.Fade('popup_alerts', {duration: 0.5});
  }
}

function alert_do_reaction() {
  current = obj_alerts.alerts[0];
  new Effect.DropOut('popup_alerts', {duration: 0.5});
  var url = baseURL + '/people/' + currentUser + '/ack-alerts';
  var ajax = new Ajax.Request(url, {
    method: 'post',
    parameters: 'id=' + current.id + '&type=' + current.type,
    onComplete: function(request) {
      if (obj_alerts.alerts[0].type == 'chat') {
        OpenChat(obj_alerts.alerts[0].reaction_url);
      } else {
        self.location = obj_alerts.alerts[0].reaction_url;
      }
    }
  });
}

function alert_cancel_reaction() {
  current = obj_alerts.alerts[0];
  obj_alerts.alerts.splice(0, 1);
  var url = baseURL + '/people/' + currentUser + '/ack-alerts';
  var ajax = new Ajax.Request(url, {
    method: 'post',
    parameters: 'id=' + current.id + '&type=' + current.type,
    onComplete: function(request) {
      update_popup_alerts();
    }
  });
}

function submit_on_enter(field, e) {
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;

  if (keycode == 13) {
   field.form.submit();
   return false;
  } else {
   return true;
  }
}

function button_over(n, t) {
  value = $('button-' + n).src;
  $('button-' + n).src = value.replace(n + '.' + t, n + '-over.' + t);
}

function button_out(n, t) {
  value = $('button-' + n).src;
  $('button-' + n).src = value.replace(n +'-over.' + t, n + '.' + t);
}

function reportError(request) {
  self.document.forms[0].submit();
}

function changeCountry(fieldname) {
  var url = baseURL + '/ajax/location';
  var value = "";
  var country = $(fieldname + '.country');

  for (var n = 0; n < country.options.length; n++) {
    if (country.options[n].selected && country.options[n].value != '-1') {
      if (value == "") {
        value = country.options[n].value;
      } else {
        value = value + " " + country.options[n].value;
        if (value.length > 240) {
          break;
        }
      }
    }
  }

  var params = 'country=' + value;
  var ajax = new Ajax.Request(url, {
      method: 'get',
      parameters: params,
      onFailure: reportError,
      onComplete: setLocationWidget(fieldname, 'C')
    });
}

function changeRegion(fieldname) {
  var url = baseURL + '/ajax/location';
  var value = "";
  var country = $(fieldname + '.country');
  var region = $(fieldname + '.region');

  for (var n = 0; n < country.options.length; n++) {
    if (country.options[n].selected && country.options[n].value != '-1') {
      if (value == "") {
        value = country.options[n].value;
      } else {
        value = value + " " + country.options[n].value;
        if (value.length > 240) {
          break;
        }
      }
    }
  }
  var params = 'country=' + value;

  value = "";
  for (var n = 0; n < region.options.length; n++) {
    if (region.options[n].selected && region.options[n].value != '-1') {
      if (value == "") {
        value = region.options[n].value;
      } else {
        value = value + " " + region.options[n].value;
        if (value.length > 240) {
          break;
        }
      }
    }
  }
  params += '&region=' + value;

  var ajax = new Ajax.Request(url, {
      method: 'get',
      parameters: params,
      onFailure: reportError,
      onComplete: setLocationWidget(fieldname, 'R')
    });
}

function setLocationWidget(fieldname, type) {
  return function(request) {
    var obj = eval("(" + request.responseText + ")");
    var len;

    if (type == "C") {
      select = $(fieldname + '.region');
      len = select.options.length;
      for (var n = 1; n < len; n++) {
        select.options[1] = null;
      }
      for (var n = 0; n < obj.regions.length; n++) {
        select.options[n+1] = new Option(obj.regions[n][1], obj.regions[n][0]);
      }
    }

    if (type == "C" || type == "R") {
      select = $(fieldname + '.city');
      len = select.options.length;
      for (var n = 1; n < len; n++) {
        select.options[1] = null;
      }
      for (var n = 0; n < obj.cities.length; n++) {
        select.options[n+1] = new Option(obj.cities[n][1], obj.cities[n][0]);
      }
    }
  }
}

function selectAll(check, container) {
  var f = $$('#' + container + ' input.option');
  for(var i=0; i<f.length; i++){
      f[i].checked = check.checked;
  }
}

function updateAlerts() {
  chat = $('last-chat-nickname');
  chat_alert = $('last-chat-alert');
  if (chat_alert.innerHTML == 'True') {
    OpenChat(baseURL + '/people/' + currentUser + '/chat.html?alert=1&to=' + chat.innerHTML);
  }
  message = $('last-message-nickname');
  message_alert = $('last-message-alert');
  if (message_alert.innerHTML == 'True') {
    OpenWindow(baseURL + '/alert.html?type=message&from=' + message.innerHTML, "loveismatch_alert", 380, 110);
    return;
  }
  flash = $('last-flash-nickname');
  flash_alert = $('last-flash-alert');
  if (flash_alert.innerHTML == 'True') {
    OpenWindow(baseURL + '/alert.html?type=flash&from=' + flash.innerHTML, "loveismatch_alert", 380, 110);
    return;
  }
  profile = $('last-profile-nickname');
  profile_alert = $('last-profile-alert');
  if (profile_alert.innerHTML == 'True') {
    OpenWindow(baseURL + '/alert.html?type=profile&from=' + profile.innerHTML, "loveismatch_alert", 380, 110);
    return;
  }
}

function updateEvents() {
  var url = baseURL + '/last-events';
  var ajax = new Ajax.Request(url, {
      method: 'post',
      parameters: 'updating=true',
      onFailure: function(request) {
        setTimeout('updateEvents();', 60*1000);
      },
      onComplete: function(request) {
        portlet = $('portlet-last-events');
        if (request.responseText != '') {
            portlet.innerHTML = request.responseText;
            updateAlerts();
        }
        setTimeout('updateEvents();', 60*1000);
      }
    });
}

function checkTextAreaLimit(field, limit) {
  var f = $(field);
  var l = $(field + '.limit');
  l.value = limit - f.value.length;
  l.style.color = (f.value.length > limit ? '#ff0000' : '#000000');
}

function OpenWindow(url, name, width, height) {
  w = width; h = height;
  w += 32; h += 96; wleft = (screen.width - w) / 2; wtop = (screen.height - h) / 2;
  var win = window.open(url, name, "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=no,menubar=no,statusbar=yes,location=no,toolbar=no,top=" + wtop + ",left=" + wleft);
  if (!win) {
    alert("Attenzione, è stato rilevato il blocco dei pop-up da parte del tuo browser.\n\nPer poter ricevere le segnalazioni degli eventi ed utilizzare la videochat, è necessario abilitare la ricezione dei pop-up nelle preferenze del tuo browser.");
  }
  return false;
}

function OpenChat(url) {
  width = 950; height = 550;
  w = width; h = height;
  w += 32; h += 96; wleft = (screen.width - w) / 2; wtop = (screen.height - h) / 2;
  var win = window.open(url, "loveismatch_chat", "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=no,menubar=no,statusbar=yes,location=no,toolbar=no,top=" + wtop + ",left=" + wleft);
  if (!win) {
    alert("Attenzione, è stato rilevato il blocco dei pop-up da parte del tuo browser.\n\nPer poter ricevere le segnalazioni degli eventi ed utilizzare la videochat, è necessario abilitare la ricezione dei pop-up nelle preferenze del tuo browser.");
  }
  return false;
}
