/** BEGIN CONFIG **************************************************/

//initialize the array that will hold the id of the wrappers where
//a given model/control is associated
var id_array = new Array();
var config_array = new Array();

//For each wrapper where we want to assign events, add ID name to
//this array. Each model and controller will contain the event attachments
//and methods that will be used within a given wrapper. At the end of the bootstrapping
//process we'll end up with array where each element is the model object
//for each ID. Each model object will also be tied to a controller in the init() function.
//Given that variable names and methods for each object will be called from
//the object context that is handed off to the controller, we don't have to worry
//about any methods being overwritten or namespace collisions. All you have to do is
//not have an id listed in this array more than once.	

id_array = ['header_search', 'front_pg_featured', 'calendar_sidebar', 'calendar_full', 'calendar_tab_container', 'concert_details', 'package_tab_container', 'search_text', 'advanced_search','concert_breadcrumb_helper'];

//0 = no debug, 1 = debug, 2 = verbose debug
config_array['_debug'] = 0;

// controller directory path, relative to dojo.js
config_array['_controllers_dir'] = '/js/controllers';

// controller and model directory path, relative to dojo.js
config_array['_models_dir'] = '/js/models';

// using modals?
config_array['modals'] = false;

/** END CONFIG ****************************************************/

/** BEGIN eiMVC class *******************************************/
//eiMVC is the name of our framework sitting on top of the Dojo toolkit.
//This boot strap mechanism loads controllers and models based upon whether or
//not an id is present in id_array()

