/**
 * shuffle plugin
 *
 * Copyright (c) 2009 PRIME-X
 *
 */

(function($){

	$.fn.shuffle = function(settings){

		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({},settings);
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		
		//check group
		function _checkGroup(){
			var group_names = new Array();
			jQueryMatchedObj.each(function(){
				var gname = $(this).attr('shuffle_id');
				if(gname==undefined){
					gname = "___default___"+ (new Date()).getTime()*Math.random();
					$(this).attr('shuffle_id',gname);
				}
				if($.inArray(gname,group_names)<0){
					group_names.push(gname);
				}
			});
			
			return group_names;
		}
		
		//make random number
		function _randomize(elem_array){
			var i = elem_array[0].length;
			while(i){
				i--;
				var j = Math.floor(Math.random()*i);
				$.each(elem_array,function(){
					var t = this[i];
					this[i] = this[j];
					this[j] = t;
				});
			}
			return elem_array;
		};
		
		var groupList = _checkGroup();
		$.each(groupList,function(i,val){
			var group_elems = new Array();
			$(".shuffle[shuffle_id='"+val+"']").each(function(){
				group_elems.push($(this).children());
			});
			group_elems = _randomize(group_elems);
			$(".shuffle[shuffle_id='"+val+"']").each(function(){
			//	$(this).empty();
				$(this).append(group_elems.shift());
			});
		});
		
	};

})(jQuery);

$(function(){
	$('.shuffle').shuffle();
});
