/*Copyright Trinity Innovations LTD 2011. All rights reserved*/
var curPage = 0;
var imgOffset  = 0;
var imgOffsetComplete = Array(); //which images have been  offset (hotspot mapping)

$(document).ready( function() {
	
	//how far is the image from left of screen
	imgOffset = $('#img_mp1').offset().left;

	/** touch wipe pages * */
	$('#pageContainer').touchwipe( {
		wipeLeft : function() {
			gonext();
		},
		wipeRight : function() {
			goprev();
		}
	});

	// double tap

		$('#pageContainer').doubletap( function(event) {
			_dtZoom(curPage);
		}, function(event) {
			return true;

		}, 400);

		var slides = $('.slide');
		var numberOfSlides = slides.length;
		$('#slidesContainer').css('overflow', 'hidden');
		slides.wrapAll('<div id="slideInner"></div>').css( {
			'float' :'left',
			'width' :slideWidth
		});
		$('#slideInner').css('width', slideWidth * totalPageCount);

		_loadPages(IMAGE_PRELOAD_P_COUNT);

		activateMap(1);

	});

/*
 * #------------------------------------------------------------------------- #
 * Project [iPad 3D] # Code By Web Werks
 */
function goprev() {
	if (curPage > 0) {
		curPage--;
		// alert(curPage);
		document.getElementById("gotoFlip").value = (curPage + 1);

		$('#slideInner').animate( {
			'marginLeft' :slideWidth * (-curPage)
		});
	}

	hotSpotTimerLoad();

}

function gonext() {

	if (Number(tmpCounter = curPage+1) < totalPageCount) {
		++curPage;
		$('#slideInner').animate( {
			'marginLeft' :slideWidth * (-(curPage))
		});

		if ($("#gotoFlip"))
			//$("#gotoFlip").attr("value", curPage == 1 ? 2 : curPage);
			$("#gotoFlip").attr("value", Number(curPage+1));

		// fetch some more pages
		_loadPages();
	}

	hotSpotTimerLoad();

}

function rightDirectFlip(pageNo) {
	if (pageNo < 0 || pageNo > totalPageCount)
		return false;
	goTo(pageNo);
}

function leftDirectFlip(pageNo) {
	if (pageNo < 0 || pageNo > totalPageCount)
		return false;
	goTo(pageNo);
}

function goTo(pageNo) {

	if (pageNo != curPage && pageNo <= totalPageCount) {

		/* Is Page Loaded */
		if (getPageLoadedCount() < pageNo) {			
			if($('#ff_panel').css('visibility') != 'visibile'){				
				$('#imgLoadScreen').show();
			}
			_loadPages(Number(Number(pageNo) - Number(getPageLoadedCount())));
			window.setTimeout(goTo, 200, pageNo); // no? set timeout and
													// comeback
			// while we load some more pages
		} else {

			if ($("#gotoFlip"))
				$("#gotoFlip").attr("value", pageNo);

			diff = (pageNo - curPage);
			delta = (diff * slideWidth);

			curOffset = (curPage - 1) * slideWidth;
			newOffset = curOffset + delta;
			// newOffset = diff <= 0 ? curOffset - delta : curOffset + delta;

			$('#slideInner').animate( {
				'marginLeft' :(newOffset * -1)
			});

			curPage = pageNo - 1;

			$('#imgLoadScreen').hide();
			$('#ff_panel').hide();
			hotSpotTimerLoad();
			
			

		}
	}
}

/**
 * How many pages have been loaded
 * 
 * @return
 */
function getPageLoadedCount() {
	var slides = $('.slide');
	return slides.size();

}

