//INCLUDE: common.js
//INCLUDE: ajaxHistory.js

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//     L O A D E R

var LOADER = function(){
  
  var NEXT_REQUEST_ID = 0;                      //next assigned request ID
  var lastRequest = null;                       //The last request
  var currentURL = null;                        //The URL of the current page
  var ready = true;                             //Can the loader process/interrupt a request?
  
  /**
   * Initialize the loader and enable AJAX requests to be processed.
   */
  function init(){

    //Get current url
    var url = getCurrentPath();
    currentURL = url;

    //Start up thread to manage requests
    setInterval(function(){
      if(ready && lastRequest && lastRequest.state == "REQUESTED"){
        load(lastRequest);
      }
    },200);
  };
  
  /**
   * Prevents the LOADER from processing any new requests.
   */
   function lock(){
     ready = false;
   };
   
   /**
    * Allows the LOADER to process new requests.
    */
    function unlock(){
      ready = true;
    };

  /**
   * Make a request for content to be loaded.
   */
  function request(url, params){
    var request = {
      id: NEXT_REQUEST_ID,
      url: url,
      params: params,
      state: "REQUESTED"
    };
    NEXT_REQUEST_ID ++;
    lastRequest = request;

  };

	/**
	 * Returns the last request.
	 */
	function getLastRequest(){
		return lastRequest;
	};
  
  /**
   * Processes a request.
   */
  function load(request){

    var url = request.url;
    var params = request.params;
    var allow_duplicates = false;
    if(params && params.allow_duplicates){
      allow_duplicates = true;
    }

    //Ignore duplicate requests
    if(currentURL == url && !allow_duplicates){
      return;
    }

    //Extract parameters
    var callbk_success = null;
    var callbk_error = null;
    var history = true;
    
    if(params){
      if(params.history){
        history = params.history;
      }
      callbk_success = params.callbk_success;
      callbk_error = params.callbk_error;
    }

    //Begin loading new content
    lock();
    request.state = "IN_PROGRESS";
    
    /* Request the content */
    $.ajax({
      url: url,
      cache: true,

      /* Could not load the content */
      error: function( html ){
        unlock();
        request.state = "FAILED";
        if(callbk_error && typeof(callbk_error) == "function"){
          callbk_error();
        }
      },

      /* Content was loaded */
      success: function( html ){
        
        //If a newer request exists, cancel this one and start the new request
        if(lastRequest && lastRequest.state == "REQUESTED"){
          request.state = "CANCELED";
          unlock();
          return;
        }

        currentURL = url;
        
        //Have to extract title from loaded document because JQuery won't allow it...
        var titleStartIx = html.indexOf("<title>");
        var titleEndIx = html.indexOf("</title>");
        var title = html.substring(titleStartIx,titleEndIx).replace("<title>","");
        
        //Add page to history
        if(history){
          $.ajaxHistory.addHistory(url, title );
        }
        
        //Allow more requests to be process and do callback
        unlock();
        if(callbk_success){
          callbk_success(html);
        }
      }
    });
  }

  return {init:init, lock:lock, unlock:unlock, request:request, getLastRequest:getLastRequest};

}();
