/**
* Application specific JS code
*
* Built with mootools 1.2b Should be compatible with Full 1.2 once complete.
*
* Documentation at: http://docs12b.mootools.net/
*
* NOT compatible with 1.1  uses too many new shortcuts and wide use of CSS3 selectors / Element.Storage
* 
* @revision $Rev: 6 $
*/
var MAYTREE = {};

/**
 * Loader.  
 *
 * Runs init() method on each child object.
 */
MAYTREE.init = function() {
	var htmlEl = document.getElementsByTagName('html');
	htmlEl[0].className = 'js';
	for (prop in this) {
		if (typeof this[prop].init == 'function') {
			this[prop].init();
		}
	}
}

/**
 * General Form highlighting and help box showing.
 *
 */
MAYTREE.forms = {
	init : function() {
		$$('input[type=text], input[type=radio], input[type=password], textarea, select').each(function(item){
			this.activate(item);	
		}.bind(this));		
	},
	
	//Activate Form field highlighting
	activate : function(element){
		element.addEvents({
			'focus' : this.active,
			'blur' : this.deactive
		});	
		element.getParent().addEvents({
			'mouseenter' : this.active.bind(element),
			'mouseleave' : this.deactive.bind(element)
		});
	},
	//highlights on
	active : function(){
		var parent = this.getParent();
		parent.addClass('active');		
		var fieldHint = parent.getChildren('.field-hint');
		if (fieldHint) {
			fieldHint.set('tween', {duration: 250});
			fieldHint.tween('opacity', 1);	
		}
	},

	//hightlights off
	deactive : function(event){
		var parent = this.getParent();
		parent.removeClass('active');		
		var fieldHint = parent.getChildren('.field-hint');
		if (fieldHint) {			
			fieldHint.tween('opacity', 0);
		}
	}
	
};

/**
 * Create interactive Multi row forms. 
 *
 * Implements Templates and MultiForm Classes.
 *
 *
 */
MAYTREE.templates = {
	init : function() {
		//Callback to activate form helpers on form widgets.
		var activateCallback = function() {
			var inputs = $(this).getElements('input[type=text], select');
			for (i=0; i < inputs.length; i++) {
				MAYTREE.forms.activate(inputs[i]);
			}
		}
		//Board experience and governance training callbacks		
		var boardHelpCallback = function () {
			var helpBox = $('board-exp-helper').removeClass('hide');
		}
		var govHelpCallback = function () {
			var helpBox = $('gov-train-helper').removeClass('hide');
		}
		
		if ($('gov-training-template')) {
			var count = $('gov-training-container').getElements('.line-block').length;
			var govForm = new multiForm('gov-training-template', { 
					addButton : 'add-gov-train',
					container : 'gov-training-container',
					counter : count,
					onComplete : activateCallback,
					onFirst : govHelpCallback
			});
		}		
		if ($('board-exp-template')) {
			var count = $('board-exp-container').getElements('.line-block').length;
			//Use Callback to attach events to append Element block
			var boardForm = new multiForm('board-exp-template', { 
					addButton : 'add-board-exp',
					container : 'board-exp-container',
					counter : count,
					onComplete : activateCallback,
					onFirst : boardHelpCallback
			});	
		}
	}	
};

/**
 * Collapsing Elements 
 *
 * Creates widgets that slide open and closed on a button event
 *
 */
MAYTREE.collapsers = {
	init : function() {
		$$('.collapse .content').each(function(panel){
			var panelHeight = panel.getStyle('height');
			panel.store('originalHeight', panelHeight);
			var panelFx = new Fx.Tween(panel, {duration: 'short'});
			panelFx.set('height', 0);
			panel.store('closed', true);
			
			var button = panel.getParent().getElement('a.view');
			button.addEvent('click', function(e) {
				e = new Event(e).stop();
				//use closure reference to copy to local scope
				var _panel = panel;
				var _panelFx = panelFx;
				if (_panel.retrieve('closed')) {
					var nextHeight = _panel.retrieve('originalHeight');
					_panel.store('closed', false);	
				} else {
					var nextHeight = 0;
					_panel.store('closed', true);
				}
				_panelFx.start('height', nextHeight);					
			})
		});	
	}
};
/**
 * Quick Search 
 *
 * Has Cookie to remember open / closed state
 *
 */
MAYTREE.quickSearch = {
	cookieLife : 100,
	init : function(){
		var quickSearch = $('quick-search');
		if (!quickSearch) return false;
		this.Cookie = new AjaxTools.Cookie( {name : 'quickSearch'});
		
		//check for quicksearch cookie
		var state = this.Cookie.read('quickSearch')
		if (state == false || state == 'open') {
			var panel = quickSearch.getElement('div.content');
			var originalHeight = panel.retrieve('originalHeight');
			panel.setStyle('height', originalHeight);
		}		
		//assign button handlers to write cookies for quick search.
		quickSearch.getElement('.summary-header a.view').addEvent('click', this.remember);
	},
	remember: function(e){
		var panel = this.getParent().getNext();
		var state = (panel.retrieve('closed')) ? 'closed' : 'open';
		MAYTREE.quickSearch.Cookie.write('quickSearch', state);
	}
};
/** 
 * Creating Position interactive element 
 * for residency requirements
 *
 */
