// Blink
$.fn.blink = function (_time) {

	if ($.browser.msie) {

		this.stop().animate({ opacity : 0.2 }, _time / 2).animate({ opacity : 1 }, _time / 2);
	
	} else {

		var $this = this;
		this.addClass('fade');
	
		setTimeout(function () { $this.removeClass('fade'); }, _time / 2);

	}

};

// jQuery Glitchy Text
$.fn.glitch = function (_spacing, _freq, _dev) {

	var defaults = {

		spacing : (_spacing) ? _spacing : 1,			// Average spacing of letters in em
		freq	: (_freq)	 ? _freq	: 500,			// Average frequency of letter twinkling
		dev		: (_dev)	 ? _dev		: 0.5			// How much of the average time to deviate by

	};

	// For each in collection
	this.each(function (_it) {

		var $this	 = $(this),
			$spanned = $("<div></div>"),
			text	 = $this.text(),
			size	 = $this.css('font-size').replace(/px/,''),
			jitter	 = 0,
			special	 = 0,
			spacing  = size;

		// Separate characters
		for (var i = 0; i < text.length; i++) {

			var $newSpan = $("<span></span>");

			jitter	= 1 - Math.random() * 2;		// Random float from -1 to 1
			spacing	= size * defaults.spacing;		// Standard spacing, times default multiplier
			special = (text[i] === ' ') ? 30 : 0;

			$newSpan.html(text[i]);
			$newSpan.css({ 'margin-left' : spacing + special + jitter * spacing * 1.2 });

			$spanned.append($newSpan);

		}

		// Add back to dom, with a bit of margin to compensate the randomness
		$this.css({ marginLeft : spacing * -1.2 }).html($spanned.children());
		
   		if ($.browser.msie) {
			
			$(".hide").hide().addClass('reveal').delay(2000).fadeIn(5000);

		} else {

			$(".hide").addClass('reveal');

		}

		// Set up to blink random letters
		function randomTime () {

			var thisTime = defaults.freq + (1 - (Math.random() * 2)) * defaults.dev * defaults.freq,
				thisSpan = Math.round(Math.random() * text.length),
				$target	 = $this.children().eq(thisSpan); 	

			$target.blink(4000);

			setTimeout(randomTime, thisTime);

		};

		randomTime();

	});

};


