// JavaScript Document
// closure compiled combining these two google elements:
// # <script src="http://gmaps-utility-library.googlecode.com/svn/trunk/mapiconmaker/release/src/mapiconmaker.js"></script>
// # <script src="http://gmaps-utility-library.googlecode.com/svn/trunk/labeledmarker/release/src/labeledmarker.js"></script>

/*
	taken from index, make me awesome!
latestHash = window.location.hash
urlTag = latestHash.substring(1)

if (urlTag!="") {
	window.location = "http://www.triphopping.com/" + urlTag
		
	// ?page &
	// http://www.triphopping.com/PAGE/
	// http://www.triphopping.com/travel/rides/7tv865d8c9776c
	// http://www.triphopping.com/people/kenflannery
	// http://www.triphopping.com/travel/nyc/boston
}

*/

var a,MapIconMaker={};
MapIconMaker.createMarkerIcon=function(c){var b=c.width||32,d=c.height||32,f=c.primaryColor||"#ff0000",g=c.strokeColor||"#000000",h=c.cornerColor||"#ffffff",e="http://chart.apis.google.com/chart?cht=mm&chs="+b+"x"+d+"&chco="+h.replace("#","")+","+f.replace("#","")+","+g.replace("#","")+"&ext=.png";c=new GIcon(G_DEFAULT_ICON);c.image=e;c.iconSize=new GSize(b,d);c.shadowSize=new GSize(Math.floor(b*1.6),d);c.iconAnchor=new GPoint(b/2,d);c.infoWindowAnchor=new GPoint(b/2,Math.floor(d/12));c.printImage=
e+"&chof=gif";c.mozPrintImage=e+"&chf=bg,s,ECECD8&chof=gif";e="http://chart.apis.google.com/chart?cht=mm&chs="+b+"x"+d+"&chco="+h.replace("#","")+","+f.replace("#","")+","+g.replace("#","");c.transparent=e+"&chf=a,s,ffffff11&ext=.png";c.imageMap=[b/2,d,0.4375*b,0.625*d,0.3125*b,0.4375*d,0.21875*b,0.3125*d,0.3125*b,0.125*d,0.5*b,0,0.6875*b,0.125*d,0.78125*b,0.3125*d,0.6875*b,0.4375*d,0.5625*b,0.625*d];for(b=0;b<c.imageMap.length;b++)c.imageMap[b]=parseInt(c.imageMap[b]);return c};function LabeledMarker(c,b){this.latlng_=c;this.opts_=b;this.labelText_=b.labelText||"";this.labelClass_=b.labelClass||"LabeledMarker_markerLabel";this.labelOffset_=b.labelOffset||new GSize(0,0);this.clickable_=b.clickable||true;this.title_=b.title||"";this.labelVisibility_=true;if(b.draggable)b.draggable=false;GMarker.apply(this,arguments)}LabeledMarker.prototype=new GMarker(new GLatLng(0,0));a=LabeledMarker.prototype;
a.initialize=function(c){GMarker.prototype.initialize.apply(this,arguments);this.map_=c;this.div_=document.createElement("div");this.div_.className=this.labelClass_;this.div_.innerHTML=this.labelText_;this.div_.style.position="absolute";this.div_.style.cursor="pointer";this.div_.title=this.title_;c.getPane(G_MAP_MARKER_PANE).appendChild(this.div_);if(this.clickable_){function b(h,e){return function(){GEvent.trigger(h,e)}}for(var d=["click","dblclick","mousedown","mouseup","mouseover","mouseout"],
f=0;f<d.length;f++){var g=d[f];GEvent.addDomListener(this.div_,g,b(this,g))}}};a.redraw=function(){GMarker.prototype.redraw.apply(this,arguments);this.redrawLabel_()};a.redrawLabel_=function(){var c=this.map_.fromLatLngToDivPixel(this.latlng_),b=GOverlay.getZIndex(this.latlng_.lat());this.div_.style.left=c.x+this.labelOffset_.width+"px";this.div_.style.top=c.y+this.labelOffset_.height+"px";this.div_.style.zIndex=b};
a.remove=function(){GEvent.clearInstanceListeners(this.div_);if(this.div_.outerHTML)this.div_.outerHTML="";this.div_.parentNode&&this.div_.parentNode.removeChild(this.div_);this.div_=null;GMarker.prototype.remove.apply(this,arguments)};a.copy=function(){return new LabeledMarker(this.latlng_,this.opts_)};a.show=function(){GMarker.prototype.show.apply(this,arguments);this.labelVisibility_?this.showLabel():this.hideLabel()};a.hide=function(){GMarker.prototype.hide.apply(this,arguments);this.hideLabel()};
a.setLatLng=function(c){this.latlng_=c;GMarker.prototype.setLatLng.apply(this,arguments);this.redrawLabel_()};a.setLabelVisibility=function(c){this.labelVisibility_=c;this.isHidden()||(this.labelVisibility_?this.showLabel():this.hideLabel())};a.getLabelVisibility=function(){return this.labelVisibility_};a.hideLabel=function(){this.div_.style.visibility="hidden"};a.showLabel=function(){this.div_.style.visibility="visible"};

// my javascript

function parseGeocode(response) {
	
	if (!response || response.Status.code == 602) {
		alert("Didn't recognize that location")
	} else if (!response || response.Status.code != 200) {
		//alert("Something went wrong, how's you're internet connection?");
		
	} else if (response.Placemark[0].AddressDetails.Accuracy==9) {
		reverseLatLong = new google.maps.LatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]);

		geocoder.getLocations(reverseLatLong, function(addresses) {
			if(addresses.Status.code != 200) {
				alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
			} else {
				address = addresses.Placemark[0];
				geocoder.getLocations(address.address, parseGeocode);
			}
		});
	
	} else {

		//clear variables
		place = ""
		point = ""
		marker = ""
		var aa = ""
		var saa = ""
		var l = ""
		state = ""
		county = ""
		city = ""
		streetLine = ""
		zip = ""
		country = ""
		latlong = ""
		
		place = response.Placemark[0];
		
		
		//structured Information
		var aa, saa, l;
		aa = place.AddressDetails.Country.AdministrativeArea;
		if ( aa ) {
			state = aa.AdministrativeAreaName;
			saa = aa.SubAdministrativeArea;
			if ( saa ) {
				county = saa.SubAdministrativeAreaName;
				l = saa.Locality;
				if (l) {
					city = l.LocalityName;
					if ( l.Thoroughfare ) {
						streetLine = l.Thoroughfare.ThoroughfareName;
					}
					if ( l.PostalCode ) {
						zip = l.PostalCode.PostalCodeNumber;
					}
				} else {
					if (saa.Thoroughfare) {
						streetLine = saa.Thoroughfare.ThoroughfareName;
					}
					if (saa.PostalCode) {
						zip = saa.PostalCode.PostalCodeNumber;
					}
				}
			} else {
				l = aa.Locality;
				if (l) {
					city = l.LocalityName;
					if ( l.Thoroughfare ) {
						streetLine = l.Thoroughfare.ThoroughfareName;
					}
					if (l.PostalCode) {
						zip = l.PostalCode.PostalCodeNumber;
					}
				} else {
					if (aa.Thoroughfare) {
						streetLine = aa.Thoroughfare.ThoroughfareName;
					}
					if (aa.PostalCode) {
						zip = aa.PostalCode.PostalCodeNumber;
					}
				}
			}
		}		

			
		if (city=="" && typeof aa!="undefined") {
			if (typeof aa.AddressLine!="undefined") {
				
				city = String(aa.AddressLine)
			}
		}
		
		if (typeof city=="undefined") {
			addy = place.address
			city = addy.split(",", 1);
		}	
		
		placeName = place.address
		//county = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;			
		lat = place.Point.coordinates[1]
		lng = place.Point.coordinates[0]
		latlong = lat + "," + lng
		point = new google.maps.LatLng(lat, lng)
		
		country = place.AddressDetails.Country.CountryNameCode;
		
		// do something with this info
			/* Assigned like this
				
				postGeoSuccess = function () {
					alert("I do awesome stuff!!")
				}
				
			*/
			
		//** MULTI ACTION
				
		geoResult = {lat: lat, lng:lng, coor:latlong, place:placeName, street_address:streetLine, city: city, state: state, zip_code: zip, county: county, country: country}
			
		//** END MULTI ACTON
				
				
		postGeoSuccess()
	}
	
}

function multiGeocode(locations, callback) {

	this.locations = locations;
	this.callback = function() {alert("tripping out, use the talkback")}
	if (typeof(locations)=='object'&&(locations instanceof Array)) {
		multiArray = locations
	} else {
		multiArray = arguments
	}

	geoString = "";
	geoResults = new Array();
	
	postGeoSuccess = function () {
		geoResults[geoResults.length]=geoResult
		if (geoResults.length<multiArray.length) {
			geocoder.getLocations(multiArray[geoResults.length], parseGeocode);
		} else {
			for (i=0; i<geoResults.length; i++) {
				var strStarter = jQuery.param(geoResults[i])
				var more = strStarter.replace(/=/g, "[]=");
				geoString += "&" + more	
			}
			//postMultiGeo();
			callback(geoResults)
		}
	}

	geocoder.getLocations(multiArray[0], parseGeocode);
	
}

function updateRidePosting() {
	
	if (!$('updateRideOrigin').value) {
		alert("You must enter a start location.")
		return false;
	} else if (!$('updateRideDest').value) {
		rideLocations = [$('updateRideOrigin').value];
	} else {
		rideLocations = [$('updateRideOrigin').value, $('updateRideDest').value];
	}
	
	new multiGeocode(rideLocations, function (resultArray) {

		x=0;
		resultArray.each(function(s) {
			if (x==0) {
				$('placeFrom').value = s['place'];
				$('cityFrom').value = s['city'];
				$('stateFrom').value = s['state'];
				$('coorFrom').value = s['coor'];
				$('countryFrom').value = s['country'];
			} else {
				$('placeTo').value = s['place'];
				$('cityTo').value = s['city'];
				$('stateTo').value = s['state'];
				$('coorTo').value = s['coor'];
				$('countryTo').value = s['country'];
			}
			x++;
		
		});
		
		// if no destination, make things blank
		if (x==1) {
			$('placeTo').value = ""; $('cityTo').value = ""; $('stateTo').value = ""; $('coorTo').value = ""; $('countryTo').value = "";
		}
		
		$('rideConfirmDetails').innerHTML = "Post your ride from <strong>" + $('placeFrom').value + "</strong> to <strong>" + $('placeTo').value + "</strong>" 

	});
}

function mainSearch(query) {
	
	toMark = query.search(/ to /i);
	
	//if (toMark != -1 || tripUsername=="noUser") {
	if (toMark != -1 || tripUsername=="") {
		fromPlace = query.slice(0,toMark);
		toPlace = query.slice((toMark+4));	
		//if (tripUsername=="noUser" && toMark == -1) {
		if (tripUsername=="" && toMark == -1) {
			travel(fromPlace)
		} else {
			travel(fromPlace, toPlace)
		}
	} else {
		if ($('origin').value) {
			travel("current", query)
		} else {
			updateLocation(query)
		}
	}
	
}

function talkback() {

	tb_div = document.createElement("div");
	tb_div.setAttribute("title",'talkback')
	tb_div.innerHTML = "loading..."
	jQuery(tb_div).dialog({
		bgiframe: true,
		height: 430,
		width: 500,
		close: function() {tb_div.innerHTML=''},
		modal: true
	});
	
	new Ajax.Updater(tb_div, '/talkBackForm', { evalScripts: true})
	
}

	
function post_new_ride() {

	jQuery('.date-pick').datepicker({dateFormat: 'yy-mm-dd', minDate: null, maxDate: 0, showOn: 'button', buttonImage: '/images/calendar.png', buttonImageOnly: true, buttonText: 'choose date'});
			
	jQuery("#start_arrival_date_early").datepicker('option', {onClose: function(e, c){
		jQuery('#start_arrival_date_late').datepicker('option', {minDate: new Date(e)})
		jQuery('#start_d_date_early').datepicker('option', {minDate: new Date(e), maxDate: null})
		jQuery('#start_d_date_late').datepicker('option', {minDate: new Date(e), maxDate: null})
		
		//jQuery('#end_arrival_date_early').datepicker('option', {minDate: new Date(e)})
		
	}});
	
	jQuery("#start_arrival_date_late").datepicker('option', {onClose: function(e, c){
		jQuery('#start_arrival_date_early').datepicker('option', {maxDate: new Date(e)})
	}});

jQuery("#start_d_date_early").datepicker('option', {minDate:0, maxDate: null, onClose: function(e, c){
		jQuery('#start_d_date_late').datepicker('option', {minDate: new Date(e)})
		jQuery('#end_arrival_date_early').datepicker('option', {minDate: new Date(e)})
		
		jQuery('end_arrival_date_early').value = $('start_d_date_early').value
	}});
	

	jQuery("#start_d_date_late").datepicker('option', {minDate:0, maxDate: null, onClose: function(e, c){
		jQuery('#start_d_date_early').datepicker('option', {maxDate: new Date(e)})
	}});

	// destination
jQuery("#end_arrival_date_early").datepicker('option', {minDate: 0, maxDate: null, onClose: function(e, c){
		jQuery('#end_arrival_date_late').datepicker('option', {minDate: new Date(e)})
		//jQuery('#end_d_date_early').datepicker('option', {minDate: new Date(e), maxDate: null})
		//jQuery('#end_d_date_late').datepicker('option', {minDate: new Date(e), maxDate: null})
	}});
	
	jQuery("#end_arrival_date_late").datepicker('option', {minDate: 0, maxDate: null, onClose: function(e, c){
		jQuery('#end_arrival_date_early').datepicker('option', {maxDate: new Date(e)})
	}});




	jQuery('#here_yes').bind('click', function(e) {
		jQuery('#start_arrival_date_early').datepicker('option', {minDate: null, maxDate: 0})
		jQuery('#start_arrival_date_late').datepicker('option', {minDate: null, maxDate: 0})
		jQuery('#start_d_date_early').datepicker('option', {minDate: null, maxDate: null})
		jQuery('#start_d_date_late').datepicker('option', {minDate: null, maxDate: null})
	});

	jQuery('#not_here').bind('click', function(e) {
		jQuery('#start_arrival_date_early').datepicker('option', {minDate: 0, maxDate: null})
		jQuery('#start_arrival_date_early').value=''
		jQuery('#start_arrival_date_late').datepicker('option', {minDate: 0, maxDate: null})
		jQuery('#start_d_date_early').datepicker('option', {minDate: 0, maxDate: null})
		jQuery('#start_d_date_late').datepicker('option', {minDate: 0, maxDate: null})
	});


}
	


function in_array(string, array) {
	for (i = 0; i < array.length; i++) {
		if(array[i] == string) {
			return true;
		}
	}
	return false;
}

function updateLocation(address) {
		
	//var address = document.dashUpdateForm.dashQ.value;
	//loadProfile(tripUsername)
	
	
	
	mainTabs('homeLink', 'home')
	postGeoSuccess = function () {
		
		
		
		// Beta
		
		locationArr = null;
		locationArr = new Array();
		in_future = false
		// Open the students.xml file
		var location_xml_url = "locations_xml?username=" + tripUsername
		jQuery.get(location_xml_url,{},function(xml){
	
			var arr_num = 0
				
			// Run the function for each location tag in the XML file
		
			var place_geocoded = place.address
			jQuery('location',xml).each(function(i) {

				locationArr[arr_num] = {
					place:jQuery(this).find("place").text(), 	
					id:jQuery(this).find("id").text(),
					number:jQuery(this).find("number").text(),
					type:jQuery(this).find("type").text(), 
					mpg:jQuery(this).find("mpg").text()
				};
			
				// Use it!

				if (locationArr[arr_num]['place']==place_geocoded && in_future==false) {
				//if (locationArr[arr_num]['place']==place_geocoded) {
					in_future = true
					future_arr_key = arr_num
				}
			
				arr_num = arr_num + 1;
		
			});
			
			if (in_future==true) {
				// use this in I've Arrive link
				edit_location_dialog(locationArr[future_arr_key]['number'], 'arrived')
			} else {
				// some code can go here
				
				// this is the regular, default, classic
				$('statusDiv').style.display='none'; 
				$('dash_container').hide();
				
				//show map with marker on it
				jQuery('#map').fadeIn('slow'); 
				jQuery('#profileTabs').fadeOut('fast'); 
				$('content').style.width='500px'; 
				//jQuery('#toolBar').slideDown('fast'); 
				
				if(typeof(map)=="undefined") {
					oonLoad();
				}
				
				sizeMap()
				updateMarker = new google.maps.Marker(point);
				map.addOverlay(updateMarker);
				updateMarker.openInfoWindowHtml("<strong>" + place.address + "</strong>");
							
				jQuery('.date-pick').datepicker({dateFormat: 'yy-mm-dd', minDate: null, maxDate: 0, showOn: 'button', buttonImage: '/images/calendar.png', buttonImageOnly: true, buttonText: 'choose date'});

				jQuery("#start_date").datepicker('option', {onClose: function(e, c){
					jQuery('#end_date').datepicker('option', {minDate: new Date(e)})
					jQuery('#d_start_date').datepicker('option', {minDate: new Date(e), maxDate: null})
					jQuery('#d_end_date').datepicker('option', {minDate: new Date(e), maxDate: null})
				}});
				
				jQuery("#end_date").datepicker('option', {onClose: function(e, c){
					jQuery('#start_date').datepicker('option', {maxDate: new Date(e)})
				}});
			
				jQuery("#d_start_date").datepicker('option', {maxDate: null, onClose: function(e, c){
					jQuery('#d_end_date').datepicker('option', {minDate: new Date(e)})
				}});
				

				jQuery("#d_end_date").datepicker('option', {maxDate: null, onClose: function(e, c){
					jQuery('#d_start_date').datepicker('option', {maxDate: new Date(e)})
				}});

				//jQuery("#datepicker").datepicker({altField: '#alternate', altFormat: 'DD, d MM, yy'});
							
			
				jQuery('#r_current').bind('click', function(e) {
					jQuery('#start_date').datepicker('option', {minDate: null, maxDate: 0})
					jQuery('#end_date').datepicker('option', {minDate: null, maxDate: 0})
					jQuery('#d_start_date').datepicker('option', {minDate: null, maxDate: null})
					jQuery('#d_end_date').datepicker('option', {minDate: null, maxDate: null})
				});

				jQuery('#r_future').bind('click', function(e) {
					jQuery('#start_date').datepicker('option', {minDate: 0, maxDate: null})
					jQuery('#start_date').value=''
					jQuery('#end_date').datepicker('option', {minDate: 0, maxDate: null})
					jQuery('#d_start_date').datepicker('option', {minDate: 0, maxDate: null})
					jQuery('#d_end_date').datepicker('option', {minDate: 0, maxDate: null})
				});
				
					
				var container = $("newPlace");      
				var div = document.createElement("div");
				div.innerHTML = "<strong>" + place.address + "</strong>";
				container.replaceChild(div, container.firstChild);
				$('destForRide').innerHTML = "<strong>" + place.address + "</strong>";

				document.updateFullForm.latlong.value = latlong			
				document.updateFullForm.place.value = place.address

				if (typeof city!="undefined") {
					document.updateFullForm.city.value = city
				}
				if (typeof state!="undefined") {
					document.updateFullForm.state.value = state
				}
				document.updateFullForm.country.value = country
				$("fillInfo").show(); 
				
				
				
				
				
				
				
			}
		});
		
		// Beta
		
		
		
		
		
		
		
		
		
		

		 
	  
	}
	
	geocoder.getLocations(address, parseGeocode);
}

