// declare global variables
//var domain = 'stadiumsquares.com';
//var website_url = 'http://test' + domain;
var domain = 'canarysquares.co.uk';
var website_url = 'http://www.' + domain;

var p = 0; //I don't understand javascript sometimes, this is to ensure the var is p is defined
			 //solely for the benefit of IE8

var fid = 0; //global var to store id of squawker being followed or unfollowed

var findaplot = 0; //global to indicate whether the find a plot function has been called

//global var to indicate whether a squawker being followed. Set in checkMobile
var beingfollowed = 'no'; 

// xml request containers
// createplots
var xmlHttp = false;

// plot info
var xmlHttp2 = false;

// form submission
var xmlHttp3 = false;

// link counting
var xmlHttp4 = false;

// stores currently highlighted row in list
var hlRow = null;

// stores last plot searched for
var searchedPlot = null;

// boolean, whether plot info is locked or not
var plotInfoLock = false;
var editingPlotLock = false;

// boolean, whether hovering over a sponsored plot or not
var overSponsoredPlot = false;
// boolean, whether hovering over a corporate plot or not
var overCorpPlotLocal = false;

// boolean to show seat numbers for debug
var showSeatNumbers = false;

// Timers for delaying functions calls
var timer = null;
var timer1 = null;
var timer2 = null;
var timer3 = null;
var timer4 = null;
var timer5 = null;
var timer6 = null;

// flag for mouseview
var mouseViewCounter = 0;

// VERSION 1
var largeWidth = 670;
var largeHeight = 510;
//var smallWidth = 520;
//var smallHeight = 430;

// APP VALUES
var app_startX = -280; // set zoom level to the minimum
var app_startY = -230; // set zoom level to the minimum
var app_minZoom = 3; // set zoom level to the minimum

// imageViewer initial coordinates / position
var maxZoom = 7;
var minZoom = 2;
var defaultZoom = maxZoom - 4; // to change the default zoom level just update this value
var defaultGridOn = 'true'; // sets whether we have the grid on or off by default, then update the element #toggleGridContainer to the class showGrid/hideGrid and the title to show grid/hide grid
//var startX = -4135.5; // default position for maxZoom - 1 (to find the coordinates once you have your desired pitch position type this into console found in firebug: document.getElementById("imageViewer").dimensions.bi.x)
//var startY = -3375; // default position for maxZoom - 1 (to find the coordinates once you have your desired pitch position type this into console found in firebug: document.getElementById("imageViewer").dimensions.bi.y)
//var startX = 34; // default position for maxZoom - 5
//var startY = -13; // default position for maxZoom - 5
var startX = -223.125; // default position for maxZoom - 2
var startY = -196.75; // default position for maxZoom - 2

var initSize = 'large';

/*var minZoom = 3;
var startX = -298;
var startY = -240;*/

// plot information
var pitchNumberOfPlots = 9163;

// seat code array look up
var seatCodeLookupTable = new Array('pitch', 'seat1', 'seat2', 'seat3', 'seat4', 'seat5', 
									'seat6', 'seat7', 'seat8', 'seat9', 'seat10', 'seat11', 
									'seat12', 'seat13', 'seat14', 'seat15', 'seat16', 'seat17', 
									'seat18', 'seat19', 'seat20');

var seatCodeLookupTable2 = new Array('pitch_2', 'seat1_2', 'seat2_2', 'seat3_2', 'seat4_2', 'seat5_2', 
									'seat6_2', 'seat7_2', 'seat8_2', 'seat9_2', 'seat10_2', 'seat11_2', 
									'seat12_2', 'seat13_2', 'seat14_2', 'seat15_2', 'seat16_2', 'seat17_2', 
									'seat18_2', 'seat19_2', 'seat20_2');
									
var seatCodeLookupTable3 = new Array('pitch_3', 'seat1_3', 'seat2_3', 'seat3_3', 'seat4_3', 'seat5_3', 
									'seat6_3', 'seat7_3', 'seat8_3', 'seat9_3', 'seat10_3', 'seat11_3', 
									'seat12_3', 'seat13_3', 'seat14_3', 'seat15_3', 'seat16_3', 'seat17_3', 
									'seat18_3', 'seat19_3', 'seat20_3');
									
var numberDefaultIcons = 12;
var current_celeb = null;
var current_famous_square = null;
var treasure_hunt_finished_notification = false;

// appends zeroes to the given plot id
function appendZeroes(plotId)
{
	var numZeroes = 4 - plotId.length;
	var zeroes;
	var plotText;
	for(var i = numZeroes; i > 0; i--)
	{
		if(!zeroes)
		{
			zeroes = "0";
		}
		else
		{
			zeroes += "0";
		}
	}
	
	if(zeroes)
	{
		plotText = zeroes + plotId;
	}
	else
	{
		plotText = plotId;
	}
	
	return plotText;
}

// for IE to use indexOf()
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt, from)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

Array.prototype.search = function(s1,s2)
{
	var len = this.length;
  	
	for(var i=0; i<len; i++)
	{
   		if(this[i].constructor == Array)
		{
      		if(this[i][0] == s1 && this[i][1] == s2)
			{
        		return i;
        		break;
      		}
     	}
  	}
  	return false;
}

/*function currencyConvertor(value, originalCurrency)
{
	value = parseFloat(value);
	var convertedValue;
	
	if(originalCurrency == 'uk' || originalCurrency == null)
	{
		if(currency == 'uk')
		{
			convertedValue = "\&pound;" + value.toFixed(2);
		}
		else if(currency == 'eu')
		{
			convertedValue = value * ukEu;
			convertedValue = "&#8364;" + convertedValue.toFixed(2);
		}
		else if(currency == 'usa')
		{
			convertedValue = value * ukUsa;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}

		else if(currency == 'can')
		{
			convertedValue = value * ukCan;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}

		else if(currency == 'aus')
		{
			convertedValue = value * ukAus;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}

		else if(currency == 'nz')
		{
			convertedValue = value * ukNz;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'jap')
		{
			convertedValue = value * ukJap;
			convertedValue = "&yen;" + convertedValue.toFixed(2);
		}
	}
	else if(originalCurrency == 'eu')
	{
		if(currency == 'uk')
		{
			convertedValue = value / ukEu;
			convertedValue = "&pound;" + convertedValue.toFixed(2);
		}
		else if(currency == 'eu')
		{
			convertedValue = "&#8364;" + value.toFixed(2);
		}
		else if(currency == 'usa')
		{
			convertedValue = (value / ukEu) * ukUsa;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'can')
		{
			convertedValue = (value / ukEu) * ukCan;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'aus')
		{
			convertedValue = (value / ukEu) * ukAus;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'nz')
		{
			convertedValue = (value / ukEu) * ukNz;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'jap')
		{
			convertedValue = (value / ukEu) * ukJap;
			convertedValue = "&yen;" + convertedValue.toFixed(2);
		}
	}
	else if(originalCurrency == 'usa')
	{
		if(currency == 'uk')
		{
			convertedValue = (value / ukUsa);
			convertedValue = "&pound;" + convertedValue.toFixed(2);
		}
		else if(currency == 'eu')
		{
			convertedValue = (value / ukUsa) * ukEu;
			convertedValue = "&#8364;" + convertedValue.toFixed(2);
		}
		else if(currency == 'usa')
		{
			convertedValue = "&#36;" + value.toFixed(2);
		}
		else if(currency == 'can')
		{
			convertedValue = (value / ukUsa) * ukCan ;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'aus')
		{
			convertedValue = (value / ukUsa) * ukAus;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'nz')
		{
			convertedValue = (value / ukUsa) * ukNz;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'jap')
		{
			convertedValue = (value / ukUsa) * ukJap;
			convertedValue = "&yen;" + convertedValue.toFixed(2);
		}
	}
	else if(originalCurrency == 'can')
	{
		if(currency == 'uk')
		{
			convertedValue = (value / ukCan);
			convertedValue = "&pound;" + convertedValue.toFixed(2);
		}
		else if(currency == 'eu')
		{
			convertedValue = (value / ukCan) * ukEu;
			convertedValue = "&#8364;" + convertedValue.toFixed(2);
		}
		else if(currency == 'usa')
		{
			convertedValue = (value / ukCan) * ukUsa;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'can')
		{
			convertedValue = "&#36;" + value.toFixed(2);
		}
		else if(currency == 'aus')
		{
			convertedValue = (value / ukCan) * ukAus;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'nz')
		{
			convertedValue = (value / ukCan) * ukNz;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'jap')
		{
			convertedValue = (value / ukCan) * ukJap;
			convertedValue = "&yen;" + convertedValue.toFixed(2);
		}
	}
	else if(originalCurrency == 'aus')
	{
		if(currency == 'uk')
		{
			convertedValue = (value / ukAus);
			convertedValue = "&pound;" + convertedValue.toFixed(2);
		}
		else if(currency == 'eu')
		{
			convertedValue = (value / ukAus) * ukEu;
			convertedValue = "&#8364;" + convertedValue.toFixed(2);
		}
		else if(currency == 'usa')
		{
			convertedValue = (value / ukAus) * ukUsa;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'can')
		{
			convertedValue = (value / ukAus) * ukCan;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'aus')
		{
			convertedValue = "&#36;" + value.toFixed(2);
		}
		else if(currency == 'nz')
		{
			convertedValue = (value / ukAus) * ukNz;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'jap')
		{
			convertedValue = (value / ukAus) * ukJap;
			convertedValue = "&yen;" + convertedValue.toFixed(2);
		}
	}
	else if(originalCurrency == 'nz')
	{
		if(currency == 'uk')
		{
			convertedValue = (value / ukNz);
			convertedValue = "&pound;" + convertedValue.toFixed(2);
		}
		else if(currency == 'eu')
		{
			convertedValue = (value / ukNz) * ukEu;
			convertedValue = "&#8364;" + convertedValue.toFixed(2);
		}
		else if(currency == 'usa')
		{
			convertedValue = (value / ukNz) * ukUsa;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'can')
		{
			convertedValue = (value / ukNz) * ukCan;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'aus')
		{
			convertedValue = (value / ukNz) * ukAus;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'nz')
		{
			convertedValue = "&#36;" + value.toFixed(2);
		}
		else if(currency == 'jap')
		{
			convertedValue = (value / ukNz) * ukJap;
			convertedValue = "&yen;" + convertedValue.toFixed(2);
		}
	}
	else if(originalCurrency == 'jap')
	{
		if(currency == 'uk')
		{
			convertedValue = (value / ukJap);
			convertedValue = "&pound;" + convertedValue.toFixed(2);
		}
		else if(currency == 'eu')
		{
			convertedValue = (value / ukJap) * ukEu;
			convertedValue = "&#8364;" + convertedValue.toFixed(2);
		}
		else if(currency == 'usa')
		{
			convertedValue = (value / ukJap) * ukUsa;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'can')
		{
			convertedValue = (value / ukJap) * ukCan;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'aus')
		{
			convertedValue = (value / ukJap) * ukAus;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'nz')
		{
			convertedValue = (value / ukJap) * ukNz;
			convertedValue = "&#36;" + convertedValue.toFixed(2);
		}
		else if(currency == 'jap')
		{
			convertedValue = "&yen;" + value.toFixed(2);
		}
	}
	return convertedValue;
}
*/

// name, value, expires_hours, path, domain, secure
function setCookie( name, value, expires_hours, 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_hours )
	{
		expires_hours = expires_hours * 1000 * 60 * 60;
	}
	
	var expires_date = new Date( today.getTime() + (expires_hours) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires_hours ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function getCookie( check_name )
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for (var i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

// this deletes the cookie when called
function deleteCookie( name, path, domain )
{
	if ( getCookie( name ) )
	{
		document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}

function clearInnerHTML(obj)
{
	// perform a shallow clone on obj
	var nObj = obj.cloneNode(false);
	// insert the cloned object into the DOM before the original one
	obj.parentNode.insertBefore(nObj,obj);
	// remove the original object
	obj.parentNode.removeChild(obj);
}

function getEvent(event)
{
    if(event == undefined) {
        return window.event;
    }
    
    return event;
}

function isInteger(s) 
{
	return (s.toString().search(/^-?[0-9]+$/) == 0);
}

function moneyFormat(value)
{
	return "\&pound;" + parseFloat(value).toFixed(2);
}

function limitText(limitField, limitNum)
{
	if (limitField.value.length > limitNum)
	{
		limitField.value = limitField.value.substring(0, limitNum);
	}
}

function getViewportDimensions(type)
{
	if(type == 'width')
	{
		if (window.innerWidth)
	    {
	    	return window.innerWidth;
	    }
		else if(document.body.clientWidth)
		{
			return document.body.clientWidth;
		}
	   	else if (document.body && document.body.offsetWidth)
	    {
	        return document.body.offsetWidth;
	    }
		else if (document.documentElement.clientWidth)
		{
			return document.documentElement.clientWidth;
		}
		else if(window.innerWidth)
		{
			return window.innerWidth;
		}
	    else
	    {
	        return 0;
	    }
	}
	else
	{
		if (window.innerHeight)
	    {
	    	return window.innerHeight;
	    }
		else if(document.body && document.body.clientHeight)
		{
			return document.body.clientHeight;
		}
	   	else if (document.body && document.body.offsetHeight)
	    {
	        return document.body.offsetHeight;
	    }
		else if (document.documentElement.clientHeight)
		{
			return document.documentElement.clientHeight;
		}
		else if(window.innerHeight)
		{
			return window.innerHeight;
		}
	    else
	    {
	        return 0;
	    }
	}
}

/***********************************************************************************************
                             Script to swap between stylesheets
  Written by Mark Wilton-Jones, 05/12/2002. v2.2.1 updated 14/03/2006 for dynamic stylesheets
************************************************************************************************

Please see http://www.howtocreate.co.uk/jslibs/ for details and a demo of this script
Please see http://www.howtocreate.co.uk/jslibs/termsOfUse.html for terms of use

To set up the page in the first place:

	Inbetween the <head> tags, put:

		<script src="PATH TO SCRIPT/swapstyle.js" type="text/javascript" language="javascript1.2"></script>

	Also between the head tags, put your stylesheets, best done as external links, but you can use
	<style ...> tags as well.

		Stylesheets cannot be switched if they have no title attribute and will be used at all times:

			<link rel="stylesheet" type="text/css" href="all.css">

		Stylesheets will be on by default if they have a title attribute and their rel attribute is set to 'stylesheet'.
		Most browsers will only allow one of these to be defined (or several sharing the same title):

			<link rel="stylesheet" type="text/css" href="default.css" title="Default">

		Stylesheets will be off by default if they have a title attribute and their rel attribute is set to 'alternate stylesheet':

			<link rel="alternate stylesheet" type="text/css" href="contrast.css" title="High Contrast">
			<link rel="alternate stylesheet" type="text/css" href="bigFont.css" title="Big Font">

To swap between stylesheets:

	changeStyle();                           //switches off all stylesheets that have title attributes
	changeStyle('Default');                  //switches off all stylesheets that have title attributes that do not match 'Default'
	changeStyle('High Contrast');            //switches off all stylesheets that have title attributes that do not match 'High Contrast'
	changeStyle('Big Font');                 //switches off all stylesheets that have title attributes that do not match 'Big Font'
	changeStyle('High Contrast','Big Font'); //switches off all stylesheets that have title attributes that do not match 'High Contrast' or 'Big Font'

	Opera 7+ and Mozilla also allow users to switch between stylesheets using the view menu (only one at a time though ...)

To make the script remember the user's choice of stylesheets, for example to use on more than one page or if they reload
- includes stylesheets chosen using the view menu in Gecko - it will only attempt to store a cookie if they actually
changed something:

	In these examples, I call the cookie used to store the choice 'styleTestStore'. You could use any name you like.

	To remember only until the browser window is closed:

		<body onload="useStyleAgain('styleTestStore');" onunload="rememberStyle('styleTestStore');">

	To remember for 10 days (for example):

		<body onload="useStyleAgain('styleTestStore');" onunload="rememberStyle('styleTestStore',10);">

Note that some browsers (most notably Opera) do not fire the onunload event when the page is
reloaded, and will only fire it when the user clicks a link or submits a form. If you need the
style preference to be stored even when reloading, you should call rememberStyle immediately
after you call changeStyle.

If you are going to provide users with a mechanism to change stylesheets, you may want to check
if the browser will allow you to change stylesheets first. Use:

	if( document.styleSheets || ( window.opera && document.childNodes ) || ( window.ScriptEngine && ScriptEngine().indexOf('InScript') + 1 && document.createElement ) ) {
		document.write('Something that allows them to choose stylesheets');
	}

It's not perfect, because it will also appear in ICEbrowser, which makes a mess when it tries to
change to an alternate stylesheet. If you want, you can use
	if( ( document.styleSheets || ( window.opera && document.childNodes ) || ( window.ScriptEngine && ScriptEngine().indexOf('InScript') + 1 && document.createElement ) ) && !navigator.__ice_version ) {
but you should then update that if ICE is updated to make it work properly.
________________________________________________________________________________________________*/

function getAllSheets() {
	if( !window.ScriptEngine && navigator.__ice_version ) { return document.styleSheets; }
	if( document.getElementsByTagName ) { var Lt = document.getElementsByTagName('link'), St = document.getElementsByTagName('style');
	} else if( document.styleSheets && document.all ) { var Lt = document.all.tags('LINK'), St = document.all.tags('STYLE');
	} else { return []; } for( var x = 0, os = []; Lt[x]; x++ ) {
		var rel = Lt[x].rel ? Lt[x].rel : Lt[x].getAttribute ? Lt[x].getAttribute('rel') : '';
		if( typeof( rel ) == 'string' && rel.toLowerCase().indexOf('style') + 1 ) { os[os.length] = Lt[x]; }
	} for( var x = 0; St[x]; x++ ) { os[os.length] = St[x]; } return os;
}
function changeStyle() {
	window.userHasChosen = window.MWJss;
	for( var x = 0, ss = getAllSheets(); ss[x]; x++ ) {
		if( ss[x].title ) { ss[x].disabled = true; }
		for( var y = 0; y < arguments.length; y++ ) { if( ss[x].title == arguments[y] ) { ss[x].disabled = false; } }
} }
function rememberStyle( cookieName, cookieLife ) {
	for( var viewUsed = false, ss = getAllSheets(), x = 0; window.MWJss && MWJss[x] && ss[x]; x++ ) { if( ss[x].disabled != MWJss[x] ) { viewUsed = true; break; } }
	if( !window.userHasChosen && !viewUsed ) { return; }
	for( var x = 0, outLine = '', doneYet = []; ss[x]; x++ ) {
		if( ss[x].title && ss[x].disabled == false && !doneYet[ss[x].title] ) { doneYet[ss[x].title] = true; outLine += ( outLine ? ' MWJ ' : '' ) + escape( ss[x].title ); } }
	if( ss.length ) { document.cookie = escape( cookieName ) + '=' + escape( outLine ) + ( cookieLife ? ';expires=' + new Date( ( new Date() ).getTime() + ( cookieLife * 86400000 ) ).toGMTString() : '' ) + ';path=/'; }
}
function useStyleAgain( cookieName ) {
	for( var x = 0; x < document.cookie.split( "; " ).length; x++ ) {
		var oneCookie = document.cookie.split( "; " )[x].split( "=" );
		if( oneCookie[0] == escape( cookieName ) ) {
			var styleStrings = unescape( oneCookie[1] ).split( " MWJ " );
			for( var y = 0, funcStr = ''; styleStrings[y]; y++ ) { funcStr += ( y ? ',' : '' ) + 'unescape( styleStrings[' + y + '] )'; }
			eval( 'changeStyle(' + funcStr + ');' ); break;
	} } window.MWJss = []; for( var ss = getAllSheets(), x = 0; ss[x]; x++ ) { MWJss[x] = ss[x].disabled; }
}

// creates an XMLHttpRequest instance
function createXmlHttpRequest()
{
	// will store the reference to the XMLHttpRequest object
	// this should work for all browsers except IE6 and older
	try
	{
		// try to create XMLHttpRequest object
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		// assume IE6 or older
		try
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
		}
		catch (e)
		{ 
			// assume IE6 or older 
		    var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0', 
		                                    'MSXML2.XMLHTTP.5.0', 
		                                    'MSXML2.XMLHTTP.4.0', 
		                                    'MSXML2.XMLHTTP.3.0', 
		                                    'MSXML2.XMLHTTP', 
		                                    'Microsoft.XMLHTTP'); 
		    // try every prog id until one works 
		    for (var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++)  
		    { 
		      try  
		      {  
		        // try to create XMLHttpRequest object 
		        xmlHttp = new ActiveXObject(XmlHttpVersions[i]); 
		      }  
		      catch (e) {} // ignore potential error 
		    }
		}
	}
	// return the created object or display an error message
	if (!xmlHttp)
	{
		alert("Error creating the XMLHttpRequest object.");
	}
	else
	{
		return xmlHttp;
	}
}

function findXmlRoot(xmlHttp)
{
//alert('JQ: function findXmlRoot ' + xmlHttp);

//var xmlResponse = xmlHttp.responseText;
//alert(xmlResponse);

	// retrieve the server's response packaged as an XML DOM object
	var xmlResponse = xmlHttp.responseXML;
//alert('JQ: xmlResponse = ' + xmlResponse);
	// catching potential errors with IE and Opera
	if (!xmlResponse || !xmlResponse.documentElement)
	{
		throw ("Invalid XML structure:\n" + xmlHttp.responseText);
	}

	// catching potential errors with Firefox
	var rootNodeName = xmlResponse.documentElement.nodeName;
	if (rootNodeName == "parsererror")
	{
		throw ("Invalid XML structure 1:\n" + xmlHttp.responseText);
	}

	// getting the root element (the document element)
	var xmlRoot = xmlResponse.documentElement;

	//testing that we received the XML document we expect
	if (rootNodeName != "response" || !xmlRoot.firstChild)
	{
		throw ("Invalid XML structure 2:\n" + xmlHttp.responseText);
	}
	return xmlRoot;
}

function readXmlFile(type, params)
{
//alert('JQ: function readXmlFile ' + type + params);
	if (type == 'createPlots')
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp)
		{
			// try to connect to server
			try
			{
				// initiate reading the file from the server
				xmlHttp.open("GET", "/scripts/php/createPlots.php?" + params, true);
//alert('JQ: /scripts/php/createPlots.php?' + params);
				xmlHttp.onreadystatechange = handleRequestStateChange;
				xmlHttp.send('');
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);
			}
		}
	}
	else if (type == 'plotInfo')
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp2)
		{
			// try to connect to server
			try
			{
				// initiate reading the file from the server
				xmlHttp2.open("GET", "/scripts/php/plotInfo.php?" + params, true);
				xmlHttp2.onreadystatechange = handleRequestStateChange2;
				xmlHttp2.send('');
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);
			}
		}
	}
	else if (type == "inputChecker")
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp3)
		{
			// try to connect to server
			try
			{
				// initiate reading the file from the server
				xmlHttp3.open("GET", "/scripts/php/inputChecker.php?" + params, true);
				xmlHttp3.onreadystatechange = handleRequestStateChange3;
				xmlHttp3.send('');
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);
			}
		}
	}
	else if (type == 'joinFree')
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp3)
		{
			// try to connect to server
			try
			{	
				xmlHttp3.open("POST", "/scripts/php/joinFree.php", true);
				xmlHttp3.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xmlHttp3.onreadystatechange = handleRequestStateChange4;
				xmlHttp3.send(params);
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);		
			}
		}
	}
	else if (type == 'tellAFriend')
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp3)
		{
			// try to connect to server
			try
			{	
				xmlHttp3.open("POST", "/scripts/php/tellAFriend.php", true);
				xmlHttp3.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xmlHttp3.onreadystatechange = handleRequestStateChange5;
				xmlHttp3.send(params);
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);		
			}
		}
	}
	else if (type == 'nextPanels')
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp3)
		{
			// try to connect to server
			try
			{	
				xmlHttp3.open("GET", "/scripts/php/nextPanels.php?" + params, true);
				xmlHttp3.onreadystatechange = handleRequestStateChange6;
				xmlHttp3.send('');
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);		
			}
		}
	}
	else if (type == 'moreInfo')
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp2)
		{
			// try to connect to server
			try
			{
				// initiate reading the file from the server
				xmlHttp2.open("GET", "/scripts/php/moreInfo.php?" + params, true);
				xmlHttp2.onreadystatechange = handleRequestStateChange7;
				xmlHttp2.send('');
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);
			}
		}
	}
	else if (type == 'plotInfoHlRow')
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp2)
		{
			// try to connect to server
			try
			{
				// initiate reading the file from the server
				xmlHttp2.open("GET", "/scripts/php/plotInfo.php?" + params, true);
				xmlHttp2.onreadystatechange = handleRequestStateChange8;
				xmlHttp2.send('');
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);
			}
		}
	}
	else if (type == 'linkCount')
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp4)
		{
			// try to connect to server
			try
			{
				// initiate reading the file from the server
				xmlHttp4.open("GET", "/scripts/php/linkCount.php?" + params, true);
				xmlHttp4.onreadystatechange = handleRequestStateChange9;
				xmlHttp4.send('');
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);
			}
		}
	}
	else if (type == 'visitSquare')
	{
		// only continue of xmlHttp isn't void
		if (xmlHttp3)
		{
			// try to connect to server
			try
			{	
				xmlHttp3.open("POST", "/scripts/php/visitSquare.php", true);
				xmlHttp3.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xmlHttp3.onreadystatechange = handleRequestStateChange10;
				xmlHttp3.send(params);
			}
			// display the error in case of failure
			catch (e)
			{
				alert("Please check you internet connection, your browser failed to make contact with " + domain);		
			}
		}
	}
}

