var gmap;
var markerIds 		= new Array();
var markerObjs 		= new Array();
var hilitMarkerObjs = new Array();
var normalIcon 		= null;
var nationalIcon	= null;
var regionalIcon	= null;
var normalIcon 		= null;
var hilightedIcon 	= null;
var hilightedMarker = null;
var hiddenMarker    = null;

function defaultIconWith( img ) {
    var ret        = new GIcon();
    ret.image      = img;
    ret.shadow     = G_DEFAULT_ICON.shadow;
    ret.iconSize   = G_DEFAULT_ICON.iconSize;
    ret.shadowSize = G_DEFAULT_ICON.shadowSize;
    ret.iconAnchor = G_DEFAULT_ICON.iconAnchor;
    return ret;
}

function getNormalIcon() {
    if( normalIcon == null ) {
        normalIcon = defaultIconWith( "../images/misc/marker.png" );
    }
    return normalIcon;
}

function getNationalIcon() {
    if( nationalIcon == null ) {
        nationalIcon = defaultIconWith( "../images/misc/nimarker.png" );
    }
    return nationalIcon;
}

function getRegionalIcon() {
    if( regionalIcon == null ) {
        regionalIcon = defaultIconWith( "../images/misc/rimarker.png" );
    }
    return regionalIcon;
}

function getHilightedIcon() {
    if( hilightedIcon == null ) {
        hilightedIcon = defaultIconWith( "../images/misc/hmarker.png" );
    }
    return hilightedIcon;
}

function showPubOnMap( id ) {
    var idx = markerIds.indexOf( id );
	if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('showPubOnMap id: ' + id)};
    if( hilightedMarker != null ) {
        hilightedMarker.hide();
    }
    if( hiddenMarker != null ) {
        hiddenMarker.show();
    }
    hilightedMarker = hilitMarkerObjs[idx];
    hilightedMarker.show();
    hiddenMarker    = markerObjs[idx];
    hiddenMarker.hide();
	// also zoom in a bit for a closer look at just this pub
    // gmap.panTo( hilightedMarker.getPoint() );
    gmap.setCenter( hilightedMarker.getPoint() );
	// if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('showPubOnMap lat: ' + hilightedMarker.getPoint().lat())};
	// if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('showPubOnMap lng: ' + hilightedMarker.getPoint().lng())};
	gmap.setZoom( 11 ); 
    hilightedMarker.setPoint( hilightedMarker.getPoint() );
}

function createPubMarker( id, name, district, region, ni_status, pnt, doPan ) {      
    var marker = new GMarker( pnt, { title: name + " (" + district + ")",
                                     icon: getNormalIcon() } );
    var nimarker = new GMarker( pnt, { title: name + " (" + district + ")",
                                     icon: getNationalIcon() } );
    var rimarker = new GMarker( pnt, { title: name + " (" + district + ")",
                                     icon: getRegionalIcon() } );
    var hiMarker = new GMarker( pnt, { title: name + " (" + district + ")",
                                       icon: getHilightedIcon() } );
	if (region != null) {
		if ((ni_status == 'N I Part One') || (ni_status == 'N I Part Two')) {
			GEvent.addListener( nimarker, "click", function() {
					window.location = 'regional-inventory-pubguide.asp?Region=' + region + '&PubID=' + id;
					});
			gmap.addOverlay( nimarker );
			gmap.addOverlay( hiMarker );
			hiMarker.hide();
		
			markerIds.push( id );
			markerObjs.push( nimarker );
			hilitMarkerObjs.push( hiMarker );
		} else {
			GEvent.addListener( rimarker, "click", function() {
					window.location = 'regional-inventory-pubguide.asp?Region=' + region + '&PubID=' + id;
					});
			gmap.addOverlay( rimarker );
			gmap.addOverlay( hiMarker );
			hiMarker.hide();
		
			markerIds.push( id );
			markerObjs.push( rimarker );
			hilitMarkerObjs.push( hiMarker );
		}
	} else {
		GEvent.addListener( nimarker, "click", function() {
				window.location = 'national-inventory-pubguide.asp?PubID=' + id;
				});
		gmap.addOverlay( nimarker );
		gmap.addOverlay( hiMarker );
		hiMarker.hide();
	
		markerIds.push( id );
		markerObjs.push( nimarker );
		hilitMarkerObjs.push( hiMarker );
	}
    if( doPan ) {
        gmap.panTo( pnt );
    }
}

