// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var tDay=new Date();
var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
//Ensure correct for language. English is "January 1, 2004"
var tDateStamp = monthname[tDay.getMonth()] + " " + tDay.getDate() + ", " + tDay.getFullYear();
//---------------   END LOCALIZEABLE   ---------------
/* control hover */
/*operations*/
var navOver = function(e) {
	var elt = Event.element(e);
	if(elt = firstAncestorOfClass(elt,'nav-btn'))
	{elt.addClassName('hover');}
}
var navOut = function(e) {
	var elt = Event.element(e);
	if(elt = firstAncestorOfClass(elt,'nav-btn'))
	{elt.removeClassName('hover');}
}
/* dom navigation */
function firstAncestorOfClass(element, ancestorClass)
{
	element = $(element);
  if (element.className.match(ancestorClass)) return element;
	while (element = element.parentNode)
		if (element.className.match(ancestorClass)) return element;
	return null;
}

function firstAncestorOfType(element, ancestorType)
{
	element = $(element);
	if (element.nodeName == ancestorType) return element;
	while (element = element.parentNode)
		if (element.nodeName == ancestorType) return element;
	return null;
}


var fieldTo = function(frmid,toid){
	if($(toid).empty() && $(toid).value.length < 1){
		$(toid).value = $F(frmid);
	}
}
//----------------------------------------------------
var mrcAddNew = function(select) {

}
var mrcConvertToBackgroundCall = function(lnk) {
	var url = lnk.href;
	lnk.href = ('#' + lnk.title).replace(' ', '_')
	var rel = lnk.rel

	var backgroundCall = function(e){
		Event.stop(e);  

		$('registration-wait').style.top = (e.clientY - 22) + 'px';
		$('registration-wait').style.left = (e.clientX - 11) + 'px';
		
		new mrcBackgroundCall(url,rel);
		return false;
	}

	Event.observe(lnk, 'click', backgroundCall.bindAsEventListener(this) );
}

var mrcBackgroundCall = function(href,rel) {
	$('da-blur').show();
	$('registration-wait').show();
	if( $('registration-agent').style.display != 'none'){
		Effect.Fade('registration-agent', { duration: 0.5 });
	}

	var oLinkOptions = {  
		method: "GET",  
		asynchronous: true,  
		onFailure: mrcShowErrXHR,  
		on200: mrcMagicFill,
		on204: mrcMagicHide,
		on205: function(oXHR) { document.location.reload(); }
	};  

	var oRequest = new Ajax.Request(href, oLinkOptions);
	return false;
}

var mrcMagicFill = function(oXHR){
	$('registration-wait').hide();
	$('registration-box').update(oXHR.responseText);
	Effect.Appear('registration-agent', { duration: 0.5 });
	$$('#registration-box .dyno-mite').each( function(btn){new ajaxyRegForm(btn)} );
	$$('#registration-box .form-cancel').each( mrcConvertToBackgroundCall );
	new ajaxyRegForm($('training_registration_submit'));
	return false;
}

var mrcMagicHide = function() {
	$('registration-wait').hide();
	$('registration-agent').hide();
	$('da-blur').hide();
}


var mrcShowErrXHR = function(oXHR){
	$('notice').update('ERR: ' + oXHR.statusText);
	$('registration-wait').hide();
	$('registration-agent').hide();
	$('notice').show();
}

