/* ###################################### */
/* ###################################### */
/*                                        */
/*     Ride Cell is powered by the        */
/*         Mr. Clean Ajax API             */
/*             by Mike Wilt               */
/*         mikewilt [AT] gmail            */
/*             (c) 2008                   */ 
/*                                        */
/* ###################################### */
/* ###################################### */


//GLOBAL TIMER
var refresh_timer = null;
var startAddressLatLng;
var endAddressLatLng;
//GLOBAL wizard
var wizard = null;
var num_prefs_checked = 0;
google.load("yui","2.7.0");


//this following if loop overrides IE's default getElementById and does it in W3C standards way...this is the only
//fix that seems be nice and permanent and we don't have to play around with html in many places.
if (/msie/i.test (navigator.userAgent)) //only override IE
{
  document.nativeGetElementById = document.getElementById; 
  document.getElementById = function(id)
  {
    var elem = document.nativeGetElementById(id);
    if(elem)
    {
      //make sure that it is a valid match on id
      if(elem.attributes['id'].value == id)
      {
        return elem;
      }
      else
      {
        //otherwise find the correct element
        for(var i=1;i<document.all[id].length;i++)
        {
          if(document.all[id][i].attributes['id'].value == id)
          {
            return document.all[id][i];
          }
        }
      }
    }
    return null;
  }
}

function dateToLocaleString(dt, cal) {
            var wStr = cal.cfg.getProperty("WEEKDAYS_LONG")[dt.getDay()];
            var dStr = dt.getDate();
            var mStr = cal.cfg.getProperty("MONTHS_LONG")[dt.getMonth()];
            var yStr = dt.getFullYear();
            return (wStr + ", " + dStr + " " + mStr + " " + yStr);
}

function handleSelect(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("cal_date");
        var rawDate = document.getElementById("rawDate");
        month = month + "";
        if (month.length < 2)
            month = '0' + month;
        day = day + ''
        if(day.length<2)
            day = '0' + day;
        rawDate.innerHTML = year + month + day;
        txtDate1.innerHTML =  dateToLocaleString(this.toDate(date), this);
}

function handlePanelClose(type, args, obj) {
        if(refresh_timer == null) {
            refresh_timer= setInterval("refresh_tab()", 20000);
        }
}

function show_mini_map(url, elem_id) {
    //alert(url);
    //alert(elem_id);
    YAHOO.example.directionsPanel.render(elem_id);
    YAHOO.example.directionsTransaction = YAHOO.util.Connect.asyncRequest('GET', url, YAHOO.example.directionsCallback, null); 
    YAHOO.example.directionsPanel.show();
    if(refresh_timer) {
        clearInterval(refresh_timer);
        refresh_timer = null;
    }
}

function show_delete(trip_id, container_id) {
    YAHOO.example.deletePanel.cfg.setProperty('context',[container_id, 'tr', 'tr', ["beforeShow"]]);
    YAHOO.example.deletePanel.render(container_id);
    YAHOO.example.deleteShowTransaction = YAHOO.util.Connect.asyncRequest('GET', '/show_delete/'+trip_id, YAHOO.example.deleteCallback, null);
    YAHOO.example.deletePanel.show();
    if(refresh_timer) {
        clearInterval(refresh_timer);
        refresh_timer = null;
    }
}

function post_newride() {

        var container_id = 'finishWait';
        var url = '/confirm_ride/';
        var mode = 'insertRide';
        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)
            + "&luckyPref=" + encodeURIComponent(scheduleLuckyPref)
            + "&scheduleRangeEndTime="+encodeURIComponent(scheduleRangeEndTime)
            + "&scheduleRangeAMPM="+encodeURIComponent(scheduleRangeAMPM)
            + "&scheduleReturnTime="+encodeURIComponent(scheduleReturnTime)
            + "&scheduleReturnAMPM="+encodeURIComponent(scheduleReturnAMPM)
            + "&scheduleReturnEndTime="+encodeURIComponent(scheduleReturnEndTime)
            + "&scheduleReturnEndAMPM="+encodeURIComponent(scheduleReturnEndAMPM)
	    + "&trafficTripRide="+encodeURIComponent(scheduleTrafficTrip);

        YAHOO.example.newrideTransaction = YAHOO.util.Connect.asyncRequest('POST', url, YAHOO.example.newrideCallback, params);
        YAHOO.example.wait.render(container_id);
        YAHOO.example.wait.show();
}

function hide_delete() {
    YAHOO.example.deletePanel.hide();
}

function show_mini_profile(user_id, elem_id, confirmed_status) {

    YAHOO.example.myPanel.render(elem_id);
    YAHOO.example.transaction = YAHOO.util.Connect.asyncRequest('GET', '/gt/profile/'+user_id+'/1/'+confirmed_status+'/', YAHOO.example.callback, null); 
    YAHOO.example.myPanel.show();
    if(refresh_timer) {
        clearInterval(refresh_timer);
        refresh_timer = null;
    }
}

