/* $Id: runometer.js 7989 2010-03-12 21:36:38Z hrishi $ */
/* define the namespace */
if (typeof RUNOMETER == "undefined") {
    var RUNOMETER = {};
}

var map;
var dateRe = /^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/;
var timeRe = /^[0-9]{2}:[0-6]{1}[0-9]{1}:[0-6]{1}[0-9]{1}$/;
var numRe = /(^\d+$)|(^\d+\.\d+$)/;
var CreatingRoute = false;
var miText;
var kmText;
var routeDistMi = 0.0;
var routeDistKm = 0.0;

/* login panel */
RUNOMETER.toggleLoginPanelAnim = function(e, obj) {
    YAHOO.util.Event.preventDefault(e);
    obj.animate();
}
RUNOMETER.initLoginPanel = function() {
    var down = new YAHOO.util.Anim('login-panel', {top: {to: 150} }, 0.25);
	down.onComplete.subscribe(function(){document.getElementById('username').focus();});
    YAHOO.util.Event.on("login-link", 'click', RUNOMETER.toggleLoginPanelAnim, down, true);

    var up = new YAHOO.util.Anim('login-panel', {top: {to: -100} }, 0.25 );
    YAHOO.util.Event.on('login-panel-close-link', 'click', RUNOMETER.toggleLoginPanelAnim, up, true);
};
YAHOO.util.Event.onAvailable('login-panel', RUNOMETER.initLoginPanel);

/* profile panel on index.php */
RUNOMETER.toggleProfilePanelAnim = function(e, obj) {
	YAHOO.util.Event.preventDefault(e);
	obj.animate();

	// display or hide the profile div
	RUNOMETER.displayProfile();
}

RUNOMETER.initProfilePanel = function() {
    var down = new YAHOO.util.Anim('profile-panel', {top: {to: -20} }, 0.25);
	down.onComplete.subscribe(RUNOMETER.displayProfile);
    YAHOO.util.Event.on("profile-link", 'click', RUNOMETER.toggleProfilePanelAnim, down, true);
	
    var up = new YAHOO.util.Anim('profile-panel', {top: {to: -100} }, 0.25 );
	up.onComplete.subscribe(RUNOMETER.resetProfile);
    YAHOO.util.Event.on('profile-panel-close-link', 'click', RUNOMETER.toggleProfilePanelAnim, up, true);
}
YAHOO.util.Event.onAvailable('profile-panel', RUNOMETER.initProfilePanel);

/* password update panel on index.php */
RUNOMETER.togglePasswordUpdatePanelAnim = function(e, obj) {
	YAHOO.util.Event.preventDefault(e);
	obj.animate();
	
	// display the form.
	RUNOMETER.displayPasswordUpdate();
}

RUNOMETER.initPasswordUpdatePanel = function() {
    var down = new YAHOO.util.Anim('passwd-update-panel', {top: {to: -20} }, 0.25);
	// down.onComplete.subscribe(RUNOMETER.displayProfile);
    YAHOO.util.Event.on("update-passwd-link", 'click', RUNOMETER.togglePasswordUpdatePanelAnim, down, true);
	
    var up = new YAHOO.util.Anim('passwd-update-panel', {top: {to: -100} }, 0.25 );
	up.onComplete.subscribe(RUNOMETER.initPasswordReset);
    YAHOO.util.Event.on('passwd-update-panel-close-link', 'click', RUNOMETER.togglePasswordUpdatePanelAnim, up, true);
}
YAHOO.util.Event.onAvailable('passwd-update-panel', RUNOMETER.initPasswordUpdatePanel);

/* registration */
RUNOMETER.toggleSubmitEnabled = function(e, obj) {
	document.getElementById('submit-button').disabled = !this.checked;
}
RUNOMETER.initRegForm = function(e, obj) {
    YAHOO.util.Event.on('agree-tos', 'click', RUNOMETER.toggleSubmitEnabled);
}
YAHOO.util.Event.onAvailable('registration-form', RUNOMETER.initRegForm);

