/*
 * Common javascript functions.
 * 
 * NOTE: as richfaces loads ALL script files before it out puts <script><script> files you cannot
 * depend on variables like contextpath being already defined.
 */

/** */
var dev = false;
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
var isSafari = false;
if (jQuery)
	isSafari = jQuery.browser.safari || jQuery.browser.webkit;
else
	isSafari = navigator.appVersion.indexOf('Safari') != -1;

/** */
function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

/* create fake console for non-firebug environments */
if (!isdefined('console'))
{
	window.console = {
		error: function() {},
		info: function() {},
		debug: function() {},
		warn: function() {}
	};
}
else if (!console.debug)
{
	console.debug = function(){
		if (typeof(console.info) == 'function')
			console.info.apply(console, arguments);
		else
			console.info("DEBUG: ", Array.prototype.slice.call(arguments));
	};
}

/**
 * logging class, wrapper around console.
 * AJAX4JSF has a class called LOG so be careful.
 * @constructor
 */
function log(){};

/**
 * Delgates to console.error
 * @return
 */
log.error = function()
{
	log._call(console.error, arguments);
};

/**
 * Delgates to console.info
 * @return
 */
log.info = function()
{
	log._call(console.info, arguments);
};

/**
 * Util function.
 * @return
 */
log._call = function(func, args)
{
	//the original caller is arguments.callee.caller
	//could do something with it...
	if (dev && isdefined('console'))
	{
		//if (isSafari)
		//	func.apply(console, args);
		if ((typeof(func) == 'function'))
			func.apply(console, args);
		else
			func(Array.prototype.slice.call(args));
	}
};

/**
 * 
 * @return
 */
log.debug = function()
{
	log._call(console.debug, arguments);
};

String.prototype.startsWith = function(prefix)
{
	if (!prefix)
		return false;
	return (this.substring(0, prefix.length)==prefix);
};

String.prototype.endsWith = function(suffix)
{
	if (!suffix)
		return false;
	return (this.substring(this.length - suffix.length) == suffix);
};

String.prototype.replaceWith = function(start, len, newVal)
{
	return this.substring(0, start) + newVal + this.substring(start + len + 1);
};

function popupWin(targetPg, winName, forceReload, secure) 
{
	if (secure != null && secure)
	{
		//popupWinForce(contextForceHttps, targetPg, winName, forceReload, secure);
		// set the target url to load
		var targetURL = contextForceHttps + '/' + targetPg;
		loadPage(targetURL);
	}
	else
		popupWinForce(contextForceHttp, targetPg, winName, forceReload, secure);
}

