var current_mouse_x;
var current_mouse_y;

var browser_name = "default";
var browser_version = "";

if (navigator.appName == "Microsoft Internet Explorer") {
	browser_name = "msie";
	if (navigator.appVersion.match(/7\.0/))
		browser_version = 7;
	else if (navigator.appVersion.match(/8\.0/))
		browser_version = 8;
	else
		browser_version = 6;
}

// this function determines whether the event is the equivalent of the microsoft
// mouseleave or mouseenter events.
function isMouseLeaveOrEnter(e, handler) {
	var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
	while (reltg && reltg != handler) {
		reltg = reltg.parentNode;
	}
	return (reltg != handler);
}

function init() {
	var i=0;

	highlight_search_terms($('content'));

	if (document.forms[0] && document.forms[0].f_user) {
		if (document.forms[0].f_user.value)
			document.forms[0].f_pass.focus();
		else
			document.forms[0].f_user.focus();
	}

	/*
	**  This is a hack to get around the fact that IE does not
	**  support position:fixed.
	*/
	if (browser_name == 'msie' && browser_version < 7) { // if IE
		if (help_pref != "hide" && document.getElementById('helpbar')) {
			document.getElementById('helpbar').getFixedPosition = function() {
					var height = 111;
					if (help_pref == "minimized")
						height = 21;
					return (scroll_top() + get_display_height() - height)+"px";
				};
			add_fixed_div(document.getElementById('helpbar'));
		}
		move_fixed_divs();
	}

	if (window.onLoad) {
		onLoad();
	}

	document.onmousemove = function(e) {
		if (document.all) {
			current_mouse_x = window.event.x+document.body.scrollLeft;
			current_mouse_y = window.event.y+document.body.scrollTop;
		} else {
			current_mouse_x = e.pageX;
			current_mouse_y = e.pageY;
		}
	}
}

// Update the contents of the page and print any error messages.
function update (response) {
	if (!response)
		return;

	// print errors
	if (response.error_msg.length) {
		alert("ERROR: "+response.error_msg);
		return;
	}

	// print the updated contents of the page
	for (var i=0; i < response.types.length; i++) {
		if (response.types[i] == 'msg' && response.msg.length) {
			alert(response.msg);
		} else {
			var div = document.getElementById('e_' + response.types[i]);
			if (div) {
				div.innerHTML = eval('response.' + response.types[i]);
				div.style.display = 'block';
			}
		}
	}
}

function showhide(id) {
	var div = document.getElementById(id);
	if (div.style.display == "none" || !div.style.display) {
		new Effect.BlindDown(div, {duration: 0.2, afterFinish: function(obj) { obj.element.style.display = 'block'; }});
	} else {
		new Effect.BlindUp(div, {duration: 0.2, afterFinish: function(obj) { obj.element.style.display = 'none'; }});
	}
}

function toggle_div(div, anim) {
	if (anim == 'undefined')
		anim = false;

	if (div.style.display == 'none') {
		if (anim)
			new Effect.BlindDown(div, {duration:0.25});
		else
			div.style.display = 'block';
	} else {
		if (anim)
			new Effect.BlindUp(div, {duration:0.25});
		else
			div.style.display = 'none';
	}
}

// Toggle the contents of one element based on whether another div is hidden
// or showing.
//   div - the name of the div which is being toggled
//   contents - the name of the element which contents are being changed
//   show - the HTML which is shown in the contents element when div is shown
//   hide - the HTML which is shown in the contents element when div is hidden
function toggle_contents (div, contents, show, hide) {
	if (div.style.display == 'none') {
		contents.innerHTML = show;
	} else {
		contents.innerHTML = hide;
	}
}

var do_toggle = 1;
function item_toggle(num) {
	if (!do_toggle) return;
	var closed_div = document.getElementById('item'+num+'_closed');
	var opened_div = document.getElementById('item'+num+'_opened');
	var item = document.getElementById('item'+num);
	if (closed_div.style.display == 'none') {
		closed_div.style.display = 'block';
		opened_div.style.display = 'none';
		item.style.background = '#fff';
	} else {
		closed_div.style.display = 'none';
		opened_div.style.display = 'block';
	}
}