/* instructions */
RUNOMETER.toggleInstructions = function(e, obj) {
	YAHOO.util.Event.preventDefault(e);
	var linkEl = document.getElementById('instruction-toggle-link');
	if (linkEl) {
		var els = YAHOO.util.Dom.getElementsByClassName("form-section-instruct");
		if (linkEl.innerHTML == "Show Instructions") {
			YAHOO.util.Dom.setStyle(els, "display", "block");
			linkEl.innerHTML = "Hide Instructions";
		} else {
			YAHOO.util.Dom.setStyle(els, "display", "none");
			linkEl.innerHTML = "Show Instructions";
		}
	}
	
}
RUNOMETER.initInstructionToggle = function(e, obj) {
	var divEl = document.getElementById('instruction-toggle-div');
	if (divEl) {
		divEl.style.display = "block";
		var linkEl = document.getElementById('instruction-toggle-link');
		if (linkEl) {
			linkEl.innerHTML = "Show Instructions";
			YAHOO.util.Event.on('instruction-toggle-link', 'click', RUNOMETER.toggleInstructions);
		}
	}
}
YAHOO.util.Event.onAvailable('instruction-toggle-div', RUNOMETER.initInstructionToggle);

/*profile*/
var editdiv;
var displaydiv;

RUNOMETER.checkBioLength = function(w, e) {
	e = e || window.event;
	ch = e.which || e.keyCode;
//	alert("Keycode: " + ch);
	
	// ignore delete/backspace key events
	if(ch != 8 && w.value.length > 512) {
		alert("Bio exceeds permitted length");
		return false;
	}
	return true;
}

RUNOMETER.upload = function(form, target) {
  	var statusdiv = document.getElementById("upload_status");
  	YAHOO.util.Connect.setForm(form, true);
  	var uploadHandler = {
		upload: function(data) {
			div.innerHTML = data.responseText;
		}
  	}  
	YAHOO.util.Connect.asyncRequest('POST', target, uploadHandler);
}


RUNOMETER.showTz = function(tz) {
	/* get continent*/
	cs = document.forms["profile_edit_form"].continent;
	if(cs.selectedIndex != 0) {
		cont = cs.options[cs.selectedIndex].value;
		document.getElementById('tzdiv').innerHTML = "";
		document.getElementById('tzdiv').style.display = "none";

	    var url =  "/tz.php?c=" + cont;
		if(tz != null && tz.length > 0) url += "&tz=" + tz;
		var request = YAHOO.util.Connect.asyncRequest('GET', url, RUNOMETER.tzCallback); 

	    /*request.open("GET", url, true);
		request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	    request.send(null);*/
	}
}

RUNOMETER.renderTz = function(o) {
	var tzel = document.getElementById('tzdiv');
	if (tzel) {
		tzel.style.display = "block";
		tzel.innerHTML = o.responseText;
	} else {
		RUNOMETER.showError('unable to display timezones.');
	}
}

RUNOMETER.tzError = function() {
	RUNOMETER.showError('unable to display timezones.');
}

RUNOMETER.tzCallback = {
  success: RUNOMETER.renderTz, 
  failure: RUNOMETER.tzError,
  argument: { payload:"none", message:"none" } 
};

RUNOMETER.toggleProfileEdit = function(e, obj) {
	// alert("In toggleProfileEdit");
	YAHOO.util.Event.preventDefault(e);
	var linkEl = document.getElementById('profile-edit-toggle-link');
	if (linkEl) {
		/*var els = YAHOO.util.Dom.getElementsByClassName("form-section-instruct");*/
		if (linkEl.innerHTML == "Edit Profile") {
			statusdiv = document.getElementById('profile-status'); 
			statusdiv.innerHTML = "Loading profile...";
			var request = YAHOO.util.Connect.asyncRequest('POST', '/handlers/profileEditForm.php', RUNOMETER.ProfileEditLoadCallback); 

			/*YAHOO.util.Dom.setStyle(els, "display", "block");
			linkEl.innerHTML = "Save Profile";

			fire the get-form request, set the handler to pop the inner results and set it visisble
			 and set the link to "Save Profile"*/
		}  else if (linkEl.innerHTML == "Save Profile") {
			/*marshal form params*/
			statusdiv = document.getElementById('profile-status'); 
			editdiv = document.getElementById('profile-edit'); 
			// displaydiv = document.getElementById('profile-display'); 
			editdiv.style.display = 'none';
			// displaydiv.style.display = 'block';
			statusdiv.innerHTML = "Saving profile...";
			var profileForm = document.getElementById("profile-edit-form");
			YAHOO.util.Connect.setForm(profileForm, false);
			var request = YAHOO.util.Connect.asyncRequest('POST', '/handlers/profileDisplay.php', RUNOMETER.ProfileSaveCallback); 
		}  /*else if (linkEl.innerHTML == "Show Profile") {
			alert("In ShowProfile handler");
			var divEl = document.getElementById('profile-edit-toggle-div');
			if (divEl) {
				divEl.style.display = "block";
				var linkEl = document.getElementById('profile-edit-toggle-link');
				if (linkEl) {
					linkEl.innerHTML = "Edit Profile";
					YAHOO.util.Event.on('profile-edit-toggle-link', 'click', RUNOMETER.toggleProfileEdit);
				}
			}
			var request = YAHOO.util.Connect.asyncRequest('GET', '/handlers/profileDisplay.php', RUNOMETER.ProfileLoadAndDisplayCallback); 	
		} */
	}	
}

