// ******************************************************************
// NestingManager.js
//
// Version 3.0
// Copyright (c) 2007 Catalog Data Solutions. All Rights Reserved.
//
// Class implementing parent/child relationships between attributes
// in which certain combinations of values make attributes either
// available or unavailable.
// ******************************************************************

cds.namespace("configurator");

// ---------------------------------------------------------
// NestingManager class
// ---------------------------------------------------------

cds.configurator.NestingManager = function(attributeManager) {
	this.attributeManager = attributeManager;
	this.rules = new Array();
	this.attributeManager.nestingManager = this;

	this.addRule = function(attributeId, elementId, expression) {
		this.rules[this.rules.length] = new cds.configurator.NestingManagerRule(this.attributeManager, attributeId, elementId, expression);
	}

	this.enforce = function() {
		for (var i = 0; i < this.rules.length; i++) {
			this.rules[i].enforce();
		}
	}

	this.destroy = function() {
		this.attributeManager = null;
		for (var i = 0; i < this.rules.length; i++) {
			if (typeof this.rules[i].destroy == "function") this.rules[i].destroy();
		}
		this.rules = null;
	}

	this.toString = function() {
		return "cds.configurator.NestingManager";
	}
}

// ---------------------------------------------------------
// NestingManagerRule class
// ---------------------------------------------------------

cds.configurator.NestingManagerRule = function(attributeManager, attributeId, elementId, expression) {
	this.elementId = elementId;
	this.attribute = attributeManager.getAttribute(attributeId);
	this.evaluator = new cds.configurator.AttributeExpressionEvaluator(attributeManager, expression);

	this.enforce = function() {
		if (this.evaluator.evaluate()) {
			var e = document.getElementById(elementId);
			if (e != null) {
				e.style.display = "";
				this.attribute.isHiddenFromNesting = false;
			}
		} else {
			this.attribute.setValue();
			var e = document.getElementById(elementId);
			if (e != null) {
				e.style.display = "none";
				this.attribute.isHiddenFromNesting = true;
			}
		}
	}

	this.destroy = function() {
		this.attribute = null;
		this.evaluator = null;
	}

	this.toString = function() {
		var s = "cds.configurator.NestingManagerRule(" + this.elementId + ")";
		return s;
	}
}

