/* 
 * $Id: AbstractAS.java 775 2006-08-31 16:37:42Z vitor.carreira $
 *
 * (C) 2006 - MetaVerse Solutions
 * Copyright 2006 MetaVerse Solutions, Inc. All rights reserved.
 * METAVERSE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

window['___debug___'] = false;

/** Init alert box code **/
alertBox = new Object();

alertBox.show = function (messageId, text, /* int */ zIndex) {
	var messageIdField = document.getElementById("alertMessageId");
	messageIdField.value = messageId;
	
	var messageText = document.getElementById("message_gadget_text");
	messageText.innerHTML = text;
	if (this.isVisible == true)
		return;
		
	var _this = document.getElementById("message_gadget");
	if (_this)
	{
		
		var toggleWarningIcon = function () {
			var icon = document.getElementById("message_gadget_error_icon");
			if (!icon.style.visibility || icon.style.visibility == "hidden")
				icon.style.visibility = "visible";
			else if (icon.style.visibility == "visible")
				icon.style.visibility = "hidden";
		}
		
		_this.warningIconCycle = toggleWarningIcon.periodical(500); 
		
		_this.style.visibility = "visible";
		if(zIndex)
			_this.style.zIndex = zIndex;
		else 
			_this.style.zIndex = 99999;
		
		this.isVisible = true;
	}	
};

alertBox.hide = function() {
	if(this.isVisible == false)
		return;
	var _this = document.getElementById("message_gadget");
	if (_this)
	{
		_this.style.visibility = "hidden";
		_this.style.zIndex = 0;
		$clear(_this.warningIconCycle);
		var icon = document.getElementById("message_gadget_error_icon");
		icon.style.visibility = "hidden";
		this.isVisible = false;
	}
};

alertBox.check = function () {
	alertBox.dummy = new Date();
	alertBox.dummy = alertBox.dummy.getTime() + $random(0, 100);
	alertBox.ajax.request(alertBox.dummy); 
}

alertBox.markMessageAsRead = function (url) {
	/*var messageId = document.getElementById("alertMessageId");
	var ajaxAux = new Ajax( url, { 
		method: "post", 
		async: true,
		postBody: Object.toQueryString({"post.message.id": messageId.value}),
		evalScripts: 	true,
		evalResponse: 	true,
		onSuccess: function( response, xml ) {
			alertBox.hide();
		}
	 } );
	 ajaxAux.request();*/
	 alertBox.hide();
	document.getElementById("alertForm").send();
}

alertBox.init = function (urlCheck, urlMarkAsRead, timer) {
	this.urlCheck = urlCheck;
	this.isVisible = false;	

	// Set the close button function
	var closeBtn = document.getElementById("alertBoxCloseBtn");
	if (!closeBtn.onclick) {
		closeBtn.onclick = function () {
			alertBox.markMessageAsRead(urlMarkAsRead);
		};
	}	
	
	
	/* our ajax istance */
	this.ajax = new Ajax( urlCheck, { 
		method: "post", 
		async: true, 
		postBody: {}, 
		evalScripts: 	true,
		evalResponse: 	true,
		onFailure: function( response, xml ) {
			//alert("Error receiving message from url: " + alertBox.url);
		}
	 } );
	
	$clear(this.periodical);
	
	this.periodical = alertBox.check.periodical(timer * 1000, this); 
	 

	this.ajax.request(); 
	
	
}
/** end alert box code **/

/** init loader code **/
loader = new Object();
loader.show = function(/* int */ zIndex) {
	var _this = document.getElementById("loader_gadget");
	if (_this)
	{
		_this.style.visibility = "visible";
		if(zIndex)
			_this.style.zIndex = zIndex;
		else 
			_this.style.zIndex = 99999;
	}
};
loader.hide = function() {
	var _this = document.getElementById("loader_gadget");
	if (_this)
	{
		_this.style.visibility = "hidden";
		_this.style.zIndex = 0;
	}
};
/** end loader code **/

