var EPSG27700 = new OpenLayers.Projection("EPSG:27700");
var EPSG4326 = new OpenLayers.Projection("EPSG:4326");
var EPSG900913 = new OpenLayers.Projection("EPSG:900913");

var map; //complex object of type OpenLayers.Map
var markers = new OpenLayers.Layer.Markers("Markers");
var polylines_ks4 = new OpenLayers.Layer.Vector("KS4 Vectors");
var polylines_ks5 = new OpenLayers.Layer.Vector("KS5 Vectors");

var isIE6 = /msie|MSIE 6/.test(navigator.userAgent); //Urgh.

var oacGroupView = false;
var showNetworkOverlay = true;

var coverSchool = 0;
var userFilter = 0;

var decileKeys = [
      	["#006837", 1, "Lowest 10%", "Highest 10%"], 
      	["#1a9850", 2, "", ""], 
      	["#66bd63", 3, "", ""],
      	["#a6d96a", 4, "", ""],
      	["#d9ef8b", 5, "", ""],
      	["#fee08b", 6, "", ""],
      	["#fdae61", 7, "", ""],
      	["#f46d43", 8, "", ""],
      	["#d73027", 9, "", ""],
      	["#a50026", 10, "Highest 10%", "Lowest 10%"]
];

var singlegradKeys = [
	["#002673", 1, "", "> 250 (100 = average)"],
	["#003990", 2, "", "200-250"],
	["#004da8", 3, "", "150-200"],
	["#bebfc0", 4, "", "100-150 "],
	["#cfd0d1", 5, "", "50-100"],
	["#e0e1e2", 6, "", "< 50 (100 = average)"],
	["#666666", 7, "", "No data available"]
];

var polarKeys = [
	["#a50026", 1, "", "1 (Lowest 20%)"],
	["#f46d43", 2, "", "2"],
	["#fee08b", 3, "", "3"],
	["#a6d96a", 4, "", "4"],
	["#006837", 5, "", "5 (Highest 20%)"]
];

var oacSupergroupKeys = [
      	["800000", 1, "Blue Collar Communities"], 
      	["808080", 2, "City Living"], 
      	["bbdd88", 3, "Countryside"],
      	["ff0000", 4, "Prospering Suburbs"],
      	["0080ff", 5, "Constrained by Circumstances"],
      	["ffff00", 6, "Typical Traits"],
      	["ff8000", 7, "Multicultural"]
];

var oacGroupKeys = [
      	["800000", "800000", "ff", "1a", "#fff", "Terraced Blue Collar"], 
      	["800000", "802222", "dd", "1b", "#fff", "Younger Blue Collar"], 
      	["800000", "804444", "bb", "1c", "#fff", "Older Blue Collar"], 
      	["808080", "808080", "ff", "2a", "#fff", "Transient Communities"], 
      	["808080", "999999", "bb", "2b", "#fff", "Settled in the City"], 
      	["bbdd88", "bbdd88", "ff", "3a", "#666", "Village Life"],
      	["bbdd88", "ccee99", "bb", "3b", "#666", "Agricultural"],
      	["bbdd88", "ddffaa", "88", "3c", "#666", "Accessible Countryside"],
      	["ff0000", "ff0000", "ff", "4a", "#fff", "Prospering Younger Families"],
      	["ff0000", "ff2222", "dd", "4b", "#fff", "Prospering Older Families"],
      	["ff0000", "ff4444", "bb", "4c", "#fff", "Prospering Semis"],
      	["ff0000", "ff6666", "88", "4d", "#fff", "Thriving Suburbs"],
      	["0080ff", "0080ff", "ff", "5a", "#fff", "Senior Communities"],
      	["0080ff", "2090ff", "dd", "5b", "#fff", "Older Workers"],
      	["0080ff", "40a0ff", "bb", "5c", "#fff", "Public Housing"],
      	["ffff00", "ffff00", "ff", "6a", "#666", "Settled Households"],
      	["ffff00", "ffff22", "dd", "6b", "#666", "Least Divergent"],
      	["ffff00", "ffff44", "bb", "6c", "#666", "Young Families in Terraces"],
      	["ffff00", "ffff66", "88", "6d", "#666", "Aspiring Households"],
      	["ff8000", "ff8000", "ff", "7a", "#fff", "Asian Communities"],
      	["ff8000", "ff9022", "dd", "7b", "#fff", "Afro-Caribbean Communities"]
];

