if (document.all && !document.getElementById) {
	document.getElementById = function(id) {
		 return document.all[id];
	}
}

function getFormObject(formName) {
	return eval('edit_form_' + formName);
}


function edit_init(form) {

	form.get_field_control = edit_form_get_field_control;
	form.DOM = document.id("form_" + form.name);
	form.generateId = edit_form_generateId;
	form.handleEnter = edit_form_handleEnter;
	form.validate = edit_form_validate;
	form.submit = edit_form_submit;
	form.ajax_submit = edit_form_ajax_submit;
	
	for (fname in form.fields) 	{
		var field = form.fields[fname];

		field.enabled       = true;
		field.visible       = true;
		field.edit_form     = form;

		field.get_id			= edit_field_get_id;
		field.get_value         = edit_field_get_value;
		field.set_value         = edit_field_set_value;
		field.force_edit        = edit_field_force_edit;
		field.caption_styles    = edit_field_caption_styles;
		field.get_error_msg     = edit_field_get_error_msg;
		field.set_visible       = edit_field_set_visible;
		field.get_visible       = edit_field_get_visible;
		field.set_enabled       = edit_field_set_enabled;
		field.set_mandatory     = edit_field_set_mandatory;
		field.validate          = edit_field_validate;
		field.update            = edit_field_update;

		field.get_field_control = edit_field_get_field_control;
		field.get_field_section = edit_field_get_field_section;
		field.get_field_marker  = edit_field_get_field_marker;
		field.get_internal_name = edit_field_get_internal_name;
	}
}


function edit_form_handleEnter(event, ajax_mode) {
    if (event.key == 'enter' && event.control == true) {
        event.stop();
        if (this.use_ajax) {
        	this.ajax_submit(ajax_mode);
        }
        else {
            if (this.validate()) this.DOM.submit();
        }
    }
}

function edit_form_submit() {
    if (this.use_ajax) {
		return false;
	}	
	return true;
}
	

function edit_form_validate() {
	disable_submit_button(this.name);
	for (fname in this.fields) {
		var field = this.fields[fname];
		if (!field.validate()) {
			enable_submit_button(this.name);
			return false;
		}	
	}

	enable_submit_button(this.name);
	return true;
}

function edit_form_generateId(prefix, fieldName) {
		return prefix + "__" + this.name + (fieldName? fieldName : '');
}


function edit_form_get_field_control(field_name) {
	return eval('document.' + this.name  + '.' + this.name_prefix + field_name);
}

function edit_field_get_id(prefix) {
	return prefix + '$' + this.edit_form.name + '$' + this.name;
}

function edit_field_get_internal_name() {
	return this.edit_form.name_prefix + this.name;
}

function edit_field_get_field_control() {

	if (this.edit_type == 'file') {
		var fname = this.get_internal_name() + '[]';
		for (var i = 0; i < this.edit_form.DOM.elements.length; i++){
		   if (this.edit_form.DOM.elements[i].name == fname)
				return this.edit_form.DOM.elements[i];
		}
		return null;
	}

	return eval('document.' + this.edit_form.name  + '.' + this.get_internal_name());
}

function edit_field_get_field_marker() {
	return document.id(this.get_id('div'))
}

function edit_field_get_field_section() {
	return document.id(this.get_id('section'))
}

function edit_field_set_visible(is_visible) {
	var div = this.get_field_section();
	if (div)
		div.style.display = (is_visible)? '' : 'none';
	this.visible = is_visible;

	var div = document.id(this.get_id('separator_a'));
	if (div)
		div.style.display = (is_visible)? '' : 'none';

	var div = document.id(this.get_id('separator_b'));
	if (div)
		div.style.display = (is_visible)? '' : 'none';

}

