/**
 * This file contains the JavaScript for manipulating and validating the
 * standard contact info form.
 *
 * @author Daniel J. Summers <daniel@djs-consulting.com>
 * @version $Id: contact.js 222 2010-02-27 23:31:19Z summersd $
 * @package TCMS
 * @subpackage View
 */
var tcmsContact = {

	/**
	 * Fill the link for Google maps from the current address.
	 * 
	 * @param psId The ID of the row to show.
	 */
	fillHref : function(psId) {
	
		// Get the state, and strip off any abbreviation.
		var sState = $(tcms.jqId("txtState" + psId) + " :selected").text();
		sState = tcms.trim(sState.substring(0, sState.indexOf("(")));
	
		// Put together the href attribute.
		var sHref = "http://maps.google.com/maps?q=" 
				+ tcms.trim($(tcms.jqId("txtAddress" + psId)).val()) + "+"
				+ tcms.trim($(tcms.jqId("txtCity"    + psId)).val()) + "+" + sState;
		sHref = sHref.replace(new RegExp(" ", "g"), "+");
	
		// Change the link to point to the appropriate URL.
		$(tcms.jqId("aGoogleMap" + psId)).attr("href", sHref);
	},

	/**
	 * Add a set of address input fields.
	 */
	addAddress : function() {
	
		var oNewRow = tcms.cloneRow("trAddressRow1", "txtNewAddressId");
	
		// Change the "Add" link to a "Delete" one.
		var oTd = oNewRow.getElementsByTagName("td")[4];
	
		oTd.innerHTML = "<br /><a href=\"javascript:void(0);\" "
				+ "onclick=\"javascript: tcmsContact.deleteAddress("
				+ $(tcms.jqId("txtNewAddressId")).val() + ")\">Delete Address</a>";
	
		// Hide the row, append it, and fade it in.
		oNewRow.style.display = "none";
		tcms.getElement("tblAddresses").appendChild(oNewRow);
		$(tcms.jqId(oNewRow.id)).fadeIn();
	
		// Set the default city and state for this organization.
		$(tcms.jqId("txtCity"  + $(tcms.jqId("txtNewAddressId")).val())).val(
				$(tcms.jqId("tcmsDefaultCity" )).val());
		$(tcms.jqId("txtState" + $(tcms.jqId("txtNewAddressId")).val())).val(
				$(tcms.jqId("tcmsDefaultState")).val());
	
		// Check for a second row (Google Maps link).
		if (0 < $(tcms.jqId("trAddressRow2")).length) {
		
			// Clone this one manually since the ID has already been updated.
			var oNewRow2 = tcms.getElement("trAddressRow2").cloneNode(true);
			oNewRow2.id += $(tcms.jqId("txtNewAddressId")).val();
		
			// Update the Google Maps link.
			var oLinkTd = oNewRow2.getElementsByTagName("td")[0];
			oLinkTd.innerHTML = "<a onclick=\"javascript: tcmsContact.fillHref('"
				+ $(tcms.jqId("txtNewAddressId")).val() + "');\" id=\"aGoogleMap"
				+ $(tcms.jqId("txtNewAddressId")).val() + "\" href=\"\" target=\"_blank\">"
				+ "View the Above Address in Google Maps</a>";
		
			// Hide, append, fade in...
			oNewRow2.style.display = "none";
			tcms.getElement("tblAddresses").appendChild(oNewRow2);
			$(tcms.jqId(oNewRow2.id)).fadeIn();
		}
	},

	/**
	 * Delete a set of address input fields.
	 * 
	 * @param psId The ID of the row(s) to remove.
	 */
	deleteAddress : function(psId) {
	
		// Prompt the user.
		if (confirm("Are you sure you wish to delete this address?")) {
			// Removing the row will take all the children with it.
			$(tcms.jqId("trAddressRow1" + psId)).fadeOut();
			$(tcms.jqId("trAddressRow1" + psId)).remove();
			if (0 < $(tcms.jqId("trAddressRow2" + psId)).length) {
				// Remove the Google Maps link row too.
				$(tcms.jqId("trAddressRow2" + psId)).fadeOut();
				$(tcms.jqId("trAddressRow2" + psId)).remove();
			}
		}
	},

	/**
	 * Add a set of phone number input fields.
	 */
	addPhone : function() {
	
		var oNewRow = tcms.cloneRow("trPhoneRow", "txtNewPhoneId");
	
		// Change the "Add" link to a "Delete" one.  (Phones with comments will have 6 columns,
		// those without have 5.)
		var oTd = oNewRow.getElementsByTagName("td")[oNewRow.getElementsByTagName("td").length - 1];
	
		oTd.innerHTML = "<br /><a href=\"javascript:void(0);\" "
				+ "onclick=\"javascript: tcmsContact.deletePhone('"
				+ $(tcms.jqId("txtNewPhoneId")).val() + "')\">Delete Phone</a>";
	
		// Hide the row, append it, and fade it in.
		oNewRow.style.display = "none";
		tcms.getElement("tblPhoneNumbers").appendChild(oNewRow);
		$(tcms.jqId(oNewRow.id)).fadeIn();
	
		// Set the area code to the default for this organization.
		$(tcms.jqId("txtAreaCode" + $(tcms.jqId("txtNewPhoneId")).val())).val(
				$(tcms.jqId("tcmsDefaultAreaCode")).val());
	},

	/**
	 * Delete a set of phone number input fields.
	 * 
	 * @param psId The ID of the row to remove.
	 */
	deletePhone : function(psId) {
	
		// Prompt the user.
		if (confirm("Are you sure you wish to delete this phone number?")) {
			// Removing the row will take all the children with it.
			$(tcms.jqId("trPhoneRow" + psId)).fadeOut();
			$(tcms.jqId("trPhoneRow" + psId)).remove();
		}
	},

	/**
	 * Add a set of e-mail address input fields.
	 */
	addEmail : function() {
	
		var oNewRow = tcms.cloneRow("trEmailAddressRow", "txtNewEmailId");
	
		// Change the "Add" link to a "Delete" one.
		var oTd = oNewRow.getElementsByTagName("td")[oNewRow.getElementsByTagName("td").length - 1];
	
		oTd.innerHTML = "<br /><a href=\"javascript:void(0);\" "
				+ "onclick=\"javascript: tcmsContact.deleteEmail('"
				+ $(tcms.jqId("txtNewEmailId")).val() + "')\">Delete E-mail Address</a>";
	
		// Hide the row, append it, and fade it in.
		oNewRow.style.display = "none";
		tcms.getElement("tblEmailAddresses").appendChild(oNewRow);
		$(tcms.jqId(oNewRow.id)).fadeIn();
	},

	/**
	 * Delete a set of e-mail address input fields.
	 * 
	 * @param psId The ID of the row to remove.
	 */
	deleteEmail : function(psId) {
	
		// Prompt the user.
		if (confirm("Are you sure you wish to delete this e-mail address?")) {
			// Removing the row will take all the children with it.
			$(tcms.jqId("trEmailAddressRow" + psId)).fadeOut();
			$(tcms.jqId("trEmailAddressRow" + psId)).remove();
		}
	},

	/**
	 * Ensure that contact information is valid.
	 *
	 * @return True if it's good, false if not.
	 */
	validateContact : function() {
	
		// At least one address is required.
		if (!this.validateAddresses()) {
			return false;
		}
	
		// At least one phone or e-mail address is required.
		if (!this.validatePhoneAndEmail()) {
			return false;
		}
	
		return true;
	},

	/**
	 * Ensure that addresses are valid.
	 * 
	 * @return True if good, false if not.
	 */
	validateAddresses : function() {
	
		var iFilledAddresses = 0;
		var oAddresses = document.getElementsByName("contactAddressId[]");
	
		for (var iIndex = 0; iIndex < oAddresses.length; iIndex++) {
			var iResult = 0;
			if ("-1" == oAddresses[iIndex].value) {
				iResult = this.validateAddress("");
			}
			else {
				iResult = this.validateAddress(oAddresses[iIndex].value);
			}
			if (-1 == iResult) {
				return false;
			}
			iFilledAddresses += iResult;
		}
	
		// Check for any addresses entered.
		if (0 == iFilledAddresses) {
			alert("You must enter at least one address");
			return false;
		}
	
		// Check for required physical address.
		if ("true" == $(tcms.jqId("physicalRequired")).val()) {
			var iPhysicalAddresses = 0;
			for (var iIndex = 0; iIndex < oAddresses.length; iIndex++) {
				if (("-1" == oAddresses[iIndex].value)
						&& ($(tcms.jqId("chkPhysical")).is(":checked"))) {
					iPhysicalAddresses++;
				}
				else {
					if ($(tcms.jqId("chkPhysical" + oAddresses[iIndex].value)).is(":checked")) {
						iPhysicalAddresses++;
					}
				}
			}
			if (0 == iPhysicalAddresses) {
				alert("You must enter at least one physical address for this entry.");
				return false;
			}
		}
	
		// Check for required mailing address.
		if ("true" == $(tcms.jqId("mailingRequired")).val()) {
			var iMailingAddresses = 0;
			for (var iIndex = 0; iIndex < oAddresses.length; iIndex++) {
				if (("-1" == oAddresses[iIndex].value)
						&& ($(tcms.jqId("chkMailing")).is(":checked"))) {
					iMailingAddresses++;
				}
				else {
					if ($(tcms.jqId("chkMailing" + oAddresses[iIndex].value)).is(":checked")) {
						iMailingAddresses++;
					}
				}
			}
			if (0 == iMailingAddresses) {
				alert("You must enter at least one mailing address for this entry.");
				return false;
			}
		}
	
		return true;
	},

	/**
	 * Ensure that a specific address is valid.
	 * 
	 * @param psId The ID of the fields to check.
	 * @return integer 1 if good, 0 if empty, -1 if no good.
	 */
	validateAddress : function(psId) {
	
		// Check for an empty entry.
		if (this.isEmptyAddress(psId)) {
			return 0;
		}
	
		// Address is a required entry.
		if (!tcms.validateString("txtAddress" + psId, "You must enter an address.")) {
			return -1;
		}
		// City is a required entry.
		if (!tcms.validateString("txtCity" + psId, "You must enter a city.")) {
			return -1;
		}
		// State is a required entry.
		if (!tcms.validateDropdown("txtState" + psId, "You must select a state.")) {
			return -1;
		}
		// ZIP code is a required entry.
		if (!tcms.validateString("txtZip" + psId, "You must enter a ZIP code.")) {
			return -1;
		}
	
		// Ensure at least one of "Physical" or "Mailing" is checked.
		if ((!$(tcms.jqId("chkPhysical" + psId)).is(":checked"))
				&& (!$(tcms.jqId("chkMailing" + psId)).is(":checked"))) {
			tcms.errorField("txtAddress" + psId,
					"You must identify this address as physical, mailing, or both.");
			return -1;
		}
		else {
			tcms.validField("txtAddress" + psId);
		}
	
		// Set a hidden field for address type; checkboxes aren't submitted if they're empty.
		if (($(tcms.jqId("chkPhysical" + psId)).is(":checked"))
				&& ($(tcms.jqId("chkMailing" + psId)).is(":checked"))) {
			$(tcms.jqId("txtAddressType" + psId)).val("B");
		}
		else if ($(tcms.jqId("chkPhysical" + psId)).is(":checked")) {
			$(tcms.jqId("txtAddressType" + psId)).val("P");
		}
		else {
			$(tcms.jqId("txtAddressType" + psId)).val("M");
		}
	
		// It's good!
		return 1;
	},

	/**
	 * Check for an empty address.
	 * 
	 * @param psId The ID of the fields to check.
	 * @return True if the address is empty, false if not.
	 */
	isEmptyAddress : function(psId) {
	
		return (   (""                                      == tcms.trim($(tcms.jqId("txtAddress" + psId)).val()))
				&& (($(tcms.jqId("tcmsDefaultCity" )).val() ==           $(tcms.jqId("txtCity"    + psId)).val())
						|| (""                              ==           $(tcms.jqId("txtCity"    + psId)).val()))
				&& (($(tcms.jqId("tcmsDefaultState")).val() ==           $(tcms.jqId("txtState"   + psId)).val())
						|| ("0"                             ==           $(tcms.jqId("txtState"   + psId)).val()))
				&& (""                                      == tcms.trim($(tcms.jqId("txtZip"     + psId)).val()))
				&& (!$(tcms.jqId("chkPhysical" + psId)).is(":checked"))
				&& (!$(tcms.jqId("chkMailing"  + psId)).is(":checked")));
	},

	/**
	 * Ensure that the user has entered at least one phone number or one e-mail address, and
	 * confirm if they have not entered any of a given type.
	 *
	 * @return True if phone and e-mail are good (or confirmed good), false if not.
	 */
	validatePhoneAndEmail : function() {
	
		var iFilledPhones = 0;
		var iFilledEmails = 0;
	
		// Validate all phone numbers.
		var oPhones = document.getElementsByName("contactPhoneId[]");
		for (var iIndex = 0; iIndex < oPhones.length; iIndex++) {
			var iResult = 0;
			if ("-1" == oPhones[iIndex].value) {
				iResult = this.validatePhone("");
			}
			else {
				iResult = this.validatePhone(oPhones[iIndex].value);
			}
			if (-1 == iResult) {
				return false;
			}
			iFilledPhones += iResult;
		}
	
		// Validate all e-mail addresses.
		var oEmails = document.getElementsByName("contactEmailId[]");
		for (var iIndex = 0; iIndex < oEmails.length; iIndex++) {
			var iResult = 0;
			if ("-1" == oEmails[iIndex].value) {
				iResult = this.validateEmail("");
			}
			else {
				iResult = this.validateEmail(oEmails[iIndex].value);
			}
			if (-1 == iResult) {
				return false;
			}
			iFilledEmails += iResult;
		}
	
		if (0 == (iFilledPhones + iFilledEmails)) {
			// No phone AND no e-mail has been entered.
			alert("You have not entered any phone numbers or e-mail addresses.  At least one "
					+ "between the two is required.");
			$(tcms.jqId("txtExchange")).focus();
			return false;
		}
	
		if (0 == iFilledPhones) {
			// No phone has been entered.
			if (!confirm("You have not entered any phone numbers.  Are you sure this is what "
					+ "you mean to do?")) {
				return false;
			}
		}
	
		if ((0 == iFilledEmails) && ("true" == $(tcms.jqId("emailRequired")).val())) {
			// No e-mail address has been entered.
			if (!confirm("You have not entered any e-mail addresses.  Without these, the system "
					+ "will not be able to automatically notify the individual.  Are you sure "
					+ "this is what you mean to do?")) {
				return false;
			}
		}
	
		return true;
	},

	/**
	 * Validate a phone number.
	 *
	 * @param psId The ID for this set of fields.
	 * @return integer 1 if good, 0 if empty, -1 if no good.
	 */
	validatePhone : function(psId) {
	
		if (this.isEmptyPhone(psId)) {
			return 0;
		}
	
		// Validate the area code.
		if (!tcms.validateNumericString("txtAreaCode" + psId, 3,
				"The area code entered is not valid")) {
			return -1;
		}
	
		// Validate the exchange.
		if (!tcms.validateNumericString("txtExchange" + psId, 3,
				"The first part of the phone number is not valid.")) {
			return -1;
		}
	
		// Validate the number.
		if (!tcms.validateNumericString("txtNumber" + psId, 4,
				"The second part of the phone number is not valid.")) {
			return -1;
		}
	
		// Validate the extension, if entered.
		if ("" != tcms.trim($(tcms.jqId("txtExtension" + psId)).val())) {
			if (!tcms.validateNumericString("txtExtension" + psId,
					$(tcms.jqId("txtExtension" + psId)).val().length,
					"The extension is not valid.")) {
				return -1;
			}
		}
	
		// Make sure a type has been selected.
		if (!tcms.validateDropdown("txtPhoneType" + psId, "You must select a phone type.")) {
			return -1;
		}
	
		return 1;
	},

	/**
	 * Determine if a phone number is empty.
	 * 
	 * @param psId The ID for this set of phone number fields.
	 * @return True if empty, false if not.
	 */
	isEmptyPhone : function(psId) {
	
		return ((($(tcms.jqId("tcmsDefaultAreaCode")).val() ==           $(tcms.jqId("txtAreaCode"  + psId)).val())
						|| (""                              == tcms.trim($(tcms.jqId("txtAreaCode"  + psId)).val())))
				&& (""                                      == tcms.trim($(tcms.jqId("txtExchange"  + psId)).val()))
				&& (""                                      == tcms.trim($(tcms.jqId("txtNumber"    + psId)).val()))
				&& (""                                      == tcms.trim($(tcms.jqId("txtExtension" + psId)).val()))
				&& ("0"                                     ==           $(tcms.jqId("txtPhoneType" + psId)).val()));
	},

	/**
	 * Validate an e-mail address.
	 *
	 * @param psId The ID for this set of input fields.
	 * @return integer 1 if good, 0 if empty, -1 if no good.
	 */
	validateEmail : function(psId) {
	
		if (this.isEmptyEmail(psId)) {
			return 0;
		}
	
		// Make sure an e-mail address has been entered.
		if (!tcms.validateString("txtEmail" + psId, "You must enter an e-mail address.")) {
			return -1;
		}
	
		// Make sure that the e-mail address is valid.
		var sEmail = $(tcms.jqId("txtEmail" + psId)).val();
		if ((0 > sEmail.indexOf("@"))
				|| (0 > sEmail.substring(sEmail.indexOf("@")).indexOf("."))) {
			tcms.errorField("txtEmail" + psId, "The e-mail address is not valid - "
					+ "it must be in the form of \"name@example.com\".");
			return -1;
		}
		else {
			tcms.validField("txtEmail" + psId);
		}
	
		// Make sure a type has been selected.
		if (!tcms.validateDropdown("txtEmailType" + psId,
				"You must select an e-mail address type.")) {
			return -1;
		}
	
		return 1;
	},

	/**
	 * Determine if a set of e-mail address entry fields is empty.
	 * 
	 * @param psId The ID for this set of input fields.
	 * @return boolean True if empty, false if not.
	 */
	isEmptyEmail : function(psId) {
	
		return (   (""  == $(tcms.jqId("txtEmail"     + psId)).val())
				&& ("0" == $(tcms.jqId("txtEmailType" + psId)).val()));
	}
};