function add_search_term(f) {
	var strings = new Array();
	var elements = f.elements;
	var count = 0;
	for (i=0; i < elements.length; i++) {
		if (elements[i].type == "text" && elements[i].name == "phrases[]") {
			strings[count] = elements[i].value;
			count++;
		}
	}
	div = document.getElementById('search_terms');
	div.innerHTML += "<input style=\"margin-top: 3px;\" type=text name=phrases[] size=35><br>\n";

	elements = document.sform.elements;
	count = 0;
	for (i=0; i < elements.length; i++) {
		if (elements[i].type == "text" && elements[i].name == "phrases[]") {
			if (strings[count]) {
				elements[i].value = strings[count];
			}
			elements[i].focus();
			count++;
		}
	}
}

function get_display_height() {
	var h;
	if (window.innerHeight) {
		h=window.innerHeight;
	} else if (document.documentElement.clientHeight) {
		h=document.documentElement.clientHeight;
	} else if (document.body.clientHeight) {
		h=document.body.clientHeight;
	}
	return h;
}

function scroll_top() {
	return filter_results (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function filter_results(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function get_true_left(e) {
	if (!e && this)
		e = this;

	var n = e.offsetLeft;
	var p = e.offsetParent;
	while (p != null) {
		n += p.offsetLeft;
		p = p.offsetParent;
	}
	return n;
}

function get_true_top(e) {
	if (!e && this)
		e = this;

	var n = e.offsetTop;
	var p = e.offsetParent;
	while (p != null) {
		n += p.offsetTop;
		p = p.offsetParent;
	}
	return n;
}

var is_blocker_visible = false;
function show_blocker(v) {
/*	var e = document.getElementById('blocker');
	if (is_blocker_visible == v)
		return;

	if (v) {
		scroll(0,0);
		var clientHeight = 0;
		is_blocker_visible = true;
		e.style.width = document.body.offsetWidth+"px";

		if (typeof(window.innerHeight) == 'number')
			clientHeight = window.innerHeight;
		else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
			clientHeight = document.documentElement.clientHeight;
		else if (document.body && ( document.body.clientWidth || document.body.clientHeight))
			clientHeight = document.body.clientHeight;

		if (document.body.offsetHeight > clientHeight)
			clientHeight = document.body.offsetHeight;

		e.style.height = clientHeight+"px";
		Effect.Appear('blocker', {duration:0.25, from:0, to:0.4, queue:'end'});
	} else {
		is_blocker_visible = false;
		Effect.Fade('blocker', {duration:0.25, from:0.4, to:0, queue:'end'});
		$('blocker').onclick = null;
	}
*/}
function hide_blocker_delay() {
}

function print_page(url) {
	show_blocker(true);
	document.getElementById('print_viewer').src = url;
	new Effect.Appear(document.getElementById('print'), {duration: .25});
}

function do_print() {
	window.frames['print_viewer'].focus();
	window.frames['print_viewer'].print();
}

function print_hide() {
	show_blocker(false);
	new Effect.Fade(document.getElementById('print'), {duration:.25});
}

function accordion(el) {
	if ($('accordion_visible') == el) {
		return;
	}
	if ($('accordion_visible')) {
		var eldown = el.parentNode.id+'_body';
		var elup = $('accordion_visible').parentNode.id+'_body';
		new Effect.Parallel(
		[
			new Effect.BlindUp(elup),
			new Effect.BlindDown(eldown)
		], { duration: 0.2 });
		$('accordion_visible').id = '';
	}
	el.id = 'accordion_visible';
}

function menu_accordion(el) {
	if (el.is_visible) {
		el.is_visible = false;
		el.className = "menu_head";
		new Effect.BlindUp(el.nextSibling, {duration:.1});
	} else {
		el.is_visible = true;
		el.className = "menu_head menu_open";
		new Effect.BlindDown(el.nextSibling, {duration:.1});
	}
}

function get_url_parameter(strParamName){
	var args_str = location.href.split("?")[1];
	if (args_str) {
		var args = args_str.split(/[&#]/);
		for (var i=0; i < args.length; i++) {
			var params = args[i].split("=");
			if (params[0] == strParamName)
				return params[1];
		}
	}
	return "";
}

function get_search_terms() {
	var str = get_url_parameter("h");
	if (str.length == 0)
		return new Array();
	return str.split(/(,|%2c)/i);
}

function highlight_search_terms(div) {
	var terms = get_search_terms();
	var term_re = "";
	var i;

	for (i=0; i < terms.length; i++) {
		var term = terms[i].replace(/(%20|\+)+/, "\\s+");
		if (term.length) {
			if (term_re)
				term_re += "|";
			term_re += term;
		}
	}
	if (term_re.length) {
		var re = new RegExp("("+term_re+")", 'gi');
		div.innerHTML = div.innerHTML.replace(re, "<a name=term0></a><span class=search_highlight>$1</span>");
	}

	if (i>0 && location.href.indexOf('term0') == -1)
		location.href = location.href+"#term0";
}

/*
**  these "fixed_div" functions are for a work-around in IE6 that
**  doesn't allow a div to be in a fixed position.  This is only
**  used for IE6 browsers.
*/
var fixed_divs = new Array();
function add_fixed_div(div) {
	fixed_divs.push(div);
}
function remove_fixed_div(div) {
	for (var i=0; i < fixed_divs.length; i++) {
		if (fixed_divs[i] == div) {
			fixed_divs.splice(i, 1);
			return;
		}
	}
}
function move_fixed_divs() {
	for (var i=0; i < fixed_divs.length; i++) {
		fixed_divs[i].style.position = "absolute";
		fixed_divs[i].style.top = fixed_divs[i].getFixedPosition();
	}
	setTimeout("move_fixed_divs()", 10);
}

/*
**  toggle_stars() - uses ajax to "star" a document.
*/
function toggle_star(id) {
	var img = document.getElementById('star_'+id);
	if (img.src.indexOf("gray_star.png") > 0) {
		var data = { color: "gold", doc_id: id };
		var a = new Ajax.Request('/util/ajax/stars', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)) });
		img.src = "/images/gold_star.png";
	}
	else {
		var data = { color: "gray", doc_id: id };
		var a = new Ajax.Request('/util/ajax/stars', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)) });
		img.src = "/images/gray_star.png"
	}
}