function handleRequestStateChange()
{
//alert('JQ: function handleRequestStateChange');
	// continue if the process is completed
	if (xmlHttp.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp.status === 200)
		{
/*
var response = xmlHttp.responseText;
alert(response);
*/
			try
			{
				// retrieve the response
//alert('JQ: createPlotsResponse');
				createPlotsResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp.status);
		}
	}
}

function handleRequestStateChange2()
{
	// continue if the process is completed
	if (xmlHttp2.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp2.status === 200)
		{
			try
			{
				// retrieve the response
				plotInfoResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp2.status);
		}
	}
}

function handleRequestStateChange3()
{
	// continue if the process is completed
	if (xmlHttp3.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp3.status === 200)
		{
			try
			{
				// retrieve the response
				inputCheckerResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp3.status);
		}
	}
}

function handleRequestStateChange4()
{
	// continue if the process is completed
	if (xmlHttp3.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp3.status === 200)
		{
			try
			{
				// retrieve the response
				joinFreeResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp3.status);
		}
	}
}

function handleRequestStateChange5()
{
	// continue if the process is completed
	if (xmlHttp3.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp3.status === 200)
		{
			try
			{
				// retrieve the response
				tellAFriendResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp3.status);
		}
	}
}

function handleRequestStateChange6()
{
	// continue if the process is completed
	if (xmlHttp3.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp3.status === 200)
		{
			try
			{
				// retrieve the response
				nextPanelsResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp3.status);
		}
	}
}

function handleRequestStateChange7()
{
	// continue if the process is completed
	if (xmlHttp2.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp2.status === 200)
		{
			try
			{
				// retrieve the response
				moreInfoResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp2.status);
		}
	}
}

function handleRequestStateChange8()
{
	// continue if the process is completed
	if (xmlHttp2.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp2.status === 200)
		{
			try
			{
				// retrieve the response
				plotInfoHlRowResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp2.status);
		}
	}
}

function handleRequestStateChange9()
{
	// continue if the process is completed
	if (xmlHttp4.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp4.status === 200)
		{
			try
			{
				// retrieve the response
				//linkCountResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp2.status);
		}
	}
}

function handleRequestStateChange10()
{
	// continue if the process is completed
	if (xmlHttp3.readyState === 4)
	{
		// continue only if the HTTP status is "OK"
		if (xmlHttp3.status === 200)
		{
			try
			{
				// retrieve the response
				visitSquareResponse();
			}
			catch (e)
			{
				//alert("failed. Response error = " + e.toString());
			}
		}
		else
		{
			//alert("failed. Status = " + xmlHttp3.status);
		}
	}
}

// function to remove event bubbling (onmouseover and onmouseout are controlled)		
// function to remove event bubbling (onmouseover and onmouseout are controlled)		
// function to remove event bubbling (onmouseover and onmouseout are controlled)		
function isMouseLeaveOrEnter(e)
{
	if (typeof(e) == "undefined" && typeof(window.event) != "undefined") 
	{
		e = window.event;
	}
	if (typeof(window.event) != "undefined")
	{
		e.cancelBubble = true;
	}
	else
	{
		e.stopPropagation();
	}
}

function getElementFromEvent(e)
{
	if (!e)
	{
		var e = window.event;
	}
	
	var el;
	
	if (e.target)
	{
		el = e.target;
	}
	else if (e.srcElement)
	{
		el = e.srcElement;
	}
	
//	if (el.nodeType===3) // defeat Safari bug
//	{
//		el = el.parentNode;
//	}
	
	return el;
}

function squawkOver(e)
{
	
}

function squawkOut()
{
	
	//Just moves the bubble off screen. 
	setTimeout("document.getElementById('bubble').style.left = '-9999px'", 1000);
	//document.getElementById('bubble').style.left = '-9999px';
	
	/*var plot
	if(!plotInfoLock && !editingPlotLock)
	{
		// get element that triggered the event
		var el = getElementFromEvent(e);
		// split the class name of the element
		var name = el.className;
		name = name.split(" ");
		
		if(name[1] == 'squawk') //Then it's a squawk plot
		{
			//Now move bubble out of the way, could clear it's contents at this point as well. 
			document.getElementById('bubble').style.left = '-9999px';
			
		}
	}*/
}
function squawkInfo()
{
	// Check xml request for squawk info
	
	if(squawkXml.readyState == 4)
	{
		if(squawkXml.status == 200)
		{
			try
			{
				bubbleInfo = squawkXml.responseText;
				
			}catch(e)
			{
				bubbleInfo = 'The server doesn\'t feel like squawking, OTBC';
			}
		}
		
	}
}

function follow(follow_id)
{
	fid = follow_id; //setting global var
	
	if(follow_id > 0) //a negative number means unfollow
	{
		var url='follow.php?follow_id=' + follow_id +'&ran=' + Math.random();
		
		
		
	}else{
		
		var url='unfollow.php?follow_id=' + follow_id +'&ran=' + Math.random();
		
	}
		
	// AJAX call that will set up or delete the links between this user
	// and the squawker they want to follow
	followXml = createXmlHttpRequest();
	
	followXml.onreadystatechange=stateChanged_followInfo;
	followXml.open("GET",url,true); // Want this call to be asynchronous
	followXml.send(null);
	
}

function stateChanged_followInfo()
{
	if(followXml.readyState == 4)
	{
		if(followXml.status == 200)
		{
			try
			{
				
				var responses = followXml.responseText.split("**");
				alert(responses[0]);
				
				// try putting call in here to iframe method to reload follows in sidebar
				document.getElementById('squawkframe').contentWindow.follows(true);
				
				//Dynamically set the text of the follow link depending on the response and
				//alter the onclick function attached to the follow link. fid is a global var
				//that stores the id of the squawker being followed or unfollowed. 
				if(responses[1] == 'followed')
				{
					//document.getElementById('followlink').innerHTML = 'Unfollow';
					$("#followlink").html('Unfollow').click(function(){follow(fid * -1);});
					//alert('about to set link in child');
					document.getElementById('squawkframe').contentWindow.toggleFollowLink(fid * -1);
					
				}else{
					
					//document.getElementById('followlink').innerHTML = 'Follow';
					$("#followlink").html('Follow').click(function(){follow(fid * -1);});
					document.getElementById('squawkframe').contentWindow.toggleFollowLink(fid * -1);
				}
				
				
				
				
			}catch(e)
			{
				alert('The server could not set up the link.')
			}
		}
		
	}

}


function squawkClick(e, sq)
{
	// ---------- JQ - highlight selected square ----------

	var this_plot_id;
	if(typeof e == "object")
		{
		var el = getElementFromEvent(e);
		this_plot_id = el.id;

		if ($('#' + this_plot_id).hasClass('selected_square'))
			{
			$('#' + this_plot_id).removeClass('selected_square');
			$('#' + this_plot_id).removeClass('searched_square');
			}
		else
			{
			$('#plots').children().removeClass('selected_square');
			$('#plots').children().removeClass('searched_square');
			$('#' + this_plot_id).addClass('selected_square');
			}
		}
	else
		{
		
		var aopts = {url: '/own/ajax_get_plot_region_price.php?plot_id=' + e, async:false, success: function(data) {
			if (data)
			{
			this_plot_id = 'plot_' + e + '_' + e + '_region_' + data;

			if ($('#' + this_plot_id).hasClass('selected_square'))
				{
				$('#' + this_plot_id).removeClass('selected_square');
				$('#' + this_plot_id).removeClass('searched_square');
				}
			else
				{
				$('#plots').children().removeClass('selected_square');
				$('#plots').children().removeClass('searched_square');
				$('#' + this_plot_id).addClass('selected_square');
				}
			}
		}};
		$.ajax(aopts);
		//Deemed the above necessary because the get operation below is performed asynchronously, 
		//this is causing problems in, you guessed it, IE. Need it to be synchronous. 
	
		
		/*	$.get('/own/ajax_get_plot_region_price.php?plot_id=' + e, function(data) {
			if (data)
				{
				this_plot_id = 'plot_' + e + '_' + e + '_region_' + data;

				if ($('#' + this_plot_id).hasClass('selected_square'))
					{
					$('#' + this_plot_id).removeClass('selected_square');
					$('#' + this_plot_id).removeClass('searched_square');
					}
				else
					{
					$('#plots').children().removeClass('selected_square');
					$('#plots').children().removeClass('searched_square');
					$('#' + this_plot_id).addClass('selected_square');
					}
				}
			});*/
		}
	// ---------- JQ - highlight selected square ----------

	var plot;
	var squawk;
	var bubbletop;
	var bubbleleft;
	var pfx = '';
	if(typeof e == "object")
	{	
	// get element that triggered the event
		var el = getElementFromEvent(e);
		// split the class name of the element
		var name = el.className;
		name = name.split(" ");
		
		// check if the element is a plot .May not need to do this? WR
		if(seatCodeLookupTable.indexOf(name[0]) != -1 || seatCodeLookupTable2.indexOf(name[0]) != -1 || seatCodeLookupTable3.indexOf(name[0]) != -1)
		{
			// gather unique plot_id number from div id, should be in position 2? WR
			var plotId = el.id;
			plotId = plotId.split("_");
			plot = plotId[1];
			
		}
		
	}else{
		
		var check = e * 1 ; // making it an integer
		
		//Had to do this in findplot as well, 
		if(isNaN(check))
			{
				e = checkQuery(e);
				if(e == '')
					{return false;}
				check = e * 1;
			
			}
		//alert('check is ' + typeof check);
		//It should be an integer from this point
		//alert(typeof check);
		if(typeof check != "number")
		{
				return false;
				
		}
		plot = e ; //it'll be an integer if it wasn't called from a click event
	}
		
		squawk = document.getElementById('bubble');
		
		// 16/06/11 We are now treating all plots as squawk plots 
		
		//if(name[1] == 'squawk') //Then it's a squawk plot
		//{
			// With the plot id, will now have to access the squawk info for that plot. This 
			// will require some AJAX and that. You'd better sit down.
			
			if(plot != null)
			{
				squawkXml = createXmlHttpRequest();
				var url="get_squawk_info.php?plot=" + plot;
				
				//If this is being called from the home page, need to amend the 
				//path, all the squawk scripts are in sq/
				
				if (typeof home === "undefined")
				{
					
					 
				}else{
					
					if(home === true)
					{
						var pfx = 'sq/';
						url = 'sq/' + url + '&home=y';
						//alert(url);
					}
					
				}
				
				url=url+"&ran="+Math.random();
				//alert(url);
				//squawkInfo.onreadystatechange=stateChanged_squawkInfo;
				squawkXml.open("GET",url,false); // Want this call to be synchronous, need the info for the bubble first
				squawkXml.send(null);
				squawkInfo();
				
			}
			// Parse bubbleinfo to split out the screen name
			
//			n = bubbleInfo.split('**');
			n = bubbleInfo.split('~*~');		// JQ: use a different separator because if the message contains '**', it will fail
			
			
			//Check to see if id is already being followed
			var ftext = 'Follow ';
			var fid = n[2];
			ftitle = 'Click to follow ';
			
			checkBeingFollowed(n[2]);
			
			if(beingfollowed == 'yes')
			{
				ftext = 'Unfollow ';
				fid = 0 - n[2]; //making it negative
				ftitle = 'Click to stop following ';
			}
			
			
			if(n[1] == '') //This is a blank screenname, ie squawker not set up or the square is free
			{
				//ftext = 'Square ' + plot;
				
				//if the square is free
				if(n[0].indexOf('free') != -1)
				{
					ftext = 'Free Square';
					
				}else{
					//Squawker not yet set up, so don't want the follow link to be visible
					ftext = '';
					
				}
				
				
			}
			
			//defaultHTML = '<a class="close" title="Click to close" href="#" onclick="MM_effectAppearFade(\'bubble\', 500, 100, 0, false);squawkOut()"><img src="squawk/images/close_bubble.jpg"></a>'; // This always needs to be there
			defaultHTML = '<a class="close" title="Click to close" href="#" onclick="$(\'#bubble\').fadeOut(300);squawkOut()"><img src="' + pfx + 'images/close_bubble.jpg"></a>'; // This always needs to be there

			squawk.innerHTML = '<div id="screenname"><span class="box">&#10063; ' + plot + '</span>  '  + n[1] + '<a id="followlink" href="#" onclick="follow('+ fid +')" class="followlink" title="' + ftext + n[1] +'\'s squawks">' + ftext + '</a></div>' + defaultHTML + n[0];
			
			//squawk.innerHTML = '<div id="screenname">'  + n[1] + '<a href="squawk/enter_mobile.php" class="lbOn" title="Click to follow '+ n[1] +'\'s squawks">follow</a></div>' + defaultHTML + n[0];
			 
			//This sets up each link with a rel attribute of 'bubble' with a colorbox. It
			//additionally defines a callback that calls the function that increments the hits
			//on that image every time it's viewed.
			$("a[rel=\'bubble\']").colorbox({current: "", opacity:0.5, onComplete: function(){setHits($(this).attr('squawk_id'));return false;}});
			
			// note to self, the function follow() referenced above will have to be an AJAX call to a script
			// that will set the follow up
			
			//alert('top is ' + squawk.style.top + ' left is ' + squawk.style.left);
			//We know the bubble is 241 x 365 pixels. We want it to appear so that 
			//the squawk plot is midway along the height of it. We know the absolute position
			//of the plot, so by doing some mathematical jiggery pokery we can work out the position
			//that we want to put the bubble in
			
			//Something of a fudge, but if this function is called in script
			//and not because of a click event, the input parm won't be an object.
			//It is an integer representing the plot id. If it's been called because the
			//squawker name had been clicked the grid is going to be positioned first so that 
	        //that square is in the middle of the grid. In this case we know what the top and 
			//left attributes are going to be, they are always the same in this case. Saves us 
			//working them out. 
			
			if(typeof e != "object")
			{
				//This means the function has been called within script, so 
				//we can hard code these.
				
				//That's defunct now, and this horrible bit of repetition 
				//does the trick. It's clumsy but works and needs must....
				el = document.getElementById(this_plot_id);
				//t = "260px";
				//l = "335px";
				
				//squawk.style.top = '89px';
				//squawk.style.left = '383px';
				
				t = el.style.top //this will return something like '232px' for example
				l = el.style.left;
				
				var imageViewer = document.getElementById('imageViewer');
				var zoomLevel = imageViewer.dimensions.zoomLevel; //Need to know the zoomlevel because this affects the size of the plot
				if(zoomLevel == 6) //mxzl -1
				{
					var pw = 24;
					var pt = 0;
					
				}else{
					
					var pw = 48;
					var pt = 8
				}
				
				
				pxi = t.indexOf('px');
				bubbletop = t.substr(0, pxi);
				bubbletop = bubbletop - (356/2) + pt;
				
				
				
				pxi = l.indexOf('px');
				bubbleleft = l.substr(0, pxi);
				bubbleleft = (bubbleleft * 1) + pw; // this is a point to the right of the plot, the plot is 48px wide
				                                 
				
				//Now reposition bubble
				squawk.style.top = bubbletop + 'px';
				squawk.style.left = bubbleleft + 'px';
				
				$('#bubble').hide().fadeIn(200);
				
			}else{
				
				t = el.style.top //this will return something like '232px' for example
				l = el.style.left;
				
				var imageViewer = document.getElementById('imageViewer');
				var zoomLevel = imageViewer.dimensions.zoomLevel; //Need to know the zoomlevel because this affects the size of the plot
				if(zoomLevel == 6) //mxzl -1
				{
					var pw = 24;
					var pt = 0;
					
				}else{
					
					var pw = 48;
					var pt = 8
				}
				
				
				pxi = t.indexOf('px');
				bubbletop = t.substr(0, pxi);
				bubbletop = bubbletop - (356/2) + pt;
				
				
				
				pxi = l.indexOf('px');
				bubbleleft = l.substr(0, pxi);
				bubbleleft = (bubbleleft * 1) + pw; // this is a point to the right of the plot, the plot is 48px wide
				                                 
				
				//Now reposition bubble
				squawk.style.top = bubbletop + 'px';
				squawk.style.left = bubbleleft + 'px';
			}
			
			//16/06/11 This used to return true so that the click event would display the bubble
			//and false to hide any open bubbles if an empty squares was clicked on. Now all bubbles
			//are being regarded as squawk squares, it must always return true. Closing bubbles is now only 
			//possible by clicking the red button
			//return true;
			
		//}else{
			
				
				
				// Need a mode here that will allow for the selection of squares. However,
				// we don't want this square selection bubble popping up every time someone
				// clicks on an empty square. Squares only need selecting during sign up so it 
				// needs to be able to differentiate between being called from signup and just being used
				// in the regular way. 
				
				if(signup) //this is a global var set in the main page conditioned on the existence of a GET var
				{
					// Build innerHTML to display the selection buttons.
					defaultHTML = '<a class="close" title="Click to close" href="#" onclick="$(\'#bubble\').fadeOut(300);squawkOut()"><img src="squawk/images/close_bubble.jpg"></a>'; // This always needs to be there
					signupHTML = '<div id="squawksignup">';
					signupHTML += '<p>You have chosen square;</p>';
					signupHTML += '<span id="plotno">' + plot + '</span>';
					signupHTML += '<p>If you are happy with this square, click the red button, your choice will be saved and you will return to the signup screen. </p>';
					signupHTML += '<p>If you want to choose a different one, just click the yellow button and drag the pitch to find another. </p>';
					signupHTML += '<img src="squawk/images/btn_yesplease.png" alt="" title="Click to squawk on this square." onclick="parent.setField('+plot+')" />';
					signupHTML += '<img src="squawk/images/btn_nothanks.png" alt="" title="" onclick="squawkOut();" /></div>';
					
					squawk.innerHTML = '<div id="screenname">Select a square.</div>' + defaultHTML + signupHTML;
					
					// Copied from above, just moves the bubble out
					t = el.style.top //this will return something like '232px' for example
					pxi = t.indexOf('px');
					bubbletop = t.substr(0, pxi);
					bubbletop = bubbletop - (356/2) + 8;
					
					l = el.style.left;;
					pxi = l.indexOf('px');
					bubbleleft = l.substr(0, pxi);
					bubbleleft = (bubbleleft * 1) + 48; // this is a point to the right of the plot, the plot is 48px wide
					                                 
					
					//Now reposition bubble
					squawk.style.top = bubbletop + 'px';
					squawk.style.left = bubbleleft + 'px';
					
					//return true;
					
				//}else{
					
				//	squawkOut();
				//	return false;
					
				}
			
			
			
		//}
				if(sq != undefined)
				{
					//This means that a direct url has been used to call squawk. This means it will
					//contain a reference to a particular squawk, this is the number sq. By taking this number
					//and searching the contents of the bubble, that were prepared earlier, it should be possible to
					//identify that squawk in the list and action it's click event so that the image pertaining to it
					//is displayed automatically
					
					$('a[squawk_id=' + sq + ']').click();
					
				}
					return true;
}

function checkBeingFollowed(id)
{
	//Checking via an AJAX call whether this id is already being followed. Need 
	//to do it this way because the id could be be followed via a cookie or an 
	//entry in the database, best to do it all in one place. 
	
	cXmlHttp = createXmlHttpRequest();
	
	var url='/sq/checkfollow.php?squawker_id=' + id + '&ran=' + Math.random();
	cXmlHttp.open("GET",url,false); // Want this call to be synchronous
	cXmlHttp.send(null);
	
	// Output the result of the request to get follow information. 
	if(cXmlHttp.readyState == 4)
	{
		if(cXmlHttp.status == 200)
		{
			try
			{
				 if(cXmlHttp.responseText == 'yes')
				 {
					 beingfollowed = 'yes'; //This is a global var
					 
				 }else{
					 
					 beingfollowed = 'no';
				 }
				
			}catch(e)
			{
				alert('The follow status could not be checked')
			}
		}
		
	}
	
}
// Checks for the existence of a cookie called 'mobile'
function checkMobile(squawker_id)
{
	// If the squawker id is set, dynamically update the value of the input field in the hidden form.
	// then when that form is submitted, the id is passed to the save_mobile.php script, allowing it 
	// to set up the appropriate cookies to remember the follows. The form may not be submitted, but
	// that's ok, and if the user doesn't enter a number
	
	if(squawker_id > 0)
	{
		document.getElementById('squawker_id').value=squawker_id;
	}
	
	cookies = document.cookie.split(";");
	for(var i = 0; i < cookies.length; i++)
	{
		var c = cookies[i].split("=");
		if(c[0].replace(' ', '') == 'mobile')
		{
			return true;	
		}
			
	}
	
	return false;
}

function populate_signup(square_id)
{
if (opener)
	{
	opener.document.form_claim_square.square.value = square_id;
	window.close();
	}
else
	{
	alert('No opener. Where did you come from?');
	}
}
// code when over a plot
function plotOver(e)
{
	// cancel "setPEVImage(false, false);"
	if(timer1)
	{
		window.clearTimeout(timer1);
	}
	if(timer2)
	{
		// cancel clearing of plotinfo
		window.clearTimeout(timer2);
	}

	if(!plotInfoLock && !editingPlotLock)
	{
		// get element that triggered the event
		var el = getElementFromEvent(e);
		// split the class name of the element
		var name = el.className;
		name = name.split(" ");
		
		// check if the element is a plot
		if(seatCodeLookupTable.indexOf(name[0]) != -1 || seatCodeLookupTable2.indexOf(name[0]) != -1 || seatCodeLookupTable3.indexOf(name[0]) != -1)
		{
			// gather unique plot_id number from div id
			var plotId = el.id;
			plotId = plotId.split("_");

			// at maximum zoom minus 2
			if(plotId[0] == 'plotview')
			{
				// show player eye view image
				setPEVImage(plotId.join("_"),true);
			}
			else
			{
				// show player eye view image
				setPEVImage(plotId.join("_"));
			}
		
			// if we're in the last two zooms
			if(name[0] == "pitch" || name[0] == "pitch_2")
			{
				setRowHighlight(hlRow);
				if(name[1] == "onList" || name[1] == "searchedOnList")
				{
					// start timer for plot info
					timer = window.setTimeout("setRowHighlight('" + el.id + "', true); updateSearchedPlot(true, '" + el.id + "');",500);
				}
				else if(name[1] == "sponsoredOnList" || name[1] == "searchedSponsoredOnList" || name[1] == "userPlot" || name[1] == "searchedUserPlot")
				{
					// start timer for plot info
					timer = window.setTimeout("setRowHighlight('" + el.id + "', true); plotInfo('" + el.id + "',false,true,true); updateSearchedPlot(true, '" + el.id + "');",500);
				}
				else if(name[1] == "famousSquareOnList" || name[1] == "searchedFamousSquareOnList" || name[1] == "famousSquareCorpOnList" || name[1] == "searchedFamousSquareCorpOnList")
				{
					// ** FAMOUS SQUARE ** //
					// start timer for plot info
					timer = window.setTimeout("setRowHighlight('" + el.id + "', true); plotInfo('" + el.id + "'); updateSearchedPlot(true, '" + el.id + "');",500);
				}
				else if(name[1] == "famousSquareOffList" || name[1] == "famousSquareCorpOffList")
				{
					// ** FAMOUS SQUARE ** //
					// start timer for plot info
					timer = window.setTimeout("plotInfo('" + el.id + "',false,true);",500);
				}
				else if(name[1] == "sponsoredOffList")
				{
					// start timer for plot info
					timer = window.setTimeout("plotInfo('" + el.id + "',false,true,true);",500);
				}
			}
		}
	}
}