/** init pagination view state **/
paginationViewState = new Object();
paginationViewState.init = function()
{
	this.paginationsFields = new Array();
	this.paginationsFields[0] = "page";
	this.paginationsFields[1] = "sort";
	this.paginationsFields[2] = "desc";
	this.paginationsFields[3] = "asc";
	this.paginationsFields[4] = "text";		
	this.params = {};	
}
paginationViewState.clear = function()
{	
	this.params = {};	
};
paginationViewState.put = function(/* string */ key, /* string */ value)
{
	if(key != undefined && value != undefined)
		this.params[key] = value;	
};
paginationViewState.get = function(/* string */ key)
{
	if(key != undefined)
		return this.params[key];	
	return undefined;
};
paginationViewState.remove = function(/* string */ key)
{
	if(key != undefined)
		this.params[key] = undefined;	
};
/**
 * Save news view state values from param 'values'
 */
paginationViewState.update = function(/* JSON */ values)
{		
	if(values == undefined)
		return;
	for(var i = 0; i < this.paginationsFields.length; i++)
	{
		if( values[this.paginationsFields[i]] != undefined )
		{	
			this.params[this.paginationsFields[i]] = values[this.paginationsFields[i]];
		}
	}		
};
/**
 * Put view state fields on param 'values'
 */
paginationViewState.setValues = function(/* JSON */ values)
{			
	if(values == undefined)
		return;
	for (keyField in this.params) {
		if( this.params[keyField] != undefined && keyField != "extend")//&& trim(this.params[keyField]).length > 0
		{	
			values[keyField] = this.params[keyField];
		}
	}		
};
//init view state pagination
paginationViewState.init();

/** end pagination view state **/

function selectOptionByValue(selectObjId, valueToSelect)
{
	var x = document.getElementById(selectObjId);
	
	for (i=0;i<x.length;i++)
	{
		if(valueToSelect == x.options[i].value) {
			x.selectedIndex = i;
			return;
		}
	}
}

function showError(/* string */ errorMessage, /* string */ backUrl, /* function */ errorCallback) {
	//setTimeout( function() {
		
		MOOdalBox.options.afterFetch = function( content ) {
	
			var messageDiv = $('err_message');
			var okButton = $('err_close_btn');
			var closeButton = $('err_mini_close');
	
			var closeFunction = function () {
				MOOdalBox.close();
				if (errorCallback)
					errorCallback(backUrl);
			};
	
			messageDiv.innerHTML = errorMessage;	
			closeButton.onclick = closeFunction;
			okButton.onclick = closeFunction;
		};
		//alert("[code me]show error function: " + errorMessage );	
		
		//dialogError.show();
		MOOdalBox.open( window['error_dialog'], "error", "502" );
	//}, 500 );
}

var emptyFunc = function(){};
function showInternalError() {
	//setTimeout( function() {
		MOOdalBox.options.afterFetch = emptyFunc;
		MOOdalBox.open( window['ierror_dialog'], "error", "502" );
	//}, 500 );
}


function showWarning(/* string */ titleMessage, /* string */ warningMessage, /* func */ yesFunction, /* func */ noFunction) {
	//setTimeout( function() {		
		MOOdalBox.options.afterFetch = function( content ) {
	
			var titleDiv = $('warn_title');
			var messageDiv = $('warn_message');
			var yesButton = $('warn_yes_btn');
			var noButton = $('warn_no_btn');
			var closeButton = $('warn_close_btn');
	
			var goFunction = function() {
				MOOdalBox.close();
				if (yesFunction)
					yesFunction();
			};
		
			var cancelFunction = function() {
				MOOdalBox.close();
				if (noFunction)
					noFunction();
			};
		
			titleDiv.innerHTML = titleMessage;
			messageDiv.innerHTML = warningMessage;
			yesButton.onclick = goFunction;
			noButton.onclick = cancelFunction;
			closeButton.onclick = cancelFunction;	
		};
	
		MOOdalBox.open( window['warn_dialog'], "warning", "502" );
	//}, 500 );
}


function showInfo(/* string */ titleMessage, /* string */ infoMessage, /* func */okFunction) {
		
		MOOdalBox.options.afterFetch = function( content ) {

			var titleDiv = $('info_title');
			var messageDiv = $('info_message');
			var okButton = $('info_close_btn');
			var closeButton = $('info_mini_close');
	
			var closeFunction = function () {
				MOOdalBox.close();
				if (okFunction)
					okFunction();
			};
		
			titleDiv.innerHTML = titleMessage;
			messageDiv.innerHTML = infoMessage;
			closeButton.onclick = closeFunction;
			okButton.onclick = closeFunction;	
		};
	
		MOOdalBox.open( window['info_dialog'], "info", "502" );
}