function futureUpdateRefresh(form) {
	
	var address = document.updateFullForm.from_home.value;
	
	if (address!="") {
	
		postGeoSuccess = function () {
			
			var stringContinue = ""
			stringContinue += "&ride_latlong=" + latlong
			stringContinue += "&ride_place=" + place.address

			if (typeof city!="undefined") {
				stringContinue += "&ride_city=" + city
			}
			if (typeof state!="undefined") {
				stringContinue += "&ride_state=" + state
			}
			stringContinue += "&ride_country=" + country

			new Ajax.Updater('profileContainer', '/homeFunctions?' + $(form).serialize() + stringContinue, {
				onComplete: function(result) {
	
					//loadProfile(tripUsername)
					new Ajax.Updater('dash', '/dash.php');
					//toggleItems(this, 'toolBar'); 
					jQuery('#map').fadeOut('slow'); 
					jQuery('#profileTabs').fadeIn('fast'); 
					$('content').style.width='100%'
				}
			});

		}
		
		geocoder.getLocations(address, parseGeocode);
	} else {
		
		new Ajax.Updater('profileContainer', '/homeFunctions?' + $(form).serialize(), {
			onComplete: function(result) {
				
				//loadProfile(tripUsername)

				new Ajax.Updater('dash', '/dash.php', {
					onComplete: function(result) {
						//toggleItems(this, 'toolBar'); 
						jQuery('#map').fadeOut('slow'); 
						jQuery('#profileTabs').fadeIn('fast'); 
						$('content').style.width='100%'
					}
				
				});
				
					

			}
		});
			
			
			
	}

}

function stayTip(form) {

	var input = form['stayAddress2'];
	var address = $F(input)

	if (address!="") {
	
		postGeoSuccess = function () {
			
			var stringContinue = ""
			stringContinue += "&stay_latlong=" + latlong
			stringContinue += "&stay_lat=" + lat
			stringContinue += "&stay_lng=" + lng
			stringContinue += "&stay_place=" + place.address

			if (typeof streetline!="undefined") {
				stringContinue += "&stay_streetline=" + streetline
			}
			if (typeof city!="undefined") {
				stringContinue += "&stay_city=" + city
			}
			if (typeof state!="undefined") {
				stringContinue += "&stay_state=" + state
			}
			stringContinue += "&stay_country=" + country
		
			advAJAX('/homeFunctions?' + form.serialize() + stringContinue, form)

		}
		
		geocoder.getLocations(address, parseGeocode);
	} else {
		alert("Location not recognized")
	}
}

function userMap(username) {
	
	if (username=="current") {
		username=tripUsername
	}
	
	new Ajax.Request('/userMap?username=' + username, {
	  onSuccess: function(transport) {
		  eval(transport.responseText)
	  }
	});


}

function showHitchSpots(centerLat, centerLng, distance) {
	/*
	var SW = map.getBounds().getSouthWest() 
	var NE = map.getBounds().getNorthEast() 
	var NW = new GLatLng(NE.lat(),SW.lng()); 
	var latHeight = SW.distanceFrom(NW); //meters 
	var lonWidth = NE.distanceFrom(NW); //meters 
	var latHeightMiles = latHeight / 1600; 
	var lonWidthMiles = lonWidth / 1600; 
	*/

	new Ajax.Request('/hitchSpots?lat=' + centerLat + "&lng=" + centerLng + "&distance=" + distance, {
	  onSuccess: function(transport) {
		  eval(transport.responseText)
	  }
	});


}

function showStaySpots(centerLat, centerLng, distance) {
	
	new Ajax.Request('/staySpots?lat=' + centerLat + "&lng=" + centerLng + "&distance=" + distance, {
	  onSuccess: function(transport) {
		  eval(transport.responseText)
	  }
	});
	
}
	
function rideLoad(rideID) {
	
	
	
	if (!$('tripDiv')) {
		new Ajax.Updater('travelInfo', '/travelContent.php', {
			onComplete: function(result) {
				rideLoad(rideID);
				
			}
		});
		
	} else {
	

		location.hash = "rides/" + rideID
		$('alertBorder').className = "alertBorderActive";
		$('taskStatus').innerHTML = "loading ride..."
		$('taskStatus').style.display="inline"
		

		
		new Ajax.Request("/rideContent.php?id=" + rideID, {
			onSuccess: function(transport) {
				//eval(transport.responseText)
					
					
					
				rideResult = transport.responseText

				javaHtmlSplit = rideResult.split("####ride javascript####")
				
				rideStops = new Array();
				for (x=1; x<javaHtmlSplit.length; x++) {
					eval(javaHtmlSplit[x])
				}

				// check if page was linked to directly for a ride
				//sideToggle('travelLink', 'travelDiv')
				
				mainTabs('travelLink', 'travel')
				
					
				toggleDivs('travOptionDiv', 'tripDiv')
				
					
				//tripDivContent = "<a href=\"#\" onclick=\"$(\'sideHolder\').style.display = \'block\'; toggleDivs(\'travOptionDiv\', \'rides\'); sizeMap(); map.clearOverlays(); addStartEndMarkers(); ridesToMap()\">&laquo;Back to rides</a><br /><br />" + javaHtmlSplit[0]
				tripDivContent = "<a href=\"#\" onclick=\"toggleDivs(\'travOptionDiv\', \'optionContainer\'); sizeMap(); map.clearOverlays(); addStartEndMarkers(); ridesToMap()\">&laquo;Back to rides</a><br /><br />" + javaHtmlSplit[0]
					
				sizeMap()
				$("tripDiv").innerHTML = tripDivContent;

				// don't create window if it's the current user's ride
				//if (rideInfo['current']['username'].toLowerCase()=="nouser" || rideInfo['current']['username'].toLowerCase()!=tripUsername) {
			/*
				if (rideInfo['current']['username'].toLowerCase()!=tripUsername) {  // bandR
					//Modal Window
					var modal = new Control.Modal($('messageSendingBox'),{
						overlayOpacity: 0.75,
						className: 'msgModal',
						fade: true
					});
				}
*/
				// Map out Ride
				map.clearOverlays(); 
				//tripMap(); // add markers
				// Add markers for individual trip posting
				pausePoint = new Array();
				for (i=0; i<rideStops.length; i++) {
					pausePoint[i] = new google.maps.LatLng(rideStops[i]['lat'], rideStops[i]['lng'])
					map.addOverlay(createRegMarker(pausePoint[i], "Stopping here", iconStop)); 
				}

				rideStartPoint = new google.maps.LatLng(rideInfo['current']['start_lat'], rideInfo['current']['start_lng'])
				map.addOverlay(createRegMarker(rideStartPoint, "<strong>starting " + rideInfo['current']['start_city'] + "</strong><br>Going to: " + rideInfo['current']['end_city'] + "<br>leaving on: " + rideInfo['current']['leave_date'] + "<br>posted by:" + rideInfo['current']['username'] + "<br>" + rideInfo['current']['cost'] + "", iconStart)); 

				rideEndPoint = new google.maps.LatLng(rideInfo['current']['end_lat'], rideInfo['current']['end_lng'])
				map.addOverlay(createRegMarker(rideEndPoint, "This is where it ends", iconEnd));
				
				
				
				
				
				
				//mileGet(); // add route polyline and calculate/display gas, mileage, time estimate
				var startFromDirection = rideInfo['current']['start_city'] + ", " + rideInfo['current']['start_state']
				var endFromDirection = rideInfo['current']['end_city'] + ", " + rideInfo['current']['end_state']
				
				tripDirections = new Array();
				i=0;
				
				while (i<=rideStops.length && rideStops.length!=0) { 
				
					iOffset = (i-1)
					
					startDir = (i==0) ? startFromDirection : rideStops[iOffset]['city'] + ", " + rideStops[iOffset]['state'];
					endDir = (i==rideStops.length) ? endFromDirection : rideStops[i]['city'] + ", " + rideStops[i]['state'];
					
					dirFill = startDir + " to " + endDir
					tripDirections[i] = new google.maps.Directions();
					tripDirections[i].load(dirFill,{ getPolyline:true, getSteps:true });
					
					if (i==rideStops.length) {
						google.maps.Event.addListener(tripDirections[i], "load", onTripDirectionsLoad);
					}
					i++
				}
				if (i==0) {
					tripDirections = null;
					tripDirections = new google.maps.Directions();
					tripDirections.load(startFromDirection + " to " + endFromDirection,{ getPolyline:true, getSteps:true });
					google.maps.Event.addListener(tripDirections, "load", onTripDirectionsLoad);
				}
				

				$('alertBorder').className = "alertBorderFinish";
				$('taskStatus').innerHTML = "Finished Loading Ride!";
				setTimeout('$(\'alertBorder\').className = \'alertBorder\'; $(\'taskStatus\').style.display=\'none\'',500)
					  
		  }
		});
	}

}


function dialog_box(url, title) {
	
	d_div = document.createElement("div");
	d_div.setAttribute("title",title)
	d_div.innerHTML = "loading..."
	jQuery(d_div).dialog({
		bgiframe: true,
		height: 430,
		width: 500,
		close: function() {d_div.innerHTML=''},
		modal: true
	});
	
	new Ajax.Updater(d_div, url, { evalScripts: true})
	
}

function onTripDirectionsLoad() {

	tripMeters = 0
	tripSeconds = 0

	goodPoly = new Array();

	i = 0

	while (i<=rideStops.length && rideStops.length!=0) {
		goodPoly[i] = tripDirections[i].getPolyline();
		map.addOverlay(goodPoly[i])
		tripMeters += tripDirections[i].getDistance().meters
		tripSeconds += tripDirections[i].getDuration().seconds
		var bounds = tripDirections[i].getBounds(); 
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds) ); 
		i++;
	}

	if (i==0) {
		goodPoly = null;
	
		goodPoly = tripDirections.getPolyline();
		map.addOverlay(goodPoly)
		
		var bounds = tripDirections.getBounds(); 
		map.setCenter( bounds.getCenter(), map.getBoundsZoomLevel(bounds) ); 
		
		tripMeters = tripDirections.getDistance().meters
		tripSeconds = tripDirections.getDuration().seconds
	}
	bounds.extend(rideStartPoint)
	bounds.extend(rideEndPoint)
	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

	totalMiles = Math.round(tripMeters/1609.344)
	totalHours = Math.floor(tripSeconds/60/60)
	extraMinutes = (Math.floor(tripSeconds/60))%60
	
	if (totalHours>23) {
		totalDays = Math.floor(totalHours/24)
		totalHours = totalHours%24 + Math.round(extraMinutes/60)
		totalTime = totalDays + " days " + totalHours + " hours"
	} else {
		totalTime =  totalHours + " hours " + extraMinutes + " minutes"
	}
	
	carMPG = rideInfo['current']['mpg']
	gallonCost = 2.50
	costTrip = Math.round((totalMiles/carMPG)*gallonCost)   
	$("justDistance").innerHTML = "<span class='simpetext'> <strong>Total:</strong> " + totalMiles + " miles (" + totalTime + "). Around $" + costTrip + " for gas at $" + gallonCost + " a gallon getting " + carMPG + "mpg (<strong>" + rideInfo['current']['cost'] + " for you</strong>)</span>";


}
	
function transitLocationAdd() {
	
	if (!$('transitOrigin').value || !$('transitDestination').value) {
		alert("You must enter a start and end location.")
		return false;
	} else {
		transitLocations = [$('transitOrigin').value, $('transitDestination').value];
	}
	
	new multiGeocode(transitLocations, function (resultArray) {

		x=0;
		resultArray.each(function(s) {
			if (x==0) {
				$("aPlace").value += s['place'] + ";"
				transit_place1 = s['place']
				$("aAddress").value += s['street_address'] + ";"
				$("aCity").value += s['city'] + ";"
				$("aState").value += s['state'] + ";"
				$("aCountry").value += s['country'] + ";"
				$("aPoint").value += s['coor'] + ";"
				
				$("oneCost").value += $('onewayCost').value + ";"
				$("roundCost").value += $('roundtripCost').value + ";"
				$("flowAll").value += $('flow').value + ";"
			} else {
				$("bPlace").value += s['place'] + ";"
				transit_place2 = s['place']
				$("bAddress").value += s['street_address'] + ";"
				$("bCity").value += s['city'] + ";"
				$("bState").value += s['state'] + ";"
				$("bCountry").value += s['country'] + ";"
				$("bPoint")	.value += s['coor'] + ";"
			}
			x++;
		
		});
		
				
		$('saveButton').disabled=false; 
		$('saveButton').value='Save'
			
		var container = $("addedRoutes")
		var div = document.createElement("div");
	/*
		if ($('flow').value=="round") {
			flow = "To/From"
		} else {
			flow = "To"
		}*/
		($('flow').value=="round") ? flow = "To/From" : flow = "To";
		div.innerHTML = transit_place1 + " <strong>" + flow + "</strong> " + transit_place2
		container.appendChild(div);


	});
}

function addTransitAddressToMap(response) {
	
		  //map.clearOverlays();
		  if (!response || response.Status.code != 200) {
			alert("Sorry, we were unable to geocode that address");
		  } else {
	
			place = response.Placemark[0];
			point = new google.maps.LatLng(place.Point.coordinates[1],
								place.Point.coordinates[0]);
			marker = new google.maps.Marker(point);
			
			//structured Information
			var aa, saa, l;
			aa = place.AddressDetails.Country.AdministrativeArea;
			if ( aa ) {
				state = aa.AdministrativeAreaName;
				saa = aa.SubAdministrativeArea;
				if ( saa ) {
					county = saa.SubAdministrativeAreaName;
					l = saa.Locality;
					if (l) {
						city = l.LocalityName;
						if ( l.Thoroughfare ) {
								streetLine = l.Thoroughfare.ThoroughfareName;
						}
						if ( l.PostalCode ) {
								zip = l.PostalCode.PostalCodeNumber;
						}
					} else {
						if (saa.Thoroughfare) {
								streetLine = saa.Thoroughfare.ThoroughfareName;
						}
						if (saa.PostalCode) {
								zip = saa.PostalCode.PostalCodeNumber;
						}
					}
				} else {
					l = aa.Locality;
					if (l) {
						city = l.LocalityName;
						if ( l.Thoroughfare ) {
								streetLine = l.Thoroughfare.ThoroughfareName;
						}
						if (l.PostalCode) {
								zip = l.PostalCode.PostalCodeNumber;
						}
					} else {
						if (aa.Thoroughfare) {
								streetLine = aa.Thoroughfare.ThoroughfareName;
						}
						if (aa.PostalCode) {
								zip = aa.PostalCode.PostalCodeNumber;
						}
					}
				}
			}		
	
			country = place.AddressDetails.Country.CountryNameCode;
			
			//map.addOverlay(marker);
			//marker.openInfoWindowHtml("<strong>" + place.address + "</strong>");
			
			point = place.Point.coordinates[1] + "," + place.Point.coordinates[0]
	
			
			//for database entry
			var startPlace = $("aPlace")
			var startAddress = $("aAddress")
			var startCity = $("aCity")
			var startState = $("aState")
			var startCountry = $("aCountry")
			var startPoint = $("aPoint")	
			
			var endPlace = $("bPlace")
			var endAddress = $("bAddress")
			var endCity = $("bCity")
			var endState = $("bState")
			var endCountry = $("bCountry")
			var endPoint = $("bPoint")
			
			var oneCost = $("oneCost")
			var roundCost = $("roundCost")
			var flowAll = $("flowAll")
			
			if (x!=1) {	//insert geocode 1 here
			
				map.addOverlay(marker);
				marker.openInfoWindowHtml("<strong>" + place.address + "</strong>");
				place1 = place.address
				startPlace.value += place.address + ";"
				
				FromString = "?style=script"
				if (typeof streetLine!="undefined") {
					FromString += "&address1=" + streetLine
					startAddress.value += streetLine + ";"
				} else {
					startAddress.value += "n/a" + ";"
				}
				if (typeof city!="undefined") {
					FromString += "&city1=" + city 
					startCity.value += city + ";"
				} else {
					startCity.value += "n/a" + ";"
				}
				if (typeof state!="undefined") {		
					FromString += "&state1=" + state
					startState.value += state + ";"
				} else {
					startState.value += "n/a" + ";"
				}
				if (typeof country!="undefined") {
					FromString += "&country1=" + country
					startCountry.value += country + ";"
				} else {
					startCountry.value += "n/a" + ";"
				}
				if (typeof point!="undefined") {
					FromString += "&point1=" + point
					startPoint.value += point + ";"
				} else {
					startPoint.value += "n/a" + ";"
				}
				
				var oner = $('onewayCost')
				if (typeof oner.value!="undefined" && oner.value!="") {
					oneCost.value += $('onewayCost').value + ";"
				} else {
					oneCost.value += "n/a" + ";"
				}
				
				var rounder = $('roundtripCost')
				if (typeof rounder.value!="undefined" && rounder.value!="") {
					roundCost.value += $('roundtripCost').value + ";"
				} else {
					roundCost.value += "n/a" + ";"
				}
				
				var flow = $('flow')
				if (flow.value=="round") {
					flowAll.value += "round" + ";"
				} else {
					flowAll.value += "one" + ";"
				}
				
				
				//$("aCheck").disabled=false
				var thecheck = $('aCheck')
				
				$('saveButton').disabled=false; 
				$('saveButton').value='Save'
				
				
				
				
				
				
				
				
				
				
				//$("saveButton").value="Save"
				//$("saveButton").disabled=false
				
				x = 1
				
				if (document.transitSearchForm.destination.value!="") {
					var address = document.transitSearchForm.destination.value;
					geocoder.getLocations(address, addTransitAddressToMap);
				} else {
					//window.location = FromString
					alert("enter a destination")
				}
			} else { //insert geocode 2 here
				map.addOverlay(marker);
				place2 = place.address
				endPlace.value += place.address + ";"
				ToString = ""
				if (typeof streetLine!="undefined") {
					ToString += "&address2=" + streetLine
					endAddress.value += streetLine + ";"
				} else {
					endAddress.value += "n/a" + ";"
				}
				if (typeof city!="undefined") {
					ToString += "&city2=" + city 
					endCity.value += city + ";"
				} else {
					endCity.value += "n/a" + ";"
				}
				if (typeof state!="undefined") {		
					ToString += "&state2=" + state
					endState.value += state + ";"
				} else {
					endState.value += "n/a" + ";"
				}
				if (typeof country!="undefined") {
					ToString += "&country2=" + country
					endCountry.value += country + ";"
				} else {
					endCountry.value += "n/a" + ";"
				}
				if (typeof point!="undefined") {
					ToString += "&point2=" + point
					endPoint.value += point + ";"
				} else {
					endPoint.value += "n/a" + ";"
				}
				
				// add to visual list
				var container = $("addedRoutes")
				var div = document.createElement("div");
				if (document.transitSearchForm.flow.value=="round") {
					flow = "To/From"
				} else {
					flow = "To"
				}
				div.innerHTML = place1 + " <strong>" + flow + "</strong> " + place2
            	container.appendChild(div);
			}
	
		  }
	}