function popupWinForce(context, targetPg, winName, forceReload, secure) 
{
	var options = {
			resizable:'yes', 
			scrollbars:'no',
			toolbars: 'no',
			status: 'yes',
			left: 0,
			top: 0,
			height: 600,
			width: 1000
	};
	
	//alert('popupWin ' + screen.width + ", " + screen.height);
	//if (secure)
	//	alert('secure == true');
	//else
	//	alert('secure == false');
	// determine the position and size of the popup based on user's screen.

	if (screen.width < 1000) {
		//alert(screen.width +'X' +screen.height);
		options.width = screen.width * 0.97;
		options.height = screen.height * 0.95;
		options.left = screen.width * 0.05 / 2.0;
		options.top = 0;
	} else {
		//alert(screen.width +'X' +screen.height);
		options.width = screen.width * 0.97;
		options.height = screen.height * 0.95;
		options.left = screen.width * 0.15 / 2.0;
		options.top = (screen.height * 0.2 / 2.0) - 40;
	}
	//alert('popupWin ' + options.left + ", " + options.top+ ", " + options.width + ", " + options.height);
	if (winName == 'memberMgmt') {
		options.width = 100;
		options.height = 100;
		var allowanceX = 400;
		var allowanceY = 300;
		options.left = (window.screen.availWidth - allowanceX) / 2 + 5;
		options.top = (window.screen.availHeight - allowanceY) / 3 + 5;
		options.scrollbars = 'yes';
	}
	if (winName == 'testwin') {
		options.left += (options.width * 0.4) / 2.0;
		options.width = options.width * 0.6;
		options.height = options.height * 0.6;
		options.scrollbars = 'yes';
	}
	if (winName == 'iypMiniTournWin') {
		options.scrollbars = 'yes';
	}
	if (winName == 'iypMajorTournWin') {
		options.scrollbars = 'yes';
	}
	if (winName == 'showLegals') {
		options.scrollbars = 'yes';
	}
	if (winName == 'iypTwoPlayerWin') {
		options.scrollbars = 'yes';
	}
	// set the target url to load
	var targetURL = context + '/' + targetPg;
	
	// open the popup window
	// if it is already open it will do nothing except give us a reference to it
	// if it is not open it will create it (with no content) and give us a
	// reference to it.
	
	if (window[winName] && !window[winName].closed && window[winName].location) 
	{
		//TODO Commented during the changes to the pool room as per the client request
		//window[winName].close();
	}
	
	var winoptions = '';
	for (var i in options)
	{
		if (winoptions!='') winoptions += ',';
		winoptions += i + '=' + options[i];
	}

	//log.debug('popupWinForce', winName + sessionid, winoptions);
	var newWindow = window.open('', winName + sessionid, winoptions);
	window[winName] = newWindow;
	if (!newWindow)
	{
		//error
		alert("Please enable pop-ups for this site");
		return;
	}

	var newWindowLocation = '' + newWindow.location.href;
	var newWindowLocation_split = new Array();
	var targetURL_split = new Array();

	// turn the current page in the popup window into an array delimited by '/'
	if (newWindowLocation.length > 1) {
		newWindowLocation_split = newWindowLocation.split('/');
	}
	// turn the target URL to be loaded into an array delimeted by '/'
	if (targetURL.length > 1) {
		targetURL_split = targetURL.split('/');
	}

	if (newWindowLocation_split.length != 0 && targetURL_split.length != 0) {
		// check if the last element of the 2 arrays matches
		if (newWindowLocation_split[newWindowLocation_split.length - 1]
				.split('?')[0] != targetURL_split[targetURL_split.length - 1]
				.split('?')[0]) {
			// they dont match so reload the game window to the target url
			forceReload = 1;
		}
	}

	if (forceReload == 1) {
		// special case - stop reload if we're in major tourns and window is not empty
		if (targetPg.split('?')[0] == '/web/majorTourn/detail.htm'
				|| targetPg.split('?')[0] == '/web/majorTourn/list.htm') {
			if (newWindowLocation == '' || newWindowLocation == 'about:blank')
				loadPage(targetURL, winName + sessionid);
		} else
			loadPage(targetURL, winName + sessionid);
	}
	newWindow.focus();
}

function loadPage(url, target) {
	var myForm = $('pageLoader');
	var d = new Date();
	myForm.iypcachedt.value = d.getTime();
	myForm.action = url;
	if (target == '' || target == null)
		myForm.target = '_self';
	else
		myForm.target = target;
	myForm.submit();
}

function reloadOpener() {
    if(window.top.opener != null && !window.top.opener.closed){
    	//alert('href=' + window.top.opener.location.href);
        window.top.opener.location.href=contextForceHttp+'/';
    } else {
        window.open(contextForceHttp+'/');
    }
    window.focus();
}

/**
 * sets the form's action to be secure(SSL).
 * @param control
 * @return
 */
function secureForm(control)
{
	if (control.form)
	{
		var form = control.form;
		var currentAction = form.action;
		form.action = buildAction(currentAction, contextForceHttps, contextForceHttp);
	}
	alert(control.form.action);
}
/**
* sets the form's action to be unsecure(HTTP).
* @param control
* @return
*/
function unsecureForm(control)
{
	if (control.form)
	{
		var form = control.form;
		var currentAction = form.action;
		form.action = buildAction(currentAction, contextForceHttp, contextForceHttps);
	}
}
/**
 * Goto to unsecure home
 * @return
 */
function gohome(url)
{
	 var top = null;
	 if ((window.top) && window.top != window)
	 {
		 top = window.top;
	 }
	 else
	 {
		 top = window;
	 }
	 top.location.href = url || homeUrl;
	 return false;
}