function showCustomDialogs(/* string */ urlDialog, /* JSON object */ param, /* function */ funcExec, /* String*/ dialogId, /*String */ width){
	/*
	var param = {'post.dialog.insert.function':'portal$web$menus$insertLink'};
	var urlDialog = "${linkDialogURL}&request.ajax=true&" + Object.toQueryString(param);
	var emptyFunc = function() {};
	*/
	MOOdalBox.options.afterFetch = funcExec;		
	//MOOdalBox.open(urlDialog + "&request.ajax=true&" + Object.toQueryString(param), dialogId, width);
	MOOdalBox.openWithPost(urlDialog + "&request.ajax=true", dialogId, width, param);
}

function submitForm(/* string */ uri, /* string */ formId) {
	var form = document.getElementById(formId);
	if (window['___portal___'] != '') 
		uri = addNameValue(uri, 'portal=' + window['___portal___']);
	form.action = uri;
	form.target = null;
	form.submit();
}

function removeNameValue(/* string */ url, /* string */ nameValue) {
	var index = url.indexOf(nameValue);
	var add = true;
	
	if (index > 0) {
		var before = url.charAt(index-1);
		if (before == '?'  || before == '&') {
			if (url.length > (index + nameValue.length)) {
				var after = url.charAt(index + nameValue.length);				
				if (after == '&') {
					url = url.replace(nameValue, "");
				}
			}
		} else {
			url = url.replace(nameValue, "");
		}
	}
	return url;
}

function addNameValue(/* string */ url, /* string */ nameValue) {
	var index = url.indexOf(nameValue);
	var add = true;
	
	if (index > 0) {
		var before = url.charAt(index-1);
		if (before == '?'  || before == '&') {
			if (url.length > (index + nameValue.length)) {
				var after = url.charAt(index + nameValue.length);				
				if (after == '&') {
					add = false;
				}
			} else if (url.length == (index + nameValue.length)) 
				add = false;
		} else {
			add = false;
		}
	}

	if (add) {
		if (url.indexOf('?') == -1)
			url = url.concat('?').concat(nameValue);
		else
			url = url.concat('&').concat(nameValue);
	}
	return url;
}



function updateTarget(
	/* string */ url, 				// The request URL
	/* JSON object */ params, 		// The request parameters
	/* string */ method, 			// The request method
	/* boolean */ sync, 			// True for synchronous requests; false otherwise
	/* string */ targetId,			// The html container
	/* dialog */ progress, 			// The progress dialog to show; or null for no progress
	
	/* function */ beforeUpdateCallback,	// Function called before updating the target id
	/* function */ afterUpdateCallback,		// Function called after updating the target id
	/* function */ onErrorCallback,			// Function called if an error occurs. Receives the backURL has a parameter.
	/* function */  errorFunction,			// Error function to call to display error messages. The function receives
	/* boolean */ useViewState										// 3 parameters: error message, the back URL and the error callback
	) 
{
	if (window['___portal___'] && window['___portal___'] != '') 
		params['portal'] = window['___portal___'];
		
	params['request.ajax'] = true;
	
	if (window['___debug___']) {
		for (name in params) {
			url = addNameValue(url, params[name]);
		};		
		url = removeNameValue(url, 'section');
		alert(url);
		window.location = url;				
		return;
	}

	// Remove after testing
	if (sync)
		alert('Synchronous requests are not support by Safari');

	if (progress)
		progress.show();

	/*if (useViewState == undefined || useViewState == true) {		
		//save pagination fields on view state
		paginationViewState.update(params);
		//put on params view state fields
		paginationViewState.setValues(params);		
	}*/
	
	// var oldcursor = document.body.style.cursor;
	// document.body.style.cursor = 'wait';
	
	var ajax = new Ajax( url, { 
		method: method, 
		async:!sync, 
		postBody: params,
		onSuccess: function( response, xml ) {
			if (progress)
				progress.hide();
			var transport = ajax.transport;
			
			if (transport.getResponseHeader('MetaPortal-Session-Expired')) {
				document.location = transport.getResponseHeader('MetaPortal-Error-Url');
				return false;
				
			} else if (transport.getResponseHeader('MetaPortal-Error')) {								
				var funcToCall = errorFunction ? errorFunction : showError;
				funcToCall(
					transport.getResponseHeader('MetaPortal-Error'), 
					transport.getResponseHeader('MetaPortal-Error-Url'),
					onErrorCallback);
				return false;
				
			} else {
				if (beforeUpdateCallback)
					beforeUpdateCallback();
					
				var elem = $(targetId);
				if ( $chk(elem) ) {
					elem.setHTML( response );
					//eval( response );
					ajax.evalScripts();
				}
				
				if (afterUpdateCallback)
					afterUpdateCallback();				
				return true;
			}
		}, 
		onFailure: function( response, xml ) {
			if (progress)
				progress.hide();
			if (errorFunction) {
				errorFunction(null, null, onErrorCallback);
			} else {
				//dialogInternalError.show();
				showInternalError();
				if (onErrorCallback)
					onErrorCallback();
			}
		}
	 } );
	ajax.request();	
}

