/**
 * Handle the front end logic for the registration form for academy
 * @require YAHOO Dom,Event
 **/
(function(){

  YAHOO.namespace('SEGAL.bb');
  YAHOO.namespace('SEGAL.util');

  var Dom   = YAHOO.util.Dom,
      Event = YAHOO.util.Event;

  //Assume these are IDs unless specified as classes
  var names = {
    FORM_ID: 'registration_form',
    //This is the div that holds the course picker dropdowns.
    COURSE_CONTROLS_CON: 'course_controls_container', 
    COURSE_TEMPLATE: 'course_control_template',
    //Class on the div for the individual course control
    COURSE_DIV_CLASS: 'add_course',
    COURSE_SELECT_CLASS: 'course_select',
    ALT_COURSE : 'alt_course_controls',
    ADD_COURSE_BUTTON : 'add_course',
    DELETE_COURSE_BUTTON_CLASS: 'but_delete_course',
    //Class of the container holding the del course button.
    DELETE_COURSE_CLASS: 'delete_course',
    //Price, totals, subs fields
    SUBTOTAL: 'subtotal',
    PRICE_CLASS: 'price',
    DONATION_AMOUNT: 'donation_amount',
    REGISTRATION_TOTAL: 'reg_total',
    DONATION_TOTAL: 'donation_total',
    GRAND_TOTAL: 'grand_total',
    COURSE_NAME_CLASS: 'course_name'
    
  };
      
  var courseCost = YAHOO.SEGAL.bb.courseCost;


  /**
   * doCourseChange
   * When user picks a new course, update the price field
   * @ todo compensate for fact ie allows selection of disabled option
   *
   **/
  var doCourseChange = function(el) {
    
    //Check if trying to pick disabled choice
    if(el.options[el.selectedIndex].disabled === true) {
      el.selectedIndex = 0;
      return false;
    }
        
    var pcon = Dom.getAncestorByClassName(el, names.COURSE_DIV_CLASS) || Dom.get(names.ALT_COURSE);

    if(!YAHOO.lang.isValue(pcon)) {
      return;
    }

    var ccost = courseCost[el.options[el.selectedIndex].value] || 0 ;
      
    Dom.getElementsByClassName(names.PRICE_CLASS, 'input', pcon, function(input) {
      input.value = ccost;
    });
    
    //Update the display of the course name.
    var displayName = '';

    //If parent is an optgroup, we know its a valid choice.
    if('optgroup' == el.options[el.selectedIndex].parentNode.tagName.toLowerCase()) {
      
      //The name of the class is the first disabled prevsibling
      var nameEl = Dom.getPreviousSiblingBy(el.options[el.selectedIndex], function(el) {
        return el.disabled;        
      });

      displayName = nameEl.innerHTML;

    }

    Dom.getElementsByClassName(names.COURSE_NAME_CLASS, 'span', pcon, function(span) {
      span.innerHTML = displayName;
    });
    
  };


  /**
   * updateCost()
   * Grabs all cost related info, and repops the totals fields
   **/
  var updateCost = function() {

    var courseSubtotal = 0;
    
    //Calc course subtotal
    Dom.getElementsByClassName(names.PRICE_CLASS, 'input', Dom.get(names.COURSE_CONTROLS_CON), function(input) {

      if(input.name=='price' && YAHOO.lang.trim(input.value != '')) {
        courseSubtotal += parseFloat(YAHOO.lang.trim(input.value));
      }
    });
    
    Dom.get(names.SUBTOTAL).value = courseSubtotal;
    Dom.get(names.GRAND_TOTAL).value = courseSubtotal;// + donationAmount;
    
  };

  // To handle when a drop down changes - 
  // put price in price field, recalc total
  // Because onchange event listening is diff between browsers, 
  // will do the call to this inline - in any el that needs this, 
  // onChange='YAHOO.SEGAL.util.changeHandler'
  // Simplifies much.
  var changeHandler = function(el) {

    switch(true) {

      //Add another course control
      case( (el.tagName) && ('select' == el.tagName.toLowerCase()) ) : 
        
        doCourseChange(el);
        updateCost();
        
        break;
      //To handle donation field
      //Might need to do this with a onBlur handler instead of onchange.
      case( (el.tagName) && ('input' == el.tagName.toLowerCase()) ) : 
        
        //Check that its a number
        if(!YAHOO.lang.isNumber(parseInt(el.value, 10))) {
          el.value = 0;
        }
        
        updateCost();
        
        break;
      default:
        break;
    }

  };

  //Make it public!
  YAHOO.SEGAL.util.changeHandler = changeHandler;

  var clickHandler = function(e) {
  
    var el = Event.getTarget(e);

    switch(true) {

      //Add another course control
      case(names.ADD_COURSE_BUTTON == el.id) : 
        
        addCourseControl();
    
        break;
      case(Dom.hasClass(el, names.DELETE_COURSE_BUTTON_CLASS)) : 
        
        removeCourseControl(el);
        // @todo recalc cost
    
        break;
    
      default:
        break;
    }
  };
  
  /**
   * Add a course selection control grouping
   * Hide the alternate course selection grouping
   *
   * @return void
   **/
  var addCourseControl = function() {
    
    //Grab the container
    var courseContainers = Dom.get(names.COURSE_CONTROLS_CON);
    
    //if we have alt course control still showing, 
    //hide it for now - not sure if i want to pop it out of the dom.
    YAHOO.SEGAL.util.hide(Dom.get(names.ALT_COURSE));
    var newCourseCon = Dom.get(names.COURSE_TEMPLATE).cloneNode(true);
    newCourseCon.id = Dom.generateId(); //replace the ID
    
    courseContainers.appendChild(newCourseCon);
    
    //Show the remove button for that one.
    var removeCon = Dom.getFirstChildBy(newCourseCon, function(el) { 
      return Dom.hasClass(el, names.DELETE_COURSE_CLASS);
    });    
    Dom.removeClass(removeCon, 'hide');
    
    //Zero out the price field
    Dom.getElementsByClassName(names.PRICE_CLASS, 'input', newCourseCon, function(input) {
      input.value = '';
    });

    //Zero out the name display
    Dom.getElementsByClassName(names.COURSE_NAME_CLASS, 'span', newCourseCon, function(span) {
      span.innerHTML = '';
    });
    
    
  }; 
  
  var removeCourseControl = function(el) {

    //Get parent div of the button
    var pcon = Dom.getAncestorByClassName(el, names.COURSE_DIV_CLASS);
    Dom.get(names.COURSE_CONTROLS_CON).removeChild(pcon);

    //Do we need to redisplay the Alt course? We count the divs class=add_course
    var len = Dom.getElementsByClassName(names.COURSE_DIV_CLASS, 'div', Dom.get(names.COURSE_CONTROLS_CON)).length;
    if(len == 1) {
      YAHOO.SEGAL.util.show(Dom.get(names.ALT_COURSE));
    }
    
    updateCost();

  };
  

  /**
   * Repopulate price fields after a bad form submit.
   */
  var repopCourseCost = function() {
    //Get all selects
    var selects = Dom.getElementsByClassName(names.COURSE_SELECT_CLASS, 'select', Dom.get(names.COURSE_CONTROLS_CON), function(el) {
      doCourseChange(el);
    });
  };


  Event.onDOMReady(function() {
    //Attach the click handler to the form. 
    Event.on(Dom.get(names.FORM_ID), 'click', clickHandler);
    
    //And make sure the container with price info is fully ready
    //This is to recalc on a bad form submit
    Event.onContentReady(names.COURSE_CONTROLS_CON, function() {
      repopCourseCost();
      updateCost();
    });
    
  }); //end domready
})();


