var $ctrl = function( elementId )
{
	return $( "#"+ elementId ).get(0).control;
}

var ImageViewer = function( id, visibleClass, txt, btnClose, btnPrev, btnNext )
{
	this.visibleClass = visibleClass;
	this.images       = new Array();
	this.root         = $( "#"+ id );
	this.img          = this.root.find( "img" );
	this.root.get(0).control = this;
	
	
	if( txt )
		this.txt = this.root.find( txt );

	if( btnClose )
	{
		this.btnClose = this.root.find( btnClose );
		this.btnClose.click( function( e )
		{
			$( "#"+ id ).click();
		} );
	}
	
	if( btnPrev )
	{
		this.btnPrev    = this.root.find( btnPrev );
		this.btnPrev.click( function( e )
		{
			e.stopPropagation();
			$ctrl( id ).Prev();
		} );
	}
	
	if( btnNext )
	{
		this.btnNext    = this.root.find( btnNext );
		this.btnNext.click( function( e )
		{
			e.stopPropagation()
			$ctrl( id ).Next();
		} );
	}
}

ImageViewer.prototype = {
	
	txtElement : null,
	
	Open : function( imageIndex )
	{
		if( !imageIndex )
			imagenIndex = 0;
	
		this.currentIndex = imageIndex;
		this.showCurrentImage();
		
		var r = this.root;
		var v = this.visibleClass;
		var b = $( "body" );
		var w = b.width();
		var m = parseInt( b.css( "marginRight" ) );
		
		r.bind( "click", function( e )
		{
			if( e.target == r.get(0) )
			{
				b.css( "overflow-y", "auto" );
				b.css( "margin-right", m );
				r.removeClass( v );
				r.unbind( "click" );
			}
		} );
		
		b.css( "overflow-y", "hidden" );
		b.css( "margin-right", m + b.width() - w );
		
		r.addClass( v );
	},
	
	Close : function()
	{
		this.root.click();
	},
	
	AddImageRange : function( args )
	{
		var img;
		
		for( var i = 0; i < arguments.length; i++ )
			this.images.push( arguments[i] );
	},
	
	Prev : function()
	{
		this.currentIndex--;
		
		if( this.currentIndex < 0 )
			this.currentIndex = this.images.length - 1;
		
		this.showCurrentImage();
	},
	
	Next : function()
	{
		this.currentIndex++;
		
		if( this.currentIndex >= this.images.length )
			this.currentIndex = 0;
		
		this.showCurrentImage();
	},
	
	showCurrentImage : function()
	{
		var img = this.images[ this.currentIndex ];
		
		this.img.attr( "src", img.Url );
		//this.imgElement.src = img.Url;
		
		if( this.txt )
			this.txt.text( img.Alt );
	}
}
