var map

//DEFAULT ZOOM AND LATLNG
var all_centre,all_latlng,default_ltlng_bounds
var geocoder
var subset_bounds

//MAP DATA
var request //USED WHEN LOADING MAP DATA
var data_xml //STORES THE MAP DATA
var poly_arr=new Array() //STORES POLYGON OBJECTS BY PCT CODE, SO THEY DO HAVE OT BE RELOADED FROM SCRATCH
var poly_name_arr=new Array() //STORES THE PCT CODES CORRESPONDING TO OBJECTS IN poly_arr
var poly_zoom_arr=new Array() //STORES ZOOM SETTING FOR EACH POLYGON
var poly_colour_arr=new Array() //STORES COLOR SETTINGS FOR EACH POLYGON
var poly_arr_coords_lowres=new Array() //IF poly_arr IS RESET EVERYTIME NEW POLYGONS ARE DRAWN, USE THIS ARRAY TO STORE THE COORDINATE STRING ON WHICH THE POLYGON IS BASED
var poly_arr_coords_highres=new Array() //IF ONLY ONE POLYGON IS SHOWING, THE HIGHRES COORDINATES CAN BE USED AND THEIR COORDINATE STRING IS STORED HERE
var info_marker //POINTS TO THE MARKER THAT APPEARS WHEN A POLYGON IS CLICKED ON
var info_latlng //CONTAINF THE LATLNG OBJECT WITH THE COORDINATES OF A CLICK
var info_points_str="" //TEMPORARY FOR DEBUG, HOLDS THE NUMBE ROF COORDS WHEN SHOWING HIGH RES
var all_ltlng_bounds //WILL CONTAIN THE BOUNDARY FOR ALL THE POLYGONS DRAWN
var all_org_nodes //CONTAINS ALL THE PCT NODES WITH COORDINATES

var time_start
var time_string

var loading_message_overlay



function load_GMap() {
	
	get_file_types_xml()
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		
		
		if(map_size=="large"){
			map.enableDoubleClickZoom()
			map.enableContinuousZoom()
			//GEvent.addDomListener(document.getElementById("map"), "DOMMouseScroll", wheelZoom); // Firefox
			//GEvent.addDomListener(document.getElementById("map"), "mousewheel",     wheelZoom); // IE
		
			map.addControl(new GSmallMapControl());
		}else{
			//map.disableDragging()	
			map.enableDoubleClickZoom()
			map.enableContinuousZoom()
			map.addControl(new GSmallMapControl());
			
		
			//GEvent.addListener(map, "move", function() {
//			 clear_highlight_overlay()
//			 })
			
		}
//		map.addControl(new GMapTypeControl());
//		map.addControl(new GScaleControl());
//		map.addControl(new GOverviewMapControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 0)));
				
		//SET DEFAULT ZOOM LEVEL AND LATLNG
		var ltlng_bounds = new GLatLngBounds();
		var max_lat="55.74400865547504"
		var max_lon="2.0771813960624725"
		var min_lat="49.8641224779472"
		var min_lon="-6.41768355783408"
		
		var arr=[[max_lat,max_lon,0],[min_lat,min_lon,0]]
		for(var i=0;i<arr.length;i++){
			//ADJUST COORDINATES FROM EASTINGS AND NORTHINGS TO LAT/LNG
			//var os1w = new OSRef(parseFloat(arr[i][1]), parseFloat(arr[i][0]));
			//var ll1w = os1w.toLatLng(os1w);
			//ll1w.OSGB36ToWGS84();
			
			//eval("ll1w_arr=new Array"+ll1w.toString());
			
			var lat=eval("arr[i][0]")
			var lng=eval("arr[i][1]")
				
			//ADJUST THE BOUNDS TO INCLUDE THE NEW POINT
			var point = new GLatLng(lat,lng);
			arr[i][2]=point
			ltlng_bounds.extend(point);
		}
		
		default_ltlng_bounds=ltlng_bounds
		zoom_to_default()
				
		var point1=map.fromLatLngToDivPixel(arr[0][2])
		var point2=map.fromLatLngToDivPixel(arr[1][2])
		
		var w=point1.x-point2.x
		var h=point1.y-point2.y
		
		//UNCOMMENT THIS TO SHOW THE PIXEL SIZE OF THE ENGLAND BOUNDARY
		//alert([w,h])
		
		
		//SET MAP VIEW TO DEFAUL
		//map.setCenter(all_latlng, all_centre);


		//FIND CENTRE OF MAP DIV
		var x=map_width/2.0
		var y=map_height/2.0
		
		//res_message DIMENSIONS
		var mes_width=164
		var mes_height=37
		
		//POSITION OF RES_MESSAGE
		x=x-(mes_width/2.0)
		y=y-(mes_height/2.0)

		
	
		
		loading_message_overlay=new GScreenOverlay(pthstr+"maps/assets/loading_schemes.png",
        new GScreenPoint(x, y, 'pixels', 'pixels'),  // screenXY
        new GScreenPoint(0, 0),  // overlayXY
        new GScreenSize(mes_width, mes_height, 'pixels', 'pixels')  // size on screen
		);
		
		
		map.addOverlay(loading_message_overlay);
	
	 	geocoder = new GClientGeocoder();
		geocoder.setBaseCountryCode("uk")
		//LOAD SCHEMES
		load_data(pscp_ID)
		
	}
}

function zoom_to_default(){
	
	zoom_to_bounds(default_ltlng_bounds)

}

//MAP DATA
var request //USED WHEN LOADING MAP DATA
var data_xml //STORES THE MAP DATA

var all_ltlng_bounds //WILL CONTAIN THE BOUNDARY FOR ALL THE POLYGONS DRAWN
var all_scheme_nodes //CONTAINS ALL THE SCHEME NODES 

function start_check_time(){
	var d = new Date();	
	time_start=d.getTime()
	time_string=""
}
function check_time(str){
	var d = new Date();	
	var t=d.getTime()-time_start
	time_string=time_string+str+": "+t+"\n"
	time_start=d.getTime()
}
function load_data(pscp_ID){
	//LOAD SCHEMES FOR PSCP
	
	request = GXmlHttp.create();
	var dt=new Date()
	
	//window.open(pthstr+"library/get_basic_active_schemes_by_pscp.asp?pscp_ID="+pscp_ID+"&d="+dt.toString())

	
	//if(pscp_ID!=""){
//		request.open("GET", pthstr+"library/get_basic_active_schemes_by_pscp.asp?pscp_ID="+pscp_ID+"&d="+dt.toString(), true);
//	}else{
		if(is_debugging!="1"){
		request.open("GET", pthstr+"library/get_basic_active_schemes_by_criteria.asp?pscp_ID="+pscp_ID+"&d="+dt.toString(), true);
		}else{
		start_check_time()
		request.open("GET", pthstr+"library/get_basic_active_schemes_by_criteria_minimum_details.asp?pscp_ID="+pscp_ID+"&d="+dt.toString(), true);
		}
	//}
	request.onreadystatechange = function() { 
		if (request.readyState == 4) {
			
			if(browser.isIE){
				data_xml=new ActiveXObject('Microsoft.XMLDOM')
				data_xml.loadXML(request.responseText)				
			}else{				
				data_xml=new DOMParser().parseFromString(request.responseText, 'text/xml')				
			}
			galert("schemes")
			all_scheme_nodes=data_xml.selectNodes("//scheme")
			galert("all_scheme_nodes="+all_scheme_nodes.length)
			//all_scheme_nodes=data_xml.selectNodes("//scheme[@google_lat]")
			if(all_scheme_nodes.length>0){
				if(is_debugging=="1"){
					check_time("DATA LOADED")
				}
				draw_scheme_list()
			}
		}		
	;}
	request.send(null)
}
var file_types_xml
var file_types_xml_loaded=0
function get_file_types_xml(){
	request = GXmlHttp.create();
	var dt=new Date()
	

	
	request.open("GET", pthstr+"news/resources/get_file_types.asp", true);
	
	request.onreadystatechange = function() { 
		if (request.readyState == 4) {
			
			if(browser.isIE){
				file_types_xml=new ActiveXObject('Microsoft.XMLDOM')
				file_types_xml.loadXML(request.responseText)				
			}else{				
				file_types_xml=new DOMParser().parseFromString(request.responseText, 'text/xml')				
			}
			
			test_nodes=file_types_xml.selectNodes("//file")
			file_types_xml_loaded=1
		}		
	;}
	request.send(null)
}

