/*  
 * Project: jQuery texify - text & color shuffling animation
 * Version: v1.0 (28/01/‎2010)
 * URL    : http://texify.borisding.com
 * License: MIT  (http://www.opensource.org/licenses/mit-license.php)
 *          Copyright (c) 2010, Boris Ding P H  
 */

(function($){
   $.fn.texify = function(){
    return this.each(function(){
 
	   $(this).bind("mouseover", function(){					
         cloneEle = $(this).clone(true);
         $.stAction().init(this);
	    });
		
	   $(this).bind("mouseout", function(){
	    $.stAction().clearInit(this);
		 $(this).replaceWith(cloneEle);
	   });	   
   });
  };
     var loopSt, cloneEle;
	 
	$.stAction = function() {
	  var action = {
	   init: function(oThis){
  	     var iType   = $(oThis).attr("type");
		 
		 var sText   = (iType === "button" || iType === "submit")
		               ? $(oThis).val()
					   : $(oThis).text();

		 var sLength = sText.length;
		 var arrChar = new Array();

		 //iterate over each char and store in array
		 for( var i = 0; i < sLength; i++ ){		   
			arrChar[i]  = sText.charAt(i);
         }

		  var nColor  = this.getRandColor();
          var obj     = this.shuffleTex(arrChar);
		  var shufTxt = obj.join("");
		 
		  if(iType === "button" || iType === "submit"){
		   $(oThis).val(shufTxt).css({"color": nColor});

		  }else{ 
			   $(oThis).html(shufTxt).css({"color": nColor});
		  }
		              
			loopSt = setTimeout( function(){
			  $.stAction().init(oThis);
			}, 10 );
	   },
	   
	   //return shuffled text
	   shuffleTex: function(arrObj){	    		 
		 for(
		  var x, y, z = arrObj.length; z; 
		  //get random index
		  x = parseInt(Math.random() * z),
		  //get char
		  y = arrObj[--z],
		  //swap
		  arrObj[z] = arrObj[x],
		  arrObj[x] = y		 
		 );
	      return arrObj;
	   },
	   
	   //get randonmized color
	   getRandColor: function(){
	    var maxRgb = 256;		
		var rgbVal = new Array();
		var rgbTxt = "rgb(";
		//iterate to get rgb value
		for( var i = 0; i < 3; i++ ){
		 rgbVal[i] = Math.floor( Math.random() * maxRgb );
		 if( i < 2 ){		  
		  rgbTxt += rgbVal[i] + ",";
		 }else{
		   rgbTxt +=  rgbVal[i] + ")";
		 }
		}
	     return rgbTxt;
	   },
	   
	   clearInit: function(oThis){
	     clearInterval( loopSt );
	   }
	  };
	  
	  return action;
    }
	  	 	
 })(jQuery);