RUNOMETER.initProfileEditToggle = function(e, obj) {
	// alert("initProfileEditToggle");
	/*
	var divEl = document.getElementById('profile-edit-toggle-div');
	if (divEl) {
		divEl.style.display = "block";
		var linkEl = document.getElementById('profile-edit-toggle-link');
		if (linkEl) {
			linkEl.innerHTML = "Edit Your Profile";
			YAHOO.util.Event.on('profile-edit-toggle-link', 'click', RUNOMETER.toggleProfileEdit);
		}
	}
	*/
	var divEl = document.getElementById('profile-edit-toggle-div');
	if (divEl) {
		divEl.style.display = "none";
		var linkEl = document.getElementById('profile-edit-toggle-link');
		if (linkEl) {
			linkEl.innerHTML = "Edit Profile";
			YAHOO.util.Event.on('profile-edit-toggle-link', 'click', RUNOMETER.toggleProfileEdit);
		}
	}
	var request = YAHOO.util.Connect.asyncRequest('GET', '/handlers/profileDisplay.php', RUNOMETER.ProfileLoadCallback); 
	/*var request = YAHOO.util.Connect.asyncRequest('GET', '/handlers/profileDisplay.php', RUNOMETER.ProfileLoadCallback); */
}


RUNOMETER.displayEditProfile = function(o) {
	editdiv = document.getElementById('profile-edit'); 
	displaydiv = document.getElementById('profile-display'); 
	statusdiv = document.getElementById('profile-status');  
	statusdiv.style.display = 'none';
	if(o.responseText !== undefined){ 
		displaydiv.style.display = 'none';
		editdiv.style.display = 'block';
		editdiv.innerHTML = o.responseText;
		var linkEl = document.getElementById('profile-edit-toggle-link');
		if (linkEl) {
			linkEl.innerHTML = "Save Profile";
		}
	} else {
		displaydiv.style.display = 'block';
		displaydiv.innerHTML = '<b>Error Loading profile for editing.</b>';
	}
}

RUNOMETER.profileError = function (o) {
	displaydiv = document.getElementById('profile-display'); 
	statusdiv = document.getElementById('profile-status');  
	statusdiv.style.display = 'none';

	if(o.responseText !== undefined){ 
		displaydiv.style.display = 'block';
		displaydiv.innerHTML = "ERROR: "+ o.argument.message;
		displaydiv.innerHTML = "the server said: "+statusText;
	}
}

RUNOMETER.loadProfile = function(o) {
	editdiv = document.getElementById('profile-edit'); 
	displaydiv = document.getElementById('profile-display'); 
	statusdiv = document.getElementById('profile-status');  
	statusdiv.style.display = 'none';

	if(o.responseText !== undefined) {
		displaydiv.style.display = 'none';
		editdiv.style.display = 'none';
		displaydiv.innerHTML = o.responseText;
		// alert("ajax callback: loadProfileDisplay: HTML=" + o.responseText);

		var linkEl = document.getElementById('profile-edit-toggle-link');
		if (linkEl) {
			linkEl.innerHTML = "Edit Profile";
		}
	} else {
		displaydiv.style.display = 'none';
		displaydiv.innerHTML = '<b>Error Loading profile for viewing.</b>';
	}
}

RUNOMETER.loadAndDisplayProfile = function(o) {
	editdiv = document.getElementById('profile-edit'); 
	displaydiv = document.getElementById('profile-display'); 
	statusdiv = document.getElementById('profile-status');  
	statusdiv.style.display = 'none';

	if(o.responseText !== undefined) {
		displaydiv.style.display = 'block';
		editdiv.style.display = 'none';
		displaydiv.innerHTML = o.responseText;
		// alert("ajax callback: loadProfileDisplay: HTML=" + o.responseText);

		var linkEl = document.getElementById('profile-edit-toggle-link');
		if (linkEl) {
			linkEl.innerHTML = "Edit Profile";
		}
	} else {
		displaydiv.style.display = 'block';
		displaydiv.innerHTML = '<b>Error Loading profile for viewing.</b>';
	}
}

