/*
Elxis CMS - plugin eLink
Created by Ioannis Sannos
Copyright (c) 2006-2025 elxis.org
https://www.elxis.org
*/

/* ADD A LINK TO A CATEGORY */
function elinkToCategory() {
	var selObj = document.getElementById('elinkctg');
	var seolink = selObj.options[selObj.selectedIndex].value;
	if (seolink == '') { return false; }
	var seltext = selObj.options[selObj.selectedIndex].text;
	seltext = seltext.replace(new RegExp("^[\\s]+", "g"), '');
	seltext = seltext.replace(new RegExp("^[\-]+", "g"), '');
	seltext = seltext.replace(new RegExp("^[\\s]+", "g"), '');
	var pcode = '<a href="#elink:content:'+seolink+'">'+seltext+'</a>';
	addPluginCode(pcode);
}

/* BROWSE CATEGORY ARTICLES */
function elinkBrowseCategory(plugid, fn) {
	var selObj = document.getElementById('elinkctg');
	var ctg_str = selObj.options[selObj.selectedIndex].id;
	var catid = ctg_str.replace(/ctg_/g, '');
	catid = parseInt(catid, 10);
	if (catid < 0) { return false; }
	var loadingtext = document.getElementById('lng_wait').innerHTML;
	var edata = {'id':plugid, 'fn':fn, 'catid':catid, 'task':'handler'};
	var eurl = document.getElementById('plugbase').innerHTML;
	var successfunc = function(xreply) {
		document.getElementById('elinkarticles').innerHTML = xreply;
		elinkOnLoadLinks();
	}
	elxAjax('POST', eurl, edata, 'elinkarticles', loadingtext, successfunc, null);
}

function elinkOnLoadInterface() {
	if (!document.getElementById('plugelinktoctg')) { return; }
	document.getElementById('plugelinktoctg').addEventListener('click', function(e){ e.preventDefault(); elinkToCategory(); }, false);
	document.getElementById('plugelinkbrowsectg').addEventListener('click', function(e){
		let pluginid = this.getAttribute('data-plugin');
		let fn = this.getAttribute('data-fn');
		elinkBrowseCategory(pluginid, fn);
	}, false);
	elinkOnLoadLinks();
}

function elinkOnLoadLinks() {
	let elinks = document.querySelectorAll('a[data-elinkpcode]');
	if (elinks.length > 0) {
		for (let w=0; w < elinks.length; w++) {
			elinks[w].addEventListener('click', function(e){
				let pcode = this.getAttribute('data-elinkpcode');
				e.preventDefault();
				addPluginCode(pcode);
			}, false);
		}
	}
}

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

