function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
	
}

var xmlDoc;
var markers;

// arrays to hold copies of the markers and html used by the side_bar
var gmarkers = [];
var visibleMarkers = [];

var startPoint;
var marker;

var branchChk = document.getElementById('branchChk');
var ATMChk = document.getElementById('ATMChk');
var branchATMChk = document.getElementById('branchATMChk');

var branchIcon = new GIcon(G_DEFAULT_ICON, "/Files/mapIcons/branchIcon.png");
var ATMIcon = new GIcon(G_DEFAULT_ICON, "/Files/mapIcons/ATMIcon.png");
var branchATMIcon = new GIcon(G_DEFAULT_ICON, "/Files/mapIcons/branchATMIcon.png");



function initialize() {
	if (GBrowserIsCompatible()) {   
		
		var geocoder = new GClientGeocoder();
				
		function showAddress(address) { // function for converting an address into longitude and latitude
		  geocoder.getLatLng(
		    address,
		    function(point) {
		      if (!point) {
		        document.getElementById('map-error').innerHTML="<p>" + address + " was not found.</p>"; // display an error message
		      } else {
				startPoint = point;
				if (marker) {
					marker.closeInfoWindow();
				}
				map.setCenter(point, 11);
		      }
		    }); 	
		} // end showAddress
		
	    var map = new GMap2(document.getElementById("map_canvas"));
	    map.addControl(new GLargeMapControl());
		
		var xcoords = $('.xcoords').val();
	    var ycoords = $('.ycoords').val();
	    var point = new GLatLng(xcoords, ycoords);
	 	
	    map.setCenter(point,11);
		var mgr = new MarkerManager(map);
		
	    loadPointsFromXML();
		

		//GEvent.addListener(map,"dragend", function(){loadPointsFromXML();});

		// GEvent.addListener(map,"zoomend", function() {
		// 	loadPointsFromXML();
		// 	if (map.getZoom()<10){
		// 		document.getElementById("side-bar").innerHTML = "<h1>Welcome to the Branch and ATM Locator</h1><p>Please enter your location to find a list of branchs and ATMs in your area.</p>";	
		// 	}
		// }); 
				
				
		GEvent.addListener(map,"moveend", function(){
			if (map.getInfoWindow().isHidden()){ // don't load the xml on moveend if a info window is open
				parseXML(xmlDoc);
			}
			if (map.getZoom()<11){
				// clear the info from the side bar
				document.getElementById("side-bar").innerHTML = "<h1>Welcome to the Branch and ATM Locator</h1><p>Please enter your location to find a list of branchs and ATMs in your area.</p>";	
			}
		});
		
				

	}  // end if
		
	function loadPointsFromXML()
	{
			if (map.getZoom()>=11){
				    var request = GXmlHttp.create();
				    //grab the xml
				    request.open("GET", "/pointdata.xml", true);
				    request.onreadystatechange = function() 
				    {
				        if (request.readyState == 4) 
				        {
				            xmlDoc = request.responseXML;
							markers = xmlDoc.documentElement.getElementsByTagName("point");
				            parseXML(xmlDoc);
						
				        }
			
				    }
				    request.send(null);
				
				}

			
	} // end loadPointsFromXML 
	
	
	var locationName;
	var address;
	var address2;
	var city;
	var state;
	var zip;
	var type;
	var phone;
	var tollFreePhone;
	var TDD;
	var email;
	var webSite;
	var restrictedAccess;
	var atmNotes;
	var branchNotes;
	var driveUpATM;
	var walkUpATM;
	var driveUpWindow;
	var nightDepository;
	var imgSrc;

	function parseXML(xmlDoc)
	{
		
	    //get the viewing area of the map...to be used later
	    var bounds = map.getBounds();
		// reset the marker letter to 'A'
		j = 0;
		

		for (var k = 0; k < visibleMarkers.length; k++) {
			
			if (bounds.containsLatLng(visibleMarkers[k].getLatLng()) == false) {
				mgr.removeMarker(visibleMarkers[k]); // remove the marker from the map
				visibleMarkers.splice(k,1); // remove from our array of visible markers	
				visibleMarkers.push(visibleMarkers[k]); // add to the end
				visibleMarkers.length--; //decrement array by one
			}
							
		}	
		
		// mgr.clearMarkers();
		// 		visibleMarkers.length = 0;

			
		// clear the info from the side bar
		document.getElementById("side-bar").innerHTML = "<h1>Welcome to the Branch and ATM Locator</h1><p>Please enter your location to find a list of branchs and ATMs in your area.</p>";
		// clear side bar variable
		side_bar_html = "<h1>Search Results</h1>";


	    for (var i = 0; i < markers.length; i++) 
	    {
	        // obtain the attribues of each marker
	        var lat = parseFloat(markers[i].getAttribute("lat"));
	        var lng = parseFloat(markers[i].getAttribute("lng"));
			
	        //create point from lat/lng
	        var point = new GLatLng(lat,lng);
	        //check if point is inside the viewing area of the map
	        if (bounds.containsLatLng(point) == true)
	        {

				if (startPoint == undefined) {
					distanceRounded = '';
				} else {
					distanceFromMeters = point.distanceFrom(startPoint);
					distanceFromMiles = distanceFromMeters/1609.344;
					distanceRounded = '<span class="distance">~'+Math.round(distanceFromMiles*Math.pow(10,1))/Math.pow(10,1)+' Miles</span>';
				}
				
	            locationName = markers[i].getAttribute("locationName");
				address = markers[i].getAttribute("address");
				address2 = markers[i].getAttribute("address2");
				if (address2 != '') {
					fullAddress = address +'<br/>'+ address2;
				} else {
					fullAddress = address;
				}
				city = markers[i].getAttribute("city");
				state = markers[i].getAttribute("state");
				zip = markers[i].getAttribute("zip");
				phone = markers[i].getAttribute("phone");
				tollFreePhone = markers[i].getAttribute("tollFreePhone");
				TDD = markers[i].getAttribute("TDD");
				email = markers[i].getAttribute("email");
				webSite = markers[i].getAttribute("webSite");
				type = markers[i].getAttribute("type");
				restrictedAccess = markers[i].getAttribute("restrictedAccess");
				atmNotes = markers[i].getAttribute("atmNotes");
				driveUpATM = markers[i].getAttribute("driveUpATM");
				walkUpATM = markers[i].getAttribute("walkUpATM");
				driveUpWindow = markers[i].getAttribute("driveUpWindow");
				nightDepository = markers[i].getAttribute("nightDepository");
				branchNotes = markers[i].getAttribute("branchNotes");
				
				if (webSite != '') {
					webSite = 'For more information, please visit<br/><a href="'+ webSite+'" target="_blank">'+webSite+'</a>';
				}
				
				if (email != '') {
					email = '<span style="display: block"><strong>Email:</strong> <a href="mailto:'+email+'">' + email + '</a></span>';
				}
				
				if (phone != '') {
					phone = '<span style="display: block"><strong>Phone:</strong> ' + phone  + '</span>';
				}
				
				if (tollFreePhone != '') {
					tollFreePhone = '<span style="display: block"><strong>Toll Free Phone:</strong> ' + tollFreePhone  + '</span>';
				}
				
				if (TDD != '') {
					TDD = '<span style="display: block"><strong>TDD-Hearing Impaired:</strong> ' + TDD  + '</span>';
				}
				
				if (atmNotes != '') {
					atmNotes = '<br/><span style="display: block">' + atmNotes + '</span>';
				}
				
				if (branchNotes != '') {
					branchNotes = '<br/><span style="display: block">' + branchNotes  + '</span>';
				}
				
				
				var daddr = address + ', ' + state + ' ' + zip; 	
				

				
				var icons = '';
				if (driveUpATM == 'true') {
					icons += '<img src="/Files/mapIcons/driveUpATMIcon.png"/>';
				}
				if (driveUpWindow == 'true') {
					icons += '<img src="/Files/mapIcons/driveUpWindowIcon.png"/>';
				}
				if (walkUpATM == 'true') {
					icons += '<img src="/Files/mapIcons/walkUpATMIcon.png"/>';
				}
				if (restrictedAccess == 'true') {
					icons += '<img src="/Files/mapIcons/restrictedAccessIcon.png"/>';
				}
				if (nightDepository == 'true') {
					icons += '<img src="/Files/mapIcons/nightDepositoryIcon.png"/>';
				}
				
				if (icons != '') {
					icons = "<div class='icons'>" + icons + "</div>"
				}
					
				var addressInfo = '<span style="display: block">' + fullAddress + '<br/> ' +
				city + ', ' + 
				state + ' ' +
				zip + '</span>';
				
				var contactInfo = '<span style="display: block">' + phone + tollFreePhone + TDD + atmNotes + webSite + '</span>';
								
				if ((branchChk != null && branchChk.checked == true && type=='branch') | (ATMChk != null && ATMChk.checked == true && type=='ATM') | (branchATMChk != null && branchATMChk.checked == true && type=='branchATM')) {
					var pointExists = false;
					marker = createMarker(point,addressInfo,contactInfo,icons,locationName,daddr,distanceRounded,type,branchNotes);

					for (var k = 0; k < visibleMarkers.length; k++) { // check the visible markers array to make sure the point doesn't already exist
						if( marker.getLatLng().equals(visibleMarkers[k].getLatLng())) {
							pointExists = true;
							break; //exit the loop if true
						} else {
							pointExists = false;
						}
						
					}
										
					if (pointExists == false) { // if point is not already plotted 
						mgr.addMarker(marker, 11); // add the marker using the marker manager
						visibleMarkers.push(marker); // add to our array of visible markers
					}

					// document.getElementById("side-bar").innerHTML = side_bar_html;
					

				}
				
			
	        }
	
	    }
		
	} // end parseXML
	
	// this variable will collect the html which will eventually be placed in the side_bar
    var side_bar_html = "";
  
    var j = 0;
	
	function createMarker(point,addressInfo,contactInfo,icons,locationName,daddr,distanceRounded,type,branchNotes) {
	  	switch(type)
		{
		case "branch":
		  var marker = new GMarker(point, {icon:branchIcon});
		  imgSrc = "/Files/mapIcons/branchIcon.png";
		  break;    
		case "ATM":
	      var marker = new GMarker(point, {icon:ATMIcon});
	      imgSrc = "/Files/mapIcons/ATMIcon.png";
		  break;
		case "branchATM":
		  var marker = new GMarker(point, {icon:branchATMIcon});
		  imgSrc = "/Files/mapIcons/branchATMIcon.png";
		  break;
		}	
	  	  
	  
      GEvent.addListener(marker, "click", function() {
   		var label1 = "Address";
   		var label2 = "Contact";
   		var info = '<h6>' + locationName + '</h6><p style="margin-bottom: 0; padding-bottom: 0;">' + addressInfo + branchNotes + icons + '<br/><span style="display: block"><a href="http://maps.google.com/maps?daddr='+daddr+'" target="_blank">Get Directions</a></span></p>';
   			
   		var contact = '<h6>' + locationName + '</h6><p>' + contactInfo + '</p>';
   		
   		marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,info), new GInfoWindowTab(label2,contact)]);
   		
         });
   
   		GEvent.addListener(map, "infowindowopen", function() { // change the tab text color and remove the underline 
   			var divs = map.getContainer().getElementsByTagName("div");
   			for(var i = 0; i<divs.length; i++){
   			var underline = divs[i].style.textDecoration;
   			var height = divs[i].style.height;
   			var width = divs[i].style.width;
   			if(underline == 'underline') {
   				divs[i].style.textDecoration = 'none';
   			}
   			if(width=="103px"&&height=="24px"){ // get the divs based on the tab size
   			divs[i].style.color = '#00649D';
   			}
   			}});
   			
   		GEvent.addListener(map.getInfoWindow(), "click", function() { // remove the underline in the infowindow tabs
   				var divs = map.getContainer().getElementsByTagName("div");
   				for(var i = 0; i<divs.length; i++){
   				var underline = divs[i].style.textDecoration;
   
   				if(underline == 'underline') {
   					divs[i].style.textDecoration = 'none';
   				}
   
   			}});
				
    // save the info we need to use later for the side_bar
	// gmarkers[j] = marker;
	// add a line to the side_bar html
	// side_bar_html += '<h6><img src="'+imgSrc+'"/><a href="javascript:myclick(' + j + ')">' + locationName + '</a></h6><p style="margin: 0; padding: 0">' +
	// addressInfo + contactInfo + '</p>' + icons + '<p class="directions"><a href="javascript:myclick(' + j + ')" class="more-info">Click for location directions</a><br/>' + distanceRounded + '</p>';
	// j++;

	// // put the assembled side_bar_html contents into the side_bar div
		document.getElementById("side-bar").innerHTML = side_bar_html;
      return marker;
    } // end createMarker
	
	searchMap = function() {
		var street = document.getElementById('street').value;
		var city = document.getElementById('city').value;
		var state = document.getElementById('state').value;
		var zip = document.getElementById('zip').value;

		 if ( ( (city != '') && (state != '') ) || (zip !='') ) {
			// clear the info from the side bar
			document.getElementById("side-bar").innerHTML = "<h1>Welcome to the Branch and ATM Locator</h1><p>Please enter your location to find a list of branchs and ATMs in your area.</p>";
			var fullAddress = street + ' ' + city + ' ' + state + ' ' + zip;
			if (document.getElementById('map-error').innerHTML != '') {
				document.getElementById('map-error').innerHTML = ''; // clear out any errors
			}
			showAddress(fullAddress);
		} else {
			document.getElementById('map-error').innerHTML="<p><img src='/Files/mapIcons/exclamation.png'/> Please enter a city and state or a zipcode.</p>";
		}
	}
	
	keyDown = function(event) {
	    if (event.keyCode == '13') {
			searchMap();
			return false;
		}		
	}
	addEvent(document.getElementById('mapGo'),'click',searchMap,false);
	addEvent(document,'keydown',keyDown,false);
		
	if (branchChk != null) {
		addEvent(document.getElementById('branchChk'),'click',clearAll,false);
	}
	if (ATMChk != null) {
		addEvent(document.getElementById('ATMChk'),'click',clearAll,false);
	}
	if (branchATMChk != null) {
		addEvent(document.getElementById('branchATMChk'),'click',clearAll,false);
	}
	
	function clearAll() {
		mgr.clearMarkers();
		visibleMarkers.length = 0;
		parseXML(xmlDoc);
	}

}

// This function picks up the click and opens the corresponding info window
function myclick(i) {
	GEvent.trigger(gmarkers[i], "click");
}