
// this variable will collect the html which will eventually be placed in the sidebar
var sidebar_html = "";
// this is the handle to the map
var map = "";
// arrays to hold copies of the markers and html used by the sidebar
// because the function closure trick doesnt work there
var gmarkers = [];
var htmls = [];
var intCount = 0;
// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];
var counter = 0;

var prefix = '';

var intZoom = 9;

var sidebar_mode = 0;
var sidebar_title = '';
var map_title = '';

var center_lat = '';
var center_lon = '';

var enable_overview = 1;

var blnDirections = 'true';

function GetXmlNodeText(node)
{ 
    if(node && node.text)
    { 
        return node.text; 
    }
    else if(node && node.textContent)
    { 
        return node.textContent; 
    } 
    else
    {
		return '';
    }
}

function gmapHelp() {
	//debugger
	var dialogWidth = 500
	var dialogHeight = 340
	var dialogTop = (screen.height - dialogHeight)/2
	var dialogLeft = (screen.width - dialogWidth)/2
    window.open('Help.aspx','','width='+dialogWidth+',height='+dialogHeight+',top='+dialogTop+',left='+dialogLeft+',toolbar=no,menubar=no,location=no,directories=no,status=yes');
}

if (GBrowserIsCompatible()) {
  // A function to create the marker and set up the event window
  function createMarker(point,name,html,iconcolour) {
    counter++;
    
    var icon = new GIcon();
    icon.image = mstrAppPath + "_themes/googlemap/images/mm_20_" + iconcolour + ".png"; //
    icon.iconSize = new GSize(12, 20);

    icon.shadow = mstrAppPath + "_themes/googlemap/images/mm_20_shadow.png";
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);     
    
    
    var marker = new GMarker(point, {icon: icon, draggable: false});  //TRUE!
/*
	GEvent.addListener(marker, "dragstart", function() {  
		map.closeInfoWindow();  
	});
	GEvent.addListener(marker, "dragend", function() {  
		marker.openInfoWindowHtml("New coordinates: <br />Lon: "+ this.getLatLng().x + ' Lat:' + this.getLatLng().y);  
	});
*/	
    var finalhtml;
    
    if(blnDirections == 'true') {
        // The info window version with the "to here" form open
        to_htmls[intCount] = html + '<br><br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + intCount + ')" class="popuplnk">From here</a>' +
           '<br><br>Start address/postcode:<br><form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" size="30" maxlength="40" name="saddr" id="saddr" value="" /><br>' +
           '<input value="Get Directions" type="submit">' +
           '<input type="hidden" name="daddr" value="' +
           point.y + ',' + point.x + "(" + prefix + ' - ' + name + ")" + '"/>';
        // The info window version with the "to here" form open
        from_htmls[intCount] = html + '<br><br>Directions: <a href="javascript:tohere(' + intCount + ')" class="popuplnk">To here</a> - <b>From here</b>' +
           '<br><br>End address/postcode:<br><form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" size="30" maxlength="40" name="daddr" id="daddr" value="" /><br>' +
           '<input value="Get Directions" type="submit">' +
           '<input type="hidden" name="saddr" value="' +
           point.y + ',' + point.x + "(" + prefix + ' - ' + name + ")" + '"/>';
        // The inactive version of the direction info
        finalhtml = html + '<br><br>Directions: <a href="javascript:tohere('+ intCount +')" class="popuplnk">To here</a> - <a href="javascript:fromhere('+ intCount +')" class="popuplnk">From here</a>';
    }
    else {
        if(name!='') {
            finalhtml = '<strong>'+name + '</strong><br>' + html;
        }
        else {
            finalhtml = html;
        }
    }
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml('<div class="popup">'+finalhtml+'</div>');
    });
    /*
    MOUSEOVER INSTEAD
    GEvent.addListener(marker, "mouseover", function() {
      marker.openInfoWindowHtml('<div class="popup">'+finalhtml+'</div>');
    });
    */
    // save the info we need to use later for the sidebar
    gmarkers[intCount] = marker;
    htmls[intCount] = finalhtml;
    // add a line to the sidebar html

    sidebar_html += '<div id="side'+counter+'"><a href="javascript:myclick(' + intCount + ')" class="Office">' + name + '</a><br />' + html + '</div>';

    intCount++;
    return marker;
  }
  

  // This function picks up the click and opens the corresponding info window
  function myclick(i) {
    document.getElementById("mapcont").focus();    
    gmarkers[i].openInfoWindowHtml('<div class="popup">'+htmls[i]+'</div>');
  }

  // functions that open the directions forms
  function tohere(i) {
    gmarkers[i].openInfoWindowHtml('<div class="popup">'+ to_htmls[i]+'</div>');

  }
  function fromhere(i) {
    gmarkers[i].openInfoWindowHtml('<div class="popup">'+ from_htmls[i] +'</div>');
  }

