

function filter_get_string() {
	var r = '';
	for ( var i in filterArray ) {
		var t = typeof(filterArray[i]);
		if ( t != 'object' && t != 'function' ) {
			if ( typeof(filterArray[i]) == 'boolean' ) {
				r += '&&' + i + '||' + ( filterArray[i] ? 1 : 0 );
			} else {
				r += '&&' + i + '||' + filterArray[i];
			}
		}
	}
	return r.substr(2);
}

function filter_set_value(key, val) {
	filterArray[key] = val;
}

function filter_remove_value(key) {
	filterArray = ac_array_remove(key, filterArray);
}




/*
function showUploadFiles() {
	var show = $('uploadBox').className == 'ac_hidden';
	ac_dom_toggle_class('uploadBox', 'ac_block', 'ac_hidden');
	if ( show ) {
		$('browseBox').className = 'ac_hidden';
		$('bookmarkBox').className = 'ac_hidden';
		//
	} else {
		$('browseBox').className = 'ac_block';
		$('bookmarkBox').className = 'ac_hidden';
	}
//	ac_dom_toggle_class('browseBox', 'ac_block', 'ac_hidden');
//	$('bookmarkBox').className = 'ac_hidden';
	return false;
}

function doUploadFiles() {
	var allBlank = true;
	var path = $('currentpath').value;
	var holderObj = $('uploadBoxHolder');
	var inputs = holderObj.getElementsByTagName('input');
	var remove = new Array();
    for ( var i = 0; i < inputs.length; i++ ) {
        if ( inputs[i].type == 'file' ) {
		    if ( inputs[i].value != '' ) {
				allBlank = false;
			} else {
				// remove node
				remove[remove.length] = inputs[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
			}
    	}
    }
	if ( allBlank ) {
		alert(jsMustUploadAtLeastOneFile);
		return false;
	}
	for ( var i = 0; i < remove.length; i++ ) {
		remove_element(remove[i]);
	}
	//displayIt('processing');
	//showUploadFiles();
	return true;
}

function addUploadFile(holderObj) {
    var newinput = holderObj.getElementsByTagName('input');
    for ( var i = 0; i < newinput.length; i++ ) {
        if ( newinput[i].type == 'file' && newinput[i].value == '' ) return;
    }
    // if we reached this point, then there are no empty file slots, so add one
    clone_1st_div(holderObj);
}
*/



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 setSafeTitle(title) {
	// if safe title is already set, don't change it
	if ( $('stringidField').value != '' ) return;
	// no safe title set, try to convert title
	$('stringidField').value = ac_str_urlsafe(title);
}



function jump(url) {
	ac_loader_show();
	window.location = url;
}








/*
	DOM
*/

// in selects with optgroups it adds/edits/removes elements (updates after those actions)
function manage_groupped_list(list, group, action, id, title, descript) {
	var rel = list.getElementsByTagName('optgroup');
	for ( var i = 0; i < rel.length; i++ ) {
		if ( rel[i].label == group ) {
			return manage_list(rel[i], action, id, title, descript);
		}
	}
	// if action is add, and group doesn't exist, add group
	if ( action == 'add' ) {
		if ( rel.length == 0 ) {
			list.innerHTML += '<optgroup label="' + group + '"><option value="' + id + '" title="' + descript + '">' + title + '</option></optgroup>';
		} else {
			var el = clone_1st_element(list, 'optgroup', false);
			el.label = group;
			el.innerHTML = '<option value="' + id + '" title="' + descript + '">' + title + '</option>';
		}
		return;
	}
	return manage_list(list, action, id, title, descript);
}