function loadMyFuncModule() {
  var dj_global = this; // global scope reference
  if (window.execScript) {

    window.execScript(maps_script); // eval in global scope for IE
    return null; // execScript doesn.t return anything
  }
  return dj_global.eval ? dj_global.eval(maps_script) : eval(maps_script);
}

function init_calendar() {
    var loader = new YAHOO.util.YUILoader({
      require: ["button", "calendar", "container", "dragdrop", "connection"],
      base: "http://ajax.googleapis.com/ajax/libs/yui/2.7.0/build/",
      onSuccess: function() {
            // start playing with buttons and calendars!
            YAHOO.namespace("example");
            if(document.getElementById("cal2Container")) {
                var today = new Date();
                var mindate = (today.getMonth()+1)+"/"+today.getDate()+"/"+today.getFullYear();
		//removed a comma after 'mindate' in the line below, to avoid errors in IE
                YAHOO.example.cal2 = new YAHOO.widget.Calendar("cal2","cal2Container", { mindate:mindate } );
                YAHOO.example.cal2.render();
                YAHOO.example.cal2.show();
                // Listener to show the single page Calendar when the button is clicked
                YAHOO.util.Event.addListener("nextRideDate", "click", YAHOO.example.cal2.show, YAHOO.example.cal2, true);
                YAHOO.example.cal2.selectEvent.subscribe(handleSelect, YAHOO.example.cal2, true);
            }

            if (document.getElementById("finishWait")) {
                // Initialize the temporary Panel to display while waiting for external content to load
                YAHOO.example.wait = 
                        new YAHOO.widget.Panel("wait",  
                            { width:"240px", 
                              fixedcenter:true, 
                              close:false, 
                              draggable:false, 
                              zindex:4,
                              modal:true,
                              visible:false
                            } 
                        );

                YAHOO.example.wait.setHeader("Loading, please wait...");
                YAHOO.example.wait.setBody('<img src="http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif" />');

                YAHOO.example.newrideSuccess = function(o) {
                    var scheduleRideDetails = document.getElementById("scheduleRideDetails");
                    scheduleRideDetails.innerHTML = o.responseText;

                    YAHOO.example.wait.hide();
                }

                YAHOO.example.newrideCallback = 
                {
                    success: YAHOO.example.newrideSuccess,
                    failure: function(o) {
                        YAHOO.example.wait.hide();
                        document.getElementById("serverError").innerHTML="<strong>  Oops. Server error. Please try again after some time. </strong>";
                    }
                }
            }

            if(document.getElementById("myPanel")) {

                YAHOO.example.myPanel = new YAHOO.widget.Panel("abcd", {
                width:"450px", 
                constraintoviewport: true, 
		//removed a comma after the line below, to avoid errors in IE
                visible:false 
                } );
             
                YAHOO.example.myPanel.setHeader('profile details');
                YAHOO.example.myPanel.setBody("loading");

                YAHOO.example.responseSuccess = function(o) {
                        YAHOO.example.myPanel.setBody(o.responseText);
                        //YAHOO.example.myPanel.render(); is this needed?
                }

                YAHOO.example.callback = 
                { 
                    success: YAHOO.example.responseSuccess, 
                    //TODO: make the failure cass fill up the fail container div
                    failure: function(o) {
                                document.getElementById("serverError").innerHTML="<strong>  Oops. Server error. Please try again after some time. </strong>";
      			//removed a comma after the bracket below, to avoid errors in IE    
		        }
                } 
                YAHOO.example.myPanel.hideEvent.subscribe(handlePanelClose, YAHOO.example.myPanel);

                YAHOO.example.directionsPanel = new YAHOO.widget.Panel("directions", {
		    width: "780px",
		    height:"480px",
                    constraintoviewport: true,
		    //removed a comma after the line below, to avoid errors in IE			
                    visible: false
                });
                YAHOO.example.directionsPanel.setHeader('direction details');
                YAHOO.example.directionsPanel.setBody('loading');

                YAHOO.example.directionsResponseSuccess = function(o) {
                    var script_regex = /\/\/start_gmaps_initialize((.|\n)*)\/\/end_gmaps_initialize/;
                    maps_script = script_regex.exec(o.responseText)[1];
                    YAHOO.example.directionsPanel.setBody(o.responseText);
                    loadMyFuncModule();
                    gmaps_initialize();
                }

                YAHOO.example.directionsCallback = 
                {
                    success: YAHOO.example.directionsResponseSuccess,
                    failure: function(o) {
                                document.getElementById("serverError").innerHTML="<strong>  Oops. Server error. Please try again after some time. </strong>";
			//removed a comma after the bracket below, to avoid errors in IE
                            }
                }

                YAHOO.example.directionsPanel.hideEvent.subscribe(handlePanelClose, YAHOO.example.directionsPanel);
                //--------------------------

                YAHOO.example.deletePanel = new YAHOO.widget.Panel("delete", {
                    width: "550px",
                    constraintoviewport: true,
                    //removed a comma from the end of the line below, to avoid errors in IE
                    visible: false
                });
                YAHOO.example.deletePanel.setHeader('choose a delete option');
                YAHOO.example.deletePanel.setBody('loading');

                YAHOO.example.deleteResponseSuccess = function(o) {
                    YAHOO.example.deletePanel.setBody(o.responseText);
                }

                YAHOO.example.deleteCallback = 
                {
                    success: YAHOO.example.deleteResponseSuccess,
                    failure: function(o) {
                                document.getElementById("serverError").innerHTML="<strong>  Oops. Server error. Please try again after some time. </strong>";
			//removed a comma after the bracket below, to avoid errors in IE
                            }
                }

                YAHOO.example.deletePanel.hideEvent.subscribe(handlePanelClose, YAHOO.example.deletePanel);
            }
      }
    });
    loader.insert();

}

