(function($) {
    $.fn.galleryBrowser = function() {
        return this.each(function() {
        $(this).click(function(e) {
            /*
                ABOUT:

                Each image has a prev-PID, next-PID anchor and the image itself
                is id'd with currentimage-PID. this loads the array of gallery
                images for the paticular contenttype/object/thumbnail size. it
                then loops through, works out what one is currently being shown
                and then whether its going forward or back increments the array
                accordingly. it handles wrapping around also.

                TODO: maybe convert the simple attr('src') re-assignment with
                a load request and fadeIn/Out behaviours. ~jaymz

                USAGE:

                Set the id of your image to currentimg with the id:
                <img id="currentimg-{{ item.id }}" />

                Then add 2 links like so:, with previmg or nextimg depending on
                the direction:
                <a href="{% url gallery:pickled "CONTENT_TYPE" OBJECT.ID "THUMBNAIL_WANTED" %}" id="previmg-{{ OBJECT.ID }}" class="gallerycontrol previmg"></a>
            */
            e.preventDefault();
            var gimages;
            var current_index;
            var current_img = $('#currentimg-'+$(this).attr('id').replace(/\D/g,''));
			var zoom_link = $('#zoom-'+$(this).attr('id').replace(/\D/g,''));
            var e_this = $(this);
            $.ajax({
                'url' : $(this).attr('href'),
                'dataType' : 'json',
                success : function(json) {
                    gimages = json;
                    for(var i in gimages) {
                        if(gimages[i]==current_img.attr('src')) {
                            current_index = parseInt(i);
                            break;
                        }
                    }
                    var target_index;
                    if(e_this.hasClass('nextimg')) {
                        target_index = current_index+1;
                    } else {
                        target_index = current_index-1;
                    }
                    if(target_index>gimages.length-1) {
                        target_index = 0;
                    } else if(target_index<0) {
                        target_index = gimages.length-1;
                    }
                    current_img.attr('src', gimages[target_index]);
					if (zoom_link.length > 0) {
						var new_link = gimages[target_index];
						//alert(zoom_link.length);
						zoom_link.attr('href', new_link.replace('200x200_crop', '640x640_crop-True_sharpen-True_upscale'));
						Shadowbox.setup();
					}
                }
            });
        });
    });
}
}) (jQuery);
