var stpnumber=1;
var parent_id='step_1';
var msg=[];
var errors=[];
var hastried;
var maxCost = 200;
var clearErrors = true;

// State for managing timing of geocoding and step proceeding
// geocodingStatus can equal:
//  - not_found
//  - geocoding
//  - found
var geocodingStatusStart = "not_found";
var geocodingStatusEnd = "not_found";
var addRideCounter = 0;
var editRideCounter = 0;

var markerPoints = [];
var map = null;
var offset;
function stickyMap(){
	if(offset && $(window).scrollTop()>offset.top-20){
		$('#column_right').addClass('mapfixed');
	}
	else{
		$('#column_right').removeClass('mapfixed');
	}
}
$(window).load(function(){
    offset=$('#column_right').offset();
})
$(document).ready(function(){
    $(window).scroll(stickyMap);
    $('.triptabs, #actionbar_addride').hide();
    $('#s').locationinput('s', userLocations, {
            onLocationFound: function(latitude, longitude) {
                updateMap('s', latitude, longitude);
                geocodingStatusStart = "found";
                validateStep();
            },
			onEmpty: function() {
        	    clearMap('s');
        	    geocodingStatusStart = "not_found";
                validateStep();
			},
			onError: function() {
        	    clearMap('s');
        	    geocodingStatusStart = "not_found";
                validateStep();
			},
			onFieldChange: function() {
			    geocodingStatusStart = "geocoding";
			},
            loc_values: start_locations,
            autocompleteOptions: { width: $('#s').width() + parseInt($('#s').css("padding-right"))  + parseInt($('#s').css("padding-left")) },
            textBlack: true
    }).focus(function() {
			// simulate a keydown event
			var e = jQuery.Event('keydown'); e.keyCode = 40; $(this).trigger(e);
	});

    $('#e').locationinput('e', userLocations, {
            onLocationFound: function(latitude, longitude) {
                updateMap('e', latitude, longitude);
                geocodingStatusEnd = "found";
                validateStep();
            },
			onEmpty: function() {
        	    clearMap('e');
        	    geocodingStatusEnd = "not_found";
                validateStep();
			},
			onError: function() {
        	    clearMap('e');
        	    geocodingStatusEnd = "not_found";
                validateStep();
			},
			onFieldChange: function() {
			    geocodingStatusEnd = "geocoding";
			},
            loc_values: end_locations,
            autocompleteOptions: { width: $('#e').width() + parseInt($('#e').css("padding-right"))  + parseInt($('#e').css("padding-left")) },
            textBlack: true
    }).focus(function() {
			// simulate a keydown event
			var e = jQuery.Event('keydown'); e.keyCode = 40; $(this).trigger(e);
	});
        
    /* If the departure date is changed to after the return date, set the
       return date equal to the depatrue date */
    $('#depart-date').change( function() {
        startDate = $('#depart-date').attr('value');
        startDate = startDate.substr( 6 ) + '/' + startDate.substr( 0, 5 );
        endDate = $('#return-date').attr('value');
        endDate = endDate.substr( 6 ) + '/' + endDate.substr( 0, 5 );

        if ( startDate > endDate )
            $('#return-date').attr('value', $('#depart-date').attr('value') );
        
    });

    /* If the return date is changed to before the start date, then set the
       departure date equal to the return date */
	$('#return-date').change(function(){
		startDate = $('#depart-date').val();
		startDate = startDate.substr(6) + '/' + startDate.substr(0, 5);
		endDate = $(this).val();
		endDate = endDate.substr(6) + '/' + endDate.substr(0, 5);            

		if (startDate > endDate) {
			$('#depart-date').val($(this).val());
		}
	});

    $('#form_submit').click(function() {
        var validRide = validatedRide();
        if ( !validRide ) {
            $('#notes').blur();
            return false;
        }
        return true;
    });

    if ( google.setOnLoadCallback ) {
    	google.setOnLoadCallback(initialize);
	}
    
    $('#back').click(function() {
            toggleReturnTrip();
    });
    
    // Enable/Disable trusted partners checkbox
    $('#post_to_platform_public').click(function() {
            // Enabled -> Disabled
            $('#include_trusted_partners').attr('disabled', 'disabled');
            $('#include_trusted_partners').removeAttr('checked');
    });
    $('#post_to_platform_private').click(function() {
            // Enabled -> Disabled
            $('#include_trusted_partners').removeAttr('disabled');
    });
    
    //************ Events code *************//
    $('#event').change(function() {
        setEventLocation($(this).val());
    });

});