google.setOnLoadCallback(init_calendar);


/* ******************************** */
/* Begin postPage function          */
/* ******************************** */

function postPage(mode, trip_id, other_data){
    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;

    if (!trip_id){
	var trip_id = 0;
    }
    if (!other_data){
	var other_data =  'none';
    }

    // Retrieve variables for the page that's to be inserted 
    var variables = retrieveVars(mode, trip_id, other_data);
    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 -->
            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 (postPageRequest.readyState == 4) {
            init_calendar();
        }
        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 = "";
	    //ticket #54
	    document.getElementById('confirm_new_location').style.visibility = "visible";
	    document.getElementById('addressConfirm').style.visibility = "hidden";
        }
        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') {
            if (document.getElementById("okay") && document.getElementById("okay").innerHTML != "" && postPageRequest.readyState==4) {
		//var JSONobject = JSON.parse(postPageRequest.responseText);
		stlat = stlng = endlat = endlng = null;
		/*if (JSONobject[0] != 0){
		    stlat = JSONobject[0];
		    stlng = JSONobject[1];
		}
		if (JSONobject[2] != 0){
		    endlat = JSONobject[2];
		    endlng = JSONobject[3];
		    }*/
		stlat = parseFloat(document.getElementById("stlat").innerHTML);
		stlng = parseFloat(document.getElementById("stlng").innerHTML);

		endlat = parseFloat(document.getElementById("endlat").innerHTML);
		endlng = parseFloat(document.getElementById("endlng").innerHTML);
		
		if(stlat==0)
		    stlat = stlng = null;
		if(endlat==0)
		    endlat = endlng = null;
                checkLocations(stlat, stlng, endlat, endlng);
            }
        }
        
        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 != "" && postPageRequest.readyState==4) {
                initialize();
                ;
            }
        }
        
        <!-- added 2/14 -->
        else if (after == 'clearRateRide') { 
            document.getElementById("rateRideContainer" + rateRideID).innerHTML = "<div class='successRate'>Success! Ride number " + rateRideID +  " has been rated.</div>";
        }
        else if (after == 'dashRides') {
             if (postPageRequest.readyState == 4) {
                document.getElementById('loadingContainer').innerHTML = "";
            }
        }
        else if (after == 'newride') {
            if (postPageRequest.readyState==4) {
                init_wizard();
            }
        }
        else if (after = 'after_show_rides_map') {
            if (postPageRequest.readyState==4) {
                var maps_script = document.getElementById('gmaps_script').text;
                eval(maps_script);
                gmaps_initialize();
                if(refresh_timer) {
                    clearInterval(refresh_timer);
                    refresh_timer = null;
                }
            }
        }
        
    }
}


/* ******************************** */
/* Return parameters for postPage   */
/* ******************************** */