// in selects without optgroups it adds/edits/removes elements (updates after those actions)
function manage_list(list, action, id, title, descript) {
	if ( action == 'add' ) {
		// ADD TO LIST
		// if we passed a group node ("groupped" function ensures that), then it will be added to that group
		var el = clone_1st_element(list, 'option', false);
		el.value = id;
		el.title = descript;
		el.innerHTML = title;
		//el.selected = false;
	} else {
		// edit and delete gotta find it first
		var options = list.getElementsByTagName('option');
		for ( var i = 0; i < options.length; i++ ) {
			if ( options[i].value == id ) {
				if ( action == 'edit' ) {
					// MODIFY IN LIST
					options[i].title = descript;
					options[i].innerHTML = title;
				} else if ( action == 'delete' ) {
					// REMOVE FROM LIST
					// get his parent
					var daddy = options[i].parentNode;
					// kill this node
					daddy.removeChild(options[i]);
					// if it was member of a group
					if ( daddy.nodeName.toLowerCase() == 'optgroup' ) {
						// if the only one
						if ( daddy.getElementsByTagName('option').length == 0 ) {
							// kill entire group
							daddy.parentNode.removeChild(daddy);
						}
					}
				}
				break;
			}
		}
	}
}




/*
    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 update_custom_fields(form_id, list) {
	var callback = ( list ? update_custom_fields_list_callback : update_custom_fields_callback );
    somethingChanged = true;
    var lists = ac_form_select_extract($('parentsList'));
    ac_ajax_call_cb('api.php', 'list.list_field_update', callback, form_id, lists.join('-'), 1);
}

function update_custom_fields_checkbox(id) {
	if ( !id ) id = 0;
    somethingChanged = true;
    var lists = ac_form_check_selection_get($('parentsListBox'), 'p[]');
    ac_ajax_call_cb('api.php', 'list.list_field_update', update_custom_fields_callback, id, lists.join('-'), 1);
}

function update_custom_fields_callback(xml, txt) {
	var rel = $('custom_fields_table');
	var ary = ac_dom_read_node(xml);
	ac_dom_remove_children(rel);
	var total = 0;
	var visible = 0;
	if ( ary.fields ) {
		for ( var i = 0; i < ary.fields.length; i++ ) {
			var row = ary.fields[i];
			var node = ac_custom_fields_cons(row);
			if ( parseInt(row.type, 10) != 6 ) {
				rel.appendChild(Builder.node(
					"tr",
					[
						Builder.node("td", { valign: 'top'/*, width: "75"*/ }, [ Builder._text(ac_custom_fields_title(row)) ]),
						Builder.node("td", [ node ])
					]
				));
			} else {
				rel.appendChild(Builder.node(
					"tr",
					[
						Builder.node("td", [ Builder._text(" ") ]),
						Builder.node("td", [ node ])
					]
				));
			}
			total++;
			if ( parseInt(row.type, 10) != 6 ) visible++;
		}
	}
}

var update_custom_fields_list_preselect = {};

function update_custom_fields_list_callback(xml, txt) {
	var rel = $('custom_fields_table');
	var ary = ac_dom_read_node(xml);
	ac_dom_remove_children(rel);
	var total = 0;
	if ( ary.fields ) {
		for ( var i = 0; i < ary.fields.length; i++ ) {
			var row = ary.fields[i];
			var props = { name: 'fields[]', id: 'custom' + row.id + 'Field', type: 'checkbox', value: row.id };
			if ( !update_custom_fields_list_preselect || ac_array_has(update_custom_fields_list_preselect, row.id) ) {
				props.checked = 'checked';
			}
			rel.appendChild(
				Builder.node(
					"tr",
					[
						Builder.node("td", [ Builder._text(" ") ]),
						Builder.node(
							"td",
							[
								Builder.node(
									'label',
									[
										Builder.node(
											'input',
											props
										),
										Builder._text(row.title)
									]
								)
							]
						)
					]
				)
			);
			total++;
		}
	}
}