function submitAndUpdateTarget(
	/* string */ url, 				// The request URL
	/* JSON object */ params, 		// The extra request parameters	
	/* string */ formId, 			// The form id to submit
	/* boolean */ sync, 			// True for synchronous requests; false otherwise
	/* string */ targetId,			// The html container
	/* dialog */ progress, 			// The progress dialog to show; or null for no progress
	
	/* function */ beforeUpdateCallback,	// Function called before updating the target id
	/* function */ afterUpdateCallback,		// Function called after updating the target id
	/* function */ onErrorCallback,			// Function called if an error occurs. Receives the backURL has a parameter.
	/* function */  errorFunction,			// Error function to call to display error messages. The function receives
	/* boolean */ useViewState				// 3 parameters: error message, the back URL and the error callback
									
	) 
{
	if (window['___portal___'] && window['___portal___'] != '') 
		params['portal'] = window['___portal___'];

	params['request.ajax'] = true;

	// Remove after testing
	if (sync)
		alert('Synchronous requests are not support by Safari');
		
	/*if (useViewState == undefined || useViewState == true) {		
		//save pagination fields on view state
		paginationViewState.update(params);
		//put on params view state fields
		paginationViewState.setValues(params);		
	}*/

	
	var form = document.getElementById( formId );
	
    form.action = url;	
		
	if ( form.method == "" || !form.method ) {
		form.method = "get";
	}
	
	if (window['___debug___']) {
		for (name in params) {
			url = addNameValue(url, params[name]);
		};		
		url = removeNameValue(url, 'section');
		alert(url);
		submitForm(url, formId);				
		return;
	}


	// var oldcursor = document.body.style.cursor;
	// document.body.style.cursor = 'wait';
	
	url = url + "&" + Object.toQueryString(params);
	
	if (progress)
		progress.show();

	var ajax = new Ajax( url, { 
		method: form.method, 
		async:!sync,
		postBody: _formToQueryString( form ), 
		onSuccess: function( response, xml ) {
			if (progress)
				progress.hide();
			var transport = ajax.transport;
			if (transport.getResponseHeader('MetaPortal-Session-Expired')) {

				document.location = transport.getResponseHeader('MetaPortal-Error-Url');
				return false;
			} else if (transport.getResponseHeader('MetaPortal-Error')) {

				var funcToCall = errorFunction ? errorFunction : showError;
				funcToCall(
					transport.getResponseHeader('MetaPortal-Error'), 
					transport.getResponseHeader('MetaPortal-Error-Url'),
					onErrorCallback);
				return false;
			} else {
				// document.body.style.cursor = oldcursor;
				if (beforeUpdateCallback)
					beforeUpdateCallback();

				var elem = $(targetId);
				if ( $chk(elem) ) {
					elem.setHTML( response );
					ajax.evalScripts();
				}

				if (afterUpdateCallback)
					afterUpdateCallback();
				return true;
			}
		}, 
		onFailure: function( response, xml ) {
			if (progress)
				progress.hide();

			if (errorFunction) {
				errorFunction(null, null, onErrorCallback);
			} else {
				//dialogInternalError.show();
				showInternalError();
				if (onErrorCallback)
					onErrorCallback();
			}
		}
	 } );
	ajax.request();
}