function retrieveVars(mode, trip_id, other_data) {

    //show editLocations panel
    if (mode == "editLocationsPanel") {
        var containerID = 'addEditDiv';
        var url = '/loginajax/locationsPopUp/';
        var params =  "mode=" + mode;
        var after = null;
    }
    
    else if (mode == "acquireOwnership"){
	var containerID = 'allRideRequests';
	var url = '/updateDispatcherTable/';
	var params = "mode=" + mode + "&trip_id=" + trip_id + "&dispatcher_name=" + other_data;
	var after = null;
    }

    else if (mode == "dispatch_from"){
	var containerID = 'allRideRequests';
	var url = '/updateDispatcherTable/';
	var params = "mode=" + mode + "&trip_id=" + trip_id + "&from=" + other_data;
	var after = null;
    }

    else if (mode == "dispatch_to"){
	var containerID = 'allRideRequests';
	var url = '/updateDispatcherTable/';
	var params = "mode=" + mode + "&trip_id=" + trip_id + "&to=" + other_data;
	var after = null;
    }
    
    //show addNewLocation panel
    else if (mode == "addNewLocationPanel") {
        var containerID = 'addEditDiv';
        var url = '/loginajax/locationsPopUp/';
        var params =  "mode=" + mode;
        var after = null;
    }

    //shared locations starts
    else if (mode == "editSharedLocationsPanel") {
        var containerID = 'addEditDiv';
        var url = '/loginajax/locationsPopUp/';
        var params =  "mode=" + mode;
        var after = null;
    }

    else if (mode == "addSharedToMyLocation"){
	var containerID = 'addEditDiv';
	var url = '/loginajax/locationsPopUp/';
	var selSharedLoc = document.getElementById('SharedLocDropDown').selectedIndex;		
	var oSharedLocId = document.getElementById('SharedLocDropDown').options[selSharedLoc].value;
	var params = "mode=" + mode + "&locationId=" + oSharedLocId;
	var after = null;
    }

    else if (mode == "removeSharedMyLocation"){
	var containerID = 'addEditDiv';
	var url = '/loginajax/locationsPopUp/';
	var params = "mode=" + mode + "&locationId=" + ParamValue;
	var after = null;
    }
   //shared locations ends

    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 selIndexDriveRideSharing = document.getElementById('driveRideSharing').selectedIndex;
        var oDriveRideSharing = document.getElementById('driveRideSharing').options[selIndexDriveRideSharing].value;

        var oCarDescPref = document.getElementById('carDescPref').value;
        var selIndexCarDescriptionSharing = document.getElementById('carDescriptionSharing').selectedIndex;
        var oCarDescriptionSharing = document.getElementById('carDescriptionSharing').options[selIndexCarDescriptionSharing].value;

        var selIndexSmoke = document.getElementById('smokePref').selectedIndex;
        var oSmokePref = document.getElementById('smokePref').options[selIndexSmoke].value; 
        var selIndexSmokerSharing = document.getElementById('smokerSharing').selectedIndex;
        var oSmokerSharing = document.getElementById('smokerSharing').options[selIndexSmokerSharing].value;
	
	var traffic_data_mins = document.getElementById('traffic_data_mins').value;
	var selSendTrafficData = document.getElementById('sendTrafficData').selectedIndex;
	var oSendTrafficData = document.getElementById('sendTrafficData').options[selSendTrafficData].value;
	if (oSendTrafficData == 'SMS')
	{
		oSendTrafficData = 'mobile';
	}	


        var containerID = 'prefsContainer';
        var url = '/loginajax/profilePrefsSave/';
        var params = "mode=" + mode 
                    + "&rideordrive=" + encodeURIComponent(oDriveRidePref) 
                    + "&cardescription=" + encodeURIComponent(trim(oCarDescPref))
                    + "&smoker=" + encodeURIComponent(oSmokePref)
                    + "&rideordrive_sharing="+encodeURIComponent(oDriveRideSharing)
                    + "&cardescription_sharing="+encodeURIComponent(oCarDescriptionSharing)
                    + "&smoker_sharing="+encodeURIComponent(oSmokerSharing)
		    + "&traffic_data_mins="+encodeURIComponent(traffic_data_mins)
		    + "&send_traffic_data="+encodeURIComponent(oSendTrafficData);

        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 selIndexAffliliationSharing = document.getElementById('affiliationSharing').selectedIndex;
        var oAffiliationSharing = document.getElementById('affiliationSharing').options[selIndexAffliliationSharing].value;
        var selIndexGender = document.getElementById('genderPersonal').selectedIndex;
        var oGenderPersonal = document.getElementById('genderPersonal').options[selIndexGender].value;
        var selIndexGenderSharing = document.getElementById('genderSharing').selectedIndex;
        var oGenderSharing = document.getElementById('genderSharing').options[selIndexGenderSharing].value;
        var oEmailPersonal = document.getElementById('emailPersonal').value;
        var selIndexEmailSharing = document.getElementById('emailSharing').selectedIndex;
        var oEmailSharing = document.getElementById('emailSharing').options[selIndexEmailSharing].value;

        var oPhonePersonal = document.getElementById('phonePersonal').value;
        var selIndexPhoneSharing = document.getElementById('phoneSharing').selectedIndex;
        var oPhoneSharing = document.getElementById('phoneSharing').options[selIndexPhoneSharing].value;
        var selIndexProvider = document.getElementById('provider').selectedIndex;
        var oProvider = document.getElementById('provider').options[selIndexProvider].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)
            + "&affiliation_sharing="+encodeURIComponent(oAffiliationSharing)
            + "&email_sharing="+encodeURIComponent(oEmailSharing)
            + "&mobileno_sharing="+encodeURIComponent(oPhoneSharing)
            + "&gender_sharing="+encodeURIComponent(oGenderSharing)
            + "&provider="+encodeURIComponent(oProvider);

        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 = '';
        if (insertPage == '/dashboard_rides/') {
            var after = 'dashRides';
        } else if (insertPage == '/newride/') {
            var after = 'newride';
        }
        else {
            var after = null;
        }
    }

    else if (mode == 'show_rides_map') {
        var containerID = 'directionsDiv';
        var url = '/' + mode + match_ids;
        var params = '';
        var after = 'after_show_rides_map';
    }
    
    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("route_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';
    }

    // 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 {
            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) {
            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');
    }

}


