/*
 * Global variables
 */
var loading = false;
var admin = 0;
var serverURL = '';
var resizeMainWindow = null;
var ajaxWindowCount = 0;

/*
 * AJAX window functions.
 */
function grayOutWindow ()
{
	var wndWidth;
	var wndHeight;
	
	// fix for getting document scroll width/height in Safari and Google Chrome
	// for TRANSITIONAL documents
	if (Browser.Engine.webkit)
	{
		wndWidth = $(document.body).scrollWidth;
		wndHeight = $(document.body).scrollHeight;
	} else
	{
		wndWidth = Window.getScrollWidth();
		wndHeight = Window.getScrollHeight();
	}
	
	var div = new Element('div', {'id': 'ajaxWindow'+ajaxWindowCount, 'class': 'ajaxWindow'});
	
	div.setStyles({
		position: 'absolute',
		left: '0px', top: '0px',
		width: wndWidth+'px', height: wndHeight+'px',
		backgroundColor: '#000000',
		opacity: 0.5,
		zIndex: 15000+ajaxWindowCount,
		visibility: 'visible'
	});
	
	$(document.body).adopt(div);
	
	ajaxWindowCount++;
	
	return ajaxWindowCount-1;
}

function ajaxWindow (_title, _content, _ajaxWndWidth, _ajaxWndHeight, _class)
{
	grayOutWindow();
	
	var wndWidth = Window.getWidth();
	var wndHeight = Window.getHeight();
	
	if (!$defined(_ajaxWndWidth))
		_ajaxWndWidth = 250;
	if (!$defined(_ajaxWndHeight))
		_ajaxWndHeight = 200;
	// by default, assume the 'ajaxWindow' class
	if (!$defined(_class))
		_class = 'ajaxWindow';
	
	var div = new Element('div', {id: 'ajaxWindow'+ajaxWindowCount, 'class': _class});
	
	div.setStyles({
		left       : (wndWidth-_ajaxWndWidth)/2,
		top        : ((wndHeight-_ajaxWndHeight)/2)+Window.getScrollTop(),
		width      : _ajaxWndWidth+'px',
		height     : _ajaxWndHeight+'px',
		opacity    : 1,
		visibility : 'visible',
		'z-index'  : 15000+ajaxWindowCount,
		'position' : 'absolute'
	});
	
	div.set('html',
		"<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"windowFrame\" id=\"ajaxWindowFrame"+ajaxWindowCount+"\">"+
		"<tr><td class=\"titleContainer\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"title\" id=\"ajaxWindowTitle"+ajaxWindowCount+"\">"+
		"		<tr><td class=\"topLeft\">&nbsp;</td>"+
		"		<td class=\"topMiddle\"><div id=\"ajaxWindowTitleText"+ajaxWindowCount+"\">"+_title+"</div></td>"+
		"		<td class=\"topClose\"><a href=\"#\" title=\"Close\" onclick=\"closeAjaxWindow('"+ajaxWindowCount+"'); return false;\"><img id=\"ajaxWindowCloseButton"+ajaxWindowCount+"\" src=\""+serverURL+"/cms/css/AjaxWindow/closeButton.jpg\" /></a></td>"+
		"		<td class=\"topRight\">&nbsp;</td></tr>"+
		"	</table></td></tr>"+
		"<tr><td>"+
		"	<table id=\"ajaxWindowBody"+ajaxWindowCount+"\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"body\">"+
		"	<tr><td class=\"border\">&nbsp;</td>"+
		"		<td class=\"leftPadding\"><img src=\""+serverURL+"/cms/css/AjaxWindow/topLeftInnerCorner.jpg\" /></td>"+
		"		<td class=\"innerTopMiddle\">&nbsp;</td>"+
		"		<td class=\"rightPadding\"><img src=\""+serverURL+"/cms/css/AjaxWindow/topRightInnerCorner.jpg\" /></td>"+
		"		<td class=\"border\">&nbsp;</td></tr>"+
		"	<tr><td class=\"border\">&nbsp;</td>"+
		"		<td class=\"leftPadding\">&nbsp;</td>"+
		"		<td class=\"innerBody\"><div id=\"ajaxWindowContent"+ajaxWindowCount+"\" class=\"contentContainer\">"+_content+"</div><br /></td>"+
		"		<td class=\"rightPadding\">&nbsp;</td>"+
		"		<td class=\"border\">&nbsp;</td></tr>"+
		"	</table>"+
		"</tr></td>"+
		"<tr><td>"+
		"	<table id=\"ajaxWindowFooter"+ajaxWindowCount+"\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"footer\">"+
		"	<tr><td class=\"bottomLeft\">&nbsp;</td>"+
		"		<td class=\"bottomMiddle\">&nbsp;</td>"+
		"		<td class=\"bottomRight\">&nbsp;</td></tr>"+
		"	</table>"+
		"</tr>"+
		"</table>");
	
	// insert the AJAX window into the document body
	$(document.body).adopt(div);
	
	var bodyHeight = _ajaxWndHeight-
		$('ajaxWindowFooter'+ajaxWindowCount).getHeight()-
		$('ajaxWindowTitle'+ajaxWindowCount).getHeight();
	
	$('ajaxWindowFrame'+ajaxWindowCount).set('width', _ajaxWndWidth+'px');
	$('ajaxWindowFrame'+ajaxWindowCount).set('height', _ajaxWndHeight+'px');
	if ($('ajaxWindowContent'+ajaxWindowCount).getHeight() > bodyHeight)
	{
		$('ajaxWindowContent'+ajaxWindowCount).setStyle('height', bodyHeight+'px');
		$('ajaxWindowContent'+ajaxWindowCount).setStyle('overflow', 'scroll');
	}
	$('ajaxWindowBody'+ajaxWindowCount).setStyle('height', bodyHeight+'px');
	
	var scrollWidth, scrollHeight;
	
	// fix for getting document scroll width/height in Safari and Google Chrome
	// for TRANSITIONAL documents
	if (Browser.Engine.webkit)
	{
		scrollWidth = $(document.body).scrollWidth;
		scrollHeight = $(document.body).scrollHeight;
	} else
	{
		scrollWidth = Window.getScrollWidth();
		scrollHeight = Window.getScrollHeight();
	}
	
	// enable window dragging
	new Drag($('ajaxWindow'+ajaxWindowCount), {handle: $('ajaxWindowTitle'+ajaxWindowCount),
		limit: {x:[0,scrollWidth-_ajaxWndWidth], y:[0,scrollHeight-_ajaxWndHeight-40]}});
	
	// increment the AJAX window counter
	ajaxWindowCount++;
	
	return ajaxWindowCount-1;
}

