/** 
 * @project       jquery.letterCycle.js
 * @description   A plugin to cycle through random letters during a mouseover event.
 * @author        Noam Almosnino http://hellonoam.com
 * @author        Cycle code borrowed from: Devon O. Wolfgang, 
                  http://blog.onebyonedesign.com/?p=56
 * @version       0.1
 * @license       MIT http://www.opensource.org/licenses/mit-license.php
 */
(function($) {
	$.fn.letterCycle = function(options) {
  	$.fn.letterCycle.defaults = {
  		speed: 50,
  		mouseover: false
  	};
		var opts = $.extend({}, $.fn.letterCycle.defaults, options);
		
		return this.each(function() {
		  if(opts.mouseover) {
		    $(this).mouseover(function() { cycleText($(this)); });
		  } else {
		    cycleText($(this));
		  }
		});
		
		function cycleText(element) {
		  if($(element).data("cycleTimer") != undefined) { return }		  
      var origText = element.text(),
		      cycleTimer = 0,
		      str1 = "",
		      str2 = "",
		      str3= "",
		      currentCycleText = "",
		      index = 0;
	      
	    cycleTimer = setInterval(function() {
	      index++;
	      str1 = "";
		    str2 = origText.substr(0, index);
		    str3 = origText.substr(index);
		    var len = str3.length;
		    
		    for (var i = 0; i < len; i++) {
		      str1 += String.fromCharCode(randRange(48, 122));
		      currentCycleText = str2 + str1;
		    }
		    element.text(currentCycleText);
		    
		    if(index == origText.length - 1) {
		      clearInterval(cycleTimer);
		      index = 0;		      
		      element.removeData("cycleTimer");
		      element.text(origText);
		    }
	    }, opts.speed);
	    element.data("cycleTimer", cycleTimer);
		};
		
		function randRange(max, min) {
		  return Math.floor(Math.random() * (max - min + 1)) + min;
		};
	};
})(jQuery);