function toggleEditor(id, action, settings) {
	if ( action == ac_editor_is(id + 'Editor') ) return false;
	ac_editor_toggle(id + 'Editor', settings);
	$(id + 'EditorLinkOn').className  = ( action ? 'currenttab' : 'othertab' );
	$(id + 'EditorLinkOff').className = ( !action ? 'currenttab' : 'othertab' );
	$(id + 'EditorLinkDefault').className = ( ( action != ( ac_js_admin.htmleditor == 1 ) ) ? 'notatab' : 'disabledtab' );
	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', null, 'htmleditor', ( isEditor ? 1 : 0 ));
	$(id + 'EditorLinkDefault').className = 'disabledtab';
	ac_js_admin.htmleditor = ( isEditor ? 1 : 0 );
	return false;
}

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



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 %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;
	}
	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 == '%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)
					});
				}
			}
		}
	}
}

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 optgroups = rel.getElementsByTagName('optgroup');
	for ( var i = 0; i < optgroups.length; i++ ) {
		if ( optgroups[i].label == strPersSenderTags ) {
			rel.removeChild(optgroups[i]);
			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 ( nodesin.length > 0 ) {
		rel.appendChild(Builder.node('optgroup', { label: strPersSenderTags }, nodesin));
	}
	rel.selectedIndex = 0;
	//alert('handle personalization now!' + nodesin.length + rel.id);
}


function form_editor_insert(field, value) {
	// only today tag should be reset
	if ( value.match( /^%TODAY[+-]\d+%$/ ) ) {
		value = '%TODAY*%';
	}
	if ( value == '%TODAY*%' ) {
		var entered = prompt(strEnterRange, '+1');
		if ( !entered || !entered.match( /^[-+]?\d+$/ ) ) {
			alert(strEnterRangeInvalid);
			return;
		}
		if ( !entered.match(/^[-+].*$/) ) {
			entered = '+' + entered;
		}
		value = '%TODAY' + entered + '%';
	}
	ac_form_insert_cursor(field, value);
}

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(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(prfx, ary, suffix);
	// 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 message_defaults() {
	var values = {
		messagesubject: '',
		messagefromemail: '',
		messagefromname: '',
		messagereply2: '',
		messagepriority: 3,
		messagecharset: '',
		messageencoding: _charset
	};
	for ( var i in values ) {
		$(i + 'Field').value = values[i];
	}
	// set editor scene
	form_editor_defaults('message', 'mime', [ 'subscriber', 'sender', 'system' ]);
	form_editor_personalization('conditionalfield', [ 'subscriber' ], 'text', '');
	// set scene
	ac_editor_mime_switch('message', $('messageformatField').value);
	// default to editor
	message_form_construct_switch('text', 'editor');
	message_form_construct_switch('html', 'editor');
	// files
	if ( $('message_attach_list') ) {
		ac_dom_remove_children($('message_attach_list'));
	}
}

function message_update(ary) {
	// message
	//$('messageconfirmField' + ( ary.message_confirm == 1 ? 'Yes' : 'No' )).checked = true;
	$('messagesubjectField').value = ary.subject;
	$('messagefromnameField').value = ary.fromname;
	$('messagefromemailField').value = ary.fromemail;
	$('messagereply2Field').value = ary.reply2;
	$('messagepriorityField').value = ary.priority;
	$('messagecharsetField').value = ary.charset;
	$('messageencodingField').value = ary.encoding;
	// panels switch
	form_editor_update('message', ary);
	form_editor_update_fields('conditionalfield', ary, '');
	ac_editor_mime_switch('message', $('messageformatField').value);
	message_form_construct_switch('text', 'editor');
	message_form_construct_switch('html', 'editor');
	// files
	if ( $('message_attach_list') ) {
		if ( ary.files ) {
			for ( var i = 0; i < ary.files.length; i++ ) {
				var this1 = ary.files[i];
				this1.action = 'message_attach';
				this1.filename = this1.name;
				this1.filesize = this1.size;
				this1.humansize = ac_str_file_humansize(this1.filesize);
				ac_form_upload_set('message_attach', 'attach', this1, ac_js_admin.limit_attachment);
			}
		}
	}
}

function optinoptout_defaults() {
	var values = {
		optname: '',
		optinsubject: strOptInSubjectDefault,
		optinfromemail: '',
		optinfromname: '',
		optoutsubject: strOptOutSubjectDefault,
		optoutfromemail: '',
		optoutfromname: ''
	};
	for ( var i in values ) {
		$(i + 'Field').value = values[i];
	}
	$('optinconfirmFieldYes').checked = true;
	$('optoutconfirmFieldNo').checked = true;
	// set editor scene
	form_editor_defaults('optin', 'html', [ 'confirm', 'subscriber', 'sender', 'system' ]);
	form_editor_defaults('optout', 'html', [ 'confirm', 'subscriber', 'sender', 'system' ]);
	form_editor_personalization('conditionalfield', [ 'subscriber' ], 'text', '');
	// set optinout scene
	ac_editor_mime_toggle('optin', $('optinconfirmFieldYes').checked);
	ac_editor_mime_toggle('optout', $('optoutconfirmFieldYes').checked);
	//ac_editor_mime_switch('optin', $('optinformatField').value); // toggle calls these
	$('optinformatField').value = "html";
	//ac_editor_mime_switch('optout', $('optoutformatField').value);
	// files
	if ( $('optin_attach_list') ) {
		ac_dom_remove_children($('optin_attach_list'));
		ac_dom_remove_children($('optout_attach_list'));
	}
	ac_form_value_set($("optinEditor"), strDefaultOptInText + "<br /><a href=\"%CONFIRMLINK%\">%CONFIRMLINK%</a>");
	$("optintextField").value = strDefaultOptInText + "%CONFIRMLINK%";
	ac_form_value_set($("optoutEditor"), strDefaultOptOutText + "<br /><a href=\"%CONFIRMLINK%\">%CONFIRMLINK%</a>");
	$("optouttextField").value = strDefaultOptOutText + "%CONFIRMLINK%";
}

function optinoptout_update(ary) {
	// optin
	$('optnameField').value = ary.optname;
	$('optinconfirmField' + ( ary.optin_confirm == 1 ? 'Yes' : 'No' )).checked = true;
	$('optinsubjectField').value = ary.optin_subject;
	$('optinfromnameField').value = ary.optin_from_name;
	$('optinfromemailField').value = ary.optin_from_email;
	// optout
	$('optoutconfirmField' + ( ary.optout_confirm == 1 ? 'Yes' : 'No' )).checked = true;
	$('optoutsubjectField').value = (ary.optout_subject != "") ? ary.optout_subject : strOptOutSubjectDefault;
	$('optoutfromnameField').value = (ary.optout_from_name == "" && ary.optin_from_name != "") ? ary.optin_from_name : ary.optout_from_name;
	$('optoutfromemailField').value = (ary.optout_from_email == "" && ary.optin_from_email != "") ? ary.optin_from_email : ary.optout_from_email;
	// optinout panels switch
	ary.format = ary.optin_format;
	ary.text = ary.optin_text;
	ary.html = ary.optin_html;
	form_editor_update('optin', ary);
	ary.format = ary.optout_format;
	ary.text = ary.optout_text;
	ary.html = ary.optout_html;
	form_editor_update('optout', ary);
	form_editor_update_fields('conditionalfield', ary, '');
	ac_editor_mime_toggle('optin', $('optinconfirmFieldYes').checked);
	ac_editor_mime_toggle('optout', $('optoutconfirmFieldYes').checked);
	//ac_editor_mime_switch('optin', $('optinformatField').value); // toggle calls these
	//ac_editor_mime_switch('optout', $('optoutformatField').value);
	// files
	if ( $('optin_attach_list') ) {
		if ( ary.optin_files ) {
			for ( var i = 0; i < ary.optin_files.length; i++ ) {
				var this1 = ary.optin_files[i];
				this1.action = 'optinoptout_attach';
				this1.filename = this1.name;
				this1.filesize = this1.size;
				this1.humansize = ac_str_file_humansize(this1.filesize);
				ac_form_upload_set('optin_attach', 'optoutattach', this1, ac_js_admin.limit_attachment);
			}
		}
		// files
		if ( ary.optout_files ) {
			for ( var i = 0; i < ary.optout_files.length; i++ ) {
				var this1 = ary.optout_files[i];
				this1.action = 'optinoptout_attach';
				this1.filename = this1.name;
				this1.filesize = this1.size;
				this1.humansize = ac_str_file_humansize(this1.filesize);
				ac_form_upload_set('optout_attach', 'optoutattach', this1, ac_js_admin.limit_attachment);
			}
		}
	}
}


function bounce_defaults() {
	var values = {
		bounceemail: '',
		bouncebatch: 120,
		bouncehost: '',
		bounceport: 110,
		bounceuser: '',
		bouncepass: '',
		bouncehard: 3,
		bouncesoft: 6
	};
	for ( var i in values ) {
		$(i + 'Field').value = values[i];
	}
	$('bouncetypeFieldPOP3').checked = true;
	// bounce
	$('bouncepop3').className = (  $('bouncetypeFieldPOP3').checked ? 'ac_table_rowgroup' : 'ac_hidden' );
	$('bounceform').className = ( !$('bouncetypeFieldNone').checked ? 'ac_block' : 'ac_hidden' );
	//$('popfaqpanel').className = 'h2_content_invis';
}

function bounce_update(ary) {
	$('bounceemailField').value = ary.email;
	$('bouncebatchField').value = ary.emails_per_batch;
	$('bouncehostField').value = ary.host;
	$('bounceportField').value = ary.port;
	$('bounceuserField').value = ary.user;
	$('bouncepassField').value = ary.pass;
	$('bouncehardField').value = ary.limit_hard;
	$('bouncesoftField').value = ary.limit_soft;
	$('bouncetypeField' + ( ary.type == 'pop3' ? 'POP3' : ( ary.type == 'pipe' ? 'Pipe' : 'None' ) )).checked = true;
	$('bounceform').className = ( !$('bouncetypeFieldNone').checked ? 'ac_block' : 'ac_hidden' );
	$('bouncepop3').className = (  $('bouncetypeFieldPOP3').checked ? 'ac_table_rowgroup' : 'ac_hidden' );
}


function export_link_build(context, ary) {
	var link = 'export.php?action=' + context;
	for ( var i in ary ) {
		link += '&' + i + '=' + ary[i];
	}
	if ( typeof(ourflag) == 'undefined' || prompt('Go to this export URL?', link) )
	window.location.href = link;
}

var listfilters = {};
function list_filter(rnd) {
	var post = ac_form_post($("listfilter" + rnd));
	listfilters[rnd] = post.listid;
	ac_ajax_post_cb(
		"api.php",
		"subscriber.subscriber_filter_post",
		function(xml) {
			var ary = ac_dom_read_node(xml);
			list_filters_update(ary.filterid, post.listid, true);
			/*
			alert(
				'filter: ' + ary.filterid +
				'\nlist: ' + ( post.listid == 0 ? '- all -' : post.listid )
			);
			*/
		},
		post
	);
}

function list_filters_update(filterid, listid, doContextFilters) {
	for ( var rnd in listfilters ) {
		if ( $('listFilterManager' + rnd).value != listid ) {
			$('listFilterManager' + rnd).value = listid;
			listfilters[rnd] = listid;
		}
	}
	if ( doContextFilters ) {
		// try to change the list filter on this context page
		if ( $('JSListManager') ) $('JSListManager').value = listid;
		// try to run assign filterid based on context
/*		try {
			var v = eval(ac_action + "_list_filter = " + filterid + ";");
		} catch (e) {
			// do nothing, none found
		}
*/		// try to run assign listid based on context
		try {
			var v = eval(ac_action + "_listfilter = " + listid + ";");
		} catch (e) {
			// do nothing, none found
		}
		// try to run a search function based on context
		var func = null;
		try {
			var func = eval(ac_action + "_list_search");
		} catch (e) {
			// do nothing, none found
		}
		if ( typeof func == "function" ) {
			func();
		}
	}
}


function optinout_get(id) {
	optinoptout_defaults();
	$('hiddenOptinId').value = id;
	if ( id > 0 ) {
		// ajax call
		ac_ui_api_call(jsLoading);
		ac_ajax_call_cb("api.php", "optinoptout.optinoptout_select_row", optinout_get_cb, id);
	//} else {alert('here');
		if ( !customFieldsObj ) { // list page
			var customFieldsObj = new ACCustomFields({
				sourceType: 'SELECT',
				sourceId: 'parentsList',
				api: 'list.list_field_update',
				responseIndex: 'fields',
				includeGlobals: 0,
				additionalHandler: function(ary) {
					// deal with personalization tags
					//form_editor_sender_personalization(ary.personalizations, $('optinPersTags'));
					//form_editor_sender_personalization(ary.personalizations, $('optoutPersTags'));
					ac_editor_toggle('optinEditor');
					ac_editor_toggle('optinEditor');
					ac_editor_toggle('optoutEditor');
					ac_editor_toggle('optoutEditor');
				}
			});
		}
		customFieldsObj.handlePersonalization(ACCustomFieldsResult, $('optinPersTags'));
		customFieldsObj.handlePersonalization(ACCustomFieldsResult, $('optoutPersTags'));
		customFieldsObj.handlePersonalization(ACCustomFieldsResult, $('conditionalfield'));
		customFieldsObj.additionalHandler(ACCustomFieldsResult);
		//customFieldsObj.fetch(0);
	}
	$('optinoutnew').className = 'ac_block';
}

function optinout_get_cb(xml) {
	var ary = ac_dom_read_node(xml);
	ac_ui_api_callback();
	optinoptout_update(ary);
}

function optinout_set() {
	var post = ac_form_post($("optinoutnew"));
	post.id = $('hiddenOptinId').value;
	optinout_save(post, optinout_set_cb);
}

function optinout_save(post, callback) {
	if ( post.optname == '' ) {
		alert(strOptNameEmpty);
		$('optnameField').focus();
		return;
	}
	if ( ac_js_admin.optinconfirm && post.optin_confirm != 1 ) {
		alert(strOptInNeeded);
		return;
	}
	if ( post.optin_confirm == 1 ) {
		if ( !ac_str_email(post.optin_from_email) ) {
			alert(strOptInEmailNotEmail);
			$('optinfromemailField').focus();
			return;
		}
		if ( post.optin_subject == '' ) {
			alert(strOptInSubjectEmpty);
			$('optinsubjectField').focus();
			return;
		}
		if ( post.optin_format != 'html' && !post.optin_text.match(/%CONFIRMLINK%/) ) {
			alert(strOptInTextConfirmMissing);
			$('optintextField').focus();
			return;
		}
		if ( post.optin_format != 'text' && !post.optin_html.match(/%CONFIRMLINK%/) ) {
			alert(strOptInHTMLConfirmMissing);
			return;
		}
	}
	if ( post.optout_confirm == 1 ) {
		if ( !ac_str_email(post.optout_from_email) ) {
			alert(strOptOutEmailNotEmail);
			$('optoutfromemailField').focus();
			return;
		}
		if ( post.optout_subject == '' ) {
			alert(strOptOutSubjectEmpty);
			$('optoutsubjectField').focus();
			return;
		}
		if ( post.optout_format != 'html' && !post.optout_text.match(/%CONFIRMLINK%/) ) {
			alert(strOptOutTextConfirmMissing);
			$('optouttextField').focus();
			return;
		}
		if ( post.optout_format != 'text' && !post.optout_html.match(/%CONFIRMLINK%/) ) {
			alert(strOptOutHTMLConfirmMissing);
			return;
		}
	}

	ac_ui_api_call(jsSaving);
	if (post.id > 0)
		ac_ajax_post_cb("api.php", "optinoptout.optinoptout_update_post", callback, post);
	else
		ac_ajax_post_cb("api.php", "optinoptout.optinoptout_insert_post", callback, post);
}

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

	if (ary.succeeded != "0") {
		ac_result_show(ary.message);
		// add to dropdown
		$('optinoutidField').appendChild(Builder.node('option', { value: ary.id, selected: true }, [ Builder._text(ary.name) ]));
		// hide add form
		$('optinoutnew').className = 'ac_hidden';
	} else {
		ac_error_show(ary.message);
	}
}




