/*
  Matthieu Follet 
  http://www.mozaik.com.mx
  Leave my name and link please
*/
onDomReady(function(){
  var light = new LightBox;
  light.initialize({lightBackOpacity:'0.7'});
});

function LightBox(){

  var current;
  
  this.options = {
    context:document,
    loadingSrc:'images/lightbox/loading.gif',
    leftBotton:'images/lightbox/left.gif',
    rightBotton:'images/lightbox/right.gif',
    closeBotton:'images/lightbox/close.gif',
    lightBackOpacity:'0.65'
  };
  
  this.initialize = function(options){
    for(var property in options)this.options[property] = options[property];
    this.lightElements = $el(this.options.context,'a.lightbox');
    this.lightElements.forEach(function(fnc){
      return function(item,index){
        addEvent(item,'click',function(event,fnc){
          stopEvent(event);
          current = index;
          fnc.setLightBack();
          fnc.showLoading();
          fnc.getImg(this);
        },fnc);
      }
    }(this))

  };
  
  this.getImg = function(el){
    var srcWidth,srcHeight;
    if(span = $el(el,'span.lightbox_src')[0]){
      var srcImg = span.firstChild.nodeValue;
      var reg = /\(([0-9\.]*)\-([0-9\.]*)\)$/;
      var hasSize;
      if(hasSize = srcImg.match(reg)){
        srcImg = srcImg.replace(reg,'');
        srcWidth = parseInt(hasSize[1]);
        srcHeight = parseInt(hasSize[2]);
      }
    }else 
      var srcImg = el.href;

    var altText = ($el(el,'img')[0])? $el(el,'img')[0].alt : '';
    if(srcWidth && srcHeight) this.showImg(srcImg,el.title,altText,srcWidth,srcHeight);
    else this.showImg(srcImg,el.title,altText);
  };
  
  this.setLightBack = function(){
    if(!this.lightBack){
      this.lightBack = addElement('div',{
        styles:{'position':'absolute','top':'0','left':'0','backgroundColor':'#000','zIndex':'10','width':'100%'},
        opacity:this.options.lightBackOpacity
      });
      $css("body")[0].insertBefore(this.lightBack, $css("body")[0].firstChild);
      this.lightBack.style.height = Window.scrollHeight()+'px';
      addEvent(this.lightBack,'click',function(event,fnc){
        fnc.lightBox.style.display = 'none';
        fnc.lightBack.style.display = 'none';
        fnc.closeImg();
        fnc.opened = false;
      },this);
    }else{
      this.lightBack.style.display = 'block';
    }
  };
  
  this.imgLeft = function(){
    current = (current-1 < 0)? (this.lightElements.length)-1 : current-1;
    this.showLoading(true);
    this.getImg(this.lightElements[current]);
  };
  
  this.imgRight = function(){
    current = (this.lightElements[current+1])? current+1 : 0;
    this.showLoading(true);
    this.getImg(this.lightElements[current]);
  };
  
  this.closeImg = function(){
    this.lightBottom.style.display = 'none';
    this.lightRight.style.display = 'none';
    this.lightLeft.style.display = 'none';
    this.boxImg.removeChild(this.objImg);
    this.lightBox.removeChild(this.boxImg);
    this.lightBox.removeChild(this.lightDesc);
  };
  
  this.setLightBox = function(widthBox,heightBox,heightBottom){
    totalHeight = heightBox+heightBottom;
    if(!this.lightBottom){
      this.lightBottom = addElement('img',{
        'id':'light_bottom',
        'src':this.options.closeBotton,
        'styles':{'display':'none','cursor':'pointer','position':'absolute','top':'0','right':'0','zIndex':'100'}
      });
      this.lightBox.appendChild(this.lightBottom);
      addEvent(this.lightBottom,'click',function(event,fnc){
        fnc.lightBox.style.display = 'none';
        fnc.lightBack.style.display = 'none';
        fnc.closeImg();
        fnc.opened = false;
      },this);
      this.lightLeft = addElement('img',{
        'id':'light_left',
        'src':this.options.leftBotton,
        'styles':{'display':'none','cursor':'pointer','position':'absolute','top':(totalHeight/2)+'px','left':'-30px'}
      });
      addEvent(this.lightLeft,'click',function(event,fnc){
        fnc.closeImg();
        fnc.imgLeft(); 
      },this);
      this.lightBox.appendChild(this.lightLeft);
      this.lightRight = addElement('img',{
        'id':'light_right',
        'src':this.options.rightBotton,
        'styles':{'display':'none','cursor':'pointer','position':'absolute','top':(totalHeight/2)+'px','right':'-30px'}
      });
      addEvent(this.lightRight,'click',function(event,fnc){
        fnc.closeImg();
        fnc.imgRight();   
      },this);
      this.lightBox.appendChild(this.lightRight);
      addEvent(document,'keydown',function(e,fnc){
        if(e.which==37){
          fnc.closeImg();
          fnc.imgLeft();
        }
        if(e.which==39){
          fnc.closeImg();
          fnc.imgRight();
        }
      },this);
    }

    var top = this.lightBox.offsetTop;
    var left = this.lightBox.offsetLeft;

    var middleY = Math.round(this.height/2);
    var middleX = Math.round(this.width/2);
    
    var boxY = Math.round(totalHeight/2);
    var boxX = Math.round(widthBox/2);
    
    var topPos = (top+(middleY)-(boxY));
    var leftPos = left+(middleX)-(boxX);
    
    var paddingTop = middleY-boxY;
    var paddingLeft = middleX-boxX;
    
    var winX = Window.width(),winY = Window.height();
    var scrollX = Window.scrollLeft(),scrollY = Window.scrollTop()
    var addY = (Math.round((winY-((topPos*2)+heightBox))/2))+scrollY;
    var addX = (Math.round((winX-((leftPos*2)+widthBox))/2))+scrollX;

    topPos = topPos+addY-10;
    paddingTop = paddingTop+addY-10;

    leftPos = leftPos+addX;
    paddingLeft = paddingLeft+addX;

    if( topPos < 10 || winY < heightBox+30){
      var aY = (winY < totalHeight+30)? winY-(totalHeight+20) : 10;
      aY = (aY<0)? 0 : aY;
      paddingTop = paddingTop-topPos+aY+scrollY;
      topPos = aY+scrollY;
    }
    
    if( leftPos < 30 || winX < widthBox){
      paddingLeft = paddingLeft-leftPos+30+scrollX;
      leftPos = 30+scrollX;
    } 
    //alert(this.boxImg.offsetHeight+' - '+heightBox);
    var fx = new Fx();
    fx.initialize([this.lightBox,this.objImg],{duration:500,curve:['cos']});
    fx.start({
      0:{
        'top':[top,topPos],
        'left':[left,leftPos],
        'width':[this.width,widthBox],
        'height':[this.height,totalHeight]
      },
      1:{
        'top':[paddingTop,0],
        'left':[paddingLeft,0],
        'opacity':[0,1]
      }
    },function(fnc){
      return function(){
        fnc.lightBox.style.overflow = 'visible';
        fnc.showNav(heightBox);
      }
    }(this));
    
  };
  
  this.showNav = function(heightBox){
    var imgHeight = this.objImg.offsetHeight;
    this.boxImg.style.height = imgHeight+'px';
    this.lightBottom.style.top = (imgHeight+5)+'px';

    setOpacity(this.lightBottom,0);
    setOpacity(this.lightDesc,0);
    setOpacity(this.lightLeft,0);
    setOpacity(this.lightRight,0);
      
    this.lightBottom.style.display='block';
    this.lightDesc.style.visibility='visible';

    this.lightLeft.style.top = (heightBox/2)+'px';
    this.lightRight.style.top = (heightBox/2)+'px';
    
    if(this.lightElements.length > 1){
      this.lightLeft.style.display = 'block';
      this.lightRight.style.display = 'block';
    }
    
    var fx = new Fx();
    fx.initialize([this.lightBottom,this.lightDesc,this.lightLeft,this.lightRight],{duration:300,curve:['linear']});
    fx.start({
      0:{'opacity':[0,1]},
      1:{'opacity':[0,1]},
      2:{'opacity':[0,1]},
      3:{'opacity':[0,1]}
    });
  };
   
  this.centerObj = function(obj,width,height){
    if(!width) width = obj.offsetHeight;
    if(!height) height = obj.offsetHeight;
    var winX = Window.width(),winY = Window.height();
    var topPos = ((winY - height)>0)? (winY - height) : 10;
    var leftPos = ((winX - width)>0)? (winX - width) : 10;
    obj.style.top = (topPos/2)+Window.scrollTop() + 'px';
    obj.style.left = (leftPos/2)+Window.scrollLeft() + 'px';		
    obj.style.visibility='visible';
  };

  
  this.showLoading = function(resize){
    if(!this.lightBox){
      this.lightBox = addElement('div',{
        'id':'light_box',
        'styles':{'position':'absolute','visibility':'hidden','backgroundColor':'#FFFFFF',
        'width':'150px','height':'150px','zIndex':'90',
        'borderWidth':'8px','borderColor':'#FFFFFF','borderStyle':'solid'}
      });
      $css("body")[0].insertBefore(this.lightBox, $css("body")[0].firstChild);
      this.centerObj(this.lightBox,150,150);
      this.width = 150;
      this.height = 150;
    }else{

      if(resize){
        this.resize = true;
        setStyles(this.lightBox,{'display':'block'});
        this.width = this.lightBox.offsetWidth-16;
        this.height = this.lightBox.offsetHeight-16;
      }else{
        this.width = 150;
        this.height = 150;
        setStyles(this.lightBox,{'display':'block','width':'150px','height':'150px'});
        this.centerObj(this.lightBox,150,150);
      }
    }
    
    if(!this.loading){
      this.loading = addElement('img',{
        'id':'light_loading','src':this.options.loadingSrc,
        'styles':{'visibility':'hidden','position':'absolute','zIndex':'100'}
      });
      this.lightBox.appendChild(this.loading);
      this.loading.src = this.options.loadingSrc;
  
      var imagesLoading=new Image();
      addEvent(imagesLoading,'load',function(event,fnc){
        setTimeout(function(fnc){   
          return function(){
            fnc.loading.style.top = ((fnc.height-fnc.loading.offsetHeight)/2)+'px';
            fnc.loading.style.left = ((fnc.width-fnc.loading.offsetWidth)/2)+'px';		
            fnc.loading.style.visibility='visible';
          }
        }(fnc),100);         
      },this);
      imagesLoading.src = this.options.loadingSrc;
    }else{
      this.loading.style.visibility='hidden';
      this.loading.style.display = 'block';
      this.loading.style.top = ((this.height-this.loading.offsetHeight)/2)+'px';
      this.loading.style.left = ((this.width-this.loading.offsetWidth)/2)+'px';		
      this.loading.style.visibility='visible';
    }
    
  };

  this.setImg = function(srcPhoto,titlePhoto,descPhoto,width,height){
    
    //var boxHeight = (height)? height+'px' : '100%';
    this.boxImg = addElement('div',{
      'styles':{'position':'relative','overflow':'hidden','height':'100%'}
    });
    this.objImg = addElement('img',{'opacity':0,'src':srcPhoto,'styles':{'position':'absolute'}});

    this.lightBox.style.overflow = 'hidden';
    this.lightBox.appendChild(this.boxImg);
    this.boxImg.appendChild(this.objImg);

    this.lightDesc = addElement('div',{
      'styles':{'visibility':'hidden','marginRight':'30px'}
    });
    this.lightBox.appendChild(this.lightDesc);
    
    var heightBox = (height)? height : this.objImg.offsetHeight;
    var widthBox = (width)? width : this.objImg.offsetWidth;
    
    var heightBottom = 0;
    
    if(titlePhoto){
      var title = addElement('div',{
        'styles':{'fontSize':'13px','fontWeight':'bold','paddingTop':'5px','width':widthBox+'px'},
        'text':titlePhoto
      });
      this.lightDesc.appendChild(title);
      heightBottom = title.offsetHeight;
    }
    
    if(descPhoto){
      var text = addElement('div',{
        'styles':{'fontSize':'12px','paddingTop':'5px','width':widthBox+'px'},
        'text':descPhoto
      });
      this.lightDesc.appendChild(text);
      heightBottom = heightBottom+text.offsetHeight;
    }
     
    if(!titlePhoto && !descPhoto) heightBottom = 20;
        
    this.loading.style.display = 'none';
    this.setLightBox(widthBox,heightBox,heightBottom);   
    
  }
    
  this.showImg = function(srcPhoto,titlePhoto,descPhoto,width,height){
  
    if(width && height && !window.ie){
      this.setImg(srcPhoto,titlePhoto,descPhoto,width,height);
    }else{
      var imagesLoader=new Image();
      addEvent(imagesLoader,'load',function(event,fnc){       
        setTimeout(function(fnc){
          return function(){
            fnc.setImg(srcPhoto,titlePhoto,descPhoto);
          }
        }(fnc),200);         
      },this);
      imagesLoader.src=srcPhoto;
    }
    
  }
 
};