function showTransitLocation() {

  x=0
  var address = document.transitSearchForm.origin.value;
  geocoder.getLocations(address, addTransitAddressToMap);  
	
}	
	
// *** NON GEO ***
/*
function editDivOpen(id) {
	var frameSrc = "/editLocation?id=" + id
	$('updateIframe').src=frameSrc
	$('updateLocationDiv').style.display='block';
	sizeMap()
}
*/

// Beta
function loading_show(area, display) {
	
	if (typeof(display)=="undefined" || display=="simple") {
		var loading_display = "<img src=\"/images/th_loader.gif\" />";
	}
	
	jQuery('#' + area).innerHTML = loading_display
	
	
}
	
function advAJAX(ajaxurl, responseArea, responseContent, responseLength) {
	
	loadingMsg = "loading...";
	endLength = "200";

	$('alertBorder').className = "alertBorderActive";
	$('taskStatus').innerHTML = loadingMsg
	$('taskStatus').style.display="inline"

	new Ajax.Request(ajaxurl, {
		onSuccess: function(transport) {
			
			$('alertBorder').className = "alertBorderFinish";
			$('taskStatus').innerHTML = "finished!"		
				
			freshResponseContent = "loading..."
			
			if (typeof(responseArea)=="string") {
				var fillArea = $(responseArea)
			} else {
				
				var fillArea = responseArea
			}
			
			if (typeof responseContent!="undefined" && responseContent!="") {
				new Ajax.Request(responseContent, {
					onSuccess: function(transport) {
						
						freshResponseContent = transport.responseText
						fillArea.innerHTML = freshResponseContent
					}
				});
			} else {
				freshResponseContent = transport.responseText
			}

			/*
			if (typeof responseLength!="undefined") {
				//$(responseArea).innerHTML = responseContent
			}
			*/
			fillArea.innerHTML = freshResponseContent

			setTimeout("$('alertBorder').className = 'alertBorder'; $('taskStatus').style.display='none'", endLength)
		}
	});

}

function toggleItems(chosenItem, chosenGroup, unselectedClass, selectedClass) {
	tabSelectors = $$('#' + chosenGroup + ' a');
	for(i=0; i<tabSelectors.length; i++) {
		tabSelectors[i].style.fontWeight='normal'//unselectedClass
	}
	//chosenItem.className=selectedClass
	if (chosenItem!="none") {
		chosenItem.style.fontWeight='bold'
	}
}

function toggleDivs(chosenDivClassGroup, chosenDiv) {

	divSelectors = $$('div.' + chosenDivClassGroup);
	for(i=0; i<divSelectors.length; i++) {
		divSelectors[i].style.display='none'
	}
	$(chosenDiv).style.display='block'

}



function edit_location_dialog(location_number, edit_or_arrived) {
		
	if (typeof(edit_or_arrived)=="undefined" || edit_or_arrived=='edit') {
		var title = 'Edit this location'
		var url = 'editLocationBeta?id=' + location_number
	} else if (edit_or_arrived=='arrived') {
		var title = 'Update this location'
		var url = 'editLocationBeta?just_arrived=yes&id=' + location_number
	}
	
	dia_div = document.createElement("div");
	dia_div.setAttribute("title",title)
	dia_div.innerHTML = "loading..."
	jQuery(dia_div).dialog({
		bgiframe: true,
		height: 430,
		width: 500,
		close: function() {dia_div.innerHTML=''},
		modal: true
	});

	new Ajax.Updater(dia_div, url, { evalScripts: true})	
	
	
	
	//new Ajax.Updater($(this).ancestors()[1].down('div.editStuff'), 'editLocationBeta?id=".$location['number']."', { evalScripts: true})
}

function loadProfile(username) {
	
	var continueLoading = true;
	location.hash = "people/" + username
	
	// dead for dash
	//if (username.toLowerCase()==tripUsername.toLowerCase()) {
	if (username.toLowerCase()==2) {
		
		var thisProfileDiv = $('profileContainer');
		$('memberContainer').innerHTML = "";
		
		if (thisProfileDiv.innerHTML.length>1000) {
			var continueLoading = false;
		} else if (typeof usersProfileTemp!="undefined") {
			var continueLoading = false;
			thisProfileDiv.innerHTML = usersProfileTemp;
		} else {
			thisProfileDiv.innerHTML = "<img src=\"/images/kangourousLoad.gif\" \> ...hopping to it."
		}
		
		//sideToggle('homeLink', 'homeDiv')
			mainTabs('homeLink', 'home')
		$$("#homeContent > div").invoke('hide')
		$('profileContainer').show()
		
	} else {
		
		$('memberSelect').innerHTML = username;
		
		if ($('profileContainer').innerHTML.length>1000) {
			usersProfileTemp = $('profileContainer').innerHTML;
			$('profileContainer').innerHTML = "";
		}
		
		var thisProfileDiv = $('memberContainer');
		thisProfileDiv.innerHTML = "<img src=\"/images/kangourousLoad.gif\" \> ...hopping to it."
		
		//sideToggle('peopleLink', 'peopleDiv')
		mainTabs('peopleLink', 'people')
		toggleItems($('memberSelect'), 'peopleSelect'); 
		toggleDivs('peopleDivs', 'memberContainer')
	}
	
	
	map.clearOverlays()
	userMap(username)
	//profileKML = new google.maps.GeoXml('http://www.triphopping.com/userKML.php?n=' + username);
	//profileLineKML = new google.maps.google.maps.GeoXml('http://www.triphopping.com/userLineKML.php?n=' + username);
	//map.addOverlay(profileKML);
	//map.addOverlay(profileLineKML);
	
	jQuery('#map').fadeOut('fast');
	$('content').style.width='100%'
	
	
	
	if (continueLoading==true) {
	
		$('alertBorder').className = "alertBorderActive";
		$('taskStatus').innerHTML = "loading profile..."
		$('taskStatus').style.display="inline"
		
		
		
		
		
		
		new Ajax.Updater(thisProfileDiv, '/profileContent.php?name=' + username, {
			evalScripts:true,
			onComplete: function(result) {
				
				/*
				if ($('messageSend')) {
					var modal = new Control.Modal($('messageSend'),{
						overlayOpacity: 0.75,
						className: 'msgModal',
						fade: true
					});		
				}
				
				if ($('friendDetailBox')) {
					var modal = new Control.Modal($('friendDetailBox'),{
						overlayOpacity: 0.75,
						className: 'msgModal',
						fade: true
					});		
				}
				*/
					
					

					
				
				$('alertBorder').className = "alertBorderFinish";
				$('taskStatus').innerHTML = "finished!";
				setTimeout('$(\'alertBorder\').className = \'alertBorder\'; $(\'taskStatus\').style.display=\'none\'','10')
			}
		});
		
		
	}
	
	
	
	/*
	
	if ($('profilePhotos')) {
		var modal = new Control.Modal($('profilePhotos'),{
			overlayOpacity: 0.75,
			position: [150, 30] ,
			className: 'picturesModal',
			fade: true
		});		
	}
		
	sizeMap();
	*/

}

function tipLoad(tipID) {
	
	new Ajax.Request('/tipPage?id=' + tipID, {
	  onSuccess: function(ajaxResult) {
		  
		  //sideToggle('travelLink', 'tipDiv');
		  toggleDivs('travOptionDiv', 'tipDiv')
		  $('tipDiv').innerHTML = "<a href=\"#\" onclick=\"toggleDivs(\'travOptionDiv\', \'optionContainer\'); sizeMap(); map.clearOverlays(); addStartEndMarkers(); ridesToMap()\">&laquo;Back to rides</a><br /><br />" + ajaxResult.responseText;

	  }
	});
	
}

// disable enter key from sending a bunk form  
function handleEnter (field, event, task) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		if (task=="go") {
			travel($('originT').value, $('destT').value)
		} else if (task=="stay") {
			//travel($('origin').value, $('stayT').value)
			stay($('stayT').value);
		} else if (task=="explore") {
			explore($('exploreT').value);
		} 
		var i;
		for (i = 0; i < field.form.elements.length; i++)
			if (field == field.form.elements[i])
				break;
		i = (i + 1) % field.form.elements.length;
		field.form.elements[i].focus();
		return false;
		
		} else {
	return true;
		}
		
}   

//functions taken from travelContent
function dateRangeToggle(toggler, toggly) {

	//toggler = $(toggler)
	toggly = $(toggly)
	
	if (toggler.selectedIndex==1) {
		toggly.disabled=false
		toggly.style.visibility = 'visible';
	} else {
		toggly.disabled='disabled';
		toggly.style.visibility = 'hidden';
	} 
	
}

// Functions used within current origin and destinations
function showCraigContent(content) {    
	var container = $("craigFull");
	container.show()
	//$('map').style.display='none'
	var div = document.createElement("div");
	div.innerHTML = content
	container.replaceChild(div, container.firstChild);
	sizeMap()
}
    
function showMap() {
	$("craigFull").hide()
	sizeMap();
}

function mainTabs(type, visibleDiv) {

	// *broken
	if (typeof(map)!="undefined") {
		clearGooglebar();
	}

	//jQuery('#toolBar').slideUp('fast')

	if (type=='homeLink') {
		jQuery('#profileTabs').fadeIn('fast'); 
		jQuery('#map').fadeOut('fast');
		$('content').style.width='100%'
	} else if (type=='peopleLink') {
		jQuery('#map').fadeOut('fast');
		$('content').style.width='100%'
		if($('memberSelect').style.fontWeight=='bold' || $('peopleContent').innerHTML.length<100) {
			if (!$('friend_feed')) {
				jQuery('#everybodySelect').click();
			} else {
				jQuery('#friend_feed').click();
			}
		} else if ($('friend_feed') && $('friend_feed').style.fontWeight=='bold') {
			jQuery('#friend_feed').click();
		}
	} else {
		//jQuery('#map').fadeIn('normal');
		
		$('map').show()
		if(typeof(map)=="undefined") {
			oonLoad()
		}
		
		
		$('content').style.width = '500px';
	}

	recentToggleLink = type
	recentToggleDiv = visibleDiv

	$$('#mainNav > li').invoke('removeClassName', 'selectedTab'); 
	$(type).addClassName('selectedTab');
	
	$$('#content > div').invoke('hide')
	//$$('div.' + visibleDiv).invoke('show')
	//$(visibleDiv).show()
		
		
	jQuery('.' + visibleDiv).each(function(i) {
	  //jQuery(this).fadeIn('fast')
		jQuery(this).show()
	});

	sizeMap()

}

function titleToggle(item, container) {
	$$('#' + container + ' > a').invoke('removeClassName', 'selectedSecond'); 
	item.addClassName('selectedSecond');
}

function toggleRecent(chosenItem) {
	tabSelectors = $$('#recentFilter a');
	for(i=0; i<tabSelectors.length; i++) {
		tabSelectors[i].className="";
	}
	chosenItem.className='filterSelected'

}

function saveCheck() {
	var thecheck = $('rideCheck')
	var saveButton = $('rideSaveButton')
	
	if (thecheck.checked==true) {
		saveButton.disabled=false; 
		saveButton.value='Save'
	} else {
		saveButton.disabled=true; 
		saveButton.value='Check the box first!'
	}
}

function radio_checker() {
	if (document.ridePostForm.custom_amount.checked) {
		document.ridePostForm.custom_donation.disabled = false;
		document.ridePostForm.custom_donation.focus();
		$('mpgDiv').style.display='none';
	} else if (document.ridePostForm.gasSplit.checked) {
		document.ridePostForm.custom_donation.disabled = true;
		$('mpgDiv').style.display='block';
	} else {
		document.ridePostForm.custom_donation.disabled = true;
		$('mpgDiv').style.display='none';
	}
}
	
function csGroups(gid, divToFill, num_entries) { 
	
	csIDs=null
    csIDs=new Array()
	
	groupURL = "http://www.couchsurfing.org/feeds/group_rss.php?gid=" + gid
	//container = $('CS_group_content')
	//container = divToFill
	divToFill.innerHTML = ""

	var feed = new google.feeds.Feed(groupURL);
	feed.includeHistoricalEntries();
	feed.setNumEntries(num_entries);
	feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
	feed.load(function(result) {
		if (!result.error) {
			for (var i = 0; i < result.feed.entries.length; i++) {
				var entry = result.feed.entries[i];
				var attributes = ["title", "link", "publishedDate", "contentSnippet", "content"]; //added content
				
					csC = entry['content']
                    var csContent = csC.replace(/(<([^>]+)>)/ig,""); 
					var all_content = "<strong>" + entry['title'] + "</strong><br /><br />" + csContent
                    csIDs[csIDs.length] = all_content

					var divFinal = document.createElement("div");
					divFinal.className = "craigEntrye"
					//divFinal.className = "craigEntry"
					//divFinal.setAttribute("onmouseover","showCraigContent(csIDs[" + (csIDs.length-1) + "])")
                    //divFinal.setAttribute("onmouseout","showMap()")
					// onmouseover='showCraigContent(csIDs[" + (csIDs.length - 1) + "])' onmouseout='showMap()'

					//divFinal.innerHTML = "<div style='float:right'><a href='#' onmouseover=\"jQuery(this).next().stop(true, true).animate({opacity: \'show\', top: \'20\'}, \'normal\')\" onmouseout=\"jQuery(this).next().animate({opacity: \'hide\', top: \'-70\'}, \'fast\')\" class='bubMore'>bubble</a><span>" + all_content + "</span></div><strong class='simpetext'><a href='" + entry['link'] + "' target='_blank'>" + entry['title'] + "</a></strong><div class=\"simpetext\"><img src='/images/cs.png' align='absmiddle' /> <a href='" + entry['link'] + "' class='resultLink' style='color:#006600'>" + result.feed.title + "</a> - " + entry['contentSnippet'] + "</div><br />"
						
					divFinal.innerHTML = "<div><strong class='simpetext'><a href=\"" + entry['link'] + "\" target=\"_blank\" onmouseover=\"jQuery(this).next().stop(true, true).animate({opacity: \'show\', top: \'120\'}, \'normal\')\" onmouseout=\"jQuery(this).next().animate({opacity: \'hide\', top: \'-70\'}, \'fast\')\">" + entry['title'] + "</a><span>" + all_content + "</span></strong><div class=\"simpetext\"><img src='/images/cs.png' align='absmiddle' /> <a href='" + entry['link'] + "' class='resultLink' style='color:#006600'>" + result.feed.title + "</a> - " + entry['contentSnippet'] + "</div></div><br />"
						
					//divFinal.innerHTML = "<div onmouseover=\"jQuery(this).next().stop(true, true).animate({opacity: \'show\', top: \'120\'}, \'normal\')\" onmouseout=\"jQuery(this).next().animate({opacity: \'hide\', top: \'-70\'}, \'fast\')\"><strong class='simpetext'><a href=\"" + entry['link'] + "\" target=\"_blank\" >" + entry['title'] + "</a></strong><div class=\"simpetext\"><img src='/images/cs.png' align='absmiddle' /> <a href='" + entry['link'] + "' class='resultLink' style='color:#006600'>" + result.feed.title + "</a> - " + entry['contentSnippet'] + "</div></div><span>" + all_content + "</span><br />"
										
					divToFill.appendChild(divFinal);

			}
		}

	})
}

function search_csGroups(gid, divToFill, cs_query, full) { 
	
	csIDs=null
    csIDs=new Array()
	num_entries = 300;
	
	var s_results = false

	if (full==true) {
		groupURL = "http://www.couchsurfing.org/feeds/group_rss.php?replies=1&gid=" + gid
	} else {
		groupURL = "http://www.couchsurfing.org/feeds/group_rss.php?gid=" + gid
	}
	
	//container = $('CS_group_content')
	//container = divToFill
	divToFill.innerHTML = ""

	var feed = new google.feeds.Feed(groupURL);
	feed.includeHistoricalEntries();
	feed.setNumEntries(num_entries);
	feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
	feed.load(function(result) {
		
		if (!result.error) {
			
			for (var i = 0; i < result.feed.entries.length; i++) {
				var entry = result.feed.entries[i];
				var attributes = ["title", "link", "publishedDate", "contentSnippet", "content"]; //added content
					
					
					var patt1 = new RegExp(cs_query, 'i');
					var c1 = entry['title'].search(patt1);
					var c2 = entry['content'].search(patt1);
					
					
					if  (c1!=-1 || c2!=-1) {
						var s_results = true
						csC = entry['content']
						var csContent = csC.replace(/(<([^>]+)>)/ig,""); 
						csIDs[csIDs.length] = "<strong>" + entry['title'] + "</strong><br /><br />" + csContent

						var divFinal = document.createElement("div");
						divFinal.className = "craigEntry"
						divFinal.setAttribute("onmouseover","showCraigContent(csIDs[" + (csIDs.length-1) + "])")
						divFinal.setAttribute("onmouseout","showMap()")

						divFinal.innerHTML = "<img src='/images/cs.png' align='absmiddle' /> <span class='simpetext'><strong><a href='" + entry['link'] + "' target='_blank' onmouseover='showCraigContent(csIDs[" + (csIDs.length - 1) + "])' onmouseout='showMap()'>" + entry['title'] + "</a></strong> - " + entry['contentSnippet'] + "</span><br /><a href='" + entry['link'] + "' class='resultLink' style='color:#006600'>" + result.feed.title + " (" + entry['publishedDate'].substr(0,11) + ")</a>" + "<br /><br />"
						divToFill.appendChild(divFinal);
					}
					
				
				

			}
			
			if (s_results == false && full==true) {
				search_csGroups($('csSelect').value, $('CS_group_content'), $('cs_g_q').value, false)
			} else if (divToFill.innerHTML=="") {
				divToFill.innerHTML = "no results found for \"" + cs_query + "\" in recent discussions"
			}
		}

	})
}