function submitFileForm(
	/* string */ url, 				// The request URL
	/* JSON object */ params, 		// The extra request parameters	
	/* string */ formId, 			// The form id to submit	
	/* dialog */ progress, 			// The progress dialog to show; or null for no progress	
	/* function */ afterLoadCallback,		// Function called after loading the iframe
	/* function */ onErrorCallback,			// Function called if an error occurs. Receives the backURL has a parameter.
	/* function */  errorFunction			// Error function to call to display error messages. The function receives
											// 3 parameters: error message, the back URL and the error callback	
	) 
{
	if (window['___portal___'] != '') 
		params['portal'] = window['___portal___'];

	params['request.ajax'] = true;

	//alert('Deprecated function - use submitFileForm instead');
	var form = document.getElementById(formId);

	// var oldcursor = document.body.style.cursor;
	// document.body.style.cursor = 'wait';

	var iframeId = 	formId + '_hiddenFrame';
	var iframeDivId = iframeId + '_hiddenFrame$div';
	var iframeDiv = document.getElementById(iframeDivId);
	if (!iframeDiv){		
		var iframeCallbackId = iframeId + '_callback';
		iframeDiv = document.createElement('div');
		iframeDiv.id = iframeDivId;
		// iframeDiv.style.display = "none"; // Causes safari to open a  new window
		iframeDiv.innerHTML = '<iframe width="0px" height="0px" frameborder="0" id="' + iframeId + '" ' +
					' name="' + iframeId + '" ' + 
					' src="" onload="window[\'' + iframeCallbackId+ '\']()"></iframe>' ;
		document.body.appendChild(iframeDiv);
		var iframe = document.getElementById(iframeId);

		window['MetaPortal-Error'] = null;
		window['MetaPortal-Error-Url'] = null;
		window['MetaPortal-Session-Expired'] = null;
		window[iframeCallbackId] = function () {
			if (progress)
				progress.hide();				

			var iframe = document.getElementById(iframeId);
			
			if (window['MetaPortal-Session-Expired']) {
				// document.body.style.cursor = oldcursor;
				document.location = window['MetaPortal-Error-Url'];
			} else if (window['MetaPortal-Error']) {
				// document.body.style.cursor = oldcursor;
				var funcToCall = errorFunction ? errorFunction : showError;
				funcToCall(
					window['MetaPortal-Error'], 
					window['MetaPortal-Error-Url'],
					onErrorCallback);
			} else {
				if (progress)
					progress.hide();				
				
				var doc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
				if (afterLoadCallback)
					afterLoadCallback(doc.body.innerHTML);
				// document.body.style.cursor = oldcursor;
			}
		};				
	}
		
	// Pass the extra params to the form to be submitted.
	for (name in params) {
		if (name != 'extend') {
			var hiddenInput = document.getElementById(name);
			if (!hiddenInput) {
				hiddenInput = document.createElement("input");
				hiddenInput.id = name;
				hiddenInput.name = name;
				hiddenInput.type = "hidden";
				form.appendChild(hiddenInput);
			}
			hiddenInput.value = params[name];
		}
	}
		
    form.action = url;	
		
	if ( form.method == "" || !form.method ) {
		form.method = "get";
	}

	if (progress)
		progress.show();
		
	form.target = iframeId;
	form.submit();
}

/**
 * Function to return parameter value from Href
 */
function getURLParam(strHref, strParamName){
	var strReturn = undefined;
	if ( strHref.indexOf("?") > -1 )
	{
		var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ )
		{
			if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
			  var aParam = aQueryString[iParam].split("=");
			  strReturn = aParam[1];
			  break;
			}
		}
	}
	return strReturn;
}


/*
 * Function that trims a string.
 */
function trim(/* string */ str) {
	if (str.replace) {
		var str = str.replace(/^\s+/, '');
		return str.replace(/\s+$/, '');
	}
	return str;
}

/**
 * Fetches the calculated style for the styleProp argument.
 * @param element target element.
 * @param styleProp target property name.
 * @return string with style value or null if not found
 */	
function getStyle( /*dom object*/ element, /*string*/ styleProp ) {
		var x = element;
		if (x.currentStyle) {
			return x.currentStyle[styleProp];
		} else if (window.getComputedStyle) {
			return document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
		} else {
			return null;
		}
}

	
/* PRIVATE FUNCTIONS */


