var locationSetByAutocomplete;
var markerPoints = [];
var map = null;
var v_lat = null;
var v_lng = null;
var prefix = null;
var loc_start = null;
var loc_start_lat = null;
var loc_start_lng = null;
var loc_end = null;
var loc_end_lat = null;
var loc_end_lng = null;

// Page manipulation
$(document).ready(
	function() {
	    
		// Picking "one-time" or "repeating"
		$('#add-ride-form #type-select').change(
			function() {
				if ($(this).val() == 'repeating') {
					$('#add-ride-form #depart-date').hide();
					$('#add-ride-form #return-date').hide();
					$('#add-ride-form #depart-days').fadeIn();
					$('#add-ride-form #return-days').fadeIn();
				} else {
					$('#add-ride-form #depart-days').hide();
					$('#add-ride-form #return-days').hide();
					$('#add-ride-form #depart-date').fadeIn();
					$('#add-ride-form #return-date').fadeIn();
				}
			}
		);
        	
        $('#wall_text').focus( function() {
            clear_generic(this,'Comment on this ride...');
            $('#wall_post_submit_button').css({display:'block'});
        });
        
        $('#wall_text').blur( function() {
            unclear_generic(this, 'Comment on this ride...');
        });
        
        $('#wall_post_submit_button').click(function() {
                if ($('#wall_text').val() == '' || $('#wall_text').val() == 'Comment on this ride...') {
                    return false;
                }
        });
        
        $('#networks').click(
			function() {
                    if ($('#networks').val() != '0') {
                        window.location.href = $('#networks').val();
                    }
				}
		);

        /** Search Bar Functions */
        $('#search_s').locationinput('s', userLocations, {
            autocompleteOptions: { max: 3, width: $('#search_s').width() + parseInt($('#search_s').css("padding-right"))  + parseInt($('#search_s').css("padding-left")) },
            textBlack: true
		});

        $('#search_e').locationinput('e', userLocations, {
			autocompleteOptions: { max: 3, width: $('#search_s').width() + parseInt($('#search_s').css("padding-right"))  + parseInt($('#search_s').css("padding-left")) },
			textBlack: true
		});
        
        $('.clickaway').focus(function(){
            if ($(this).val() == $(this).attr('placeholder')) {
                $(this).val('');
            }
            $(this).css('color','#111111');

			// simulate a keydown event
			var e = jQuery.Event('keydown');
			e.keyCode = 40;
			$(this).trigger(e);
        });

        $('.clickaway').blur(function(){
            if (0 == $(this).val().length) {
                $(this).val($(this).attr('placeholder')).css('color','#999999');
            }
        });

        $('.clickaway_confirm').click(function(){
            $(this).parents('form:first').find('.clickaway').each(function(){
                if ($(this).val() == $(this).attr('placeholder')) {
                    $(this).val('');
                }
            });
        });

		/* User homepage actions */
		$('.feedback .input_text').focus(function(){
			if ($(this).val() == $(this).attr('placeholder')) {
				$(this).val('');
			}
			$(this).css('color','#111111');
		});

		$('.feedback .input_text').blur(function(){
			if (0 == $(this).val().length) {
				$(this).val($(this).attr('placeholder')).css('color','#999999');
			}
		});

		$('.feedback button').click(function(){
			$('.feedback .input_text').each(function(){
				if ($(this).val() == $(this).attr('placeholder')) {
					$(this).val('');
				}
			});
		});
	}
);

$(window).load(
	function() {
		var options = {
			keysClose: ['c', 27]
		};
	}
);

function callback_rideSearchStart(response) {
	if (response.Status.code == G_GEO_SUCCESS) {
		var place = response.Placemark[0];
		loc_start_lat = place.Point.coordinates[1];
		loc_start_lng = place.Point.coordinates[0];

		loc_start = place.address;

		var marker = new google.maps.Marker(new google.maps.LatLng(loc_start_lat, loc_start_lng));
		map.addOverlay(marker);
		map.setCenter(new google.maps.LatLng(loc_start_lat, loc_start_lng), 8);

		if (loc_start && loc_end) {
			map.clearOverlays();
			directions = new google.maps.Directions(map);
			directions.load(loc_start + ' to ' + loc_end);
		}
	} else {
		loc_start = null;
		loc_start_lat = null;
		loc_start_lng = null;
	}
}

function callback_rideSearchEnd(response) {
	if (response.Status.code == G_GEO_SUCCESS) {
		var place = response.Placemark[0];
		loc_end_lat = place.Point.coordinates[1];
		loc_end_lng = place.Point.coordinates[0];

		loc_end = place.address;

		var marker = new google.maps.Marker(new google.maps.LatLng(loc_end_lat, loc_end_lng));
		map.addOverlay(marker);
		map.setCenter(new google.maps.LatLng(loc_end_lat, loc_end_lng), 8);

		if (loc_start && loc_end) {
			map.clearOverlays();
			directions = new google.maps.Directions(map);
			directions.load(loc_start + ' to ' + loc_end);
		}
	} else {
		loc_end = null;
		loc_end_lat = null;
		loc_end_lng = null;
	}
}

// Clear all hidden fields for a location
function clear_locations(prefix) {
            // Clear all hidden fields
            $('#'+prefix+'_error_code').val('');
            $('#'+prefix+'_name').val('');
            $('#'+prefix+'_full_text').val('');
            $('#'+prefix+'_address').val('');
            $('#'+prefix+'_city').val('');
            $('#'+prefix+'_state').val('');
            $('#'+prefix+'_zip').val('');
            $('#'+prefix+'_country').val('');
            $('#'+prefix+'_lat').val('');
            $('#'+prefix+'_lng').val('');
            $('#'+prefix+'_location_key').val('');
}


