//////////////////////////////////////////////////////////////////////////////////
// Cloud Zoom V1.0.2
// (c) 2010 by R Cecco. <http://www.professorcloud.com>
// MIT License
//
// Please retain this copyright header in all versions of the software
//////////////////////////////////////////////////////////////////////////////////
(function ($) {

    function format(str) {
        for (var i = 1; i < arguments.length; i++) {
            str = str.replace('%' + (i - 1), arguments[i]);
        }
        return str;
    }

    function CloudZoom(jWin, opts) {
        var img1;
        var $zoomDiv = null;
        var softFocus = null;
        var $ie6Fix = null;
        var zoomImage;
        var controlTimer = 0;
        var cw, ch;
        var destU = 0;
        var destV = 0;
        var currV = 0;
        var currU = 0;
        var mx = 0;
        var my = 0;
        
        var ctx = this;
        var zw;
        var iDevice = (/iphone|ipod|ipad|android/i).test(navigator.userAgent);


        setTimeout(function () {
            if ($zoomDiv === null) {
                var w = jWin.width();
                //MMM jWin.parent().append(format('<div style="width:%0px;position:absolute;top:75%;left:%1px;text-align:center" class="cloud-zoom-loading" >Loading...</div>', w / 3, (w / 2) - (w / 6))).find(':last').css('opacity', 0.5);
            }
        }, 200);


        var ie6FixRemove = function () {

            if ($ie6Fix !== null) {
                $ie6Fix.remove();
                $ie6Fix = null;
            }
        };

        // Removes cursor, tint layer, blur layer etc.
        this.removeBits = function () {
            ie6FixRemove();

            $('.cloud-zoom-loading', jWin.parent()).remove();
        };


        this.destroy = function () {
            jWin.data('zoom', null);

            if ($zoomDiv) {
                $zoomDiv.remove();
                $zoomDiv = null;
            }
            //ie6FixRemove();
            this.removeBits();
            // DON'T FORGET TO REMOVE JQUERY 'DATA' VALUES
        };


        // This is called when the zoom window has faded out so it can be removed.
        this.fadedOut = function () {

            if ($zoomDiv) {
                $zoomDiv.remove();
                $zoomDiv = null;
            }
            this.removeBits();
            //ie6FixRemove();
        };

        this.controlLoop = function () {

            if($zoomDiv){    
	        	var x = (mx - $zoomDiv.offset().left - (cw * 0.5)) >> 0;
	            var y = (my - $zoomDiv.offset().top - (ch * 0.5)) >> 0;                
	
	            if (x < 0) {
	                x = 0;
	            }
	            else if (x > ($zoomDiv.width() - cw)) {
	                x = ($zoomDiv.width() - cw);
	            }
	            if (y < 0) {
	                y = 0;
	            }
	            else if (y > ($zoomDiv.height() - ch)) {
	                y = ($zoomDiv.height() - ch);
	            }    
	          
	            destU = (((x) / $zoomDiv.width()) * zoomImage.width) >> 0;
	            destV = (((y) / $zoomDiv.height()) * zoomImage.height) >> 0;
	            currU += (destU - currU) / opts.smoothMove;
	            currV += (destV - currV) / opts.smoothMove;
	
	            if ($(window).width() > zoomImage.width) {
	                $zoomDiv.css('background-position', 'center ' + (-(currV >> 0) + 'px'));
	            } else {
	                $zoomDiv.css('background-position', (-(currU >> 0) + 'px ') + (-(currV >> 0) + 'px'));
	            }                            
	
	            controlTimer = setTimeout(function () {
	                ctx.controlLoop();
	            }, 30);
            }
        };


        /* Init function start.  */
        this.init = function (img) {
        	
            zoomImage = img;
            
            if (iDevice) {
                (zoomImage.width*2 > 1024) ? zoomImage.width = zoomImage.width*2 : zoomImage.width;
                (zoomImage.height*2 > 1024) ? zoomImage.height = zoomImage.height*2 : zoomImage.width;
            }        	
            // Remove loading message (if present);
        	$('.cloud-zoom-loading', jWin.parent()).remove();
        	
           
            
            $('body').css('overflow','hidden');
            
            $zoomDivOld = $('#cloud-zoom-big');
            $zoomDiv = $('<div>').attr('id','cloud-zoom-big').addClass('cloud-zoom-big').css({'display':'none','position':'fixed','left':'0','top':'50px','width':$(window).width(),'height':($(window).height()-50),'background': '#B4B3B0 url(' + zoomImage.src + ') no-repeat '/*,'webkit-background-size':'1800px 1800px'*/,'z-index':'999'});
            $close = $('<a class="zoom_close" />');
            $close.click(this.fadeOut);
            $zoomDiv.append($close);
            //$zoomDiv.data('this',this);
            $(window).resize(function() {
                $('#cloud-zoom-big').width( $(window).width() ).height( $(window).height()-50 );
            });
            
            $('body').append($zoomDiv);
            
            $zoomDiv.fadeIn(400,function(){
            	$zoomDivOld.click();
            	$('body').css('overflow','hidden');
            	$('.cloud-zoom-big-thumbs').show();
            	$('.cloud-zoom-big-thumb').removeClass('selected');
             	$('.cloud-zoom-big-thumb').hide();
            	$('.cloud-zoom-big-thumbs.sub .cloud-zoom-big-thumb[type="'+jWin.attr('type')+'"]').show();
            	$('.cloud-zoom-big-thumb[href="'+jWin.attr('href')+'"]').addClass('selected');
            	$('.cloud-zoom-big-thumbs.main .cloud-zoom-big-thumb').show();
            	if($('.cloud-zoom-big-thumbs.sub .cloud-zoom-big-thumb[type="'+jWin.attr('type')+'"]').length==1){
            		$('.cloud-zoom-big-thumbs.sub .cloud-zoom-big-thumb[type="'+jWin.attr('type')+'"]').first().hide();
            	}
            });
            
            //////////////////////////////////////////////////////////////////////          
            /* Do as little as possible in mousemove event to prevent slowdown. */
            $zoomDiv.bind('mousemove touchmove', this, function (event) {
                // Just update the mouse position
                event.preventDefault();
                (iDevice) ? mx = event.originalEvent.touches[0].pageX :  mx = event.pageX;
                (iDevice) ? my = event.originalEvent.touches[0].pageY :  my = event.pageY;

            });
            //////////////////////////////////////////////////////////////////////                  
            $zoomDiv.bind('click touchend', this, function (event) {
                                                   
                $('body').css('overflow','');
                                                   
               jWin.data('zoom', null);
    
                if ($zoomDiv) {
                    $zoomDiv.fadeOut(400, function() { $(this).remove(); });
                    $zoomDiv = null;
                }

                $('.cloud-zoom-big-thumbs').hide();
                ie6FixRemove();

            });
            $(document).bind('keydown', $zoomDiv, function (event) {
                if(event.data !=null && event.keyCode == 27)
                      event.data.trigger('click');                             

            });            
            //////////////////////////////////////////////////////////////////////
            $zoomDiv.bind('mouseenter touchstart', this, function (event) {
                                                     
                event.preventDefault();
                (iDevice) ? mx = event.originalEvent.touches[0].pageX :  mx = event.pageX;
                (iDevice) ? my = event.originalEvent.touches[0].pageY :  my = event.pageY;
                zw = event.data;

                cw = ($zoomDiv.width() / zoomImage.width) * $zoomDiv.width();
                ch = ($zoomDiv.height() / zoomImage.height) * $zoomDiv.height();
          
                //alert(sImg.outerHeight() + ';'+ sImg.outerHeight()+ ';'+zoomImage.height+ ';'+$zoomDiv.height()+ ';'+cw+ ';'+ch);
                // Attach mouse, initially invisible to prevent first frame glitch
               
                
                $zoomDiv.css('cursor', 'move');

                // Start processing. 
                zw.controlLoop();

                return; // Don't return false here otherwise opera will not detect change of the mouse pointer type.
            });
            
            this.controlLoop(true);
        };

        img1 = new Image();
        $(img1).load(function () {
            ctx.init(this);
        }).attr('src', jWin.attr('href'));
    }

    $.fn.CloudZoom = function (options) {
        
        var defaults = {
            smoothMove: 10
        };

        return this.each(function () {
                                   
                                   
            $(this).bind('click', function (event) {
                    opts = $.extend(defaults, options);
                    $(this).data('zoom', new CloudZoom($(this), opts));
                    return false;
            });
            
        });
    };

})(jQuery);// JavaScript Document