function _loadPages(preLoadCount) {

	toPreLoad = PRELOAD_P;

	if(IS_LANDSCAPE_PUB)
		imgLay = LANDSCAPE_FOLDER; /* extern */
	else
		imgLay = PORTRAIT_FOLDER; /* extern */

	if (preLoadCount)
		toPreLoad = preLoadCount;

	if (curPage == -1)
		curPage = 1;

	var pagesLoaded = getPageLoadedCount();

	if (consoleLog) {
		console.log("Have " + pagesLoaded + " pages");
		console.log("(" + preLoadCount + ") Preloading:" + toPreLoad);
	}

	if (pagesLoaded > 1 && curPage + toPreLoad < pagesLoaded) {/*
																 * Load Factor
																 * Check
																 */
		if (consoleLog)
			console.log("Threshold InTact, Have: " + pagesLoaded
					+ " Loaded, Currently At " + curPage);
		return;
	}

	if (consoleLog)
		console.log("Threshold Exceeded, Have: " + pagesLoaded
				+ " Loaded, Currently At " + curPage);

	if (pagesLoaded >= totalPageCount /* extern */)
		return;

	imagesToFetch = new Array();
	for (pageLoader = pagesLoaded; pageLoader < pagesLoaded + toPreLoad
			&& pageLoader < totalPageCount; pageLoader++) {
		imgId = pageLoader + 1;
		imagesToFetch.push(imgLay + imgId + '.jpg');
	}

	$('#imgLoadScreen').show();
	$.imgpreload(imagesToFetch, function() {
		$('#imgLoadScreen').hide();
		loadPages(preLoadCount);

	});

}

/* Function that Loads Pages Into myBook */
function loadPages(preLoadCount) {
	toPreLoad = PRELOAD_P;

	if (preLoadCount)
		toPreLoad = preLoadCount;

	if (curPage == -1)
		curPage = 1;

	var pagesLoaded = getPageLoadedCount();

	if (consoleLog) {
		console.log("Have " + pagesLoaded + " pages");
		console.log("(" + preLoadCount + ") Preloading:" + toPreLoad);
	}

	if (pagesLoaded >= totalPageCount /* extern */ )
		return;

	for (pageLoader = pagesLoaded; pageLoader < pagesLoaded + toPreLoad
			&& pageLoader < totalPageCount; pageLoader++) {
		_insertPage(pageLoader);
	}
}

/**
 * retrun a page container div
 * 
 * @return DIV -> DIV -> DIV -> IMG -> DIV
 */
function _insertPage(pid) {

	if(IS_LANDSCAPE_PUB)
		imgLay = LANDSCAPE_FOLDER; /* extern */
	else
		imgLay = PORTRAIT_FOLDER; /* extern */

	var containerDiv = document.createElement('div');
	containerDiv.setAttribute("class", "slide");
	containerDiv.setAttribute("style", "float:left; width:" + slideWidth);

	var slideImg = document.createElement('img');
	var imgId = pid + 1;
	slideImg.setAttribute("src", imgLay + imgId + '.jpg');
	slideImg.setAttribute("border", '0');
	slideImg.setAttribute("id", 'img_mp'+ imgId );	
	containerDiv.appendChild(slideImg);

	$("#slideInner").append(containerDiv);

}

 
function activateMap(index) { /* empty function */

	if (index){
		activeA = "parts" + Number(index);
	}
	else{
		activeA = "parts" + Number(curPage + 1);
		index = Number(curPage + 1);		
	}

	if(consoleLog) console.log("activeA=" + activeA);

	$('.mapparts').each( function() {
		mid = $(this).attr('id');
		if (mid == activeA) {
			if(consoleLog) console.log("activating HS/Button:" + mid);
			
			//get offset from left and add to bookinfo 0 based calcs			
			//each hotspot on the page needs to be offset by 0+imgLeft pixels  once and once only 
			if(/*!IS_LANDSCAPE_PUB && */imgOffsetComplete[index] != 1){
				$('.hs_mp'+index).each ( function(_elIndex) {					
					curOffset = parseInt($(this).css('left'));					 
					newPos = Number(imgOffset+curOffset);
					$(this).css('left',Math.floor(newPos));
					imgOffsetComplete[index] = 1;
					if(consoleLog) console.log("Page " + index+ " has been Offset by " + imgOffset + " to " + newPos);
				});
			}
			
			$('#' + mid).show();

		} else {
			$('#' + mid).hide();
		}
	});
}