/**
* $Id: mck.js 41 2009-09-22 11:31:56Z brandon $
*
* McKeel Academies
* Core v1.0
* Global JS
* Last Updated: $Date: 2009-09-22 07:31:56 -0400 (Tue, 22 Sep 2009) $
*
* @author			Brandon Davie
* @copyright	(c) 2009 McKeel Academies
* @package		Core
* @subpackage	Javascript
* @link				http://mckeelacademy.com/
* @since			2008-05-13
* @version		$Rev: 41 $
* @author			$Author: brandon $
*/

window.mckjs = Class.create({
	vars: [],
		
	initialize: function()
	{
		/* DOM loaded? */
		document.observe( 'dom:loaded', function()
		{
			/* Init the AJAX loading message */
			if ( $( 'ajax_loading' ) )
			{
				$( 'ajax_loading' ).hide();
			}
			
			Ajax.Responders.register({
			  onLoading: function()
			  {
			    if ( $( 'ajax_loading' ) )
					{
						var effect = new Effect.Appear( $( 'ajax_loading' ), { duration: 0.2 } );
					}
				},
			  
			  onComplete: function()
			  {
					if ( $( 'ajax_loading' ) )
					{
						var effect = new Effect.Fade( $( 'ajax_loading' ), { duration: 0.2 } );
					}			    
			  }
			});

			/* Setup global element visibility toggles and the sidebar */
			mck.initToggles();
			mck.initSidebar();
			
			/* Setup the global user menu and custom pages menu */
			if ( $( 'nav_more_menu' ) )
			{
				$( 'nav_more_menu' ).hide();
				this.initGlobalMenu( 'nav_more_menu' );
			}
			
			if ( $( 'user_menu' ) )
			{
				$( 'user_menu' ).hide();
				this.initGlobalMenu( 'user_menu' );
			}			
		}.bind( this ) );
	},
	
	initGlobalMenu: function( menu )
	{
		/* Full menu exists? */
		if ( ! $( menu ) || ! $( menu + '_link' ) )
		{
			return;
		}
		
		/* Initialmatize it */
		var menuLink = $( menu + '_link' );
		
		menuLink.observe( 'click', function( e )
		{
			if ( ! $( menu ).visible() )
			{
				$( menu ).setStyle( 'visibility: visible' );
			}
			
			new Effect.Appear( $( menu ), { duration: 0.2 } );
			Event.stop( e );
			Event.observe( document, 'click', function( e )
			{
				new Effect.Fade( $( menu ), { duration: 0.2 } );
			} );
		} );
	},
	
	initToggles: function()
	{
		/* Hide anything that needs to be hidden */
		var toHide = $$( '.init_hide' );
		
		if ( toHide )
		{
			toHide.each( function( elem )
			{
				elem.hide();
			} );
		}
		
		/* Anything with the toggle class needs to have an event attached */
		var toEvent = $$( '.toggle' );
		
		if ( toEvent )
		{
			/* Bind the toggleVisibility function to it */
			toEvent.each( function( toggle )
			{
				Event.observe( toggle.id, 'click', mck._toggleVisibility.bind( this ) );
				toggle.href = "javascript:void(0)";
				toggle.addClassName( 'toggleselected' );
			}.bind( this ) );
		}
		
		/* Do we have any toggles saved in a particular position? */
		var layoutCookie = this.getCookie( 'layout' );
		
		if ( layoutCookie )
		{
			/* Hide 'em! */
			$w( layoutCookie ).each(function( elem )
			{
				if ( $( elem ) && $( 'sub_for_' + elem ) )
				{
					var theElement = $( elem );
					var theSub		 = $( 'sub_for_' + elem );
						
					/* Hide it and mark it as selected */						
					theSub.hide();
					theElement.removeClassName( 'toggleselected' );
				}
			}	);
		}
	},
	
	initSidebar: function()
	{		
		/* Already specified the visibility status of the sidebar? */
		var theBar			= this.getCookie( 'sidebar' );
		var rightBoxes	= $$( '.right_box' );
		
		if ( theBar == '0' || ! rightBoxes.length )
		{
			/* Close 'ze bar! */
		 	if ( $( 'right_col' ) )
		 	{
		 		$( 'right_col' ).hide();
		 	}
		 	
		 	/* ... and expand all the left boxes */
		 	var theBoxes = $$( '.left_box' );
		 	
		 	theBoxes.each( function( elem )
		 	{	
		 		$( elem ).removeClassName( 'open' );
		 	} );
		}	
		
		/* Init the open/close icon */
		if( $( 'right_col' ).visible() )
		{
			if ( $( 'open_sidebar' ) ) $( 'open_sidebar' ).hide();
			if ( $( 'close_sidebar' ) ) $( 'close_sidebar' ).show();
		}
		else
		{
			if ( $( 'open_sidebar' ) ) $( 'open_sidebar' ).show();
			if ( $( 'close_sidebar' ) ) $( 'close_sidebar' ).hide();
		}
		
		/* Attach the close event */
		if ( $( 'close_sidebar' ) )
		{
			$( 'close_sidebar' ).observe( 'click', function( e )
			{
				/* Fade the right col */
				new Effect.Fade( $( 'right_col' ), {duration: 0.4, afterFinish: function()
				{
					$$( '.left_box' ).each( function( elem )
					{
						/* Morph each left box to 100% width */
						new Effect.Morph( $( elem ), { style: 'no_sidebar', duration: 0.4, afterFinish: function()
						{
							$( elem ).removeClassName( 'no_sidebar' ).removeClassName( 'open' );
						}	} );
					} );
				}	} );
				
				Event.stop(e);
				$( 'close_sidebar' ).toggle();
				$( 'open_sidebar' ).toggle();
				
				/* Set the cookie */
				mck.setCookie( 'sidebar', '0', '' );
			} );
		}
		
		/* Attach the open event */
		if( $( 'open_sidebar' ) )
		{
			$( 'open_sidebar' ).observe( 'click', function( e )
			{
				/* Morph each left box to ~80% width */
				$$( '.left_box' ).each( function( elem )
				{
					new Effect.Morph( $( elem ), { style: 'open', duration: 0.4 } );
				} );
				
				/* Bring in the right col */
				new Effect.Appear( $( 'right_col' ), { duration: 0.4, queue: 'end' } );
				
				Event.stop(e);
				$( 'close_sidebar' ).toggle();
				$( 'open_sidebar' ).toggle();
				
				/* Update the cookie */
				mck.setCookie( 'sidebar', '1', '' );
			} );
		}
	},
	
	_toggleVisibility: function( e )  
	{
		/* Grab the element */
		toggle = Event.element( e );
		toggleClasses = toggle.classNames();
		
		/* We're unhiding this element... */
		if ( toggleClasses == 'toggle' ) 
		{
			/* Mark it as selected */
			toggle.addClassName( 'toggleselected' );
			
			/* Update the layout cookie, removing this one */
			var layoutCookie = this.getCookie( 'layout' );
			var theCookie 	 = this._trimString( layoutCookie.replace( toggle.id, '' ) );
			this.setCookie( 'layout', theCookie, '' );
		}
		else
		{
			/* We're hiding this element... */
			toggle.removeClassName( 'toggleselected' );
			
			/* Update the layout cookie, adding this one */
			var layoutCookie = this.getCookie( 'layout' );
		
			if ( layoutCookie )
			{
				var theCookie = layoutCookie + ' ' + toggle.id;
			}
			else
			{
				var theCookie = toggle.id;
			}
			theCookie = this._trimString( theCookie );
			
			this.setCookie( 'layout', theCookie, '' );
		}
		
		var theId = 'sub_for_' + Event.element( e ).id
		
		/* Finally, toggle the visibility */
		Effect.toggle( $( theId ), 'slide', {duration: 0.4} );
	},
	
	getCookie: function( cookieName )
	{
		/* Attach prefix */
		cookieName = mck.vars[ 'cookiePrefix' ] + cookieName;
		var theCookie = document.cookie.match( cookieName + '=(.*?)(;|$)' );
		
		if ( theCookie )
		{
			return unescape( theCookie[ 1 ] );
		}
		else
		{
			return null;
		}
	},
	
	setCookie: function( cookieName, cookieValue, expires )
	{
		/* Attach prefix */
		cookieName = mck.vars[ 'cookiePrefix' ] + cookieName;
		
		try {
			cookieValue = String( cookieValue.toString() );
			
			if ( ! expires )
			{
				var theDate = new Date();
				theDate = new Date( theDate.getTime() + ( ( 100 * 24 * 60 * 60 ) * 1000 ) );
				expires = theDate.toGMTString();
			}
			
			var theCookie = cookieName + "=" + escape( cookieValue ) + '; expires=' + expires;
			document.cookie = theCookie;
		}
		catch ( e )
		{
			return false;
		}
		
		return true; 
	},
	
	_trimString: function( toClean )
	{
		return toClean.replace( /^\s+|\s+$/g, '' );
	}
});