/* RESEARCH FOLDERS */
function createFolder() {
	var folder_name = document.getElementById('new_folder').value;
	var err_div = document.getElementById('err_div');
	if (!folder_name) {
		err_div.innerHTML = "You must specify a folder name!";
		err_div.style.display = "block";
		return;
	}
	if (folder_name.length > 50) {
		err_div.innerHTML = "Please use a shorter folder name!";
		err_div.style.display = "block";
		return;
	}
	document.getElementById('new_folder').value = "";
	err_div.innerHTML = "";
	err_div.style.display = "none";
	var data = { action: "add", fname: folder_name };
    var a = new Ajax.Request('/util/ajax/folders', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
        onSuccess: function(r) {
			var div = document.getElementById('print_folders');
            div.innerHTML = r.responseText;
    }});
}

function deleteFolder(folder_id, folder_name) {
	if (confirm("Are you sure you want to delete folder '" + folder_name + "'?")) {
		var data = { action: "delete", fid: folder_id };
		var a = new Ajax.Request('/util/ajax/folders', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
			onSuccess: function(r) {
				var div = document.getElementById('print_folders');
				if (div != null) {
					div.innerHTML = r.responseText;
				} else {
					window.location = "/tools/research/folders";
				}
		}});
	}
}

function renameFolder(folder_id) {
	var new_name = prompt("Enter a new folder name");
	if (new_name != null) {
		var err_div = document.getElementById('err_div');
		if (new_name.length>50) {
			err_div.innerHTML = "Please use a shorter folder name.";
			err_div.style.display = "block";
			return;
		}
		err_div.innerHTML = "";
		err_div.style.display = "none";
		new_name = new_name.replace(/</g,"&lt;");
		new_name = new_name.replace(/>/g,"&gt;");
		var data = { action: "rename", fid: folder_id, fname: new_name };
		var a = new Ajax.Request('/util/ajax/folders', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
			onSuccess: function(r) {
				var div = document.getElementById('folder_name_'+folder_id);
				div.innerHTML = r.responseText;
		}});
	}
}

