/**************************************************************

        Script          : superGallery - Drag extension
        Version         : 2
        Authors         : poudro -  http://scripts.poudro.org   (thanks to Olivier Couston for some help on 1.2 rewrite of code)
        Desc            : Fully functional picture gallery using mootools
        Licence         : Open Source MIT Licence

**************************************************************/

SuperGallery.implement({
	buildDrag: function() {
				this.draggable = true;
			if(Browser.Engine.trident)
				document.ondragstart = function (){return false;}
			this.dropBar = new Element('div',{
				'styles':{
					'height':100,
					'width':this.options.dropArea,
					'border':this.options.dropBarBorder,
					'background':this.options.dropBarOut,
					'text-align':'center',
					'overflow':'auto',
					'opacity':0.75,
					'margin-top':10,
					'float':'right'
				}
			}).inject(this.dropAreaContainer);
			this.saveButton = new Element('button',{
				'type':'button',
				'html': this.options.saveSelectionButtonText,
				'events':{
					'click':this.saveSelected.bindWithEvent(this)
				}
			}).inject(this.dropBar);
			

			
			Cookie.write('superGallery','test');
			var testCookie = Cookie.read('superGallery');

			if (!testCookie)
			{
				if ($('_ssid'))
					this.ssid = this.options.saveSessionName+"="+$('_ssid').get('html');
				else
					this.ssid = "nothing__I_need_ssid__read_README";

				this.saveListRequest = new Request ({
					method:'get', 
					url: this.options.savelistNoCookieAJAX,
					onComplete: function (response) {
						var regexp1 = new RegExp(";;");
						var regexp2 = new RegExp(",");
					
						var temp = response.split(regexp1);
	
						if (temp.length==2)
						{
							var keys = temp[0].split(regexp2);
							var values = temp[1].split(regexp2);	
							
							for (i=0; i<keys.length; ++i)
								this.saveList.set(keys[i],values[i]);
								
							this.iniPopulateDropArea();
						}
	
					}.bind(this)
				});
			}

			this.saveList = new Hash.Cookie("saveList", {autoSave: true});
			var searchString = new RegExp("retainSelection");
			if(location.href.split('#')[0].test(searchString)) {
				if (this.ssid)
					this.saveListRequest.send(this.ssid+'&read');
				else 
					this.iniPopulateDropArea();
			}
			else {
				if (this.ssid)
					this.saveListRequest.send(this.ssid+'&empty');
				this.saveList.empty();
			}
			
			
			this.spaceBeforeInject = new Element('div',{'styles':{'font-size':1,'line-height':0.,'margin-top':2, 'position':'relative', 'top':0, 'left':0, 'width':this.options.dropArea-10}});
			this.spaceBeforeInject.set('morph',this.options.dropAreaTransitions);
	},

	iniPopulateDropArea: function () {
		if (this.saveList.getValues().length!=0) {
			this.dropBarEarlyInjects = new Asset.images(this.saveList.getKeys(),{
				onComplete: function() {
					this.dropBarEarlyInjects.reverse();
					this.dropBarEarlyInjects.each(function(image){
						var h=image.height;
						var w=image.width;
						if (h>w) {
							w = (this.options.dropArea-10)*w/h;
							h = this.options.dropArea-10;
						}
						else {
							h = (this.options.dropArea-10)*h/w;
							w = this.options.dropArea-10;
						}
						image.setStyles({'width':w,'height':h,'position':'relative','top':0,'left':((Browser.Engine.trident) ? 0 : (this.options.dropArea-w)/2),'display':'block','margin-top':2}).inject(this.dropBar);
						this.dropBar.setStyle('height',this.dropBar.getCoordinates().height+h+2);
					},this);
				}.bind(this)
			});
			this.saveButton.erase('disabled');
		}
	},


	startDrag:function (e){
		if (!this.loaded) return;
		var event = new Event(e).stop();
		var image = $(event.target);
		this.mouseDown = true;
		image.fireEvent('mouseleave',e);
		this.drag.delay(200,this,[image,event]);
		return false;
	},

	drag:function(image,ev) {
		if (this.Moving) return;
		if(this.mouseDown){
		this.mouseCoords = ev.page;
			if (image.retrieve('turned')){
				var h = this.options.dropArea-10;
				var w = h*image.retrieve('ratio'); 
			}else{
				var w = this.options.dropArea-10;
				var h = w/image.retrieve('ratio'); 
			}
			if (this.images.has(image.get('src'))) {
				var imageToClone = image;
			} else {
				var imageToClone = this.loadedThumbs[this.images.getKeys().indexOf(this.images.indexOf(image.get('src')))];
			}
			
			
			this.clone =  imageToClone.clone();
			this.clone.store('left',ev.page.x-15);
			this.clone.store('top',ev.page.y-15);
			this.clone.set('src',imageToClone.get('src'));
			this.clone.setStyles({
				'width':w,
				'height':h,
				'top':ev.page.y-15,
				'left':ev.page.x-15,
				'z-index':500,
				'cursor':'move',
				'opacity':0.5,
				'margin-top':2
			}).inject(document.body);
			this.dragged_img = this.clone.makeDraggable({
				droppables: [this.dropBar],
				snap: 0,
				onDrop: function(element,droppable) {
					this.mouseDown=false;
					this.dragged_img.detach();
					this.dropBar.removeEvents();
					var morph = this.clone.get('morph');
					if(droppable){
						this.dropBar.setStyle('background', this.options.dropBarOut);
						var imagepath = this.images.get(this.clone.get('src')).substring(this.images.get(this.clone.get('src')).lastIndexOf('/')+1);
						if(!this.saveList.contains(imagepath)){
							this.dropBar.morph({height:this.dropBar.getCoordinates().height+h+2});
							this.saveList.set(this.clone.get('src'),imagepath);
							if (this.ssid)
								this.saveListRequest.send(this.ssid+'&keys='+this.clone.get('src')+'&values='+imagepath);
							var lastImage = this.dropBar.getElement('button');
							if(this.saveList.getValues().length==1){
								this.saveButton.erase('disabled');
							}else{
								this.spaceBeforeInject.setStyles({'height':0,'margin-top':0}).inject(this.saveButton,'after');
								this.spaceBeforeInject.get('morph').start({'height':h,'margin-top':2});
							}
							lastImage = lastImage.getCoordinates();
							morph.start({'top':lastImage.bottom+2, 'left':this.dropBar.getCoordinates().left+(this.options.dropArea-w)/2,opacity:0.75}).chain(function(){
								this.spaceBeforeInject.dispose();
								this.clone.clone().setStyles({
									'position':'relative',
									'top':0,
									'left': ((Browser.Engine.trident) ? 0 : (this.options.dropArea-w)/2),
									'cursor':'default',
									'opacity':1,
									'display': 'block'
								}).inject(this.saveButton,'after');
								this.clone.destroy();
							}.bind(this));
						}else{
							morph.start({'top':this.clone.retrieve('top'), 'left':this.clone.retrieve('left'),opacity:0}).chain(function(){this.clone.destroy();}.bind(this));
						}
					}else{
						morph.start({'top':this.clone.retrieve('top'), 'left':this.clone.retrieve('left'),opacity:0}).chain(function(){this.clone.destroy();}.bind(this));
					}
				}.bind(this),
				onEnter: function () {
					this.dropBar.setStyle('background', this.options.dropBarOver);
				}.bind(this),
				onLeave: function () {
					this.dropBar.setStyle('background', this.options.dropBarOut);
				}.bind(this)
			});	

			this.clone.addEvent('mouseup', function(ev) {
				if ((this.mouseCoords.x==ev.page.x)&&(this.mouseCoords.y==ev.page.y)) {
					this.mouseDown=false;
					this.clone.destroy();
				}
			}.bindWithEvent(this));

			this.dragged_img.start(ev);
			return false;
		}
	}
});