MAYTREE.residencyRequirement = {
	init : function() {
		var selector = $('PositionResidencyRequirementType');
		if (!selector) {
			return;
		}
		var options = {
			update : 'PositionResidencyRequirementValue',
			onComplete : MAYTREE.residencyRequirement.showBox,
			onRequest : MAYTREE.residencyRequirement.hideBox		
		};
		var requestObj = new Request.HTML(options);
		selector.addEvent('change', function() {
			var url = selector.getProperty('rel') + this.value;
			requestObj.get(url);
			if (selector.value == 'none') {
				$(options.update).set('disabled', 'disabled');
			} else {
				$(options.update).set('disabled', '');
			}
		});
	},
	showBox : function(responseTree, responseElements, responseHtml, responseJavascript) {
		var targetBox = $(this.options.update);
		AjaxTools.unDim(targetBox.getParent());
		targetBox.getParent().fade('in');		
	},
	hideBox : function(request) {
		var targetBox = $(this.options.update);
		AjaxTools.dim(targetBox.getParent());
	}
};

/**
 * Applicant requesting additional 
 * information about position
 *
 */
MAYTREE.positionInfo = {
	init : function() {
		var button = $('get-position-info-button');
		if (button == null) {
			return;
		}
		var container = $('position-contact-info');		 
		var options = {
			url : button.getProperty('href'),
			update : 'position-contact-info'	
		};
		
		button.addEvent('click', function(e) {
			AjaxTools.dim(container);
			AjaxTools.link(e, this, options);
		});
	}	
};

/**
 * Add An Applicant to a positions list of people 
 * uses XHR.
 *
 */
MAYTREE.addApplicant = {
	init : function() {
		var form = $('get-applicant-info');
		if (form == null) {
			return;
		}
		var container = $('applicant-contact-info');		 
		var options = {
			url : form.get('action'),
			method : form.get('method'),
			update : 'applicant-contact-info',
			onComplete : function() {}	
		};
		
		form.addEvent('submit', function(e) {
			e = new Event(e).stop();
			AjaxTools.dim(container);
			this.get('load', options);
			this.load();
		});
	}

};


/**
 * Closing a Position
 *
 */
MAYTREE.closePosition = {
	init : function() {
		var form = $('position-close-reason');
		if (form == null) {
			return
		}
		var radioButtons = form.getElements('input[type=radio]');
		for (var i = 0; i < radioButtons.length; i++) {
			var radio = radioButtons[i];
			radio.addEvent('click', function(e) {
				MAYTREE.closePosition.handleRadio(this, form);
			});
		}
	},
	/**
	* Handle the radio button click and 
	* dispatch to the sub event.
	*/
	handleRadio : function(element, form) {
		var value = element.value;
		this.containerEl = $('close-type-selection');
		this.containerEl.empty();
		switch (value) {
			case '1':
				MAYTREE.closePosition.withdrawn(form);
			break;
			case '2':
				MAYTREE.closePosition.nonMaytree(form);
			break;
			case '3':
				MAYTREE.closePosition.applicant(form);
			break;		
		}
	},
	/**
	* Position has been withdrawn show reason box.
	*/
	withdrawn : function(form) {
		var textBox = $('close-reason-withdrawn').getParent().clone();
		this.containerEl.adopt(textBox);
	},
	/**
	 * non Maytree applicant chosen do nothing.
	 *
	 */
	nonMaytree : function(form) {
		// do nothing.
	},
	/**
	* Applicant has been chosen. Do fancy things.
	*/
	applicant : function(form) {
		var radioSets = $('related-maytree-applicants').clone();
		this.containerEl.adopt(radioSets);
		
		var radioTable = radioSets.getElement('tbody');
		
		var completerElement = radioSets.getElement('.auto-complete');
		new Autocompleter.Request.HTML(completerElement, window.baseURL + '/applicants/lastNameSearch', {
			'indicatorClass' : 'autocompleter-loading',
			'postVar' : 'data[Applicant][last_name]',
			'injectChoice' : function(choice) {
				var text = choice.getFirst().get('text');
				choice.inputValue = text;
				this.addChoiceEvents(choice);
			},
			'onSelection' : function(input, selection, currentValue, selectedValue) {
				MAYTREE.closePosition.addRow(radioTable, selection);
				input.set('value', '');
			}
		});
	},
	/**
	 * Add a new row to the table and select it.
	 */
	addRow : function(tableElement, applicantElement) {
		var existingHTML = tableElement.get('html');
		var applicantId = applicantElement.getLast().getElement('.id').get('text');
		var templateVars = {
			'name' : applicantElement.getFirst().get('text'),
			'email' : applicantElement.getLast().getElement('.email').get('text'),
			'phone' : applicantElement.getLast().getElement('.phone').get('text'),
			'input' : '<input type="radio" name="data[Applicant][id]" value="' + applicantId + '" id="ApplicantId' + applicantId + '" />'
		};
		//Build table as new Elements as IE will not allow innerHTML use on <table>
		var row = new Element('tr').adopt(
				new Element('td', {'html' : templateVars.input})
			).adopt(
				new Element('td', {'text' : templateVars.name})
			).adopt(
				new Element('td', {'text' : templateVars.email})
			).adopt(
				new Element('td', {'text' : templateVars.phone})
		);
		tableElement.adopt(row);
		$('ApplicantId' + applicantId).set('checked', true);
	}
};

