/**
 * toggler.js functions for Planksters
 * @requires - utilities.js
 * @author mitchell amihod
 *
 *	How To:
 *	Include this on the page. You should also have included the utilities.js file.
 *	see toggler.html for an example.
 *
 *
 **/

YAHOO.namespace('Plank.Base');

YAHOO.Plank.Base.Toggler = function () {

	var $D = 	YAHOO.util.Dom;
	var $E = 	YAHOO.util.Event;
	
	//Collect object. We return it after the onContentReady
	var publicMethods = {

		init: function () {
			//Set up the listener on body. If there's no ID for body, will be generated
			$E.on($D.generateId(document.body, 'genbodyid'),
			 		"click", 
					publicMethods.toggler
				);
		},

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

			var elTarget = $E.getTarget(e);
			var command = elTarget.id.split('-')[1];

			if( 'toggler' !== command ) { return; }
			
			//If its a link, we'll want to stop the event.
			$E.stopEvent(e);		

			var target = elTarget.id.split('-')[2];
			
			var el = $D.get("toggler_"+target)			
			
			var curVisibility = $D.getStyle(el,'visibility'); 

			if( 'visible' == curVisibility ) {

				//store the elements current height, to restore once hidden, so its available on the next call.
				var anim = new YAHOO.util.Anim(el, {opacity: {to: 0 }, height: {to:0, unit: '%' } } , .5);

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

			} else {
				//Set Opacity to 0, so it doesnt pop in.
				$D.setStyle(el, 'opacity', '0');
				var anim = new YAHOO.util.Anim(el, {opacity: { to: 1 }, height:{ from: 0 , to: 100, unit: '%'} } , .5);
			}
			
			//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' ;
			
			//Compensate for IE bug - make it block regardless of if its a tr
			if(YAHOO.env.ua.ie > 0) { displayStyle = 'block';}

			$D.setStyle(el, 'display', displayStyle);

			anim.animate();

		}
	};	//End Closure Wrapper

	$E.onDOMReady(publicMethods.init);
	return publicMethods;
	
} ();
