function detectMobile() {
    var agent = navigator.userAgent.toLowerCase(); 

    if(agent.search("iphone") > -1 ||
       agent.search("ipad") > -1 ||
       agent.search("ipod") > -1 ||
       agent.search("android") > -1)
	return true;

    return false;
}

function loadMain() {
    setSizes();

    if(!detectMobile()) {
	window.onresize = function() { resizePage(); };
    }

    var winWidth = $(window).width();
    var winHeight = $(window).height();
    var mainCanvas = document.getElementById("mainCanvas");
    var mainContext = mainCanvas.getContext("2d");
    
    // Display "cutflat" centre of screen while bg image loads
    mainContext.font = "bold 90px arial";
    mainContext.fillStyle="#999";
    mainContext.textAlign="center";
    mainContext.fillText("cutflat", winWidth/2, winHeight/2);
   
    // Set up main background image
    var bgImg = new Image();
    bgImg.src = backgroundImageSrc;

    bgImg.onload = function() {
	setTimeout(function() { 
	    $(".blocker").show();
	    drawBGImage(bgImg);
	    $(".blocker").fadeOut(1500);
	    $("#mainMenu").delay(1600).fadeIn(500);
	}, 500);
    };
}

function setSizes() {
    var winWidth = $(window).width();
    var winHeight = $(window).height();
    var mainCanvas = document.getElementById("mainCanvas");
    mainCanvas.width = winWidth;
    mainCanvas.height = winHeight;
    $(".blocker").width(winWidth);
    $(".blocker").height(winHeight);
}

var timeoutID = 0;

function resizePage() {
    setSizes();
    img = new Image();
    img.src = backgroundImageSrc;
    drawBGImage(img);
    
    if($("#photoPane").css("display") != "none") {
	$("#thumbPane").hide();
	
	clearTimeout(timeoutID);
	timeoutID = setTimeout(function() { reloadPhotoPage(); }, 500);
    }
}

function reloadPhotoPage() {
    $("#thumbPane").fadeIn(200);
    positionThumbPane();
    showPhoto(currentCollection, currentPhoto);
}

function drawBGImage(bgImg) {
    var winWidth = $(window).width();
    var winHeight = $(window).height();
    var imgHeight = bgImg.height;
    var imgWidth = bgImg.width;

    var mainCanvas = document.getElementById("mainCanvas");
    var mainContext = mainCanvas.getContext("2d");
    
    imgAspect = imgWidth / imgHeight;
    winAspect = winWidth / winHeight;
    
    var x = 0;
    var y = 0;
    var overrun = 0;
    
    if(imgAspect > winAspect) {
	imgHeight = winHeight;
	imgWidth = imgHeight*imgAspect;
	overrun = imgWidth - winWidth;
	x = 0 - (overrun/2);
    } else {
        imgWidth = winWidth;
	imgHeight = imgWidth/imgAspect;
	overrun = imgHeight - winHeight;
	y = 0 - (overrun/2);
    }	

    mainContext.drawImage(bgImg, x, y, imgWidth, imgHeight);
}

// Show the collections menu next to div.menu
function showPane(paneId) {
    closeAll();
    var left = parseFloat($("#mainMenu").css("left"), 10) + 
	$("#mainMenu").outerWidth() + 10 +'px';
    $(paneId).css("left", left);
    $(paneId).fadeIn(500);
}

// Close all sub-menus
function closeAll() {
    $(".subMenu").fadeOut(500);
}

function showCollection(coll) {
    // Fade in blocker to hide background image, and fade out menus
    $(".blocker").fadeIn(500);
    closeAll();
    $(".mainMenu").fadeOut(500);

    // Create thumbnail pane
    var thumbHTML = "<li style='padding-left:5px'>";
    var img;

    for(i = 0; i < collectionFiles[coll].length; i++) {
	img = new Image();
	img.src = collectionPrefix + coll + thumbPrefix + collectionFiles[coll][i][0];

	if(i > 0) 
	    thumbHTML = thumbHTML + "<li>";
	thumbHTML = thumbHTML + 
	    "<a href='javascript:showPhoto(\"" + coll + "\"," + i + ")' class='thumbA'>" +
	    "<img src=" + img.src + " class='thumb'></a></li>";
    }

    $("#slidingThumbs").html(thumbHTML)
    positionThumbPane();
    $("#thumbPane").fadeIn(500);

    // Show pane and photo
    $('#photoPane').fadeIn(500);
    showPhoto(coll, 0);

    $("#thumbLinkDiv").delay(1500).effect("highlight", 500);

    // Set up key bindings
    $(document).bind('keyup', 'right', function() { nextPhoto(); });
    $(document).bind('keyup', 'left', function() { prevPhoto(); });
    $(document).bind('keyup', 'esc', function() { hideCollections(); });
}

function positionThumbPane() {
    $("#thumbLinkDiv").html("<a href='javascript:showThumbs()' class='thumbLink'>THUMBNAILS</a>");
    $("#thumbPane").css("top", $(window).height() - 
			parseFloat($("#thumbLinkDiv").css("height")) -
			parseFloat($("#thumbLinkDiv").css("padding-top")) - 
			parseFloat($("#thumbLinkDiv").css("padding-bottom")) + "px");
}

function hideCollections() {
    $(document).unbind();

    hideThumbs();
    $("#photoPane").fadeOut(500);
    $("#thumbPane").fadeOut(500);
    $(".blocker").delay(500).fadeOut(500);
    $(".mainMenu").delay(1000).fadeIn(1000);
    $("#collectionsMenu").delay(1000).fadeIn(1000);
}