function plotOut(e)
{
	if(!plotInfoLock && !editingPlotLock)
	{
		// cancel "plotInfo('" + el.id + "',false,true,true);"
		if(timer)
		{
			window.clearTimeout(timer);
		}
		
		timer1 = window.setTimeout("setPEVImage(false);",300);
		
		// get element that triggered the event
		var el = getElementFromEvent(e);
		// split the class name of the element
		var name = el.className;
		name = name.split(" ");

		if(seatCodeLookupTable.indexOf(name[0]) != -1 || seatCodeLookupTable2.indexOf(name[0]) != -1 || seatCodeLookupTable3.indexOf(name[0]) != -1)
		{
			// if we're in the last two zooms
			if(name[0] == "pitch" || name[0] == "pitch_2")
			{
				// show info for highlighted square, or clear if none
				if(document.getElementById(hlRow))
				{
					var cname = document.getElementById(hlRow).getElementsByTagName('td')[1].className;
					cname = cname.split(" ");
					if(cname[1] == 'unsponsored')
					{
						window.clearTimeout(timer1);
						timer1 = window.setTimeout("setPEVImage('"+hlRow+"');",300);
						clearPlotInfo();
					}
					else if(cname[1] == 'sponsored')
					{
						plotInfo(hlRow,false,false,true,false,true);
					}
					else if(cname[1] == 'famousSquare' || cname[1] == 'famousSquareCorp' || cname[1] == 'corp')
					{
						// ** FAMOUS SQUARE and/or CORP SQUARE ** //
						plotInfo(hlRow,false,false,false,false,true);
					}
				}
				else
				{
					hlRow = null;
					clearPlotInfo();
				}
			}
		}
	}
}

function plotClick(e)
{
	var el = getElementFromEvent(e);
	var name = el.className;
	name = name.split(" ");

	if (name[1] == "offList" || name[1] == "sponsoredOffList" || name[1] == "corpOffList" || name[1] == "famousSquareOffList" || name[1] == "famousSquareCorpOffList")
	{
		selectPlot(el);
	}
	else if (name[1] == "onList" || name[1] == "searchedOnList" || name[1] == "sponsoredOnList" || name[1] == "searchedSponsoredOnList" || name[1] == "corpOnList" || name[1] == "searchedCorpOnList" || name[1] == "famousSquareOnList" || name[1] == "searchedFamousSquareOnList" || name[1] == "famousSquareCorpOnList" || name[1] == "searchedFamousSquareCorpOnList")
	{
		// cancel showing the information in the info panel
		if(timer)
		{
			window.clearTimeout(timer);
		}
		
		unselectPlot(el.id);
		if(!plotInfoLock)
		{
			clearPlotInfo();
		}
	}
	else if (name[1] == "userPlot" || name[1] == "searchedUserPlot")
	{
		el.className = name[0] + " searchedUserPlot";
		setRowHighlight(el.id, true);
		plotInfo(el.id, false, false, true);
	}
}

function listOver(e)
{
	if(timer3)
	{
		window.clearTimeout(timer3);
	}
	if(!plotInfoLock && !editingPlotLock)
	{
		var el = getElementFromEvent(e);
		
		if(el.className == 'moreInfo')
		{
			// catch any events triggered when hovering over the "see more" or "Jump" links, change the element to the parent node which is the column
			el = el.parentNode;
		}
		else if(el.className == 'jump')
		{
			el = el.parentNode.parentNode;
		}
		else if(el.className == 'invite')
		{
			el = el.parentNode.nextSibling;
		}
		// split class name of column
		var className = el.className;
		className = className.split(" ");
		
		var listId = el.parentNode.id;
		var listIdArr = listId.split("_");
		listIdArr.splice(0,1,"plot");
		
		// check if either the first class name or the second equal columnHL as they could either be "columnHL" or "currency columnHL"
		if (className[0] == "columnHL" || className[1] == "columnHL")
		{
			if(hlRow)
			{
				// clear old highlight
				setRowHighlight(hlRow,false,true);
			}
			
			setRowHighlight(listId, true);
			
			updateSearchedPlot(true, listIdArr.join("_"));
			
			// check if the last class name is "unsponsored"
			if(className[className.length-1] == "unsponsored" || className[className.length-1] == "corp")
			{
				setPEVImage(listId);
				// cancel plot info (this is necessary if the user is mousing up and down the list fast and the xmlhttp request response executes out of sync with what the user is on)
				if(xmlHttp2)
				{
					xmlHttp2.abort();
				}
				//timer3 = window.setTimeout("plotInfo('"+listId+"');",250);
			}
			else if(className[className.length-1] == "famousSquareCorp" || className[className.length-1] == "famousSquare")
			{
				// hovering over a famous square in the basket list
				setPEVImage(false);
				plotInfo(listId);
			}
			else
			{
				// otherwise the plot is sponsored
				//timer3 = window.setTimeout("plotInfo('"+listId+"',false,false,true);",250);
				setPEVImage(false);
				plotInfo(listId,false,false,true);
			}
		}
		else if(className[0] == "lockedColumnHL" || className[1] == "lockedColumnHL")
		{
			// check if the last class name is "unsponsored"
			if(className[className.length-1] == "unsponsored" || className[className.length-1] == "corp")
			{
				setPEVImage(listId);
				//timer3 = window.setTimeout("plotInfo('"+listId+"');",250);
			}
		}
	}
}

function tabClick(type, overSponsoredPlot)
	{
	// legacy code. do nothing now.
	}

function tabClick_old(type, overSponsoredPlot)
{
	/*
		info pane divs
		0 = login container
		1 = tabbed pages
			2 = why
			3 = join free
			4 = tell a friend
			5 = squawk
			6 = get started
			7 = my profile
			8 = visit square
		9 = player eye view container
		10 = list help container
		11 = intro text container
		12 = intro image container
		13 = plot info
			14 = grab this square container
			15 = owner profile
				16 = edit all owner images container / owner image container
				17 = edit owner message container / owner message container
		18 = list container
			19 = list table header container
			20 = list table container
	*/
	var infoPane = document.getElementById('infoPane')
	var infoPaneDivs = infoPane.getElementsByTagName('div');
	var loggedInMessage = document.getElementById('loggedInMessage');
	
	// hide all tab related divs, intro text div and plot info div first
	for(var i=1; i<=15; i++)
	{
		infoPaneDivs[i].style.display = 'none';
	}

	// hide list
	infoPaneDivs[18].style.display = 'none';

	// display chosen div
	if((type == 'joinfree') || (type == 'tellafriend') || (type == 'squawk') || (type == 'why') || (type == 'getstarted'))
	{
		// clear more info if being displayed, don't alter basket list or info panel
		clearMoreInfo(true, true);
		
		infoPane.style.background = "url(/images/v2/enlarged-green-slab.png) no-repeat";
		infoPaneDivs[1].style.display = 'block';
		
		if(type == 'why')
		{
			infoPaneDivs[2].style.display = 'block';
		}
		else if(type == 'joinfree')
		{
			infoPaneDivs[3].style.display = 'block';
		}
		else if(type == 'tellafriend')
		{
			infoPaneDivs[4].style.display = 'block';
		}
		else if(type == 'squawk')
		{
			infoPaneDivs[5].style.display = 'block';
		}
		else if(type == 'getstarted')
		{
			infoPaneDivs[6].style.display = 'block';
		}
		plotInfoLockSwitch(true);
	}
	else if((type == 'home') || (type == 'myprofile') || (type == 'visitsquare'))
	{
		// if list has any rows
		if(infoPaneDivs[20].getElementsByTagName('td').length > 0 || overSponsoredPlot)
		{	
			// change info panes background image
			infoPane.style.background = "url(/images/v3/two-panels.png) no-repeat";
			// show plot info and list
			if(type == 'home')
			{
				infoPaneDivs[13].style.display = 'block';
				if(overSponsoredPlot || editingPlotLock)
				{
					// if an owner square then show all elements
					for(var i=15; i<=17; i++)
					{
						infoPaneDivs[i].style.display = 'block';
					}
				}
				else
				{
					infoPaneDivs[16].style.visibility = 'hidden';
					infoPaneDivs[9].style.display = 'block';
				}
				plotInfoLockSwitch(false);
			}
			else if(type == 'myprofile')
			{
				infoPaneDivs[1].style.display = 'block';
				infoPaneDivs[7].style.display = 'block';
				plotInfoLockSwitch(true);
			}
			else if(type == 'visitsquare')
			{
				infoPaneDivs[1].style.display = 'block';
				infoPaneDivs[8].style.display = 'block';
				infoPaneDivs[13].style.display = 'block';
				
				for(var i=15; i<=17; i++)
				{
					infoPaneDivs[i].style.display = 'block';
				}
				plotInfoLockSwitch(true);
			}
			if(infoPaneDivs[20].getElementsByTagName('td').length > 0 && type != 'visitsquare')
			{
				infoPaneDivs[18].style.display = 'block';
			}
		}
		else
		{	
			if(type == 'home')
			{
				var imageViewer = document.getElementById('imageViewer');
				var zoomLevel = imageViewer.dimensions.zoomLevel;
				// check if at grid level
				if(zoomLevel <= (maxZoom - 2)) // if not then show intro text and image
				{
					// change info panes background image depending on zoom level
					if(zoomLevel == (maxZoom - 2))
					{
						infoPane.style.background = "url(/images/v4/top-white-slab.png) no-repeat";
					}
					else
					{
						infoPane.style.background = "url(/images/v2/top-green-slab.png) no-repeat";
					}
										
					// show intro text and image
					infoPaneDivs[11].style.display = 'block';
					infoPaneDivs[12].style.display = 'block';
				}
				else
				{
					// change info panes background image
					infoPane.style.background = "url(/images/v3/two-panels.png) no-repeat";
				}
				plotInfoLockSwitch(false);
			}
			else if(type == 'myprofile')
			{
				// change info panes background image
				infoPane.style.background = "url(/images/v3/two-panels.png) no-repeat";
				infoPaneDivs[1].style.display = 'block';
				infoPaneDivs[7].style.display = 'block';
				plotInfoLockSwitch(true);
			}
		}
	}
}

function toggleGrid(e)
{
	
		var imageViewer = document.getElementById('imageViewer');
		
		if($('#grid-show').css('display') == 'block') //The grid is off because the show grid button is displayed
		{
			//Show it
			
			changeStyle('justGrid');
			imageViewer.switches.showGrid = 'arse';
			
		}else{
			
			//Hide it
			changeStyle('hideAll');
			imageViewer.switches.showGrid = 'false';
			
			
		}
		
		saveViewerPosition();
		
	
}

function x_toggleGrid(el)
{
	alert('called');
	if(!el)
	{
		el = document.getElementById('toggleGrid');
	}
	
	var imageViewer = document.getElementById('imageViewer');
	
	// check if zoomed into grid level
	if(imageViewer.dimensions.zoomLevel >= (imageViewer.dimensions.maxZoom - 1))
	{
		if(el.parentNode.className == 'hideGrid')
		{
			el.parentNode.className = 'showGrid';
			el.parentNode.title = 'show grid';
		
			// check what state the sponsors toggle is in
			if(document.getElementById('toggleSponsorsContainer').className == 'hideSponsors') // so the sponsors are showing
			{
				// change style sheet
				//changeStyle('justIcons'); // No longer want an icon layer showing WR 290710
				changeStyle('hideAll'); // WR 290710
			}
			else
			{
				// change style sheet
				changeStyle('hideAll');
			}
			imageViewer.switches.showGrid = 'false';
		}
		else
		{
			el.parentNode.className = 'hideGrid';
			el.parentNode.title = 'hide grid';
		
			// check what state the sponsors toggle is in
			if(document.getElementById('toggleSponsorsContainer').className == 'hideSponsors')
			{
				// change style sheet
				//changeStyle('showAll'); // No longer want an icon layer showing WR 290710
				changeStyle('justGrid'); // WR 290710
			}
			else
			{
				// change style sheet
				changeStyle('justGrid');
			}
			imageViewer.switches.showGrid = 'true';
		}
		saveViewerPosition();
	}
	else
	{
		//alert("Zoom in more to see the grid and owned squares and use this button to hide/ view");
		alert("To use show/hide owner icons or show/hide grid you need to zoom in more.");
	}
}

/*function toggleSponsors(el)
{
	if(!el)
	{
		el = document.getElementById('toggleSponsors');
	}
	
	var imageViewer = document.getElementById('imageViewer');
	
	// check if zoomed into grid level
	if(imageViewer.dimensions.zoomLevel >= (imageViewer.dimensions.maxZoom - 1))
	{
		if(el.parentNode.className == 'hideSponsors')
		{
			el.parentNode.className = 'showSponsors';
			el.parentNode.title = 'show owners';
		
			// check what state the grid toggle is in
			if(document.getElementById('toggleGridContainer').className == 'hideGrid')
			{
				// change style sheet
				changeStyle('justGrid');
			}
			else
			{
				// change style sheet
				changeStyle('hideAll');
			}
			imageViewer.switches.showSponsors = 'false';
		}
		else
		{
			el.parentNode.className = 'hideSponsors';
			el.parentNode.title = 'hide owners';
		
			// check what state the grid toggle is in
			if(document.getElementById('toggleGridContainer').className == 'hideGrid')
			{
				// change style sheet
				changeStyle('showAll');
			}
			else
			{
				// change style sheet
				changeStyle('justIcons');
			}
		
			imageViewer.switches.showSponsors = 'true';
		}
		saveViewerPosition();
	}
	else
	{
		//alert("Zoom in more to see the grid and owned squares and use this button to hide/ view");
		alert("To use show/hide owner icons or show/hide grid you need to zoom in more.");
	}
}*/

function toggleSponsors(el)
{
	// 28/07/10 WJR Orginal function definition commented out above. This is an attempt to
	// rewrite the toggleSponsors function so that instead of swapping stylesheets to hide 
	// owners, it rebuilds the imageviewer from a directory containing tiles that have no 
	// merged icons on them. And then swaps between them. It is a copy of the toggleSeats 
	// function with just the class names and directory names changed.
	
	if(!el)
	{
		el = document.getElementById('toggleSponsors');
	}
	
	var imageViewer = document.getElementById('imageViewer');
	
	if(el.parentNode.className == 'hideSponsors')
	{
		el.parentNode.className = 'showSponsors';
		el.parentNode.title = 'show sponsers';
		imageViewer.dimensions.tileDir = "/images/canopy_on_icons"; // Contains tiles merged with icons
		
		imageViewer.switches.showSponsors = 'false';
	}
	else
	{
		el.parentNode.className = 'hideSponsors';
		el.parentNode.title = 'hide sponsors';
		//imageViewer.dimensions.tileDir = "/images/canopy_off_icons"; // Contains tiles that are NOT merged with icons, i.e. just pitch
		imageViewer.dimensions.tileDir = "/images/canopy_on"; // Contains tiles merged with icons 10/08/10 This will cause confusion if the seats have
															  // been toggled off. It's because I haven't yet created all the directories that the pitch
															  // needs, although by the time you read this, you never know. 
		imageViewer.switches.showSponsors = 'true';
	}
	
	saveViewerPosition();
	resetTiles(imageViewer);
	createPlots(imageViewer);
}

function toggleSeats(el)
{
	if(!el)
	{
		el = document.getElementById('toggleSeats');
	}
	
	var imageViewer = document.getElementById('imageViewer');
	
	if(el.parentNode.className == 'hideSeats')
	{
		el.parentNode.className = 'showSeats';
		el.parentNode.title = 'show seats';
		imageViewer.dimensions.tileDir = "/images/canopy_on";
		imageViewer.switches.showSeats = 'false';
	}
	else
	{
		el.parentNode.className = 'hideSeats';
		el.parentNode.title = 'hide seats';
		imageViewer.dimensions.tileDir = "/images/canopy_off";
		imageViewer.switches.showSeats = 'true';
	}
	saveViewerPosition();
	resetTiles(imageViewer);
	createPlots(imageViewer);
}

function toggleSize(el)
{
	if(!el)
	{
		el = document.getElementById('resize');
	}
	
	if(el.parentNode.className == 'enlarge')
	{
		el.parentNode.className = 'reduce';
		el.parentNode.title = 'reduce view';
		resizeViewer(document.getElementById('imageViewer'));
	}
	else
	{
		el.parentNode.className = 'enlarge';
		el.parentNode.title = 'enlarge view';
		resizeViewer(document.getElementById('imageViewer'));
	}
	saveViewerPosition();
}

function openWindow(name)
{
	if(name == 'corporate')
	{
		window.open(website_url+"/corporate.php");
	}
	else if(name == 'whatownersget')
	{
		window.open(website_url+"/what_you_get.php");
	}
	else if(name == 'videotutorial')
	{
		window.open(website_url+"/video-tutorial.php", '_blank', 'scrollbars=no,directories=no,location=no,menubar=no,resizeable=no,status=no,titlebar=no,toolbar=no,width=660,height=525');
	}
	else if(name == 'goldencanary')
	{
		window.open(website_url+"/goldencanary.php");
	}
}

function pageLevelRefresh(zoomLevel)
{
	if(plotInfoLock)
	{
		tabClick('home');
	}

/*
	var showList = false;
	if(document.getElementById('listTableContainer').getElementsByTagName('td').length > 0)
	{
		showList = true;
	}
*/

	if(zoomLevel >= (maxZoom - 2))
	{
/*
		if(showList)
		{
			document.getElementById('playerEyeViewContainer').style.display = 'none';
		}
		else
		{
			document.getElementById('playerEyeViewContainer').style.display = 'block';
		}
*/
		
		if(zoomLevel == maxZoom)
		{
			// maximum zoom
			document.getElementById('zoomIndicator').className = "zoom_6";
//			document.getElementById('infoPane').style.background = "url(/images/v3/two-panels.png) no-repeat";
//			document.getElementById('introImageContainer').style.display = 'none';
//			document.getElementById('introTextContainer').style.display = 'none';
		}
		else if(zoomLevel == (maxZoom - 1))
		{
			// maximum zoom minus 1
			document.getElementById('zoomIndicator').className = "zoom_5";
//			document.getElementById('infoPane').style.background = "url(/images/v3/two-panels.png) no-repeat";
//			document.getElementById('introImageContainer').style.display = 'none';
//			document.getElementById('introTextContainer').style.display = 'none';
		}
		else if(zoomLevel == (maxZoom - 2))
		{
			// maximum zoom minus 2
			document.getElementById('zoomIndicator').className = "zoom_4";
/*
			if(showList)
			{
				document.getElementById('introImageContainer').style.display = 'none';
				document.getElementById('introTextContainer').style.display = 'none';
				document.getElementById('infoPane').style.background = "url(/images/v3/two-panels.png) no-repeat";
			}
			else
			{
				document.getElementById('introImageContainer').style.display = 'block';
				document.getElementById('introTextContainer').style.display = 'block';
				document.getElementById('introTextContainer').style.visibility = 'hidden';
				document.getElementById('infoPane').style.background = "url(/images/v4/top-white-slab.png) no-repeat";
			}
*/
		}
	}
	else
	{
//		document.getElementById('playerEyeViewContainer').style.display = 'none';
/*		
		if(showList)
		{
			document.getElementById('infoPane').style.background = "url(/images/v3/two-panels.png) no-repeat";
			document.getElementById('introTextContainer').style.display = 'none';
			document.getElementById('introImageContainer').style.display = 'none';
		}
		else
		{
			document.getElementById('infoPane').style.background = "url(/images/v2/top-green-slab.png) no-repeat";
			document.getElementById('introTextContainer').style.display = 'block';
			document.getElementById('introImageContainer').style.display = 'block';
			document.getElementById('introTextContainer').style.visibility = 'visible';
		}
*/		
		if(zoomLevel == (maxZoom - 4))
		{
			// maximum zoom minus 4
			document.getElementById('zoomIndicator').className = "zoom_2";
		}
		else if(zoomLevel == (maxZoom - 5))
		{
			// maximum zoom minus 5
			document.getElementById('zoomIndicator').className = "zoom_1";
		}
	}
}

// save the image viewers position
function saveViewerPosition()
{
	var imageViewer = document.getElementById('imageViewer');
	var dim = imageViewer.dimensions;
	var switches = imageViewer.switches;
	
	var vpos = dim.bi.x + "," + dim.bi.y + "," + dim.zoomLevel + "," + dim.iv.size + "," + switches.showGrid + "," + switches.showSponsors + "," + switches.showSeats;
	
	setCookie('viewer_position', vpos, 24, '/', '', '');
}

function reloadViewerPosition()
{
	if(getCookie('viewer_position'))
	{
		if(document.getElementById('imageViewer'))
		{
			var vpos = getCookie('viewer_position');
			//vpos[x, y, zoom level] 
			vpos = vpos.split(",");
			
			var imageViewer = document.getElementById('imageViewer');
			var dim = imageViewer.dimensions;

			// find out the number of zooms needed to new zoom level
			var zooms = vpos[2] - dim.zoomLevel;
			if(zooms > 0)
			{
				zoomImage(imageViewer, undefined, zooms, true);
			}

			// now reposition map
			// set x,y coordinates and centre viewer
			dim.x = vpos[0];
			dim.y = vpos[1];

			// define mouse
			var mouse = {'x': dim.width / 2, 'y': dim.height / 2};
			imageViewer.start = mouse;

			// perform refresh of tiles and position
			zoomImage(imageViewer, mouse, 0);
		}
		else
		{
			alert('no imageviewer');
		}
	}
	else
	{
		alert('no cookie');
	}
}

function updateBasketListCookie(plotId, type)
{	
	var listCookie = getCookie('basket_list');
	
	if(type == 'add')
	{
		// make sure the plot id is valid
		if(plotId != null && plotId != '')
		{
			if(listCookie === null || listCookie == '')
			{
				listCookie = plotId;
			}
			else
			{
				listCookie = listCookie + ',' + plotId;
			}

			// name, value, expires_hours, path, domain, secure
			setCookie('basket_list',listCookie,24,'/','','');
		}
	}
	else if(type == 'del')
	{
		if(listCookie != null && listCookie != '')
		{
			// split list into an array
			var listArr = listCookie.split(',');
			listCookie = '';
			var j = 0;
			// loop through array
			for(var i=0; i<listArr.length; i++)
			{
				// if listId equals the plotId we are deleting then skip it, also if the listId is empty then skip it
				if(listArr[i] != plotId || listArr[i] == '')
				{
					// if the first id in the list, then skip the addition of the comma
					if(j !== 0)
					{
						// include comma
						listCookie = listCookie + ',' + listArr[i];
					}
					else
					{
						// add first plotId to list 
						listCookie = listArr[i];
					}
					j++;
				}
			}
			
			// name, value, expires_hours, path, domain, secure
			setCookie('basket_list',listCookie,24,'/','','');
		}
	}
}

function continueInIE6()
{
	document.getElementById('ie6-container').style.display = 'none';
	document.getElementById('pageContainer').style.display = 'block';
}

function homePrompt()
{
	deleteCookie('viewer_position','/',''); 
	deleteCookie('basket_list','/','');
	
	var a=confirm("Would you also like to logout?");
	
	if (a==true)
	{
		window.location = "/index.php?task=logout";
	}
	else
	{
		window.location = "/index.php";
	}
}

function linkCount(id)
{
	xmlHttp4 = createXmlHttpRequest();
	//imageViewer.switches.movable = false;
	var params = "id=" + id + "&d=" + new Date().getTime();
	readXmlFile('linkCount', params);
}

function toggleAutoZoom(display,type)
{
	var azc = document.getElementById('autoZoomContainer');
	if(display == 'show')
	{
		if(type == 'sl')
		{
			azc.style.backgroundImage = 'url(/images/v5/overlay_sl.png)';
		}
		else if(type == 'fs')
		{
			azc.style.backgroundImage = 'url(/images/v5/overlay_fs.png)';
		}
		else
		{
			azc.style.backgroundImage = 'url(/images/v5/overlay.png)';
			azc.style.cursor = 'progress';
		}
		azc.style.display = 'block';
	}
	else
	{
		azc.style.backgroundImage = '';
		azc.style.display = 'none';
		azc.style.cursor = 'default';
	}
}

function beginAutoZoom(square_id, el)
{
	// remove onclick event from the autozoom element
	el.onclick = null;
	// begin timers
	timer6 = window.setTimeout("autoZoom(1,'"+square_id+"'); toggleAutoZoom('show')",500);
}

