/*======================================================================*\
|| #################################################################### ||
|| # Php Ajax Multimedia website framework, or just "Pam"             # ||
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2007 Digital Media Graphix LLC. All Rights Reserved.  # ||
|| # ---------------------------------------------------------------- # ||
|| # Revision Alpha - Build 9 - Jan 8		                          # ||
|| #################################################################### ||
\*======================================================================*/

/*	This is PAM's core javascript file. */

/* ####################################################################
 * PAMWF Core Object.
 #################################################################### */
/**
 * Singleton Class instance, PAMWF Core.
 */
var PAMWF = {
	_tips: new Array(),
	debug: true,
	/* First create a null console so that Firebug console calls do not disturb 
	 * other browsers while parsing pages when not in debug mode. 
	 */
	console: {
		log: function(){},		
		debug: function(){},
		info: function(){},
		warn: function (){},
		error: function(){},
		assert: function(){},
		dir: function(){},
		dirxml: function(){},
		trace: function(){},
		group: function(){},
		groupEnd: function(){},
		profile: function(){},
		profileEnd: function(){},
		count: function(){}		
	},

	/**
	 * Initialize a console for error messages
	 */
	_initConsole: function()
	{
		if (typeof(console) == 'object' && typeof(console.group) == 'function') 
		{
			this.console = console;
		}
	},
	
	/**
	 * In this function we deal with the operations we can perform while we wait for the
	 * page to load. Note that any operation dependent on document load to complete will
	 * fail here, however we can use document.write and document.writeln without destroying
	 * the load in here if we need to use them.
	 *
	 * A call to preLoadInit is automatically included by PAM's PHP framework. If you want to
	 * modify this call, it is in /controllers/ PAMWF_Templates.php
	 *
	 */
	preLoadInit: function() 
	{
		this._initConsole();
		
		// Console Greeting Message
		this.console.group ('PHP Ajax Multimedia Website Framework Javascript', '\n(c) 2007 Digital Media Graphix, Knoxville TN \nFirebug Console Initialized.');
		
		// Display debug data
		if (typeof(PAMWF_debug) != 'undefined')
		{
			this.console.dir(PAMWF_debug);
		}
		
		// Display PHP Warnings and errors. 
		Event.observe( window, 'load', this._errorHandler.bindAsEventListener(this));
		
		// This ends the page opening stuff
		this.console.groupEnd();
		
		// Mask resizing
		Event.observe( window, 'resize', this._resizeMasks.bindAsEventListener(this));
		
		Event.observe( window, 'load', this._postLoad.bindAsEventListener(this));
	},
	
	_postLoad: function()
	{
		if (PAMWF.Tooltip)
		{
			$$('.Tooltip').each(function(s){
				this._tips.push(new PAMWF.Tooltip(s));
			}.bindAsEventListener(this));
		}
	},
	
	/**
	 * If PAM encounters a non-critical PHP warning or notice in debug mode, or if the user
	 * hit's a 404, 402 or the like a popup needs to be displayed. This is also used for
	 * status messages on rare occasion.
	 */
	_errorHandler: function()
	{
		if ($('PageError'))
		{
			new this.Dialog('PageError');
		}
	},
	
	/**
	 * Javascript implementation of PAMWF_Draw::calendar()
	 */
	drawCalendar: function ( name, id, value, attributes )
	{
		return '<input id="'+id+'" name="'+name+'" value="'+value+'" type="hidden">'
			+'<input id="Display'+id+'" name="Display'+name+'" value="" type="text" onchange="$(\''+id+'\').value = Date.parse(this.value)/1000;">'
			+'<input class="calButton" id="Button'+id+'" type="button" value="" onclick="new CalendarDateSelect(\'Display'+id+'\', '+attributes+');"/>';
	},
	
	Uploaders: {},
	
	/**
	 * Extensions to the prototype library used by some PAM objects.
	 */
	ElementExtensions: {
		center: function ( element, limitX, limitY )
		{
			element = $(element);
			
			var elementDims = element.getDimensions();
			var viewPort =  PAMWF._findMaskArea();

			var offsets = document.viewport.getScrollOffsets();
			var centerX = viewPort.width / 2 + offsets.left - elementDims.width / 2;
			var centerY = viewPort.height / 2 + offsets.top - elementDims.height / 2;
			if ( limitX && centerX < limitX )
			{
				centerX = parseInt(limitX);
			}
			if ( limitY && centerY < limitY )
			{
				centerY = parseInt(limitY);
			}
			
			element.setStyle( { position: 'absolute', top: Math.floor(centerY) + 'px', left: Math.floor(centerX) + 'px' } );
			
			return element;			
		}
	},
	
	/**
	 * Misc functions
	 */
	implode: function ( arr, glue )
	{
		output = '';
		if (typeof(glue) != 'string')
		{
			glue = ' ';
		}
		
		for( var i=0; i<arr.length; i++)
		{
			output += glue + arr[i];
		}
		
		return output;
	},
	
	/**
	 * Return the first value encountered for a tag
	 */
	getValue: function( node, tag )
	{
		return node.responseXML.getElementsByTagName(tag)[0].firstChild.nodeValue;
	},
	
	logout: function ( url )
	{
		if (!url)
		{
			url = location.href + '?action=logout';
		}
		
		var mask = this.drawMask( false );
				
		new Effect.Appear( mask, { from:0.0, to: 0.5, afterFinish: function(){	
			if (confirm('Are you sure you wish to log out?'))
			{
				// Do the request.
				new Ajax.Request(url, { method: 'post' });
			}
			else
			{
				new Effect.Fade( mask, { afterFinish: function(e){
					mask.remove();
				}});
			}			
		}});	
	},
	
	/**
	 * Draw a mask and return it.
	 */
	drawMask: function( appear )
	{
		if (typeof(appear) == 'undefined')
		{
			appear = true;
		}
		
		var viewPort = this._findMaskArea();
		
		e = new Element('div', { 'class': 'mask', 'style': 'display:none; position: absolute; height:'+ viewPort.height+'px; width: '+viewPort.width+'px;' });

		var body = $$('BODY')[0];
		body.insert( { bottom: e });
				
		if ( appear )
		{
			new Effect.Appear( e );
		}
		
		return e;
	},
	
	_resizeMasks: function( e )
	{
		$$('.mask').each(function (s){
				var viewPort = this._findMaskArea();
				s.setStyle({height: viewPort.height+'px', width: viewPort.width+'px'});
			}.bindAsEventListener(this));
		
	},
	
	_findMaskArea: function()
	{
		// Get the viewport.
		try
		{
			var viewPort = { height: window.innerHeight, width: window.innerWidth };
		} catch (e) {}
		
		/** If undefined browser is IE or IE clone - try again checking IE version of the above **/
		if (typeof(viewPort.height) == 'undefined')
		{
			viewPort.height = document.body.clientHeight;
			viewPort.width = document.body.clientWidth;
		}
		
		docDimensions = document.viewport.getDimensions();
		
		// Slight adjustment to prevent accidental startup of scrollbars.
		viewPort.height = viewPort.height -1;
		viewPort.width = viewPort.width -1;
		
		return {
			height: ( viewPort.height > docDimensions.height ) ? viewPort.height : docDimensions.height,
			width: ( viewPort.width > docDimensions.width ) ? viewPort.width : docDimensions.width
		};
	}
};

Element.addMethods(PAMWF.ElementExtensions);

PAMWF.preLoadInit();