var locationFinder = {

	invokeAPI : function(){
    
		/* 
		 * Check whether location has been found earlier and preserved.
		 * If so use it, else make the api call.
		 */
		
		if (typeof window.localStorage != 'undefined' 
			&& typeof window.localStorage.country != 'undefined' 
			&& window.localStorage.country != null) {
			
			locationFinder.setCountryValue(window.localStorage.country);                   
			
		}
		else {            
		
			$.getJSON('http://api.wipmania.com/jsonp?callback=?', '', locationFinder.invokeAPICallback);
			
		}
		
	},

    invokeAPICallback : function(json) {
    
		/* 
		 * On success, set the country information both in uvOptions and
		 * in local storage for future use.
		 */
		if(typeof json != 'undefined' && typeof json.address != 'undefined' && typeof json.address.country != 'undefined') {
			
			locationFinder.setCountryValue(json.address.country);  
			
			if (typeof window.localStorage != 'undefined') {
			
				window.localStorage.country = json.address.country;        
			
			}      
		}
		
	},

    setCountryValue : function(value) {    
    
		if(typeof uvOptions != 'undefined' && typeof uvOptions.custom_fields != 'undefined') {		
			uvOptions.custom_fields["country-name"] = value;		
		}
		
	}
};

$(document).ready(function() {
    
	locationFinder.invokeAPI();
    
});
