var FormFieldRegistry = new Array();

$(document).ready(function() {

	$('form div.row').each(function(index) {
		try {
			if ($(this).meta('fieldtype')[0]) eval('FormFieldRegistry[index] = new ' + $(this).meta('fieldtype')[0] + '($(this).meta("fieldname")[0]);');
		} catch(e) {
			// alert('Feldtyp noch nicht implementiert (JS): ' + $(this).meta('fieldtype') + '!');
		}
	});

	$('div.row[class*="validator-maxLength-"] textarea').each(function() {
		var maxlen = $(this).parents('div.row').meta('validator-maxLength')[0];
		var fieldname = $(this).attr('name');
		new MaxLengthHelper(fieldname, maxlen, TextareaField.prototype.maxLengthHelperMessage);
	});

	$('div.row[class*="fieldname-certificate_variables__use_alternative_signer_description"] input').change(function() {

		var alternativeDefinition = $(this).parents('form').find('div.row[class*="fieldname-certificate_variables_ld__signer_description"]');
		if ($(this).attr('checked')) {
			alternativeDefinition.show();
		} else {
			alternativeDefinition.hide();
		}

	}).change();

	$('form.autosave').each(function() {
		var form = $(this);
		window.setInterval(function() {
			$.post('./?autosave=true', form.serialize(), function(contextSerial) {
				$('input[name="_contextSerial"]').val(contextSerial);
			});
		}, 30000);
	});

	$('div.changes').each(function() {
		var div = $(this).find('div.helptext');
		div.before('<img height="16px" width="16px" src="' + WFD_STATIC_COMMON + 'img/icon-info-small.png" />');
		var icon = div.prev();
		icon.css({height: '16px', width: '16px', verticalAlign: 'middle'});
	});
});

function FormField(name) {
	this.init(name);
}

FormField.prototype = {
		
	init: function(name) {
		this.name = name;
		this.row = $('div.row.fieldname-' + this.name);
		this.compactMode = this.row.parents('form').is('.compact');
		this.fieldContainer = this.row.find('div.field');
		this.field = this.findField();
		this.fieldInner = this.findFieldInner();
		this.helptext = this.row.find('div.helptext');
		this.helptext.visible = false;
		this.editLink = null;
		this.fieldHideFunction = jQuery.prototype.hide;
		this.initField();
		this.initHelpText();
	},

	findField: function() {
		return this.fieldContainer.find('input');
	},

	findFieldInner: function() {
		return this.findField();
	},

	initField: function() {
		if (this.compactMode) {
			this.fieldContainer.append('<a href="#" class="edit-link" title="Click here to edit">' + this.getEditLinkText() + '</a>');
			this.editLink = this.fieldContainer.find('a.edit-link');
			this.editLink.focus(this.onFocus.calledOn(this));
			this.editLink.click(this.onFocus.calledOn(this)); // Safari
			this.editLink.click(function() { return false; }); // Safari
			if (this.field) {
				this.field.blur(this.onBlur.calledOn(this));
				this.fieldInner.hide();
			}
		} else {
			if (this.field) {
				this.field.focus(this.onFocus.calledOn(this));
				this.field.blur(this.onBlur.calledOn(this));
			}
		}
	},

	initHelpText: function() {
		this.helptext.hide().find('a').attr('tabindex', 99999);
	},

	onFocus: function() {
		if (this.compactMode) {
			this.editLink.hide();
			if (this.fieldInner.show()) this.field.focus();
		}
		this.showHelptext();
	},

	onBlur: function(e) {
		if (this.compactMode) {
			this.fieldHideFunction.calledOn(this.fieldInner)();
			this.editLink.html(this.getEditLinkText());
			this.editLink.show();
		}
		this.hideHelptext();
	},

	showHelptext: function() {
		for (var i in FormFieldRegistry) {
			if (FormFieldRegistry[i] && FormFieldRegistry[i].helptext && FormFieldRegistry[i].helptext.visible) FormFieldRegistry[i].hideHelptext();
		}
		if (this.helptext.visible == false) {
			this.helptext.fadeIn(200);
			this.helptext.visible = true;
		}
	},

	hideHelptext: function() {
		if (this.helptext.visible) this.helptext.fadeOut(500);
		this.helptext.visible = false;
	},

	getTextValue: function() {
		return this.field.attr('value');
	},

	getEditLinkText: function() {
		v = this.getTextValue();
		if (!v || v.match(/^ +$/)) v = this.getEmptyEditLinkHTML();
		else if (v.length > 52) v = v.substring(0,50) + ' ...';
		return v;
	},

	getEmptyEditLinkHTML: function() {
		return '<span class="empty">' + this.enterDataMessage + '</span>';
	}

}