// Call this function when the page has been loaded
function initialize() {

    if ($('#map').length > 0) {
        map = new google.maps.Map(document.getElementById("map"), {scrollwheel:false, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl: false, center:new google.maps.LatLng(defaultLocation.lat, defaultLocation.lng), zoom:13});
        
        if ($("#add_ride input[name='s_lat']").val() && $("#add_ride input[name='s_lng']").val()) {
            updateMap('s', $("#add_ride input[name='s_lat']").val(), $("#add_ride input[name='s_lng']").val());
        }
        
        if ($("#add_ride input[name='e_lat']").val() && $("#add_ride input[name='e_lng']").val()) {
            updateMap('e', $("#add_ride input[name='e_lat']").val(), $("#add_ride input[name='e_lng']").val());
        }
        
        if (events.length > 0) {
            if ( typeof eventID != 'undefined' )
                setEventLocation(eventID);
            else
                setEventLocation(events[0].id);
        }
   }

    $('.bigradio, .medradio').click(function(e){
		var id=$(this).attr('id');
		$(this).find('input').attr('checked','checked');
		switch(id) {
			case 'driverselect': {
				$('.seats-visibility').show();
				$('label[for="cost"]').html('How much do you want each passenger to contribute?');
			}
			break;
			case 'passengerselect': {
				$('.seats-visibility').hide();
				$('label[for="cost"]').html('How much are you willing to contribute?');
			}
			break;
			case 'regcommute': {
				$('.triptabs').show();
				$('.medradio').css({'opacity':0.7,'margin-bottom':0});
				$(this).css('opacity',1);
				$('#there_repeating, #back_repeating, #repeating_cost_frequency, #price-per').show();
				$('label[for="depart-date"], label[for="return-date"], #there_one_time, #back, #back_one_time, #one_time_cost_frequency, #singletripwrapper').hide();
				$('#caret').animate({'padding-left':'158px'},150);
				$('label[for="advanced"]').removeClass('invisible');
				$('#price-per').html('per day');
                prepopulateCost();
			}
			break;
			case 'singletrip': {
				$('.triptabs').show();
				$('.medradio').css({'opacity':0.7,'margin-bottom':0});
				$(this).css('opacity',1);
				$('#caret').animate({'padding-left':'445px'},150);
				$('#there_repeating, #back_repeating, #repeating_cost_frequency').hide();
				$('label[for="depart-date"], label[for="return-date"], #there_one_time, #back, #back_one_time, #one_time_cost_frequency, #singletripwrapper, #price-per').show();
				$('label[for="advanced"]').addClass('invisible');
                $('#price-per').html('each way');
                if ($('#back').not(':checked').length) {
                    $('#price-per').hide();
                }
                prepopulateCost();
			}
			break;
		}
	});

	$('form#add_ride button[type="button"]').click( validateAndNextStep );
	
	$('form#add_ride a.back, .bigradio, .medradio, #commute-table input[type=checkbox]').click( validateStep );
	
	$('#commute-table select[name^="there_time_"], #commute-table select[name^="back_time_"]').change( validateStep );
	
	$('#s, #e').change( validateStep );
	
	$('form#add_ride a.back').click(function(){
		var parent = $(this).closest('fieldset');
		parent.hide();
		parent.prev().fadeIn();
		stpnumber--;
		$('.step_container').css('background','url("/assets/step'+stpnumber+'.png") bottom center no-repeat');
		parent_id = parent.prev().attr('id');
	});

    if (preselect_driver_passenger == 'need') {
        $('#needid').click();
    }
    else if (preselect_driver_passenger == 'either') {
        $('#offerid').click();
    }
    if (preselect_ride_type) {
        if (preselect_ride_type == 'one-time') {
            $('#singletrip').click();
        } else if (preselect_ride_type == 'repeating') {
            $('#regcommute').click();
        }
    }

    if(onetime_only) {
        $('.triptabs').show();
        $('#there_repeating, #back_repeating, #repeating_cost_frequency').hide();
        $('label[for="depart-date"], label[for="return-date"], #there_one_time, #back, #back_one_time, #one_time_cost_frequency, #singletripwrapper').show();
        $('label[for="advanced"]').addClass('invisible');
        $('#price-per').html('each way');
    }

	
	$('#flex .pillbuttons div').click(function(){
		$('#flex .pillbuttons div').removeClass('chosen');
		$(this).addClass('chosen');
        $('#flex_global').val($(this).text());
	});
	$('form#add_ride .edit').click(function(){
		num=$(this).parents('li').prevAll().length;
		selectors=$('#commute-table ul:eq(1) li:eq('+num+') select, #commute-table ul:eq(2) li:eq('+num+') select');
		if(!$(selectors).hasClass('hidden')){
			$(this).html('edit').css('opacity','');
			$(selectors).addClass('hidden').parent().find('p').removeClass('hidden');
            $('select[name^="there_time_"]:hidden').val($('#there_time_0').val());
            $('select[name^="back_time_"]:hidden').val($('#back_time_0').val());
		}
		else {
			$(this).html('revert').css('opacity',0.6);
			$(selectors).removeClass('hidden').parent().find('p').addClass('hidden');
		}
	});
	
	function toggleDaysOfWeek(){
		$('#commute-table input[type="checkbox"]').each(function(){
			check=$(this).attr('checked');
			num=$(this).parents('li').prevAll().length;
			row=$('#commute-table ul:eq(1) li:eq('+num+'), #commute-table ul:eq(2) li:eq('+num+'), #commute-table ul:eq(3) li:eq('+num+')');
			if(check==false){
				$(row).find('p').css('color','#bbb');
				$(row).find('a').css('visibility','hidden');
				$(row).find('select').attr('disabled','disabled');
			}
			else{
				$(row).find('p').css('color','');
				$(row).find('a').css('visibility','visible');
				$(row).find('select').removeAttr('disabled');
			}
		});
	};
	toggleDaysOfWeek();
	$('#commute-table input[type="checkbox"]').click(toggleDaysOfWeek);
	
	$('#there_time_0').change(function(){
		timeval=$(this).val();
		$('.time-alias1').html(timeval);
        $('select[name^="there_time_"]:hidden').val(timeval);
        prepopulateCost();
	});
	$('#back_time_0').change(function(){
		timeval=$(this).val();
		$('.time-alias2').html(timeval);
        $('select[name^="back_time_"]:hidden').val(timeval);
        prepopulateCost();
	});
	
	$('form#add_ride .input-arrows:eq(0) a').click(function(){
		input=$(this).parents('dd').find('input');
		val=$(input).val();
		i=1;
		if(val==''){val='0'};
		if($(this).prevAll().length==1){
			val=(parseFloat(val)-i);
		}
		else{
			val=(parseFloat(val)+i);
		}
		if(val<1){val='0'};
		$(input).val(val);
	});
	
	$('form#add_ride .input-arrows:eq(1) a').click(function(){
		input=$(this).parents('dd').find('input');
		val=$(input).val();
		if($(this).prevAll().length==1){
			val--;
		}
		else{
			val++;
		}
		if(val<1){val=1};
		$(input).val(val);
	});

    $('#seats, #cost').keyup( function() {
        var val = $(this).val();
        var newVal = val.replace( /[^0-9]/g, '');
        if (val != newVal) {
            $(this).val( newVal );
        }
    });

    $('#cost').blur( function() {
        var val = $(this).val();
        if (!val || parseInt(val) < 0) {
            $(this).val('0');
        }
    });

    $('#seats').blur( function() {
        var val = $(this).val();
        if (!val || parseInt(val) < 1) {
            $(this).val('1');
        }
    });
    
    toggleReturnTrip();
}

