/*	VERSION:	1.3
	1.3		Add: 		Attempts to first load an internal version of the file (using the fileName as the linkage) stored as a movieClip containing an onLoad() function which returns the file contents.  If that fails then it loads an external file like normal.
	1.2		Change:	Failure returns undefined instead of an error string,  because I typically test for failure by looking for undefined or falsey values.

USAGE
	#include "functions/VOW.as"
	#include "functions/VOW/loadFile.as"
	
	loadFile("file 2.txt")
		.then( function(file_str){
			trace(file_str);
		} );
*/
var loadFile = function( fileName ){
	var vow = VOW.make();
	
	loadInternal()
	.then( success, loadExternal );
	
	
	function success( result ){
		// no result => fail instead
		if( result === undefined )		return fail();
		// else:  output the result
		vow.keep( result );
	}// success()
	
	
	function fail(){
		vow.dobreak( undefined );
	}// fail()
	
	
	function loadInternal(){
		var vow = VOW.make();
		var newDepth = getRandomEmptyDepth( _root );
		var newName = "internalFile" + newDepth;
		var loader_mc = _root.attachMovie( fileName, newName, newDepth, {onLoad: success} );
		if( !loader_mc )		fail();
		
		function success( result ){
			// remove the temporary movieClip
			loader_mc.removeMovieClip();
			loader_mc._name = null;
			// 
			if( result === undefined )		return fail();
			// output that movieClip's stored contents
			vow.keep( result );
		}// success()
		
		function fail(){
			vow.doBreak( undefined );
		}// fail()
		
		function getRandomEmptyDepth( mc ){
			var baseDepth = 4000;
			var range = 1000;
			var newDepth = -1;
			do{
				newDepth = Math.floor(Math.random() * range) + baseDepth;
			}while( mc.getInstanceAtDepth(newDepth) !== undefined );
			return newDepth;
		}// getRandomEmptyDepth()
		
		return vow;
	}// loadInternal()
	
	
	function loadExternal(){
		function afterLoad( result ){
			if( result === undefined )		return fail();
			// remove redundant carriage-returns from external file contents  (strings from loadInternal() won't have them)
			var enter13 = String.fromCharCode(13);
			result = result.split(enter13).join('');
			// 
			success( result );
		}// afterLoad()
		
		var loader = new XML();
		loader.onData = afterLoad;
		loader.load( fileName );
	}// loadExternal()
	
	
	return vow.promise;
}// loadFile()