/* ###################################### */
/* ###################################### */
/*                                        */
/*     Ride Cell is powered by the        */
/*         Mr. Clean Ajax API             */
/*             by Mike Wilt               */
/*         mikewilt [AT] gmail            */
/*             (c) 2008                   */ 
/*                                        */
/* ###################################### */
/* ###################################### */


/* ******************************** */
/* Begin postPage function          */
/* ******************************** */

function postPage(mode){
	var postPageRequest = false;
    if (window.XMLHttpRequest) // if Mozilla, Safari, etc.
        postPageRequest = new XMLHttpRequest();
    else if (window.ActiveXObject){ // if IE
        try {
            postPageRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (e){
			try{
				postPageRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	else
		return false;
	
    // Retrieve variables for the page that's to be inserted 
    var variables = retrieveVars(mode);
    var containerID = variables.containerID;
    var url = variables.url;
    var params =  variables.params;
    var after = variables.after;
    
    // Execute ajax
    postPageRequest.onreadystatechange=function() { postLoadPage(postPageRequest, containerID, after); }
    postPageRequest.open('POST', url, true);
    postPageRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    postPageRequest.send(params);
        
}

function postLoadPage(postPageRequest, containerID, after) {
    if (postPageRequest.readyState == 4) { 
        if (postPageRequest.status==200) {

	        document.getElementById("serverError").innerHTML="";
	
            if (containerID == 'broadcastNewLocationsJSON') {
                var JSONobject = JSON.parse(postPageRequest.responseText);
                //update the locations in the "profile insert" panel on left side of page
                document.getElementById('locationsContainer').innerHTML = JSONobject[0];
                if (document.getElementById('planNextLocationsSelect')) {
                    //only update drop down menus if plan new ride panel is on page
                    document.getElementById('planNextLocationsSelect').innerHTML = JSONobject[1];			
                    document.getElementById('planNextLocationsSelect2').innerHTML = JSONobject[2];
                    }
                //output a confirmation message to the add/edit location panel
                document.getElementById('addEditLocationFeedback').innerHTML = JSONobject[3];
                    if (document.getElementById('editLocationsTable')) {
                        //update row if user is editing row on the edit locations panel
                        var rowID = JSONobject[4];
                        document.getElementById('locationRow'+ rowID).innerHTML = JSONobject[5];
                        }
                }
            
          // added 2/14 -- okay to remove as of 3/9
         //   else if (containerID == 'rateRideNew') {
          //      document.getElementById(containerID).innerHTML+=postPageRequest.responseText;
          //      }
            
            else {
                document.getElementById(containerID).innerHTML=postPageRequest.responseText;
                }
         //   }
        //something bad happened in the server side. internal server error? hope there is an error container
      //  else {
      //      document.getElementById("serverError").innerHTML="<strong>  Oops. Server error. Please try again after some time. </strong>";
       //     }
	//    }
		
    if (after != null) {

        if (after == 'savePrefsAfter') {
            document.getElementById('editPrefsToggleContainer').innerHTML = "<a class='green4' href='javascript:void(0);' onclick='editPreferences();'>click here to edit</a>";
            }
        else if (after == 'savePersonalAfter') {
            document.getElementById('editPersonalToggleContainer').innerHTML = "<a class='green4' href='javascript:void(0);' onclick='editPersonal();'>click here to edit</a>";
            }
        else if (after =='afterDropDownNewLocation') {
            document.getElementById('workLocations').value = 0;
            document.getElementById('martaStations').value = 0;
            document.getElementById('commuterLots').value = 0;
            }
        else if (after == 'afterCreateNewLocation') {
            document.getElementById('createNewLocationLabelInput').value = "";
            document.getElementById('createNewLocationAddressInput').value = "";
            }
        else if (after == 'afterRemoveAvatar') {
            thefileVar = document.getElementById('avatarHere').innerHTML;
            document.getElementById('avatarFeedback').innerHTML = "Image removed. <a class='under' href='javascript:void(0);' onclick='closeAvatarPanel();'/>Click here to close window.</a>";
            }
        else if (after == 'checkMapLocationsAfter') {
            checkLocations();
            }
        
        else if (after == 'insertRideAfter') {
            //make sure no error occurred. (check for ID or lack of an ID) then initialize
            if (document.getElementById("okay") && document.getElementById("okay").innerHTML != "") {
                initialize();
                }
            }
        
        <!-- added 2/14 -->
        else if (after == 'clearRateRide') { 
            document.getElementById("rateRideContainer" + rateRideID).innerHTML = "<div class='successRate'>Success! Ride number " + rateRideID +  " has been rated.</div>";
        }

			}
		}
    }
}


/* ******************************** */
/* Return parameters for postPage   */
/* ******************************** */

function retrieveVars(mode) {

	//show editLocations panel
	if (mode == "editLocationsPanel") {
		var containerID = 'addEditDiv';
		var url = '/loginajax/locationsPopUp/';
		var params =  "mode=" + mode;
		var after = null;
		}
	
	//show addNewLocation panel
	else if (mode == "addNewLocationPanel") {
		var containerID = 'addEditDiv';
		var url = '/loginajax/locationsPopUp/';
		var params =  "mode=" + mode;
		var after = null;
		}
	
	else if (mode == 'showEditLocationPanel') {
		var containerID = 'addEditDiv';
		var url = '/loginajax/locationsPopUp/';
		var params =  "mode=" + mode;
		var after = null;	
		}
	
	// edit user profile preferences
	else if (mode == "editPrefs") {
		var containerID = 'prefsContainer';
		var url = '/loginajax/profilePrefsEdit/';
		var params = '';
		var after = null;
		}
	
	// save user profile preferences
	else if (mode == "savePrefs") {
		var selIndexDriveRide = document.getElementById('driveRidePref').selectedIndex;
		var oDriveRidePref = document.getElementById('driveRidePref').options[selIndexDriveRide].value;
		var oCarDescPref = document.getElementById('carDescPref').value;
		// var oMaxPassPref = document.getElementById('maxPassPref').value; 
		var selIndexSmoke = document.getElementById('smokePref').selectedIndex;
		var oSmokePref = document.getElementById('smokePref').options[selIndexSmoke].value;	
		var containerID = 'prefsContainer';
		var url = '/loginajax/profilePrefsSave/';
		var params = "mode=" + mode + "&rideordrive=" + encodeURIComponent(oDriveRidePref) + "&cardescription=" + encodeURIComponent(trim(oCarDescPref))+ "&smoker=" + encodeURIComponent(oSmokePref);
		var after = 'savePrefsAfter';
		}
	
	else if (mode == "editPersonal") {
		var containerID = 'personalContainer';
		var url = '/loginajax/profilePersonalEdit/';
		var params = '';
		var after = null;	
		}

    else if (mode == "savePersonal") {
		var selIndexAffiliation = document.getElementById('affiliationPersonal').selectedIndex;
		var oAffiliation = document.getElementById('affiliationPersonal').options[selIndexAffiliation].value;
        var selIndexGender = document.getElementById('genderPersonal').selectedIndex;
        var oGenderPersonal = document.getElementById('genderPersonal').options[selIndexGender].value;
		var oEmailPersonal = document.getElementById('emailPersonal').value;
		var oPhonePersonal = document.getElementById('phonePersonal').value;
        var oZipPersonal = document.getElementById('zipPersonal').value;
		var selIndexIncentive = document.getElementById('incentivePersonal').selectedIndex;
		var oIncentivePersonal = document.getElementById('incentivePersonal').options[selIndexIncentive].value;
        var containerID = 'personalContainer';
        var url = '/loginajax/profilePersonalSave/';
		var params = "mode=" + mode
            + "&affiliation=" + encodeURIComponent(oAffiliation)
            + "&gender=" + encodeURIComponent(trim(oGenderPersonal))
            + "&email=" + encodeURIComponent(trim(oEmailPersonal))
            + "&mobileno=" + encodeURIComponent(trim(oPhonePersonal))
            + "&homezip=" + encodeURIComponent(trim(oZipPersonal))
            + "&incentive=" + encodeURIComponent(oIncentivePersonal);
        var after = 'savePersonalAfter';
    }
    
	else if (mode == "editBilling") {
		var containerID = 'billingContainer';
		var url = 'profileBillingEdit.php';
		var params = '';
		var after = null;	
		}
	
	else if (mode == "saveEditLocation") {
		var oLocation = theLocation;
		var oLabel = document.getElementById('createNewLocationLabelInput').value;
		var oAddress = document.getElementById('createNewLocationAddressInput').value;
		var containerID = 'broadcastNewLocationsJSON';
		var url = '/loginajax/locationsPopUp/';
		var params = "mode=" + mode + "&locationID=" + encodeURIComponent(oLocation) + "&label=" + encodeURIComponent(oLabel) + "&address=" + encodeURIComponent(oAddress);
		var after = null;	
		}
	
	else if (mode == "deleteEditLocation") {
		var oLocation = theLocation;
		var containerID = 'broadcastNewLocationsJSON';
		var url = '/loginajax/locationsPopUp/';
		var params = "mode=" + mode + "&locationID=" + encodeURIComponent(oLocation);
		var after = null;
		}
	
	else if (mode == "dropDownNewLocation") {
		var oLocationRefID = locationRefID;
		var containerID = 'broadcastNewLocationsJSON';
		var url = '/loginajax/locationsPopUp/';
		var params = "mode=" + mode + "&locationRefID=" + encodeURIComponent(oLocationRefID);	 	
		var after = 'afterDropDownNewLocation';
		}
	
	else if (mode == "createNewLocation") {
		var oLabel = document.getElementById('createNewLocationLabelInput').value;
		var oAddress = document.getElementById('createNewLocationAddressInput').value;
		var containerID = 'broadcastNewLocationsJSON';
		var url = '/loginajax/locationsPopUp/';
		var params = "mode=" + mode + "&new_label=" + encodeURIComponent(oLabel) + "&new_address=" + encodeURIComponent(oAddress);	 	
		var after = 'afterCreateNewLocation';
		}
		
	else if (mode == "changeCal") {
		var oMonth = changeMonth;
		var oYear = changeYear;
		var containerID = 'calContainer';
		var url = '/calendar/' + encodeURIComponent(oYear) + "/" + encodeURIComponent(oMonth)+"/";;
		var params = ''; 
		var after = null;
		}
	
	else if (mode == 'updateDash') {
		var containerID = 'ridesContent';
		var url = insertPage;
		var params = '';
		var after = null;	
	}
	
	else if (mode == 'userNameBox') {
		var oUserName = document.getElementById('userNameBox').value;
		var containerID = 'feedback_user';
		var url = 'validate.php';
		var params = "mode=" + mode + "&userName=" + encodeURIComponent(oUserName);
		var after = null;		
	}
	
	else if (mode == 'emailBox') {
		var oEmail = document.getElementById('emailBox').value;
		var containerID = 'feedback_email';
		var url = 'validate.php';
		var params = "mode=" + mode + "&email=" + encodeURIComponent(oEmail);
		var after = null;		
	}
	
	else if (mode == 'cellPhoneBox') {
		var oPhone = numberParsed;
		var containerID = 'feedback_phone';
		var url = 'validate.php';
		var params = "mode=" + mode + "&phone=" + encodeURIComponent(oPhone);
		var after = null;		
	}
	
	else if (mode == 'displayProfile') {
		var oProfileName = profileName;
		var containerID = 'profilePopUpContainer';
		var url = 'displayProfile.php';
		var params = "mode=" + mode + "&profileName=" + encodeURIComponent(oProfileName);
		var after = null;		
	}
	
	else if (mode == 'removeAvatar') {
		var containerID = 'avatarHere';
		var url = 'profileAvatar.php';
		var params = "mode=" + mode;
		var after = 'afterRemoveAvatar';
		}	
	
	else if (mode =='checkMapLocations') {
	
		document.getElementById("scheduleRideLocations").innerHTML = "";
		if (document.getElementById("okay")) {document.getElementById("okay").innerHTML = "";}
		document.getElementById("map_canvas").innerHTML = "";
		document.getElementById("directions").innerHTML = "";  
		document.getElementById("generateMapError").innerHTML = ""; 
		document.getElementById("scheduleRideDetails").innerHTML = "";
		 
		var containerID = 'scheduleRideLocations';
		var url = '/confirm_ride/';
		var params = "mode=" + mode + "&rideFrom=" + encodeURIComponent(scheduleRideFrom) + "&rideTo=" + encodeURIComponent(scheduleRideTo);
		var after = 'checkMapLocationsAfter';
		}

	else if (mode =='insertRide') {
		
		var containerID = 'scheduleRideDetails';
		var url = '/confirm_ride/';
		var params = "mode=" + mode + "&rideFrom=" + encodeURIComponent(scheduleRideFrom)
									+ "&rideTo=" + encodeURIComponent(scheduleRideTo)
									+ "&rideFrequency=" + encodeURIComponent(scheduleRideFrequency)
									+ "&rideTime=" + encodeURIComponent(scheduleRideTime)
									+ "&rideDate=" + encodeURIComponent(scheduleRideDate)
									+ "&rideAMPM=" + encodeURIComponent(scheduleRideAMPM)
                                    + "&driveRidePref=" + encodeURIComponent(scheduledriveRidePref)
                                    + "&recurringPref=" + encodeURIComponent(scheduleRecurringPref)
									+ "&rideOffset=" + encodeURIComponent(scheduleRideOffset);

		var after = 'insertRideAfter';
		}
	
	<!-- added 2/14 -->
	else if (mode == 'rateRide') {
		var oRideID = rateRideID; //variable is set when function is called below
		var oComment = document.getElementById('rateRideComment'+rateRideID).value;
		
		var selIndexRating = document.getElementById('rideRatingSelect'+rateRideID).selectedIndex;
		var oRating = document.getElementById('rideRatingSelect'+rateRideID).options[selIndexRating].value;
	
		var containerID = 'rateRideNew';
		var url = '/rate_ride/';
		var params = "mode=" + mode + "&rideID=" + encodeURIComponent(oRideID) + "&comment=" + encodeURIComponent(oComment) + "&rating=" + encodeURIComponent(oRating);
		var after = 'clearRateRide'; // place table within div that has id = rideID so that it can be reset to ""
	}
	
	return {containerID : containerID, url : url, params : params, after : after};

}

/* ************************************** */
/* Toggle                                 */
/* ************************************** */

function toggle(div) {
	var el = document.getElementById(div);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
		setCookie(div,div,'14');
			if (div == 'planNew') {
				document.getElementById("planNewSwap").src="/site_media/images/planNewRide.gif";
				}
	}
	else {
		el.style.display = '';
		deleteCookie(div, '', '');
			if (div == 'planNew') {
				document.getElementById("planNewSwap").src="/site_media/images/planNewRide-open.gif";
				}		
	}
}

function swap() {
	document.getElementById("planNewSwap").src="/site_media/images/scheduleButtonBig-2.gif";
}


/* ************************************** */
/* Validate after log in                  */
/* ************************************** */

function validateForm(thisForm) {

// need to use trim function here ...

if (document.getElementById("id_username").value.length < 5 && document.getElementById("id_password").value.length < 5) {
	alert("The user name and password fields must be at least five characters long.");
	document.getElementById("id_username").focus();
	return false;
		} else if (document.getElementById("id_username").value.length < 5) {
		alert("The user name field must be at least five characters long.");
		document.getElementById("id_username").focus();
		return false;
			} else if (document.getElementById("id_password").value.length < 5) {
			alert("The password field must be at least five characters long.");
			document.getElementById("id_password").focus();
			return false;
				} else {		
				return true;
	}
}


/* ************************************** */
/* Sign Out                               */
/* ************************************** */

function signOut() {
	deleteCookie('userName', '', '');
	location.href="http://www.room117.com/ridecell/index.php";
	setTimeout( function() {document.getElementById("id_username").focus();}, 1000 );
}


/* ************************************** */
/* Set Focus                              */
/* ************************************** */

function setFocus() {
	if (document.getElementById("id_username")) {
		document.getElementById("id_username").focus();
		}
}

function focusUserName() {
	if (document.getElementById('userNameBox')) {
		document.getElementById('userNameBox').focus();
		}
	}
	
	
/* ******************************** */
/* Trim the input value             */
/* ******************************** */

function trim(s) {
    return s.replace(/(^\s+)|(\s+$)/g, "")
}

/* ******************************** */
/* Register                         */
/* ******************************** */


function preValidate(mode) {

	if (trim(document.getElementById(mode).value).length > 0) {
		validateSignUp(mode);
		}
		else if (mode == 'userNameBox') {
			document.getElementById('feedback_user').innerHTML = "5 character minimum";
			}
		else if (mode == 'emailBox') {
			document.getElementById('feedback_email').innerHTML = "";
			}
		else if (mode == 'cellPhoneBox') {
			document.getElementById('feedback_phone').innerHTML = "";
			}

}


var numberParsed = "";

function validateSignUp(mode) {

if (mode =='userNameBox') {
	if (document.getElementById('userNameBox').value.length > 4) {
		postPage('userNameBox');
		} else {
			document.getElementById("feedback_user").innerHTML = "<span class=red>Five character minimum!</span>";
			}
	}

else if (mode == 'emailBox') {
	// based on http://www.regular-expressions.info/email.html
	var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]*gatech\.edu$/i;
	
	if (document.getElementById('emailBox').value.search(emailRegEx) == -1) {
		document.getElementById('feedback_email').innerHTML = '<span class=red>Georgia Tech email required.</span>';
		} else {
		//document.getElementById('feedback_email').innerHTML = '<img class=okay src=images/okay.gif>';
		postPage('emailBox');
		}
	}

else if (mode == 'cellPhoneBox') {
	//remove non numbers
	var number = document.getElementById('cellPhoneBox').value;
	numberParsed = number.replace(/[\(\)-]/g, "") //Returns "3044345454" (removes "(", ")", and "-")
	
	//numbers only
	var numericExpression = /^[0-9]+$/;
	
	//make sure number has 10 digits
	if (numberParsed.length == 10 && numberParsed.search(numericExpression) != -1) {
		//document.getElementById('feedback_phone').innerHTML = '<img class=okay src=images/okay.gif>';
		postPage('cellPhoneBox');
		} else {
			document.getElementById('feedback_phone').innerHTML = '<span class=red>xxx-xxx-xxxx</span>'
		}
	}
	
}


function checkPassword(it) {
	var illegalChars = /[\W_]/; // allow only letters and numbers	
	trim(it.value);
	if (it.value.length == 0) {
		document.getElementById("feedback_pass1").innerHTML = "5 character minimum";
	}
		else if (it.value.length < 5) {
			document.getElementById("feedback_pass1").innerHTML = "<span class=red>Five character minimum!</span>";
			}
			else if (illegalChars.test(it.value)) {
				document.getElementById("feedback_pass1").innerHTML = "<span class=red>The password contains illegal characters.</span>";
			}
				else {
					document.getElementById("feedback_pass1").innerHTML = '<img class=okay src=images/okay.gif>';
				}
}


function compare(field) {
	if (field == 'pass') {
		if (!document.getElementById("passBox2").value.length > 0) {
			document.getElementById("feedback_pass2").innerHTML = "";
			}
		else if (document.getElementById("passBox1").value == document.getElementById("passBox2").value) {
			document.getElementById("feedback_pass2").innerHTML = '<img class=okay src=images/okay.gif>';
			} else {
				document.getElementById("feedback_pass2").innerHTML = "<span class=validateError>No match yet...</span>";
				}
		}
	}

function checkZip() {
	var numericExpression = /^[0-9]+$/;
	if (document.getElementById("signUpZip").value.length < 5  || document.getElementById("signUpZip").value.search(numericExpression) == -1) {
		document.getElementById("feedback_zip").innerHTML = "Must be five digits.";
		} else {
			document.getElementById("feedback_zip").innerHTML = '<img class=okay src=images/okay.gif>';	
			}
		
}


function validateRegister(thisform) {

//get values from drop down menus
var selIndexSignUpGender = document.getElementById('signUpGender').selectedIndex;
var signUpGenderID = document.getElementById('signUpGender').options[selIndexSignUpGender].value;

	if (document.getElementById('feedback_user').getElementsByTagName('img').length < 1 || document.getElementById('userNameBox').value.length <5) {
		alert('Please enter a valid user name. (Five character minimum.)');
		document.getElementById('userNameBox').focus();
		return false;
	} else if (document.getElementById('feedback_email').getElementsByTagName('img').length < 1) {
		alert('You must enter a valid Georgia Tech email address.');
		document.getElementById('emailBox').focus();
		return false;
	} 	else if (document.getElementById('feedback_phone').getElementsByTagName('img').length < 1) {
			alert('Please enter a valid phone number (xxx-xxx-xxxx)');
			document.getElementById('cellPhoneBox').focus();
			return false;
	} 	else if (document.getElementById('feedback_pass1').getElementsByTagName('img').length < 1) {
			alert('Please enter a valid password. (Five character minimum.)')
			document.getElementById('passBox1').focus();
			return false;
	} 	else if (document.getElementById('feedback_pass2').getElementsByTagName('img').length < 1) {
			alert('Passwords do not match.')
			document.getElementById('passBox2').focus();
			return false;
	} 	else if (signUpGenderID == 'select') {
			alert('Please select your gender.')
			return false;
	} 	else if (document.getElementById('feedback_zip').getElementsByTagName('img').length < 1) {
			document.getElementById('signUpZip').focus();
			alert('Please enter your zip code.')
			return false;
	} 	else if (document.getElementById('signUpTC').checked == false) {
			alert('Please agree to the terms and conditions.')
			return false;																					
	} else {
	
	
	var j = 0;
	var imgs = document.body.getElementsByTagName("img");
	var fields = 6;
	
	if (imgs.length) {for (var i = 0; i < imgs.length; i++) {
		if (imgs[i].className == "okay") {j++;}}
		 	}
			
		 if (j==fields) {
				return true;
			}
		}
			
}

function showIncentivesTC() {
var selIndexIncentive = document.getElementById('signUpIncentive').selectedIndex;
var incentiveID = document.getElementById('signUpIncentive').options[selIndexIncentive].value;

	if (incentiveID != 'none') {
		document.getElementById('termsContainer').innerHTML = '<div class="signUpYellow" style="text-align:center;margin-bottom:0px;"><span class="signUpYellowHeading">To qualify for this incentive you must use ridecell an average of two (2) times per week during the trail period (January XX to March XX).</span><br/><br/>I have read and agree with the <a class="under" href="terms.php">Terms and Conditions</a>: <input type="checkbox" name="signUpTC" id="signUpTC" value="checkbox"></div>';
		} else {
			document.getElementById('termsContainer').innerHTML = 'I have read and agree with the <a class="under" href="terms.php">Terms and Conditions</a>: <input type="checkbox" name="signUpTC" id="signUpTC" value="checkbox">';
			}
}

/* ******************************** */
/* Toggle Profile                   */
/* ******************************** */


var profileName = "";
function toggleProfile(theprofile) {

	profileName = theprofile;

	var ns = (navigator.appName.indexOf("Netscape") != -1) || window.opera;
	var pY = ns ? pageYOffset : iecompattest().scrollTop;	
	var y2 = pY + 100;
	document.getElementById('viewProfilePopUp').style.top=y2+"px";
	
	// "loading..."
	document.getElementById('profilePopUpContainer').innerHTML = "<div style='text-align:center;margin:0px auto;'><br/><br/>Loading...</br><br/><br/><img src='/site_media/images/ajax-loader.gif'/></div>";
	
	document.getElementById('viewProfilePopUp').style.display='';
	
	postPage('displayProfile');
	}

function closeProfile() {
	document.getElementById('viewProfilePopUp').style.display='none';
	}



/* ******************************** */
/* Toggle Avatar                    */
/* ******************************** */

function toggleAvatar() {
	document.getElementById('avatarForm').style.display='';
	}


function uploadImg(theform) {
	if (parent.document.getElementById('myFile').value.length>0) {
		parent.document.getElementById('avatarFeedback').innerHTML = "Loading...";
		theform.submit();
		} else {
			alert("Select a file to continue.");
			}
}

var thefileVar = "";

function doneLoading(thefile) {
	parent.thefileVar = "<img src='" + thefile + "'/>";
	parent.document.getElementById('avatarHere').innerHTML = "<img src='" + thefile + "'/>";
	parent.document.getElementById('avatarFeedback').innerHTML = "Image Saved. <a class='under' href='javascript:void(0);' onclick='closeAvatarPanel();'/>Click here to close window.</a>";
	parent.document.getElementById("uploadForm").reset(); //clears upload box
}

function closeAvatarPanel() {
if (thefileVar.length > 0) {
	document.getElementById('avatarImageID').innerHTML = thefileVar;
	}
	document.getElementById('avatarForm').style.display= 'none';
	document.getElementById('avatarFeedback').innerHTML = "&nbsp;";
}

function removeAvatar() {
	if (document.getElementById('avatarHere').innerHTML == '<img src="avatars/photo-2.gif">') {
		alert("There is no image to remove.");
		} else if (document.getElementById('avatarHere').innerHTML == "<IMG src=\"avatars/photo-2.gif\">") {
			alert("There is no image to remove"); // IE bug - ???
			} else { 
				postPage('removeAvatar');
				//alert(document.getElementById('avatarHere').innerHTML);
				}

}


/* ******************************** */
/* Edit profile                     */
/* ******************************** */

/* Preferences */
var originalPrefs = "";

function editPreferences() {
	// Save all original values, then insert edit page
	originalPrefs = document.getElementById('prefsContainer').innerHTML;
	document.getElementById('editPrefsToggleContainer').innerHTML = "<a class='green4' href='javascript:void(0);' onclick='cancelPreferences();'>cancel</a>";
	postPage('editPrefs');
}

function savePreferences() {
	if (trim(document.getElementById('carDescPref').value) == "") {
		alert("This field cannot be left blank.");
		document.getElementById('carDescPref').focus();
		// } else if (trim(document.getElementById('maxPassPref').value) == "") {
		// 	alert("This field cannot be left blank.");
		// 	document.getElementById('maxPassPref').focus();
			} else {	
				postPage('savePrefs');
				}
}

function cancelPreferences() {
	document.getElementById('editPrefsToggleContainer').innerHTML = "<a class='green4' href='javascript:void(0);' onclick='editPreferences();'>click here to edit</a>";
	document.getElementById('prefsContainer').innerHTML = originalPrefs;
}

/* Personal info */
var originalPersonal = "";

function editPersonal() {
	// Save all original values, then insert edit page
	originalPersonal = document.getElementById('personalContainer').innerHTML;
	document.getElementById('editPersonalToggleContainer').innerHTML = "<a class='green4' href='javascript:void(0);' onclick='cancelPersonal();'>cancel</a>";
	postPage('editPersonal');
}

function savePersonal() {
	// Do we need some validation functions here?
    postPage('savePersonal');
}

function cancelPersonal() {
	document.getElementById('editPersonalToggleContainer').innerHTML = "<a class='green4' href='javascript:void(0);' onclick='editPersonal();'>click here to edit</a>";
	document.getElementById('personalContainer').innerHTML = originalPersonal;
}

/* Billing info */
var originalBilling = "";

function editBilling() {
	// Save all original values, then insert edit page
	originalBilling = document.getElementById('billingContainer').innerHTML;
	document.getElementById('editBillingToggleContainer').innerHTML = "<a class='green4' href='javascript:void(0);' onclick='cancelBilling();'>cancel</a>";
	postPage('editBilling');
}

function saveBilling() {
	alert('This function is not active.');
}

function cancelBilling() {
	document.getElementById('editBillingToggleContainer').innerHTML = "<a class='green4' href='javascript:void(0);' onclick='editBilling();'>click here to edit</a>";
	document.getElementById('billingContainer').innerHTML = originalBilling;
}


/* ******************************** */
/* Change dashboard panel           */
/* ******************************** */

// to improve: use cookie to select tab to show using php. in js, get current tab based on cookie
// if current tab is passed into fucntion, do nothing.  otherwise update the tabs and load the page
var insertPage = ""
function switchTabs(tab) {
	if (tab == 'dashboard_rides') {
		document.getElementById('dashboard_rides').innerHTML = '<img id="tabRides" src="/site_media/images/tab_week_1.gif">';
		document.getElementById('dashboard_history').innerHTML = '<a href="javascript:void(0);" onclick="switchTabs(\'dashboard_history\');" onmouseover="document.getElementById(\'tabHistory\').src=\'/site_media/images/tab_hist_2.gif\';" onmouseout="document.getElementById(\'tabHistory\').src=\'/site_media/images/tab_hist_3.gif\';"><img id="tabHistory" src="/site_media/images/tab_hist_3.gif"></a>';
		document.getElementById('newride').innerHTML = '<a href="javascript:void(0);" onclick="switchTabs(\'newride\');" onmouseover="document.getElementById(\'tabNew\').src=\'/site_media/images/tab_new_2.gif\';" onmouseout="document.getElementById(\'tabNew\').src=\'/site_media/images/tab_new_3.gif\';"><img id="tabNew" src="/site_media/images/tab_new_3.gif"></a>';
		} else if (tab == 'dashboard_history') {
		document.getElementById('dashboard_rides').innerHTML = '<a href="javascript:void(0);" onclick="switchTabs(\'dashboard_rides\');" onmouseover="document.getElementById(\'tabRides\').src=\'/site_media/images/tab_week_2.gif\';" onmouseout="document.getElementById(\'tabRides\').src=\'/site_media/images/tab_week_3.gif\';"><img id="tabRides" src="/site_media/images/tab_week_3.gif"></a>';
		document.getElementById('dashboard_history').innerHTML = '<img id="tabHistory" src="/site_media/images/tab_hist_1.gif">';
		document.getElementById('newride').innerHTML = '<a href="javascript:void(0);" onclick="switchTabs(\'newride\');" onmouseover="document.getElementById(\'tabNew\').src=\'/site_media/images/tab_new_2.gif\';" onmouseout="document.getElementById(\'tabNew\').src=\'/site_media/images/tab_new_3.gif\';"><img id="tabNew" src="/site_media/images/tab_new_3.gif"></a>';	
		} else if (tab == 'newride') {
		document.getElementById('dashboard_rides').innerHTML = '<a href="javascript:void(0);" onclick="switchTabs(\'dashboard_rides\');" onmouseover="document.getElementById(\'tabRides\').src=\'/site_media/images/tab_week_2.gif\';" onmouseout="document.getElementById(\'tabRides\').src=\'/site_media/images/tab_week_3.gif\';"><img id="tabRides" src="/site_media/images/tab_week_3.gif"></a>';
		document.getElementById('dashboard_history').innerHTML = '<a href="javascript:void(0);" onclick="switchTabs(\'dashboard_history\');" onmouseover="document.getElementById(\'tabHistory\').src=\'/site_media/images/tab_hist_2.gif\';" onmouseout="document.getElementById(\'tabHistory\').src=\'/site_media/images/tab_hist_3.gif\';"><img id="tabHistory" src="/site_media/images/tab_hist_3.gif"></a>';
		document.getElementById('newride').innerHTML = '<img id="tabNew" src="/site_media/images/tab_new_1.gif">';
		}
		insertPage = "/" + tab + "/";
		postPage('updateDash');
}


function editRideDetails() {
	alert("This feature is not yet active.");
}

function deleteRide() {
	if (confirm('Are you sure you want to delete this ride?')) {
		alert("This feature is not yet active.");
	}
}

function confirm_delete(form) {
    var is_delete = confirm("Are you sure you want to delete this ride?");

    var is_delete_rollout = false;
    if (is_delete && !isNaN(parseInt(form.recurrence_of.value))) {
        is_delete_rollout = confirm("This is part of a recurring ride request. Do you want to delete all events of this recurring request, including the recurring request. (Press Cancel to delete this instance alone");
    }

    if(is_delete_rollout) {
        form.delete_rolled_out.value = "true";
    }
        
    if (is_delete) {
        return true;
    } else {
        return false;
    }

}


/* Browser detection for toggle functions */

function iecompattest(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
	}

/* ******************************** */
/* Location menu                    */
/* ******************************** */

function toggleAddEditLocationPanel(mode) {
		
	var ns = (navigator.appName.indexOf("Netscape") != -1) || window.opera;
	var pY = ns ? pageYOffset : iecompattest().scrollTop;	
	var y2 = pY + 75;
	document.getElementById('addEditLocationPopUp').style.top=y2+"px";

	var el = document.getElementById('addEditLocationPopUp');
	el.style.display = '';

	document.getElementById('addEditDiv').innerHTML = "<br/><br/>Loading...</br><br/><br/><img src='/site_media/images/ajax-loader.gif'/>";
	
	if (mode == 'addNewLocationPanel') {
		document.getElementById('radioButtonAddLocation').checked = true;
		} else {
			document.getElementById('radioButtonEditLocation').checked = true;
			}
	
	postPage(mode);	
}

function closeAddEditLocationPanel() {
	var el = document.getElementById('addEditLocationPopUp');
	if ( el.style.display != 'none' ) {
			el.style.display = 'none';
		}
	}

function switchEditAddMenu() {
if (document.getElementById('editLocationsTable')) {
	document.getElementById('addEditDiv').innerHTML = "<br/><br/>Loading...</br><br/><br/><img src='/site_media/images/ajax-loader.gif'/>";
	postPage('addNewLocationPanel');	
	} else {
		document.getElementById('addEditDiv').innerHTML = "<br/><br/>Loading...</br><br/><br/><img src='/site_media/images/ajax-loader.gif'/>";
		postPage('editLocationsPanel');	
	}
}

var editLocationRowOriginal = "";
var theLocation = "";
function editLocation(locationID) {
	editLocationRowOriginal = document.getElementById('locationRow'+locationID).innerHTML;
	var locationTag = document.getElementById("locationTag"+locationID).innerHTML;
	locationTag = locationTag.split("'").join("\'"); // escape single quote (apostrophes)
	var locationAddress = document.getElementById('locationAddress'+locationID).firstChild.innerHTML;
	locationAddress = locationAddress.split("'").join("\'"); // escape single quote (apostrophes)
	if (document.getElementById('editLocationLabelInput')) {
		alert('You can only edit one location at a time.');
    } else {
        var addressConfirm =  '<div id="map_canvas" style="width :520px; height: 300px"></div> <p>Make sure that the marker on the map shows your intended location and press Save Location.</p> <div id="canonicalAddress" style="display:none"></div> <input type="submit" value="Save Location" onclick="saveEditLocation(' + locationID + ')"/>';
        document.getElementById('locationRow'+locationID).innerHTML = 'Label: <input class="editInput" type="text" id="createNewLocationLabelInput" value="' + locationTag + '" maxlength="40"><br/><br/>Address: <input class="editInputLong" type="text" id="createNewLocationAddressInput" value="' + locationAddress + '" maxlength="255"><br/><div class="center"><input class="bold" type="submit" value="Confirm Location"  onclick="confirmLocation();"> &nbsp; &nbsp; <input type="submit" value="Cancel" onclick=\'cancelEditLocation("' + locationID + '");\'></div>';
        document.getElementById('addressConfirm').innerHTML = addressConfirm;
    }
}

function cancelEditLocation(locationID) {
	document.getElementById('locationRow'+locationID).innerHTML = editLocationRowOriginal;
}

function saveEditLocation(locationID) {
	theLocation = locationID;
    var address = document.getElementById('createNewLocationAddressInput');
    var canonical = document.getElementById('canonicalAddress').innerHTML;
    if (canonical === "") {
        return;
    }
    address.value = canonical;
    postPage('saveEditLocation');
}

function deleteEditLocation(locationID) {
	if (confirm('Are you sure you want to delete this location?')) {
		theLocation = locationID;
		postPage('deleteEditLocation');
	}
}


var locationRefID = "";
function dropDownNewLocation() {

	var selIndexWorkLocation = document.getElementById('workLocations').selectedIndex;
	var workLocationRefID = document.getElementById('workLocations').options[selIndexWorkLocation].value;
	
	var selIndexMartaStation = document.getElementById('martaStations').selectedIndex;
	var martaStationRefID = document.getElementById('martaStations').options[selIndexMartaStation].value;	
	
	var selIndexCommuterLot = document.getElementById('commuterLots').selectedIndex;
	var commuterLotRefID = document.getElementById('commuterLots').options[selIndexCommuterLot].value;
	
	if (workLocationRefID == 0 && martaStationRefID == 0 && commuterLotRefID == 0) {
		alert('You must choose a location to continue.');
		} else if ((workLocationRefID > 0 && martaStationRefID > 0) || (martaStationRefID > 0 && commuterLotRefID > 0) || (workLocationRefID > 0 && commuterLotRefID > 0)) {
		alert('Please select one drop down location at at time.');
		} else if (workLocationRefID > 0) {
			alert('This feature is not active.');
			document.getElementById('workLocations').value = 0;
			} else if (martaStationRefID > 0) {
					locationRefID = martaStationRefID;
					postPage('dropDownNewLocation');
					} else if (commuterLotRefID > 0) {
						alert('This feature is not active.');
						document.getElementById('commuterLots').value = 0;
						}
			
	}

function createNewLocation() {
    var address = document.getElementById('createNewLocationAddressInput');
    var canonical = document.getElementById('canonicalAddress').innerHTML;
    if (canonical === "") {
        return;
    }
    address.value = canonical;
    postPage('createNewLocation');
}

var map;
var geocoder;

function confirmLocation() {
    var address = document.getElementById('createNewLocationAddressInput').value;
    var label = document.getElementById('createNewLocationLabelInput').value;
    if (trim(address) === "") {
        alert("Address field cannot be left blank.");
        document.getElementById('createNewLocationAddressInput').focus();
        return;
    } else if (trim(label) === "") {
        alert("Label field cannot be left blank.");
        document.getElementById('createNewLocationLabelInput').focus();
        return;
    }
    document.getElementById('addressConfirm').style.display = '';
    map = new GMap2(document.getElementById('map_canvas'));
    geocoder = new GClientGeocoder();
    geocoder.getLocations(address, addAddressToMap);
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(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 GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
        map.setCenter(point, 13);
        marker = new GMarker(point);
        map.addOverlay(marker);
        map.addControl(new GSmallMapControl());
        marker.openInfoWindowHtml(place.address);
        var canonical = document.getElementById('canonicalAddress');
        canonical.innerHTML = place.address;
    }
}

/* ************************************** */
/* Plan new ride panel                    */
/* ************************************** */

var changeMonth = "";
var changeYear = "";

function upateCal(mode,month,year) {
	if (mode == 'prev') {
		changeMonth = month;
		changeYear = year;
		} else if (mode == 'next') {
			changeMonth = month;
			changeYear = year;
			}
	postPage('changeCal');
}


function nextRideDateSelect(year,month,day,dayNumeric) {

	monthFix = month-1;
		
	var month_names = new Array ( );
	month_names[0] = "January";
	month_names[1] = "February";
	month_names[2] = "March";
	month_names[3] = "April";
	month_names[4] = "May";
	month_names[5] = "June";
	month_names[6] = "July";
	month_names[7] = "August";
	month_names[8] = "September";
	month_names[9] = "October";
	month_names[10] = "November";
	month_names[11] = "December";
	
	var day_names = new Array ( );
	day_names[0] = "Sunday";
	day_names[1] = "Monday";
	day_names[2] = "Tuesday";
	day_names[3] = "Wednesday";
	day_names[4] = "Thursday";
	day_names[5] = "Friday";
	day_names[6] = "Saturday";
	
	document.getElementById('nextRideDate').innerHTML = day_names[dayNumeric] +", " + month_names[monthFix] + " " + day +", " + year + " &nbsp; (<a class='green4' href='javascript:void(0);' onclick='toggle(\"calPopUp\");'>edit</a>) <span id=\"rawDate\" style='display:none;'>" + year + month + day + "</span>";
	toggle('calPopUp');
}


function showRecurringOptions() {
	document.getElementById('specificASAProw').innerHTML = "<select class='planNextInputSelect' id='planNextRideRecurring'/><option value='everySun'>Every Sunday</option><option value='everyMon'>Every Monday</option><option value='everyTue'>Every Tuesday</option><option value='everyWed'>Every Wednesday</option><option value='everyThu'>Every Thursday</option><option value='everyFri'>Every Friday</option><option value='everySat'>Every Saturday</option><option value='MonTueWedThuFri'>Monday - Friday</option><option value='SatSun'>Saturday - Sunday</option><option value='MonWedFri'>Mon, Wed, Fri</option><option value='TueThu'>Tue, Thu</option></select>";
    //NOTE: same nextRideDate thing used for selecting the final date... might need some UI tweaks in the future to help the user
	//document.getElementById('nextRideDate').innerHTML = "Recurring ride";
    document.getElementById('planRideDateType').innerHTML = "Recur Till Date";
    document.getElementById('recurRideMessage').innerHTML = "<br/><br/>Leave it empty for no limit on Recur Till Date";
}

function showSingleOptions() {
	document.getElementById('specificASAProw').innerHTML = ""; 
     //NOTE: commented till feature is added in the backend
    //"<input type='radio' id='specificTime' name='specificASAPradioButton' value='specificTime' onclick='specificSelected();' checked> At a specific time  &nbsp; <input type='radio' id='asapTime' name='specificASAPradioButton' value='asapTime' onclick='asapSelected();'> As soon as possible";

    document.getElementById('planRideDateType').innerHTML = "Date:";
    document.getElementById('recurRideMessage').innerHTML = "";

	document.getElementById('nextRideDate').innerHTML = "<a href='javascript:void(0);' onclick='toggle(\"calPopUp\");'>Click here to select date <img src='/site_media/images/calendar.png'></a>";
    //NOTE: commented till feature is added in the backend
	document.getElementById('nextRideTime').innerHTML = "<input class='planNextInputDate' id='planNextRideTimeInput' type='text' value='9:00'> <select class='planNextInputSelect' id='planNextRideAMPM'/><option value='0'>AM or PM</option><option value='AM'>AM</option><option value='PM'>PM</option></select>"; // <select class='planNextInputSelect' id='planNextRideOffset'/><option value='5'>+/- 5 minutes</option><option value='15'>+/- 15 minutes</option><option value='30'>+/- 30 minutes</option><option value='45'>+/- 45 minutes</option><option value='60'>+/- 60 minutes</option><option value='90'>+/- 90 minutes</option><option value='120'>+/- 120 minutes</option></select>";
	}

function asapSelected() {
	document.getElementById('nextRideDate').innerHTML = "As soon as possible";
	document.getElementById('nextRideTime').innerHTML = "As soon as possible";
}

function specificSelected() {
	document.getElementById('nextRideDate').innerHTML = "<a href='javascript:void(0);' onclick='toggle(\"calPopUp\");'>Click here to select date <img src='/site_media/images/calendar.png'></a>";
	document.getElementById('nextRideTime').innerHTML = "<input class='planNextInputDate' id='planNextRideTimeInput' type='text' value='9:00'> <select class='planNextInputSelect' id='planNextRideAMPM'/><option value='0'>AM or PM</option><option value='AM'>AM</option><option value='PM'>PM</option></select> <select class='planNextInputSelect' id='planNextRideOffset'/><option value=0>+/-</option><option value='5'>5 minutes</option><option value='15'>+/- 15 minutes</option><option value='30'>+/- 30 minutes</option><option value='45'>+/- 45 minutes</option><option value='60'>+/- 60 minutes</option><option value='90'>+/- 90 minutes</option><option value='120'>+/- 120 minutes</option></select>";
}


var scheduleRideFrom;
var scheduleRideTo;
var scheduleRideFrequency;
var scheduleRideTime;
var scheduleRideDate;
var scheduleRideAMPM;
var scheduleRideOffset;
var scheduledriveRidePref;
var scheduleRecurringPref;

function scheduleRide() {

    var recurringPref = '';
    var planRideDate = '';
	
	// get drive or ride preference
	var selIndexDriveRide = document.getElementById('driveRidePref').selectedIndex;
	var driveRidePref = document.getElementById('driveRidePref').options[selIndexDriveRide].value;
				
	// get frequency -- single or recurring ride?		
	if (document.getElementById('frequencySingle').checked == true) {
		var frequency = 'single';
		} else if (document.getElementById('frequencyRecurring').checked == true) {
			var frequency = 'recurring';
			}
	
	// if frequency = single, get the time -- specific time or ASAP. if frequency = recurring, get the days from the drop down menu
    //NOTE: previously this block was only for single rides if (frequency == 'single') 
	{
        //NOTE: radiobuttons removed till feature supported in backend
		//if (document.getElementById('specificTime').checked == true) {
		{
			// get time
			var planRideTime = document.getElementById('planNextRideTimeInput').value;
			//get date
			if (document.getElementById('rawDate')) {
				var planRideDate = document.getElementById('rawDate').innerHTML;
				}
			//get am or pm
			var selIndexAMPM = document.getElementById('planNextRideAMPM').selectedIndex;
			var ampmPref = document.getElementById('planNextRideAMPM').options[selIndexAMPM].value;			
			//NOTE: get offset commented till feature is added
            /*
			var selIndexOffset = document.getElementById('planNextRideOffset').selectedIndex;
			var offsetPref = document.getElementById('planNextRideOffset').options[selIndexOffset].value;
            */
		} 
        //NOTE: commented till feature is added
        /*
        if (document.getElementById('asapTime').checked == true) {
			var planRideTime = 'ASAP';
			var planRideDate = 'ASAP';
			var ampmPref = 'N/A';
			//NOTE: get offset commented till feature is added
			//var offsetPref = 'N/A';
		}
        */
    }
	if (frequency == 'recurring') {
		//var planRideTime = document.getElementById('planNextRideTimeInput').value;
		var selIndexRecurring = document.getElementById('planNextRideRecurring').selectedIndex;
		recurringPref = document.getElementById('planNextRideRecurring').options[selIndexRecurring].value;
		//var planRideDate = recurringPref;
		//var selIndexAMPM = document.getElementById('planNextRideAMPM').selectedIndex;
		//var ampmPref = document.getElementById('planNextRideAMPM').options[selIndexAMPM].value;
		//NOTE: get offset commented till feature is added
        /*
		var selIndexOffset = document.getElementById('planNextRideOffset').selectedIndex;
		var offsetPref = document.getElementById('planNextRideOffset').options[selIndexOffset].value;				
        */
		}
	
	//get arrival and departure destinations
		var selIndexDepart = document.getElementById('planNextLocationsSelectDD').selectedIndex;
		var departPref = document.getElementById('planNextLocationsSelectDD').options[selIndexDepart].value;
		
		var selIndexTo = document.getElementById('planNextLocationsSelectDD2').selectedIndex;
		var toPref = document.getElementById('planNextLocationsSelectDD2').options[selIndexTo].value;

    if (document.getElementById('frequencySingle').checked == true && !(document.getElementById('rawDate'))) {
		alert('You must specify a date to continue.');
        return;
    } 

    if (ampmPref == 0) {
            alert('Please specify AM or PM');
            return;
    } 
    
    if (departPref == toPref) {
            alert('Your Depart and Arrive locations cannot be the same.');
            return;
    } 

    /*
        alert('Drive or ride preference: ' + driveRidePref + '\n' + 
              'Frequency: ' + frequency + '\n' +
              'Time: ' + planRideTime + '\n' +
              'Date: ' + planRideDate + '\n' +
              'AM or PM?: ' + ampmPref + '\n' +
              'Offset: ' + offsetPref + ' minutes\n' +
              'From: Location ID ' + departPref + '\n' +
              'To: Location ID ' + toPref);
    */
    scheduleRideFrequency = frequency;
    scheduleRideTime = planRideTime;
    scheduleRideDate = planRideDate;
    scheduleRideAMPM = ampmPref;
    //NOTE:commented till feature is added
    scheduleRideOffset = null; //offsetPref;					
    scheduleRideFrom = departPref;
    scheduleRideTo = toPref;
    scheduledriveRidePref = driveRidePref;
    scheduleRecurringPref = recurringPref;
    
    postPage('checkMapLocations');

}

<!-- added 2/14 -->
var rateRideID = '';
function rateRide(rideID) {
 rateRideID = rideID;
 // get rating and commment inside postPage function above
 // to make div IDs unique on the form on the actual dashboard page, append rideID to each ID within the form
 
	var selIndexRating = document.getElementById('rideRatingSelect'+rateRideID).selectedIndex;
	var ratingCheck = document.getElementById('rideRatingSelect'+rateRideID).options[selIndexRating].value;
	
	if (ratingCheck == "rankPref") {
		alert('Please select a rating to rate this ride.');
		} else {
			postPage('rateRide');
			}
		

}

/* ************************************** */
/* Cookies!                               */
/* ************************************** */

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}


/* ************************************** */
/* Google Maps API */
/* ************************************** */

    var map;
    var gdir;
    var geocoder;
    var addressMarker;
	
	var startAddress;
	var startAddress;
	var endAddress;
	var startAddressReply;
	var endAddressReply;

	function checkLocations() {
		
		if (document.getElementById('mapStartAddress')) {
			geocoder = new GClientGeocoder();
			startAddress = document.getElementById('mapStartAddress').innerHTML;
			geocoder.getLocations(startAddress,checkStart);
			}
				

		}

    function checkStart(response) {
		
      if (!response || response.Status.code != 200) {
        document.getElementById("generateMapError").innerHTML = "Sorry, we cannot geocode the start address";
      } else {
		startAddressReply = response.Placemark[0].AddressDetails.Accuracy;
      }
	  if (startAddressReply >= 8) {
		endAddress = document.getElementById('mapEndAddress').innerHTML;
	  	geocoder.getLocations(endAddress,checkEnd);
	  	} else {
		document.getElementById("generateMapError").innerHTML = "The starting address must be more precise."
		}
    }

    function checkEnd(response) {
      if (!response || response.Status.code != 200) {
        document.getElementById("generateMapError").innerHTML = "Sorry, we cannot geocode the end address";
      } else {
		endAddressReply = response.Placemark[0].AddressDetails.Accuracy;
      }
	  if (endAddressReply >= 8) {
		postPage('insertRide');
	  		} else {
			document.getElementById("generateMapError").innerHTML = "The ending address must be more precise."
			}
    }
	
   function initialize() {
      if (GBrowserIsCompatible()) {    
		
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "error", handleErrors);
        setDirections(startAddress, endAddress, "en_US");
		// Note: info at http://code.google.com/apis/maps/documentation/reference.html#GDirections
      }
    }
    
    function setDirections(fromAddress, toAddress, locale) {
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }

    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     document.getElementById("errorContainer").innerHTML = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code;
	   
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     document.getElementById("errorContainer").innerHTML = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code;
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     document.getElementById("errorContainer").innerHTML = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code;

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     document.getElementById("errorContainer").innerHTML = "The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code;
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	    document.getElementById("errorContainer").innerHTML = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code;

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     document.getElementById("errorContainer").innerHTML = "A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;
	    
	   else document.getElementById("errorContainer").innerHTML = "An unknown error occurred.";
	   
	}	