var oacGroups = []
var oacNames = []
var oacText = []

//Static set-up.
for (var i=0; i<oacGroupKeys.length; i++)
{
	oacGroups[i] = oacGroupKeys[i][3];
	oacNames[i] = oacGroupKeys[i][5];
	oacText[i] = oacGroupKeys[i][4];
}


OpenLayers.Util.onImageLoadError = function()
{
        if (this.src != null && this.src.match(/tiles1/))
        {
                this.src = this.src.replace("tiles1", "tiler1");
                //Replace tiler3 with tiler2 when tiler2 working.
        }
        else
        {
                this.src = "http://censusprofiler.org/images/404.png";
        }
};

OpenLayers.ImgPath = "http://js.mapbox.com/theme/dark/";

//Functions from hereon.

function dismiss()
{
	document.getElementById('error').style.display = 'none';
	document.getElementById('warn').style.display = 'none';
	document.getElementById('info').style.display = 'none';
	document.getElementById('splash').style.display = 'none';
	document.getElementById('select').style.display = 'none';
	document.getElementById('screen').style.display = 'none';
	document.getElementById('selectla').style.visibility = 'visible';
	if (coverSchool == 1)
	{
		coverSchoolPanel();			
		coverSchool = 0;
	}
	if (userFilter == 1)
	{
		var selectedId;
		for (var j = 0; j < document.getElementsByName("selectschool").length; j++)
		{
			if (document.getElementsByName("selectschool")[j].checked == true)
			{
				selectedId = document.getElementsByName("selectschool")[j].value;
			}
		}
		for (var i = 0; i < markersArr.length; i++)
		{
			if (markersArr[i]['id'] == selectedId)
			{	
				addAndHighlightSingleMarker(markersArr[i]);
			}
		}
	}
}

function addAndHighlightSingleMarker(marker)
{
	current_selected_marker = marker;
	markers.addMarker(current_selected_marker);
	current_filter_name = current_selected_marker['name'];
	document.getElementById('filtertext').innerHTML = "Currently showing <b>" + current_filter_name + "</b>.";
	highlightMarker(current_selected_marker);
      	map.setCenter(current_selected_marker.lonlat, 13);					
}

function highlightMarker(marker)
{
	current_selected_marker = marker;
	current_selected_marker.events.triggerEvent("mousedown", current_selected_marker.events[0]); 
}

function setKey(lookupTable, invert)
{
    var keyHTML = "";
    for (var i = 0; i < lookupTable.length; i++)
    {
	var j = lookupTable.length - (i+1);
	if (invert)
	{
		keyHTML += "<div class='keyitem' style='bottom: " + i*20 + "px;'><div class='keyitembox' style='background-color: " + lookupTable[i][0] + "'></div><div class='keyitemcaption'>" + lookupTable[i][2] + "</div></div>";
	}
	else
	{
		keyHTML += "<div class='keyitem' style='bottom: " + j*20 + "px;'><div class='keyitembox' style='background-color: " + lookupTable[i][0] + "'></div><div class='keyitemcaption'>" + lookupTable[i][3] + "</div></div>";
	}
    }
    document.getElementById("keypanel").innerHTML = keyHTML; // + "<br />The data is grouped by deciles, with equal numbers of areas in each decile.";
}

function setOacSupergroupKey()
{
	var keyHTML = "";
	for (var i=0; i<oacSupergroupKeys.length; i++)
	{
		var j = oacSupergroupKeys.length - (i+1);
		keyHTML += "<div class='keyitem' style='bottom: " + j*20 + "px;'><div class='keyitembox' style='background-color: #" + oacSupergroupKeys[i][0] + "'></div><div class='keyitemcaption'>" + oacSupergroupKeys[i][2] + "</div></div>";
	}
	document.getElementById("keypanel").innerHTML = keyHTML;
	oacGroupView = false;
}