function load_sha_boundary(sha_ID){
	//LOAD SCHEMES FOR PSCP
	
	request = GXmlHttp.create();
	var dt=new Date()
	
	//window.open(pthstr+"library/get_basic_active_schemes_by_pscp.asp?pscp_ID="+pscp_ID+"&d="+dt.toString())

	
	//if(pscp_ID!=""){
//		request.open("GET", pthstr+"library/get_basic_active_schemes_by_pscp.asp?pscp_ID="+pscp_ID+"&d="+dt.toString(), true);
//	}else{
		request.open("GET", pthstr+"library/get_sha_boundary.asp?sha_ID="+sha_ID+"&d="+dt.toString(), true);
	//}
	request.onreadystatechange = function() { 
		if (request.readyState == 4) {
			
			if(browser.isIE){
				var loader_xml=new ActiveXObject('Microsoft.XMLDOM')
				loader_xml.loadXML(request.responseText)				
			}else{				
				loader_xml=new DOMParser().parseFromString(request.responseText, 'text/xml')				
			}
			
			coord_nodes=loader_xml.selectNodes("//coords")
		
			if(coord_nodes.length>0){
				var use_nodes=data_xml.selectNodes("//shas[@sha_ID='"+coord_nodes[0].getAttribute("name")+"']")
				for(var i=0;i<coord_nodes.length;i++){
					use_nodes[0].appendChild(coord_nodes[i].cloneNode(1))
				}
				draw_sha_boundary(coord_nodes[0].getAttribute("name"))
			}
			
		}		
	;}
	request.send(null)
}

function draw_sha_boundary(sha_ID){
	
	var coord_nodes=data_xml.selectNodes("//shas[@sha_ID='"+sha_ID+"']/coords")
	if(coord_nodes.length==0){
		load_sha_boundary(sha_ID)
	}else{
		draw_poly(sha_ID,"H","#ee1c24","1","0")
		change_map_copyright(1)
	}
}

function change_map_copyright(tothis){
	if(map_size=="small"){
		if(typeof document.getElementById("map_copyright")!="undefined" && !!document.getElementById("map_copyright")){
			if(tothis==1){
				document.getElementById("map_copyright").style.display="block"	
			}else{
				document.getElementById("map_copyright").style.display="none"
			}
		}
	}	
}
var scheme_ob_list
var scheme_latlng_loaded_list
function draw_scheme_list(){
	
	all_ltlng_bounds = new GLatLngBounds();
	scheme_ob_list=new Array()
	scheme_latlng_loaded_list=new Array()
	if(is_debugging=="1"){
		check_time("START draw_scheme_list loop: "+all_scheme_nodes.length+" nodes")
	}
	for(var i=0;i<all_scheme_nodes.length;i++){
		scheme_ob_list.push(new scheme_class(all_scheme_nodes[i],scheme_ob_list.length))
		
		setTimeout("scheme_ob_list["+(scheme_ob_list.length-1)+"].get_latlng()",5)
		
		//var lat=""
//		var lng=""
//		var postcode=""
//		
//		if(typeof all_scheme_nodes[i].getAttribute("wgs84_latitude")!="undefined" && !!all_scheme_nodes[i].getAttribute("wgs84_latitude")){
//			lat=all_scheme_nodes[i].getAttribute("wgs84_latitude")	
//		}
//		if(typeof all_scheme_nodes[i].getAttribute("wgs84_longitude")!="undefined" && !!all_scheme_nodes[i].getAttribute("wgs84_longitude")){
//			lng=all_scheme_nodes[i].getAttribute("wgs84_longitude")	
//		}
//		if(typeof all_scheme_nodes[i].getAttribute("site_postcode")!="undefined" && !!all_scheme_nodes[i].getAttribute("site_postcode")){
//			postcode=all_scheme_nodes[i].getAttribute("site_postcode")	
//		}
//		
//		if(lat!="" && lng!=""){
//			
//			var point = new GLatLng(lat,lng);
//			draw_marker(point)
//		}else{
//			if(postcode!=""){
//				
//				 if (geocoder) {
//        			geocoder.getLatLng(postcode+",England",function(point){
//						 if (!!point) {	
//						 	draw_marker(point)
//						 }
//					})
//				 }
//			}
//		}
	}
	galert("scheme_ob_list.length="+scheme_ob_list.length)
	if(is_debugging=="1"){
		check_time("FINISHED draw_scheme_list loop")
	}
	setTimeout("check_latlng_loaded()",5)
	
}
var pixelgroups,exact_pixelgroups
var highlight_overlay_arr=new Array()
var marker_manager

function check_latlng_loaded(){
	pixelgroups=0
	exact_pixelgroups=0
	subset_bounds = new GLatLngBounds();
	
	
	if(scheme_latlng_loaded_list.length==scheme_ob_list.length){
		if(is_debugging=="1"){
			check_time("scheme_latlng_loaded_list.length==scheme_ob_list.length")
		}
		if(map_filter_sent==1){
			
			var by_ob=document.getElementById("map_filter_by")
			var value_ob=document.getElementById("map_filter_value")
			if(typeof by_ob!="undefined" && !!by_ob){
				change_map_filter(by_ob)
				change_map_filter(value_ob)
			}
			
		}
		map_filter_sent=0
		//marker_manager=new GMarkerManager(map)
		
		var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and @pixelgroup=-1 and @in_filter=1]")
		
		var safety=0
		var mnl=matching_nodes.length
		galert(browser.version)
		while(mnl>0 && safety<5000){
			safety++
			
			if(false){
				var pixelx=matching_nodes[0].getAttribute("pixelx")
				var pixely=matching_nodes[0].getAttribute("pixely")
			
				if(browser.isIE && browser.version<7){
					var matching_nodes2=data_xml.selectNodes("//scheme[@pixelgroup=-1 && @has_latlng=1 && @in_filter=1 && @pixelx='"+pixelx+"' && @pixely='"+pixely+"']")
				}else{
					var matching_nodes2=data_xml.selectNodes("//scheme[@pixelgroup=-1 and @has_latlng=1 and @in_filter=1 and @pixelx='"+pixelx+"' and @pixely='"+pixely+"']")
				}
				
				
			}else{
				var pixelleft=matching_nodes[0].getAttribute("pixelleft")
				var pixelright=matching_nodes[0].getAttribute("pixelright")
				var pixeltop=matching_nodes[0].getAttribute("pixeltop")
				var pixelbottom=matching_nodes[0].getAttribute("pixelbottom")	
				
				if(browser.isIE && browser.version<7){
					var matching_nodes2=data_xml.selectNodes("//scheme[@pixelgroup=-1 && @has_latlng=1 &&  @in_filter=1 && @pixelx>"+pixelleft+" && @pixelx<"+pixelright+" && @pixely>"+pixeltop+" && @pixely<"+pixelbottom+"]")
				}else{
					var matching_nodes2=data_xml.selectNodes("//scheme[@pixelgroup=-1 and @has_latlng=1 and  @in_filter=1 and @pixelx>"+pixelleft+" and @pixelx<"+pixelright+" and @pixely>"+pixeltop+" and @pixely<"+pixelbottom+"]")
				}
			}
			if(matching_nodes2.length>1){
				pixelgroups=pixelgroups+1
		
						
				for(var j=0;j<matching_nodes2.length;j++){
					
					matching_nodes2[j].setAttribute("pixelgroup",pixelgroups)
					scheme_ob_list[parseInt(matching_nodes2[j].getAttribute("listpos"))].pixelgroup=pixelgroups
				}
			}else{
				matching_nodes[0].setAttribute("pixelgroup",0)
				scheme_ob_list[parseInt(matching_nodes[0].getAttribute("listpos"))].pixelgroup=0
			}
			matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and @pixelgroup=-1 and @in_filter=1]")
			mnl=matching_nodes.length
		}
		if(is_debugging=="1"){
			check_time("finished coords grouping loop")
		}
		
		var delay_time=0
		for(var i=0;i<=pixelgroups;i++){
			var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and @pixelgroup="+i+" and @in_filter=1]")
			delay_time=delay_time+20
			if(i==0){
				
				for(j=0;j<matching_nodes.length;j++){
					var ob=scheme_ob_list[parseInt(matching_nodes[j].getAttribute("listpos"))]
					if(is_debugging!="1"){
						//ob.draw_marker(ob.latlng,icon_arr[0])
						ob.delay_draw_marker(ob.latlng,icon_arr[0],delay_time)
					}else{
						ob.delay_draw_marker(ob.latlng,icon_arr[0],delay_time)
					}
					subset_bounds.extend(ob.latlng)
				}
			}else{
				
				if(matching_nodes.length<10){
					var icn=icon_arr[matching_nodes.length-1]
				}else{
					
					var icn=icon_arr[9]
				}
				
				var ob=scheme_ob_list[parseInt(matching_nodes[0].getAttribute("listpos"))]
				if(is_debugging!="1"){
					//ob.draw_marker(ob.latlng,icn)
					ob.delay_draw_marker(ob.latlng,icn,delay_time)
				}else{
					ob.delay_draw_marker(ob.latlng,icn,delay_time)
				}
				
				subset_bounds.extend(ob.latlng)
				
				//MARKER MANAGER
				//marker_manager.addMarker(ob.marker, 1, map.getZoom()+4)
			
			//	for(j=0;j<matching_nodes.length;j++){
//					var ob=scheme_ob_list[parseInt(matching_nodes[j].getAttribute("listpos"))]
//					ob.store_marker(ob.latlng,icon_arr[0])
//					marker_manager.addMarker(ob.stored_marker, map.getZoom()+5)
//				}
			//END OF MARKER MANAGER
				
			}
			//marker_manager.refresh()

		}
		if(is_debugging=="1"){
			check_time("finished delay_draw loop")
		}
			loading_message_overlay.hide()
		if(map_filtered_by_sha==0){
			zoom_to_default()
		}else{
			if(document.getElementById("map_filter_value").options[document.getElementById("map_filter_value").selectedIndex].value=="Q99"){
				//DOH DIRECT
				zoom_to_bounds(subset_bounds)
			
			}else{
				draw_sha_boundary(document.getElementById("map_filter_value").options[document.getElementById("map_filter_value").selectedIndex].value)
			}
		}
		galert(time_string)

	}else{
		setTimeout("check_latlng_loaded()",20)
	}
}