// Standardfelder //

TextField = FormField;

FileUploadField = FormField;

ImageResizeField = FormField;


// mehrzeiliges Textfeld / Textarea //
function TextareaField(name) {
	this.init(name);
	this.fieldHideFunction = jQuery.prototype.slideUp;
}
TextareaField.prototype = new FormField();

TextareaField.prototype.findField = function() {
	return this.fieldContainer.find('textarea');
}


// Select-Feld //
function SelectField(name) {
	this.init(name);
}
SelectField.prototype = new FormField();

SelectField.prototype.findField = function() {
	return this.fieldContainer.find('select');
}

SelectField.prototype.getTextValue = function() {
	return this.field.get(0).options[this.field.get(0).selectedIndex].text;
}

SelectField.prototype.getEditLinkText = function() {
	if (this.field.val()) {
		return FormField.prototype.getEditLinkText.calledOn(this)();
	} else {
		return this.getEmptyEditLinkHTML();
	}
}


// CountrySelect-Feld //
CountrySelectField = SelectField;

// Select-Feld für DomainObject-Listen //
DomainObjectSelectField = SelectField;


// LanguageSelectField //
function LanguageSelectField(name) {
	this.init(name);
}
LanguageSelectField.prototype = new SelectField();

var initialLanguageSelection = new Array();
LanguageSelectField.prototype.initField = function() {
	this.fieldContainer.find('select').each(function(index) {
		if(index>0 && !this.value) $(this).hide();
		$(this).change(function(e) {
			var selectedLanguages = new Array();
			$(this).parent().children('select').each(function() {
				if (this.value) selectedLanguages.push(this.value);
			});
			var deletedLanguages = new Array();
			for (var i=0; i<initialLanguageSelection.length; i++) {
				if (!selectedLanguages.contains(initialLanguageSelection[i])) {
					var options = $(this).parent().children('select').get(0).options;
					for (var j=0; j<options.length; j++) {
						if (options[j].value == initialLanguageSelection[i]) {
							deletedLanguages.push(options[j].text);
							break;
						}
					}
				}
			}
			var f = $(this).parents('div.field');
			f.find('.deleted-languages').remove();
			if (deletedLanguages.length) {
				var s = '<div class="flash info deleted-languages">' + LanguageSelectField.prototype.deletedLanguagesMessage + '<ul>';
				for (var i=0; i<deletedLanguages.length; i++) s += '<li>' + deletedLanguages[i] + '</li>';
				s += '</ul></div>';
				f.append(s);
			}
		});
		if (this.value) initialLanguageSelection.push(this.value);
	});
	this.fieldContainer.append('<a href="#' +this.name+ '" class="add-language" onclick="var nextSelect = $(\'div.fieldname-'+this.name+' div.field select:visible\').next(); nextSelect.show(); if ($(\'div.fieldname-'+this.name+' div.field select:hidden\').length == 0) $(this).remove(); return false;">Add another language</a>');
}


// Date-Feld //
function DateField(name) {
	this.init(name);
	this.blurTimeOut = null;
}
DateField.prototype = new FormField();

DateField.prototype.findField = function() {
	return this.fieldContainer.find('select');
}

DateField.prototype.getTextValue = function() {
	var year = $(this.field[2]).attr('value')
	var month = $(this.field[1]).attr('value')
	var day = $(this.field[0]).attr('value');
	if (month.length == 1) month = '0' + month;
	if (day.length == 1) day = '0' + day;
	return day + '/' + month + '/' + year;
}

DateField.prototype.getEditLinkText = function() {
	if ($(this.field[0]).val() &&
		$(this.field[1]).val() &&
		$(this.field[2]).val()
	)
	{
		return FormField.prototype.getEditLinkText.calledOn(this)();
	} else {
		return this.getEmptyEditLinkHTML();
	}
}

DateField.prototype.initField = function() {
	FormField.prototype.initField.calledOn(this)();
	if (this.compactMode) {
		this.field.focus(this.onFocus.calledOn(this));
		this.fieldContainer.find('span.separator').hide();
	}
}

DateField.prototype.onFocus = function() {
	if (this.compactMode) {
		if (this.blurTimeOut) {
			window.clearTimeout(this.blurTimeOut);
		}
		this.editLink.hide();
		if ($(this.field[0]).css('display') == 'none') {
			this.field.show();
			this.showHelptext();
			this.field[0].focus();
		}
	} else {
		this.showHelptext();
	}
}