function parents_list_select(all, firstIsAll) {
	if ( all ) {
		ac_form_select_multiple_all($('parentsList'), firstIsAll);
	} else {
		ac_form_select_multiple_none($('parentsList'));
	}

	// campaign_new - only stuff
	if ( $('step2next') ) {
		// stop the scene until the call returns
		$('step2next').disabled = true;
		$('campaignfilterbox').className = 'ac_hidden';
	}
	if (typeof customFieldsObj == "object")
		customFieldsObj.fetch(0);
	return false;
}


/*

ACTIVE RSS

*/


function form_editor_activerss_open(type, insertObj) {
	if ( !insertObj ) insertObj = '';
	// set type
	$('activerss4').value = type;
	$('activerss2').value = insertObj;
	// set data
	$('activerssurl').value = 'http://';
	$('activerssloop').value = '10';
	$('activerssall').checked = true;
	$('activersspreviewbox').className = 'ac_hidden';
	// open modal
	ac_dom_toggle_display('message_activerss', 'block');
}

function form_editor_activerss_insert() {
	// close the modal
	ac_dom_toggle_display('message_activerss', 'block');
	// build the code
	var code = form_editor_activerss_build();
	if ( code == '' ) return;
	// push it into needed editor
	if ( $('activerss4').value == 'html' ) {
		tinyMCE.activeEditor.execCommand('mceInsertContent', false, nl2br(code));
	} else {
		ac_form_insert_cursor($($('activerss2').value), code);
	}
}

