var queueJS;
var queuePre;
var manif = new Array();
var images = new Array();
var jsons = new Array();
var __disSuffiks;
var __koefDisplay;
var __audio_supported;
addToHomeConfig = {
		autostart: false
	};

function start()
{
	// alert("devicePixelRatio" + window.devicePixelRatio);
	//// Определение набора графики
	if(window.devicePixelRatio && Math.max(window.innerWidth, window.innerHeight)*window.devicePixelRatio>700){
		__disSuffiks = "@2x";
		__koefDisplay = 1;
	}else{
		__disSuffiks = "";
		__koefDisplay = 2;
	};
	document.getElementsByTagName("body")[0].setAttribute('bgcolor', '#000000');
	if(navigator.platform == "Win32" || navigator.platform == "Win16" || navigator.platform == "MacIntel" || navigator.platform == "MacPPC" || navigator.platform == "Mac68K"
		|| navigator.platform == "Linux armv7l" || navigator.platform == "Linux i686" || navigator.platform == "HP-UX" || navigator.platform == "WinCE")
		document.getElementsByTagName("body")[0].setAttribute('bgcolor', '#ffffff');
	//// Инициализация библиотеки facebook
	(function(d, s, id){
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) {return;}
		js = d.createElement(s); js.id = id;
		js.src = "//connect.facebook.net/en_US/all.js";
		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));
	//// Загрузка необходимых компонентов для отображения прелоадера 
	queuePre = new createjs.LoadQueue(true);
	queuePre.addEventListener("complete", completePreloader);
	queuePre.loadManifest([
								// {id:"minpreload", src:"pregame.min.js", type: createjs.LoadQueue.JAVASCRIPT},

								{id:"utils", src:"src/lib/mylibjs/utils.js", type: createjs.LoadQueue.JAVASCRIPT},
								{id:"timer", src:"src/lib/mylibjs/Timer.js", type: createjs.LoadQueue.JAVASCRIPT},
								{id:"preloader", src:"src/PreloaderWnd.js", type: createjs.LoadQueue.JAVASCRIPT},
								{id:"visualctrl", src:"src/lib/str/VisualCTRL.js", type: createjs.LoadQueue.JAVASCRIPT},
								{id:"musjs", src:"src/lib/str/MusicCTRL.js", type: createjs.LoadQueue.JAVASCRIPT},

								{id:"bg_preloaderimg", src:"lib/graphics/loading" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},
								{id:"iconimg", src:"lib/graphics/icon" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},

						]);
}
	//// Конец загрузки компонентов прелоадера