function setOacGroupKey()
{
	var keyHTML = "";
	for (var i=0; i<oacGroupKeys.length; i++)
	{
		var j = oacGroupKeys.length - (i+1);
		keyHTML += "<div class='keyitem' style='bottom: " + j*20 + "px;'><div class='keyitembox' style='background-color: #" + oacGroupKeys[i][1] + "; color: " + oacGroupKeys[i][4] + ";'>" + oacGroupKeys[i][3] + "</div><div class='keyitemcaption'>" + oacGroupKeys[i][5] + "</div></div>";
	}
	document.getElementById("keypanel").innerHTML = keyHTML;
	//http://www.publicprofiler.org/publicprofiles/feedback.php?id=geodem&r=n&postcode=X
	oacGroupView = true;
}

function show(showDiv, hideDiv)
{
	document.getElementById(showDiv).style.display = 'block';
	document.getElementById(hideDiv).style.display = 'none';	
}

function showPanelSet(panelDiv, tabDiv)
{
	document.getElementById(tabDiv).className = 'tab_sel';
	document.getElementById(panelDiv).style.display = 'block';
}

function hidePanelSet(panelDiv, tabDiv)
{
	document.getElementById(tabDiv).className = 'tab';
	document.getElementById(panelDiv).style.display = 'none';
}

function coverSchoolPanel()
{
	document.getElementById("schoolpanel").style.display='none';
	document.getElementById("statspanel").style.display='none';
	document.getElementById("mappanel").style.left='6px';
	map.updateSize();
}

function changeLayer(layer, lookupTable, invert)
{
	map.setBaseLayer(layer); 

	if (map.baseLayer == layerMapnik)
	{
		layerBW.setVisibility(false);
		document.getElementById("cbBW").checked = false;
		document.getElementById("cbBW").disabled = true;
	}
	else
	{
		layerBW.setVisibility(showNetworkOverlay);
		document.getElementById("cbBW").checked = showNetworkOverlay;
		document.getElementById("cbBW").disabled = false;
	}
	
        if (lookupTable)
        {
		setKey(lookupTable, invert);
	}
        else
        {
		document.getElementById("keypanel").innerHTML = "";
	}
}

function getAjaxFunction()
{
  request = false;
  if (window.XMLHttpRequest) //IE7 & proper browsers
  {
    request = new XMLHttpRequest();
    if (request.overrideMimeType) //Proper browsers
    {
      //This is needed when calling php page that echos back XML, but should not be set if returning XML file directly 
      //- as if the file doesn't exist, HTML 404 response will cause Firefox error if set. //(N.B. Not necessarily a problem.)
      request.overrideMimeType('text/xml');
    }
    else //IE7
    {
	//request.setRequestHeader("Content-Type", "text/xml");
    }
  }
  else if (window.ActiveXObject) //IE6-
  {
    try { request = new ActiveXObject("Msxml2.XMLHTTP"); } 
    catch (e) { 
      try { request = new ActiveXObject("Microsoft.XMLHTTP"); } 
      catch (e) { }
    }   
  }
  if (!request) {
    alert("This web application requires an AJAX-compatable browser to operate.");
  }
  return request;
}

function getChoroplethLayer(name, attrib)
{
	return new OpenLayers.Layer.OSM("", "http://splintdev.geog.ucl.ac.uk/Tiles/" + name + "/${z}/${x}/${y}.png", {numZoomLevels: 14, transitionEffect: "resize", attribution: attrib});
}

