/////////////////////////////////////////////////////////////////////////////////////
var InlinePopups=new Class({
	//default options
	img:[],
	back:[],
	now:[],
	started:false,
	loadingImg:false,
	fx:[],
	options:{
       links:'a'
       ,durationIn:800
       ,opacityIn:0.7
       ,durationOut:400
       ,opacityOut:0.3
       ,durationPopup:200
       ,transitionIn:Fx.Transitions.Expo.easeIn
       ,transitionOut:Fx.Transitions.Expo.easeOut
       ,slideShow: 2000
       ,loadText:'Loading...'
       ,slideText:'Slide'
       ,downloadButton:'Download'
       ,displayIn:null
    },
    initialize: function(options){
		this.setOptions(this.options, options);
		if(this.options.displayIn==null)
			this.options.displayIn=$(document.body);
		var l=0;
        $$(this.options.links).each(function(a, i){
			if(a.replaced)
				return;
			a.replaced=true;
            var h=a.getProperty('rel');
            if(!h)
                return;     
            var ex=(h.substr(h.length-4)).toLowerCase();
            if(ex=='.jpg'){
				//search for sub image
				var subImage=a.getChildren('img').getLast();
				if(subImage!=null) {
					a.l=l;
					this.saveImgData(a, l, h, subImage);
					a.addEvent('click', function(e){
						new Event(e).stop();
						this.linkClick(a.l);
						
					}.bind(this));
					l++;
				}
            }
        }.bind(this));
    },
    //////////////////////////////////////////////////////////////////////////
    saveImgData: function(a, i, h, subImage){
		var linkName=a.getProperty('title');
		linkName=linkName=='' ? el.getChildren().getProperty('alt') : linkName;
		var imCoor=subImage.getCoordinates(this.options.displayIn);
		var sImages = h.split(';');
		this.img[i]={
			'sm':{
				'_this':subImage
				,'top': imCoor.top
				,'left':imCoor.left
			},
			'dt':{
				'name':linkName
			},
			'bg':{
				'src':sImages[0]
			},
			'or':{
				'src':!sImages[1] ? false : sImages[1]
			}
		}
		//console.info(this.img);
    },
    ////////////////////////////////////////////////////////////////////////////////
    updateParams: function(img){
		var el=this.img[this.now['active']];
		this.back['imgCont'].setStyles({
			'overflow':'hidden'
		});
		img.inject(this.back['imgCont']);
		var imgSize=img.getSize();
		img.setStyles({
			'display': 'none'
		});
		this.back['imgCont'].setStyles({
			'overflow':'visible'
		});
		var smSize=this.img[this.now['active']].sm._this.getSize();
		this.img[this.now['active']].bg.width=imgSize.x;
		this.img[this.now['active']].bg.height=imgSize.y;
		this.img[this.now['active']].bg.top=el.sm.top-imgSize.x/2<10 ? 10 : el.sm.top-imgSize.y/2;
		this.img[this.now['active']].bg.left=this.back['bSize'].x/2-imgSize.x/2<0 ? 0 : this.back['bSize'].x/2-imgSize.x/2;
		this.img[this.now['active']].sm.width=smSize.x;
		this.img[this.now['active']].sm.height=smSize.y;
		this.img[this.now['active']].bg._this=img;
    },
    ////////////////////////////////////////////////////////////////////////////////
    linkClick: function(i){
		//console.info(this.options);
		this.now['slide']=false;
		this.now['loading']=true;
		this.now['active']=i;
		var el=this.img[i];
		this.createPopup();
		this.started=true;
		this.showLoading(el.sm.top, el.sm.left);
		this.loadBgImage('first');
    },
    ////////////////////////////////////////////////////////////////////////////////
    buttonClick: function(i){
		//console.info(this.options);
		if(this.now['loading'])
		  return;
		this.now['loading']=true;
		var elPrevious=this.img[this.now['active']];
		this.now['active']=i;
		//var el=this.img[i];
		this.showLoading(this['topPosition'], elPrevious.bg.left);
		this.buttonEffects();
		this.loadBgImage();
    },
    ////////////////////////////////////////////////////////////////////////////////
    loadBgImage: function(type){
		var el=this.img[this.now['active']];
		var img=new Element('img', {
			'src': el.bg.src+'?'+$time()
			,'alt': el.dt.name
			,'title': el.dt.name
			,styles: {
				'position':'absolute'
			}
		});
		this.loadingImg=img;
		img.onload=function(){
			if(!this.started)
				return;
			this.removeLoading();
			this.updateParams(img);
			this.downloadLink();
			if(type!=undefined)
				this.firstImageLoaded(img);
			else
				this.imageLoaded(img);
		}.bind(this);
    },
    ////////////////////////////////////////////////////////////////////////////////
    firstImageLoaded: function(img){
		var el=this.img[this.now['active']];
		img.setStyles({
			'top': el.sm.top
			,'left': el.sm.left
			,'width': el.sm.width
			,'height': el.sm.height
			,'display': 'block'
			,'opacity': 0.3
		});
		var fx=this.fx[0]=this.img[this.now['active']].dt.fx=new Fx.Morph(img, {duration: this.options.durationIn, transition: this.options.transitionIn});
		var _this=this;
		this['topPosition']=el.bg.top;
		fx.start({
		   'top':el.bg.top
			,'left':el.bg.left
			,'width':el.bg.width
			,'height':el.bg.height
			,'opacity':1
		}).chain(function(){
			if(_this.img.length>1)
				_this.showNavigation();
		});
		
    },
    ////////////////////////////////////////////////////////////////////////////////
    downloadLink: function(){
    	if(this.img[this.now['active']].or.src){
    		this.back['popupButtonDownload'].setStyle('display','block');
    		this.back['popupButtonDownload'].getElement('a').set('href', this.img[this.now['active']].or.src);
    	} else {
    		this.back['popupButtonDownload'].setStyle('display','none');
    	}
    },
    ////////////////////////////////////////////////////////////////////////////////
    imageShow: function(img){
        this.now['loading']=false;
        if(this.now['slide'])
            if(this.now['active']+1<this.img.length) {
                this.now['slideTimer']=this.buttonClick.delay(this.options.slideShow+this.options.durationIn, this, this.now['active']+1);
            }
            else {
                this.now['slide']=false;
                this.buttonEffects();
            }
 		var el=this.img[this.now['active']];
		img.setStyles({
		    'display':'block'
			,'opacity':0
			,'top':this['topPosition']
			,'left':el.bg.left
		});
		var fx=this.fx[1]=this.img[this.now['active']].dt.fx=new Fx.Morph(img, {duration: this.options.durationPopup, transition: this.options.transitionIn});
		var _this=this;
		fx.start({
			'opacity':1
		});/*.chain(function(){
			if(_this.img.length>1)
				//_this.showNavigation();
		});	*/
    },
    ////////////////////////////////////////////////////////////////////////////////
    imageLoaded: function(img){
        var el=this.img[this.now['active']];
        var fxPopup=this.fx[2]=new Fx.Morph(this.back['popupDecoration'], {duration: this.options.durationPopup, transition: this.options.transitionIn});
		var _this=this;
        fxPopup.start({
			'width': el.bg.width+this.now['size'].x
			,'height': el.bg.height+this.now['size'].h
			,'left': el.bg.left-this.now['size'].x/2
		}).chain(function(){
            _this.imageShow(img);
        });
    },
    ////////////////////////////////////////////////////////////////////////////////
    showNavigation: function(){
		//$('popup-decoration').set('html', this.img.length);
		this.now['size']={x:140, y:21, h:86};
		var el=this.img[this.now['active']];
		if(!this.back['popupDecoration'])
			return;
		this.back['popupDecoration'].setStyles({
            'top':el.bg.top-this.now['size'].y
			,'left':el.bg.left-this.now['size'].x/2
			,'width':el.bg.width+this.now['size'].x
			,'height':el.bg.height+this.now['size'].h
			,'display': 'block'
			//,'opacity': 0.1
        });
		this.back['popupDecoration'].addEvent('click', function(e){
            //new Event(e).stop();
        });
        this.now['loading']=false;
        this.buttonEffects();
        this.buttonPressed();
    },
    
    ////////////////////////////////////////////////////////////////////////////////
    buttonEffects: function(){
        if(this.now['active']>0&&!this.now['slide']){
            this.back['popupButtonLeft'].addClass('can-press');
        } else {
            this.back['popupButtonLeft'].removeClass('can-press');
        }
        if(this.now['active']+1<this.img.length&&!this.now['slide']){
            this.back['popupButtonRight'].addClass('can-press');
        } else {
            this.back['popupButtonRight'].removeClass('can-press');
        }
        if(this.now['slide']){
            this.back['popupButtonSlide'].removeClass('can-press');
        }  else {
            this.back['popupButtonSlide'].addClass('can-press');
        }
    },
    ////////////////////////////////////////////////////////////////////////////////
    buttonPressed: function(){
        this.back['popupButtonLeft'].addEvent('click', function(e){
            new Event(e).stop();
            if(this.now['active']>0&&!this.now['slide'])
                this.buttonClick(this.now['active']-1);
        }.bind(this));
        this.back['popupButtonRight'].addEvent('click', function(e){
            new Event(e).stop();
            if(this.now['active']+1<this.img.length&&!this.now['slide'])
                this.buttonClick(this.now['active']+1);
        }.bind(this));
        this.back['popupButtonSlide'].addEvent('click', function(e){
            new Event(e).stop();
            if(!this.now['loading'])
                if(this.now['slide']){
                    this.now['slide']=false;
                    $clear(this.now['slideTimer']);
                    this.buttonEffects();
                } else {
                    if(this.now['active']+1<this.img.length) {
                        this.now['slide']=true;
                        this.buttonEffects();
                        this.now['slideTimer']=this.buttonClick.delay(this.options.slideShow, this, this.now['active']+1);
                    } else {
                        this.now['slide']=true;
                        this.buttonEffects();
                        this.now['slideTimer']=this.buttonClick.delay(this.options.slideShow, this, 0);
                    }
                }
        }.bind(this));
        this.back['popupButtonDownload'].addEvent('click', function(e){
        	e.stopPropagation();
        });
    },
    ////////////////////////////////////////////////////////////////////////////////
    createPopup: function(){
		var bSize=this.back['bSize']=this.options.displayIn.getSize();
		this.back['IeBack']=new Element('div', {
			'id': 'inline-popup-back'
			, styles: {
				'position':'absolute'
				,'top':0
				,'left':0
				,'width':bSize.x
				,'height':bSize.y
			}
			//,html: '<a href="#" style="position: relative;">some link</a>'
		}).inject(this.options.displayIn);
		this.back['popup']=new Element('div', {
			'id': 'inline-popup'
			, styles: {
				'position':'absolute'
				,'top':0
				,'left':0
				,'width':bSize.x
				,'height':bSize.y
			}
			//,html: '<a href="#" style="position: relative;">some link</a>'
		}).inject(this.options.displayIn);
		this.back['popupDecoration']=new Element('div', {
			'id': 'popup-decoration'
			//,'z-index': '998'
			,'html':''
		}).inject(this.back['popup']);
		this.back['imgCont']=new Element('div', {
			'id': 'inline-popup-image'
			,styles:{
				'position':'relative'
				,'top':0
				,'left':0
				,'width':0
				,'height':0
			//	,'z-index': '999'
			}
		}).inject(this.back['popup']);
		
		this.back['popupButtonLeft']=new Element('div', {
			'id': 'popup-button-left'
			//,html: '<span></span>'
		}).inject(this.back['popupDecoration']);
		this.back['popupButtonRight']=new Element('div', {
			'id': 'popup-button-right'
			//,html: '<a href="#">link</a>'
		}).inject(this.back['popupDecoration']);
        this.back['popupButtonSlide']=new Element('div', {
			'id': 'popup-button-slide'
			,'title':this.options.slideText
			,html: '<div class="popup-slide-left"></div><div class="popup-slide-center"><span class="describe-slide-text">'+this.options.slideText+'</span></div><div class="popup-slide-right"></div><div class="popup-slide-right-2"></div>'
		}).inject(this.back['popupDecoration']);
		this.back['popupButtonDownload'] = new Element('div', {
			'id': 'download-button'
			, 'html': '<a target="_blank" href="#" title="'+this.options.downloadButton+'">'+this.options.downloadButton+'</a>'
		}).inject(this.back['popupDecoration']);
		this.back['popup'].addEvent('click', function(){
			this.removePopup();
		}.bind(this));
    },
    ////////////////////////////////////////////////////////////////////////////////
    removePopup: function(){
        if(this.now['loading']){
    		/*this.back['popup'].destroy();//dispose();
    		this.back['IeBack'].destroy();//dispose();
    		this.back=[];*/
    		this.removeAllParams();
		} else {
			if(this.back['popupDecoration'])
				this.back['popupDecoration'].destroy();//dispose();
		    if(this.now['slideTimer'])
				$clear(this.now['slideTimer']);
            var el=this.img[this.now['active']];
    		var fx=this.fx[3]=new Fx.Morph(el.bg._this, {duration: this.options.durationOut, transition: this.options.transitionOut});
    		var _this=this;
    		this['topPosition']=el.bg.top;
    		fx.start({
    		   'top':el.sm.top
    			,'left':el.sm.left
    			,'width':el.sm.width
    			,'height':el.sm.height
    			,'opacity':0.2
    		}).chain(function(){
					/*_this.back['popup'].destroy();//dispose();
					_this.back['IeBack'].destroy();//dispose();
					_this.back=[];*/
					var fn=_this.removeAllParams.bind(_this);
					fn();
    		});
        }
    },
    ////////////////////////////////////////////////////////////////////////////////
    removeAllParams: function(){
		//t=t==undefined?this:t;
		/*d(this.started);
		d(this.fx);*/
		this.cancelAnimation();
		this.started=false;
		this.now=[];
		this.back['popup'].destroy();//dispose();
		this.back['IeBack'].destroy();//dispose();
		this.back=[];
		if(this.loadingImg)
			this.loadingImg.onload=function(){ return false;}
    },
    ////////////////////////////////////////////////////////////////////////////////
    cancelAnimation:function(){
		for(i=0; i<=3; i++)
			if(this.fx[i]!=undefined)
				this.fx[i].cancel();
		this.fx=[];
    },
    ////////////////////////////////////////////////////////////////////////////////
    showLoading: function(top, left){
		var load = new Element('span', {
			'html': this.options.loadText
			,'class': 'loading'
			,styles: {
				'position':'absolute'
				,'top':top
				,'left':left
			}
		}).inject(this.back['imgCont']);
    },
    ////////////////////////////////////////////////////////////////////////////////
    removeLoading: function(){
		this.back['imgCont'].empty();
    }
    
});
//////////////////////////////////////////////////////////////////////////////////////////////////
InlinePopups.implement(new Events);
InlinePopups.implement(new Options);
