//<![CDATA[
var map;
var geocoder;

function load() {
  if (GBrowserIsCompatible()) {
	geocoder = new GClientGeocoder();
	map = new GMap2(document.getElementById('Map'));
	map.removeMapType(G_PHYSICAL_MAP);
	map.setCenter(new GLatLng(36.85, -99.12), 3);
	var customUI = map.getDefaultUI();
	customUI.controls.largemapcontrol3d = false;
	customUI.controls.smallzoomcontrol3d = true;
	customUI.controls.menumaptypecontrol = true;
	customUI.controls.scalecontrol = false;
	map.setUI(customUI);
	//var view = 'all';
	//var storeid = 0
	//searchLocationsNear(map.getCenter(), view, storeid);
	gdir = new GDirections(map, document.getElementById('Directions'));
    //GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);
  }
}

//map all locations
function searchAllLocations() {
	var latlng = new GLatLng(36.85, -99.12);
     var view = 'all';
	 searchLocationsNear(latlng, view, 0);
}

//map the corporate office
function MapIt(Zip) {
 var address = new String(Zip); 
 geocoder.getLatLng(address, function(latlng) {
   if (!latlng) {
	 alert(address + ' not found');
   } else {
     var view = 'hq';
	 searchLocationsNear(latlng, view, 0);
   }
 });
}

//map store and sales locations
function searchStoreLocations(StoreID) {
	var latlng = new GLatLng(36.85, -99.12);
     var view = 'store';
	 searchLocationsNear(latlng, view, StoreID);

}

//map local stores within 200 miles
function searchLocations() {
 var address = document.getElementById('addressInput').value;
 geocoder.getLatLng(address, function(latlng) {
   if (!latlng) {
	 alert(address + ' Invalid Entry');
   } else {
     var view = 'local';
	 searchLocationsNear(latlng, view, 0);
   }
 });
}

function searchLocationsNear(center, view, storeid) {
 var searchUrl = 'locator_genxml.cfm?lat=' + center.lat() + '&lng=' + center.lng() + '&view=' + view + '&storeid=' + storeid;	
 GDownloadUrl(searchUrl, function(data) {
   var xml = GXml.parse(data); 	     
   var markers = xml.documentElement.getElementsByTagName('marker');	   
   map.clearOverlays();
   var sidebar = document.getElementById('Locations');
   if (view == 'local' || view == 'store'){
	  sidebar.innerHTML = ''; 
   }
   else{
	 sidebar.innerHTML = '<p>Enter an Address, City, State, or Zip Code in the Search field above the map to find your local TUFF SHED Showrooms.</p>';  
   }
   
   if (markers.length == 0) {
	 sidebar.innerHTML = '<p>No TUFF SHED Showrooms in your area.</p>';
	 map.setCenter(new GLatLng(36.85, -99.12), 3);
	 showLocations();
	 return;
   }

   var bounds = new GLatLngBounds();
   for (var i = 0; i < markers.length; i++) {
   	 var storeid = markers[i].getAttribute('storeid');
	 var name = markers[i].getAttribute('name');
	 var address = markers[i].getAttribute('address');
	 var city = markers[i].getAttribute('city');
	 var state = markers[i].getAttribute('state');
	 var zipcode = markers[i].getAttribute('zipcode');
	 var phone = markers[i].getAttribute('phone');
	 var tollfree = markers[i].getAttribute('tollfree');
	 var fax = markers[i].getAttribute('fax');
	 var mtof = markers[i].getAttribute('mtof');
	 var sat = markers[i].getAttribute('sat');
	 var sun = markers[i].getAttribute('sun');
	 var distance = parseFloat(markers[i].getAttribute('distance'));
	 var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
							 parseFloat(markers[i].getAttribute('lng')));
	 
	 var marker = createMarker(point, storeid, name, address, city, state, zipcode, phone, tollfree, fax);
	 map.addOverlay(marker);
	 //only populate the sidebar for non corporate offices
	 if (view == 'local' || view == 'store'){
	 	var sidebarEntry = createSidebarEntry(i, marker, storeid, name, address, city, state, zipcode, phone, tollfree, fax, mtof, sat, sun, distance);
	 	sidebar.appendChild(sidebarEntry);
	 	if (i == (markers.length - 1) && view == 'local'){
			showLocations();
	 	}
	 }
	 bounds.extend(point);	 
   }
   //zoom to a marker
   if (view == 'hq'){
   		GEvent.trigger(marker, 'click');
   		map.setCenter(point, 10);		
   }
   else {
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
   }
 });   
}
 
