// DOM ready

$(document).ready(function() {


    $('#image-holder').fadeIn(1000);
    $("#content").fadeIn(1000, function() { $(this).fixClearType() });

    //Cleartype fix
    jQuery.fn.fixClearType = function() {
        return this.each(function() {
            if (!!(typeof this.style.filter && this.style.removeAttribute))
                this.style.removeAttribute("filter");
        })
    }


    // Image Sources
    var images = new Array(
         	'images/projects/Small/portfolio_1.jpg'
        	, 'images/projects/Small/portfolio_2.jpg'
        	, 'images/projects/Small/portfolio_3.jpg'
        	, 'images/projects/Small/portfolio_4.jpg'
        	, 'images/projects/Small/portfolio_5.jpg'
			, 'images/projects/Small/portfolio_6.jpg'
			, 'images/projects/Small/portfolio_7.jpg'
			, 'images/projects/Small/portfolio_8.jpg'
			, 'images/projects/Small/portfolio_9.jpg'
			, 'images/projects/Small/portfolio_10.jpg'
			, 'images/projects/Small/portfolio_11.jpg'
			, 'images/projects/Small/portfolio_12.jpg'
			, 'images/projects/Small/portfolio_13.jpg'
    );

    //Loads first image to main pic.
    if( images.length > 0 )
        $("#image-holder img").attr("src", images[0].replace(/\/small[\/]/gi, "/large/"));
    


// images length
var max = $(images).length;
// at least 1 image exist
if (max > 0) {
    // create the UL element
    var ul = $('<ul id="portfolio"></ul>');
    // append to div#wrapper
    $(ul).appendTo($('#thumbnails'));
    // load the first image
    LoadImage(0, max);
}

// function of loading image
// params: (int) index of image in array, (int) length of images array
function LoadImage(index, max) {
    // if current index is lower then max element (max-1)
    if (index < max) {
        // create the LI, add loading class
        var list = $('<li id="portfolio_' + index + '"></li>').attr('class', 'loading').css({cursor:"pointer"});

        list.click(function() {
			$("#image-holder img").hide();
            $("#image-holder img").attr("src", $("img", this).attr("src").replace(/\/small[\/]/gi, "/large/"));
			$("#image-holder img").fadeIn(1000);
        });


        // append to UL
        $('ul#portfolio').append(list);
        // current LI
        var curr = $("ul#portfolio li#portfolio_" + index);
        // new image object
        var img = new Image();
        // image onload
        $(img).load(function() {
            $(this).css('display', 'none'); // since .hide() failed in safari
            $(curr).removeClass('loading').append(this);
            $(this).fadeIn('slow', function() {
                // once the current loaded, trigger the next image
                LoadImage(index + 1, max);
            });
        }).error(function() {
            // on error remove current
            $(curr).remove();
            // trigger the next image
            LoadImage(index + 1, max);
        }).attr('src', images[index]);
    }
}


});


