/**
 * Base js functions for Plank Sites
 *
 * @requires - utilities.js
 *
 *Includes:
 *	-Image Rollovers
 *	-Div Togglers
 *	-Input Switchers
 *	-Open in External Window
 *  -Menu Hover
 **/

var $plank = YAHOO.namespace('Plank.Base');

$plank = function () {

	var $D = YAHOO.util.Dom;
	var $E = YAHOO.util.Event;
	
	//Used for the inputHandler	
	var oldInputValues = new Array();
	
	return {

		/**
		 * Init function
		 */
		init: function () {

			//console.log('Init');
			//Listen to the element id=container for any clicks.
			$E.on('container', "click", this.clickHandler, {}, $plank);

			$E.on('container', "mouseover", this.rollover);
			$E.on('container', "mouseout", this.rollover);
			$E.on('container', "submit", function(e) {$E.stopEvent(e)});

			this.inputInit();
		//  this.navHover();			
		//	this.test();
		},

		/**
		 * Event Handlers
		 */
		clickHandler: function(e) {
			// console.log(e,'clickHandler');

			//In general, use classes and IDs to filter clicks.
			var passThru = true; //Whether to allow an action to execute. ie: regular page links - true in production on, false in debug mode

			var el = $E.getTarget(e);

			var command = el.id.split('-')[1];
			var target = el.id.split('-')[2];

			//EXTERNAL/INTERNAL Link Targets
			//This marks a link as open target='_blank' if external
			if('a' == el.tagName.toLowerCase()){
				passThru = true;
				var href = window.location.hostname;
			    // make the regex
			    var re = new RegExp('\\b' + href + '\\b', "i");

				//Check if its an external link
		        if (el.href.search(re) == -1) {
		            el.target = "_blank";
		        }
			}

			switch(true) {

				case('toggler' == command):

					passThru = false;			
					//Pattern for el to toggle:
					//listing id_toggle
					this.toggler($D.get("toggler_"+target));

				break;
				
			}

			if(passThru == false ) $E.stopEvent(e);

		},
		
		/* 
		 * Initializes inputs with listeners.
		 */

		inputInit : function(){

			//Input Blur/Focus events don't bubble, so we target them 
			//specifically to any input element with inputHandler class.
			var formInputs = $D.getElementsByClassName('inputHandler', 'input');
			
			formInputs=formInputs.concat($D.getElementsByClassName('inputHandler', 'textarea') );
			
			//Store the original input values
			$D.batch(formInputs, function(el){
				var formIdentifier = el.parentNode.id+'_'+el.name;
				oldInputValues[formIdentifier] = el.value;
			});

			$E.on(formInputs, "blur", this.inputHandler);
			$E.on(formInputs, "focus", this.inputHandler);

		},
	
		/*
	     * Handles managing default values for forms. form inputs managed if they have a class of inputHandler
	     * will empty a field on focus, and refill with default if there's no change.
		 * Will check ID of input tosee if word password is found - if so, assume its a PW field, and switch it accordingly
	     * @type string
	     */
		inputHandler: function(e) {

			var elTarget = $E.getTarget(e);

			if(elTarget.parentNode.id === undefined ) {
				$D.generateId(elTarget.parentNode);
			}
			var formIdentifier = elTarget.parentNode.id+'_'+elTarget.name;

			switch(e.type.toLowerCase()) {

				case('focus'):
					if( oldInputValues[formIdentifier] == elTarget.value) {
						elTarget.value = '';
						if(elTarget.id.indexOf('password') > -1){
							elTarget.type='password';
						}
					}
					$D.removeClass(elTarget, 'blur');
					$D.addClass(elTarget, 'focus');
				break;
				
				case('blur'):
					if(YAHOO.lang.trim(elTarget.value) == ''){
						if(elTarget.id.indexOf('password') > -1){
							elTarget.type='text';
						}
						elTarget.value =  oldInputValues[formIdentifier];
					}
					$D.removeClass(elTarget, 'focus');
					$D.addClass(elTarget, 'blur');
				break;
				
				default:
				 //nothing yet.
			}

		},

		/*
		*Creates drop downs across all browsers. faux hover:
		*id of nav root should be navContainer
		*/

		navHover : function() {

			navRoot = $D.get("navContainer");
			
			liEls = $D.getChildrenBy(navRoot, function(node) { if(node.nodeName=="LI") return true; return false ; })
			
			var	processNodes = function(node) {
				node.onmouseover=function() {
	  				$D.setStyle(this.childNodes[1], 'display', 'block');
	  			}

	  			node.onmouseout=function() {
					$D.setStyle(this.childNodes[1], 'display', 'none');
	   			}
			};
			
			$D.batch(liEls, processNodes );
	
		},

		/*
		 * Handles rollovers on images
		 * Currently targeted to element having class=rollover
		 * original_file.xyz
		 * rolloverfile == original_file_o.xyz
		 *
		 * @TODO: Q: Is it better to just attach a few listeners to the els with 
		 * rollover class as oppossed to capturing and analyzing every mouseover?
		 *
		 */
		rollover : function(e) {

			var el = $E.getTarget(e);

			if( false === $D.hasClass(el, 'rollover') ) { return; }

			var filetype = el.src.substring(el.src.lastIndexOf('.'), el.src.length);

			switch(e.type){
				case 'mouseover':
					el.src = el.src.replace(filetype, '_o'+filetype);
				break;
				case 'mouseout':
					el.src = el.src.replace("_o"+filetype, filetype);
				break;
				default:
					throw('Unexpected e.type in rollover handler');
			}
		},

		/*
		 * To toggle visibility of element
		 * Uses "visibility" property to decide whether to show or hide
		 */
		toggler : function (el) {

			var curVisibility = $D.getStyle(el,'visibility'); 

			if( 'visible' == curVisibility ) {
				
				var anim = new YAHOO.util.Anim(el, {opacity: {to: 0, unit: '%' }, height: {to:0} } , .5, YAHOO.util.Easing.easeOut);

				//Once the animation is done.
				anim.onComplete.subscribe(
					function () {
						$D.setStyle(el, 'visibility', 'hidden');
						$D.setStyle(el, 'display', 'none');
					}
				);

			} else {
				var anim = new YAHOO.util.Anim(el, {opacity: {to: 1 }, height:{ from: 0 , to: 100, unit: '%'} } , 1, YAHOO.util.Easing.easeIn);
			}
			//Set this up first, results in smoother anims, though not on table row efects
			$D.setStyle(el, 'visibility', 'visible');
			var displayStyle = (el.tagName.toLowerCase() == 'tr') ? 'table-row' : 'block' ;
			$D.setStyle(el, 'display', displayStyle);

			anim.animate();

		},
		
		test : function() {
			var el = $D.get('testlink');
			el.onmouseover = function() { alert('foo')};
		}
	};	//End Closure Wrapper


	
} ();

/*
 * Load Init script once the container is ready
 * We pass in $plank as scope object, so init has access to 'this'
 */
YAHOO.util.Event.onDOMReady($plank.init, {}, $plank);
