/*
	JCE.js: Journal CSS Editor; Editor and AJAX objects.
	Copyright (c) 2006-2009 Kalle Räisänen.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero 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 Affero General Public License for more details.

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

*/

var JCE_templates = {
	sleek_jhead: '<img src="http://s.deviantart.com/styles/minimal/minish/icon-journal.gif" '
                        + '  style="vertical-align: middle;" alt="" />'
	,sleek: 
		'<div class="journalcontrol journalcontrol-v5" id="thejournal"'+
		' style="position: relative; overflow: hidden;">'+
			'<div id="error-container"></div>'+
			'<div class="journalbox box">'+
				'<div class="boxtop journaltop">'+
					'<h2 id="jheader">'+
						'<img'+
						' src="http://s.deviantart.com/styles/minimal/minish/icon-journal.gif"'+
						' style="vertical-align: middle;" alt=""'+
						'/>'+
						'Devious Journal Entry'+
					'</h2>'+
					'Journal Entry: <span title="1d 20h ago" id="journal-date">Wed Sep 27, 2006, 5:16 PM</span>'+
				'</div>'+
				'<ul class="f list" id="gerund-top">'+
					'<li class="f a"><strong>Reading:</strong> Something</li>'+
					'<li class="f"><strong>Watching:</strong> Something else</li>'+
					'<li class="f a"><strong>Playing:</strong> With something</li>'+
				'</ul>'+
				'<div class="text pp journaltext" id="jcontent">'+
					//'%CONTENT%'+
				'</div>'+
				'<div class="c ppb alink journalbottom">'+
					'<a class="commentslink" href="#">No Comments</a>'+
					' | <a class="prevlink" href="#">Previous Journal Entries</a>'+
				'</div>'+
				'<ul class="f list" style="display: none;" id="gerund-bottom">'+
					'<li class="f a"><strong>Reading:</strong> Something</li>'+
					'<li class="f"><strong>Watching:</strong> Something else</li>'+
					'<li class="f a"><strong>Playing:</strong> With something</li>'+
				'</ul>'+
			'</div>'+
		'</div>'

	,gruze_jhead: '<img src="/minish/gruzecontrol/icons/journal.gif"'+
							' style="vertical-align:middle" alt=""/>'
	,gruze:
		'<div class="journalcontrol" style="margin:0;position:relative;overflow:hidden" id="journal-22104313" id="thejournal">'+
			'<div id="error-container"></div>'+
			'<div class="gr-box gr-genericbox">'+
				'<i class="gr1"><i></i></i>'+
				'<i class="gr2"><i></i></i>'+
				'<i class="gr3"><i></i></i>'+
				'<div class="gr-top">'+
					'<i class="tri"></i>'+
					'<div class="gr">'+
						'<h2 id="jheader"><img src="/minish/gruzecontrol/icons/journal.gif"'+
							' style="vertical-align:middle" alt=""/> Devious Journal Entry</h2>'+
						'<span title="1s ago" id="journal-date">Sun Dec 21, 2008, 11:17 PM</span>'+
					'</div>'+
				'</div>'+

				'<div class="gr-body">'+
					'<div class="gr">'+
						'<div class="grf-indent">'+
							'<ul class="f list" id="gerund-top">'+
								'<li class="f a"><strong>Listening to:</strong> Last Splash</li>'+
								'<li class="f"><strong>Reading:</strong> Albert Einstein. A Biography</li>'+
								'<li class="f a"><strong>Watching:</strong> Top Gear</li>'+
							'</ul>'+
							'<div class="text" id="jcontent" id="journal-date">'+
								//'%CONTENT%'+
							'</div>'+
							'<div class="c ppb alink bottom">'+
								'<a class="a commentslink" href="#comments">4 Comments</a>' +
        						'<span class="hsep"> | </span><a class="a prevlink" href="#">Previous Journal Entries</a>' +
							'</div>'+

							'<ul class="f list" id="gerund-bottom">'+
								'<li class="f a"><strong>Listening to:</strong> Last Splash</li>'+
								'<li class="f"><strong>Reading:</strong> Albert Einstein. A Biography</li>'+
								'<li class="f a"><strong>Watching:</strong> Top Gear</li>'+
							'</ul>'+
						'</div>'+
					'</div>'+
				'</div>'+
				'<i class="gr3 gb"></i>'+
				'<i class="gr2 gb"></i>'+
				'<i class="gr1 gb gb1"></i>'+
			'</div>'+
		'</div>'
};

