/*Copyright Trinity Innovations LTD 2011. All rights reserved*/
$(document).ready(function(){
	
	ini();/*bookFlip.js*/
	
	/** touch wipe pages * */	
	$('#myBook').touchwipe({		
 		wipeLeft: function() {
		    gonext();
 		},
		    wipeRight: function() { 			
		    goprev();
 		}
	    });
	
	_reloadEvents(0);	 
	$("#flipHtml0").append($("#parts1"));
	$('#parts1').show(); // I inherited this mess - don't ask!
	
 });


function _loadPages(preLoadCount){	
	toPreLoad  = PRELOAD;
	
	if(preLoadCount) 
			toPreLoad = preLoadCount;
	
	if(consoleLog)
		console.log("PreLoad Request:" + preLoadCount); 

	imgLay = LANDSCAPE_FOLDER;

	_curPage = 0;
	
	if(curPage == -1)
		_curPage = 1;
	else 
		_curPage = rightStart;
	
	var myBook = $('#myBook');
	var pagesLoaded = myBook.children().size();
	
	//threshold / load check
	if(pagesLoaded > 1 && _curPage+toPreLoad <  pagesLoaded){
		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');
	}

	
	if(curPage!=1)
		$('#imgLoadScreen').show();
	$.imgpreload(imagesToFetch, 
	function() {			
		$('#imgLoadScreen').hide();
		loadPages(preLoadCount);		
	});

	
}



/* Function that Loads Pages Into myBook */
function loadPages(preLoadCount){
	toPreLoad  = PRELOAD;
	
	if(preLoadCount) 
			toPreLoad = preLoadCount;	
	
	imgLay = LANDSCAPE_FOLDER;
	

	if(curPage == -1)
		curPage = 1;
	
	var myBook = $('#myBook');
	var pagesLoaded = myBook.children().size();
	
	if(consoleLog){
		console.log("Have " + pagesLoaded  + " pages, asked For:" + preLoadCount + ", Preloading:" + toPreLoad);	
	}
	

	if(pagesLoaded >= totalPageCount /* extern */)		
			return;	
	
	for(pageLoader = pagesLoaded; pageLoader < pagesLoaded+toPreLoad && pageLoader < totalPageCount ; pageLoader++){
		var _nextDiv = _insertPage(pageLoader,imgLay);
		myBook.append(_nextDiv);
		/*if(consoleLog)
			console.log("Adding :" + pageLoader);*/
	}
	
	_reloadEvents(pagesLoaded);
	
}

/**
 * retrun a page container div
 * 
 * @return DIV -> DIV -> DIV -> IMG -> DIV
 */
function _insertPage(pid,imgLay){	
	
	var pWidth=myPageW_L+(pageBorderWidth*2); // pageBorderWidth & myPageW ext def
	var pHeight=myPageH_L+(pageBorderWidth*2);// myPageH ext def
	
	var containerDiv = document.createElement('div');	
	containerDiv.style.position="absolute";
	containerDiv.style.left=pWidth+'px';
	containerDiv.style.top="0px";
	containerDiv.style.width=pWidth+"px";
	containerDiv.style.height=pHeight+"px";			
	containerDiv.style.backgroundColor="#f1f1f1";
	//containerDiv.style.background="transparent url(images/loading.gif) center center no-repeat";
	containerDiv.style.overflow="hidden";	
	containerDiv.style.zIndex=totalPageCount - pid; // totalPageCount extern
	containerDiv.setAttribute("id","flipPage"+pid);
	
	var innerDiv = document.createElement('div');
	innerDiv.setAttribute("id","flipHtml"+pid);	
	innerDiv.style.position="absolute";
	innerDiv.style.width=myPageW_L+"px";
	innerDiv.style.height=myPageH_L+"px";
	innerDiv.style.top="0px";
	innerDiv.style.left="0px";		
	innerDiv.style.overflow="hidden";			
	// innerDiv.style.borderWidth=pageBorderWidth+"px";
	// innerDiv.style.borderColor=pageBorderColor;
	innerDiv.setAttribute("class","uiContainerPage");
	innerDiv.setAttribute("onTouchStart","setCurPage($('#gotoFlip').attr('value')); return true;");
	
	// add the image
	var pageImgHolder = document.createElement('div');
	pageImgHolder.setAttribute("align","center");
	var pageImg = document.createElement('img');
	var imgId = pid+1;
	

	//$.imgpreload(imgLay+imgId+'.jpg',function(){});	
	
	pageImg.setAttribute("src",imgLay+imgId+'.jpg');
	pageImg.setAttribute("usemap",'#parts'+imgId);
	pageImg.setAttribute("border",'0');
	pageImgHolder.appendChild(pageImg);
	innerDiv.appendChild(pageImgHolder);
	
	
	if(!number_check(counter)){
		if(document.all){
			original.style.filter="progid:DXImageTransform.Microsoft.Alpha(Opacity=100, FinishOpacity=30, Style=1, StartX=80, FinishX=100, StartY=0, FinishY=0)";
		}else{
			var myPngDiv = document.createElement('div'); 
			myPngDiv.style.position="absolute";
			myPngDiv.style.left=(pWidth-80)+'px';
			myPngDiv.style.top="0px";
			myPngDiv.style.width=80+"px";
			myPngDiv.style.height=pHeight+"px";			
			//myPngDiv.style.background="transparent url(images/black_gradient.png) top right repeat-y";				
			myPngDiv.style.opacity="0.7";	
			myPngDiv.style.filter="alpha(opacity=30)";				
			innerDiv.appendChild(myPngDiv);
		}			
	}
	
	containerDiv.appendChild(innerDiv);
	
	
	return containerDiv;
}

/**
 * Rebind new elements
 * 
 * @return
 */
function _reloadEvents(startAt){
	taparea = $('.uiContainerPage');	 
	taparea.each(			
			function(index){
				if(index>=startAt){ // some of these have been set up already,
									// if we repeat it gets buggy!
					$(this).doubletap (
						function(event){			
							if(consoleLog)
								console.log("dt");
								_dtZoom(index);						
						},
						function(event){
							if(consoleLog)
								console.log("st");							
						},
						400
					)
				}
	});
}


/**
 * How many pages have been loaded
 * 
 * @return
 */
function getPageLoadedCount(){	
	var myBook = $('#myBook');
	return myBook.children().size();
	
}

/**
 * Activate the map for the current page
 * 
 * @return
 */
function activateMap(pageIndex){	
	active = $("#gotoFlip").attr('value');
	activeA = "parts"+active;
	activeB = "parts"+(active-1);	
	if(consoleLog) console.log("activeA=" + activeA);
	if(consoleLog) console.log("activeB=" + activeB);
	
	$('.mapparts').each( function() {		
		mid = $(this).attr('id');
		if(mid == activeA){
			if(consoleLog) console.log ("activating" + mid);
			$("#flipHtml" + (active-1)).append($('#'+mid));
			$('#'+mid).show();
			
		}
		else if(mid == activeB){
			if(consoleLog) console.log ("activating" + mid);
			$("#flipHtml" + (active-2)).append($('#'+mid));
			$('#'+mid).show();
			//$('#mp3').show();
		}
		else{
			$('#'+mid).hide();
		}
	});
	
}