//================================================
// Attaching WAI-ARIA functionality via class names
//================================================

var aria = function() {
  function init () {
	// wird initiert in basic.js
    $.AW2_roles({
      'banner':         '#headerLeftCol',
      'navigation':     '#metaLeftCol, #metaRightCol, #mainNav, #mainLeftCol, #mainRightCol',
      'main':           '#mainContentCol',
      'contentinfo':    '#footerLeftCol'
    });
    
	// magic
    $.AW2_assignByClasses();
  }
  
  return {
    init: init
  };
}();

// Define our functions
$.fn.AW2_role = function(role) {
  return this.each(function() {
    $(this).attr('role', role);
  });
};

// Define our static functions
$.AW2_roles = function(rolesObject) {
  $.each(rolesObject, function(key, val) {
    $(val).AW2_role(key);
  });
};

/*
    Aria assignment by Classes
    * Reacts on Classes starting with "role" and "aria"
    * Pattern is "attrribute_value"
    * with "aria" the value can be omitted and "true" will be assumed
      * e.g. class="aria-required" == class="aria-required_true"
      
    Examples
    * class="aria-live_polite"
    * class="aria-labelledby_someID"
*/
$.AW2_assignByClasses = function() {
  var ariaSelector = '[class*="role"], [class*="aria"]';

  $(ariaSelector).each(function() {
    var element = this;
    var classes = $(this).attr('class').split(' '); // all classnames
    
    $.each(classes, function(i) { // for each classname
      if ( this.indexOf('role') == 0 ) // if the classname starts with 'role'
      {
        AW2.AW2_role.call($(element), this.split('_')[1]); // role classnames look like: 'role_main'
        $(element).removeClass(this);
      } 
      else if ( this.indexOf('aria') == 0 ) // if the classname starts with aria
      {
        var parts = this.split('_');
        var attribute = parts[0];
        // aria classnames look like: 'aria-activedescendant_something' or 'aria-required'
        // that means if the value is just 'true' we can ommit it in the classname therefore we can us 'aria-required' instead of 'aria-required_true'
        var value = parts[1] != undefined ? parts[1].replace(',', ' ') : 'true';
        
        $(element).attr(attribute, value);
        $(element).removeClass(this+'');
      }
    });
  });
};
