//document.onkeypress = document_keypress
window.onscroll = hide_tooltip;

window.onload = function () {
	$('container').setOpacity(0);
	$('loading').hide();
	new Effect.Opacity('container', { from: 0, to: 1, duration: 0.5 });	
	$('container').show();
	$('footer').show();
	
	show = $('config').readAttribute('initwindow');
	if (show && $(show))
		show_window(show);
	
}
function  show_tooltip(tooltip) {
	if ($('tooltip')) {
		$('tiptext').innerHTML = tooltip;
		$('tooltip').show();
		$('tooltip').removeClassName('red');
		$('tooltip').addClassName('blue');
	}
}
function  hide_tooltip() {
	if ($('tooltip'))
		$('tooltip').hide();
}

function document_keypress(e){
	var key = get_keycode(e);
	if (key == 37) {
		table = $('word_table');
		pg = parseInt(table.readAttribute('page')) - 1;
		lpg = table.readAttribute('lpage');
		flt = table.readAttribute('filter');
		table_pager(pg, lpg, flt, 'searchall');
	} 
	else if (key == 39) {
		table = $('word_table');
		pg = parseInt(table.readAttribute('page')) + 1;
		lpg = table.readAttribute('lpage');
		flt = table.readAttribute('filter');
		flt = table.readAttribute('filter');
		table_pager(pg, lpg, flt, 'searchall');
	}
		; //right
}
function get_username() {
	return $('config').readAttribute('username');
}
function set_username(username) {
	$('config').writeAttribute('username', username);
}
function get_language() {
	return $('config').readAttribute('lang');
}
function cell_out(e) { 
	$(e).removeClassName('cellover'); 
	hide_tooltip();
}
function cell_listen(id) { 
	var e = $('tts_' + id);
	if (e) {
		if (!e.visible()) 
			Effect.BlindDown(e);
  
  		var sound = soundManager.createSound({
		    id: id,
		    url: '/tts/' + id
		});
		sound.play();
	}
}
function cell_over(e, customtip, tip, onlyCustomTip) { 
	$(e).addClassName('cellover'); 
	if ($('tooltip') && !$('tooltip').visible()) {
		if (customtip && tip) {
			if (!onlyCustomTip)
				tip += " - "  + $('tip').getAttribute('c'); 
			show_tooltip(tip); 
		}
		else if (!customtip)
			show_tooltip($('tip').getAttribute('c')); 
	}
}

function cell_edit(id, field, multi) {
	var cellid = field + "_" + id;
	var editid = 'edit_' + cellid;
	var e = $(cellid);
	if (!e) return;

	var input = $(editid);
	if (input) {
		var value = cell_value(cellid, multi);
		var oldvalue = e.readAttribute('oldvalue').strip();
		e.innerHTML = value;
		if (oldvalue != value) {
			cell_set_status(id, 'unsaved');
		}
		hide_tooltip();
	}
	else {
		var value = cell_value(cellid, 1);
		e.writeAttribute('oldvalue', value);
		if (multi)
			e.innerHTML =
				'<textarea rows="3" id="' + editid + '" ' + 
					'onblur="cell_edit(\'' + id + '\',\'' + field + '\',\'1\');" ' + 
					'onkeypress="cell_edit_keypress(event, \'' + id +
						'\', \'' + field + '\', \'1\'); return true;" >' + 
					value + '</textarea>';

		else
			e.innerHTML =
			'<input type="text" value="' + value + '" ' +
				'id=\"' + editid + '\" ' + 
				'onblur="cell_edit(\'' + id + '\',\'' + field + '\'); return true;" ' +
				'onkeypress="cell_edit_keypress(event, \'' + 
					id + '\', \'' + field + '\'); return true;" >';
		$(editid).activate();
		var tip = $('tip');
		if (tip) 
			show_tooltip(tip.getAttribute('e'));
	}
}
function defn_add(wordid) {
	container_disable();
	new Ajax.Request(
		'/definition',
		{ 
			method: 'post',
			parameters: {
				lang: get_language(),
				id: wordid
			},
			onSuccess: ajax_success,
			onException: ajax_fail,
			onFailure: ajax_fail
		});
}

