/*--
Description: The "Controller" is the object responsible for processing change generated by a user's actions with the 'View'.
It acts as a dispatcher of events to the appropriate handling functions.

Steps to use:
1. Instantiate a version of the controller.
2. Decide what events you want to monitor on the page. Define handling functions for the events.
3. Load event types into the controller. Each should be composed of a label and the corresponding handling function.
4. Assign the contollers exec() method as the event handler for DOM elements. Pass in the evt type and evt obj as args.

Note: A controller is not an accountant who gets promoted.
Todo: Write a setter method to update/add event type arguments. handy for use after page loads in response to some user action
--*/

//Constructor
function JControllerBase() {
  this.types = {};
};

//Add an event type which is composed of a label and the corresponding function to be called.
JControllerBase.prototype.addEventType = function(_label,_func,_args){
  if(!this.types[_label]){this.types[_label]=[];}
  //make "handler" object literal
  var _handler = {'func':_func,'args':_args};
  this.types[_label].push(_handler);  
}

//Remove an event type reference by label
JControllerBase.prototype.deleteEventType = function(_label){
  delete this.types[_label];
}

//Find event type and execute associated handling function(s).
//always pass event object as first argument
//each "event type" has an array of handlers. Each 'handler object' is composed of a function and arguments.
//arguments can also be passed in directly from the element via its event handler - take precedence over the handler functions arguments
//return value is determined by combination of handlers return values. if any handlers return false - this returns false.
JControllerBase.prototype.exec = function(_type,_evt,_elem_args){
  //alert("JControllerBase: type= "+_type)
  var _r = true;
  for(var i in this.types){
    if(_type == i){
      for(var handler=0;handler<this.types[i].length;handler++){
        var _args = (_elem_args)?_elem_args:this.types[i][handler].args;
        //execute associated function
        _r = _r && this.types[i][handler].func(_evt,_type,_args);
      }
    }
  }
  return _r;
}

