/*
 * Copyright (C) 2009 Mo Chen <withinsea@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Damn IE6.
 */
 
(function ($) {

	var _addClass = $.fn.addClass,
		_removeClass = $.fn.removeClass,
		_toggleClass = $.fn.toggleClass;
	
	var SPLITTER = "__";
	var PERMUTATION = false;
	
	$.fn.extend({
	
		addClass: function () {
			_addClass.apply(this, arguments);
			$(this).multiClasses();
			return this;
		},
	
		removeClass: function () {
			_removeClass.apply(this, arguments);
			$(this).multiClasses();
			return this;
		},
	
		toggleClass: function () {
			_toggleClass.apply(this, arguments);
			$(this).multiClasses();
			return this;
		},
	
		multiClasses: function () { $(this).each(function () {
		
			var classes = (this.className || '').replace(/^\s+|\s+$/g, '').split(/\s+/);
			if (classes.length < 2) return;

			var singles = [], doubles = [];
			var singles = $.grep(classes, function (claz) { return claz.indexOf(SPLITTER) < 0; });
			classes = [];
			
			for (var n=1; n<=singles.length; n++) {
				(function (claz, i) {
					if (claz.length >= n) {
						classes.push(claz.join(SPLITTER));
					} else {
						for (var j=(PERMUTATION ? 0 : i); j<singles.length; j++) {
							if ($.inArray(singles[j], claz) < 0) {
								arguments.callee(claz.concat(singles[j]), j+1);
							}
						}
					}
				}) ([], 0);
			}
			
			_removeClass.apply($(this));
			_addClass.apply($(this), [classes.join(" ")]);
			
		}); }
		
	});
	
	$.fn.multiClasses.splitter = function (spl) {
		if (spl) {
			SPLITTER = spl;
		} else {
			return SPLITTER;
		}
	}
	
	$.fn.multiClasses.permutation = function (permu) {
		if (permu != undefined && permu != null) {
			PERMUTATION = permu;
		} else {
			return PERMUTATION;
		}
	}
	
	$(function () {
		$('*').multiClasses();
	});
	
}) (jQuery);
