/**
 * this code is borrowed from Appcelerator (appcelerator.org).
 * the borrowed code is heavily modified, so the remoteLoad function will work
 * without the overhead of the rest of the framework.
 * 
 * the external API is preserved from Appcelerator, so you should be able
 * to swap this out for the actual full Appcelerator framework, without breaking
 * your code. (should you decide you need the full framework, that is).
 */

/*!
 * This file is part of Appcelerator.
 *
 * Copyright 2006-2008 Appcelerator, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
RemoteLoadBootstrapper = {
	fetching: { }
}

Appcelerator = {
	Browser: {
		
	},
	Core: { 
		HeadElement: null,

		initialize: function() {
			this.HeadElement = document.getElementsByTagName('head')[0];
		}
	},
	URI: {
		absolutizeURI: function(path, base) {
			// stub
			return path;
		}
	}
}
APPCELERATOR_DEBUG = true;

(function() {
	var ua = navigator.userAgent.toLowerCase();
	Appcelerator.Browser.isPreCompiler = (ua.indexOf('Appcelerator Compiler') > -1);
	Appcelerator.Browser.isOpera = (ua.indexOf('opera') > -1);
	Appcelerator.Browser.isSafari = (ua.indexOf('safari') > -1);
	Appcelerator.Browser.isSafari2 = false;
	Appcelerator.Browser.isSafari3 = false;
	Appcelerator.Browser.isIE = !!(window.ActiveXObject);
	Appcelerator.Browser.isIE6 = false;
	Appcelerator.Browser.isIE7 = false;
	Appcelerator.Browser.isIE8 = false;
	
	if (Appcelerator.Browser.isSafari)
	{
		var webKitFields = RegExp("( applewebkit/)([^ ]+)").exec(ua);
		if (webKitFields[2] > 400 && webKitFields[2] < 500)
		{
			Appcelerator.Browser.isSafari2 = true;
		}
		else if (webKitFields[2] > 500 && webKitFields[2] < 600)
		{
			Appcelerator.Browser.isSafari3 = true;
		}
	}
	
})();

Logger =
{
	console:function(type,msg)
	{
		try
		{
			if (console && console[type]) console[type](msg);
		}
		catch(e)
		{

		}
	},
	debug:function(msg) { if (APPCELERATOR_DEBUG) this.console('debug',msg);  },
	info:function(msg)  { this.console('info',msg);   },
	error:function(msg) { this.console('error',msg);  },
	warn:function(msg)  { this.console('warn',msg);   },
	trace:function(msg) { if (APPCELERATOR_DEBUG) this.console('debug',msg);  },
	fatal:function(msg) { this.console('error',msg);  }
};

function $D(msg) {
	Logger.debug(msg);
}

function $A(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

Object.extend(Function.prototype, {
	curry: function() {
	  if (!arguments.length) return this;
	  var __method = this, args = $A(arguments);
	  return function() {
	    return __method.apply(this, args.concat($A(arguments)));
	  }
	},

	delay: function() {
	  var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
	  return window.setTimeout(function() {
	    return __method.apply(__method, args);
	  }, timeout);
	}
});
Function.prototype.defer = Function.prototype.delay.curry(0.01);

/**
 * dynamically load a remote file
 *
 * @param {string} name of the tag to insert into the DOM
 * @param {string} type as in content type
 * @param {string} full path to the resource
 * @param {function} onload to invoke upon load
 * @param {function} onerror to invoke upon error
 */
Appcelerator.Core.remoteLoad = function(tag,type,path,onload,onerror)
{
	$D('remoteLoad '+tag+',type='+type+',path='+path+',onload='+onload+',onerror='+onerror);

	// fixup the URI
	path = Appcelerator.URI.absolutizeURI(path,Appcelerator.DocumentPath);
	
    var array = RemoteLoadBootstrapper.fetching[path];
    if (array)
    {
        if (onload)
        {
            array.push(onload);
        }
        return;
    }
    if (onload)
    {
        RemoteLoadBootstrapper.fetching[path]=[onload];
    }
    var element = document.createElement(tag);
    element.setAttribute('type',type);

    switch(tag)
    {
        case 'script':
            element.setAttribute('src',path);
            break;
        case 'link':
            element.setAttribute('href',path);
            element.setAttribute('rel','stylesheet');
            break;
    }
	var timer = null;
    var loader = function()
    {
	   $D('loaded '+path);
	   if (timer) clearTimeout(timer);
       var callbacks = RemoteLoadBootstrapper.fetching[path];
       if (callbacks)
       {
           for (var c=0;c<callbacks.length;c++)
           {
               try { callbacks[c](); } catch (E) { }
           }
           delete RemoteLoadBootstrapper.fetching[path];
       }
    };    
    if (tag == 'script')
    {
	    if (Appcelerator.Browser.isSafari2)
	    {
	        //this is a hack because we can't determine in safari 2
	        //when the script has finished loading
	        loader.delay(1.5);
	    }
	    else
	    {
	        (function()
	        {
	            var loaded = false;
	            element.onload = loader;
				if (onerror)
				{
					if (!loaded)
					{
						// max time to determine if we've got an error
						// obviously won't work if takes long than 3.5 secs to load script
						timer=setTimeout(onerror,3500);
					}
					element.onerror = function()
					{
						// for browsers that support onerror
						if (timer) clearTimeout(timer);
						onerror();
					};
				}
	            element.onreadystatechange = function()
	            {
	                switch(this.readyState)
	                {
	                    case 'loaded':   // state when loaded first time
	                    case 'complete': // state when loaded from cache
	                        break;
	                    default:
	                        return;
	                }
	                if (loaded) return;
	                loaded = true;
	                
	                // prevent memory leak
	                this.onreadystatechange = null;
	                loader();
	            }   
	        })();
	    }   
	}
	else
	{
	   loader.defer();
	}
    Appcelerator.Core.HeadElement.appendChild(element);
};



/** the following code initiates the bootstrapping process for the javascript audio player **/
		(function() {
			
			var handlePtLoaded = function() {
				Appcelerator.Core.remoteLoad(
					"script", "text/javascript", "/scripts/player.js", 
					function() {
						AudioPlayer.InitializePage();
						$$(".audio-player").each( function(e) {
							e.setStyle({visibility: 'visible'});
						});
					}
				);
			};
			
			var f = function() {
				Appcelerator.Core.initialize();

				Appcelerator.Core.remoteLoad(
					"script", "text/javascript", "/scripts/prototype-1.6.0.3.js",
					handlePtLoaded
				);
			};
			
			if (window.addEventListener) {
				window.addEventListener("load", f, false);
			} else {
				window.attachEvent("onload", f);
			}
			
		})();


