﻿
// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
    arguments.callee = arguments.callee.caller;
    var newarr = [].slice.call(arguments);
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};

// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try
{console.log();return window.console;}catch(err){return window.console={};}})());


// place any jQuery/helper plugins in here, instead of separate, slower script files.

(function($){    

	$.fn.ScreamBloodyGore = function(options) {
		
		function showBaby() {
			$(".baby-gore").show();
			setTimeout(function () {
				$(".baby-gore").hide();
			}, Math.random * 50 + 100);
			setTimeout(showBaby, Math.random() * 1000);
		}
	
		var defaults = {
			color:"red",
			maxHeight:80,
			anchor: "bottom"
		};
		var options = $.extend(defaults, options); 
		$("body").append("<img src='/laboratorio/jquery-scream-bloody-gore/it.jpg' class='baby-gore' />")
		setTimeout(showBaby, Math.random() * 1000);
		return this.each(function() {			
			$(this).css("position", "relative");
			var w = $(this).width();
			var h = options.anchor == "bottom" ? $(this).height() : 0;
			var drops = [];
			for(var i=0; i<w; i++) {
				var rand = Math.random();
				var drop = $("<b class='bloody-drop'></b>");
				$(this).append(drop);
				drop.css("top", h+"px");
				drop.css("left", i+"px");
				drop.animate({
					height: rand * options.maxHeight,
				}, Math.random() * 25000 + 5000);
			}			
		});		
	};
    $.fn.jamming = function(options) {
		
		function buildASCIIalphabet() {
			var alphabet = [];
			for(var i = 0; i <= 94; i++)
			{    
				alphabet.push(String.fromCharCode(32+i));
			}
			return alphabet;
		}
		
        function getRandomChar(alphabet) 
		{
            return alphabet[Math.floor(Math.random() * alphabet.length)];
        }

        var Jammer = (function(root) {            
				
				var pickElement = function(root, instance) {
					var items = $(root).find(".jquery-jamming:not(.jamming-current)");
					instance.el = items.eq(Math.floor(Math.random() * items.size()));
				}
				
				var recharge = function(instance) {
					instance.current_step = instance.el.parent().data("maxSteps") - 
								Math.floor(Math.random() * (instance.el.parent().data("maxSteps") / 10));
				}
				
                var change_char = function (instance) {
                    var _self = instance;
                   					
                    
					if(Math.floor(Math.random() * (_self.jammingStrength + 1)) == 0) {
                        $(_self.el).text(_self.orig_char).removeClass("jammed-char");
                    } else {					
                        $(_self.el).text(getRandomChar(_self.alphabet)).addClass("jammed-char");
                    }
                    _self.current_step--;                    

                    if(_self.current_step > 0) {
                        _self.timeout = setTimeout(function() { 
                            change_char(_self);
                        }, _self.flickeringTimeout);
                    } else {
                        clearInterval(_self.timeout);
                        $(_self.el).removeClass("jamming-current").removeClass("jammed-char").text(_self.orig_char); 
						var pause = _self.maxPause * Math.random();

						recharge(_self);
						setTimeout(function () {
							new Jammer(_self.root);
						}, pause);
                    }
                }
				
				this.root = $(root);
				pickElement(root, this);
				this.maxPause = this.root.data("maxPause");
				var charsToJam = this.root.data("charsToJam");
				var jammingChars = this.root.find(".jamming-current").size();
				
				if(jammingChars >= charsToJam) {
					setTimeout(function () {
						new Jammer(root);
					}, this.maxPause);
				} else {				
					
					this.el.addClass("jamming-current");
					this.orig_char = this.el.text();
					this.alphabet = this.root.data("alphabet");
					
					this.flickeringTimeout = this.root.data("flickeringTimeout");
					this.jammingStrength = this.root.data("jammingStrength");
									
					recharge(this);
					change_char(this);
				}
        });
		
		
		
        var ret = this.each(function() {  		
			var settings = jQuery.extend({
				flickeringTimeout: 250,
				jammingStrength: 3,
				maxSteps: 20,
				maxPause: 2000,
				jammingRatio: .2 //0.0 - 1.0
			}, options);
			
			if(settings.alphabet == undefined)
				settings.alphabet = buildASCIIalphabet();
			
			var jamId = "j"+Math.random();
			$(this).addClass("jam-id", jamId);
			$(this).data("jam-id", jamId);
			$(this).data("alphabet", settings.alphabet);
			
			$(this).data("flickeringTimeout", settings.flickeringTimeout);
			$(this).data("jammingStrength", settings.jammingStrength);
			$(this).data("maxSteps", settings.maxSteps);
			$(this).data("maxPause", settings.maxPause);
			
			var charsCount = 0;
            $.each($(this).get(0).childNodes, function(i, o) {                    
                if(o.nodeType == 3) { //text node	
					var text = $.trim($(o).text());
                                        
                    var replaced = "";
                    for(var i=0; i<text.length; i++) {
                        replaced += "<span class='jquery-jamming'>"+text.charAt(i)+"</span>";
						charsCount++;
                    }
                    
                    $(o).parent().html(replaced);
                }
            });
			
			$(this).data("charsToJam", Math.max(charsCount * settings.jammingRatio, 1));
			
			for(var i=0; i<$(this).data("charsToJam"); i++)
				new Jammer(this);
				
        });
		return ret;
    };
})(jQuery);



$(function () {
	$(".entry-content p").each(function () {
		var html = $(this).html();
		if($.trim($(this).text()).length > 0)
			$(this).html(html + "¶");
	});
	
	$(".entry-title a, .entry-title, h1 a").jamming({
		alphabet: ['?', '©', '½', '?', '8', '±', 'Ø', '†', '•', 'ð', 'Ð', '?', '?'],
		flickeringTimeout: 100,
		maxSteps: 10,
		maxPause: 5000,
		jammingRatio: .05,
		jammingStrength: 1
	});	
});
