
jQuery(document).ready(function() {
	var ImageList = new Collection( jQuery("#imagelist") );
	ImageList.init();
});

function Collection( element ) {
	
	this.element = element;
	this.totalElements = 0;
	this.position = 0;
	this.limit = 3;
	
	this.nextObj = jQuery( "img.next" );
	this.prevObj = jQuery( "img.previous" );
	
	/* get total elements than show first 3 */
	this.init = function() {
		this.totalElements = jQuery(".paging").attr("class").split(" ")[1];
		this.ShowandHide( "forward" );
		
		var _self = this;
		jQuery( this.nextObj ).click( function() {
			_self.getImages();
		} );
		jQuery( this.prevObj ).click( function() {
			_self.ShowandHide( "" );
		} );
		
	}
	
	this.ShowandHide = function( action ) {
		var Pos = 0;
		var _self = this;

		var Start = action == "forward" ? this.position : this.position - ( this.limit * 2);
		var End = action == "forward" ? this.position + ( this.totalElements < 3 ? this.totalElements : 3 ) : this.position - this.limit;
		End = End > this.totalElements ? this.totalElements : End;
		
		if ( this.position <= this.limit && action != "forward" ) return;
		if ( Start >= this.totalElements && action == "forward" ) return; 
		
		jQuery( this.element ).find( "li" ).each( function() {
			if ( Pos >= Start && Pos < End ) {
				jQuery(this).css( "display", "block" );
			} else {
				jQuery(this).css( "display", "none" );
			} 
			Pos++;
		} );
		
		this.position = action == "forward" ? this.position + 3 : this.position - 3;
		jQuery( ".paging").html( ( Start + 1 )  + " - " + End  + " of " + this.totalElements );
	};
	
	this.getImages = function() {
		var _self = this;
		if ( jQuery( this.element ).find("li").length < this.totalElements ) {
			jQuery.getJSON( document.location + "listimages/" + this.limit + "/", { 'start' : ( this.position ) }, function(data,textStatus){
				jQuery.each( data.items, function( i, item ) {
					item["Name"] = "null" == item["Name"] ? "" : item["Name"];
					jQuery( _self.element ).append( '<li><a href="#" title="' +  item["Name"] + '" alt="' +  item["Name"] + '"><img src="' +  item["SmallImage"] + '" alt="' +  item["Name"] + '" title="' +  item["Name"] + '"/></a></li>' );
					jQuery( _self.element ).find("li:last").click( function() { 
						CollectionMainImage( item["SelectLink"] );
						return false;
					});
				} );
				_self.ShowandHide( "forward" );
			});
		} else {
			_self.ShowandHide( "forward" );
		}
	};
	
}

function CollectionMainImage( url ) {
	jQuery.getJSON( url, function ( data ) {
		jQuery( "#collectionDownload a").attr( "href", data["download"] );
		jQuery( "#collectionMainImage").html( data["image"] );
		jQuery( "#CollectionAdditional").html( data["description"] );
		jQuery( "#image_name").text( data["title"] );
	} );
}