// send xml data from pubdataxml.asp to the gmap
function xml2map( req ) {
    var doc = req.responseXML;
	var id = null;
	var id2 = null;
	var name = null;
	var town = null;
	var ni_status = null;
	var pnt = null;
    var h = $H( window.location.search.substring(1).toQueryParams() );
    // was there an appropriate query string for region?
	var region = null;
    if( $A( h.keys() ).indexOf( "Region" ) != -1 ) {region = h["Region"];}
	if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('xml2map region: ' + region);}
	if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {showPubOnMap(2)};
    // IE and Firefox want to get at the namespaced xml data in
    // slightly different ways. Argh.
    var results = $A(doc.getElementsByTagName("z:row"));
    if( results.length == 0 ) {
        results = $A(doc.getElementsByTagName("row"));
    }
	if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('xml2map num pubs: ' + results.length);}
	for( i = 0; i < results.length; i++ ) {
		id = results[i].getAttribute( "PubID" );
		if( markerIds.include( id ) ) {
			// do nothing
			markerIds.detect( function( val, idx ) {
				if( val == id ) {
					var marker = markerObjs[idx];
					gmap.panTo( marker.getPoint() );
				}
			});
		} else {
			id2    = results[i].getAttribute( "PubID" );
			name   = results[i].getAttribute("PubName");
			town = results[i].getAttribute( "Town" );
			ni_status = results[i].getAttribute( "NI_StatusCurrent" );
			pnt    = new GLatLng( results[i].getAttribute( "Latitude" ), 
									  results[i].getAttribute( "Longitude" ) );
			createPubMarker( id2, name, town, region, ni_status, pnt, results.length==1 );
		}
	}
    // if there was an appropriate query string, highlight show that pub
    if( $A( h.keys() ).indexOf( "PubID" ) != -1 ) {
		if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('xml2map PubID: ' + h["PubID"])};
		showPubOnMap( h["PubID"] );
	}
}

// get rid of all pubs
function clearMarkers() {
    markerObjs.each( function( marker, idx ) {
        gmap.removeOverlay( marker );
        GEvent.clearInstanceListeners( marker );
        hiMarker = hilitMarkerObjs[idx];
        gmap.removeOverlay( hiMarker );
        GEvent.clearInstanceListeners( hiMarker );
    });
    markerObjs      = new Array();
    hilitMarkerObjs = new Array();
    markerIds       = new Array();
}