DateField.prototype.onBlur = function() {
	if (this.compactMode) {
		this.blurTimeOut = window.setTimeout(function(e) {
			this.field.hide();
			this.editLink.html(this.getEditLinkText());
			this.editLink.show();
			this.hideHelptext();
		}.calledOn(this), 100);
	} else {
		this.hideHelptext();
	}
}


// Passwort-Feld //
function PasswordField(name) {
	this.init(name);
}
PasswordField.prototype = new FormField();

PasswordField.prototype.findField = function() {
	return this.fieldContainer.find('input[type=password]');
}

PasswordField.prototype.getTextValue = function () {
	var v = FormField.prototype.getTextValue.call(this);
	return v.replace(/./g, '*');
}


// Button //
function Button(name) {
	this.init(name);
}
Button.prototype = new FormField();

Button.prototype.initField = function() {};


// Readonly-Feld //
function ReadonlyField(name) {
	this.init(name);
}
ReadonlyField.prototype = new FormField();

ReadonlyField.prototype.findField = function() {
	return null;
}


// Checkbox //

function CheckboxField(name) {
	this.init(name);
}
CheckboxField.prototype = new FormField();
CheckboxField.prototype.initField = function() {};


// MultilingualFormField (generisch)

function MultilingualFormField(name) {
	this.init(name);
	this.blurTimeOut = null;
}
MultilingualFormField.prototype = new FormField();

MultilingualFormField.prototype.onFocus = function() {
	if (this.compactMode) {
		if (this.blurTimeOut) {
			window.clearTimeout(this.blurTimeOut);
		}
		this.editLink.hide();
		if ($(this.fieldInner).css('display') == 'none') {
			this.fieldInner.show();
			this.fieldContainer.find('label.lang').show();
			this.showHelptext();
			this.field[0].focus();
/*
	Die letzte Zeile sorgt dafür, dass bei mehrsprachigen Feldern immer das erste Eingabefeld fokussiert wird,
	auch wenn man den 2., 3., usw. Wert angeklickt hat. Das Problem ist, dass wir es hier mit einem alle Werte
	umfassenden <a>-Link zu tun haben, bei dessen Fokussierung diese onFocus-Methode hier getriggert wird. Da
	das Event-Target das <a>-Tag ist, lässt sich nicht mehr erkennen, welche Sprachversion angeklickt wurde, um
	das entsprechende Feld zu fokussieren. Bei einem Click-Event könnten wir anhand der Position des angeklickten
	Elements innerhalb des <div class="field"> erkennen, um welche Sprachversion es sich handelt. In etwa so:

	var selectedFieldIndex = $(evt.target).parents('div.ld-value').prevAll().length;
	if (selectedFieldIndex) this.field[selectedFieldIndex].focus();

*/
		}
	} else {
		this.showHelptext();
	}
}

MultilingualFormField.prototype.onBlur = function() {
	if (this.compactMode) {
		this.blurTimeOut = window.setTimeout(function(e) {
			this.fieldInner.hide();
			this.fieldContainer.find('label.lang').hide();
			this.editLink.html(this.getEditLinkText());
			this.editLink.show();
			this.hideHelptext();
		}.calledOn(this), 100);
	} else {
		this.hideHelptext();
	}
}

MultilingualFormField.prototype.getTextValue = function() {
	var s = [];
	for (var i=0; i<this.field.length; i++) {
		s.push({
			lang: $(this.field[i]).attr('lang'),
			description: $(this.field[i]).siblings('label').text(),
			value: $(this.field[i]).val(),
			src: $(this.field[i]).siblings('label').find('img').attr('src')
		});
	}
	return s;
}

MultilingualFormField.prototype.getEditLinkText = function() {
	v = this.getTextValue();
	var s = '';
	if (!v || !v.length) v = this.getEmptyEditLinkHTML();
	else {
		for (var i=0; i<v.length; i++) {
			var vi = v[i].value;
			if (!vi || vi.match(/^ +$/)) vi = this.getEmptyEditLinkHTML();
			else if (vi.length > 49) vi = vi.substring(0,47) + ' ...';
			s += '<img src="' + v[i].src + '" alt="' + v[i].description + '" /> ' + vi + '<br/>';
		}
	}
	return s;
}

MultilingualFormField.prototype.findFieldInner = function() {
	return this.fieldContainer.find('div.ld-field');
}


// MultilingualTextField //

