var autosaveTimer = null;
var changedTimer = null;

var finalSaveState = null;

var postHash = null;

var defaultReply = '';
var contentReply = '';

var somethingChanged = false;

var ticketUpdatePosts = [];

/* menu */
function menu_add_toggle() {
	ac_dom_toggle_class('nav_add_button_contents', 'ac_block', 'ac_hidden');
	if ( $('nav_add_button_contents').className == 'ac_block' ) {
		ac_dom_clicker_add(
			'nav_add_button_contents',
			{
				nav_add_button: function() {
					ac_dom_toggle_class('nav_add_button_contents', 'ac_block', 'ac_hidden');
				}
			}
		);
	} else {
		ac_dom_clicker_remove('nav_add_button_contents', false);
	}
}

/*
	TICKETS
*/

function ticket_onload() {
	window.setTimeout(function() { contentReply = ac_form_value_get($('messageEditor')); }, 1000);
	//contentReply = ac_form_value_get($('messageEditor'));
	//contentReply = contentReply.replace(/^<p>&nbsp;<\/p>/, '<p><br></p>');
	// check if changed every three (one for now) seconds
	changedTimer = window.setInterval(
		function() {
			var newReply = ac_form_value_get($('messageEditor'));
			if ( newReply != contentReply && contentReply ) {
				/*
				alert(newReply + '\n\n' + contentReply + '\n\n\n' + typeof newReply + typeof contentReply);
				prompt('newReply', newReply);
				prompt('contentReply', contentReply);
				*/
				ticket_reply_changed();
			}
			// now save this current content so we can compare it again in X seconds (if it changed again)
			contentReply = newReply;
		},
		3 * 1000
	);
}

function ticket_unload() {
	//alert(contentReply);alert(ac_form_value_get($('messageEditor')));
	//if ( contentReply != ac_form_value_get($('messageEditor')) ) somethingChanged = true;
	/*
	var newReply = ac_form_value_get($('messageEditor'));
	if ( newReply != contentReply ) {
		ticket_reply_changed();
	}
	*/
	if ( somethingChanged ) {
		return messageLP;
	}
}

// this function fires every three seconds, when the message box is updated
function ticket_reply_changed() {
	somethingChanged = true;
	// auto-save written posts
	if ( $('ticket_reply_save') ) ticket_reply_autosave();
	//$('ticket_reply_send').disabled = false;
	// notify the system he's typing
	if ( $('user_indicator') ) {
		// issue an ajax call with no need for callback
		ac_ajax_call_cb(apipath, "user.user_typing", ticket_reply_changed_cb, ticket.id);
	} else {
		// should we do the same if public side?
		if ( $('update_indicator') ) {
			//ac_ajax_call_cb(apipath, "user.user_typing", null, ticket.id);
		}
	}
}

function ticket_reply_changed_cb() {
	// added this because there kept showing a JS error: "ReferenceError: cb_user_typing is not defined",
	// if ticket_reply_changed() had "null" for the callback function
}

function ticket_info_toggle(panel) {
	var panels = [ 'general', 'userinfo', 'tickets', 'attachments', 'history', 'relatedkb', 'billing' ];
	for ( var i = 0; i < panels.length; i++ ) {
		if ( $(panels[i] + 'link') ) {
			if ( $(panels[i] + 'link').className != 'ac_hidden' ) {
				// set link
				$(panels[i] + 'link').className = ( panel == panels[i] ? 'here' : '' );
				// set panel
				$('ticket_info_' + panels[i]).className = ( panel == panels[i] ? 'ticket_info' : 'ac_hidden' );
			}
		}
	}
}

function ticket_reply() {
	ticket_reply_save(true);
}

function ticket_draft_save() {
	ticket_reply_save(false);
}

function ticket_reply_reset_cb(xml) {
	var ary = ac_dom_read_node(xml);
	ac_ui_api_callback();

	if (ary.succeeded == 1) {
		ac_result_show(ary.message);
		// reset the reply form
		ticket_reply_reset();
	} else {
		ac_error_show(ary.message);
	}

}

function ticket_reply_reset() {
	somethingChanged = false;
	draft.id = 0;
	if ( typeof ismobile != 'undefined' && ismobile ) {
		ac_form_value_set($('messageEditor'), draft.content_plain);
	}
	else {
		ac_form_value_set($('messageEditor'), defaultReply);
	}
	draft.content = defaultReply = contentReply = ac_form_value_get($('messageEditor'));
	//$('ticket_reply_send').disabled = true;
	if ( $('ticket_reply_save') ) {
		$('ticket_reply_save').disabled = true;
		$('ticket_reply_discard').disabled = true;
	}
	$('postid').value = ticket_generate_postid();
	// attachments
	ac_dom_remove_children($('ticket_attach_list'));
	//$('ticket_attach_iframe').contentDocument.location.reload(true); // don't do reload, might be posted
	if ( $('ticket_attach_iframe').contentDocument ) {
		$('ticket_attach_iframe').contentDocument.location.href = $('ticket_attach_iframe').src;
	} else {
		$('ticket_attach_iframe').src = $('ticket_attach_iframe').src;
		//$('ticket_attach_iframe').document.location.href = $('ticket_attach_iframe').src;
	}
	$('ticket_attach_iframe').className = 'ac_hidden';
	// admin side only has comment checkbox
	if ( $('comment') ) {
		//$('comment').checked = false;
		$('comment').value = 0;
		ticket_reply_type_set('respond');
	}
	// public side only has close/rate fields
	if ( $('close') ) $('close').checked = false;
}


function ticket_reply_autosave() {
	if ( ac_js_admin.autosave == 0 ) return;
	if ( !autosaveTimer ) {
		autosaveTimer = window.setInterval(function() { ticket_reply_save(false) }, ac_js_admin.autosave * 1000);
	}
	$('ticket_reply_save').disabled = false;
	$('ticket_reply_discard').disabled = false;

}

function ticket_reply_autosave_stop() {
	if ( ac_js_admin.autosave == 0 ) return;
	if ( autosaveTimer ) {
		clearInterval(autosaveTimer);
	}
	autosaveTimer = false;
}

function ticket_reply_save(finalSave) {
	// run this again in case they click submit within the first 3 secs after they start typing
	var newReply = ac_form_value_get($('messageEditor'));
	if ( newReply != contentReply ) {
		somethingChanged = true;
	}

	var post = ac_form_post($("form"));
	post.tid = ticket.stringid;
	post.hash = ticket.hash;
	post.ticketid = ticket.id;
	post.postid = draft.id;

	if ( finalSave ) {
		if ( postHash == $('postid').value ) {
			// can not post twice
			//alert(ticket_reply_twice_str);
			//return;
		}
	}

	finalSaveState = finalSave;

	ticket_reply_autosave_stop();
	if ( $('ticket_reply_save') ) {
		$('ticket_reply_save').disabled = true;
	}

	ticket_reply_save_send(post, finalSave);
}

function ticket_reply_cb(xml, txt) {
	var ary = ac_dom_read_node(xml);
	ac_ui_api_callback();
	if ( typeof ary.row == 'string' && xml.nodeName == 'error' ) {
		if ( ary.row == jsAPIErrorAuthMessage ) {
			ticket_reply_reset();
			window.location.reload(true);
			return;
		}
		alert(( !ary.row ? txt : ary.row ));
		return;
	}

	if (ary.succeeded == 1) {
		ac_result_show(ary.message);
		if ( finalSaveState ) {
			if ( draft.id && $('post_' + draft.id) ) {
				// rename this post from draft into reply
				var rel = $('post_' + draft.id);
				rel.className = 'ticket_' + ( ary.comment == 1 ? 'comment' : 'admin' ) + 'post';
			} else {
				// add this post to the posts list
				ticket_reply_add(ary);
			}
			if ( $('poststatus') ) ticket.statusid = ary.statusid;
			// reset the reply form
			ticket_reply_reset();
			if ( typeof ismobile == 'undefined' || !ismobile ) {
				// add the response to history
				if ( ary.history_entry ) ticket_history_add(ary.history_entry);
			}
			emailqueue_spawn();
		} else {
			// save draft id
			draft.id = ary.postid;
			// do not add this post to the posts list
			//ticket_reply_add(ary);
		}
		// add this post to the posts list
	} else {
		ac_error_show(ary.message);
		// reset post hash
		postHash = null;
	}
}


