﻿$(document).ready(function() {
    $('.zoom').click(function(evnt) {
        evnt.preventDefault();
        new ImageOverlay(this.href);
    });

});
Overlay = function(content) {
    var win = $(window), doc = $(document).css({ position: 'relative' }), bod = $('body'), self = this;

    this._mask = $('<div class="mask"></div>').appendTo(bod).hide();
    this._wrapper = $('<div class="overlay"></div>').appendTo(bod).hide();
    this._content = $('<div class="overlay-content"></div>').append(content).appendTo(this._wrapper);
    this._toggle = $('<span class="close">Close</span>').prependTo(this._content);

    var hide = function() {
        self.hide();
    };

    this._toggle.click(hide);
    this._mask.click(hide);

    this._mask.css({
        zIndex: 1000,
        position: 'absolute',
        top: 0,
        left: 0,
        opacity: 0,
        backgroundColor: '#000',
        display: 'block'
    });

    this._wrapper.css({
        zIndex: 1001,
        position: 'absolute',
        top: 0,
        left: 0
    });

    this.show = function() {
        var x = doc.width(),
            y = doc.height();

        if ($.browser.msie && parseFloat($.browser.version) < 7) {
            x -= 22;
            y -= 22;
        }

        this._mask.css({
            width: x + 'px',
            height: y + 'px'
        });

        return this._mask.fadeTo(400, 0.8, function() {
            self._wrapper.fadeIn(400);
        });
    };

    this.hide = function() {
        return this._wrapper.fadeOut(400, function() {
            self._mask.fadeOut(400, function() {
                self._mask.remove();
                self._wrapper.remove();
                self._content.remove();
                self._toggle.remove();
                $("body").css("overflow", "auto"); 

            });
        });
    };

    this.centre = function() {
        var x, y;

        x = Math.round((win.width() - this._wrapper.width()) / 2);
        //y = Math.round((win.height() - this._wrapper.height()) / 2);
        y = $(window).scrollTop() + win.height() / 4;

        $("body").css("overflow", "hidden");  
        
        this._wrapper.css({
            left: (x > 0 ? x : 0) + 'px',
            top: (y > 0 ? y : 0) + 'px'
        });

        return this;
    };
};

ImageOverlay = function(href) {
    var self = this;

    this._img = $('<img alt="" src="' + href + '">').css({
        display: 'block'
    });

    this._img.load(function() {
        self._overlay = new Overlay(self._img);

        self.show = self._overlay.show;
        self.hide = self._overlay.hide;
        self.centre = self._overlay.centre;

        self._overlay.centre().show();
    });
};


