/*****************************************************************************************
 * jQuery plug-in
 * Flickr Photo Gallery
 * Developed by J.P. Given (http://johnpatrickgiven.com)
 * Additional development by J. Gay (http://jasongay.info)
 * Useage: anyone so long as credit is left alone...oh and get your own API key ;)
 ******************************************************************************************/
//Globals
var obj = null; // Container objectcccccccc                         
var x = 0; // Object X
var y = 0; // Object Y
var c = 0; // Object center point
var ct = 0; // Object center point from top
var mX = 0; // Mouse X
var mY = 0; // Mouse Y
var imgArray = new Array(); // Array to hold urls to flickr images
var titleArray = new Array(); // Array to hold image titles if they exist
var currentIndex = 0; // Default image index
var fImg = null; // For checking if the image object is loaded.
// Callback for Flickr - Simply set array


function setFlickrData(flickrData) {
    var length = flickrData.photoset.photo.length;
    var thumbHTML = '';

    for (i = 0; i < length; i++) {

var photoURL = 'http://farm' + flickrData.photoset.photo[i].farm + '.static.flickr.com/' + flickrData.photoset.photo[i].server + '/' + flickrData.photoset.photo[i].id + '_' + flickrData.photoset.photo[i].secret + '_b.jpg'

var thumbURL = 'http://farm' + flickrData.photoset.photo[i].farm + '.static.flickr.com/' + flickrData.photoset.photo[i].server + '/' + flickrData.photoset.photo[i].id + '_' + flickrData.photoset.photo[i].secret + '_s.jpg'

        thumbHTML += '<img src=' + thumbURL + ' width="50" height="50" onclick="navImg(' + i + ');" style="cursor: pointer;">';
        imgArray[i] = photoURL;
        titleArray[i] = flickrData.photoset.photo[i].title;
    }

    
	$("#flickr_thumbs").html(thumbHTML);



}
////////////////////////////////////////////////////////////////////////////////////////////
//  Image navigation logic
function navImg(index) {

    // Set the global index
    currentIndex = index;

    // Set the loader gif pos and display
    $("#flickr_loader").css("top", y + "px");
    $("#flickr_loader").css("left", x + "px");
    $("#flickr_loader").css("display", "block");


    // Create an image Obj with the URL from array
    var thsImage = null;
    thsImage = new Image();
    thsImage.src = imgArray[index];

    // Set global imgObj to jQuery img Object
    fImg = $(thsImage);

    // Display the image
    obj.html('');
    obj.html('<img id="thsImage" src=' + imgArray[index] + ' border=0>');
	$("#thsImage").hide();
   
	// Call to function to take loader away once image is fully loaded
    checkImageLoad();

    // Set image size in relation to container
    // Set the aspect ratio
    var w = $("#thsImage").outerWidth(true);
    var h = $("#thsImage").outerHeight(true);
    var fRatio = w / h;
    
    $("#thsImage").width(obj.outerWidth(true));
    $("#flickr_div").height("#thsImage");
	
}
////////////////////////////////////////////////////////////////////////////////////////////


// Simple function to check if the image is fully loaded


function checkImageLoad() {
    if (fImg.attr("complete") == false) {
        setTimeout("checkImageLoad()", 1000);
    } else {
        $("#flickr_loader").fadeOut();
		$("#thsImage").fadeIn(600);
        var current_count = currentIndex + 1;
        $("#flickr_count").html();
        if (titleArray[currentIndex] != "") {
            $("#flickr_count").append(titleArray[currentIndex]);
        }
    }
}



// Sort of like an init() but re-positions dynamic elements if browser resized.
$(window).resize(function () {
    // Get the position of the element Flickr obj will be loaded into
    x = obj.offset().left;
    y = obj.offset().top;
    c = x + (obj.outerWidth(true) / 2);
    ct = y + (obj.outerHeight(true) / 2);

    $("#flickr_loader").css("background-color", "#FFF"); // Set background color of loader to the background-color of container
    $("#flickr_loader").css("width", obj.width() + "px");
    $("#flickr_loader").css("height", obj.height() + "px");

    $("#flickr_thumbs").css("background-color", obj.css("background-color"));
    $("#flickr_thumbs").css("width", obj.width() + "px");
    $("#flickr_thumbs").css("left", x + "px");
    $("#flickr_thumbs").css("top", y + "px");
});

// Plug-In
(function ($) {

    // plugin definition
    $.fn.flickrGallery = function (setID, apiKEY) {
        // Set Obj to the Object
        obj = this;

        // Assure images are centered
        this.css("text-align", "center")

        // init the image loader and set values
        $("flickr_div").append('<div id="flickr_loader"></div>');
		$("#flickr_loader").css("background", "url(../images/loader.gif) no-repeat center center")
        $("#flickr_loader").css("background-color", "#FF0000"); // Set background color of loader to the background-color of container
        $("#flickr_loader").height("#flickr_div");
        $("#flickr_loader").width("#flickr_div");

        // CSS object overflow for aspect ratio
        obj.css("overflow", "hidden");

        // Get the Flickr Set :)
        $.getScript("http://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&photoset_id=" + setID + "&api_key=" + apiKEY + "&jsoncallback=setFlickrData", function (data) {
            // When data is set, load first image.
            navImg(0);
        });



        // Get the position of the element Flickr obj will be loaded into
        x = this.offset().left;
        y = this.offset().top;
        c = x + (obj.outerWidth(true) / 2);
        ct = y + (obj.outerHeight(true) / 2);

        // position loader
        $("#flickr_loader_table").css("left", x + "px");
        $("#flickr_loader_table").css("top", y + "px");



        // Set navigation click events
        $("#flickr_next").click(function () {
            if (currentIndex < (imgArray.length - 1)) {
                currentIndex = currentIndex + 1;
                navImg(currentIndex);
            }
        });

        $("#flickr_prev").click(function () {
            if (currentIndex > 0) {
                currentIndex = currentIndex - 1;
                navImg(currentIndex);

            }
        });


    };

    // private function for debugging


    function debug(msg) {
        window.console.log(msg);
    };
})(jQuery);
