var googleApiAdditionalScripts = "";
var googleApiInitialized = false;
var googleApiCallbackMethod = 0;
var _additionalLibrariesLoading = false;
var _additionalLibraries = [];

/**
 * Method to ensure google API is loaded and initialized. Use this method with a 
 * callback to call any google API.
 */
function callGoogleApi(callbackMethod) {

	// Ensure API is only initialized if not already
	if ( !googleApiInitialized ) {
  
		// Store callback method
		googleApiCallbackMethod = callbackMethod;

		// Update DOM
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = googleApiUrl + '&async=2&callback=handleGoogleApiLoaded';
		document.body.appendChild(script);
	} else {
		callbackMethod();
	}
}

/**
 * Called when Google API is loaded. Load additional scripts or call callback. 
 */
function handleGoogleApiLoaded() {
    // Update state
	googleApiInitialized = true;
	
	// Initialize geocoding
	if ( initializeGeocoding ) initializeGeocoding();
	
	// Add additional scripts
	if ( "" + googleApiAdditionalScripts != "" ) {
		// Setup additional libraries
		
		// Check guard
		if ( !_additionalLibrariesLoading) {
			// Set guard
			_additionalLibrariesLoading = true;
			_additionalLibraries = googleApiAdditionalScripts;
			
			// Do load
			loadAdditionalScript();
		} else {
			googleApiCallbackMethod();
		}
		
	} else {
		googleApiCallbackMethod();
	}
}

/**
 * Recursively load additional scripts. At the end the googleApiCallback is called.
 */
function loadAdditionalScript() {

	if ( _additionalLibraries.length > 0 ) {
		script = _additionalLibraries.shift();
	
		$.getScript(script, function() {
			loadAdditionalScript();
		});
	} else {
		googleApiCallbackMethod();
	}

}
