/****************************************
   $Id$
   $Change$
   $DateTime$
   $Author$
 ***************************************/
var flippingBook;
var bodyStyle;

if (document.documentElement)
   bodyStyle = document.documentElement.style;
else if (document.body)
   bodyStyle = document.body.style;

bodyStyle.visibility = "hidden";

function InitFlippingBook(initializationHandler) {
   flippingBook = new FlippingBook(initializationHandler);
   flippingBook.create();
}

function FlippingBook(initializationHandler) {
   if (!initializationHandler)
      throw new Error("No initialization handler specified.");

   this.pages = [];
   this.zoomPages = [];
   this.printPages = [];
   this.contents = [];

   this.stageWidth = "100px";
   this.stageHeight = "100px";

   this.settings = {
      bookWidth: 640,
      bookHeight: 480,
      pagesSet: this.pages,
      zoomPagesSet: this.zoomPages,
      printPagesSet: this.printPages,
      scaleContent: true,
      preserveProportions: false,
      centerContent: true,
      hardcover: false,
      hardcoverThickness: 3,
      hardcoverEdgeColor: 0xFFFFFF,
      highlightHardcover: true,
      frameWidth: 0,
      frameColor: 0xFFFFFF,
      frameAlpha: 100,
      firstPageNumber: 1,
      autoFlipSize: 50,
      navigationFlipOffset: 30,
      flipOnClick: true,
      handOverCorner: true,
      handOverPage: true,
      alwaysOpened: false,
      staticShadowsType: "Asymmetric", // Asymmetric, Symmetric, Default
      staticShadowsDepth: 1,
      staticShadowsLightColor: 0xFFFFFF, // works for "Symmetric" shadows only
      staticShadowsDarkColor: 0x000000,
      dynamicShadowsDepth: 1,
      dynamicShadowsLightColor: 0xFFFFFF, // works for "dark" pages only
      dynamicShadowsDarkColor: 0x000000,
      moveSpeed: 2,
      closeSpeed: 3,
      gotoSpeed: 3,
      rigidPageSpeed: 5,
      flipSound: "",
      hardcoverSound: "",
      preloaderType: "Thin", // "Progress Bar", "Round", "Thin", "Dots", "Gradient Wheel", "Gear Wheel", "Line", "Animated Book", "None"
      pageBackgroundColor: 0x99CCFF,
      loadOnDemand: true,
      allowPagesUnload: true,
      showUnderlyingPages: false,
      playOnDemand: true,
      freezeOnFlip: false,
      darkPages: false,
      smoothPages: false,
      rigidPages: false,
      flipCornerStyle: "manually", // "first page only", "each page", "manually"
      flipCornerPosition: "bottom-right", // "bottom-right","top-right","bottom-left","top-left"
      flipCornerAmount: 50,
      flipCornerAngle: 20,
      flipCornerRelease: true,
      flipCornerVibrate: true,
      flipCornerPlaySound: false,
      zoomEnabled: true,
      zoomPath: "pages/large/",
      zoomImageWidth: 900,
      zoomImageHeight: 1165,
      zoomOnClick: true,
      zoomUIColor: 0x8f9ea6,
      zoomHint: "Double click to zoom.",
      zoomHintEnabled: false,
      centerBook: true,
      useCustomCursors: true,
      dropShadowEnabled: true,
      dropShadowHideWhenFlipping: true,
      backgroundColor: 0xFFFFFF,
      backgroundImage: "img/bookBackground.jpg",
      backgroundImagePlacement: "fit", //  "top left", "center", "fit"
      printEnabled: true,
      printTitle: "Print Pages",
      downloadURL: "",
      downloadTitle: "Download PDF",
      downloadSize: "<NOT SET>",
      downloadComplete: "Complete",
      extXML: "",
      /*Added 5/15/2009 mpf */
      useContainerDimensions: false,
      useCssStyles: false
   };

   this.containerId = "fbContainer";
   this.forwardButtonId = "fbForwardButton";
   this.backButtonId = "fbBackButton";
   this.gotoPageId = "fbGotoPage";
   this.zoomButtonId = "fbZoomButton";
   this.printButtonId = "fbPrintButton";
   this.downloadButtonId = "fbDownloadButton";
   this.currentPagesId = "fbCurrentPages";
   this.totalPagesId = "fbTotalPages";
   this.footerId = "fbFooter";
   this.contentsMenuId = "fbContentsMenu";

   this.sidebar = new Sidebar(this);

   /*Added 5/01/2009 mpf */
   if (initializationHandler)
      initializationHandler(this);

   this.sidebar.create();
}

