var isLive = false;

var permIsOfficial           = 0x01;
var permGetAnyUserDetails    = 0x02;
var permGetAnyTagDetails     = 0x04;
var permGetAnyCommentDetails = 0x08;

var baseHandlerUrl      = 'http://www.bl.uk/onlinegallery/proxy/';
var userHandlerUrl      = baseHandlerUrl + 'userhandler';
var galleryHandlerUrl   = baseHandlerUrl + 'personalgalleryhandler';
var commentHandlerUrl   = baseHandlerUrl + 'commenthandler';
var tagHandlerUrl       = baseHandlerUrl + 'taghandler';
var itemHandlerUrl      = baseHandlerUrl + 'itemhandler';
var favouriteHandlerUrl = baseHandlerUrl + 'favouritehandler';

var basePageUrl         = 'http://www.bl.uk/onlinegallery/';
var viewMyGalleriesUrl  = basePageUrl + 'mygalleries.html';
var xslBaseUrl          = basePageUrl + 'xsl/';
var imageBaseUrl        = basePageUrl + 'images/';
var registerUserUrl     = basePageUrl + 'register.html';
var searchTagsUrl       = basePageUrl + 'itemlist.html?tag=';

var defaultItemImage    = basePageUrl + 'images/dummy.jpg';

var whatIsThisUrl       = basePageUrl + 'what/';

var myUserId = -1;
var myPermissions = 0;
var myCommentId = -1;
var gotEntryPoint = false;

function initMain(allowLogin)
{
	// Never allow login from any page other than login.html - functionality not wanted by Adrian (but left in as it may be required again later)

	allowLogin = false;

	var cookie = $.cookie('blLogin');

	if (cookie)
	{
		var cookieParts = cookie.split(':');

		myUserId      = cookieParts[0];
		myPermissions = cookieParts[1];

		$('.userFullName').text(cookieParts[2] + ' ' + cookieParts[3]);
		$('#loginLink').text('Log out');

		if (allowLogin)
			$('#authLoginBanner').removeClass('invisible');

		$('#welcomeOnlyBanner').removeClass('invisible');
	}
	else
	{
		$('#loginLink').text('Log in');
		if (allowLogin)
		{
			$('#newLoginBanner').removeClass('invisible');
			$('#forgottenPasswordBanner').removeClass('invisible');
		}

		$('#loginOnlyBanner').removeClass('invisible');
	}

	if (allowLogin)
		$('#loginOrRegisterBanner').removeClass('invisible');

	$('#userName').focus(function(event) {
		this.select();
	});

	$('#password').focus(function(event) {
		$(this).val('');
	});

	$('#loginLink').click(function(event) {
		var cookie = $.cookie('blLogin');

		if (cookie)
			logoutLinkClick(event);
		else
			loginLinkClick(event);
	});

	$('#registerLink').click(function(event) {
		if (event && typeof(event.preventDefault) != 'undefined')
			event.preventDefault();

		document.location.href = registerUserUrl;
	});

	if (allowLogin)
	{
		$('#forgottenPasswordLink').click(function(event) {
			if (event && typeof(event.preventDefault) != 'undefined')
				event.preventDefault();

			var userName = $('#userName').val();

			if (userName == '')
			{
				alert('Enter your user name in the box and click the Forgotten Password link to reset your password.');
				return;
			}

			resetPassword(userName);
		});
	}

	$('#password').keyup(function(event) {
		if (event.keyCode == 13)
			loginLinkClick(event);
	});

	$('#buddyIcons').removeClass('invisible');
	$('#buddyIcons a').each(function(index) {
		var link = $(this);

		var linkUrl = link.attr('href');

		link.attr('href', linkUrl.replace('{0}', encodeURIComponent(document.location.href)).replace('{1}', encodeURIComponent(document.title)));
	});

	digg_url   = reddit_url   = document.location.href;
	digg_title = reddit_title = document.title;
	digg_skin  = 'compact';
}

function onAjaxCallback(loggedIn)
{
	var cookie = $.cookie('blLogin');

	if (cookie && !loggedIn)
	{
		onIdleLogout();

		alert(
			'You have been logged out of the system, most likely due to a session timeout.\n' +
			'Session timeouts are used to make the site more secure, but this means that you now\n' +
			'need to log in again.  Please use the link at the top of the page.'
		);
	}
}

function onAjaxWithoutXsltCallback(data)
{
	var xmlData = $.xslt.textToXML(data);

	var nodes = xmlData.documentElement.getElementsByTagName('loggedin');

	var loggedIn = nodes.length != 1? false: (xmlValue(nodes[0]).toLowerCase() == 'true');

	onAjaxCallback(loggedIn);

	return(loggedIn);
}

function isSuccessResult(data)
{
	var xmlData = $.xslt.textToXML(data);

	var nodes = xmlData.documentElement.getElementsByTagName('success');

	return(nodes.length != 1? false: (xmlValue(nodes[0]).toLowerCase() == 'true'));
}

function renderWeb2Panels()
{
	$('#web2RightPanel').removeClass('invisible');
}

function whatIsThis(fileName, event)
{
	var whatIsThisDiv = $('#whatIsThisContainer');

	if (whatIsThisDiv.length < 1)
	{
		whatIsThisDiv = $('<div id="whatIsThisContainer"><div style="float: left"><h4>What is this?</h4></div><div style="float: right"><a href="javascript:void(0);" onclick="javascript:$(' + "'#whatIsThisContainer'" + ').hide();">Close</a></div><div style="clear: both; height: 1px;"></div><iframe frameborder="0" border="0" src="about:blank"></iframe></div>');
		whatIsThisDiv.appendTo($('body'));
	}

	$('iframe', whatIsThisDiv).attr('src', whatIsThisUrl + fileName + '.html');

	if (!event)
		event = window.event;

	event = jQuery.event.fix(event);
	event.preventDefault();

	var x = event.pageX, y = event.pageY, $window = $(window);

	var maxX = $window.width(), maxY = $window.height();

	if ((event.clientX + whatIsThisDiv.width()) >= maxX)
		x -= whatIsThisDiv.width();

	if ((event.clientY + whatIsThisDiv.height()) >= maxY)
		y -= whatIsThisDiv.height();

	whatIsThisDiv.css('top',  y + 'px');
	whatIsThisDiv.css('left', x + 'px');

	whatIsThisDiv.show();
}

function isValidEmailAddress(emailAddress)
{
	/* See http://www.regular-expressions.info/email.html for limitations - the special case of '.museum' included because it's probably more likely to have those customers use the British Library...:) */

	return(emailAddress.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.([A-Z]{2,4}|museum)$/i));
}