function clearMap(prefix) {
    markerPoints[prefix].setVisible(false);
    
    updateBounds();
}

function updateMap(prefix, lat, lng) {
    if (map) {
        var lat = parseFloat(lat);
        var lng = parseFloat(lng);
        
        if (markerPoints[prefix] == null) {
            if (prefix == 's') {
                var iconImage = 'http://www.google.com/mapfiles/dd-start.png';
            } else {
                var iconImage = 'http://www.google.com/mapfiles/dd-end.png';
            }
            markerPoints[prefix] = new google.maps.Marker({icon:iconImage, position: new google.maps.LatLng(lat, lng), map:map});
        } else {
            markerPoints[prefix].setPosition(new google.maps.LatLng(lat, lng));
        }
        markerPoints[prefix].setVisible(true);
    }
    
    updateBounds();
    prepopulateCost();
}

function updateBounds() {
    var bounds = new google.maps.LatLngBounds();
    
    if (markerPoints['s'] != null && markerPoints['s'].getVisible()) {
        bounds.extend(markerPoints['s'].getPosition());
    }
    
    if (markerPoints['e'] != null && markerPoints['e'].getVisible()) {
        bounds.extend(markerPoints['e'].getPosition());
    }
    
    if ((markerPoints['e'] == null || !markerPoints['e'].getVisible()) && (markerPoints['s'] == null || !markerPoints['s'].getVisible())) {
        // dont have either point now
        map.setCenter(new google.maps.LatLng(defaultLocation.lat, defaultLocation.lng));
        map.setZoom(13);
    } else if (markerPoints['e'] != null && markerPoints['e'].getVisible() && markerPoints['s'] != null && markerPoints['s'].getVisible()) {
        // have both points
        map.fitBounds(bounds);
    } else {
        // only have one
        map.setCenter(bounds.getCenter());
        if ( events.length > 0 && (markerPoints['s'] == null || markerPoints['e'] == null) ) {
            map.setZoom(9);
        }
        else {
            map.setZoom(13);
        }
    }
}