function ticket_generate_postid() {
	return parseInt(Math.random() * 10000000, 10);
}

function ticket_email_add_cb(xml) {
	var ary = ac_dom_read_node(xml);
	ac_ui_api_callback();

	if (ary.succeeded == 1) {
		ac_result_show(ary.message);
		// add the email to notifications box
		$('ticket_email_list').appendChild(
			Builder.node(
				'li',
				{ id: 'emailnotify-' + ary.emailid },
				[
					Builder._text(ary.email + ' ['),
					Builder.node(
						'a',
						{ href: '#', onclick: 'ticket_email_remove(' + ary.emailid + ');return false;' },
						[ Builder._text(ticket_email_remove_str) ]
					),
					Builder._text(']')
				]
			)
		);
		// reset this object
		$('ticketemail').value = '';
		ac_dom_toggle_class('ticket_info_email_add', 'ac_block', 'ac_hidden');
		// show the assigned box if not shown already
		/*
		if ( $('ticket_email_box').className == 'ac_hidden' ) {
			$('ticket_email_box').className = 'ac_block';
		}
		*/
		if ( ary.history_entry ) ticket_history_add(ary.history_entry);
	} else {
		ac_error_show(ary.message);
	}
}

function ticket_email_remove_cb(xml) {
	var ary = ac_dom_read_node(xml);
	ac_ui_api_callback();

	if (ary.succeeded == 1) {
		ac_result_show(ary.message);
		// remove this div from assigned box
		$('ticket_email_list').removeChild($('emailnotify-' + ary.emailid));
		if ( ary.history_entry ) ticket_history_add(ary.history_entry);
	} else {
		ac_error_show(ary.message);
	}
}

function ticket_history_add(entry) {
	if ( entry[0] && entry[0].action ) entry = entry[0];
	if ( !entry || !entry.action ) return;
	var rel = $('ticket_history_holder');
	if ( !rel ) return;

	var descript = ( entry.descript ? '( ' + entry.descript + ' )' : '' );

	var historyNode = Builder.node(
		'tr',
		{ className: 'ticket_history_row' },
		[
			Builder.node('td', { width: 100 }, [ Builder._text(sql2date(entry.tstamp).format(datetimeformat)) ]),
			Builder.node('td', [ Builder._text(entry.username) ]),
			Builder.node('td', [ Builder._text(entry.actionname + ' ' + jsTicket4Status) ]),
			Builder.node('td', [ Builder._text(descript) ])
		]
	);
	if ( rel.firstChild ) {
		// add to the top
		rel.insertBefore(historyNode, rel.firstChild);
	} else {
		// add first
		rel.appendChild(historyNode);
	}
	// show the panel if it was the first action
	if ( $('historylink').className == 'ac_hidden' ) $('historylink').className = '';
}


function ticket_update() {
	if ( !ticketUpdatePosts.length ) return false;
	// now add new posts
	for ( var i = 0; i < ticketUpdatePosts.length; i++ ) {
		var row = ticketUpdatePosts[i];
		if ( !$('post_' + row.id) ) {
			ticket_reply_add(row);
		}
	}
	// now reset the array
	ticketUpdatePosts = [];
	// and hide the panel(s)
	if ( $("user_indicator"  ) ) $("user_indicator"  ).className = 'ac_hidden';
	if ( $("update_indicator") ) $("update_indicator").className = 'ac_hidden';
	return false;
}


/*
	TICKET POST
*/

function ticket_post_expand(id) {
	var show = $('post_content_' + id).className == 'ac_hidden';
	if ( show ) {
		if ( $('post_' + id).className.match(/ compressed/) ) ticket_post_decompress(id);
		ticket_post_toggle(id);
	}
}

function ticket_post_collapse(id) {
	var show = $('post_content_' + id).className == 'ac_hidden';
	if ( !show ) ticket_post_toggle(id);
}

function ticket_post_toggle(id) {
	var show = $('post_content_' + id).className == 'ac_hidden';
	var fetch = $('post_content_body_' + id).className == 'ac_hidden';
	if ( $('post_' + id).className.match(/ compressed/) ) {
		ticket_post_decompress(id);
		return;
	}
	// toggle the main content div
	ac_dom_toggle_class('post_content_' + id, 'ticket_post_content', 'ac_hidden');
	// if hidding, stop
	if ( !show ) return;
	if ( !fetch ) return;
	$('post_content_loading_' + id).className = 'ac_block';
	$('post_content_body_' + id).className = 'ac_hidden';
	if ( $('post_content_edit_' + id) ) $('post_content_edit_' + id).className = 'ac_hidden';

	// send the request
	ticket_post_get(id, 0);
}

function ticket_post_toggle_cb(xml, txt) {
	var ary = ac_dom_read_node(xml);
	if ( typeof ary.row == 'string' && xml.nodeName == 'error' ) {
		if ( ary.row == jsAPIErrorAuthMessage ) {
			ticket_reply_reset();
			window.location.reload(true);
			return;
		}
		alert(( !ary.row ? txt : ary.row ));
		return;
	}
	if ( !ary.postid ) return;

	if ( ac_str_trim(ary.content) == '' ) {
		var preview = ac_str_trim($('post_content_body_' + ary.postid).innerHTML);
		if ( preview.length > 0 ) {
			ary.content = preview;
		} else {
			if (ary.draft) {
				ary.content = '<em>' + ticket_str_post_nodata2;
			}
			else {
				ary.content = '<em>' + ticket_str_post_nodata;
				//if ( typeof ticket_str_post_viewsource != 'undefined' ) {
				// if there is an email source present in #ticket_source
				if (ary.source) {
					ary.content +=
						' <a href="#post-' + ary.postid  + '" onclick="ticket_post_original(' + ary.postid + ');return false;">' +
						ticket_str_post_viewsource +
						'</a>.'
					;
				}
			}
			ary.content += '</em>';
		}
	}
	$('post_content_loading_' + ary.postid).className = 'ac_hidden';
	$('post_content_body_' + ary.postid).className = 'ac_block';
	$('post_content_body_' + ary.postid).innerHTML = ary.content;
	// malicious code panels
	$('post_content_tagwarn_' + ary.postid).className = ( ary.striptag == 1 ? 'ticket_post_warntag' : 'ac_hidden' );
	// show images panels
	$('post_content_showimg_' + ary.postid).className = ( ary.stripimg == 1 ? 'ticket_post_showimg' : 'ac_hidden' );
	$('post_content_hideimg_' + ary.postid).className = ( ary.stripimg != 1 && ary.showimg == 1 ? 'ticket_post_hideimg' : 'ac_hidden' );
	if ( $('post_content_rate_' + ary.postid) ) {
		$('post_content_rate_' + ary.postid).className = ( ary.admin == 1 ? 'ac_block' : 'ac_hidden' );
	}
	if ( $('post_quote_' + ary.postid) ) {
		$('post_quote_content_' + ary.postid).innerHTML = ary.quote;
		$('post_quote_' + ary.postid).className = ( ary.quote != '' ? 'ticket_post_quote' : 'ac_hidden' );
	}
	SyntaxHighlighter.highlight();
}



function ticket_post_expand_bundle(what) {
	ticket_post_toggle_bundle(what, true);
	ac_dom_toggle_class('expandbox', 'ac_block', 'ac_hidden');
}

function ticket_post_collapse_bundle(what) {
	ticket_post_toggle_bundle(what, false);
	ac_dom_toggle_class('collapsebox', 'ac_block', 'ac_hidden');
}

