var Gal = {};
Gal.aItems = []; // 'name1','name2','name2'
Gal.ulID = 'gallery1';
Gal.liPfx = 'li_';
Gal.reqProcessor = 'index.php';

(function() {

Gal.App = {
	init: function() {
		new YU.DDTarget(Gal.ulID);
		var aItems = Gal.aItems;
		for (var i=0; i<aItems.length; i++) new Gal.List(Gal.liPfx + aItems[i]);
	},
	getNewOrder: function() {
		var ul = YD.get(Gal.ulID), items = ul.getElementsByTagName('li'), str = ''; 
		for (var i=0; i<items.length; i++) str += this.getId(items[i].id) + '||';
		return str;
	},	
	getId: function(liId) { 
		return liId.replace(/li_/, ''); 
	},
	saveNewOrder: function() {
		Gal.Req.send('cmd=updateSeq&order='+this.getNewOrder());
	},
	updateCaption: function(id, newCaption, callback) {		
		Gal.Req.send('cmd=updateCaption&name='+id+'&caption='+newCaption, callback);
	},
	deleteImage: function(id) {
		Gal.Req.send('cmd=deleteImage&name='+id);
	},
	addImage: function(id) {
		if (!Gal.uploadDlg) {
			Gal.uploadDlg = new YW.Panel("uploadDlg", { draggable:false,close:true,visible:false,modal:true,fixedcenter:true} );
			Gal.uploadDlg.render(document.body);	
		}
		_dsp('uploadDlg',1);
		Gal.uploadDlg.show();
	}
};

Gal.Req = {
	handleSuccess: function(o) { if (console) console.log(o); },
	handleFailure: function(o) { if (console) console.log(o); },
	send: function(sParams, callback) {
		callback = callback || { success:Gal.Req.handleSuccess, failure:Gal.Req.handleFailure, scope:Gal.Req };
		YU.Connect.asyncRequest('POST', Gal.reqProcessor, callback, sParams);
	}
};

Gal.List = function(id, sGroup, config) {
	Gal.List.superclass.constructor.call(this, id, sGroup, config);
	var el = this.getDragEl();
	YD.setStyle(el, 'opacity', 0.67);
	this.goingUp = false;
	this.lastX = 0;
	this.lastY = 0;	
};

Y.extend(Gal.List, YU.DDProxy, {
	startDrag: function(x, y) {
		var dragEl = this.getDragEl(), clickEl = this.getEl();
		YD.setStyle(clickEl, 'visibility', 'hidden');
		dragEl.innerHTML = clickEl.innerHTML;
        YD.setStyle(dragEl, "color", YD.getStyle(clickEl, "color"));
        YD.setStyle(dragEl, "backgroundColor", YD.getStyle(clickEl, "backgroundColor"));
        YD.setStyle(dragEl, "border", "2px solid gray");		
	},	
	endDrag: function(e) {
		var srcEl = this.getEl(), proxy = this.getDragEl();
		YD.setStyle(proxy, 'visibility', '');
		var a = new YU.Motion(proxy, {points:{to:YD.getXY(srcEl)}}, 0.2, YU.Easing.easeOut);
		var proxyId = proxy.id, thisId = this.id;		
		a.onComplete.subscribe(function() {
			YD.setStyle(proxyId, 'visibility', 'hidden');
			YD.setStyle(thisId, 'visibility', '');
			Gal.App.saveNewOrder();
		});
		a.animate();
	},	
	onDragDrop: function(e, id) {
		if (YDDM.interactionInfo.drop.length === 1) {
			var pt = YDDM.interactionInfo.point, region = YDDM.interactionInfo.sourceRegion;
			if (!region.intersect(pt)) {
				var destEl = YD.get(id), destDD = YDDM.getDDById(id);
				destEl.appendChild(this.getEl());
				destDD.isEmpty = false;
				YDDM.refreshCache();				
			}				
		}
	},	
	onDrag: function(e) {
		var x = YE.getPageX(e), y = YE.getPageY(e);
		if (y<this.lastY || x<this.lastX) this.goingUp = true;
		else if (y>this.lastY || x>this.lastX) this.goingUp = false;
		this.lastX = x;
		this.lastY = y;
	},	
	onDragOver: function(e, id) {
		var srcEl = this.getEl(), destEl = YD.get(id);
		if (destEl.nodeName.toLowerCase() == 'li') {
			var orig_p = srcEl.parentNode, p = destEl.parentNode;
			if (this.goingUp) p.insertBefore(srcEl, destEl);
			else p.insertBefore(srcEl, destEl.nextSibling);
			YDDM.refreshCache();
		}
	}
});

YE.onDOMReady(Gal.App.init, Gal.App, true);

})();

YE.onContentReady('gallery1', function() {
    var oGallery = this, oLI = oGallery.getElementsByTagName('li')[0];
    var aMenuItems = ['Insert Before', 'Insert After', 'Move to Top', 'Move to Bottom', 'Edit Caption', 'Delete'];
    var oContextMenu = new YW.ContextMenu('contextMenu', {trigger:oGallery.childNodes, itemdata:aMenuItems, lazyload:true});

    function onContextMenuRender(p_sType, p_aArgs) { this.subscribe('click', onContextMenuClick) };
    oContextMenu.subscribe('render', onContextMenuRender);

    function onContextMenuClick(p_sType, p_aArgs) {
        var oItem = p_aArgs[1], /* item clicked */ oTarget = this.contextEventTarget, oLI;
        if (!oItem) return;
		oLI = oTarget.nodeName.toUpperCase()=='LI'?oTarget:YD.getAncestorByTagName(oTarget, 'LI');
		switch(oItem.index) {
			case 0: insertBefore(oLI); break;
			case 1: insertAfter(oLI); break;
			case 2: moveToTop(oLI); break;
			case 3: moveToBtm(oLI); break;
			case 4: editCaption(oLI); break;
			case 5: deleteImage(oLI); break;
		}
    }
   
    function insertBefore(p_oLI) {
		_gel('fldMethod').value = 'insertBefore';
		_gel('fldRefImg').value = Gal.App.getId(p_oLI.id);
		Gal.App.addImage();
	}
	
    function insertAfter(p_oLI) {
		_gel('fldMethod').value = 'insertAfter';
		_gel('fldRefImg').value = Gal.App.getId(p_oLI.id);
		Gal.App.addImage();
	}
    
	function editCaption(p_oLI) {
		var cap = YD.getLastChild(p_oLI).innerHTML;
		var input = prompt('Edit your caption', cap);
		if (!input) return;
		var callback = { success:function(){ YD.getLastChild(p_oLI).innerHTML = input; } };
		Gal.App.updateCaption(Gal.App.getId(p_oLI.id), input, callback);
	}
    
	function moveToTop(p_oLI) {
		var srcEl = p_oLI, destEl = YD.getFirstChild(oGallery);
		oGallery.insertBefore(srcEl, destEl);
		Gal.App.saveNewOrder();
	}
    
	function moveToBtm(p_oLI) {
		var srcEl = p_oLI, destEl = YD.getLastChild(oGallery);
		oGallery.insertBefore(srcEl, destEl); // workaround for insertAfter()
		oGallery.insertBefore(destEl, srcEl);
		Gal.App.saveNewOrder();
	}
	
    function deleteImage(p_oLI) {
		var isSure = confirm('Are you sure you want to delete this item?');
		if (!isSure) return;
        var oUL = p_oLI.parentNode;
        oUL.removeChild(p_oLI);
		Gal.App.deleteImage(Gal.App.getId(p_oLI.id));
    }
});