function autoZoom(phase, square_id)
{
	var speed = 2000;
	if(phase == 1)
	{
		zoomImageIn(document.getElementById('imageViewer'),undefined);
		timer6 = window.setTimeout("autoZoom(2,'"+square_id+"');",speed);
	}
	else if(phase == 2)
	{
		zoomImageIn(document.getElementById('imageViewer'),undefined);
		timer6 = window.setTimeout("autoZoom(3,'"+square_id+"');",speed);
	}
	else if(phase == 3)
	{
		zoomImageIn(document.getElementById('imageViewer'),undefined);
		timer6 = window.setTimeout("autoZoom(4,'"+square_id+"');",speed);
	}
	else if(phase == 4)
	{
		findPlot(square_id, true);
		timer6 = window.setTimeout("autoZoom(5);",speed);
	}
	else if(phase == 5)
	{
		// turn grid off
		toggleGrid();
		timer6 = window.setTimeout("autoZoom(6);",speed);
	}
	else if(phase == 6)
	{
		// enlarge pitch
		//toggleSize();
		timer6 = window.setTimeout("autoZoom(7);",speed);
	}
	else if(phase == 7)
	{
		// turn sponsors off
		toggleSponsors();
		toggleAutoZoom();
	}
}

function checkLoginInfo(loginForm)
{
	if(loginForm.email.value == "")
	{
		alert("please enter your email to login");
		loginForm.email.focus();
		return false;
	}
	else if(loginForm.password.value == "")
	{
		alert("please enter your password to login");
		loginForm.password.focus();
		return false;
	}
	else
	{
		return true;
	}
}

function checkList()
{
	// boolean to check if any squares are checked
	var anyChecked = false;
	
	// check if any elements
	if (document.listForm.elements)
	{
		var els = document.listForm.elements;
		var els_length = els.length - 1;
		
		for (var i = els_length; i > -1; i--)
		{
			if (els[i].checked)
			{
				anyChecked = true;
				if (els[i].name == "plot_id[]")
				{
					i = -1;
					document.listForm.action = "/ss_checkout.php";
					document.listForm.method = "POST";
					document.listForm.target = "_self";
					document.listForm.submit();
				}
			}
		}
	}
	if (!anyChecked)
	{
		// no plots were selected
		alert('Identify the squares you want to purchase by ticking the "Buy" box.  Seats can\'t be purchased.');
	}
}

function clearList()
{
	var trs = document.getElementById('list').getElementsByTagName('tr');
	
	if(plotInfoLock)
	{
		clearMoreInfo();
	}
	
	for(var i = trs.length - 1; i >= 0; i--)
	{
		tds = trs[i].getElementsByTagName('td');
		if(tds.length > 0)
		{
			if(tds[0].innerHTML != 'Mine' && tds[0].innerHTML != 'Unpaid')
			{
				unselectPlot(trs[i].id);
			}
		}
	}
}

function joinFree(fmform)
{	
	// legend, email, legend, password, password 2

	// if the email field has not failed and has a value then continue
	if(fmform.elements[1].style.backgroundColor == 'lightgreen' && fmform.elements[1].value != '')
	{
		// if the first password field has a value then continue
		if(fmform.elements[3].value != '')
		{
			// if both passwords match then continue
			if(fmform.elements[3].value == fmform.elements[4].value)
			{
				// create params
				var params = 'new_e=' + fmform.elements[1].value +
							'&new_p=' + fmform.elements[3].value +
							'&new_p_2=' + fmform.elements[4].value;
					
				// send info to server
				xmlHttp3 = createXmlHttpRequest();
				readXmlFile('joinFree', params);
			}
			else
			{
				alert('The passwords you have entered do not match.');
			}
		}
		else
		{
			alert('Please enter a password.');
		}	
	}
	else
	{
		alert('Please enter a valid email address.');
	}
}

function tellAFriend(form)
{
	var params = 'yn=' + form.elements[1].value;
	params = params + '&ye=' + form.elements[2].value;
	params = params + '&fn=' + form.elements[4].value;
	params = params + '&fe=' + form.elements[5].value;
	params = params + '&m=' + form.elements[6].value;
	
	xmlHttp3 = createXmlHttpRequest();
	readXmlFile('tellAFriend', params);
}

function submitEditOwnerDetails()
{
	// function to update user profile with information added in edit plot forms
	
	// check all form data then submit

	if ((document.form_plot.plot_picture.value) && ((document.form_plot.plot_picture.value.toLowerCase().indexOf('.jpg') == -1) && (document.form_plot.plot_picture.value.toLowerCase().indexOf('.jpeg') == -1) && (document.form_plot.plot_picture.value.toLowerCase().indexOf('.gif') == -1) && (document.form_plot.plot_picture.value.toLowerCase().indexOf('.png') == -1)))
	{
		alert('Please upload only GIF, JPG, JPEG and PNG files.');
		return false;
	}

	if ((document.form_plot_text.plot_text.value) && (document.form_plot_text.plot_text.value != 'Upload a personal message here...'))
	{
		document.form_plot.plot_text.value = document.form_plot_text.plot_text.value;
	}

	document.form_plot.icon_image.value = document.getElementById('iconImage').className;
	document.form_plot.submit();
}

function checkInput(value, type, id)
{
	if(type == 'email')
	{
		if (value.search(/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) <= -1)
		{
			document.getElementById(id).style.backgroundColor = 'yellow';
		}
		else
		{
			xmlHttp3 = createXmlHttpRequest();
			readXmlFile('inputChecker', 'v=' + value + '&t=' + type + '&id=' + id);
		}	
	}
	else
	{
		xmlHttp3 = createXmlHttpRequest();
		readXmlFile('inputChecker', 'v=' + value + '&t=' + type + '&id=' + id);
	}
}

function joinFreeResponse()
{
	if (xmlHttp3.responseText == "password")
	{
		alert("The passwords you entered do not match.");
	}
	else if(xmlHttp3.responseText == "email")
	{
		alert("The email you entered is already taken.");
	}
	else
	{
		var reply = confirm("You are now a member, your login details have been sent to the email address provided. Update your Profile?");
		// OK
		if(reply == true)
		{
			window.location = website_url + "/index.php?task=showMyProfile";
		}
		else
		{
			window.location = website_url + "/index.php";
		}
	}
}

function tellAFriendResponse()
{
	alert(xmlHttp3.responseText);
}

function inputCheckerResponse()
{
	var response = xmlHttp3.responseText;

	// split response
	response = response.split("-");
	// id _ passed/failed
	
	// passed = 1, failed = 0
	if(response[1] == '1')
	{
		document.getElementById(response[0]).style.backgroundColor = "lightgreen";		
	}
	else
	{
		document.getElementById(response[0]).style.backgroundColor = "yellow";
	}
}

function checkMyProfileForm(profileForm, isPassword)
{
	if(profileForm.email.value.search(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) <= -1)
	{
		alert('Please fill in your e-mail address.');
		profileForm.email.focus();
		return false;
	}
	if((!profileForm.name.value) || (profileForm.name.value.match(/^\s+$/)))
	{
		alert('Please fill in your name.');
		profileForm.name.focus();
		return false;
	}

	if(isPassword)
	{
		if ((!profileForm.password.value) || (profileForm.password.value.match(/^\s+$/)))
		{
			alert('Please fill in your preferred password.');
			profileForm.password.focus();
			return false;
		}
	}
}

/* added by JQ 20090918
function capitalises the first letter of each word
*/
function toUpper(thisfield)
{
	var a = thisfield.value.split(/\s+/g); // split the sentence into an array of words

	for (i = 0 ; i < a.length ; i ++ )
	{
		var firstLetter = a[i].substring(0, 1).toUpperCase();
		var restOfWord = a[i].substring(1, a[i].length).toLowerCase();

		a[i] = firstLetter + restOfWord; // re-assign it back to the array and move on
	}

	thisfield.value = a.join(' '); // join it back together
}

function updateVisitSquareForm(id, email)
{
	if(id)
	{	
		// update hidden id value so the we know the square that is being viewed
		document.getElementById('visitSquareId').value = id;
	
		if(email)
		{
			// if the user is logged in their email will be input for them
			document.getElementById('visitSquareUserEmail').value = email;
		}
	}
	else
	{
		document.getElementById('visitSquareUserEmail').value = '';
		document.getElementById('visitSquareEmails').value = '';
		document.getElementById('visitSquareUserMessage').value = '';
		document.getElementById('visitSquareId').value = '';
	}
}

function visitSquareAddNewEmail()
{
	// get new email address entered by user
	var emailElement = document.getElementById('visitSquareAddEmail');
	var email = emailElement.value;
	email = email.replace(", ",",");
	email = email.replace(" ",",");
	var emailArray = email.split(",");
	
	for(var i=0;i<emailArray.length;i++)
	{
		// check that it is a valid email address
		if (emailArray[i].search(/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) <= -1)
		{
			// if not valid then colour the field yellow, focus on it and display an alert
			emailElement.style.backgroundColor = 'yellow';
			emailElement.focus();
			alert('Please ensure all email addresses are valid');
		}
		else
		{
			var duplicateFound = false;
			// get the other email addresses entered by the user so far
			var emailsElement = document.getElementById('visitSquareEmails');
			var emails = emailsElement.value;

			if(emails != '')
			{
				// split emails into an array
				var emailsArray = emails.split(",");

				// cycle through array
				for(var j=0; j<emailsArray.length; j++)
				{
					// check that none of the emails entered match the new one
					if(emailsArray[i] == emailArray[i])
					{
						// if we have a duplicate then highlight the field , focus on it and display an alert
						//emailElement.style.backgroundColor = 'yellow';
						//emailElement.focus();
						//alert('You have already entered this email address');
						duplicateFound = true;
					}
				}

				if(!duplicateFound)
				{
					// if no duplicates were found then push new email onto array, join it into one string and replace value of textarea
					emailElement.style.backgroundColor = '';
					emailElement.value = '';
					emailsArray.push(emailArray[i]);
					emails = emailsArray.join(',');
					emailsElement.value = emails;
				}
			}
			else
			{
				emailElement.style.backgroundColor = '';
				emailElement.value = '';
				emailsElement.value = emailArray[i];
			}
		}
	}	
}

function visitSquareSubmit()
{
	var userEmailField = document.getElementById('visitSquareUserEmail');
	var userEmail = userEmailField.value;
	var emailsField = document.getElementById('visitSquareEmails');
	var emails = emailsField.value;
	var proceed = true;
	
	if (userEmail.search(/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) <= -1)
	{
		// if not valid then colour the field yellow, focus on it and display an alert
		userEmailField.style.backgroundColor = 'yellow';
		userEmailField.focus();
		alert('Please enter a valid email address for yourself');
		proceed = false;
	}
	else
	{
		userEmailField.style.backgroundColor = '';
	}
	
	if(proceed)
	{
		if(emails == '')
		{
			emailsField.style.backgroundColor = 'yellow';
			emailsField.focus();
			alert('Please enter at least one recipient email address');
			proceed = false;
		}
		else
		{
			emailsField.style.backgroundColor = '';
		}
		
		if(proceed)
		{
			var userMessage = document.getElementById('visitSquareUserMessage').value;
			var id = document.getElementById('visitSquareId').value;

			var params = 'ye=' + userEmail;
			params = params + '&re=' + emails;
			params = params + '&id=' + id;
			
			if(userMessage != '')
			{
				params = params + '&ym=' + userMessage;
			}

			xmlHttp3 = createXmlHttpRequest();
			readXmlFile('visitSquare', params);
		}
	}
}

function visitSquareClose()
{
	// clear form
	updateVisitSquareForm(false);
	// return to normal view
	tabClick('home');
}

function visitSquareResponse()
{
	visitSquareClose();
	// alert user their emails were sent
	alert("Email(s) sent, thanks for spreading the word!");
}

function buyBoxClicked(el)
{
	
}

function clearPlotInfo(overSponsored)
{
	var plotInfoDivs = document.getElementById('plotInfo').getElementsByTagName('div');
	
	// check if hovering over a sponsored plot
	/*if(!overSponsored)
	{
		// and hide the owner info
		for(var i=1;i<plotInfoDivs.length;i++)
		{
			plotInfoDivs[i].style.display = "none";
		}
		// show generic plot info container
		plotInfoDivs[0].style.display = "block";
		var spans = plotInfoDivs[0].getElementsByTagName('span');
		spans[0].style.display = 'block';
		spans[1].style.display = 'none';
		spans[2].style.display = 'none';
	}
	else
	{
		// hide generic plot info container
		plotInfoDivs[0].style.display = "none";
	}*/
	
	for(var i=0;i<plotInfoDivs.length;i++)
	{
		plotInfoDivs[i].style.display = "none";
	}
	
	// refresh info pane, in case there are no more plots in the list.
	tabClick('home');
}

function plotInfo(listId, search, plotClick, overSponsoredPlotLocal, overCorpPlotLocal, showHlRow)
{
	// get unique plot_id number from row id
	var listIdArray = listId.split("_");
	var localSearchedPlot = 'plot';
	var localHlRow = 'list';
	// check if editing plot first
	if(!plotInfoLock)
	{	
		// set global boolean
		overSponsoredPlot = overSponsoredPlotLocal;
		
		// if hovering over a sponsored plot on the viewer
		if(overSponsoredPlot)
		{
			if(showHlRow)
			{
				// use this to gather unique information for this particular plot by making an xml request to the database
				xmlHttp2 = createXmlHttpRequest();
				var params = "id=" + listIdArray[1] + "&type=sponsored&d=" + new Date().getTime();
				readXmlFile('plotInfoHlRow', params);
			}
			else
			{
				// use this to gather unique information for this particular plot by making an xml request to the database
				xmlHttp2 = createXmlHttpRequest();
				var params = "id=" + listIdArray[1] + "&type=sponsored&d=" + new Date().getTime();
				readXmlFile('plotInfo', params);
			}
		}
		else
		{			
			// check if a seat or pitch
			if(listIdArray[3] == 'Stands')
			{
				// display information
				displayInfo('seat');
				// update square status text
				document.getElementById('grabThisSquareText').innerHTML = "<b>You have clicked on a seat.</b><br /><br />Please note that seats are not for sale, but by visiting different seats you can compare the view from different parts of the stadium.";
			}
			else
			{
				if(showHlRow)
				{
					// use this to gather unique information for this particular plot by making an xml request to the database
					xmlHttp2 = createXmlHttpRequest();
					var params = "id=" + listIdArray[1] + "&type=famous&d=" + new Date().getTime();
					readXmlFile('plotInfoHlRow', params);
				}
				else
				{
					// use this to gather unique information for this particular plot by making an xml request to the database
					xmlHttp2 = createXmlHttpRequest();
					var params = "id=" + listIdArray[1] + "&type=famous&d=" + new Date().getTime();
					readXmlFile('plotInfo', params);
				}
			}
		}
	
		if(search)
		{
			// center map on plot
			listSearch(listId);
		}
		else
		{
			// if a plot has not just been clicked
			if(!plotClick)
			{
				// highlight plot on viewer, if it is visible
				updateSearchedPlot(true, listId);
				
				// update searchedplot and hlrow global variables
				for(var i=1;i<listIdArray.length;i++)
				{
					localSearchedPlot = localSearchedPlot + '_' + listIdArray[i];
					localHlRow = localHlRow + '_' + listIdArray[i];
				}
				
				searchedPlot = localSearchedPlot;
				hlRow = localHlRow;
			}
		}
	}
	else
	{
		updateSearchedPlot(true, listId);
		
		// update searchedplot and hlrow global variables
		for(var i=1;i<listIdArray.length;i++)
		{
			localSearchedPlot = localSearchedPlot + '_' + listIdArray[i];
		}
		
		searchedPlot = localSearchedPlot;
	}
}

// arguments: id = id attribute of row or plot, highlight = (highlight:true) (unhighlight:false)
function setPlotHighlight(id, highlight)
{
	var idArray = id.split("_");
	// check if plot is already visible, if so change its class
	var visiblePlot = document.getElementById('plot_' + idArray[1] + '_' + idArray[2] + '_' + idArray[3] + '_' + idArray[4]);
	// if plot is visible the continue
	if (visiblePlot)
	{	
		// split the plot class name into an array
		var plotCNArr = visiblePlot.className.split(' ');
		
		if(highlight)
		{
			// highlight plot
			if(plotCNArr[1] == 'onList')
			{
//				visiblePlot.className = plotCNArr[0] + " searchedOnList";
			}
			else if(plotCNArr[1] == 'sponsoredOnList')
			{
				visiblePlot.className = plotCNArr[0] + " searchedSponsoredOnList";
			}
			else if(plotCNArr[1] == 'userPlot')
			{
				visiblePlot.className = plotCNArr[0] + " searchedUserPlot";
			}
			else if(plotCNArr[1] == 'corpOnList')
			{
				visiblePlot.className = plotCNArr[0] + " searchedCorpOnList";
			}
			else if(plotCNArr[1] == 'famousSquareOnList')
			{
				visiblePlot.className = plotCNArr[0] + " searchedFamousSquareOnList";
			}
			else if(plotCNArr[1] == 'famousSquareCorpOnList')
			{
				visiblePlot.className = plotCNArr[0] + " searchedFamousSquareCorpOnList";
			}
			
			// return true if successfully highlighted visible plot
			return true;
		}
		else
		{
			// unhighlight plot
			if(plotCNArr[1] == 'searchedOnList')
			{
				visiblePlot.className = plotCNArr[0] + " onList";
			}
			else if(plotCNArr[1] == 'searchedSponsoredOnList')
			{
				visiblePlot.className = plotCNArr[0] + " sponsoredOnList";
			}
			else if(plotCNArr[1] == 'searchedUserPlot')
			{
				visiblePlot.className = plotCNArr[0] + " userPlot";
			}
			else if(plotCNArr[1] == 'searchedCorpOnList')
			{
				visiblePlot.className = plotCNArr[0] + " corpOnList";
			}
			else if(plotCNArr[1] == ' searchedFamousSquareOnList')
			{
				visiblePlot.className = plotCNArr[0] + " famousSquareOnList";
			}
			else if(plotCNArr[1] == ' searchedFamousSquareCorpOnList')
			{
				visiblePlot.className = plotCNArr[0] + " famousSquareCorpOnList";
			}
			// return true if successfully unhighlighted visible plot
			return true;
		}
	}
	else
	{
		// return false if plot is not visible
		return false;
	}
}

// arguments: id = id attribute of row or plot, highlight = (highlight:true) (unhighlight:false)
function setRowHighlight(id, highlight, keepInfo)
{
	if(id && !plotInfoLock)
	{
		var overSquare = false;
		// turn plot id into list id
		var idArray = id.split("_");
		if(idArray[0] == 'plot')
		{
			overSquare = true;
		}
		idArray.splice(0,1,"list");
		id = idArray.join("_");
		
		// check if row exists
		if(document.getElementById(id))
		{	
			// find the row, then the columns of the row
			var row = document.getElementById(id);
			var cols = row.getElementsByTagName('td');
			var className;
			
			if(highlight)
			{
				if(overSquare)
				{
					if(hlRow && (hlRow != id))
					{
						setRowHighlight(hlRow, false);
					}
					// highlight row
					// loop through second, third, fourth and fifth columns
					for(var i=1;i<=4;i++)
					{
						// split class name into an array
						className = cols[i].className;
						className = className.split(" ");
						// loop through class name array looking for columnHL
						for(var j=0; j<className.length;j++)
						{
							if(className[j] == 'columnHL')
							{
								// remove columnHL from the class name and replace with lockedColumnHL
								className.splice(j,1,"lockedColumnHL");
								// re join up class name array
								cols[i].className = className.join(" ");
								break;
							}
						}
					}
					row.parentNode.insertBefore(row,row.parentNode.getElementsByTagName('tr')[0]);
					document.getElementById('listTableContainer').scrollTop = 0;
					// update global variable containing currently highlighted row
					hlRow = id;
				}
				else
				{
					if(hlRow && (hlRow != id))
					{
						setRowHighlight(hlRow, false);
					}
					
					// highlight row
					// loop through second, third, fourth and fifth columns
					for(var i=1;i<=4;i++)
					{
						// split class name into an array
						className = cols[i].className;
						className = className.split(" ");
						// loop through class name array looking for columnHL
						for(var j=0; j<className.length;j++)
						{
							if(className[j] == 'columnHL')
							{
								// remove columnHL from the class name and replace with lockedColumnHL
								className.splice(j,1,"lockedColumnHL");
								// re join up class name array
								cols[i].className = className.join(" ");
								break;
							}
						}
					}

					// update global variable containing currently highlighted row
					hlRow = id;
				}
			}
			else
			{
				// unhighlight row
				// loop through second, third, fourth and fifth columns
				for(var i=1;i<=4;i++)
				{
					// split class name into an array
					className = cols[i].className;
					className = className.split(" ");
					// lopp through class name array looking for columnHL
					for(var j=0; j<className.length;j++)
					{
						if(className[j] == 'lockedColumnHL')
						{
							// remove columnHL from the class name and replace with lockedColumnHL
							className.splice(j,1,"columnHL");
							// re join up class name array
							cols[i].className = className.join(" ");
							break;
						}
					}
				}
				
				var seeMore = cols[2].getElementsByTagName('a')[0];
				if(seeMore.className == "return")
				{
					// change return to moreinfo
					seeMore.className = "moreInfo";
					seeMore.innerHTML = "see more";
					
					if(document.getElementById('imageViewerContainer').style.display == "none")
					{
						clearMoreInfo(true);
					}
				}

				// search for plot in map, if searched plot has a value then use it to search
				if(searchedPlot)
				{
					setPlotHighlight(searchedPlot, false);
				}
				else
				{
					setPlotHighlight(hlRow, false);
				}
				if(!keepInfo)
				{
					clearPlotInfo();
				}
				// clear hlRow and searchedPlot global variables 
				hlRow = null;
				searchedPlot = null;
			}
		}
	}
}

function setTopRowHighlight(highlight)
{
	var topRow = document.getElementById('list').getElementsByTagName('tr')[0];
	if(topRow.className == 'listHeader')
	{
		topRow = document.getElementById('list').getElementsByTagName('tr')[1];
	}
	if(topRow)
	{
		// split id
		var topRowId = topRow.id;
		var topRowIdArr = topRowId.split("_");
		//alert('top row id = '+topRowId);
		// split class name of column
		var secondColumn = topRow.getElementsByTagName('td')[1];
		var className = secondColumn.className;
		className = className.split(" ");

		setRowHighlight(topRowId, true);
		updateSearchedPlot(true, topRowId);

		// check if the last class name is "unsponsored"
		if(className[className.length-1] == "unsponsored" || className[className.length-1] == "corp")
		{
			setPEVImage(topRowId);
		}
		else if(className[className.length-1] == "famousSquareCorp" || className[className.length-1] == "famousSquare")
		{
			setPEVImage(false);
			plotInfo(topRowId);
		}
		else
		{
			setPEVImage(false);
			plotInfo(topRowId,false,false,true);
		}
	}
}

// arguments: id = PLOT_ID, if false then default to camera image
function setPEVImage(idArray, plotview)
{
	var pic = document.getElementById('playerEyeViewContainer');
	var imgs = pic.getElementsByTagName("img");
	var ps = pic.getElementsByTagName("p");
	
	if(idArray)
	{
		idArray = idArray.split("_");
		var plot_id = null;
		var th_id = null;
	
		if(!plotview)
		{
			plot_id = idArray[2];
		
			// check if this is a treasure hunt square
			if(idArray[5] != "url" && idArray[5])
			{
				th_id = idArray[5];
			}
			else if(idArray[5] == "url" && idArray[6])
			{
				th_id = idArray[6];
			}
		
		}
		else
		{
			plot_id = idArray[1];
		}
	
		if(plot_id && !th_id)
		{
			for(var i=0;i<ps.length;i++)
			{
				ps[i].style.display = 'none';
			}
			//ps[0].style.display = 'none';
			// check if player eye view (pev) thumbnail is already being displayed
			if(!document.getElementById("pev_thumb_" + plot_id))
			{
				// edit thumbnail
				// locate image element
				var img = imgs[0];
				// build id for thumbnail
				img.id = "pev_thumb_" + plot_id;
				// build image src
				//img.src = "/scripts/php/timthumb.php?src=/images/sub_regions/" + id + ".jpg&h=123&zc=0";
				if(treasure_hunt_finished_notification)
				{
					img.src = "/images/treasure_hunt/finished.jpg";
				}
				else
				{
					img.src = "/images/sub_regions/pev/" + plot_id + ".jpg";
				}
				
			}
			pic.style.display = 'block';
		
			if(document.getElementById('imageViewer').dimensions.zoomLevel >= (maxZoom - 1))
			{
				if(document.getElementById('listTableContainer').getElementsByTagName('td').length == 0)
				{
					document.getElementById('listHelpContainer').style.display = 'block';
				}
				else
				{
					document.getElementById('listHelpContainer').style.display = 'none';
				}
			}
		}
		else if(plot_id && th_id)
		{
			// check if player eye view (pev) thumbnail is already being displayed
			if(!document.getElementById("pev_thumb_" + plot_id))
			{
				// edit thumbnail
				// locate image element
				var img = imgs[0];
				// build id for thumbnail
				img.id = "pev_thumb_" + plot_id;
				
				if(treasure_hunt_finished_notification)
				{
					img.src = "/images/treasure_hunt/finished.jpg";
					// treasure square
					for(var i=0;i<ps.length;i++)
					{
						ps[i].style.display = 'none';
					}
					//ps[0].style.display = 'none';
				}
				else
				{
					// build image src
					img.src = "/scripts/php/timthumb.php?src=/images/treasure_hunt/" + plot_id + ".jpg&h=143&zc=0";
					// treasure square
					for(var i=0;i<ps.length;i++)
					{
						if(ps[i].id == 'th_text_'+plot_id)
						{
							ps[i].style.display = 'block';
						}
						else
						{
							ps[i].style.display = 'none';
						}
					}
					//ps[0].style.display = 'block';
					
				}
			}
			pic.style.display = 'block';
		
			if(document.getElementById('imageViewer').dimensions.zoomLevel >= (maxZoom - 1))
			{
				if(document.getElementById('listTableContainer').getElementsByTagName('td').length == 0)
				{
					document.getElementById('listHelpContainer').style.display = 'block';
				}
				else
				{
					document.getElementById('listHelpContainer').style.display = 'none';
				}
			}
		}
	}
	else
	{
		for(var i=0;i<ps.length;i++)
		{
			ps[i].style.display = 'none';
		}
		//ps[0].style.display = 'none';
		// default image to camera
		imgs[0].id = "";
		imgs[0].setAttribute("src", "/images/transparentpixel.gif");
		pic.style.display = 'none';
		
		document.getElementById('listHelpContainer').style.display = 'none';
	}
}