function ticket_post_toggle_bundle(what, show) {
	var papa = $('post_holder');
	var posts = papa.getElementsByTagName('div');
	for ( var i = 0; i < posts.length; i++ ) {
		// if is post div
		if ( posts[i].parentNode == papa ) {
			var id = posts[i].id.replace('post_', '');
			var rel = $('post_content_' + id);
			var type = posts[i].className.replace(/ticket_(.*)post/, '$1');
			var allowed = ( what == 'all' || what == type );
			if ( allowed ) {
				if ( show == ( rel.className == 'ac_hidden' ) ) {
					ticket_post_toggle(id);
				}
			}
		}
	}
}



function ticket_post_quote(id) {
	var content = $('post_content_body_' + id).innerHTML;
	var val = '<div><blockquote><em><font color="#999999">' + content + '</font></em></blockquote></div>';
	ticket_post_options(id);
	ac_editor_insert('messageEditor', val);
}

function ticket_post_forward_cb(xml) {
	var ary = ac_dom_read_node(xml);
	ac_ui_api_callback();
	if ( ary.content && ary.content != '' ) {
		// show the source dialog
		ac_dom_toggle_display('forward', 'block');
		$('forwardpost').value = ary.postid;
		$('forwardsubject').value = 'FWD: ' + ticket.subject;
		var val = '<div><blockquote><em><font color="#999999">' + ary.content + '</font></em></blockquote></div>';
		var attObj = $('post_attach_' + ary.postid);
		if ( $('post_attach_' + ary.postid) ) {
			//var att = $('post_attach_' + ary.postid).innerHTML;
			var att = '';
			var files = $$('#post_attach_' + ary.postid + ' div.ticket_post_attachment');
			for ( var i = 0; i < files.length; i++ ) {
				var file = files[i].getElementsByTagName('a')[0];
				att += '<a href="' + file.href + '">' + file.innerHTML + '</a><br />\n';
			}
			val += '<div><strong>' + ticket_attach_title_str + '</strong><br />\n' + att + '</div>';
		}
		var body = '<p>' + sprintf(ticket_forward_message_str, ticket.stringid) + '</p>\n' + val;
		ac_form_value_set($('forwardEditor'), body);
	}
	// hide the options for this post
	ticket_post_options(ary.postid);
}

function ticket_post_forward_send_cb(xml) {
	var ary = ac_dom_read_node(xml);
	ac_ui_api_callback();

	if (ary.succeeded == 1) {
		ac_result_show(ary.message);
		// hide the forward dialog
		ac_dom_toggle_display('forward', 'block');
		// add history
		if ( ary.history_entry ) ticket_history_add(ary.history_entry);
	} else {
		ac_error_show(ary.message);
	}
}

function ticket_post_options(id) {
	ac_dom_toggle_class('post_options_' + id, 'ticket_post_options_menu', 'ac_hidden');
	if ( $('post_options_' + id).className == 'ticket_post_options_menu' ) {
		var props = {};
		props['post_options_link_' + id] = function(x) {
			return function() {
				ac_dom_toggle_class('post_options_' + x, 'ticket_post_options_menu', 'ac_hidden');
			}
		}(id);
		ac_dom_clicker_add('post_options_' + id, props);
	} else {
		ac_dom_clicker_remove('post_options_' + id, false);
	}
}

function ticket_post_compress(id) {
	var postObj = $('post_' + id);
	postObj.className = postObj.className + ' compressed';
	postObj.onclick = function() { ticket_post_decompress(id); return false; };
}

function ticket_post_decompress(id) {
	var postObj = $('post_' + id);
	postObj.className = postObj.className.replace(' compressed', '');
	postObj.onclick = function() { return false; };
	// decompress all siblings in both directions
	var nextObj = postObj.nextSibling;
	while ( nextObj ) {
		if ( nextObj.nodeName == 'DIV' ) {
			if ( nextObj.className.match(/ compressed/) ) {
				nextObj.className = nextObj.className.replace(' compressed', '');
				nextObj.onclick = function() { return false; };
			} else {
				break;
			}
		}
		nextObj = nextObj.nextSibling;
	}
	var prevObj = postObj.previousSibling;
	while ( prevObj ) {
	//while ( prevObj && prevObj.className.match(/ compressed/) ) {
		if ( prevObj.nodeName == 'DIV' ) {
			if ( prevObj.className.match(/ compressed/) ) {
				prevObj.className = prevObj.className.replace(' compressed', '');
				prevObj.onclick = function() { return false; };
			} else {
				break;
			}
		}
		prevObj = prevObj.previousSibling;
	}
}


/*
	CUSTOM FIELDS
*/

function ticket_update_fields(departments_id) {
    //somethingChanged = true;
    var departments = [];
    var options = $(departments_id).getElementsByTagName('option');

    var root_depts = [];
    for ( var i = 0; i < options.length; i++ ) {
    	// ADMIN SIDE: check for a dash in the display value
    	// does the innerHTML (display value) have a dash at the beginning, indicating a sub-department?
    	var has_dash = ( options[i].innerHTML.substring(0, 1) == '-' );
    	// if no dash, then it's a root department. add it to array
			if (!has_dash) {
				root_depts.push(options[i].value);
			}
    	if (options[i].selected) {
    		// always add the selected option to the custom fields array
    		departments.push(options[i].value);
    		// if there is a dash, and it's selected, it's a sub-department. grab it's parent
    		// (admin side only)
    		if (has_dash) {
    			// we grab the last department added to the array. since the depts are ordered in how they would structurally (tree-like) appear, this seems to work
    			var this_option_parent = root_depts[ root_depts.length - 1 ];
    			departments.push(this_option_parent);
    		}
    	}
    }

    // PUBLIC SIDE: the other select list for departments on the page.
    // IE: if they onchange for 'department' select list, the other one is 'subdepartment.' and vice-versa
    var other_dept_select = (departments_id == 'department') ? 'subdepartment' : 'department';

    if ( $(other_dept_select) ) {
	  	var other_dept_options = $(other_dept_select).getElementsByTagName('option');
	  	if (other_dept_options.length > 0) {
		    for ( var i = 0; i < other_dept_options.length; i++ ) {
		    	if ( other_dept_options[i].selected ) departments.push(other_dept_options[i].value);
		    }
	  	}
    }

    ac_ajax_call_cb('api.php', 'hd.custom_field_update', ticket_update_fields_callback, departments);
}

function ticket_update_fields_callback(xml, txt) {
	var rel = $('custom_fields_box');
	var ary = ac_dom_read_node(xml, null);
	ac_dom_remove_children(rel);
	var total = 0;
	var visible = 0;
	if ( ary.row ) {
		for ( var i = 0; i < ary.row.length; i++ ) {
			var row = ary.row[i];
			if ( typeof prefields != 'undefined' ) {
				if ( typeof prefields[row.id] != 'undefined' ) {
					row.val = prefields[row.id];
				}
			}
			var node = ac_custom_fields_cons(row);
			if ( parseInt(row.type, 10) != 6 ) {
				rel.appendChild(Builder.node(
					"div",
					[
						Builder.node("span", { className: 'custom_field_title' }, [ Builder._text(ac_custom_fields_title(row)) ]),
						Builder.node("br"),
						node
					]
				));
				visible++;
			} else {
				rel.appendChild(Builder.node("div", [ node ] ));
			}
			total++;
		}
	}
	$('custom_fields_box').className = ( visible > 0 ? 'ac_block' : 'ac_hidden' );
}


/*
	COMMON FUNCS
*/

function setIcon(ico) {
	$('iconField').value = ico;
	var box = $('iconSelect');
	var icons = box.getElementsByTagName('a');
	for ( var i = 0; i < icons.length; i++ ) {
		icons[i].className = ( ico == icons[i].title ? 'ac_icon_selected' : '' );
	}
	return false;
}

function toggleEditor(id, action, settings) {
	settings.language = _twoletterlangid;
	if ( action == ac_editor_is(id + 'Editor') ) return false;
	ac_editor_toggle(id + 'Editor', settings);

	if ($(id + 'EditorLinkOn'))
		$(id + 'EditorLinkOn').className  = ( action ? 'currenttab' : 'othertab' );

	if ($(id + 'EditorLinkOff'))
		$(id + 'EditorLinkOff').className = ( !action ? 'currenttab' : 'othertab' );

	if ($(id + 'EditorLinkDefault'))
		$(id + 'EditorLinkDefault').className = ( ( action != ( ac_js_admin.htmleditor == 1 ) ) ? 'ac_block' : 'ac_hidden' );

	if ( !$(id + 'Editor') ) tmpEditorContent = ac_form_value_get($(id + '_form')); else // heavy hack!!!
	tmpEditorContent = ac_form_value_get($(id + 'Editor'));

	return false;
}

