/*
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/



// CHTML creates real elements from HTML code contained in comments of the form "<!--(CHTML)...-->".
// This allows for conditional HTML to be defined outside of JS code.

var CHTML = {
	callbacks: [],
	parse: function() {
		comments = document.evaluate('//comment()', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		for(i = 0; i < comments.snapshotLength; i++) {
			comment = comments.snapshotItem(i);
			
			// Check it is a CHTML comment
			if(comment.nodeValue.substring(0,7) != '(CHTML)') continue;
			
			// Create the elements
			temp = document.createElement('div');
			temp.innerHTML = comment.nodeValue.substring(7);
			
			// Callbacks
			r = null;
			for(j = 0; j < this.callbacks.length; j++) {
				r = this.callbacks[j](temp);
				if(r == false) break;
				if(r instanceof Element) temp = r;
			}
			if(r == false) continue;
			
			// Replace the comment by the elements
			while(temp.childNodes.length != 0) {
				comment.parentNode.insertBefore(temp.childNodes[0], comment);
			}
			comment.parentNode.removeChild(comment);
		}
	}
};



// cookies class
var Cookies = {
	get: function(key) {
		var o = new RegExp("(?:^|; ?)" + escape(key) + "=([^;]+)").exec(document.cookie);
		return o && unescape(o[1]);
	},
	
	search: function(regex) {
		var o = new RegExp("(?:^|; ?)(" + regex + ")=").exec(document.cookie);
		return o && unescape(o[1]);
	},
	
	set: function(key, value, days) {
		var expires = "";
		if(days) expires = "; expires=" + new Date(new Date().getTime() + days*24*60*60*1000).toGMTString();
		document.cookie = escape(key) + "=" + escape(value) + expires + "; path=/";
	},
	
	erase: function(name) {
		this.set(name, "", -1);
	}
};



logged = Boolean(Cookies.search('ikiwiki_session_.*?'));

CHTML.callbacks.push(function(el){
	if(el.innerHTML.substring(0,8) == '(logged)') {
		if(!logged) return false;
		el.innerHTML = el.innerHTML.substring(8);
		return el;
	} else if(el.innerHTML.substring(0,9) == '(!logged)') {
		if(logged) return false;
		el.innerHTML = el.innerHTML.substring(9);
		return el;
	}
})

document.addEventListener('DOMContentLoaded', function(){CHTML.parse()}, false);