function scheme_class(nd,listpos){
	var _me=this
	this.node=nd
	this.pos=listpos
	this.pixelgroup=-1
	this.in_filter=1
	
	
	this.node.setAttribute("pixelgroup",this.pixelgroup)
	this.node.setAttribute("listpos",this.pos)
	this.node.setAttribute("in_filter",this.in_filter)
	
	this.node.setAttribute("pixelx",-1)
	this.node.setAttribute("pixely",-1)
	this.node.setAttribute("pixelleft",-1)
	this.node.setAttribute("pixelright",-1)
	this.node.setAttribute("pixeltop",-1)
	this.node.setAttribute("pixelbottom",-1)
	
	if(typeof this.node.getAttribute("scheme_ID")=="undefined" || !this.node.getAttribute("scheme_ID")){
		this.node.setAttribute("scheme_ID",this.node.getAttribute("sc"))
		this.node.setAttribute("pscp_ID",this.node.getAttribute("ps"))
		this.node.setAttribute("sha_ID",this.node.getAttribute("sh"))
		this.node.setAttribute("project_stage_ID",this.node.getAttribute("st"))
		
		if(typeof this.node.getAttribute("ev")!="undefined" && !!this.node.getAttribute("ev")){
			this.node.setAttribute("estimated_value",this.node.getAttribute("ev"))
		}
		if(typeof this.node.getAttribute("sp")!="undefined" && !!this.node.getAttribute("sp")){
			this.node.setAttribute("site_postcode",this.node.getAttribute("sp"))
		}
		if(typeof this.node.getAttribute("lt")!="undefined" && !!this.node.getAttribute("lt")){
			this.node.setAttribute("wgs84_latitude",this.node.getAttribute("lt"))
			this.node.setAttribute("wgs84_longitude",this.node.getAttribute("ln"))
		}
		
	}
	
	var str=this.node.getAttribute("scheme_ID")
	while(str.length<4){
		str="0"+str	
	}
	this.scheme_code=str+this.node.getAttribute("original_trust_code")
	this.scheme_title=this.node.getAttribute("scheme_title")
	this.trust_name=this.node.getAttribute("trust_name")
	this.has_latlng=0
	this.latlng=0
	this.node.setAttribute("has_latlng",this.has_latlng)
	
	//GET PROJECT TYPE LINKS
	
	var test_nodes=this.node.selectNodes("./project_type_links")
	
	if(test_nodes.length==0){
		var link_nodes=data_xml.selectNodes("//project_type_links[@scheme_ID="+this.node.getAttribute("scheme_ID")+"]")
		
		if(link_nodes.length>0){
			for(var i=0;i<link_nodes.length;i++){
				this.node.appendChild(link_nodes[i])
			}
		}
	}
	
	//CASE STUDY ATTACHMENTS
	var attachment_nodes=data_xml.selectNodes("//news_item_attachments[@scheme_ID="+this.node.getAttribute("scheme_ID")+"]")
	
	if(attachment_nodes.length>0){
		for(var i=0;i<attachment_nodes.length;i++){
			this.node.appendChild(attachment_nodes[i])
		}
	}
	this.get_latlng=function(){
		var lat=""
		var lng=""
		var postcode=""
		
		if(typeof _me.node.getAttribute("wgs84_latitude")!="undefined" && !!_me.node.getAttribute("wgs84_latitude")){
			lat=_me.node.getAttribute("wgs84_latitude")	
		}
		if(typeof _me.node.getAttribute("wgs84_longitude")!="undefined" && !!_me.node.getAttribute("wgs84_longitude")){
			lng=_me.node.getAttribute("wgs84_longitude")	
		}
		if(lat=="" && lng==""){
			if(typeof _me.node.getAttribute("google_lat")!="undefined" && !!_me.node.getAttribute("google_lat")){
				lat=_me.node.getAttribute("google_lat")	
			}
			if(typeof _me.node.getAttribute("google_lng")!="undefined" && !!_me.node.getAttribute("google_lng")){
				lng=_me.node.getAttribute("google_lng")	
			}
		}
		if(typeof _me.node.getAttribute("site_postcode")!="undefined" && !!_me.node.getAttribute("site_postcode")){
			postcode=_me.node.getAttribute("site_postcode")	
		}
		
		if(lat!="" && lng!=""){
			
			var point = new GLatLng(lat,lng);
			_me.has_latlng=1
			_me.node.setAttribute("has_latlng",1)
			_me.latlng=point
			_me.calculate_bounds()
			scheme_latlng_loaded_list.push(1)
		}else{
			scheme_latlng_loaded_list.push(1)	
			//if(postcode!=""){
//				
//				 if (geocoder) {
//				
//        			geocoder.getLatLng(postcode+",England",function(point){
//						 if (!!point) {	
//						 	_me.has_latlng=1
//							_me.node.setAttribute("has_latlng",1)
//							_me.latlng=point
//						 	_me.calculate_bounds()
//						 }
//						 scheme_latlng_loaded_list.push(1)
//						
//					})
//				 }else{
//				 	scheme_latlng_loaded_list.push(1)
//				 }
//			}else{
//				scheme_latlng_loaded_list.push(1)	
//			}
		}
	}
	
	this.calculate_bounds=function(){
		var pixel_border=2
		_me.pixel_point=map.fromLatLngToDivPixel(_me.latlng)	
		var sw_point=new GPoint(_me.pixel_point.x-pixel_border, _me.pixel_point.y+pixel_border)
		var ne_point=new GPoint(_me.pixel_point.x+pixel_border, _me.pixel_point.y-pixel_border)
		_me.pixel_bounds=new GBounds(sw_point,ne_point)
		
		_me.node.setAttribute("pixelx",_me.pixel_point.x)
		_me.node.setAttribute("pixely",_me.pixel_point.y)
		
		_me.node.setAttribute("pixelleft",sw_point.x)
		_me.node.setAttribute("pixelright",ne_point.x)
		_me.node.setAttribute("pixeltop",ne_point.y)
		_me.node.setAttribute("pixelbottom",sw_point.y)
	}
	
	this.change_filter=function(tothis){
		_me.in_filter=tothis
		_me.pixelgroup=-1
		_me.node.setAttribute("in_filter",_me.in_filter)
		_me.node.setAttribute("pixelgroup",_me.pixelgroup)
	}
	
	this.delay_draw_marker=function(point,icn,delay_time){
		_me.delay_point=point
		_me.delay_icon=icn
		setTimeout(_me.call_draw_marker,delay_time)
	}
	this.call_draw_marker=function(){
		_me.draw_marker(_me.delay_point,_me.delay_icon)
	}
	this.draw_marker=function(point,icn){
				
		all_ltlng_bounds.extend(point)
		//zoom_to_bounds(all_ltlng_bounds,-1)
		//DRAW ICON
	
		var icon = new GIcon(icn)
		//icon.image = "http://maps.google.com/mapfiles/ms/micons/red-dot.png";
//		icon.iconSize = new GSize(32, 32);
//		icon.shadowSize=new GSize(56,32); 
//		icon.iconAnchor=new GPoint(16,32); 
//		icon.infoWindowAnchor=new GPoint(16,0); 
				
	
		//var markerOptions = { icon:icon,title:_me.trust_name+"\n"+_me.scheme_code+": "+_me.scheme_title};
		var markerOptions = { icon:icon};	  
		_me.marker = new GMarker(point,markerOptions);
		
		
				//  var marker = new GMarker(point);
			  GEvent.addListener(_me.marker, "click", function() {
				var txt=""
				if(_me.pixelgroup==0){
					txt+=_me.get_InfoWindowHTML()
				}else{
					var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and @pixelgroup="+_me.pixelgroup+" and @in_filter=1]")
					for(var i=0;i<matching_nodes.length;i++){
						txt+=scheme_ob_list[parseInt(matching_nodes[i].getAttribute("listpos"))].get_InfoWindowHTML()
						
					}
				}
				if(map_size=="large"){
					_me.marker.openInfoWindowHtml(txt);
				}else{
					clear_highlight_overlay()
					//var pixel_point=map.fromLatLngToDivPixel(_me.latlng)	
//					var y=map_height-pixel_point.y
//					
//					highlight_overlay_arr[0]=new GScreenOverlay(pthstr+"maps/assets/flag_highlight.png",
//					new GScreenPoint(pixel_point.x, y, 'pixels', 'pixels'),  // screenXY
//					new GScreenPoint(14, 0),  // overlayXY
//					new GScreenSize(29, 20, 'pixels', 'pixels')  // size on screen
//					);
					highlight_overlay_arr[0]=new highlighter(_me.latlng,pthstr+"maps/assets/flag_highlight.png",29,20);
					map.addOverlay(highlight_overlay_arr[0]);
					
					document.getElementById("map_info").innerHTML=txt
				}
				 })
	//GEvent.addListener(marker, "click", function() {
//				  window.open("http://maps.google.co.uk/maps?q="+address,"_blank","width=1000 height=750 toolbar=1 location=1 menubar=1 scrollbars=1 resizable=1 status=1")
//					})
		map.addOverlay(_me.marker);
				 // marker.openInfoWindowHtml(address);
	}
	
	this.store_marker=function(point,icn){
		var icon = new GIcon(icn)
		var markerOptions = { icon:icon};	  
		_me.stored_marker = new GMarker(point,markerOptions);
		GEvent.addListener(_me.stored_marker, "click", function() {
				var txt=""
				txt+=_me.get_InfoWindowHTML()
				_me.stored_marker.openInfoWindowHtml(txt);
		 })
	}
	this.get_InfoWindowHTML=function(){
		
		var pscp_icon=_me.node.getAttribute("pscp_name").toLowerCase()
		pscp_icon=pscp_icon.replace(/ /g,"_")
		pscp_icon=pscp_icon.replace(/'/g,"")
		var show_logo=1
		switch(pscp_icon){
			case "wates_group":
			case "taylor_woodrow":
			case "awaiting_appointment":
				show_logo=0
				break;
			case "acm":
				pscp_icon="costain"
				break;
			default:
				break;
		}
		var txt=""
		txt+='<div class="map_details">'
		txt+='<div class="map_scheme_title">'+_me.node.getAttribute("scheme_title")+'</div>'
		txt+='<div class="map_trust_name">'+_me.node.getAttribute("trust_name")+'</div>'
		if(show_logo==1){
			txt+='<div class="map_pscp_logo"><img src="'+pthstr+'assets/pscp_logos/mini/'+pscp_icon+'.jpg"/></div>'
		}
		txt+='<div class="map_value">&pound;'+_me.node.getAttribute("estimated_value")+'m</div>'
		
		var attachment_nodes=_me.node.selectNodes("./news_item_attachments")
		if(attachment_nodes.length>0){
			for(var i=0;i<attachment_nodes.length;i++){
				var attachment_title=""
				if(typeof attachment_nodes[i].getAttribute("attachment_title")!="undefined" && !!attachment_nodes[i].getAttribute("attachment_title")){
					attachment_title=attachment_nodes[i].getAttribute("attachment_title")
				}
				if(attachment_title==""){
					attachment_title=attachment_nodes[i].getAttribute("attachment_filename")
				}
				if(attachment_nodes.length==1){
					attachment_title="Case study"
				}
		
				var suff=attachment_nodes[i].getAttribute("attachment_filename").substr(attachment_nodes[i].getAttribute("attachment_filename").length-3,3)
			
				if(file_types_xml_loaded==1){
					var ftype_nodes=file_types_xml.selectNodes("//*[@suff='"+suff+"']")
					if(ftype_nodes.length>0){
						var file_description=ftype_nodes[0].getAttribute("name")
					}else{
						file_description=suff+" file"
					}
				}else{
					file_description=suff+" file"
				}
		
				//if(attachment_nodes.length>1){
					txt+='<div class="download_link_item">Download: <a href="'+pthstr+'news/downloads/'+attachment_nodes[i].getAttribute("news_item_ID")+'/'+attachment_nodes[i].getAttribute("attachment_filename")+'" target="_blank">'+attachment_title+'</a></div>'
					txt+='<div class="download_details">'+attachment_nodes[i].getAttribute("filesize_description")+'&nbsp;'+file_description+'</div>'
				//}else{
//					txt+='<div><a href="'+pthstr+"news/downloads/"+attachment_nodes[i].getAttribute("news_item_ID")+'/'+attachment_nodes[i].getAttribute("attachment_filename")+'" target="_blank">Download '+attachment_nodes[i].getAttribute("filesize_description")+' '+file_description+'...</a></div>'
//				}
			}
		}
		txt+='</div>'
		return txt;
	}
}