function setDefaultEditor(id) {
	var isEditor = ac_editor_is(id + 'Editor');
	if ( isEditor == ( ac_js_admin.htmleditor == 1 ) ) return false;
	// send save command
	// save new admin limit remotelly
	ac_ajax_call_cb('api.php', 'user.user_update_value', ac_ajax_cb(setDefaultEditor_cb), 'htmleditor', ( isEditor ? 1 : 0 ));
	$(id + 'EditorLinkDefault').className = 'ac_hidden';
	ac_js_admin.htmleditor = ( isEditor ? 1 : 0 );
	return false;
}

function setDefaultEditor_cb(ary) {
}

// not used...
function editorContentChanged(inst) {
	tmpEditorContent = inst.getContent();
	//somethingChanged = true;
}

function sort_row(id, func, dir) {
	ac_ui_api_call(jsSaving);
	ac_ajax_call_cb("api.php", func, sort_row_cb, id, dir);
}

function sort_row_cb(xml) {
	var ary = ac_dom_read_node(xml);
	ac_ui_api_callback();

	if (ary.succeeded != "0") {
		ac_result_show(ary.message[0]);

		var func = eval(ary.message[1] + "_list_anchor");
		if (typeof func == "function") {
			ac_ui_anchor_set(func());
		}

	} else {
		ac_error_show(ary.message[0]);
	}
}


/*
	SITE EXPLORER
*/

function browseCategory(obj, id) {
	// flip plus/minus img
	obj.src = ( obj.src.match(/minus/) ? obj.src.replace(/minus/, 'plus') : obj.src.replace(/plus/, 'minus') );
	ac_dom_toggle_class('children4idCat' + id, 'ac_hidden', 'ac_block');
	//setCookie(id, $('children4idCat' + id).className);
	return false;
}


/*
    CLONER FUNCTIONS
*/

function clone_1st_element (node, elem, clearInputs) {
	return ac_dom_clone_node (node, elem, 0, clearInputs);
}

function clone_1st_div (node) {
    return clone_1st_element (node, 'div', true);
}

function clone_1st_tr (node) {
    return clone_1st_element (node, 'tr', false);
}

function clear_inputs (node)
{
    var newinput = node.getElementsByTagName ('input');
    for (var i=0; i<newinput.length; i++) {
        if (newinput[i].type == 'text' || newinput[i].type == 'file') newinput[i].value = '';
    }
}

function clear_areas (node)
{
    var newinput = node.getElementsByTagName ('textarea');
    for (var i=0; i<newinput.length; i++) {
        newinput[i].innerHTML = '';
    }
}
function remove_element (node)
{
    var papa = node;
    var divs = node.parentNode.getElementsByTagName ('div');
    var subDivs = 0;
    for ( var i = 0; i < divs.length; i++ ) {
   		// is directly underneath, count it
    	if ( divs[i].parentNode == node.parentNode ) {
    		subDivs++;
    	}
    }
    if (subDivs > 1)
    {
        node.parentNode.removeChild (node);
    }
    else
    {
	    var newinput = node.getElementsByTagName ('input');
	    for (var i=0; i<newinput.length; i++) {
	        if (newinput[i].type == 'text' || newinput[i].type == 'file') newinput[i].value = '';
	    }
	    var newselect = node.getElementsByTagName ('select');
	    for (var i=0; i<newselect.length; i++) {
	        newselect[i].selectedIndex = -1;
	        //newselect[i].selectedIndex = (newselect[i].multiple?-1:0);
	    }
    }
}
/*
    CLONER END
*/

function account_user_email_delete(emailid) {

	if ( confirm(strings_user_email_delete) ) {

		var post = [emailid];

		ac_ajax_post_cb("api.php", "user.user_email_delete_post", account_user_email_delete_cb, post);
	}
}

function account_user_email_delete_cb(xml) {

	var ary = ac_dom_read_node(xml, null);

	if (ary.succeeded) {
		$("add_email_" + ary.emailid).innerHTML = '';
	}
}

function ticket_list_table_row(row, tr) {
	// set this ticket's status style
	var className = 'ac_table_row ticket_list_row_out';
	if ( row.a_statusstyle != '' ) className += '_' + row.a_statusstyle;
	tr.className = className;
	return tr;
}

function ticket_list_table_cell(row, td, clickable) {
	// if this can be clicked
	if ( clickable ) {
		// set the link to a view ticket page
		td.onclick = function(id) {
			return function() {
				window.location.href = ( typeof row.adminurl != 'undefined' ? row.adminurl : row.url );
				//window.location.href = ( typeof row.url != 'undefined' ? row.url : 'main.php?action=ticket&id=' + id );
			}
		}(row.id);
	}
	// set the mouseover/out classes for this ticket's status style
	td.onmouseover  = function(style) {
		return function() {
			var className = 'ac_table_row ticket_list_row_over';
			if ( style != '' ) className += '_' + style;
			this.parentNode.className = className;
		};
	}(row.a_statusstyle);
	td.onmouseout   = function(style) {
		return function() {
			var className = 'ac_table_row ticket_list_row_out';
			if ( style != '' ) className += '_' + style;
			this.parentNode.className = className;
		};
	}(row.a_statusstyle);
	return td;
}

function privatemessage_list_table_cell(row, td, clickable) {
	// if this can be clicked
	if ( clickable ) {
		// set the link to a view ticket page
		td.onclick = function(id) {
			return function() {
				window.location.href = ( typeof row.adminurl != 'undefined' ? row.adminurl : sprintf("#form-%d", row.id) );
				//window.location.href = ( typeof row.url != 'undefined' ? row.url : 'main.php?action=ticket&id=' + id );
			}
		}(row.id);
	}
	// set the mouseover/out classes for this ticket's status style
	td.onmouseover  = function(style) {
		return function() {
			var className = 'ac_table_row privatemessage_list_row_over';
			//if ( style != '' ) className += '_' + style;
			this.parentNode.className = className;
		};
	}();
	td.onmouseout   = function(style) {
		return function() {
			var className = 'ac_table_row privatemessage_list_row_out';
			//if ( style != '' ) className += '_' + style;
			this.parentNode.className = className;
		};
	}();
	return td;
}


function user_online() {
	//$('user_online_load').className = 'ac_block';
	//$('user_online_list').className = 'ac_hidden';
	//$('user_online_none').className = 'ac_hidden';

	// issue an ajax call
	ac_ajax_call_cb(apipath, "user.user_online", user_online_cb);
}

function user_online_cb(xml) {
	var ary = ac_dom_read_node(xml);
	if ( typeof ary.row == 'string' && xml.nodeName == 'error' ) {
		if ( ary.row == jsAPIErrorAuthMessage ) {
			window.location.reload(true);
			return;
		}
		//alert(ary.row);
		alert('There was a problem retrieving online users list.')
		return;
	}

	var rel = $('user_online_list');
	ac_dom_remove_children(rel);
	var cnt = ( ary.row ? ary.row.length : 0 );
	if ( cnt > 0 ) {
		var spans = [];
		for ( var i = 0; i < cnt; i++ ) {
			var row = ary.row[i];

			if (row.username == "" || row.username.match(/^[ ]+$/))
				continue;

			var labeltitle =
				row.username + ' ' + row.actionname + ' ' + jsTicket4Status +
				( row.descript != '' ? ' ( ' + row.descript + ' ) ' : '' ) +
				' - ' + sql2date(row.tstamp).format(ac_js_site.datetimeformat)
			;
			spans.push(Builder.node(
					'span',
					{ className: 'user_online_label' },
					[
						Builder.node(
							'a',
							{
								href: 'main.php?action=user_view&id=' + row.userid,
								title: labeltitle,
								style: sprintf("color: #%s", row.status == 0 ? "999" : (row.status == 1 ? "333" : "3F7C04"))
							},
							[ Builder._text(row.username) ]
						),
					]
				)
			);

			if ((i+1) < cnt)
				spans.push(Builder._text(", "));
		}

		rel.appendChild(Builder.node("div", { className: "user_online_row" }, spans));
	}

	// set the stage
	//$('user_online_load').className = 'ac_hidden';
	$('user_online_list').className = ( cnt != 0 ? 'ac_block' : 'ac_hidden' );
	$('user_online_none').className = ( cnt == 0 ? 'ac_block' : 'ac_hidden' );
}