RUNOMETER.displayProfile = function() {
	statusdiv = document.getElementById('profile-status');  
	statusdiv.style.display = 'none';

	editdiv = document.getElementById('profile-edit'); 
	displaydiv = document.getElementById('profile-display'); 
	divEl = document.getElementById('profile-edit-toggle-div');
	
	editdiv.style.display = 'none';
	displaydiv.style.display = 'block';
	divEl.style.display = "block";

	var linkEl = document.getElementById('profile-edit-toggle-link');
	if (linkEl) {
		linkEl.innerHTML = "Edit Profile";
	}
}


RUNOMETER.resetProfile = function() {
	var editdiv = document.getElementById('profile-edit'); 
	var displaydiv = document.getElementById('profile-display'); 
	var divEl = document.getElementById('profile-edit-toggle-div');
	var linkEl = document.getElementById('profile-edit-toggle-link');
	
	editdiv.style.display = 'none';
	displaydiv.style.display = 'none';
	divEl.style.display = "none";
}

RUNOMETER.togglePasswordReset = function(e, obj) {
	YAHOO.util.Event.preventDefault(e);
	var linkEl = document.getElementById('passwd-update-link');
	if (linkEl) {
		if (linkEl.innerHTML == "Save password") {
			//alert("Saving password");
			/*marshal form params*/
			displaydiv = document.getElementById('passwd-update-display'); 
			// displaydiv.style.display = 'block';
			var passwordResetForm = document.getElementById("password-update-form");
			YAHOO.util.Connect.setForm(passwordResetForm, false);
			var request = YAHOO.util.Connect.asyncRequest('POST', '/handlers/changePassword.php', RUNOMETER.PasswordSaveCallback); 
			displaydiv.innerHTML = "Saving password...";
		} 
	}	
}

RUNOMETER.initPasswordReset = function(e, obj) {
	var divEl = document.getElementById('passwd-update-link-div');
	if (divEl) {
		divEl.style.display = "none";
		var linkEl = document.getElementById('passwd-update-link');
		if (linkEl) {
			linkEl.innerHTML = "Save password";
			YAHOO.util.Event.on('passwd-update-link', 'click', RUNOMETER.togglePasswordReset);
		}
	}
	var request = YAHOO.util.Connect.asyncRequest('GET', '/handlers/changePassword.php', RUNOMETER.PasswordUpdateLoadCallback); 
}

RUNOMETER.loadPasswordUpdate = function(o) {
	displaydiv = document.getElementById('passwd-update-display'); 
	if(o.responseText !== undefined) {
		displaydiv.style.display = 'none';
		displaydiv.innerHTML = o.responseText;
		// alert("ajax callback: loadProfileDisplay: HTML=" + o.responseText);

		var linkEl = document.getElementById('passwd-update-link');
		if (linkEl) {
			linkEl.innerHTML = "Save password";
		}
	} else {
		displaydiv.style.display = 'none';
		displaydiv.innerHTML = '<b>Error password update form.</b>';
	}
}


RUNOMETER.passwordSaved = function(o) {
	displaydiv = document.getElementById('passwd-update-display'); 
	if(o.responseText !== undefined) {
		displaydiv.style.display = 'block';
		displaydiv.innerHTML = o.responseText;
		var linkEl = document.getElementById('passwd-update-link');
		if (linkEl) {
			if(o.responseText.substring(7,0) == "<p><div") {// error occurred
				linkEl.innerHTML = "Save password";
			} else {
				linkEl.innerHTML = "";
			}
		}
	} else {
		displaydiv.style.display = 'block';
		displaydiv.innerHTML = '<b>Error password update form.</b>';
	}
}

RUNOMETER.displayPasswordUpdate = function() {
	displaydiv = document.getElementById('passwd-update-display'); 
	divEl = document.getElementById('passwd-update-link-div');
	
	displaydiv.style.display = 'block';
	divEl.style.display = "block";
	
	var linkEl = document.getElementById('passwd-update-link');
	if (linkEl) {
		linkEl.innerHTML = "Save password";
	}
}