function defn_add(wordid) {
	container_disable();
	new Ajax.Request(
		'/definition',
		{ 
			method: 'post',
			parameters: {
				lang: get_language(),
				id: wordid
			},
			onSuccess: ajax_success,
			onException: ajax_fail,
			onFailure: ajax_fail
		});
}

function cell_comments(id, page, callpage) {

	comments = $('comments_' + id);

	if (!page && comments) {
		comments.toggleClassName('hidden');
		if (!comments.hasClassName('hidden'))
			comments.scrollTo();
	}
	
	else {
		if (callpage == 'word')
			container_disable('word.comments');
		else
			container_disable();
		new Ajax.Request(
			'/comments',
			{ 
				method: 'post',
				parameters: {
					lang: get_language(),
					id: id,
					page: page,
					callpage: callpage
				},
				onSuccess: ajax_success,
				onException: ajax_fail,
				onFailure: ajax_fail
			});
	}
}
function comment_submit(id, callpage)
{
	comment = $('comment.edit.' + id).getValue().strip();
	name = $('comment.name.' + id).getValue().strip();
	set_username(name);

	if (callpage == 'word')
		container_disable('word.comments');
	else
		container_disable();

	new Ajax.Request(
		'/comments',
		{ 
			method: 'post',
			parameters: {
				lang: get_language(),
				id: id,
				action: 'add',
				comment: comment,
				callpage: callpage,
				username: name
			},
			onSuccess: ajax_success,
			onException: ajax_fail,
			onFailure: ajax_fail
		});
}

