/**
 * Base UI namespace
 */
Lifetype.UI = function() {}

/**
 * Base Pages namespace
 */
Lifetype.UI.Pages = function() {}

/**
 * Implements all the functionality required by the Ajax pager. The current
 * implementation is restricted to only one ajax pager per page, so all the 
 * methods below should be called statically.
 */
Lifetype.UI.AjaxPager = function() {}

/**
 * Namespace for events generated by the AjaxPager class
 */
Lifetype.UI.AjaxPager.Events = function() {}

/**
 * CustomEvent object fired when the table has been loaded. It should be used to trigger other tasks 
 * that need to happen when the table loads (i.e. reprocessing of the rel="overlay" links, table
 * row striping, etc)
 */
Lifetype.UI.AjaxPager.Events.dataLoaded = new YAHOO.util.CustomEvent('dataLoaded');

/**
 * Jumps to the previous page in the ajax pager.
 * @static
 */
Lifetype.UI.AjaxPager.previousPage = function()
{
	el = Lifetype.Dom.$( 'Pager' );
	el.selectedIndex = el.selectedIndex - 1;
	Lifetype.UI.AjaxPager.onChangeEvent( el );	

	return( false );
}

/**
 * Jumps to the first page in the ajax pager.
 * @static
 */
Lifetype.UI.AjaxPager.firstPage = function()
{
	el = Lifetype.Dom.$( 'Pager' );
	el.selectedIndex = 0;
	Lifetype.UI.AjaxPager.onChangeEvent( el );	

	return( false );
}

/**
 * Jumps to the last page in the ajax pager.
 * @static
 */
Lifetype.UI.AjaxPager.lastPage = function()
{
	el = Lifetype.Dom.$( 'Pager' );
	el.selectedIndex = el.options.length - 1;
	Lifetype.UI.AjaxPager.onChangeEvent( el );	

	return( false );
}

/**
 * Jumps to the next page in the ajax pager.
 * @static
 */
Lifetype.UI.AjaxPager.nextPage = function()
{
	el = Lifetype.Dom.$( 'Pager' );
	el.selectedIndex = el.selectedIndex + 1;
	Lifetype.UI.AjaxPager.onChangeEvent( el );
	
	return( false );
}

/**
 * Tells the pager to reload the current page
 * @static
 */
Lifetype.UI.AjaxPager.reload = function()
{
	el = Lifetype.Dom.$( 'Pager' );
	Lifetype.UI.AjaxPager.onChangeEvent( el );
}

/**
 * Handles the onChange event of the drop-down list containing
 * the list of pages.
 * @static
 */
Lifetype.UI.AjaxPager.onChangeEvent = function( el )
{	
	nextPageUrl = el.options[el.selectedIndex].value.replace(/&amp;/g, "&") + "&output=tableOnly";

	var cObj = YAHOO.util.Connect.asyncRequest('GET', nextPageUrl,
		callback = {
			success: function( o ) {
				Lifetype.Dom.$( 'list' ).innerHTML = o.responseText;

				// fire the 'dataLoaded' in case somebody else wants to do so some post-processing of the data
				Lifetype.UI.AjaxPager.Events.dataLoaded.fire( el );
			}
		}
	);
}

/**
 * This is a common thing to do after loading a table, as we need to reprocess all those links that
 * have been marked as "rel='overlay'" in the markup that was just loaded via Ajax. We cannot provide
 * a direct reference to the processAnchors() function becauseit does not exist yet when this file is
 * loaded (ui.js is one of the first files to be loaded)
 */
Lifetype.UI.AjaxPager.Events.dataLoaded.subscribe( function() { Lifetype.UI.ContentOverlay.processAnchors() } );

/**
 * Implements a table that is able to change its data dynamically. This should only be used
 * when the table doesn't display paginated data, please use Lifetype.UI.AjaxPager in all
 * other cases.
 */
Lifetype.UI.DataTable = function() {}

/**
 * Events for the DataTable
 */
Lifetype.UI.DataTable.Events = function() {}
Lifetype.UI.DataTable.Events.dataLoaded = new YAHOO.util.CustomEvent( 'tableDataLoaded' );

/**
 * Triggers a refresh of the table
 * @param url
 * @static
 */
Lifetype.UI.DataTable.reload = function( url )
{	
	url = url.replace(/&amp;/g, "&") + "&output=tableOnly";
	
	var cObj = YAHOO.util.Connect.asyncRequest('GET', url,
		callback = {
			success: function( o ) {
				Lifetype.Dom.$( 'list' ).innerHTML = o.responseText;

				// fire the 'dataLoaded' in case somebody else wants to do so some post-processing of the data
				Lifetype.UI.DataTable.Events.dataLoaded.fire( Lifetype.Dom.$( 'list' ));
			}
		}
	);
}

Lifetype.UI.DataTable.Events.dataLoaded.subscribe( function() { Lifetype.UI.ContentOverlay.processAnchors() } );

/**
 * Namespace for helper methods
 */
Lifetype.Helpers = function() {}

/**
 * Transforms a boolean value into "yes" or "no", by means of the
 * Lifetype.Locale set of functions.
 *
 * @param val
 * @static
 * @return A string representation of the given boolean value
 */