function form_editor_activerss_preview() {
	// build the code
	var code = form_editor_activerss_build();
	if ( code == '' ) return;
	if ( $('activerss4').value == 'html' ) code = nl2br(code);
	// push it into preview box
	$('activersspreview').value = code;
	$('activersspreviewbox').className = 'ac_block';
}

function form_editor_activerss_build() {
	// what type of code to build
	var type = $('activerss4').value;
	// what url to fetch
	var url = $('activerssurl').value;
	if ( !ac_str_is_url(url) ) {
		alert(strURLNotURL);
		$('activerssurl').focus();
		return '';
	}
	// how many to show
	if ( !ac_ui_numbersonly($('activerssloop')) ) {
		$('activerssloop').value = 0;
	}
	var loop = $('activerssloop').value;
	// what to show
	var show = ( $('activerssnew').checked ? 'NEW' : 'ALL' ); // ALL/NEW
	// what are line breaks
	var nl = ( type == 'html' ? '<br />\n' : '\n' );
	var code =
		'%RSS-FEED|URL:' + url + '|SHOW:' + show + '%\n\n' + // start feed section
		'%RSS:CHANNEL:TITLE%\n\n' + // print out title
		'%RSS-LOOP|LIMIT:' + loop + '%\n\n' + // start item section
		'%RSS:ITEM:DATE%\n' + // within a section
		'%RSS:ITEM:TITLE%\n' +
		'%RSS:ITEM:SUMMARY%\n' +
		'%RSS:ITEM:LINK%\n\n' +
		'%RSS-LOOP%\n\n' +
		'%RSS-FEED%\n' // end section
	;
	return code;
}

