//Change this to your localhost for dev and debugging according to your need, remember to include http://
var host_domain = 'http://' + window.location.hostname;

//Please use jQuery instead of $ here for maximum compatibility since this file will also
//be used by the WGB widget

jQuery(function(){
	
	function getScrollTop() {
		var scrollTop = 0;
		
		if (window.pageYOffset) {
			scrollTop = window.pageYOffset;
		} else if (document.documentElement) {
			scrollTop = document.documentElement.scrollTop;
		} else if (document.body) {
			scrollTop = document.body.scrollTop;
		}
		
		return scrollTop;
	}

	//Caching selector for performance
	var readerOverlay = jQuery("#issuu-reader-overlay");
	var readerBackgroundOverlay = jQuery("#issuu-reader-background-overlay");
	var readerIframe = jQuery("#issuu-reader-iframe");
	var browserWindow = jQuery(window);
	
	
	//Read This Book is clicked
	jQuery(".read_book").live('click', function(event){
		event.preventDefault();
		//The rel attribute consists of book id
		
		var bookId = $(this).attr("rel");
		
		readerIframe.attr("src", host_domain +  "/reader/" + bookId);
		
		readerOverlay.css({
			"width" : browserWindow.width()-38, 
			"height" : browserWindow.height()-35, 
			"top" : getScrollTop()
		})
		
		setTimeout(function() {
			readerOverlay.css("left", browserWindow.width()/2 - readerOverlay.outerWidth()/2);
			jQuery("#issuu-viewer").attr("height", browserWindow.height()-142);
			readerOverlay.fadeIn(200);
		}, 200);
	
		readerBackgroundOverlay.show();
		
		//Make sure that the black overlay behind the reader covers the entire browser viewport in IE6
		if (jQuery.browser.msie && jQuery.browser.version == "6.0") {
			readerBackgroundOverlay.css({width:browserWindow.width(), height:jQuery(document).height()});
		}
	})
	
	//Resize the reader overlay when the window is resized, and move the reader along as user scrolls the scrollbar
	browserWindow.resize(function(){
		if (browserWindow.width() >= 1024) {
			readerOverlay.css({
				"width" : browserWindow.width()-38, 
				"height" : browserWindow.height()-35
			})
			.css("left", browserWindow.width()/2 - readerOverlay.outerWidth()/2);
		}
	}).scroll(function(){
		readerOverlay.css("top", getScrollTop());
	})
	
	//Close reader by clicking on the (X) button
	jQuery("#close-reader").click(function(){
		readerOverlay.hide();
		readerBackgroundOverlay.hide();
		//Reset the iframe so that the next time the book load, the iframe won't flickr with the previous book read
		//(this only happens if a person read a book, closes, read again)
		readerIframe.attr("src", "");
	})

})