function clear_highlight_overlay(){
	if(highlight_overlay_arr.length>0){
		map.removeOverlay(highlight_overlay_arr[0])
	}
	highlight_overlay_arr=new Array()
	if(typeof document.getElementById("map_info")!="undefined" && !!document.getElementById("map_info")){
		document.getElementById("map_info").innerHTML=""	
	}
}


var upright_icon = new GIcon();
upright_icon.image=pthstr+"maps/assets/flag_centre.png"
upright_icon.shadow = pthstr+"maps/assets/flag_shadow.png"
upright_icon.iconSize = new GSize(29, 20);
upright_icon.shadowSize = new GSize(29, 20);
upright_icon.iconAnchor = new GPoint(14, 20);
upright_icon.infoWindowAnchor = new GPoint(8, 1);

var lean_left_icon = new GIcon();
lean_left_icon.image=pthstr+"maps/assets/flag_left.png"
//lean_left_icon.shadow = pthstr+"maps/assets/flag_shadow.png"
lean_left_icon.iconSize = new GSize(29, 20);
//lean_left_icon.shadowSize = new GSize(29, 20);
lean_left_icon.iconAnchor = new GPoint(14, 20);
lean_left_icon.infoWindowAnchor = new GPoint(8, 1);

var lean_right_icon = new GIcon();
lean_right_icon.image=pthstr+"maps/assets/flag_right.png"
//lean_left_icon.shadow = pthstr+"maps/assets/flag_shadow.png"
lean_right_icon.iconSize = new GSize(29, 20);
//lean_left_icon.shadowSize = new GSize(29, 20);
lean_right_icon.iconAnchor = new GPoint(14, 20);
lean_right_icon.infoWindowAnchor = new GPoint(8, 1);

var icon_arr=new Array()

for(var i=0;i<=10;i++){
	if(i!=1){
		istr=i.toString()
		if(istr.length==1){
			istr="0"+istr	
		}
		icon_arr[icon_arr.length]=new GIcon()
		icon_arr[icon_arr.length-1].image=pthstr+"maps/assets/flag_"+istr+".png"
		icon_arr[icon_arr.length-1].shadow = pthstr+"maps/assets/flag_shadow.png"
		icon_arr[icon_arr.length-1].iconSize = new GSize(29, 20);
		icon_arr[icon_arr.length-1].shadowSize = new GSize(29, 20);
		icon_arr[icon_arr.length-1].iconAnchor = new GPoint(14, 20);
		icon_arr[icon_arr.length-1].infoWindowAnchor = new GPoint(8, 1);
	}
}

function draw_marker(point,icn){
				
	all_ltlng_bounds.extend(point)
	zoom_to_bounds(all_ltlng_bounds)
	//DRAW ICON
	var icon = new GIcon(icn)
	//var icon = new GIcon(G_DEFAULT_ICON)
	//icon.image = "http://maps.google.com/mapfiles/ms/micons/red-dot.png";
//	icon.iconSize = new GSize(32, 32);
//	icon.shadowSize=new GSize(56,32); 
//	icon.iconAnchor=new GPoint(16,32); 
//	icon.infoWindowAnchor=new GPoint(16,0); 
			

	var markerOptions = { icon:icon };
			  
	var marker = new GMarker(point,markerOptions);
			  
            //  var marker = new GMarker(point);
		  GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(address);
			 })
