function getPlacemarkProperty(placemark,propertyname) {
	for (var property in placemark) {
		if((property == propertyname)) {
			return String(placemark[property]);
		} else if (typeof(placemark[property]) == 'object') {
			var r = getPlacemarkProperty(placemark[property], propertyname);
			if (r != null) return r;
		}
	}
	return null;
}
// link the route to workout while viewing the route
function linkToWorkout(routeId, from, itemId){
	var newDuration = getNewDuration();
	var newPace = $('pace').value;
	if (newPace == 'undefined'){
		newPace = '';
	}
	document.forms[0].action ='linkRoute.do?routeId='+routeId+'&itemId='+itemId+'&from='+unescape(from)
		+'&command=link&newDuration='+newDuration+'&newPace='+newPace+"&fromLinking="+$('importToWorkout').checked;
 	document.forms[0].method='POST';
 	document.forms[0].submit();
}

// link the route to adding workout, it's a little different, because the workout has not added to db yet
function linkToAddingWorkout(routeId, year, month, day, workoutId, logWorkout){
	var newDuration = getNewDuration();
	var newPace = $('pace').value;
	document.forms[0].action ='addWorkoutStep1.do?selectedMenuItemId=17&year='+year+'&month='+month+'&day='+day+'&workoutId='+workoutId
	+'&next=next&linkedRouteId='+routeId+'&newDuration='+newDuration+'&newPace='+newPace+'&logWorkout='+logWorkout+"&fromLinking="+$('importToWorkout').checked+"&timedOut=false";
	document.forms[0].method='POST';
 	document.forms[0].submit();
}

function cancelLinkingToAddingWorkout(year, month, day, workoutId, logWorkout){
	document.forms[0].action ='addWorkoutStep1.do?selectedMenuItemId=17&year='+year+'&month='+month+'&day='+day+'&workoutId='+workoutId+'&next=next&logWorkout='+logWorkout+"&timedOut=false";
	document.forms[0].method='POST';
 	document.forms[0].submit();
}

function cancelLinkingToWorkout(from){
	document.forms[0].action =from;
	document.forms[0].method='POST';
 	document.forms[0].submit();
}

function getNewDuration(){
	var dH = $('durationH').value;
	var dM = $('durationM').value;
	var dS = $('durationS').value;
	if (dH == '' && dM == '' && dS == ''){
		return '';
	} else {
		return getDurationCellValue(dH) + ':' + getDurationCellValue(dM) + ':' + getDurationCellValue(dS);
	}
}

function getDurationCellValue(original){
	if (original == 'undefined' || original == ''){
		return '00';
	} else {
		var temp = '00' + original;
		var len = temp.length;
		return temp.substr(len-2, 2);
	}
}
// go to create new route page
function createRoutePage(){
	document.location.replace('routes.do');
}
function createRouteForLoggingWorkout(from, linkedItemId){
	document.location.replace('routes.do?linkToCalendar=true&linkedCalendarItemId='+linkedItemId+'&from='+from);
}
function createRouteForAddingWorkout(year, month, day, workoutId, logWorkout){
	document.location.replace('routes.do?linkToCalendar=true&isAddingWorkout=true&from=addWorkoutStep1.do?selectedMenuItemId=17'
		+'&year='+year+'&month='+month+'&day='+day+'&workoutId='+workoutId+'&linkedCalendarItemId=-1&logWorkout='+logWorkout);
}
function deleteRoute(){
	return confirm('Are you sure you want to delete this route?');
}

function cancelBack(){
	document.location.replace('routes.do?fromCanceling=true');
}
function cacelBackToViewingPage(){
	var viewingId = document.getElementById('viewingRouteId').value;
	if (parseInt(viewingId) > 0){
		document.location.replace('viewRoute.do?currentId='+viewingId);
	} else {
		document.location.replace('routes.do');
	}
}
// Flag for hidden Example address
var isExampleAddressHidden = false;
// Hidden Example address
function hiddenExampleAddress(){
	if (!isExampleAddressHidden){
		$('location').value = '';
		$('location').className = 'txtbx font11px';
		isExampleAddressHidden = true;
	}
}
function hiddenLocationAddress(){
	if (!isExampleAddressHidden){
		$('templocation').value = '';
		$('templocation').className = 'txtbx font11px';
		isExampleAddressHidden = true;
	}
}

function triggleExampleAddress(evt){
	var  _key = window.event ? evt.keyCode : evt.which;
	if(_key == 13){
		_key = 9;
		routeInstance.findAddr($('location').value);
	}
}

function showRouteContent(){
	//$('addRouteStep1').hide();
	Effect.BlindUp('addRouteStep1', {duration: 0.5});
	Effect.BlindDown('addRouteFinal', {duration: 0.5});
	return false;
}
function showRouteStep1(){
	Effect.BlindUp('addRouteFinal', {duration: 0.5});
	Effect.BlindDown('addRouteStep1', {duration: 0.5});
	return false;
}
// Save a route and redirect to adding workout page
function saveRouteForAddingWorkout(year, month, day, workoutId, logWorkout){
	// Set the action, and submit the form.
	document.forms[0].action = "addRoute.do?isAddingWorkout=true&year="+year+"&month="+month+"&day="+day+"&workoutId="+workoutId+"&logWorkout="+logWorkout;
	routeInstance.saveRoute();
}
// Save a route and redirect to adding workout page
function editRouteForAddingWorkout(year, month, day, workoutId, logWorkout){
	// Set the action, and submit the form.
	document.forms[0].action = "editRouteFinal.do?isAddingWorkout=true&year="+year+"&month="+month+"&day="+day+"&workoutId="+workoutId+"&logWorkout="+logWorkout;
	routeInstance.saveRoute();
}
function backToMyRoutesPage() {
	document.location.replace('myRoutes.do?by=mine');
	return false;
}
function backToViewRoutePage(currentId) {
	document.location.replace('viewRoute.do?currentId=' + currentId);
	return false;
}