// jump to plot icon clicked
function listSearch(listId)
{
	if(!editingPlotLock)
	{
		setRowHighlight(listId, true);
	
		var listIdArray = listId.split("_");
		var localSearchedPlot = 'plot';
		// update searchedplot and hlrow global variables
		for(var i=1;i<listIdArray.length;i++)
		{
			localSearchedPlot = localSearchedPlot + '_' + listIdArray[i];
		}
		
		// check if plot to highlight is visible
		if (!updateSearchedPlot(true, localSearchedPlot))
		{
			// hide the autoZoom container
			toggleAutoZoom();
			
			var imageViewer = document.getElementById('imageViewer');
			// if returns false then failed to highlight plot, so it is not visible
			// use this to find the x,y coordinates of the plot by making an xml request to the database
			xmlHttp = createXmlHttpRequest();
			var params = "q=" + listIdArray[1] + "&l=" + imageViewer.dimensions.zoomLevel + "&s=" + imageViewer.dimensions.iv.size + "&c=" + imageViewer.switches.showSeats + "&d=" +  + new Date().getTime();
			readXmlFile('createPlots', params);
		}
		else
		{
			// split column class name to find if sponsored or unsponsored
			var td = document.getElementById(listId).getElementsByTagName('td')[1];
			var className = td.className;
			var type = className.split(" ");
			if(type[1] == 'unsponsored' || type[1] == 'corp')
			{
				setPEVImage(listId);
			}
			else if(type[1] == 'sponsored')
			{
				plotInfo(listId,false,false,true);
			}
			else if(type[1] == 'famousSquareCorp' || type[1] == 'famousSquare')
			{
				plotInfo(listId);
			}
		}
	}
	else
	{
		// editing a plot
		alert("You are in edit mode. Please cancel or save to use this function");
	}
}

// edit plot icon clicked
function editMyPlot(listId, shortCut)
{	
	//listSearch(listId);
	// function to allow editing on the main page
	saveViewerPosition();
	if(!shortCut)
	{
		listId = listId.split("_");
		listId = listId[1];
	}
	window.location = "/index.php?edit_plot=" + listId;
}

function sponsorURL(listId)
{
	window.open("/sponsor_site_redirect.php?id=" + listId);
}

function moreInfo(el)
{
	if(!editingPlotLock)
	{
		if(el.className == "moreInfo")
		{
			listId = el.parentNode.parentNode.id;

			plotInfoLockSwitch(false);
			if(hlRow)

			{
				setRowHighlight(hlRow, false);
			}	

			setRowHighlight(listId, true);

			el.className = "return";
			el.innerHTML = "return";

			listId = listId.split("_");
			xmlHttp2 = createXmlHttpRequest();
			var params = "id=" + listId[1];
			readXmlFile('moreInfo', params);
		}
		else
		{
			clearMoreInfo();
		}
	}
	else
	{
		alert("You are in edit mode. Please cancel or save to use this function");
	}
}

function clearMoreInfo(justElements, tabClick)
{
	if(!justElements)
	{
		plotInfoLockSwitch(false);
		if(hlRow)
		{
			setRowHighlight(hlRow, false);
		}
	}
	
	document.getElementById("moreInfoText").style.display = "none";
	document.getElementById("imageViewer").style.display = "inline";
	document.getElementById("moreInfoImageContainer").style.display = "none";
}

function updateSearchedPlot(refresh, plotId)
{
	// remove old searched plot, this will remove it if it is visible
	if(searchedPlot)
	{
		setPlotHighlight(searchedPlot, false);
	}
	
	// if the searched plot is to be refreshed (i.e. a new search is being done)
	if(refresh)
	{
		// new searched plot, to replace current one
		if(setPlotHighlight(plotId, true))
		{
			searchedPlot = plotId;
			// if plot to be highlighted is visible 
			return true;
		}
		else
		{
			// if plot to be highlighted is not visible 
			return false;
		}
	}
}

function changeIcon(direction, id, status)
{
	var icon = document.getElementById('iconImage');
	
	// split class name to find out which icon we are on 
	var cName = icon.className;
	var cNameArray = cName.split("_");
	
	if(direction == 'next')
	{
		// if the current Icon is the last one
		if(parseInt(cNameArray[1], 10) == numberDefaultIcons)
		{
			if(status == 1)
			{
				// if the icon is approved set to user uploaded icon
				cNameArray[1] = '0';
			}
			else
			{
				// if the icon is not approved or uploaded set to first default icon
				cNameArray[1] = '1';
			}
		}
		else
		{
			// if not last plot then increment by 1
			cNameArray[1] = parseInt(cNameArray[1], 10) + 1;
		}
	}
	else
	{
		// if the current Icon is the user icon
		if(parseInt(cNameArray[1], 10) == 0)
		{
			// set to the last icon
			cNameArray[1] = numberDefaultIcons;
		}
		else
		{
			// if the user icon has not been uploaded or been approved
			if(status != 1 && parseInt(cNameArray[1], 10) == 1)
			{
				// skip the the user icon and go to the last icon
				cNameArray[1] = numberDefaultIcons;
			}
			else
			{
				// else decrement by 1
				cNameArray[1] = parseInt(cNameArray[1], 10) - 1;
			}
		}
	}
	
	cName = cNameArray.join("_");
	icon.className = cName;
	if(cNameArray[1] == 0)
	{
		// if icon is 0 then status must be 1
		/*if(status == 0)
		{
			icon.src = "/images/user/default_icons/none.jpg";
		}
		else if(status == 3)
		{
			icon.src = "/images/user/default_icons/rejected.jpg";
		}
		else if(status == 2)
		{
			icon.src = "/images/user/default_icons/awaiting.jpg";
		}
		else */
		if(status == 1)
		{
			icon.src = "/images/user/user_icons/" + id + ".jpg?";
		}
	}
	else
	{
		icon.src = "/images/user/default_icons/" + cNameArray[1] + ".png";
	}
}

function displayInfo(type, hidden)
{
	/*
		plot info divs
		
		0 = grab this square container
		1 = owner profile
		2 = edit owner image container / owner image container
		3 = edit owner message container / owner message container
	
	*/
	
	var plotInfoDivs = document.getElementById('plotInfo').getElementsByTagName('div');
	
	if(type == 'owner-edit')
	{
		// clear and hide all plot info
		if(!hidden)
		{
			tabClick('home');
		}
		plotInfoLockSwitch(true);
		editingPlotSwitch(true);
		// hide generic plot info container
		plotInfoDivs[0].style.display = "none";
		// if an owner square then show all elements
		for(var i=1; i<plotInfoDivs.length; i++)
		{
			plotInfoDivs[i].style.display = 'block';
		}
		// also hide image and message as IE7 won't hide even if parent is hidden
		plotInfoDivs[2].style.visibility = 'visible';
	}
	else if(type == 'unsponsored')
	{
		// clear and hide all plot info
		if(!hidden)
		{
			tabClick('home');
		}
		
		/*// if an unsponsored square then hide all elements
		for(var i=1; i<plotInfoDivs.length; i++)
		{
			plotInfoDivs[i].style.display = 'none';
		}
		
		// also hide image and message as IE7 won't hide even if parent is hidden
		plotInfoDivs[3].style.visibility = 'hidden';
		
		// show generic text container
		plotInfoDivs[0].style.display = "block";
		
		var spans = plotInfoDivs[0].getElementsByTagName('span');
		spans[0].style.display = 'none';
		spans[1].style.display = 'block';
		spans[2].style.display = 'none';*/
		
		for(var i=0; i<plotInfoDivs.length; i++)
		{
			plotInfoDivs[i].style.display = 'none';
		}
		
		// also hide image and message as IE7 won't hide even if parent is hidden
		plotInfoDivs[3].style.visibility = 'hidden';
		
	}
	else if(type == 'seat')
	{
		// clear and hide all plot info
		if(!hidden)
		{
			tabClick('home');
		}
		
		// if an unsponsored square then hide all elements
		/*for(var i=1; i<plotInfoDivs.length; i++)
		{
			plotInfoDivs[i].style.display = 'none';
		}
		
		// also hide image and message as IE7 won't hide even if parent is hidden
		plotInfoDivs[3].style.visibility = 'hidden';
		
		// show generic text container
		plotInfoDivs[0].style.display = "block";
		
		var spans = plotInfoDivs[0].getElementsByTagName('span');
		spans[0].style.display = 'none';
		spans[1].style.display = 'block';
		spans[2].style.display = 'none';*/
		
		for(var i=0; i<plotInfoDivs.length; i++)
		{
			plotInfoDivs[i].style.display = 'none';
		}
		
		// also hide image and message as IE7 won't hide even if parent is hidden
		plotInfoDivs[3].style.visibility = 'hidden';
	}
	else if(type == 'corp')
	{
		// clear and hide all plot info
		if(!hidden)
		{
			tabClick('home');
		}
		// bmj:  currently only showing generic info when hovering over a corp square in the list, can be changed here
		/*plotInfoDivs[0].style.display = "block";
		var spans = plotInfoDivs[0].getElementsByTagName('span');
		spans[0].style.display = 'block';
		spans[1].style.display = 'none';
		spans[2].style.display = 'none';*/
		
		for(var i=0; i<plotInfoDivs.length; i++)
		{
			plotInfoDivs[i].style.display = 'none';
		}
		
		// also hide image and message as IE7 won't hide even if parent is hidden
		plotInfoDivs[3].style.visibility = 'hidden';
	}
	else if(type == 'moreinfo')
	{
		// clear and hide all plot info
		if(!hidden)
		{
			tabClick('home');
		}
		
		document.getElementById('plotInfo').style.display = 'block';
		setPEVImage(false);
		
		plotInfoLockSwitch(true);
		// if an unsponsored square then hide all elements
		for(var i=1; i<plotInfoDivs.length; i++)
		{
			plotInfoDivs[i].style.display = 'none';
		}
		
		// also hide image and message as IE7 won't hide even if parent is hidden
		//plotInfoDivs[3].style.visibility = 'hidden';
		
		plotInfoDivs[0].style.display = "block";
		var spans = plotInfoDivs[0].getElementsByTagName('span');
		spans[0].style.display = 'none';
		spans[1].style.display = 'none';
		spans[2].style.display = 'block';
	}
	else if(type == 'famous-square')
	{
		// clear and hide all plot info
		if(!hidden)
		{
			tabClick('home', true);
		}
		plotInfoDivs[0].style.display = "none";
		// if an owner square then show all elements
		for(var i=1; i<plotInfoDivs.length; i++)
		{
			plotInfoDivs[i].style.display = 'block';
		}
		// also show image and message as IE7 won't hide even if parent is hidden
		plotInfoDivs[3].style.visibility = 'visible';
	}
	else
	{
		// clear and hide all plot info
		if(!hidden)
		{
			tabClick('home', true);
		}
		plotInfoDivs[0].style.display = "none";
		// if an owner square then show all elements
		for(var i=1; i<plotInfoDivs.length; i++)
		{
			plotInfoDivs[i].style.display = 'block';
		}
		// also hide image and message as IE7 won't hide even if parent is hidden
		plotInfoDivs[3].style.visibility = 'visible';
	}
}

function plotInfoResponse()
{
	var xmlRoot = findXmlRoot(xmlHttp2);
	var iconIdNode = xmlRoot.getElementsByTagName("icon");
	var plotTextNode = xmlRoot.getElementsByTagName("text");
	var typeNode = xmlRoot.getElementsByTagName("type");
	var idNode = xmlRoot.getElementsByTagName("id");
	var plotText;
	var iconId;
	var type;

	if(plotTextNode.item(0).firstChild)
	{
		plotText = plotTextNode.item(0).firstChild.data;
	}

	if(idNode.item(0).firstChild)
	{
		id = idNode.item(0).firstChild.data;
	}

	if(typeNode.item(0).firstChild)
	{
		type = typeNode.item(0).firstChild.data;
	}
	
	if(type)
	{
		if(type == 'unsponsored')
		{
			// update the unsponsored squares text
			if(plotText)
			{
				plotText = plotText.replace(/\n/g, '<br />');
				document.getElementById('grabThisSquareText').innerHTML = plotText;
			}
			displayInfo('unsponsored');
		}
		else if(type == 'famous')
		{
			var defaultImageNode = xmlRoot.getElementsByTagName("defaultImage");
			defaultImage = defaultImageNode.item(0).firstChild.data;
			var parent = document.getElementById('ownerMessageContainer');
			if(parseInt(defaultImage) == 0) // use uploaded image
			{
				//<img class="thumb" id="ownerImage" alt="Sponsorer Picture" src="/scripts/php/timthumb.php?src=/images/no-image.jpg&w=99&zc=0" onerror="this.src = \'/scripts/php/timthumb.php?src=/images/no-image.jpg&w=99&zc=0\'" />
				parent.removeChild(document.getElementById('ownerImage'));
				var ownerImage = document.createElement("img");
				ownerImage.className = "thumb";
				ownerImage.id = "ownerImage";
				ownerImage.alt = "Sponsorer Picture";
				ownerImage.src = "/images/famous_squares/pictures/" + id + ".png";
				ownerImage.onError = function () { this.src = '/scripts/php/timthumb.php?src=/images/no-image.jpg&w=99&zc=0'; };
				parent.insertBefore(ownerImage,parent.firstChild);
				//document.getElementById('ownerImage').src = "/images/famous_squares/pictures/" + id + ".png";
			}
			else if(parseInt(defaultImage) == 1)
			{
				parent.removeChild(document.getElementById('ownerImage'));
				var ownerImage = document.createElement("img");
				ownerImage.className = "thumb";
				ownerImage.id = "ownerImage";
				ownerImage.alt = "Sponsorer Picture";
				ownerImage.src = "/images/famous_squares/pictures/default/goal.png";
				ownerImage.onError = function () { this.src = '/scripts/php/timthumb.php?src=/images/no-image.jpg&w=99&zc=0'; };
				parent.insertBefore(ownerImage,parent.firstChild);
				//document.getElementById('ownerImage').src = "/images/famous_squares/pictures/default/goal.png";
			}
			else // use default image
			{
				parent.removeChild(document.getElementById('ownerImage'));
				var ownerImage = document.createElement("img");
				ownerImage.className = "thumb";
				ownerImage.id = "ownerImage";
				ownerImage.alt = "Sponsorer Picture";
				ownerImage.src = "/images/famous_squares/pictures/default/question-mark.png";
				ownerImage.onError = function () { this.src = '/scripts/php/timthumb.php?src=/images/no-image.jpg&w=99&zc=0'; };
				parent.insertBefore(ownerImage,parent.firstChild);
				//document.getElementById('ownerImage').src = "/images/famous_squares/pictures/default/question-mark.png";
			}
			
			// update the owner square text
			if(plotText)
			{
				plotText = plotText.replace(/\n/g, '<br />');
				document.getElementById('ownerMessage').innerHTML = plotText;
			}
			displayInfo('famous-square');
		}
		else if(type == 'sponsored')
		{
			var parent = document.getElementById('ownerMessageContainer');
			
			if(iconIdNode.item(0).firstChild)
			{
				iconId = iconIdNode.item(0).firstChild.data;
				
				// update the owner picture
				if(iconId == 0)
				{
					parent.removeChild(document.getElementById('ownerImage'));
					var ownerImage = document.createElement("img");
					ownerImage.className = "thumb";
					ownerImage.id = "ownerImage";
					ownerImage.alt = "Sponsorer Picture";
					ownerImage.src = "/scripts/php/timthumb.php?src=/images/user/pictures/" + id + ".jpg&w=99&zc=0";
					ownerImage.onError = function () { this.src = '/scripts/php/timthumb.php?src=/images/no-image.jpg&w=99&zc=0'; };
					parent.insertBefore(ownerImage,parent.firstChild);
					//document.getElementById('ownerImage').src = "/scripts/php/timthumb.php?src=/images/user/pictures/" + id + ".jpg&w=99&zc=0";
				}
				else
				{
					parent.removeChild(document.getElementById('ownerImage'));
					var ownerImage = document.createElement("img");
					ownerImage.className = "thumb";
					ownerImage.id = "ownerImage";
					ownerImage.alt = "Sponsorer Picture";
					ownerImage.src = "/images/user/default_icons/" + iconId + ".png";
					ownerImage.onError = function () { this.src = '/scripts/php/timthumb.php?src=/images/no-image.jpg&w=99&zc=0'; };
					parent.insertBefore(ownerImage,parent.firstChild);
					//document.getElementById('ownerImage').src = "/images/user/default_icons/" + iconId + ".png";
				}
			}
			else
			{
				parent.removeChild(document.getElementById('ownerImage'));
				var ownerImage = document.createElement("img");
				ownerImage.className = "thumb";
				ownerImage.id = "ownerImage";
				ownerImage.alt = "Sponsorer Picture";
				ownerImage.src = "/scripts/php/timthumb.php?src=/images/user/pictures/" + id + ".jpg&w=99&zc=0";
				ownerImage.onError = function () { this.src = '/scripts/php/timthumb.php?src=/images/no-image.jpg&w=99&zc=0'; };
				parent.insertBefore(ownerImage,parent.firstChild);
				//document.getElementById('ownerImage').src = "/scripts/php/timthumb.php?src=/images/user/pictures/" + id + ".jpg&w=99&zc=0";
			}
			
			// update the owner square text
			if(plotText)
			{
				plotText = plotText.replace(/\n/g, '<br />');
				document.getElementById('ownerMessage').innerHTML = plotText;
			}
			else
			{
				document.getElementById('ownerMessage').innerHTML = "Owner has not yet uploaded any text.";
			}
			displayInfo('sponsored');
		}
	}	
}

function plotInfoHlRowResponse()
{
	var xmlRoot = findXmlRoot(xmlHttp2);
	var iconIdNode = xmlRoot.getElementsByTagName("icon");
	var plotTextNode = xmlRoot.getElementsByTagName("text");
	var typeNode = xmlRoot.getElementsByTagName("type");
	var idNode = xmlRoot.getElementsByTagName("id");
	var plotText;
	var type;

	if(plotTextNode.item(0).firstChild)
	{
		plotText = plotTextNode.item(0).firstChild.data;
	}
	
	if(idNode.item(0).firstChild)
	{
		id = idNode.item(0).firstChild.data;
	}
	
	if(typeNode.item(0).firstChild)
	{
		type = typeNode.item(0).firstChild.data;
	}

	if(type)
	{
		if(type == 'unsponsored')
		{
			// update the unsponsored squares text
			if(plotText)
			{
				plotText = plotText.replace(/\n/g, '<br />');
				document.getElementById('grabThisSquareText').innerHTML = plotText;
			}
			displayInfo('unsponsored', true);
		}
		else if(type == 'famous')
		{
			var defaultImageNode = xmlRoot.getElementsByTagName("defaultImage");
			defaultImage = defaultImageNode.item(0).firstChild.data;
			
			if(parseInt(defaultImage) == 0) // use uploaded image
			{
				document.getElementById('ownerImage').src = "/images/famous_squares/pictures/" + id + ".png";
			}
			else if(parseInt(defaultImage) == 1)
			{
				document.getElementById('ownerImage').src = "/images/famous_squares/pictures/default/goal.png";
			}
			else // use default image
			{
				document.getElementById('ownerImage').src = "/images/famous_squares/pictures/default/question-mark.png";
			}
			
			// update the owner square text
			if(plotText)
			{
				plotText = plotText.replace(/\n/g, '<br />');
				document.getElementById('ownerMessage').innerHTML = plotText;
			}
			displayInfo('famous-square', true);
		}
		else if(type == 'sponsored')
		{
			if(iconIdNode.item(0).firstChild)
			{
				var iconId = iconIdNode.item(0).firstChild.data;
				
				// update the owner picture
				if(iconId == 0)
				{
					document.getElementById('ownerImage').src = "/scripts/php/timthumb.php?src=/images/user/pictures/" + id + ".jpg&w=99&zc=0";
				}
				else
				{
					document.getElementById('ownerImage').src = "/images/user/default_icons/" + iconId + ".png";
				}
			}
			else
			{
				// if the icon_id has not been set then show the users image if it exists. This though is just a fail safe
				document.getElementById('ownerImage').src = "/scripts/php/timthumb.php?src=/images/user/pictures/" + id + ".jpg&w=99&zc=0";
			}
			
			// update the owner square text
			if(plotText)
			{
				plotText = plotText.replace(/\n/g, '<br />');
				document.getElementById('ownerMessage').innerHTML = plotText;
			}
			else
			{
				document.getElementById('ownerMessage').innerHTML = "Owner has not yet uploaded any text.";
			}
			displayInfo('sponsored', true);
		}
	}	
}

function moreInfoResponse()
{
	var xmlRoot = findXmlRoot(xmlHttp2);
	var regionIdNode = xmlRoot.getElementsByTagName("id");
	var regionNameNode = xmlRoot.getElementsByTagName("name");
	var regionTextNode = xmlRoot.getElementsByTagName("text");
	
	if(regionIdNode.item(0).firstChild)
	{
		// hide image viewer and show more info image container
		document.getElementById("imageViewer").style.display = "none";
		document.getElementById("moreInfoImageContainer").style.display = "block";
		document.getElementById("moreInfoImage").src = "/images/sub_regions/lowres/" + regionIdNode.item(0).firstChild.data + ".jpg";
	}
	
	if(regionNameNode.item(0).firstChild)
	{
		// hide image viewer and show more info image container
		var text = regionNameNode.item(0).firstChild.data;
		
		if(regionTextNode.item(0).firstChild)
		{
			text = "<b>" + text + "</b><br /><br />" + regionTextNode.item(0).firstChild.data;
		}
		
		text = text + "<br /><br /><a href=\"#\" onclick=\"clearMoreInfo(); return false;\"><img src=\"/images/v2/return.png\" /></a>";
		
		document.getElementById("moreInfoText").innerHTML = text;
		displayInfo('moreinfo');
	}
		
}

function plotInfoLockSwitch(lock)
{
	// this function controls whether plot info can be displayed and/or changed (certain actions can unlock)
	plotInfoLock = lock;
}

function editingPlotSwitch(lock)
{
	// this function controls whether plot info can be displayed and/or changed (only finishing editing plot can unlock)
	editingPlotLock = lock;
}

function initPanels(celebId, fsId)
{
	// set global variables
	current_celeb = celebId;
	current_famous_square = fsId;
}

function nextPanels()
{
	xmlHttp3 = createXmlHttpRequest();
	var params = "c_id=" + current_celeb + "&fs_id=" + current_famous_square + "&d=" + new Date().getTime();
	readXmlFile('nextPanels', params);
}