function category_article_select_update(categoryObj, articleObj, func) {
	articleObj.selectedIndex = 0;
	articleObj.disabled = true;
	if ( categoryObj.value == 0 ) {
		return;
	}
	var thisfunc = function(xml) {
		var ary = ac_dom_read_node(xml);
		ac_ui_api_callback();

		// remove old articles
		var options = articleObj.getElementsByTagName('option');
		for ( var i = options.length - 1; i > 0; i-- ) articleObj.removeChild(options[i]);

		// add articles
		for ( var i = 0; i < ary.cnt; i++ ) {
			articleObj.appendChild(Builder.node('option', { value: ary.rows[i].id }, [ ary.rows[i].title ]));
		}

		articleObj.disabled = false;
		articleObj.selectedIndex = 0;
	};
	if ( typeof func == 'function' ) {
		var runfunc = function(xml) { thisfunc(xml); func(xml); }
	} else {
		var runfunc = thisfunc;
	}
	// issue an ajax call
	ac_ui_api_call(jsLoading);
	ac_ajax_call_cb(
		kb_path,
		'category_articles',
		runfunc,
		categoryObj.value
	);
}

/*
     TICKET RELATIONS FOR TASKS, CALENDAR EVENTS
*/

function task_remove_time() {
	if ($("no_time").checked == true) {
		if ($("task_form_ddateField").value != "") {
			var ddate_array = $("task_form_ddateField").value.split(" ");

			$("task_form_ddateField").value = ddate_array[0];
		}
	}
}

function ticket_rel_field_delete(ticket_dom_row) {

	var ticket_td_inputs = $("ticket_td").getElementsByTagName("input");

	// Only remove entire row if there's more than one input, otherwise just clear contents
	if (ticket_td_inputs.length > 1) {
		$("ticket" + ticket_dom_row).value = "";
		$("ticket_div" + ticket_dom_row).className = "ac_hidden";
		//ac_dom_remove_children($("ticket_div" + ticket_dom_row));
	}
	else {
		$("ticket" + ticket_dom_row).value = "";
	}
}

function ticket_rel_field_add() {

	var ticket_td_inputs = $("ticket_td").getElementsByTagName("input");
	var ticket_td_next = ticket_td_inputs.length;

	var new_input = Builder.node("input", { type: "text", size: "35", name: "tickets[]", id: "ticket" + ticket_td_next }, "");
	var new_input_delete = Builder.node( "a", { href: "javascript: ticket_rel_field_delete(" + ticket_td_next + ");", style: "margin-left: 5px; vertical-align: top;" }, Builder.node("img", { src: "images/delete.gif", border: "0" }) );
	var new_input_div = Builder.node("div", { id: "ticket_div" + ticket_td_next, style: "margin-top: 5px;" }, [new_input, new_input_delete]);

	$("ticket_td").appendChild(new_input_div);
}

function ticket_search_inline_defaults() {
	$("search_content").value = '';

	var boxes = $("search").getElementsByTagName("input");

	for (var i = 0; i < boxes.length; i++) {
		if (boxes[i].type == "checkbox")
			boxes[i].checked = true;
	}
}

function ticket_rel_search_display() {

	// display ticket search div
	ac_dom_display_block("ticket_rel_search_div");

	// focus search text field
	$("ticket_search_inline_query").focus();

	// have to do this here (on launch of the div) because we need the results in the DOM after Adding tickets from search div to page
	ac_dom_remove_children($("ticket_search_inline_results_tbody"));
}

function ticket_search_inline_check_close() {

	// close ticket search div
	ac_dom_toggle_display('ticket_rel_search_div', 'block');

	// hide result table, and no results div, in ticket search popup
	$("ticket_search_inline_results").className = "ac_hidden";
	$("ticket_search_inline_noresults").className = "ac_hidden";

	// clear out search value
	$("ticket_search_inline_query").value = "";

	var task_ticket_search_results_inputs = $("ticket_search_inline_results").getElementsByTagName("input");

	// uncheck all "form_search_tickets[]" checkboxes
	for (var i = 0; i < task_ticket_search_results_inputs.length; i++) {

		var input = task_ticket_search_results_inputs[i];

		if (input.type == "checkbox") {

			input.checked == false;
		}
	}

	//ac_dom_display_block("form");
}

function ticket_search_inline() {
	var post = ac_form_post($("ticket_rel_search_div"));

	if (post.ticket_search_inline_query != "") {
		ac_ajax_post_cb("api.php", "ticket.ticket_search_inline", ticket_search_inline_cb, post);
	}
	else {
		alert(search_noquery);
	}
}

function ticket_search_inline_cb(xml) {

	var ary = ac_dom_read_node(xml);

	ac_dom_remove_children($("ticket_search_inline_results_tbody"));

	// if there are results returned
	if (ary.row) {
		$("ticket_search_inline_results").className = "ac_block";
		$("ticket_search_inline_noresults").className = "ac_hidden";

		for (var i = 0; i < ary.row.length; i++) {

			var row = ary.row[i];

			var table_cells = new Array();

			table_cells.push( Builder.node( "td", {}, Builder.node("input", { type: "checkbox", name: "tickets_search_inline_select[]", value: row.stringid } ) ) );
			table_cells.push( Builder.node("td", {}, row.stringid ) );
			table_cells.push( Builder.node("td", {}, ac_str_shorten(row.subject, 25) ) );
			table_cells.push( Builder.node("td", {}, sql2date(row.pdate).format("%m/%d/%Y") ) );

			var table_row = Builder.node("tr", {}, table_cells);

			$("ticket_search_inline_results_tbody").appendChild(table_row);
		}
	}
	else {
		$("ticket_search_inline_results").className = "ac_hidden";
		$("ticket_search_inline_noresults").className = "ac_block";
	}
}

// adds the selected tickets from the search div back to the Edit Task form
function ticket_search_inline_add() {

	var post = ac_form_post($("ticket_search_inline_results"));

	// if any tickets from the search results are checked
	if (post.tickets_search_inline_select) {

		var ticket_td_inputs = $("ticket_td").getElementsByTagName("input");
		var ticket_td_next = ticket_td_inputs.length;

		for (var i = 0; i < post.tickets_search_inline_select.length; i++) {

			var ticket = post.tickets_search_inline_select[i];

			// if we're on the first ticket, and there's only one <input> field there, and that one field is empty,
			// it's the default empty one - use that first.
			if (i == 0 && ticket_td_next == 1 && $("ticket0").value == "") {

				$("ticket0").value = ticket;
			}
			else {

				var dom_counter = i + ticket_td_next;

				var new_input = Builder.node("input", { type: "text", size: "35", name: "tickets[]", id: "ticket" + dom_counter, value: ticket }, "");
				var new_input_delete = Builder.node( "a", { href: "javascript: ticket_rel_field_delete(" + dom_counter + ");", style: "margin-left: 5px; vertical-align: top;" }, Builder.node("img", { src: "images/delete.gif", border: "0" }) );
				var new_input_div = Builder.node("div", { id: "ticket_div" + dom_counter, style: "margin-top: 5px;" }, [new_input, new_input_delete]);

				$("ticket_td").appendChild(new_input_div);
			}
		}

		ticket_search_inline_check_close();
	}
	else {
		alert(ticket_search_inline_str_ticket_none);
	}
}