// call this to load all pubs
function showAllPubs(strType) {
	var xmlrequest;
	var region = null;
    var h = $H( window.location.search.substring(1).toQueryParams() );
    if( $A( h.keys() ).indexOf( "Region" ) != -1 ) {region = h["Region"];}
	if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('showAllPubs: strType=' + strType)};
	if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('showAllPubs: region=' + region)};
	if (strType == 'NI') {xmlrequest = "national-inventory-pubdataxml.asp";}
	else if (strType == 'RI') {xmlrequest = "regional-inventory-pubdataxml.asp";}
	if ((region == 'East%20Anglia') || (region == 'East Anglia')) {xmlrequest = "eastanglia-pubdataxml.asp";
	} else if ((region == 'East%20Midlands') || (region == 'East Midlands')) {xmlrequest = "eastmidlands-pubdataxml.asp";
	} else if ((region == 'West%20Midlands') || (region == 'West Midlands') ) {xmlrequest = "westmidlands-pubdataxml.asp";
	} else if ((region == 'North%20East%20England') ||  (region == 'North East England')) {xmlrequest = "northeast-pubdataxml.asp";
	} else if ((region == 'North%20West%20England') || (region == 'North West England')) {xmlrequest = "northwest-pubdataxml.asp";
	} else if ((region == 'South%20East%20England') ||  (region == 'South East England')){xmlrequest = "southeast-pubdataxml.asp";
	} else if ((region == 'South%20West%20England') || (region == 'South West England') ) {xmlrequest = "southwest-pubdataxml.asp";
	} else if (region == 'London') {xmlrequest = "london-pubdataxml.asp";
	} else if ((region == 'Northern%20Ireland') || (region == 'Northern Ireland')) {xmlrequest = "northernireland-pubdataxml.asp";
	} else if (region == 'Scotland') {xmlrequest = "scotland-pubdataxml.asp";
	} else if (region == 'Wales') {xmlrequest = "wales-pubdataxml.asp";
	} else if (region == 'Yorkshire') {xmlrequest = "yorkshire-pubdataxml.asp";} 
	if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('showAllPubs: xmlrequest=' + xmlrequest)};
    var myLog = new Ajax.Request (
        xmlrequest,
        {
            method: "get",
            onComplete: xml2map
        });
}

function PubMapLoad() {
	var region = null;
    // was there an appropriate query string for region?
    var h = $H( window.location.search.substring(1).toQueryParams() );
    if( $A( h.keys() ).indexOf( "Region" ) != -1 ) {region = h["Region"];}
	if( $A( h.keys() ).indexOf( "Test" ) != -1 ) {alert('load: ' + region);}
	var latitude = null;
    var longitude  = null;
    var scale = null;
	if ((region == 'East%20Anglia') || (region == 'East Anglia')) { 
			latitude = 52.34;
			longitude = 0.60;
			scale = 9;
	} else if ((region == 'East%20Midlands') || (region == 'East Midlands')) {
			latitude = 53.08;
			longitude = -0.82;
			scale = 9;
	} else if ((region == 'West%20Midlands') || (region == 'West Midlands') ) {
			latitude = 52.59;
			longitude = -2.13;
			scale = 9;
	} else if ((region == 'North%20East%20England') ||  (region == 'North East England')) {
			latitude = 54.98;
			longitude = -1.60;
			scale = 9;
	} else if ((region == 'North%20West%20England') || (region == 'North West England')) {
			latitude = 54.04;
			longitude = -2.81;
			scale = 9;
	} else if ((region == 'South%20East%20England') ||  (region == 'South East England')){
			latitude = 51.48;
			longitude = -0.12;
			scale = 9;
	} else if ((region == 'South%20West%20England') || (region == 'South West England') ) {
			latitude = 51.06;
			longitude = -3.63;
			scale = 8;
	} else if (region == 'London') {
			latitude = 51.48;
			longitude = -0.12;
			scale = 11;
	} else if ((region == 'Northern%20Ireland') || (region == 'Northern Ireland')) {
			latitude = 54.65;
			longitude = -6.57;
			scale = 9;
	} else if (region == 'Scotland') {
			latitude = 56.30;
			longitude = -4.01;
			scale = 8;
	} else if (region == 'Wales') {
			latitude = 52.40;
			longitude = -3.60;
			scale = 8;
	} else if (region == 'Yorkshire') {
			latitude = 53.95;
			longitude = -1.09;
			scale = 9;
	} else {
			latitude = 54.0;
			longitude = -2.5;
			scale = 7;
	}
    if (GBrowserIsCompatible()) {
        gmap = new GMap2(document.getElementById("pubguidemap"));
	gmap.addControl(new GLargeMapControl());
	gmap.addControl(new GMapTypeControl());
	gmap.setCenter( new GLatLng(latitude,longitude),scale);
    }
}