//GEvent.addListener(marker, "click", function() {
//			  window.open("http://maps.google.co.uk/maps?q="+address,"_blank","width=1000 height=750 toolbar=1 location=1 menubar=1 scrollbars=1 resizable=1 status=1")
//				})
	map.addOverlay(marker);
             // marker.openInfoWindowHtml(address);
}
function draw_poly_list(){
	//LOOPS THROUGH THE PCTS WITH COORDINATES, DRAWING THEIR POLYGON AND ADJUSTING THE TOTAL BOUNDARY
	remove_poly()
	
	//all_ltlng_bounds WILL CONTAIN THE BOUNDARY FOR ALL THE POLYGONS DRAWN
	all_ltlng_bounds = new GLatLngBounds();
	var colour_pos=0
	var stroke_weight=0
	
	for(var i=0;i<all_org_nodes.length;i++){
		
		coord_nodes=all_org_nodes[i].selectNodes("./coords")
		
		if(coord_nodes.length>0){
			//MAKE SURE THE FIRST AND LAST COORDINATES ARE THE SAME
			if(coord_nodes[0].getAttribute("lat")!=coord_nodes[coord_nodes.length-1].getAttribute("lat") || coord_nodes[0].getAttribute("lon")!=coord_nodes[coord_nodes.length-1].getAttribute("lon")){
				
				all_org_nodes[i].appendChild(coord_nodes[0].cloneNode(1))
					
			}
		}
		
		
		if(colour_pos>=polygon_colour_arr.length){
			colour_pos=0
			
			//IF THE COLOURS ARE BEING REPEATED, TURN ON THE OUTLINE
			stroke_weight=1
		}
		var col=polygon_colour_arr[colour_pos]
		colour_pos=colour_pos+1
		
		draw_poly(all_org_nodes[i].getAttribute("node_ID"),all_org_nodes[i].getAttribute("HorL"),col,stroke_weight,1)
		
		//ADD AN ITEM TO THE LIST OF VISIBLE PCTS
		var dv=document.createElement("div")
		var cb=document.createElement("input")
		var lb=document.createElement("label")
		cb.type="checkbox"
		cb.style.border="2px solid "+col
		
		cb.value=all_org_nodes[i].getAttribute("node_ID")
		cb.name="pct_"+all_org_nodes[i].getAttribute("node_ID")
		cb.id="pct_"+all_org_nodes[i].getAttribute("node_ID")
		
		cb.onclick=function(){change_polygon_visibility(this)}
		dv.appendChild(cb)
		
		
		
		lb.id="pct_"+all_org_nodes[i].getAttribute("node_ID")+"_label"
		lb.htmlFor="pct_"+all_org_nodes[i].getAttribute("node_ID")
		lb.innerHTML=all_org_nodes[i].getAttribute("node_name")+" - "+all_org_nodes[i].getAttribute("node_ID")
		
		dv.appendChild(lb)
		//dv.style.backgroundColor=col
		document.getElementById("pct_list_holder").appendChild(dv)
		
		document.getElementById("pct_"+all_org_nodes[i].getAttribute("node_ID")).checked=1
		//GET THE BOUNDS FOR THIS POLY
		
		var bounds=poly_zoom_arr[all_org_nodes[i].getAttribute("node_ID")][1]
		
		//CONVERT TO LATLNG
		var latlng1=bounds.getSouthWest()
		var latlng2=bounds.getNorthEast()
	
		//EXTEND THE BOUNDARY
		all_ltlng_bounds.extend(latlng1);
		all_ltlng_bounds.extend(latlng2);
		
	}	
	zoom_to_bounds(all_ltlng_bounds)
	show_pct_info()
	
}

function show_pct_info(nid){
	
	clear_label_weight()
	
	if(typeof nid=="undefined" || !nid){
		if(all_org_nodes.length==1){
			nid=all_org_nodes[0].getAttribute("node_ID")
		}
	}
	if(typeof nid!="undefined" && !!nid){
		
		document.getElementById("pct_"+nid+"_label").style.fontWeight="bold"
		info_latlng=poly_zoom_arr[nid][0]	
		load_pct_details(nid,"table")
		
	}
}

function clear_label_weight(){
	if(typeof document.getElementById("pct_"+node_xml_ID+"_label")!="undefined" && !! document.getElementById("pct_"+node_xml_ID+"_label")){
		document.getElementById("pct_"+node_xml_ID+"_label").style.fontWeight=""
	}	
}
function zoom_to_bounds(boundsOb,zoomAdjust){
	//ZOOMS TO THE EXTENT OF A BOUNDARY PASSED IN boundsOb
	//GET CENTRE OF ALL POLYGON BOUNDARYS
	var bounds=boundsOb
	var center_lat = (bounds.getNorthEast().lat() +
	bounds.getSouthWest().lat()) / 2.0;
		
	var center_lng = (bounds.getNorthEast().lng() +
	bounds.getSouthWest().lng()) / 2.0;
	if(bounds.getNorthEast().lng() < bounds.getSouthWest().lng()){
		center_lng += 180;
	}
		  
	var center = new GLatLng(center_lat,center_lng)
	
	if(typeof zoomAdjust!="undefined" && !!zoomAdjust){
		var zoomval=map.getBoundsZoomLevel(bounds)+zoomAdjust
	}else{
		var zoomval=map.getBoundsZoomLevel(bounds)
	}
	
	//ZOOM TO BOUNDS IF REQUIRED
	map.setCenter(center,zoomval); 	
}

function adjust_bounds(node_ID){
	//ADJUSTS THE OVERALL BOUNDS AND RESETS THE ZOOM AND CENTRE AFTER POLYGON VISIBILITY HAS CHANGED
	all_ltlng_bounds = new GLatLngBounds();
	
	var check_count=0
	var check_found=0
	var checked_ID=""
	
	for(var i=0;i<all_org_nodes.length;i++){
		var ob=document.getElementById("pct_"+all_org_nodes[i].getAttribute("node_ID"))
		if(typeof ob!="undefined" && !!ob){
			check_found=1
			if(ob.checked==1){
				check_count++
				checked_ID=all_org_nodes[i].getAttribute("node_ID")
				//GET THE BOUNDS FOR THIS POLY
				var bounds=poly_zoom_arr[all_org_nodes[i].getAttribute("node_ID")][1]
				
				//CONVERT TO LATLNG
				var latlng1=bounds.getSouthWest()
				var latlng2=bounds.getNorthEast()
			
				//EXTEND THE BOUNDARY
				all_ltlng_bounds.extend(latlng1);
				all_ltlng_bounds.extend(latlng2);
			}
		}
	}
	
	
	if(check_found=1 && check_count==0){
		//IF ALL THE CHECKBOXES ARE TURNED OFF, TURN BACK ON THE LAST ONE
		var ob=document.getElementById("pct_"+node_ID)
		if(typeof ob!="undefined" && !!ob){
			ob.checked=1
			show_poly(node_ID)
		}
		
	}else{
		
		zoom_to_bounds(all_ltlng_bounds)
		
		
		if(check_count==1){
			//IF ONLY ONE IS TURNED ON, USE ITS HIGRES COORDS
			res_message_overlay.show()
			setTimeout("load_highres_node_data('"+checked_ID+"')",1000)
		}else{
			if(typeof node_ID=="undefined" || !node_ID){
				//IF NO NODE_ID HAS BEEN SENT, THE THE CHECKBOX MUST HAVE BEEN TURNED ON
				if(check_count==2){
					//IF TWO CHECKBOXES ARE TURN ON, THEN PREVIOUSLY ONLY ONE WAS TURNED ON, SO THAT POLYGON MUST BE HIGHRES
					if(swapped_poly_node_ID!=""){
						swap_poly(swapped_poly_node_ID,"L")
						//setTimeout("swap_poly('"+swapped_poly_node_ID+"','L')",1000)
					}
					//swapped_poly_node_ID=""
				}
			}
			
		}
		
	}
}

