// JavaScript Document
function checkform(thisform) {
	var d = document;
	var send = true;
	
	str = d.getElementById('um_name');
	if (str.value.length > 4 && str.value.indexOf("Full") == -1) {
		str.parentNode.className = '';
	}
	else {
		str.parentNode.className = 'error';
		send = false;
	}
	
	str = d.getElementById('um_email');
	if (str.value.indexOf(".") > 2 && str.value.indexOf("@") > 0 && str.value.indexOf("Enter") == -1) {
		str.parentNode.className = '';
	}
	else {
		str.parentNode.className = 'error';
		send = false;
	}

	str = d.getElementById('um_phone');
	if (str.value.length > 9 && str.value.indexOf("Phone") == -1) {
		str.parentNode.className = '';
	}
	else {
		str.parentNode.className = 'error';
		send = false;
	}
	
  str = d.getElementById('um_subject');
	if (str.value.length > 4 && str.value.indexOf("Enter") == -1) {
		str.parentNode.className = '';
	}
	else {
		str.parentNode.className = 'error';
		send = false;
	}
	
	str = d.getElementById('um_message');
	//alert (str.innerHTML.length+" "+str.innerHTML.indexOf("Enter")+"\n\r"+str.value)
	if (str.value.length > 20 && str.value.indexOf("Enter") != 0) {
		str.parentNode.className = '';
	}
	else {
		str.parentNode.className = 'error';
		send = false;
	}
	
	if (send) { 
		thisform.submit();
	}
	else { 
		d.getElementById('user_msg').innerHTML = 'Please correct the fields outlined in this color!';
		d.getElementById('user_msg').className = 'error_msg';
	}
}

// Store Locator
var locations = new Array(
		{
			"name":'La Montanita Co-op, Gallup',
			"address":'105 E COAL AVE, GALLUP, NM 87301',
			"site":'WWW.LAMONTANITA.COOP'
		},
		{
			"name":'La Montanita Coop, Santa Fe',
			"address":'913 W.ALAMEDA, SANTA FE, NM 87501',
			"site":'WWW.LAMONTANITA.COOP'
		},
		{
			"name":'La Montanita, Rio Grande',
			"address":'2400 RIO GRANDE BLVD NW, ALBUQUERQUE, NM 8710',
			"site":'WWW.LAMONTANITA.COOP'
		},
		{
			"name":'Silver City Food Co-op',
			"address":'520 N. BULLARD ST, SILVER CITY, NM 88061',
			"site":'www.silvercityfoodcoop.com'
		},
		{
			"name":'Mountain View Market',
			"address":'1300 S. EL PASEO RD, STE M, LAS CRUSES, NM 88001',
			"site":'www.mountainviewmarket.com'
		},
		{
			"name":'THE HERB STORE',
			"address":'107 CARLISLE BLVD SE, ALBUQUERQUE, NM 87106',
			"site":'www.herbstorenm.com'
		},
		{
			"name":'NATURAL PLANET',
			"address":'3787 STOCKTON HILL RD. STE A, KINGMAN, AZ 86409',
			"site":''
		},
		{
			"name":'NEW FRONTIERS SEDONA',
			"address":'1420 W. HWY 89A, SEDONA, AZ 86336',
			"site":'www.newfrontiers5.com'
		},
		{
			"name":'PURE HEALTH FOODS',
			"address":'7575 W. WASHINGTON AVE #129, LAS VEGAS, NV 89128',
			"site":'www.purehealthfoodslv.com'
		},
		{
			"name":'Toledo Natural Food Co-op',
			"address":'1447 West Sylvania Ave., Toledo, OH 43612',
			"site":'WWW.TOLEDONATURALFOODCOOP.COM'
		}
	);
	//alert(locations.length);
	
	var geocoder;
	var map;
	var maxDistance = 60;
	var origin;
	var resultFound;
	var noResultsMsg = "There were no locations within "+maxDistance+" of the zip code entered.<br /><br />Want to buy Beyond Organics near you? <a href='http://beyondorganicsraw.com/connect_with_us.php'>Let us know</a>!";
	var mapContainer = 'map_canvas';
	var outputID = 'location_results';
	var outputContainer = document.getElementById(outputID);
	var rendererOptions = {
		draggable: true
	};
	var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
	var directionsService = new google.maps.DirectionsService();
	
	var startingPoint = new google.maps.LatLng(34.9727305, -105.0323635);
	
	// initialize
  function initialize() {
		geocoder = new google.maps.Geocoder();
		directionsDisplay = new google.maps.DirectionsRenderer();
		outputContainer.style.display = "none";
    outputContainer.innerHTML = noResultsMsg;
		resultFound = false;
    var myOptions = {
      zoom: 9,
      center: startingPoint,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById(mapContainer), myOptions);
		directionsDisplay.setMap(map);
  	directionsDisplay.setPanel(document.getElementById("directionsPanel"));
  }
	
	// set search marker or stores (determined by start[boolean] flag)
	function codeAddress(obj, i) {
		
		geocoder.geocode( {'address':obj.address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				
				if (i < 0) {
					obj.name = 'Value Entered: '+results[0].address_components[0].long_name;
					obj.position = results[0].geometry.location;
					obj.address = obj.position;
					obj.site = 'maps.google.com';
					obj.distance = 0;
					obj.icon = null;
					map.setCenter(obj.position);
					origin = obj.position;
					
					setMarker (obj);
	
					cycleResults();
					
				}
				else {
					locations[i].position = results[0].geometry.location;
					calcRoute(i);
				}
	
			}
			else {
				alert("Geocode was not successful for the following reason: " + status);
			}
		});
	}
	
	// Interates through the locations object
	function cycleResults(){
		for (i=0;i<locations.length;i++) {
			locations[i].icon = 'http://google-maps-icons.googlecode.com/files/drugs.png';
			locations[i].index = i;
			codeAddress (locations[i], i);
		}
	}
	
	// Calculates the Route of the points.
	function calcRoute(i) {
		var dist = 0;
		var request = {
			origin:origin, 
			destination:locations[i].position,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		
		directionsService.route(request, function(response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				dist = computeTotalDistance(response);
				locations[i].distance = dist;
				if ( dist < maxDistance && dist > 0 ) {
					setMarker(locations[i]);
					if (!resultFound) {
						outputContainer.innerHTML = locations[i].content;
						resultFound = true;
					}
					else {
						outputContainer.innerHTML += locations[i].content;
					}
				}
				
				if(i == locations.length-1){
					outputContainer.style.display = "block";
				}
			}
		});
	}
	
	// Calculates the total distance driving
	function computeTotalDistance(response) {
		var total = 0;
		var myroute = response.routes[0];
		for (i = 0; i < myroute.legs.length; i++) {
			total += myroute.legs[i].distance.value;
		}
		
		total = total / 1000;
		
		return total;
		//document.getElementById("total").innerHTML += total + " km<br>";
	}
	
	function setMarker(obj) {
		var marker = new google.maps.Marker({
			map:map,
			icon:obj.icon,
			position:obj.position
		});
	
		var content = '<div style="font-size:.75em;"><h2 style="margin:0;">'+obj.name+'</h2>'+
		'<small>'+obj.distance+' miles</small>'+
		'<p>'+obj.address+'<br />'+
		'<a href="http://'+obj.site+'" target="_blank">'+obj.site+'</a></div>';
		
		var infowindow = new google.maps.InfoWindow({
				content: content
		});
		
		if (obj.icon) locations[obj.index].content = content;
		
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map,marker);
		});
	}