function firstClick()
{
    myclick(0);   
}

	// Download the data in data.xml and load it on the map. The format we
	// expect is:
	// <markers>
	//   <marker lat="37.441" lng="-122.141" title="blah" desc="comp name1"/>
	//   <marker lat="37.322" lng="-121.213" title="blah" desc="comp name2"/>
	// </markers>
	function init() {
        var request = GXmlHttp.create();
        request.open("GET", xmlFile, true);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {





                var xmlDoc = request.responseXML;
                
                var mode_check = xmlDoc.getElementsByTagName("metadata");
                

                if(mode_check.length==1) {
                    //meta data xml
                    
                    //create the map and add a couple of toolbars
                    map = new GMap2(document.getElementById("mapcont"));
                    map.addControl(new GLargeMapControl()); //pan & zoom
                    //map.addControl(new GMapTypeControl());  //map type: map, satellite, hybrid
                    //map.addControl(new GOverviewMapControl());                   
                    
                    blnDirections = false;
                    intZoom = 4;
                    
   
                    var markers = xmlDoc.getElementsByTagName("item");
                    for (var i = 0; i < markers.length; i++) {
                    
                       var gpsLon = parseFloat(GetXmlNodeText(markers[i].getElementsByTagName("gpslongitude")[0]));
                        var gpsLat = parseFloat(GetXmlNodeText(markers[i].getElementsByTagName("gpslatitude")[0]));
                        if(i==0) {
                            //center near blackpool
                            //map.setCenter(new GLatLng(parseFloat('54.6021'), parseFloat('-4.3636')), intZoom, null);
							
							//center on first point
							map.setCenter(new GLatLng(gpsLat, gpsLon), intZoom, null);
                        }

                        var iconColour = 'red';
						
						var title = GetXmlNodeText(markers[i].getElementsByTagName("companyname")[0]);
						var desc = GetXmlNodeText(markers[i].getElementsByTagName("address")[0]);
						var tel = GetXmlNodeText(markers[i].getElementsByTagName("telephone")[0]);
						var fax = GetXmlNodeText(markers[i].getElementsByTagName("fax")[0]);
						if(typeof(desc)=='undefined') {
							desc = '';
						}
						var img = GetXmlNodeText(markers[i].getElementsByTagName("image")[0]);
						var link = GetXmlNodeText(markers[i].getElementsByTagName("website")[0]);

						desc = '<table class="datatbl" cellspacing="0" cellpadding="0" border="0">'+
								'<tr>'+
								'<td valign="top"><strong>'+title+'</strong>'+
								desc;
						
						if(tel!='') {
							desc += '<br/>Tel: '+tel+'';
						}
						if(fax!='') {
							desc += '<br/>Fax: '+fax+'';
						}
						
						if(link!='') {
							desc += '<br/><br/><a href="http://'+link+'" target="_blank">'+link+'</a>';
						}
			   
						
						desc += '</td>';
						
						if(img!='')
						{

							desc += '<td width="10" nowrap></td>'+
									'<td valign="top" width="90" nowrap><img src="'+img+'" align="top" title="'+title+'" /></td>';
						}
						desc += '</tr>'+
							'</table><br />';
			  
                        
                        if(!isNaN(gpsLon) && !isNaN(gpsLat)) {
                            var point = new GPoint(gpsLon,gpsLat);

                            var marker = createMarker(point,'',desc,iconColour);
                            map.addOverlay(marker);
                        }
						else
						{
							sidebar_html += '<div class="popup"><a class="Office"></a><br/>' +desc+'</div>';
						}
                    }   
                         
         
                    
                }

                // put the assembled sidebar_html contents into the sidebar div
                //sidebar_html = '<h1 class="elContentTitle">Contact Us</h1>' + sidebar_html;
                if(document.getElementById("sidebar")) {

                    document.getElementById("sidebar").innerHTML = sidebar_title + sidebar_html;
                }
            }
        }
        request.send(null);
    }
    
    //addEvent(window, 'load', init, false);
	Event.observe(document, 'dom:loaded', init);
    //DomLoaded.load(init);
}
else {
  alert('Sorry, the Google Maps API is not compatible with this browser');
}  
 