function toggleReturnTrip() {
	$returnDate = $('#return-date');
	$returnDateCalendar = $('#end_calendar img');
	$backTime = $('#back_time');
	$backFlex = $('#back_flex');

	if ($('#back').attr('checked')) {
		// Disabled -> Enabled
		$returnDate.removeClass('disabled').removeAttr('disabled');
		$returnDateCalendar.removeClass('disabled');
		$backTime.removeAttr('disabled');
		$backFlex.removeAttr('disabled');
		$('label[for=return-date]').fadeTo(0,1);
        $('#price-per').show();
	} else {
		// Enabled -> Disabled
		$returnDate.addClass('disabled').attr('disabled', 'disabled');
		$returnDateCalendar.addClass('disabled');
		$backTime.attr('disabled', 'disabled');
		$backFlex.attr('disabled', 'disabled');
		$('label[for=return-date]').fadeTo(0,0.5);
        $('#price-per').hide();
	}
}

function disableTimeFlex(id, trip, element){
    var fields = $("#" + trip + "_time_" + id + "," + "#" + trip + "_flex_" + id);
    if ($(element).is(":checked")) {
        fields.removeAttr("disabled");
    } else {
        fields.attr("disabled", true);
    }
}

function setFlexCheckboxes() {
	$(':checkbox[id^="there"],:checkbox[id^="back"]').each(function() {
        var parts = $(this).attr('id').split('_');

		disableTimeFlex(parts[1], parts[0], $(this));

		if (0 == $('#advanced').val() && $(this).is(':checked')) {
			$('#' + parts[0] + '_time_1' + ',' + '#' + parts[0] + '_flex_1').removeAttr('disabled');
		}
	});
}

function setEventLocation(eventId) {
    var lat;
    var lng;
    for(var i=0; i<events.length; i++) {
        if ( events[i].id == eventId) {
            lat = events[i].lat;
            lng = events[i].lng;
            $('#add_ride input[name="e_location_key"]').val(events[i].location);
            $('#event_id').val(events[i].id);
            //$('#event_title').val(events[i].name);
            $('#event_url').val(events[i].show_url);

			if ( events[i].location_only == 0 ) {
            	$('#depart-date').val(events[i].date);
            	$('#there_time').val(events[i].time);
            	$('#return-date').val(events[i].returnDate);
            	$('#back_time').val(events[i].returnTime);
			}

        }
    }
    updateMap('e', lat, lng);
}

function processRepeatingRide(direction) {
	var days = '';
	for (var i=1; i<=7; i++) {
		key = direction + '_' + i;
		if ( $('#' + key).attr('checked') ) {
			if ( days != '' ) {
				days += ',';
			}
			days += i;
		}
	}
	return days;
}