function edit_field_set_enabled(is_enabled) {
	this.enabled = is_enabled;
	var div = this.get_field_section();
	if (div) {
		if (this.is_block) {
			for (fname in this.edit_form.fields) {
				var edit_field = this.edit_form.fields[fname];
				if (edit_field.in_block == this.name) {
					edit_field.set_enabled(is_enabled);
				}
			}
			return;
		}

		if (this.edit_type == 'plugin') {
			var f = document.id(this.get_id('content'));
			if (f) {
				f.className = (is_enabled)? 'ED_inline_combo ED_enabled' + this.class_name : 'ED_inline_combo ED_disabled ' + this.class_name;
			}
			f = document.id(this.get_id('display'));
			if (f) {
				f.disabled = !this.enabled;
				f.className = (is_enabled)? this.class_name : 'ED_disabled ' + this.class_name;
			}
		}
		else if (this.edit_type == 'list' && this.display_type == 'checkboxes') {
			var f  = this.get_field_control();
			var f1 = this.edit_form.get_field_control(this.name + '_');
			if (f1) {
				if (f1.length) {
					for (i = 0; i < f1.length; i++) {
						f1[i].disabled = !this.enabled;
					}
				}
				else {
					f1.disabled = !this.enabled;
				}
			}

			if (this.other_field_name) {
				var f1 = this.edit_form.get_field_control(this.name + '_cb');
				if (f1) {
					f1.disabled = !this.enabled;
				}
				var edit_field = this.edit_form.fields[this.other_field_name];
				if (edit_field)
					edit_field.set_enabled(is_enabled);
			}
		}
		else {
			var f = this.get_field_control();
			if (f) {
				if (this.edit_type == 'radio' && f.length) {
					for (counter = 0; counter < f.length; counter++) {
						f[counter].disabled = !this.enabled;
						f[counter].className = (is_enabled)? this.class_name : 'ED_disabled ' + this.class_name;
					}
				}
				else {
					f.disabled = !this.enabled;
					f.className = (is_enabled)? this.class_name : 'ED_disabled ' + this.class_name;
				}
			}
		}

		var save_mandatory = this.mandatory;
		this.set_mandatory(is_enabled && this.mandatory);
		this.mandatory = save_mandatory;
	}
}

function edit_field_set_mandatory(is_mandatory) {
	if (this.is_block)
		return;

	this.mandatory = is_mandatory;
	var div = this.get_field_marker();
	div.className = (this.mandatory)? 'ED_mandatory' : 'ED_optional';
}


function edit_field_force_edit(error_msg) {

	if (!error_msg)
		error_msg = this.get_error_msg();

	if (error_msg)
		alert(error_msg);

	var f = this.get_field_control();
	if (f == null) return '';

	if (f.focus) {
		this.caption_styles({'font-weight': 'bold', 'color': 'red'});
		f.focus();
	}
	else if (f.length) {
		f = this.edit_form.DOM.getElementById('radio_' + this.name + '_0');
		if (f && f.focus)
			f.focus();
	}
}

function edit_field_caption_styles(styles) {
	var el = 'caption_' + this.name;
	$(el).setStyles(styles);
}


function edit_field_get_value() {
	var f = this.get_field_control();
	if (f == null) return '';

	if (this.edit_type == 'radio') {
		if (f.checked) {
			return f.value;
		}

		for (counter = 0; counter < f.length; counter++) {
			if (f[counter].checked) {
				return f[counter].value;
			}
		}

		return '';
	}
	else if (this.edit_type == 'html') {
		var editor = CKEDITOR.instances[this.get_internal_name()];
		return editor.getData()
	}

	if (this.edit_type == 'list' && this.display_type == 'checkboxes') {
		var f  = this.get_field_control();
		var f1 = this.edit_form.get_field_control(this.name + '_');
		var aoptions = [];

		if (f1.length) {
			for (i = 0; i < f1.length; i++) {
				if (f1[i].checked)
					aoptions.push(f1[i].value)
			}
			f.value = aoptions.join();
		}
		else
			f.value = f1.value;
	}

	if (f.type == 'checkbox') {
		return f.checked;
	}

	return f.value.trim();
}