var JCE = {
	VERSTAG:           'JCE 0.10.17'

	,DATE_MONTHS:      $w('Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec')
	,DATE_WEEKDAYS:    $w('Sun Mon Tue Wed Thu Fri Sat')
	,full_gruze:       false
	,GERUND_LIST : {
		'Listening to': 'Fear',
		'Reading':      'Pottery',
		'Watching':     'Commando Cody',
		'Playing':      'Saxomophone',
		'Eating':       'Grubs',
		'Drinking':     'Yes'
	}
	,gerund_lim:       6
	,IMG_GERUND_MOOD:  '<img src="http://e.deviantart.com/emoticons/moods/fear/horror/hysterical.gif"'
                        + ' /> Hysterical'
	,IMG_JOURNAL_HEAD: '<img src="http://s.deviantart.com/styles/minimal/minish/icon-journal.gif" '
                        + '  style="vertical-align: middle;" alt="" />'
	,journal_pos_curr: 0
	,poweruser:        true
	,THUMB_TPL: '<span class="shadow-holder"><span style="background-image: url(http://sh.deviantart.com/shadow/alpha-000000/2.6667-0.35/%width%/%height%/logo.png);" '
			+ 'class="shadow"><a href="http://www.deviantart.com/deviation/%devid%/"><img src="%thumbimg%" height="%height%" width="%width%" /></a></span></span>'
	,THUMBS:           [
		{
			'devid':     '84386103',
			'thumbimg':  'http://tn1-3.pv.deviantart.com/fs30/150/i/2008/121/2/5/Life_is_Hard_by_laurapalmer.jpg',
			'height':    150,
			'width':     145
		},
		{
			'devid':     '42183681',
			'thumbimg':  'http://tn1-4.pv.deviantart.com/fs12/150/i/2006/302/5/9/___there_was_a_time_before_you_by_dismarum.png',
			'height':    150,
			'width':     102
		},
		{
			'devid':     '77835374',
			'thumbimg':  'http://tn1-2.pv.deviantart.com/fs29/150/f/2008/050/6/3/bang_bang_by_meandermind.jpg',
			'height':    79,
			'width':     150
		},
		{
			'devid':     '51711044',
			'thumbimg':  'http://tn1-1.pv.deviantart.com/fs13/150/i/2007/084/d/d/Oxford_Comma_by_bananaprincess.jpg',
			'height':    59,
			'width':     150
		},
		{
			'devid':     '43926998',
			'thumbimg':  'http://tn1-2.pv.deviantart.com/fs12/150/i/2006/334/c/d/war_poem_by_inziladun.png',
			'height':    23,
			'width':     150
		},
		{
			'devid':     '34435644',
			'thumbimg':  'http://tn1-1.pv.deviantart.com/fs10/150/i/2006/158/a/b/electron_john_by_meandermind.jpg',
			'height':    150,
			'width':     107
		},
		{
			'devid':     '78920572',
			'thumbimg':  'http://tn1-4.pv.deviantart.com/fs29/150/i/2008/073/f/f/Journal_CSS_Editor_0_10_by_xork.png',
			'width':     150,
			'height':    132
		}
	]
	,update_last:      0
	,uptate_timer:     null
	,UPDATE_INTERVAL:  523


	,parse_tpl: function(tpl, data) {
		var out = tpl;
		for(var k in data) {
			var re = new RegExp('%' + k + '%', 'g'); 
			out = out.replace(re, data[k]);
		}
		return out;
	}


	,warn: function(message) {
		JCE.show_error(JCE.VERSTAG + ':',  message);
		setTimeout('JCE.delete_error_div()', 4500);
	}

	,create_error_div: function() {
		JCE.delete_error_div();

		$('error-container').insert('<div id="error-div" class="ppp h altaltview"></div>');
		$('error-div').insert('<i class="tl"></i><i class="tr"></i><i class="bl"></i><i class="br"></i>');
	}

	,delete_error_div: function() {
		if($('error-div')) $('error-div').remove();
	}

	,show_error: function(title, items) {
		if(!(items instanceof Array))
			items = [items];

		JCE.create_error_div();

		var err_msg = '<h3>' + title + '</h3><ul>'
		        + '<li>' + items.join('</li><li>') + '</li>'
		        + '</ul>'; 

		$('error-div').insert(err_msg);
	}

	,_r_mb: null

	,show_replace: function() {
		if(JCE._r_mb == null) {
			var id_f = 'jce-sr-f';
			var id_r = 'jce-sr-r';
			var mb = MsgBox.create(
				'Search &amp; Replace',
				'<p>'
				+ '<label><strong>Find</strong>: '
					+ ' <input type="text" id="' + id_f + '" />'
				+ '</label>'
				+ '</p><p>'
				+ '<label><strong>Replacement</strong>: '
					+ ' <input type="text" id="' + id_r + '" />'
				+ '</label>'
				+ '</p>'
				,
				function(res) {
					if(typeof res[id_f] == 'string' && res[id_f].length &&
					   typeof res[id_r] == 'string' && res[id_r].length) {
 						var re = new RegExp(res[id_f], 'g');

						alert(res[id_f] + ' : ' + res[id_r]);
						$('journal-css').update( $F('journal-css').replace(res[id_f], res[id_r]) );
						return true;
					} else {
						return false;
					}
				}
			);
			JCE._r_mb = mb;
		}

		MsgBox.show(JCE._r_mb);
	}

	,match_css_token: function(css_str, re_find, re_filter, mode, erroronfound) {
		var err_str = '';
		var tkns = css_str.match(re_find);
		var haystack;

		if(mode == 'css')          haystack = VALID_PROPERTIES;
		else if(mode == 'classes') haystack = DEVIANTART_CLASSES;
		else if(mode == 'ids')     haystack = DEVIANTART_IDS;

		var filter = (re_filter instanceof Array) ? re_filter : [re_filter, ''];

		if(tkns) {
			tkns = $A(map(tkns, function(str) { return str.replace(filter[0], filter[1])} )).uniq();

			$A(tkns).each( function(tkn) {
				var found = false;
				if(mode == 'css')
					tkn = tkn.replace(/^_/, '');

				if((typeof haystack[tkn] != 'undefined' && haystack[tkn] == true) || (mode == 'css' && tkn.match(/^-moz-/)))
					found = true;

				if((erroronfound && found) || (!erroronfound && !found))
					err_str +=
						(err_str != '' ? ', ' : '') +
						String(
							'<strong>#{tkn}</strong>&nbsp;[<a href="#ikwid-#{tkn}" title="I know what I\'m doing: Ignore \'#{tkn}\'" '+
							'  onclick="JCE.ignore_token(\'#{tkn}\', \'#{mode}\'); return false;">IKWID</a>]'
						).interpolate({tkn: tkn, mode: mode});        
			});
		}
		return err_str;
	}

	,validate_css: function(css_str) {
		var error_token = '';
		var errors = [];

		if(css_str.match(/\/\*|\*\//))
			errors.push('Comments aren\'t allowed.');
		if(error_token = css_str.match(/.+[\>,].+\{/))
			errors.push(
				'Only descendant, class selectors, and IDs are allowed (<code>'+ error_token +'</code>).'
			);
		if(error_token = css_str.match(/\@[a-z]+\b/))
			errors.push('<strong>' + error_token + '</strong> not supported.');
		if(error_token = css_str.match(/\\./))
			errors.push('Character escapes not supported (' + error_token + ')');
		if(
			(
				error_token = JCE.match_css_token
				(
					css_str,
					/[a-z\-]+\s*\:\s*[^{]*?[;\}]/gi,
					[/([a-z\-]+)\s*\:\s*[^{]*?[;\}]/i, '$1'],
					'css',
					false
				)
			) != ''
		)
			errors.push('Invalid property: ' + error_token);

		if(errors.length)
			JCE.show_error('CSS Error' + (errors.length > 1 ? 's' : '') + ': ', errors);

		return errors.length ? false : true;
	}

	,validate_names: function(css_str) {
		var error_token = '';
		var errors      = [];

		if((error_token = JCE.match_css_token(css_str, /\.[a-z0-9\-]+\s*[\>,\{]/gi, /[^a-z0-9\-]/gi, 'classes', true)) != '')
			errors.push('Class name(s) in use on deviantART: ' + error_token);

		if((error_token = JCE.match_css_token(css_str, /\#[a-z0-9\-]+\s*[\>,\{]/gi, /[^a-z0-9\-]/gi, 'ids', true)) != '')
			errors.push('ID(s) in use on deviantART: ' + error_token);

		if(errors.length)
			JCE.show_error('CSS Warning' + (errors.length > 1 ? 's' : '') + ': ', errors);
			
		return errors.length ? false : true;
	}

	,ignore_token: function(token, list) {
		if(list == 'css')          VALID_PROPERTIES[token]   = true;
		else if(list == 'classes') DEVIANTART_CLASSES[token] = false;
		else if(list == 'ids')     DEVIANTART_IDS[token]     = false;

		JCE.update_css();		
	}

	,_toggle_gruze: function() {
		var css = $F('journal-css');

		if(!css.match(/.journal(text|top|bottom|box)/)) {
			if(!JCE.full_gruze) {
				$('journal-preview').innerHTML = JCE_templates.gruze;
				JCE.IMG_JOURNAL_HEAD = JCE_templates.gruze_jhead;
				JCE.full_gruze = true;
			} else {
				return false;
			}
		} else if(JCE.full_gruze) {
			$('journal-preview').innerHTML = JCE_templates.sleek;
			JCE.IMG_JOURNAL_HEAD = JCE_templates.sleek_jhead;
			JCE.full_gruze = false;
		} else {
			return false;
		}

		return true;
	}

	,toggle_journal_pos: function() {
		$('posbutton').value = JCE.journal_pos_curr ? 'Left' : 'Right';
		$('journal-preview').setStyle({cssFloat: JCE.journal_pos_curr ? 'left' : 'right'});
		JCE.journal_pos_curr ^= 1;
	}

	,update_all: function() {
		if(!JCE.update_content())
			return false;
		if(!JCE.update_css())
			return false;

		JCE.update_gerunds();
		JCE.update_title();
	}

	,update_content: function() {
		var cont = $F('journal-content').replace(/\r?\n/g, "<br />");

		JCE.delete_error_div();

		if($('journal-restrict').checked) {
			if(new RegExp('\<\s*(?!(div|img))[^\>]+class="').exec(cont)) {
				JCE.show_error('HTML Warning:', 'Classes are only supported on divs and imgs.');
				return false;
			}
		}

		var i = 0;
		while(cont.match(/\:thumb\d+\:/)) {
			cont = cont.replace(/\:thumb\d+\:/, JCE.parse_tpl(JCE.THUMB_TPL, JCE.THUMBS[i]));
			i = (i + 1) % JCE.THUMBS.length;
		}

		$('jcontent').update(cont);

		JCE.update_date();
		return true;
	}

	,update_css: function() {
		if(JCE._toggle_gruze()) {
			JCE.update_content();
			JCE.update_gerunds();
			JCE.update_title();
		}

		var css = $F('journal-css');
		JCE.delete_error_div();

		if((!$('journal-restrict').checked || JCE.validate_css(css)) &&
		   (!$('journal-unique').checked   || JCE.validate_names(css)) ) {
			css = css.replace(/ ?!important/g, '');
			css =	"/* begin custom journal css */\n"
			    + css.replace(/;/g, ' !important;')
			    + "\n/* end custom journal css */\n";

			if($('journal-style').styleSheet) /* IE */
				$('journal-style').styleSheet.cssText = css;
			else if($('journal-style').innerHTML)
				$('journal-style').update(css);
			else
				JCE.warn("Can't update journal CSS!");

			JCE.update_date();
			return true;
		}
		return false;
	}

	,update_date: function() {
		var dt    = new Date();
		var hours = dt.getHours();
		var mins  = dt.getMinutes();
		var ampm  = 'AM';

		if(hours > 12) {
			hours -= 12;
			ampm = 'PM';
		}

		var dt_str = JCE.DATE_WEEKDAYS[dt.getDay()] + ' ' + JCE.DATE_MONTHS[dt.getMonth()] + ' ' + dt.getDate()
	   	        + ', ' + dt.getFullYear() + ', ' + hours + ':' + (mins < 10 ? '0' : '') + mins + ' ' + ampm;

		$('journal-date').innerHTML = dt_str;
	}

	,update_gerunds: function() {
		JCE.gerund_lim = $F('gerund-num');

		var v = $F('gerund-switch');
		$('gerund-top').style.display    = ((v == 0) ? 'block' : 'none');
		$('gerund-bottom').style.display = ((v == 1) ? 'block' : 'none');

		$('gerund-top').innerHTML = $('gerund-bottom').innerHTML = '';

		if(v > 1) return;

		var gobj = (v == 0) ? $('gerund-top') : $('gerund-bottom');

		var i = 0, mood = 0;

		if($('gerund-mood').checked) {
			gobj.innerHTML = '<li class="f a"><strong>Mood:</strong> ' + JCE.IMG_GERUND_MOOD + '</li>';
			i++;
			mood = 1;
		}

		for(var k in JCE.GERUND_LIST) {
			if((i - mood) == (JCE.gerund_lim))
				return;
			var li = document.createElement('li');
			li.className = 'f' + ((i++ % 2 == 0) ? ' a' : '');
			li.innerHTML = '<strong>' + k + ':</strong> ' + JCE.GERUND_LIST[k];
			gobj.appendChild(li);
		}

		JCE.update_date();
	}

	,update_title: function() {
		$('jheader').innerHTML = JCE.IMG_JOURNAL_HEAD + ' ' + $('journal-title').value;

		JCE.update_date();
	}

	,init: function() {
		var qvid;

		if(qvid = get_query_var('username')) {
			var jid;

			if(jid = get_query_var('id')) {
				JCE_AJAX.load_userpage_both(qvid, jid);
			} else {
				JCE_AJAX.load_userpage_both(qvid);
			}
		}

		if(qvid = get_query_var('pbcss'))
			JCE_AJAX.load_pastebin_css(qvid);
		if(qvid = get_query_var('pbcontent'))
			JCE_AJAX.load_pastebin_content(qvid);

		var watchees = {
			'journal-editor-form':   ['submit', function(evt) { JCE.update_all; Event.stop(evt); }],
			'journal-title':         ['keyup',  JCE.update_title],
			'journal-content':       ['keyup',  JCE.update_content],
			'journal-css':           ['keyup',  function(evt) {
				var tm   = (new Date()).getTime();
				var diff = tm - JCE.update_last;

				if(diff > JCE.UPDATE_INTERVAL) {
					JCE.update_css();
					JCE.update_last = tm;

					if(JCE.update_timer != null) {
						clearTimeout(JCE.update_timer);
						JCE.update_timer = null;
					}

				} else {
					JCE.update_timer = setTimeout('JCE.update_css()', JCE.UPDATE_INTERVAL - diff);
				}
			}],
			'journal-editor-update': ['click',  JCE.update_all],
			'journal-restrict':      null,
			'journal-unique':        null,
			'gerund-switch':         ['change', JCE.update_gerunds],
			'gerund-num':            null,
			'gerund-mood':           ['click',  JCE.update_gerunds],
			'posbutton':             ['click',  JCE.toggle_journal_pos],
			'journal-get-css':       ['click',  function() { JCE_AJAX.get_userpage_css(); }],
			'journal-get-content':   ['click',  function() { JCE_AJAX.get_userpage_content(); }],
			'journal-get-both':      ['click',  function() { JCE_AJAX.get_userpage_both(); }],
			'pastebin-get-css':      ['click',  function() { JCE_AJAX.get_pastebin_css(); }],
			'pastebin-get-content':  ['click',  function() { JCE_AJAX.get_pastebin_content(); }]
		};

		var p;
		for(var k in watchees) {
			if($(k)) {
				var w = watchees[k] || (watchees[k] = watchees[p]);
				$(k).observe(w[0], w[1]);
				p = k;
			}
		}

		if($('journal-content').value == '') {
			var cont = $('jcontent').innerHTML.replace(/([\r\n\t]|\r\n)+/g, ' ');
			$('journal-content').value = cont.replace(/ {2,}/g, ' ').replace(/^\s/,'');
		}

		JCE.update_all();
	}
};


var JCE_AJAX = {
	_msgboxes: {}

	,msgbox_history: {
		COOKIE_NAME: 'jce-ajax-fh'

		,_loaded: false

		,names: []

		,add: function(user, journal) {
			var uid = '-' + user;
			var jid = '-' + journal;

			if(typeof JCE_AJAX.msgbox_history.names[uid] != 'undefined') {
				var js = JCE_AJAX.msgbox_history.names[uid];
				for(var i = 0; i < js.length; i++) {
					if(js[i] == jid) return;
				}	
			} else {
				JCE_AJAX.msgbox_history.names[uid] = [];
			}

			if(journal != false)
				JCE_AJAX.msgbox_history.names[uid].push(jid);
		}

		,get: function() {
			if(!JCE_AJAX.msgbox_history._loaded) {
				JCE_AJAX.msgbox_history._loaded = true;
			}
			return JCE_AJAX.msgbox_history.names;
		}

		,get_HTML: function(target_uid, target_jid) {
			var ns   = JCE_AJAX.msgbox_history.get();
			var HTML = '';
			var i = 0;
			for(var k in ns) {
				if(k.match(/^-/)) {
					var nm = k.replace(/^-/, '');

					if(i)
						HTML += '; ';

					HTML += '<strong><a href="#' + nm + '" onclick="$(\'' + target_uid + '\').value = \''+ nm + '\'; '
							+'$(\''+ target_jid + '\').value = \'\'; return false;">' + nm + '</a></strong> ';

					if(ns[k].length) {
						var j  = 0;
						var js = ns[k];

						HTML += ' [ ';

						for(var i = 0; i < js.length; i++) {
							if(js[i].match(/^-/)) {
								if(j) HTML += ', ';
								jid = js[i].replace(/^-/, '');
								HTML += '<a href="#' + nm + jid + '" onclick="$(\'' + target_uid + '\').value = \''+ nm + '\'; '
									+'$(\''+ target_jid + '\').value = \'' + jid + '\'; return false;">' + jid + '</a> ';
								j++;
							}
						}

						HTML += '] ';
					}
					i++;
				}
			}
			if(i) {
				HTML = '<p><small>History: ' + HTML + '</small></p>';
			}

			return HTML;
		}

		,load: function() {
			var nm = COOKIE.get(JCE_AJAX.msgbox_history.COOKIE_NAME);
			if(nm != null) {
				alert(nm);
				var    nms = String(nm).evalJSON();
				return nms;
			}
			return [];
		}

		,save: function(nms) {
			var json = Object.toJSON(nms);
			alert(nms.length + ';;' + json);

			COOKIE.set(JCE_AJAX.msgbox_history.COOKIE_NAME, json, 7);
		}
	}

	,msgbox_pb: function(tit, callback) {
		if(typeof JCE_AJAX._msgboxes[tit] == 'undefined') {
			var mbin = 'jce-' + MsgBox._idify(tit);
			var mb = MsgBox.create(
				tit,
				'<p><label><strong>ID</strong>: '
				+ 'devart.pastebin.com/<input type="text" id="' + mbin + '" /></label>'
				+ '</p>',
				function(res) {
					if(typeof res[mbin] == 'string' && res[mbin].length) {
 						callback(res[mbin]);
						return true;
					} else {
						return false;
					}
				}
			);
			JCE_AJAX._msgboxes[tit] = mb;
		}
		MsgBox.show(JCE_AJAX._msgboxes[tit]);
	}

	,msgbox_da: function(tit, callback) {
		var id_u = 'jce-' + MsgBox._idify(tit) + '-user';
		var id_j = 'jce-' + MsgBox._idify(tit) + '-jid';

		if(typeof JCE_AJAX._msgboxes[tit] == 'undefined') {
			var mb = MsgBox.create(
				tit,
				'<p><strong>Username &amp; Journal-ID</strong>:</p>'
				+ '<input type="text" id="' + id_u + '" style="width: 6.5em; text-align: right;" />'
				+ '.deviantart.com/'
				+ (JCE.poweruser
					? '<em>journal/<input type="text" id="' + id_j + '" style="width: 6em;" /></em></p>'
					: '')
				+ '<div id="' + id_u + id_j +'">' + JCE_AJAX.msgbox_history.get_HTML(id_u, id_j) + '</div>' 
				,
				function(res) {
					if(typeof res[id_u] == 'string' && res[id_u].length) {
						JCE_AJAX.msgbox_history.add(res[id_u], typeof res[id_j] == 'undefined' ? false : res[id_j]);

 						callback(res[id_u], typeof res[id_j] == 'undefined' ? undefined : res[id_j]);
						return true;
					} else {
						return false;
					}
				}
			);
			JCE_AJAX._msgboxes[tit] = mb;
		} else {
			$(id_u + id_j).update(JCE_AJAX.msgbox_history.get_HTML(id_u, id_j));
		}
		MsgBox.show(JCE_AJAX._msgboxes[tit]);
	}

	,toggle_buttons: function (buttons, state) {
		if(typeof buttons != 'string') {
			for(var i = 0; i < buttons.length; i++)
				JCE_AJAX.toggle_buttons(buttons[i], state);
		} else {
			$(buttons).disabled = state;
		}
	}

	,fetch_page: function(url, pars, callback, button) {
		if(typeof button != 'undefined')
			JCE_AJAX.toggle_buttons(button, 'disabled');

		var req = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
				onComplete: function(req) {
					callback(req);
					if(typeof button != 'undefined')
						JCE_AJAX.toggle_buttons(button, '');
				}
			}
		);
	}

	,load_userpage: function (button, username, callback, jid) {
		if(typeof username == 'undefined' || username == null)
			username = prompt('Username:');

		if(username == '' || username == null)
			return false;

		var pars = 'username=' + username.replace(/[^a-z0-9\-]/gi, '');

		if(typeof jid != 'undefined' && jid.length)
			pars += '&jid=' + jid.replace(/[^0-9]/g, '');

		JCE_AJAX.fetch_page('/get_userpage.php', pars, callback, button);
	}

	,userpage_cssgotten: function(req) {
		var regex = new RegExp('<style type="text\/css">((.|\n|\r)*?)<\/style>', 'i');
		var css   = regex.exec(req.responseText);
		if(css) {
			css = css[1].replace(/body\.deviant div\.bubbleview div\.journalcontrol#journal-\d+ /g, '');
			css = css.replace(/body\.gruze div\.bubbleview div\.journalcontrol#journal-\d+ /g, '');
			css = css.replace(/\/\*(.|\n|\r)*?\*\//g, '');
			css = css.replace(/^\s*|\s*$/g, '');
			$('journal-css').value = css;

			JCE.update_css();
		} else {
			JCE.warn('Didn\'t find any CSS data!');
		}
	}

	,deentitise: function(str) {
			return str.replace(/&#(\d+);/g, function(str, p1, offset, s) {
				return String.fromCharCode(p1);
			});
	}

	,userpage_contentgotten: function(req) {
		var cont_regex  = new RegExp(
			'<div class="(text pp journal)?text">(\s*<keeper(.|\n|\r)*?)<\/div> *'
			+ '(<div class="(c ppb alink (journal)?bottom|flatview comments section)"|<ul class="f list">)',
			'i'
		);
		var cont  = cont_regex.exec(req.responseText);
		if(cont) {
			for(var k in JCE.GERUND_LIST) {
				var count = 0, res;
				var re = new RegExp('<li class="f( a)?">\s*<strong>' + k + ':</strong>\s*(.*?)\s*</li>', '');
				if(res = re.exec(req.responseText)) {
					JCE.GERUND_LIST[k] = res[2];
					count++;
				}
				if(count) {
					for(var i = 0; i < 6 ; i++)
						$('gerund-num-' + i).selected = false;

					$('gerund-num-6').selected = true;
					JCE.update_gerunds();
				}
			}
			cont = cont[2].replace(
				/<a class="u" href="(http:\/\/[\w\-]+\.deviantart\.com\/)">([\w\-]+)<\/a>/g,
				'<a href="$1">$2</a>'
			);
			cont = cont.replace(/<a\s+class="mature"/g, '<a ');
			cont = cont.replace(/<span class="shadow(-holder)?">/g, '');
			cont = JCE_AJAX.deentitise(cont.replace(/<br( \/)?>\n?/g, "\n"));

			var titl = /"Journal: (.*?)"/.exec(cont);

			$('journal-content').value = cont.replace(/<keeper.*?smoothie>/, '');
			JCE.update_content();

			if(titl) {
				$('journal-title').value = JCE_AJAX.deentitise(titl[1].replace(/&amp;/g, "&"));
				JCE.update_title();
			}
		} else {
			JCE.warn('Didn\'t find any journal data!');
		}
	}

	,load_userpage_css: function(username, jid) {
		JCE_AJAX.load_userpage('journal-get-css', username, JCE_AJAX.userpage_cssgotten, jid);
	}

	,load_userpage_content: function(username, jid) {
		JCE_AJAX.load_userpage('journal-get-content', username, JCE_AJAX.userpage_contentgotten, jid);
	}

	,load_userpage_both: function(username, jid) {
		JCE_AJAX.load_userpage(
			map(
				$('journal-get-buttons').getElementsByTagName('input'),
				function(a) {
					return a.id;
				}
			),
			username,
			function(req) {
				JCE_AJAX.userpage_cssgotten(req);
				JCE_AJAX.userpage_contentgotten(req);
			},
			jid
		);
	}

	,get_userpage_css: function() {
		JCE_AJAX.msgbox_da('dA: Get CSS', JCE_AJAX.load_userpage_css);
	}
	,get_userpage_content: function() {
		JCE_AJAX.msgbox_da('dA: Get Content', JCE_AJAX.load_userpage_content);
	}
	,get_userpage_both: function() {
		JCE_AJAX.msgbox_da('dA: Get Content and CSS', JCE_AJAX.load_userpage_both);
	}
	,get_pastebin_css: function() {
		JCE_AJAX.msgbox_pb('Pastebin: Get CSS',JCE_AJAX.load_pastebin_css);
	}
	,get_pastebin_content: function() {
		JCE_AJAX.msgbox_pb('Pastebin: Get Content', JCE_AJAX.load_pastebin_content);
	}


	,load_pastebin: function(button, id, callback) {
		if(typeof id == 'undefined' || id == null)
			id = prompt('Pastebin URL or ID: ');

		if(id == '' || id == null)
			return false;

		id = id.replace(/^(http:\/\/)?(devart\.pastebin\.com\/)?/i, '');
		var pars = 'id=' + id.replace(/[^A-Z0-9]/gi, '');

		JCE_AJAX.fetch_page('/get_pastebin.php', pars, callback, button);
	}

	,pastebin_cssgotten: function(req) {
		if(req.responseText) {
			$('journal-css').value = req.responseText;
			JCE.update_css();
		} else {
			JCE.warn('Didn\'t find any CSS data!');
		}
	}

	,pastebin_contentgotten: function(req) {
		if(req.responseText) {
			$('journal-content').value = req.responseText;
			JCE.update_content();
		} else {
			JCE.warn('Didn\'t find any journal data!');
		}
	}

	,load_pastebin_css: function(id) {
		JCE_AJAX.load_pastebin('pastebin-get-css', id, JCE_AJAX.pastebin_cssgotten);
	}

	,load_pastebin_content: function(id) {
		JCE_AJAX.load_pastebin('pastebin-get-content', id, JCE_AJAX.pastebin_contentgotten);
	}
};


Event.observe(window, 'load', JCE.init);