function showPhoto(collection, n) {
    currentPhoto = n;
    currentCollection = collection;
    img = new Image();
    img.src = collectionPrefix+collection+"/"+collectionFiles[collection][n][0];
    var caption = "";
    if(collectionFiles[collection][n].length == 2 &&
       $(window).width() > 500) {
	caption = " - " + collectionFiles[collection][n][1];
    }

    $("#photoCanvas").hide();
    $("#photoNav").hide();
    $("#prevLink").show();
    $("#nextLink").show();
    $("#loadingDiv").show();
    
    // Hide prev/next links if at start/end
    if(currentPhoto == 0)
	$("#prevLink").hide();
    else if(currentPhoto == collectionFiles[collection].length - 1)
	$("#nextLink").hide();
    
    $("#photoCaption").text(collectionNames[collection] + " " + eval(n+1) + "/"
			    + collectionFiles[collection].length + caption);

    img.onload = function() {
	// Immediately start to load the next two images when this one is loaded
	if(currentPhoto+1 < collectionFiles[collection].length) {
	    next = new Image();
	    next.src = collectionPrefix+collection+"/"+
		collectionFiles[collection][n+1][0];
	}

	var aspect = img.width / img.height;
	var borderAmt = 0.05;
	var w;
	var h;
	var border;

	var availHeight = parseFloat($("#thumbPane").css("top")) - 
	    $("#photoNav").outerHeight() - 
	    $("#thumbLinkDiv").outerHeight();

	var winAspect = $(window).width() / availHeight;
	
	if(aspect > winAspect) { 
	    // Try to leave 5% width on each side of photo
	    border = $(window).width() * borderAmt;
	    w = $(window).width() - (2*border);
	    h = w / aspect;
	} else { 
	    // Try to leave 5% height above and below photo
	    border = $(window).height() * borderAmt;
	    h =  availHeight - (2*border);
	    w = h * aspect;
	}

	// Don't scale larger than real image size
	if(w > img.width)
	    w = img.width;
	if(h > img.height)
	    h = img.height;

	var canvas = document.getElementById("photoCanvas");
	var context = canvas.getContext("2d");
	var wait = 0;

	if(w != canvas.width || h != canvas.height ||
	   x != parseFloat($("photoPane").css("left")) ||
	   y != parseFloat($("photoPane").css("top"))) {
	    var wPadding = parseFloat($("#photoPane").css("padding-left")) + 
		parseFloat($("#photoPane").css("padding-right"));
	    var hPadding = parseFloat($("#photoPane").css("padding-top")) + 
		parseFloat($("#photoPane").css("padding-bottom"));
	    var navPadding = $("#photoNav").outerHeight();

	    // Center image on screen
	    x = ($(window).width() - w - wPadding) / 2;
	    y = (parseFloat($("#thumbPane").css("top")) - h - 
		 navPadding - hPadding) / 2;

	    $("#photoPane").animate({
		left: x, 
		top: y,
		width: w,
		height: h + navPadding
	    }, 300, function() { 
		context.drawImage(img, 0, 0, w, h);
		$("#photoCanvas").fadeIn(200);
		$("#photoNav").delay(100).fadeIn(200);
	    });
	    wait = 300;
	    
	    canvas.width = w;
	    canvas.height = h;
	} else {
	    context.drawImage(img, 0, 0, w, h);
	    $("#photoCanvas").fadeIn(200);
	    $("#photoNav").delay(wait + 1).fadeIn(200);
	}
	$("#loadingDiv").hide();
    }
}

function nextPhoto() {
    if(currentPhoto+1 < collectionFiles[currentCollection].length)
	showPhoto(currentCollection, currentPhoto+1);
}

function prevPhoto() {
    if(currentPhoto-1 >= 0)
	showPhoto(currentCollection, currentPhoto-1);
}

function showThumbs() {
    setupScrollbar();
    $("#thumbPane").animate({
	top: $(window).height() - $("#thumbPane").outerHeight()
    }, 100);
    $("#thumbLinkDiv").html("<a href='javascript:hideThumbs()' class='thumbLink'>X</a>");

    setTimeout(function() {
	recentrePhoto();

	if((parseFloat($("#photoPane").css("top")) + $("#photoPane").outerHeight()) > 
	   parseFloat($("#thumbPane").css("top"))) {
	    showPhoto(currentCollection, currentPhoto);
	}
    }, 110);
}

function recentrePhoto() {
    var newTop = (parseFloat($("#thumbPane").css("top")) - 
		  $("#photoPane").outerHeight()) / 2;
    var newLeft = ($(window).width() - $("#photoPane").outerWidth()) / 2;

    $("#photoPane").animate({
	top: newTop,
	left: newLeft
    }, 100);
}

function hideThumbs() {
    $("#thumbPane").animate({
	top: $(window).height() - $("#thumbLinkDiv").outerHeight()
    }, 100);
    $("#thumbLinkDiv").html("<a href='javascript:showThumbs()' class='thumbLink'>THUMBNAILS</a>");
    setTimeout(function() { recentrePhoto(); }, 101);
}

function setupScrollbar() {
    $("#slidingThumbs").css("left", 0);
    $("#handle").css("left", 0);

    if($(window).width() < parseFloat($('#slidingThumbs').innerWidth())) {
	$("#sliderDiv").show();
	// $("#slider").css("top", parseFloat($("#slidingThumbs").css("height")));
	$("#sliderDiv").css("width", $(window).width() - 
			    parseFloat($(".handle").css("width")));
	
	var width = $('#slidingThumbs').innerWidth() - $(window).width();
	
	var slider = $('#sliderDiv').slider({ 
	    min: 0,
	    max: width,
	    slide: function (ev, ui) {
		$("#slidingThumbs").css('left', '-' + ui.value + 'px');
	    }, 
	});
    } else {
	$("#sliderDiv").hide();
    }
}