RUNOMETER.ProfileSaveCallback = {
  success: RUNOMETER.loadAndDisplayProfile, 
  failure: RUNOMETER.profileError,
  timeout: 5000, 
  argument: { payload:"<none>", message:"Your profile could not be saved." } 
};

RUNOMETER.ProfileLoadCallback = {
  success: RUNOMETER.loadProfile, 
  failure: RUNOMETER.profileError,
  timeout: 5000, 
  argument: { payload:"<none>", message:"profile loaded" } 
};

RUNOMETER.ProfileLoadAndDisplayCallback = {
  success: RUNOMETER.loadAndDisplayProfile, 
  failure: RUNOMETER.profileError,
  timeout: 5000, 
  argument: { payload:"<none>", message:"profile loaded" } 
};

RUNOMETER.ProfileEditLoadCallback = {
  success: RUNOMETER.displayEditProfile, 
  failure: RUNOMETER.profileError,
  timeout: 5000, 
  argument: { payload:"<none>", message:"profile prepared for editing" } 
};
YAHOO.util.Event.onAvailable('profile-edit-toggle-div', RUNOMETER.initProfileEditToggle);

RUNOMETER.PasswordUpdateLoadCallback = {
  success: RUNOMETER.loadPasswordUpdate, 
  // failure: RUNOMETER.profileError,
  timeout: 5000, 
  argument: { payload:"<none>", message:"password reset loaded" } 
};

RUNOMETER.PasswordSaveCallback = {
  success: RUNOMETER.passwordSaved, 
  // failure: RUNOMETER.profileError,
  timeout: 5000, 
  argument: { payload:"<none>", message:"password reset loaded" } 
};
YAHOO.util.Event.onAvailable('passwd-update-link-div', RUNOMETER.initPasswordReset);

/* system message display methods */
RUNOMETER.showStatus = function(message) {
    var ediv = document.getElementById('status');
	if (typeof(ediv) != 'undefined') {
	    ediv.innerHTML = message + "<br>\n";
	    ediv.style.display = 'block';
	}
}
RUNOMETER.hideStatus = function() {
    var ediv = document.getElementById('status');
	if (typeof(ediv) != 'undefined') {
	    ediv.style.display = 'none';
	}
}
RUNOMETER.showError = function(message) {
    var ediv = document.getElementById('err');
	if (typeof(ediv) != 'undefined') {
	    ediv.innerHTML = message + "<br>\n";
	    ediv.style.display = 'block';
	}
}
RUNOMETER.hideError = function() {
    var ediv = document.getElementById('err');
	if (typeof(ediv) != 'undefined') {
	    ediv.style.display = 'none';
	}
}

RUNOMETER.addManualRunRow = function() {
	var rowinput = document.getElementById("row_count");
	var count = Number(rowinput.value);
	var rowIndex = count + 1;
	var runarea = document.getElementById("runinput");
	//DEBUG: alert(count);
	var newdiv = document.createElement('div');
	var divIdName = 'rr'+count;
	newdiv.setAttribute('id',divIdName);
	newdiv.innerHTML = '<div id="rr'+count+'">Time:&nbsp;<input type="text" class="input-2d-gray" name="runtime'+count+'" id="runtime'+count+'" value="00:00:00" onblur="RUNOMETER.checkTime(this.value);" />&nbsp;&nbsp;Distance:&nbsp;<input type="text" class="input-2d-gray" id="rundist'+count+'" name="rundist'+count+'" value="0.0" onblur="RUNOMETER.checkDist(this.value);" onkeydown="RUNOMETER.newRowOnTab(event, '+rowIndex+');" />&nbsp;&nbsp;</div>';
	runarea.appendChild(newdiv);
	count = count +1;
	rowinput.value= count;
	if (count > 2) {
		var bb = document.getElementById('backbutton');
		bb.disabled = false;
	}
}

RUNOMETER.delManualRunRow = function() {
	var rowinput = document.getElementById("row_count");
	var count = Number(rowinput.value);
	if (count > 2) {
		count = count-1;
		rowinput.value = count;
		//DEBUG: alert(count);
		
		var runarea = document.getElementById('runinput');
		var deldiv = document.getElementById('rr'+count);
		  runarea.removeChild(deldiv);
				
	}
	
	if (count <= 2) {
		var bb = document.getElementById('backbutton');
		bb.disabled = true;
	}	
}


