var notificationCenter = null;

function checkPermission()
{
  $("permPending").hide();
  $("permDenied").hide();

  var permission = notificationCenter.checkPermission();

  if(permission == 0)
    $("control").show();
  else
    $("permNeeded").show();
}

function requestPermission()
{
  $("permNeeded").hide();
  $("permPending").show();

  notificationCenter.requestPermission(function() {
    checkPermission();
  });
}

function showNotification(num)
{
  $("control").hide();
  $("notifActive").show();

  var notification = notificationCenter.createNotification("http://sambro.is-super-awesome.com/wp-content/uploads/powpow.gif", "Test Message", "Witty catchphrase here.");
  notification.ondisplay = function()
  {
    window._currentNotif = this;
  };

  notification.onerror = function()
  {
    alert("Error while displaying notification. Try again perhaps?");
    this.onclose();
  }

  notification.onclose = function()
  {
    $("control").show();
    $("notifActive").hide();
  }

  notification.show();
}

function showManyNotifications()
{
  $("control").hide();
  $("manyNotifActive").show();

  var title = "Test Message";

  var numOpen = 0;
  for(var i = 1; i < 6; i++)
  {
    numOpen ++;
    var notification = notificationCenter.createNotification("http://sambro.is-super-awesome.com/wp-content/uploads/powpow.gif", "Test Message #" + i, "Witty catchphrase here.");
    notification.ondisplay = function()
    {
    };

    notification.onerror = function()
    {
      this.onclose();
    }

    notification.onclose = function()
    {
      numOpen--;
      $("numActiveNotifs").innerHTML = numOpen;

      if(numOpen == 0)
      {
        $("control").show();
        $("manyNotifActive").hide();
      }
    }

    notification.show();
  }

  $("numActiveNotifs").innerHTML = numOpen;
}

function showTimedNotification()
{
  $("control").hide();
  $("timedNotifTimer").show();

  var time = 5;
  var timerFunc = function() {
    time--;

    if(time == 0)
    {
      $("timedNotifTimer").hide();
      showNotification();
    }
    else
    {
      $("notifTimer").innerHTML = time;
      window.setTimeout(timerFunc, 1000);
    }
  };

  window.setTimeout(timerFunc, 1000);

  $("notifTimer").innerHTML = time;
}

function cancelNotification()
{
  if(!window._currentNotif) return;

  window._currentNotif.cancel();
}

$(document).observe("dom:loaded", function() {
notificationCenter = window.webkitNotifications;

if(!notificationCenter)
{
  $("notifications").hide();
  $("notif_unsupported").show();
  return;
}
checkPermission();
});
