/**
 * Ajax wysiwyg Plugin
 *
 * @see http://drupal.org/project/ajax
 *
 */

/**
 * Ajax Forms plugin for wysiwyg API
 * 
 */
Drupal.Ajax.plugins.friendlyFormMessages = function(hook, args) {
  var p, e;
  if (hook === 'message') {
    args.options.action = 'display friendly form messages'
    $('div.form-item div.tool-tip-wrapper').remove();
    $('#tool-tip').remove();
    $('div.form-item .error').removeClass('error');
    
    /**
     * array of possible extentions for field
     * This comes from Drupal supporting error meesages being assigned to parent elements
     * ajax module's ajax_clean_id() then generated our ID's however they won't all exist as you expect in the dom.
     * so we use this array to loop through all the options - notice the first element is blank - this is for the assumption that the ID is correct on recipt.
     */
    var fieldIdExtentions = ['', '-0-value', '-value'] // array of possible extentions for field
    var field = null;
    var unlocatedErrors = []; // this array will be filled with messages which we couldn't find the elements for
    for(message in args.messages_error){ // loop through each error message
      var errorSet = false;
      
      for(exention in fieldIdExtentions){ // loop through each possible ID if it exists we'll break out of the loop
        field = $('#' + args.messages_error[message].id + fieldIdExtentions[exention]);
        if(field.length){
          field.addClass('error');
          field.parent().prepend('<div class="tool-tip-wrapper" id="' + args.messages_error[message].id +'-tool-tip"><div class="tool-tip">' + args.messages_error[message].value + '</div></div>');
          field.parent().find('.tool-tip-wrapper').click(function(event){
             $(this).fadeOut(250, function() { $(this).remove(); });
          });
          errorSet = true;
          break; // error has been applied we can now leave this field.
        }
      }
      
      /**
       * Finally If we've still failed to set the error on an element add it to an array so we can later display it genericly
       */
      if(!errorSet){
        unlocatedErrors[unlocatedErrors.length] = args.messages_error[message];
      }
      //$('#' + args.data.messages_error[message].id + '-wrapper').append('<span class="tool-tip">' + args.data.messages_error[message].value + '</span>');
    }
    
    var errorMessage = $(document.createElement('ul')).attr('id', 'tool-tip');
    for (message in unlocatedErrors){
      var messageItem = $(document.createElement('li')).append(unlocatedErrors[message].value);
      errorMessage.append(messageItem);
    }
  $('.progress-tabs').after(errorMessage);
    alert("There are some errors in your application.Use the navigation at the top of the application to go back and check sections of the form which are not ticked.");
  }

  return true;
}
