/*-----------------------------------------------------------------------------


@author:		Martí Congost
@contact:		marti.congost@whads.com
@organization:	Whads/Accent SL
@since:			August 2007
-----------------------------------------------------------------------------*/

weblib.controls.ObjectForm = function () {

	var translations = weblib.dom.get(this, ".translations");
	this.__translationDisabledText =
		weblib.state.get(this, "text-translationDisabled");
	
	if (translations) {
		
		this.__activeTranslations = {};
		this.__tbody = weblib.dom.get(translations, "tbody");

		this.hasActiveTranslations = function () {

			for (var i in this.__activeTranslations) {
				if (this.__activeTranslations[i]) {
					return true;
				}
			}
		
			return false;
		}

		this.translationIsActive = function (language) {
			return this.__activeTranslations[language];
		}

		this.shouldApply = function (validation, language) {
			return !validation.multiLanguage
				|| this.translationIsActive(language);
		}

		var headers = weblib.dom.select(translations, ".translationHeader");

		headers.forEach(function (trans, index) {
			
			trans.__form = this;
			trans.__table = translations;
			trans.__index = index;
			trans.__check = weblib.dom.get(trans, ".translationActivation");
			trans.__check.__translation = trans;
			
			var pos = trans.__check.name.lastIndexOf("-");
			trans.__language = trans.__check.name.substr(pos + 1);
			this.__activeTranslations[trans.__language] = true;

			trans.setContentVisible = function (visible) {
				
				this.__form.__activeTranslations[this.__language] = visible;
				var rows = weblib.dom.children(this.__form.__tbody, "tr");
				
				rows.forEach(function (row, index) {
					var cell = weblib.dom.children(row, "td")[this.__index];
					weblib.ui.setVisible(cell, visible);
				}, this);

				weblib.ui.setClass(
					this.__form.__tbody,
					"hidden",
					!this.__form.hasActiveTranslations()
				);
			}

			if (!trans.__check.checked) {
				trans.setContentVisible(false);
			}

			this.__activeTranslations[trans.__language] = trans.__check.checked;
			
			trans.focusContent = function () {
				var row = this.__table.getElementsByTagName("tr")[1];
				var cell = weblib.dom.children(row, "td")[this.__index];
				var control = weblib.dom.get(cell, ".control");
				control.focus();
			}

			weblib.events.add(trans.__check, "click", function () {
				this.__translation.setContentVisible(this.checked);
				if (this.checked) {
					this.__translation.focusContent();
				}
			});
		}, this);
	}
}

weblib.dom.bind(".views-ObjectForm", weblib.controls.ObjectForm);