function ajaxRequest (_data, _onComplete, _onFailure, _onException, _onCancel)
{
	var _requestVar = new Request({url: serverURL+'ajax',
				method: 'post',
				data: _data,
				onFailure: function (_xhr) {
					alert('The request failed due to connection problems, please try again.');
					if ($defined(_onFailure))
						_onFailure(_xhr);
				},
				onException: function (_header, _value) {
					alert('An exception occurred while setting the request header:\n\n'+_header+'\n\n'+_value);
					_onFailure('exception');
					if ($defined(_onException))
						_onException(_header, _value);
				},
				onCancel: function () {
					alert('The request has been cancelled.');
					if ($defined(_onCancel))
						_onCancel();
				},
				onComplete: function (_data)
				{
					var _returnObject;
					_returnObject = eval('('+_data+')');
					//if( (_returnObject = JSON.decode(_data)) != false )
					//{
						switch (_returnObject.status)
						{
							case 'error':
								alert(_returnObject.message);
								break;
							case 'warning':
								alert(_returnObject.message);
								break;
							case 'success':
								if ($defined(_onComplete))
									_onComplete(_returnObject.data);
								break;
						}
					//}
				}
			});
	
	if(_requestVar == '')
	{
		alert('Fatal error, no request has been specified, please contact the administrators.');
		return null;
	}
	
	// Check if the request is running
	if(!$defined(_requestVar.running) || _requestVar.running==false)
	{
		// setup the AJAX request
		_requestVar.send();
		return _requestVar;
	} else
		alert('Another request is currently processing, please try again later.');
		
	return null;
}

