//-------------------------------------------------------------------------------------------
//
//                   JQUERY  MAGNIFY ZOOM image
//
//   Это простой плагин для увеличения изображений с эффектом лупы.
//  This is a simple plugin to zoom the image with  effect of magnifying glass.
//  Autor: Dream_LOKO
//
// -----------------------------------------------------------------------------------------


jQuery.fn.simplezoom = function( options ) {
var settings = {
		lensWidth: 100,
		lensHeight: 100,
		stageCss: {},
		jcarouselId:'#jcarousel',
		lensCss: {}
	 };
	
options ? jQuery.extend( settings, options ) : null; 

return this.each(function() {



var a = jQuery(this);
var img=$(this).find("img");
var mousepos={};
var normalImageData={};
var bigImageData={};
var lensdata={};
lensdata.w=100;
lensdata.h=100;
var scale = {};
var bigimgloaded=false;
var loadmesshow=false;
var stageDivSize={};
// after end, delete this variable
var time = new Date()
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
var bleft=0;
var btop=0;
var reloadimage=img[0].src;

run=false;
// --------------------------- interaction with jcarousel ---------------------------------------
$('#load_big_img').live('click', function(){
      //alert($(this).attr('alt')+'    '+$('.zoom').find('img').attr('src'));
     if ( $(this).attr('alt')!=$('.zoom').find('img').attr('src')) {
              // // $('#alert-msg').append('<br />load new image!!!!!'+settings.jcarouselId+$(this).attr('alt'));
              if (run) {deactivate();};
              a.unbind('mouseover');
              normalImage();
              $('body').append('<div id="loadingDiv">Loading ...</div>');
              $('#loadingDiv').addClass('loadingDiv');
              $('#loadingDiv').css({left:(normalImageData.pos.l+normalImageData.w/2-40)+'px',
                                    top:(normalImageData.pos.t+normalImageData.h/2-11)+'px'
                                    });
              $('#loadingDiv').fadeIn(200);
              $('.zoom').find('img').load (function(){
                             $('#loadingDiv').remove(); 
                            bigimgloaded=true; 
                            a.bind('mouseover',function(e){ activate(e)});
                            firsttime=false;
                           //  alert('loaded!'); 
                             });
             };
    $('.zoom').attr('href','http://www.musthavebags.ru/published/publicdata/U170651/attachments/SC/products_pictures/'+$(this).attr('alt'));
    $('.zoom').find('img').attr('src','http://www.musthavebags.ru/published/publicdata/U170651/attachments/SC/products_pictures/'+$(this).attr('alt'));
    });
// ------------------ bind   activate zoom ---------------------------------------------------
//a.hover(function(e){activate(e);},function(){});
a.bind('mouseover',function(e){ activate(e)});
//a.bind('mouseout',function(e){ outimg=true;});
  a.bind('mouseout',function(e){  // $('#alert-msg').append('<br />out img');
  //if (!run) {deactivate(e)};
  }); 
  
// -------------------------- ACTIVATE function ------------------------------------------  
         
function activate (e) {
    a.unbind('mouseover');
    run=true;
    firsttime=false;
  
    	//ritorna false al click dell href
			$(a).click(function(){return false;});
    lensdata.w=100;
    lensdata.h=100;

     // $('#alert-msg').append('<br />run activate');
    //$(img).css('border','0');
    
      Stage();//create stage html
    normalImage(); //get normal image size and position
     Lens(); //create lens html
    bigImage(); //get big image size and position
    //scale.x=normalImageData.w/100;
    //scale.y=normalImageData.h/100;
    //$('#lensDiv').bind('mouseout',function(e){ deactivate(e)});
   
		mousepos.x = e.pageX;
		mousepos.y	= e.pageY;
		  // $('#alert-msg').append('<br />Normal Image: w-'+normalImageData.w);
		$('body').mousemove(function(e){handleMouseMove2(e);});
    a.bind('mousemove',function(e) { ;handleMouseMove(e);});
    $('#lensDiv').bind('mousemove',function(e) { handleMouseMove(e);});
    $('#lensDiv').bind('mouseout',function(e) {
        
        
     // $('#alert-msg').append('<br />out lens'+normalImageData.pos.l+''+mousepos.x);

    });
    
    };

function deactivate (e) {
   $('#lensDiv').remove();
    $('#stageDiv').remove();
    $('img#BigImg').remove();
    a.unbind('mousemove');
    img.unbind('mousemove');
    $('#lensDiv').unbind('mousemove');
    $('div#loadedDiv').remove();
    run=false;
     // $('#alert-msg').append('<br />deactivate');
    
    
    } ;

// ---------------------- CREATE LENS ----------------------------------------------
function Lens() {
    $('body').append("<div id='lensDiv'></div>");
    $('#lensDiv').addClass('lensDiv');
    var left=normalImageData.pos.l+normalImageData.w/2-lensdata.w/2;
    var top=normalImageData.pos.t+normalImageData.h/2-lensdata.h/2;
    // // $('#alert-msg').append('<br />aaaaaa'+top+left);
   // $('#lensDiv').css('display','none');
     //$('#lensDiv').fadeIn(100);
    $('#lensDiv').css({left:left+'px',top:top+'px'});
    $('#lensDiv').css('display','none');
   // showLoadMsg;
    //$('#lensDiv').css('position','absolute');
    };
// ---------------------- CREATE Stage ----------------------------------------------
function Stage() {
     $('body').append("<div id='stageDiv'></div>");
    //stageDiv =document.body.appendChild('div');
    //stageDiv.attr('id','stageDiv');
    $('#stageDiv').addClass('stageDiv');
    //  ratio resize  lensDiv --------------------------------------
    stageDivSize.w=parseInt($('#stageDiv').css('width'));
    stageDivSize.h=parseInt($('#stageDiv').css('height'));
    $('#stageDiv').css('display','block');
  //  var ratio2=stageDivSize.w/stageDivSize.h;
    // $('#alert-msg').append('<br />stage size'+stageDivSize.w+' '+stageDivSize.h+' '); 
    //if (stageDivSize.w>stageDivSize.h) {lensdata.h=parseInt(lensdata.h/ratio2);} 
   /// else if (stageDivSize.w<stageDivSize.h) {lensdata.w=parseInt(lensdata.w*ratio2);} ;
    //  // $('#alert-msg').append('<br />lens size'+lensdata.w+' '+lensdata.h);
     // save ratio from lensdiv
     // $('#lensDiv').css('width',lensdata.w+'px').css('height',lensdata.h+'px');
      
    
    };


     
      //return {x:x, y:y};
// ---------------------------- GLOBAL MOUSE MOVE EVENT ------------------------------------
function handleMouseMove2(e){
    mousepos.x=e.pageX;
    mousepos.y=e.pageY;
    //$('#showXY2').text('x:'+mousepos.x+' y:'+mousepos.y);
    if (run){
    if ((mousepos.x<normalImageData.pos.l)||(mousepos.x>(normalImageData.pos.l+normalImageData.w+2))) {
          deactivate(e);
          run=false;
          a.bind('mouseover',function(e){activate(e)});
          $('body').unbind('mousemove');
          };
    if ((mousepos.y<normalImageData.pos.t)||(mousepos.y>(normalImageData.pos.t+normalImageData.h+2))) {
          deactivate(e);
          run=false;
          a.bind('mouseover',function(e){activate(e)});
          $('body').unbind('mousemove');
          };    
    };	
}
// ---------------------- MOUSE MOVE EVENT ------------------------------------------
function handleMouseMove(e){
  if ($('#lensDiv').css('display')=='none') $('#lensDiv').css('display','block');
    if (bigimgloaded==false) {
        // // $('#alert-msg').append('<br />mouse loaded false:'+e.pageX+' '+lensdata.h);
        lensdata.w=100;
        lensdata.h=100;
        
         if (!loadmesshow) {showLoadMsg();};
        }
    else {};

     //mousepos.x=e.pageX;
    //mousepos.y=e.pageY;
    var leftpos=e.pageX-lensdata.w/2;
    var toppos=e.pageY-lensdata.h/2;
    realwidth =  parseInt($('#lensDiv').css('width')) 
								+ parseInt($('#lensDiv').css('border-left-width')) 
								+ parseInt($('#lensDiv').css('border-right-width')) ;
		realheight = parseInt($('#lensDiv').css('height')) 
								+ parseInt($('#lensDiv').css('border-top-width'))
								+ parseInt($('#lensDiv').css('border-bottom-width'));
		bleft=realwidth-lensdata.w;
		btop=realheight-lensdata.h;
		 // $('#alert-msg').append('<br />lens size:'+e.pageX+lensdata.w+' '+lensdata.h+'b'+scale.x);
   
    // side and corner -----------------------------------------------
    if ((leftpos)<normalImageData.pos.l+bleft) {
        leftpos=normalImageData.pos.l;
        // // $('#alert-msg').append('<br />NIM left '+normalImageData.pos.l);
        }
    if (toppos<normalImageData.pos.t+btop) {
        toppos=normalImageData.pos.t;
        // // $('#alert-msg').append('<br />NIM top '+normalImageData.pos.t);
        }
    if (leftpos>(normalImageData.pos.l+normalImageData.w-lensdata.w-bleft)) {
        leftpos=normalImageData.pos.l+normalImageData.w-lensdata.w-bleft;
        // // $('#alert-msg').append('<br />NIM right '+(normalImageData.pos.l+normalImageData.w));
        }
    if (toppos>(normalImageData.pos.t+normalImageData.h-lensdata.h-btop)) {
        toppos=normalImageData.pos.t+normalImageData.h-lensdata.h-btop;
        // // $('#alert-msg').append('<br />NIM bottom '+(normalImageData.pos.t+normalImageData.h));
        } 
    
          
    // render ---------------------------------------------
    leftpos = parseInt(leftpos);
		toppos = parseInt(toppos);

		//$('#showXY').text('x:'+leftpos+' y:'+toppos);
    $('#lensDiv').css({left:leftpos+'px',top:toppos+'px'});	
    bigImageSetPos();
   // bigImageSetPos();
    // // $('#alert-msg').append('<br />mouse'+realwidth+' '+e.pageX+' '+lensdata.h);

    //if (!bigimgloaded) { showLoadMsg();};
    
    };
// ------------------------- get OFFSET LENS FROM NORMALIMAGE ------------------------------------
function lensGetOffset() {
			var o = {};
			o.left = (parseInt($('div#lensDiv').css('left')) - parseInt(normalImageData.pos.left));
			o.top =  parseInt($('div#lensDiv').css('top'))  - parseInt(normalImageData.pos.top) ;
			 // $('#alert-msg').append('<br />offset '+	o.left+' '+	o.top+' '+$('div#lensDiv').css('top'));
			return o;
		};
		
// -----------------------  function MOVE BIG IMAGE ------------------------------------------------
 function bigImageSetPos() {
      // // $('#alert-msg').append('<br />Offset '+ lensGetOffset().left+' '+lensGetOffset().top);
			$('img#BigImg').css('left',  Math.ceil( -scale.x * parseInt(lensGetOffset().left)) + 'px');
			$('img#BigImg').css('top', Math.ceil( -scale.y * parseInt(lensGetOffset().top)) + 'px');
		};
// --------------------------- show message LOADED... ----------------------------------
 function showLoadMsg() {
        loadmesshow=true;
        $('body').append('<div id="loadedDiv">Loading...</div>');
        $('div#loadedDiv').addClass('loadedDiv');
        var l=parseInt($('div#stageDiv').css('left'))+20+'px';
        var t=parseInt($('div#stageDiv').css('top'))+20+'px';
          // $('#alert-msg').append('<br />load message show  l='+l+' t'+t+' time'+h+':'+':'+m+':'+s);
        $('div#loadedDiv').css('left',l);
        $('div#loadedDiv').css('top',t); 
        $('div#loadedDiv').show(); 
       // return this; 
 };
// ---------------------- NORMAL IMAGE MODEL ------------------------------------------
function normalImage(){
    //var imag = new Image();
    
    //imag.src = img[0].src;
 // // $('#alert-msg').append('<br />NIM load h='+imag.src);
    //normalImageData.w=imag.style.width;
    //normalImageData.h=imag.style.height;
    //imag.onload= function() {
       normalImageData.w = $(img).width();
        normalImageData.h = $(img ).height();
         // $('#alert-msg').append('<br />NIM size '+normalImageData.w+' '+normalImageData.h);
      
    		normalImageData.pos = $( img).offset();
    		normalImageData.pos.l = $(img).offset().left;
    		normalImageData.pos.t = $(img).offset().top;
    		normalImageData.pos.r = normalImageData.w + normalImageData.pos.l;
    		normalImageData.pos.b = normalImageData.h + normalImageData.pos.t;
         // $('#alert-msg').append('<br />NIM left w '+normalImageData.pos.t+' '+normalImageData.pos.l+' '+normalImageData.w);
       // };
   
    
    };
// ---------------------- BIG IMAGE MODEL ------------------------------------------
function bigImage(){
   if (a[0].href!=img[0].src) {
    var bigimag = new Image();
  /*  if (a[0].href!=img[0].src) {*/
   
    $(bigimag).load(function(){
     bigimgloaded=true; 
     if (loadmesshow) {loadmesshow=false; };
     $(bigimag).css('display','block');
     $('#stageDiv').fadeIn(300);
    //bigimag.style.display = 'block';
      // bigImageData.w = bigimag.width;
        //bigImageData.h = bigimag.height;
        bigImageData.w = $(bigimag).width();
        bigImageData.h = $(bigimag).height();
//bigimag.style.display = 'none';
         scale.x=bigImageData.w/(normalImageData.w);
         scale.y=bigImageData.h/(normalImageData.h);
         lensdata.w=parseInt(normalImageData.w/(bigImageData.w/stageDivSize.w));
         lensdata.h=parseInt(normalImageData.h/(bigImageData.h/stageDivSize.h));
         //lensdata.w=100;
         //lensdata.h=100;
          $('#lensDiv').css('width',lensdata.w+'px').css('height',lensdata.h+'px');
         // $('#alert-msg').append('<br /> scale '+bigimag.height+scale.x+' '+scale.y);
        // $('#alert-msg').append('<br />BIGIM loaded 2 '+bigImageData.w+' '+bigImageData.h+'<br />new lens size '+stageDivSize.w+lensdata.w+' '+lensdata.h);
      
       

      // $('#alert-msg').append('<br />load message hide  time'+h+':'+':'+m+':'+s);
      //$('div#loadedDiv').remove();  
      loadmesshow=false;
      bigimgloaded=true; 
      $('div#loadedDiv').hide();
      
    });
    
 /*   } else {
          $('body').append('<img id="1url2img" src="'+a[0].href+'">');
          $('#1url2img').css({
                position:'absolute',
                left:'-500000px',
                display:'block',
                overflow:'visible'
                });
           bigImageData.w = parseInt($('#1url2img').css('width'));
          bigImageData.h = parseInt($('#1url2img').css('height'));
          $('#1url2img').remove();
          scale.x=bigImageData.w/(normalImageData.w);
         scale.y=bigImageData.h/(normalImageData.h);
         lensdata.w=parseInt(normalImageData.w/(bigImageData.w/stageDivSize.w));
         lensdata.h=parseInt(normalImageData.h/(bigImageData.h/stageDivSize.h));
         $('#lensDiv').css('width',lensdata.w+'px').css('height',lensdata.h+'px');
           // $('#alert-msg').append('<br />loaded  url'+scale.y+bigImageData.w+' '+bigImageData.h);
           
      $('div#loadedDiv').hide();
       bigimgloaded=true; 
     if (loadmesshow) {loadmesshow=false; };
     $(bigimag).css('display','block');
     $('#stageDiv').fadeIn(300);
          };*/
    bigimag.src = a[0].href;
    //loadmessage();
    $('div#stageDiv').append( bigimag );
    bigimag.style.position = 'absolute';
		bigimag.style.display = 'none';
		bigimag.style.left = '-5000px';
		bigimag.style.top = '10px';
		$(bigimag).attr('id','BigImg');
		
   // $('#alert-msg').append('<br />loaded 2 url'+a[0].href+' '+img[0].src); 
  // $('#alert-msg').append('<br />BIGIM load h='+bigimag.src+' time'+h+':'+':'+m+':'+s);
    //bigImageData.w=imag.style.width;
    //bigImageData.h=imag.style.height;
 //   bigimag.onload= function() {
 
   //    };
     
    }else {
          
  
          $('div#stageDiv').append('<img id="BigImg" src="'+a[0].href+'">');
          $('#BigImg').css({
                position:'absolute',
                left:'-500000px',
                top:'10px',
                display:'block'
                
                });
                 // $('#alert-msg').append('<br />BIGIM aaaaaa');
           bigImageData.w = parseInt($('#BigImg').width());
          bigImageData.h = parseInt($('#BigImg').height());
    
          scale.x=bigImageData.w/(normalImageData.w);
         scale.y=bigImageData.h/(normalImageData.h);
         lensdata.w=parseInt(normalImageData.w/(bigImageData.w/stageDivSize.w));
         lensdata.h=parseInt(normalImageData.h/(bigImageData.h/stageDivSize.h));
         $('#lensDiv').css('width',lensdata.w+'px').css('height',lensdata.h+'px');
           // $('#alert-msg').append('<br />loaded 1 url'+scale.y+bigImageData.w+' '+bigImageData.h);
           
      $('div#loadedDiv').hide();
       bigimgloaded=true; 
     if (loadmesshow) {loadmesshow=false; };
     $('#BigImg').css('display','block');
     $('#stageDiv').fadeIn(300);
          };
    };
});
}