var MAPS = [
    {
        "index": 0,
        "zipCode": 23602,
        "url": '/peninsula-area',
        "lat": 37.1120848,
        "long": -76.5372625,
        "distance": 0
    }, 
    {
        "index": 1,
        "zipCode": 23225,
        "url": '/richmond-area',
        "lat": 37.5374438,
        "long": -77.5275463,
        "distance": 0
    }, 
    {
        "index": 2,
        "zipCode": 23518,
        "url": '/south-hampton-roads-area',
        "lat": 36.9116232,
        "long": -76.2189421,
        "distance": 0
    }];

var JID = 
    {
        'submitButton': '#btnLocate',
        'originLocation': '#txtLocation',
		'searchIndicator': '#imgSearchIndicator'
    };

var COUNT_MAPS = MAPS.length;
var MAX_DISTANCE = 999999999999;
var ERROR_CODES =
{
	GENERAL_MAPPING_ERROR:-1,
	INVALID_START_ADDRESS:-2	
};

// SEE:  http://code.google.com/apis/maps/documentation/directions/
var BASE_MAPPING_SERVICE_URL = '/google-maps-web-service-proxy?';

function isInteger(n)
{
    return (!isNaN(parseInt(n)) && isFinite(n));
}

function findClosestStore()
{
    // Reset the map distance calculation variables.
    var mapIndexWithShortestDistance = -1;
    // The current, shortest distance from origin ZIP Code to map ZIP Code.
    var currentShortestDistance = MAX_DISTANCE;
    
    // Retrieve the origin ZIP Code from the text field.
    var originLocation = jQuery.trim($(JID.originLocation).val());
    
    // Proceed if the originZIPCode is non-null and has a 5 digit character length and is a valid integer.
    if ((originLocation != null) && (originLocation.length > 0)) 
    {
     	// Examine the originLocation for the presence of a comma that would denote a state value.
		if (originLocation.indexOf(',') <= -1)		
		{
			// It is probable that a state value was not included, so append a ",VA" text suffix.
			originLocation += (',VA');
		}
		
		$(JID.searchIndicator).show();
	 
	    for (var i = 0; i < COUNT_MAPS; i++) 
        {
            var mappingServiceURL = BASE_MAPPING_SERVICE_URL + 'origin=' + encodeURIComponent(originLocation) + '&dest=' + encodeURIComponent(MAPS[i].zipCode);
            
            // Retreive the distance from the origin ZIP code to each of the map ZIP codes
            // using the Google Maps Web Service.
            $.ajax(
                {
                    url: mappingServiceURL,
                    async: false,
                    dataType: 'xml',
                    success: function(data, textStatus, xhr)
                    {
                        // The <DirectionsResponse> should return a status of "OK".
                        var _status = $(data).find("status:first");
                        
                        if ((_status != null) && (_status.text() == 'OK')) 
                        {
                            // Determine if the Google map service calculated a valid start address.
							var _startAddress = $(data).find("start_address:first");
							
							if ((_startAddress != null) && (_startAddress.text() != 'Virginia, USA'))							
							{
								var _distance = $(data).find("leg:first > distance:first > value:first");
	                            MAPS[i].distance = parseInt(_distance.text());
	                            
	                            if (MAPS[i].distance < currentShortestDistance) 
	                            {
	                                mapIndexWithShortestDistance = i;
	                                currentShortestDistance = MAPS[i].distance;
	                            }	
							}
							else							
							{
								mapIndexWithShortestDistance = ERROR_CODES.INVALID_START_ADDRESS;								
							}
                        }
                        else 
                        {
                            mapIndexWithShortestDistance = ERROR_CODES.GENERAL_MAPPING_ERROR;
                        }
                    },
                    error: function(xhr, textStatus, errorThrown)
                    {
                        mapIndexWithShortestDistance = -1;
						
						//alert(errorThrown);
                    }
                });
            
            // One of the queries failed, so break from the loop.
            if (mapIndexWithShortestDistance <= -1) 
            {
                break;
            }
        }
        
		$(JID.searchIndicator).hide();
		
        if ((mapIndexWithShortestDistance > -1) && (mapIndexWithShortestDistance < COUNT_MAPS)) 
        {
            window.location.href = MAPS[mapIndexWithShortestDistance].url;
        }
		else if (mapIndexWithShortestDistance == ERROR_CODES.INVALID_START_ADDRESS)		
		{
			if(confirm("Unfortunately, the starting address could not be located.  Would you like to view a list of all current MiniPrice Storage locations?"))			
			{
				window.location.href = "locations";
			}
		}
        else
        {
            alert("Unfortunately, the closest MiniPrice Storage facility could not be located.  Please check that the starting search address exists and is formatted properly.");
        }        
    }
    else 
    {
        alert("You must enter an origin location to check for the nearest MiniPrice Storage facility.");
    }    
}

$(window).load(function()
{
    $(JID.submitButton).click(function()
    {
        findClosestStore();
    });
});