/* Calendar for manual run entry */
/* TODO: namespace this function */
function handleCalSelect(type,args,obj) { 
	    var dates = args[0]; 
	    var date = dates[0]; 
	    var year = date[0], month = date[1], day = date[2];  
	    var txtDate1 = document.getElementById("rundate"); 
	    txtDate1.value = month + "/" + day + "/" + year; 
		RUNOMETER.cal1.hide();
		RUNOMETER.hideError();	    
} 

RUNOMETER.initCalendar = function(e, obj) {
	RUNOMETER.cal1 = new YAHOO.widget.Calendar("cal1","run_calendar_div", {title:"Run Date:", close:true}); 
	RUNOMETER.cal1.render(); 
	RUNOMETER.cal1.selectEvent.subscribe(handleCalSelect, RUNOMETER.cal1, true);
	YAHOO.util.Event.addListener("rundate", "focus", RUNOMETER.cal1.show, RUNOMETER.cal1, true); 
	YAHOO.util.Event.addListener("showcal", "click", RUNOMETER.cal1.show, RUNOMETER.cal1, true); 
} 
YAHOO.util.Event.onAvailable('run_calendar_div', RUNOMETER.initCalendar);


RUNOMETER.checkDist = function(dist) {
    RUNOMETER.hideError();
	if (!numRe.test(dist)) {
		RUNOMETER.showError('Please check your distance value and resubmit; "'+dist+'" is not valid. Distances should be in the form: x.y');
	}
}

RUNOMETER.checkDate = function(date) {
    RUNOMETER.hideError();
	if (date != '' && !dateRe.test(date)) {
		RUNOMETER.showError('Please check your date value and resubmit; "'+date+'" is not valid.');
	}
}


RUNOMETER.checkTime = function(time) {
    RUNOMETER.hideError();
	if (!timeRe.test(time)) {
		RUNOMETER.showError('Please check your time value and resubmit; "'+time+'" is not valid. Times should be in the form: hours:minutes:seconds');
	}
}

RUNOMETER.newRowOnTab = function(evt, row_index) {
	var rowinput = document.getElementById("row_count");
	var count = Number(rowinput.value);
	var charCode = (evt.which) ? evt.which : event.keyCode	
//	alert("count="+count+",charcode="+charCode+',rowindex='+row_index);
	// if focus was lost due to tab, add a new row
	if(charCode == 9 && row_index == count) {
		RUNOMETER.addManualRunRow();
	}
}

RUNOMETER.checkManualRun = function() {

  var error = 0;

  RUNOMETER.hideError();

  var errStr = '';

  var dateInput = document.getElementById("rundate");
  if (! dateRe.test(dateInput.value)) {
	errStr = 'Please check your date value and resubmit<br/>';
	error = 1;
  }


  var rowinput = document.getElementById("row_count");
  var count = Number(rowinput.value);
  for (var i = 0; i < count; i++) {
	var thisTimeInput = document.getElementById('runtime'+i);
	if (! timeRe.test(thisTimeInput.value)) {
		errStr += 'Please the time value "'+thisTimeInput.value+'" and try again.<br/>';
	  error = error +1;
	}
	var thisDistInput = document.getElementById('rundist'+i);
		if ( ! numRe.test(thisDistInput.value) ) {
		errStr += 'Please the distance value "'+thisDistInput.value+'" and try again.<br/>';
		error = error +1;	  
	}
  }
  if (error > 0) {
	RUNOMETER.showError(errStr);
	return false;
  }
  return true;
}

var ua = YAHOO.env.ua,
	oAnim;

YAHOO.util.Event.onDOMReady(function () {	
	
 	// uses YUI's menubar to supplant the simple HTML controls
    var oMenuBar = new YAHOO.widget.MenuBar("navbar-links");
  
    oMenuBar.render();	
});

RUNOMETER.DrawnDistControl = function() {
}