// fill array with CS groups, pull feeds, rank entries, sort, trim
function externalRidesTest (divy, c_display) {
		
	if (typeof(c_display)=="undefined") {
		content_display = "full"
	} else {
		content_display = "short"
	}
	
	
	csRideArray = null
	csRideArray = new Array
	allRideArrayCount = 0;
	areasSearched = 0;
	
	var runIt = false;
	if (allRideArray.length>0) {
		runIt = true
	}
	
	//create db scheme for this growing list...

	//type: unknown(0), ride(1), request(2), offer(3)
	
	allRideArray[allRideArray.length] = {fullURL:"http://welcomehere.org/cgi-bin/yabb2/YaBB.pl?action=RSSboard;board=need;", urlID:"need", site:"WH", origin_distance:"300", destination_distance:"300", type:2}
	
	allRideArray[allRideArray.length] = {fullURL:"http://welcomehere.org/cgi-bin/yabb2/YaBB.pl?action=RSSboard;board=got;", urlID:"need", site:"WH", origin_distance:"300", destination_distance:"300", type:3}
	
	//http://www.couchsurfing.org/feeds/group_rss.php?gid=658
	// CS Ride Share
	allRideArray[allRideArray.length] = {urlID:"658", site:"CS", origin_distance:"300", destination_distance:"300", type:1}
	

	
	if (typeof(entriesShown)=="undefined") {
		entriesShown = 20;
	}

	if (runIt==true) {
		parseAllRides(divy);	
	}
}

function parseAllRides(divy) { 

	divToFill = $('newIdea')
	divToFill = divy;
	

	
	var urlID = allRideArray[allRideArrayCount]['urlID'] // gid or area
	var site = allRideArray[allRideArrayCount]['site'] // 'CS' or 'CL'
	var feedType = allRideArray[allRideArrayCount]['type'] // 'ride', 1 or 'unknown', 0, 2 request, 3 offer
	
	var originDistance = allRideArray[allRideArrayCount]['origin_distance'] // number in miles
	var destDistance = 100; // junk variable
	
	allRideArrayCount++
	
	// grab CL too, all at once?
	if (site=="CS") {
		var feedURL = "http://www.couchsurfing.org/feeds/group_rss.php?gid=" + urlID
		var numOfEntries = 30
		var daysBack = 14
	} else if (site=="CL") {
		var feedURL = "http://" + urlID + ".craigslist.org/rid/index.rss";
		var numOfEntries = 100
		var daysBack = 14
			// cut off 2 week old entries
	} else {
		var numOfEntries = 100
		var daysBack = 14

	}
	
	if (allRideArray[allRideArrayCount-1]['fullURL']!="" && typeof(allRideArray[allRideArrayCount-1]['fullURL'])!="undefined") {
		var feedURL = allRideArray[allRideArrayCount-1]['fullURL'];
	}
	
	var feed = new google.feeds.Feed(feedURL);
	feed.includeHistoricalEntries();
	feed.setNumEntries(numOfEntries);
	feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
	feed.load(function(result) {
		if (!result.error) {
			

			for (var i = 0; i < result.feed.entries.length; i++) {
				var entry = result.feed.entries[i];
				var attributes = ["title", "link", "publishedDate", "contentSnippet", "content"]; //added content
				
				if (site=="CS") {
					if (feedType==1) {
						var isRide = true;
					} else {
						var isRide = false;
					}
				} else {
					var isRide = true
				}	
				
				

//alert("beta10")
				// ** See if they're talking about a ride **

				// offering a ride?
				offerPhrases = null
				offerPhrases = new Array("offering a ride", "can give you a lift", "anyone need a lift", "anyone need a ride", "offering a lift", "can drive you", "can drive someone", "im driving", "i'm driving", "if you need a ride", "ride offered", "i'll drive my car", "rideshare offered", "give you a ride", "i will be driving", "need a ride?", "ride offer:");
			
				requestPhrases = null
				requestPhrases = new Array("requesting a ride", "i need a ride", "i need a lift", "can someone drive", "i'm looking for a ride", "can drive me", "ride needed:", "give me a ride", "i am looking for a ride", "is anybody driving", "i would love a ride", "ride wanted:", "give me a ride", "need ride", "i am seeking a ride");
			
				ridePhrases = null
				ridePhrases = new Array(" ride ", "anyone need a lift", "anyone needs a lift", "offering a lift", "drive", "road trip", "need a ride");
			
				for (x=0; x<offerPhrases.length; x++) {
					var p1 = new RegExp(offerPhrases[x], 'i');
					var offPh = entry['title'].search(p1);
					var offPh2 = entry['content'].search(p1);
					if (offPh!=-1 || offPh2!=-1) {
						var offerCheck = true;
						isRide = true;
						break;
					} else {
						var offerCheck = false;
					}
				}
				
				for (x=0; x<requestPhrases.length; x++) {
					var p1 = new RegExp(requestPhrases[x], 'i');
					var offPh = entry['title'].search(p1);
					var offPh2 = entry['content'].search(p1);
					if (offPh!=-1 || offPh2!=-1) {
						var requestCheck = true;
						isRide = true;
						break;
					} else {
						var requestCheck = false;
					}
				}
				
				for (x=0; x<ridePhrases.length; x++) {
					var p1 = new RegExp(ridePhrases[x], 'i');
					var offPh = entry['title'].search(p1);
					var offPh2 = entry['content'].search(p1);
					if (offPh!=-1 || offPh2!=-1) {
						isRide = true;
						break;
					} else {
						//isRide = false;
					}
				}
				
			
				//Determine how old
				
				if (feedType==2) {
					var requestCheck = true;
					var offerCheck = false;
				} else if (feedType==3) {
					var offerCheck = true
					var requestCheck = false;
				}
					
				var minutes = 1000 * 60;
				var hours = minutes * 60;
				var days = hours * 24;
				var years = days * 365;
				var t = Date.parse(entry['publishedDate']);
				var now = Date.parse(Date())
				var d = (now-t)/days;
				
				if (d > daysBack) {
					isRide=false
				}					
				
				
				//alert("betaMax")
				
				if (isRide==true) {
					
					
					
					// Rank
						
						// origin proximity to search origin
						// dest prox to search dest
						
						
						
					var patt1 = new RegExp(cityFrom, 'i');
					var r1 = entry['title'].search(patt1);
					var r2 = entry['content'].search(patt1);
					
					if (cityTo!="") {
						var patt2 = new RegExp(cityTo, 'i');
						var r3 = entry['title'].search(patt2);
						var r4 = entry['content'].search(patt2);
					} else {
						var r3 = -1
						var r4 = -1
					}
					
					// qualify origin
					if (r1!=-1 || r2!=-1 || originDistance<30) {
						var rank_origin = 2
					} else if (originDistance<80) {
						var rank_origin = 1
					} else {
						var rank_origin = 0
					}
					
					// qualify destination
					if (r3!=-1 || r4!=-1 || destDistance<70) {
						var rank_dest = 3
					} else {
						var rank_dest = 0
					}
					
					
					
					var entryRank = 1 + rank_origin + rank_dest

					if (site=="CS") {
						entryRank = entryRank + .5
					}									
		
					cRaN = csRideArray.length
					csRideArray[cRaN] = new Array()
			
					//alert(cRaN)
					
					var dateP = Date.parse(entry[attributes[2]])
					
					//filter out 2 week old crap
					// filter out CL low ranks from extra cities away
					
					if (entryRank>2 && entry[attributes[2]]!='') {
						csRideArray[cRaN][0] = entryRank*1000000000000000 + dateP
						
						csRideArray[cRaN][1] = entry[attributes[1]]; // link
						
						
						
						csRideArray[cRaN][2] = entry[attributes[2]]; // publishedDate
						csRideArray[cRaN][3] = entry[attributes[3]]; // contentSnippet
						csRideArray[cRaN][4] = entry[attributes[0]]; // title
						csRideArray[cRaN][5] = result.feed.title; // site title
						csRideArray[cRaN][6] = entry[attributes[4]]; // full content
						
					
						
						//csRideArray[cRaN][6] //rank
						//csRideArray[cRaN][7] //city
						
						if (offerCheck==true) {
							csRideArray[cRaN][8] = "offer" // ride type offer
						} else if (requestCheck==true) {
							csRideArray[cRaN][8] = "request" // ride type request
						} else {
							csRideArray[cRaN][8] = "burn" // ride type unknown
						}
						
						if (site=="CS") {
							csRideArray[cRaN][9] = "/images/cs.png" //icon
						} else if (site=="CL") {
							csRideArray[cRaN][9] = "/images/craigslist.png" //icon
						} else if (site=="WH") {
							csRideArray[cRaN][9] = "/images/welcomehere.png" //icon
						}
						

					}
				}
					
				
			} // end filling array with this group
				
			
			areasSearched++; 
			divToFill.innerHTML = "<img src='/images/loading_green_sway.gif' align='absmiddle' /> Searching " + areasSearched + " of " + allRideArray.length + " resources";
				
			if (allRideArray.length>allRideArrayCount) {
				
				parseAllRides(divy);
			} else {
				
			
				
				csIDs=null
				csIDs=new Array()
				
				
				
				divToFill.innerHTML = ""
				// sort, trim/filter, display
				
				csRideArray.sort();
                csRideArray.reverse();
				
				if (csRideArray.length<=entriesShown) {
					forCount = csRideArray
				} else {
					forCount = entriesShown
				}	
				
				
				
				for (h=0; h<forCount; h++) { // each array entry
							
					var csC = csRideArray[h][6]
					var csContent = csC.replace(/(<([^>]+)>)/ig,""); 
					var all_content = "<strong>" +csRideArray[h][4] + "</strong><br /><br />" + csContent
					csIDs[csIDs.length] = all_content

				
					var divFinal = document.createElement("div");
					divFinal.className = "craigEntrye"
					//divFinal.setAttribute("onmouseover","showCraigContent(csIDs[" + (csIDs.length-1) + "])")
					//divFinal.setAttribute("onmouseout","showMap()")
						
						

					if (csRideArray[h][8]=="request") {
						var type_img = "/images/thumb_up.png";
					} else if (csRideArray[h][8]=="offer") {
						var type_img = "/images/car.png";
					} else {
						var type_img = "/images/bullet_green.gif";
					}
					
					
					if (content_display=="short") {
						
						divFinal.innerHTML = "<img src='" + type_img + "' align='absmiddle' /> <strong class='simpetext'><a href=\"" + csRideArray[h][1] + "\" target=\"_blank\" onmouseover=\"jQuery(this).next().stop(true, true).animate({opacity: \'show\', top: \'120\'}, \'normal\')\" onmouseout=\"jQuery(this).next().animate({opacity: \'hide\', top: \'-70\'}, \'fast\')\">" + csRideArray[h][4] + "</a><span>" + all_content + "</span></strong><br /><!--<img src='" + csRideArray[h][9] + "' align='absmiddle' /> --><a href='" + csRideArray[h][1] + "' class='resultLink' style='color:#006600'><strong>posted " + csRideArray[h][2].substr(0,11) + " to " + csRideArray[h][5] + "</a><br /><br />"
							
						
							
					} else {
						divFinal.innerHTML = "<img src='" + csRideArray[h][9] + "' align='absmiddle' /> <img src='" + type_img + "' align='absmiddle' /> <strong class='simpetext'><a href=\"" + csRideArray[h][1] + "\" target=\"_blank\" onmouseover=\"jQuery(this).next().stop(true, true).animate({opacity: \'show\', top: \'120\'}, \'normal\')\" onmouseout=\"jQuery(this).next().animate({opacity: \'hide\', top: \'-70\'}, \'fast\')\">" + csRideArray[h][4] + "</a><span>" + all_content + "</span> - " + csRideArray[h][3] + " (posted on " + csRideArray[h][2].substr(0,11) + ")</strong> <a href='" + csRideArray[h][1] + "' class='resultLink' style='color:#006600'><strong>" + csRideArray[h][5] + "</strong></a><br /><br />"
					}
						
						
					divToFill.appendChild(divFinal);
					
					
					
				}
			}
		}

	})
}

function CSridesharePull(area) { 
	
	csHits=null
    csHits=new Array()
	
	var feed = new google.feeds.Feed(area);
	feed.includeHistoricalEntries();
	feed.setNumEntries(30);
	feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
	feed.load(function(result) {
		if (!result.error) {
			for (var i = 0; i < result.feed.entries.length; i++) {
				var entry = result.feed.entries[i];
				var attributes = ["title", "link", "publishedDate", "contentSnippet", "content"]; //added content
				

				var patt1 = new RegExp(cityFrom, 'i');
				var c1 = entry['title'].search(patt1);
				var c2 = entry['content'].search(patt1);
				
				if (cityTo!="") {
					var patt2 = new RegExp(cityTo, 'i');
					var c3 = entry['title'].search(patt2);
					var c4 = entry['content'].search(patt2);
				} else {
					var c3 = -1
					var c4 = -1
				}
				
				/* shows "GA" instead of Georgia
				var patt3 = new RegExp(stateFrom, 'i');
				var c5 = entry['title'].search(patt3);
				var c6 = entry['content'].search(patt3);
				
				var patt4 = new RegExp(stateTo, 'i');
				var c7 = entry['title'].search(patt4);
				var c8 = entry['content'].search(patt4);
				*/

					csC = entry['content']
                        var csContent = csC.replace(/(<([^>]+)>)/ig,""); 
                        csHits[csHits.length] = "<strong>" + entry['title'] + "</strong><br /><br />" + csContent

				if (c1!=-1 || c2!=-1 || c3!=-1 || c4!=-1) {
					var divFinal = document.createElement("div");
					divFinal.className = "craigEntry"
					divFinal.setAttribute("onmouseover","showCraigContent(csHits[" + (csHits.length-1) + "])")
                    divFinal.setAttribute("onmouseout","showMap()")
					
					
					divFinal.innerHTML = "<img src='/images/cs.png' align='absmiddle' /> <span class='simpetext'><strong><a href='" + entry['link'] + "' target='_blank' onmouseover='showCraigContent(csHits[" + (csHits.length - 1) + "])' onmouseout='showMap()'>" + entry['title'] + "</a></strong> - " + entry['contentSnippet'] + "</span><br /><a href='" + entry['link'] + "' class='resultLink' style='color:#006600'>" + entry['link'] + "</a><br /><br />"
					$('CS_rides').appendChild(divFinal);
				}
				
				
				
                   
				
					
				
				
				
			}
		}

	})
}

function craigUpdate(feedStrFrom) { 
	
	var FA = new Array();
	if (typeof feedStrFrom=="undefined") {
		feedStrFrom = cityFrom.toLowerCase().replace(/ /gi,'');
	}
	
	FA[0]="http://" + feedStrFrom + ".craigslist.org/rid/index.rss"
	
	if (cityTo!="") {
		feedStrTo = cityTo.toLowerCase().replace(/ /gi,'');
		FA[1]="http://" + feedStrTo + ".craigslist.org/rid/index.rss"
	}

	//function initialize() {
	var feedsArr = new Array();
	var rankedEntries = new Array();
	var numEntr = 75;
	var container = $("feed");
	var cnt = FA.length;
	pp=0
	for (var k=0; k<FA.length; k++) {
		pp++;
		//alert(pp)
		var feed = new google.feeds.Feed(FA[k]);
		feed.setNumEntries(numEntr);
		feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
		feed.load(function(result) {
			if (!result.error) {
				for (var i = 0; i < result.feed.entries.length; i++) {
					var entry = result.feed.entries[i];
					var attributes = ["title", "link", "publishedDate", "contentSnippet", "content"]; //added content
					var ind = feedsArr.length;

					feedsArr[ind] = new Array();
					//feedsArr[ind][0] = (craigRank*10000000000000) + Date.parse(entry[attributes[2]]); // sort 
					feedsArr[ind][0] = Date.parse(entry[attributes[2]]); // sort 
					feedsArr[ind][1] = entry[attributes[1]]; // link
					feedsArr[ind][2] = entry[attributes[2]]; // publishedDate
					feedsArr[ind][3] = entry[attributes[3]]; // contentSnippet
					feedsArr[ind][4] = entry[attributes[0]]; // title
					feedsArr[ind][5] = result.feed.title; // site title
					feedsArr[ind][6] = entry[attributes[4]]; // full content
				}
			}
			
			cnt--;
			if (cnt == 0) {
			
				for (var j = 0; j < feedsArr.length;  j++) {
	
					var indo = rankedEntries.length;
					
					var craigContent = feedsArr[j][6];
					var craigTitle = feedsArr[j][4];
					var craigLink = feedsArr[j][1];
					var craigDate = feedsArr[j][2];
					var craigSnippet = feedsArr[j][3];
					var craigSiteTitle = feedsArr[j][5];
				
					// RANKING CODE START
					possibleWaste = false;
					if (FA.length==1) {
						craigRank = 1
					} else {
					
						var craigRank = 2;
						
									
						var feedStrFromFind = new RegExp(feedStrFrom, 'i');
						var feedStrToFind = new RegExp(feedStrTo, 'i');
						
						if (craigLink.search(feedStrFromFind)!=-1) {
							
							var cityPriority = cityTo
							var cityThis = cityFrom
							craigRank = craigRank + 1
						} else {
							
							var cityPriority = cityFrom
							var cityThis = cityTo
							possibleWaste = true;
						}

						var citySearchHigh = new RegExp(cityPriority, 'i');
						//var citySearchLow = new RegExp(cityThis, 'i');
			
						if (craigContent.search(citySearchHigh)!=-1) {
							craigRank = craigRank + 2
							possibleWaste = false
						}
						
						if (craigTitle.search(citySearchHigh)!=-1) {
							craigRank = craigRank + 2
							possibleWaste = false
						}
					} // RANKING CODE END
	  
		
				   
					if (possibleWaste == false) {
						rankedEntries[indo] = new Array();
						//rankedEntries[indo][0] = Date.parse(entry[attributes[2]]); // sort 
						rankedEntries[indo][0] = ((craigRank*1000000000000000000000000000) + Date.parse(craigDate)) // sort 
						rankedEntries[indo][1] = craigLink; // link
						rankedEntries[indo][2] = craigDate; // publishedDate
						rankedEntries[indo][3] = craigSnippet; // contentSnippet
						rankedEntries[indo][4] = craigTitle; // title
						rankedEntries[indo][5] = craigSiteTitle; // site title
						rankedEntries[indo][6] = craigContent; // full content
					}
					
				}

				rankedEntries.sort();
				rankedEntries.reverse();
				
				
				var container = $("craigListings");
				container.innerHTML = ""
				
				craigHits=null
				craigHits=new Array()
				
				// show ALL entries
				//for (var j = 0; j < rankedEntries.length;  j++) {
					
				//show just 10
				for (var j = 0; j < 10;  j++) {
				
					//var craigContent = rankedEntries[j][6].substr(0,100) + "..."
					var craigTitle = rankedEntries[j][4]
					var craigContent = rankedEntries[j][6].replace(/(<([^>]+)>)/ig,""); 
					craigHits[craigHits.length] = "<strong>" + craigTitle + "</strong><br /><br />" + craigContent
					
					cityFromRe = new RegExp(cityFrom, 'gi');
					stateFromRe = new RegExp(stateFrom, 'gi');
					var craigTitle=craigTitle.replace(cityFromRe, "<strong>" + cityFrom + "</strong>")
					
					if (cityTo) {
						cityToRe = new RegExp(cityTo, 'gi');
						stateToRe = new RegExp(stateTo, 'gi');
						var craigTitle=craigTitle.replace(cityToRe, "<strong>" + cityTo + "</strong>")
					}
	
					var craigLink = rankedEntries[j][1]
					var craigDate = rankedEntries[j][2]
					var craigSnippet = rankedEntries[j][3]
					
					
					var div = document.createElement("div");
					div.className = "craigEntry"
					div.setAttribute("onmouseover","showCraigContent(craigHits[" + (craigHits.length-1) + "])")
					div.setAttribute("onmouseout","showMap()")
					div.innerHTML = "<a href='" + craigLink + "' target='_blank' onmouseover='showCraigContent(craigHits[" + (craigHits.length - 1) + "])' onmouseout='showMap()'>" + craigTitle + "</a> - <span class='simpetext'>" + craigSnippet + "(posted on " + craigDate.substr(0,11) + ")</span><br /><a href='" + craigLink + "' class='resultLink' style='color:#006600'>" + craigLink + "</a><br /><br />"
					
					container.appendChild(div);          
	  
				}
	
				var divFinal = document.createElement("div");
				divFinal.innerHTML = "<span class='simpetext'><strong><a href='" + "http://" + feedStrFrom + ".craigslist.org/rid' target='_blank'>More Craigslist Listings...</a></strong></span><br /><div style='clear:both'></div>"
				container.appendChild(divFinal);
			}
		});
	}
}
	