function MultilingualTextField(name) {
	this.init(name);
	this.blurTimeOut = null;
}
MultilingualTextField.prototype = new MultilingualFormField();

MultilingualTextField.prototype.initField = function() {
	FormField.prototype.initField.calledOn(this)();
	if (this.compactMode) {
		this.field.focus(this.onFocus.calledOn(this));
		this.fieldContainer.find('label.lang').hide();
	}
}

// MultilingualTextareaField //

function MultilingualTextareaField(name) {
	this.init(name);
	this.blurTimeOut = null;
}
MultilingualTextareaField.prototype = new MultilingualFormField();

MultilingualTextareaField.prototype.findField = function() {
	return this.fieldContainer.find('textarea');
}

MultilingualTextareaField.prototype.initField = function() {
	FormField.prototype.initField.calledOn(this)();
	if (this.compactMode) {
		this.field.focus(this.onFocus.calledOn(this));
		this.fieldContainer.find('label.lang').hide();
	}
}

function ReferenceField(name) {
	this.init(name);
	this.overFieldInner = false;
	this.blurTimeOut = null;
}
ReferenceField.prototype = new FormField();

ReferenceField.prototype.findField = function() {
	return this.fieldContainer.find('select:not(.originalSelectField), button');
}

ReferenceField.prototype.findFieldInner = function() {
	return this.fieldContainer.find('.ITReferenceUserInterface');
}

ReferenceField.prototype.initField = function() {
	FormField.prototype.initField.calledOn(this)();
	if (this.compactMode) {
		this.fieldInner.mouseover(function() {
			this.overFieldInner = true;
		}.calledOn(this));
		this.fieldInner.mouseout(function() {
			this.overFieldInner = false;
			this.field[0].focus();
		}.calledOn(this));
		this.field.focus(this.onFocus.calledOn(this));
	}
}

ReferenceField.prototype.getTextValue = function() {
	var select = this.fieldContainer.find('.originalSelectField');
	var options = select.find('option');
	var text = new Array();
	for (var i = 0; i < options.length; i++) {
		var option = options[i];
		if (option.selected) text.push(option.text);
	}
	return text.join(', ');
}

ReferenceField.prototype.onFocus = function() {
	if (this.compactMode) {
		if (this.blurTimeOut) {
			window.clearTimeout(this.blurTimeOut);
		}
		this.editLink.hide();
		if ($(this.fieldInner).css('display') == 'none') {
			this.fieldInner.show();
			this.showHelptext();
			this.field[0].focus();
		}
	} else {
		this.showHelptext();
	}
}

ReferenceField.prototype.onBlur = function() {
	if (this.compactMode) {
		if (this.overFieldInner) return;
		this.blurTimeOut = window.setTimeout(function(e) {
			this.fieldInner.hide();
			this.editLink.html(this.getEditLinkText());
			this.editLink.show();
			this.hideHelptext();
		}.calledOn(this), 100);
	} else {
		this.hideHelptext();
	}
}

// CountryReference-Feld //
CountryReferenceField = ReferenceField;


/* MaxLengthHelper */
function MaxLengthHelper(fieldName, maxLength, message) {
	this.field = $('textarea[name="' + fieldName + '"]');
	this.field.after('<div class="maxLengthDisplay"></div>');
	this.display = this.field.parent().find('div.maxLengthDisplay');
	this.domField = this.field.get(0);

	this.maxLength = maxLength;
	this.message = message;

	this.field.keyup(this.keyup.calledOn(this));

	this.keyup();
}

MaxLengthHelper.prototype = {
	keyup: function() {
		var text = this.message;
		var currentLength = this.domField.value.length;
		text = text.replace(/\$\{currentLength\}/, currentLength);
		text = text.replace(/\$\{maxLength\}/, this.maxLength);
		this.display.html(text);
		(currentLength > this.maxLength) ? this.display.addClass('error') : this.display.removeClass('error');
	}
}


// MultipleSelectField //
function MultipleSelectField(name) {
	this.init(name);
}
MultipleSelectField.prototype = new SelectField();

// MultipleCheckboxField //
function MultipleCheckboxField(name) {
	this.init(name);
}

MultipleCheckboxField.prototype = new SelectField();

MultipleCheckboxField.prototype.findField = function() {
	return this.fieldContainer.find('input');
}

// MultipleCheckboxField //
function RadioField(name) {
	this.init(name);
}

RadioField.prototype = new SelectField();

RadioField.prototype.findField = function() {
	return this.fieldContainer.find('input');
}
