/**
 * @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', 'onSlideReady'],
	autocount: 0,
	autoScroll: true,	
	autoDirection: 'forward',
	countitem: 0,	
	
    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;		
		if (this.mctype == 'article') {
			this.slideWidth = 189;//128 189
		}else{
			this.slideWidth = 128;
		}
		this.slideEnabled = true;
		this.initEvents();
		

		
   	},
   	
   	isVisible: function(index) {
   		return (index >= this.currentPage * this.slideitems) && (index <= ((this.currentPage + 1) * this.slideitems - 1));
   	},
   	
	slidePrev: function(){
		if (this.mctype == 'article') {
			var counterleft = Ext.get('nofloating_left');
			var counterright = Ext.get('nofloating_right');
			var newcounterleft = parseInt(counterleft.dom.innerHTML) - 3;
			var newcounterright = parseInt(counterright.dom.innerHTML) - 3;
			
			if (Math.ceil(this.items.length / 3) - 1 == this.currentPage) {
				newcounterright = parseInt(this.currentPage * this.slideitems);
			}
			Ext.get('nofloating_left').update(newcounterleft);
			Ext.get('nofloating_right').update(newcounterright);
		}
		if(this.currentPage <= 0){
			return;
		}
		this.currentPage--;
		this.doSlide('right');
	},
	
	slideNext: function(){
		if (this.mctype == 'article') {
			var counterleft = Ext.get('nofloating_left');
			var counterright = Ext.get('nofloating_right');
			var newcounterleft = parseInt(counterleft.dom.innerHTML) + 3;
			var newcounterright = parseInt(counterright.dom.innerHTML) + 3;
			
			
			if (newcounterright > this.items.length) {
				newcounterright = this.items.length;
			}
			Ext.get('nofloating_left').update(newcounterleft);
			Ext.get('nofloating_right').update(newcounterright);
		}
		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>';
					
				
				//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.appendChild(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();

		if(navigator.userAgent.search("Safari") != -1){
			this.slideNext();
		}
		
   	},
   	
	doSlide: function(dir){
	   	var sliderHeight = 0;
			// groesste hoehe bestimmen
			for (var i = 0; i < this.items.length; i++) {
				var elH = this.items[i];
				var tmpHeight = elH.origHeight;
				var sliderHeight = Math.max(sliderHeight, tmpHeight);										
			}
			
			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: sliderHeight,					
					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.autoScroll = false;
			this.slidePrev();
		}, this);

		this.ffwbtn.on('click', function(e, p){
			this.autoScroll = false;
			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);
			//this.autoScroll = false;
			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);
			//this.autoScroll = false;
			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 current = Ext.get(p.id);				
				var parent = current.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);
				}
				//else{
				//	iel.addClass('lbox_big'+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.nobilis.de','');
			clearlink = clearlink + '/';
			pageTracker._trackPageview(clearlink);	
							
			} catch(err){}
		
	},

	autoSlide: function(){			
		if(this.autocount > 0){
			
			if (this.autoScroll) {
				
				if (Math.ceil(this.items.length / this.slideitems - 1) == this.currentPage) {
					this.autoDirection = 'backward';
				}
				if(this.currentPage == 0){
					this.autoDirection = 'forward';
				}
			
				if(this.autoDirection == 'forward'){
					this.slideNext();
				}else{
					this.slidePrev();
				}
			}					
				
		}
		
	
		// zaehler erhoehen
		this.autocount++;
		this.fireEvent('onSlideReady');	
					
	},
	
	
	listeners: {
		'onThumbsLoaded': function(){

			// Aufruf der automatischen Slidefunktion nach x Sekunden 
			// equivalent using TaskMgr
			if (this.mctype == 'article' && this.items.length >=4) {
							
			
				Ext.TaskMgr.start({
					run: this.autoSlide,
					interval: 7000,
					scope: this
				});
			}
			


		},
		'onSlide': function(){
			if (this.autoScroll) {				
				//this.backbtn.unselectable();
				//this.ffwbtn.unselectable();
				this.backbtn.slideOut();
				this.ffwbtn.slideOut();
			}
	
			
		},
		'onSlideReady': function(){
			if (this.autoScroll) {
				if (this.currentPage > 0) {
					this.backbtn.slideIn();					
				}
				/* ffw slider */
				if ((this.currentPage + 1) * this.slideitems < this.items.length) {
					this.ffwbtn.slideIn();
					
				}				
			}
			
		}

	}

});