Lifetype.Helpers.boolToString = function( val ) 
{
	if( val == true || val == 1 )
		return( Lifetype.Locale.tr( "yes" ));
	else
		return( Lifetype.Locale.tr( "no" ));
}

/**
 * Strips tags from the given string
 *
 * @param str
 * @static
 * @return A string without HTML tags
 */
Lifetype.Helpers.stripTags = function( str )
{	
  return( str.replace(/<\/?[^>]+>/gi, ''));
}

/**
 * Namespace for prompt windows
 */
Lifetype.UI.Prompt = function() {}

/**********
 * Displays a very simple prompt with an input text box, an "Ok" button
 * and a "Cancel" button
 **********/

/**
 * Diplays a new prompt with the "Ok" and "Cancel" buttons
 *
 * @param str The string message to show
 * @param props An object that may contain the following properties:
 *   okCallback: the function to call when the 'ok' button is clicked
 *   cancelCallback: the function to call then the 'cancel' button is clicked
 *   defaultValue: the default value to show in the prompt, if any
 */
Lifetype.UI.Prompt.OkCancelPrompt = function( str, props )
{
	Lifetype.UI.Prompt.OkCancelPrompt.superclass.constructor.call( this, YAHOO.util.Dom.generateId(), {
		fixedcenter:true,
		constraintoviewport:true,
		visible:false, 
		close: true,
		draggable: false,
		effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration: 0.25},
		underlay:"shadow",
		modal:true,
		buttons : [ { text:tr("cancel"), handler:this.handleCancel },
		            { text:tr("ok"), handler:this.handleOk } ]		
	});
	
	if( props != undefined ) {
		this.okCallback = props.handleOk;
		this.cancelCallback = props.handleCancel;
		this.defaultValue = props.defaultValue;
	}
	
	var promptBody = document.createElement( 'div' );
	promptBody.className = 'promptBody';
	promptBody.appendChild( document.createTextNode( str ));
	promptBody.appendChild( document.createElement( 'br' ));
	var inputField = document.createElement( 'input' );
	inputField.type = 'text';
	inputField.name = 'dlgPromptText';
	inputField.id = 'dlgPromptText';
	inputField.className = 'dlgPromptText';
	inputField.size = '50';
	inputField.onkeypress = Lifetype.bind( this.onKeyPressHandler, this );
	if( this.defaultValue)
		inputField.value = defaultValue;
	promptBody.appendChild( inputField );

	this.setBody( promptBody );
	this.render( document.body );
}

YAHOO.extend( Lifetype.UI.Prompt.OkCancelPrompt, YAHOO.widget.Dialog );

/**
 * Handless key-presses in this dialog, so that we can redirect
 * the enter key to handleOk and the esc key to the cancel event
 */
Lifetype.UI.Prompt.OkCancelPrompt.prototype.onKeyPressHandler = function( e )
{
    //ie only
    if (!e) {
        var e = window.event;
    }

    if( e.keyCode == 13 ) {
        this.handleOk();
    }
    else if( e.keyCode == 27 ) {
        this.handleCancel();
    }

}

/**
 * Handler for the Ok button. You should not reimplement this one,
 * as it takes care of fetching the value that was typed in the field 
 * and passing it to the okCallback function
 * @private
 */
Lifetype.UI.Prompt.OkCancelPrompt.prototype.handleOk = function()
{
	if( this.okCallback != undefined ) {
		var value = Lifetype.Dom.$( 'dlgPromptText' ).value;
		this.okCallback( value );
		this.handleCancel();
	}
	else {
		this.handleCancel();
	}
}

/**
 * Handler for Cancel button. You should not reimplement this one either
 * @private
 */
Lifetype.UI.Prompt.OkCancelPrompt.prototype.handleCancel = function()
{
	this.hide();
	this.setBody( '' );
}

/**
 * Static method that can be called to use the Lifetype.UI.Prompt.OkCancelPrompt class
 * @static
 */
Lifetype.UI.Prompt.OkCancelPrompt.show = function( txt, props )
{
	var p = new Lifetype.UI.Prompt.OkCancelPrompt( txt, props );
	p.show();
	var dlgPromptText = Lifetype.Dom.$( 'dlgPromptText' );
	dlgPromptText.focus();	
}

/**
 * Miscellaneous UI functions
 */
Lifetype.UI.Misc = function() {}

/**
 * This should be used in the onClick event for a link, and it will trigger
 * it to open in a new window if Javascript is enabled. 
 * 
 * @param anchor The A object
 */
Lifetype.UI.Misc.openInNewWindow = function( anchor )
{
	anchor.target = "_blank";
	return( true );
}

/**
 * Class that formats file sizes into readable data
 */
Lifetype.UI.Misc.nicerFileSize = function( fileSize )
{
	var result;
	if( fileSize < 1024 ) {
		 result = fileSize + Lifetype.Locale.tr( " bytes" );
	}
	else {
		if( fileSize < (1024 * 1024 )) {
			result = Math.round((fileSize / 1024)) + Lifetype.Locale.tr( " kb" );
		}
		else {
			result = Math.round((fileSize / ( 1024 * 1024 ))) + Lifetype.Locale.tr( " mb" );
		}
	}
	
	return( result );
}