var completePreloader = function (e){
	writeData(e, queuePre);

	t_startTicker();                                                          // Глобальный таймер
	ResizeGame();                                                           // Применение ресайза к прелоадеру
	window.addEventListener('resize', ResizeGame, false);
	var p =  v_startPreloader();                                              // Отображение прелоадера

	//// Загрузка основного содержимого
	queueJS = new createjs.LoadQueue(true);
	queueJS.removeAllEventListeners();
	
	manif = [
							//---- Скрипты -----//
									{id:"configjs", src:"src/lib/config.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"field_paramsjs", src:"src/lib/field_params.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"bezierjs", src:"src/lib/bezier.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Tweener", src:"src/lib/mylibjs/Tweener.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Buttonjs", src:"src/lib/mylibjs/Button.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Textjs", src:"src/lib/mylibjs/Text.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Arrowjs", src:"src/lib/mylibjs/Arrow.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"ResizeTopBottomjs", src:"src/lib/mylibjs/ResizeTopBottom.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"mainjs", src:"src/main.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"storagejs", src:"src/Storage.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"gamejs", src:"src/wnds/Game.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Pausejs", src:"src/wnds/Pause.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"GameOverjs", src:"src/wnds/GameOver.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Menujs", src:"src/wnds/Menu.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Settingjs", src:"src/wnds/Setting.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Aboutjs", src:"src/wnds/About.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Instructionsjs", src:"src/wnds/Instructions.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"BonusWndjs", src:"src/wnds/BonusWnd.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"ChoiseLvljs", src:"src/wnds/ChoiseLvl.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Shopjs", src:"src/wnds/Shop.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"YouAreReadyjs", src:"src/wnds/YouAreReady.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"viewmodelgamejs", src:"src/view-model/ViewModelGame.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"viewmodelInterfaceejs", src:"src/view-model/ViewModelInterface.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"VisualGamejs", src:"src/visual/VisualGame.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"VisualInterfaceejs", src:"src/visual/VisualInterface.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"FloatFrameejs", src:"src/visual/FloatFrame.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"TopInterfaceejs", src:"src/visual/interface/TopInterface.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"BottomInterfaceejs", src:"src/visual/interface/BottomInterface.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Modalejs", src:"src/visual/interface/Modal.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Hintjs", src:"src/visual/interface/Hint.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Tutorialjs", src:"src/visual/interface/Tutorial.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Timerjs", src:"src/visual/interface/Timer.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Fieldjs", src:"src/visual/game/Field.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"TweenerObjectsjs", src:"src/visual/game/TweenerObjects.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Bombjs", src:"src/visual/game/Bomb.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Shipjs", src:"src/visual/objects/Ship.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Minejs", src:"src/visual/objects/Mine.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"ItemShopjs", src:"src/visual/objects/ItemShop.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"LogicGamejs", src:"src/logic/LogicGame.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"BattleShipjs", src:"src/logic/BattleShip.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"BotLogicjs", src:"src/logic/BotLogic.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"SeaObjectsjs", src:"src/logic/SeaObjects.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"TargetSelectionjs", src:"src/logic/TargetSelection.js", type: createjs.LoadQueue.JAVASCRIPT},
									{id:"Fightjs", src:"src/logic/Fight.js", type: createjs.LoadQueue.JAVASCRIPT},
							//---- Графика ----//
									{id:"bgimg", src:"lib/graphics/bg" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},
									{id:"bg_windowimg", src:"lib/graphics/bg_window" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},
									{id:"bg_instructionsimg", src:"lib/graphics/bg_instructions" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},
									{id:"menuimg", src:"lib/graphics/menu" + __disSuffiks + ".jpg", type: createjs.LoadQueue.IMAGE},
									{id:"instrimgs_1", src:"lib/graphics/instructions_1" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},
									{id:"instrimgs_2", src:"lib/graphics/instructions_2" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},

							//------- SpriteSheet's -------//
								{id:"JSON1img", src:"lib/graphics/spriteSheet/items1" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},
								{id:"JSON2img", src:"lib/graphics/spriteSheet/items2" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},
								{id:"JSON3img", src:"lib/graphics/animations/explode1" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},
								{id:"JSON4img", src:"lib/graphics/animations/explode2" + __disSuffiks + ".png", type: createjs.LoadQueue.IMAGE},

							// ---- JSON's ------//
								{id:"JSON1", src:"lib/graphics/spriteSheet/items1" + __disSuffiks + ".json", type: createjs.LoadQueue.JSON},
								{id:"JSON2", src:"lib/graphics/spriteSheet/items2" + __disSuffiks + ".json", type: createjs.LoadQueue.JSON},
								{id:"JSON3", src:"lib/graphics/animations/explode1" + __disSuffiks + ".json", type: createjs.LoadQueue.JSON},
								{id:"JSON4", src:"lib/graphics/animations/explode2" + __disSuffiks + ".json", type: createjs.LoadQueue.JSON}

							];

	createjs.Sound.registerPlugins([createjs.WebAudioPlugin]);
	__audio_supported = createjs.WebAudioPlugin.isSupported();
	if(__audio_supported){
		createjs.Sound.alternateExtensions = ["mp3"];
		queueJS.installPlugin(createjs.Sound);
		manif.push(
					{id:"sound1", src:"lib/sounds/Cannon_Shot.ogg", type: createjs.LoadQueue.SOUND},
					{id:"sound2", src:"lib/sounds/hit-ship-mine.ogg", type: createjs.LoadQueue.SOUND},
					{id:"sound3", src:"lib/sounds/Lose_Sound.ogg", type: createjs.LoadQueue.SOUND},
					{id:"sound4", src:"lib/sounds/reward-chest.ogg", type: createjs.LoadQueue.SOUND},
					{id:"sound5", src:"lib/sounds/WaterExplosion-miss.ogg", type: createjs.LoadQueue.SOUND},
					{id:"sound6", src:"lib/sounds/win.ogg", type: createjs.LoadQueue.SOUND},
					{id:"music", src:"lib/sounds/Pirate-Adventures-music.ogg", type: createjs.LoadQueue.SOUND}
				);
	}

	//// Отслеживание прогресса загрузки
	queueJS.addEventListener("progress", function(e){
														p.setLvl(e.progress);
													});
	//// Окончание загрузки содержимого
	queueJS.addEventListener("complete", function(e){
														/// Запись загруженных данных
														writeData(e, queueJS);
														/// Init Share Facebook
														// FB.init({
														// 	appId      : config.appId,
														// 	status     : true,
														// 	xfbml      : true
														// });
														/// Старт музыки
														MusicCTRL.start(e);
														/// Точка входа в игру
														init();
													});
	queueJS.loadManifest(manif);
};

var writeData = function (e, queue){
	var loadResourses = e.target._loadQueueBackup;
	for (var i = 0; i < loadResourses.length; i++) {
	//------- Если загруженный объект - скрипт
		if (loadResourses[i]._item.type == createjs.LoadQueue.JAVASCRIPT) {
			var script = queue.getResult(loadResourses[i]._item.id);
			document.body.appendChild(script);
		}
	//------- Если загруженный объект картинка
		if (loadResourses[i]._item.type == createjs.LoadQueue.IMAGE) {
			// console.log(loadResourses[i]._item.id)
			images[loadResourses[i]._item.id] = queue.getResult(loadResourses[i]._item.id);
		};
	//------- Если загруженный объект JSON
		if (loadResourses[i]._item.type == createjs.LoadQueue.JSON) {
			var ob = queue.getResult(loadResourses[i]._item.id);
			ob.images = [images[loadResourses[i]._item.id + "img"]];
			jsons[loadResourses[i]._item.id] = new createjs.SpriteSheet(ob);
		};
	};
};

/// Всплывающие окна
var FB_GO = function(){
		FB.ui({
			method: 'feed',
			name: __config.fb_name,
			link: window.location.href,
			picture: window.location.href.substring(0, window.location.href.lastIndexOf('/')+1) + "lib/graphics/starload.png",
			caption: __config.fb_caption,
			description: __config.fb_description
		});
}

var ADD_TO_HOME = function(){
	addToHome.show(true);
}
