'use strict';

/**
 *@author Felipe Vargas South RIC
 *A module representing a book
 *@Module sgBook
 */
define(['jquery',  'turnJs'], function($) {
	var app = {};
	app.init = function() {


		var containerBook = $("[data-sg-id='elem-book']");
		// console.log(containerBook);
		if (containerBook.length > 0) {
			// $("head").append($("<link rel='stylesheet' href='../../common/css/modules/sgBook.css' type='text/css' media='screen' />"));
		};


		containerBook.each(

			function(i, e) {

				var nextPrev = "<button ignore='1' class='previous-button'  onclick=\"$('.sj-book').turn('previous')\" >Anterior</button>" +
					"<button ignore='1' class='next-button' onclick= \"$('.sj-book').turn('next')\">Siguiente</button>";


				$(this).append(nextPrev);

				var bookDiv = $("<div>", {
					class: "sj-book"
				});


				var width=$(this).attr('data-sg-width')==undefined? 960:parseInt($(this).attr('data-sg-width'));
				var height=$(this).attr('data-sg-height')==undefined? 600:parseInt($(this).attr('data-sg-height'));
				


				bookDiv.append('<div data-sg-id="elem-page-book" depth="5" class="hard ">  </div>'+
				                         '<div data-sg-id="elem-page-book"  depth="5" class="hard front-side"> <div class="depth"></div> </div>'); 

				$(this).find("[data-sg-id='elem-page-book']").each(function() {

					$(this).addClass("own-size");
					$(this).addClass('own-size');
					$(this).css( {
							width: width/2-20,
							height: height-20
							
						});
					

					bookDiv.append(this);
				});

				 bookDiv.append('<div data-sg-id="elem-page-book" class="hard fixed back-side last1 "> <div class="depth"> </div> </div>'+
				                         '<div data-sg-id="elem-page-book"  class="hard last2"></div>');


				$(this).append(bookDiv);

				$(this).css({
					visibility: 'hidden'
				});
				loadApp(bookDiv, $(this),width,height);
			}
		);



		// Load turn.js
		// yepnope({
		// 	test: Modernizr.csstransforms,
		// 	yep: ['js/turn.js'],
		// 	nope: ['js/turn.html4.js', 'css/book-html4.css'],
		// 	both: ['js/book.js', 'css/book.css'],
		// 	complete: loadApp
		// });

	}


	function loadApp(sjBook, bookContainer,width,height) {
		console.log(sjBook);

		var flipbook = sjBook;
		//console.log(flipbook);

		// Check if the CSS was already loaded

		if (flipbook.width() == 0 || flipbook.height() == 0) {

			setTimeout(function() {

				loadApp(sjBook, bookContainer);
			}, 10);

			return;
		}
		// Arrows
		$(document).keydown(function(e) {

			var previous = 37,
				next = 39;

			switch (e.keyCode) {
				case previous:

					$('.sj-book').turn('previous');

					break;
				case next:

					$('.sj-book').turn('next');

					break;
			}
		});
		// Flipbook
		flipbook.turn({
			elevation: 50,
			acceleration: !isChrome(),
			autoCenter: true,
			gradients: true,
			duration: 1000,

			width:width,
			height:height,

			

			when: {
				turning: function(e, page, view) {
					var book = $(this),
						currentPage = book.turn('page'),
						pages = book.turn('pages');
					if (currentPage > 3 && currentPage < pages - 3) {
						if (page == 1) {
							book.turn('page', 2).turn('stop').turn('page', page);
							e.preventDefault();
							return;
						} else if (page == pages) {
							book.turn('page', pages - 1).turn('stop').turn('page', page);
							e.preventDefault();
							return;
						}
					} else if (page > 3 && page < pages - 3) {
						if (currentPage == 1) {
							book.turn('page', 2).turn('stop').turn('page', page);
							e.preventDefault();
							return;
						} else if (currentPage == pages) {
							book.turn('page', pages - 1).turn('stop').turn('page', page);
							e.preventDefault();
							return;
						}
					}
					updateDepth(book, page);

					if (page >= 2)
						$('.sj-book .p2').addClass('fixed');
					else
						$('.sj-book .p2').removeClass('fixed');

					if (page < book.turn('pages'))
						$('.sj-book .p' + (book.turn('pages') - 1)).addClass('fixed');
					else
						$('.sj-book .p' + (book.turn('pages') - 1)).removeClass('fixed');
				},

				turned: function(e, page, view) {
					var book = $(this);
					if (page == 2 || page == 3) {
						book.turn('peel', 'br');
					}
					updateDepth(book);
					book.turn('center');
				},
				end: function(e, pageObj) {
					var book = $(this);
					updateDepth(book);
				}


			}
		});
		flipbook.addClass('animated');

		// Show canvas

		bookContainer.css({
			visibility: ''
		});
	}


	function updateDepth(book, newPage) {

		var page = book.turn('page'),
			pages = book.turn('pages'),
			depthWidth = 16 * Math.min(1, page * 2 / pages);

		newPage = newPage || page;

		if (newPage > 3)
			$('.sj-book .p2 .depth').css({
				width: depthWidth,
				left: 20 - depthWidth
			});
		else
			$('.sj-book .p2 .depth').css({
				width: 0
			});

		depthWidth = 16 * Math.min(1, (pages - page) * 2 / pages);

		if (newPage < pages - 3)
			$('.sj-book .p' + (pages - 1) + ' .depth').css({
				width: depthWidth,
				right: 20 - depthWidth
			});
		else
			$('.sj-book .p' + (pages - 1) + ' .depth').css({
				width: 0
			});

	}

	function numberOfViews(book) {

		return book.turn('pages') / 2 + 1;

	}

	function getViewNumber(book, page) {

		return parseInt((page || book.turn('page')) / 2 + 1, 10);

	}

	function setPreview(view) {

		var previewWidth = 115,
			previewHeight = 73,
			previewSrc = 'pages/preview.jpg',
			preview = $(_thumbPreview.children(':first')),
			numPages = (view == 1 || view == $('#slider').slider('option', 'max')) ? 1 : 2,
			width = (numPages == 1) ? previewWidth / 2 : previewWidth;

		_thumbPreview.
		addClass('no-transition').
		css({
			width: width + 15,
			height: previewHeight + 15,
			top: -previewHeight - 30,
			left: ($($('#slider').children(':first')).width() - width - 15) / 2
		});

		preview.css({
			width: width,
			height: previewHeight
		});

		if (preview.css('background-image') === '' ||
			preview.css('background-image') == 'none') {

			preview.css({
				backgroundImage: 'url(' + previewSrc + ')'
			});

			setTimeout(function() {
				_thumbPreview.removeClass('no-transition');
			}, 0);

		}

		preview.css({
			backgroundPosition: '0px -' + ((view - 1) * previewHeight) + 'px'
		});
	}

	function isChrome() {

		// Chrome's unsolved bug
		// http://code.google.com/p/chromium/issues/detail?id=128488

		return navigator.userAgent.indexOf('Chrome') != -1;

	}

	return app;

});