//Initialise the 'map' object
function init() 
{
	initMessage();
	map = new OpenLayers.Map ("map", 
	{
    	controls:[
                new OpenLayers.Control.Navigation(),
                new OpenLayers.Control.PanZoomBar(),
                new OpenLayers.Control.Attribution(),
		new OpenLayers.Control.MouseDefaults(),
		new OpenLayers.Control.KeyboardDefaults()],
            maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
 	    restrictedExtent: new OpenLayers.Bounds(-35, 40, 30, 68).transform(EPSG4326, EPSG900913),
    	    numZoomLevels:14,
            maxResolution: 156543.0399,
            units: 'm',
            projection: EPSG900913,
            displayProjection: EPSG4326
    	} );
    
        layerMapnik = new OpenLayers.Layer.OSM(null, null, {transitionEffect: "resize", numZoomLevels: 14});
	layerBW = new OpenLayers.Layer.OSM("Chorogen Context", 
                "http://tiles1.censusprofiler.org/context/${z}/${x}/${y}.png",
		{transitionEffect: "none", isBaseLayer: false, attribution: "OSM"});

	lc_ks4_mplevl2em = getChoroplethLayer("choro_ks4_mplevl2em", "Data Crown Copyright DCSF");
	lc_ks4_mpfsm     = getChoroplethLayer("choro_ks4_mpfsm", "Data Crown Copyright DCSF");
	lc_ks5_mppoints  = getChoroplethLayer("choro_ks5_mppoints24", "Data Crown Copyright DCSF");
	lc_ks5_seng = getChoroplethLayer("seng", "Data Crown Copyright DCSF");
	lc_ks5_smat = getChoroplethLayer("smat", "Data Crown Copyright DCSF");
	lc_ks5_sphy = getChoroplethLayer("sphy", "Data Crown Copyright DCSF");
	lc_ks5_sche = getChoroplethLayer("sche", "Data Crown Copyright DCSF");
	lc_ks5_sbio = getChoroplethLayer("sbio", "Data Crown Copyright DCSF");
	lc_ks5_sgeo = getChoroplethLayer("sgeo", "Data Crown Copyright DCSF");
	lc_ks5_shis = getChoroplethLayer("shis", "Data Crown Copyright DCSF");
	lc_ks5_spli = getChoroplethLayer("spli", "Data Crown Copyright DCSF");
	lc_ks5_spsy = getChoroplethLayer("spsy", "Data Crown Copyright DCSF");
	lc_ks5_ssoc = getChoroplethLayer("ssoc", "Data Crown Copyright DCSF");
	lc_ks5_sbus = getChoroplethLayer("sbus", "Data Crown Copyright DCSF");
	lc_ks5_sfre = getChoroplethLayer("sfre", "Data Crown Copyright DCSF");
	lc_ks5_slaw = getChoroplethLayer("slaw", "Data Crown Copyright DCSF");
	lc_ks5_spe  = getChoroplethLayer("spe",  "Data Crown Copyright DCSF");
        
        layerIdaci = getChoroplethLayer("idaci24", "Data Crown Copyright CLG");
        layerPolar = getChoroplethLayer("polar24", "Data Crown Copyright HEFCE");

        layerOac = new OpenLayers.Layer.OSM("", 
		"http://tiler1.censusprofiler.org/oacsubg/${z}/${x}/${y}.png",  
		{transitionEffect: "resize", attribution: "Data from AreaClassification", numZoomLevels: 14
	});
                    
        baseLayers = [
	layerMapnik,
    	lc_ks4_mplevl2em,
	lc_ks4_mpfsm,
	lc_ks5_seng, lc_ks5_smat, lc_ks5_sphy, lc_ks5_sche, lc_ks5_sbio, lc_ks5_sgeo, lc_ks5_shis, lc_ks5_spli, lc_ks5_spsy, lc_ks5_ssoc, lc_ks5_sbus, lc_ks5_sfre, lc_ks5_slaw, lc_ks5_spe, 
	lc_ks5_mppoints,
	layerPolar, layerOac,
	layerIdaci];

	map.addLayers(baseLayers);
	map.addLayer(layerBW);
  
	map.events.register("zoomend", map, function(e)
	{
		if (map.baseLayer == layerOac)
		{
			if (map.getZoom() == 14 && !oacGroupView)
			{
				setOacGroupKey();
				oacGroupView = true;

			}
			else if (map.getZoom() != 14 && oacGroupView)
			{
				setOacSupergroupKey();
				oacGroupView = false;
			}

		}
	});

	//Set defaults on the form, clear out any existing values if on a reload.
	changeLayer(lc_ks4_mplevl2em, decileKeys, false);
	document.getElementById("rbchoro_ks4_mplevl2em").checked = true;

  	document.getElementById("selectlaIntro").value = ""; 
  	document.getElementById("selectpcIntro").value = ""; 
  	document.getElementById("selectla").value = ""; 
  	document.getElementById("selectpc").value = ""; 
  	document.getElementById("selectname").value = ""; 

	if (isIE6)
	{
		layerBW.setOpacity(0.3);
	}

        map.setCenter(new OpenLayers.LonLat(-3.5, 54.5).transform(EPSG4326, EPSG900913), 6);

	//These need to go at end so that IE6 doesn't through JS error.
	map.addLayers([polylines_ks4, polylines_ks5]);
	map.addLayer(markers); //Must go last, so it is the top vector layer and receives clicks.
}    
       

