/*
  Creator: Kevin Hastie
  Date: Apr 3, 2006
  Time: 3:45:50 PM
  Contents are property of Cappex.com LLC, and strictly confidential.
*/

/********************************/
/******* DECLARE CLASSES ********/
/********************************/

var HsNameEditor = new Class({

	hsInfo : {hsID : -1, schoolName : '', locationAddr : '', locationCity : '', stateAbbr : '', locationZip : ''}, // contains name/address info for a hs
	loadHSDropdownIndicator : null, // displays while hs dropdown is loading
	loadHSInfoIndicator : null, // displays while hs edit info is loading
	doneHSInfoIndicator : null, // displays while hs edit info is loading
	showDoneIndicator : true, // allows you to skip the doneIndicator animation ONCE (for instance, when the ajax is called automatically when reloading the page on pageError). It is reset to true every time, so it must be set to false each time you call loadHSInfo if you don't want the indicator to show
	ajaxHelper : new AjaxCpx(), // extended Ajax object used only for the buildIndicators. TODOKH: use this object for all of the ajax in this class (in this.loadHSInfo())

	init : function () {
		
		// load HS address info onchange
		$('hsID').addEvent("change", hsNameEditor.loadHSInfo);

		// toggle edit mode and update fields onclick
		$('hsEditLink').addEvent("click", hsNameEditor.toggleEditHS);
		$('hsEditLink').addEvent("click", hsNameEditor.updateHSInfo.bind(hsNameEditor));

		// build ajax indicators
		this.loadHSDropdownIndicator = this.ajaxHelper.buildIndicator('hsID', 'after');
		this.loadHSInfoIndicator = this.ajaxHelper.buildIndicator('hsEditHeader', 'after');
		this.doneHSInfoIndicator = this.ajaxHelper.buildIndicatorDone('hsName', 'after');

		// ajax arrow fx
		this.hsArrowFxBounceIn = this.doneHSInfoIndicator.effects({
			duration: 600,
			transition: Fx.Transitions.bounceOut
		})
		this.hsArrowFxFade = this.doneHSInfoIndicator.effects({
			duration: 3000,
			transition: Fx.Transitions.quintOut
		})

		// enable hs edit fields and load the values into the hsInfo object if editing is enabled
		if (!hsEditDisabled) {
			// load hsInfo object from form
			hsNameEditor.hsInfo.schoolName = $('createGCForm').hsName.value;
			hsNameEditor.hsInfo.locationAddr = $('createGCForm').overrideLocationAddr.value;
			hsNameEditor.hsInfo.locationCity = $('createGCForm').overrideLocationCity.value;
			hsNameEditor.hsInfo.stateAbbr = $('createGCForm').overrideStateAbbr.value;

			hsEditDisabled = !hsEditDisabled; // toggleEditHS will change this value, so first we need to reverse its state so it can be doubly-negated
			this.toggleEditHS();
			
		// otherwise, populate the fields (from an ajax call if a school is selected)
		} else {
			hsNameEditor.showDoneIndicator = false; // don't show the doneIndicator when doing this on pageload
			hsNameEditor.loadHSInfo();
		}

// REMOVEKH: This is now done in updateHSInfo
//		// add event to copy the information from disabled fields to hidden fields on submit so that they will be passed in the post
//		$('createGCForm').addEvent("submit", function() {
//			if (hsEditDisabled) {
//				$('currentHsName').value = $('hsName').value;
//				$('currentLocationAddr').value = $('overrideLocationAddr').value;
//				$('currentLocationCity').value = $('overrideLocationCity').value;
//				$('currentLocationStateAbbr').value = $('overrideStateAbbr').value;
//			}
//		}.bind(this));



		/* Function:
		* 		This will switch which events will be added to what object, when the "is independent" is selected/checked
		*  Notes:
		*  		The first is for GC sign up, since there are radio buttons there.
		*  		The second is for college materials request, which is a check box.
		*/
		if ($$('#isIndependent1').valueOf() != '') {
			$('createGCForm').isIndependent0.addEvent("click", hsNameEditor.showHideHSInfo);
			$('createGCForm').isIndependent1.addEvent("click", hsNameEditor.showHideHSInfo);
		} else if ($$('#isIndependent').valueOf() != '') {
			$('createGCForm').isIndependent.addEvent("click", hsNameEditor.showHideHSInfo);
			$('createGCForm').isIndependent.addEvent("change", hsNameEditor.showHideHSInfo);
		}

		hsNameEditor.showHideHSInfo();

	},

	/**
	 * Check hsID dropdown, and if a school has been selected, load the hs info via an ajax call. Otherwise, clear the info.  Disable/enable fields as appropriate.
	 * @param skipDoneIndicator optional boolean instruction to skip the display of the "done" indicator (for instance, when this is called on domready). Defaults to false. 
	 */
	loadHSInfo: function () {

		if ($('hsID').value > 2) { // a school has been selected (not "My high school is not listed" or "Select High School")

			new AjaxCpx('/hsinfofromid?hsID=' + $('hsID').value, {

				onRequest: function () {
					hsNameEditor.loadHSInfoIndicator.setStyle('display', ''); // show indicator
				},

				onSuccess: function (req) {

					hsNameEditor.hsInfo = Json.evaluate(req); // load the hs name/address info from the ajax call
					hsNameEditor.updateHSInfo(); // update the info in the hs name/address fields
					hsNameEditor.loadHSInfoIndicator.setStyle('display', 'none'); // hide indicator

					if (!hsEditDisabled) { // disable fields
						hsNameEditor.toggleEditHS();
					}

					if (hsNameEditor.showDoneIndicator) {
						hsNameEditor.indicateAjaxChange();
					}
				}
			}).request();

		} else {
			
			hsNameEditor.clearHSInfo();

			if ($('hsID').value == 0 && !hsEditDisabled) { // disable fields if "Enter Zipcode" (before zip has been entered) or "Select High School" (once zip has been entered) has been selected
				hsNameEditor.toggleEditHS();
			} else if ($('hsID').value == 1 && hsEditDisabled) { // enable fields if 1 = "My high school is not listed" has been entered
				hsNameEditor.toggleEditHS();			
			}
		}

		hsNameEditor.showDoneIndicator = true; // ensure that this gets reset to true every time a call to loadHSInfo is made
	},

	/**
	 * Populates the hs edit info fields from the hsInfo object 
	 */
	updateHSInfo : function () {

		// update edit fields
		$('createGCForm').hsName.value = this.hsInfo.schoolName;
		$('createGCForm').overrideLocationAddr.value = this.hsInfo.locationAddr;
		$('createGCForm').overrideLocationCity.value = this.hsInfo.locationCity;
		$('createGCForm').overrideStateAbbr.value = this.hsInfo.stateAbbr;

		// update hidden fields (copy the information to hidden fields on submit so that they will be passed in the post for when the edit fields are disabled (and therefore not passed))
		$('currentHsName').value = $('hsName').value;
		$('currentLocationAddr').value = $('overrideLocationAddr').value;
		$('currentLocationCity').value = $('overrideLocationCity').value;
		$('currentLocationStateAbbr').value = $('overrideStateAbbr').value;

	},

	/**
	 * Clears the hs edit info fields and the hsInfo object 
	 */
	clearHSInfo : function () {
		$('createGCForm').hsName.value = this.hsInfo.schoolName = '';
		$('createGCForm').overrideLocationAddr.value = this.hsInfo.locationAddr = '';
		$('createGCForm').overrideLocationCity.value = this.hsInfo.locationCity = '';
		$('createGCForm').overrideStateAbbr.value = this.hsInfo.stateAbbr = '';

		// clear hidden fields
		$('currentHsName').value = '';
		$('currentLocationAddr').value = '';
		$('currentLocationCity').value = '';
		$('currentLocationStateAbbr').value = '';

	},

	/**
	 * Toggle the editability of the HS edit info fields. Maintains a global var (hsEditDisabled) linked to a hidden field (id=hsEditDisabled),
	 * enables or disables the form fields and controls the highlighting of the fieldset. If the fields are being disabled, it resets
	 * their values from hsInfo (via updateHSInfo()).
	 */	
	toggleEditHS : function () {

		// toggle global var
		hsEditDisabled = !hsEditDisabled;

		// set form field to retain state on error
		$('hsEditDisabled').value = hsEditDisabled;

		// disable/enable form fields
		hsNameEditor.setDisableAllFields('hsAddressFields', hsEditDisabled);

		// add/remove gray disabled background from the fieldset and change link text and hidden fields
		if (hsEditDisabled) {
			$('hsAddressFields').addClass('disabled');
			$('hsEditLink').innerHTML = 'Edit School Info';
		} else {
			$('hsAddressFields').removeClass('disabled');
			$('hsEditLink').innerHTML = 'Undo Changes';
		}
		return false;
	},

	/**
	 * Used to enable/disable all the fields in a container
	 * @param containerID The id of the element containing the fields to be enabled/disabled
	 * @param newState Disable them? 'true' to disable, 'false' to enable.
	 */
	setDisableAllFields : function(containerID, newState) {
		var containerElem = $(containerID);

		var inputElems = containerElem.getElementsByTagName("input");
		var selectElems = containerElem.getElementsByTagName("select");

		$each(inputElems, function (elem) {
			elem.disabled = newState;
		});
		$each(selectElems, function (elem) {
			elem.disabled = newState;
		});

		if (!newState) {

			// delay to attempt to avoid crashing FF (must increase to like 2000ms to do any good:

			(function () {
				try {
					inputElems[0].focus();
				} catch (e) {
					global.handleError(e);
				}
			}).delay(1000);

		}
	},

	/**
	 * Displays the ajax done indicator
	 */
	indicateAjaxChange : function () {
		hsNameEditor.doneHSInfoIndicator.setStyle('display', '');
		hsNameEditor.hsArrowFxBounceIn.stop();
		hsNameEditor.hsArrowFxFade.stop();
		hsNameEditor.hsArrowFxBounceIn.start({
			'width':[84,32],
			'height':[84,32],
			'opacity':[0,1]
		}).chain(function(){hsNameEditor.doHsArrowFxFade.delay(500, hsNameEditor.hsArrowFxFade)});
	},

	/**
	 * Ajax arrow fade (done indicator) stuff
	 */
	hsArrowFxBounceIn : null,
	hsArrowFxFade : null,
	doHsArrowFxFade : function() {
		this.start({
			'opacity':[1,0]
		})
	},

	/**
	 * Hides the Find Your HS section, and shows the IECA/HECA checkboxes on the Create GC Form, or the Mailing Address on College Materials
	 */
	showHideHSInfo : function () {

		// show/enable independent fields
		if ($$('#isIndependent').valueOf() != '' && $('createGCForm').isIndependent.checked) {

				$('findYourHS').addClass('jsHide');
				if ($('hsInfo')) { // college materials page only
					$('independentSubfields').removeClass('jsHide');
					$('hsInfo').disabled = '';
					global.stringUtil.addToDelimitedList('requiredFields', 'hsInfo');
					global.stringUtil.removeFromDelimitedList('requiredFields', 'hsID');
					global.stringUtil.removeFromDelimitedList('requiredFields', 'hsZip');

				}
		} else if ($$('#isIndependent1').valueOf() != '' && ($('createGCForm').isIndependent1.checked)) {
				$('findYourHS').addClass('jsHide');

		// hide/disable independent fields
		} else {
			$('findYourHS').removeClass('jsHide');
			if ($('hsInfo')) { // college materials page only
				$('independentSubfields').addClass('jsHide');
				$('hsInfo').disabled = 'disabled';
				global.stringUtil.removeFromDelimitedList('requiredFields', 'hsInfo');
				global.stringUtil.addToDelimitedList('requiredFields', 'hsID');
				global.stringUtil.addToDelimitedList('requiredFields', 'hsZip');
			}
		}
	}

})

/********************************/
/***** DECLARE GLOBAL VARS ******/
/********************************/

// object that handles all edit name/address functionality
var hsNameEditor = new HsNameEditor();

/********************************/
/******** EVENT HANDLERS ********/
/********************************/

window.addEvent("domready", function() {

	hsNameEditor.init();

	// scroll to edit heading when loading schools
	if (onlyLoadSchools == 'true') {
		var winScroller = new Fx.Scroll(window, {duration : 1});
		winScroller.toElement($('findYourHSHeading'));
	}

});

/********************************/
/********** FUNCTIONS ***********/
/********************************/

/**
 * Displays a loading indicator and submits the form to load schools into the dropdown. 
 */
function loadSchools() {
	hsNameEditor.loadHSDropdownIndicator.setStyle('display', ''); // show indicator
	// now handled by an autoscroll - document.forms.createGCForm.action += "#hsZip";
	// prevent form from processing fully
	document.forms.createGCForm.onlyLoadSchools.value = true;
	document.forms.createGCForm.submit();
}