/**
 *  Main page object
 */
var Main = new function() {
  var self = this;  // reference to itself


  /**
   *  OnNavigate event handler - Triggered on click for every A element
   *
   *  @param {Object} item A Element
   *  @param {Object} historyObject used by DSHistory JS library to control back/forward buttons for AJAX
   *  @return true
   *  @type boolean
   */
  this.onNavigate = function(item, historyObject) {
    debug('Main.onNavigate()');
    // quit if this function has already been called (used to forbid users from hitting one and the same link more than twice in a row)
    //if (arguments.callee.href == item.href) return false;
    //arguments.callee.href = item.href;    // flag this function so we don't do the same thing twice

    // if anchor or new window or javascript or resource, skip this function and follow the link
    if (!item.href || (item.target && item.target != '_self') || item.href.match(/resource/) || item.href.match(/javascript/))
      return true;

    // show progress
    Global.setProgress(true);

    // back/forward button support for AJAX
    if (!historyObject || !historyObject.calledFromHistory)
      dsHistory.addFunction(self.onNavigate, window, item);

    var result = false;

    // hide the messages
    Message.hide();

    // hide the tooltips
    self.hideTooltips();

    // store the requested URL in the cookie
    Cookie.write('requestedURL', item.href);

    // AJAX onFailure handler
    var __onFailure = function(transport) {
      debug("Main.onNavigate().__onFailure()");
      Global.onFailure(this, transport);
    }

    // AJAX onComplete handler
    var __onComplete = function(transport) {
      debug("Main.onNavigate().__onComplete()");
      // hide progress
      setTimeout(
        function() {
          Global.setProgress(false);
        },
        200
      );
    }

    // AJAX onSuccess handler
    var __onSuccess = function(tree, elements, html, scripts) {
      debug("Main.onNavigate().__onSuccess()");
      // avoid AJAX loading of home pages
      if (item.href.indexOf('/index.') > -1)
        result = true;
      // or load everything else through AJAX
      else {
        //setTimeout(function(){Global.loadContent({'html': html, 'scripts': scripts, 'elements': elements, 'tree': tree});}, 100);
        Global.loadContent({'html': html, 'scripts': scripts, 'elements': elements, 'tree': tree});
      }
    }

    setTimeout(
      function() {
        //debug('item.href='+ item.href);
        new Request.HTML({
          url: item.href,
          method: 'get',
          async: false,
          evalScripts: false,
          autoCancel: true,
          onSuccess: __onSuccess,
          onComplete: __onComplete,
          onFailure: __onFailure
        }).send();
      },
      400
    );

    // in case we're calling the function from Flash file, we will set this property (in order to avoid returning of result which is causing redirection)
    var silent = false;
    try {
      silent = item.silent;
    } catch(e) {
      silent = false;
    }

    if (!silent)
      return result;
  }


  /**
   *  hideTooltips() - Hides the tooltoips
   *
   */
  this.hideTooltips = function() {
    //try { this.tooltips['wstips'].tip.setStyle('visibility', 'hidden'); } catch(e) {}
    //try { this.tooltips['nstips'].tip.setStyle('visibility', 'hidden'); } catch(e) {}
  }


  /**
   *  onLoad() - Main page onLoad event handler
   *
   */
  this.onLoad = function() {
    var param = null;
    try {
      param = location.href.split("?")[1];
    } catch(e) {}

    if (!param)
      param = 'home';

    // Check if the page exists
    var path = "pages/{0}.html";
    new Request({
      url: path.replace('{0}', param),
      method: 'get',
      async: false,
      evalScripts: false,
      autoCancel: true,
      onFailure: function(transport) { param = 'home'; }
    }).send();

    this.onNavigate({href: path.replace('{0}', param), target: '_self'});
  }
}


// triggers an event when the page has finished its rendering
window.addEvent('domready', function() {  Main.onLoad();  });