function addRemoveFolderItem(folder_id, id, type) {
    var checkbox = document.getElementById('folder_checkbox_'+folder_id);
    var checked = checkbox.checked;
    if (checked) {
        addToFolder(folder_id, id, type);
    } else {
        removeItem(folder_id, id, type);
    }
}

function removeItem(folder_id, document_id, doc_type) {
	var act = "remove_" + doc_type;
	if (confirm("Are you sure you want to remove this item?")) {
		var data = { action: act, fid: folder_id, did: document_id };
		new Ajax.Request('/util/ajax/folders', { method:'post', parameters:'data='+Object.toJSON(data),
			onSuccess: function(r) {
				var div = document.getElementById('print_folder_contents');
            	div.innerHTML = r.responseText;
			}});
	}
}

/* Adds a document to the specified folder */
function addToFolder(folder_id, document_id, doc_type) {
	var act = "add_" + doc_type;
	var data = { action: act, fid: folder_id, did: document_id };
	var a = new Ajax.Request('/util/ajax/folders', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)) });
}

function writeNote(folder_id) {
	popup('/util/popup/note/'+folder_id);
}

function editNote(folder_id, note_id) {
	popup('/util/popup/note/'+folder_id+'/'+note_id);
}

function saveNote(note_id) {
	var folder_id = document.getElementById('fid').value;
	var ftitle = document.getElementById('title').value;
	var fcontent = document.getElementById('note_content').value;
	if (!ftitle || !fcontent)
		alert('You must provide a title and content.');
	else {
		var data = { action: 'save_note', did: note_id, fid: folder_id, title: ftitle, content: fcontent };
		new Ajax.Request('/util/ajax/folders', { method:'post', parameters:'data='+Object.toJSON(data),
			onSuccess: function(r) {
				parent.window.location.reload(false);
		}});
	}
}

/* Moves an item up in the order */
function moveItem(folder_id, item_id, doc_type, dir) {
	var data = { action: 'move', fid: folder_id, did: item_id, direction: dir, type: doc_type };
	var a = new Ajax.Request('/util/ajax/folders', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
		onSuccess: function(r) {
			var div = document.getElementById('print_folder_contents');
        	div.innerHTML = r.responseText;
		}});
}

/* Functions for printing folders */
// select all of the parameters for documents, commentary, saved searches or notes
function selectAllPrintOptions(doc_type, chk) {
	var all = document.getElementById(doc_type+'_all').checked;
	var none = document.getElementById(doc_type+'_none');
	if (all) {
		none.checked = false;
		for(i = 0; i < chk.length; i++)
			chk[i].checked = true;
	}
}

// uncheck the "all" checkbox because all options are no longer selected
function uncheckBox(doc_type, chk) {
	var all = document.getElementById(doc_type+'_all');
	var none = document.getElementById(doc_type+'_none');
	for(i = 0; i < chk.length; i++) {
		if (!chk[i].checked) {
			all.checked = false;
		}
		if (chk[i].checked) {
			none.checked = false;
		}
	}
}

// select none of the parameters for documents, commentary, saved searches or notes
function selectNonePrintOptions(doc_type, chk) {
	var none = document.getElementById(doc_type+'_none').checked;
	var all = document.getElementById(doc_type+'_all');
	if (none) {
		all.checked = false;
		for(i = 0; i < chk.length; i++)
			chk[i].checked = false;
	}
}
/*** END RESEARCH FOLDERS ***/

/*
** popup()
*/
var popup_list_id = 0;
var popup_list_list = new Array();

function popup_list_element(offset, url_base) {
	var index = 0;
	for (var i=0; i < popup_list_list.length; i++) {
		if (popup_list_list[i] == popup_list_id) {
			index = i;
			break;
		}
	}

	if (index+offset < 0 || index+offset >= popup_list_list.length) {
		return;
	}
	popup_list_id = popup_list_list[index+offset];
	var url = url_base+popup_list_id;

	$('popup_img_previous').style.display = (popup_list_list[0] == popup_list_id?"none":"block")
	$('popup_img_next').style.display = (popup_list_list[popup_list_list.length-1] == popup_list_id?"none":"block")
	$('popup_viewer').src = url;
}

