function Gallery(domId, fetchUrl, imageUrls) {
    this.slugs = new Array();
    this.images = new Array();

    var fetch = true;
    var that = this;

    var num = imageUrls.length;
    if (num == 0) { return; }

    /*
     * Format array for simplegallery
     */

    for (var i=0; i < num; i++) {
	this.parseImageData(imageUrls[i]);
    }

    var simpleOptions = {
	wrapperid: domId,
	dimensions: [550, 480],
	imagearray: this.images,
	autoplay: [true, 7000, 2],
	persist: false,
	fadeduration: 1600,
	oninit: function(){},
	onslide: function(currentSlide, i) {
	    if (i == that.images.length - 1) {
		fetchImages();
	    }
	}
    };

    var myGallery = null;
	window.setTimeout(function() {
		myGallery = new simpleGallery(simpleOptions);
	}, 200);

    /*
     * Callback for ajax request
     * Should receive a json object
     */

    var fetchImages = function() {
	if (fetch !== true) { return; }

	var options = {
	    cache: false,
	    data: { exclude: that.slugs.join(',') },
	    url: fetchUrl,
	    success: processFetch,
	    error: function() { fetch = false; },
	    dataType: 'json'
	};

	$.ajax(options);
    };

    var processFetch = function(rsp) {
	if (rsp.none_found) { fetch = false; return; }
	that.parseImageData(rsp);
    };
}

Gallery.prototype = {
    parseImageData: function(arg) {
	var obj = (typeof arg == 'string') ? eval('('+arg+')') : arg;
	for(k in obj) {
	    var url = obj[k][0];
	    var attr = obj[k][1];
		var caption = obj[k][2];
	    this.slugs.push(this.slugFromUrl(url));
	    this.images.push([url, '', '', attr, caption]);
	}
    },

    slugFromUrl: function(url){
	var m = /gallery\/(.*?)\.(jpg|png|jpeg)$/.exec(url);
	if(!m) {
	    alert('unable to parse filename from url');
	    return false;
	}
	return m[1];
    }
};