function ac_editor_activerss_click() {
	//tinyMCE.activeEditor.execCommand('mceInsertContent', false, form_editor_activerss_build());
	form_editor_activerss_open('html');
}



function form_editor_activerss_loop_changed() {
	window.setTimeout(
		function() {
			ac_ui_numbersonly($('activerssloop'), true);
		},
		100
	);
}


/*

CONDITIONAL CONTENT

*/


function form_editor_conditional_open(type, insertObj) {
	if ( !insertObj ) insertObj = '';
	// set type
	$('conditional4').value = type;
	$('conditional2').value = insertObj;
	// set data
	$('conditionalfield').value = '';
	$('conditionalcond' ).selectedIndex = 0;
	$('conditionalvalue').value = '';
	// open modal
	ac_dom_toggle_display('message_conditional', 'block');
}

function form_editor_conditional_insert() {
	if ( $('conditionalfield').value == '' ) {
		alert(strPersMissing);
		$('conditionalfield').focus();
		return;
	}
	// close the modal
	ac_dom_toggle_display('message_conditional', 'block');
	// build the code
	var code = form_editor_conditional_build();
	if ( code == '' ) return;
	// push it into needed editor
	if ( $('conditional4').value == 'html' ) {
		var ed = tinyMCE.activeEditor;
		ed.execCommand('mceInsertContent', false, nl2br(code));
	} else {
		ac_form_insert_cursor($($('conditional2').value), code);
	}
}

