// JAVASCRIPT FILE  - TIGER DATA ENTRY FIELD OBJECT

// TigerField object - when a field is added to the form, a corresponding javascript object should be
// 	created to contain full information about the field and the way it should behave. The name of the
// field should match the name of the main data field.
function TigerField(cName, cNiceName) { 
	this.FieldName = cName; 				// Name to identify the field. Must be specified.
	this.FieldType = eFieldType.Contact;	// Type of field, e.g. Contact/DPA/Demog
	this.DataEntryStyle = eDataEntryStyle.Text; 	// What type of data entry box. Default to textbox
	this.FormatType = eFormatType.None; 	// Which rules to format this data
	this.FormatTitleType = eFormatType.Standard; 	// Which sub-rules to format this data if title-case
	this.FieldElements = new Array(); 		// An array to store information about all related form elements
	this.IsAddressField = false;			// Set to specify address fields (up to, but not including postcode).
	this.IsPostcodeField = false;			// Set to specify postcode field
	this.LastRequestedPostcode = ""			// Last postcode requested from AJAX
	this.LastFetchedPostcode = ""			// Last postcode fetched through AJAX
	this.PostcodeFetchInProgress = false	// Flag to indicate if an AJAX fetch is currently in progress
	this.TabLastPressed = false				// For postcode field, to keep track if TAB was the last key pressed. To pass on to the 'blur' event
	this.HouseNumberID = ""					// The HTML ID of the whole span for 'House Number' - only used if IsPostcodeField is TRUE
	this.HouseNumberFieldName = ""			// The Field Name of the 'House Number' box - only used if IsPostcodeField is TRUE
	this.IsSelected = false;				// Keeps track of whether this field is currently selected for data entry
	this.IsVisible = true;					// Keeps track of whether this field is currently visble
	this.IsDisabled = false;				// Keeps track of whether this field is currently disabled (visible, but can't type in it)
	this.Compulsory = true;				// Sets whether this field is compulsory
	this.ValidType = eValidType.NoValidation;	// Specifies the validation rules to use
	this.Multiple = false;					// Specifies for demographics if the user is allowed to select multiple options
	this.InitialDisplayStatus = eDisplayStatus.Normal;	// Remembers how the control 'started out' - invisible, disabled, useable
	this.CurrentErrorMsg = "";				// Keeps track of the current error message being displayed
	this.NiceFieldName = cNiceName ? cNiceName : this.FieldName;				// A nice field name used for automatically-generated messages to the user
	this.ErrorMsgEmpty = this.NiceFieldName+" is empty";				// Text to prompt if the field is left empty
	this.LastVal = "";						// Keeps track of the value of a field before a user edited it, so that it can be compared afterwards
	this.OrigVal = "";						// Keeps track of the original value when the page was loaded
	this.LayoutStyle = eLayoutStyle.Standard;	// HTML layout style for the control - one of predefined templates
	this.IssueLevel = eIssueLevel.None;		// Keeps track of the current 'issue level' or 'error status'
	this.DemogOptions = new Array();		// An array to store information about each demog answer
	this.Conditionals = new Array();		// An array to store information about any conditionals arising from this field
	this.DisplayStatusIfActive = eDisplayStatus.Normal;	// For 'other text'
	this.DisplayStatusIfNotActive = eDisplayStatus.Disabled;	// For 'other text'
}



//////////////////////////////////////////////////////////////////////////////////////////////////////
// DATA FUNCTIONS
//////////////////////////////////////////////////////////////////////////////////////////////////////

// method to create a link to the HTML data field
TigerField.prototype.GetDataField = function () {
	return this.Form[this.FieldName]
}

// GetValue - fetches the value of the data. If there is more than one value, it is returned as an array
TigerField.prototype.GetValue = function () {
	oField = this.GetDataField();
	if (!this.Multiple) {
		if (this.DataEntryStyle==eDataEntryStyle.Radio || this.DataEntryStyle==eDataEntryStyle.Checkbox ) {
			return getCheckedValue(oField);
		} else {
			return oField.value;
		}
	} else {
		aValues = new Array();
		
		for ( var i=0; i < oField.length; i++ ) {
			if ( oField[i].selected || oField[i].checked ) {
				aValues[aValues.length] = oField[i].value;
			}
		}
		return aValues;
	}
}

// SetValue - writes the value of the field
TigerField.prototype.SetValue = function (cVal) {
	if (!this.Multiple) {
		this.GetDataField().value = cVal;
	}
}


// FetchAddress