function draw_poly(new_node_ID,HorL,col,stroke_weight,show_all){
	//DRAWS A POLYGON
	node_ID=new_node_ID
	if(typeof poly_arr[node_ID]=="undefined" || !poly_arr[node_ID]){
		//IF THE POLYGON HASN'T PREVIOUSLY BEEN CREATED
		poly_colour_arr[node_ID]=col
		
		
		//CHECK TO SEE IF THIS RESOLUTION OF COORDINATES IS ALREADY LOADED
		var get_polystr=0
		if(HorL=="H"){
			if(typeof poly_arr_coords_highres[node_ID]=="undefined" || !poly_arr_coords_highres[node_ID]){
				get_polystr=1
			}
		}else{
			if(typeof poly_arr_coords_lowres[node_ID]=="undefined" || !poly_arr_coords_lowres[node_ID]){
				get_polystr=1
			}
		}
		
		if(get_polystr==1){
			//IF THIS RES OF COORDINATES AREN'T LOADED, GET THEM FROM THE MATCHING NODE
			
			active_node=data_xml.selectNodes("//shas[@sha_ID='"+node_ID+"']")[0]
				
			
		
		coord_nodes=active_node.selectNodes("./coords")
		
			//BUILD A STRING CONTINING ALL THE COORDINATES TO USE IN THE POLYGON
			polystr=""
			
			//CREATE A BOUNDS OBJECT TO HOLD THE MAXIMUM BOUNDARY OF THE POLYGON
			var ltlng_bounds = new GLatLngBounds();
			for(var i=0;i<coord_nodes.length;i++){
				
				//ADJUST COORDINATES FROM EASTINGS AND NORTHINGS TO LAT/LNG
				var os1w = new OSRef(parseFloat(coord_nodes[i].getAttribute("lon")), parseFloat(coord_nodes[i].getAttribute("lat")));
				var ll1w = os1w.toLatLng(os1w);
				ll1w.OSGB36ToWGS84();
				
				eval("ll1w_arr=new Array"+ll1w.toString());
				
				var lat=eval("ll1w_arr[0]")
				var lng=eval("ll1w_arr[1]")
					
				//ADJUST THE BOUNDS TO INCLUDE THE NEW POINT
				var point = new GLatLng(lat,lng);
				ltlng_bounds.extend(point);
				 
				polystr=polystr+"new GLatLng("+ll1w_arr[0]+", "+ll1w_arr[1]+"),"
			}
			if(HorL=="H"){
				poly_arr_coords_highres[node_ID]=polystr
			}else{
				poly_arr_coords_lowres[node_ID]=polystr
			}
			
		}else{
			if(HorL=="H"){
				polystr=poly_arr_coords_highres[node_ID]
			}else{
				polystr=poly_arr_coords_lowres[node_ID]
			}
		}
		
		if(polystr!=""){
			//IF POLYGON COORDINATES HAVE BEEN GENERATED
			polystr=polystr.substr(0,polystr.length-1)
			
			//CREATE POLYGON IN LIST //points, strokeColor?, strokeWeight?, strokeOpacity?, fillColor?, fillOpacity?, opts?)
			poly_arr[node_ID] = eval('new GPolygon([ '+polystr+'], "#FFFFFF", stroke_weight, 0.5, col, 0.5);')
			poly_name_arr[poly_name_arr.length]=node_ID
			
			//GIVE THE POLYGON A VALUE SO IT KNOWS WHAT IT'S PCT CODE IS
			poly_arr[node_ID].value=node_ID
			poly_arr[node_ID].coord_count=coord_nodes.length-1
			//poly_arr[node_ID].total_points=active_node.getAttribute("total_points")
			//ADD A CLICK EVENT
			//GEvent.addListener( poly_arr[node_ID] , "click", function(latlng) {
//			
//			 	 if (latlng) {
//
//					info_latlng=latlng
//					
//					//TEMPORARY DEBUG STRING TO SHOW THE TOTAL POINTS OF THE ITEM CLICKED ON AND THE NUMBER DISPLAYED
//					if(HorL=="H"){
//						info_points_str=this.coord_count+"/"+this.total_points
//					}else{
//						info_points_str=""
//					}
//					html="Loading..."
//					
//					//SHOW INFOWINDOW
//					//map.openInfoWindowHtml(info_latlng,html);
//					
//					//load_pct_details(this.value,"table")
//					show_pct_info(this.value)
//					
//					
//				}
//			});
			
			
			
			//DRAW POLYGON ON MAP
			map.addOverlay(poly_arr[node_ID]);
			  
			if(typeof poly_zoom_arr[node_ID]=="undefined" || !poly_zoom_arr[node_ID]){
				//GET CENTRE OF POLYGON BOUNDARY
				bounds=ltlng_bounds
				var center_lat = (bounds.getNorthEast().lat() +
				bounds.getSouthWest().lat()) / 2.0;
					
				var center_lng = (bounds.getNorthEast().lng() +
				bounds.getSouthWest().lng()) / 2.0;
				if(bounds.getNorthEast().lng() < bounds.getSouthWest().lng()){
					center_lng += 180;
				}
					  
				var center = new GLatLng(center_lat,center_lng)
				
				//ADD CENTRE AND BOUNDS TO LIST
				poly_zoom_arr[node_ID]=[center,bounds]
			}
					
			if(show_all==0){
			
				//IF NOT SHOWING ALL UK, ZOOM TO EXTREMITES OF BOUNDS
				map.setCenter(poly_zoom_arr[node_ID][0], map.getBoundsZoomLevel(poly_zoom_arr[node_ID][1])); 
			}
		}
	}else{
		//POLYGON HAS BEEN PREVIOUSLY CREATED SO IT IS IN THE LIST
		 map.addOverlay(poly_arr[node_ID]);
		
		if(show_all==0){
			//ZOOM TO BOUNDS IF REQUIRED
				
			map.setCenter(poly_zoom_arr[node_ID][0], map.getBoundsZoomLevel(poly_zoom_arr[node_ID][1])); 
	 	}
	}
}

function show_poly(node_ID){
	//SHOWS A POLYGON THAT HAS PREVIOUSLY BEEN HIDDEN	
	if (navigator.vendor != "Apple Computer, Inc." && navigator.vendor != "KDE") { // WebCore/KHTML
		poly_arr[node_ID].show()
	}else{
		map.addOverlay(poly_arr[node_ID]);
	}
	adjust_bounds()
}

function hide_poly(node_ID){
	//HIDES A POLYGON
	if (navigator.vendor != "Apple Computer, Inc." && navigator.vendor != "KDE") { // WebCore/KHTML
		poly_arr[node_ID].hide()
	}else{
		map.removeOverlay(poly_arr[node_ID]);
	}
	
	adjust_bounds(node_ID)
}

function remove_poly(){
	//REMOVES ALL POLYGONS FROM THE MAP
	
	//MAKE SURE THE INFOWINDOW AND MARKER ARE REMOVED
	map.closeInfoWindow()
	document.getElementById("chart_holder").innerHTML=""
	clear_label_weight()
	//CLEAR THE PCT LIST DIV
	document.getElementById("pct_list_holder").innerHTML=""
					
	if(poly_name_arr.length>0){
		for(var i=0;i<poly_name_arr.length;i++){
			if(typeof poly_arr[poly_name_arr[i]]!="undefined" && !!poly_arr[poly_name_arr[i]]){
				map.removeOverlay(poly_arr[poly_name_arr[i]]);
			}
		}
	}
	
	poly_arr=new Array()
	poly_name_arr=new Array()
	poly_colour_arr=new Array()
	
	
	zoom_to_default()
}

function change_polygon_visibility(thisone){
	map.closeInfoWindow()
	document.getElementById("chart_holder").innerHTML=""
	clear_label_weight()
	if(thisone.checked==1){
		show_poly(thisone.value)
	}else{
		hide_poly(thisone.value)
	}
}

//NODE STRUCTURE SCRIPTS
var node_xml_loader //USED WHEN LOADING SHA AND PCT XML
var node_xml_ID //USED TO STORE THE NODE ID OF THE XML BEING LOADE WHEN LOADING NODE DETAILS
var sha_xml //STORES THE SHA AND PCT XML

function load_node_list(sha_ID){
	//LOAD SHAS OR THE PCTS BELONGING TO AND SHA	
	var load_path=""
	
	if(typeof sha_ID=="undefined" || !sha_ID){
		//LOAD SHAS
		load_path=pthstr+"map/get_node_list.asp"
	}else{
		var pct_nodes=sha_xml.selectNodes("//node[@parent_ID='"+sha_ID+"']")
		if(pct_nodes.length==0){
			//LOAD PCTS FOR SELECTED SHAS
			load_path=pthstr+"map/get_node_list.asp?sha_ID="+sha_ID
		}else{
			//THE PCTS FOR THE SHA HAVE ALREADY BEEN LOADED
			draw_node_dropdown(sha_ID)
		}
	}

	if(load_path!=""){
		//XML NEEDS TO BE LOADED
		node_xml_loader = GXmlHttp.create();
		node_xml_loader.open("GET", load_path, true);
		node_xml_loader.onreadystatechange = function() { 
		
			if (node_xml_loader.readyState == 4) {
				
				if(browser.isIE){
					loaded_xml=new ActiveXObject('Microsoft.XMLDOM')
					loaded_xml.loadXML(node_xml_loader.responseText)
				}else{
					loaded_xml=new DOMParser().parseFromString(node_xml_loader.responseText, 'text/xml')
				}
				
				
				//GET THE ROOT NODE OF THE RETURNED XML TO SEE IF IT'S SHA OR PCT
				var rootnodes=loaded_xml.selectNodes("//data")
				
				if(rootnodes.length>0){
					if(rootnodes[0].getAttribute("level")=="3"){
						//SHAS
						sha_xml=loaded_xml
						draw_node_dropdown("")
					}else{
						//PCTS
						var sha_nodes=sha_xml.selectNodes("//node[@node_ID='"+rootnodes[0].getAttribute("sha_ID")+"']")
						if(sha_nodes.length>0){
							for(var i=0;i<rootnodes[0].childNodes.length;i++){
								//ADD THE PCT NODES TO THEIR PARENT SHA SO THEY DON'T NEED TO BE LOADED AGAIN
								sha_nodes[0].appendChild(rootnodes[0].childNodes[i].cloneNode(1))
							}
						}
						draw_node_dropdown(rootnodes[0].getAttribute("sha_ID"))
					}
				}
				
			}
		}
		node_xml_loader.send(null)
	}
}


var pct_details_tab_arr
var pct_details_text_arr
var pct_details_html_arr

