
// requires getObject and showHide metods within the general.js 

FieldController = function(pName){
	this._name = pName; // reference to defining variable name
	this._fieldItems = []; // array of toggle items
};


FieldController.prototype.init = function(){
	for(var i=0; i<this._fieldItems.length; i++){
		var oField = getObject(this._fieldItems[i].fieldID);
		if(oField){
			oField.onkeyup = this.textCounter;
			oField.onchange = this.textCounter;
			oField.maxLength = this._fieldItems[i].maxChars;
			oField.fieldControl = this;
			this.updateCounter(oField, this._fieldItems[i].maxChars);
		}
	}
}

FieldController.prototype.add = function(pFieldID, pMaxChars){
	var oData = {};
	oData.fieldID = pFieldID;
	oData.maxChars = pMaxChars;
	var maxWords = Math.round(pMaxChars/5);
	this._fieldItems[this._fieldItems.length] = oData;
	if(pMaxChars > 0){
		document.write("<p class=\"formInfo\"><span id=\"counter_" + pFieldID + "\">" + pMaxChars + "</span> of " + pMaxChars + " characters (approx. " + maxWords + " words) remaining.<\/p>");
	}
};

// NOTE: this method is in the scope of the field
FieldController.prototype.textCounter = function(){
	if(this.value.length > this.maxLength){ // if too long...trim it!
		this.value = this.value.substring(0, this.maxLength);
	}
	this.fieldControl.updateCounter(this, this.maxLength);
};


FieldController.prototype.updateCounter = function(oField, pMaxLength){
	var oFieldCounter = this.getFieldCounter(oField.id);
	var counterVal = pMaxLength - oField.value.length;
	if(oFieldCounter.innerText){
		oFieldCounter.innerText = counterVal;
	}else{
		oFieldCounter.textContent = counterVal;
	}
};


FieldController.prototype.getField = function(pFieldID){
	for(var i=0; i<this._fieldItems.length; i++){
		if(this._fieldItems[i].fieldID == pFieldID){
			return this._fieldItems[i];
		}
	}
};


FieldController.prototype.getFieldCounter = function(pFieldID){
	return getObject("counter_" + pFieldID);
};

