window.addEvent('domready', function() {
	var previewables = $$('.previewable');
	previewables.each(function(previewable) {
		previewable.previewable = new Previewable(previewable);
	});
	
	var live_previewables = $$('.live-previewable');
	live_previewables.each(function(p) {
		p.previewable = new LivePreviewable(p);
	});
});

// Previewable elements (used in news editor) post using ajax to get
// 100% quality of preview. This is also because we do some other
// server-side filtering here.
var Previewable = new Class({
	ajaxWaiting : false,
	previewable_id : null,
	ajaxObject : null,
	ajaxTimer : null,
	
	initialize : function(element) {
		element.onkeydown = this.handleEdit.bindWithEvent(this);
		this.previewable_id = element.id;
		this.handleEdit();
	},
	
	handleEdit : function(incoming_event) {
		if (this.ajaxTimer) {
			clearTimeout(this.ajaxTimer);
		}
		this.ajaxTimer = this.ajaxPost.delay(1000, this);
	},
	
	ajaxPost : function() {
		var url = '';
		
		switch (this.previewable_id) {
			case 'news-body': url = '/news/ajax/preview'; break;
			case 'post_body': url = '/forum/ajax/preview'; break;
		}
		this.ajaxObject = new Ajax(url, {
			method : 'post',
			postBody : {body : $(this.previewable_id).value},
			onComplete : this.ajaxPostComplete,
			update : $(this.previewable_id + '-preview')
		});
		this.ajaxObject.request();
		this.ajaxWaiting = false;
	},
	
	ajaxPostComplete : function() {
		this.ajaxWaiting = false;
	}
});

// LivePreviewable elements (used in forum posts) don't post using
// ajax, and also have a more limited subset of Textile (i.e. no
// block-level elements).
var LivePreviewable = new Class({
	initialize : function(element) {
		element.onkeyup = this.handleEdit.bindWithEvent(this);
		this.previewable_element = element;
		this.handleEdit();
	},
	
	handleEdit : function(incoming_event) {
		// see textile.js for implementation of superTextile()
		var str = this.previewable_element.value;
		str = this.customFormats(str);
		str = superTextile(str);
		
		$(this.previewable_element.id + '-preview').innerHTML = str;
	},
	
	customFormats : function(str) {
		str = str.replace(/>/g, '&gt;');
		str = str.replace(/</g, '&lt;');
		
		while (str.match(/&lt;citat(.*)&gt;/i) && str.match(/&lt;\/citat&gt;/i)) {
			str = str.replace(/&lt;citat(.*?)&gt;([^\0]*)&lt;\/citat&gt;/igm, function(str, quote_args, quote_body) {
				if (quote_args.length > 0 && quote_args[0] == '=') {
					return '<blockquote><div class="from">' + quote_args.substr(1) + ' skrev:</div>' + quote_body + '</blockquote>';
				} else {
					return '<blockquote>' + quote_body + '</blockquote>';
				}
			});
		}
		return str;
	}
});