var Loader = {
	boot: function()
	{
		/* Grab all current scripts */
		$A( document.getElementsByTagName( 'script' ) ).findAll( function( script )
		{
			/* Return the 'src' attribute if it's our mck.js */
			return ( script.src && script.src.match( /mck\.js(\?.*)?$/ ) );
		} ).each( function( script )
		{
			/* Nuke mck.js and grab what we're loading */
			var scriptPath	= script.src.replace( /mck\.js(\?.*)?$/, '' );
			var loadScripts =	script.src.match( /\?.*load=([a-z0-9_,]*)/ );
			
			if ( loadScripts && loadScripts[ 1 ] )
			{
				loadScripts[ 1 ].split( ',' ).each( function( theScript )
				{
					if ( theScript )
					{
						/* Include it */
						Loader._requireScript( scriptPath + 'mck.' + theScript );
					}
				} )
			}
		} );
	},
	
	_requireScript: function( scriptSrc )
	{
		/* Simply print it */
		document.write( '<script type="text/javascript" src="' + scriptSrc + '.js"></script>' );
	}
}

var Script = {
	
  _loadedScripts: [],
  
  include: function( script ){
    
    /* Already loaded it? */
    if ( this._loadedScripts.include( script ) )
    {
      return false;
    }
    
    /* Grab it */
    var code = new Ajax.Request( script, {
      asynchronous: false, method: "GET",
      evalJS: false, evalJSON: false
    }).transport.responseText;
    
    /* Eval it */
    if ( Prototype.Browser.IE )
    {
      window.execScript( code );
    }
    else if ( Prototype.Browser.WebKit )
    {
      $$( 'head ').first().insert( Object.extend(
        new Element( "script", { type: "text/javascript" } ), { text: code }
      ));
    }
    else
    {
      window.eval( code );
    }
    
    /* Mark it as loaded */
    this._loadedScripts.push( script );
  }
};

mck = new mckjs;