function validateStep() { 

    if ( clearErrors ) {
        msg = [];
        errors = [];
    }
    
	switch(parent_id){
		case 'step_1':
		    
		    //check if geocoding and return false if still geocoding
            if ((geocodingStatusStart == "geocoding") || (geocodingStatusEnd == "geocoding")) {
                // Timing for add ride screen
                // We are still geocoding at least one of the addresses.
                // Try again in a little bit.
                if (addRideCounter > 10) {
                    // jumpstart geocoding to prevent infinite loop due to timing mess up
                    geocodingStatusStart = "not_found";
                    geocodingStatusEnd = "not_found";
                    $('#s').change();
                    $('#e').change();
                    addRideCounter = 0;
                } else {
                    addRideCounter++;
                }
                return false;
            }
		    
			if ( !$('input[name=who]:checked').val() ) {
				errors.push('driverselect');
				errors.push('passengerselect');
				msg.push('Hold on! Are you a driver or a passenger?');
			}
			
			if ( $('#driverselect').find('input').is(':checked') ) {
				$('.seats-visibility').show();
				$('label[for="cost"]').html('How much do you want each passenger to contribute?');
			}
			else if ( $('#passengerselect').find('input').is(':checked') ) {
				$('.seats-visibility').hide();
				$('label[for="cost"]').html('How much are you willing to contribute?');
			}

			if (!$('#add_ride input[name="s_lat"]').val() && !$('#add_ride input[name="s_location_key"]').val()) {
				errors.push('s');
				msg.push('Oops! We couldn&rsquo;t find your starting location.');
			}

            if (!$('#add_ride input[name="e_lat"]').val() && !$('#add_ride input[name="e_location_key"]').val()) {
				errors.push('e');
				msg.push('Oops! We couldn&rsquo;t find your ending location.');
			}

            if ($('#s').val() == $('#e').val() ) {
			    errors.push('s');
				errors.push('e');
				msg.push('Oops! Your starting and ending locations are the same.');
			}
			
		break;
		
		case 'step_2':
			
			if ( !$('.medradio input:checked').val() && !$('#onetime-only').val()) {
				errors.push('singletrip');
				errors.push('regcommute');
				msg.push('Hold on! Choose your trip type first.');
			}

            if (!$('#commute-table input[type=checkbox]:checked').val() && !$('#singletrip input:checked').val()) {
                errors.push('there_1');
				msg.push('Oops! You gotta pick least one day of the week for a commute.');
			}

            if ($('#regcommute input:checked').val()) {
            // it's a commute, loop through commute days
                var thereOK = false;
                for(var day=1; day<=7; day++) {
                    // already handled no day selected, so only have to worry if no commute on a day that's been selected
                    if($('input[name="there_'+day+'"]:checked').val() && $('select[name="there_time_'+day+'"]').val() == 'No Trip' && $('select[name="back_time_'+day+'"]').val() == 'No Trip') {
                        msg.push("Oops! You can't have 'No Trip' for both depart and return times.");
                    }
                    if($('input[name="there_'+day+'"]:checked').val() && $('select[name="there_time_'+day+'"]').val() != 'No Trip') {
                        thereOK = true;
                    }
                }
                
                if (!thereOK) {
                    errors.push('there_time_1');
                    msg.push("Oops! You really need to have at least one departure time!");
                }
            }
            
            // If it's a one-time trip, make sure they have selected valid dates
            if ( $('#singletrip input:checked').val() || $('#onetime-only').val()) {
                if ( !isValidDate($('#depart-date').val()) ) {
                    errors.push('depart-date');
                    msg.push("Oops! You've entered an invalid date\n. Try using the calendar to help you!"); 
                }
                
                if ( $('#back').attr('checked')  && !isValidDate($('#return-date').val()) ) {
                    errors.push('return-date');
                    msg.push("Oops! You've entered an invalid date\n. Try using the calendar to help you!"); 
                }
            }
            
		break;
		
		case 'step_3':
		    
            if ($('#cost').val() > maxCost) {
                errors.push('cost');
                msg.push("That's a lotta money! Zimride only supports trips up to $" + maxCost);
                return false;
            }
		                
            if ( $('input[name="post_to_platform"][type="radio"]').length > 0 && $('input[name="post_to_platform"][type="radio"]:checked').length == 0 ) {
                errors.push('post_to_platform_choices');
                msg.push('Oops! You need to select a privacy option!');
                return false;
            }
		    
		break;
	}
	checkStepAbility();
	return true;
	
}

function isValidDate( date ) {
    // Check to make sure that the slashes are in the correct spot and that
    // the length of the string is correct
    if ( date.length != 10 || date.charAt(2) != '/' || date.charAt(5) != '/') {
        return false;
    }
    
    // Have javascript parse the date
    var userDate = Date.parse(date);
    
    // If ther parsing failed, return false
    if ( !userDate ) {
        return false;
    }

    // Get the current time    
    var now = new Date();
    now = now.getTime();
    // subtract a day to ensure that the user is allowed to post rides
    // with the current date
    now -=  86400000;
    
    // Check to make sure that they are not posting a ride in the past
    if ( now > userDate ) {
        return false;
    }
    
    return true;
}