function form_editor_conditional_build() {
	// what type of code to build
	var type = $('conditional4').value;
	// what value to use
	var field = $('conditionalfield').value;
	var cond  = $('conditionalcond' ).value;
	var value = $('conditionalvalue').value;
	field = '$' + field.replace(/%/g, '').replace(/-/g, '_');
	value = "'" + value.replace(/'/g, '\\\'') + "'";
	if ( cond.indexOf('CONTAINS') != -1 ) {
		var expr = 'in_string(' + value + ', ' + field + ')';
		if ( cond == 'DCONTAINS' ) expr = '!' + expr;
	} else {
		var expr = field + ' ' + cond + ' ' + value;
	}
	var code =
		'%IF ' + expr + '%\n' + editorConditionalText + '\n%ELSE%\n' + editorConditionalElseText + '\n%/IF%\n'
	;
	return code;
}

function ac_editor_conditional_click() {
	var ed = tinyMCE.activeEditor;
	//tinyMCE.activeEditor.execCommand('mceInsertContent', false, form_editor_conditional_build());
	form_editor_conditional_open('html');
}




/*

TEMPLATES

*/


function form_editor_template_open(insertObj) {
	if ( !insertObj ) insertObj = '';
	// set type
	$('editortemplate2').value = insertObj;
	// set data
	$('templateinsert').selectedIndex = -1;
	// open modal
	ac_dom_toggle_display('message_template', 'block');
}