/* ============================================================= */
var WHSGrowSelect = Class.create();
WHSGrowSelect.prototype = {
	initialize: function(link) {
		this._link = $(link);
		this._href = this._link.href;
		this._sel  = $(this._link.rel);
		this._form = null;
		link.href = ('#' + link.title).replace(' ', '_')
		link.onclick = function() {return false;};

//		this._link.observe( 'click', this.whsOpenDialog.bindAsEventListener(this) );
		Event.observe( this._link, 'click', this.whsOpenDialog.bindAsEventListener(this) );
	},

	_busyOn: function() {
		$('da-blur').show();
		$('registration-wait').show();
		if( $('registration-agent').style.display != 'none'){
			Effect.Fade('registration-agent', { duration: 0.5 });
		}
	},

	// _rewireForm: function(){
	// 	$$('#registration-box .dyno-mite-not').each( function( obj ) {
	// 		Event.observe(obj, 'click', this.closeDialog.bindAsEventListener(this));
	// 	} );
	// 	$$('#registration-box .dyno-mite').each( function( obj ) {
	// 		this._form = $(obj.form);
	// 		obj.form.onsubmit = function() {return false;}
	// 		Event.observe(obj, 'click', this.sendForm.bindAsEventListener(this,obj.form) );
	// 	} );
	// },

	whsOpenDialog: function(e) {
		window.whsDialog = this;
		this.key_listener = this.dialogKeyHandler.bind(this)
		Event.observe(document, 'keypress', this.key_listener);

		this._busyOn();

		new Ajax.Request(
			this._href, {
				method: "GET",
				asynchronous: true,
				parameters: 'reload=' + Math.random()*100,
				onFailure: this.showErrXHR.bind(this),
				onException: this.showErrXHR.bind(this),
				onComplete:this._handleResponse.bind(this)
			}
		);
		return false;
	},

	_handleResponse: function(oXHR) {
		switch (oXHR.status) {
			case 200:
				window.whsDialog.populateDialog(oXHR);
				break;
			case 201:
				window.whsDialog.extendSelect(oXHR);
				break;
			case 205:
				window.whsDialog.pageReload();
				break;
			default:
				window.whsDialog.closeDialog();
				break;
		}
	},

	populateDialog: function(oXHR){
		$('registration-wait').hide();
		$('registration-box').update(oXHR.responseText);
		Effect.Appear('registration-agent', { duration: 0.5 });
		$$('#registration-box .dyno-mite-not').each( function( obj ) {
			obj.observe('click', window.whsDialog.closeDialog.bind(window.whsDialog));
		} );
		$$('#registration-box .dyno-mite').each( function( obj ) {
			window.whsDialog._form = $(obj.form);
			obj.form.onsubmit = function() {return false;}
			Event.observe(obj, 'click', window.whsDialog.sendForm.bind(window.whsDialog) );
		} );
		$$('#registration-box form').each( function( form ) {
			form.focus(); 
			var element = $(form).getElements().detect(function(element) {
	      return 'hidden' != element.type && !element.disabled;
	    });
			element.focus();
			// alert('Element : ' + element.id)
		} );
	},

	sendForm: function(e,daForm){
		// we stop the default submit behaviour
		Event.stop(e);
		$('registration-wait').show();
		if( $('registration-agent').style.display != 'none'){
			Effect.Fade('registration-agent', { duration: 0.5 });
		}
		new Ajax.Request(
			this._form.action, {
				method: "POST",
				parameters: this._form.serialize(),
				asynchronous: true,
				onFailure: mrcShowErrXHR,
				onComplete:this._handleResponse.bind(this)
			}
		);
		return false;
	},

	extendSelect: function(oXHR) {
		str = oXHR.responseText;
		divide = str.lastIndexOf("\t");
		if(divide > 0) {
			optName = str.substr(0,divide);
			optVal  = str.substr(divide+1);
			var new_option = new Option(optName, optVal, false, true);
			var opt_groups = this._sel.getElementsByTagName("optgroup");
			switch(opt_groups.length) {
				case 0:
					// regular select--just append option
					this._sel.options[this._sel.options.length] = new_option;
					break;
				case 1:
				// grouped select -- but one one group, so append option to it
					opt_groups[0].appendChild(new_option);
					break;
				default:
					// its complicated. Create new group and insert option there--unless new group exists
					var needs_new_group = true;
					var new_label = "My New Choices";
					for (var i = 0; i < opt_groups.length; i++) {
						if( opt_groups[i].label == new_label ) {
							needs_new_group = false;
							new_group.appendChild(new_option);
							break;
						}
					}
					if (needs_new_group) {
						new_group = document.createElement("optgroup");
						new_group.label = new_label;
						new_group.appendChild(new_option);
						this._sel.appendChild(new_group);
					}
			}
			this.closeDialog(null);
		}else{
			alert("Could not new location. Reload the page or try again.\nError: " + oXHR.responseText)
		}
	},

	closeDialog: function(e) {
		$('registration-wait').hide();
		$('registration-agent').hide();
		$('da-blur').hide();
		if(window.whsDialog){
			Event.stopObserving(document, 'keypress', window.whsDialog.key_listener);
			window.whsDialog = null;
		}
		return false;
	},

	showErrXHR: function(oXHR, stuff){
		errMsg = 'ERR: ' + oXHR.statusText;
		if(stuff){
			errMsg += '<br/>' + stuff;
		}
		$('notice').update(errMsg);
		$('registration-wait').hide();
		$('registration-agent').hide();
		$('notice').show();
	},

	pageReload: function() {
		document.location.reload();
	},

	dialogKeyHandler: function(event) {
		if(Event.KEY_ESC == event.keyCode){
			if( window.whsDialog ){
				window.whsDialog.closeDialog();
			}
		}
	}
};

var whsDialogKeyHandler = function(event) {
	if(Event.KEY_ESC == event.keyCode){
		if( window.whsDialog ){
			window.whsDialog.closeDialog();
		}
	}
}


