
var exercice = exercice || {};
exercice.Diaporama = (function (data) {
	
	var fakeDatas = {
		"diaporama_id" : "",
		"diaporama_creator" : "",
		"diaporama_date" : "",
		"diaporama_order" : "[]",
		"diaporama_comments": 0, // show comments of photo
		"diaporama_auto": 0, // auto play
		"diaporama_title": "titre du diaporama",
		"diaporama_speed" : 120000,
		"diaporama_collection": [
			{ "CREDITS": "", "COMMENTAIRES": "commentaire", "TITRE": "photo 1", "FICHIER": "1.png" },
			{ "CREDITS": "", "COMMENTAIRES": "", "TITRE": "photo 2", "FICHIER": "2.png" }
		]

	}


	var windowHeight;
	var headerHeight;
	var footerHeight;
	var windowWidth;
	var arrayPictures = [];
	var _myCurrentPicture = [];
	var indexPicture;
	var _pause = false;
	var _timer;
	var heightDispo;
	var widthDispo;
	var datas;
	var url =""

	function init() {
		
		
		
		if (window.diaporamaDatas) {
			datas = JSON.parse(window.diaporamaDatas);
			url = "img/"
			
		}
		
		 else {
			 if(datas){datas =  fakeDatas; url = datas.diaporama_id+'/';} 
			 else {
				 datas = getDataFromApp()
				url = "uploads/"+datas.diaporama_id+'/';
				
			}

		}
		$(".info").hide();
		$("#currentComment").hide();
		$('.title').html(datas.diaporama_title);

		loadImage();
	}

	

	function addDatasInDiaporama(datas){
		datas = datas
	}

	function loadImage(){
		
		var collection = [];
		var image_loaded = 0;
		if(typeof datas.diaporama_collection==="string") {
			datas.diaporama_collection = JSON.parse(datas.diaporama_collection)
		}
		if(typeof datas.diaporama_order==="string") {
			datas.diaporama_order = JSON.parse(datas.diaporama_order)
		}
		var nbrOfImage = datas.diaporama_collection.length;
		var _tempCollection = [];

		if(datas.diaporama_order.length) {
			for(var u=0;u<nbrOfImage;u++){
				for(var i=0;i<nbrOfImage;i++){
				if(datas.diaporama_collection[i].FICHIER===datas.diaporama_order[u]){
					
					_tempCollection.push(datas.diaporama_collection[i])
				} }
			}
		}

		if(datas.diaporama_order.length) {
			datas.diaporama_collection = _tempCollection
		}
		
	
		
		for (var t = 0; t < nbrOfImage; t++) {
			collection.push(url + datas.diaporama_collection[t].FICHIER)
			
		}

	windowWidth = parseInt(window.innerWidth);
	windowHeight = parseInt(window.innerHeight);
	headerHeight = parseInt($('div#header').css('height'));
	footerHeight = parseInt($('div#footer').css('height'));


	$("#boutons").hide();

	window.onresize = resize;
	resize();

		preloadimages(collection).done(function (images) {
			$.each(images, function (index, value) {
				
				var arrPict = [];
				var imgUrl = images[index].src;
				
				arrPict.push(imgUrl);
				var imgWidth = images[index].width;
			
				arrPict.push(imgWidth);
				var imgHeight = images[index].height;
				
				arrPict.push(imgHeight);
				var imgTitle = datas.diaporama_collection[index].TITRE;
				
				arrPict.push(imgTitle);
				var imgComment = datas.diaporama_collection[index].COMMENTAIRES;
			
				arrPict.push(imgComment);
				var imgCredit = datas.diaporama_collection[index].CREDITS;
			
				arrPict.push(imgCredit);
				
				arrayPictures.push(arrPict);
				
				image_loaded++;
				
				if (image_loaded === nbrOfImage) {
					createDiaporama();

					
					
					if(Number(datas.diaporama_comments)) {
						$(".info").show();
						var _event;
						$("#currentComment").hide();
						if(isTablet()) {
							_event = "touchstart"
						} else {
							_event ="mousedown"
						}
						$(".info").on(_event, function () {
							$("#currentComment").toggle();
						})
					} else {
						$(".info").hide();
					}
					
				}
			});
	
		})
	}

	function isTablet() {
        if( navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPad/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
            || navigator.userAgent.match(/Windows Phone/i)
        ){
            return true;
        }
        else {
            return false;
        }
    }


	function createDiaporama(){
		$("#boutons").show();
		if(!datas.auto) {
			$('#btnPause').hide()
		}
		$("#datas").hide();
		indexPicture = 0;
		afficheCurrent();
		myTimer();
		$('#btnPause').click(function () {
			_pause = true;
			$('#btnPause').hide();
			$('#btnPlay').show();
		});
		$('#btnPlay').click(function () {
			_pause = false;
			$('#btnPause').show();
			$('#btnPlay').hide();
			myTimer();
		});
		$('#btnNext').click(function () {
			nextImage();
			afficheCurrent();
			myTimer();
		});
		$('#btnPrev').click(function () {
			prevImage();
			afficheCurrent();
			myTimer();
		});

	}

	function nextImage() {
		
		if (indexPicture == arrayPictures.length - 1) { indexPicture = 0; }
		else { indexPicture = indexPicture + 1; }
	}
	function prevImage() {
		
		if (indexPicture == 0) { indexPicture = arrayPictures.length - 1; }
		else { indexPicture = indexPicture - 1; }
	}
	function afficheCurrent() {

		_myCurrentPicture = arrayPictures[indexPicture];
		
		$("#currentComment").hide();
		$('#currentPicture').html('<img src="' + _myCurrentPicture[0] + '" />');
		$('#currentPictureTitle span').html(_myCurrentPicture[3] + "<p class='copyright'> ©" + _myCurrentPicture[5]+"</p>");
	
		if((_myCurrentPicture[4]==="" && Number(datas.diaporama_comments))||(_myCurrentPicture[4]===undefined &&  Number(datas.diaporama_comments))||(_myCurrentPicture[4]==='undefined' &&  Number(datas.diaporama_comments))){
			$(".info").hide();
		}else  if( Number(datas.diaporama_comments)){
			$(".info").show();
		}
		$('#currentComment span').text(_myCurrentPicture[4]);
		resize();
	}
	function myTimer() {
		
		if(!Number(datas.diaporama_auto)) {
			return
		}


		if(_timer) {
			clearInterval(_timer);
		}
		
		_timer = setInterval(function () {
			if (!_pause) {
				nextImage();
				afficheCurrent();
			}
		}, Number(datas.diaporama_speed));
	}


	function resize() {
		windowWidth = parseInt(window.innerWidth);
		windowHeight = parseInt(window.innerHeight);
		heightDispo = parseInt(windowHeight - headerHeight - footerHeight);
		widthDispo = parseInt(windowWidth);
	
		$("#loading").css("width", windowWidth + "px");
		$("#loading").css("height", heightDispo + 'px');
		$("#loading").css("padding-top", (heightDispo) / 4 + "px");
		$("div#content").css("height", heightDispo + 'px');
	
		var imageWInit = _myCurrentPicture[1];
		var imageHInit = _myCurrentPicture[2];
		var ratio = imageWInit / imageHInit;
		var widthImage = widthDispo;
		var heightImage = heightDispo;
	
		if ((widthDispo / ratio) > heightDispo) {
			optimizeImg = 'hauteur';
			$('#currentPicture img').css("height", heightImage + 'px');
			$('#currentPicture img').css("width", '');
			$('#currentPicture img').css("margin-top", '');
		}
		else {
			optimizeImg = 'largeur';
			$('#currentPicture img').css("height", '');
			$('#currentPicture img').css("width", widthImage + 'px');
			$('#currentPicture img').css("margin-top", (heightDispo - (widthImage / ratio)) / 2);
		}
	
		
		var spanTextTitleImage = $('#currentPictureTitle span');
		spanTextTitleImage.css("font-size", "");
		var fontSizeInit = spanTextTitleImage.css("font-size").replace("px", "");
		var titleWidthText = spanTextTitleImage.outerWidth();
		var maxLengthText = widthDispo - $('#boutons').outerWidth();
		if (titleWidthText > maxLengthText) {
			spanTextTitleImage.css("font-size", fontSizeInit * (maxLengthText / (titleWidthText + 30)) + "px");
			
		}
		else { spanTextTitleImage.css("font-size", fontSizeInit); }
	
	
	
	}

	

	function preloadimages(arr) {
		var newimages = [], loadedimages = 0
		var postaction = function () { }
		var arr = (typeof arr != "object") ? [arr] : arr
		function imageloadpost() {
			loadedimages++
			if (loadedimages == arr.length) {
				postaction(newimages) 
			}
		}
		for (var i = 0; i < arr.length; i++) {
			newimages[i] = new Image()
			newimages[i].src = arr[i]
			newimages[i].onload = function () {
				imageloadpost()
			}
			newimages[i].onerror = function () {
				imageloadpost()
			}
		}
		return { 
			done: function (f) {
				postaction = f || postaction 
			}
		}
	}


	return {
		init: init
		
	}


})();


$(document).ready(function () {
	
	exercice.Diaporama.init()
})