var Popup = require ('./popup');
var Spinner = require ('./spinner');

module.exports = new Class
({
	Extends: Vn.Object
	,Properties:
	{
		/**
		 * Subdirectory where full images are allocated.
		 **/
		fullDir:
		{
			type: String
			,set: function (x)
			{
				this._fullDir = x;
			}
			,get: function ()
			{
				return this._fullDir;
			}
		}
	}

	,show: function (src)
	{
		var popup = new Popup ({class: 'htk-full-image', modal: true});

		var img = document.createElement ('img');
		img.className = 'htk-full-image';
		img.addEventListener ('click', this._onImageClick.bind (this, popup));
		//img.addEventListener ('error', this._onImageError.bind (this, popup));
		img.src = src;
		
		if (!img.complete)
		{
			img.addEventListener ('load', this._onImageLoad.bind (this, popup, img));

			var spinner = new Spinner ();
			spinner.start ();
			popup.child = spinner;
		}
		else
			this._onImageLoad (popup, img);
		
		popup.open ();
	}
	
	,_onImageLoad: function (popup, img)
	{
		var scale = null;
		var width = img.width;
		var height = img.height;
		var innerWidth = Vn.Browser.getInnerWidth () - 50;
		var innerHeight = Vn.Browser.getInnerHeight () - 50;
	
		if (width > innerWidth)
		{
			scale = width / innerWidth;
			height = parseInt (height / scale);
			width = innerWidth;
		}
		if (height > innerHeight)
		{
			scale = height / innerHeight;
			width = parseInt (width / scale);
			height = innerHeight;
		}

		if (scale !== null)
		{
			img.style.width = width +'px';
			img.style.height = height +'px';
		}
		
		popup.childNode = img;
		popup.reset ();
	}
	
	,_onImageClick: function (popup)
	{
		popup.hide ();
	}

	,_onImageError: function (popup) {}
});