/**
 * Attach Wysiwyg Editors.
 *
 */
MAYTREE.editors = {
	init : function() {
		if ($type(Element.mooEditable) == 'function') {
			var editors = $$('.moo-editable').mooEditable( {
					buttons: 'bold,italic,|,insertunorderedlist,insertorderedlist,indent,outdent,|,undo,redo,|,toggleview'
			});
		} 	
	} 
}


/**
 * Create Drag and drops for Reports and graphs.
 *
 */
MAYTREE.reports = {
	sortTables : [],
	tables : [],
	counter : 0,
	
 	init : function() {
 		var dest = $('graphs-destination-box');
 		var source = $('graphs-source-box');
 		if (!dest || !source) {
 			return 
 		}
 		var tables = $$('table.drag-table');
 		this.tables = tables;
 		for (var i = 0, len = tables.length; i < len; i++) {
 			var table = tables[i];
 			this.initTable(table);
 		}
 		
 		source.getElements('div').each(function(element){
 			new Drag.Move(element, {
 				droppables : this.tables[0], 				
 				onDrop : function(el, drop) {				
 					var newRow = MAYTREE.reports.makeRow(el);
 					MAYTREE.reports.addRow(newRow); 					
 					drop.getElement('tbody').adopt(newRow);
 					el.destroy();
 				}
 				
 			}); 			
 		}, this);
 	}, 	
 /**
  * Attach events and create sortable list.
  *
  */
 	initTable : function(tableEl) {
 		var tableRows = tableEl.getElement('tbody');
 		this.sortTables.push(new WeightTable(tableRows));
 		
 		tableRows.getChildren().each(function(row) {
 			row.getElement('a.remove-row').addEvent('click', this.removeRow);
 		}, this);
 		
 		this.counter = tableRows.getChildren().length;
 	},
 	
/**
 * Delete a row from the table sorter and remove the elements.
 *
 */
 	removeRow : function(e) {
 		e = new Event(e).stop();
 		MAYTREE.reports.sortTables[0].removeItems(this.getParent().getParent()).destroy();
 	},
 	
 /**
  * Make a new Row.
  */
 	makeRow : function(el, id) { 	 	
 		var newRow = new Element('tr').adopt(
			new Element('td', {
				'text' : el.getFirst().get('text')
			}).adopt(
				new Element('input', {
					'type' : 'hidden',
					'name' : 'data[GraphsReport][' + this.counter + '][graph_id]',
					'value' : el.getLast().get('text')
				}) 
			)					
		);
		newRow.adopt(
			new Element('td').adopt(
				new Element('input', {
					'type' : 'text',
					'name' : 'data[GraphsReport][' + this.counter + '][weight]',
					'class' : 'weight',
					'value' : 0
				}))
		);
		newRow.adopt(
			new Element('td').adopt(
				new Element('a', {
					'href' : '#',
					'class' : 'remove-row',
					'text' : 'Remove from report'
				}))
		);
		this.counter++;
		return newRow;
 	},
 /**
 * Add a Row to the sortables list and add extra events.
 *
 */
 	addRow : function(row) {
 		row.getElement('a.remove-row').addEvent('click', this.removeRow);
 		this.sortTables[0].addRow(row);
 	}
 	
}

/**
 * Text Area / input count down elements.
 *
 */
 MAYTREE.textCounter = {
 	init : function() {
 		$$('.letter-count-down .counter').each(function(counter) {
 			var textbox = counter.getParent().getParent().getElement('textarea');
 			
 			textbox.addEvent('keyup', function() {
 				MAYTREE.textCounter.updateTotal(this, counter);
 			});
 			this.updateTotal(textbox, counter);
 		}, this);
 	},
 	updateTotal : function(textarea, counter) {
 		var maxLength = textarea.get('maxLength');
 		var currentLength = textarea.get('value').length;
 		if (currentLength >= maxLength) {
 			textarea.value = textarea.get('value').substring(0, maxLength);
 			counter.set('text', 0);	
 		} else {
 			counter.set('text', maxLength - currentLength);
 		}
 	} 
 };


/**
 * Attach Window Event and load everything
 *
 */
window.addEvent('domready', function() {
	MAYTREE.init();
});