function GSCLoad(defaultSearch, searchEngine) { 
  // Create a search control 
	
	if (searchEngine=="stay") {
		restrictionCode = "013602994325965359162:k0lk9u5lei4"
		searchDiv = "staySearchControl"
	} else {
		restrictionCode = "000519232147513413721:7awm5yzfdai" //travel
		searchDiv = "searchcontrol"
	}
	
  var searchControl = new google.search.SearchControl(); 

  //var localSearch = new google.search.LocalSearch(); 
  //searchControl.addSearcher(localSearch); 
  
  var webSearch = new google.search.WebSearch()
  webSearch.setSiteRestriction(restrictionCode);
  searchControl.addSearcher(webSearch); 
  
  //searchControl.setResultSetSize(GSearch.LARGE_RESULTSET);
  webSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET); 
 
   // Set the Local Search center point 
  //localSearch.setCenterPoint("New York, NY"); 

  // tell the searcher to draw itself and tell it where to attach 
  var drawOptions = new google.search.DrawOptions(); 
  drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED); 

  searchControl.draw($(searchDiv), drawOptions); 

  // execute an inital search 
  searchControl.execute(defaultSearch); 
} 

	
// add Transit Functions

function saveCheck2() {
	
	var thecheck = $('aCheck')
	if (thecheck.checked==true) {
		$('saveButton').disabled=false; 
		$('saveButton').value='Save'
	} else {
	
		$('saveButton').disabled=true; 
		$('saveButton').value='Check the box first!'
	}

}
	
function onChange() {
	if (document.transitSearchForm.date_type.selectedIndex==1) {
		document.transitSearchForm.second_date.disabled=false
		document.transitSearchForm.second_date.style.visibility = 'visible';
	} else {
		document.transitSearchForm.second_date.disabled='disabled';
		document.transitSearchForm.second_date.style.visibility = 'hidden';
	}	
}

	
// Hitch Functions
	
function saveCheck22() {
	
	var thecheck = $('aCheck2')
	if (thecheck.checked==true) {
		$('saveButton2').disabled=false; 
		$('saveButton2').value='Save'
	} else {
	
		$('saveButton2').disabled=true; 
		$('saveButton2').value='Check the box first!'
	}

}
		
	function addHitchAddressToMap(response) {
	
		  //map.clearOverlays();
		  if (!response || response.Status.code != 200) {
			alert("Sorry, we were unable to geocode that address");
		  } else {

			place = response.Placemark[0];
			point = new google.maps.LatLng(place.Point.coordinates[1],
								place.Point.coordinates[0]);
			marker = new google.maps.Marker(point);
			
			
			//structured Information
				
			var aa, saa, l;
			aa = place.AddressDetails.Country.AdministrativeArea;
			if ( aa ) {
				state = aa.AdministrativeAreaName;
				saa = aa.SubAdministrativeArea;
				if ( saa ) {
					county = saa.SubAdministrativeAreaName;
					l = saa.Locality;
					if (l) {
						city = l.LocalityName;
						if ( l.Thoroughfare ) {
							streetLine = l.Thoroughfare.ThoroughfareName;
						}
						if ( l.PostalCode ) {
							zip = l.PostalCode.PostalCodeNumber;
						}
					} else {
						if (saa.Thoroughfare) {
							streetLine = saa.Thoroughfare.ThoroughfareName;
						}
						if (saa.PostalCode) {
							zip = saa.PostalCode.PostalCodeNumber;
						}
					}
				} else {
					l = aa.Locality;
					if (l) {
						city = l.LocalityName;
						if ( l.Thoroughfare ) {
							streetLine = l.Thoroughfare.ThoroughfareName;
						}
						if (l.PostalCode) {
							zip = l.PostalCode.PostalCodeNumber;
						}
					} else {
						if (aa.Thoroughfare) {
							streetLine = aa.Thoroughfare.ThoroughfareName;
						}
						if (aa.PostalCode) {
							zip = aa.PostalCode.PostalCodeNumber;
						}
					}
				}
			}		
			
			country = place.AddressDetails.Country.CountryNameCode;
			coor = place.Point.coordinates[1] + "," + place.Point.coordinates[0]
			
			
			
			

			//for database entry
			var startPlace = $("hitchPlace")
			var startAddress = $("hitchAddress")
			var startCity = $("hitchCity")
			var startState = $("hitchState")
			var startCountry = $("hitchCountry")
			var startPoint = $("hitchPoint")	
			
			map.addOverlay(marker);
			marker.openInfoWindowHtml("<strong>" + place.address + "</strong>");
			
			place1 = place.address
			startPlace.value += place.address + ";"
			
			FromString = "?style=script"
			if (typeof streetLine!="undefined") {
				FromString += "&address1=" + streetLine
				startAddress.value += streetLine + ";"
			} else {
				startAddress.value += "n/a" + ";"
			}
			if (typeof city!="undefined") {
				FromString += "&city1=" + city 
				startCity.value += city + ";"
			} else {
				startCity.value += "n/a" + ";"
			}
			if (typeof state!="undefined") {		
				FromString += "&state1=" + state
				startState.value += state + ";"
			} else {
				startState.value += "n/a" + ";"
			}
			if (typeof country!="undefined") {
				FromString += "&country1=" + country
				startCountry.value += country + ";"
			} else {
				startCountry.value += "n/a" + ";"
			}
			if (typeof coor!="undefined") {
				FromString += "&point1=" + coor
				startPoint.value += coor + ";"
			} else {
				startPoint.value += "n/a" + ";"
			}
			
			$("aCheck2").disabled=false
			$('saveButton2').value = "Check the box before saving"
			
			// add to visual list
			var container = $("routeHitchList")
			var div = document.createElement("div");
			div.innerHTML = place1
			container.appendChild(div);
	
		  }
	}

	function showHitchLocation() {
	  var address = document.hitchForm.hitchOrigin.value;
	  document.hitchForm.hitchOrigin.value = ""
	  geocoder.getLocations(address, addHitchAddressToMap);  
	}
	
	function onChange2() {
		if (document.hitchForm.date_type2.selectedIndex==1) {
			document.hitchForm.second_date2.disabled=false
			document.hitchForm.second_date2.style.visibility = 'visible';
		} else {
			document.hitchForm.second_date2.disabled='disabled';
			document.hitchForm.second_date2.style.visibility = 'hidden';
		}	
	}
	
	function addCityOnEnter (field, event) {
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13) {
			/*
			var i;
			for (i = 0; i < field.form.elements.length; i++)
				if (field == field.form.elements[i])
					break;
			i = (i + 1) % field.form.elements.length;
			field.form.elements[i].focus();*/
			showHitchLocation();
			return false;
		} 
		else
		return true;
	}  
	
	
	// NYC Functions
	   function subwaySelect() {
            var subdiv = $("subwayDiv");
            var startCounty = $(countyFrom);
            var endCounty = $(countyTo + "a");
            startCounty.selected = true
            endCounty.selected = true
            subdiv.style.display = "block";
        }
        
        function metroNorth() {
            var xxx=1
            while (xxx<3) {
            
                decide = "no"
                if (xxx==1) {
                    var metroSelect = $("orig_station");
                } else {
                    var metroSelect = $("dest_station");
                }
                    
                var selNum = 0
                        
                while (decide=="no") {
                    metroSelect.options[selNum].selected = "1"
                    var metroChosen = metroSelect.selectedIndex
                    var metroLabel = metroSelect.options[metroChosen].text  
                    
                    if (xxx==1) {
                        var cityCompare = cityFrom
                        var countyCompare = countyFrom
                    } else {
                        var cityCompare = cityTo 
                        var countyCompare = countyTo      
                    }
                    
                    //special instances         
                    if (cityCompare=="New York" || countyCompare=="Queens" || countyCompare=="Bronx" || countyCompare=="Brooklyn" || countyCompare=="Staten Island") {
                        
                        var cityCompare = "Grand Central Terminal"
                    }
                    //end special
                
                    if (metroLabel == cityCompare) {
                        decide = "stay";                
                        if (xxx==1) {
                            var firstMetro = cityCompare;
                        }
                    } 
                    
                    selNum++        
                    
                    if (metroLabel == "Yonkers") {
                        decide = "stay";
                        if (cityCompare != metroLabel) {
                            metroSelect.options[34].selected = "1"  
                            var metdiv = $("metrodiv");
                            metdiv.style.display = "none";
                        }
                    } 
                }   
                xxx++
            }//new
            
            if (firstMetro==metroLabel) {
                var metdiv = $("metrodiv");
                metdiv.style.display = "none";        
            }
            
            //time
			now = new Date();
			hour = now.getHours();
			if (hour > 12) {
			  hour = hour - 12;
			  ampm = "PM";
			} else {
			  hour = hour;
			  ampm = "AM";
			}
			if (hour == 12) {
			  ampm = "PM";
			}
			if (hour == 00) {
			  hour = "12";
			}		
			
            var decide = "no"
            var timeNum = 0
            var timeSelect = $("currentTime");
            while (decide=="no") {
                
                timeSelect.options[timeNum].selected = "1"
                var timeChosen = timeSelect.selectedIndex
                var timeLabel = timeSelect.options[timeChosen].text 
                    
                if (timeLabel == hour + ":00") {
                    decide = "stay";                
                } 
                    
                timeNum++       
                
            }   
            var ampmSelect = $("ampm");
            var ampmChosen = ampmSelect.selectedIndex
            var ampmLabel = ampmSelect.options[ampmChosen].text 
            if (ampmLabel != ampm) {
                    timeSelect.options[timeNum].selected = "1"              
            } 
            //end time  
        }
        
        function longIsland() {
        var aaa=1
        while (aaa<3) {
        
            decide2 = "no"
            if (aaa==1) {
                var longSelect = $("county1");
            } else {
                var longSelect = $("county2");
            }
                
            var newselNum = 0
            //longSelect.options[newselNum].selected = "1"
                    
            while (decide2=="no") {
            
                longSelect.options[newselNum].selected = "1"
                var longChosen = longSelect.selectedIndex
                var longLabel = longSelect.options[longChosen].text 
                
                
                if (aaa==1) {
                    var cityCompare = cityFrom + ", NY"
                } else {
                    var cityCompare = cityTo + ", NY"               
                }
                
            
                if (longLabel == cityCompare) {
                    decide2 = "stay";               
                } 
                
                newselNum++     
                
                if (longLabel == "Yaphank, NY") {
                    decide2 = "stay";
                    if (cityCompare != longLabel) {
                        //longSelect.options[34].selected = "1"
                        
                        
                        var lidiv = $("LI");
                        lidiv.style.display = "none";
                    }
                    
                } 
            }   
            aaa++
        }   
    }
		

//old maps.js
//define icons
	currentLocationIcon = new google.maps.Icon();
	currentLocationIcon.image = "/images/current_location.png";
	currentLocationIcon.shadow = "/images/current_location_shadow.png";
	currentLocationIcon.iconSize = new google.maps.Size(48, 48);
	currentLocationIcon.shadowSize = new google.maps.Size(73, 48);
	currentLocationIcon.iconAnchor = new google.maps.Point(24, 50);
	currentLocationIcon.infoWindowAnchor = new google.maps.Point(5, 1);

	tripStartIcon = new google.maps.Icon();
	tripStartIcon.image = "/images/tripStart.png";
	tripStartIcon.shadow = "/images/flagShadow.png";
	tripStartIcon.iconSize = new google.maps.Size(48, 48);
	tripStartIcon.shadowSize = new google.maps.Size(73, 48);
	tripStartIcon.iconAnchor = new google.maps.Point(31, 45);
	tripStartIcon.infoWindowAnchor = new google.maps.Point(5, 1);
	
	tripEndIcon = new google.maps.Icon();
	tripEndIcon.image = "/images/tripEnd.png";
	tripEndIcon.shadow = "/images/flagShadow.png";
	tripEndIcon.iconSize = new google.maps.Size(48, 48);
	tripEndIcon.shadowSize = new google.maps.Size(73, 48);
	tripEndIcon.iconAnchor = new google.maps.Point(31, 45);
	tripEndIcon.infoWindowAnchor = new google.maps.Point(5, 1);
	
	/*
	smallStartFlagIcon = new google.maps.Icon();
	smallStartFlagIcon.image = "/images/flag_green_small.png";
	smallStartFlagIcon.shadow = "/images/flag_green_small_shadow.png";
	smallStartFlagIcon.iconSize = new google.maps.Size(24, 24);
	smallStartFlagIcon.shadowSize = new google.maps.Size(37, 24);
	smallStartFlagIcon.iconAnchor = new google.maps.Point(15, 25);
	smallStartFlagIcon.infoWindowAnchor = new google.maps.Point(5, 1);
	
	smallEndFlagIcon = new google.maps.Icon();
	smallEndFlagIcon.image = "/images/flag_red_small.png";
	smallEndFlagIcon.shadow = "/images/flag_green_small_shadow.png";
	smallEndFlagIcon.iconSize = new google.maps.Size(24, 24);
	smallEndFlagIcon.shadowSize = new google.maps.Size(37, 24);
	smallEndFlagIcon.iconAnchor = new google.maps.Point(15, 25);
	smallEndFlagIcon.infoWindowAnchor = new google.maps.Point(5, 1);
	*/
	
	iconStart = new google.maps.Icon();
	iconStart.image = "http://triphopping.com/images/start.png";
	iconStart.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	iconStart.iconSize = new google.maps.Size(21, 34);
	iconStart.shadowSize = new google.maps.Size(22, 20);
	iconStart.iconAnchor = new google.maps.Point(10, 34);
	iconStart.infoWindowAnchor = new google.maps.Point(5, 1);
        
	iconEnd = new google.maps.Icon();
	iconEnd.image = "http://triphopping.com/images/end.png";
	iconEnd.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	iconEnd.iconSize = new google.maps.Size(21, 34);
	iconEnd.shadowSize = new google.maps.Size(22, 20);
	iconEnd.iconAnchor = new google.maps.Point(10, 34);
	iconEnd.infoWindowAnchor = new google.maps.Point(5, 1);
        
	iconStop = new google.maps.Icon();
	iconStop.image = "http://triphopping.com/images/pause.png";
	iconStop.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	iconStop.iconSize = new google.maps.Size(21, 34);
	iconStop.shadowSize = new google.maps.Size(22, 20);
	iconStop.iconAnchor = new google.maps.Point(10, 34);
	iconStop.infoWindowAnchor = new google.maps.Point(5, 1);


	
function friends_to_map() {
	
	if (typeof(friendKML)=="undefined") {
		friendKML = new google.maps.GeoXml('http://www.triphopping.com/friendKML.php?friendType=all&n=' + tripUsername);
	}
	
	map.addOverlay(friendKML);
}

// We define the function first
function TextualZoomControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
TextualZoomControl.prototype = new google.maps.Control();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  
if (coorFrom) {
  var zoomInDiv = document.createElement("div");
  this.setButtonStyle_(zoomInDiv);
  container.appendChild(zoomInDiv);
  zoomInDiv.appendChild(document.createTextNode("Zoom to " + cityFrom));
  google.maps.Event.addDomListener(zoomInDiv, "click", function() {
    map.setCenter(new google.maps.LatLng(latFrom, lngFrom), 11);
  });
}

if (coorTo) { 
  var zoomOutDiv = document.createElement("div");
  this.setButtonStyle_(zoomOutDiv);
  container.appendChild(zoomOutDiv);
  zoomOutDiv.appendChild(document.createTextNode(cityTo));
  google.maps.Event.addDomListener(zoomOutDiv, "click", function() {
    map.setCenter(new google.maps.LatLng(latTo, lngTo), 11);
  });
}