// Add ride address verification
function event_updateLocation(response) {
    // Only run this check if a location key is already set.
    if ($('#'+prefix+'_location_key').val()) {
        // Look for the user input value in the userLocations array
        for (var i = 0; i < userLocations.length; i++) 
        { 
            if ($('#'+prefix).val() == userLocations[i].name) {
                return false;
            }
        }
    }
    
	if (response.Status.code != G_GEO_SUCCESS) {
		$('#'+prefix).removeClass('input-valid');
		$('#'+prefix).addClass('input-invalid');
        
        // Clear all hidden fields for the location
        clear_locations(prefix);
	} else {
		$('#'+prefix).removeClass('input-invalid');
		$('#'+prefix).addClass('input-valid');

		var address = breakout_address(response.Placemark[0]);
        
        // Clear all hidden fields for the location
        clear_locations(prefix);
        
        // If there is a map, add marker
        updateMap(prefix, address['lat'], address['lng']);
        
        $('#'+prefix+'_lat').val(address['lat']);
		$('#'+prefix+'_lng').val(address['lng']);
		$('#'+prefix+'_full_text').val(address['fullText']);
		if (address['country']) {
		    $('#'+prefix+'_country').val(address['country']);
		}

		$('#'+prefix).val(address['fullText']);
		
		if (address['city']) {
		    $('#'+prefix+'_city').val(address['city']);
		}
		if (address['state']) {
		    $('#'+prefix+'_state').val(address['state']);
		}
		if (address['zip']) {
		    $('#'+prefix+'_zip').val(address['zip']);
		}
		if (address['house_address']) {
		    $('#'+prefix+'_address').val(address['house_address']);
		}
	}
}

function init(x, y) {
	v_lat = x;
	v_lng = y;
}

function mapsLoaded() {
	if (google.maps.BrowserIsCompatible())
	{
		map = new google.maps.Map2(document.getElementById("map_canvas"));
		map.addControl(new google.maps.SmallMapControl());
		if (v_lat && v_lng) {
			map.setCenter(new google.maps.LatLng(v_lat, v_lng), 9);
		} else {
			map.setCenter(new google.maps.LatLng(37.926868, -97.294922), 3);
		}
	}
}

function addLocation(markerInfo) {
	if (map) {
		var icon = new google.maps.Icon(G_DEFAULT_ICON);
		icon.image = 'images/icons/gmap_marker.png';
		icon.iconSize = new google.maps.Size(21, 35);
		icon.iconAnchor = new google.maps.Point(6, 21);    
		icon.infoWindowAnchor = new google.maps.Point(9, 5);

		var marker = new google.maps.Marker(new google.maps.LatLng(markerInfo.lat, markerInfo.lng), icon);
		map.addOverlay(marker);

		google.maps.Event.addListener(
			marker,
			"click",
			function() {
				marker.openInfoWindowHtml( '<strong class="label">' + markerInfo.start + ' &rarr; ' + markerInfo.end + '</strong><br /><a href="share.php?ride=' + markerInfo.id + '">View this ride</a><br /><br />' + '~' + markerInfo.distance + ' miles from you.' );
			}
		);
	}
}

function clearMap(defaultLat, defaultLng, prefix) {
    if ( prefix ) {
        delete markerPoints[prefix];
    }
    refreshMap(defaultLat, defaultLng);
}

function updateMap(prefix, lat, lng) {
    if (map) {
        var lat = parseFloat(lat);
        var lng = parseFloat(lng);
        
        markerPoints[prefix] = new GLatLng(lat,lng);
        refreshMap();
    }
}

function refreshMap(lat, lng) {
    if (map) {
        var icon = new google.maps.Icon(G_DEFAULT_ICON);
        map.clearOverlays();
        // ===== Start with an empty GLatLngBounds object =====     
        bounds = new GLatLngBounds();
        
        // create the marker
        if (markerPoints['s']) {
       		//icon.image = 'http://www.zipcar.com/images/zipmarker.png';
       		icon.image = 'http://www.google.com/mapfiles/dd-start.png';
            var marker = new GMarker(markerPoints['s'], icon);
            map.addOverlay(marker);
           // ==== Each time a point is found, extent the bounds to include it =====
           bounds.extend(markerPoints['s']);
        }

        if (markerPoints['e']) {
       		icon.image = 'http://www.google.com/mapfiles/dd-end.png';
            var marker = new GMarker(markerPoints['e'], icon);
            map.addOverlay(marker);
           // ==== Each time a point is found, extent the bounds to include it =====
           bounds.extend(markerPoints['e']);
        }
        
        if (markerPoints['s'] && markerPoints['e']) {
            // ===== determine the zoom level from the bounds =====
            map.setZoom(map.getBoundsZoomLevel(bounds)-1);
        } else {
            map.setZoom(13);
        }
        
        // ===== determine the centre from the bounds ======
        if ( !markerPoints['s'] && !markerPoints['e'] ) { 
            map.setCenter(new GLatLng(lat, lng));
        }
        else {
            map.setCenter(bounds.getCenter());
        }
    }
}

$(window).unload(
	function() {
		if (map) {
			//google.Unload();
		}
	}
);



