﻿var currentList = null;
var imageTimeout = null;
var SLIDE_DELAY = 2000;

$(document).ready(function () {

    $("#work li").each(function () {

        $(this)
                    .css("top", -$(this).prevAll().length * $(this).parent().parent().height())
                    .css("left", $(this).prevAll().length * $(this).parent().parent().width());
    });



    $("#work article").hover(function () {
        $(this).addClass("hoverState").find("h1").css("opacity", 0).css("display", "block").animate({ opacity: 0.75 });
        if ($(this).find("ul").queue().length == 0) {
            currentList = $(this).find("ul")[0];
            imageTimeout = setTimeout(swapImages, 500);
        }
    }, function () {
        $(this).removeClass("hoverState").find("h1").animate({ opacity: 0 });
        clearTimeout(imageTimeout);
        imageTimeout = null;
        currentList = null;
    });

    $.getJSON("http://www.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&user_id=43961645@N04&per_page=10&extras=url_sq&format=json&api_key=926370ae6b34f28c639cbb3c1e9b2148&jsoncallback=?"
        , jsonFlickrApi);

});

function jsonFlickrApi(rsp){

	if (rsp.stat != "ok"){

		// something broke!
		return;
	}

	for (var i = 0; i < rsp.photos.photo.length; i++){

		var photo = rsp.photos.photo[i];

		var img = $("<img/>").attr("src", photo.url_sq).attr("alt", photo.title);
		var a = $("<a/>").attr("href", "http://www.flickr.com/photos/iandroutledge/" + photo.id + "/").append(img);
		var li = $("<li/>").attr("title", photo.title).append(a);

        $("#flickrPhotos").append(li);
	}
}

function swapImages() {

    if (currentList != null) {

        var ul = $(currentList);

        var width = ul.parent().width();

        if (Math.round(ul.position().left / width) <= 1 - ul.children().length) {
            ul.animate({ left: 0 }, 600, 'easeInOutQuart', function () { imageTimeout = setTimeout(swapImages, SLIDE_DELAY); });
        }
        else {
            ul.animate({ left: ul.position().left - width }
                        , 600
                        , 'easeInOutQuart'
                        , function () {
                            var oP = $(this).position().left;
                            var off = oP % width;
                            if (off < -107)
                                oP += (-width - off);
                            else if (off < 0)
                                oP -= (off);
                            $(this).css("left", oP);
                            if ($(this)[0] == currentList)
                                imageTimeout = setTimeout(swapImages, SLIDE_DELAY);
                        });
        }
    }
}
