/* LINK TO A FOLDER */
function egal5toFolder() {
	var selObj = document.getElementById('egalleryctg');
 	var fpath = selObj.options[selObj.selectedIndex].value;
	if (fpath != '') {
		var relp = selObj.getAttribute('data-relpath');
		var code = '{gallery}'+relp+fpath+'{/gallery}';
		addPluginCode(code);
	} else {
		return;
	}
}

/* LIST FOLDER IMAGES */
function egal5FolderImages(plugid, fn) {
	var selObj = document.getElementById('egalleryctg');
	var fpath = selObj.options[selObj.selectedIndex].value;
	if (fpath == '') {
		document.getElementById('egalimages').innerHTML = '';
		return;
	}
	var edata = { 'id':plugid, 'fn':fn, 'fpath':fpath, 'task':'handler', 'act':'list' };
	var eurl = document.getElementById('plugbase').innerHTML;
	var successfunc = function(xreply) {
		elx5StopPageLoader();
		document.getElementById('egalimages').innerHTML = xreply;
		plugGalOnLoadLinks();
	}
	var errorfunc = function (XMLHttpRequest, textStatus, errorThrown) {
		elx5StopPageLoader();
		alert('Action failed! '+errorThrown);
	};
	elx5StartPageLoader();
	elxAjax('POST', eurl, edata, 'egalimages', null, successfunc, errorfunc);
}

/* SUBMIT UPLOAD GALLERY FORM */
function plugGallerySubmit() {
	var selObj = document.getElementById('galfolder');
 	var folder = selObj.options[selObj.selectedIndex].value;
	var newfolder = document.getElementById('galnewfolder').value;
	if (folder == '') {
		if (newfolder == '') { alert('Select a folder to upload images!'); return false; }
	}
	if (newfolder != '') {
		var reg = /^([a-zA-Z0-9_-]+)$/;
		if (!reg.test(newfolder)) { alert('Invalid folder name!'); return false; }
	}
	document.pluggalform.submit();
	return true;
}

/* ADD IMAGE CAPTION */
function plugGalleryAddCaption(elid, act, pluginid, fn) {
	var initvalue = '';
	var prompttxt = 'Caption';
	if (act == 'edit') { initvalue = document.getElementById(elid).innerHTML; }
	if (document.getElementById('plugal_lng_cap')) { prompttxt = document.getElementById('plugal_lng_cap').innerHTML; }

	var successfunc = function(xreply) {
		try {
			var jsonObj = JSON.parse(xreply);
		} catch(e) {
			return false;
		}
		if (parseInt(jsonObj.success, 10) == 1) {
			document.getElementById(elid).className = 'plug_gallery_editcap';
			document.getElementById(elid).innerHTML = caption;
			document.getElementById(elid).removeEventListener('click', function(e){}, false);//this is wrong, must be assigned to var to be removed
			document.getElementById(elid).addEventListener('click', function(e){
				e.preventDefault();
				plugGalleryAddCaption(elid, 'edit', pluginid, fn);
			}, false);
		}
	}

	var errorfunc = function (XMLHttpRequest, textStatus, errorThrown) {}

	var caption = prompt(prompttxt, initvalue);
	if (caption != null) {
		var rnd = Math.floor((Math.random()*100)+1);
		var eurl = document.getElementById('plugal_url').innerHTML;
		var image = document.getElementById(elid).getAttribute('data-img');
		var fpath = document.getElementById(elid).getAttribute('data-path');
		var edata = { 'task': 'handler', 'act':'setcaption', 'id':pluginid, 'fn': fn, 'caption': caption, 'image':image, 'fpath':fpath, 'rnd':rnd };
		elxAjax('POST', eurl, edata, null, null, successfunc, errorfunc);
	}
}