function popup_list(id, list, url_base) {
	if (browser_name == 'msie' && browser_version < 7) {
		alert('Please upgrade to Internet Explorer 7 or Firefox to use this feature.');
		return;
	}
	var url = url_base+id;
	popup_list_id = id;
	popup_list_list = list;

	scroll(0,0);
	$('popup_toolbar').style.display = "block";
	$('popup_img_previous').onclick = function(){ popup_list_element(-1, url_base); }
	$('popup_img_next').onclick = function(){ popup_list_element(1, url_base); }
	$('popup_img_previous').style.display = (list[0] == id?"none":"block")
	$('popup_img_next').style.display = (list[list.length-1] == id?"none":"block")

	$('popup_viewer').style.height = (pageHeight()-120)+"px";
	$('popup_viewer').src = url_base+id;
	popup_show();
}

function popup(url, print) {
	if (browser_name == 'msie' && browser_version < 7) {
		alert('Please upgrade to Internet Explorer 7 or Firefox to use this feature.');
		return;
	}
	$('popup_img_previous').style.display = "none";
	$('popup_img_next').style.display = "none";
	$('popup_viewer').style.height = (pageHeight()-120)+"px";
	$('popup_viewer').src = url;
	popup_show();
	if (print) setTimeout("popup_print()", 1000);
	scroll(0,0);
}
function popup_hide() {
	$('popup_viewer').src = "/blank";
	$('popup').style.display = "none";
	show_blocker(false);
}
function popup_show() {
	show_blocker(true);
	$('blocker').onclick = popup_hide;
	$('popup').style.display = "block";
	setTimeout("popup_resize()", 500);
}
function popup_print() {
	window.frames['popup_viewer'].focus();
	window.frames['popup_viewer'].print();
}
function popup_resize() {
	if ($('popup').style.display == "block") {
		$('popup_viewer').style.height = (pageHeight()-120)+"px";
		setTimeout("popup_resize()", 500);
	}
}

function toggle_beta(mode) {
	new Ajax.Request(
		'/util/ajax/betabox',
		{method:'post', parameters:'mode='+mode}
		);

	beta_pref = mode;
	if (mode == "show") {
		$('betafb_minimized').style.display = "none";
		$('betafb_show').style.display = "block";
	} else if (mode == "minimized") {
		$('betafb_show').style.display = "none";
		$('betafb_minimized').style.display = "block";
	}
}

function fix_link_targets(div, library) {
	if (div) {
		var links = div.getElementsByTagName('a');
		for (var i=0; i < links.length; i++) {
			var link = links[i];
			if (!link.href)
				continue;
			if (link.href.match(/javascript:/))
				continue;

			if (link.href.match(/\/cpc_\d+/)) {
				link.target = "_blank";
			} else if (link.href.match(/^http/i) && !link.href.match(/charitableplanning.com/i)) {
				link.target = "_blank";
			}

			if (library && link.href.match(/\/library\//)) {
				link.target = "_blank";
			}
		}
	}
}

// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well
function pageWidth() {return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;}
function pageHeight() {return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;}
function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;}
function posTop() {return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;}
function posRight() {return posLeft()+pageWidth();}
function posBottom() {return posTop()+pageHeight();}

function set_busy_cursor(v) {
	

	document.body.style.cursor = (v?'wait':'default');
	zz = document.getElementsByTagName('a')
	for (var i=0;i < zz.length; i++) {
		if (v)
			zz[i].style.cursor = 'wait';
		else
			zz[i].style.cursor = 'pointer';
	}
	zz = document.getElementsByTagName('input')
	for (var i=0;i < zz.length; i++) {
		if (v)
			zz[i].style.cursor = 'wait';
		else if (zz[i].type == 'text')
			zz[i].style.cursor = 'text';
		else
			zz[i].style.cursor = 'default';
	}
}

function show_feedback(v) {
	if (v) {
		scroll(0,0);
		show_blocker(true);
		$('feedback').show();
		$('feedbackmsg').focus();
	} else {
		$('feedback').hide();
		$('feedbackmsg').value = '';
		show_blocker(false);
	}
}