// if (tripUsername!="" && tripUsername != "noUser") {
if (tripUsername!="") { // bandR
	friendsLayerVisible = false
		
  friendOverlay = document.createElement("div");
	//friendOverlay.setAttribute('id', 'friendButtonDiv')
  this.setButtonStyle_(friendOverlay);
  friendOverlay.style.fontWeight = 'normal'
  container.appendChild(friendOverlay);
  friendOverlay.appendChild(document.createTextNode("Friends"));
  google.maps.Event.addDomListener(friendOverlay, "click", function() {
	  
	if (friendsLayerVisible==false) {
		
		friends_to_map();
		friendsLayerVisible = true
		this.style.fontWeight = 'bold'
		
		//friendsMap()

	} else {

		/*
		for (var i=0; i<friendMarker.length; i++) { 
            friendMarker[i].hide(); 
        }*/
		
		friendsLayerVisible = false
		this.style.fontWeight = 'normal'
		map.removeOverlay(friendKML);
	}
    
  });
  
  justYouVisible = false
  justYouDiv = document.createElement("div");
//justYouDiv.setAttribute('id', 'youButtonDiv')
  this.setButtonStyle_(justYouDiv);
  justYouDiv.style.fontWeight = 'normal'
  container.appendChild(justYouDiv);
  justYouDiv.appendChild(document.createTextNode("You"));
  google.maps.Event.addDomListener(justYouDiv, "click", function() {
  
    if (justYouVisible==false) {
        //map.clearOverlays()
        //userMap('current')
		/*
		for (var i=0; i<youMarker.length; i++) { 
          if (youMarker[i].mycategory == 'userYou') { 
            map.addOverlay(youMarker[i])
          } 
        }
		
		for (var i=0; i<youPolyline.length; i++) { 
            map.addOverlay(youPolyline[i])
        }
		*/
			
		if (typeof(youKML)=="undefined") {	
			youKML = new google.maps.GeoXml('http://www.triphopping.com/userKML.php?n=' + tripUsername);
			youLineKML = new google.maps.GeoXml('http://www.triphopping.com/userLineKML.php?n=' + tripUsername);
		}	
		
		map.addOverlay(youKML);
		map.addOverlay(youLineKML);
		
			
        justYouVisible = true
		this.style.fontWeight = 'bold'
    } else {
        //map.clearOverlays()
		
		
		justYouVisible = false
		this.style.fontWeight = 'normal'
		
	
		/*
		for (var i=0; i<youMarker.length; i++) { 
		  if (youMarker[i].mycategory == 'userYou') { 
			youMarker[i].hide(); 
		  } 
		}
	
		for (var i=0; i<youPolyline.length; i++) { 
			youPolyline[i].hide(); 
		}
		*/
		map.removeOverlay(youKML);
		map.removeOverlay(youLineKML);

        
    }

    //container.replaceChild(div, container.firstChild);
    
  });
  
  
} // end if tripUsername exists
  
 


  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new google.maps.ControlPosition(G_ANCHOR_TOP_RIGHT, new google.maps.Size(180, 3));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button) {
  //button.style.textDecoration = "underline";
  button.style.color = "#0000cc";
  button.style.backgroundColor = "white";
  button.style.font = ".8em Arial";
  button.style.border = "1px solid black";
  button.style.padding = "2px";
  button.style.marginBottom = "0px";
  button.style.textAlign = "center";
  button.style.width = "58px";
  button.style.cursor = "pointer";
  button.style.cssFloat = "left";
}



// ** LAYER CHECK BOXES ON MAP ***

var timer;
var chosen = [];
 
/* Array of GLayers
 * The 'name' property is not being used here
*/
var layers = [
 { name: "Pano", obj: new GLayer("com.panoramio.all") },
 { name: "Tube", obj: new GLayer("com.youtube.all") },
 { name: "Wiki", obj: new GLayer("org.wikipedia.en") }
];
 
function hideAll() {
 
 var boxes = document.getElementsByName("mark");
 for(var i = 0; i < boxes.length; i++) {
  if(boxes[i].checked) {
   boxes[i].checked = false;
   switchLayer(false, layers[i].obj);
   chosen.push(i);
  }
 }
}
 
function checkChecked() {
 
 /* Returns true if a checkbox is still checked
 *  otherwise false
 */
 var boxes = document.getElementsByName("mark");
 for(var i = 0; i < boxes.length; i++) {
  if(boxes[i].checked) return true;
 }
 return false;
}
 
function switchLayer(checked, layer) {
 
 /* Function was originally borrowed from Esa:
 *  http://esa.ilmari.googlepages.com/dropdownmenu.htm
 */
 var layerbox = document.getElementById("box");
 var boxlink = document.getElementById("boxlink");
 var button = document.getElementById("more_inner");
 
 if(checked) {
   map.addOverlay(layer);
   // Reset chosen array
   chosen.length = 0;
   /* Highlight the link and
   *  make the button font bold.
   */
   boxlink.className ="highlight";
   layerbox.className ="highlight";
   button.className ="highlight";
 }
 else {
   map.removeOverlay(layer);
   /*  Reset the link and the button
    * if all checkboxes were unchecked.
   */
   if(!checkChecked()) {
    boxlink.blur();
    boxlink.className ="";
    layerbox.className ="";
    button.className ="";
   }
 }
}
 
function showLayerbox() {
 
 var layerbox = document.getElementById("box");
 // Left size of more control
 var offsetX = 90;
 // Top size of more control plus more button height
 var offsetY = 7 + 18;
 
 var lpos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(offsetX, offsetY));
 lpos.apply(layerbox);
 if(window.timer) clearTimeout(timer);
 layerbox.style.display = "block";
}
 
function setClose(e) {
 
 if(!e) e = window.event;
 var layerbox = document.getElementById("box");
 
 if(checkMouseLeave(layerbox, e))
  timer = window.setTimeout(function() {
   layerbox.style.display = "none"; }, 400);
}
 
function checkMouseLeave(element, evt) {
 
 /* Avoid firing a mouseout event
 *  when the mouse moves over a child element.
 *  Borrowed from:
 *  http://www.faqts.com/knowledge_base/view.phtml/aid/1606/fid/145
 */
 if(element.contains && evt.toElement) {
   return !element.contains(evt.toElement);
 }
 else if(evt.relatedTarget) {
   return !containsDOM(element, evt.relatedTarget);
 }
}
 
function containsDOM(container, containee) {
 
 var isParent = false;
 do {
  if((isParent = container == containee))
   break;
   containee = containee.parentNode;
 }
 while(containee != null);
 return isParent;
}
 
function toggleLayers() {
 
 if(chosen.length > 0 ) {
   /* Make an independent copy of chosen array since switchLayer()
   *  resets the chosen array, which may not be useful here.
   */
   var copy = chosen.slice();
   for(var i = 0; i < copy.length; i++) {
    var index = parseInt(copy[i]);
    switchLayer(true, layers[index].obj);
    document.getElementsByName("mark")[index].checked = true;
   }
 }
 else {
  hideAll();
 }
}
 
function MoreControl() {};
MoreControl.prototype = new GControl();
MoreControl.prototype.initialize = function(map) {
 
 var more = document.createElement("div");
 more.style.border = "1px solid black";
 more.title = "Show/Hide Layers";
 var inner = document.createElement("div");
 inner.id = "more_inner";
 inner.appendChild(document.createTextNode("More..."));
 more.appendChild(inner);
 more.onmouseover = showLayerbox;
 more.onmouseout = setClose;
 more.onclick = toggleLayers;
 map.getContainer().appendChild(more);
 return more;
}
 
MoreControl.prototype.getDefaultPosition = function() {
 return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(90, 7));
}

// *** END layer check boxes on map ***

var map; 
var geocoder;
//var amtrakStations = new google.maps.GeoXml("http://mapmash.googlepages.com/amtrak_stations_all.kml");
//var amtrakRoutes = new google.maps.GeoXml("http://mapmash.googlepages.com/amtrak_lines.kml");
//hitchWikiSpots = new google.maps.GeoXml("http://www.triphopping.com/hitchWiki.kml");

function searchGooglebar(term){  

	if ($(":0:inputId")) {
		$(":0:inputId").value = term;
		$(":0:buttonId").click();
	}
}
      
function clearGooglebar(){  
  searchGooglebar(' ');
}

// uses OLD variables
function oonLoad() {

  //if (google.maps.BrowserIsCompatible()) { 
	var mapOptions = {
		googleBarOptions : {
			style : "new",
			adsOptions: {
				client: "partner-pub-2873728022126830",
				channel: "5772561365",
				adsafe: "high",
				language: "en"
			},
			searchFormHint : "local search...", 
			onSearchCompleteCallback : function(searcher){
				
				var resultBlock = "<span></span>";
				var s = searcher.results
				for (i=0; i<s.length; i++) {
					resultBlock += "<p><a href=\"" + s[i].url + "\">" + s[i].titleNoFormatting + "</a><br />" + s[i].streetAddress + "</p>";
					
				}
				
				//if (recentToggleDiv=="stayDiv") {
					//alert(resultBlock)
					$('stay_results').innerHTML = resultBlock;
				//}
				
			} 
		}
	}
	 
    map = new google.maps.Map2($("map"), mapOptions); 
    map.setCenter(new google.maps.LatLng(35.493138,-97.459141), 3); 
	
	// Map Behavior
	map.enableDoubleClickZoom()
    map.enableContinuousZoom()
	
	// Map Controls
	map.addControl(new google.maps.LargeMapControl3D()); 
	map.addControl(new google.maps.ScaleControl(), new google.maps.ControlPosition(G_ANCHOR_BOTTOM_RIGHT, new google.maps.Size(10,10)));
	
	
    
	// Add "friends" and "just you"
	map.addControl(new TextualZoomControl());   
    
	map.addMapType(G_SATELLITE_3D_MAP);
    map.addMapType(G_PHYSICAL_MAP);
	//map.addControl(new google.maps.MapTypeControl());
    //map.addControl(new google.maps.HierarchicalMapTypeControl());
	map.addControl(new GMenuMapTypeControl());
	//map.setMapType(G_SATELLITE_TYPE);
	
	
	//map.enableRotation()
	
	// Add the self created control
	 map.addControl(new MoreControl());
	 // Remove invisible box from its location and add it to the map
	 map.getContainer().appendChild(document.getElementById("box"));

		
//	geocoder = new google.maps.ClientGeocoder();

	//**NEW** Location Prediction
	if (google.loader.ClientLocation && $('origin').value=="") {
		ipCity = google.loader.ClientLocation.address.city
		ipRegion = google.loader.ClientLocation.address.region
		ipCountry = google.loader.ClientLocation.address.country
		ipVis = ipCity + ", " + ipRegion + ", " + ipCountry
		$("origin").value = ipVis
		map.setCenter(new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude), 6);
	}
	
	
    map.enableGoogleBar();

	var adsManager = new google.maps.AdsManager(map, "ca-pub-2873728022126830"); 
    adsManager.enable(); 
		
    
    //context menu START]
    contextmenu = document.createElement("div");
    contextmenu.style.visibility="hidden";
    contextmenu.style.background="#ffffff";
    contextmenu.style.border="1px solid #8888FF";
    contextmenu.className = "contextmenu"
    contextDefault = '<a href="javascript:reverseit(\'end\', clickedPixel)">Travel To</a><br />'
                        + '<a href="javascript:reverseit(\'start\', clickedPixel)">Travel From</a><br />'
                        + '<a href="javascript:zoomInHere()">Zoom In</a><br />'
						+ '<a href="javascript:addHitchhikingSpot()">Add Hitchhiking Spot</a><br />'
						+ '<a href="javascript:addStaySpot()">Add place to stay (like a campsite)</a><br />';
    contextmenu.innerHTML = contextDefault
    map.getContainer().appendChild(contextmenu);

    
    // === listen for singlerightclick ===
    google.maps.Event.addListener(map,"singlerightclick",function(pixel,tile) {
		clickedPixel = pixel;
		var x=pixel.x;
		var y=pixel.y;
		if (x > map.getSize().width - 200) { x = map.getSize().width - 200 }
		if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
		var pos = new google.maps.ControlPosition(G_ANCHOR_TOP_LEFT, new google.maps.Size(x,y));  
		pos.apply(contextmenu);
			
		// distance from origin and destination
		
		// reset menu
		contextmenu.innerHTML = contextDefault
		
		latlngClick = map.fromContainerPixelToLatLng(clickedPixel)
		
		//latlngFrom = new GLatLng(startMarker.getPoint().lat(),startMarker.getPoint().lng());
		//latlngTo = new GLatLng(endMarker.getPoint().lat(),endMarker.getPoint().lng());

		geocoder.getLocations(latlngClick, function(addresses) {
			if(addresses.Status.code != 200) {
				alert("reverse geocoder failed to find an address for " + latlngClick.toUrlValue());
			} else {
				structureAd = addresses.Placemark[0];
				structureClick = structureAd.address
				directionsClick = new google.maps.Directions();
				directionsClick.load(structureFrom + " to " + structureClick,{ getPolyline:true, getSteps:true });
				//google.maps.Event.addListener(directionsClick, "load", onGDirectionsClickLoad);
				
				google.maps.Event.addListener(directionsClick, "load", function () {
					contextmenu.innerHTML = contextDefault + "<br /><strong>" + structureClick + "</strong><br /><span class='simpetext'>" + directionsClick.getDistance().html + " from " + structureFrom + " (" + directionsClick.getDuration().html + ")</span>";
				});
			}
		});
		
		 
		
		// end distance preview
        
        
        contextmenu.style.visibility = "visible";
    });

      
	google.maps.Event.addListener(map, "click", function() {
		contextmenu.style.visibility="hidden";
	});
      
      
    
    //context menu END 

    mapLoaded=true

  //}
}

// can replace instances and kill
function reverseit(pos, newPoint) {

    if (mapLoaded==true) {

        if (pos=="start") {
            if(typeof(newPoint)=="undefined") {
                latlng = new google.maps.LatLng(startMarker.getPoint().lat(),startMarker.getPoint().lng());
                
            } else {
                contextmenu.style.visibility="hidden";
                latlng = map.fromContainerPixelToLatLng(newPoint)
            }
            locBox = $('origin')
        } else {
            if(typeof(newPoint)=="undefined") {
                latlng = new google.maps.LatLng(endMarker.getPoint().lat(),endMarker.getPoint().lng());
            } else {
                contextmenu.style.visibility="hidden";
                latlng = map.fromContainerPixelToLatLng(newPoint)
            }
            locBox = $('destination')
        }
        geocoder.getLocations(latlng, function(addresses) {
            if(addresses.Status.code != 200) {
                alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
            } else {
                address = addresses.Placemark[0];
                locBox.value = address.address
                showLocation(); 
            }
        });
    }
}

function addHitchhikingSpot() {
	
	contextmenu.style.visibility="hidden";
    var hitchPoint = map.fromContainerPixelToLatLng(clickedPixel)
		
	postGeoSuccess = function () {

		var d = new Date();
		thisMonthNum = d.getMonth()
		dateMonthSelect = "<select name=\"month_there\" id=\"month_there\">"
		
		var date_arr = new Array;
		var date_num = new Array;
	

		date_arr[0]="January"
		date_arr[1]="February"
		date_arr[2]="March"
		date_arr[3]="April"
		date_arr[4]="May"
		date_arr[5]="June"
		date_arr[6]="July"
		date_arr[7]="August"
		date_arr[8]="September"
		date_arr[9]="October"
		date_arr[10]="November"
		date_arr[11]="December"
		
		date_num[0]="01"
		date_num[1]="02"
		date_num[2]="03"
		date_num[3]="04"
		date_num[4]="05"
		date_num[5]="06"
		date_num[6]="07"
		date_num[7]="08"
		date_num[8]="09"
		date_num[9]="10"
		date_num[10]="11"
		date_num[11]="12"

		for (i=0; i<12; i++) {
			select = ""
			if (i==thisMonthNum) {
				select=" selected=\"selected\""
			}
			dateMonthSelect += "<option value=\"" + date_num[i] + "\"" + select + ">" + date_arr[i] + "</option>"
		}
		
		dateMonthSelect += "</select>"
			
		thisYear = d.getFullYear()
		lastYear = thisYear - 1
		dateYearSelect = "<select name=\"year_there\" id=\"year_there\"><option selected=\"selected\">" + thisYear + "</option>"
		for(i=lastYear; i>1900; i--) { 
			dateYearSelect += "<option>" + i + "</option>"
		} 
		dateYearSelect += "</select>"

		hitchWindowContent = "<div id=\"hitchSpotAdd\"><form name=\"hitchhiking_spots_form\" id=\"hitchhiking_spots_form\" action=\"/homeFunctions.php\" onsubmit=\"advAJAX(\'/homeFunctions?\' + $(\'hitchhiking_spots_form\').serialize(), \'hitchSpotAdd\'); return false;\">" +
		"Rate this spot: <select name=\"spot_rating\" id=\"spot_rating\">" +
			"<option value=\"0\">DANGER!</option>" +
			"<option value=\"1\">Negative</option>" +
			"<option value=\"2\" selected=\"selected\">OK</option>" +
			"<option value=\"3\">Positive</option>" +
		"</select><br />" +
		
		"Your experience: <select name=\"experience\" id=\"experience\">" +
			"<option selected=\"selected\">I hitchhiked from here!</option>" +
			"<option>I picked someone up here</option>" +
			"<option>I heard about it or saw someone here</option>" +
			"<option>Just a hunch</option>" +
		"</select><br />" +
		
		"Time experienced:" + dateMonthSelect + dateYearSelect + "<span class=\"simpetext\">optional</span><br />" +

		"Spot Type: <select name=\"spot_type\" id=\"spot_type\"><option>Freeway Shoulder</option><option selected=\"selected\">Ramp</option><option>Gas Station or Truck Stop</option></select><br />" +
		"<textarea name=\"spot_description\" id=\"spot_description\" cols=\"30\" rows=\"4\"></textarea><br />" +
		
		"<div style=\"display:none\">" +
		"<input type=\"text\" name=\"place\" value=\"" + placeName + "\" /><br />" +
		"<input type=\"text\" name=\"lat\" value=\"" + lat + "\" /><br />" +
		"<input type=\"text\" name=\"lng\" value=\"" + lng + "\" /><br />" +
		"<input type=\"text\" name=\"city\" value=\"" + city + "\" /><br />" +
		//"<input type=\"text\" name=\"county\" value=\"" + county + "\" /><br />" +
		"<input type=\"text\" name=\"state\" value=\"" + state + "\" /><br />" +
		"<input type=\"text\" name=\"country\" value=\"" + country + "\" /><br />" +
		"</div>" +
		
		"<input type=\"submit\" name=\"button\" id=\"button\" value=\"Add This Spot!\" onclick=\"this.style.display=\'none\'; $(\'hitchSpin\').style.display=\'block\';\" /><span id=\"hitchSpin\" style=\"display:none\"><img src=\"/images/loading.gif\" /></span><input type=\"hidden\" name=\"MM_insert\" value=\"hitchhiking_spots_form\" /></form></div>"

		map.openInfoWindow(hitchPoint, hitchWindowContent);
	}
		
	geocoder.getLocations(hitchPoint, parseGeocode) 
		

	
	
	
	
}

