// Ugliness... was quickly hacked together
var cache_loc = '';
var cache_addy = '';
var $from = '';
var $to = '';
var $loading = '';
var $hold_on = '';

jQuery(function($){
    
    $from = $('#from');
    $to = $('#to');
    $loading = $('#loading');
    $hold_on = $('#hold-on');
    
	$('#starting_fare, #meters, #cents').change(function(){
		$('#use_custom').attr('checked', 'checked');
	});
	
	$('#submit').click(function(){
	
	    $(['from', 'to']).each(function(i, val){
	    
	         var cur_val = window['$' + val][0].value;
	         if(cur_val.indexOf(',') === -1 && cache_addy){
	             window['$' + val][0].value = (cur_val + ', ' + cache_addy);
	         }
	    
	    })
		showLoading();
		
	});
	
	if(geo_position_js && geo_position_js.init()){
	    
        $hold_on.show();
	    
		geo_position_js.getCurrentPosition(function(data){
		     
			cache_loc = data.coords.latitude + ',' + data.coords.longitude;
			setDefaultCity.apply(null, cache_loc.split(','));

		    $hold_on.hide();
			$('#geo-loc').show().click(function(){
			    $from.val(cache_loc);
			});
			
		}, function(){
			alert('Sorry, we could not find your address!');
		}, { enableHighAccuracy: true });
		
    }
	
	function setDefaultCity(lat, lng){

        var geocoder = new GClientGeocoder();
        var self = this;
        
        geocoder.getLocations(lat + ',' + lng, function(addresses) {
        
            if(addresses.Status.code != 200) {
                notice("Reverse geocoder failed to find an address");
            }
            else {
                var addy = addresses.Placemark[0];
                
                if(addy.address){
                
                    var parts = addy.address.split(',');
                    // If we have 3 chunks, we have "city, prov, country"
                    if(parts.length == 3){
                        city = 0; // array keys
                        prov = 1;
                    }
                    // We have "address, city, prov, country"
                    else if(parts.length == 4){
                        city = 1;
                        prov = 2;
                    }
                    
                    cache_addy = $.trim(parts[city]) + ', ' + ($.trim(parts[prov])).substr(0, 2);

                }
            }
            
        });
        
	}
	
	function showLoading(){
		
		$loading.show().css({
			top: ($(window).height() - $loading.outerHeight(true)) / 5,
			left: ($(window).width() - $loading.outerWidth()) / 2
		});	
	}
	
	function hideLoading(){
		$loading.hide();
	}

	
})