/*jquery.lazybox
start date: 7/31/2009
ver. 1.0.0: 8/10/2009
author:Lazarevski Vladimir 
mailto: vladimir.lazarevski@adamantus.com
*/
/*jquery plugin that enables you to zoom your pictures just like a picture viewer*/
(function($){
$.fn.lazyzoom=function(o){
        
        var el=this.get(0);
        oh=_init(el,o);
        return this.each(function(){new $lz(this,oh);});
};
    var template={
            lz_lazyzoom:'lz_lazyzoom',lz_overlay:'lz_overlay',lz_window:'lz_window',lz_caption:'lz_caption',
            lz_zoom:'lz_zoom',lz_closebutton:'lz_close',lz_imageholder:'lz_imageholder'
    };
    var defaults={
        ajaxloader:'templates/kipo/images/loader.gif',
        ajaxwidth:32,
        ajaxheight:32,
        D:{width:450,height:375,chW:250,chH:20},//image dimensions,captionholderWidth,
        cXo:-29,//controls X offsest
        cYo:25,//controls Y offset
        wTo:36,//window Top offset
        wETo:15,//window Top offset from caption
        cbXo:5,//close button X offset
        cbYo:25, //close button Y offset
        hook:'#imageholder',
        zoomer:'.controls'        
    };
    var _init=function(el,o)
        {
            var o=$.extend({}, defaults, o || {});
        if ($(o.hook).length>0&&$(o.hook).get(0).tagName=='DIV')
        {
             var object={};
          
            object.hook=$(o.hook);
            o.hooked=true;
            //object.hook.css({positon:'relative',overflow:'hidden',width:o.D.width,height:o.D.height});
            if ($(o.zoomer).length>0&&$(o.zoomer).get(0).tagName=='DIV')
            {
                object.controls=$(o.zoomer);
                object.zinb=object.controls.children('a.zin').length>0?object.controls.children('a.zin'):object.controls.append("<a class='zin' href='#'></a>").children('a.zin');
                object.zoutb=object.controls.children('a.zout').length>0?object.controls.children('a.zout'):object.controls.append("<a class='zout' href='#'></a>").children('a.zout');
            }
            object.hook.html("<img src='"+o.ajaxloader+"'/>");
           
               var LZ=new $lz(el,o);
               LZ.load_image(el.href);
              
        }
        else
        {
            
        $(document.body)
        .append("<div id='lz_lazyzoom'></div>")
        .children('#lz_lazyzoom').hide()
        .append("<div id='lz_overlay'></div>")
        .append("<div id='lz_zoom' class='trans'><a href='#' class='zin'></a><a href='#' class='zout'></a></div>")
        .append("<div id='lz_close' class='trans'><a href='#' class='close roundcorners'></a></div>")
        .append("<div id='lz_caption' class='trans'></div>")
        .append("<div id='lz_window'></div>")
        .children('#lz_window')        
        .append("<div id='lz_imageholder'></div>");
        o.hooked=false;
        }
         return o;
     };
$.lazyzoom=function(e,o){
          //  alert(o.hooked);
        this.images=[];
        this.options = $.extend({}, defaults, o || {});
        this.wrapper=$("#lz_lazyzoom");this.window=$("#lz_window");
        this.ch=$("#lz_caption");
        this.close=$("#lz_close");this.overlay=$("#lz_overlay");
        this.controls=$("#lz_zoom");this.zinb=this.controls.children('a.zin');this.zoutb=this.controls.children('a.zout');
        this.caption = e.title || $(e).text() || e.href;
        var LZ=this;
        this.D={width:0,height:0,loaded:false}; //dimenziite na slikata otkoga kje se loadira
        this.cD={width:this.options.D.width,height:this.options.D.height,iszin:false,iszoot:false};
        
        this.url=e.href;
        this.el=$(e);
        
        if (this.options.hooked)
        {
            this.hook=$(this.options.hook);
            this.controls=$(this.options.zoomer);
            this.zinb=this.controls.children('a.zin');
            this.zoutb=this.controls.children('a.zout');
            this.hook.css({position:'relative',overflow:'hidden',width:this.cD.width,height:this.cD.height});
        }
        else
        {
            this.hook=$("#lz_imageholder");
        }
        //event binding
        this.close.children('a').click(function(){LZ.hideW();return false;});
        this.close.children('a').hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');});
        this.el.click(function(){LZ.load_image(LZ.url);LZ.zinb.removeClass('hover');LZ.zoutb.removeClass('hover');return false;});
    }
        var $lz=$.lazyzoom;
        $lz.fn = $lz.prototype = {lazyzoom: '1.0.1'};
        $lz.fn.extend=$lz.extend=$.extend;
$lz.fn.extend({
    get_type:function(url)
    {
        var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;var urlType = url.toLowerCase().match(urlString);
        return urlType;
    },
    load_image:function(url)
    {
        if (this.get_type(url))
        {
           var D=this.D;var img=new Image();var LZ=this;
           
         if ($.browser.opera) {window.onunload=function(){};} 
//back/forward button fix (also opera wasnt firing the image when loading from cache, this solves the problem)
        //nemam pojma zasho koristam browser iako e preporacano da ne se koriste, ama ednostavno tava nema vrska
         img.onload=function(){LZ.addimage(LZ,this,url);};
         img.src=url;    
        }
     return D;  
    },
    preload:function(){
       this.hook.html("<img src='"+this.options.ajaxloader+"' />");
       this.position(true);
       if (!this.options.hooked) {
           this.ch.hide();
       this.controls.hide();
       this.close.hide();
           this.wrapper.show();
           this.window.show();
       }
      
    },
    addimage:function(LZ,img,url)
    {
        LZ.D.width=img.width;
        LZ.D.height=img.height;
        LZ.D.loaded=true;
        LZ.hook.html("<img src='"+url+"' style='width:"+LZ.cD.width+"px;height:"+LZ.cD.height+"px'/>");
        LZ.zimg=LZ.hook.children('img');
        LZ.zimg.css({'msInterpolationMode':"bicubic",width:LZ.options.D.width,height:LZ.options.D.height,position:'relative','z-index':951});
             //odredi pozicii
              LZ.position();
      if (!LZ.options.hooked)
      {
         LZ.wrapper.show();LZ.ch.html(LZ.caption);LZ.ch.show();LZ.close.show();LZ.controls.show();LZ.window.show();             }
      else
      {
                // LZ.window.hide();LZ.wrapper.show();LZ.controls.show();
      }
              //dodadi listeneri
              //iskluci go desniot klik vrz slikata
      LZ.hook.bind("contextmenu",function(e){return false;});
      LZ.zimg.bind("mousedown",{D:LZ.D,LZ:LZ},LZ._keydown);
      LZ.zinb.bind("click",{LZ:LZ},LZ._zint);
      LZ.zoutb.bind("click",{LZ:LZ},LZ._zoutt);
      $(document).bind("keydown",{LZ:LZ},LZ._dokeydown);
    },
    _dokeydown:function(e){
          e=e?e:window.event;
          a=e.altKey,s=e.shiftKey;
          if (s&&!a){e.data.LZ.cur_zoom(1,e.data.LZ.B,$(e.data.LZ.zimg));}else if (!s&&a) {e.data.LZ.cur_zoom(2,e.data.LZ.B,$(e.data.LZ.zimg));}
    },
    _mouseover:function(e){
        e=e?e:window.event;
        var code = (e.keyCode ? e.keyCode : e.which),a=e.altKey,s=e.shiftKey;
    },
    _keydown:function(e){
        var LZ=e.data.LZ;
        var D=e.data.D;
     
        var zimg=this;
        e=e?e:window.event;
        var code = (e.keyCode ? e.keyCode : e.which),a=e.altKey,s=e.shiftKey;
        var bzi=s&&!a?true:LZ.cD.iszin&&!a?true:false;
        var bzo=!s&&a?true:LZ.cD.iszoot&&!s?true:false;
        var curLeft=LZ.intval($(zimg).css('left')),curTop=LZ.intval($(zimg).css('top'));
        var mouseStartPos={startLeft:e.pageX-$(zimg).parent().offset().left,startTop:e.pageY-$(zimg).parent().offset().top};
       if (e.preventDefault){e.preventDefault();document.ondragstart=function(e){return false;}}
      if (bzi){LZ.zoom(zimg,D,mouseStartPos,true);LZ.cur_zoom(1,LZ.B,$(zimg));} else if (bzo) {LZ.zoom(zimg,D,mouseStartPos,false);LZ.cur_zoom(2,LZ.B,$(zimg));}else
       {
            var moveHandler=function(e){
                var dragLeft=e.pageX-$(zimg).parent().offset().left-mouseStartPos.startLeft,dragTop=e.pageY-$(zimg).parent().offset().top-mouseStartPos.startTop;
                var newcords=LZ.boundaries({left:curLeft+dragLeft,top:curTop+dragTop},LZ.cD);
                $(zimg).css({left:newcords.left,top:newcords.top});LZ.cur_zoom(0,LZ.B,$(zimg));
            };
            var upHandler=function(e){
                $(zimg).unbind("mousemove",moveHandler);$(zimg).unbind("mouseup",upHandler);
            };
                $(zimg).mousemove(moveHandler);$(zimg).mouseup(upHandler);$(zimg).mouseout(upHandler);
       }
    },
    cur_zoom:function(ac,browser,img)
    {
       if (ac==1)
       {img.removeClass('cur_zoomout').addClass('cur_zoomin');}
       else if (ac==2)
       {img.removeClass('cur_zoomin').addClass('cur_zoomout');}
       else
       {img.removeClass('cur_zoomin').removeClass('cur_zoomout');}
    },
    _zint:function(e)
    {   var LZ=e.data.LZ;
        
        LZ.cD.iszin=!LZ.cD.iszin;LZ.cD.iszoot=false;
        LZ.cD.iszin?LZ.cur_zoom(1,LZ.B,LZ.zimg):LZ.cur_zoom(0,LZ.B,LZ.zimg);
        $(this).hasClass('hover')?$(this).removeClass('hover'):$(this).addClass('hover');
        LZ.zoutb.removeClass('hover');
        return false;
    },
    _zoutt:function(e)
    {   
        var LZ=e.data.LZ;
        LZ.cD.iszoot=!LZ.cD.iszoot;LZ.cD.iszin=false;
        LZ.cD.iszoot?LZ.cur_zoom(2,LZ.B,LZ.zimg):LZ.cur_zoom(0,LZ.B,LZ.zimg);
        $(this).hasClass('hover')?$(this).removeClass('hover'):$(this).addClass('hover');
        LZ.zinb.removeClass('hover');
        return false;
    },
    zoom:function(zimg,dim,mouseclick,inout){
        //dim se originalnite dimenzii na slikata; this.cD e momentalnite dimenzii na slikata
       var cof=(inout?1.1:1/1.1);
       var cd=this.cD;
       var od=this.options.D;
       //od.width=od.width;
       //od.height=od.height;
       $('#footer').html('current width:'+od.width+' current height:'+od.height)
       var im_offset={left:$(zimg).css('left'),top:$(zimg).css('top')};
       cd.width=(dim.width>cd.width*cof?cd.width*cof>od.width?Math.round(cd.width*cof):od.width:dim.width);
      
       cd.height=(dim.height>cd.height*cof?cd.height*cof>od.height?Math.round(cd.height*cof):od.height:dim.height);
       $('#footer').append('current width:'+cd.width+' current height:'+cd.height);
       var z_offset=this.boundaries({left:(od.width/2)-mouseclick.startLeft+this.intval(im_offset.left),top:(od.height/2)-mouseclick.startTop+this.intval(im_offset.top)},cd);
       $(zimg).css({width:cd.width,height:cd.height,left:z_offset.left,top:z_offset.top});
    },
    intval: function(v) {
        v = parseInt(v);
        return isNaN(v) ? 0 : v;
    },

    show:function(win,cont,close,caphead){
        
          LZ.wrapper.show();
          LZ.ch.html(LZ.caption);
          
          LZ.ch.show();
          LZ.close.show();
          LZ.controls.show();     
    },
    hideW:function(){
        this.cD.width=this.options.D.width;this.cD.height=this.options.D.height;this.cD.iszin=false;this.cD.iszoot=false;
        this.zinb.removeClass('hover');this.zoutb.removeClass('hover');
        this.wrapper.hide();
    },
    position:function(pre){
     var pos=this.viewport();
     var O=this.options;
     if (!O.hooked)
     {
     var imgWidth=O.D.width>0?pre?32:O.D.width:250;
     var imgHeight=O.D.height>0?pre?32:O.D.height:375;
     this.window.css({width:(imgWidth),height:(imgHeight),left: ((pos.cx - imgWidth)/2),top:(pos.y+O.wTo)});
     this.controls.css({left:((pos.cx-imgWidth)/2)+O.cXo,top:(pos.y+O.cYo+O.D.chH+O.wTo+imgHeight/2)});
     this.close.css({left:((pos.cx+imgWidth)/2)+O.cbXo,top:pos.y+O.wTo});
     this.ch.css({width:O.D.width-7,height:O.D.chH,left:((pos.cx-imgWidth)/2)+3,top:pos.y+O.wTo+3});
     }
     else
     {
        //$('#status5').html('left:'+this.hook.offset().left+' Top:'+this.hook.offset().top);
        this.controls.css({left:this.hook.offset().left,top:this.hook.offset().top});
     }
   },
   boundaries:function(newcords,D){
        var rightbound=D.width>this.options.D.width?(D.width-this.options.D.width)*(-1):0;
        var bottombound=D.height>this.options.D.height?(D.height-this.options.D.height)*(-1):0;
        if (newcords.left>0) newcords.left=0;
        if (newcords.left<rightbound) newcords.left=rightbound;
        if (newcords.top>0) newcords.top=0;
        if (newcords.top<bottombound) newcords.top=bottombound;
        return newcords;
    },
    viewport:function(){
        return {
            x: $(window).scrollLeft(),
            y: $(window).scrollTop(),
            cx: $(window).width(),
            cy: $(window).height()
        };
  }
});
})(jQuery);
