var introPlayed = false;
var Intro = {
  selector:"#slideshow",
  init: function(){
    
    var flashvars = {forwardURL: "/aust/en/home", xml: "/public/introduction.xml"};
    var params = { quality:"high", bgcolor:0x000000, allowScriptAccess:"sameDomain", allowFullScreen:"false", wmode:"opaque" };
    var attributes = {};
    
    if(introPlayed){
      Nodes.nav.fadeOut(2000);
      Nodes.siteTitle.fadeOut(2000, function(){
        swfobject.embedSWF("/intro-slideshow.swf", "slideshow", "562", "375", "9.0.0", null, flashvars, params, attributes);
      });
    } else {
      Nodes.nav.css({opacity:"0"}).hide();
      Nodes.siteTitle.css({opacity:"0"}).hide();
      swfobject.embedSWF("/intro-slideshow.swf", "slideshow", "562", "375", "9.0.0", null, flashvars, params, attributes);
    }
    
    introPlayed = true;
    
    $("#skipIntro a").click(introCompleted);
    
  },
  deactivate: function(){
    Nodes.nav.fadeIn(2000);
    Nodes.siteTitle.fadeIn(2000);
  }
}

var Home = {
  selector: "#features",
  init: function() {
    CatoAjax.flagBody("home");
    $("#features").featuresFadeIn();
    $("ul.newsTicker").newsticker();
    CatoAjax.flagBody("home");
    
    $("dl#featuresFade a, ul.newsTicker a").click(function(e) {
      var url = this.href;
      CatoAjax.load(true, url, Nodes.content);
      e.preventDefault();
    });
  }
};

var Profiles = {
  selector: "div.profile",
  init: profileSwapper
};

var News = {
  selector: "#newsItems",
  init: function() {
    CatoAjax.flagBody("news");
    newsSlider("#newsItems");
  }
};

var Contacts = {
  selector: "div.office",
  init: function() {CatoAjax.flagBody("contacts");}
};

var Careers = {
  selector: "#careersList",
  init: function() {
    CatoAjax.flagBody("careers");
    $("#careersList a").click(Careers.click);
  },
  click: function(e) {
    var url = this.href;
    CatoAjax.load(false, url, Nodes.content, Careers.loadedCallback);
    e.preventDefault();
  },
  loadedCallback: function() {
    $("#backToCareers, #careersList a").click(Careers.click);
  }
};

// Handles all the events related to the portfolio
var Portfolio = {
  ANIMATION_SPEED: 1000,
  selector: "#portfolioEntryNav",
  init: function() {
    this.setup();
    if (this.nav.get(0)) {
      this.activate();
      $("#portfolioEntryNav, #portfolioEntry").wrapAll('<div id="entryWrapper"></div>');
      this.wrapper = $("#entryWrapper");
      
      CatoAjax.flagBody("portfolio");
    }
    else if (this.active) {
      this.deactivate();
    }
  },
  setup: function(skipMainNav) {
    this.entryNav = $("#portfolioEntryNav");
    $("#portfolioImages").scrollPanel(this.entryNav);
    this.entry = $("#portfolioEntry");
    if (!skipMainNav) {
      this.nav = $("#portfolioNav");
      if (this.nav.get(0)) {
        this.nav.scrollNavigation();
        this.nav.find("a").click(Portfolio.click);
      }
    }
  },
  click: function(e) {
    var url = this.href + "?navigation=false";
    CatoAjax.load(false, url, Portfolio.wrapper, Portfolio.loadedCallback);
    e.preventDefault();
  },
  loadedCallback: function() {
    Portfolio.setup(true);
  },
  activate: function() {
    this.active = true;
    // Fade the background out to white.
    Nodes.wrapper.animate({"backgroundColor": "#ffffff"}, this.ANIMATION_SPEED);
    Nodes.body.addClass("portfolio");
  },
  deactivate: function() {
    this.active = false;
    Nodes.wrapper.animate({"backgroundColor": "#000000"}, this.ANIMATION_SPEED);
    Nodes.body.removeClass("portfolio");
  }
};