function buildAction(currentAction, newUrl, oldUrl)
{
	var newAction;
	
	if (!newUrl.endsWith("/"))
		newUrl = newUrl + "/";
	
	if (currentAction.startsWith("/"))
	{
		//this won't work!!!
		var n = -1;
		//gives http:/
		n = newUrl.indexOf("/", n + 1);
		//should give http://host/
		n = newUrl.indexOf("/", n + 2);
		if (n > 7)
		{
			//remove the context path and use the context path from the action
			newUrl = newUrl.substring(0, n);
		}
		newAction = newUrl + currentAction;
	}
	else if (currentAction.startsWith(newUrl))
	{
		//don't change
		newAction = currentAction;
	}
	else if (currentAction.startsWith(oldUrl))
	{
		newAction = currentAction.replaceWith(0, oldUrl.length, newUrl);
	}
	else
	{
		return currentAction;
	}
	return newAction;
}

function postDataToParent(close, secure){
	if (close)
	{
		if (secure == null || secure == false)
		{
			//Passes popup screen's name value to parent screen's name value.
			// window.opener.document.frmMain['frmMain:name'].value=document.forms['frmPopup']['frmPopup:name'].value;
			//submits popup screen to set values to beans
			// frmPopup.submit();
			//submits parent screen to display records based on name input from popup screen.
			//window.opener.document.pageLoader.submit();
			//
			reloadOpener();
			//
			//window.opener.location.document.getElementById('id OfButton').click()
			//close popup window.
			//setTimeout('alert("Hello, World")', 2000);
			self.close();//can only close from a click & not a timer!
			//setTimeout('window.close()', 2000);
			//window.close();
		}
		else if (close)
		{
			window.location.href = contextForceHttp + '/';
		}
	}
}

// function popupSummary() {
// 	popupWin('../web/member/summary.html', 'memberMgmt', 1);
// }
// function popupAffiliateSummary() {
// 	popupWin('../web/member/affiliate.html', 'memberMgmt', 1);
// }
// function popupAffiliateForm() {
// 	popupWin('../web/member/affiliateForm.html', 'memberMgmt', 1);
// }

function popupPortTest() {
	popupWin('../web/test/port.htm', 'testwin', 0);
}

function popupGameWin() {
	popupWin('../web/iypLessons.htm', 'iypGameWin', 0);
}
function popupLessonWin() {
    popupWin('gameWindow/lessonPanel.faces', 'iypLessonWin', 0);
}
function popupTrickWin() {
    popupWin('gameWindow/trickShotPanel.faces', 'iypLessonWin', 0);
}
function popupDemoWin() {
	popupWin('../web/demoLesson.htm', 'iypDemoWin', 0);
}
function popupPracticeWin() {
	// var targetPage = userRole=='wanderer'? '../web/iypPractice/join.html' : '../web/iypPractice.htm';
	var targetPage = 'gameWindow/practicePanel.faces';//'../web/iypPractice.htm';
	popupWin(targetPage, 'iypPracticeWin', 0);
}
function popupPracticeWinOld() {
	// var targetPage = userRole=='wanderer'? '../web/iypPractice/join.html' : '../web/iypPractice.htm';
	var targetPage = '../web/iypPractice.htm';
	popupWin(targetPage, 'iypPracticeWin', 0);
}

function popupMultiPlayer(hallId) {
	var targetPage = 'twoplayer/main.faces';
	if (hallId != 0 && hallId != '' && hallId != '0')
		targetPage += '?hallid=' + hallId;
	popupWin(targetPage, 'iypTwoPlayerWin', 0);
}

function popupMultiPlayerNew(hallId) {
	var targetPage = 'twoplayer_new/main_new.faces';
	if (hallId != 0 && hallId != '' && hallId != '0')
		targetPage += '?hallid=' + hallId;
	popupWin(targetPage, 'iypTwoPlayerWin', 0);
}

function popupMultiPlayerTrmt(hallId) {
	var targetPage = 'twoplayer_new/main_trmt_new.faces';
	if (hallId != 0 && hallId != '' && hallId != '0')
		targetPage += '?hallid=' + hallId;
	popupWin(targetPage, 'iypTwoPlayerWin', 0);
}

