
// 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 '';
    }
}

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);
    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
    if(sidebar_mode == 0) {
        sidebar_html += '<div id="side'+counter+'"><a href="javascript:myclick(' + intCount + ')" class="Office">' + name + '</a><br /></div>'; //' + html + '</div>';
    }
    else if(sidebar_mode == 1) {
        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 = 6;
                    
   
                    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);
                        }
                        try {
                            var iconColour = GetXmlNodeText(markers[i].getElementsByTagName("mapiconcolour")[0]);
                        }
                        catch(e) {
                            var iconColour = 'red';
                        }
                        
                        if(!isNaN(gpsLon) && !isNaN(gpsLat)) {
                            var point = new GPoint(gpsLon,gpsLat);
                            var title = GetXmlNodeText(markers[i].getElementsByTagName("title")[0]);
                            var desc = GetXmlNodeText(markers[i].getElementsByTagName("description")[0]);
                            if(typeof(desc)=='undefined') {
                                desc = '';
                            }
                            var img = GetXmlNodeText(markers[i].getElementsByTagName("image")[0]);
                            var link = GetXmlNodeText(markers[i].getElementsByTagName("link")[0]);
                            var docpdfNode = markers[i].getElementsByTagName("pdfdocument")[0];
                            var docpdf = '';
                            if (docpdfNode != null)
                            {
								docpdf = GetXmlNodeText(docpdfNode);
							}
							
                            desc = '<table class="datatbl" cellspacing="0" cellpadding="0" border="0">'+
                                    '<tr>'+
                                    '<td valign="top"><strong>'+title+'</strong>'+
                                    desc;
                            
                            if(link!='') {
                                desc += '<br/><br/><a href="'+link+'">Read More</a>';
                            }
                            if(docpdf!='') {
                                desc += '<br/><a href="'+docpdf+'" target="_blank">Download PDF</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>';
                  
                            var marker = createMarker(point,'',desc,iconColour);
                            map.addOverlay(marker);
                        }
                    }   
                         
         
                    
                }
                else {
                
                    //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


                    var properties = xmlDoc.documentElement.getElementsByTagName("property");
                    for (var i = 0; i < properties.length; i++) {
                        if(properties[i].getAttribute("name") == 'company_name') {
                            prefix = GetXmlNodeText(properties[i]);   
                        }
                        else if (properties[i].getAttribute("name") == 'sidebar_mode') {
                            sidebar_mode = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'sidebar_title') {
                            sidebar_title = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'map_title') {
                            map_title = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'zoom') {
                            intZoom = parseInt(GetXmlNodeText(properties[i]));
                        }
                        else if (properties[i].getAttribute("name") == 'directions') {
                            blnDirections = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'center_lat') {
                            center_lat = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'center_lon') {
                            center_lon = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'enable_overview') {
                            enable_overview = GetXmlNodeText(properties[i]);
                        }
                         
                    }	

                    if(parseInt(enable_overview) == 1)
                    {
                        //map.addControl(new GOverviewMapControl());    
						window.setTimeout("overview = new GOverviewMapControl();map.addControl(overview)",500); 

                    }
                    
                    
                    if(map_title != '') {
                        
                        var objMap = document.getElementById("mapcont");
                        if(objMap) {
                            var objTitle = document.createElement('h1');
                            objTitle.innerText = map_title;
                            objTitle.className = 'MapTitle';
                            objMap.insertAdjacentElement('beforeBegin', objTitle);
                            
                        }
                    }                
                    	    
                    var markers = xmlDoc.documentElement.getElementsByTagName("marker");
                    for (var i = 0; i < markers.length; i++) {
                        if(i==0) {
                            //center near first point
                            if(center_lat=='')
                            {
                               map.setCenter(new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng"))), intZoom, null);
                            }
                            else
                            {
                                map.setCenter(new GLatLng(parseFloat(center_lat), parseFloat(center_lon)), intZoom, null);
                            }
                        }
                        
                        try {
                            var iconColour = markers[i].getAttribute("icon").toString()
                        }
                        catch(e) {
                            var iconColour = 'red';
                        }
                        var point = new GPoint(parseFloat(markers[i].getAttribute("lng")),parseFloat(markers[i].getAttribute("lat")));
                        var title = markers[i].getAttribute("title").toString();
                        var desc = markers[i].getAttribute("desc").toString();
                        var marker = createMarker(point,title,desc,iconColour);
                        map.addOverlay(marker);
                    }
                    if(i==1)
                    {
                        firstClick();
                        
                    }
                }

                // put the assembled sidebar_html contents into the sidebar div
                //sidebar_html = '<h1 class="elContentTitle">Contact Us</h1>' + sidebar_html;
                if(document.getElementById("sidebar")) {
                    if(sidebar_title!='') {
                        sidebar_title = '<h1 class="SideBarTitle"><span>'+sidebar_title+'</span>'+sidebar_title+'</h1>';
                    }
                    document.getElementById("sidebar").innerHTML = sidebar_title + sidebar_html;
                }
            }
        }
        request.send(null);
    }

    Event.observe(window, 'load', init, false);
    //DomLoaded.load(init);
}
else {
  alert('Sorry, the Google Maps API is not compatible with this browser');
}  
 