var CatoAjax = {
  CHECKS: [Portfolio, Home, Profiles, News, Contacts, Careers, Intro],
  init: function() {
    this.hostAndProtocol = location.protocol+"//"+location.host;
    this.startTime = null;
    // Figure out what section this is.
    this.findCurrent();
    // Set up the loading display
    this.loadingDisplay = $('<div id="ajax-loading">&nbsp;</div>');
    Nodes.inner.append(this.loadingDisplay);
    // Check to see if the body has been flagged
    if (Nodes.body.attr("id")) CatoAjax.bodyFlag = Nodes.body.attr("id");
    
    Nodes.nav.find("a:not(a.toggles)").click(this.click);
    Nodes.nav.find("a.toggles").click(this.toggleClick);
    
    $.ajaxHistory.addCallback(function(newHash){
      CatoAjax.load(true, newHash, Nodes.content);
    });
    $.ajaxHistory.init(function(hash){
      CatoAjax.load(true, hash, Nodes.content);
    }, { baseURL: "/index", defaultTitle:$.trim($("title").text()) });
  },
  findCurrent: function() {
    for (var i = 0; i < CatoAjax.CHECKS.length; i++) {
      if (Nodes.content.find(CatoAjax.CHECKS[i].selector).get(0)) {
        var next = CatoAjax.CHECKS[i];
        break;
      }
    }
    
    if (CatoAjax.current && CatoAjax.current != next) {
      CatoAjax.unflagBody();
      if (CatoAjax.current.deactivate) CatoAjax.current.deactivate();
    }
    if (next) {
      next.init();
      CatoAjax.current = next;
    }
    else {
      CatoAjax.current = null;
    }
  },
  click: function(e) {
    var target = $(this);
    CatoAjax.load(true, target.attr("href"), Nodes.content);
    e.preventDefault();
  },
  toggleClick: function(e) {
    // Get the first anchor in the sublist
    var anchor = $(this).parent().find("ul a:first-child");
    CatoAjax.load(true, anchor.attr("href"), Nodes.content);
    e.preventDefault();
  },
  load: function(checkForCurrent, url, targetNode, callback) {
    disclosureNavigation.select(url);
    //add to history
    $.ajaxHistory.addHistory(url);
    // Check to see if the url has a query string
    if (url.indexOf("?") >= 0) {
      url = url.replace("?", ".htmlf?");
    }
    else {
      if (/\.htmlf$/.test(url) == false) url = url + ".htmlf"; //add htmlf to the end of the url if its not there
    }
    //clear the previous content var
    CatoAjax.pendingContent = null;
    this.startTime = new Date();
    // Store target and callback so we can refer to them later
    this.checkForCurrent = checkForCurrent;
    this.targetNode = targetNode;
    if (callback) this.afterLoadCallback = callback;
    // Show loading, hide existing content
    CatoAjax.fadeOut(this.targetNode);
    // Register loaded handler on the target
    $.get(url, {}, this.displayWhenReady);
    
  },
  // Inserts and initialises the contents
  insertContent: function() {
    CatoAjax.targetNode.html(CatoAjax.pendingContent);
    if (CatoAjax.checkForCurrent) {
      CatoAjax.findCurrent();
      CatoAjax.checkForCurrent = null;
    }
    Headings.init();
  },
  markContentLoaded: function() {
    CatoAjax.contentLoaded = true;
  },
  // Loops until the content is fully loaded, or until a predefined period has
  // elapsed — at present a minimum of two seconds
  displayWhenReady: function(responseText) {
    // If this is the first time we've been called, store the response text
    if (responseText && !CatoAjax.pendingContent){
      CatoAjax.pendingContent = responseText;
    }
    var duration = new Date() - CatoAjax.startTime;
    if (duration > 2000 && Headings.isComplete()) {
      CatoAjax.insertContent();
      resizeContent();
      CatoAjax.fadeIn(CatoAjax.targetNode);
      if (CatoAjax.afterLoadCallback) {
        CatoAjax.afterLoadCallback();
        CatoAjax.afterLoadCallback = null;
      }
      CatoAjax.targetNode = null;
    }
    else {
      window.setTimeout(CatoAjax.displayWhenReady, 200);
    }
  },
  fadeOut: function(node) {
    this.startTime = new Date();
    this.loadingDisplay.stop().css({opacity: 1, width: 0});
    this.loadingDisplay.animate({width: 764}, 5000);
    node.animate({opacity: 0}, 200);
  },
  fadeIn: function(node) {
    this.loadingDisplay.stop().animate({width: 764}, 200).animate({opacity: 0}, 500, "linear", function() {
      node.animate({opacity: 1}, 1000);
    });
  },
  flagBody: function(flag) {
    Nodes.body.attr("id", flag);
    CatoAjax.bodyFlag = flag;
  },
  unflagBody: function() {
    if (CatoAjax.bodyFlag) {
      Nodes.body.attr("id", "");
      CatoAjax.bodyFlag = null;
    }
  }
};
