/**
    This is the page loader for the game and loads all of the ancillary scripts and css where required
    relies on the javascript templating engine to create the DOM elements. 
**/

// Standard component that is the same across all teams

// Then the Game loader controls loading all of the other components
// Try and abstract the target. When the page is loaded register the 
// component in this.components and then on team change do a this.components.each
// and reload the component from the team config.

// Nasty global function here


var DEBUG = false;
var EXTRAS_BASE = 'http://extras.timesonline.co.uk/conchango/';

debug = function(data){
	if(DEBUG) console.log(data);
}

var TheGameLoader = new function(){
    //this.base_dir = 'http://www.conchango.net/thetimes/';
    this.base_dir = 'http://extras.timesonline.co.uk/conchango/static/';
    
    this.jsfiles = [
        'js/jquery.pack.js',    
        'js/feed_loader.js',     //
        'js/page_controller.js', // 'js/jquery.color.js',   
        'js/team_controller.js'
    ];
    
    this.cssfiles = [
        'css/thegame.css'
    ];
   
    
    this.loaderImageSrc = this.base_dir + 'images/loading.gif';
    this.scriptsToLoad = 0;
    this.stillToLoad = 0;
    this.maxLoad = 0;
    this.loadingBegun = false;
    this.imgLoadTimeout = false;
    this.errorTimeout = false;
    this.loadingCompleteCall = new Array();
	this.progressDiv = false;
    this.initialised = false;
    var self = this;
    
    this.displayLoader = function(){}
    this.hideLoader = function(){}
    this.updateProgress = function(){
        // Update the progress bar on the loader
        // hide the loader if done
		if(this.progressDiv) this.progressDiv.style.width = ((this.maxLoad - this.stillToLoad)/this.maxLoad * 370) + 'px';
		else{
			this.progressDiv = document.getElementById('thegame_progress_inner');
		}
		
       	if(this.stillToLoad == 0){
       		// jQuery should have loaded by now but do this manually
       		debug('Hiding the loading page');
       		$('#thegame_loader_target').hide();
       		window.clearTimeout(this.errorTimeout);
       		debug('TheGameLoader thinks everything has loaded and is calling:');
       		debug(this.loadingCompleteCall);
       		for(var lcc in this.loadingCompleteCall){
       			callable = this.loadingCompleteCall[lcc];
       			callable();
       		}
       		this.loadingCompleteCall = new Array();
       	}
        debug('Loaded '+(this.maxLoad - this.stillToLoad)+'/'+this.maxLoad);
    }
    this.errorLoading = function(){
    	$('div#thegame_loadmessage').show();
    }
    this.loadEvent = function(){
        // Decrement the still to load and if it's 0 hide the loader
        this.stillToLoad--;
        //alert('Still To Load: ' + this.stillToLoad);        
        // Reset the timeout as we are getting updateProgress will cancel it if we are done
        if(this.errorTimeout) window.clearTimeout(this.errorTimeout);
        this.errorTimeout = window.setTimeout(this.errorLoading, 30000);
        this.updateProgress();

    }
    this.loadErrorEvent = function(){
    	// This should display that there was an error somehow but also just
    	// call the regular loadEvent() 
    	this.loadEvent();
    }
    this.queueLoadEvent = function(){
        // This is called before a component is loaded and increments the still to load var
        this.stillToLoad++;
        this.maxLoad = this.stillToLoad;
        debug('Queued Load total events: '+this.stillToLoad);
        this.updateProgress();
        // Set a timeout in case the load event fails.
        if(this.errorTimeout) window.clearTimeout(this.errorTimeout);
        this.errorTimeout = window.setTimeout(this.errorLoading, 30000);
    }
    
    this.init = function(){
        // Load the loading image and set up the callback to call load
        // So it's never not displayed
		
        img = new Image();
        // This is a critical path so we will set a timeout aswell incase
        // the image fails to load for some reason
        this.imgLoadTimeout = window.setTimeout(this.loadCallback, 30000);
        img.onload = this.loadCallback;
        img.src = this.loaderImageSrc;
    }
    
    this.loadCallback = function(){
		this.initialised = true;
        self.loadFiles();
    }
    
    this.loadFiles = function(){
        debug('(TheGameLoader::loadFiles) Load called [this.loadingBegun = '+this.loadingBegun+'].');
        // Cancel the timeout in case it's still running 
        window.clearTimeout(this.imgLoadTimeout);
        if(this.loadingBegun == true) return false;
        this.loadingBegun = true;
        
        // Then lets display the loading overlay so that we don't show the user any
        // funky empty or unstyled divs
        this.progressDiv = document.getElementById('thegame_progress_inner');
        this.displayLoader();
        
        var head = document.getElementsByTagName('head')[0];
        
        /** We should probably display a loading overlay here and do stuff in the back ground 
            then fade out the loader once done **/
        
        /** Load CSS first so things look pretty **/
        for(j = 0; j < this.cssfiles.length; j++){
            var cssf = document.createElement('link');
            cssf.setAttribute('href', this.base_dir + this.cssfiles[j]);
            cssf.setAttribute('rel', 'stylesheet');
            cssf.setAttribute('type', 'text/css');
            head.appendChild(cssf);
        }
        /** Then load the Javascript files **/
        d = new Date();
		
        this.scriptsToLoad =  this.jsfiles.length;
        for(i = 0; i < this.jsfiles.length; i++){
            var jsf = document.createElement('script');
            jsf.setAttribute('src', this.base_dir + this.jsfiles[i] + '?' + d.getTime());
            jsf.setAttribute('chartset', 'utf-8');
            jsf.setAttribute('type', 'text/javascript');
            head.appendChild(jsf);
        }
        
    }
    
    this.scriptLoadCallback = function(script){
    	this.scriptsToLoad--;
		//alert('Loaded: ' + script + '; Still to load: ' + this.scriptsToLoad);
    	if(this.scriptsToLoad == 0){
    		TeamController.initialise();
			PageController.initialise();
    	}
    }
    
    
}

document.TheGameLoader = TheGameLoader;

TheGameLoader.init();



