function shuffle(array) {
    var tmp, current, top = array.length;

    if(top) while(--top) {
        current = Math.floor(Math.random() * (top + 1));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
    }

    return array;
};

function scale_photo_size(width, height, max_width, max_height){
    var photo_size = new Array(2);
    var aspect_ratio = width/height;
    if (height >= width && height > max_height){
        height = max_height;
        width = Math.round(aspect_ratio*height);
    }
    if (width >= height && width > max_width){
    	width = max_width;
    	height = Math.round(width/aspect_ratio);
    }
    photo_size[0] = width;
    photo_size[1] = height;
    return photo_size;
};

function mycarousel_itemLoadCallback(carousel, state)
{
    // Since we get all URLs in one file, we simply add all items
    // at once and set the size accordingly.
    var filenameDiv = document.getElementById('photoFileName');
    
    if (state != 'init')
        return;
        
    jQuery.get(filenameDiv.className, function(data) {
        mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
    });
};

function mycarousel_itemAddCallback(carousel, first, last, data)
{
    // Simply add all items at once and set the size accordingly.
    var items = data.split('*');
    var urls = items[0];
    urls = urls.split('|');
    // remove last blank item in sizes so that it only contains the urls.
    urls.splice(urls.length-1)
    
    var sizes = items[1];
    sizes = sizes.split('|');
    
    // get max width and height and then remove from size array
    var max_size = sizes[0];
    max_size = max_size.split(',');
    var max_width = max_size[0];
    var max_height = max_size[1]; 
    sizes.splice(0,1);
    // remove last blank item in sizes so that it only contains the sizes.
    sizes.splice(sizes.length-1);
    
    for (i = 0; i < urls.length; i++) {
    	var photo_size = sizes[i];
    	photo_size = photo_size.split(',');
    	var width = photo_size[0];
    	var height = photo_size[1];
    	photo_size = scale_photo_size(parseInt(width), parseInt(height), parseInt(max_width), parseInt(max_height));
        carousel.add(i+1, mycarousel_getItemHTML(urls[i], photo_size[0], photo_size[1]));
    }

    carousel.size(urls.length);
};

/**
 * Item html creation helper.
 */
function mycarousel_getItemHTML(url, width, height)
{
    //return '<img src="' + url + '" width="75" height="75" alt="" />';
    //return '<p>' + url + ' ' + width + ' ' + height + ' </p>';
    var ans = '<center><img src="' + url + '" width="' + width + '" height="' + height +'" alt="" /></center>';
    return ans;   
};

jQuery(document).ready(function() {
    jQuery('#mycarousel').jcarousel({
        itemLoadCallback: mycarousel_itemLoadCallback,
        scroll: 1,
        wrap : "both"
    });
});