function launchTournaments() {
	//var targetPage = userRole == 'wanderer' ? '../web/miniTourn/join.html'
	//		: '../web/miniTourn/redirect.htm';
	var targetPage = '../web/miniTourn/redirect.htm';
	popupWin(targetPage, 'iypMiniTournWin', 0);
}
function popupMajorTourns(tournId) {
	targetPage = '../web/majorTourn/main.htm';
	if (tournId != 0 && tournId != '' && tournId != '0')
		targetPage += '?tournid=' + tournId;
	popupWin(targetPage, 'iypMajorTournWin', 0);
}
function popupMajorTournsNew(tournId) {
	//targetPage = 'tournament/majorTournList.faces';
	var targetPage = 'twoplayer/main_trnmt.faces';
	if (tournId != 0 && tournId != '' && tournId != '0')
		targetPage += '?tournid=' + tournId;
	popupWin(targetPage, 'iypMajorTournWin', 0);
}
function popupMajorTournsNew2(tournId) {
	targetPage = 'tournament/majorTournList2.faces';
	if (tournId != 0 && tournId != '' && tournId != '0')
		targetPage += '?tournid=' + tournId;
	popupWin(targetPage, 'iypMajorTournWin', 0);
}
function rePosition(settoWidth, settoHeight)
{
	var leftM = (window.screen.availWidth - settoWidth) / 2 + 5;
	var topM = (window.screen.availHeight - settoHeight) / 3 + 5;
	resizeTo(settoWidth,settoHeight);
	moveTo(leftM, topM);
}
function showLegals(pageId)
{
	//
	var targetPg = "page/" + pageId;
	var winName = "showLegals";
	var forceReload = false;
	var secure = false;
	popupWin(targetPg, winName, forceReload, secure);	
}

/**
 * 
 * @param targetString
 * @return
 */
function parseAsDate(targetString)
{
    split_a     = targetString.split(' ');
    split_a[0]  = split_a[0].replace(/-/g,"/");
    year        = split_a[0].split('/')[0];
    month       = split_a[0].split('/')[1];
    day         = split_a[0].split('/')[2];
    hours       = '00';
    minutes     = '00';
    seconds     = '00';
    if(split_a.length==2)
    {
        hours       = split_a[1].split(':')[0];
        minutes     = split_a[1].split(':')[1];
        if(split_a[1].split(':').length==3)
            seconds     = split_a[1].split(':')[2];
    }
    theDate = new Date(year, (month*1)-1, day, hours, minutes, seconds);
    return theDate;
}

/**
 * 
 * @param timeNowString
 * @param timeout
 * @return
 */
function serverclock(timeNowString, timeout) {
	/*var now = new Date();
	Time = now.getUTCFullYear() + '/' + eval(now.getUTCMonth() + 1) + '/' + now.getUTCDate() + ' ' + now.getUTCHours() + ':' + eval(now.getUTCMinutes()) + ':'+eval(now.getUTCSeconds());
    timeNow         = parseAsDate(Time); 
	*/
    timeNow         = parseAsDate(timeNowString);
    monthArray      = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
    _hours          = timeNow.getHours();
    _minutes        = timeNow.getMinutes() < 10 ? '0'+timeNow.getMinutes() : timeNow.getMinutes();
    _seconds	      =  timeNow.getSeconds()< 10 ? '0'+timeNow.getSeconds() : timeNow.getSeconds();
    _dateString     = monthArray[timeNow.getMonth()]+' '+timeNow.getDate();
    _ampm           = _hours >= 12 ? 'pm' : 'am';
    _hours          = _hours > 12 ? _hours - 12 : _hours < 1 ? 12 : _hours;
    var CLOCK_START = ''; // '<span style="font-size: 14px; font-weight: bold;">'
    var CLOCK_END = ''; // '</span>'

    var clock = document.getElementById('clock');
    if (!clock)
    	return;
    
    if (clock != null)
		clock.innerHTML = CLOCK_START + _hours + ':' + _minutes + ':' +_seconds + ' ' + _ampm+ CLOCK_END;
	
    _newTime = timeNow.getFullYear() + '/' + eval(timeNow.getMonth() + 1) + '/' + timeNow.getDate() + ' ' + timeNow.getHours() + ':' + eval(timeNow.getMinutes()) + ':'+eval(timeNow.getSeconds() + 1);
	mainClockTimeout = setTimeout("serverclock('" + _newTime + "', 1)", timeout * 1000);
}

