// wysiwyg_cleaner.api.js,v 1.1 2009/10/11 23:59:16 jide Exp

/**
 * @file
 * Main javascript API.
 */

Drupal.Wysiwyg = Drupal.Wysiwyg || {};

/**
 * Main function.
 * Process settings.
 */
Drupal.Wysiwyg.Cleaner = function(element, preset, showErrors) {

	if (!preset) {
		return;
	}

	var errors = [];

	for (var i in preset.rules) {

		var row = preset.rules[i];
		var rule = row.rule;
		var value = row.value;
		var arguments = row.arguments;
		
		// Handle arguments
		if (value.match(/%[s|d|f|%]/) && arguments) {
			arguments = arguments.split(',');
			for (var i in arguments) {
				value = value.replace(/%[s|d|f|%]/, arguments[i]);
			}
		}
	
		// RegExp
		var ruleParts = rule.match(/^\/(.*)\/([g|i|m]*)$/);
		if (ruleParts) {
			try {
				var re = new RegExp(ruleParts[1], ruleParts[2]);
				element.html(element.html().replace(re, value));
			}
			catch(e) {
				if (showErrors) {
					errors.push(e.message);
				}
			}
		}
		// JQuery selector
		else {
			// Corrects a bug where rules like span[style*='font-size: medium'] won't work
			// if we pass element as the context, so we pass the original selector instead.
			// Crap !
			selector = $(element.selector+' '+rule);

			// We need to reverse order since we want the deepest children to be treated first
			// or they won't be available in the dom after changes on the parents.
			selector.WysiwygCleanerReverse().each(function(i) {
				try {
					eval(value);
				}
				catch(e) {
					if (showErrors) {
						errors.push(e.message);
					}
				}
			});
		}
	}

	if (errors.length) {
		alert(errors.join("\n"));
	}
};


/**
 * jQuery process function.
 * Change tag.
 */
jQuery.fn.WysiwygCleanerChangeTag = function(element, stripAttributes) {
	replacement = '<'+element+'></'+element+'>';
  return this.each(function(){
    element = $(this);
    $(this)
      .after(replacement).next()
      .html(element.html());

		if (!stripAttributes) {
			if (element.attr('class')) {
				element.next().attr('class', element.attr('class'));
			}
			if (element.attr('id')) {
				element.next().attr('id',element.attr('id'));
			}
			if (element.attr('style')) {
				element.next().attr('style',element.attr('style'));
			}
		}
	
	  element.remove();
  });
};

/**
 * jQuery process function.
 * Strip tag.
 */
jQuery.fn.WysiwygCleanerStripTag = function() {
	$(this).replaceWith($(this).html());
};

/**
 * jQuery process function.
 * Remove all attributes.
 */
jQuery.fn.WysiwygCleanerRemoveAllAttributes = function() {
	var tagName;
	$(this).each(function() {
		tagName = this.tagName;
	});
	$(this).WysiwygCleanerChangeTag(tagName.toLowerCase(), true);
};


/**
 * jQuery helper.
 * Reverse "each" statements.
 */
jQuery.fn.WysiwygCleanerReverse = [].reverse;