function form_editor_template_insert(type) {
	// close the modal
	ac_dom_toggle_display('message_template', 'block');
	// build the code
	var code = ac_b64_decode($('templateinsert').value);
	if ( code == '' ) return;
	// push it into needed editor
	if ( type == 'html' ) {
		tinyMCE.activeEditor.execCommand('mceInsertContent', false, code);
	} else {
		ac_form_insert_cursor($($('editortemplate2').value), code);
	}
}


function startup_toggle_tab(container, section_show) {
	var container_divs = $(container).getElementsByTagName("div");
	var container_spans = $(container).getElementsByTagName("span");

	// Tab div on top always shows
	container_divs[0].className = "startup_box_title";

	// First make all other divs hidden
	// Start at 1, since we manually target the first div already
	for (var i = 1; i < container_divs.length; i++) {
		container_divs[i].className = "ac_hidden";
	}

	// First make all spans default style
	for (var i = 0; i < container_spans.length; i++) {
		container_spans[i].className = "";
	}

	// Then show the div
	$("startup_box_div_" + section_show).className = "startup_box_container_inner";

	// Grab all inner divs within the section we are showing
	var selected_container_divs = $("startup_box_div_" + section_show).getElementsByTagName("div");

	// Make sure all inner divs are displayed, since they may have been hidden when we looped through all divs above
	for (var i = 0; i < selected_container_divs.length; i++) {
		selected_container_divs[i].className = "";
	}

	// Style the span selected
	$("startup_box_span_" + section_show).className = "startup_selected";
}

function quick_search() {
	var post = ac_form_post($("quick_search"));
	list_filters_update(0, post.listid, false);
	ac_ajax_post_cb("api.php", post.qaction + "." + post.qaction + "_filter_post", quick_search_cb, post);
}

function quick_search_cb(xml) {
	var ary = ac_dom_read_node(xml);

	var action = $('quicksearch_action').value;

	var sortorder = '01';

	if ( action == 'campaign' ) {
		sortorder = '01D';
	} else if ( action == 'subscriber' ) {
		sortorder = '01';
	}

	window.location.href = 'main.php?action=' + action + '#list-' + sortorder + '-0-' + ary.filterid;
}
