//$Rev: 16654 $
//$Date: 2009-01-30 08:20:10 -0500 (Fri, 30 Jan 2009) $
var SlideshowModule;

if ($type(window['Module']) == 'class'){
	SlideshowModule = new Class({
		Extends: Module, 
		options:{
		},
		initialize:function(el,options){
			this.parent(el,options);
			this.editors = this.module.getElements('textarea');
			this.loadPreview('preview');
		},
		loadEdit:function(panelname){
			var panel=this.getPanel(panelname);
		
			if (panel.get('initialized') != 'initialized'){
				var addMultiple = this.module.getElement('.add_media_btn');
				addMultiple.addEvent('click',function(){
					var address = addMultiple.getProperty('address').replace(/moduleinstid=\d+/,'moduleinstid='+this.id);
					var popup = window.open(address,'myfiles',
						'width=500,height=500,left=200,top=100,resizable=yes');
					popup.focus();
				}.bind(this));
				this.initializeSlides();
				this.module.getElements('.slideshow_layout a').each(function(a){
					a.addEvent('click',function(){
						var input = this.module.getElement('input[name=thumbnails]');
						var current = input.get('value');
						this.module.getElement('a[rel='+current+']').removeClass('active');
						input.set('value',a.getProperty('rel'));
						a.addClass('active');
						var feedback = input.form.getElement('.feedback');
						feedback.fade('show');
						input.form.set('send',{
							onComplete:function(response){
								if (handleError(response))
									return false;
								
								this.reloadPublishPanel();
								var result=this.module.getElement('.thumbnails');
								result.set('html',response);
								this.getPanel('preview').erase('initialized');
								feedback.set('tween',{duration:200});
								feedback.fade('out');
							}.bind(this)
						});
						input.form.send();
					}.bind(this));
				},this);
				var form = panel.getElement('form.thumbnail_settings');
				form.addEvent('submit',this.formHandler.bindWithEvent(this,form));
			
				panel.set('initialized','initialized');
			}
		
			var list = panel.getElement('.slideshow_edit');
			panel.getElement('.slideshow_layout').setClass('hidden',(list.getChildren().length == 0));
			
			if (!this.sortable){
				this.sortable = new Reorder(list,{
					ghost:true,
					onStart : function(element,event){
						element.addClass('dragClass');
						this.ghost.setStyles({listStyle:'none',width:462});
					},
					onChange : function(){
					},
					onComplete:function(element,event){
						element.removeClass('dragClass');
						var position = element.getParent().getChildren().indexOf(element)+1;
						var id = element.getProperty('id').replace(/[^\d]/g,'');
					
						new Request({
							url:this.module.getElement('.reorder_slide_url').get('value'),
							data : "slideid="+id+"&to="+position,
							method : 'post',
							onComplete:function(result){
								if (handleError(result))
									return false;
								
								this.module.getElement('.thumbnails').set('html',result);
							}.bind(this)
						}).send();
					}.bind(this)
				
				});
			}
			var textareas = this.module.getElements('.editing textarea');
			textareas.each(function(t){TextElement.load(t,{moduleinstid:this.id})},this);
			this.setEditMode(textareas.length);
		},
	
		initializeSlides : function(){
			this.module.getElement('.slideshow_edit').getElements('li').each(function(li){
				var form = li.getElement('form');
				form.addEvent('submit',this.saveCaption.bindWithEvent(this,form));
				var edit = li.getElement('.expander');
				edit.addEvent('mousedown',function(event){
					if (event.rightClick) return;
					event.stopPropagation();
					var editing = !li.hasClass('editing');
					li.setClass('editing',editing);
					li.getElement('.expander').setClass('active',editing);
					li.getElement('.slide_edit').setClass('hidden',!editing);
				
					this.setEditMode(this.module.getElements('.editing').length);
					if(editing)
						TextElement.load(li.getElement('textarea'),{moduleinstid:this.id});
					else
						TextElement.unload(li.getElement('textarea'));
				}.bindWithEvent(this));
				var media = li.getElement('.media');
				var thumbnail = li.getElement('.thumnail img');
				media.addEvent('mousedown',function(event){
					if (event.rightClick) return;
					event.stopPropagation();
					this.slideId = li.getProperty('id').replace(/[^\d]/g,'');
					var address = media.getProperty('address').replace(/moduleinstid=\d+/,'moduleinstid='+this.id);
					var popup = window.open(address,'myfiles',
						'width=500,height=500,left=200,top=100,resizable=yes');
					popup.focus();
				}.bindWithEvent(this));
				var deleteButton = li.getElement('.delete_slide_btn');
				deleteButton.addEvent('mousedown',function(event){
					if (event.rightClick) return;
					event.stopPropagation();
					var address = deleteButton.getProperty('address').replace(/moduleinstid=\d+/,'moduleinstid='+this.id);
					if (confirm('This action can not be undone. \n\nAre you sure you want to delete this?')){
						li.setStyle('opacity',.3);
						li.getElements('button').each(function(button){
							button.removeEvents();
							button.disabled = true;
						});
						var c = li.getCoordinates();
					
						var img = new Element('img',{src:this.options.saveImg,styles:{
							position:'absolute',
							zIndex:100,
							top:c.top+(c.height/2)-8,
							left:c.left+(c.width/2)-8
						}});
						document.body.adopt(img);
						this.sortable.disable();
						new Request({url:address+'&ajax=1',onComplete:function(result){
							if (handleError(result))
								return false;
							
							this.module.getElement('.thumbnails').set('html',result);
							this.module.getElement('.slideshow_layout').setClass('hidden',(li.getParent().getChildren().length == 1));
							if (li.getParent().getChildren().length == 1)
								this.module.getElement('.preview_content .slide').set('html','');
							li.set('morph',{onComplete:function(){
								li.destroy();
								img.destroy();
								this.sortable.enable();
							}.bind(this)});
							li.morph({height:0,opacity:0});
						}.bind(this)}).send();
					}
				}.bindWithEvent(this));
			},this);
			this.module.getElement('.slideshow_layout').setClass('hidden',(this.module.getElement('.slideshow_edit').getChildren().length == 0));
		},
	
		setEditMode : function(on){
			if (on){
				layout.idle = false;
				layout.dropAreas.removeClass('draggable');
				this.sortable.disable();
				this.module.getElement('.slideshow_edit').removeClass('draggable');
			}else{
				layout.idle = true;
				layout.dropAreas.addClass('draggable');
				this.sortable.enable();
				this.module.getElement('.slideshow_edit').addClass('draggable');
			}
		},
	
		saveCaption:function(event,form){
			event.stop();
			this.setFeedback('save:start',form.getElement('.feedback'));
			TextElement.saveText(form.getElement('textarea'));
			form.set('send',{
				onComplete:function(response){
					TextElement.unlockText(form.getElement('textarea'));
					if (handleError(response))
						return this.setFeedback('save:error',form.getElement('.feedback'));
					
					this.reloadPublishPanel();
					this.setFeedback('save:done',form.getElement('.feedback'));
				}.bind(this)
			});
			form.send();
		},
	
		shouldUnloadEdit : function() {
			for (editor in this.editors)
				if (!TextElement.askToSaveIfDirty(this.editors[editor]))
					return false;
		},
	
		unloadEdit:function(panelname){
			this.sortable.disable();
		
			this.module.getElements('.editing textarea').each(TextElement.unload);
		},
		reloadPreview : function(){
			this.module.getElement('.thumbnail_settings').fireEvent('submit');
		},
	
		loadPreview:function(panelname){
			this.current_slide = (this.module.getElement('.thumbnails').getElement('a.next')) ? 1 : 0;
			var panel=this.getPanel(panelname);
			panel.getElement('.thumbnails').getElements('li').each(function(li){
				li.getElements('a').removeEvents('click');
				li.getElement('a').addEvent('click',function(event){
					if (event)
						event.stop();
					var a = li.getElement('a');
					var slides = li.getParent().getChildren();
					a.blur();
					var current_slide = this.current_slide;
					
					if (a.hasClass('next') && this.current_slide < (slides.length - 2))
						this.current_slide++;
					else if (a.hasClass('previous') && this.current_slide > 1)
						this.current_slide--;
					else if (!a.hasClass('previous') && !a.hasClass('next'))
						this.current_slide = slides.indexOf(li);
						
					if (panel.getElement('a.next')){
						panel.getElement('a.next').setClass('hide', (this.current_slide == slides.length - 2));
						panel.getElement('a.previous').setClass('hide', (this.current_slide == 1));
					}
					
					li.getParent().getElements('.selected').each(function(el){
						el.removeClass('selected');
					}.bind(this));
					slides[this.current_slide].addClass('selected');
					panel.getElement('.slides').load(slides[this.current_slide].getElement('a').get('href') + '&ajax=1');
				}.bind(this));
			},this);
			var first = panel.getElement('.thumbnails li a');
			if (first)
				(panel.getElements('.thumbnails li a')[this.current_slide] || first).fireEvent('click');
		},	
		unloadPreview:function(panelname){
		},
		formHandler : function(event,form){
			if(event && event.stop)
				event.stop();
			var update = form.getProperty('update');
			form.set('send',{
				onComplete:function(response){
					if (handleError(response))
						return false;
					
					var result=this.module.getElement('.preview_content .thumbnails');
					result.set('html',response);
					this.getPanel('preview').getElement('.slides').load(result.getElement('li.selected a').get('href') + '&ajax=1');
					result.erase('initialized');
				}.bind(this)
			});
			form.send();
		},
		
		reload : function(fn){
			this.sortable.detach();
			this.sortable.list.set('load',{onComplete:function(){
				this.sortable.elements = [];
				this.sortable.handles = [];
				this.sortable.reinitialize();
				this.initializeSlides();
				this.reloadPreview();
				if (fn)
					fn();
			}.bind(this)});
			this.sortable.list.load('/'+Session.portfolio.url+'/'+Navigation.page_url+'/slideshow/get_edit_list?ajax=1&moduleinstid='+this.id)
		},
	
		execCommand : function(command,popup,file){
			switch(command){
				case 'UploaderFinishedMultiple':
					this.reload();
					break;
				case 'UploaderFinishedSingle':
					this.reloadPublishPanel();
					this.reloadPreview();
					this.module.getElement('#slide_'+this.slideId+' .thumbnail').set('html', file.thumbnail.html);
					break;
				case 'UploaderChoseWeb':
					var thumb = this.module.getElement('#slide_'+this.slideId+' .thumbnail');
					if (thumb){
						this.reloadPublishPanel();
						this.reloadPreview();
						thumb.set('html', file.thumbnail.html);
						popup.close();
					}else{
						this.reload(popup.close);
					}
					break;
				case 'UploaderSubmitted':
				case 'UploaderClosing':
					popup.close();
					break;
				default:
					this.parent.apply(this, arguments);
			}
		}

	
	});

	$extend(SlideshowModule,{ //static methods
		instances:{}	
	});


	var Reorder = new Class({
		Implements : [Events,Options],
		options :  {
			handle : '.handle',
			ghost : false,
			serialCallback : function(element){return element.getProperty('id')},
			scrollDistance : 30
		},
	
		initialize : function(list,options){
			this.setOptions(options);
			this.list = $(list);
			this.handles = [];
			this.elements = [];
			this.bound = {
				start : [],
				move : this.move.bindWithEvent(this),
				end : this.end.bindWithEvent(this)
			};
			this.idle = true;
			this.windowScroll = new Fx.Scroll(window);
			this.reinitialize();
		},
	
		reinitialize : function(){
			this.detach();
			this.handles = [];
			this.elements = this.list.getChildren();
			this.elements.each(function(element){
				this.handles.push(element.getElement(this.options.handle) || element);
			},this);
			this.attach();
		},
	
		enable : function(){
			this.idle = true;
		},
	
		disable : function(){
			this.idle = false;
		},
	
		attach : function(){
			this.bound.start = [];
			this.elements.each(function(element,i){
				this.bound.start[i] = this.start.bindWithEvent(this,element);
				this.handles[i].addEvent('mousedown',this.bound.start[i]);
			},this);
		},
	
		detach : function(){
			this.elements.each(function(element,i){
				this.bound.start[i] = this.start.bindWithEvent(this,element);
				if (!Browser.Engine.trident)
					this.handles[i].removeEvent('mousedown',this.bound.start[i]);
			},this);
		},
	
		start : function(event,element){
			if (!this.idle || event.rightClick) return;
			event.stop();
			this.element = element;
			if (this.options.ghost){
				var position = this.element.getCoordinates(this.list);
				this.offset = {
					x : event.page.x - position.left,
					y : event.page.y - position.top
				}
				this.ghost = this.element.clone();
				this.ghost.setStyles({
					position : 'absolute',
					left : event.page.x - this.offset.x,
					top : event.page.y - this.offset.y,
					width : position.width,
					height : position.height,
					zIndex : '1000',
					opacity : .6
				});
				this.ghost.inject(this.list,'bottom');
			}
		
			document.addEvent('mousemove',this.bound.move);
			document.addEvent('mouseup',this.bound.end);
			this.bound.scroll = this.scroll.periodical(50,this);
		
			this.fireEvent('onStart', [this.element,event]);
		},
	
		move : function(event,element){
			event.stop();
			this.lastEvent = event;
			var windowScrollTop  = window.getScroll().y;
			var windowScrollHeight = window.getScrollSize().y;
			var windowHeight = window.getSize().y;
		
			if ((event.page.y - windowScrollTop) < this.options.scrollDistance && windowScrollTop > 0)
				this.scrollDirection = 'up';
			else if ((windowScrollTop + windowHeight - event.page.y) < this.options.scrollDistance && (windowScrollHeight - windowScrollTop) > this.options.scrollDistance)
				this.scrollDirection = 'down';
			else
				this.scrollDirection = '';

			if (this.options.ghost){
				this.ghost.setStyles({
					left : event.page.x - this.offset.x,
					top : event.page.y - this.offset.y
				});
			}
		
			var sibling = this.posFinder(event.page);
		
			if (sibling){
				this.element.inject(sibling.element,sibling.position);
				this.fireEvent('onChange',[this.element,event]);
			}
		},
	
		scroll:function(){
			if (this.scrollDirection == 'up'){
				this.windowScroll.set(0, window.getScroll().y - this.options.scrollDistance);
				this.lastEvent.page.y -= this.options.scrollDistance;
				this.move(this.lastEvent);
			}else if (this.scrollDirection == 'down'){
				this.windowScroll.set(0, window.getScroll().y + this.options.scrollDistance);
				this.lastEvent.page.y += this.options.scrollDistance;
				this.move(this.lastEvent);
			}
		},
	
		posFinder: function(mouse){
				var coords = this.list.getCoordinates();
				var module = null;
				if (mouse.x > coords.left && mouse.x < coords.right && mouse.y > coords.top && mouse.y < coords.bottom){
					var children = this.list.getChildren();
					for (var i=0; i < children.length; i++) {
						var mCoords = children[i].getCoordinates();
						if (mouse.y < (mCoords.top + mCoords.height/2))
							return {element:children[i],position:'before'};
					}
					return {element:this.list,position:'inside'};
				}
			return false;
		},
	
	
		end : function(event,element){
			if (this.options.ghost)
				this.ghost.destroy();

			$clear(this.bound.scroll);
			document.removeEvent('mousemove',this.bound.move);
			document.removeEvent('mouseup',this.bound.end);
			this.idle = true;
			this.fireEvent('onComplete',[this.element,event]);
		},
	
		serialize : function(){
			var serial = [];
			this.elements.each(function(element){
				if (element != this.ghost) serial.push(this.options.serialCallback(element));
			},this);
			return serial;
		}
	});
}else{
	SlideshowModule = new Class({
		initialize : function(module){
			this.module = $(module);
			this.content = this.module.getElement('.slides');
			this.slides = this.content.getChildren();
			this.slide = this.slides[0];
			this.current_slide = this.module.getElements('.slideshow_thumbnails li').indexOf(this.module.getElement('.slideshow_thumbnails li.selected'));
			for (var i=1; i < this.slides.length; i++) {
				this.slides[i].addClass('hidden');
			};
			this.thumbnails = this.module.getElements('.slideshow_thumbnails a');
			this.thumbnails.each(function(thumbnail){
				thumbnail.addEvent('click',function(event){
					event.stop();
					thumbnail.blur();
					this.content.setStyle('height', this.content.getScrollSize().y);

					var slides = thumbnail.getParent().getParent().getChildren();
					var current_slide = this.current_slide;
					

					if (thumbnail.hasClass('next') && this.current_slide < this.thumbnails.length-2)
						this.current_slide++;
					else if (thumbnail.hasClass('previous') && this.current_slide > 1)
						this.current_slide--;
					else if (!thumbnail.hasClass('previous') && !thumbnail.hasClass('next'))
						this.current_slide = slides.indexOf(thumbnail.getParent());
					if (this.current_slide == current_slide)
						return;
					if (this.slide)
						this.slide.addClass('hidden');
						
					var li = thumbnail.getParent();
					
					li.getParent().getElements('.selected').each(function(el){
						el.removeClass('selected');
					}.bind(this));
					slides[this.current_slide].addClass('selected');

					var slide = $(this.thumbnails[this.current_slide].get('content'));
					if (slide){
						this.slide = slide;
						this.slide.removeClass('hidden');
						this.content.setStyle('height','');
					}else{
						new Request.HTML({url:this.thumbnails[this.current_slide]+'&ajax=1',onComplete:function(response){
							this.content.adopt(response);
							this.slide = $(this.thumbnails[this.current_slide].get('content'));
							this.content.setStyle('height','');
						}.bind(this)}).send();
					}
				}.bind(this));
			},this);
		}
	});
}