function form_editor_personalize_open(type, insertObj) {
	if ( !insertObj ) insertObj = '';
	// set type
	$('personalize4').value = type;
	$('personalize2').value = insertObj;
	// collapse all open divs
	var divs = $$('#personalizelist ul');
	for ( var i = 0; i < divs.length; i++ ) {
		divs[i].className = ( i == 0 ? 'personalizelistgroup' : 'ac_hidden' );
	}
	// open modal
	ac_dom_toggle_display('message_personalize', 'block');
}

function form_editor_personalize_insert(value) {
	if ( value == '' ) {
		alert(strPersMissing);
		return;
	}
	// close the modal
	ac_dom_toggle_display('message_personalize', 'block');
	// build the code
	var code = form_editor_personalize_build(value);
	if ( code == '' ) return;
	// push it into needed editor
	ac_editor_insert($('personalize2').value, ( $('personalize4').value == 'html' ? nl2br(code) : code ));
}

function form_editor_personalize_build(val) {
	// what type of code to build
	var type = $('personalize4').value;
	// now handle custom (html?) cases
	var text = '';
	// only today tag should be reset
	if ( val.match( /^%TODAY[+-]\d+%$/ ) ) {
		val = '%TODAY*%';
	}
	if ( val == '%CONFIRMLINK%' ) {
		text = strConfirmLinkText;
	} else if ( val == '%UNSUBSCRIBELINK%' ) {
		text = strUnsubscribeText;
	} else if ( val == '%UPDATELINK%' ) {
		text = strSubscriberUpdateText;
	} else if ( val == '%WEBCOPY%' ) {
		text = strWebCopyText;
	} else if ( val == '%FORWARD2FRIEND%' ) {
		text = strForward2FriendText;
	} else if ( val == '%SOCIALSHARE%' ) {
		//text = strForward2FriendText; // don't prompt for anything, just use val
	} else if ( val == '%TODAY*%' ) {
		var entered = prompt(strEnterRange, '+1');
		if ( !entered ) return;
		if ( !entered.match( /^[-+]?\d+$/ ) ) {
			alert(strEnterRangeInvalid);
			return;
		}
		if ( !entered.match(/^[-+].*$/) ) {
			entered = '+' + entered;
		}
		val = '%TODAY' + entered + '%';
	}
	if ( type == 'html' && text != '' ) {
		entered = prompt(strEnterText, text);
		if ( !entered ) entered = text;
		val = '<a href="' + val + '">' + entered + '</a>';
	}
	return val;
}

function form_editor_personalization(prfx, sets, type, suffix) {
	if ( typeof suffix != 'string' ) suffix = 'PersTags';
	if ( type != 'mime' && type != 'text' && type != 'html' ) type = 'mime';
	if ( type != 'html' ) {
		// personalization tags select
		var rel = $(prfx + suffix);
		// clean up personalization tags
		ac_dom_remove_children(rel);
		// add "peronalize" text
		rel.appendChild(Builder.node('option', { value: '', selected: 'selected' }, [ Builder._text(strPersPersonalize) ]));
	}
	// check passed sets
	if ( !sets.length || sets.length == 0 ) sets = [ 'confirm', 'subscriber', 'sender', 'system' ];
	// prepare optgroups
	var subnodes = []; // subscriber personalization nodes
	var sysnodes = []; // system personalization nodes
	var sndnodes = []; // sender personalization nodes
	var gcfnodes = []; // global custom fields nodes
	// add confirm link to system nodes
	if ( ac_array_has(sets, 'confirm') ) {
		// set %CONFIRMLINK%
		sysnodes.push(Builder.node('option', { value: '%CONFIRMLINK%' }, [ Builder._text(strPersConfirmLink) ]));
	}
	// build regular system nodes
	if ( ac_array_has(sets, 'system') ) {
		// set %PERS_UNSUB%
		sysnodes.push(Builder.node('option', { value: '%UNSUBSCRIBELINK%' }, [ Builder._text(strPersUnsubLink) ]));
		// set %PERS_UPDATE%
		sysnodes.push(Builder.node('option', { value: '%UPDATELINK%' }, [ Builder._text(strPersUpdateLink) ]));
		// set %PERS_WCOPY%
		sysnodes.push(Builder.node('option', { value: '%WEBCOPY%' }, [ Builder._text(strPersWCopyLink) ]));
		// set %PERS_FRIEND%
		sysnodes.push(Builder.node('option', { value: '%FORWARD2FRIEND%' }, [ Builder._text(strPersFriendLink) ]));
		// set %SOCIALSHARE%
		sysnodes.push(Builder.node('option', { value: '%SOCIALSHARE%' }, [ Builder._text(strPersSocialLink) ]));
		// set %PERS_TODAY%
		sysnodes.push(Builder.node('option', { value: '%TODAY%' }, [ Builder._text(strPersTodayLink) ]));
		// set %PERS_TODAY%
		sysnodes.push(Builder.node('option', { value: '%TODAY*%' }, [ Builder._text(strPersTodayRangeLink) ]));
	}
	// build subscriber nodes
	if ( ac_array_has(sets, 'subscriber') ) {
		// set %PERS_EMAIL%
		subnodes.push(Builder.node('option', { value: '%EMAIL%' }, [ Builder._text(strPersEmailLink) ]));
		// set %PERS_FIRSTNAME%
		subnodes.push(Builder.node('option', { value: '%FIRSTNAME%' }, [ Builder._text(strPersFNameLink) ]));
		// set %PERS_LASTNAME%
		subnodes.push(Builder.node('option', { value: '%LASTNAME%' }, [ Builder._text(strPersLNameLink) ]));
		// set %PERS_LASTNAME%
		subnodes.push(Builder.node('option', { value: '%FULLNAME%' }, [ Builder._text(strPersNameLink) ]));
		// set %PERS_IP%
		subnodes.push(Builder.node('option', { value: '%SUBSCRIBERIP%' }, [ Builder._text(strPersIPLink) ]));
		// set %PERS_DATETIME%
		subnodes.push(Builder.node('option', { value: '%SUBDATETIME%' }, [ Builder._text(strPersSDateTimeLink) ]));
		// set %PERS_DATE%
		subnodes.push(Builder.node('option', { value: '%SUBDATE%' }, [ Builder._text(strPersSDateLink) ]));
		// set %PERS_TIME%
		subnodes.push(Builder.node('option', { value: '%SUBTIME%' }, [ Builder._text(strPersSTimeLink) ]));
		// set %PERS_ID%
		subnodes.push(Builder.node('option', { value: '%SUBSCRIBERID%' }, [ Builder._text(strPersSIDLink) ]));
	}
	// build global custom fields nodes
	if ( ac_array_has(sets, 'subscriber') && fields ) {
		// general custom fields
		var gcfnodes  = [];
		for ( var i in fields ) {
			var f = fields[i];
			if ( !f.perstag || f.perstag == '' ) {
				f.perstag = 'PERS_' + f.id;
			}
			var tag = '%' + f.perstag + '%';
			gcfnodes.push(Builder.node('option', { value: tag }, [ Builder._text(f.title) ]));
		}
	}
	if ( type != 'html' ) {
		if ( subnodes.length > 0 ) {
			rel.appendChild(Builder.node('optgroup', { label: strPersSubscriberTags }, subnodes));
		}
		if ( sysnodes.length > 0 ) {
			rel.appendChild(Builder.node('optgroup', { label: strPersSystemTags }, sysnodes));
		}
		if ( sndnodes.length > 0 ) {
			rel.appendChild(Builder.node('optgroup', { label: strPersSenderTags }, sndnodes));
		}
		if ( gcfnodes.length > 0 ) {
			rel.appendChild(Builder.node('optgroup', { label: strPersGlobalFields }, gcfnodes));
		}
		rel.selectedIndex = 0;
	}
	/*
	// don't do this
	if ( type != 'text' ) {
		// tinyMCE support
		ac_editor_personalize_render = function(c, m) {
			// uses ACCustomFieldsResult
			var sub;
			if ( subnodes.length > 0 ) {
				//m.add({title : strPersSubscriberTags, 'class' : 'mceMenuItemTitle'}).setDisabled(1);
				sub = m.addMenu({ title : strPersSubscriberTags });
				for ( var i = 0; i < subnodes.length; i++ ) {
					sub.add({
						title : subnodes[i].innerHTML,
						onclick : function(val) {
							return function() {
								tinyMCE.activeEditor.execCommand('mceInsertContent', false, val);
							}
						}(subnodes[i].value)
					});
				}
			}
			if ( sysnodes.length > 0 ) {
				//m.add({title : strPersSystemTags, 'class' : 'mceMenuItemTitle'}).setDisabled(1);
				sub = m.addMenu({ title : strPersSystemTags });
				for ( var i = 0; i < sysnodes.length; i++ ) {
					sub.add({
						title : sysnodes[i].innerHTML,
						onclick : function(val) {
							return function() {
								var text = '';
								// only today tag should be reset
								if ( val.match( /^%TODAY[+-]\d+%$/ ) ) {
									val = '%TODAY*%';
								}
								if ( val == '%CONFIRMLINK%' ) {
									text = strConfirmLinkText;
								} else if ( val == '%UNSUBSCRIBELINK%' ) {
									text = strUnsubscribeText;
								} else if ( val == '%UPDATELINK%' ) {
									text = strSubscriberUpdateText;
								} else if ( val == '%WEBCOPY%' ) {
									text = strWebCopyText;
								} else if ( val == '%FORWARD2FRIEND%' ) {
									text = strForward2FriendText;
								} else if ( val == '%SOCIALSHARE%' ) {
									//text = strForward2FriendText; // don't prompt for anything, just use val
								} else if ( val == '%TODAY*%' ) {
									var entered = prompt(strEnterRange, '+1');
									if ( !entered ) return;
									if ( !entered.match( /^[-+]?\d+$/ ) ) {
										alert(strEnterRangeInvalid);
										return;
									}
									if ( !entered.match(/^[-+].*$/) ) {
										entered = '+' + entered;
									}
									val = '%TODAY' + entered + '%';
								}
								if ( text != '' ) {
									entered = prompt(strEnterText, text);
									if ( !entered ) entered = text;
									val = '<a href="' + val + '">' + entered + '</a>';
								}
								tinyMCE.activeEditor.execCommand('mceInsertContent', false, val);
							}
						}(sysnodes[i].value)
					});
				}
			}
			var sndnodes  = [];
			if ( ac_array_has(sets, 'sender') ) {
				if ( persResultSet && persResultSet[0] && persResultSet[0].html ) {
					for ( var i in persResultSet[0].html ) {
						var f = persResultSet[0].html[i];
						if ( typeof f != 'function' ) {
							if ( !f.tag || f.tag == '' ) {
								f.tag = 'PERS_' + f.id;
							}
							f.tag = '%' + f.tag + '%';
							sndnodes.push( Builder.node('option', { value: f.tag }, [ Builder._text(f.name) ]));
						}
					}
				}
				if ( sndnodes.length > 0 ) {
					//m.add({title : strPersSenderTags, 'class' : 'mceMenuItemTitle'}).setDisabled(1);
					sub = m.addMenu({ title : strPersSenderTags });
					for ( var i = 0; i < sndnodes.length; i++ ) {
						sub.add({
							title : sndnodes[i].innerHTML,
							onclick : function(val) {
								return function() {
									tinyMCE.activeEditor.execCommand('mceInsertContent', false, val);
								}
							}(sndnodes[i].value)
						});
					}
				}
			}
			if ( gcfnodes.length > 0 ) {
				//m.add({title : strPersGlobalFields, 'class' : 'mceMenuItemTitle'}).setDisabled(1);
				sub = m.addMenu({ title : strPersGlobalFields });
				for ( var i = 0; i < gcfnodes.length; i++ ) {
					sub.add({
						title : gcfnodes[i].innerHTML,
						onclick : function(val) {
							return function() {
								tinyMCE.activeEditor.execCommand('mceInsertContent', false, val);
							}
						}(gcfnodes[i].value)
					});
				}
			}
			var lcfnodes  = [];
			for ( var i in ACCustomFieldsResult ) {
				var f = ACCustomFieldsResult[i];
				if ( typeof f != 'function' ) {
					if ( !f.perstag || f.perstag == '' ) {
						f.perstag = 'PERS_' + f.id;
					}
					f.perstag = '%' + f.perstag + '%';
					lcfnodes.push( Builder.node('option', { value: f.perstag }, [ Builder._text(f.title) ]));
				}
			}
			if ( lcfnodes.length > 0 ) {
				//m.add({title : strPersListFields, 'class' : 'mceMenuItemTitle'}).setDisabled(1);
				sub = m.addMenu({ title : strPersListFields });
				for ( var i = 0; i < lcfnodes.length; i++ ) {
					sub.add({
						title : lcfnodes[i].innerHTML,
						onclick : function(val) {
							return function() {
								tinyMCE.activeEditor.execCommand('mceInsertContent', false, val);
							}
						}(lcfnodes[i].value)
					});
				}
			}
		}
	}
	*/
}


