/*
    zoom.js - 
	This script uses a set of variable-sized images to
	achieve a zoom-like effect in a lightbox-like popup
	
    Copyright (C) 2010 Matthijs van Henten <matthijs_AT_ischen_DOT_nl>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

jQuery(document).ready(function(){
	zoomer = new dZoom({
    images: [ '/static/punch/punchthispainting-20.jpg'
        , '/static/punch/punchthispainting-30.jpg'
        , '/static/punch/punchthispainting-50.jpg'
        , '/static/punch/punchthispainting-70.jpg'
        , '/static/punch/punchthispainting-100.jpg'
        , '/static/punch/punchthispainting-120.jpg'
        , '/static/punch/punchthispainting-160.jpg'
    ]
    });
	var img = jQuery('#document .firstimg');
	if(img.attr('src').test(/ogut/i))
	 	img.parent().click(function() {
		zoomer.show();
		return false;
	});
    //zoomer.show();
});

dZoom = function( arg ){
    this._images = arg.images || [];
}

dZoom.prototype = {
    index: 0,
    pointer: null,
    canDrag: false,
    show: function(){
        var body = document.getElementsByTagName('body')[0];
            var html =
            '<div style="position:absolute;top:0;left:0;bottom:0;right:0;z-index:9999;">'
                + '<div style="cursor:pointer; position:absolute;top:0;left:0;bottom:0;right:0;z-index:-1;background-color:#000;"></div>'
                + '<div style="cursor:default;position:relative;width: 40%;background-color:#000; overflow: hidden;text-align:center;">'
                + '<div style="cursor:default;position:absolute;z-index:2;left:20px;background: #fff;padding:3px 10px 3px 10px; margin: 20px;line-height:22px;">'
                + '<span style="line-height:22px;padding-left: 20px; background:url(data:image/gif;base64,'
		+ 'R0lGODlhEAAQAOMIAFpaWmpqant7e46Ojpubm6urq7+/v9HR0f///////////////////////////////yH5BAEKAAgALAAAAAAQABAAAARMEMlJKy0YEzsxJZvlVWA1WsNwcZPaWaDqSgVsyN83EAYhBJ8QYmAwFIxAnWQgGBQGAABqFigADrdpKhA9YJOsoQFLkIbFPXA4MEhGAAA7) no-repeat">'
                + 'enlarge &amp; zoom </span>'
                + '<button onclick="return false;" style="padding:0 7px 0 7px;cursor:pointer;font:bold 15px/22px fixed;color:#000;">+</button>'
                + '<button onclick="return false;" style="padding:0 7px 0 7px;cursor:pointer;font:bold 15px/22px fixed;color:#000;">&minus;</button>'
		+ '<button onclick="return false;" style="padding:1px 7px 1px 7px;cursor:pointer;font:normal 13px/22px sans-serif;color:#000;">close</button>'
                + '</div>'
                + '<img ondragstart="return false;" src="" title="drag to move, double-click to resize" '
                + 'style="left:0;cursor: move; position: absolute;z-index:0;"/></div>';

            jQuery(body).prepend(html)

            this.element = jQuery(body).children().first()
        var bg = jQuery(this.element).children().first();

        jQuery(bg).fadeTo(1, 0.0, function(){
            jQuery(bg).fadeTo(200, 0.7);
        });

	var buttons = jQuery(this.element).find('button');
        jQuery(buttons[0]).bind('mousedown', this, this.zoomIn );
        jQuery(buttons[1]).bind('mousedown', this, this.zoomOut );
	jQuery(buttons[2]).bind('mousedown', this.element, this.hide);

        var self = this;
        jQuery(this.element).find('img').first()
            .bind('dblclick', this, this.zoomIn)
            .bind('mousedown', this, this.onMousedown)
            .bind('load', function(evt){
                jQuery(self.element).find('div').css('cursor', 'default');
                self.center(evt.currentTarget);
                jQuery(evt.currentTarget).fadeTo(200,1);
            });

        jQuery(document)
            .bind( 'dragstart', function(){return false})
            .bind( 'mouseup', this, this.onMouseup)
            .bind('mousemove', this, this.move)
            .bind( 'scroll', this.element, this.scroll )

        jQuery(window)
            .bind('resize',this.element,this.resize);

        jQuery(jQuery(this.element).children().first())
            .bind('click',this.element,this.hide);

        if(jQuery.browser.msie ){
            jQuery(window).bind('scroll', this.element, this.scroll);
        }

	this.index = 1;

        this.resize({data:this.element}); // position overlay
        this.zoomOut({data:this}); // sets index, loads file
        this.center(jQuery(this.element).find('img').first()); // load event may not be triggered
    },

    onMousedown: function(evt){
        evt.data.canDrag = true;
    },

    onMouseup: function( evt ){
        evt.data.canDrag = false;
    },

    move: function(evt){
        var self = evt.data;

        if( self.canDrag ){
            if( self.pointer ){
                var delta = {
                    x: self.pointer.x - evt.clientX,
                    y: self.pointer.y - evt.clientY
                }

                var img =jQuery(self.element).find('img');

                var top = img.css('top');
                var left = img.css('left');

                img.css({
                    top: parseInt(top) - delta.y,
                    left: parseInt(left) - delta.x
                })
            }

            self.pointer = {
                x: evt.clientX,
                y: evt.clientY
            }
        }
        else{
            self.pointer = null
        }
    },

    center: function( img ){
        var width = jQuery(img).width();

        if( width > 0 ){
            var offset = {
                top: parseInt(jQuery(img).css('top')),
                left: parseInt(jQuery(img).css('left'))
            }

            var height = jQuery(img).height();

            //@todo calculate offsets and return to the focus of the viewport
            // previous zoom
            var left   = parseInt((jQuery(img).parent().width() - width)/2);//-offset.left;
            var top    = parseInt((jQuery(img).parent().height() - height)/4);//-offset.top;

            jQuery(img).css({
                top: top + 'px',
                left: left + 'px',
                margin:0
            });
        }
    },

    zoomIn: function(evt){
        var self    = evt.data;

        self.index++;

        if( self.index > self._images.length - 1 ){
            self.index = self._images.length - 1;
            return false;
	}

       var img = jQuery(self.element).find('img').first().hide();

       jQuery(self.element).find('div').css('cursor', 'wait');
       jQuery(img).attr('src', self._images[self.index]);

       self.center( img );
    },

    zoomOut: function(evt){
        var self    = evt.data;

        self.index--;

        if( self.index < 0 ){
            self.index = 0;
	    return false;
	}

       var img = jQuery(self.element).find('img').first().hide();

       jQuery(self.element).find('div').css('cursor', 'wait');
       jQuery(img).attr('src', self._images[self.index]);

       self.center( img );
    },

    hide: function(evt){
        element = evt.data;
        jQuery(document).unbind('scroll', evt.data.scroll)
        jQuery(element).remove(); //@todo recycle this HTML for the next time?
    },

    resize: function(evt){
        var element = evt.data;
        var box = jQuery(element.children()[1]);

        jQuery(element).hide()

    	var pos = {
            top: jQuery(document).scrollTop(),
            left: jQuery(document).scrollLeft(),
            width: jQuery(document).width(),
            height: jQuery(document).height(),
            viewportWidth: jQuery(window).width(),
            viewportHeight: jQuery(window).height()
        }


        jQuery(element).css({width: pos.width + 'px', height: pos.height + 'px'})


        jQuery(box).css({
            width: (pos.viewportWidth*0.6) + 'px',
            height: (pos.viewportHeight*0.8) + 'px',
            top: (pos.top+pos.viewportHeight*0.1) + 'px',
            left: (pos.left+pos.viewportWidth*0.2) + 'px'
        });


        jQuery(element).show()
    },

    scroll: function(evt){
        var element = evt.data;
        var box = jQuery(element.children()[1]);

        var pos = {
            viewportWidth: jQuery(window).width(),
            viewportHeight: jQuery(window).height(),
            top: jQuery(document).scrollTop(),
            left: jQuery(document).scrollLeft()
        }

        jQuery(box).css({
            top: (pos.top+pos.viewportHeight*0.1) + 'px',
            left: (pos.left+pos.viewportWidth*0.2) + 'px'
        })
    }


}