function nextPanelsResponse()
{
	var xmlRoot = findXmlRoot(xmlHttp3);
	
	// get nodes from xml doc
	var celebIdNode = xmlRoot.getElementsByTagName("c_id");
	var celebNameNode = xmlRoot.getElementsByTagName("c_name");
	var famousSquareIdNode = xmlRoot.getElementsByTagName("fs_id");
	var famousSquareTitleNode = xmlRoot.getElementsByTagName("fs_title");
	var famousSquareDefaultImageNode = xmlRoot.getElementsByTagName("fs_di");
	
	// get values from nodes
	var celebId = celebIdNode.item(0).firstChild.data;
	var celebName = celebNameNode.item(0).firstChild.data;
	var famousSquareId = famousSquareIdNode.item(0).firstChild.data;
	var famousSquareTitle = famousSquareTitleNode.item(0).firstChild.data;
	var famousSquareDefaultImage = famousSquareDefaultImageNode.item(0).firstChild.data;
	
	// update Celebrity Dom elements 
	
	// update onclick event for celeb div
	document.getElementById('celeb').onclick = function () {findPlot(celebId); return false;};
	// update name of celeb
	document.getElementById('celebName').innerHTML = celebName;
	// update image of celeb
	document.getElementById('celebPic').src = "/scripts/php/timthumb.php?src=/images/user/pictures/" + celebId + ".jpg&h=85&zc=0;";
	document.getElementById('celebPic').title = celebName;
	
	// update Famous Square Dom elements
	
	// update onclick event for famous square div
	document.getElementById('famousSquare').onclick = function () {findPlot(famousSquareId); return false;};
	// update title of famous square
	document.getElementById('famousSquareTitle').innerHTML = famousSquareTitle;
	// update image of famous square
	if(famousSquareDefaultImage == 0)
	{
		document.getElementById('famousSquarePic').src = "/images/famous_squares/panels/" + famousSquareId + ".png";
	}
	else if(famousSquareDefaultImage == 1)
	{
		document.getElementById('famousSquarePic').src = "/images/famous_squares/panels/default/goal.png";
	}
	else if(famousSquareDefaultImage == 2)
	{
		document.getElementById('famousSquarePic').src = "/images/famous_squares/panels/default/question-mark.png";
	}
	document.getElementById('famousSquarePic').title = famousSquareTitle;
	
	current_celeb = celebId;
	current_famous_square = famousSquareId;	
}

function selectPlot(el, searched)
{
	if(!editingPlotLock)
	{
		var proceed = true;
		var id = el.id;
		var idArray = id.split("_");
		idArray.splice(0,1,"list");
		var listId = idArray.join("_");

		// backup to remove any highlighted rows not removed through plotOver()
		if(document.getElementById(hlRow))
		{
			if(hlRow == listId)
			{
				// already on the list and highlighted (listSearch)
				proceed = false;
			}
			else
			{
				//alert(hlRow);
				plotInfoLockSwitch(false);
				setRowHighlight(hlRow, false);
			}
		}
		else
		{
			hlRow = null;
		}
		
		if(proceed)
		{	
			var className = el.className;
			var newClassName;
			className = className.split(" ");

			var sponsored = false;
			var corp = false;
			var famousSquare = false;
			var seat = false;
			var tunnel = false;

			if(seatCodeLookupTable.indexOf(className[0],1) != -1 || seatCodeLookupTable2.indexOf(className[0],1) != -1)
			{
				if((className[0] == 'seat18') || (className[0] == 'seat18_2'))
				{
					tunnel = true;
				}
				else
				{
					seat = true;
				}
			}

			// change class name of plot
			if(className[1] == "offList")
			{
				if(searched)
				{
//					el.className = className[0] + " searchedOnList";
					searchedPlot = id;
				}
				else
				{
					el.className = className[0] + " onList";
				}
	
				listClassName = " unsponsored";
			}
			else if(className[1] == "famousSquareOffList")
			{
				if(searched)
				{
					el.className = className[0] + " searchedFamousSquareOnList";
					searchedPlot = id;
				}
				else
				{
					el.className = className[0] + " famousSquareOnList";
				}
				listClassName = " famousSquare";
				famousSquare = true;
			}
			else if(className[1] == "famousSquareCorpOffList")
			{
				if(searched)
				{
					el.className = className[0] + " searchedFamousSquareCorpOnList";
					searchedPlot = id;
				}
				else
				{
					el.className = className[0] + " famousSquareCorpOnList";
				}
				listClassName = " famousSquareCorp";
				famousSquare = true;
				corp = true;
			}
			else if(className[1] == "corpOffList")
			{
				if(searched)
				{
					el.className = className[0] + " searchedCorpOnList";
					searchedPlot = id;
				}
				else
				{
					el.className = className[0] + " corpOnList";
				}
				listClassName = " corp";
				corp = true;
			}
			else if(className[1] == "sponsoredOffList")
			{
				if(searched)
				{
					el.className = className[0] + " searchedSponsoredOnList";
					searchedPlot = id;
				}
				else
				{
					el.className = className[0] + " sponsoredOnList";
				}
				listClassName = " sponsored";
				sponsored = true;
			}

			// declare variables
			var list = document.getElementById('list');
			var listContainer = list.parentNode.parentNode.parentNode.parentNode;

			var plot_id = idArray[1];
			var region_name = idArray[3];
			var price = idArray[4];

			// create row to display in the list table
			var tr = document.createElement("tr");
			var td = document.createElement("td");
			var td1 = document.createElement("td");
			var td2 = document.createElement("td");
			var td3 = document.createElement("td");
			var td4 = document.createElement("td");
			var td5 = document.createElement("td");
			var a = document.createElement("a");
			var a1 = document.createElement("a");
			var a2 = document.createElement("a");
			var a3 = document.createElement("a");
			var a4 = document.createElement("a");
			var img = document.createElement("img");
			var img1 = document.createElement("img");
			var img2 = document.createElement("img");

			if(sponsored)
			{
				// create visit link and append it to first column
				a4.href = "#";
				a4.onclick = function () { tabClick('visitsquare'); updateVisitSquareForm(plot_id); return false; };
				a4.className = 'invite';
				a4.appendChild(document.createTextNode("Invite"));
				td.appendChild(a4);
				td3.appendChild(document.createTextNode("Owned"));
			}
			else if(corp)
			{
				td.appendChild(document.createTextNode("Reserved"));
			}
			else if(seat || tunnel)
			{
				// leave td clear
			}
			else
			{
				// only if the plot is not sponsored should there be assigned a BUY tick box
				var chk = document.createElement("input");
				// set attributes for checkbox
				chk.setAttribute("type", "checkbox");
				chk.setAttribute("name", "plot_id[]");
				chk.setAttribute("value", plot_id);
				//chk.setAttribute("CHECKED", true);
				chk.onclick = function () {buyBoxClicked(this);};
				td.appendChild(chk);
			}

			// table structure
			// Buy PlotID Area Cost Remove Jump

			// add attributes to img and link for remove
			a.className = "jump";
			a.href = "#";
			a.onclick = function () { listSearch(this.parentNode.parentNode.id); return false; };

			img.className = "jump";
			img.src = "/images/v1/go-to.png";
			a.appendChild(img);

			a1.className = "remove";
			a1.href = "#";
			a1.onclick = function () { unselectPlot(this.parentNode.parentNode.id); return false; };

			img1.src = "/images/v1/cross.png";
			img1.title = "remove";
			a1.appendChild(img1);

			a2.className = "moreInfo";
			a2.href = "#";
			a2.onclick = function () { moreInfo(this); return false; };
			a2.appendChild(document.createTextNode("see more"));

			if(idArray[5] == "url")
			{
				a3.className = "url";
				a3.href = "#";
				a3.onclick = function () { sponsorURL(this.parentNode.parentNode.id); return false; };

				img2.src = "/images/v2/internet.gif";
				img2.title = "visit sponsor website";
				a3.appendChild(img2);
			}
			
			// display home page (this will return to normal state)
			tabClick('home');
			
			// append info to columns
			td1.className = 'lockedColumnHL' + listClassName;
			td2.className = 'lockedColumnHL' + listClassName;
			td3.className = 'currency lockedColumnHL' + listClassName;
			td4.className = 'lockedColumnHL' + listClassName;
			// add id to row and highlightedRow div
			tr.id = hlRow = listId;
	
			if(seat)
			{
				td1.appendChild(document.createTextNode("Seat"));
			}
			else if(tunnel)
			{
				td1.appendChild(document.createTextNode("Tunnel"));
			}
			else
			{
				td1.appendChild(document.createTextNode(appendZeroes(plot_id)));
			}
			td2.appendChild(a2);
			td4.appendChild(a);

			if(idArray[5] == "url")
			{
				td5.appendChild(a3);
			}

			td5.appendChild(a1);
			//tr.className = "listRow";
			// append all columns and links
			tr.appendChild(td);
			tr.appendChild(td1);
			tr.appendChild(td2);
			tr.appendChild(td3);
			tr.appendChild(td4);
			tr.appendChild(td5);

			// add rows to the bottom of the table
			//list.appendChild(tr);
	
			// add rows to the top of the table
			list.insertBefore(tr, list.getElementsByTagName('tr')[0]);

			// price must be added last to avoid method leak with currencyConvertor
			//td3.innerHTML = currencyConvertor(plotIdArray[3]);
			if(!seat && !tunnel && !sponsored)
			{
				td3.innerHTML = "\&pound;" + parseFloat(price).toFixed(2);
			}

			updateBasketListCookie(plot_id, 'add');

			if(sponsored)
			{
				linkCount(plot_id);
				plotInfo(listId, false, false, true);
			}
			else if(famousSquare)
			{
				plotInfo(listId);
			}
			else
			{
				//plotInfo(listId);
				clearPlotInfo();
				setPEVImage(listId);
			}
	
			//document.getElementById(listId).scrollIntoView(false);
			// for IE8 which doesn't understand scrollintoview
			document.getElementById('listTableContainer').scrollTop = 0;
		}
	}
	else
	{
		// editing a plot
		alert("You are in edit mode. Please cancel or save to use this function");
	}
}

function unselectPlot(id)
{
	var idArray = id.split("_");
	var listId;
	var plotId;
	
	// the plot is being removed from the map
	if(idArray[0] == "plot")
	{
		// remove the "plot" prefix and replace it with the "list" prefix
		idArray.splice(0,1,"list");
		listId = idArray.join("_");
		
		plotId = id; 
	}
	// plot is being removed from the list
	else
	{
		// remove the "list" prefix and replace it with the "plot" prefix
		idArray.splice(0,1,"plot");
		var plotId = idArray.join("_");
		
		listId = id; 
	}
	
	// find plot on map to be changed
	if(document.getElementById(plotId))
	{
		var plotToChange = document.getElementById(plotId);
		if (plotToChange)
		{
			//change classname
			var cnArray = plotToChange.className.split(" ");
						
			if(cnArray[1] == 'onList' || cnArray[1] == 'searchedOnList')
			{
				plotToChange.className = cnArray[0] + ' offList';
			}
			else if(cnArray[1] == 'corpOnList' || cnArray[1] == 'searchedCorpOnList')
			{
				plotToChange.className = cnArray[0] + ' corpOffList';
			}
			else if(cnArray[1] == 'famousSquareOnList' || cnArray[1] == 'searchedFamousSquareOnList')
			{
				plotToChange.className = cnArray[0] + ' famousSquareOffList';
			}
			else if(cnArray[1] == 'famousSquareCorpOnList' || cnArray[1] == 'searchedFamousSquareCorpOnList')
			{
				plotToChange.className = cnArray[0] + ' famousSquareCorpOffList';
			}
			else
			{
				plotToChange.className = cnArray[0] + ' sponsoredOffList';
			}
		}
	}
	
	// remove row from table
	document.getElementById("list").removeChild(document.getElementById(listId));
	
	if(listId == hlRow)
	{
		// if the plot being removed was the highlihgted row, then make hlRow null
		hlRow = null;
	}
	
	updateBasketListCookie(idArray[1], 'del');
	// refresh info pane (if no plots remain then this will hide the list and plot info)
	if(!plotInfoLock)
	{
		tabClick('home');
	}
}

function checkQuery(query)
{
	//Check query if it's not a number, assuming it's a screenname and
	//find a plot id if one exists for it.
	var ret = '';
	var options = ({url: 'getsquawkerplot.php', async: false,  type: 'GET', data:{'sn': query}, success:function(r){ ret = r;}});
	$.ajax(options);
	return ret;
	
}
function findPlot(query,mzl1)
{
	//This is a squawk requirement but isn't conditioned on mode yet
	//so you may see errors in the browser consoles because of this
	$('#bubble').fadeOut(300);
	
	//set global
	
	//squawkOut();
	
	//alert(query);
//alert('JQ: function findPlot ' + query + mzl1);
	// currently only supports search for plot id's
	// checks that the query entered is a number (is not NaN (not a number))
	
	//First, if it's not a number, assume it's a screen name and go find
	//a plot for it if there is one.
	
	if(isNaN(query))
	{	
		query = checkQuery(query);
		
	}
	
	if(!isNaN(query) && query != '')
	{	query = query.toString();
		// check if plot is visible first
		
		// remove all leading zeroes
		while(query.indexOf("0") === 0)
		{
			query = query.substr(1);
		}
		
		query = Number(query);
		
		//if(query <= pitchNumberOfPlots && query >= 1)
		if(query >= 1)
		{
			/*
			// need to search through all visible plots to find if any match the query using match()
			var allPlots = document.getElementById('plots').getElementsByTagName('div');
			var plotId;
			var visiblePlot = null;
			for(var i = 0; i < allPlots.length; i++)
			{
				// get id of current plot
				plotId = allPlots[i].id;
				// check if the id contains this pattern
				if(plotId.match("plot_"+query+"_"))
				{
					// if so then assign it to visible plot and end loop
					visiblePlot = allPlots[i];
					i = allPlots.length;
				}
			}
		
			// if a match was found
			if(visiblePlot)
			{
				var className = visiblePlot.className;
				className = className.split(" ");
				// check if the plot is not on the list
				if(className[1] == "offList" || className[1] == "searchedOffList" || className[1] == "sponsoredOffList" || className[1] == "searchedSponsoredOffList")
				{
					selectPlot(visiblePlot, true);
				}
				else if(className[1] == "onList" || className[1] == "searchedOnList")
				{
					// highlight plot and row
					setRowHighlight(visiblePlot.id, true);
					var idArray = visiblePlot.id;
					idArray = idArray.split("_");
					setPEVImage(idArray[2]);
					//plotInfo(visiblePlot.id,false,true);
				}
				else
				{
					// highlight plot and row
					setRowHighlight(visiblePlot.id, true);
					plotInfo(visiblePlot.id,false,true,true);
				}
			}
			else
			{*/
				if(!mzl1)
				{
					// hide the autoZoom container
					toggleAutoZoom();
				}
				// if no match was found then continue with ajax request
				var imageViewer = document.getElementById('imageViewer');
				// use this to find the x,y coordinates of the plot by making an xml request to the database
				xmlHttp = createXmlHttpRequest();
				//imageViewer.switches.movable = false;
				var params = "q=" + query + "&l=" + imageViewer.dimensions.zoomLevel + "&s=" + imageViewer.dimensions.iv.size + "&c=" + imageViewer.switches.showSeats + "&d=" + new Date().getTime();
				if(mzl1)
				{
					params = params + "&m=" + 1;
				}
//alert('JQ: readXmlFile');
				readXmlFile('createPlots', params);
			
				
				
			//}
		}
		else
		{
			// entered a number 
			alert("Please enter a square number between 1 and 9163 or a valid username.");
		}
	}
	else
	{
		alert("Please enter a square number that you want to go to (between 1 and 9163) or a valid username.");
	}
}

function createPlots(imageViewer, hide)
{	
	//alert('I have been called');
	// if function called using a timer, then need to define imageViewer
	if(!imageViewer)
	{
		imageViewer = document.getElementById('imageViewer');
	}
	
	var switches = imageViewer.switches;
	// check if at any plot level
	if((switches.plotLevel || switches.plotLevel2 || switches.plotViewLevel) && !hide)
	{
		// at a plot level
		// fetch plots
		var dim = imageViewer.dimensions;
		xmlHttp = createXmlHttpRequest();
		// prevent the surface from being moved whilst creating the grid
		//switches.movable = false;
		//alert(imageViewer.switches.showSeats);
		// set coordinate parameters for createPlots.php, including the zoom level (date is added to avoid caching problem in IE)
		var params = "x=" + dim.bi.x + "&y=" + dim.bi.y + "&l=" + dim.zoomLevel + "&s=" + dim.iv.size + "&c=" + imageViewer.switches.showSeats + "&d=" + new Date().getTime();
		readXmlFile('createPlots', params);
	}
	else
	{
		// clear all plots from the plots div 
		clearInnerHTML(document.getElementById("plots"));
	}
}