function load_pct_details(pct_ID,load_type){
	//LOAD SHAS OR THE PCTS BELONGING TO AND SHA	
	node_xml_ID=pct_ID
	
	var load_path=""
	
	var dt=new Date()

	//LOAD PCTS DETAILS
	switch(load_type){
		
		case "tabs":
			load_path=pthstr+"content/output_tabs.asp"
		break;
		case "table":
			load_path=pthstr+"content/map_output_table.asp?node_ID="+pct_ID+"&d="+dt.toString()
		break;
		case "chart":
			load_path=pthstr+"content/results_output.asp?chart_type=mini&chart_bar_width="+chart_bar_width+"&node_ID="+pct_ID+"&d="+dt.toString()
		break;
	}
	

	if(load_path!=""){
		//XML NEEDS TO BE LOADED
		node_xml_loader = GXmlHttp.create();
		node_xml_loader.open("GET", load_path, true);
		
		switch(load_type){
		
			case "tabs":
			node_xml_loader.onreadystatechange = function() { 
			
				if (node_xml_loader.readyState == 4) {
					
					var str=node_xml_loader.responseText
					
					if(str!=""){
						pos1=str.indexOf("<body")
						pos2=str.indexOf(">",pos1)+1
						pos3=str.lastIndexOf("</body")
						
						str=str.substr(pos2,pos3-pos2)
						
						if(info_points_str!=""){
						//   str=str+"<br>"+info_points_str
						}
						
				
						pct_details_text_arr=new Array()
						pct_details_text_arr.push(str)
						
						
						//map.openInfoWindowHtml(info_latlng,str);
						
						load_pct_details(node_xml_ID,"table")
					
					}
					
				}
			}
			break;
			case "table":
		
			node_xml_loader.onreadystatechange = function() { 
			
				if (node_xml_loader.readyState == 4) {
					
					var str=node_xml_loader.responseText
					
					if(str!=""){
						pos1=str.indexOf("<body")
						pos2=str.indexOf(">",pos1)+1
						pos3=str.lastIndexOf("</body")
						
						str=str.substr(pos2,pos3-pos2)
						
						if(info_points_str!=""){
						//   str=str+"<br>"+info_points_str
						}
						
						pct_details_text_arr=new Array()
						pct_details_text_arr.push('<div id="info_tab_'+(pct_details_text_arr.length+1)+'_holder" style="display:none;">'+str+'</div>')
						
						////IF USING GOOGLE TABS
//						pct_details_tab_arr=new Array()
//						pct_details_tab_arr.push(new GInfoWindowTab("table", str))
						
						
						//map.openInfoWindowHtml(info_latlng,str);
						
						load_pct_details(node_xml_ID,"chart")
					
					}
					
				}
			}
			break;
			case "chart":
			node_xml_loader.onreadystatechange = function() { 
			
				if (node_xml_loader.readyState == 4) {
					
					var str=node_xml_loader.responseText
					
					if(str!=""){
						pos1=str.indexOf("<body")
						pos2=str.indexOf(">",pos1)+1
						pos3=str.lastIndexOf("</body")
						
						str=str.substr(pos2,pos3-pos2)
						
						pct_details_text_arr.push('<div id="info_tab_'+(pct_details_text_arr.length+1)+'_holder" style="display:none;">'+str+'</div>')
						
//						//IF USING GOOGLE TABS
//						pct_details_tab_arr.push(new GInfoWindowTab("chart", str))
//						map.openInfoWindowTabsHtml(info_latlng,pct_details_tab_arr);

						
						var tab_str=""
						tab_str+='<div id="tabbed_menu">'
						tab_str+='<div id="info_tab_1" class="tab_menu_item" onClick="change_info_tab(this.id)" style="cursor:pointer">Table</div>'
						tab_str+='<div id="info_tab_2" class="tab_menu_item" onClick="change_info_tab(this.id)" style="cursor:pointer">Chart</div>'
						tab_str+='</div>'
						
						var tab_str1=""
						tab_str1+='<div id="tabbed_menu">'
						tab_str1+='<div id="info_tab_1" class="tab_menu_item selected" onClick="change_info_tab(this.id)">Table</div>'
						tab_str1+='<div id="info_tab_2" class="tab_menu_item" onClick="change_info_tab(this.id)">Chart</div>'
						tab_str1+='</div>'
						
						
						
						var tab_str2=""
						tab_str2+='<div id="tabbed_menu">'
						tab_str2+='<div id="info_tab_1" class="tab_menu_item" onClick="change_info_tab(this.id)">Table</div>'
						tab_str2+='<div id="info_tab_2" class="tab_menu_item selected" onClick="change_info_tab(this.id)">Chart</div>'
						tab_str2+='</div>'
						
						
						pct_details_html_arr=new Array()
						pct_details_html_arr["info_tab_1"]=tab_str1+pct_details_text_arr[0]	
						pct_details_html_arr["info_tab_2"]=tab_str2+pct_details_text_arr[1]	
						
						
						str=""
						for(var i=0;i<pct_details_text_arr.length;i++){
							str+=pct_details_text_arr[i]		
						}
						
						map.openInfoWindowHtml(info_latlng,tab_str+str);
						
						if(selected_info_tab==""){
							change_info_tab("info_tab_1")
						}else{
							change_info_tab(selected_info_tab)
						}
					}
					
				}
			}
			break;
		}
		node_xml_loader.send(null)
	}
}
var selected_info_tab=""
function change_info_tab(thisdivid){
	
	close_info_tab()
	selected_info_tab=thisdivid
	
	//map.openInfoWindowHtml(info_latlng,pct_details_html_arr[selected_info_tab]);
	
	document.getElementById(selected_info_tab).className="tab_menu_item selected"
	ob2=document.getElementById(selected_info_tab+"_holder")
	if(typeof ob2!="undefined" && !!ob2){
		ob2.style.display="block"
	}
}
function close_info_tab(){
	if(selected_info_tab!=""){
		ob1=document.getElementById(selected_info_tab)
		ob2=document.getElementById(selected_info_tab+"_holder")
		if(typeof ob1!="undefined" && !!ob1){
			ob1.className="tab_menu_item"	
		}
		if(typeof ob2!="undefined" && !!ob2){
			ob2.style.display="none"
		}
	}
}

function draw_node_dropdown(sha_ID){
	//DRAW SHA AND PCT DROP DOWN MENUS
	var sha_ob =document.getElementById("sha_selector")
	var pct_ob =document.getElementById("pct_selector")
	
	if(sha_ID==""){
		//DRAW SHA MENU
		var sha_nodes=sha_xml.selectNodes("//data/node")
		
		if(sha_nodes.length>0){
			var ob =sha_ob
			if(typeof ob!="undefined" && !!ob){
				if(ob.options.length>1){
					ob.options.length=1
				}
				for(var i=0;i<sha_nodes.length;i++){
					var nm=sha_nodes[i].getAttribute("node_name")
					if(nm.indexOf(" STRATEGIC HEALTH AUTHORITY")!=-1){
						nm=nm.substr(0,nm.indexOf(" STRATEGIC HEALTH AUTHORITY"))+" SHA" +" - "+sha_nodes[i].getAttribute("node_ID")
					}
					
					ob.options[ob.options.length]=new Option(nm,sha_nodes[i].getAttribute("node_ID"))
				}
			}
		}
	}else{
		//DRAW PCT MENU
		var pct_nodes=sha_xml.selectNodes("//node[@parent_ID='"+sha_ID+"']")
		
		if(pct_nodes.length>0){
			var ob =pct_ob
			if(typeof ob!="undefined" && !!ob){
				if(ob.options.length>1){
					ob.options.length=1
				}
				for(var i=0;i<pct_nodes.length;i++){
					var nm=pct_nodes[i].getAttribute("node_name")
					if(pct_nodes[i].getAttribute("node_ID")!="all"){
						nm=nm+" - "+pct_nodes[i].getAttribute("node_ID")
					}else{
						nm="All PCTs"	
					}
					ob.options[ob.options.length]=new Option(nm,pct_nodes[i].getAttribute("node_ID"))
				}
				pct_ob.className="popup_input"
				pct_ob.disabled=0
			}
		}
	}
}