var ajaxyRegForm = function(btn) {
	this.url = btn.form.action;
	this.form = $(btn.form);

	if(btn.value.toLowerCase() == 'cancel'){
		function closeForm(event){  
			Event.stop(event);  
			mrcMagicHide();
			return false;
		}
		Event.observe(btn, 'click', closeForm.bindAsEventListener(this) );
	} else {
		function sendForm(event){  
			// we stop the default submit behaviour  
			$('registration-wait').show();
			Event.stop(event);  
			var oFormOptions = {  
				method: "POST",  
				parameters: this.form.serialize(),  
				asynchronous: true,  
				onFailure: mrcShowErrXHR,  
				on200: mrcMagicFill,
				on204: mrcMagicHide,
				on205: function(oXHR) { document.location.reload(); }
			};
			if( $('registration-agent').style.display != 'none'){
				Effect.Fade('registration-agent', { duration: 0.5 });
			}
			var oRequest = new Ajax.Request(this.form.action, oFormOptions);
			return false;
		}  
		Event.observe(btn, 'click', sendForm.bindAsEventListener(this) );
	}

}

var mrcCreateMagicBox = function(){
	var blur   = document.createElement('div');
	blur.id    = 'da-blur'
	var attr   = document.createAttribute('style');
	attr.value = 'display:none;';
	blur.setAttributeNode(attr);

	var wait   = document.createElement('div');
	wait.id    = 'registration-wait'

	var agent   = document.createElement('div');
	agent.id    = 'registration-agent'
	var box     = document.createElement('div');
	box.id      = 'registration-box'
	var attr2   = document.createAttribute('style');
	attr2.value = 'display:none;';
	agent.setAttributeNode(attr2);

	document.body.appendChild(blur);
	blur.appendChild(agent);
	agent.appendChild(box);
	blur.appendChild(wait);
}


var initializeNav = function(){
	// untilBox = $('until_box')
	// Event.observe(untilBox,'click', hideShow);
	// Event.observe(untilBox,'mouseover', locOptOver);
	// Event.observe(untilBox,'mouseout', locOptOut);
	// 
	// allDayBox = $('all_day_box')
	// Event.observe(allDayBox,'click', toggleAllDay);
	// Event.observe(allDayBox,'mouseover', locOptOver);
	// Event.observe(allDayBox,'mouseout', locOptOut);
	// 
	// Event.observe($('our_location_key'),'change', myPlaceChosen);
	// 
	//   $('loc-search-link').onclick = performLocationSearch;

	// $$('.nav-btn').each( function(e,v){
	// 	//Event.observe(e,'click', navGo);
	// 	Event.observe(e, 'mouseover', navOver);
	// 	Event.observe(e, 'mouseout', navOut);
	// } );
	$$('.nav-btn a').each( function(lnk,v){
		//Event.observe(e,'click', navGo);
		var div = lnk.up();
		div.addClassName('linked')
		Event.observe(div, 'mouseover', navOver);
		Event.observe(div, 'mouseout', navOut);
		Event.observe(div, 'click', function(){document.location = lnk.href});
	} );

	// if( $$('a.reg-link') != nil ){
		mrcCreateMagicBox();
	// }

	$$('a.reg-link').each( mrcConvertToBackgroundCall );
	// $$('dyno-might').each( mrcAddNew );
	$$('a.add-item-link').each(function(link){
		new WHSGrowSelect(link);
	});
}


// Event.observe(window,'load',initializeWin);
document.observe('dom:loaded', initializeNav);


/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}
// });   

function collapseTwisty(effect, twisty) {
	twisty = (twisty == null) ? $(effect.element.twisty) : $(twisty);
	if(twisty){
		twisty.addClassName('twisty-collapsed');
		twisty.innerHTML = '<span>expand</span>';
	}
}

function expandTwisty(effect, twisty) {
	twisty = (twisty == null) ? $(effect.element.twisty) : $(twisty);
	if(twisty){
		twisty.removeClassName('twisty-collapsed');
		twisty.innerHTML = '<span>collapse</span>';
	}
}

function toggleTwistyBox(boxid, direction, animate)
{
	var box = $(boxid)
	if (direction == null) {direction = 'none';}
	if (animate == null) {animate = true;}
	box.twisty = boxid + "-twisty"
	box.twistext = boxid + "-twistext"
	if (box.visible() && direction != 'open') {
		if (animate) {
			Effect.Appear(box.twistext, {duration:0.15});
			Effect.BlindUp(box, {duration:0.15, afterFinish:collapseTwisty});
		} else {
			box.hide(); collapseTwisty(null, box.twisty);
			box.twistext.show();
		}
	} else if( direction != 'close' ){
		if (animate) {
			Effect.Fade(box.twistext, {duration:0.15});
			Effect.BlindDown(box, {duration:0.15, afterFinish:expandTwisty});
		} else {
			box.show(); expandTwisty(null, box.twisty);
			box.twistext.hide();
		}
	}
}