/* ******************************** */
/* 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(document.getElementById('carDescPref').name + " field cannot be left blank.");
        document.getElementById('carDescPref').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;
}


function refresh_tab() {
    // "loading..."
    switchTabs('dashboard_rides');
}
        
/* ******************************** */
/* 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) {

	var dashboard_rides_tab, dashboard_history_tab, newride_tab, loadingContainer_tab;

if(refresh_timer!=null && tab!='dashboard_rides') {
    clearInterval(refresh_timer);
    refresh_timer = null;
    num_prefs_checked = 0;
}
	//although the if-loop at the start of this js file should remove all this problem, i'm still reluctant to 
	//remove this.....
	if (navigator.appName == 'Microsoft Internet Explorer'){
		dashboard_rides_tab = document.getElementById("dashboard_rides");
		dashboard_history_tab = document.getElementById("dashboard_history");
		newride_tab = document.getElementById("newride");
		loadingContainer_tab = document.getElementById("loadingContainer");
	}
	else{
		dashboard_rides_tab = document.getElementById( 'dashboard_rides' );
		dashboard_history_tab = document.getElementById('dashboard_history');
		newride_tab = document.getElementById('newride');
		loadingContainer_tab = document.getElementById('loadingContainer');
	}


if (tab == 'dashboard_rides'){
    if(refresh_timer == null) {
        refresh_timer= setInterval("refresh_tab()", 20000);
        num_prefs_checked = 0;
    }



    dashboard_rides_tab.innerHTML = '<img id="tabRides" src="/site_media/images/tab_week_1.gif">';
    dashboard_history_tab.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>';
    newride_tab.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>';
    
    loadingContainer_tab.innerHTML = "<div style='position:absolute;top:0;left:0;color:#fff;padding:2px 2px 20px; display:block; width: 1200px; height: 1200px;zIndex:3;background-color: azure; opacity: 0.7'><br/><br/><br/><br/><br/><br/><img src='/site_media/images/ajax-loader.gif'/><br/><br/><h2 style='opacity:1.0; color: black'>Getting latest matches....</h2></br><br/><br/><br/><br/><br/><br/></div>";

    } else if (tab == 'dashboard_history') {
        dashboard_rides_tab.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>';

        dashboard_history_tab.innerHTML = '<img id="tabHistory" src="/site_media/images/tab_hist_1.gif">';

        newride_tab.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') {
        dashboard_rides_tab.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>';
        dashboard_history_tab.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>';
        newride_tab.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                    */
/* ******************************** */

/* Shared locations */
function SharedToMyLocation(mode){
	postPage(mode);
}


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 != 'editSharedLocationsPanel'){*/
	    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="location_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 = '';
    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) {
    if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to geocode that address");
    } else {
        place = response.Placemark[0];
        if (place.AddressDetails.Accuracy < 8) {
            alert("Please specifiy a more accurate address");
            return;
        }
        map = new GMap2(document.getElementById('location_map_canvas'));
        map.clearOverlays();
        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;

	var confirmLocation = document.getElementById('confirm_new_location');
	confirmLocation.style.visibility = "hidden";
	document.getElementById('addressConfirm').style.visibility = "visible";
    }
}

/* ************************************** */
/* directions Popup                       */
/* ************************************** */
var match_ids = null;
function toggledirectionsPanel(url) {
        
    var ns = (navigator.appName.indexOf("Netscape") != -1) || window.opera;
    var pY = ns ? pageYOffset : iecompattest().scrollTop;   
    var y2 = pY + 75;
    document.getElementById('directionsPopUp').style.top=y2+"px";

    var el = document.getElementById('directionsPopUp');
    el.style.display = '';

    match_ids = '/'+url;
    postPage('show_rides_map'); 
}

function closedirectionsPanel() {
    var el = document.getElementById('directionsPopUp');
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
        if(refresh_timer == null) {
            refresh_timer= setInterval("refresh_tab()", 20000);
        }
    }
}


