/**
* First attempt to a completely new codebase for the WPS_javascript-clients
* In general the idea is to refactor most of the functionality needed right now to a more clever object-based structure.
* This structure is bound to a wps-namespace, to ensure functions will not clash.
* Libraries themselves must strive to be as standalone as possible, to make individual scripts available to the public.
* 
* 3rd party project which we intend to use: 
*	* prototype 1.50
*	* peterned-inheritance script
*	* scriptaculous library
*
* This page will try to set paths, instantiate the autoloader and load the most basic libraries
* @version 1.00
*/
	/**
	* set's the absolute path from the domain to the src of the scripts
	*/
	//var gRootPath = '/wpsRepos/';
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
	/**
	* Declares namespace
	*/
	var wps = function(){
		this.instID = 'wps_' + parseInt(Math.random()*1000000);
	}

	/**
	* helper to load libraries after checking their availability. 
	* This function might be usefull for calling object without actually including them first.
	* If catched to this function it might be able to recursively find the script.
	*/
	wps._require = function(srcArr){ 
		//srcArr.reverse();
		for (var cnt=0;cnt<srcArr.length;cnt++){
			if (!wps._scriptExists(srcArr[cnt])){
				wps._injectScript(srcArr[cnt]);
			}
		}
		//document.write('<input type="button" value="DebugRequire" onClick="debugRequire();"/>');		
	}
	
	/**
	 * Javascript library loader
	 * Use this to include libraries AFTER the page has been rendered
	 * srcArr can be an array containing references to files, or containing references to objects 
	 * Objects should have 2 properties: file and onLoaded;
	 * file =reference to a Js-file
	 * onLoaded = STRING referencing the function to be executed when the file has loaded. 
	 * 
	 * If you're using a object-reference the onLoaded-string will be put into a dispatchArray, this dispatchArray is a kind of queue with functions to execute when the file is loaded and ready
	*/
	wps._live_require = function(srcArr){ 
		//srcArr.reverse();
		for (var cnt=0;cnt<srcArr.length;cnt++){
			if (srcArr[cnt].file){
				wps._live_require_inject(srcArr[cnt].file);
				wps.addToDispatch(srcArr[cnt].onLoaded);
			}else{
				wps._live_require_inject(srcArr[cnt]);
			}
		}
		wps.runDispatch(); // run the onloaded-functions defined in object-references
	}

	wps._live_require_inject = function(src){
		if (wps.forceReloading){
			// remove script
			wps.blockScript(src);
			wps._injectScript(src, true);
		}else{
			if (!wps._scriptExists(src)){
				wps._injectScript(src, true);
			}
		}
	}

	wps.runDispatch = function(){
		wps.dispatchRetries = 0;
		if (wps.dispatchArr){
			$(wps.dispatchArr).each(
				function(strFunc){
					wps.execDispatch(strFunc);
					wps.dispatchArr.pop(strFunc); // remove the dispatch-item from array, else it would run again after a next call to runDispatch
				}
			)
		}
	}

	wps.execDispatch = function(strFunc){
		if (wps.dispatchRetries > 100){
			alert('WPS:execDispatch tried to execute ' + strFunc + ' but failed after 100 tries.. Process dying gracefully (error: ' + wps.lastError + ')');
			wps.dispatchRetries = 0;
			wps.dispatchArr = new Array();
			return;
		}
		try{
			eval(strFunc);
		}catch(e){
			if ( ( e.message.indexOf('is not a function') > -1) || ( e.message.indexOf("Object doesn't support") > -1) ){
				wps.lastError = e;
				wps.dispatchRetries++;
				var func =function(){wps.execDispatch(strFunc)}
				setTimeout(func, 100);
			}else{
				alert("Error at execDispatch::" + e.message + ' ( ' + strFunc + ' )');
			}
		}
	}
	
	wps.addToDispatch = function(str){
		if (!wps.dispatchArr){
			wps.dispatchArr = new Array();
		}
		wps.dispatchArr.push(str);
	}
	
	/*
	* Checks whether a script was already required
	*/ 
	wps._scriptExists = function(sScriptSrc){
		var scripts = document.getElementsByTagName("script");
		//alert(scripts.length);
		for (var y=0;y<scripts.length;y++){
			if (scripts[y].src){
				var scriptSrc = new String(scripts[y].src);
				if (scriptSrc.indexOf(sScriptSrc) > -1){
					return true;
				}
			}
		}		
		return false;
	}
	
	/**
	* Actually inject the script into the head-node of the page
	*/
	wps._injectScript = function(src, doLiveInjection){
		if (!doLiveInjection) doLiveInjection = false
		if (doLiveInjection){
			wps._domInject(src);
			return;
		}
		if ((BrowserDetect.browser == 'Safari') ){
			document.write('<script type="text/javascript" src="'+src+'"></script>');
			return;
		}
        try {
            var dingDong = new ActiveXObject('Msxml2.XMLHTTP');
            document.write('<script type="text/javascript" src="'+src+'"></script>');
        }catch(e){
        	wps._domInject(src);
        }
	}
	
	wps._domInject = function(src){
    	var theHead = document.getElementsByTagName("head");
		if (!theHead) {alert("no head?");return false;}
		theHead = theHead.item(0);
    	var oScriptElem = document.createElement('script');
		oScriptElem.setAttribute("src",src);
		oScriptElem.setAttribute("language","Javascript");
//		oScriptElem.setAttribute("defer","");
		oScriptElem.setAttribute("type","text/javascript");
		theHead.insertBefore(oScriptElem, theHead.childNodes.item(0));
	}
	
	wps.blockScript = function(src){
		//removes a injected script (to be overloaded by something
		$A(document.getElementsByTagName('script')).each(
			function(script){
				if (script.getAttribute('src') == src){
					// remove the script
					var parentNode = script.parentNode;
					parentNode.removeChild(script);
				}
			}
		)
	}	
	/**
	* Set's requirement for the prototype-library, before doing anything else (like creating classes).
	*/
	//DEVELOPMENT INC
	wps._require(
		[
			gRootPath+'lib/3rd/peterned_inheritance.js',
			gRootPath+'lib/3rd/quirksmode/browserDetect.js',
			gRootPath+'lib/3rd/prototype.js',
			gRootPath+'lib/3rd/scriptaculous/builder.js',
			gRootPath+'lib/3rd/scriptaculous/effects.js',
			gRootPath+'lib/3rd/scriptaculous/dragdrop.js',
			gRootPath+'lib/3rd/scriptaculous/controls.js',
			gRootPath+'lib/3rd/scriptaculous/slider.js',
			gRootPath+'lib/3rd/eventHandler.js',
			gRootPath+'lib/3rd/windows/javascripts/window.js',
			gRootPath+'lib/3rd/windows/javascripts/window_ext.js',
			gRootPath+'lib/3rd/windows/javascripts/tooltip.js',			
 			gRootPath+'lib/3rd/tiny_mce/tiny_mce.js',
			gRootPath+'lib/3rd/calendar/calendar.js',
			gRootPath+'lib/3rd/calendar/lang/calendar-en.js',
			gRootPath+'lib/3rd/calendar/calendar-setup.js',
			gRootPath+'lib/wps.debug.js',
			gRootPath+'lib/wps.base.js',
			gRootPath+'lib/wps.base.cache.js',
			gRootPath+'lib/wps.rpc.js',
			gRootPath+'lib/wps.file.js',
			gRootPath+'lib/wps.dom.js',
			gRootPath+'lib/wps.base.stringbuffer.js',
			gRootPath+'lib/wps.gallery.js',
			gRootPath+'lib/wps.gallery.image.js',
			gRootPath+'lib/imageBrowser/wps.imageViewer.js',
			gRootPath+'lib/editMode/wps.editMode.js',
			gRootPath+'lib/ui/wps.uiInterface.js',
			gRootPath+'lib/ui/wps.uiBase.js',
			gRootPath+'lib/wps.ui.js',
			gRootPath+'lib/ui/wps.uiObject.js',
			gRootPath+'lib/ui/wps.ui.panel.js',
			gRootPath+'lib/ui/wps.ui.staticPanel.js',
			gRootPath+'lib/ui/wps.ui.blocker.js',
			gRootPath+'lib/ui/wps.ui.menu.js',
			gRootPath+'lib/ui/wps.ui.dhtmlXmenu.js',
			gRootPath+'lib/ui/wps.ui.dhtmlXcontextMenu.js',
			gRootPath+'lib/ui/wps.ui.dhtmlXtab.js',
			gRootPath+'lib/ui/wps.ui.dhtmlXgrid.js',
			gRootPath+'lib/ui/wps.ui.dhtmlXtree.js',
			gRootPath+'lib/ui/wps.ui.menuItem.js',
			gRootPath+'lib/ui/wps.ui.xml.js',
			gRootPath+'lib/ui/wps.ui.html.js',
			gRootPath+'lib/ui/wps.ui.iframe.js',
			gRootPath+'lib/ui/wps.ui.button.js',
			gRootPath+'lib/ui/wps.ui.floatingWindow.js',
			gRootPath+'lib/ui/wps.ui.miniFloater.js',
			gRootPath+'lib/ui/wps.ui.floatingWindowDeLuxe.js',
			gRootPath+'lib/ui/wps.ui.image.js',
			gRootPath+'lib/ui/wps.ui.alttext.js',
			gRootPath+'lib/ui/wps.ui.scrollerY.js',
			gRootPath+'lib/ui/wps.ui.rpc.js',
			gRootPath+'lib/ui/wps.ui.flowPlayer.js',
			gRootPath+'lib/ui/wps.ui.editable.js',
			gRootPath+'lib/ui/wps.ui.selectable.js',
			gRootPath+'lib/ui/wps.ui.multiSelectable.js',
			gRootPath+'lib/ui/wps.ui.form.js',
			gRootPath+'lib/ui/form/formFactory.js',
			gRootPath+'lib/ui/form/form_Lang.js',
			gRootPath+'lib/ui/form/formElement.js',
			gRootPath+'lib/ui/form/form_Textarea.js', 
			gRootPath+'lib/ui/form/form_Select.js', 
			gRootPath+'lib/ui/form/form_Radio.js', 
			gRootPath+'lib/ui/form/form_Checkbox.js', 
			gRootPath+'lib/ui/form/form_Input.js',
			gRootPath+'lib/ui/form/form_Hidden.js',
			gRootPath+'lib/ui/form/form_Button.js',
			gRootPath+'lib/ui/form/form_Image.js',
			gRootPath+'lib/ui/form/form_Date.js',
			gRootPath+'lib/ui/form/form_File.js',
			gRootPath+'lib/ui/form/form_PostValidator.js',			
			gRootPath+'lib/ui/wps.ui.tinyMCE.js',
			gRootPath+'lib/react/react.js'
		]
	);

/* Production inc. (compressed!)*/
/*
	wps._require(
	[
			gRootPath+'lib/3rd/peterned_inheritance.js',
			gRootPath+'lib/3rd/quirksmode/browserDetect.js',
			gRootPath+'lib/3rd/prototype.js',
			gRootPath+'compressed.js',
			gRootPath+'lib/3rd/scriptaculous/scriptaculous.js',
			gRootPath+'lib/3rd/eventHandler.js',
			gRootPath+'lib/3rd/sortableTable/fastinit.js',
			gRootPath+'lib/3rd/sortableTable/tablesort.js',
			gRootPath+'lib/3rd/windows/javascripts/window.js',
			gRootPath+'lib/3rd/windows/javascripts/window_ext.js',
			gRootPath+'lib/3rd/windows/javascripts/tooltip.js',			
 			gRootPath+'lib/3rd/tiny_mce/tiny_mce.js',
  			gRootPath+'lib/3rd/calendar/calendar.js',
			gRootPath+'lib/3rd/calendar/lang/calendar-en.js',
			gRootPath+'lib/3rd/calendar/calendar-setup.js'		,
			// MOVE THIS TO COMPRESSED/development!!
			gRootPath+'lib/mixins/eventstack.js'
			
	]
	);
*/