/*
 * Pops up an AJAX window and loads its content from the server via the given command.
 */ 
function ajaxWindowFromModule (_page, _slot, _module, _cmd, _params, _onComplete)
{
	// make sure we define the _params variable
	if (!$defined(_params))
		_params = '';
		
	var wndID = ajaxWindow('Loading...', "<img src=\""+serverURL+"/cms/css/AjaxWindow/loading.gif\" />");
	var wndWidth = Window.getWidth();
	var wndHeight = Window.getHeight();
	
	var request = ajaxRequest({page: _page, slot: _slot, module: _module, cmd: _cmd, params: _params},
		// _onComplete
		function (_data) {
			// assume that the title, content, width and height variables
			// are set in the _data object
			$('ajaxWindow'+wndID).setStyles({left: (wndWidth-_data.width)/2,
				top: ((wndHeight-_data.height)/2)+Window.getScrollTop()});
			$('ajaxWindow'+wndID).setStyles({width: _data.width+'px', height: _data.height+'px'});
			$('ajaxWindowFrame'+wndID).setStyles({width: _data.width+'px', height: _data.height+'px'});
			$('ajaxWindowTitleText'+wndID).set('html', _data.title);
			$('ajaxWindowContent'+wndID).set('html', _data.content);
			var bodyHeight = _data.height-$('ajaxWindowFooter'+wndID).getHeight()-
				$('ajaxWindowTitle'+wndID).getHeight();
				
			if ($('ajaxWindowContent'+wndID).getHeight() > bodyHeight)
			{
				$('ajaxWindowContent'+wndID).setStyle('height', bodyHeight+'px');
				$('ajaxWindowContent'+wndID).setStyle('overflow', 'scroll');
			}
			$('ajaxWindowBody'+wndID).setStyle('height', bodyHeight+'px');
			
			if ($defined(_onComplete))
				_onComplete(wndID, _data);

		},
		// _onFailure
		function (_xhr) {
			closeAjaxWindow(wndID);
		},
		// _onException
		function (_header, _value) {
			closeAjaxWindow(wndID);
		}
	);
	
	if (request == null)
	{
		window.alert('Unable to initialize AJAX request. Please contact the system administrator.');
		closeAjaxWindow(wndID);
	} else
	{
		// add an event to cancel the AJAX request
		$('ajaxWindowCloseButton'+wndID).addEvent('click', function() { request.cancel(); });
	}
	
	return wndID;
}

function closeAjaxWindow (_wndID)
{
	var wnd = 'ajaxWindow'+_wndID;
	var grayWnd = 'ajaxWindow'+(_wndID-1);
	
	$(wnd).dispose();
	ajaxWindowCount--;

	if ($defined($(grayWnd)))
	{
		$(grayWnd).dispose();
		ajaxWindowCount--;
	}
}

/*
 * Date validation by regular expression.
 */ 
function isValidDate (_date)
{
	var expr = /(2[0-8][0-9][0-9])-([0-1][0-9])-([0-3][0-9])/;
	
	// first test if it simply conforms to the standard
	if (!expr.test(_date))
		return false;
	
	// then, check each component for validity
	var ar = expr.exec(_date);
	// check the months
	if ((ar[2] > 12) || (ar[2] < 1))
		return false;
	// check the days
	if ((ar[3] > 31) || (ar[3] < 1))
		return false;
	
	return true;
}

/*
 * E-mail address validation by regular expression
 */
function isValidEmail (_email)
{
	var emailChecker = /^[a-zA-Z]([a-zA-Z0-9_-]+\.?)+@([a-zA-Z0-9_-]+\.)([a-zA-Z0-9_-]+\.?)+$/g;
	// reset the regular expression
	emailChecker.lastIndex = 0;
	
	return emailChecker.test(_email);
}