FlippingBook.prototype.create = function() {
   this.settings.pagesSet = this.pages;
   this.settings.zoomPagesSet = this.zoomPages;
   this.settings.printPagesSet = this.printPages;

   if (location.hash.substr(1) != "")
      this.settings.firstPageNumber = location.hash.substr(1);

   swfobject.embedSWF(this.swfFlippingBook, this.containerId, this.stageWidth, this.stageWidth, "8.0.0", this.swfExpressInstall, this.settings, { WMode: "Transparent", allowScriptAccess: "always", bgcolor: "#" + this.settings.backgroundColor.toString(16) });
   this.addLoadEvent(this.onWindowLoad);
   addEvent(window, "resize", sizeContent);
};

FlippingBook.prototype.resize = function() {
   if (bodyStyle)
      bodyStyle.visibility = "hidden";

   if (this.sidebar)
      this.sidebar.redraw();

   var container = this.getObjectReference(this.containerId);
   var footer = this.getObjectReference(this.footerId);

   container.style.position = "absolute";
   container.style.top = footer.offsetHeight + "px";
   var contentHeight = this.getContentHeight();
   var contentWidth = getWindowWidth() - (this.sidebar ? this.sidebar.settings.tabWidth : 0);
   container.style.height = (contentHeight > 0 ? contentHeight : 0) + "px";
   container.style.width = (contentWidth > 0 ? contentWidth : 0) + "px";

   if (bodyStyle)
      bodyStyle.visibility = "visible";
};

function sizeContent() {
   flippingBook.resize();
}

FlippingBook.prototype.useCssStyles = false;

FlippingBook.prototype.getFlippingBookReference = function() {
	return this.getObjectReference( this.containerId );
};

FlippingBook.prototype.getObjectReference = function( id ) {
	return document.getElementById( id );
};

FlippingBook.prototype.flipForward = function() {
	flippingBook.getFlippingBookReference().flipForward();
};

FlippingBook.prototype.gotoPageChanged = function(evt) {
   return (true);
	//flippingBook.getFlippingBookReference().flipGotoPage(pageNum);
};

FlippingBook.prototype.gotoPageKeyPress = function(evt) {
   var keyCode = evt ? (evt.charCode > 0 ? evt.charCode : evt.keyCode ) : event.keyCode;
   if (keyCode == 13) {
      if (evt)
         evt.cancelBubble = true;
      else
         event.cancelBubble = true;
         
      var gotoPage = flippingBook.getObjectReference(flippingBook.gotoPageId);
      
      try
      {
         var val = parseInt(gotoPage.value, 10);
         flippingBook.getFlippingBookReference().flipGotoPage(val);
      }
      catch (e) {}
      
      var currentPages = flippingBook.getObjectReference(flippingBook.currentPagesId);
      
      if (currentPages)
      {
         gotoPage.style.display = "none";
         currentPages.style.display = "";
      }
      return (false);
	}
	else if (keyCode < 48 || keyCode > 57)
	   return (false);
};

FlippingBook.prototype.flipBack = function() {
	flippingBook.getFlippingBookReference().flipBack();
};

FlippingBook.prototype.zoomButtonClick = function() {
	if( flippingBook.getFlippingBookReference().isZoomedIn() )
		flippingBook.zoomOut();
	else
		flippingBook.zoomIn();
};

FlippingBook.prototype.zoomIn = function() {
	this.getFlippingBookReference().zoomIn();
};

FlippingBook.prototype.zoomOut = function() {
	this.getFlippingBookReference().zoomOut();
};

FlippingBook.prototype.print = function() {	
	flippingBook.getFlippingBookReference().print();
};

FlippingBook.prototype.downloadFile = function() {	
	if( flippingBook.settings.downloadURL )
		flippingBook.getFlippingBookReference().downloadFile();
};