function _formToQueryString( form ) {
	var str = "";
	var queryString = [];
	
	$$( form.getElementsByTagName('input'), 
		form.getElementsByTagName('select'), 
		form.getElementsByTagName('textarea') ).each(function(el){


		var name = $(el).name;
		var value = el.getValue();
		var type = el.getProperty("type");
	
		if ( type ) {
			switch( type.toLowerCase() ) {
				case "checkbox":
				case "radio":
					if ( value == false ) {
						break;
					}
					queryString.push(encodeURIComponent(name)+'='+encodeURIComponent(value));
					break;
				case "button":
				case "reset":
				case "submit":
					break;
				default:
					queryString.push(encodeURIComponent(name)+'='+encodeURIComponent(value));
			}
		} else {
			queryString.push(encodeURIComponent(name)+'='+encodeURIComponent(value));
		}
		/*
		if ( !( type && 
			( type.toLowerCase() == "checkbox" || type.toLowerCase() == "radio" ) &&
			value == false ) ) {
			queryString.push(name+'='+value);
		}
		*/
		//queryString.push(encodeURIComponent(name)+'='+encodeURIComponent(value));
		//queryString.push(name+'='+value);
	});	
		
	return queryString.join('&');
}
 
 


function _addPaginationsFields ( /* JSON */ params)
{
	// Add pagination state
	var pagParams = paginationViewState.params;
	for (keyField in pagParams) {
		if(!params[keyField])
			params[keyField] = pagParams[keyField];
	}	
}


// Implement the ScriptLoader using async true for Safari
// For that use an array to check the order of loaded files
/*window['scriptLoader$filesLoadingState'] = new Array();
    load: function() {
        for (var i = 0, len = arguments.length; i < len; i++) {
            var filename = arguments[i];
            if (!this.loaded[filename] && this.isFileInHeadTag() == false) {
            	var loader = this;
            	
            	var loadFunc = function () {
            		if (window['scriptLoader$filesLoadingState'][filename] && window['scriptLoader$isLoading'] == true) {
            			setTimeout(loadFunc, 100);
            		}else {            		
	            		window['scriptLoader$isLoading'] = true;
	            		alert("Load: " + filename);
		            	var ajax = new Ajax( filename, { 
							method: "get", 
							async: true, 
							onSuccess: function( response, xml ) {
								try {
									loader.globalEval(response);
			                        loader.loaded[filename] = true;
								}catch(e) {
									alert("Error on eval script for " + filename + ":\r\n" + e);
								}
								alert("File loaded: " + filename);
								window['scriptLoader$isLoading'] = false;
							}, 
							onFailure: function( response, xml ) {
								alert("Error loading script (" + filename + ")");
								window['scriptLoader$isLoading'] = false;
							}
						 } );
						ajax.request();	            		
            		}
            	};
            	loadFunc();
            }
        }*/