function createMarker(point, storeid, name, address, city, state, zipcode, phone, tollfree, fax) {
  var tsIcon = new GIcon(G_DEFAULT_ICON);
  tsIcon.image = "/img/icon_mapmarker.png";
  tsIcon.iconSize = new GSize(35, 30);
  markerOptions = {title:name, icon:tsIcon};
  var marker = new GMarker(point, markerOptions);
  var locationAddress = address + ', ' + zipcode;
  var html = '<strong>' + name + '</strong> <br/>' + address + '<br />' + city + ', ' + state + ' ' + zipcode + '<br />Phone: '+ phone + '<br />Toll Free: ' + tollfree + '<br />Fax: ' + fax;
  
  //don't show the store details link for corporate offices
  if (storeid > 10) {
  	var html = html + '<p><a href="/locator.cfm?StoreID=' + storeid +'">Local Specials &amp; Upcoming Events</a></p>';
  }
  
  //add directions form
  var html = html + '<form action="#" onsubmit="setDirections(this.from.value, this.to.value); return false" id="DirectionsForm"><b>Driving Directions:</b> (from address)<input name="to" id="toAddress" type="hidden" value="' + locationAddress + '" /><fieldset><input name="from" id="fromAddress" type="text" size="18" onEnter="form.submit();" /> <input name="bttn" type="submit" id="bttn" value="Go!" /></fieldset></form>';
  
  GEvent.addListener(marker, 'click', function() {
	marker.openInfoWindowHtml(html);
	map.setCenter(point, 10);
  });
  return marker;
}

function createSidebarEntry(i, marker, storeid, name, address, city, state, zipcode, phone, tollfree, fax, mtof, sat, sun, distance){
	var div = new Element('div', {
		'id': 'ShowroomLocation'
		}
	);
	div.addEvents({
	  'click':function(){
		  $('Locations').getElements('div').removeClass('Selected');
		  div.addClass('Selected');					  
		  GEvent.trigger(marker, 'click');					  
	  },
	  'mouseover':function(){
		  div.addClass('Highlight');
	  },
	  'mouseout':function(){
		  div.removeClass('Highlight');
	  }
	  });
	if(i%2 != 0){
		div.addClass('RowAlt');
	}
	var html = '<div style="display:block; width:100%;"><strong>' + name + ' - Store #' + storeid + '</strong> (' + distance.toFixed(1) + ' miles)<br /><div style="display:block; float:left; width:70%;">' + address + '<br />' + city + ', ' + state + ' ' + zipcode + '<br /><br />Phone: ' + phone + '<br />Toll Free: ' + tollfree + '<br />Fax: ' + fax + '</div><div style="display:block; float:left; width:30%;">Showroom Hours<br />Mon-Fri: ' + mtof + '<br />Sat: ' + sat + '<br />Sun: ' + sun + '</div><br clear="all" /></div>';
	div.set('html',html);
	return div;
}

function setDirections(fromAddress, toAddress) {
	$('Directions').set('html','');
  	gdir.load("from: " + fromAddress + " to: " + toAddress);
  	showDirections();  
}
function handleErrors(){
 if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
   alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
 else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
   alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
 
 else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
   alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
   
 else if (gdir.getStatus().code == G_GEO_BAD_KEY)
   alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

 else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
   alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
  
 else alert("An unknown error occurred.");
}

//]]>
window.addEvent('domready', function() {	
	var accordion = new Fx.Accordion($$('#MapInfo h3'),$$('.MapInfoBox'), {
		opacity: 0, 
    	onActive: function(toggler) {
			if(toggler.getProperty('id') == 'InactiveTab'){ 
				toggler.setStyle('opacity',0);
			}
			else{
				toggler.setStyle('color', '#000000');
			}
		}, 
    	onBackground: function(toggler) {
			if(toggler.getProperty('id') == 'InactiveTab'){ 
				toggler.setStyle('opacity',0);
			}
			else{
				toggler.setStyle('color', '#cf1a14');
			}
		} 
  	}); 
	
});
function showLocations() {
		$('InactiveTab').fireEvent('click');
		(function(){$('ShowroomTab').fireEvent('click');}).delay(1500);
	}
	function showDirections() {
		$('InactiveTab').fireEvent('click');
		(function(){$('DirectionsTab').fireEvent('click');}).delay(1500);
	}