function addStaySpot() {
	
	contextmenu.style.visibility="hidden";
    var stayPoint = map.fromContainerPixelToLatLng(clickedPixel)
	map.openInfoWindow(stayPoint, "<div id='mapStayAdd' style='height:200px'>loading...</div>");
	advAJAX("/neededHead?draw=drawAddStay&ref=map&addy=" + stayPoint, "mapStayAdd");

}

function zoomInHere() {
        // perform the requested operation
        contextmenu.style.visibility="hidden";
        var point = map.fromContainerPixelToLatLng(clickedPixel)
        map.zoomIn(point,true);
        // hide the context menu now that it has been used
        
      } 


// ** USES old Variables

function attachInfoWindow(marker, myHtml) {

  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(myHtml);
  });
}

function grabWeatherAddToMap(pointsArray) {
	
	// Takes an array of lat/lng/zip and fetches weather from yahoo, then places marker with icon on the map
	
	var weatherLat = pointsArray[p]['lat']
	var weatherLng = pointsArray[p]['lng']
	
	var feed = new google.feeds.Feed("http://weather.yahooapis.com/forecastrss?p=" + pointsArray[p]['zip_code']);
	feed.setResultFormat(google.feeds.Feed.XML_FORMAT);
	feed.load(function(result) {
	  //var container = document.getElementById("Yweather");
	  if (!result.error) {
		var items = result.xmlDocument.getElementsByTagName("item");
		for (var i = 0; i < items.length; i++) {
		  var titleElement = items[i].getElementsByTagName("title")[0];
		  var title = titleElement.firstChild.nodeValue;
		  
		  var descElement = items[i].getElementsByTagName("description")[0];
		  var desc = descElement.firstChild.nodeValue;
		  var descAdv = title + "<br />" + desc
		  
		  //get weather conditions image from description
		  var a = desc.split("img src=\"");

		  var b = a[1].split(".gif");
		  var weatherIMG = b[0] + ".gif";

			//alert(weatherIMG)
			weatherIcon = new google.maps.Icon();
			weatherIcon.image = weatherIMG;
			weatherIcon.shadow = "images/friend_map_shadow.png";
			weatherIcon.iconSize = new google.maps.Size(26, 26);
			weatherIcon.shadowSize = new google.maps.Size(26, 26);
			weatherIcon.iconAnchor = new google.maps.Point(13, 13);
			weatherIcon.infoWindowAnchor = new google.maps.Point(5, 1);
			
			//alert("munch")
		  
			var weatherPoint = new google.maps.LatLng(weatherLat, weatherLng)
//alert("kokpokp")		  
			weatherMarker[p] = new google.maps.Marker(weatherPoint, {icon:weatherIcon})   
			//weatherMarker[i] = new google.maps.Marker(weatherPoint)   
			
			map.addOverlay(weatherMarker[p]);
			//alert("marker added")
		
			
			/*
			google.maps.Event.addListener(weatherMarker[i], "click", function() {
				alert("clicked")
				weatherMarker[i].openInfoWindowHtml(desc);
			});
			*/
			attachInfoWindow(weatherMarker[p], descAdv)
			
		
		  
		  
		}
	  }
	  
	  p++;
	  if (p<pointsArray.length) {
		  grabWeatherAddToMap(pointsArray)
	  }
	  
	});
	
}

function directionsLoad(spotType) {
   
    if (spotType=="latlong") {
        latlngFrom = new google.maps.LatLng(startMarker.getPoint().lat(),startMarker.getPoint().lng());
        latlngTo = new google.maps.LatLng(endMarker.getPoint().lat(),endMarker.getPoint().lng());

        geocoder.getLocations(latlngFrom, function(addresses) {
            if(addresses.Status.code != 200) {
                alert("reverse geocoder failed to find an address for " + latlngFrom.toUrlValue());
            } else {
                structureFrom = addresses.Placemark[0];
            }
        });
        
        geocoder.getLocations(latlngTo, function(addresses) {
            if(addresses.Status.code != 200) {
                alert("reverse geocoder failed to find an address for " + latlngTo.toUrlValue());
            } else {
                structureTo = addresses.Placemark[0];
            }
        });
    }
    

	
    routeBox = $('dirBox')
    //directions = new google.maps.Directions(map, routeBox);
    //directions.load(starting + " to " + ending);
    directions = new google.maps.Directions();
    directions.load(structureFrom + " to " + structureTo,{ getPolyline:true, getSteps:true });
    //google.maps.Event.addListener(directions, "load", onGDirectionsLoad); 
	google.maps.Event.addListener(directions, "load", function() {
		
		
		

		
		
		
		var goodPoly = directions.getPolyline();
		//alert(goodPoly.getVertexCount())
			
			
		// function is called after multiGeocode
		/*
		postMultiGeo = function () {
			
			weatherMarker = Array();

			// sets initial array index to start with, geoResults
			p=0;

			// initial call, is looped at end of function because google feed api take a second to grab each one
			grabWeatherAddToMap();
			
		}
		*/
	
		
		midPointNum = Math.round(goodPoly.getVertexCount() / 2)
		midPoint = goodPoly.getVertex(midPointNum)
		
		midPoints = Array()
		vertexCount = 5;
		for (v=0; vertexCount<goodPoly.getVertexCount(); v++) {
			midPoints[v] = goodPoly.getVertex(vertexCount)
			vertexCount = vertexCount + 500
		}

		//multiGeocode(midPoints);
		
		// weather along route
		
		if (midPoints!="") {
			new multiGeocode(midPoints, function (resultsArray) {
				weatherMarker = Array();
				// sets initial array index to start with, geoResults
				p=0;
				// initial call, is looped at end of function because google feed api take a second to grab each one
				
				grabWeatherAddToMap(resultsArray);
				
				jQuery.getScript("http://www.automotive.com/gas-prices/gaspricewidgetfeed.html?zip=" + resultsArray[0]['zip_code'], function(){
					//go go gadget gas	
					
					var str = $('spPrice').innerHTML
					var perGallon = parseFloat(str.substr(1))
					
					//var mileDis = parseFloat(directions.getDistance().html)
					var mileDis = directions.getDistance().meters/1609.344
					
					var milePerGallon = 25;
					var tripPrice = (mileDis/milePerGallon) * perGallon
					var rounded_total = Math.round(tripPrice)
					$('total_gas_price').innerHTML = "$" + rounded_total;
					
					
				});
				
				
				
			
			});
		}
		

			
		
		

		goodPoly.weight=10
		//goodPoly.color="#664500"
		
		map.addOverlay(goodPoly)
		
		 var bounds = directions.getBounds(); 
		 
		 map.setCenter( bounds.getCenter(), map.getBoundsZoomLevel(bounds) ); 
		
		dirDesc = ""
		for (x=0; x<directions.getRoute(0).getNumSteps(); x=x+1) {
			var dirDesc = dirDesc + directions.getRoute(0).getStep(x).getDescriptionHtml() + "<br />"
		}
		// fill directions box
		$('dirBox').innerHTML = dirDesc
		
		// fill basic trip details, mileage and time estimate
		var container = $("directionsLink");
		var distanceData = $("distanceData");
		container.innerHTML = "Directions <span class='simpetext'>" + directions.getDistance().html + " (" + directions.getDuration().html + ")</span>";
		distanceData.innerHTML = directions.getDistance().html + " (" + directions.getDuration().html + ")"; 
		
		
		// GAS!!!
		// get zip code using lat long, as city doesn't always cut it... hacky
		//postGeoSuccess = function () {
			
			//jQuery.getScript("http://www.automotive.com/gas-prices/gaspricewidgetfeed.html?zip=" + geoResult['zip_code'], function(){
				/*
			jQuery.getScript("http://www.automotive.com/gas-prices/gaspricewidgetfeed.html?zip=" + resultsArray[0]['zip_code'], function(){
				//go go gadget gas	
				
				var str = $('spPrice').innerHTML
				var perGallon = parseFloat(str.substr(1))
				
				//var mileDis = parseFloat(directions.getDistance().html)
				var mileDis = directions.getDistance().meters/1609.344
				
				var milePerGallon = 25;
				var tripPrice = (mileDis/milePerGallon) * perGallon
				var rounded_total = 
Math.round(tripPrice)
				$('total_gas_price').innerHTML = "$" + rounded_total;
				
				
			});
			*/
		//}
		
		//geocoder.getLocations(latFrom + "," + lngFrom, parseGeocode);	
		
		
		
		
		
		
		
		
		
		
		
	}); 

}

function addStartEndMarkers() {

    mapLoaded = false
    directionsLoad("place")

    if (typeof(latFrom)!="undefined") {
    
        //var currentIcon = MapIconMaker.createMarkerIcon({width: 30, height: 30, primaryColor: "#006600"});
		var currentIcon = tripStartIcon
        var startPoint = new google.maps.LatLng(latFrom, lngFrom)
        startMarker = new google.maps.Marker(startPoint, {icon: currentIcon, draggable: true});    
        map.addOverlay(startMarker);
        
        
        
        google.maps.Event.addListener(startMarker, "click", function() {
            map.setCenter(new google.maps.LatLng(latFrom, lngFrom), 11);
            startMarker.openInfoWindowHtml(cityFrom);
        });
    
//      google.maps.Event.addListener(startMarker, "drag", function() {
//          directionsLoad("latlong")
//      });
        
        google.maps.Event.addListener(startMarker, "dragstart", function() {
            map.closeInfoWindow();
        });
            
        google.maps.Event.addListener(startMarker, "dragend", function() {
            reverseit('start')
			/*	var sY = new google.maps.LatLng(startMarker.getPoint().lat(),startMarker.getPoint().lng());
			multiGeocode(sY, $('destination').value) */
        });
  
    }

    if (typeof(latTo)!="undefined" && latTo!="") {
        //var currentIcon = MapIconMaker.createMarkerIcon({width: 30, height: 30, primaryColor: "#990000"});
		var currentIcon = tripEndIcon
        var endPoint = new google.maps.LatLng(latTo, lngTo)
        endMarker = new google.maps.Marker(endPoint, {icon: currentIcon, draggable: true});
        map.addOverlay(endMarker);
        
        //bound code
        var searchBounds = map.getBounds()
        searchBounds.extend(startPoint)
        searchBounds.extend(endPoint)
        map.setCenter( searchBounds.getCenter(), map.getBoundsZoomLevel(searchBounds) );
        
        
        google.maps.Event.addListener(endMarker, "click", function() {
            map.setCenter(new google.maps.LatLng(latTo, lngTo), 11);
            endMarker.openInfoWindowHtml(cityTo);
        }); 
        
//      google.maps.Event.addListener(endMarker, "drag", function() {
//          directionsLoad("latlong")
//      });
        
        google.maps.Event.addListener(endMarker, "dragstart", function() {
            map.closeInfoWindow();
        });
            
        google.maps.Event.addListener(endMarker, "dragend", function() {
            reverseit('end')
        });
    }
    mapLoaded = true

}

// END old USAGE OF Variable

function createRegMarker(point, infobox, pickIcon) {
    var marker = new google.maps.Marker(point, pickIcon);
    google.maps.Event.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(infobox);
    });
    
    /*
    google.maps.Event.addListener(marker, "mouseover", function() {
        marker.openInfoWindowHtml(infobox);
      });
     */
    
    return marker;
}

function createLocationMarker(point, infobox, pickIcon, labelCount) {
  //var marker = new google.maps.Marker(point, pickIcon);
  var marker = new LabeledMarker(point, {icon: pickIcon, labelText: labelCount, labelOffset: new google.maps.Size(-4, -30)});
  //marker.mycategory="userYou"

  google.maps.Event.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(infobox);
  });

    google.maps.Event.addListener(marker, "mouseover", function() {
    marker.openInfoWindowHtml(infobox);
  });
  return marker;
}

function createYouMarker(point, infobox, pickIcon, markerCount, labelCount) {
	//youCount += 1
  youMarker[markerCount] = new LabeledMarker(point, {icon: pickIcon, labelText: labelCount, labelOffset: new google.maps.Size(-4, -30)});
  youMarker[markerCount].mycategory="userYou"
	  
	  var thisMarker = youMarker[markerCount]

  google.maps.Event.addListener(thisMarker, "click", function() {
    //youMarker[youCount].openInfoWindowHtml(infobox);
	thisMarker.openInfoWindowHtml(infobox)
  });

    google.maps.Event.addListener(thisMarker, "mouseover", function() {
    //youMarker[youCount].openInfoWindowHtml(infobox);
	thisMarker.openInfoWindowHtml(infobox)
  });
  
  return youMarker[markerCount];
  
	  
}


// * DOES NOT use OLD VARIABLES

function ridesToMap() {
	
	/*
    var iconStart = new google.maps.Icon();
            iconStart.image = "http://triphopping.com/images/start.png";
            iconStart.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
            iconStart.iconSize = new google.maps.Size(21, 34);
            iconStart.shadowSize = new google.maps.Size(22, 20);
            iconStart.iconAnchor = new google.maps.Point(10, 34);
            iconStart.infoWindowAnchor = new google.maps.Point(5, 1);
            */
				
    var iconEnd = new google.maps.Icon();
            iconEnd.image = "http://triphopping.com/images/ride_end.png";
            iconEnd.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
            iconEnd.iconSize = new google.maps.Size(16, 16);
            iconEnd.shadowSize = new google.maps.Size(22, 20);
            //iconEnd.iconAnchor = new google.maps.Point(10, 34);
			iconEnd.iconAnchor = new google.maps.Point(8, 8);
            iconEnd.infoWindowAnchor = new google.maps.Point(5, 1);
            
    var iconStop = new google.maps.Icon();
            iconStop.image = "http://triphopping.com/images/pause.png";
            iconStop.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
            iconStop.iconSize = new google.maps.Size(21, 34);
            iconStop.shadowSize = new google.maps.Size(22, 20);
			
	var iconOffer = new google.maps.Icon();
            iconOffer.image = "http://triphopping.com/images/car.png";
            iconOffer.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
            iconOffer.iconSize = new google.maps.Size(16, 16);
            iconOffer.shadowSize = new google.maps.Size(22, 20);
            iconOffer.iconAnchor = new google.maps.Point(8, 8);
            iconOffer.infoWindowAnchor = new google.maps.Point(5, 1);
			
	var iconRequest = new google.maps.Icon();
            iconRequest.image = "http://triphopping.com/images/thumb_up.png";
            iconRequest.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
            iconRequest.iconSize = new google.maps.Size(16, 16);
            iconRequest.shadowSize = new google.maps.Size(22, 20);
            iconRequest.iconAnchor = new google.maps.Point(8, 8);
            iconRequest.infoWindowAnchor = new google.maps.Point(5, 1);
    
	iconStop.iconAnchor = new google.maps.Point(10, 34);
            iconStop.infoWindowAnchor = new google.maps.Point(5, 1);


    // draw lines and points where rides are
	rideDirections = new Array();

    for (var y=0; y<rideInfo.length; y++) {
		
		if (rideInfo[y]['type']=="offer") {
			var lineColor = "#009900"
			var thisRideIcon = iconOffer
		} else {
			var lineColor = "#ff3300"
			var thisRideIcon = iconRequest
		}
			
		
		
		if (typeof(rideInfo[y]['end_lat'])!="undefined" && rideInfo[y]['end_lat']!="") {
			/*
			// Show direct lines
			var polyline = new google.maps.Polyline([
				new google.maps.LatLng(rideInfo[y]['start_lat'], rideInfo[y]['start_lng']), 
				new google.maps.LatLng(rideInfo[y]['end_lat'], rideInfo[y]['end_lng'])
			], lineColor, 5);
			map.addOverlay(polyline);
			*/
			
			// show route instead
			rideDirections[y] = new google.maps.Directions();
			rideDirections[y].load(rideInfo[y]['start_place'] + " to " + rideInfo[y]['end_place'],{ getPolyline:true, getSteps:true });

			var test = y;
			var a = function(arg, color){
				return function(evt){
					
					try{
						
						rideDirections[arg].getPolyline().color=color; 
						map.addOverlay(rideDirections[arg].getPolyline());
						
						//alert(arg + rideDirections[arg].getVertexCount())
					}
					catch(e) {
					}
					
				}
			}

			google.maps.Event.addListener(rideDirections[y], "load", a(test, lineColor)); 
			
			google.maps.Event.addListener(rideDirections[y], "error", function() { 
			  //alert("error" + y) 
			}); 
	
		}
        
        var rideContent = "<a href=\"#/people/" + rideInfo[y]['username'] + "\" onclick=\"loadProfile(\'" + rideInfo[y]['username'] + "\')\"><img src=\"" + rideInfo[y]['pic_url'] + "\" align=\"left\" hspace=\"5px\" /></a>" + rideInfo[y]['type'] + " <span class=\"startPlace\">" + rideInfo[y]['start_place'] + "</span> to <span class=\"endPlace\">" + rideInfo[y]['end_place'] + "</span><br>Leaving on: <strong>" + rideInfo[y]['leave_date'] + "</strong><br>posted by: <a href=\"#/people/" + rideInfo[y]['username'] + "\" onclick=\"loadProfile(\'" + rideInfo[y]['username'] + "\')\">" + rideInfo[y]['name'] + "</a><br>Your cost: " + rideInfo[y]['cost'] + " - <a href=\"#\" onclick=\"rideLoad('" + rideInfo[y]['entry_id'] + "')\">more info&raquo;</a>";
        
        var ridePoint1 = new google.maps.LatLng(rideInfo[y]['start_lat'], rideInfo[y]['start_lng']);
        map.addOverlay(createRegMarker(ridePoint1, rideContent, thisRideIcon)); 
    
		if (typeof(rideInfo[y]['end_lat'])!="undefined" && rideInfo[y]['end_lat']!="") {
			var ridePoint2 = new google.maps.LatLng(rideInfo[y]['end_lat'], rideInfo[y]['end_lng']);
			map.addOverlay(createRegMarker(ridePoint2, rideContent, iconEnd)); 
		}
    
    }

}

function flashLines(num) {
	
	if (rideInfo[num]['type']=="offer") {
		var oColor = "#009900"
	} else {
		var oColor = "#ff3300"
	}
	//oColor = rideDirections[num].getPolyline().color

	map.removeOverlay(rideDirections[num].getPolyline());
	
	rideDirections[num].getPolyline().color="#000"; 
	
	map.addOverlay(rideDirections[num].getPolyline())
 
	window.setTimeout(function() {map.removeOverlay(rideDirections[num].getPolyline()); rideDirections[num].getPolyline().color=oColor; map.addOverlay(rideDirections[num].getPolyline())}, 300);

}
 
