

var SourcedGallery = new Class
({
	
	container: null,
	view: null,
	data:null,
	currentPos: -1,
	loadedAssets: null,
	imgId: null,
	
	
	initialize: function( container, data )
	{
		this.container = container;
		this.data = data;
		this.loadedAssets = new Array( data.length );
		this.imgId = "sgImg_"+this.container.get("id");
		this.buildView();
		this.configureBehaviour();
		this.next();
	},
	next: function()
	{
		++this.currentPos;
		if( this.currentPos > this.data.length - 1 ) this.currentPos = 0;
		this.loadImage();
		
	},
	prev: function()
	{
		--this.currentPos;
		if( this.currentPos < 0 ) this.currentPos = this.data.length - 1;
		this.loadImage();
	},
	
	//  ################### PUBLIC GETTERS / SETTERS
	getCurrentItem: function()
	{
		return this.data[ this.currentPos ];
	},
	
	
	// ################### PRIVATES
	buildView: function()
	{
		this.view = {
				controlBar : this.container.getElement(".sgControlbar"),
				btnPrev : this.container.getElement(".sgBtnPrev"),
				btnNext : this.container.getElement(".sgBtnNext"),
				caption : this.container.getElement(".sgCaption"),
				viewport : this.container.getElement(".sgViewport"),
				loader: this.container.getElement(".loader"),
				position: this.container.getElement(".sgPosition"),
				vW : null,
				vH : null
		};	
		this.view.vW = parseInt( this.view.viewport.getWidth() );
		this.view.vH = parseInt( this.view.viewport.getHeight()  );
		this.view.loader.set( "opacity", .4 );
	},
	
	loadImage: function()
	{
		this.view.loader.setStyle( "display", "inline" );
		new Asset.image( this.getCurrentItem()[0], { id:this.imgId, onload: this.imageLoadedHandler.bind( this ) } );
	},
	
	configureBehaviour: function()
	{
		this.view.btnNext.addEvent( "click", this.next.bind( this ) );
		this.view.btnPrev.addEvent( "click", this.prev.bind( this ) );
	},
	
	// ###################   LISTENERS
	imageLoadedHandler: function( img )
	{
		this.view.loader.setStyle( "display", "none" );
		if( $chk( $( this.imgId ) ) ) $( this.imgId ).dispose();
		this.view.viewport.adopt( img );
		var targetW = this.view.vW;
		var fac = targetW / img.width;
		var newW = img.width * fac;
		var newH = img.height * fac;
		
		img.width = newW;
		img.height = newH;
		
		this.updateCaptionDisplay();
		this.updatePositionInSetDisplay();
	},
	
	updateCaptionDisplay: function()
	{
		this.view.caption.set( "text", this.getCurrentItem()[ 1 ] );
	},
	
	
	updatePositionInSetDisplay: function()
	{
		var l = this.data.length;
		this.view.position.set("text", this.currentPos + 1 + " / " + l);
	}
	
	
});
