var _ = null;

$.fn.thickBox = function( appendTo, data )
{
    _ = this;

    _.pageDims = getPageDims();

    _.overlay = document.createElement( 'div' );

    _.modal = document.createElement( 'div' );
    _.mClose = document.createElement( 'a' );
    _.mHeader = document.createElement( 'h1' );
    _.mContent = document.createElement( 'div' );

    _.modal = $( _.modal ).addClass( 'modal-window' ).append( _.mHeader ).append( _.mContent );
    _.mHeader = $( _.mHeader ).addClass( 'modal-window-header' ).append( _.mClose );
    _.mContent = $( _.mContent ).addClass( 'modal-window-content' );

    _.overlay = $( _.overlay ).addClass( 'modal-overlay' );

    _.mClose = $( _.mClose ).addClass( 'modal-window-close' ).attr( 'href', 'javascript:;' );
    _.mClose = $( _.mClose ).attr( 'title', 'Закрыть' );

    $( _.overlay ).animate( { 'opacity' : 0.55 }, { 'duration' : 500 } );

    $( _.mHeader ).append( data.header );
    $( _.mContent ).append( data.content );

    $( 'body' ).prepend( _.overlay );
    $( appendTo ).prepend( _.modal );

    var left = ( _.pageDims.width - $( _.modal ).innerWidth() ) / 2;

    $( _.modal ).css( {
        width: $( _.modal ).width(),
        top: '-' + $( _.modal ).height() + 'px',
        left: left + 'px'
    } );

    $( _.modal ).show().animate( { top: (( _.pageDims.height - $( _.modal ).height() ) / 2) + 'px' } );

    $( _.overlay ).click( $().removeThickBox );
    $( _.mClose ).click( $().removeThickBox );

    $(window).resize
    (
        function ()
        {
            _.pageDims = getPageDims();
            var left = ( _.pageDims.width - $( _.modal ).innerWidth() ) / 2;
            $( _.modal ).animate( {
                top: ( _.pageDims.height - $( _.modal ).height() ) / 2,
                left: left
            } );
        }
    );

    function getPageDims()
    {
        var d = document.documentElement;
        var w = window.innerWidth || self.innerWidth || ( d && d.clientWidth ) || document.body.clientWidth;
        var h = window.innerHeight || self.innerHeight || ( d && d.clientHeight ) || document.body.clientHeight;

        return {
            'width' : w,
            'height' : h
        };
    }

    return this;
};

$.fn.removeThickBox = function ()
{
    $( _.modal ).animate( {
        top: '-' + $( _.modal ).height() + 'px'
    }, function () {
        $( _.overlay ).fadeOut(); $( _.modal ).remove();
    } );
};