/* NOTE: do a conditional include of 'DD_belatedPNG' include AFTER including this file for IE6 */
var DD_belatedPNG = null;

var DEBUG;

var CONTENT_MANAGER = {
  
  baseURL: null,
  isBase: false,
  changeRequests: new Array(),
  ready: false,
  
  init: function(){
    
    //Apply PNG fix
    CONTENT_MANAGER.fixPNG();
    
    var pathName;
    var hashName;
    
    /* Get the path of this file */
    pathName = CONTENT_MANAGER.getPath();
    
    // Add ajax history callbacks
    if($.ajaxHistory){
      $.ajaxHistory.addCallback(function(newHash, isBase){

        CONTENT_MANAGER.isBase = isBase;
        var hash = CONTENT_MANAGER.getHash();

        // Load the content in the URL specified in the hash
        CONTENT_MANAGER.changeContent(hash,null,null,false);
      });
    }
    
    CONTENT_MANAGER.baseURL = pathName;
    
    // Init ajax history
    if($.ajaxHistory){
      $.ajaxHistory.init(
        function(hash){
          $.ajaxHistory.addHistory( hash, document.title );
        },
        { baseURL: CONTENT_MANAGER.baseURL, titlePrefix: "PORT AUGUSTA : THE REGIONAL CENTRE OF CULTURE 2008", defaultTitle: document.title }
      );
    }

    /* Get the hash URL */
    var hashName = CONTENT_MANAGER.getHash();
    
    /* Show sound stuff if we have flash */
    if(flash){
      /* Add sound stuff to the bottom of the document */
      $("#south-interface-container").append("<div id='flashSound'></div>");
      $("#south-interface-container").append("<div id='flashSoundReplace'></div>");
    }
    
    /* Create sound manager */
    flashSound = new FlashSound();
    
    /* Get type of this page */
    var pageType = $(".wrapper").attr("rel");

    /* Show loader so we cant see the dirty work being done... */
    CONTENT_MANAGER.showLoader( 1 );

    /* Do initialization */
    CONTENT_MANAGER.getPageManager(pageType).init( $(".wrapper"));
    
    /* Load content without performing transitions or AJAX history... */
    CONTENT_MANAGER.changeContent(hashName,function(){
      
      /* Get type of this page */
      var newPageType = $(".wrapper").attr("rel");
      
      // Do slide-in transition
      CONTENT_MANAGER.getPageManager(newPageType).slideIn();
      
    },null,false,1,false);
    
    /* Process any pending change content requests */
    CONTENT_MANAGER.ready = true;
    setInterval(function(){
        CONTENT_MANAGER.processChangeRequests();
    },200);

    //Google Tracking
    pageTracker._trackPageview( CONTENT_MANAGER.getHash() );
    
  },
  
  getPath: function(){
    
    /* Get the path of this file */
    var pathName = window.location.pathname;
    
    /* If there is no path, then this is the home page */
    if( pathName == null || pathName.length <= 1 ){
      pathName = "/index.html";
    }
    
    /* Ensure there is a leading '/' on the pathname */
    if( pathName.charAt(0) != '/' ){
      pathName = "/" + pathName;
    }
    
    return pathName;
  },
  
  getHash: function(){
    
    // Remove '#' from the hash value
    var hash = window.location.hash;
    if(hash.charAt(0) == '#'){
      hash = hash.slice(1,hash.length);
    }
    
    // If there is no hash, then hash the current path
    if(hash.length <= 0){
      hash = CONTENT_MANAGER.getPath();
    }
    
    return hash;
  },
  
  getPageManager: function( type ){
    if( type == "sub-menu" ){
      return SUB_MENU;
    }else if( type == "main-menu" ){
      return HOME_MENU;
    }else if( type == "slideshow" ){
      return SLIDESHOW;
    }else{
      return OTHER;
    }
  },
  
  processChangeRequests: function(){
    
    if(!CONTENT_MANAGER.ready){
      return;
    }
    
      /* If there are requests to process... */
      if(CONTENT_MANAGER.changeRequests.length > 0){
        
          CONTENT_MANAGER.ready = false;
        
          /* We only process the newest request, so do failure callbacks to all the others... */
          while(CONTENT_MANAGER.changeRequests.length > 1){
            var failedRequest = CONTENT_MANAGER.changeRequests.shift();
            var failedCallbk = failedRequest.callbk_fail;
            if(failedCallbk != null){
              failedCallbk();
            }
          }
        
          /* Get the last queued request */
//?? NOTE: If array operations are not atomic, we probably have race conditions which will mess up AJAX history...
          var request = CONTENT_MANAGER.changeRequests.shift();
          var url = request.url;
          var callbk_success = request.callbk_success;
          var callbk_fail = request.callbk_fail;
          var addToHistory = request.addToHistory;
          var opacity = request.opacity;
          var doTransition = request.doTransition;
          
          url = toAbsoluteURL(url);
          
          /* Show loader with the specified opacity */
          if(opacity == null || typeof(opacity) != "number"){
            /* If no opacity was specified, use default of 0.5 */
            CONTENT_MANAGER.showLoader( 0.5 );
          }else{
            CONTENT_MANAGER.showLoader( opacity );
          }

          /* Request the content */
          $.ajax({
            url: url,
            cache: true,

            /* If we fail hide the loader and do a callback */
            error: function( html ){
              CONTENT_MANAGER.hideLoader();
              if(callbk_fail != null){
                callbk_fail();
              }
              
              /* Do next request */
              CONTENT_MANAGER.ready = true;
              return;
            },

            /* If we succeed ... */
            success: function( html ){
              
              /* Get page title */
              var title = '';
              var titleElement = $(html).filter("#page-title").find("h1");
              if( titleElement !== null ){
                title = $(titleElement).text();
              }

              /* Get the wrappers wrapping the contents */
              var newWrapper = $(html).filter(".wrapper");
              var currentWrapper = $(".wrapper");

              /* Get z-index of current wrapper */
              var zIx = $(currentWrapper).css("z-index");

              /* Insert new wrapper behind this */
              $(newWrapper).css("z-index", zIx-1);
              $(newWrapper).insertAfter(currentWrapper);

              /* Get the type of each page via the rel attribute in the wrappers */
              var newPageType = $(newWrapper).attr("rel");
              var currentPageType = $(currentWrapper).attr("rel");

              /* Play first sound that may appear in the document when the sound player is ready */
              /* NOTE: We can only play one sound at a time */
              var sound = $(newWrapper).find("a.playSound");
              if(sound.length > 0){
                flashSound.enable();
                flashSound.waitReady(function(){
                  flashSound.play($(sound[0]).attr("href"));
                });
              }

              // Create barrier to wait for loading to complete...
              var loadingBarrier = new BarrierSync(1);
              
              /* Init page whilst pre-loading */
              CONTENT_MANAGER.getPageManager(newPageType).init( newWrapper );
              
              /* Find the content that needs preloading */
              var preloads = $(newWrapper).find(".preload");
              
              CONTENT_MANAGER.preload( preloads, loadingBarrier.getNotifier(0) ); // waiting for preloading...

              /* Wait for images to load */
              loadingBarrier.wait(200, function(){
                
                /* Add page to ajax history? */
                if(addToHistory == null || addToHistory == true){
                  /* Only add this url to history if we havent backed to the start page - eg hash of '' */
                  if( !CONTENT_MANAGER.isBase && $.ajaxHistory ){
                    $.ajaxHistory.addHistory( url, title );
                    //Google Tracking
                    pageTracker._trackPageview( CONTENT_MANAGER.getHash() );
                  }
                  /* Set isBase to false for next time */
                  CONTENT_MANAGER.isBase = false;
                }

                /* Fix PNGs */
                //CONTENT_MANAGER.fixPNG();

                /* Hide loader */
                CONTENT_MANAGER.hideLoader();

                /* Slide in new content if we are doing transition */
                if(doTransition || doTransition == null){
                  CONTENT_MANAGER.getPageManager(currentPageType).transitionTo( currentWrapper, newWrapper, doCallback );
                }else{
                  doCallback();
                }

                function doCallback(){

                  /* Change wrappers */
                  $(currentWrapper).remove();
                  $(newWrapper).css("z-index",zIx);

                  /* Do callback */
                  if(callbk_success != null){
                      callbk_success();
                  }
                  
                  /* Do next request */
                  CONTENT_MANAGER.ready = true;
                  return;
                }
              });
            }
          });

      }
  },
  
  showLoader: function( opacity ){

    /* Ensure opacity is in the correct range */
    if( opacity == null || typeof(opacity) != 'number' || opacity < 0 || opacity > 1){
      opacity = 1;
    }
    
    /* If we don't have a loader, add one.*/
    if($("#loader").length <= 0){
      $("body").append("<div id='loader'></div>");
    }
    
    /* If we do not have a pre-loader, add one. */
    if($("#loader .preloader").length <= 0){
      $("#loader").append("<div class='preloader'></div>");
    }
    
    /* If we do not have a wrapper, add one. */
    if($("#loader .loader-wrapper").length <= 0){
      $("#loader").append("<div class='loader-wrapper'></div>");
    }
    
    /* If we do not have a spinning loader image, add one. */
    if($("#loader .loader-wrapper .spinner").length <= 0){
      var img = $('<img />')
      $(img).attr("src","/images/ajax-loader.gif");
      $(img).addClass("spinner");
      $("#loader .loader-wrapper").append(img);
    } 
    
    /* If we do not have a loading bar, add one. */
    if($("#loader .loader-wrapper .loader-bar").length <= 0){
      $("#loader .loader-wrapper").append("<div class='loader-bar'></div>");
      var loading_img = $('<img />');
      $(loading_img).attr("src","/images/LOADING.jpg");
      $(loading_img).addClass("loading");
      $("#loader .loader-wrapper .loader-bar").append(loading_img);
      var small_spinner = $('<img />');
      $(small_spinner).attr("src","/images/ajax-loader-small.gif");
      $(small_spinner).addClass("small_spinner");
      $("#loader .loader-wrapper .loader-bar").append(small_spinner);
    }
    
    if(opacity == 1){
      $("#loader .loader-wrapper .spinner").css("opacity",1);
    }else{
      $("#loader .loader-wrapper .spinner").css("opacity",0);
    }
    
    /* Show the loader at the appropriate opacity */
    $("#loader").css("z-index",127);
    $("#loader").css("width","100%");
    $("#loader").stop().animate({opacity : opacity}, 400);
    
  },
  
  hideLoader: function(){
    
    /* If we don't have a loader then there is nothing to hide...*/
    if($("#loader").length <= 0){
      return;
    }
    
    /* Hide the loader */
    $("#loader").stop().animate({opacity : 0}, 400, function(){
        /* Set loader to back */
        $("#loader").css("width","0px");
        $("#loader").css("z-index",-128);});
  },
  
  preload: function( preloads, callback ){
    
    var loader = $("#loader")
    
    /* If we don't have a loader in the document then do nothing...*/
    if(loader.length <= 0){
      if(callback != null && typeof(callback) == "function"){
        callback();
      }
      return;
    }
    
    var preloader = $(loader).find(".preloader")
    
    /* If we don't have a preloader, then do nothing also... */
    if(preloader.length <= 0){
      if(callback != null && typeof(callback) == "function"){
        callback();
      }
      return;
    }
    
    /* If we don't have anything to preload, then do nothing also... */
    if(preloads.length <= 0){
      if(callback != null && typeof(callback) == "function"){
        callback();
      }
      return;
    }
    
    /* Preload the content */
    var images = new Array();
    $(preloads).each( function( i ){
      
      var src = $(this).attr("src");
      var img = $('<img />');
      
      /* Create a new image with the same src */
      if( src != null){
        img.attr("src",src);
      }else{
        src = $(this).css("background-image");
        /* If this element has a background... */
        if(src != null){
          /* remove the junk we don't want */
          src = src.replace(/"|'|url|\(|\)/g, '');
          /* use bg image as src */
          img.attr("src",src);
        } 
      }

      if(src != null && src != "none" && src != "/none"){
      
        /* If this is a PNG, we may need to apply PNG fix */
        if(src.length > 4 && src.slice(src.length - 4, src.length).toLowerCase() == ".png"){
          $(this).addClass("pngfix");
        }
      
        /* Put the image in the preloader */
        $(preloader).append(img);
        images.push(img);
      }
    });
    
    /* Wait for images to load */
    var wait = setInterval(function() {
      
      /* Check if each image has loaded */
      var hasFinished = true;
      for(i = 0; i < images.length; i++){
        if(images[i].attr("complete") == false){
          hasFinished = false;
        }
      }

      /* If all images have loaded, break */
      if(hasFinished == true){
        clearInterval(wait);
        
        $("#loader .preloader").children().remove();

        if(callback != null && typeof(callback) == "function"){
          callback();
        }

        return;
      }
    }, 200);
    
  },
  
  fixPNG: function(){
    
    //This is only included for IE6
    if(DD_belatedPNG == null){
      return;
    }
    
    //var pngs = $(".pngfix");
    
    //Make all PNGs fully visible
    //var opacities = new Array();
    //$(pngs).each(function(i){
    //  opacities.push($(this).css("opacity"));
    //  $(this).css("opacity",1);
    //});
    
    //Apply fix
    DD_belatedPNG.fix(".pngfix");
    
    //Reverse opacity changes
    //$(pngs).each(function(i){
    //  $(this).css("opacity",opacities.shift());
    //});
    
  },

// ?? Fix up these params later
  changeContent: function( url, callbk_success, callbk_fail, addToHistory, opacity, doTransition ){
    
    /* Require a String */
    if( typeof(url) != "string"){
      if(DEBUG) DEBUG.printError("CONTENT_MANAGER.changeContent( url, callbk_success, callbk_fail ): url was not a String.");
      return;
    }
    
    /* If callbacks are defined, they MUST be a function... */
    if( callbk_success != null && typeof(callbk_success) != 'function'){
      if(DEBUG) DEBUG.printError("CONTENT_MANAGER.changeContent( url, callbk_success, callbk_fail ): callbk-success was not a function.");
      return;
    }
    if( callbk_fail != null && typeof(callbk_fail) != 'function'){
      if(DEBUG) DEBUG.printError("CONTENT_MANAGER.changeContent( url, callbk_success, callbk_fail ): callbk-fail was not a function.");
      return;
    }
    
    //Ignore duplicate requests
    if(CONTENT_MANAGER.changeRequests.length > 0){
      if(url == CONTENT_MANAGER.changeRequests[CONTENT_MANAGER.changeRequests.length -1].url){
        return;
      }
    }
    
    var request = {
      url : url,
      callbk_success : callbk_success,
      callbk_fail : callbk_fail,
      addToHistory : addToHistory,
      opacity : opacity,
      doTransition : doTransition
    };
    
    CONTENT_MANAGER.changeRequests.push( request );
  }
};