function edit_field_set_value(val) {
	var f = this.get_field_control();
	if (f == null) return '';

	if (this.edit_type == 'radio') {
		f.checked = (val)? true : false;

		for (counter = 0; counter < f.length; counter++) {
			f[counter].checked = (val)? true : false;
		}
		return;
	}
	else if (this.edit_type == 'html') {
		var editor = CKEDITOR.instances[this.get_internal_name()];
		editor.setData(val)
	
		return;
	}


	if (f.type == 'checkbox') {
		f.checked = (val)? true : false;
		return;
	}

	f.value = val;
}


function edit_field_get_visible() {
	if (!this.visible)
		return false;

	if (this.in_block != "") {
		return this.edit_form.fields[this.in_block].get_visible();
	}

	return true;
}

function edit_field_get_error_msg() {

	var err_msg = this.err_msg_empty;
	if (err_msg == "") {
		err_msg = (this.edit_type == 'text' || this.edit_type == 'html')? 'Please enter' :  'Please select';
		var ch = this.title.charAt(this.title.length-1);
		var field_title = this.title;
		if (ch == '.' || ch == ':' || ch == '?')
			field_title = this.title.substring(0, this.title.length-1);
		err_msg += ' ' + field_title + '.';
	}
	return err_msg;
}

function edit_field_validate() {

	if (this.get_visible() && this.editable && this.enabled) {

		var value = this.get_value();

		if (this.mandatory) {
			if (value == "") {
				this.force_edit();
				return (false);
			}
		}


		if (this.date) {
			if (value != "" && !isDate(value, 'M/d/y')) {
				this.force_edit("Invalid date format: " + this.title);
				return false;
			}
		}

		if (this.email) {
			if (value != "" && !isValidEmail(value)) {
				this.force_edit("Please enter a valid email address!");
				return false;
			}
		}

		if (this.on_validate) {
			result = eval( this.on_validate + "(this)" );
			if (!result)
				return false;
		}
	}

	return true;
}

// method of Form
function edit_form_ajax_submit(ajax_mode) {
	var edit_form = this;

	if (!this.validate())
		return false;

	for (fname in this.fields) {
		var field = this.fields[fname];
		field.caption_styles({'font-weight': '', 'color': ''});
	}

	var form_id = 'form_' + this.name;

	var canPost = true;
	var options = {	
				useSpinner: false,
				async: false,
				onComplete: function(responseTXT){
					var response = JSON.decode(responseTXT);
					if (response.status == 'success') {
						canPost = true;
					}
					else if (response.status == 'request_input') {
						var target_name = 'ajax_' + form_id;
						$(target_name).set('html',  response.html);
						var field = edit_form.fields[response.error_field];
						if (field)
							field.caption_styles({'font-weight': 'bold', 'color': 'red'});
					}
					else {
						var target_name = 'ajax_' + form_id;
						$(target_name).set('html', '');
						if (response.error_field) {
							var field = edit_form.fields[response.error_field];
							field.force_edit(response.error_message);
						}
						else {
							alert(response.error_message);
						}
					}
				}				
			};

	if (this.use_ajax_validation) {
		canPost = false;
		var extra_data = {action: 'validate', ajax_component_id: this.ajax_component_id};
		var ajax_data = AlloyJS.Ajax.mergeData($(form_id), extra_data);
		AlloyJS.Ajax.doRequest(this.url, ajax_data, options);
	}

	if (canPost) {
		if (typeof ajax_mode =="string" && ajax_mode == "ajax") {
			var extra_data = {action: 'post', ajax_component_id: this.ajax_component_id};
			var ajax_data = AlloyJS.Ajax.mergeData($(form_id), extra_data);
			AlloyJS.Ajax.doRequest(this.url, ajax_data, options);
			AlloyJS.formEditPosted();
		}
		else {
			if (this.ajax_component_id)
				ajax_component_send(this.ajax_component_id, form_id);
			else
				$(form_id).submit();
		}
	}

}