TigerField.prototype.FetchAddress = function (ev) {
	if (ev.type == "keydown") {
		if (ev.keyCode==9 && !ev.shiftKey) {
			this.TabLastPressed = true;
		} else {
			this.TabLastPressed = false;
		}
		return true;
	}
		
	if (ev.type == "focus") {
		this.LastRequestedPostcode = "";
	}
	
	if (this.parent.PAFLookup && !this.parent.AddressDataTouched) {
		var cCountry = this.parent.CountryField.GetValue();
		if (cCountry != "GB" && cCountry != "UK" && cCountry != "UNITED KINGDOM" && cCountry != "") return false;
		var cVal = this.GetValue();
		if (cVal.length < 5) {
			this.HideHouseNumber();
			this.UpdateAddress("");
			this.LastRequestedPostcode = cVal;
			this.LastFetchedPostcode = "";
			return false;
		}
		if (ev.type == "blur") {
			if (this.TabLastPressed) {
				this.TabLastPressed = false;
				if (this.PostcodeFetchInProgress || cVal != this.LastRequestedPostcode) {
					this.ShowHouseNumber();
					this.parent.Form[this.HouseNumberFieldName].focus();
				}
			}
		}

		if (!this.PostcodeFetchInProgress || cVal != this.LastRequestedPostcode) {
			var cURL = this.parent.PAFLookupURL + escape(cVal)

			xmlHTTP=GetXmlHttpObject(StateChanged);
			xmlHTTP.open("GET", cURL , true)
			xmlHTTP.send()
			this.LastRequestedPostcode = cVal;
			this.PostcodeFetchInProgress = true;
		}
	}
}




TigerField.prototype.UpdateAddress = function (cStream)
{
	this.PostcodeFetchInProgress = false;
	if (this.parent.AddressDataTouched) return false;
    var aResponse=cStream.split("|");
	if (aResponse[1]==undefined) aResponse[1]="";
	if (aResponse[2]==undefined) aResponse[2]="";
	if (aResponse[3]==undefined) aResponse[3]="";
	if (aResponse[4]==undefined) aResponse[4]="";
	if (aResponse[5]==undefined) aResponse[5]="";
    this.parent.Address1Field.SetValue(aResponse[1]);
    this.parent.Address1Field.LastVal=aResponse[1];
    this.parent.Address2Field.SetValue(aResponse[2]);
    this.parent.Address2Field.LastVal=aResponse[2];
    this.parent.TownField.SetValue(aResponse[3]);
    this.parent.TownField.LastVal=aResponse[3];
    this.parent.CountyField.SetValue(aResponse[4]);
    this.parent.CountyField.LastVal=aResponse[4];
    if (aResponse[5].length>0) {
    	this.SetValue(aResponse[5]);
    	this.LastVal=aResponse[5];
    	this.ShowHouseNumber();
    	if (aResponse[5] != this.LastFetchedPostcode) TigerReg.Form[this.HouseNumberFieldName].value="";
    } else {
    	this.HideHouseNumber();
    }
    this.LastFetchedPostcode=aResponse[5];
}
//
//TigerField.prototype.FetchAddressOld = function () {
//	if (this.parent.PAFLookup && !this.parent.AddressDataTouched) {
//		var cVal = this.GetValue();
//		if (cVal.length < 5) {
//			this.HideHouseNumber();
//			return false;
//		}
////		if (this.LastRequestedPostcode.toUpperCase() != cVal.toUpperCase()) {
//			var cCountry = this.parent.CountryField.GetValue();
//			if (cCountry != "GB" && cCountry != "") return false;
//			var cURL = this.parent.PAFLookupURL + escape(cVal)
//			
//			xmlHTTP=GetXmlHttpObject(StateChanged);
//			xmlHTTP.open("GET", cURL , true)
//			xmlHTTP.send(null)
//			this.LastRequestedPostcode = cVal;
////		}
//	}
//}
//



TigerField.prototype.ShowHouseNumber = function () {
	document.getElementById(this.HouseNumberID).style.display="";
}
 
TigerField.prototype.HideHouseNumber = function () {
	document.getElementById(this.HouseNumberID).style.display="none";
}
 
TigerField.prototype.AppendHouseNumber = function () {
	// Get HouseNumber value and format it
	var cHN = AllTrim(titlecase(this.parent.Form[this.HouseNumberFieldName].value));
	var cOrigAdd1 = this.parent.Address1Field.GetValue();
	var cOrigAdd2 = this.parent.Address2Field.GetValue();
	var cAdd1 = "";
	var cAdd2 = "";
	// Merge in to Add1 & 2 as appropriate
	if (cHN.length == 0) {
			cAdd1 = cOrigAdd1;
			cAdd2 = cOrigAdd2;
	} else if (CountDigits(cHN)>1 && CountAlpha(cHN)<=1) {
		cAdd1 = AllTrim(AllTrim(cHN) + " " + AllTrim(cOrigAdd1));
		cAdd2 = cOrigAdd2;
	} else {
		if (cOrigAdd1 == "") {
			cAdd1 = AllTrim(cHN);
			cAdd2 = cOrigAdd2;
		} else if (cOrigAdd2 == "") {
			cAdd1 = AllTrim(cHN);
			cAdd2 = cOrigAdd1;
		} else if (cHN.length > cOrigAdd2.length) {
			cAdd1 = AllTrim(cHN);
			cAdd2 = AllTrim(cOrigAdd1) + ", " + AllTrim(cOrigAdd2);
		} else {
			cAdd1 = AllTrim(cHN) + ", " + AllTrim(cOrigAdd1);
			cAdd2 = AllTrim(cOrigAdd2);
		}
	}
	this.parent.Address1Field.SetValue(cAdd1);
	this.parent.Address1Field.LastVal=cAdd1;
	this.parent.Address2Field.SetValue(cAdd2);
	this.parent.Address2Field.LastVal=cAdd2;
	this.HideHouseNumber();
}
 


