/**
 * @author paraboom
 */

/**
 * Тестовая функция
 * @param {String} str Тестовая строка
 * @param {Element[]} elems Массив элементов
 * @return {String}
 */

if (undefined === Common) {
	var Common = {};
}

Common.checkCanvas = function() {
	if (undefined !== window.HTMLCanvasElement)
		return true;

	if (!document.namespaces['v']) {
		document.namespaces.add('v', 'urn:schemas-microsoft-com:vml');

		var ss = document.createStyleSheet();

		ss.cssText = '.vml {behavior:url(#default#VML);display:block;}';
	}

	return false;
}
Common.isCanvas = Common.checkCanvas();

function randomNumber(number){
	return Math.floor(Math.random()*number);
}

var graphicAdapter = (function() {

	function createCanvas(block, img) {
		$(block).height(50).width(img.width+10);

		var canvas = $('<canvas class="shape"></canvas>').appendTo(block).attr({
			height: 50,
			width: img.width+10
		});
		var ctx = canvas.get(0).getContext('2d');
		var obj = [ctx];
		return obj;
	}

	function updateCanvas(ctx, img, dy, angle, isKit) {

		try{
		ctx.clearRect(0, 0, img.width+10, 50);
		if (!isKit){
			ctx.save();
			ctx.translate(angle, 0);
	        ctx.rotate(angle * Math.PI / 360);
			ctx.drawImage(img, 5, 50-img.height+dy, img.width, img.height);
			ctx.restore();
		}
		else{
			ctx.drawImage(img, 5, 50-img.height+dy, img.width, img.height);
		}
		}
		catch (e){
//			console.log(e, ctx, img, dy, angle, isKit);
		}
	}

	function updateCanvasKit(ctx, img, dy, angle, isKit, fontain) {
		ctx.clearRect(0, 0, img.width+10, 50);
		ctx.drawImage(img, 5, 50-img.height+dy);
		if(fontain > 0){
			ctx.drawImage(littlePics.loadedImg[2], 0, 39*(fontain-1), 34, 39, 5, -3, 34, 39);
		}
	}

	function createVml(block, img, isKit) {
		$(block).height(50).width(img.width+10);

		var canvas = $(document.createElement('v:image')).addClass('shape vml').css({
			height: img.height,
			width: img.width,
			position: 'relative',
			left: 5,
			top: 50-img.height
		}).attr('src', img.src).appendTo(block);

		if(isKit){
			var fontainPic = $(document.createElement('v:image')).addClass('shape vml').css({
				height: littlePics.loadedImg[2].height,
				width: littlePics.loadedImg[2].width,
				position: 'absolute',
				left: 5,
				top: -(39*7),
				clip: "rect("+39*7+", 34, "+39*8+", 0)"
			}).attr('src', littlePics.loadedImg[2].src).appendTo(block);
			var obj = [canvas, fontainPic];
		}
		else{
			var obj = [canvas, null];
		}

		return obj
	}

	function updateVml(ctx, img, dy, angle, isKit) {
		if (!isKit){
			ctx.css({
				top: 50-img.height+dy-2,
				"rotation": angle
			});
		}
		else{
			ctx.css({
				top: 50-img.height+dy-2
			});
		}
	}

	function updateVmlKit(ctx, img, dy, angle, isKit, fontain, fontainPic) {
		ctx.css({
			top: 50-img.height+dy
		});
		if(fontain >= 0){
			fontainPic.css({
				top: -(39*fontain),
				clip: "rect("+39*fontain+", 34, "+39*(fontain+1)+", 0)"
			});
		}
		else{
			fontainPic.css({
				"visibility": "hidden"
			});
		}
	}

	return Common.isCanvas ? {
		create: createCanvas,
		update: updateCanvas,
		updateKit: updateCanvasKit
	} : {
		create: createVml,
		update: updateVml,
		updateKit: updateVmlKit
	};
})();


var littlePics = {
	init: function(){
		var that = this;

		this.container = $(".pic_place");

		this.loadedImg = [];
		this.place = []

		this.imgArr = [];
		this.imgArr.push("/f/1/global/i/kit.png");
		this.imgArr.push("/f/1/global/i/ice.png");
		this.imgArr.push("/f/1/global/i/fontain.png");
		var index = 0;

		function onImageLoad(src){
			that.loadedImg.push(src);
			if(that.loadedImg.length == that.imgArr.length){
				that.container.each(
					function(i){
						that.place[i] = new animatedPic(this);
					}
				);
				that.place[0].init(that.loadedImg[0]);
				that.place[1].init(that.loadedImg[1]);
			}
			else{
				index = index + 1;
				startLoad(that.imgArr[index]);
			}
		};

		function startLoad(img){
			var image = new Image();
			var src = img;
			image.onload = function(img){onImageLoad(this)};
			image.src = src;
		}

		startLoad(this.imgArr[index]);
	}

}