/* DELETE GALERY IMAGE */
function plugGalleryDeleteImage(grnd, gi, pluginid, fn) {
	var confirmtxt = document.getElementById('plugal_lng_sure').innerHTML;

	var successfunc = function(xreply) {
		try {
			var jsonObj = JSON.parse(xreply);
		} catch(e) {
			return false;
		}
		if (parseInt(jsonObj.success, 10) == 1) {
			var objTbl = document.getElementById('plug_gallery'+grnd);
			var rowid = 'plugal'+grnd+'_row'+gi;
			if (objTbl.rows.length > 0) {
				for (var i = 0; i < objTbl.rows.length; i++) {
					if (objTbl.rows[i].id == rowid) {
						objTbl.deleteRow(i);
						break;
					}
				}
			}
		}
	}

	var errorfunc = function (XMLHttpRequest, textStatus, errorThrown) {}

	if (confirm(confirmtxt)) {
		var rnd = Math.floor((Math.random()*100)+1);
		var eurl = document.getElementById('plugal_url').innerHTML;
		var elid = 'plugal'+grnd+'_dimg'+gi;
		var image = document.getElementById(elid).getAttribute('data-img');
		var fpath = document.getElementById(elid).getAttribute('data-path');
		var edata = { 'task': 'handler', 'act':'delimage', 'id':pluginid, 'fn': fn, 'image':image, 'fpath':fpath, 'rnd':rnd };
		elxAjax('POST', eurl, edata, null, null, successfunc, errorfunc);
	}
}

function plugGalOnLoadLinks() {
	let acaps = document.querySelectorAll('a.plug_gallery_addcap');
	if (acaps.length > 0) {
		for (let w=0; w < acaps.length; w++) {
			acaps[w].addEventListener('click', function(e){
				let arnd = this.getAttribute('data-rnd');
				let ai = this.getAttribute('data-i');
				let aplugin = this.getAttribute('data-plugin');
				let afn = this.getAttribute('data-fn');
				e.preventDefault();
				plugGalleryAddCaption('plugal'+arnd+'_img'+ai, 'add', aplugin, afn);
			}, false);
		}
	}
	let ecaps = document.querySelectorAll('a.plug_gallery_editcap');
	if (ecaps.length > 0) {
		for (let w=0; w < ecaps.length; w++) {
			ecaps[w].addEventListener('click', function(e){
				let arnd = this.getAttribute('data-rnd');
				let ai = this.getAttribute('data-i');
				let aplugin = this.getAttribute('data-plugin');
				let afn = this.getAttribute('data-fn');
				e.preventDefault();
				plugGalleryAddCaption('plugal'+arnd+'_img'+ai, 'edit', aplugin, afn);
			}, false);
		}
	}

	let dimgs = document.querySelectorAll('a.plug_gallery_delete');
	if (dimgs.length > 0) {
		for (let w=0; w < dimgs.length; w++) {
			dimgs[w].addEventListener('click', function(e){
				let arnd = this.getAttribute('data-rnd');
				let ai = this.getAttribute('data-i');
				let aplugin = this.getAttribute('data-plugin');
				let afn = this.getAttribute('data-fn');
				e.preventDefault();
				plugGalleryDeleteImage(arnd, ai, aplugin, afn);
			}, false);
		}
	}
}

function plugGalOnLoadInterface() {
	if (!document.getElementById('pgaltofoldlink')) { return; }
	document.getElementById('pgaltofoldlink').addEventListener('click', function(e){ e.preventDefault(); egal5toFolder(); }, false);
	document.getElementById('egalleryctg').addEventListener('change', function(){
		let pluginid = this.getAttribute('data-plugin');
		let fn = this.getAttribute('data-fn');
		egal5FolderImages(pluginid, fn);
	}, false);

	plugGalOnLoadLinks();

	if (document.getElementById('fmrtedit')) {
		document.getElementById('fmrtedit').addEventListener('submit', function(e){
			e.preventDefault();
			plugGallerySubmit();
		}, false);
	}

	let dlinks = document.querySelectorAll('a[data-fimgdelimage]');
	if (dlinks.length > 0) {
		for (let q=0; q < dlinks.length; q++) {
			dlinks[q].addEventListener('click', function(e){
				let fimgdelimage = this.getAttribute('data-fimgdelimage');
				e.preventDefault();
				elx5FileimgDeleteImage(fimgdelimage);
			}, false);
		}
	}
}

if (document.getElementById('pgaltofoldlink')) {
	plugGalOnLoadInterface();
} else {
	if (document.readyState != 'loading') {
		plugGalOnLoadInterface();
	} else if (document.addEventListener) {
		document.addEventListener('DOMContentLoaded', function(){ plugGalOnLoadInterface(); });
	} else {
		document.attachEvent('onreadystatechange', function() { if (document.readyState == 'complete') { plugGalOnLoadInterface(); } });
	}
}
