'use strict';
jQuery(document).ready(function(){
	var $ = jQuery;
	var min = 0.2, max = 1;
	function _draw(i,c,g,v) {
		c.save();
		c.clearRect(0,0,i.width,i.height);
		c.drawImage(g,0,0);
		c.globalAlpha = v;
		c.drawImage(i,0,0);
		c.restore();
	}
	function _fadein(i,c,g) {
		_draw(i,c,g,max);
	}
	function _fadeout(i,c,g) {
		_draw(i,c,g,min);
	}
	function _init() {
		var _this = this;
		if(!(this.naturalHeight && this.naturalWidth)) return window.setTimeout(function(){ _init.call(_this); }, 12);
		var
			self = this,
			w = this.width,
			h = this.height,
			img = $(new Image(w,h)),
			t = $('<canvas/>').attr({'width':w,'height':h}),
			tctx = t[0].getContext('2d'),
			c = $('<canvas/>').attr({'width':w,'height':h}),
			ctx = c[0].getContext('2d'),
			grayscale = {
				'fadeIn'  : function() {_fadein(img[0],tctx,c[0])},
				'fadeOut' : function() {_fadeout(img[0],tctx,c[0]);}
			},
			data=0,imgdata=null,i=0,j=0,idx=0,avg;
		if(!$(this).sfx) $(this).sfx = {'grayscale':grayscale};
		else $(this).sfx.grayscale = grayscale;
		img.load(function(){
			ctx.drawImage(self,0,0);
			data = ctx.getImageData(0,0,c[0].width,c[0].height);
			imgdata = data.data;
			for(j=data.height;j--;) {
				for(i=data.width;i--;) {
					idx=j*4*data.width + (i*4);
					avg = (imgdata[idx]+imgdata[idx+1]+imgdata[idx+2])/3;
					imgdata[idx]   = avg;
					imgdata[idx+1] = avg;
					imgdata[idx+2] = avg;
				}
			}
			ctx.putImageData(data,0,0);
			tctx.putImageData(data,0,0);
			tctx.save();
			tctx.globalAlpha = min;
			tctx.drawImage(self,0,0);
			tctx.restore();
			if($(self).hasClass('sfx-grayscale')) {
				$(self).replaceWith(t);
				t.mouseover(grayscale.fadeIn).mouseout(grayscale.fadeOut);
			} else {
				$(self).replaceWith(t);
				$(t).parent('.sfx-grayscale').mouseover(grayscale.fadeIn).mouseout(grayscale.fadeOut);
			}
		}).attr({'src':this.src});
	}
	var init;
	if($('.msie.no-canvas').length) {
		init = function() {
			var
				_ = $(this),
				lowIE = ($.browser.msie && parseInt($.browser.version) < 8),
				property = lowIE ? 'filter' : '-ms-filter',
				filter = lowIE ? 'Gray()' : 'progid:DXImageTransform.Microsoft.Gray()';
			_.live('mouseover', function(){_.css(property,filter)}).live('mouseout',function(){_.css(property,filter)});
		};
	} else {
		init = _init;
	}
	$('img.sfx-grayscale,.sfx-grayscale img').each(init);
	$.fn.grayscale = function(){
		return this.each(function(){ init.apply(this,arguments); });
	}
});
