if (typeof(LIB) == 'undefined') {
  var LIB = {};
}

LIB.baseDialogOps = {
  autoOpen: true
  ,close: function() {
    $(this).dialog('destroy').remove();
    history.back();
  }
  ,modal: true
  ,buttons: {
    Cancel: function() {$(this).dialog('close');}
    ,Ok:  function() {
      var oDialog = LIB.vMessageDialog('Saving', 'Saving...');
      $.post($(this).attr('action'), $(this).serialize(), function(oData) {
        oDialog.dialog('close');
        if (oData.sError) {
          LIB.vErrorDialog(oData.sError);
          return false;
        }
        LIB.vMessageDialog('Success', oData.sHtml);
      }, 'json');

      $(this).dialog('close');
    }
  }
};

LIB.historyClick = function(e) {
  if (typeof($(this).attr('href')) == 'undefined') {
    return false;
  }
  e.preventDefault();
  updatePage($(this).attr('href'));
  history.pushState(null, null, $(this).attr('href'));
}

LIB.vErrorDialog = function(sMessage) {
  return LIB.vMessageDialog('Error', sMessage);
}

LIB.vMessageDialog = function(title, sMessage) {
  return $('<div title="' + title + '">' + sMessage + '</div>').dialog({
    close: function() {
      $(this).dialog('destroy').remove();
    }
    ,modal: true
  });
}

$(document).ready(function() {
  //$('.nav a, #header a').live('click', LIB.historyClick);
  $('.nav li').hover(
    function() {
      $(this).addClass('ui-state-highlight');
    }
    ,function() {
      $(this).removeClass('ui-state-highlight');
    }
  );
});

// use for History API pages
function refreshPage(oData) {
  if ($(oData).first().hasClass('dialog')) {
    $(oData).dialog(LIB.baseDialogOps);
  }
  else {
    //close any dialogs, too...
    $('.dialog').remove();
    $('#' + $(oData).first().attr('id')).replaceWith(oData);
  }
  $('body').trigger('pageLoaded', {id: $(oData).first().attr('id')});
}

function updatePage(link) {
  if (link.search(/ajax/) == -1) {
    if (link.search(/\?/) != -1) {
      var newLink = link + '&ajax=true';
    }
    else {
      var newLink = link + '?ajax=true';
    }
  }
  else {
    var newLink = link;
  }
  $.get(newLink, refreshPage);
}

window.addEventListener('popstate', function(e) {
  updatePage(location.href);
}, false);

/*** Suckerfish code ***/
sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