RUNOMETER.initializeGoogleMap  = function() {
        map = new google.maps.Map2(document.getElementById("map"));
        map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 2);
	map.addControl(new GLargeMapControl3D());
	map.addControl(new GMapTypeControl());
	map.addControl(new GOverviewMapControl());
	map.addControl(new GNavLabelControl());
	map.enableGoogleBar();
	
	RUNOMETER.DrawnDistControl.prototype = new google.maps.Control();


	var starticon = new google.maps.Icon();
  starticon.image = "/img/start.png";
  starticon.iconSize = new GSize(16, 16);

	GEvent.addListener(map, "dragend", function() {
     		clickMode = 'drag';
	});

	GEvent.addListener(map, "click", function(overlay,  point) {
      
		clickMode = 'click';
		if (/*(clickMode == 'click') &&*/ (CreatingRoute)) {
	   		RUNOMETER.addPoint(point);
			map.clearOverlays();
			if (pts.length > 0) {
              		var lines = new google.maps.Polyline(pts, '#0000FF', 4);
              		map.addOverlay(lines);
              		var point = new google.maps.Point(pts[0].x, pts[0].y);
              		var marker = new google.maps.Marker(point);
              		map.addOverlay(marker);
          		}
      		}

  	});


	RUNOMETER.DrawnDistControl.prototype.initialize = function(map) {
		var container = document.createElement("div");

		var milesDiv = document.createElement("div");
		milesDiv.setAttribute("id", "milesDiv");
		container.appendChild(milesDiv);
		miText = document.createTextNode("");
		milesDiv.appendChild(miText);

		var kmDiv = document.createElement("div");
		kmDiv.setAttribute("id", "kmDiv");
		kmText = document.createTextNode("");
		container.appendChild(kmDiv);
		kmDiv.appendChild(kmText);

		map.getContainer().appendChild(container);
		return container;
	}

	RUNOMETER.DrawnDistControl.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(70, 7));
	}


	map.addControl(new RUNOMETER.DrawnDistControl());

  	GEvent.addListener(map, "moveend", function() {
      		var curCenter = map.getCenter();

	});

        var unload_func = typeof(RUNOMETER.unloadGoogleMap) != 'undefined' ? RUNOMETER.unloadGoogleMap : (function () {});
        YAHOO.util.Event.on(window, 'unload', unload_func);  
}

RUNOMETER.unloadGoogleMap = function(e, obj) {
        //DEBUG: alert("Unload body detected.");
        GUnload();
}

RUNOMETER.addPoint = function(point) {
	if (pts.length > 0 ) {
	  var updates = RUNOMETER.haversineDist(point, new google.maps.LatLng(pts[pts.length-1].y, pts[pts.length-1].x));
	}
	pts.push(new google.maps.LatLng(point.lat(), point.lng()));
	if (pts.length > 1 ) {
	    routeDistMi += updates['mi'];
	    routeDistKm += updates['km'];
	    RUNOMETER.updateDistances(routeDistMi, routeDistKm); 
	    //RUNOMETER.showError('total distance: ' + routeDistMi +'mi or '+routeDistKm+'km .');
	}	
}

RUNOMETER.degToRad = function(deg) {
  return (deg * Math.PI/180.0);
}

/**
 * get the haversine distance between two googmaps points. Yeah, yeah, we're doing math on the client browser, but not a LOT of math.
 */
RUNOMETER.haversineDist = function(pointA, pointB) {
   var latA = RUNOMETER.degToRad(pointA.lat()); 
   var lonA = RUNOMETER.degToRad(pointA.lng());
   var latB = RUNOMETER.degToRad(pointB.lat());
   var lonB = RUNOMETER.degToRad(pointB.lng());

   var dlon = lonA - lonB;
   var dlat = latA - latB;
   var a = Math.pow(Math.sin(dlat/2),2) +
       Math.cos(latB) * Math.cos(latA) * Math.pow(Math.sin(dlon/2),2);
   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
   var distMeters=  6378140.0 * c;  /* 6378140 is the radius of the Earth in meters*/
   // DEBUG: RUNOMETER.showError('latA: ' + pointA.lat() +' lonA: '+pointA.lng()+' latB: '+pointB.lat()+' lonB: '+pointB.lng()+' dlon: '+dlon+' dlat:'+dlat+'distMets: '+distMeters);  
   var result = [];
   result['km'] = distMeters*.001;
   result['mi'] = distMeters*0.000621371192;
   return result;
}

RUNOMETER.updateDistances = function(mi, km) {
	var miles = document.getElementById("milesDiv");
	miles.innerHTML = '<span class="rundistnum">'+mi.toFixed(3)+'</span><span class="rundistunits"> mi</span>';
	var kilometers = document.getElementById("kmDiv");
	kilometers.innerHTML = '<span class="rundistnum">'+km.toFixed(3)+'</span><span class="rundistunits"> km</span>';
}

RUNOMETER.setMapCenter = function(latitude, longitude, zoom) {
	map.setCenter(new GLatLng(latitude, longitude), zoom);
}