function greyLocation(stationAddress, id) {
	
	var address = stationAddress
	currentGHID = id
	geocoder.getLocations(address, addGreyToMap);    
}

function addGreyToMap(response) {
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	} else {
		place = response.Placemark[0];
		point = new google.maps.LatLng(place.Point.coordinates[1],
							place.Point.coordinates[0]);
		marker = new google.maps.Marker(point);
	}
	map.addOverlay(marker);
	marker.openInfoWindowHtml("<strong>Greyhound Station</strong><br />" + place.address + "<br /><a href='http://www.greyhound.com/home/TicketCenter/en/terminal.asp?city=" + currentGHID + "'>More Info</a>");
	map.setCenter(new google.maps.LatLng(place.Point.coordinates[1], place.Point.coordinates[0]), 13); 
}

function showLocation() {
	
	if (typeof(map)=="undefined") {
		oonLoad();
	} //new
	
	if (document.mapSearchForm.origin.value!="" && document.mapSearchForm.origin.value!="From") {
		x=0
		address = document.mapSearchForm.origin.value;
		//new code
		postGeoSuccess = function () {
			if (x!=1) {
				structureFrom = ""
				FromString = "?style=script"
				structureFrom = place.address
				FromString += "&structure1=" + structureFrom
				if (typeof streetLine!="undefined") {
					FromString += "&address1=" + streetLine
					
				}
				if (typeof city!="undefined") {
					FromString += "&city1=" + city 
					cityFrom = city
				}
				
				if (typeof zip!="undefined") {
					FromString += "&zip1=" + zip 
					zipFrom = zip
				}
				
				if (typeof county!="undefined") {
					FromString += "&county1=" + county 
					countyFrom = county
				}
				
				if (typeof state!="undefined") {		
					FromString += "&state1=" + state
					stateFrom = state
				}
				if (typeof country!="undefined") {
					FromString += "&country1=" + country
					countryFrom = country
				}
				if (typeof point!="undefined") {
					FromString += "&point1=" + latlong
					latFrom = place.Point.coordinates[1]
					lngFrom = place.Point.coordinates[0]
				}
				x = 1
				if (document.mapSearchForm.destination.value!="" && document.mapSearchForm.destination.value!="To") {
					address = document.mapSearchForm.destination.value;
					geocoder.getLocations(address, parseGeocode);
				} else {
					//window.location = FromString
					getString = FromString
					updateTravelContent(getString)
				}
			} else {
				structureTo = ""
				ToString = ""
				structureTo = place.address
				ToString += "&structure2=" + structureTo
				if (typeof streetLine!="undefined") {
					ToString += "&address2=" + streetLine
					
				}
				if (typeof city!="undefined") {
					ToString += "&city2=" + city 
					cityTo = city
				}
				if (typeof zip!="undefined") {
					ToString += "&zip2=" + zip 
					zipTo = zip
				}
				if (typeof state!="undefined") {		
					ToString += "&state2=" + state
					stateTo = state
				}
				
				if (typeof county!="undefined") {
					ToString += "&county2=" + county 
					countyTo = county
				}
				
				if (typeof country!="undefined") {
					ToString += "&country2=" + country
					countryTo = country
				}
				if (typeof point!="undefined") {
					ToString += "&point2=" + latlong
					latTo = place.Point.coordinates[1]
					lngTo = place.Point.coordinates[0]
				}
				var goodpage = "http://www.triphopping.com/" + $('geoPageLink').value;
				getString = FromString + "&" + ToString
				
				//window.location = goodpage + FromString + "&" + ToString
				updateTravelContent(getString)
			}
		} // end success code
		// end new code
		cityFrom = "";
		cityTo = "";
		stateFrom = "";
		stateTo = "";
		countryFrom = "";
		countryTo = "";
		structureFrom = "";
		structureTo = "";
		latFrom = "";
		lngFrom = "";
		latTo = "";
		lngTo = "";
		geocoder.getLocations(address, parseGeocode);  
		
	} else {
		//alert("Enter a start location")
		updateTravelContent('?style=script');
	}
}

function updateTravelContent(urlstr, tab) { 

	preLoaded=false;
	if (recentToggleDiv=="explore") {
		
		if (exploreLoaded==urlstr) {
			preLoaded = true;
		} else {
			var url="/exploreContent.php" + urlstr
			mateDiv = 'exploreDiv'
			exploreLoaded=urlstr
		}
		
		map.clearOverlays(); 
		map.setCenter(new google.maps.LatLng(latFrom,lngFrom), 13); 
		
		var exploreIcon = currentLocationIcon
        var explorePoint = new google.maps.LatLng(latFrom, lngFrom)
        exploreMarker = new google.maps.Marker(explorePoint, {icon: exploreIcon, draggable: true});
        map.addOverlay(exploreMarker);
	
	} else if (recentToggleDiv=="stay") {
		
		if (stayLoaded==urlstr) {
			preLoaded = true;
		} else {
			var url="/stayContent.php" + urlstr
			mateDiv = 'stayDiv'
			stayLoaded=urlstr
		}
		
		map.clearOverlays(); 
		if (latTo!="") {
			map.setCenter(new google.maps.LatLng(latTo,lngTo), 13); 
		}
		
	} else {
		
		map.clearOverlays(); 
		if (travelLoaded==urlstr) {
			preLoaded = true;

			mainTabs('travelLink', 'travel')

			ridesToMap()
			addStartEndMarkers()
		} else {
			var url="/travelContent.php" + urlstr
			mateDiv = "travelInfo"
			travelLoaded=urlstr
		}
		
	}
			
	url=url+"&sid="+Math.random()
	travelURL = url
	
	
	if (preLoaded!=true) {
		
		$(mateDiv).innerHTML = "<img src=\"/images/earth_spin.gif\" /> ah, travel...";
		
		
		$('alertBorder').className = "alertBorderLoading";
		$('taskStatus').innerHTML = "loading..."
		$('taskStatus').style.display="inline"
		
		if (recentToggleDiv!="travel" && recentToggleDiv!="explore" && recentToggleDiv!="stay") {
			recentToggleLink = "travelLink"
			recentToggleDiv = "travel"	
		}
		
		//sideToggle(recentToggleLink, recentToggleDiv)
		mainTabs(recentToggleLink, recentToggleDiv)

			
				
		new Ajax.Request(url, {
			onSuccess: function(transport) {
							
				updatedResult = transport.responseText
				
				javaHtmlSplit = updatedResult.split("####ride javascript####")
				
			
				
				if (javaHtmlSplit[0]!="") {
					$(mateDiv).innerHTML=javaHtmlSplit[0] 
				} else {
					$(mateDiv).innerHTML=updatedResult
				}
				
	
				//$("sideHolder").style.display="block";
				sizeMap()
				
			
					
				if (recentToggleDiv=="travel") {
					$('optionContainer').show()
						
					if (latFrom && latTo) {
						jQuery('#gas_and_directions').show()
					}

					map.clearOverlays(); 
					
					if (latFrom || latTo) {
						
						rideInfo = null;
						rideInfo = new Array();
						// Open the students.xml file
						var ride_xml_url = "ride_xml?lat_from=" + latFrom + "&lng_from=" + lngFrom
						if (latTo) {
							ride_xml_url += "&lat_to=" + latTo + "&lng_to=" + lngTo
						}

						
						jQuery.get(ride_xml_url,{},function(xml){
							// Run the function for each ride tag in the XML file
					
							var arr_num = 0
							
							jQuery('ride',xml).each(function(i) {
								//alert("in there")
								var f = jQuery(this).find("entry_id").text()
								//alert(f)
									
								rideInfo[arr_num] = {
									start_lat:jQuery(this).find("start_lat").text(), 	
									start_lng:jQuery(this).find("start_lng").text(), 
									end_lat:jQuery(this).find("end_lat").text(), 
									end_lng:jQuery(this).find("end_lng").text(), 
									start_place:jQuery(this).find("start_place").text(),	
									end_place:jQuery(this).find("end_place").text(),
									start_city:jQuery(this).find("start_city").text(), 
									end_city:jQuery(this).find("end_city").text(), 
									start_state:jQuery(this).find("start_state").text(), 
									end_state:jQuery(this).find("end_state").text(), 
									leave_date:jQuery(this).find("leave_date").text(), 
									username:jQuery(this).find("username").text(), 
									name:jQuery(this).find("name").text(), 
									pic_url:jQuery(this).find("pic_url").text(), 
									cost:jQuery(this).find("cost").text(), 
									entry_id:jQuery(this).find("entry_id").text(), 
									type:jQuery(this).find("type").text(), 
									mpg:jQuery(this).find("mpg").text()
								};
							
								// Use it!
						
							
								arr_num = arr_num + 1;

						
							});
					
							//alert("out")
							//alert(rideInfo[0]['start_lng'])
							//alert(rideInfo[0]['start_place'])
							//alert("pass")
							ridesToMap()
							addStartEndMarkers()

						});
				
						for (x=1; x<javaHtmlSplit.length; x++) {
							eval(javaHtmlSplit[x])
						}
				
						
						
						//craigUpdate($('craigSelect').value);
						entriesShown = 20
						externalRidesTest($('newIdea'));
					
						// CS Ride Share
						//CSridesharePull("http://www.couchsurfing.org/feeds/group_rss.php?gid=658");
						// Ride Share USA
						//CSridesharePull("http://www.couchsurfing.org/feeds/group_rss.php?gid=5691");
						// Ridesurfing USA
						//CSridesharePull("http://www.couchsurfing.org/feeds/group_rss.php?gid=2227");
						// Ride Share Canada
						//CSridesharePull("http://www.couchsurfing.org/feeds/group_rss.php?gid=3440");
						
							
						
					
						GSCLoad(structureFrom + " to " + structureTo, "travel");
						new Ajax.Request('/expediaJavascript.php' + getString, {
						  onSuccess: function(transport) {
							  eval(transport.responseText)
						  }
						});	
					}
					

					
					// Keep sub tab persistent, Rides.Hithhike.Transit.Links
					//this one line is simpler than the lines below, but IE is a POS
					//jQuery("#travelSelect a[style*=bold]").click()
					
					/* Useless with new change to snippets
					var selectedSubTab = jQuery("#travelSelect a")
					for (i=0; i<selectedSubTab.length; i++) {
						if (selectedSubTab[i].className=='selectedSecond') {
							jQuery(selectedSubTab[i]).click();
							break;
						}
					}
					*/
					
				} else if (recentToggleDiv=="stay") {
					
					if (latTo!="") {
						//GLocalSearchControl.execute('hotels OR hostels')	
						searchGooglebar('hotels OR hostels')
						
						GSCLoad(structureTo, "stay");
						new Ajax.Request('/expediaJavascript.php' + getString + "&dealType=hotel", {
						  onSuccess: function(transport) {
							  eval(transport.responseText)
						  }
						});
					
						showStaySpots(latTo, lngTo, 100)
					}
					
				} else if (recentToggleDiv=="explore") {

					csGroups($('csSelect').value, $('CS_group_content'), 30);
	
					// *** start get zip ***

					var find_zip = new Array();
		
					find_zip[0] = latFrom + "," + lngFrom
					
					
					new multiGeocode(find_zip, function (resultsArray) {

						var explore_zip = resultsArray[0]['zip_code'];
						
						var feed = new google.feeds.Feed("http://weather.yahooapis.com/forecastrss?p=" + explore_zip);
						feed.setResultFormat(google.feeds.Feed.XML_FORMAT);
						feed.load(function(result) {
						  //var container = document.getElementById("Yweather");
						  if (!result.error) {
							var items = result.xmlDocument.getElementsByTagName("item");
							for (var i = 0; i < items.length; i++) {
							  var titleElement = items[i].getElementsByTagName("title")[0];
							  var title = titleElement.firstChild.nodeValue;
							  
							  var descElement = items[i].getElementsByTagName("description")[0];
							  var desc = descElement.firstChild.nodeValue;
							  var descAdv = title + "<br />" + desc
							  
							  //get weather conditions image from description
							  var a = desc.split("img src=\"");

							  var b = a[1].split(".gif");
							  var weatherIMG = b[0] + ".gif";
							  
							  var weatherIMG = "<img src=\"" + weatherIMG + "\" />"
								  
								var comp = weatherIMG;

								
								//alert("munch")
							  
								
							//$('exploreWeather').innerHTML = descAdv
							$('exploreWeather').innerHTML = weatherIMG
								
							
							  
							  
							}
						  }
						  
						 
						  
						});
						
					
						
					});
					
					// *** end get zip ***
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
				}
				
				
				/*
				if (stateFrom == "NY" || stateFrom == "CT") { 
					//metroNorth(); 
					//longIsland();
					//subwaySelect();
				}
				*/
	
				// Let user know that they're good to go
				$('alertBorder').className = "alertBorderFinish";
				$('taskStatus').innerHTML = "Finished!";
				setTimeout('$(\'alertBorder\').className = \'alertBorder\'; $(\'taskStatus\').style.display=\'none\'',100)			
				
			}
		});
			
	} //end if preloaded!=true	
}

function travel(origin, destination) {
	
	if (origin!="current") {
		document.mapSearchForm.origin.value = origin;
	}
    if (typeof(destination)!="undefined") {
		location.hash="travel/" + origin + "/" + destination
        document.mapSearchForm.destination.value = destination;
    } else {
		location.hash="travel/" + origin
	}
	mainTabs("travelLink", "travel")
    showLocation()
}

function explore(dest) {
	$('origin').value=dest
	if (!$('origin').value) {
		$('origin').value = dest
	}
	mainTabs("exploreLink", "explore")
	showLocation();
}

function stay(dest) {
	
	$('destination').value=dest
	if (!$('origin').value) {
		$('origin').value = dest
	}
		
	mainTabs("stayLink", "stay")
	showLocation()
	
}

function addHubToList() {
			
			var container = $('route_list');

			var divFinal = document.createElement("div");
			divFinal.innerHTML = "<table style=\"background-color:#fff; border:1px solid #a5c98b; display:block; margin-top:11px\"><tr><td><span class=\"form_items\">Name</span><br /><input name=\"station_name[]\" type=\"text\" size=\"20\" onkeypress=\"return handleEnter(this, event)\" /><br /><span class=\"simpetext\">\"Grand Central\"</span></td><td><span class=\"form_items\">Address *</span><br /><input name=\"station_address[]\" type=\"text\" size=\"35\" onkeypress=\"return handleEnter(this, event)\" /><br /><span class=\"simpetext\">\"15 Vanderbilt Ave, New York, NY\"</span></td></tr><tr><td colspan=2><span class=\"form_items\" style=\"color:#4d7f5d\">URL Value</span>: <input name=\"URL_value[]\" type=\"text\" size=\"10\" onkeypress=\"return handleEnter(this, event)\" />	<span class=\"simpetext\">\"New York, NY\"</span><input type=\"hidden\" name=\"station_street[]\" /><input type=\"hidden\" name=\"station_city[]\" /><input type=\"hidden\" name=\"station_state[]\" /><input type=\"hidden\" name=\"station_country[]\" /><input type=\"hidden\" name=\"station_lat[]\" /><input type=\"hidden\" name=\"station_lng[]\" /><input type=\"hidden\" name=\"station_id[]\" /></td></tr><tr><td></td></tr></table><a href=\"#\" onclick=\"$(this).previous(0).innerHTML=''; $(this).hide()\">remove</a>"
				
			container.appendChild(divFinal);
		
		}
		
		
		function displayRoutes() {
			
			var route_content = "";
			var station_names = document.getElementsByName('station_name[]');
			var station_addresses = document.getElementsByName('station_address[]');
			var stations_vals = document.getElementsByName('URL_value[]');
			var station_streets = document.getElementsByName('station_street[]');
			var station_cities = document.getElementsByName('station_city[]');
			var station_states = document.getElementsByName('station_state[]');
			var station_countries = document.getElementsByName('station_country[]');
			var station_lats = document.getElementsByName('station_lat[]');
			var station_lngs = document.getElementsByName('station_lng[]');
			var station_IDs = document.getElementsByName('station_ID[]');

			// create manageable array
			addysToGeo = new Array();
			for (h=0; h<station_addresses.length; h++) {
				addysToGeo[h] = station_addresses[h].value
			}	
	
			// fill form with geo specifics 
			new multiGeocode(addysToGeo, function (resultArray) {
				x=0;
				resultArray.each(function(s) {
					station_streets[x].value = s['street_address']
					station_cities[x].value = s['city']
					station_states[x].value = s['state']
					station_countries[x].value = s['country']
					station_lats[x].value = s['lat']
					station_lngs[x].value = s['lng']
					x++;
				});
				
				new Ajax.Request('/neededHead?function=add_hubs&c_id=' + $('company_select').value, {
				  onSuccess: function(ajaxResult) {
					  
					  eval(ajaxResult.responseText);

				  }
				});
				
				
				for (i=0; i<station_names.length; i++) {
				
					var gip = (i+1)
					for (x=gip; x<station_names.length; x++) {
						route_content += "<table><tr><td><strong>" + station_names[i].value + "</strong><br /><span class=\"simpetext\">" + station_cities[i].value + ", " + station_states[i].value + "</span></td><td><></td><td><strong>" + station_names[x].value + "</strong><br /><span class=\"simpetext\">" + station_cities[x].value + ", " + station_states[x].value + "</span></td></tr><tr><td colspan=3><span class=\"form_items\">Cost one way: </span><input name=\"cost_ow[]\" type=\"text\" size=\"8\" /> <span class=\"form_items\">Cost roundtrip: </span><input name=\"cost_rt[]\" type=\"text\" size=\"8\" /></td></tr></table><a href=\"#\" onclick=\"$(this).previous(0).innerHTML=''; $(this).hide()\">remove route</a><br /><br />";
					}
								
				}
				
				$('routeList').innerHTML = route_content;

			});

		}







// gas
function IsNumeric(sText) { var ValidChars = "0123456789"; var IsNumber=true; var Char; for (i = 0; i < sText.length && IsNumber == true; i++) {Char = sText.charAt(i); if (ValidChars.indexOf(Char) == -1) { IsNumber = false; } } return IsNumber; } function clearTextBox(myTextBoxID) { document.getElementById(myTextBoxID).value = ""; } function defaultSubmit(myEvent, submitButtonID) { if(myEvent.keyCode==13) { myEvent.keyCode = null; window.document.getElementById(submitButtonID).click(); } return true; } function automotiveRedirect(myTextBoxID) { var myTextBoxValue = document.getElementById(myTextBoxID).value; if (!IsNumeric(myTextBoxValue)) { window.open = "http://www.automotive.com/gas-prices/index.html"; } else { window.open = "http://www.automotive.com/gas-prices/results.html?zip=" + myTextBoxValue; } }
