bgSuffix = '.png'

jQuery.fn.log = function (msg) {
     console.log("%s: %o", msg, this);
     return this;
};

$.extend({'autoplayer': {
	'delay': 5000,
	'on': true,
	'looping': false,
	'loadQueue': [],
	'imageQueue': [],
	'runQueue': function() {
		next = $.autoplayer.loadQueue.shift();
		if (next) {
			next();
		}
		window.setTimeout($.autoplayer.runQueue, 100);
	},
	'loadPage': function(img, page) {
		if ($(img).attr("actual") != undefined) {
			$.autoplayer.loadQueue.push(function() {
				newImg = new Image();
				newImg.src = $(img).attr("actual");
				$.autoplayer.imageQueue.push({
					"img": newImg,
					"page": page
				});
				$(newImg).imagesLoaded(function() {
					$(img).attr("src", $(this).attr("src"));
					$(img).removeAttr("actual");
				});
			});
		}
	},
	'bookletPreload': function(currPage) {
		// load next 4 pages
		for (i=-1; i<3; i++) {
			$.autoplayer.loadPage($('.b-page-'+(currPage+i)).find('img'), currPage+i+1);
		}
		$.autoplayer.currPage = currPage;
	},
	// 1-based
	'currPage': 1,
	'currPageImgsSelector': function() {
		currPage = $.autoplayer.currPage;
		return '.b-page-'+(currPage-1)+",.b-page-"+currPage;
	},
	'goto': function(node) {
		var section = $(node).attr("section");
        $('#pages').booklet(parseInt($(node).attr("pagenum")));
		if ($(node).attr("pause") == "true") {
			$.autoplayer.pause();
		}
		else
		{
			$.autoplayer.play();
		}
	},
	'next': function() {
		if (location.hash in $.autoplayer.hash_nav) {
			$.autoplayer.hash_nav[location.hash]();
		} else {
			// hash_nav not a clean interface
			$('#pages').booklet('next');
		}
	},
	'prev': function() {
		if (location.hash in $.autoplayer.hash_nav_reverse) {
			$.autoplayer.hash_nav_reverse[location.hash]();
		} else {
			// hash_nav not a clean interface
			$('#pages').booklet('prev');
		}
	},
	'currPageLoaded': function() {
		return $($.autoplayer.currPageImgsSelector()).find("[actual]").size() == 0;
	},
	'loopId': undefined,
	'loop': function() {
		$.autoplayer.looping = true;
		$.autoplayer.loopId = window.setTimeout(function() {
			if ($.autoplayer.on) {
				if ($.autoplayer.currPageLoaded()) {
					$.autoplayer.next();
				}
			}
			$.autoplayer.loop();
		}, $.autoplayer.delay);
	},
	'play': function() {
		$.autoplayer.pause();
		$.autoplayer.on = true;
		// looks dangerous, but no race condition since js for a window executes serially
		if (!$.autoplayer.looping) {
			$.autoplayer.loop();
		}
	},
	'pause': function() {
		window.clearTimeout($.autoplayer.loopId);
		$.autoplayer.looping = false;
		$.autoplayer.on = false;
	},
	'hash_nav': {},
	'hash_nav_reverse': {}
}});
	
booklet_left = function () {
	return $('td img[src*="left'+bgSuffix+'"]').parent().offset().left;
};

booklet_top = function () {
	return $('td img[src*="left'+bgSuffix+'"]').parent().offset().top;
};

booklet_width = function () {
	return parseInt($('td img[src*="left'+bgSuffix+'"]').attr("width")) + parseInt($('td img[src*="right'+bgSuffix+'"]').attr("width"));
};

booklet_height = function() {
	return parseInt($('td img[src*="left'+bgSuffix+'"]').attr("height"));
};

center_booklet = function() {
	$('#pages').css("position","absolute");
	$('#pages').css("left", booklet_left());
	$('#pages').css("top", booklet_top());
};

dimRatio = function () {
    var h = $(window).height();
    var w = $(window).width();
    var albumH = $('table').height();
    var albumW = $('table').width();
    var adjH = w/albumW * albumH;
    var adjW = h/albumH * albumW;
    var newH = albumH;
    var newW = albumW;
    if (adjH > albumH && adjH <= h)
    {
    	newH = adjH;
    	newW = w;
    }
    else if (adjW < w)
    {
    	newH = h;
    	newW = adjW;
    }
	dim = {'h':newH/albumH,'w':newW/albumW};
    $.autoplayer.dim = dim;
	resizeFrame();
}

function resizeFrame() 
{
    var dim = $.autoplayer.dim;

    $("table").each(function (i,e)
	{
		$(e).height(dim.h*$(e).height());
		$(e).width(dim.w*$(e).width());		
	});
    $("table img").each(function (i,e)
	{
		$(e).height(dim.h*$(e).height());
		$(e).width(dim.w*$(e).width());		
	});
}

resizeImage = function (img) {
	$(img).height(booklet_height());
	$(img).width(booklet_width());
}

position_popup_help = function() {
	popup_help = $("div.booklet_help");
	popup_help.css("left", booklet_left()+booklet_width()+5);
	popup_help.css("top", booklet_top());
};

resizeBackground = function() {    

        var theWindow        = $(window),
            $bg              = $("#bg"),
            aspectRatio      = $bg.width() / $bg.height();

        function resizeBg() {

                if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
                    $bg
                        .removeClass()
                        .addClass('bgheight');
                } else {
                    $bg
                        .removeClass()
                        .addClass('bgwidth');
                }

        }

        theWindow.resize(function() {
                resizeBg();
        }).trigger("resize");

};

vegasLoadBg = function() {
	$.vegas({
    		src:'images/background.jpg'
  	});
};

$(function() {
    //dimRatio();
	$.swapImage(".swapImage");
        $('#pages').booklet({
		width: booklet_width(),
		height: booklet_height(),
                pageNumbers: false,
                pagePadding: 0,
                hash: true,
                shadows: false,
		manual: false,
		overlays: false,
		before: function(opts) {
			$.autoplayer.bookletPreload(opts.curr);
		}
        });
	center_booklet();
	$(window).resize(function() {
		//location.reload();
		//dimRatio();
		center_booklet();
	});
        $('.book-link').each(function(index, element) {
                $(this).click(function(e) {
                        e.preventDefault();
			$.autoplayer.goto($(this));
                });
        });
	$('div.left').mousedown(function(e) {
		e.preventDefault();
		$.autoplayer.pause();
		$.autoplayer.prev();
	});
	$('div.right').mousedown(function(e) {
		e.preventDefault();
		$.autoplayer.pause();
		$.autoplayer.next();
	});
	$('img[src*="right_page_edge"]').mousedown(function(e) {
		e.preventDefault();
		$.autoplayer.pause();
		$.autoplayer.next();
	});
	$(document).bind("contextmenu",function(e) {
		return false; 
	});
	$.autoplayer.runQueue();
	$.autoplayer.goto($('td[section="kids"]'));
	window.setTimeout(center_booklet, 20);
/*
	$("#pages").bt({
		"trigger": 'none',
		"contentSelector": "$('div.booklet_help')",
		"width":150,
		"fill":"rgb(190,190,190)",
		"cssClass": 'help_opacity'
	});
	$("#pages").btOn();
	window.setTimeout(function() {
		$("#pages").btOff();
	}, 8000);
*/
});