function submitRideForm() {
    $('#form-addride-button').click();
}

function validatedRide() {
    
    // Timing mainly for edit ride screen
    // make sure that we aren't still geocoding one of the addresses
    if (geocodingStatusStart == "geocoding" || geocodingStatusEnd == "geocoding") {
        // We are still geocoding atleast one of the addresses.
        // Try again in a little bit.
        if (editRideCounter > 10) {
            // jumpstart geocoding to prevent infinite loop due to timing mess up
            geocodingStatusStart = "not_found";
            geocodingStatusEnd = "not_found";
            $('#s').change();
            $('#e').change();
            editRideCounter = 0;
        } else {
            editRideCounter++;
        }
        setTimeout("submitRideForm()", 200);
        return false;
    }
    
    // On the edit ride page, we must validate all three steps at this point
    if ( isEditRide ) {
        // B/c we're on ride edit page, we'll be on step_1
        validateStep();
        
        // Don't overwrite errors in step_1 when checking for errors in step_2 or step_3
        clearErrors = false;
        
        parent_id = 'step_2';
        validateStep();
        
        parent_id = 'step_3';
    }
    
    // This should validate the 3rd step on both the add ride and edit ride pages
    validateStep();
    
    if(msg.length){
        $('.errormsg').fadeTo(0,1).html(msg[0]);
        $('.errormsg').delay(1300).fadeTo(1000,0.5);
        hastried=true;
        $.each(errors,function(i,e){
            $('#'+e+'').addClass('errored');
        })
        // If we were on the edit ride page, set the step back to step_1
        if ( isEditRide )
            parent_id = 'step_1';

        // We'll need to clear errors the next time they hit submit        
        clearErrors = true;
        
        // Prevent the submit from going through
        return false;
    }
    
    return true;
}

function checkStepAbility() {
	//clear previous errors
	$('.errormsg').fadeTo(0,0);
	$('.errormsg').html('');
	$('.errored').removeClass('errored');
	if(hastried==true){
		$.each(errors,function(i,e){
			$('#'+e).addClass('errored');
		});
        $('.errormsg').fadeTo(0,0.5).html(msg[0]);
	};
}

function validateAndNextStep() {
    if(validateStep()) {
        nextStep(this);
    } else {
        setTimeout('validateAndNextStep()', 100);
    }
}

// step 1 -> 2 -> 3 ... back or Next Step
function nextStep(ele) {
    
	if(msg.length){
		$('.errormsg').fadeTo(0,1).html(msg[0]);
		$('.errormsg').delay(1300).fadeTo(1000,0.5);
		hastried=true;
		$.each(errors,function(i,e){
			$('#'+e+'').addClass('errored');
		})
	}
	else{
        
   		var parent = $(ele).closest('fieldset');
        stpnumber++;
        $('.step_container').css('background','url("/assets/step'+stpnumber+'.png") bottom center no-repeat');
        parent.hide();
        parent.next().hide();
        parent.next().removeClass('hidden');
        parent.next().fadeIn();
        parent_id = parent.next().attr('id');
        hastried=false;
        validateStep();
        
        if ( parent_id == 'step_3' )
            $('#notes').blur();
	}
}

function prepopulateCost() {
    if (markerPoints['s'] != null && markerPoints['e'] != null) {
        var start = markerPoints['s'].getPosition();
        var end = markerPoints['e'].getPosition();
        var distance = calculateLatLongDistance(
            start.lat(),
            start.lng(),
            end.lat(),
            end.lng()
        );

        var val, price;
        
        if($('input[name="type"]:checked').val() == 'repeating') {
            price = distance < 100 ? Math.max(2, 0.18 * distance) : 0.1 * distance + 7; 
            val = Math.round(price);
            if ($('#back_time_0').val() != 'No Trip' && $('#there_time_0').val() != 'No Trip') {
                val *= 2;
            }
        } else {   
            price = distance < 100 ? Math.max(5, 0.18 * distance) : 0.1 * distance + 7; 
            val = Math.round(price / 5.00) * 5;
        }
        
        if ( val > maxCost ) {
            val = maxCost;
            $('#suggested_price_text').text('is the maximum price Zimride allows for a ride');
        } else {
            $('#suggested_price_text').text('based on the Zimride average for this trip');
        }
        
        if (!$('#saved_cost').val()) {
            $('#cost').val(val);
        }
        $('#suggested_price').text(val.toFixed(2));
    }
}