function init_country_selector(edit_form, country_field, state_field, country_value, state_value) {

		for (var i=0; i < countries.length; i++) {
			country_field.options[i+1] = new Option(countries[i][1], countries[i][0]);
		}

	if (country_value != "") {
		for (var i=0; i < countries.length; i++) {
			if (countries[i][1] == country_value || countries[i][0] == country_value) {
				country_field.value = countries[i][0];
				country_changed(edit_form, country_field.name);
				break;
			}
		}
	}
	if (state_value != "") {
		for (var i=0; i < states.length; i++) {
			if (states[i][1] == state_value || states[i][0] == state_value) {
				if (states[i][2] == country_value) {
					state_field.value = states[i][1];
					break;
				}
			}
		}
	}

}

function country_changed(edit_form, country_field_name) {
	for (var i=0; i < country_selectors.length; i++) {
		if (country_field_name == edit_form.name_prefix + country_selectors[i][0]) {
			var country_field = edit_form.get_field_control(country_selectors[i][0]);
			var state_field   = edit_form.get_field_control(country_selectors[i][1]);

			country_code = country_field.value;

			var state_edit_field = edit_form.fields[country_selectors[i][1]];
			if (state_edit_field) {
				state_edit_field.mandatory = (country_code == 'US');

				state_field.options.length = 0;
				state_field.options[0] = new Option("--   Select State/Province   --", "");

				s = 0;
				for (var i=0; i < states.length; i++) {
					if (country_code == states[i][2]) {
						s++;
						state_field.options[s] = new Option(states[i][0], states[i][1]);
					}
				}

				if (s == 0) {
					state_field.options.length = 0;
					state_field.options[s] = new Option("--   No State   --", "");
				}

				break;
			}
		}
	}
}

function edit_field_update() {
	if (this.edit_type == 'plugin') {
		var main_field = this.get_field_control();
		if (main_field == null) return;

		var f;

		main_field.value = this.value;

		f = document.id(this.get_id('display'));
		if (f)
			f.value = (this.display_value)? this.display_value : this.value;

		f = document.id(this.get_id('content'));
		if (f) {
			DeleteChildren(f);
			f.innerHTML = (this.display_content)? this.display_content : '';
		}

		if (main_field.onchange)
			main_field.onchange();
	}
}

function textarea_controller(edit_form, field_name, maxlength) {
	var f = edit_form.get_field_control(field_name);
	if (f.value.length > maxlength)
		f.value = f.value.substring(0, maxlength);
}

function edit_popup_window_create(anchor_name, w, h, open_url, window_name) {

	var a;
	if (anchor_name) {
        var el = $(anchor_name);
        var a = el.getPosition();		
	}
	else {
        var ww = window.getWidth();
        var wh = window.getHeight();
        a = {x: window.getScrollLeft() + (ww-w)/2, y: window.getScrollTop() + (wh-h)/2}
    }

	var l = a.x + 40;
	var t = a.y - 155;

	if (typeof window_name == 'undefined') {
		window_name = 'edit_popup_window';
	}

	var c = 'scrollbars,resizable'
	if (w) {
		c = c + 'width=' + w; 
	}
	if (h) {
		c = c + 'height=' + h; 
	}
		
	c = c + ',left=' + l + ',top=' + t;

	if (open_url != "" && open_url != 'about:blank')
		open_url = open_url + "&winmode=popup"

	var w = window.open(open_url, window_name, c);
	w.focus();
	return w;
}

function edit_popup_window(anchor_name, w, h, open_url, window_name) {
	edit_popup_window_create(anchor_name, w, h, open_url, window_name)
}

function edit_field_popup(edit_form, field_name, w, h, href, value_field_name) {
	var f = edit_form.get_field_control(field_name);

	if (value_field_name)
		href = href + '&' + value_field_name + '=' + f.value
		
	var edit_field = edit_form.fields[field_name];
	var anchor_id = edit_field.get_id('anchor');		

	edit_popup_window(anchor_id, w, h, href);
}

