var lastWidth = undefined;
var lastHeight = undefined;

var imagediv = undefined;
var image = undefined;
var spinner = undefined;

var hotspots = undefined;
var sideHotspots = undefined;
var arcNav = undefined;

var nextImage = $('<img />');

var hotspotOpacity = '0.85'

var quality = $.cookie("imageQuality");
if(quality == null)
{
	quality = 'medium';
}


function loadComic(url)
{
	$.getJSON(url, {'format': 'json'},
			function(data)
			{
				// [{"pk": 1, "model": "comic.comic", "fields": {"date": "2009-12-30", "image": "images/comics/test-page300.tif", "arc": 1, "title": "Testing, 1, 2, 5!"}}]
				var comic = data[0];
				
				if (comicId == comic.pk)
				{
					return;
				} // end if

				comicId = comic.pk;
				comicDate = comic.fields["date"];
				comicTitle = comic.fields["title"];
				comicImage = comic.fields["image"];
				document.title = comicTitle;
				$("#comictitle").html(comicTitle);
				$("a#permalink").attr("href", "/comic/" + comicId + "/")
				loadImage();
				if(calendars)
				{
					var comicDateSplit = comicDate.split("-");
					calendars.forEach(
							function(calendar)
							{
								calendar.switchMonth(comicDateSplit[0], comicDateSplit[1]);
								calendar.updateCurrent(comicId);
							});
				}
                if(arcNav)
                {
                    arcNav.attr('selectedIndex', $("option[value=" + comic.fields["arc"] + "]", arcNav).attr('index'));
				}
			});
}

function loadImage()
{
	width = Math.round(lastWidth);
	height = Math.round(lastHeight);

	spinner.css("display", "block");
	spinner.css("opacity", "0.5");

    nextImage.load(
            function()
            {
				image.load(
						function()
						{
							spinner.fadeOut("normal");
						});
                image.attr("src", $(this).attr("src"));
            });
    nextImage.attr('src', '/tools/resize/' + width + '/' + height + '/' + comicImage + '?quality=' + quality + "&forceSize");
}

function resizeImage(width, height)
{
	lastWidth = width;
	lastHeight = height;

	width = Math.round(width);
	height = Math.round(height);

	image.stop();
	if(image.css("display") == "block")
	{
		image.animate({width: width + "px", height: height + "px"}, "slow", "swing");
	}
	else
	{
		image.css("width", width + "px");
		image.css("height", height + "px");
	}
    imagediv.stop();
    imagediv.animate({width: width + "px", height: height + "px"}, "slow", "swing",
			function()
			{
				image.css("display", "block");
			});

	loadImage();
}

function resizeToWidth(width)
{
    var height = fullHeight * (width / fullWidth);
    resizeImage(width, height);
}

function resizeToHeight(height)
{
    var width = fullWidth * (height / fullHeight);
    resizeImage(width, height);
}


function fitToWidth()
{
    var width = document.documentElement.clientWidth - 200;
	resizeToWidth(width);
}

function fitToHeight()
{
    var height = document.documentElement.clientHeight - 50;
	resizeToHeight(height);
}


function zoomIn()
{
	resizeToWidth(lastWidth * (125 / 100));
}

function zoomOut()
{
	resizeToWidth(lastWidth * (100 / 125));
}

function preloadQualityButtons()
{
	for(var qualityLevel in ["high", "medium", "low"])
	{
		var image = $('<img />');
		image.attr('src', mediaUrl + "images/" + qualityLevel + "-quality-current.png");

		if(qualityLevel == quality)
		{
			image.load(
					function()
					{
						updateQualityButtons();
					});
		}
	}
}

function updateQualityButtons()
{
	$("a#highquality, a#mediumquality, a#lowquality").each(
		function (i, domElement)
		{
			if (domElement.id == quality + "quality")
			{
				$("img", domElement).attr('src', mediaUrl + "images/" + domElement.id.replace('quality', '') + "-quality-current.png");
			}
			else
			{
				$("img", domElement).attr('src', mediaUrl + "images/" + domElement.id.replace('quality', '') + "-quality.png");
			}
		});
}