FlippingBook.prototype.onWindowLoad = function() {
   var forwardButton = flippingBook.getObjectReference(flippingBook.forwardButtonId);
   if (forwardButton) {
      forwardButton.style.cursor = "pointer";
      forwardButton.onclick = flippingBook.flipForward;
   }

   var backButton = flippingBook.getObjectReference(flippingBook.backButtonId);
   if (backButton) {
      backButton.style.cursor = "pointer";
      backButton.onclick = flippingBook.flipBack;
   }

   var gotoPage = flippingBook.getObjectReference(flippingBook.gotoPageId);
   if (gotoPage) {
      gotoPage.onkeypress = flippingBook.gotoPageKeyPress;
      var currentPages = flippingBook.getObjectReference(flippingBook.currentPagesId);
      if (currentPages) {
         currentPages.style.cursor = "pointer";
         currentPages.onclick = function() {
            var currentPages = flippingBook.getObjectReference(flippingBook.currentPagesId);
            var gotoPage = flippingBook.getObjectReference(flippingBook.gotoPageId);
            currentPages.style.display = "none";
            gotoPage.style.display = "";
            gotoPage.focus();
         };
         gotoPage.onblur = function() {
            var currentPages = flippingBook.getObjectReference(flippingBook.currentPagesId);
            var gotoPage = flippingBook.getObjectReference(flippingBook.gotoPageId);
            currentPages.style.display = "";
            gotoPage.style.display = "none";
         };
      }
   }

   var zoomButton = flippingBook.getObjectReference(flippingBook.zoomButtonId);
   if (zoomButton) {
      zoomButton.style.cursor = "pointer";
      zoomButton.onclick = flippingBook.zoomButtonClick;
   }

   var printButton = flippingBook.getObjectReference(flippingBook.printButtonId);
   if (printButton) {
      printButton.style.cursor = "pointer";
      printButton.onclick = flippingBook.print;
   }

   var downloadButton = flippingBook.getObjectReference(flippingBook.downloadButtonId);
   if (downloadButton) {
      downloadButton.style.cursor = "pointer";
      downloadButton.onclick = flippingBook.downloadFile;
   }

   flippingBook.buildContentsMenu();
   flippingBook.resize();
};

/* Added 4/28/2009 mpf */
FlippingBook.prototype.OnFlipPage = null;
/* Modified 4/28/2009 mpf */
FlippingBook.prototype.onPutPage = function( leftPageNumber, rightPageNumber )
{
	if (this.OnFlipPage != null)
	{
	   if (this.OnFlipPage(leftPageNumber, rightPageNumber))
	      return;
	}
	this.updatePagination( leftPageNumber, rightPageNumber );
	this.updateContentsMenu(leftPageNumber, rightPageNumber);
	this.updateThumbnailIndex(leftPageNumber, rightPageNumber);
};
FlippingBook.prototype.updateThumbnailIndex = function(leftPageNumber, rightPageNumber) {
   var thumbnailIndex = document.getElementById("fbThumbnailIndex");
   if (!thumbnailIndex)
      return;
   var leftPageExists = (leftPageNumber != undefined);
   var rightPageExists = (rightPageNumber != undefined);
   var images = thumbnailIndex.getElementsByTagName("img");
   for (var i = 0; i < images.length; i++) {
      var image = images[i];
      var pageNumber = image.getAttribute("pageNumber");
      if (pageNumber == undefined)
         continue;
      if ((leftPageExists && pageNumber == leftPageNumber) ||
          (rightPageExists && pageNumber == rightPageNumber)) {
         image.style.borderColor = 'Red';
         image.style.borderStyle = 'solid';
         image.style.borderWidth = '2px';
      }
      else {
         image.style.borderColor = '';
         image.style.borderStyle = '';
         image.style.borderWidth = '';
      }
   }
}
/* Modified 4/28/2009 mpf */
FlippingBook.prototype.updatePagination = function( leftPageNumber, rightPageNumber ){
   var oCurrentPage = this.getObjectReference( flippingBook.currentPagesId );
   var oGotoPage = this.getFlippingBookReference(flippingBook.gotoPageId);
   var oTotalPages = this.getObjectReference( flippingBook.totalPagesId );
   if (!oCurrentPage && !oTotalPages)
      return;
	var validLeftPage = ( leftPageNumber != undefined );
	var validRightPage = ( rightPageNumber != undefined );
	var pageNumberString = leftPageNumber + "-" + rightPageNumber;
	if( !validLeftPage )
		pageNumberString = rightPageNumber;	
	if( !validRightPage )
		pageNumberString = leftPageNumber;
   if (oCurrentPage)
      oCurrentPage.innerHTML = pageNumberString;
   if (oGotoPage)
   {
      var pageNum = (validLeftPage) ? leftPageNumber : rightPageNumber;
      oGotoPage.value = parseInt(pageNum, 10);
      oGotoPage.defaultValue = pageNum;
   }
   if (oTotalPages)
      oTotalPages.innerHTML = " / " + this.getFlippingBookReference().totalPages();	
};

