Array.prototype.exists = function(o) {
	for(var i = 0; i < this.length; i++) {
		if(this[i] === o) {
			return true;
		}
	}
	return false;
}


Phantom = function() {
	var oThis = this;
	
	setTimeout(function() {
		oThis.init_DOM();
	}, 3000);
}

Phantom.prototype = {
	iSHOTS: 4, //Количество кадров анимации
	
	iIMG_HEIGHT: 320, //Высота картинки с фантомом
	
	MIN_PHANTOMS_ON_PAGE: 3, //Максимальное количество фантомов, одновременно показываемых на странице
	MAX_PHANTOMS_ON_PAGE: 10, //Максимальное количество фантомов, одновременно показываемых на странице

	iANIMATION_DURATION: 1000, //Длительности анимации

	sPATH: '/f/1/', //Путь до картинок
	//sPATH: '', //Путь до картинок
	
	iMAX_DELAY_APEAR: 1000, //Максимальная задержка перед появлением фантома

	iMAX_DELAY_REMOVE: 2500, //Максимальная задержка перед удалением фантома


	PHANTOM: {
		0: {
			img: 'phantom_01.png',
			//compatible: [2,8,9,10,11] //фантомы, с которыми сочетается
			incompatible: [0,1,3,4,5,6,7] //фантомы, с которыми не сочетается
		},
		1: {
			img: 'phantom_02.png',
//			compatible: [6,7,8,9]
			incompatible: [0,1,2,3,4,5,10,11]
		},
		2: {
			img: 'phantom_03.png',
//			compatible: [0,4,5,6,7]
			incompatible: [1,2,3,8,9,10,11]
		},
		3: {
			img: 'phantom_04.png',
//			compatible: [6,7,10,11]
			incompatible: [0,1,2,3,4,5,8,9]
		},
		4: {
			img: 'phantom_05.png',
//			compatible: [2,6,7,8,9,10,11]
			incompatible: [0,1,3,4,5]
		},
		5: {
			img: 'phantom_06.png',
//			compatible: [2,6,7,8,9,10,11]
			incompatible: [0,1,3,4,5]
		},
		6: {
			img: 'phantom_07.png',
//			compatible: [1,2,3,4,5,8,9,10,11]
			incompatible: [0,6,7]
		},
		7: {
			img: 'phantom_08.png',
//			compatible: [1,2,3,4,5,8,9,10,11]
			incompatible: [0,6,7]
		},
		8: {
			img: 'phantom_09.png',
//			compatible: [0,1,4,5,6,7,10,11]
			incompatible: [2,3,8,9]
		},
		9: {
			img: 'phantom_10.png',
//			compatible: [0,1,4,5,6,7,10,11]
			incompatible: [2,3,8,9]
		},
		10: {
			img: 'phantom_11.png',
//			compatible: [0,3,4,5,6,7,8,9]
			incompatible: [1,2,10,11]
		},
		11: {
			img: 'phantom_12.png',
//			compatible: [0,3,4,5,6,7,8,9]
			incompatible: [1,2,10,11]
		}
	},

	init_DOM: function() {
		this.jBody = $('body');
		this.jPhantom_container = $('#phantoms');
		
		this.init();
	},
	
	init: function() {		
		this.iAmount_phantoms = this.rand_amount_phantoms();
		this.aPositions_in_array = []; //Массив позиций картинок в массиве
		this.aPhantoms = []; //Массив картинок, показываемых в данный момент на странице

		var oThis = this;
		
		for (var i = 0; i < this.iAmount_phantoms; i++) {
			setTimeout(function() {
				oThis.rand_phantom_number();
				oThis.show_phantoms();
			}, this.rand_delay_apear());
		}
		
		this.removing();
	},
	
	removing: function() {
		var oThis = this;
			
		setTimeout(function() {
			if(
				oThis.rand_action() === 0 && //Если приходит 0 - удаляем картинку. Если 1 - добавляем новую.
				oThis.aPhantoms.length - 1 >= oThis.MIN_PHANTOMS_ON_PAGE //Количество картинок после удаления должно быть не меньше, чем MIN_PHANTOMS_ON_PAGE
			) {
				oThis.remove_phantom(oThis.rand_victim()); //Рандомно выбираем жертву на удаление со страницы
			}
			else if(oThis.aPhantoms.length + 1 < oThis.MAX_PHANTOMS_ON_PAGE) { //Количество картинок после добавления должно быть меньше, чем MAX_PHANTOMS_ON_PAGE
				oThis.show_phantoms(oThis.rand_phantom_number());
			}
			
			oThis.removing();
		}, this.rand_delay_remove());
		//}, this.iMAX_DELAY_REMOVE);
	},

	rand_victim: function() {
		return Math.floor(Math.random() * this.aPhantoms.length);
	},

	rand_action: function() {
		return Math.floor(Math.random() * 2);
	},
	
	rand_delay_apear: function() {
		return Math.floor(Math.random() * this.iMAX_DELAY_APEAR);
	},
	
	rand_delay_remove: function() {
		return this.iMAX_DELAY_APEAR + Math.floor(Math.random() * (this.iMAX_DELAY_REMOVE - this.iMAX_DELAY_APEAR));
	},
	
	//Рандомное количество картинок от MIN_PHANTOMS_ON_PAGE до MAX_PHANTOMS_ON_PAGE
	rand_amount_phantoms: function() {
		return this.MIN_PHANTOMS_ON_PAGE + Math.floor(Math.random() * (this.MAX_PHANTOMS_ON_PAGE - this.MIN_PHANTOMS_ON_PAGE));
	},
	
	rand_position: function() {
		do {
			var position = Math.floor(Math.random() * this.MAX_PHANTOMS_ON_PAGE);
		} while (this.aPositions_in_array.exists(position)); 
		
		this.aPositions_in_array.push(position);
		
		return position;
	},
	
	//Рандомом выбираем, какую картинку будем показываеть
	rand_phantom_number: function() {
		/*
		 * Генерим случайные числа от 0 до "общее количество картинок минус 1" до тех пор, 
		 * пока не найдем картинку, которой еще нет на странице
		*/
		do {
			var phantom_number = Math.floor(Math.random()*11);
		} while (this.aPhantoms.exists(phantom_number));
		
		this.aPhantoms.push(phantom_number);
		return phantom_number;
	},
	
	remove_phantom: function(i) {
		var oThis = this;
		
		this.aPhantoms.splice(i, 1);
		this.aPositions_in_array.splice(i, 1);

		this.jPhantom_container.find('>div').eq(i).animate({opacity: 0}, this.iANIMATION_DURATION, function() {
			$(this).remove();
		});
	},
	
	show_phantoms: function(i) {
		if(i === undefined) {
			i = this.aPhantoms[this.aPhantoms.length - 1];
		}
		
		this.create_phantom(this.create_images(i));
	},
	
	create_phantom: function(oImage) {
		var oThis = this;
		
		/* Для визуального плезиру запускаем анимацию с задержкой */
		setTimeout(function() {
			new Animation(oImage[0], oThis);
		}, this.rand_delay_apear());
	},
	
	create_images: function(i) {
		var
			iPos = this.position_random(this.rand_position()),
			oThis = this;
			
		var
			eDiv = $(document.createElement('div')),
			image = new Image(),
			image_transparent = new Image(),
			inner_div = $(document.createElement('div')),
			transparent_div = $(document.createElement('div')).addClass('transparent');
		
		inner_div.append($(image).addClass('png'));
		transparent_div.append($(image_transparent).addClass('png'));
		eDiv.css({left: iPos, opacity: 0}).append(inner_div, transparent_div);
		this.jPhantom_container.append(eDiv);
		
		image.onload = function(){
			eDiv.animate({opacity: 1}, oThis.iANIMATION_DURATION);
		}
		
		image.src = this.sPATH + this.PHANTOM[i].img;
		image_transparent.src = this.sPATH + this.PHANTOM[i].img;

		return [eDiv, iPos];
	},
	
	position_random: function(i) {
		var
			iBody_width = this.jBody[0].offsetWidth,
			iLeft = iBody_width/this.MAX_PHANTOMS_ON_PAGE * i;
		
		if(i === 0) {
			iLeft = 0;
		}

		var iRight = iBody_width/this.MAX_PHANTOMS_ON_PAGE * (i+1) - 100;
		
		return iLeft + Math.floor(Math.random() * (iRight - iLeft));
	}
}