/* ************************************** */
/* 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 = "<input type='checkbox' name='planNextRideRecurring' value='Sun' />Sunday <input type='checkbox' name='planNextRideRecurring' value='Mon' />Monday <input type='checkbox' name='planNextRideRecurring' value='Tue' />Tuesday <input type='checkbox' name='planNextRideRecurring' value='Wed' />Wednesday <input type='checkbox' name='planNextRideRecurring' value='Thu' />Thursday <input type='checkbox' name='planNextRideRecurring' value='Fri' />Friday <input type='checkbox' name='planNextRideRecurring' value='Sat' />Saturday";
    //NOTE: same nextRideDate thing used for selecting the final date... might need some UI tweaks in the future to help the user
    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'> AM<input type='radio' name='nextride_radio' id='nextride_radio1' value='AM'> PM<input type='radio' name='nextride_radio' id='nextride_radio2' value='PM'> "; }

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'>  AM<input type='radio' name='nextride_radio' id='nextride_radio1' value='AM'> PM<input type='radio' name='nextride_radio' id='nextride_radio2' value='PM'> <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;
var scheduleLuckyPref;
var scheduleRangeEndTime;
var scheduleRangeAMPM;
var scheduleReturnTime;
var scheduleReturnAMPM;
var scheduleReturnEndTime;
var scheduleReturnEndAMPM;

//traffic trip only ride
var scheduleTrafficTrip;

function scheduleRide() {

    var recurringPref = '';
    var planRideDate = '';
    var driveRidePref = null;
    
    // get drive or ride preference
    var driveRideRadio = document.getElementsByName('driveRidePref');
    for(var i=0; i <driveRideRadio.length; i++) {
        if (driveRideRadio[i].checked) {
            driveRidePref = driveRideRadio[i].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';
    }

    //get traffic trip choice 
    var get_traffic_trip = 'false';
    if (document.getElementById('traffic_trip_yes').checked == true){
	get_traffic_trip = 'true';
	driveRidePref = 'drivePrefer';
    }

    //get lucky
    var is_lucky = 'false';
    if (document.getElementsByName('lucky')[0].checked == true) {
        is_lucky = 'true';
    }
    
    // get time
    var planRideTime = document.getElementById('planNextRideTimeInput').value;
    if (!checkTime(document.getElementById('planNextRideTimeInput'),
                   planRideTime)) {
        return;
    }

    //get end time
    var planRideRangeEndTime = document.getElementById('rangeEndTimeInput').value;
    if(document.getElementById('rangeEndTimeInput').value!="") {
        if (!checkTime(document.getElementById('rangeEndTimeInput'),
                       planRideRangeEndTime)) {
            return;
        }
    }

    //get return time 
    var planReturnRideTime = document.getElementById('planReturnRideTimeInput').value;
    if(document.getElementById('planReturnRideTimeInput').value!="") {
        if(!checkTime(document.getElementById('planReturnRideTimeInput'),
                    planReturnRideTime)) {
                        return;
        }
    }

    //get return end time
    var planReturnEndTime = document.getElementById('planReturnEndTimeInput').value;
    if(document.getElementById('planReturnEndTimeInput').value!="") {
        if(!checkTime(document.getElementById('planReturnEndTimeInput'), planReturnEndTime)) {
            return;
        }
    }
        
    //get date
    if (document.getElementById('rawDate')) {
        var planRideDate = document.getElementById('rawDate').innerHTML;
    }
    
    //get am or pm
    var ampmPref = 0;
    if(document.getElementById('nextride_radio1').checked) {
        ampmPref = document.getElementById('nextride_radio1').value;
    } else if(document.getElementById('nextride_radio2').checked) {
        ampmPref = document.getElementById('nextride_radio2').value;
    }

    //get range end am or pm
    var rangeAMPMPref = 0;
    if(document.getElementById('rangeend_radio1').checked) {
        rangeAMPMPref = document.getElementById('rangeend_radio1').value;
    } else if(document.getElementById('rangeend_radio2').checked) {
        rangeAMPMPref = document.getElementById('rangeend_radio2').value;
    }

    //get return am or pm
    var returnAMPMPref = 0;
    if(document.getElementById('returnride_radio1').checked) {
        returnAMPMPref = document.getElementById('returnride_radio1').value;
    } else if(document.getElementById('returnride_radio2').checked) {
        returnAMPMPref = document.getElementById('returnride_radio2').value;
    }

    var returnEndAMPMPref = 0;
    if(document.getElementById('returnend_radio1').checked) {
        returnEndAMPMPref = document.getElementById('returnend_radio1').value;
    } else if(document.getElementById('returnend_radio2').checked) {
        returnEndAMPMPref = document.getElementById('returnend_radio2').value;
    }
    
    //get recurring days
    if (frequency == 'recurring') {
        var choices = document.getElementsByName('planNextRideRecurring');

        recurringPref="";

        for(var i=0; i<choices.length; i++) {
            if(choices[i].checked) {
                recurringPref+=choices[i].value;
            }
        }

        if (!recurringPref) {
            alert('please give one or more days as your recurring preference');
            return; 
        }

    }
    
    //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').innerHTML)) {
        alert('You must specify a date to continue.');
        return;
    } 

    if (ampmPref == 0) {
        alert('Please specify AM or PM');
        return;
    } 

    if (planRideRangeEndTime!='' && rangeAMPMPref==0) {
        alert('Please specify AM or PM for the end of time range');
        return;
    }

    if (planReturnRideTime!='' && returnAMPMPref==0) {
        alert('Please specify AM or PM for the return trip');
        return;
    }

    if(planReturnEndTime!='' && returnEndAMPMPref==0) {
        alert('Please sepcify AM or PM for the upto time of return trip');
        return;
    }   
    
    if (departPref == toPref) {
        alert('Your Depart and Arrive locations cannot be the same.');
        return;
    } 

    scheduleRideFrequency = frequency;
    scheduleRideTime = planRideTime;
    scheduleRangeEndTime = planRideRangeEndTime;
    scheduleRideDate = planRideDate;
    scheduleRideAMPM = ampmPref;
    scheduleRangeAMPM = rangeAMPMPref;
    scheduleRideOffset = null; //offsetPref;                    
    scheduleRideFrom = departPref;
    scheduleRideTo = toPref;
    scheduledriveRidePref = driveRidePref;
    scheduleRecurringPref = recurringPref;
    scheduleLuckyPref = is_lucky;
    scheduleReturnTime = planReturnRideTime;
    scheduleReturnAMPM = returnAMPMPref;
    scheduleReturnEndTime = planReturnEndTime;
    scheduleReturnEndAMPM = returnEndAMPMPref;

    scheduleTrafficTrip = get_traffic_trip;    

    post_newride();

}

<!-- 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 endAddress;
var startAddressReply;
var endAddressReply;

var flagSt = false;

function checkLocations(stlat, stlng, endlat, endlng) {
    flagSt = false;
    if (document.getElementById('mapStartAddress')) {
        geocoder = new GClientGeocoder();
        startAddress = document.getElementById('mapStartAddress').innerHTML;
	if(stlat == null)
	    geocoder.getLocations(startAddress,checkStart);
	else{
	    geocoder.getLocations(new GLatLng(stlat,stlng), checkStart);
	    //document.getElementById("generateMapError").innerHTML = "";
	    //flagSt = false;
	    //startAddressLatLng = stlng +","+ stlat;
	}
	if(!flagSt){
	    endAddress = document.getElementById('mapEndAddress').innerHTML;
	    if(endlat == null)
		geocoder.getLocations(endAddress,checkEnd);
	    else{
		geocoder.getLocations(new GLatLng(endlat,endlng), checkEnd);
		//document.getElementById("generateMapError").innerHTML = "";
		//flagSt = false;
		
		//endAddressLatLng = endlng +","+ endlat;
		//initialize();
	    }
	}
    }
                

}

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;
        var place = response.Placemark[0];
        startAddressLatLng = place.Point.coordinates[1]+","+place.Point.coordinates[0];
    }
    if (startAddressReply >= 6) {
        //endAddress = document.getElementById('mapEndAddress').innerHTML;
        //geocoder.getLocations(endAddress,checkEnd);
    } else {
	flagSt = true;
        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 >= 6) {
        var place = response.Placemark[0];
        endAddressLatLng = place.Point.coordinates[1]+","+place.Point.coordinates[0];
        initialize();
    } else {
	flagSt = true;
        document.getElementById("generateMapError").innerHTML = "The ending address must be more precise."
            }
}
    
function initialize() {
    if (GBrowserIsCompatible()) {    
       
        map = new GMap2(document.getElementById("route_map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "error", handleErrors);
        setDirections(startAddressLatLng, endAddressLatLng, "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.";
       
}   

function checkTime(field, time) {
    timeRegex = /^(\d{1,2})[:\.](\d\d)$/;
    if (!time.match(timeRegex)) {
        timeRegex = /^(\d{1,2})$/;
        if(!time.match(timeRegex)) {
            alert('Please enter a valid 12 hour time. eg 9:00');
            field.focus();
            return false;
        }
    }
    // split time field into hour and min and check validity of each 
    var timeSplit = null;
    if(time.indexOf(':')!=-1) {
        timeSplit = time.split(':');
    } else if(time.indexOf('.')!=-1){
        timeSplit = time.split('.');
    }
    if(timeSplit) {
        if ((timeSplit[0] < 1 || timeSplit[0] > 12) ||
            (timeSplit[1] < 0 || timeSplit[1] > 59)) {
            alert('Please enter a valid 12 hour time. eg 9:00 or 9.00 or 9');
            field.focus();
            return false;
        }
    } else if(time[0] < 1 || time[0] > 12) {
            alert('Please enter a valid 12 hour time. eg 9:00 or 9.00 or 9');
            field.focus();
            return false;
    }
    return true;
}



function init_wizard() {
    wizard = new Object();
    wizard.previous_slide = null;
    wizard.current_slide = document.getElementById("addresses");

    wizard.showDriveRide = null;

    wizard.trafficDataRide = function(trafficRadio){
	wizard.showDriveRide = trafficRadio;
    }

    wizard.changeSlide = function(new_slide_name) {
        wizard.current_slide.style.display = "none";
        wizard.current_slide = document.getElementById(new_slide_name);
        wizard.current_slide.style.display = "block";
    }
    wizard.nextSlide = function(slidename, checkfunction, form) {
        if ((wizard.showDriveRide == null) & (slidename == "rideordrive")){
		alert("Please choose an option for the traffic data");
		return;
	}
	var is_ok = true;
        if(checkfunction!=null) {
            is_ok = checkfunction(form);
        }
        if (is_ok==true) {
		if ((wizard.showDriveRide == "yes") & (slidename == "rideordrive")){
			if (checkfunction != null){
				slidename = "date_recurrence";
			}
			else{
				slidename = "addresses";
			}
		}
            wizard.changeSlide(slidename);
        }
    } 

    wizard.check_address = function(form) {
        //get arrival and departure destinations
        var selIndexDepart = document.getElementById('planNextLocationsSelectDD').selectedIndex;
        if(selIndexDepart==-1) {
            alert('please specify a from address');
            return false;
        }
        var departPref = document.getElementById('planNextLocationsSelectDD').options[selIndexDepart].value;
            
        var selIndexTo = document.getElementById('planNextLocationsSelectDD2').selectedIndex;
        if(selIndexTo==-1) {
            alert('please specify a to address');
            return false;
        }
        var toPref = document.getElementById('planNextLocationsSelectDD2').options[selIndexTo].value;

        if(!departPref || !toPref) {
            alert('from and to addresses cannot be empty');
            return false;
        }

        if(departPref==toPref) {
            alert('from and to locations cannot be the same');
            return false;
        }

        scheduleRideFrom = departPref;
        scheduleRideTo = toPref;

        postPage('checkMapLocations');

        return true;
    }

    wizard.check_date_recurrence = function(form) {
        if (document.getElementById('frequencySingle').checked == true) {
            var frequency = 'single';
        } else if (document.getElementById('frequencyRecurring').checked == true) {
            var frequency = 'recurring';
        }

        if (frequency == 'recurring') {
            var choices = document.getElementsByName('planNextRideRecurring');

            recurringPref="";

            for(var i=0; i<choices.length; i++) {
                if(choices[i].checked) {
                    recurringPref+=choices[i].value;
                }
            }

            if (!recurringPref) {
                alert('please give one or more days as your recurring preference');
                return false; 
            }

        }
        
        if (frequency == 'single' && !(document.getElementById('rawDate').innerHTML)) {
            alert('You must specify a date to continue.');
            return false;
        } 

        return true;
    
    }

    wizard.showRecurring = function() {
        var recurringOptions = document.getElementById('recurringOptions');
        recurringOptions.style.display = 'block';
        var planRideDateType = document.getElementById('planRideDateType');
        planRideDateType.innerHTML = 'Repeat this trip up to:';
        var recurRideMessage = document.getElementById('recurRideMessage');
        recurRideMessage.style.display = 'block';

    }

    wizard.hideRecurring = function() {

        var recurringOptions = document.getElementById('recurringOptions');
        recurringOptions.style.display = 'none';
        var planRideDateType = document.getElementById('planRideDateType');
        planRideDateType.innerHTML = 'Date:';
        var recurRideMessage = document.getElementById('recurRideMessage');
        recurRideMessage.style.display = 'none';

    }
}

function toggleDisplay(elem_id) {
    console.log('hi');
    console.log(elem_id);
    var elem = document.getElementById(elem_id);
    console.log(elem);
    console.log(elem.style);

    console.log(elem.style.display);

    if (elem.style.display == "none" || elem.style.display=="") {
        elem.style.display = "block";
    }
    else {
        elem.style.display = "none";
    }
}


function toggleIncludeConfirmed() {
    var radio = document.getElementById('recurring_trips');
    var checkbox = document.getElementById('include_confirmed');

    if (!checkbox)
        return;

    if (radio.checked) {
        checkbox.disabled = false; 
    } else {
        checkbox.disabled = true; 
    }
}

function disableMinutes(){
	var traffic_data_mins = document.getElementById('traffic_data_mins');
	var selSendTrafficData = document.getElementById('sendTrafficData').selectedIndex;	
	var oSendTrafficData = document.getElementById('sendTrafficData').options[selSendTrafficData].value;
	if (oSendTrafficData == 'no'){
		traffic_data_mins.disabled = true;
	}
	else{
		traffic_data_mins.disabled = false;
	}
}