//////////////////////////////////////////////////////////////////////////////////////////////////////
// DISPLAY FUNCTIONS - VISIBILITY & CLASSES
//////////////////////////////////////////////////////////////////////////////////////////////////////

// SetClasses - loops through each element, and each 'other text' element, cand calls its SetClasses method
TigerField.prototype.SetClasses = function (lIsListboxSelect) {
	for (FieldElement in this.FieldElements) {
		if (!lIsListboxSelect || this.FieldElements[FieldElement].ElementType != eElementType.Listbox) {
			this.FieldElements[FieldElement].SetClass();
		}
	}
	if (this.FieldType == eFieldType.Demog) {
		for (var DemogOption in this.DemogOptions) {
			if (this.DemogOptions[DemogOption].OtherTextAllowed) {
				this.DemogOptions[DemogOption].OtherText.SetClasses();
			}
		}
	}

};

// SetDisplayStatus - takes parameter of enum eDisplayStatus, and applies to the whole control
TigerField.prototype.SetDisplayStatus = function (DisplayStatus) {
	this.ShowHideFull(DisplayStatus != eDisplayStatus.Hidden);
	this.DisableControls(DisplayStatus == eDisplayStatus.Disabled);
	// Other text
	if (this.FieldType == eFieldType.Demog) {
		for (var DemogOption in this.DemogOptions) {
			this.DemogOptions[DemogOption].SetDisplayStatus(DisplayStatus);
		}
	}
	this.SetClasses();


}

// ShowHideFull - Locate elements of type 'Full' and show or hide as appropriate
TigerField.prototype.ShowHideFull = function (lShow) {
	for (FieldElement in this.FieldElements) {
		if (this.FieldElements[FieldElement].ElementType==eElementType.WholeField) {
			document.getElementById(this.FieldElements[FieldElement].ElementID).style.display = (lShow ? "" : "none");
		}
	}
	this.IsVisible = lShow;
}

// DisableControls - Locate all data controls, and disable/enable as appropriate
TigerField.prototype.DisableControls = function (lDisable) {
	for (FieldElement in this.FieldElements) {
		if (this.FieldElements[FieldElement].ElementType==eElementType.Textbox || this.FieldElements[FieldElement].ElementType==eElementType.Listbox || this.FieldElements[FieldElement].ElementType==eElementType.Radio || this.FieldElements[FieldElement].ElementType==eElementType.Checkbox) {
			document.getElementById(this.FieldElements[FieldElement].ElementID).disabled = lDisable;
		}
	}
	this.IsDisabled = lDisable;
}

// SelectField - Mark this field as 'selected' so that it can be visually identified. Normally called from 'onFocus'
TigerField.prototype.SelectField = function () {
	this.IsSelected = true;
	this.SetClasses((this.DataEntryStyle == eDataEntryStyle.Listbox));
};

// UnselectField - Mark this field as 'no longer selected'. Normally called from 'onBlur'
TigerField.prototype.UnselectField = function () {
	this.IsSelected = false;
	this.SetClasses();
};

// SetConditionals - apply any conditionals (including 'other text') for this field.
TigerField.prototype.SetConditionals = function () {
	// Standard conditionals
	for (Condition in this.Conditionals) {
		this.Conditionals[Condition].Set();
	}


	// Other text
	if (this.FieldType == eFieldType.Demog) {
		for (var DemogOption in this.DemogOptions) {
			if (this.DemogOptions[DemogOption].OtherTextAllowed) {
				this.DemogOptions[DemogOption].SetConditionals();
			}
		}
	}

};

//////////////////////////////////////////////////////////////////////////////////////////////////////
// CHILD OBJECT CREATION
//////////////////////////////////////////////////////////////////////////////////////////////////////

// Create a new 'demog answer' object
TigerField.prototype.AddDemogOption = function (cOptionID) {
	this.DemogOptions[cOptionID] = new TigerDemogOption(cOptionID);
	this.DemogOptions[cOptionID].parent = this;
	this.DemogOptions[cOptionID].Form = this.Form;
	return this.DemogOptions[cOptionID];
}

// Create a new conditional, where this is the source field
TigerField.prototype.AddConditional = function (cTargetField, nConditionType, ValueList, nActionIfFalse, nActionIfTrue) {
	var i = this.Conditionals.length;
	this.Conditionals[i] = new TigerConditional(this, this.parent.Fields[cTargetField], nConditionType, ValueList, nActionIfFalse, nActionIfTrue);
	this.Conditionals[i].parent = this;
	this.Conditionals[i].Form = this.Form;
	return this.Conditionals[i];
}



// AddFieldElement - method to register a new element relating to the field. ID and type must be specified
TigerField.prototype.AddFieldElement = function (cElementID, nElementType) {
	this.FieldElements[cElementID] = new TigerFieldElement(cElementID, nElementType) ;
	this.FieldElements[cElementID].parent = this;
	this.FieldElements[cElementID].Form = this.Form;
}