dojo.declare("eiMVC", null, {
    constructor: function(id_array, config_array){
        //load up our constructor variables
        this._debug = config_array['_debug'];
        this._controllers_dir = config_array['_controllers_dir'];
        this._models_dir = config_array['_models_dir'];
        this._id_array = id_array;
        //This will hold the name of a dom node on each loop through bootstrap()
        this.dom_node = '';
        //We're going to use this array to hold all of our model objects.
        //It will be easy to loop through the array in order to launch
        //controllers for each needed model.
        this.MVC_model_array = new Array();
        this.MVC_controller_array = new Array();
        //model/controller super classes contain methods used across many/all models/classes
        this.model_superclass = new Array();
        this.controller_superclass = new Array();
        //Let's get started by looping through our this._id_array
        //in order to determine which models we need to load for a given
        //page. We'll call bootstrap() to do this.
        this.bootstrap();
		//let's include jQuery so we can access
		//the jQuery object and its methods using the familiar syntax
		//Not needed for Penske
		//this.include_jQuery();
        if (this._debug > 0) {
            // c.log('eiMVC constructed, jQuery instantiated, and bootstrap() done');
        }
    },
	
	load_modals: function(){
		//let's instantiate the modal model. (say that 10 times fast.)
		dojo.registerModulePath("models", this._models_dir);
        dojo.require("models.modal_model");
		var load_modal_model = "modal_model_class = new modal_model(" + this._debug + ");"
        if(eval(load_modal_model)){
			// c.log('modal_model_class loaded');
		}
		
		//let's construct our modal controller 
		dojo.registerModulePath("controllers", this._controllers_dir);	
		dojo.require("controllers.modal_controller");
		var load_modal_controller = "modal_controller_class = new modal_controller(model_superclass, " + config_array['_debug'] + ");";
		//eval(load_controller_superclass);
		if(eval(load_modal_controller)){
			// c.log('modal_controller_class loaded');
		}			
		
		
	},
	
    include_jQuery: function(){
        // Add a dojo.require hook to try to sync new code additions.
        // Do this first so that $.require has the same functionality
        dojo.connect(dojo, "require", function(require){
            var parts = require.split(".");
            if (parts.length >= 2) {
                if (parts[0] == "dojo" && typeof $[parts[1]] == "undefined") {
                    // Use addOnLoad to make this work with a cross-domain build (AOL CDN)
                    dojo.addOnLoad(function(){
                        $[parts[1]] = dojo[parts[1]];
                    });
                }
            }
        });
        
        // Create our $
        $ = dojo.mixin(function(){
            return dojo.mixin(dojo.query.apply(this, arguments), $.fn);
        }, dojo, {
            fn: {}
        });
        
        // Add some plugins
        $.fn.each = function(callback){
            dojo.forEach(this, function(node, i){
                callback.call(node, i);
            });
            return this;
        }
        $.fn.click = function(callback){
            dojo.forEach(this, function(node){
                dojo.connect(node, "onclick", function(e){
                    callback.call(e.target, e);
                });
            });
            return this;
        }
        
        // Add $.ready
        $.ready = $.addOnLoad;
    },
    bootstrap: function(){
		
		//let's instantiate the model_superclass. it extends various
		//objects and includes functions that can be used
		//across all models.
		dojo.registerModulePath("models", this._models_dir);
        dojo.require("models.model_superclass");
		var load_model_superclass = "model_superclass = new model_superclass(" + this._debug + ");"
        if(eval(load_model_superclass)){
			// c.log('model_superclass loaded');
		}
		
		//let's construct our controller superclass
		dojo.registerModulePath("controllers", this._controllers_dir);	
		dojo.require("controllers.controller_superclass");
		var load_controller_superclass = "load_controller_superclass = new controller_superclass(model_superclass, " + config_array['_debug'] + ");";
		//eval(load_controller_superclass);
		if(eval(load_controller_superclass)){
			// c.log('controller_superclass loaded');
		}	
		
		//load modals if configured to use them
		if (config_array['modals'] == true) {
			this.load_modals();
		}			
		
		//Let's do a foreach loop for each id in our this._id_array
        //We'll construct a dynamically named array in order
        //to query the DOM for given IDs
        var id_array_size = this._id_array.length;
        for (i = 0; i < id_array_size; i++) {
            //We'll add consider_ + id name in order to form
            //a dynamically named function that will consider whether or not
            //we need to load a model
            var dynamic_function_name = 'consider_' + this._id_array[i];
            if (this.debug > 0) {
                // c.log('module #' + i + ' - ' + dynamic_function_name + '() created');
            }
            //We'll temporarily assign this.dom_node to the particular value for each array element
            this.dom_node = this._id_array[i];
            ///////////////////////////////////////////////////////////
            //Now we'll set up the function that will query the DOM
            //on each page and return a value of true/false regarding
            //whether or not we found a DOM id
            dynamic_function_name = function(dom_node, models_dir, debug){
                //The value of this will be changed to true and returned
                //as true if this function determined a particular
                //model needed to be loaded.
                var if_load_model = false;
                if (debug > 0) {
                    // c.log('(id ' + i + ') dynamic_function_name() starting');
                }
                //We'll add the necessary # to each dom_node name so
                //we can perform a query via dojo.query(id_name)
                var id_name = '#' + dom_node;
                var dom_id = dojo.query(id_name);
                if (debug > 0) {
                    // c.log('(id ' + i + ')' + ' dom #' + dom_node + ' queried');
                }
                if (debug > 0) {
                    if (dom_id[0]) {
                        if (debug > 1) {
                            // c.dir(dom_id[0]);
                        }
                        // c.log('#' + dom_id[0] + " found!");
                        // c.log(dom_id[0] + ' is ' + typeof(dom_id[0]));
                    }
                    else {
                        if (debug > 0) {
                            // c.log("DOM id NOT found");
                            // c.log("No need to load model or controller.");
                        }
                    }
                }
                //If properties exist for element [0] then we
                //found the DOM node. Let's make sure it really is
                //an object first.
                var found_dom = typeof(dom_id[0]);
                //Return if_load_model as true/false to determine whether
                //or not we need to actually load the model/module
                if ((found_dom == 'object')) {
                    var if_load_model = true;
                }
                else {
                    var if_loaded_model = false;
                }
                //We'll load a model based upon this value.
                return if_load_model;
            }
            ///////////////////////////////////////////////////////////				
            //Execute the previously defined dynamic function. We'll assign
            //the return value of if_load_model and assign it to should_load_model
            var should_load_model = dynamic_function_name(this.dom_node, this._models_dir, this._debug);
            if (this._debug > 0) {
                // c.log('Should we load the model/module? Answer: ' + should_load_model);
            }
            //If should_load_model == true, then register the module path and
            //make the dojo.require call.
            if (should_load_model == true) {
                if (this._debug > 0) {
                    // c.log('Set to load registerModulePath for ' + this.dom_node);
                }
                //Registering the model path.
                dojo.registerModulePath("models", this._models_dir);
                
                //Since there are no file handler functions in JavaScript to check
                //whether or not a file exits, this next line will cause an error if you 
                //forgot to drop a model file in the correct directory 
                //or named it differently from the element in the id_array.
                dojo.require("models." + this.dom_node);
                //if (this._debug > 0) {
                   // c.log(this.dom_node + ' ModulePath loaded.');
                //}
                //We can't call dynamically named classes so we'll build the
                //constructor than eval() it in order to instantiate the model.
                var load_model = "this.MVC_model_array['" + i + "'] = new " + this.dom_node + "(" + this._debug + ");";
               // c.log('load model ' + load_model);
				//Run the previously constructed class instantiation.
                eval(load_model);
                if (this._debug > 1) {
                    // c.log('Check if load_model works...');
                    // c.dir(this.MVC_model_array[i]);
                }
               if (this._debug > 0) {
                    // c.log(this.dom_node + ' fully loaded.');
                }
            }
        }
    }
});
/** END eiMVC class **********************************************/
function init(){
    
    //Instantiate the bootstrapping class
    var OurEIMVC = new eiMVC(id_array, config_array);
    //Register the module path for which we expect to load
    //at least 1 model/controller
	//c.log('-----------------------------------');
    dojo.registerModulePath("controllers", config_array['_controllers_dir']);
    
    if (config_array['_debug'] > 0) {
        // c.log('Number of OurEIMVC models loaded: ' + OurEIMVC.MVC_model_array.length);
		// c.dir(OurEIMVC);
    }
    if (config_array['_debug'] > 1) {
        // c.log('Enumerate the mvc array:');
       // c.dir(OurEIMVC.MVC_model_array);
    }
		
    if (config_array['_debug'] > 0) {
        // c.log('Get ready to load a controller!');
    }
    for (i = 0; i < OurEIMVC.MVC_model_array.length; i++) {
		if (config_array['_debug'] > 1) {
			// c.log("Enumerate a single model on this loop:")
			// c.dir(OurEIMVC.MVC_model_array[i]);
		//            c.dir(OurEIMVC.MVC_model_array[i]);
		}
		if (dojo.isObject(OurEIMVC.MVC_model_array[i])) {
			//Grab the name of the controller/module name from the object's declaredClass
			var controller_name = OurEIMVC.MVC_model_array[i]['declaredClass'];
			if (config_array['_debug'] > 0) {
				// c.log('declaredClass: ' + controller_name);
				// c.log('Controller name to load: ' + controller_name);
			}
			//Since there are no file handler functions in JavaScript to check
			//whether or not a file exits, this next line will cause an error if you 
			//forgot to drop a controller file in the correct directory 
			//or named it differently from the element in the id_array. Todo: Figure
			//out a work around for that.
			dojo.require("controllers." + controller_name);			
			//Build the call that will instantiate our controller class/module.
			var load_a_controller = "var load_controller = new " + controller_name + "(OurEIMVC.MVC_model_array[" + i + "], " + config_array['_debug'] + ");";
			if (config_array['_debug'] > 0) {
				// c.log("Print call controller constructor call...");
				// c.log(load_a_controller);
			}
			if (config_array['_debug'] > 0) {
				// c.log("Get ready to call controller constructor...");
			}
			//Now make the call and instantiate controller module/class for real.
			eval(load_a_controller);
			
			if (config_array['_debug'] > 0) {
				// c.log('No error, controller and model for ' + controller_name + ' has been loaded.');
			}
		}
	}

    if (config_array['_debug'] > 0) {
        // c.log('eiMVC Delivers. DojoMVC INITIALIZATION COMPLETE!!!');
    }   
}