function form_editor_personalization_link_push(value, title) {
	return Builder.node(
		'li',
		[
			Builder.node(
				'a',
				{
					href: '#',
					onclick: "form_editor_personalize_insert('" + value + "');return false;"
				},
				[ Builder._text(title) ]
			)
		]
	);
}

function form_editor_personalization_section_push(nodes, title) {
	return Builder.node(
		'div',
		{
			className: 'personalizelistsection'
		},
		[
			Builder.node(
				'div',
				{
					className: 'personalizelisttitle'
				},
				[
					Builder.node(
						'a',
						{
							href: '#',
							onclick: "var x=this.parentNode.parentNode.getElementsByTagName('ul')[0];x.className=(x.className=='ac_hidden'?'personalizelistgroup':'ac_hidden');return false;"
						},
						[ Builder._text(title) ]
					)
				]
			),
			Builder.node('ul', { className: 'ac_hidden' }, nodes)
		]
	);
}

function form_editor_personalization_links(sets, type) {
	if ( type != 'mime' && type != 'text' && type != 'html' ) type = 'mime';
	// personalization tags box
	var rel = $('personalizelist');
	// clean up personalization tags
	ac_dom_remove_children(rel);
	// add "peronalize" text
	//rel.appendChild(form_editor_personalization_link_push('', strPersPersonalize));
	// check passed sets
	if ( !sets.length || sets.length == 0 ) sets = [ 'confirm', 'subscriber', 'sender', 'system' ];
	// prepare optgroups
	var subnodes = []; // subscriber personalization nodes
	var sysnodes = []; // system personalization nodes
	var sndnodes = []; // sender personalization nodes
	var gcfnodes = []; // global custom fields nodes
	// add confirm link to system nodes

	if ( ac_array_has(sets, 'email') ) {
		sysnodes.push(form_editor_personalization_link_push("%TICKETID%"       , form_editor_personalization_str_ticketid));
		sysnodes.push(form_editor_personalization_link_push("%EMAIL%"          , form_editor_personalization_str_email));
		sysnodes.push(form_editor_personalization_link_push("%LASTPOST%"       , form_editor_personalization_str_lastpost));
		sysnodes.push(form_editor_personalization_link_push("%LASTPOST:5%"     , form_editor_personalization_str_lastpost5));
		sysnodes.push(form_editor_personalization_link_push("%TICKETLINK%"     , form_editor_personalization_str_ticketlink));
		sysnodes.push(form_editor_personalization_link_push("%STATUS%"         , form_editor_personalization_str_status));
		sysnodes.push(form_editor_personalization_link_push("%SUBJECT%"        , form_editor_personalization_str_subject));
		sysnodes.push(form_editor_personalization_link_push("%DATE%"           , form_editor_personalization_str_date));
		sysnodes.push(form_editor_personalization_link_push("%TIME%"           , form_editor_personalization_str_time));
		sysnodes.push(form_editor_personalization_link_push("%DUEDATE%"        , form_editor_personalization_str_duedate));
		sysnodes.push(form_editor_personalization_link_push("%CLIENT-EMAIL%"   , form_editor_personalization_str_clientemail));
		sysnodes.push(form_editor_personalization_link_push("%CLIENT-USERNAME%", form_editor_personalization_str_clientuser));
		sysnodes.push(form_editor_personalization_link_push("%CLIENT-IP%"      , form_editor_personalization_str_clientip));
		sysnodes.push(form_editor_personalization_link_push("%CLIENT-COMPANY%" , form_editor_personalization_str_clientcompany));
		sysnodes.push(form_editor_personalization_link_push("%LAST-IP%"        , form_editor_personalization_str_lastip));
		sysnodes.push(form_editor_personalization_link_push("%OPEN-DATE%"      , form_editor_personalization_str_opendate));
		sysnodes.push(form_editor_personalization_link_push("%OPEN-TIME%"      , form_editor_personalization_str_opentime));
		sysnodes.push(form_editor_personalization_link_push("%DURATION%"       , form_editor_personalization_str_duration));
		sysnodes.push(form_editor_personalization_link_push("%PRIORITY%"       , form_editor_personalization_str_priority));
		sysnodes.push(form_editor_personalization_link_push("%POSTS-COUNT%"    , form_editor_personalization_str_postscount));
		sysnodes.push(form_editor_personalization_link_push("%DESK%"           , form_editor_personalization_str_desk));
		sysnodes.push(form_editor_personalization_link_push("%RELATEDKB%"      , form_editor_personalization_str_relatedkb));
		sysnodes.push(form_editor_personalization_link_push("%DEPARTMENT%"     , form_editor_personalization_str_department));
		sysnodes.push(form_editor_personalization_link_push("%ATTACHMENTS%"    , form_editor_personalization_str_attachments));
	}
	// build global custom fields nodes

	if ( ac_array_has(sets, 'email') && fields ) {
		// general custom fields
		var gcfnodes  = [];
		for ( var i in fields ) {
			var f = fields[i];
			var tag = '%FIELD-' + f.id + '%';
			gcfnodes.push(form_editor_personalization_link_push(tag, f.title));
		}
	}

	if ( subnodes.length > 0 ) {
		rel.appendChild(form_editor_personalization_section_push(subnodes, strPersSubscriberTags));
	}
	if ( sysnodes.length > 0 ) {
		rel.appendChild(form_editor_personalization_section_push(sysnodes, strPersSystemTags));
	}
	if ( sndnodes.length > 0 ) {
		rel.appendChild(form_editor_personalization_section_push(sndnodes, strPersSenderTags));
	}
	if ( gcfnodes.length > 0 ) {
		rel.appendChild(form_editor_personalization_section_push(gcfnodes, strPersGlobalFields));
	}
	//rel.selectedIndex = 0;
}

