var can_popup    = true;
var popup_uri    = 'http://' + document.domain + '/popup/subscribe';
var popup_width  = 450;
var popup_height = 300;

if(document.all && !document.getElementById) {
  document.getElementById = function(id) {
    return document.all[id];
  };
}

function set_subscribe() {
  var subscribe = document.getElementById('subscribe');

  var expiry = new Date();
  expiry.setTime((Math.pow(2, 31) - 1) * 1000);

  subscribed = new cookieObject('subscribed', expiry, '/');

  // hide the subscription box if already signed up
  if(subscribed.found) subscribe.style.display = 'none';

  addEvent(subscribe, 'submit', function() {
    subscribed.fields[0] = (new Date()).getTime();
    subscribed.write();
  });

  return true;
}

function popup_exit() {
  if(can_popup == false) return;

  subscribed = new cookieObject('subscribed', 1, '/');
  if(subscribed.found) return;

  seen_popup = new cookieObject('seen_popup', 1, '/');
  if(seen_popup.found) return;

  var properties   = 'toolbar=0,directories=0,menubar=0,scrollbars=0,resizable=0,width=' + popup_width + ',height=' + popup_height;
  var popup_window = window.open(popup_uri, 'Subscribe', properties);
  if(window.focus && popup_window) popup_window.focus();

  // Set a cookie so that the popup only appears once per day
  seen_popup.fields[0] = true;
  seen_popup.write();

  return false;
}

function no_popup_exit() {
  can_popup = false;
  return true;
}

function no_popup_forms_onsubmit() {
  var forms = document.forms;
  var max   = forms.length;

  for(var i = 0; i < max; i++) {
    addEvent(forms[i], 'submit', no_popup_exit);
  }

  return false;
}

function no_popup_links_onclick() {
  var links = document.links;
  var max   = links.length;

  for(var i = 0; i < max; i++) {
    addEvent(links[i], 'click', no_popup_exit);
  }

  return false;
}

function no_popup_conditions() {
  no_popup_forms_onsubmit();
  no_popup_links_onclick();
  return false;
}

function set_status() {
  window.defaultStatus=document.title
}

function addEvent(obj, evType, fn){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
  }
  else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  }
  else {
    return false;
  }
}

addEvent(window, 'load',   set_status);
addEvent(window, 'load',   no_popup_conditions);
addEvent(window, 'load',   set_subscribe);
//addEvent(window, 'unload', popup_exit);