function mytimeclock(timeNowString, timeout) {
    var Today = new Date();
    var hours = Today.getHours();
    var min = Today.getMinutes();
    var sec = Today.getSeconds();
    var Time = ((hours > 12) ? hours - 12 :(hours == 0) ? 12 :hours);
    Time += ((min < 10) ? ':0' : ':') + min;
    Time += ((sec < 10) ? ':0' : ':') + sec;
    Time += (hours >= 12) ? ' PM' : ' AM';
    timeNow         = parseAsDate(timeNowString);

    monthArray      = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
    _hours          = timeNow.getHours();
    _minutes        = timeNow.getMinutes() < 10 ? '0'+timeNow.getMinutes() : timeNow.getMinutes();
    _seconds	      =  timeNow.getSeconds()< 10 ? '0'+timeNow.getSeconds() : timeNow.getSeconds();
    _dateString     = monthArray[timeNow.getMonth()]+' '+timeNow.getDate();
    _ampm           = _hours >= 12 ? 'pm' : 'am';
    _hours          = _hours > 12 ? _hours - 12 : _hours < 1 ? 12 : _hours;
    var CLOCK_START = ''; // '<span style="font-size: 14px; font-weight: bold;">'
    var CLOCK_END = ''; // '</span>'

    var clock = document.getElementById('myclock');
    if (!clock)
    	return;
    
    if (clock != null)
		clock.innerHTML = CLOCK_START + Time  + CLOCK_END;
	
    _newTime = timeNow.getFullYear() + '/' + eval(timeNow.getMonth() + 1) + '/' + timeNow.getDate() + ' ' + timeNow.getHours() + ':' + eval(timeNow.getMinutes()) + ':'+eval(timeNow.getSeconds() + 1);
	mainClockTimeout = setTimeout("mytimeclock('" + _newTime + "', 1)", timeout * 1000);
}

/**
 * called from onshow event
 */
function onShowModal(e, obj)
{
	mdlTbl = $(e.rich.component.contentTable);
	mdlCntn = $(e.rich.component.contentDiv);
	sizeModal(jQuery(mdlTbl), jQuery(mdlCntn));
}

/**
 * 
 * @param mdlTbl
 * @param mdlCntn
 * @return
 */
function sizeModal(mdlTbl, mdlCntn)
{
	var height = mdlTbl.height();
	if (jQuery(window).height() < mdlCntn.height() || jQuery(window).height() < height)
	{
		mdlCntn.height(jQuery(window).height() - 20);
		mdlCntn.css('overflow-y', 'scroll');
	}
	else if (height > 0)
	{
		mdlCntn.height(height);
		mdlCntn.css('overflow-y', '');
	}
	//recenter
	mdlCntn.parents('.rich-mp-container').centerScreen(true);
}

function getInternetExplorerVersion()
// Returns the version of Windows Internet Explorer or a -1
// (indicating the use of another browser).
{
   var rv = -1; // Return value assumes failure.
   if (navigator.appName == 'Microsoft Internet Explorer')
   {
      var ua = navigator.userAgent;
      var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
      if (re.exec(ua) != null)
         rv = parseFloat( RegExp.$1 );
   }
   return rv;
}

