var hs;
window.addEvent('resize',function(){
	if(hs) hs.resize();
});

window.addEvent('domready',function(){

	if($('window')) {
		hs = new noobSlide({
			box: $('slideshow_content'),
			items: $$('#slideshow_content span'),
			size: 500,
			addButtons: {
				previous: $('slide_prev'),
				play: $('slide_play'),
				stop: $('slide_pause'),
				next: $('slide_next'),
				close: $('slide_close'),
				show: $('option-play'),
				nextpic: $$('#slideshow_content span')
			},
			interval: 3000,
			onWalk: function(currentItem,currentHandle){			
				var picnum=currentItem.getChildren()[0].getProperty('id').substr(3,4).toInt();
				
				//paginate gallery overview in the background
				
				if(picnum>((gallery_page+1)*gallery_ppp-1)) {
					gallery_page++;
					loadPics(gallery_page*gallery_ppp, gallery_ppp);
					activePage(gallery_page);
				}
				else if( picnum<(((gallery_page+1)*gallery_ppp)-gallery_ppp)) {
					gallery_page--;
					loadPics(gallery_page*gallery_ppp, gallery_ppp);
					activePage(gallery_page);
				}
				
				
				//show/hide prev/next button
				this.buttoncontrol(picnum);

				//preload next picture
				var nextItem;
				if(nextItem=currentItem.getNext()) {
					var nextItemChild = nextItem.getChildren()[0];
					if(nextItemChild.getProperty('src')!=nextItemChild.getProperty('alt')) 
						nextItemChild.setProperty('src', nextItemChild.getProperty('alt')).addEvent('load', function(){this.resize()}.bind(this));
					
					if(nextItem=nextItem.getNext()) {
						var nextItemChild = nextItem.getChildren()[0];
						if(nextItemChild.getProperty('src')!=nextItemChild.getProperty('alt')) 
							nextItemChild.setProperty('src', nextItemChild.getProperty('alt')).addEvent('load', function(){this.resize()}.bind(this));
					}
				}
				//preload previous picture 
				if(nextItem=currentItem.getPrevious()) {
					var nextItemChild = nextItem.getChildren()[0];
					if(nextItemChild.getProperty('src')!=nextItemChild.getProperty('alt')) 
						nextItemChild.setProperty('src', nextItemChild.getProperty('alt')).addEvent('load', function(){this.resize()}.bind(this));
					
					if(nextItem=nextItem.getPrevious()) {
						var nextItemChild = nextItem.getChildren()[0];
						if(nextItemChild.getProperty('src')!=nextItemChild.getProperty('alt')) 
							nextItemChild.setProperty('src', nextItemChild.getProperty('alt')).addEvent('load', function(){this.resize()}.bind(this));
					}
				}
				
				
				//var h=currentItem.getChildren()[0].getSize().y;
				//var w=currentItem.getChildren()[0].getSize().x;
				
				//console.log("add resize event");
				//currentItem.getChildren()[0].onload = this.resize;
				
				if($('HDbutton')) {
					$('HDbutton').href=currentItem.getChildren()[0].getProperty('title');
				}
				
			}
		});
	
		// AutoPlay
		if (play)
			hs.jumpinto(0);
	
		
		// Rating
	if (!rated && $$('.gallery-options'))
	{
		$$('.gallery-options a.star').each(function(el)
		{
			el.addEvent('click', function(clip_id)
			{
				var index = el.getFirst().getAttribute('alt');
				jslink('/DE/gallery/vote', {'id': clip_id, 'value': index}, 'Content::rate', function(result) {
					$$('.gallery-options a.star').each(function(el2)
							{
								var index2 = el2.getFirst().getAttribute('alt');
								el2.removeEvents('click');
								el2.addEvent('click', function() { return false; });
								el2.removeEvents('mouseover');
								el2.removeEvents('mouseout');
								if (index2 <= index)
									el2.getFirst().setProperty('src', '/images/gallery/star.png');
							});
				});
				return false;
			}.pass(clip_id));
			el.addEvent('mouseover', function()
			{
				var index = el.getFirst().getAttribute('alt');
				$$('.gallery-options a.star').each(function(el2)
				{
					var index2 = el2.getFirst().getAttribute('alt');
					if (index2 <= index)
						el2.getFirst().setProperty('src', '/images/gallery/star.png');
				});
			});
			el.addEvent('mouseout', function()
					{
						var index = el.getFirst().getAttribute('alt');
						$$('.gallery-options a.star').each(function(el2)
						{
							var index2 = el2.getFirst().getAttribute('alt');
							if (index2 <= index)
								el2.getFirst().setProperty('src', '/images/gallery/starg.png');
						});
					});
		});
	}
	


	//myTips.options.offsets = {x: -55, y: -130};

	
			document.addEvent('keydown', function(event){
				event = new Event(event);
				//if(event.target.getTag()=='input' || event.target.getTag()=='textarea') {return}
				if((event.key=='right' || event.key=='down') && hs.started){
					hs.next(true);
					event.stop();
				}else if((event.key=='left' || event.key=='up') && hs.started){
					hs.previous(true);
					event.stop();
				}else if((event.key=='esc') && hs.started){
					hs.hideSlideShow();
					event.stop();
				}else if(event.key=='space'){
					hs.showSlideShow();
					event.stop();
				}
			});
			
			
			$$('#pics a').each(function(el) {
			
				el.addEvent('click', function(event) {
					addclickevent(event);
				});
			});
			
				
	}

function addclickevent(event) {
	event = new Event(event).stop();
	var picid=event.target.getProperty('id').match(/^thumbboxitem([0-9]*)$/)[1].toInt()+gallery_page*gallery_ppp;
	hs.jumpinto(picid);
}



	/* gallery pages */
	function loadPics(start, max)
	{
		$('pics').empty();
		$('pics').setStyles(
		{
			'height':		'200px',
			'background':	'transparent url("/images/common/loading.gif") scroll no-repeat center center'
		});
		var req = new Request.JSON(
		{
			'url': '/DE/gallery',
			'method': 'post',
			'data': 'jscall=getPics&clip_id=' + clip_id + '&max=' + max + '&start=' + start + '&format=200x',
			'onComplete': function(el)
			{
				$('pics').setStyles(
					{
						'height':			'auto',
						'background-image':	'none'
					});
				el.each(function(el, index)
				{
					var pic = new Element('a');
					pic.setStyle('background-image', 'url("' + el + '")');
					pic.setStyle('color', 'red');
					pic.addClass('thumb');
					pic.setProperty('id', 'thumbboxitem'+index);
					pic.inject($('pics'));
					pic.addEvent('click', function(event) { addclickevent(event) });
				})
			}
		}).send();		
	}

	function activePage(active)
	{
		$$('.pages span.page').each(function(el)
		{
			if (el.get('html')-1 == active)
				el.addClass('active');
			else
				el.removeClass('active');
		});
	}
	
	function addPagingEvents()
	{
		$$('.page').each(function(el)
		{
			el.addEvent('click', function(event)
			{
				if(typeof(gallery_page) == 'undefined') return true;
				event = new Event(event).stop();
				gallery_page = this.innerHTML.toInt()-1;
				loadPics(gallery_page*gallery_ppp, gallery_ppp);
				activePage(gallery_page);
				return false;
			});
		});
	
		$$('.page_next').each(function(el)
		{
			el.addEvent('click', function()
			{
				gallery_page++;
				if (gallery_page*gallery_ppp >= gallery_max)
					gallery_page = 0;
				loadPics(gallery_page*gallery_ppp, gallery_ppp);
				activePage(gallery_page);
				return false;
			});
		});
	
		$$('.page_prev').each(function(el)
		{
			el.addEvent('click', function()
			{
				gallery_page--;
				if (gallery_page < 0)
					gallery_page = (gallery_max/gallery_ppp).ceil()-1;
				loadPics(gallery_page*gallery_ppp, gallery_ppp);
				activePage(gallery_page);
				return false;
			});
		});
	}
	/* pics per page */
	$$('.ppp').each(function(el)
	{
		el.addEvent('click', function()
		{
			gallery_ppp = this.innerHTML.toInt();
			gallery_page = 0;
			loadPics(gallery_page*gallery_ppp, this.innerHTML);
			// build new pagination
			$$('.pages').each(function(el) { el.empty() });
			for (var c = 0; c < gallery_max/this.innerHTML; c++) {
				$$('.pages').each(function(el)
				{
					var li = new Element('li', {'class': 'paginate_middle'});
					var span = new Element('span', {'class': 'page', 'html': c+1 });
					span.inject(li);
					li.inject(el);
				});
			}
			
			$$('.pages').each(function(el) {
				var li_prev = new Element('li', {'class': 'page_prev'});
				var li_next = new Element('li', {'class': 'page_next'});

				li_prev.inject(el);
				li_next.inject(el);
			});
			
			addPagingEvents();
			
			// css active
			$$('.ppp').each(function(el2)
			{
				if (el2.get('html') == gallery_ppp)
					el2.addClass('active')
				else
					el2.removeClass('active')
			});
			activePage(0);
			return false;
		});
	});
	
	addPagingEvents();
	
});