Animation = function(jPhantom, oPhantom) {
	this.jPhantom = jPhantom;
	this.oPhantom = oPhantom;
	
	this.jFirst = this.jPhantom.find('div:first-child');
	this.jSecond = this.jPhantom.find('div.transparent');
	
	this.init();
}

Animation.prototype = {
	iANIMATION_DELAY: 1000, //Задержка между анимациями

	iANIMATION_DURATION: 600, //Длительности анимации

	init: function() {
		var oThis = this;

		setTimeout(function() {
			oThis.isAnimate = true;

			oThis.animation(oThis.jFirst, 0.05);
			oThis.animation(oThis.jSecond, 0.9);
		}, oThis.iANIMATION_DURATION);
	},

	animation: function(jPtr, i) {
		var oThis = this;

		jPtr.animate({opacity: i}, this.iANIMATION_DURATION, 'linear',  function() {
			oThis.change_position(jPtr);
        });
	},

	change_position: function(jPtr) {
		if(jPtr.css('opacity') == 0.05 && this.isAnimate) {
			var iTop = jPtr.siblings('div')[0].offsetTop - this.oPhantom.iIMG_HEIGHT/this.oPhantom.iSHOTS;

			if(iTop <= -this.oPhantom.iIMG_HEIGHT) {
				iTop = 0;
			}

			jPtr[0].style.top = iTop + 'px';
			this.animation(jPtr, 0.9);
		}
		else {
			if((jPtr.css('opacity') == 0.9 && jPtr[0].offsetTop == 0) || (jPtr.css('opacity') == 0.05 && jPtr[0].offsetTop !== 0)) {
				this.isAnimate = false;
				return false;
			}
			this.animation(jPtr, 0.05);
		}
	}
}


$(function() {
	new Phantom();
});