function get_form(el) {
	while (el && el.nodeName != "FORM") {
		el = el.getParent();
	}	
	
	return el;
}

function edit_plugin_activate(edit_form, field_name, popup_width, popup_height, plugin_params) {
	var form_name = edit_form.name;
	var elForm = edit_form.DOM;

	var f = edit_form.get_field_control(field_name);

	var edit_field = edit_form.fields[field_name];
	if (edit_field.enabled == false)
		return;

	var plugin_options = {};
	if (plugin_params) {
		var param_pairs = plugin_params.split("&");
		param_pairs.each(function(pair){
			var p = pair.split("=");
			plugin_options[p[0]] = p[1];
		});
	}
	

	plugin_options = $extend({	field_name: field_name,
								field_value: f.value,
								action: 'plugin',
								edit_plugin_mode: 'activate',
								plugin_name: edit_field.plugin_name,
								popup_width: popup_width,
								popup_height: popup_height,
								plugin_owner: elForm.signature.value,
								persistent_signature: elForm.persistent_signature.value
								}, plugin_options);

	if (edit_field.plugin_type == 'combo') {
		var popupFormName = 'frmCombo_' + form_name;
		var s = "<html><body>\n" ;
		s = s + "<form name='" + popupFormName + "' action='/?mode=persistent_handler' method='post'>\n";
		for (var x in plugin_options) {
			if (x) {
				s = s + "<input type='hidden' name='" + x + "' value='" + plugin_options[x] + "' />\n";
			}	
		}
		s = s + "<input type='hidden' name='winmode' value='popup' />\n";
		s = s + "</form>\n";
        s = s + "<script type='text/javascript'>\n";
        s = s + "document." + popupFormName + ".submit();\n";
        s = s + "</script>";
		s = s + "</body></html>" ;
		
		popup_width = "";

		var w = edit_popup_window_create(edit_field.get_id('anchor'), popup_width, popup_height, "", 'popup_' + field_name);
        w.document.write(s);
        w.document.close()
	}
	else if (edit_field.plugin_type == 'picker') {

		var activate_picker = function() {
			var input_field = $('picker_text');
			if (input_field)
				input_field.focus();
		}

		popup_width = "";

		var options = {onComplete: activate_picker,
						draggable: false,
						noOffsetWidth: true,
						offsetX: 1,
						offsetY: 8,
						width: popup_width,
						height: popup_height
						}

		if (window.ie7) {
			options.offsetX = 1;
			options.offsetY = 1;
		}

		var href = edit_form.url;
		var anchor = $(edit_field.get_id('anchor'));

		var ajaxRequest = new Request({
											url: href,
											method: 'post',
											data: plugin_options,
											evalScripts: true,
											onComplete: function(responseText) {
												show_popup(responseText, anchor, options);
											}
										});
		ajaxRequest.send();
	}
}


function DeleteChildren(node){

	if(node){
		for(var x = node.childNodes.length - 1; x >= 0; x--){
			var childNode = node.childNodes[x];
			 if(childNode.hasChildNodes()){
			   DeleteChildren(childNode);
			}
			node.removeChild(childNode);
			if(childNode.outerHTML){
				childNode.outerHTML = '';
			}
			childNode=null;
		}
		node=null;
	}
}