FlippingBook.prototype.buildContentsMenu = function(){
	var contentsSelect = this.getObjectReference( this.contentsMenuId );
	
	if( contentsSelect ){
		for( var i = 0; i < this.contents.length; i++ )
			contentsSelect.options[i] = new Option(this.contents[i][0], this.contents[i][1]);
			
		contentsSelect.onchange = this.onContentsChange;
	}
};

FlippingBook.prototype.onContentsChange = function(){
	var contentsSelect = flippingBook.getObjectReference( flippingBook.contentsMenuId );
	var pageNumber = contentsSelect.options[contentsSelect.selectedIndex].value;
	
	if( pageNumber )
		flippingBook.getFlippingBookReference().flipGotoPage( pageNumber );
};

FlippingBook.prototype.updateContentsMenu = function( leftPageNumber, rightPageNumber ){
	var contentsSelect = flippingBook.getObjectReference( flippingBook.contentsMenuId );

	if( contentsSelect ){
		for( var i = 0; i < this.contents.length - 1; i++ ){
			var minPage = contentsSelect.options[i].value;
			var maxPage = contentsSelect.options[i+1].value;
			var leftOK = false;
			var rightOK = false;
			
			if( leftPageNumber )
				leftOK = ( Number( leftPageNumber ) >=  minPage && Number( leftPageNumber ) <= maxPage );
			else
				leftOK = true;

			if( rightPageNumber )
				rightOK = ( Number( rightPageNumber ) >=  minPage && Number( rightPageNumber ) <= maxPage );
			else
				rightOK = true;
				
			if( leftOK && rightOK )	
				break;
		}	
		contentsSelect.selectedIndex = i;
	}
};

FlippingBook.prototype.getWindowHeight = function() {
	var windowHeight = 0;
	
	if (typeof(window.innerHeight) == 'number' ) {
		windowHeight=window.innerHeight;
	}
	else {
		if (document.documentElement &&	document.documentElement.clientHeight) {
				windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body&&document.body.clientHeight) {
				windowHeight=document.body.clientHeight;
			}
		}
	}
	
	return windowHeight;
};
FlippingBook.prototype.getContentHeight = function() {
   var footer = this.getObjectReference(this.footerId);
   var container = this.getObjectReference(this.containerId);
   return (this.getWindowHeight() - footer.offsetHeight);
}

FlippingBook.prototype.addLoadEvent = function ( fn ) {
	if (typeof window.addEventListener != "undefined") {
		window.addEventListener("load", fn, false);
	}
	else if (typeof document.addEventListener != "undefined") {
		document.addEventListener("load", fn, false);
	}
	else if (typeof window.attachEvent != "undefined") {
		window.attachEvent("onload", fn);
	}
	else if (typeof window.onload == "function") {
		var fnOld = window.onload;
		window.onload = function() {
			fnOld();
			fn();
		};
	}
	else {
		window.onload = fn;
	}
};

FlippingBook.prototype.handleWheel = function ( delta ){
	this.getFlippingBookReference().onWheelScroll( delta );
};

function wheel(event){
	var delta = 0;
	if (!event) event = window.event;
	if (event.wheelDelta) {
		delta = event.wheelDelta/120; 
		if (window.opera) delta = -delta;
	} else if (event.detail) {
		delta = -event.detail/3;
	}
	if (delta)
		flippingBook.handleWheel(delta);
        if (event.preventDefault)
                event.preventDefault();
        event.returnValue = false;
}

if (window.addEventListener)
	window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;

function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj.attachEvent( "on"+type, function() { obj["e"+type+fn](); } );
	}
}

function getWindowHeight() {
	var windowHeight=0;
	if ( typeof( window.innerHeight ) == 'number' ) {
		windowHeight=window.innerHeight;
	}
	else {
		if ( document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body&&document.body.clientHeight) {
				windowHeight=document.body.clientHeight;
			}
		}
	}
	
	return windowHeight;
}

function getWindowWidth() {
	var ww = 0;
	if (self.innerWidth)
		ww = self.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth)
		ww = document.documentElement.clientWidth;
	else if (document.body)
		ww = document.body.clientWidth;
	return ww;
}