var animatedPic = function(elem){
	this.container = $(elem);
	this.isActive = false;
}

animatedPic.prototype = {

	init : function(pic){

		this.image = pic;
		this.kit = (pic.src.indexOf('kit.png') == '-1') ? false : true;

		this.isHovered = false;
		this.isBusy = false;
		this.isActive = true;
		this.currFrame = 0;
		this.currAngle = -3;

		$("<div class='pic'></div>").appendTo(this.container);
		this.water = $(".pic", this.container);

		var obj = graphicAdapter.create(this.container, this.image, this.kit);

		if (obj.length == 2){
			this.canvas = obj[0];
			this.fontainPic = obj[1];
		}
		else{
			this.canvas = obj[0];
			this.fontainPic = null;
		};

		graphicAdapter.update(this.canvas, this.image, 0, 0, this.kit);
		this.water.width(this.container.width());

		this.attachEvents();
		this.container.css({
			"visibility": "visible",
			"cursor": "pointer"
		});
		this.animateStart(50-this.image.height);
	},

	animateImgHover: function(dy, f, angle, ang){
		var that = this;

		if(this.isHovered && !this.isBusy){
			if(dy == 0){
				f = 1;
			}
			else if(dy == 3){
				f = -1;
			}
			if(angle == -3){
				ang = 1;
			}
			else if(angle == 3){
				ang = - 1;
			}
			that.currFrame = dy;
			that.currAngle = angle;
			graphicAdapter.update(this.canvas, this.image, dy, angle, this.kit);
			setTimeout(function(){
				if(angle % 2 == 0){
					that.container.toggleClass("woow");
				}
				that.animateImgHover(dy+f, f, angle+ang, ang);
			}, 80);
		}
	},

	animateImgClick: function(dy, angle, isKit, fontain, fontainPic){
		var that = this;

		this.isBusy = true;

		if(fontain == undefined && isKit){
			fontain = 7;
		}

		if(isKit){
			if(dy % 3 == 0 || fontain % 3 == 0){
				that.container.toggleClass("woow");
			}
			graphicAdapter.updateKit(this.canvas, this.image, dy, angle, isKit, fontain, fontainPic);
		}
		else{
			if(dy % 3 == 0){
				that.container.toggleClass("woow");
			}
			graphicAdapter.update(this.canvas, this.image, dy, angle, isKit);
		}

		if(isKit && !(dy == that.image.height+1)){
			if(fontain >= 0){
				setTimeout(function(){
					that.animateImgClick(dy, angle, isKit, fontain-1, fontainPic);
				}, 75);
			}
			else{
				setTimeout(function(){
					that.animateImgClick(dy+1, angle+1, isKit, fontain, fontainPic);
				}, 50);
			}
		}
		else if(!isKit && !(dy == that.image.height+1)){
			setTimeout(function(){
				that.animateImgClick(dy+1, angle+1,isKit);
			}, 50);
		}
		else{
			this.currAngle = -3;
			this.hideImg();
		}
	},

	animateStart: function(dy){
		var that = this;

		this.isBusy = true;

		if(dy % 3 == 0){
			that.container.toggleClass("woow");
		}
		graphicAdapter.update(this.canvas, this.image, dy, 0, false);

		if(!(dy == 0)){
			setTimeout(function(){
				that.animateStart(dy-1);
			}, 50);
		}
		else{
			this.isBusy = false;
		}
	},

	hideImg: function(){
		var that = this;
		var oldWidth = this.water.width();

		this.water.animate({
			width: 0,
			left: oldWidth/2
		}, 800, function(){
			that.container.empty();
			that.isActive = false;
			that.container.css({
				"cursor": "default"
			});
			var c = randomNumber(9);
			while (littlePics.place[c].isActive) {
				c = randomNumber(9);
			}
			littlePics.place[c].init(littlePics.loadedImg[randomNumber(2)]);
			this.isBusy = false;
		});
	},

	attachEvents: function(){
		var that = this;

		this.container.hover(
			function(){
				that.isHovered = true;
				that.animateImgHover(that.currFrame, 1, 0, 1);
			},
			function(){
				that.isHovered = false;
			}
		).click(
			function(){
				if(!that.isBusy){
					that.animateImgClick(that.currFrame, that.currAngle, that.kit, undefined, that.fontainPic);
				}
			}
		);
	}
}

$( function() {
	littlePics.init();
});