;


//$.fx.interval = 20;

if(!Math.randomFromTo){ // Рандомизация Math.randomFromTo(100,1000)
	Math.randomFromTo = function(from, to){
		return Math.floor(Math.random() * (to - from + 1) + from);
	};
}
if(!Array.prototype.randomItem){ // Рандомизация элеменкта из массива [1,34,56,76,9,67,5].randomItem();
	Array.prototype.ramdomItem = function(){
		return this[Math.randomFromTo(0, this.length - 1)];
	};
}

var ra_de = function(val){ // Преобразует радианы в градусы
	return ((eval(val))*(180/Math.PI));
}

var de_ra = function(val){ // Преобразует градусы в радианы
	return ((eval(val))*(Math.PI/180));
} 

function log(obj, level){
	if(typeof level == 'undefined'){
//		return; // Скрываем спонтанные логи
	}else{
//		if(level == 1) return; // Скрываем логи порядка запуска методов
	}
//	console.log(obj);
}

function getImageAngle(element){
	return element.Wilq32.PhotoEffect._angle;
}

function portClass(){
	var _this = this;

	this.setSpeed = function(val){
		this.speedRatio = val;
	}
	
	
	
	this.$area = $('#port-animation'); // Поле анимации

	this.offset = this.$area.offset();

	this.globalOffset = (screen.width - 900) / 2;

	this.speedRatio = 4; // Ускорение в N раз

	this.object = {
		truck: {},
		train: {}
		}
		

	this.ship = new shipClass({'port': this});
	this.crane = new craneClass({'port': this, 'id': 'crane1'});
	this.createAllTrucks();



	this.createAllTrains();
	
	


	
	this.animation1 = function(callback) // Анимация первая (разгрузка)
	{
		this.showAllTrucks();
		$('.cargo','#ship').remove();
		this.crane.clearStack();
		this.ship.equip([[4,1,4],[4,1,4],[4,1,4],
			[4,4,5],[4,4,5],[4,4,5],
			[4,7,6],[4,7,6],[4,7,6],
			[3,2,4], [3,5,5], [3,8,6], [3,3,4], [3,6,5], [3,9,6]]);

		this.equipWarehouses();

		this.ship.show(function(){ // выводим корабль
			_this.crane.processingStack(function(){
				_this.ship.hide(function(){
					_this.crane.goToSleep(function(){ // Выводим кран на позицию ожидания
						_this.animation2();
					});
				});
			});
		});
	};
	
	this.animation2 = function(callback) // Анимация вторая (погрузка)
	{
		$('.cargo','#ship').remove();
		_this.crane.clearStack();
//		this.ship.equip([[4,1,4],[4,4,5],[4,7,6]]);
		
		this.addToStackFromWarehouse(1);
//		this.showAllTrucks();
		_this.ship.show(function(){ // выводим корабль
			_this.object.train['train1'].equip({cargo: [[5,1], [5,1], [5,1]]}).show(function(){
				_this.crane.processingStack(function(){
					_this.object.train['train1'].hide();
	
					_this.ship.hide(function(){
						_this.animation3();
					});
				});
			});
		});
	};

	this.animation3 = function(callback) // Анимация третья (складирование)
	{
		$('.cargo','#ship').remove();
/*		
		var shipEquipData = [
			[5,3,7], [5,6,7], [5,9,7]
		];
*/
		setTimeout(function(){
			_this.crane.stop();
		}, 10000)

		
		_this.object.train['train2'].equip({cargo: [[5,7], [5,7], [5,7]]}).show(function(){
			_this.object.train['train1'].equip({cargo: [[5,7], [5,7], [5,7]]}).show();
//		_this.ship.show(shipEquipData,function(){ // выводим корабль
			_this.crane.processingStack(function(){
				_this.object.train['train2'].hide();
				_this.object.train['train1'].hide(function(){
//				_this.ship.hide(function(){
					_this.animation1();
				});
			});
		});
	};
	this.animation1();



	this.createCargo(3,0).appendTo('#warehouse2 .cargo-holder:empty:first'); // Набираем стек
	this.createCargo(3,0).appendTo('#warehouse2 .cargo-holder:empty:first'); // Набираем стек
	this.createCargo(3,0).appendTo('#warehouse2 .cargo-holder:empty:first'); // Набираем стек
	this.createCargo(3,0).appendTo('#warehouse2 .cargo-holder:empty:first'); // Набираем стек
	this.createCargo(3,0).appendTo('#warehouse2 .cargo-holder:empty:first'); // Набираем стек
	this.createCargo(3,0).appendTo('#warehouse2 .cargo-holder:empty:first'); // Набираем стек


//	_this.crane.stackInit(); \\ Запускаем инициализацию обработки стека	
}