var map = null;
function loadSearchMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(42.16, -100.72), 4);
		map.addControl(new GLargeMapControl());
	}	
}

function submitPublicRoutesSearch() {
	var value = $('templocation').value;
	$('location').value = value;
	$('command').value = 'searchNormal';	
	if (value.blank() || value == 'City, State or Zip') {
		alert('Please enter a location into the search field!');
	} else {
		var geo = new GClientGeocoder();
		geo.getLocations(value, function(response) {
			if(!response || response.Status.code != 200) {
				alert("Sorry, google can't find the address: " + value + ". be more specific.");
			} else {
				var placemark = response.Placemark[0];
				
				var countryCode = getPlacemarkProperty(placemark, "CountryNameCode");
				if (countryCode != null && countryCode != 'null') {
					$('countryCode').value = countryCode;
				} else {$('countryCode').value == '';}
				var areaName = getPlacemarkProperty(placemark, "AdministrativeAreaName");
				if (areaName != null && areaName != 'null') {
					$('administrativeAreaName').value = areaName;
				} else {$('administrativeAreaName').value == '';}
				var subAreaName = getPlacemarkProperty(placemark, "SubAdministrativeAreaName");
				if (subAreaName != null && subAreaName != 'null') {
					$('subAdministrativeAreaName').value = subAreaName;
				} else {$('subAdministrativeAreaName').value == '';}
				var localityName = getPlacemarkProperty(placemark, "LocalityName");
				if (localityName != null && localityName != 'null') {
					$('localityName').value = localityName;
				} else {$('localityName').value == '';}
				var thoroughfare = getPlacemarkProperty(placemark, "ThoroughfareName");
				if (thoroughfare != null && thoroughfare != 'null') {
					$('thoroughfare').value = thoroughfare;
				} else {$('thoroughfare').value == '';}
				var postalCode = getPlacemarkProperty(placemark, "PostalCodeNumber");
				if (postalCode != null && postalCode != 'null') {
					$('postalCode').value = postalCode;
				} else {$('postalCode').value == '';}
				var accuracy = getPlacemarkProperty(placemark, "Accuracy");
				if (accuracy != null && accuracy != 'null') {
					$('accuracy').value = accuracy;
				} else {$('accuracy').value == ''}
				document.forms[0].action = 'searchPublicRouteFinal.do';
				document.forms[0].submit();
			}
		});
	}
}

function submitPublicRoutesSearchTest() {
	var value = $('templocation').value;	
	if (value.blank() || value == 'City, State or Zip') {
		alert('Please enter a location into the search field!');
	} else {
		$('location').value = value;
		$('command').value = 'searchNormal';
		document.forms[0].action = 'searchPublicRouteFinalTest.do';
		document.forms[0].submit();
	}
}

function trigglePublicRoutesSearchTest(evt){
	var  _key = window.event ? evt.keyCode : evt.which;
	if(_key == 13){
		_key = 9;
		submitPublicRoutesSearchTest();
	}
}

function trigglePublicRoutesSearch(evt){
	var  _key = window.event ? evt.keyCode : evt.which;
	if(_key == 13){
		_key = 9;
		submitPublicRoutesSearch();
	}
}

var SearchDelay = {
    timeout : null,
    updateSearch : function(){
       	this.abort();
        this.timeout = setTimeout(function(){
           	SearchDelay.abort();
			updateSearchPublicRoutesList();
       }, 1200);
    },
    abort : function(){
        if(this.timeout != null) {
            clearTimeout(this.timeout);
			this.timeout = null;
        }
    } 
};
function changeFilterSubChoice(ele, anyID) {
	if (ele.checked == false) {
		var any = $(anyID);
		if (any.checked == true) {
			any.checked = false;
		}
	}
	SearchDelay.updateSearch();
}
function changeFilterAnyChoice(ele, subCss) {
	if (ele.checked == true) {
		$$(subCss).map(function(sub){
			if (sub.checked == false) {sub.checked = true;}
		});
	}
	SearchDelay.updateSearch();
}
function updateSearchPublicRoutesList() {
	$('command').value = 'searchAjax';
	new Dialog.Box("messagebox");
	$("messagebox").persistent_show();
	
	$('searchPublicRouteForm').request({
  		method : 'POST',
  		onCreate : function() {
  		},
  		onComplete : function(t) {
  			$("messagebox").hide();
  			$('search_results_div').innerHTML = t.responseText;
  		},
  		onFailure : function() { 
	      	//alert("There was an error happening!");
	      	$("messagebox").hide();
	    },
	    onException : function() {
	    	$("messagebox").hide();
	    }
	})
}