// arrays to hold copies of the markers and html used by the side_bar
var gmarkers = [];
var startPoint;
var marker;

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) {
		        $$('.map-error').setHTML("<p><img src='../i/exclamation.png'/> " + address + " was not found.</p>"); // display an error message
		      } else {
				startPoint = point;
				if (marker) {
					marker.closeInfoWindow();
				}
				$$('.map-instructions').setHTML("<p>Click on the map markers for retail store information.<br/>Commercial Dealer locations are listed in the right side panel.</p>"); // display an error message
		        map.setCenter(point, 10);
		      }
		    }); 	
		} // end showAddress
		
	    var map = new GMap2($("map_canvas"));
	    map.addControl(new GLargeMapControl());
	    var point = new GLatLng(38,-95);
	    map.setCenter(point,3);
		
	    loadPointsFromXML();
	
		if (loc != '') {
			showAddress(loc);
		}
		
    	GEvent.addListener(map,"moveend", function(){
			if (map.getInfoWindow().isHidden()){ // don't load the xml on moveend if a info window is open
				loadPointsFromXML();
			}
		}); 
		
		GEvent.addListener(map,"dragend", function(){loadPointsFromXML();});

		GEvent.addListener(map,"zoomend", function() {
			loadPointsFromXML();
			if (map.getZoom()<6){
				// clear the info from the side bar
				$("side-bar").innerHTML = "<h4>Welcome to the Rapid Refill Store Locator</h4><p>Please enter your location to find a list of stores and commercial dealers in your area.</p>";	
			}
		}); // end zoomend addListener
				
		var mgr = new MarkerManager(map);
		

			

	}  // end if
		
	function loadPointsFromXML()
	{

			if (map.getZoom()>=6){
				    var request = GXmlHttp.create();
				    //grab the xml
				    request.open("GET", "SelectStoresXML.ajax", true);
				    request.onreadystatechange = function() 
				    {
				        if (request.readyState == 4) 
				        {
				            var xmlDoc = request.responseXML;
				            parseXML(xmlDoc);
						
				        }
			
				    }
				    request.send(null);
				
				}

			
	} // end loadPointsFromXML 
	
	var markers;
	var storeName;
	var storeNumber;
	var address;
	var city;
	var state;
	var zip;
	var phone;
	var fax;
	var email;
	var monHours;
	var tuesHours;
	var wedHours;
	var thursHours;
	var friHours;
	var satHours;
	var sunHours;
	var webSite;
	var storeID;
	// var webSiteaddr;
	
	function parseXML(xmlDoc)
	{

	    markers = xmlDoc.documentElement.getElementsByTagName("point");
	    //get the viewing area of the map...to be used later
	    var bounds = map.getBounds();
		// reset the marker letter to 'A'
		j = 0;
		// clear existing markers
		mgr.clearMarkers();
		// clear the info from the side bar
		$("side-bar").innerHTML = "<h4>Don't see a store?</h4><p>Try increasing the map size to view a larger area by pressing the <img src='/i/minus.png' style='vertical-align:middle' /> map control button.</p>";
		// clear side bar variable
		side_bar_html = "<h4>Search Results</h4>";
		// clear commercial dealer variable
		commercialDealerHTML = "";

	    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.contains(point) == true)
	        {
				if (startPoint == undefined) {
					distanceRounded = '';
				} else {
					distanceFromMeters = point.distanceFrom(startPoint);
					distanceFromMiles = distanceFromMeters/1609.344;
					distanceRounded = '<br/><span class="distance">~'+Math.round(distanceFromMiles*Math.pow(10,1))/Math.pow(10,1)+' Miles</span>';
				}
				
	            storeName = markers[i].getAttribute("storeName");
				storeNumber = markers[i].getAttribute("storeNumber");
				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");
				fax = markers[i].getAttribute("fax");
				email = markers[i].getAttribute("email");
				webSite = markers[i].getAttribute("webSite");
				storeID = markers[i].getAttribute("id");
				
				if (webSite != '') {
					webSite = '<a href="'+ webSite+'" target="_blank">Click for Store Website</a><br/>';
				}
				
				monHours = markers[i].getAttribute("monHours");
				tuesHours = markers[i].getAttribute("tuesHours");
				wedHours = markers[i].getAttribute("wedHours");
				thursHours = markers[i].getAttribute("thursHours");
				friHours = markers[i].getAttribute("friHours");
				satHours = markers[i].getAttribute("satHours");
				sunHours = markers[i].getAttribute("sunHours");
				
				commercialDealer = markers[i].getAttribute("commercialDealer");
				var commercialDealerHTML;	
				
				var daddr = address + ', ' + state + ' ' + zip; 	
				
				var hours = '<h6>' + storeName + '</h6>'+
				'<p><strong>Mon:</strong> '+monHours+'<br/>'+
				'<strong>Tues:</strong> '+tuesHours+'<br/>'+
				'<strong>Wed:</strong> '+wedHours+'<br/>'+
				'<strong>Thurs:</strong> '+thursHours+'<br/>'+
				'<strong>Fri:</strong> '+friHours+'<br/>'+
				'<strong>Sat:</strong> '+satHours+'<br/>'+
				'<strong>Sun:</strong> '+sunHours+'<br/>'+
				'</p>';	
					
				var html = fullAddress + '<br/> ' +
				city + ', ' + 
				state + ' ' +
				zip + '<br/>' +
				'<strong>Phone:</strong> ' + phone  + '<br/>' +
				'<strong>Fax:</strong> ' + fax   + '<br/>' +
				'<strong>Email:</strong> <a href="mailto:'+email+'">' + email + '</a>';
				if (commercialDealer != 'true') {
	            	marker = createMarker(point,html,storeName,storeNumber,daddr,hours,distanceRounded,webSite,storeID);
					mgr.addMarker(marker, 6); // add the marker using the marker manager
				} else {
					commercialDealerHTML += '<h6 class="commercial">' + storeName + '</h6><p>' + city + ', ' + 
					state + ' ' +
					zip + '<br/>' +
					'<strong>Phone:</strong> ' + phone  + '<br/>' +
					'<strong>Fax:</strong> ' + fax   + '<br/>' +
					'<strong>Email:</strong> <a href="mailto:'+email+'">' + email + '</a><br/>' +
					webSite +
					'<a href="/business_rfq.aspx?storeid='+storeID+'">Request a quote</a></p>';	
				}
				
				$("side-bar").innerHTML = side_bar_html + commercialDealerHTML;
				
	        }
	    }
		
	} // 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,html,storeName,storeNumber,daddr,hours,distanceRounded,webSite,storeID) {
      // use a custom icon with letter A - Z
      var letter = String.fromCharCode("A".charCodeAt(0) + j);
      var myIcon = new GIcon(G_DEFAULT_ICON, "http://www.google.com/mapfiles/marker" + letter + ".png");
      myIcon.printImage = "http://maps.google.com/mapfiles/marker"+letter+"ie.gif"
      myIcon.mozPrintImage = "http://maps.google.com/mapfiles/marker"+letter+"ff.gif"
      var marker = new GMarker(point, {icon:myIcon});
	  
	  
      GEvent.addListener(marker, "click", function() {
		 var label1 = "Store Info";
		 var label2 = "Hours";
		 var info = '<h6>' + storeName + '</h6><p>' +
		html + '<br/><a href="http://maps.google.com/maps?daddr='+daddr+'" target="_blank">Get Directions</a><br/><a href="/business_rfq.aspx?storeid='+storeID+'">Request a quote</a></p>';
		
		marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1,info), new GInfoWindowTab(label2,hours)]);
		
      });

		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><span class="letter">'+letter+'</span> <a href="javascript:myclick(' + j + ')">' + storeName + '</a></h6><p>' +
	  html + distanceRounded+'<a href="javascript:myclick(' + j + ')" class="more-info">Click for hours and directions</a>'+webSite+'<a href="/business_rfq.aspx?storeid='+storeID+'">Request a quote</a></p>';
      j++;

	// put the assembled side_bar_html contents into the side_bar div
 	$("side-bar").innerHTML = side_bar_html;

      return marker;
    } // end createMarker

	$$('.mapGo').addEvent('click', function(){ // add the functionality to the search form
		searchMap();
		return false;
	});
	
	document.addEvent('keydown', function(event){ // add the functionality when the enter key is pressed
	    var event = new Event(event);
	    //event is now the Event class.
	    if (event.key == 'enter') {
			searchMap();
			return false;
		}
	});
	
	function searchMap() {
		var street = $('street').value;
		var city = $('city').value;
		var state = $('state').value;
		var zip = $('zip').value;

		 if ( ( (city != '') && (state != '') ) || (zip !='') ) {
			// clear the info from the side bar
			$("side-bar").innerHTML = "<h4>Welcome to the Rapid Refill Store Locator</h4><p>Please enter your location to find a list of stores and commercial dealers in your area.</p>";
			var fullAddress = street + ' ' + city + ' ' + state + ' ' + zip;
			$$('.map-error').setHTML(""); // clear out any errors
			showAddress(fullAddress);
		} else {
			$$('.map-error').setHTML("<p><img src='../i/exclamation.png'/> Please enter a city and state or a zipcode.</p>");
		}
	}
}

// This function picks up the click and opens the corresponding info window
function myclick(i) {
	GEvent.trigger(gmarkers[i], "click");
}