var persResultSet = null;
function form_editor_sender_personalization(ary, rel) {
	persResultSet = ary;
	// custom fields
	var nodesin  = [];
	// check if there is an existing group
	// if yes, we'll remove it first
	var divgroups = $$('#' + rel.id + ' div.personalizelisttitle a');
	for ( var i = 0; i < divgroups.length; i++ ) {
		if ( divgroups[i].innerHTML == strPersSenderTags ) {
			rel.removeChild(divgroups[i].parentNode.parentNode);
			break;
		}
	}
	if ( ary[0].text ) {
		for ( var i in ary[0].text ) {
			var f = ary[0].text[i];
			if ( typeof f != 'function' ) {
				if ( !f.tag || f.tag == '' ) {
					f.tag = 'PERS_' + f.id;
				}
				var ftag_value = '%' + f.tag + '%';
				//f.tag = '%' + f.tag + '%';
				nodesin.push( Builder.node('option', { value: ftag_value }, [ Builder._text(f.name) ]));
			}
		}
	}
	if ( ary[0].html ) {
		for ( var i in ary[0].html ) {
			var f = ary[0].html[i];
			if ( typeof f != 'function' ) {
				if ( !f.tag || f.tag == '' ) {
					f.tag = 'PERS_' + f.id;
				}
				var ftag_value = '%' + f.tag + '%';
				//f.tag = '%' + f.tag + '%';
				nodesin.push(form_editor_personalization_link_push(ftag_value, f.name));
			}
		}
	}
	if ( nodesin.length > 0 ) {
		rel.appendChild(form_editor_personalization_section_push(nodesin, strPersSenderTags));
	}
	//alert('handle personalization now!' + nodesin.length + rel.id);
}

function form_editor_defaults(prfx, format, sets) {
	//$(prfx + 'textField').value = '';
	//$(prfx + 'formatField').value = format;
	ac_form_value_set($(prfx + 'Editor'), '');
	// prepare personalization tags
	form_editor_personalization_links(sets, format);
	//form_editor_personalization(prfx, sets, format);
	// show appropriate editor
	//ac_editor_mime_switch(prfx, $(prfx + 'formatField').value);
}

function form_editor_update(prfx, ary, suffix) {
	if ( typeof suffix != 'string' ) suffix = 'PersTags';
	$(prfx + 'formatField').value = ary.format;
	$(prfx + 'textField').value = ary.text;
	ac_form_value_set($(prfx + 'Editor'), ary.html);
	// custom fields
	form_editor_update_fields_links(ary);
	// show appropriate editor
	ac_editor_mime_switch(prfx, $(prfx + 'formatField').value);
}


function form_editor_update_fields(prfx, ary, suffix) {
	if ( typeof suffix != 'string' ) suffix = 'PersTags';
	// custom fields
	var rel = $(prfx + suffix);
	if ( !$('messageField') && typeof customFieldsObj != 'undefined' ) {
		ACCustomFieldsResult = ary.fields;
		customFieldsObj.handlePersonalization(ACCustomFieldsResult, rel);
		customFieldsObj.additionalHandler(ary);
	} else {
		var nodesin  = [];
		for ( var i in ary.fields ) {
			var f = ary.fields[i];
			if ( typeof f != 'function' ) {
				if ( !f.perstag || f.perstag == '' ) {
					f.perstag = 'PERS_' + f.id;
				}
				f.perstag = '%' + f.perstag + '%';
				nodesin.push( Builder.node('option', { value: f.perstag }, [ Builder._text(f.title) ]));
			}
		}
		if ( nodesin.length > 0 ) {
			rel.appendChild(Builder.node('optgroup', { label: strPersListFields }, nodesin));
		}
		rel.selectedIndex = 0;
	}
}

function form_editor_update_fields_links(ary) {
	// custom fields
	var rel = $('personalizelist');
	if ( !$('messageField') && typeof customFieldsObj != 'undefined' ) {
		ACCustomFieldsResult = ary.fields;
		customFieldsObj.handlePersonalizationLinks(ACCustomFieldsResult, rel);
		customFieldsObj.additionalHandler(ary);
	} else {
		var nodesin  = [];
		for ( var i in ary.fields ) {
			var f = ary.fields[i];
			if ( typeof f != 'function' ) {
				if ( !f.perstag || f.perstag == '' ) {
					f.perstag = 'PERS_' + f.id;
				}
				f.perstag = '%' + f.perstag + '%';
				nodesin.push( Builder.node('option', { value: f.perstag }, [ Builder._text(f.title) ]));
				nodesin.push(form_editor_personalization_link_push(f.perstag, f.title));
			}
		}
		if ( nodesin.length > 0 ) {
			rel.appendChild(form_editor_personalization_section_push(nodesin, strPersListFields));
		}
	}
}

function menu_option_over(obj) {
	var topitem = obj.parentNode.getElementsByTagName('a')[0];
	obj.parentClassName = topitem.className;
	topitem.className = 'topmenucurrent';
}

function menu_option_out(obj) {
	var topitem = obj.parentNode.getElementsByTagName('a')[0];
	topitem.className = ( typeof obj.parentClassName != 'undefined' ? obj.parentClassName : '' );
}

function emailqueue_spawn() {
	ac_ajax_call_cb(ac_js_site.p_link + "/admin/api.php", "emailqueue.emailqueue_spawn", ac_ajax_cb(emailqueue_spawn_cb));
}

function emailqueue_spawn_cb(ary) {
	// Do nothing.
}

