/**
 * YAHOO.Plank.util
 * plank_util.js
 * 
 * Collection of commmon utils/wrappers for common actions
 * 
 * @package plank yui
 * @author  Mitchell Amihod 2008-07-19
 */
(function(){

  YAHOO.namespace('Plank.util');

  var Dom = YAHOO.util.Dom,
      Lang = YAHOO.lang,
      JSON = YAHOO.lang.JSON,
      Event = YAHOO.util.Event;
      
    
  // ===============================================
  // = Scroller. Used instead of window.location. 
  // = I suppose I could just override window.location, but that feels rude.
  // ===============================================

  //Saves last position for scroll back.
  var scrollBack = false;
  /**
   * Scroll to a window position. If nothing passed in, then scroll to the scrollback position. 
   *
   * @param array Where to scroll to. If empty, then its a scroll back.
   * @param bool deault:false  To animate or not? Works ok, but not so well with other animations: ie: modal container opening.
   * @return void
   **/  
  YAHOO.Plank.util.scroll = function (scrollPos, animate) {
        
    if( Lang.isUndefined(scrollPos) && Lang.isArray(scrollBack) ) {

      window.scroll(scrollBack[0], scrollBack[1]);      
      scrollBack = false;

    } else if( Lang.isArray(scrollPos) ) {
      //get original position
      scrollBack = [Dom.getDocumentScrollLeft(),Dom.getDocumentScrollTop()];
      window.scroll(scrollPos[0], scrollPos[1]);        
    }

    return;
    
  };
    
	/*
	 * Handles rollovers on images
	 * Currently targeted to element having class=rollover
	 * original_file.xyz
	 * rolloverfile == original_file_o.xyz
	 *
	 *  Rules:  img with class rollover
	 *          For an active IMG (ie: menu item in 'ON' state) also add the class active - this will supress rollover behaviour.
	 *
	 * @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?
	 *
	 */
  YAHOO.Plank.util.rollover = function(e) {

  	var el = Event.getTarget(e);

  	//SPecific fix for img inside button tag not picking up on the mouseover
  	if(el.tagName.toLowerCase() == 'button') {
  		el = Dom.getElementsByClassName('rollover', 'img',el)[0] || el;
  	}
 
  	if( false === Dom.hasClass(el, 'rollover') ) { return; }
  	if( true === Dom.hasClass(el, 'active') ) { 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');
  	}
  };

  /**
   * utility for container making. 
   * container is used generically by me to mean all yui container subclasses
   * 
   * customize to each projects needs, needed often enough to put it in with default for now.
   * @refactor  move into myUtil object
   * 
   * @param el    {string}  look for panel id string in overlay manager - not found? return new container
   *              {element} create new container from that el.
   *
   * @param oConfigs  {object} 
   *                 .conType Which container type to make. http://developer.yahoo.com/yui/container/
   *                          defaults to Ovelay
   * @return {container}  So you can chain
   **/
   
  //Set up short alias to oManager & makeit globally accessible.
  if(YAHOO.widget && YAHOO.widget.OverlayManager) {
    var oManager = YAHOO.Plank.util.oManager = new YAHOO.widget.OverlayManager();    
  }

  YAHOO.Plank.util.container = function(el, oConfigs) {

    oConfigs = oConfigs || {};

    var oDefaults = {
      'conType' : 'Overlay', //This is personal setting- not needed by yui.
      'width'   : '600px',
      // 'height'  : '400px',
      'dragOnly': true // Make false to interact with drop targets
    };

    Lang.augmentObject(oConfigs, oDefaults);

    //Default to panel. Expected types map to those available YUI container types
    //Should be cased accordingly.
    var containerType = oConfigs.conType || oDefaults.conType;
    var container = null;

    //String? Look it up in oManager
    if(Lang.isString(el)) {
      container = oManager.find(el);      
    }

    //We use isValue here instead of inNull because of bug in overlayManager.find()
    // where it returns undefined instead of null when there's no overlays registered.
    if(!Lang.isValue(container)) {

      container = new YAHOO.widget[containerType](el, oConfigs);

      //Register it
      //YAHOO.log(container, 'info', 'register');
      oManager.register([container]);

    } else {
      //Apply any new configs
      container.cfg.applyConfig(oConfigs);
    }

    if(!Lang.isUndefined(oConfigs.source)) {
      var iframe = document.createElement('iframe');
      iframe.setAttribute('src', oConfigs.source);
      iframe.setAttribute('scrolling', 'no');
      iframe.setAttribute('height', parseInt(oConfigs.height, 10) - 55 );
      iframe.setAttribute('width', parseInt(oConfigs.width,10) - 30);
      container.setBody(iframe);
    }

    //Apply settings
    return container;

  };
  

  /*
  *Trigger motion and animation together.
  */
  var animate = function(toAnim, motionAttribs, animAttribs) {
    
    var oAnims = {};
    
  	oAnims.motion = new YAHOO.util.Motion(toAnim, motionAttribs, .7, YAHOO.util.Easing.easeOutStrong);
  	oAnims.anim = new YAHOO.util.Anim(toAnim,animAttribs, .9, YAHOO.util.Easing.bounceOut );		

  	oAnims.motion.onStart.subscribe(
  		function() {
  			oAnims.anim.animate();
  		}
  	);

  	oAnims.motion.animate();
  	
  	return oAnims;
  };

  
  /**
   * remove el function. 
   * right now, used for removing an item from a DnD list. 
   *
   * @param el HTMLElement
   * @return void
   **/
  YAHOO.Plank.util.remove = function(el) {

			var rpoint = Dom.getXY(el);

			var xy_anim = [rpoint[0] + 235, rpoint[1] + -100]; 
			var points = { to: xy_anim, control: [  [rpoint[0] + 300, rpoint[1] + 100] ] } ;
			
			var motionAttribs = { points:  points };
			var animAttribs = {opacity: { to: 0 }, height:{to:0} };
			
			var anims = animate(el, motionAttribs, animAttribs);
    
      anims.anim.onComplete.subscribe(
        function() {
          el.parentNode.removeChild(el);
        }
      );
      //el.parentNode.removeChild(el);    
  };

  YAHOO.register("plank_util", YAHOO.Plank.util, {version: "1.2", build: "1"}); 

})();