function createPlotsResponse()
{
//alert('JQ: function createPlotsResponse');
//var response = xmlHttp.responseText;
//alert('JQ: ' + response);

	if(xmlHttp.responseText == "not found")
	{
		alert("Looks like this square doesn't exist, please try again");
	}
	else if(xmlHttp.responseText == "fail")
	{
		// clear grid if none found
		clearInnerHTML(document.getElementById("plots"));
	}
	else
	{
//alert('JQ: findXmlRoot xmlHttp = ' + xmlHttp);
		var xmlRoot = findXmlRoot(xmlHttp);
//alert('JQ: ' + xmlRoot);
		// create values for x and y attributes if they exist	
		var plots = xmlRoot.getElementsByTagName('plots')[0];
		var x = plots.getAttribute("x");		
		var y = plots.getAttribute("y");
		var userId = plots.getAttribute("userId");
		var searchedPlotId = plots.getAttribute("id");
		var mzl1 = plots.getAttribute("mzl1");
		// set treasure_hunt_finished_notification 
		treasure_hunt_finished_notification = plots.getAttribute("thfn");
		
		var rowArray = xmlRoot.getElementsByTagName("row");
		var colArray = xmlRoot.getElementsByTagName("col");
		var numberPlots = rowArray.length;
		
		var cancelGrid = false;
		
		// get imageViewer element and the dimensions
		var imageViewer = document.getElementById("imageViewer");
		var dim = imageViewer.dimensions;
		var switches = imageViewer.switches;
/*
alert('JQ: switches.plotLevel = ' + switches.plotLevel);
alert('JQ: switches.plotLevel2= ' + switches.plotLevel2);
alert('JQ: switches.plotViewLevel= ' + switches.plotViewLevel);
*/
		// check if searchedPlotId has been sent back, if so it means that the map needs repositioning to find it
		if (searchedPlotId)
		{
//alert('JQ: searchedPlotId = ' + searchedPlotId);

		// ---------- JQ - highlight searched square in white ----------
		$.get('../own/ajax_get_plot_region_price.php?plot_id=' + searchedPlotId, function(data) {
			if (data)
				{
				var this_plot_id = 'plot_' + searchedPlotId + '_' + searchedPlotId + '_region_' + data;

				// ---------- JQ - highlight searched square ----------
				$('#plots').children().removeClass('searched_square');
				$('#' + this_plot_id).addClass('searched_square');

/*
				var searched_square_left = $('#' + this_plot_id).css('left');
				var searched_square_top = $('#' + this_plot_id).css('top');

				searched_square_left = searched_square_left.replace(/px/, '')
				searched_square_top = searched_square_top.replace(/px/, '')

				searched_square_left = parseInt(searched_square_left) - 4 + 'px';
				searched_square_top = parseInt(searched_square_top) - 4 + 'px';

				$('#' + this_plot_id).css({'left': searched_square_left, 'top': searched_square_top, 'border': '5px solid #f00'});
*/
				// ---------- JQ - highlight searched square ----------
				}
			});
		// ---------- JQ - highlight searched square in white ----------

			if(mzl1) // if showing squares at max zoom minus 1
			{
				var zooms = dim.maxZoom - dim.zoomLevel - 1;
				if(zooms > 0)
				{
					zoomImage(imageViewer, undefined, zooms, true);
				}
			}
			else if(dim.zoomLevel < dim.maxZoom) // if the current zoom level is less then the highest plot level
			{
				// then find out the number of zooms needed to get to plot view
				var zooms = dim.maxZoom - dim.zoomLevel;
				if(zooms > 0)
				{
					zoomImage(imageViewer, undefined, zooms, true);
				}
			}
		
			// now reposition map
			// set x,y coordinates and centre viewer
			dim.bi.x = parseInt(x);
			dim.bi.y = parseInt(y);

			// define mouse
			var mouse = {'x': dim.iv.width / 2, 'y': dim.iv.height / 2};
			imageViewer.start = mouse;
			
			// perform refresh of tiles and position
			//resetTiles(imageViewer);			
			zoomImage(imageViewer, undefined, 0, true);
		}

		if(switches.plotLevel || switches.plotLevel2)
		{
			var idArray = xmlRoot.getElementsByTagName("id");
			// create clone of plots, the clone will be modified, then will replace the original, this will save on dom reflows
			var original = document.getElementById("plots");
			// (false) means it only clones the element and excludes its children
			var cloned = original.cloneNode(false);

			// create local variables
			var newDiv;
			var divStyleText;
			var plotId;
			var owner;
			var ownerId;
			var celeb;
			var url;
			var icon;
			var famousSquare;
			var treasureHunt;
			var region;
			var regionName;
			var price;
			var corp;
			var subRegionId;
			var seatCodeId;
			var col;
			var listId;
			var onList;
			var highlighted;
			var searched;
			var addSearchedPlot = false;
			var addSearchedPlotId = null;
			var showSearchedPlot = false;
			var showSearchedPlotId = null;
			var showSearchedPlotIdOwned = false;
			var showSearchedPlotIdFamous = false;
			var squawk; // WJR
			var owner_plot; //JQ

//alert('JQ: numberPlots = ' + numberPlots);

			for (var i = 0;i < numberPlots; i++)
			{
//alert('JQ: 1 i = ' + i);
				plotId = idArray.item(i).firstChild.data;
				ownerId = idArray.item(i).getAttribute('ownerId');
				celeb = idArray.item(i).getAttribute('celeb');
				url = idArray.item(i).getAttribute('url');
				seatCodeId = idArray.item(i).getAttribute('sc');
				icon = idArray.item(i).getAttribute('icon');
				famousSquare = idArray.item(i).getAttribute('fs');
				treasureHunt = idArray.item(i).getAttribute('th');
				region = idArray.item(i).parentNode.parentNode.parentNode;
				regionName = region.getAttribute("name");
				price = region.getAttribute("price");
				corp = region.getAttribute("corp");
				subRegionId = idArray.item(i).parentNode.parentNode.getAttribute("id");
				col = parseInt(colArray.item(i).firstChild.data, 10);
				squawk = idArray.item(i).getAttribute('squawk'); // WR
				owner_plot = idArray.item(i).getAttribute('owner_plot'); // JQ
/*
alert('JQ: plotId = ' + plotId);
alert('JQ: ownerId = ' + ownerId);
alert('JQ: url = ' + url);
alert('JQ: icon = ' + icon);
alert('JQ: region = ' + region);
alert('JQ: regionName = ' + regionName);
*/
				// create new div
				newDiv = document.createElement("div");
//alert('JQ: 2 i = ' + i);
				//declare initial style attributes, this may be added to if the plot is owned and has an icon uploaded for it
				divStyleText = "position:absolute; left:" + rowArray.item(i).firstChild.data + "px; top:" + col + "px; font-size:14px;";
				
				listId = "list_" + plotId + "_" + subRegionId + "_" + regionName + "_" + price;
				
				if(url)
				{
					listId = listId + "_url";
				}
				
				//check if new div had been previously selected before image was moved or zoomed
				if(document.getElementById(listId))
				{
					onList = true;
				}
				else
				{
					onList = false;
				}
				
				if(searchedPlotId == plotId)
				{
					searched = true;
				}
				else
				{
					searched = false;
					addSearchedPlot = false;
					showSearchedPlot = false;
				}
				
				if(switches.pressed)
				{
					i = numberPlots;
					break;
					cancelGrid = true;
				}
//alert('JQ: 3 i = ' + i);
				// if owned
				if(ownerId)
				{
					if (regionName) //KDB
					{ //KDB
						var newName = regionName.replace(/-/, " "); //KDB
						regionName = newName; //KDB
					//KDB regionName = regionName.replace(/-/, " ");
					} // KDB
					// if this owned plot is owned by the logged in user
					if(ownerId != userId)
					{
						//check if new div had been previously selected before image was moved or zoomed
						if (onList)
						{
							if(searched)
							{
								newDiv.className = "searchedSponsoredOnList";
								showSearchedPlot = true;
							}
							else
							{
								newDiv.className = "sponsoredOnList";
							}
						}
						else
						{
							newDiv.className = "sponsoredOffList";
						
							if(searched)
							{
								addSearchedPlot = true;
							}
						}
					}
					else
					{
						if(searched)
						{
							newDiv.className = "searchedUserPlot";
							showSearchedPlot = true;
						}
						else
						{
							newDiv.className = "userPlot";
						}
						
					}
					// check if icon has a value
					if(icon)
					{
						// if icon value is 0 then the icon has been uploaded by the user
						if(icon == 0)
						{
							if(switches.plotLevel)
							{
								// 48 x 48
								if(celeb)
								{
									///divStyleText += " background-image:url(/images/user/user_icons/"+plotId+".png);";
								}
								else
								{
//									divStyleText += " background-image:url(/images/user/user_icons/"+plotId+".jpg);";
								}
							}
							else if(switches.plotLevel2)
							{
								// 24 x 24
								if(celeb)
								{
									//divStyleText += " background-image:url(/scripts/php/timthumb.php?src=/images/user/user_icons/"+plotId+".png&w=24&zc=0);";
								}
								else
								{
									//divStyleText += " background-image:url(/scripts/php/timthumb.php?src=/images/user/user_icons/"+plotId+".jpg&w=24&zc=0);";
								}
							}
						}
						// otherwise the icon is a default one
						else
						{
							if(switches.plotLevel)
							{
								// 48 x 48
								//divStyleText += " background-image:url(/images/user/default_icons/"+icon+".png);";
							}
							else if(switches.plotLevel2)
							{
								// 24 x 24
								//divStyleText += " background-image:url(/scripts/php/timthumb.php?src=/images/user/default_icons/"+icon+".png&w=24&zc=0);";
							}
						}
					}
				}
				// if not owned 
				else
				{
					if (regionName) //KDB
					{ //KDB
//alert('JQ: 4 i = ' + i);
//alert('JQ: 5 regionName = ' + regionName);
						var newName = (regionName ? regionName.replace(/-/, " ") : ''); //KDB
						regionName = newName; //KDB
//					regionName = regionName.replace(/-/, " ");
//alert('JQ: 5 regionName = ' + regionName);
					} //KDB
					if(famousSquare)
					{
//alert('JQ: 6 famousSquare i = ' + i + plotId);
						if(famousSquare == 0)
						{
							if(switches.plotLevel)
							{
								// 48 x 48
								//divStyleText += " background-image:url(/images/famous_squares/icons/"+plotId+".png);";
							}
							else if(switches.plotLevel2)
							{
								// 24 x 24
								//divStyleText += " background-image:url(/scripts/php/timthumb.php?src=/images/famous_squares/icons/"+plotId+".png&w=24&zc=0);";
							}
						}
						else if(famousSquare == 1)
						{
							if(switches.plotLevel)
							{
								// 48 x 48
								//divStyleText += " background-image:url(/images/famous_squares/icons/default/goal.png);";
							}
							else if(switches.plotLevel2)
							{
								// 24 x 24
								//divStyleText += " background-image:url(/scripts/php/timthumb.php?src=/images/famous_squares/icons/default/goal.png&w=24&zc=0);";
							}
						}
						else if(famousSquare == 2)
						{
							if(switches.plotLevel)
							{
								// 48 x 48
								//divStyleText += " background-image:url(/images/famous_squares/icons/default/question-mark.png);";
							}
							else if(switches.plotLevel2)
							{
								// 24 x 24
								//divStyleText += " background-image:url(/scripts/php/timthumb.php?src=/images/famous_squares/icons/default/question-mark.png&w=24&zc=0);";
							}
						}
					}
					
					// check if this is a corporate block
					if(corp == 0)
					{
						if(famousSquare)
						{
							//check if new div had been previously selected before image was moved or zoomed
							if (onList)
							{
								if(searched)
								{
									newDiv.className = "searchedFamousSquareOnList";
									showSearchedPlot = true;
								}
								else
								{
									newDiv.className = "famousSquareOnList";
								}						
							}
							else
							{
								newDiv.className = "famousSquareOffList";
								if(searched)
								{
									addSearchedPlot = true;
								}						
							}
						}
						else
						{
							//check if new div had been previously selected before image was moved or zoomed
							if (onList)
							{
								if(searched)
								{
//									newDiv.className = "searchedOnList";
									showSearchedPlot = true;
								}
								else
								{
									newDiv.className = "onList";
								}						
							}
							else
							{
								newDiv.className = "offList";
								if(searched)
								{
									addSearchedPlot = true;
								}						
							}
						}
					}
					else
					{
						if(famousSquare)
						{
							if (onList)
							{
								if(searched)
								{
									newDiv.className = "searchedFamousSquareCorpOnList";
									showSearchedPlot = true;
								}
								else
								{
									newDiv.className = "famousSquareCorpOnList";
								}						
							}
							else
							{
								newDiv.className = "famousSquareCorpOffList";
								if(searched)
								{
									addSearchedPlot = true;
								}						
							}
						}
						else
						{
							if (onList)
							{
								if(searched)
								{
									newDiv.className = "searchedCorpOnList";
									showSearchedPlot = true;
								}
								else
								{
									newDiv.className = "corpOnList";
								}						
							}
							else
							{
								newDiv.className = "corpOffList";
								if(searched)
								{
									addSearchedPlot = true;
								}						
							}
						}
					}
				}

				// 06/06/10 WJR Check if div has been selected for Squawk
				
				if(squawk == 'y')
				{
					//newDiv.className = newDiv.className + ' squawk';
					newDiv.className =  'squawk'; //Deliberately overwriting any other classes, want 'squawk' to be the only one
				}
				
				
				if(switches.pressed)
				{
					i = numberPlots;
					break;
					cancelGrid = true;
				}

				if(owner_plot == 'y')
				{
					newDiv.className = newDiv.className + ' stb_owner_square';
				}
				
				if(switches.plotLevel)
				{
					if(seatCodeId == 0)
					{
						// pitch plot
						newDiv.className = seatCodeLookupTable[seatCodeId] + " " + newDiv.className;
					}
					else if(seatCodeId > 0)
					{
						// seat plot
						newDiv.className = seatCodeLookupTable[seatCodeId] + " " + newDiv.className;
						
						if(showSeatNumbers)
						{
							if ((plotId > 100000) && (plotId < 200000)) // Barclay End
								newDiv.innerHTML = plotId.substr(2);
								else if ((plotId > 200000) && (plotId < 300000)) // Jarrold Stand
								newDiv.innerHTML = plotId.substr(2,2) + '<br>' + plotId.substr(4,2);
							else if ((plotId > 300000) && (plotId < 400000)) // Norwich & Peterborough End
								newDiv.innerHTML = plotId.substr(2);
							else if ((plotId > 400000) && (plotId < 500000)) // City Stand
								newDiv.innerHTML = plotId.substr(2,2) + '<br>' + plotId.substr(4,2);
							else // Other
								newDiv.innerHTML = plotId;
						}
					}
				}
				else if(switches.plotLevel2)
				{
					if(seatCodeId == 0)
					{
						// pitch plot
						newDiv.className = seatCodeLookupTable2[seatCodeId] + " " + newDiv.className;
					}
					else if(seatCodeId > 0)
					{
						// seat plot
						newDiv.className = seatCodeLookupTable2[seatCodeId] + " " + newDiv.className;
						
						if(showSeatNumbers)
						{
							if ((plotId > 100000) && (plotId < 200000)) // Barclay End
								newDiv.innerHTML = plotId.substr(2);
							else if ((plotId > 200000) && (plotId < 300000)) // Jarrold Stand
								newDiv.innerHTML = plotId.substr(2,2) + '<br>' + plotId.substr(4,2);
							else if ((plotId > 300000) && (plotId < 400000)) // Norwich & Peterborough End
								newDiv.innerHTML = plotId.substr(2);
							else if ((plotId > 400000) && (plotId < 500000)) // City Stand
								newDiv.innerHTML = plotId.substr(2,2) + '<br>' + plotId.substr(4,2);
							else // Other
								newDiv.innerHTML = plotId;
						}
					}
				}

				// generate id for div
				//newDiv.id = "plot_" + plotId + "_" + subRegionId + "_" ;
				// currently sub region element is not needed
				newDiv.id = "plot_" + plotId + "_" + subRegionId + "_" + regionName + "_" + price;
				if(url)
				{
					newDiv.id = newDiv.id + "_url";
				}
				
				if(treasureHunt)
				{
					newDiv.id = newDiv.id + "_" + treasureHunt;
				}
				
				if(addSearchedPlot)
				{
					addSearchedPlotId = newDiv.id;
				}
				else if(showSearchedPlot)
				{
					showSearchedPlotId = newDiv.id;
					if(ownerId)
					{
						showSearchedPlotIdOwned = true;
					}
					else if(famousSquare)
					{
						showSearchedPlotIdFamous = true;
					}
				}

				// assign style information to plot				
				// for ie	
				newDiv.style.cssText = divStyleText;
				// other browsers
				newDiv.setAttribute("style", divStyleText);
				//newDiv.appendChild(document.createTextNode(plotId));
				cloned.appendChild(newDiv);
				if(switches.pressed)
				{
					i = numberPlots;
					break;
					cancelGrid = true;
					alert("cancelled");
				}
			}
			if(!cancelGrid)
			{
				// now we check if the x and y coordinates received from the XML file (created by createPlots.php) match the current x,y coordinates
				if((x == dim.bi.x && y == dim.bi.y) || searchedPlotId)
				{
					// if we have a match then copy the edited element (cloned) over the original element (original)
					// now replace original with modified clone
					original.parentNode.replaceChild(cloned, original);
					//switches.movable = true;
					//kdb resetTiles(imageViewer);
					//positionTileContainer(imageViewer);
				}
				else
				{
					/* 
						if we don't have a match then the imageviewer has been moved in the time it 
						has taken for createPlots.php to generate the XML and the javascript to process it
						therefore we need to re-run the process with the new coordinates
					*/
					//alert("re-adjusting x=" + x + ", y=" + y + ". bi.x=" + dim.bi.x + ",bi.y=" + dim.bi.y);
					createPlots(imageViewer);				
				}
			
				if(addSearchedPlotId)
				{
					// if the plot searched is not in the List then, call the selectPlot function to add it
				//	selectPlot(document.getElementById(addSearchedPlotId), true);
					//alert('add');
				}
				else if(showSearchedPlotId)
				{
					setRowHighlight(showSearchedPlotId, true); 
					
					if(showSearchedPlotIdOwned)
					{
						//alert('owned');
						plotInfo(showSearchedPlotId,false,true,true);
					}
					else if(showSearchedPlotIdFamous)
					{
						//alert('famous');
						plotInfo(showSearchedPlotId,false,false,false,false,true);
					}
					else
					{
						//alert('unowned');
						//plotInfo(showSearchedPlotId,false,true);
						setPEVImage(showSearchedPlotId);
					}
				}
				else
				{
					//alert('none');
				}
				
			}
		}
		else if(switches.plotViewLevel)
		{
//alert('JQ: switches.plotViewLevel');
			//alert('plot view level');
			// create clone of plots, the clone will be modified, then will replace the original, this will save on dom reflows
			var original = document.getElementById("plots");
			// (false) means it only clones the element and excludes its children
			var cloned = original.cloneNode(false);

			// create local variables
			var newDiv;
			var divStyleText;
			var subRegionId;
			var seatCodeId;
			var col;
			
			for (var i = 0;i < numberPlots; i++)
			{
				subRegionId = rowArray.item(i).parentNode.getAttribute("id");
				seatCodeId = rowArray.item(i).parentNode.getAttribute("sc");
				col = parseInt(colArray.item(i).firstChild.data, 10);
			
				// create new div
				newDiv = document.createElement("div");
				
				//declare initial style attributes
				// for other browsers
				divStyleText = "position:absolute; left:" + rowArray.item(i).firstChild.data + "px; top:" + col + "px; font-size:10px;";
				
				if(seatCodeId == 0)
				{
					// pitch plot
					newDiv.className = seatCodeLookupTable3[seatCodeId];
				}
				else if(seatCodeId > 0)
				{
					// seat plot
					newDiv.className = seatCodeLookupTable3[seatCodeId];
					
					if(showSeatNumbers)
					{
						if ((plotId > 100000) && (plotId < 200000)) // Barclay End
							newDiv.innerHTML = plotId.substr(2);
						else if ((plotId > 200000) && (plotId < 300000)) // Jarrold Stand
							newDiv.innerHTML = plotId.substr(2,2) + '<br>' + plotId.substr(4,2);
						else if ((plotId > 300000) && (plotId < 400000)) // Norwich & Peterborough End
							newDiv.innerHTML = plotId.substr(2);
						else if ((plotId > 400000) && (plotId < 500000)) // City Stand
							newDiv.innerHTML = plotId.substr(2,2) + '<br>' + plotId.substr(4,2);
						else // Other
							newDiv.innerHTML = plotId;
					}
				}
				
				// generate id for div
				newDiv.id = "plotview_" + subRegionId;
				
				// assign style information to plot
				// for ie	
				newDiv.style.cssText = divStyleText;
				// other browsers
				newDiv.setAttribute("style", divStyleText);
				//newDiv.appendChild(document.createTextNode(plotId));
				cloned.appendChild(newDiv);
				if(switches.pressed)
				{
					i = numberPlots;
					break;
					cancelGrid = true;
					alert("cancelled");
				}
			}
			if(!cancelGrid)
			{
				// now we check if the x and y coordinates received from the XML file (created by createPlots.php) match the current x,y coordinates
				if(x == dim.bi.x && y == dim.bi.y)
				{
					// if we have a match then copy the edited element (cloned) over the original element (original)
					// now replace original with modified clone
					original.parentNode.replaceChild(cloned, original);
					//switches.movable = true;
					//kdb resetTiles(imageViewer);
				}
				else
				{
					/* 
						if we don't have a match then the imageviewer has been moved in the time it 
						has taken for createPlots.php to generate the XML and the javascript to process it
						therefore we need to re-run the process with the new coordinates
					*/
					//alert("re-adjusting");
					//alert("BMJ: rerun");
					createPlots(imageViewer);				
				}
			}
		}
	}
// WR 020711 Dragging the squawk pitch is toggling the grid, well, toggling it off if it was on prior to the drag.
//Further drags than keep toggling it off. As this function is called when the pitch is dragged, it looks like it 
//is setting the grid back to it's default (which is off) each time.
	
// ---------- JQ 20101115 - grid is toggled off by default ----------
if ((document.getElementById('imageViewer').dimensions.zoomLevel == 6) || (document.getElementById('imageViewer').dimensions.zoomLevel == 7))
	{
		//el = document.getElementById('toggleGrid');
		//if(el.parentNode.className != 'hideGrid')//In other words, if the grid is on, leave it on
			//{
				
			//	el.parentNode.className = 'hideGrid';
			//	el.parentNode.title = 'hide grid';
				///toggleGrid(document.getElementById('toggleGrid'));
			//}
	}
// ---------- JQ 20101115 - grid is toggled off by default ----------
}

// remove any previous searched plots
function removeSearchedPlot()
{
	var plots = document.getElementById("plots");
	
	var searchedPlots = document.getElementsByClassName("searchedOnList", plots);
	if(searchedPlots.length > 0)
	{
		searchedPlots[0].className = "onList";
	}
	else
	{
		searchedPlots = document.getElementsByClassName("searchedOutBasket", links);
		if(searchedPlots.length > 0)
		{
			searchedPlots[0].className = "outBasket";
		}
		else
		{
			searchedPlots = document.getElementsByClassName("searchedSponsoredInBasket", links);
			if(searchedPlots.length > 0)
			{
				searchedPlots[0].className = "sponsoredInBasket";
			}
			else
			{
				searchedPlots = document.getElementsByClassName("searchedSponsored", links);
				if(searchedPlots.length > 0)
				{
					searchedPlots[0].className = "sponsored";
				}
				else
				{
					searchedPlots = document.getElementsByClassName("searchedUserPlot", links);
					if(searchedPlots.length > 0)
					{
						searchedPlots[0].className = "userPlot";
					}
					else
					{
						searchedPlots = document.getElementsByClassName("searchedForSale", links);
						if(searchedPlots.length > 0)
						{
							searchedPlots[0].className = "forSale";
						}
						else
						{
							searchedPlots = document.getElementsByClassName("searchedForSaleInBasket", links);
							if(searchedPlots.length > 0)
							{
								searchedPlots[0].className = "forSaleInBasket";
							}
						}
					}
				}
			}
		}
	}
}

function gridToggle(gridToggle)
{
	var imageViewer = document.getElementById('imageViewer');
	
	// at zoom level where grid is visible
	if(imageViewer.dimensions.zoomLevel >= (maxZoom - 1))
	{
		var iconToggle = document.getElementById('iconToggle');
		
		if(iconToggle.name == 'showIcons') // icons are currently hidden
		{
			if(gridToggle.name == 'hideGrid') // grid is currently shown
			{
				changeStyle('hideAll'); // change style to hide all
				gridToggle.name = 'showGrid';
				gridToggle.src = '/images/v1/show-grid-on.png';
				gridToggle.onmouseover = function () { this.src = '/images/v1/show-grid-on.png'; };
				gridToggle.onmouseout = function () { this.src = '/images/v1/show-grid-off.png'; };
			}
			else
			{
				changeStyle('justGrid'); // change style to just hide icons, but show grid
				gridToggle.name = 'hideGrid';
				gridToggle.src = '/images/v1/hide-grid-on.png';
				gridToggle.onmouseover = function () { this.src = '/images/v1/hide-grid-on.png'; };
				gridToggle.onmouseout = function () { this.src = '/images/v1/hide-grid-off.png'; };
			}
		}
		else // icons are currently shown
		{
			if(gridToggle.name == 'hideGrid') // grid is currently shown
			{
				changeStyle('justIcons'); // change style to just show icons, not grid
				gridToggle.name = 'showGrid';
				gridToggle.src = '/images/v1/show-grid-on.png';
				gridToggle.onmouseover = function () { this.src = '/images/v1/show-grid-on.png'; };
				gridToggle.onmouseout = function () { this.src = '/images/v1/show-grid-off.png'; };
			}
			else
			{
				changeStyle('showAll'); // change style to show both grid and icons
				gridToggle.name = 'hideGrid';
				gridToggle.src = '/images/v1/hide-grid-on.png';
				gridToggle.onmouseover = function () { this.src = '/images/v1/hide-grid-on.png'; };
				gridToggle.onmouseout = function () { this.src = '/images/v1/hide-grid-off.png'; };
			}
		}
	}
	else
	{
		alert("you need to be at 100% zoom for the grid to appear");
	}
}

function iconToggle(iconToggle)
{
	var imageViewer = document.getElementById('imageViewer');
	
	// at zoom level where grid is visible
	if(imageViewer.dimensions.zoomLevel >= (maxZoom - 1))
	{
		var gridToggle = document.getElementById('gridToggle');
		
		if(gridToggle.name == "showGrid") // grid is currently hidden
		{
			if(iconToggle.name == 'hideIcons') // icons are currently shown
			{
				changeStyle('hideAll'); // change style to hide all
				iconToggle.name = 'showIcons';
				iconToggle.src = '/images/v1/show-icons-on.png';
				iconToggle.onmouseover = function () { this.src = '/images/v1/show-icons-on.png'; };
				iconToggle.onmouseout = function () { this.src = '/images/v1/show-icons-off.png'; };
			}
			else
			{
				changeStyle('justIcons'); // change style to just show icons, not grid
				iconToggle.name = 'hideIcons';
				iconToggle.src = '/images/v1/hide-icons-on.png';
				iconToggle.onmouseover = function () { this.src = '/images/v1/hide-icons-on.png'; };
				iconToggle.onmouseout = function () { this.src = '/images/v1/hide-icons-off.png'; };
			}
		}
		else
		{
			if(iconToggle.name == 'hideIcons')
			{
				changeStyle('justGrid'); // change style to hide icons, but show grid
				iconToggle.name = 'showIcons';
				iconToggle.src = '/images/v1/show-icons-on.png';
				iconToggle.onmouseover = function () { this.src = '/images/v1/show-icons-on.png'; };
				iconToggle.onmouseout = function () { this.src = '/images/v1/show-icons-off.png'; };
			}
			else
			{
				changeStyle('showAll'); // change style to show both grid and icons
				iconToggle.name = 'hideIcons';
				iconToggle.src = '/images/v1/hide-icons-on.png';
				iconToggle.onmouseover = function () { this.src = '/images/v1/hide-icons-on.png'; };
				iconToggle.onmouseout = function () { this.src = '/images/v1/hide-icons-off.png'; };
			}
		}
	}
	else
	{
		alert("you need to be at 100% zoom for the owner plots to appear");
	}
}

function prepareViewer(imageViewer, tileDir, tileSize, app)
{
    for(var child = imageViewer.firstChild; child; child = child.nextSibling)
    {
        if(child.className == 'surface')
        {
            imageViewer.activeSurface = child;
            child.imageViewer = imageViewer;
        }
        else if(child.className == 'tileContainer')
        {
            imageViewer.tileContainer = child;
            child.imageViewer = imageViewer;
        } 
    }

	var zoomLevel;
	var initX;
	var initY;
	var size;
	var grid;
	var sponsors;
	var seats;
	var width;
	var height;
	var plotLevel = false;
	var plotLevel2 = false;
	var plotViewLevel = false;
	var defaultView = true;
	
	if(app)
	{
		// we are in the app
		// ignore viewer_position cookie
		
		initX = (getViewportDimensions('width') / 2) + app_startX; // set zoom level to the minimum
		initY =  (getViewportDimensions('height') / 2) + app_startY; // set zoom level to the minimum
		zoomLevel = app_minZoom - 1; // set zoom level to the minimum
		size = 'large'; // set imageViewer size original value 'app'
		grid = 'true';
		sponsors = 'true';
		seats = 'false';
		//alert(getViewportDimensions('width'));
		width = getViewportDimensions('width');
		//alert(getViewportDimensions('height'));
		height= getViewportDimensions('height');
	}
	else if(getCookie('viewer_position'))
	{
		var vpos = getCookie('viewer_position');
		vpos = vpos.split(",");
		
		// x , y , zoomlevel , size , grid , sponsors , seats
		
		// set position values from cookie
		initX = parseInt(vpos[0], 10);
		initY = parseInt(vpos[1], 10);
		zoomLevel = parseInt(vpos[2], 10);
		size = vpos[3];
		grid = vpos[4];
		sponsors = vpos[5];
		seats = vpos[6];
		
		if(zoomLevel == maxZoom)
		{
			plotLevel = true;
		}
		else if(zoomLevel == (maxZoom - 1))
		{
			plotLevel2 = true;
		}
		else if(zoomLevel == (maxZoom - 2))
		{
			plotViewLevel = true;
		}
		
		
					
		width = largeWidth;
		height = largeHeight;
		
		/* removed if statement as we are no longer using the small verison of the pitch
		if(size == 'small')
		{
			width = smallWidth;
			height = smallHeight;
		}
		else
		{
			// change class name of resize toggle
			//document.getElementById('resizeContainer').className = 'reduce';
			//document.getElementById('resizeContainer').title = 'reduce view';
			
			width = largeWidth;
			height = largeHeight;
			
			// hide elements in DOM
			document.getElementById('rightColumn').style.display = 'none';			
			document.getElementById('leftFooter').style.marginTop = "-66px";

			// perform all css resizes
			imageViewer.style.width = width+'px';
			imageViewer.style.height = height+'px';
			imageViewer.style.minWidth = width+'px';
			imageViewer.style.minHeight = height+'px';
			imageViewer.style.maxWidth = width+'px';
			imageViewer.style.maxHeight = height+'px';
			imageViewer.parentNode.style.width = width+'px';
			imageViewer.parentNode.style.height = height+'px';
		}
		*/		
		if(grid && sponsors)
		{
			if(grid == 'true')
			{
				if(sponsors == 'false')
				{
					document.getElementById('toggleSponsorsContainer').className = 'showSponsors';
					document.getElementById('toggleSponsorsContainer').title = 'show owners';
					changeStyle('justGrid');
				}
			}
			else // grid is off
			{
				document.getElementById('toggleGridContainer').className = 'showGrid';
				document.getElementById('toggleGridContainer').title = 'show grid';
				if(sponsors == 'true')
				{
					changeStyle('justIcons');
				}
				else
				{
					document.getElementById('toggleSponsorsContainer').className = 'showSponsors';
					document.getElementById('toggleSponsorsContainer').title = 'show owners';
					changeStyle('hideAll');
				}
			}
		}
		
		if(seats)
		{
			if(seats == 'true')
			{
				document.getElementById('toggleSeatsContainer').className = 'hideSeats';
				document.getElementById('toggleSeatsContainer').title = 'hide seats';
				tileDir = "/images/canopy_off";
			}
		}
		
		pageLevelRefresh(zoomLevel);
	}
	else
	{
	    initX = startX; // set zoom level to the minimum
		initY = startY; // set zoom level to the minimum
		zoomLevel = defaultZoom; // set zoom level to the minimum
		size = initSize; // set imageViewer size
		grid = defaultGridOn;
		sponsors = 'true';
		seats = 'false'; //WR 051011, changed from....true
		width = largeWidth;
		height = largeHeight;
	//	plotLevel2 = defaultView;
		pageLevelRefresh(zoomLevel);
		
	}
	
	var fullSize = tileSize * Math.pow(2, zoomLevel); // full pixel size of the image at this zoom level
    
    var top = 0;
    var left = 0;
    for(var node = imageViewer; node; node = node.offsetParent) {
        top += node.offsetTop;
        left += node.offsetLeft;
    }

    imageViewer.dimensions = {
    
    	 'iv':{ 
			'width': width, 
			'height': height,
			'size':size
    	 },
    		
    	 'bi':{ 
    		// initial imageViewer position
       		// defined as window-relative x,y coordinate of upper-left hand corner of complete image
			// usually negative. constant until zoomLevel changes
			'x': initX, 
			'y': initY,
		
			// Center points relative to the big image and the image viewer
			'cx': width / 2 / fullSize, 
			'cy': height / 2 / fullSize,
		
			'fullSize': fullSize
    	 },

         // location and height of each tile; they're always square
         'tileDir': tileDir, 
         'tileSize': tileSize,

         // zero or higher; big number == big image, lots of tiles
         'zoomLevel': zoomLevel,
         
         'maxZoom':maxZoom,
		 'minZoom':minZoom,
		 'startX':startX,
		 'startY':startY
         };

    imageViewer.start = {'x': 0, 'y': 0}; // this is reset each time that the mouse is pressed anew
    imageViewer.previous = {'x': 0, 'y': 0}; // records the previous x,y coordinates of the mouse
    
    imageViewer.switches = {
	
		//'movable' : true,
    	
    	'pressed' : false,
    	
    	'plotLevel' : plotLevel,

		'plotLevel2' : plotLevel2,
		
		'plotViewLevel' : plotViewLevel,
		
		'showGrid' : grid,
		
		'showSponsors' : sponsors,
		
		'showSeats' : seats
    	
    	};

    if(document.body.imageViewers == undefined) {
        document.body.imageViewers = [imageViewer];
        document.body.onmouseup = releaseViewer;
		document.body.onmousemove = moveViewer;

    } else {
        document.body.imageViewers.push(imageViewer);
    
    }

    prepareTiles(imageViewer);
}