function filter_blur() {		
	var filter = $('filter');
	value = filter.getValue().strip();
	old = filter.readAttribute('oldvalue');
	hide_tooltip();	

	if (value != old)
		table_filter();
}
function filter_keypress(e) {
	if (is_enter_key(e))
		table_filter();

	else if (is_escape_key(e)) {
		var filter = $('filter');
		old = filter.readAttribute('oldvalue').strip();
		filter.value = old;
	}
}
function cell_edit_keypress(e, id, field, multi) {
	if (!multi && is_enter_key(e))
		cell_edit(id, field);

	else if (is_escape_key(e)) {
		var cellid = field + "_" + id;
		var oldvalue = $(cellid).readAttribute('oldvalue').strip();
		$(cellid).innerHTML = oldvalue;
	}
}
function cell_value(id, multi) {	
	var e = $(id);
	if (!e) return;

	var input = $('edit_' + id);
	var txt;
	if (input) {
		txt = input.getValue().escapeHTML().strip();
		if (txt && multi)
			txt = txt.replace(/\n+/g, "<br>");
	}
	else {
		txt = e.innerHTML.strip();
		if (txt && multi)
			txt = txt.replace(/\n?\<br\>\n?/gi, "\n");
	}
	txt = txt.replace(/"/g, "'");
	return txt;
}
function word_id_from_cell_id(id) {
	return id.split('_')[0];
}
function cell_set_status(id, status) {
	var word_id = word_id_from_cell_id(id);
	e = $('word_' + word_id);
	if (e) {
		e.removeClassName('approved');
		e.removeClassName('pending');
		e.removeClassName('unsaved');
		e.addClassName(status);
	}
}

function comment_edit_keypress(e, id) {
	if (is_escape_key(e))
		comment_cancel(id);
}
function comment_cancel(id) {
	cont = $('comment.new.' + id);
	com = $('comment.edit.' + id);
	txt = cont.readAttribute('text');
	html  = "<div style='width: 100%; text-align: center;'><a href=\"#\" " +
		"onclick=\"comment_new('" +  id + "'); " + "return false;\">" + 
		txt + "</a></div>";
	cont.update(html);
}
function cell_expand(id) {
	var list = [];
	var visible = $('row.' + id + '.1').visible();
	for (i = 1; i < 10; i++) {
		icon = $('icon.' + id + '.' + i);
		row = $('row.' + id + '.' + i);
		if (icon) icon.toggleClassName('hidden');
		if (row) row.toggleClassName('hidden');
	}
}
function addnew_keypress(e, enterallowed) {
	if (!enterallowed && is_enter_key(e))
		addnew_submit();

	else if (is_escape_key(e))
		addnew_hide();
}
function autocomplete_keypress(e) {
	if (is_enter_key(e)) {
		if ($('autowordid').value)
			autocomplete_submit();
	}
	else if (is_escape_key(e))
		autocomplete_hide();
	else
		$('autowordid').clear();
}
function get_new_relations(wordId, relation) {
	var e = $(relation + '_' + wordId);
	var ch = e.childElements();
	var res = "";
	for (i = 0; i < ch.length; i++ ){
		if (ch[i].hasClassName('newRelation')) {
			if (res)
				res += ",";
			res += ch[i].identify();
		}
	}
	return res;
}
function autocomplete_submit() {
	var id = $('autowordid').value;
	var text = $('autowordtext').value;

	if (!id) {
		$('autowordok').disable();
	}
	else {
		var rel = $('autowordrel').value;
		var wid = $('autowordword').value;
		var e = $('new_' + wid + '_' + rel);

		newId = rel + '_' + wid + '_' + id;
		html = " <a class='newRelation' href=\"#\" id='" + newId + "' onclick='cell_reload(" + id + "," + wid + "); return false;'>" + text + "</a> ";
		e.insert({before: html});
		autocomplete_hide();
		cell_set_status(wid, 'unsaved');
	}

}
function is_cell_expanded(id) {
	var e = $("row." + id + ".1");
	if (e) {
		if (e.hasClassName('hidden')) return 0;
		return 1;
	}
	return 0;
}

function cell_reload(id, insert_after) {
	var e = $("word_" + id);
	if (!e && !insert_after) return;

	if (insert_after && e) {
		new Effect.ScrollTo(e);
		return;
	}

	container_disable();
	new Ajax.Request(
		'/reload',
		{ 
			method: 'post',
			parameters: {
				lang: get_language(),
				expanded: is_cell_expanded(id),
				id: id,
				insert_after: insert_after,
				ajax: 1
			},
			onSuccess: ajax_success,
			onException: ajax_fail,
			onFailure: ajax_fail
		}
	);
}
function table_pager(page, lpage, filter, searchall) {
	container_disable();
	new Ajax.Request(
		'/view',
		{ 
			method: 'post',
			parameters: {
				lang: get_language(),
				page: page,
				lpage: lpage,
				filter: filter,
				searchall: searchall,
				ajax: 1
			},
			onSuccess: ajax_success,
			onException: ajax_fail,
			onFailure: ajax_fail
		}
	);
}
function table_filter() {
	val = $('filter').getValue().strip();
	table_pager(1, '', val, 'searchall');
	hide_tooltip();
}
function defn_fill_in_params(params, i, defid) {
	params['def_' + i + '_id'] = defid;
	params['def_' + i + '_word_gr'] = cell_value('word_gr_' + defid, 1);
	params['def_' + i + '_word_en'] = cell_value('word_en_' + defid, 1);
	params['def_' + i + '_grammar'] = cell_value('grammar_' + defid);
	params['def_' + i + '_language'] = cell_value('language_' + defid);
	params['def_' + i + '_metaphorical'] = $('check_metaphorical_' + defid).checked;
	params['def_' + i + '_example'] = cell_value('example_' + defid, 1);
	params['def_' + i + '_etymology'] = cell_value('etymology_' + defid, 1);
	params['def_' + i + '_notes'] = cell_value('notes_' + defid, 1);
	return params;
}

function cell_save(id, accept) {
	var worddata = $('word_data_' + id);
	var isnew = $('word_new_' + id);

	var params = {
		lang: get_language(),
		id: id,
		pronunciation: cell_value('pronunciation_' + id),
		language: cell_value('language_' + id),
		etymology: cell_value('etymology_' + id, 1),
		notes: cell_value('notes_' + id, 1),
		alias: get_new_relations(id, 'alias'),
		derivative: get_new_relations(id, 'derivative'),
		base: get_new_relations(id, 'base')
	}
	if (isnew)
		params['word_cy'] = isnew.getValue();
	else if ($('word_cy_' + id))
		params['word_cy'] = cell_value('word_cy_' + id);
		
	if (accept)
		params['accept'] = 1


	
	defn = worddata.next();
	i = 0;
	while (defn) {
		if (defn.hasClassName('defntable')) {
			defid = defn.identify().substring('word_def_'.length);
			params = defn_fill_in_params(params, i, defid);
			i = i + 1;
		}
		else if (defn.hasClassName('newdefn')) {
			defid = defn.firstDescendant().identify().substring('word_def_'.length);
			params = defn_fill_in_params(params, i, defid);
			i = i + 1;
		}
		defn = defn.next();
	}

	container_disable();
	new Ajax.Request(
		'/save',
		{ 
			method: 'post',
			parameters: params,
			onSuccess: ajax_success,
			onException: ajax_fail,
			onFailure: ajax_fail
		}
	);
}

function container_enable(cont) {
	if (!cont)
		cont = $('config').readAttribute('container');
	element_enable(cont);
}

function element_enable(id) {
	new Effect.Enable(id, {
		color: '#eae8e3',
		icon: '/images/waiting.gif'
	});
}
function ajax_fail() {
	container_enable();
	message_show('Ajax request has failed', 'error');
}
function ajax_success(transport) {
	var res = transport.responseText;
	var st_status;
	var st_id
	if (res.indexOf("&&") != -1) {
		sp = res.split("&&");
		res = sp[0] + "*";

		star = sp[1].indexOf("*");
		if (star == -1)
			res += sp[1];
		else if (star == 0)
			res += sp[1].substring(1);
		else {
			st_status = sp[1].substring(0, star);
			st_id = sp[1].substring(star + 1);
			star = st_id.indexOf("*");
			res += st_id.substring(star + 1);
			st_id = st_id.substring(0, star);
		}
	}

	var cont = '';
	var first = res.substr(0, 1);
	if (first == '=') {
		i = 1;
		while (i < res.length) {
			c = res.substr(i, 1);
			if (c != '=')
				cont += c;
			else
				break;
			i++;
		}
		i++;
		if (cont)
			res = res.substr(i)
	}
	var code = res.substr(0, 4);
	var content = res.substr(4);

	if (code == 'err:')
		message_show(content, 'error');
	
	else if (code == 'msg:')
		message_show(content, 'success');
	
	else if (code == 'ins:') {
		sp = split(content, '*');
		if (!sp)
			message_show('Error: Invalid Ajax Request');
		pos = sp[0];
		sp = split(sp[1], '*');
		if (!sp)
			message_show('Error: Invalid Ajax Request');
		e = $(sp[0]);
		if (e) {
			var show, id;
			id = 'self';
			if (sp[1].charAt(0) == '+') {
				sp = split(sp[1].substring(1), '*');
				show = sp[0];
				sp = split(sp[1], '*');
				id = sp[0];
			}
			var arg = new Object();
			arg[pos] = sp[1];
			var r = e.insert(arg);
			var scr = 1;
			if (show == 'scroll') {
				new Effect.ScrollTo(id);
				scr = 0;
			}
			else {
				if (id == 'self') {
					Effect.BlindDown(e.next());
					new Effect.ScrollTo(e);
				}
				else {
					Effect.BlindDown(id, { afterFinish: function() { new Effect.ScrollTo(id); }});
				}
			}
		}
		else
			message_show('Element not found: ' + id, 'error');
	}
	else if (code == 'upd:' || code == 'rpl:') {
		sp = split(content, '*');
		if (sp) {
			var scrollId;
			id = sp[0];
			content = sp[1];
			
			if (content.charAt(0) == '+') {
				sp = split(content.substring(1), '*');
				scrollId = sp[0];
				content = sp[1];
			}
			var element = $(id);
			if (element) {
				if (code == 'upd:')
					element.update(content);
				else 
					element.replace(content);
				if (scrollId)
					new Effect.ScrollTo($(scrollId));
				else if ($(id))
					new Effect.ScrollTo($(id));
				else
					new Effect.ScrollTo(element);

			}
			else
				message_show('Element not found: ' + id, 'error');
		}
		else
			message_show('Error: Invalid Ajax Request');
	}
	else if (code == 'ok!:')
		;

	else	
		message_show('Unrecognised Ajax response', 'error');
	if (st_status)
		cell_set_status(st_id, st_status);
	container_enable(cont);
}
function message_show(text, type) {
	screen_disable();

	if (!type)
		type  = 'error'
	// the close window icon
	text += "<div style='padding-top: 5px; padding-right: 5px; text-align:right'>" +
			"<a href='#' onclick='message_hide()'>" +
			"<img src='/images/cancel.png'></a>"
/*
	mtitle = $('messagetitle');
	mtext = $('messagetext');
	mtitle.className = 'msg' + type;
	mtext.className = 'msg' + type;
	mtext.update(text);
	mtitle.update($('messagetitles').readAttribute(type + 'title'));

	w = $('screen').getWidth()
	w = (w - 400) / 2;

	mtitle.style.top = "150px";
	mtitle.style.height = "20px";
	mtext.style.top = "175px";
	mtitle.style.left = w + "px"
	mtext.style.left = w + "px"
	mtitle.show();
	mtext.show();
*/
	$('titleboxcontent').update($('messagetitles').readAttribute(type + 'title'));
	$('boxcontent').update(text);
	$('titlebox').show();
	$('contentbox').show();
	new Effect.ScrollTo('screen');
	
}
function deactivate_tabs()
{
	$('wiki').removeClassName('active');
	$('purpose').removeClassName('active');
	$('help').removeClassName('active');
	$('more').removeClassName('active');
	$('contact').removeClassName('active');
}
function show_window(which) {
	deactivate_tabs();
	$(which).addClassName('active');

	container_disable();
	msgbox = $('messagewin');
	msgtext = $('messagewintext');
	msgtitle = $('messagewintitle');
	msgtext.update($(which + '_text').innerHTML);
	msgtitle.update($(which + '_title').innerHTML);
	show_popup(msgbox);
}
function hide_window() {
	$('messagewin').hide();
	container_enable();
	
	deactivate_tabs();
	$('wiki').addClassName('active');
}
function container_disable(cont) {
	if (!cont)
		cont = $('config').readAttribute('container');
	element_disable(cont);
}
function element_disable(id) {
	new Effect.Disable(id, {
		color: '#eae8e3',
		icon: '/images/waiting.gif'
	});
}

function screen_disable() {
	new Effect.Disable('screen');
}

function screen_enable() {
	new Effect.Enable('screen');	
}

function addnew_show() {
	
	screen_disable();

	var n = $('newword');
	var t = $('newwordtext');
	t.value = $('filter').value;
	show_popup(n);
	t.activate();
}

function autocomplete_show(wordid, rel) {
	
	screen_disable();

	var n = $('autoword');
	var t = $('autowordtext');
	var ok = $('autowordok');
	var id = $('autowordid');
	$('autowordword').value = wordid;
	$('autowordrel').value = rel;
	t.clear();
	id.clear();
	ok.disable();
	show_popup(n);
	t.activate();
}
function autocomplete_hide() {
	$('autoword').hide();
	screen_enable();
	$('word_' + $('autowordword').value).scrollTo();
}
function show_popup(popup) {
	popup = $(popup);
	popup.style.position = "absolute";
	popup.style.zIndex = "10";
	popup.style.top = '20%';
	popup.show();
//	new Effect.ScrollTo('container');
	$('container').scrollTo();
}
function message_hide() {
	$('titlebox').hide();
	$('contentbox').hide();
	screen_enable();
}

function addnew_hide() {
	$('newword').hide();
	screen_enable();
}

function addnew_submit() {
	addnew_hide();
	container_disable();
	addnew_request($('newwordtext').getValue());
}

function addnew_from_filter() {
	container_disable();
	addnew_request($('filter').getValue());
}

function addnew_request(word) {	
	new Ajax.Request(
		'/add',
		{ 
			method: 'post',
			parameters: {
				lang: get_language(),
				word: word
			},
			onSuccess: ajax_success,
			onException: ajax_fail,
			onFailure: ajax_fail
		}
	);
}