//function to be executed on browser load.
jQuery(window).load(function() {
	
	//once loaded size modals 
	jQuery('.rich-mpnl-content').each(function(){
		mdlTbl = jQuery('.rich-mp-content-table', this);
		mdlCntn = jQuery(this);
		sizeModal(mdlTbl, mdlCntn);
	});

	jQuery('.resizeContent').each(function(){
		//poolHallModalContainer
		var theId = this.id.substr(0, this.id.length - 'Container'.length);
		var modal = $(theId).component;
		var previous = modal.options.onshow;
		var ver = getInternetExplorerVersion();
		if ( ver> -1 )
		{
			if ( ver>= 8.0 ){
		         //alert("You're using Windows Internet Explorer 8.");
		modal.options.onshow = (function(previous, obj){return function(event) {
			onShowModal(event, obj);
			if (previous)
				previous(event);
		};})(modal.options.onshow, modal);
			}
		      //else if ( ver == 7.0 )
		    	  //alert("You're using Windows Internet Explorer 7.");
		}else{
			modal.options.onshow = (function(previous, obj){return function(event) {
				onShowModal(event, obj);
				if (previous)
					previous(event);
			};})(modal.options.onshow, modal);
		}
		//function(event){onShowModal(event, this);document.getElementById('viewUser:email').focus()}
		//modal.options.onshow = modal.options.onshow + ";onShowModal(event, this);";
	});
	
	jQuery('.resizeContent .rich-mp-content-table').resize(function() {
		mdlTbl = jQuery(this);
		mdlCntn = mdlTbl.parents('.rich-mpnl-content');
		//var mainDiv = jQuery(this).parents('.rich-mpnl-panel').parent();
		//log.debug('load', mainDiv, mainDiv.css('display'));
		//if (mainDiv.css('display') != 'none')
		sizeModal(mdlTbl, mdlCntn);
	});
});

//functions to be loaded when document loaded
jQuery(document).ready(function() {
	jQuery.fn.centerScreen = function(loaded) 
	{
		var obj = this;

		if(!loaded) 
		{
			if (obj.offsetWidth)
			{
				obj.css('top', jQuery(window).height() / 2 - obj.height() / 2);
				obj.css('left', (jQuery(window).width() - obj.width()) / 2);
			}
			jQuery(window).resize(function() { 
				obj.centerScreen(!loaded); 
			});
		} 
		else 
		{
			obj.stop();
			if (obj.width())
			{
				obj.animate( {
					top : jQuery(window).height() / 2 - obj.height() / 2,
					left : (jQuery(window).width() - obj.width()) / 2
				}, 200, 'linear');
			}
        }
	};

	jQuery(window).resize(function() {
		//on resize check modals aren't too big
		jQuery('.rich-mpnl-content').each(function(){
			mdlCntn = jQuery(this);
			if (!mdlCntn.height()) return; //ingore hidden
			//log.debug('window.resize', jQuery(window).height(), mdlCntn.height());
			mdlTbl = jQuery('.rich-mp-content-table', this);
			if (mdlCntn.height() > jQuery(window).height() 
					|| mdlCntn.height() < mdlTbl.height() - 10 // If hieght of internal table - padding/borders bigger
					|| mdlCntn.css('overflow-y')=='scroll') // If currently has scroll bar
			{
				sizeModal(mdlTbl, mdlCntn);
			}
		});
	});
	//once ready add modal center function
	jQuery('.rich-mp-container').each(function(){
		var obj = jQuery(this); 
		obj.centerScreen();
	});
});

//=========================================================================
//Cookie functions 
//=========================================================================
/* This function is used to set cookies */
function setCookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "=" 
	var start = document.cookie.indexOf(prefix) 
	
	if (start==-1) {
		return null;
	}
	
	var end = document.cookie.indexOf(";", start+prefix.length) 
	if (end==-1) {
		end=document.cookie.length;
	}
	
	var value=document.cookie.substring(start+prefix.length, end) 
	return unescape(value);
}

/* This function is used to delete cookies */
function deleteCookie(name,path,domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

function checkCookies(errorContainer, errorMessage, redirectTarget) 
{
	setCookie( 'test', 'none', '', '/', '', '' );
	if ( getCookie( 'test' ) )
	{
		if(errorContainer!='' && errorMessage!='') {
			errorContainer.innerHTML='';
			errorContainer.style.display='none';
		}
		cookie_set = true;
		deleteCookie('test', '/', '');
	} else {
		if(errorContainer!='' && errorMessage!='') {
			errorContainer.innerHTML+=errorMessage;
			errorContainer.style.display='block';
		} else if(redirectTarget!=='') {
			loadPage(contextpath+'/noCookies.htm', redirectTarget)
		}
		cookie_set = false;
	}
}

/**
 * try to focus (work around ie problems).
 * @param id the id of an element or the element
 * @return
 */
function tryFocus(id)
{
	try
	{
		var obj = $(id);
		if (obj)
		{
			obj.focus();
		}
	}
	catch (obj) 
	{
		//ignore
	}
}