function resizeWindow(w, h) {
	w=parseInt(w);
	h=parseInt(h);
	var fxresize = new Fx.Elements($$('#window','#window div.top .middle','#window div.center','#window div.bottom .middle'), {duration:250,wait:false});
	
	
	
	fxresize.start({
		'0'	:	{'width': (w+60), 'height': (h+110)},
		'1'	:	{'width': (w+40)},
		'2'	:	{'width': (w+40), 'height': h},
		'3'	:	{'width': (w+40)}
	});
	
}




var noobSlide = new Class({

	initialize: function(params){
		this.started=false;
		this.items = params.items;
		this.mode = params.mode || 'horizontal';
		this.modes = {horizontal:['left','width'], vertical:['top','height']};
		this.size = params.size || 240;
		this.box = params.box.setStyle(this.modes[this.mode][1],(this.size*this.items.length)+'px');
		this.button_event = params.button_event || 'click';
		this.handle_event = params.handle_event || 'click';
		this.onWalk = params.onWalk || null;
		this.currentIndex = null;
		this.previousIndex = null;
		this.nextIndex = null;
		this.interval = params.interval || 5000;
		this.autoPlay = params.autoPlay || false;
		this._play = null;
		this.handles = params.handles || null;
		if(this.handles){
			this.addHandleButtons(this.handles);
		}
		this.buttons = {
			previous: [],
			next: [],
			play: [],
			playback: [],
			stop: [],
			close: [],
			show: [],
			nextpic: []
		};
		if(params.addButtons){
			for(var action in params.addButtons){
				this.addActionButtons(action, $type(params.addButtons[action])=='array' ? params.addButtons[action] : [params.addButtons[action]]);
			}
		}
		this.fx = new Fx.Tween(this.box,$extend((params.fxOptions||{duration:500,wait:false}),{property:this.modes[this.mode][0]}));
		this.walk((params.startItem||0),true,true);
		this.shadow=new Element('div', { 'class' : 'shadow'});
		this.shadowEffect=new Fx.Elements(this.shadow, {duration: 500,wait:false});
		
	},

	addHandleButtons: function(handles){
		for(var i=0;i<handles.length;i++){
			handles[i].addEvent(this.handle_event,this.walk.bind(this,[i,true]));
		}
	},

	addActionButtons: function(action,buttons){
		for(var i=0; i<buttons.length; i++){
			switch(action){
				case 'previous': buttons[i].addEvent(this.button_event,this.previous.bind(this,[true])); break;
				case 'next': buttons[i].addEvent(this.button_event,this.next.bind(this,[true])); break;
				case 'play': buttons[i].addEvent(this.button_event,this.play.bind(this,[this.interval,'next',false])); break;
				case 'playback': buttons[i].addEvent(this.button_event,this.play.bind(this,[this.interval,'previous',false])); break;
				case 'stop': buttons[i].addEvent(this.button_event,this.stop.bind(this)); break;
				case 'close': buttons[i].addEvent(this.button_event,this.hideSlideShow.bind(this)); break;
				case 'show': buttons[i].addEvent(this.button_event,this.showSlideShow.bind(this)); break;
				case 'nextpic': buttons[i].addEvent(this.button_event,this.next.bind(this,[true])); break;
			}
			this.buttons[action].push(buttons[i]);
		}
	},

	previous: function(manual){
		if((this.currentIndex-1)<0) {
			return;
		}
		this.walk((this.currentIndex>0 ? this.currentIndex-1 : this.items.length-1),manual);
	},

	next: function(manual){
		if((this.currentIndex+1)>=gallery_max) {
			this.stop();
			return;
		}
		this.walk((this.currentIndex<this.items.length-1 ? this.currentIndex+1 : 0),manual);
	},

	play: function(interval,direction,wait){
		this.stop();
		if(!wait){
			this[direction](false);
		}
		$('slide_play').setStyle('display', 'none');
		$('slide_pause').setStyle('display', 'block');
		
		
		this._play = this[direction].periodical(interval,this,[false]);
	},

	stop: function(){
		$clear(this._play);
		$('slide_pause').setStyle('display', 'none');
		$('slide_play').setStyle('display', 'block');
	},

	walk: function(item,manual,noFx){
		if(item!=this.currentIndex){
			this.currentIndex=item;
			this.previousIndex = this.currentIndex + (this.currentIndex>0 ? -1 : this.items.length-1);
			this.nextIndex = this.currentIndex + (this.currentIndex<this.items.length-1 ? 1 : 1-this.items.length);
			if(manual){
				this.stop();
			}
			if(noFx){
				this.fx.cancel().set((this.size*-this.currentIndex)+'px');
			}else{
				this.fx.start(this.size*-this.currentIndex);
			}
			if(manual && this.autoPlay){
				this.play(this.interval,'next',true);
			}
			if(this.onWalk){
				this.onWalk((this.items[this.currentIndex] || null), (this.handles && this.handles[this.currentIndex] ? this.handles[this.currentIndex] : null));
			}
		}
	},
	
	showSlideShow: function() {
		this.currentIndex=0;
		$('slideshow_content').setStyle('left', 0);
		
		
		$('content').adopt(this.shadow);
		this.shadowEffect.start({'0': {'opacity': 0.6}});
		$('window').setStyle('display', 'block');

		this.play(this.interval, 'next', true);
		this.started=true;
		
		this.resize();
		
		//hide slideshow on click out of the box
		$$('.shadow').addEvent('click', function(e) {
			this.hideSlideShow();
		}.bind(this));
	},
	
	hideSlideShow: function() {
		$('window').setStyle('display', 'none');
		this.shadowEffect.start({'0': {'opacity': 0}});
		this.shadow.dispose();
		this.started=false;
		this.stop();
	},
	
	
	resize: function() {
		$('window').setStyle('left', (window.getWidth()/2)-305);
		

		var num=hs.currentIndex;
	
		var h=hs.items[num].getChildren()[0].getSize().y;
		
		
		if(h==0) return;

		hs.items[num].getChildren()[0].setStyle('height', 'auto');
		h=hs.items[num].getChildren()[0].getSize().y;
		if(h>window.getHeight()-250) {
			h-=h-window.getHeight()+150;
			hs.items[num].getChildren()[0].setStyle('height', h);
		}
		
		resizeWindow(550, h);
		
		
		hs.items[num].getChildren()[0].removeEvent('load');
	},
	
	jumpinto: function(num) {
		this.currentIndex=num;
		$('slideshow_content').setStyle('left', -(num*this.size));		
		
		$('content').adopt(this.shadow);
		this.shadowEffect.start({'0': {'opacity': 0.6}});
		$('window').setStyle('display', 'block');
		
					if(num>0) {
						this.items[num-1].getChildren()[0].setProperty('src', this.items[num-1].getChildren()[0].getProperty('alt'));
					}
					this.items[num].getChildren()[0].setProperty('src', this.items[num].getChildren()[0].getProperty('alt'));
					
					this.items[num].getChildren()[0].onload= this.resize;
					this.resize();
					
					//this.resize();
					if(num<(gallery_max-1)) {
						this.items[num+1].getChildren()[0].setProperty('src', this.items[num+1].getChildren()[0].getProperty('alt'));
					}

					
		
		
		this.buttoncontrol(num);
		
		//window.scrollTo(0,0);
		this.started=true;
		this.stop();
		
		//hide slideshow on click out of the box
		$$('.shadow').addEvent('click', function(e) {
			this.hideSlideShow();
		}.bind(this));
		
		if($('HDbutton')) {
			$('HDbutton').href=this.items[num].getChildren()[0].getProperty('title');
		}
	},
	
	buttoncontrol: function(picnum) {
		if(picnum==(gallery_max-1)) {
			$('slide_next').setStyle('visibility', 'hidden');
		}
		else {
			$('slide_next').setStyle('visibility', 'visible');
		}

		if(picnum==0) {
			$('slide_prev').setStyle('visibility', 'hidden');
		}
		else {
			$('slide_prev').setStyle('visibility', 'visible');
		}
	}
	
});