function edit_plugin_set_value(form_name, field_name, field_value) {
	var have_opener = false;
	var openerForm = null;
	
	if (typeof opener != "undefined" && opener != null) {
		openerForm = eval("opener.document." + form_name)
		have_opener = (opener && typeof openerForm != "undefined");
	}	

	if (have_opener) {
		var edit_form = eval("opener.edit_form_" + form_name);
		var edit_field = edit_form.fields[field_name];
		var href = edit_form.url;
		var signature = openerForm.signature.value;
		var persistent_signature = openerForm.persistent_signature.value;
	}
	else {
		var edit_form = eval('edit_form_' + form_name);
		var edit_field = edit_form.fields[field_name];
		var href = edit_form.url;
		var signature = edit_form.DOM.signature.value;
		var persistent_signature = edit_form.DOM.persistent_signature.value;
	}

	var update_field = function(responseText){

		var get_response_field = function(field, subject) {
			var exp = '<' + field +'>(.*)</'+ field + '>';
			var re = new RegExp(exp);
			var m = re.exec(subject);
			return m[1];
		}

		var re_compact = new RegExp("\n", "gm");    //.. convert to a single string by removing newline characters
		var response = responseText.replace(re_compact, '');

		edit_field.value = get_response_field('value', response);
		edit_field.display_value = get_response_field('display_value', response);
		edit_field.display_content = get_response_field('display_content', response);


		edit_field.update();
		if (have_opener)
			self.close();
		else
			hide_popup();
	}


	var request = { field_value: field_value,
					field_name: field_name,
					action: 'plugin',
					signature: signature,
					persistent_signature: persistent_signature,
					plugin_name: edit_field.plugin_name,
					edit_plugin_mode: 'query'};

	var ajaxRequest = new Request(  {url: href,
									method: 'post',
									data: request,
									onComplete: update_field
									});
	ajaxRequest.send();
}


function picker_submit(edit_form, field_name, request_uri) {

	var f = edit_form.get_field_control(field_name);
	var edit_field = edit_form.fields[field_name];
	if (edit_field.enabled == false)
		return;
		
	var pickerForm = eval('document.frmPicker_' + field_name);		

	var search_text = pickerForm.picker_text.value;
	var signature = edit_form.DOM.signature.value;

	var request = { edit_plugin_mode: 'search',
					action: 'plugin',
					field_name: field_name,
					field_value: f.value,
					plugin_name: edit_field.plugin_name,
					persistent_signature: edit_form.DOM.persistent_signature.value,
					signature: signature,
					search: search_text
					};

	var ajaxRequest = new Request({ url: request_uri,
									method: 'post',
									data: request,
									onComplete: function(responseText){
										var el = $('picker_list');
										DeleteChildren(el);
										el.innerHTML = responseText;
									}
									});
	ajaxRequest.send();
}

function other_toggle_click(edit_form, field_name, other_field_name) {

	var f_cb = edit_form.get_field_control(field_name + '_cb');
	var val = f_cb.checked;

	var f = edit_form.fields[other_field_name];
	f.set_enabled(val);

	var f = edit_form.fields[field_name];
	f.set_enabled(!val);

	if (val) {
		var f1 = edit_form.get_field_control(field_name + '_cb');
		if (f1) {
			f1.disabled = false;
		}
		var edit_field = edit_form.fields[other_field_name];
		if (edit_field)
			edit_field.set_enabled(true);
	}
	else {
		var edit_field = edit_form.fields[other_field_name];
		if (edit_field)
			edit_field.set_enabled(false);
	}
}


function edit_field_validate_integer(f) {
	var value = f.get_value();
	if (value == '' || isInteger(value))
		return true;

	f.force_edit("Please enter a valid number!");

	return false;
}


var cal1x;

function open_calendar(id, anchor, format) {
	if (typeof cal1x == "undefined") {
		var div = document.createElement("div");
		div.setAttribute('id', 'calendar');
		document.body.appendChild(div);

		div.style.visibility	= "hidden";
		div.style.position 		= "absolute";		
		div.style.background 	= "white";		
		
		cal1x = new CalendarPopup("calendar");
		cal1x.offsetX = -83;
		cal1x.offsetY = 20;
	}
		
	cal1x.select(id, anchor, format);
}

function disable_submit_button(form_name) {
	var id = form_name + '_submit'
	var e = $(id)
	e.disabled = true;
}
function enable_submit_button(form_name) {
	var id = form_name + '_submit'
	var e = $(id)
	e.disabled = false;
}