// ПРОТОТИПЫ

portClass.prototype = {
	targets: {
		1: 'ship',
		2: 'train1',
		3: 'train2',
		4: 'truck1',
		5: 'truck2',
		6: 'truck3',
		7: 'warehouse1',
		8: 'warehouse2',
		9: 'warehouse3',
	},
	sizesByType: {
		1: 1,
		2: 2,
		3: 4,
		4: 1,
		5: 4
	},
	cargosCreated: 0,
	speed: function(speed){
		return Math.round( speed / this.speedRatio );
	},
	getSpeed: function(distance,speed){ // Вычисляем время необходимое на анимацию
		return Math.round( ( (1000 / speed) * Math.abs(distance) ) / this.speedRatio );
	},
	createCargo: function(type, target, place){
		if(typeof target == 'number' && typeof this.targets[target] == 'string') target = this.targets[target];
		this.cargosCreated++; // Увеличиваем общее число созданных грузов
		var newCargoId = 'cargo'+this.cargosCreated; // Формируем идентификатор нового груза
		
/*
		<div class="cargo-wrapper" style="top:488px; left: 308px;">
			<div class="cargo type4"></div>
			<div class="cargo-shadow type4"></div>
		</div>
*/

		
		var $cargo = $("<div/>", {'class': 'cargo type'+type, 'id': newCargoId}).data({'type':type, 'target':target});
		var classImage = 'cargo-image';
		if(type == 5) classImage += ' random_'+Math.randomFromTo(1,6);
		$("<div/>", {'class': classImage}).appendTo($cargo);
		$("<div/>", {'class': 'cargo-shadow type'+type}).appendTo($cargo);

		if(target == 'ship' && typeof place == 'number'){ // Если передан массив первое значение == 1 то задаем конкретное место для груза по второму параметру
			$cargo.data('target_holder_id', '#ship-cargo-place-'+place);
		}else{
			$cargo.addClass('target-'+target);
		}
		return $cargo;
	},
	createAllTrucks: function(){ // Создает все грузовики
		var _this = this;
		var positions = [354,405,454];
		$.each(positions, function(i,el){
			var newTruck = new truckClass({'port':_this});
			_this.object.truck[newTruck.id] = newTruck;
			newTruck.$truck.css('top',el);
		});
	},
	createAllTrains: function(){ // Создает все поезда
		var _this = this;
		
		var newTrain = new trainClass({'port':_this, 'offsetTop':514,'id':'train1'});
		_this.object.train[newTrain.id] = newTrain;

		var newTrain2 = new trainClass({'port':_this, 'offsetTop':554, 'id':'train2'});
		_this.object.train[newTrain2.id] = newTrain2;
	},
	equipWarehouses: function(){
		$('#warehouse1 .cargo').remove();
		this.createCargo(5,1).appendTo('#warehouse1 .cargo-holder:empty:first'); // Набираем стек
		this.createCargo(5,1).appendTo('#warehouse1 .cargo-holder:empty:first'); // Набираем стек
		this.createCargo(5,1).appendTo('#warehouse1 .cargo-holder:empty:first'); // Набираем стек
		this.createCargo(5,1).appendTo('#warehouse1 .cargo-holder:empty:first'); // Набираем стек
		this.createCargo(5,1).appendTo('#warehouse1 .cargo-holder:empty:first'); // Набираем стек
		this.createCargo(5,1).appendTo('#warehouse1 .cargo-holder:empty:first'); // Набираем стек
	},
	addToStackFromWarehouse: function(id){
		var _this = this;
		$('#warehouse'+id+' .cargo').each(function(i,el){
			_this.crane.stack.push($(this)); // Набираем стек
		})
	},
	hideAllTrucks: function(){
		
		var _this = this;
	
		var startPosition = 0 - 220 - this.globalOffset;	
	
		$('.truck:visible').each(function(){
			var $truck = $(this);
			$truck.data('class').hide(function(){
				$(this).children('.cargo').remove();
			});
		});
	},
	showAllTrucks: function(){
		var _this = this;
		$('.truck').each(function(){
			var truck = $(this).data('class');
			setTimeout(function(){
				truck.show();
			}, _this.speed(Math.randomFromTo(1000,8000)));
		});
	}
};



$(function(){
	var port = new portClass('port-animation');
	$('#turrrbo').toggle(function() {
		port.setSpeed(12);
		$(this).html('&times1');
	}, function() {
		port.setSpeed(2);
		$(this).html('&times10');
	});

});