// Folder code
var global_folder_document_id; // hack! oh well
var global_folder_doc_type; // hack! oh well
function show_folder_chooser(v, elem, did, doc_type) {
	if (v) {
		scroll(0,0);
		global_folder_document_id = did;
		global_folder_doc_type = doc_type;
		show_blocker(true);
		$('blocker').onclick = function() { show_folder_chooser(false); };
		$('folders_list').innerHTML = "<center><img src=\"/images/working.gif\"></center>";
		$('folders').show();
		render_folder_chooser_list(did, doc_type);
	} else {
		$('folders').hide();
		show_blocker(false);
	}
}

function render_folder_chooser_list(did, doc_type) {
	data = { action:'list_folders_'+doc_type, did:did };
	new Ajax.Request(
		'/util/ajax/folders',
		{
			method: 'post',
			parameters: 'data='+encodeURIComponent(Object.toJSON(data)),
			onComplete: function(r) {
				var response = r.responseText.evalJSON();
				var html = "";
				if (response.length > 0) {
					for (var i=0; i < response.length; i++) {
						html += "<input type=checkbox id=\"folder_checkbox_"+response[i].fid+"\" ";
                        if (response[i].docExists) {
                            html += "checked=true ";
                        }
                        html += "onclick=\"addRemoveFolderItem('"+response[i].fid+"', '"+did+"', '"+doc_type+"');\"";
                        html += " \> " + response[i].name;
						html += "<br>";
					}
					html += "<br>";
				} else {
					html += "<p class=notice>No folders have been created.</p>";
				}
				$('folders_list').innerHTML = html;
			}
		});
}

function create_folder_from_div(name) {
	var data = { action: "add", fname: name };
	var a = new Ajax.Request('/util/ajax/folders', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
		onComplete: function(r) {
			render_folder_chooser_list(global_folder_document_id, global_folder_doc_type);
	}});
}

function impersonateUser (uname) {
	if (!uname)
		uname = prompt('Please enter the username of the user you would like to impersonate.');
	var data = { uname: uname };
	var a = new Ajax.Request('/admin/users/impersonate', { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
		onComplete: function(r) {

			var response = r.responseText.evalJSON();
			if (!response)
				return;

			// print errors
			if (response.error_msg.length) {
				alert("ERROR: "+response.error_msg);
				return;
			}

			location.href = '/home';
	}});
}

/*
**  This function will display the text editor window.  The first
**  parameter is boolean to specify show or hide.  The second parameter
**  is the type that we want to edit.  This can be ctitle, teaser, summary,
** commentary, or note_add.
*/
function show_texteditor(v, url, id, name) {
	if (v) {
		$('texteditor_save').onclick = function() {
				save_texteditor(url, id, name);
				show_texteditor(false);
			};

		var data = { action: "get_"+name, id: id };
		var a = new Ajax.Request(url, { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
			onSuccess: function(r) {
				var response = r.responseText.evalJSON();
				if (response.text)
					tinyMCE.activeEditor.setContent(response.text);
				$('texteditor_container').style.display = 'block';
				update(response);
				resize_texteditor();
		}});

	} else {
		$('texteditor_container').style.display = 'none';
	}
}

function save_texteditor(url, id, name) {
	var html = tinyMCE.activeEditor.getContent();
	var data = { action: "save_"+name, id: id, value: html };
	var a = new Ajax.Request(url, { method:'post', parameters:'data='+encodeURIComponent(Object.toJSON(data)),
		onSuccess: function(r) {
			var response = r.responseText.evalJSON();
			update(response);
	}});
}

/*
**  These are functions called every 0.5 seconds while the respective
**  windows are displayed.  They monitor the size of the browser
**  window and resize themselves accordingly.
*/
function resize_texteditor() {
	if ($('texteditor_container').style.display != 'block')
		return;
	$('texteditor_container').style.height = (pageHeight()-115)+"px";
	$('texteditor_tbl').style.height = (pageHeight()-200);
	$('texteditor_ifr').style.height = (pageHeight()-200);
	setTimeout("resize_texteditor()", 500);
}

function resize_viewer() {
	if ($('viewer_container').style.display != 'block')
		return;
	$('viewer_container').style.height = (pageHeight()-115)+"px";
	$('viewer').style.height = (pageHeight()-180);
	setTimeout("resize_viewer()", 500);
}