function setQuality(qual)
{
	quality = qual;

	updateQualityButtons();

	$.cookie("imageQuality", qual, {expires: 7});

	loadImage();
}

/* Generic show/hide for hotspots */
function showHotspots(hotspots, callback)
{
	hotspots.stop();
	hotspots.css("display", "block");
	hotspots.animate({marginTop: '0', marginBottom: '0', marginLeft: '0', marginRight: '0', opacity: hotspotOpacity}, "fast", callback);
}

function hideHotspots(hotspots)
{
	hotspots.stop();
	hotspots.css("opacity", hotspotOpacity);
	hotspots.animate({marginTop: '-64px', marginBottom: '-64px', marginLeft: '-64px', marginRight: '-64px', opacity: '0'}, "slow");
}

function resetHotspotCss()
{
	$(".container", hotspots).css({
			'display': 'block',
			marginTop: '-64px',
			marginBottom: '-64px',
			marginLeft: '0',
			marginRight: '0',
			opacity: '0',
			});
	$(".container", sideHotspots).css({
			marginTop: '0',
			marginBottom: '0',
			marginLeft: '-64px',
			marginRight: '-64px',
			});
}

/* Hover handlers for individual hotspots */
function showThis()
{
	showHotspots($(".container", this));
}

function hideThis()
{
	hideHotspots($(".container", this));
}

function setHoverHandlers()
{
    hotspots.bind("mouseenter", showThis);
    hotspots.bind("mouseleave", hideThis);
}

function unsetHoverHandlers()
{
    hotspots.unbind("mouseenter", showThis);
    hotspots.unbind("mouseleave", hideThis);
}

/* Show/hide all hotspots */
function hideAll()
{
	hideHotspots($(".container", hotspots));
	setHoverHandlers();
}

function showAll(animateIn)
{
	unsetHoverHandlers();

	if(animateIn)
	{
		resetHotspotCss();
		showHotspots($(".container", hotspots),
				function()
				{
					setTimeout(hideAll, 2000);
				});
	}
	else
	{
		setTimeout(hideAll, 2000);
	}
}


/* Page Load */
$(document).ready(function comicPageLoad()
{
    imagediv = $("#comic");
    image = $("#comic>img");
    spinner = $("#spinner");

    hotspots = $("div.hotspot");
    sideHotspots = $("div.hotspot.leftside, div.hotspot.rightside");
    arcNav = $("#arcnav");

    /*
	imagediv.css("width", "25%");
    imagediv.css("height", "25%");
	*/

	image.click(
			function()
			{
				showAll(true);
			});

    $("a.first").click(
			function()
			{
				loadComic("/comic/first/");
			});
    $("a.previousarc").click(
			function()
			{
				loadComic("/comic/" + comicId + "/prevarc/");
			});
    $("a.prev").click(
			function()
			{
				loadComic("/comic/" + comicId + "/prev/");
			});
    $("a.next").click(
			function()
			{
				loadComic("/comic/" + comicId + "/next/");
			});
    $("a.nextarc").click(
			function()
			{
				loadComic("/comic/" + comicId + "/nextarc/");
			});
    $("a.latest").click(
			function()
			{
				loadComic("/comic/latest/");
			});

    $("a.highquality").click(
			function()
			{
				setQuality("high");
			});
    $("a.mediumquality").click(
			function()
			{
				setQuality("medium");
			});
    $("a.lowquality").click(
			function()
			{
				setQuality("low");
			});

	updateQualityButtons();

    $("a#zoomin").click(zoomIn);
    $("a#zoomout").click(zoomOut);

    $("a#fullwidth").click(fitToWidth);
    $("a#fullheight").click(fitToHeight);

    /*$("#manualnav").css("display", "none");*/

    /*hotspots.css("display", "block");*/

	showAll(false);

	image.css("display", "none");
	resizeToWidth(640);
    /*fitToHeight();*/
});