//FILTER SCRIPTS
var map_filtered_by_sha=0
function change_map_filter(thisone){
	map_filtered_by_sha=0
	
	var large_map_link_ob=document.getElementById("large_map_link")
	if(typeof large_map_link_ob!="undefined" && !!large_map_link_ob){
		var targ=large_map_link_ob.href.toString()
		if(targ.indexOf("&filter_by")!=-1){
			var targ_arr=targ.split("&filter_by")
			large_map_link_ob.href=targ_arr[0]
		}
	}
	
	if(thisone.name=="map_filter_by"){
		var value_ob=document.getElementById("map_filter_value")
		value_ob.options.length=0
		var name_str="name"
		var value_str="value"
		
		if(thisone.selectedIndex==0){

			value_ob.style.display="none"
			map.clearOverlays()
			zoom_to_default()
			clear_highlight_overlay()
			change_map_copyright(0)
			
			for(var i=0;i<scheme_ob_list.length;i++){
				scheme_ob_list[i].change_filter(1)
				
				
			}
			check_latlng_loaded()
		}else{
			
			zoom_to_default()
				
			map.clearOverlays()
			clear_highlight_overlay()
			change_map_copyright(0)
		
			for(var i=0;i<scheme_ob_list.length;i++){
				scheme_ob_list[i].change_filter(0)
				
				
			}
			value_ob.style.display="inline"
			switch(thisone.options[thisone.selectedIndex].value){
				case "sha":
					var use_nodes=data_xml.selectNodes("//shas")
					if(use_nodes.length>0){
						if(typeof use_nodes[0].getAttribute("name")=="undefined" || !use_nodes[0].getAttribute("name")){
							name_str="sha_name"	
							value_str="sha_ID"	
						}
					}
				break;
				case "project_stage":
					if(browser.isIE && browser.version<7){
						var use_nodes=data_xml.selectNodes("//project_stages_lookup[@project_stage_ID>8 || @project_stage_ID=-1]")
					}else{
						var use_nodes=data_xml.selectNodes("//project_stages_lookup[@project_stage_ID>8 or @project_stage_ID=-1]")	
					}
					if(use_nodes.length>0){
						if(use_nodes[use_nodes.length-1].getAttribute("project_stage_ID")!="-1"){
							var newnode=use_nodes[0].cloneNode(1)
							newnode.setAttribute("project_stage_ID","-1")
							newnode.setAttribute("project_stage_name","Projects in the earlier stages")
						
							//use_nodes[0].parentNode.insertBefore(newnode,use_nodes[0])
							use_nodes[0].parentNode.appendChild(newnode)
						}
						if(browser.isIE && browser.version<7){
							var use_nodes=data_xml.selectNodes("//project_stages_lookup[@project_stage_ID>8 || @project_stage_ID=-1]")
						}else{
							var use_nodes=data_xml.selectNodes("//project_stages_lookup[@project_stage_ID>8 or @project_stage_ID=-1]")
						}
						if(typeof use_nodes[0].getAttribute("name")=="undefined" || !use_nodes[0].getAttribute("name")){
							name_str="project_stage_name"	
							value_str="project_stage_ID"	
						}
					}
				break;
				case "project_type":
					var use_nodes=data_xml.selectNodes("//project_type_lookup")
					if(use_nodes.length>0){
						if(typeof use_nodes[0].getAttribute("name")=="undefined" || !use_nodes[0].getAttribute("name")){
							name_str="project_type"	
							value_str="project_type_ID"	
						}
					}
				break;
				case "value":
					var use_nodes=data_xml.selectNodes("//value_range")
					if(use_nodes.length==0){
						var root_node=data_xml.selectSingleNode("//data")
						var name_arr=new Array("£1-5m", "£5-15m","£15-25m","£25m and above")
						var val_arr=new Array("1-5", "5-15","15-25","25+")
						var range_arr=new Array([1,5], [5,15],[15,25],[25,"+"])
						for(var i=0;i<name_arr.length;i++){
							var newnode=data_xml.createElement("value_range")
							newnode.setAttribute("name",name_arr[i])
							newnode.setAttribute("value",val_arr[i])
							newnode.setAttribute("start_range",range_arr[i][0])
							newnode.setAttribute("end_range",range_arr[i][1])
							root_node.appendChild(newnode)
						}
						var use_nodes=data_xml.selectNodes("//value_range")
					}
				break;
			}
			if(use_nodes.length>0){
				
				value_ob[value_ob.length]=new Option("Select...", "")
				
				for(var i=0;i<use_nodes.length;i++){
					if(name_str!="name"){
						use_nodes[i].setAttribute("name",use_nodes[i].getAttribute(name_str))
						use_nodes[i].setAttribute("value",use_nodes[i].getAttribute(value_str))
					}
					var nm=use_nodes[i].getAttribute("name")
					switch(thisone.options[thisone.selectedIndex].value){
					
						case "project_stage":
							if(nm.indexOf(" - ")>-1){
								var pos1=nm.indexOf(" - ")+3
								nm=nm.substr(pos1,nm.length-pos1)
							}
						break;
					}
					value_ob[value_ob.length]=new Option(nm, use_nodes[i].getAttribute("value"))
					if(value_ob[value_ob.length-1].innerHTML.indexOf("£")!=-1){
						//REPLACE £ WITH &pound;
						var str=value_ob[value_ob.length-1].innerHTML
						str="&pound;"+str.substr(1,str.length)
						value_ob[value_ob.length-1].innerHTML=str
					}
					if(map_filter_sent==1){
						if(map_filter_sent_value==use_nodes[i].getAttribute("value")){
							value_ob[value_ob.length-1].selected=1
						}
					}
				}
			}
			
		}
	}else{
		
		//FILTER VALUE SELECTED
		var by_ob=document.getElementById("map_filter_by")
		if(thisone.selectedIndex==0){
			
			map.clearOverlays()
			clear_highlight_overlay()
			change_map_copyright(0)
			for(var i=0;i<scheme_ob_list.length;i++){
				scheme_ob_list[i].change_filter(0)
				
				
			}
		}else{
			map.clearOverlays()
			clear_highlight_overlay()
			change_map_copyright(0)
			for(var i=0;i<scheme_ob_list.length;i++){
				scheme_ob_list[i].change_filter(0)
			}
			switch(by_ob.options[by_ob.selectedIndex].value){
				case "sha":
					if(browser.isIE && browser.version<7){
						var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 && @sha_ID='"+thisone.options[thisone.selectedIndex].value+"']")
					}else{
						var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and @sha_ID='"+thisone.options[thisone.selectedIndex].value+"']")
					}
					if(matching_nodes.length>0){
						map_filtered_by_sha=1	
						
					}
					
				break;
				case "project_stage":
					if(thisone.options[thisone.selectedIndex].value=="-1"){
						if(browser.isIE && browser.version<7){
							var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 && @project_stage_ID<8]")
						}else{
							var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and @project_stage_ID<8]")
						}
					}else{
						if(browser.isIE && browser.version<7){
							var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 && @project_stage_ID="+thisone.options[thisone.selectedIndex].value+"]")
						}else{
							var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and @project_stage_ID="+thisone.options[thisone.selectedIndex].value+"]")
						}
					}
				break;
				case "project_type":
					if(browser.isIE && browser.version<7){
						var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 && ./project_type_links[@project_type_ID="+thisone.options[thisone.selectedIndex].value+"]]")
					}else{
						var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and ./project_type_links[@project_type_ID="+thisone.options[thisone.selectedIndex].value+"]]")
					}
				break;
				case "value":
					var value_node=data_xml.selectSingleNode("//value_range[@value='"+thisone.options[thisone.selectedIndex].value+"']")
					var start_range=value_node.getAttribute("start_range")
					var end_range=value_node.getAttribute("end_range")
					if(end_range=="+"){
						if(browser.isIE && browser.version<7){
							var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 && @estimated_value>="+start_range+"]")
						}else{
							var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and @estimated_value>="+start_range+"]")
						}
					}else{
						if(browser.isIE && browser.version<7){
							var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 && @estimated_value>="+start_range+" && @estimated_value<"+end_range+"]")
						}else{
							var matching_nodes=data_xml.selectNodes("//scheme[@has_latlng=1 and @estimated_value>="+start_range+" and @estimated_value<"+end_range+"]")
						}
					}
				break;
			}
			
			if(matching_nodes.length>0){
				for(var i=0;i<matching_nodes.length;i++){
					
					scheme_ob_list[parseInt(matching_nodes[i].getAttribute("listpos"))].change_filter(1)
				}		
			}
			
			if(map_filter_sent==0){
				check_latlng_loaded()
			}
			
			if(typeof large_map_link_ob!="undefined" && !!large_map_link_ob){
				var targ=large_map_link_ob.href.toString()
				targ=targ+"&filter_by="+by_ob.options[by_ob.selectedIndex].value
				targ=targ+"&filter_value="+thisone.options[thisone.selectedIndex].value
				large_map_link_ob.href=targ
			}
		}
	}
}

//FORM SCRIPTS
function search_form_submit(){
	//STARTS SEARCH FOR SEARCH_TERM
	var ft=document.forms["criteria_form"].search_term.value
	if(ft!=""){
		load_data(ft,"")
	}
	return false;
}

function change_freetext(thisone){
	//TRIGGERED WHEN TEXT IS ENTERED INTO THE SEARCH BOX
	var sha_ob =document.getElementById("sha_selector")

	if(sha_ob.selectedIndex>0){
		sha_ob.options[0].selected=1
		change_node(sha_ob)
	}
}

function change_node(thisone){
	//TRIGGERED WHEN THE PCT OR SHA MENU IS USED
	var sha_ob =document.getElementById("sha_selector")
	var pct_ob =document.getElementById("pct_selector")
	var freetext_ob =document.getElementById("search_term")
	
	if(thisone.name=="sha_selector"){
		//SHA SELECTED
		if(thisone.selectedIndex>0){

		
			freetext_ob.value=""
			load_node_list(thisone.options[thisone.selectedIndex].value)
			//load_data("",thisone.options[thisone.selectedIndex].value)
		}else{
			remove_poly()
			zoom_to_default()
			pct_ob.options.length=1
			pct_ob.disabled=1
			pct_ob.className="popup_input disabled"
		}
	}else{
		//PCT SELECTED
		if(thisone.selectedIndex>0){
			freetext_ob.value=""
			
			if(thisone.options[thisone.selectedIndex].value=="all"){
				load_data("",sha_ob.options[sha_ob.selectedIndex].value)
			}else{
				load_data("",thisone.options[thisone.selectedIndex].value)
			}
		}else{
			change_node(sha_ob)
		}
	}
}

//SCROLLWHEEL ZOOM SCRIPTS
function wheelZoom(a)
{
  if (a.detail) // Firefox
  {
    if (a.detail < 0)
    { map.zoomIn(); }
    else if (a.detail > 0)
    { map.zoomOut(); }
  }
  else if (a.wheelDelta) // IE
  {
    if (a.wheelDelta > 0)
    { map.zoomIn(); }
    else if (a.wheelDelta < 0)
    { map.zoomOut(); }
  }
}
