/**
�* Popup image viewer
�*
�*�@copyright��2008�Kamikaze
 * 
 * Requirements:
 * 	- MooTools 1.2:
 * 		Core:
 * 		- Element.Dimensions
 * 		- DomReady
 * 		- Selectors
 * 		- Fx.Tween
 * 		- Fx.Morph
 * 		More:
 * 		- Assets
�*/

var popupImage = null;

var config = {
	loadingIcon : 'js/common/popup_image/loader.gif',
	padding : {
		top : 9,
		right : 9,
		bottom : 26,
		left : 9
	}
}

window.addEvent('domready', function() {
	var popups = $$('.popupImage');
	popups.each(function (element) {
		element.addEvent('click', function(event) {
			var event = new Event(event).stop();
			if (popupImage == null) {
				popupImage = true;
				Popup(element);
			} else {
				popupImage.reload(this);
			}
		});
	});
});

function Popup(link) {
	popupImage = this;

	this.wrapper = null;
	this.elements = {};
	this.link = null;
	this.thumb = null;
	this.image = null;

	var _popup = this;
	var _body = $(document.body);
	var _background = null;
	var _wrapper = null;
	var _wrapperSize = null;
	var _wrapperMorph = null;
	var _imageDescription = null;
	var _next = null;
	var _prev = null;
	var _close = null;

	/**
	 * function create()
	 */
	this.create = function() {
		this.link = link;
		this.thumb = link.getChildren('img')[0];
		this.thumb.coordinates = this.thumb.getCoordinates(_body);

		// Tło zakrywające całą stronę
		var bodySize = $$('body').getScrollSize()[0];
		this.background = new Element('div');
		this.background.set('class', 'popupBackground');

		this.background.setStyles({
			width: bodySize.x,
			height : bodySize.y,
			left : 0,
			top: 0,
			opacity : 0,
			padding : 0,
			position : 'absolute'
		});
		this.background.inject(_body);
		_background = this.background;

		var bodySize = $$('body').getSize()[0];
		this.wrapper = new Element('div');
		this.wrapper.set('class', 'popupWrapper');

		this.wrapper.setStyles({
			height : 0,
			left : bodySize.x / 2,
			opacity : 0,
			padding : 0,
			position : 'absolute',
			top: bodySize.y / 2,
			width: 0
		});
		this.wrapper.coordinates = this.thumb.coordinates;
		this.wrapper.inject(_body);
		_wrapper = this.wrapper;

		this.elements.background = new Element('div');
		this.elements.background.set('class', 'popupBackground');
		this.elements.background.setStyles({
			height : '100%',
			width : '100%',
			background: '#000000',
			opacity: 0.5
		});
		this.elements.background.inject(this.wrapper);

		this.elements.imageContainer = new Element('div');
		this.elements.imageContainer.set('class', 'popupImageContainer');
		this.elements.imageContainer.setStyles({
			left : 0,
			position : 'absolute',
			top : 0
		});
		this.elements.imageContainer.inject(this.wrapper);

        // Utworzenie podstawowego kontenera na opis zdjęcia, jeśli jest w nim co przechowywać
        this.elements.imageDescription = new Element('div');
        this.elements.imageDescription.set('class', 'popupImageDescription');
        this.elements.imageDescription.setStyles({
            left : 0,
            position : 'absolute',
            top : 0
        });
        this.elements.imageDescription.inject(this.wrapper);

        if (this.thumb.get('title') && this.thumb.get('title').length > 0) {
            this.elements.imageDescription.set('html', this.thumb.get('title'));
        }
        _imageDescription = this.elements.imageDescription;


		// Przycisk 'następne zdjęcie'
		this.elements.next = new Element('img');
		this.elements.next.src = './js/common/popup_image/next.png';
		this.elements.next.setStyles({
			left : 0,
			position : 'absolute',
			top : 0,
			cursor : 'pointer',
			'z-index': 1
		});

        this.elements.next.addEvent('click', function(event) {
            changeImage(1);
        });

		_next = this.elements.next;
		this.elements.next.inject(this.wrapper);


        // Przycisk 'poprzednie zdjęcie'
        this.elements.prev = new Element('img');
        this.elements.prev.src= './js/common/popup_image/prev.png';
        this.elements.prev.setStyles({
            left : 0,
            position : 'absolute',
            top : 0,
            cursor : 'pointer',
            'z-index': 1
        });

        _prev = this.elements.prev;
        this.elements.prev.inject(this.wrapper);

        this.elements.prev.addEvent('click', function(event) {
            changeImage(-1);
        });


        // Przycisk 'zamknij'
        this.elements.imageClose = new Element('div');
        this.elements.imageClose.set('class', 'popupImageClose');
        this.elements.imageClose.inject(this.wrapper);
        this.elements.imageClose.setStyles({
        	position : 'absolute',
    		left : 0,
    		top : 0,
    		height : 19,
    		width : '100%'
        });
        this.elements.close = new Element('img');
        this.elements.close.src = './js/common/popup_image/close.gif';
        this.elements.close.setStyles({
            cursor : 'pointer',
            float: 'right',
            margin: '4px 10px 0 0',
            'z-index': 1
        });

        _close = this.elements.close;
        this.elements.close.inject(this.elements.imageClose);

        this.elements.close.addEvent('click', function(event) {
            close();
        });


		// Uruchomienie podglądu zdjęcia
		var openTween = new Fx.Tween(_background, {duration: '100'});
		openTween.start('opacity', 0.7).chain(function() {
			_wrapper.tween('opacity', 1);
			popupImage.loadImage();
		});
	}

    /**
     * function unloadImage()
     */
    this.unloadImage = function() {
        if (popupImage._imageDescription) {
            popupImage._imageDescription.tween('opacity', 0);
        }

        this.image.tween('opacity', 0);
    }

	/**
	 * function reload()
	 */
    this.reload = function (newLink) {

        if (newLink) {
            this.link = newLink;
            this.loadImage();
        }
    }

	/**
	 * function loadImage()
	 */
	this.loadImage = function() {
		if (null != this.image) {
			this.unloadImage();
		}

		/* loading icon */
		var _loading = new Asset.image(config.loadingIcon, {
			'class' : 'popupLoadingIcon',
			'onload' : function() {
				_loading.setStyle('opacity', 0);
				_loading.inject(_wrapper);
				var _loadingSize = _loading.getSize();
				_loading.setStyles({
					left : (_wrapper.coordinates.width / 2) - (_loadingSize.x / 2),
					opacity : 1,
					position : 'absolute',
					top : (_wrapper.coordinates.height / 2) - (_loadingSize.y / 2)
				});
				_loading._visible = true;
			}
		});
		this.elements.loadingIcon = _loading;

		/* load and show image */
		var _image = new Asset.image(this.link.get('href'), {
			'class' : 'popupImage',
			'onload' : function() {
				_image.setStyles({
					cursor : 'pointer',
					left : config.padding.left,
					opacity : 0,
					position : 'absolute',
					top : config.padding.top + 18
				});
				_image.inject(_wrapper);
				
				var _screenSize = window.getSize();
				_image._size = _image.getSize();
				if ((_screenSize.x - _image._size.x)  < 50)  {
					var _resize = (_screenSize.x-50)/_image._size.x;
					_image.setStyles({
						width : parseInt(_image._size.x * _resize),
						height : parseInt(_image._size.y * _resize)
					});
					_image._size = _image.getSize();
				}
				if ((_screenSize.y - _image._size.y)  < 50)  {
					var _resize = (_screenSize.y-50)/_image._size.y;
					_image.setStyles({
						width : parseInt(_image._size.x * _resize),
						height : parseInt(_image._size.y * _resize)
					});
					_image._size = _image.getSize();
				}
				
                if (_imageDescription) {
                    _imageDescription.setStyles({
                        cursor : 'pointer',
                        background : '#ffffff',
                        color : '#7189A5',
                        left : config.padding.left,
                        opacity : 0,
                        position : 'absolute',
                        top : config.padding.top + _image._size.y,
                        width: _image._size.x - 10,
                        padding: '5px'
                    });

                    _imageDescription._size = _imageDescription.getSize();
                }

                var text = popupImage.link.getElement('img').get('title');
                if (text && text.length > 0) {
                    _imageDescription.setStyle('visibility', 'visible');
                    _imageDescription.set('html', text);
                } else {
                    _imageDescription.setStyle('visibility', 'hidden');
                    _imageDescription.set('html', '');
                }

				if (true == _loading._visible) {
					_loading.setStyle('opacity', 0);
					_loading._visible = false;
				}

				var _screenSize = window.getSize();
				var _scroll = document.getScroll();
				_wrapperSize = {
					x : _image._size.x + config.padding.left + config.padding.right,
					y : _image._size.y + config.padding.top + config.padding.bottom
				};

                var showNext = false;
                var showPrev = false;
                var eleme = $$('a[class=popupImage]');
                for (i = 0; i < eleme.length; i++) {
                    if (eleme[i] == popupImage.link) {
                        if (i < (eleme.length - 1)) {
                            showNext = true;
                        } else {
                            showNext = false;
                        }
                        if (i > 0) {
                            showPrev = true;
                        } else {
                            showPrev = false;
                        }
                        break;
                    }
                }

                _next.morph({
					//left : _wrapperSize.x / 2 + _next.getSize().x + 8,
					left : _wrapperSize.x -9,
					//top : -_next.getSize().y - 9
					top : -_next.getSize().y + _image._size.y / 2 + 30
				});

				_prev.morph({
					//left : _wrapperSize.x / 2 - _prev.getSize().x - 8,
					left : _wrapperSize.x - _image._size.x - 33,
					//top : -_prev.getSize().y - 9
					top : -_next.getSize().y + _image._size.y / 2 + 30
				});

				_close.morph({
					left : _wrapperSize.x - _close.getSize().x,
					top : -_close.getSize().y - 9
				});

				if (showNext) {
					_next.setStyle('visibility', 'visible');
				} else {
					_next.setStyle('visibility', 'hidden');
				}

				if (showPrev) {
					_prev.setStyle('visibility', 'visible');
				} else {
					_prev.setStyle('visibility', 'hidden');
				}

				if (_imageDescription && _imageDescription.get('html').length > 0) {
					_wrapperSize.y += _imageDescription._size.y;
				}

				_wrapperMorph = new Fx.Morph(_wrapper);
				var _wrapperMorphTop = _scroll.y + ((_screenSize.y / 2) - (_wrapperSize.y / 2));
				_wrapperMorph.start({
					left : _scroll.x + ((_screenSize.x / 2) - (_wrapperSize.x / 2)),
					height : _wrapperSize.y,
					width : _wrapperSize.x,
					top : (_wrapperMorphTop < 0)?0:_wrapperMorphTop
				}).chain(function() {
					_image.tween('opacity', 1);
					if (_imageDescription && _imageDescription.get('html').length > 0) {
						_imageDescription.tween('opacity', 1);
					}
				});

				_image.addEvent('click', close);
				if (_imageDescription) {
					_imageDescription.addEvent('click', close);
				}
			}
		});
		this.image = _image;

		window.addEvent('scroll', this.moveToCenter);
		window.addEvent('resize', this.resize);
		$$('body').setStyle('overflow', 'hidden');
	}

	this.resize = function() {
		this.moveToCenter();

		var bodySize = $$('body').getScrollSize()[0];
		this.background.setStyles({
			width: bodySize.x,
			height : bodySize.y
		});
	}

	/**
	 * function moveToCenter()
	 */
	this.moveToCenter = function() {
		if (_wrapperSize) {
			var _screenSize = window.getSize();
			var _scroll = document.getScroll();
			var _wrapperMorphTop = _scroll.y + ((_screenSize.y / 2) - (_wrapperSize.y / 2));
			_wrapperMorph.start({
				left : _scroll.x + ((_screenSize.x / 2) - (_wrapperSize.x / 2)),
				top : (_wrapperMorphTop < 0)?0:_wrapperMorphTop
			});
		}
	}

	/**
	 * function showImage()
	 */
	this.showImage = function() {
		if (null == this.image) {
			this.loadImage();
		}
	}

	this.close = close;
	function close() {
		var closeTween = new Fx.Tween(_wrapper);
		closeTween.start('opacity', 0).chain(function() {
			_wrapper.destroy();
			popupImage = null;

			var closeTween2 = new Fx.Tween(_background, {duration: '100'});
			closeTween2.start('opacity', 0).chain(function() {
				_background.destroy();
			});
		});
		$$('body').setStyle('overflow', 'auto');
	}

	this.changeImage = function(direction) {
		var elements = $$('a[class=popupImage]');
		for (i = 0; i < elements.length; i++) {
			if (elements[i] == popupImage.link) {
				if (direction == null) {
					direction = 1;
				}

				if ((direction < 0 && i > 0) || (direction > 0 && i < elements.length)) {
					popupImage.reload(elements[i + direction]);
					return true;
				}
			}
		}
	}

	this.create();
}