function prepareTiles(imageViewer)
{
	resetTiles(imageViewer);
    imageViewer.activeSurface.onmousedown = pressViewer;
	imageViewer.activeSurface.ondblclick = doubleClickZoom;
    positionTileContainer(imageViewer, {'x': 0, 'y': 0}, true); // x, y should match imageViewer.start x, y
	createPlots(imageViewer);
}

function resetVisibleTiles()
{
	// Called to force a refresh of the tiles in the visible area of the pitch
	// when an MMS comes in to a tile that is visible. The idea is to speed up 
	// the appearance of this new image on the pitch
	
	var imageViewer = document.getElementById('imageViewer');
	var tiles = imageViewer.tiles;
	var numberRows = tiles[0].length;
	var numberCols = tiles.length;
	

	for(j=2; j<numberCols - 1;j++)
	{
		
		for(var r = 2; r < numberRows - 1; r += 1) 
		{
			var tile = tiles[j][r];			
			
			setTileImage(tile, false);
		
		}

	}
}

function positionTileContainer(imageViewer, mouse, prepare, newTop, newLeft)
{	
	var tiles = imageViewer.tiles;
	var dim = imageViewer.dimensions;
	var previous = imageViewer.previous;
	var divs = imageViewer.getElementsByTagName('div');
	var left = parseInt(divs[0].style.left);
	var top = parseInt(divs[0].style.top);
	var prevLeft = left;
	var prevTop = top;
	var numberRows = tiles[0].length;
	var numberCols = tiles.length;
	var i = 0;
	var j = 0;
	var distance;
	
	// move the tileContainer which contains all the tiles
	if(!prepare)
	{
		if(newTop || newLeft)
		{
			if(newTop)
			{
				top += newTop;
				imageViewer.previous.y += newTop;
				
			}
			else
			{
				left += newLeft;
				imageViewer.previous.x += newLeft;
			}
			mouse = imageViewer.previous;
		}
		else
		{
			left += (mouse.x - previous.x);
			top += (mouse.y - previous.y);
			
			// set previous coordinates to avoid ballooning of difference
			imageViewer.previous = mouse;
		}
		
		// divs[0] is the "tileContainer"
		divs[0].style.left = left + "px";
		divs[0].style.top = top + "px";
	}
	else
	{
		// set previous coordinates to avoid ballooning of difference
		imageViewer.previous = mouse;
	}
	
	// round ratio's to lowest integer, this will give which area each coordinate is , in the multiples of dim.tileSize
	var ratioLeft = Math.floor(left / dim.tileSize);
	var ratioTop = Math.floor(top / dim.tileSize);
	var ratioPrevLeft = Math.floor(prevLeft / dim.tileSize);
	var ratioPrevTop = Math.floor(prevTop / dim.tileSize);

	if(ratioLeft != ratioPrevLeft)
	{
		// if integer then the distance that the tileContainer has been moved is a multiple of the tileSize
		// we therefore need to shift the tiles either to the left or right
		if(ratioLeft > ratioPrevLeft)
		{
			//dragged right
			// check how far it has been dragged
			distance = ratioLeft - ratioPrevLeft;
			
			// make changes to tiles, loop through according to how far moved
			for(j=0; j< distance;j++)
			{
				// if dragged to the right more than a tilesize, then cycle through the last column of tiles and move them to the far left 
				for(var r = 0; r < numberRows; r += 1) 
				{
					var tile = tiles[tiles.length-1][r];
					// change the x coordinate by subtracting the tilesize multiplied by how many columns there are
					tile.x_tc -= dim.tileSize * numberCols;
					tile.c_bi -= numberCols;
					
					
					setTileImage(tile, false);
				
		    		tile.img.style.left = tile.x_tc+'px';
				}
	
				// now we must reset the order of the tile's in the tiles array
				var temp = tiles.pop();
				tiles.unshift(temp);
			}
		}
		else if(ratioLeft < ratioPrevLeft)
		{
			// dragged left
			// check how far it has been dragged
			distance = ratioPrevLeft - ratioLeft;
			
			// make changes to tiles, loop through according to how far moved
			for(j=0; j<distance;j++)
			{
				// if dragged to the left more than a tilesize, then cycle through the first column of tiles and move them to the far right 
				for(var r = 0; r < numberRows; r += 1) 
				{
					var tile = tiles[0][r];
					// change the x coordinate by adding the tilesize multiplied by how many columns there are
					tile.x_tc += dim.tileSize * numberCols;
					tile.c_bi += numberCols;
				
					setTileImage(tile, false);
				
		    		tile.img.style.left = tile.x_tc+'px';
				}
	
				// now we must reset the order of the tile's in the tiles array
				var temp = tiles.shift();
				tiles.push(temp);
			}
		}
		else
		{
			// moved up or down on the border line, so do nothing
		}
	}
	
	if(ratioTop != ratioPrevTop)
	{
		// if integer then the distance that the tileContainer has been moved is a multiple of the tileSize
		// we therefore need to shift the tiles either up or down
		if(ratioTop > ratioPrevTop)
		{
			//moved down
			// check how far it has been dragged
			distance = ratioTop - ratioPrevTop;
			
			// make changes to tiles, loop through according to how far moved
			for(j=0; j<distance;j++)
			{
				// if dragged down more than a tilesize, then cycle through the last row of each column in tiles and move them to the far top
				for(var c = 0; c < numberCols; c += 1) 
				{
					var tile = tiles[c][numberRows-1];
					// change the y coordinate by subtracting the tilesize multiplied by how many rows there are
					tile.y_tc -= dim.tileSize * numberRows;
					tile.r_bi -= numberRows;
					
				
					setTileImage(tile, false);
				
		    		tile.img.style.top = tile.y_tc+'px';
		    		
		    		// now we must reset the order of the tile's in the tiles array
					var temp = tiles[c].pop();
					tiles[c].unshift(temp);
				}
			}
		}
		else if(ratioTop < ratioPrevTop)
		{
			// moved up
			// check how far it has been dragged
			distance = ratioPrevTop - ratioTop;
			
			// make changes to tiles, loop through according to how far moved
			for(j=0; j<distance;j++)
			{
				// if dragged to the top more than a tilesize, then cycle through the first row of each column in tiles and move them to the bottom 
				for(var c = 0; c < numberCols; c += 1) 
				{
					var tile = tiles[c][0];
					// change the y coordinate by adding the tilesize multiplied by how many columns there are
					tile.y_tc += dim.tileSize * numberRows;
					tile.r_bi += numberRows;
					
					setTileImage(tile, false);
				
		    		tile.img.style.top = tile.y_tc+'px';
		    		
		    		// now we must reset the order of the tile's in the tiles array
					var temp = tiles[c].shift();
					tiles[c].push(temp);
				}
			}
		}
		else
		{
			// moved left or right on the border line, so do nothing
		}
	}
}

function setTileImage(tile, nullOverride)
{
	
    var dim = tile.imageViewer.dimensions;

	var cache_killer = new Date().valueOf();

    // build tile filename, using tile directory, zoom level, column and row
    var src = dim.tileDir+'/'+dim.zoomLevel+'-'+tile.c_bi+'-'+tile.r_bi+'.jpg?uwr=' + cache_killer;

    if (nullOverride || tile.c_bi < 0 || tile.r_bi <  0)
	{
		src = '/images/none.png';
	}
	
    tile.img.src = src;
	tile.img.onerror = function() { tileRetry(this); };
}

function tileRetry(tileImg)
{
	tileImg.onerror = function()
	{
		// replace with none.png (white)
    	tileImg.src = "/images/none.png";
	};
	tileImg.src = tileImg.src;
}

function localizeCoordinates(imageViewer, client)
{
    var local = {'x': client.x, 'y': client.y};

    for(var node = imageViewer; node; node = node.offsetParent) {
        local.x -= node.offsetLeft;
        local.y -= node.offsetTop;
    }
    
    return local;
}

function pressViewer(event)
{
// if createPlots() timer is running, cancel it
	if (timer)
	{
		window.clearTimeout(timer);
	}
	
    var imageViewer = this.imageViewer;
    var ev = getEvent(event);
	if(imageViewer.switches.pressed == false)
	{
		var mouse = localizeCoordinates(imageViewer, {'x': ev.clientX, 'y': ev.clientY});
    	imageViewer.switches.pressed = true;
    	imageViewer.tileContainer.style.cursor = imageViewer.activeSurface.style.cursor = 'pointer';
    	
    	imageViewer.previous = mouse;
    	imageViewer.start = mouse;
  
    }
}

function moveViewer(event)
{
	
	var imageViewer = document.getElementById('imageViewer');
	var switches = imageViewer.switches;
	//imageViewer.switches.movable == true
	if(switches.pressed == true)
	{
		var ev = getEvent(event);
		var mouse = localizeCoordinates(imageViewer, {'x': ev.clientX, 'y': ev.clientY});
	
		// check if at maximum zoom level after the zoom
		if(switches.plotLevel || switches.plotLevel2 || switches.plotViewLevel)
		{
			var distX = Math.abs(imageViewer.start.x - mouse.x);
			var distY = Math.abs(imageViewer.start.y - mouse.y);
			if(distX > 9 || distY > 9)
			{
				// if createPlots() timer is running, cancel it
				if (timer)
				{
					window.clearTimeout(timer);
				}
				if(document.getElementById("plots").firstChild)
				{
					clearInnerHTML(document.getElementById("plots"));
				}
				//switches.moving = true;
				positionTileContainer(imageViewer, mouse);
			}
		}
		else
		{
			positionTileContainer(imageViewer, mouse);
		}
	}
}

function releaseViewer(event)
{	
	
	var ev = getEvent(event);
    
    var imageViewer = document.getElementById("imageViewer");
    var mouse = localizeCoordinates(imageViewer, {'x': ev.clientX, 'y': ev.clientY});
    var dim = imageViewer.dimensions;
	var switches = imageViewer.switches;

	
    if(switches.pressed)
    {
    	imageViewer.activeSurface.onmousemove = null;
        imageViewer.tileContainer.style.cursor = imageViewer.activeSurface.style.cursor = 'pointer';
        switches.pressed = false;
		
		if(switches.plotLevel || switches.plotLevel2 || switches.plotViewLevel)
		{
			var distX = Math.abs(imageViewer.start.x - mouse.x);
			var distY = Math.abs(imageViewer.start.y - mouse.y);
			// checks if the surface has been dragged more than 9px in either direction
			if(distX > 9 || distY > 9)
			{
				dim.bi.x += (mouse.x - imageViewer.start.x);
	        	dim.bi.y += (mouse.y - imageViewer.start.y);
				//positionTileContainer(imageViewer, mouse, true);
				// call function using a timer, gives the user 0.75 seconds to re drag the map before grid is loaded
				timer = window.setTimeout('createPlots();',50);
			}
			else if(!document.getElementById('plots').firstChild)
			{
				// if the surface has been clicked before the grid has appeared on a previous drag then there will not be a grid, so need to create one here
				timer = window.setTimeout('createPlots();',200);
			}
		}
		else
		{
			if(dim.zoomLevel <= dim.minZoom + 1)
			{
				var distX = Math.abs(imageViewer.start.x - mouse.x);
				var distY = Math.abs(imageViewer.start.y - mouse.y);
				if(distX < 1 || distY < 1)
				{
					if(timer5) // if this timer is already running then cancel it as the user has double clicked
					{
						window.clearTimeout(timer5);
						timer5 = null;
					}
					else // if the timer is not yet running, then start it.
					{
						//alert('Might need to do something here');
						//alert('mouse x ' + mouse.x + ' mouse y ' + mouse.y);
						
						//This is a crude and imprecise way of determining if the mouse is 
						//over the pitch at fully zoomed out level. If the x and y coords
						//fall within a certain range, then they are over the pitch. It does
						//rely on the user not having dragged the pitch too far, but I don't think they 
						//should be allowed to do that anyway at this level
						
						if(dim.zoomLevel = 3)
						{
							if((mouse.x > 160) && (mouse.x < 512) && (mouse.y > 140) && (mouse.y < 370))
							{
								//Zoom in once
								$('#slider').slider('option', 'value', 50);
							}
						}
						//timer5 = window.setTimeout("clickHelp()",350); WR
					}
				}
			}
			dim.bi.x += (mouse.x - imageViewer.start.x);
	        dim.bi.y += (mouse.y - imageViewer.start.y);
		}
	}
}

// function called by the navigator arrows 
function slideViewer(imageViewer, direction)
{
	if(imageViewer.switches.plotLevel || imageViewer.switches.plotLevel2 || imageViewer.switches.plotViewLevel)
	{
		createPlots(imageViewer, true);
	}
	
	// distance in pixels the compass moves the map
	var paulsDistance = 192;
	var bi = imageViewer.dimensions.bi;
	
	// make changes to the dimension coordinates depending on which arrow is clicked
	switch(direction)
	{
		case 'up':
			positionTileContainer(imageViewer, undefined, false, paulsDistance);
        	bi.y += paulsDistance;
			break;
		case 'down':
			positionTileContainer(imageViewer, undefined, false, -paulsDistance);
			bi.y -= paulsDistance;
			break;
		case 'left':
			positionTileContainer(imageViewer, undefined, false, false, paulsDistance);
			bi.x += paulsDistance;
			break;
		case 'right':
			positionTileContainer(imageViewer, undefined, false, false, -paulsDistance);
			bi.x -= paulsDistance;
			break;
	}
	
	if(imageViewer.switches.plotLevel || imageViewer.switches.plotLevel2 || imageViewer.switches.plotViewLevel)
	{
		createPlots(imageViewer);
	}
}

function resizeViewer(imageViewer)
{
	
	// function to resize imageViewer	
	var dim = imageViewer.dimensions;
	
	// check if the imageViewer is currently small or large
	if(dim.iv.size == 'small')
	{
		// enlarge
		
		// change elements in DOM
//		document.getElementById('rightColumn').style.display = 'none';
//		document.getElementById('leftFooter').style.marginTop = "-66px";
		
		// perform all css resizes
		imageViewer.style.width = largeWidth+'px';
		imageViewer.style.height = largeHeight+'px';
		imageViewer.style.minWidth = largeWidth+'px';
		imageViewer.style.minHeight = largeHeight+'px';
		imageViewer.style.maxWidth = largeWidth+'px';
		imageViewer.style.maxHeight = largeHeight+'px';
		imageViewer.parentNode.style.width = largeWidth+'px';
		imageViewer.parentNode.style.height = largeHeight+'px';
		
		// perform all dom value changes
		dim.iv.width = largeWidth;
		dim.iv.height = largeHeight;
		dim.iv.size = 'large';
	}
	else
	{
		// shrink
		
		// change elements in DOM
//		document.getElementById('rightColumn').style.display = 'block';
//		document.getElementById('leftFooter').style.marginTop = "0px";
		
		// perform all css resizes
		imageViewer.style.width = smallWidth+'px';
		imageViewer.style.height = smallHeight+'px';
		imageViewer.style.minWidth = smallWidth+'px';
		imageViewer.style.minHeight = smallHeight+'px';
		imageViewer.style.maxWidth = smallWidth+'px';
		imageViewer.style.maxHeight = smallHeight+'px';
		imageViewer.parentNode.style.width = smallWidth+'px';
		imageViewer.parentNode.style.height = smallHeight+'px';
		
		// perform all dom value changes
		dim.iv.width = smallWidth;
		dim.iv.height = smallHeight;
		dim.iv.size = 'small';
	}
	saveViewerPosition();
	createPlots(imageViewer);
}

function clickHelp()
{
	alert("Please click on the +/- buttons above or use the slider to to zoom into the pitch and see the squares.");
	timer5 = null;
}

function doubleClickZoom(event)
{
	//var imageViewer = this.imageViewer;
    //var ev = getEvent(event);
	//zoomImageIn(imageViewer, localizeCoordinates(imageViewer, {'x': ev.clientX, 'y': ev.clientY}));
}

function zoomImageIn(imageViewer, mouse)
{
	// You can change the zoom increments here, just update the third arguement in the zoomimage function
	var dim = imageViewer.dimensions;
	if(dim.zoomLevel < dim.maxZoom)
	{
		if(dim.zoomLevel == (minZoom+1))
    	{
			zoomImage(imageViewer, mouse, 2);
		}
		else
		{
			zoomImage(imageViewer, mouse, 1);
		}
	}
}

function zoomImageOut(imageViewer, mouse)
{
	// You can change the zoom increments here, just update the third arguement in the zoomimage function
	var dim = imageViewer.dimensions;
	if(dim.zoomLevel >= dim.minZoom)
    {
		if(dim.zoomLevel == minZoom + 3)
    	{
			zoomImage(imageViewer, mouse, -2);
		}
		else
		{
			zoomImage(imageViewer, mouse, -1);
		}
	}
}

function debugInfo()
{
	document.getElementById("debug").innerHTML = "";
}

function zoomImage(imageViewer, mouse, direction, noPlotCreation)
{

	var dim = imageViewer.dimensions;
	var switches = imageViewer.switches;
	
	// Get Centre in proportion of big image dimensions
	// dim.x is offset of BI left edge from IV left edge so
	// by subtracting it from mid-point of IV, we get the BI
	// co-ord of the IV mid-point.
	// Then divide by BI size to get proportion.
	dim.bi.cx = ((dim.iv.width / 2) - dim.bi.x) / dim.bi.fullSize;
	dim.bi.cy = ((dim.iv.height / 2) - dim.bi.y) / dim.bi.fullSize;

	// to recalulate the fullsize of the big image we need to multiply it by 2 to the power of the direction
	// zooming "in" the direction is 1 (2^1 = 2) zooming "out" the direction is -1 (2^-1 = 0.5)
	// therefore either doubling or halfing the width and height of the big image
	dim.zoomLevel += direction;
	dim.bi.fullSize = dim.bi.fullSize * Math.pow(2, direction);

	// Reverse the earlier equation using new big image dimensions
	dim.bi.x = -((dim.bi.cx * dim.bi.fullSize) - (dim.iv.width / 2));
	dim.bi.y = -((dim.bi.cy * dim.bi.fullSize) - (dim.iv.height / 2));

	resetTiles(imageViewer);
	
	// check if at maximum zoom level after the zoom
	if(dim.zoomLevel == dim.maxZoom)
	{
		switches.plotLevel = true;
		switches.plotLevel2 = false;
		switches.plotViewLevel = false;
	}
	else
	{
		switches.plotLevel = false;
		
		if(dim.zoomLevel == (dim.maxZoom - 1))
		{
			switches.plotLevel2 = true;
			switches.plotViewLevel = false;
		}
		else
		{
			switches.plotLevel2 = false;
			
			if(dim.zoomLevel == (dim.maxZoom - 2))
			{
				switches.plotViewLevel = true;
			}
			else
			{
				switches.plotViewLevel = false;
			}
		}
	}
	if(!noPlotCreation)
	{
		createPlots(imageViewer);
	}
	pageLevelRefresh(dim.zoomLevel);
	
	//Save viewer position cookie. Doing it here, because it's now not called from 
	//pretty much anywhere else, bar togglegrid, which is odd and there is now a 
	//requirement for all pitches to show the same zoom level as the last one
	
	saveViewerPosition();
	
}

function resetTiles(imageViewer)
{
	var tileContainer = imageViewer.tileContainer;
    var dim = imageViewer.dimensions;
    var tileMargin = 2; 
    // we want a margin outside the imageViewer which is this many tiles deep,
    // i.e. if margin==2 then there are 2 extra columns outside the left of the
    // imageViewer, 2 extra columns outside the right of it,
    // and 2 extra rows outside the top and 2 extra rows outside the bottom.
    			
    // assign an empty array to tiles to clear it
	imageViewer.tiles = [];
	
	// reset tileContainer
	tileContainer.innerHTML = "";
	
	if(dim.bi.x > 0)
	{
		tileContainer.style.left = ((dim.bi.x % dim.tileSize) - dim.tileSize) + "px";
	}
	else
	{
		tileContainer.style.left = (dim.bi.x % dim.tileSize) + "px";
	}
	if(dim.bi.y > 0)
	{
		tileContainer.style.top = ((dim.bi.y % dim.tileSize) - dim.tileSize) + "px";
	}
	else
	{
		tileContainer.style.top = (dim.bi.y % dim.tileSize) + "px";
	}
    
    // work out how many tiles are needed to be displayed based on the size of the imageViewer and the size of the tile 
    var rows = Math.ceil(dim.iv.height / dim.tileSize) + (2 * tileMargin);
    var cols = Math.ceil(dim.iv.width / dim.tileSize) + (2 * tileMargin);
   
    for(var c = -tileMargin; c < cols-tileMargin; c += 1)
    {
        var tileCol = [];
    
        for(var r = -tileMargin; r < rows-tileMargin; r += 1) 
        {

            var tile = {'c_bi':0, 'r_bi':0, 'x_tc':0, 'y_tc':0, 'img': document.createElement('img'), 'imageViewer': imageViewer};

            tile.img.className = 'tile';
            // by removing the width and height we avoid skewing of any image tiles that are not this size
            //tile.img.style.width = dim.tileSize+'px';
            //tile.img.style.height = dim.tileSize+'px';
            //tile.img.id = "c" +c+ ",r"+r;
			
			// c is col number relative to dim (e.g. col 0 is first visible column).
			// tile.x is num pixels from the left edge of dim therefore based on c and pixel width of tiles
			// tile.c is col number relative to big image because the filename of the image file contains
			//	a column number (which is tile.c) that says what column number (in the big image) the file
			//  comes from; therefore we need to get the number of pixels from the left edge of the big
			//  image (which is tile.x - dim.x) and divide it by the width of the tile (and round it down
			//  to nearest integer).
			tile.x_tc = (c * dim.tileSize);
			tile.c_bi = Math.floor((tile.x_tc - dim.bi.x) / dim.tileSize);
            
			tile.y_tc = r * dim.tileSize;
			tile.r_bi = Math.floor((tile.y_tc - dim.bi.y) / dim.tileSize);
			
           	tile.img.style.top = tile.y_tc+'px';
           	tile.img.style.left = tile.x_tc+'px';

            setTileImage(tile, false);
            
            tileContainer.appendChild(tile.img);
            tileCol.push(tile);
        }
        
        imageViewer.tiles.push(tileCol);
    }
}
