/**
 * @author mba
 */

function showLightBox(href, idx, group){
	var images = Ext.query('a[rel='+href+']');
	var image = {};
	if(images.length > 0){
		if(images.length>1){
			images[images.length-1].href = images[images.length-1].rel;
			image = images[images.length-1];
		}else{
			images[0].href = image[0].rel;
			image = images[0];
		}
		Ext.ux.Lightbox.open(image, 'a[class='+group+']', true);
	}
};

Ext.ns('Ext.ux');
Ext.ux.MediaCenter = Ext.extend(Ext.util.Observable, {
	
    transitionEasing: 'easeIn',
	transitionDuration: 0.75,
    itemSelector: 'div.item',
    sliderSelector: 'div.slider',
	flvplayer: '/js/player-licensed.swf',
	events: ['onItemShow', 'onSlide', 'onThumbsLoaded'],

    constructor: function(elId, config) {

        config = config || {};
        Ext.apply(this, config);
        Ext.ux.MediaCenter.superclass.constructor.call(this, config);
        
		this.elId = elId;
		this.items = Ext.select(this.itemSelector, true, this.elId).elements;		
		this.backbtn = Ext.select('div[@class=back]', true, this.elId);
		this.ffwbtn = Ext.select('div[@class=more]', true, this.elId);
		this.slider = Ext.select('div[@class=slider]', true, this.elId);
		this.spinner = Ext.select('div[@class=spinner clearfix]', true, this.elId);
		this.caption = Ext.select('div[@class=cb-head]', true, this.elId);
		this.detail = Ext.select('div[@class=detail]', true, this.elId);

		this.backbtnSingle = Ext.select('div[@class=back single]', true, this.elId);
		this.ffwbtnSingle = Ext.select('div[@class=more single]', true, this.elId);

		this.currentThumb = 0;
		this.loadedThumbs = 0;
		this.currentPage = 0;
		this.slideitems = 1;
		this.slideWidth = 128;
		
		this.initEvents();
		
   	},
   	
   	isVisible: function(index) {
   		return (index >= this.currentPage * this.slideitems) && (index <= ((this.currentPage + 1) * this.slideitems - 1));
   	},
   	
	slidePrev: function(){
		if(this.currentPage <= 0){
			return;
		}
		this.currentPage--;
		this.doSlide('right');
	},
	
	slideNext: function(){
		if((this.currentPage + 1) * this.slideitems >= this.items.length){
			return;
		}
		this.currentPage++;
		this.doSlide('left');
	},

	/* getting the index of active item */
	findItemIndex: function(item){
		var retval = 0;
		for(var i=0; i<this.items.length; i++){
			var titem = Ext.select('img', true, this.items[i].id);
			if(titem.elements[0].id == item.id){
				retval=i;
			}
		}
		return(retval);
	},
	
	showItem: function(e, item){
		/* showing video-detail */
		if (this.mctype == 'video') {
			var mediaspace = Ext.select('div[@class=mediaplayer]', true, this.elId);
			var canvas = mediaspace.elements[0];
            var so = new SWFObject(this.flvplayer, 'ply', canvas.getWidth(), canvas.getHeight(), '9', '#ffffff');
            so.addParam('allowfullscreen','true');
            so.addParam('allowscriptaccess','always');
            so.addParam('wmode','opaque');
			so.addVariable('file',item.parentNode.href);
			so.addVariable('image',item.parentNode.rel);
            so.write(canvas.id);
			var thumbs = Ext.select('div[@class*=active]', true, this.elId);
			var thdiv = Ext.get(item.parentNode.parentNode);
			
			//pageTracker Aufruf fuer google
			this.callTracker(item.parentNode.href, item.parentNode.title);
			
			thumbs.removeClass('active');
			thdiv.addClass('active');
			if(typeof e != 'undefined'){
				e.stopEvent();
			}
		}
		/* showing image-detail */
		if (this.mctype == 'image') {
			var mediaspace = Ext.select('div[@class=image]', true, this.elId);
			var mediatitle = Ext.select('h2[@class=imgtitle]', true, this.elId);
			var mediacopy  = Ext.select('div[@class=copy]', true, this.elId);
			var mediadesc  = Ext.select('p[@class=imgdesc]', true, this.elId);
			
			Ext.each(mediatitle.elements, function(el){
				var thtml = item.parentNode.title;				
				el.update(thtml);				
			}, this);
			
			var thumbdescription = Ext.select('p[@class=imgedesc_thumb]', true, item.parentNode.parentNode.parentNode);
			var thumbcopy = Ext.select('p[@class=copy_thumb]', true, item.parentNode.parentNode.parentNode);

			Ext.each(mediacopy.elements, function(el){			
				if(thumbcopy.elements.length){
					el.update(thumbcopy.elements[0].dom.innerHTML);
				}
			}, this);
		
			Ext.each(mediadesc.elements, function(el){				
				if(thumbdescription.elements.length){
					el.update(thumbdescription.elements[0].dom.innerHTML);
				}
			}, this);
			
			Ext.each(mediaspace.elements, function(el, index){			
				var currid = item.id;
				var idx = this.findItemIndex(item);
				
				var thtml = '<a onclick="javascript:showLightBox(\'' + item.parentNode.rel + '\', ' + idx + ', \'lbox_big\' );" href="javascript:void(0);" title="' + item.parentNode.title + '" rel="' + item.parentNode.rel + '">' // class="lbox_big">'
				+'<img src="' + item.parentNode.href + '" alt="' + item.parentNode.title +	'" />' +
				'</a>';
						
				/*
				var thtml = '<a href="'+item.parentNode.rel+'" title="'+item.parentNode.title+'" rel="lightbox" class="lb_'+ this.elId + '">'
									+ '<img src="'+item.parentNode.href+'" alt="'+item.parentNode.title+'" />'
									+ '</a>';
				*/	
				
				//tracker fuer google analytics	
				this.callTracker(item.parentNode.rel, item.parentNode.title);				
				
				el.fadeOut({
				    endOpacity: 0, //can be any value between 0 and 1 (e.g. .5)
				    easing: 'easeOut',
				    duration: 1,
				    remove: false,
				    useDisplay: true,
					scope: this,
					callback: function(){
						el.update(thtml);
						el.fadeIn({
						    endOpacity: 1, //can be any value between 0 and 1 (e.g. .5)
						    easing: 'easeOut',
						    duration: 1
						});
						Ext.ux.Lightbox.register('a[rel^=lightbox]');
					}
				});
				
			}, this);
			var count = Ext.select('div[@class*=count]', true, this.elId);

			this.currentThumb = this.findItemIndex(item);

			Ext.each(count.elements, function(el){
				el.update(parseInt(this.currentThumb+1)+' '+this.lang.from+' '+this.items.length);
			}, this);

			var thumbs = Ext.select('div[@class*=active]', true, this.elId);
			var thdiv = Ext.get(item.parentNode.parentNode);
			thumbs.removeClass('active');
			thdiv.addClass('active');
			if(typeof e != 'undefined'){
				e.stopEvent();
			}
		}
		
		this.doArrows();
		this.fireEvent('onItemShow');
	},

	doArrows: function(){

		if(this.currentThumb > 0){
			this.backbtnSingle.setVisible(true);
		}else{
			this.backbtnSingle.setVisible(false);
		}
		
		if(this.currentThumb < this.items.length - 1){
			this.ffwbtnSingle.setVisible(true);
		}else{
			this.ffwbtnSingle.setVisible(false);
		}
		
		/* ffw slider */		
		if((this.currentPage + 1) * this.slideitems < this.items.length){
			this.ffwbtn.setVisible(true);
		}else{
			this.ffwbtn.setVisible(false);
		}

		/* back slider */
		if(this.currentPage > 0){
			this.backbtn.setVisible(true);
		}else{
			this.backbtn.setVisible(false);
		}
	},
	
   	showGallery: function() {
   		var sliderHeight = 0;
		for (var i = 0; i < this.items.length; i++) {
			this.items[i].setVisible(true);
			if (!this.isVisible(i)) {
				this.items[i].setHeight(1);
			}
			sliderHeight = Math.max(sliderHeight, this.items[i].getHeight());
		}
		
		this.spinner.setVisible(false);
		this.detail.setVisible(true);
		this.slider.shift({
			height: sliderHeight,
			easing: this.transitionEasing,
			duration: this.transitionDuration
		});
		
		var item = {};
		
		/* for initial use */
		if (this.mctype == 'video') {
			item = Ext.select('img', true, this.items[0].id).elements[0].dom;
			this.showItem(undefined, item);
		}
		if (this.mctype == 'image') {
			item = Ext.select('img', true, this.items[0].id).elements[0].dom;
			this.showItem(undefined, item);
		}

		this.doArrows();
   	},
   	
	doSlide: function(dir){
   		var sliderHeight = 0;
		for (var i = 0; i < this.items.length; i++) {
			var el = this.items[i];
			
			// Innerhalb des sichtbaren bereichs oder nicht
			if (this.isVisible(i)) {
				var newHeight = el.origHeight;
				sliderHeight = Math.max(sliderHeight, newHeight);
			}
			else {
				var newHeight = 1;
			}

			// Links oder rechts
			if(dir == 'left'){
				var newX = el.getX() - (this.slideWidth * this.slideitems);
			}
			else{
				var newX = el.getX() + (this.slideWidth * this.slideitems);
			}
			
			el.shift({
				x: newX,
				height: newHeight,
				easing: this.transitionEasing,
				duration: this.transitionDuration
			});
			
		}
		
		this.slider.shift({
			height: sliderHeight,
			easing: this.transitionEasing,
			duration: this.transitionDuration
		});

		this.doArrows();
		this.fireEvent('onSlide');
	},   	
   	
	initEvents: function(){
		var tempSrc = '';
		
		this.backbtn.on('click', function(e, p){
			this.slidePrev();
		}, this);

		this.ffwbtn.on('click', function(e, p){
			this.slideNext();
		}, this);
   	
		this.backbtnSingle.on('click', function(e, p){
			var item = Ext.select('img', true, this.items[this.currentThumb-1].id).elements[0].dom;
			this.showItem(e, item);
			if(this.currentThumb < this.currentPage * this.slideitems){
				this.slidePrev();
			}
		}, this);

		this.ffwbtnSingle.on('click', function(e, p){
			var item = Ext.select('img', true, this.items[this.currentThumb+1].id).elements[0].dom;
			this.showItem(e, item);
			if(this.currentThumb >= (this.currentPage + 1) * this.slideitems ){
				this.slideNext();
			}
		}, this);
		
		Ext.each(this.items, function(el, p){

			el.child('img').on('load', function(e, p) {
				var parent = Ext.get(p.id).parent().parent().parent();
				parent.origWidth = Ext.decode(Ext.encode(parent.getWidth()));
				parent.origHeight = Ext.decode(Ext.encode(parent.getHeight()));
				this.itemwidth = parent.origWidth;
				
				this.slideitems = parseInt(this.slider.elements[0].getWidth() / this.itemwidth);
				
				this.loadedThumbs++;

				if (this.loadedThumbs === this.items.length) {
					this.fireEvent('onThumbsLoaded');
					this.showGallery();
				}
			}, 
			this,
			{
				single: true
			});
			
			
			tmpSrc = el.child('img').dom.src;
			el.child('img').dom.src = '/img/0.gif';
			el.child('img').dom.src = tmpSrc;
			
			var link = Ext.select('a', true, el.id);
			var linkcount = 1;
			Ext.each(link.elements, function(iel){
				if(linkcount == 1){
					iel.addClass('lb_'+this.elId);
				}
				if (this.mctype != 'lightbox') {
					iel.on('click', function(e, p, c){
						this.showItem(e, p);						
					}, this);
				}
				linkcount++;
			}, this);
		}, this);
   	
		if (this.mctype == 'lightbox') {
			Ext.ux.Lightbox.register('a.' + 'lb_' + this.elId, true);			
		}
		
		if (this.mctype == 'image'){			
			Ext.ux.Lightbox.register('a.' + 'lbox_big', true);
		}
   	},
   
   	/* JW nbsp funktion zum tracken einzelner Bilder in der Galerie */		
	callTracker: function(link,title){
		try{
			//var clearlink = link;
			var clearlink = link.replace('http://www.veterinaerwissen.de','');
			clearlink = clearlink + '/';
			pageTracker._trackPageview(clearlink);					
			} catch(err){}
		
	}


});