//if (window.khtml == true) {
// TODO Check for how to include the files with safari
/*if (window.khtml == true) {
	alert("Loader not working yet for safari, I have to guarentee that files are loaded");
	window['isLoading'] = false;
	var ScriptLoader = {
		delay: 100,
		isLoading: false,
		filesStack: null,
	    request: null,
	    loaded: {},
	    load: function() {
	    	if (!this.filesStack)
	    		this.filesStack = new Array();

	    	
	        for (var i = 0, len = arguments.length; i < len; i++) {
	            var filename = arguments[i];
	            
	            if (!this.loaded[filename] && this.isFileInHeadTag() == false) {
	            	
	            	// Add file to the stack of files to be loaded
	            	this.filesStack.push(filename);
		            var loader = this;	
		            var loadFunc = function () {	
		            	if (window['isLoading'] == false) {
		            		var fileAux = loader.filesStack.shift(); // Removes the first file of the array and try to load it
		            		if (fileAux) {
		            			
		            			window['isLoading'] = true;		            			
								var ajax = new Ajax( fileAux, { 
									method: "get", 
									async: true, 
									onSuccess: function( response, xml ) {										
										try {
											loader.globalEval(response);
											window['isLoading'] = false;
											alert("File " + fileAux + " loaded.");
										}catch(e) {
											alert("Error on eval script for " + fileAux + ":\r\n" + e);
										}
									}, 
									onFailure: function( response, xml ) {
										alert("Error loading script (" + fileAux + ")");
										window['isLoading'] = false;
									}
								 } );
								ajax.request();		            			
		            		}
		            	}else
		            		setTimeout(loadFunc, loader.delay);		            		
			        };
		        	loadFunc();
	        	}
	        }
	    },
	    globalEval: function(code) {	    	
	        if (window.execScript) window.execScript(code, 'javascript');
	        else window.eval(code);
//			if(window.execScript){
//	    		return window.execScript(code, "javascript");
//			} else if(window.khtml == true){ //safari, konqueror..
//	      		var s = document.createElement("script");
//		      	s.type = "text/javascript";
//		      	s.innerHTML = code;
//		      	document.getElementsByTagName("head")[0].appendChild(s);
//			} else {
//				return window.eval(code);
//			}
	    },
	    isFileInHeadTag: function (filename) {
	    	var head = document.getElementsByTagName("head")[0];
	    	if (head) {
	    		var scripts = head.getElementsByTagName("script");
	    		for (var i = 0; i < scripts.length; i ++) {
	    			if (scripts[i].src == filename)
	    				return true;
	    		}    		
	    	}
	    	return false;
	    }
	}
}else {*/
	var ScriptLoader = {
	    request: null,
	    loaded: {},
	    load: function() {
	        for (var i = 0, len = arguments.length; i < len; i++) {
	            var filename = arguments[i];
	            if (!this.loaded[filename] && this.isFileInHeadTag() == false) {
	            	var loader = this;	
	            	if (!loader.request) {	            		
            			if (window.XMLHttpRequest) {
            				loader.request = new XMLHttpRequest;            				
            			}else if (window.ActiveXObject) {            				
            		    	try { loader.request = new ActiveXObject('MSXML2.XMLHTTP'); }
            		    	catch (e) { loader.request = new ActiveXObject('Microsoft.XMLHTTP'); }
            			}
                	}
                	if (loader.request) {                		
                    	loader.request.open('GET', filename, false); // synchronous request!
                    	loader.request.send(null);
                    	if (loader.request.status == 200) {                    		
                        	loader.globalEval(loader.request.responseText);
                        	loader.loaded[filename] = true;
                    }
                }
	            	
	            	
	            	            	
	            	/*var ajax = new Ajax( filename, { 
						method: "get", 
						async: true,
						onSuccess: function( response, xml ) {
							
							try {
								loader.globalEval(response);
								loader.loaded[filename] = true;
							}catch(e) {
								alert("Error on eval script for " + filename + ":\r\n" + e);
							}
						}, 
						onFailure: function( response, xml ) {
							alert("Error loading script (" + filename + ")");
						}
					 } );					
					ajax.request();*/					
	            }
	        }
	    },
	    globalEval: function(code) {
	    	try {	    	
	        	if (window.execScript) window.execScript(code, "javascript");
	        	else window.eval(code);
	        }catch(err) {
	        	alert("Error loading file: " + err.description);
	        }
	/*		if(window.execScript){
	    		return window.execScript(code, "javascript");
			} else if(window.khtml == true){ //safari, konqueror..
	      		var s = document.createElement("script");
		      	s.type = "text/javascript";
		      	s.innerHTML = code;
		      	document.getElementsByTagName("head")[0].appendChild(s);
			} else {
				return window.eval(code);
			}*/
	    },
	    isFileInHeadTag: function (filename) {
	    	var head = document.getElementsByTagName("head")[0];
	    	if (head) {
	    		var scripts = head.getElementsByTagName("script");
	    		for (var i = 0; i < scripts.length; i ++) {
	    			if (scripts[i].src == filename)
	    				return true;
	    		}    		
	    	}
	    	return false;
	    }
	}	
//}		

var CSSLoader = {
    loaded: {},
    load: function() {
        for (var i = 0, len = arguments.length; i < len; i++) {
            var filename = arguments[i];
            if (!this.loaded[filename] && this.isFileInHeadTag() == false) {
	        	this.loaded[filename] = true;
				new Asset.css(filename, {}); // Put the link in head tag
            }
        }
    },
    isFileInHeadTag: function (filename) {
    	var head = document.getElementsByTagName("head")[0];
    	if (head) {
    		var links = head.getElementsByTagName("link");
    		for (var i = 0; i < links.length; i ++) {
    			if (links[i].href == filename)
    				return true;
    		}    		
    	}
    	return false;
    }
}


