/*
Script: j-applo.js

Author:
	Heiko Pfefferkorn (<http://ifabrik.de>)

License:
	MIT style license (<http://www.opensource.org/licenses/mit-license.php>, <http://de.wikipedia.org/wiki/MIT-Lizenz>)

Credits:
	Funktionalitaet basiert auf dem Javascript Framework MooTools (<http://mootools.net>), License see <http://mootools.net>
	DBUG - See <http://clientside.cnet.com>. License see <http://clientside.cnet.com>

Copyright:
	Include-Script/Object 'J-applo' - @copyright 2007 Heiko Pfefferkorn
*/

	// MooTools bereit
	if (typeof(MooTools)=='object' && MooTools.version.toFloat()>=1.11) {

		// Global verfuegbares Object
		if(!SITE_CONFIG)
			var SITE_CONFIG = {};

		SITE_CONFIG.debug = (window.location.href.indexOf('jsdebug')!=-1) ? true : false;
		SITE_CONFIG.language = 'de';

		var DBG = {
			logged : [],
			timers : {},
			firebug: false,
			debug  : false,

			/*
			Property: log
				Sends a message to the console if DBG is enabled, otherwise it stores this info until DBG is enabled.

			Arguments:
				message - The message to log, includes various substition options, see <http://www.getFirebug.com>

			Syntax:
				> DBG.log("message");
				> > message
				> DBG.log("my var is %s", myVar)
				> > my var is x

				For more examples, see <http://www.getFirebug.com>
			*/
			log: function() {
				DBG.logged.push(arguments);
			},

			nolog: function(msg) {
				DBG.logged.push(arguments);
			},

			/*
			Property: time
				Starts a console timer with the given name if DBG is enabled. See <http://www.getFirebug.com> for details.
			*/
			time: function(name){
				DBG.timers[name] = new Date().getTime();
			},

			/*
			Property: timeEnd
				Ends a console timer with the given name if DBG is enabled. See <http://www.getFirebug.com> for details.
			*/
			timeEnd: function(name){
				if (DBG.timers[name]) {
					var end = new Date().getTime() - DBG.timers[name];
					DBG.timers[name] = false;
					DBG.log('%s: %s', name, end);
				} else DBG.log('no such timer: %s', name);
			},

			/*
			Property: enable
				Turns on the DBG functionality so that messages will show up in the firebug console. Any messages sent to DBG.log()
				previously will be displayed in the console immediately and	all future logging statements will echo to the console.

			See also:
				<DBG.log>, <DBG.disable>

			Syntax:
				> DBG.enable()
				> > enabling DBG
			*/
			enable: function() {
				if(DBG.firebug) {
					try {
						DBG.debug = true;
						DBG.log = console.debug || console.log;
						DBG.time = console.time;
						DBG.timeEnd = console.timeEnd;
						DBG.log('DBG - enabled');

						for (var i=0; i<DBG.logged.length; i++)
							DBG.log.apply(console, DBG.logged[i]);
						DBG.logged=[];
					} catch(e) {
						DBG.enable.delay(400);
					}
				}
			},

			/*
			Property: disable
				Turns the DBG functionality off. all future logging calls will be stored in the logged array until DBG is enabled again.

			See also:
				<DBG.log>, <DBG.enable>, <DBG.logged>

			Syntax:
				> DBG.disable()
			*/
			disable: function(){
				DBG.log('DBG - disabled');
				if (DBG.firebug)
					DBG.debug = false;
				DBG.log = DBG.nolog;
				DBG.time = function(){};
				DBG.timeEnd = function(){};
			},

			/*
			Property: cookie
				DBG.cookie turns debugging on for the rest of the day for that domain. This lets you click around and use the debugging version
				of libraries without having to add jsdebug=true to each new page's url and reload the page. Calling DBG.cookie() when the cookie
				is already present will disable it (toggle).

			Arguments:
				set - (boolean; optional); If true sets the cookie even if it's already set (overrides toggle), If false overrides to disable the cookie (same as <DBG.disableCookie>);
			*/
			cookie: function(set){
				var value = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
				var debugCookie = value ? unescape(value[1]) : false;
				if((debugCookie != 'true' || set) && !set) {
					DBG.enable();
					DBG.log('DBG - setting debugging cookie');
					var date = new Date();
					date.setTime(date.getTime()+(24*60*60*1000));
					document.cookie = 'jsdebug=true;expires='+date.toGMTString();
				} else DBG.disableCookie();
			},

			/*
			Property: disableCookie
				This removes the cookie set by <DBG.cookie> and turns off debugging for subsequent page loads.
			*/
			disableCookie: function(){
				DBG.log('DBG - disabling debugging cookie');
				document.cookie = 'jsdebug=false';
			}
		};

		if (typeof console!="undefined" && console.warn) {
			DBG.firebug = true;

			var value       = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
			var debugCookie = value ? unescape(value[1]) : false;

			if (window.location.href.indexOf("jsdebug=true")>0 || debugCookie=='true')
				DBG.enable();

			if (debugCookie=='true')
				DBG.log('DBG - debugging cookie enabled');

			if (window.location.href.indexOf("jsdebugCookie=true")>0) {
				DBG.cookie();
				if (!DBG.debug)
					DBG.enable();
			}
			if(window.location.href.indexOf("jsdebugCookie=false")>0)
				DBG.disableCookie();
		}

		var JAPPLO = {
			/*
			Property: initialize
			*/
			start: function(){
				DBG.log('MooTools is loaded and ready');
				DBG.time('JAPPLO.start ');

				JAPPLO.doc             = document;
				JAPPLO.jsPath          = '';
				JAPPLO.jsQuery         = '';
				JAPPLO.lastInclude     = '';
				JAPPLO.jsAssets        = [];
				JAPPLO.fileDebugString = (SITE_CONFIG.debug==true) ? '.debug' : '';


				JAPPLO.incModMain = {
					// Hauptfiles
					'native': {
						'path' : 'native/',
						'files': {
							'string'            : ['string%d.js'],
							'date.parse'        : ['date.parse%d.js'],
							'element.dimensions': ['element.dimensions%d.js'],
							'element.legacy'    : ['element.legacy%d.js'],
							'element.pin'       : ['element.pin%d.js'],
							'element.position'  : ['element.position%d.js'],
							'element.shortcuts' : ['element.shortcuts%d.js'],
							'window'            : ['window.cnet%d.js']
						}
					},
					'remote': {
						'path': 'remote/',
						'files': {
							//'ajax.cnet': ['ajax.cnet%d.js']
						}
					}
				};


				JAPPLO.incModUser = {
					// Utilities
					'utl': {
						'path' : 'utilities/',
						'files': {
							'datecheck': ['datecheck%d.js']
						}
					},

					// Browserspezifische Files
					'bof': {
						'path' : 'browser.fixes/',
						'files': {
							'fixpng'    : ['fixpng%d.js'],
							'swfobject' : ['swfobject%d.js']
						}
					},

					// verschiedene Plugins
					'pl': {
						'path' : '3rd.party/',
						'files': {
							'calendar'     : ['calendar/calendar.js','calendar/lang/calendar-%l.js','calendar/calendar-setup.js'],
							'cl.asuggest'  : ['cl.asuggest%d.js'],
							'cl.ajaxform'  : ['cl.ajaxform%d.js'],
							'cl.down'      : ['cl.down%d.js'],
							'cl.zebra'     : ['cl.zebra%d.js']
						}
					}
				};

				JAPPLO.hdlReq();
				DBG.timeEnd('JAPPLO.start ');
			},

			/*
			Property: hdlReq (Handle request)
				Querystring verarbeiten und gewuenschte Optionen setzen bzw initialisieren. Check das 'J-applo' nur einmal
				im Dokument eingebunden sein darf (loesche, wenn mehrere da, alle anderen raus) und das kein anderes File
				schon vorher aus dem J-applo-Verzeichnis eingebunden wurde.
			*/
			hdlReq: function() {
				var flag = false;

				$$('script[src*="/j-applo."]').each(function(el) {
					if(!flag && el.src.indexOf('j-applo')!=-1) {
						var src = el.getProperty('src');

						JAPPLO.lastInclude = el;

						if(src.indexOf('debug')!=-1)
							JAPPLO.jsPath = src.replace(/j-applo\.debug\.js(\?.*)?$/,'');
						else
							JAPPLO.jsPath = src.replace(/j-applo\.js(\?.*)?$/,'');

						JAPPLO.jsQuery = new Hash(JAPPLO.parseQs(src));

						DBG.log('JAPPLO.hdlReq > (jsQuery) '+src);

						JAPPLO.getLanguage();
						JAPPLO.getMainModule();
						JAPPLO.getMiscModule();
						JAPPLO.getUserModule();
						JAPPLO.setModule();

						flag = true;
					} else
						el.remove();
				});
			},

			/*
			Property: setLanguage
				Sprache im global verfuegbaren Objekt 'SITE_CONFIG.language', sofern SITE_CONFIG vordefiniert, setzen
			*/
			getLanguage: function() {
				if(JAPPLO.jsQuery.hasKey('language')) {
					SITE_CONFIG.language = JAPPLO.jsQuery.get('language').toLowerCase();
					JAPPLO.jsQuery.remove('language');

					DBG.log('JAPPLO.setLanguage > %s', SITE_CONFIG.language);
				}
			},

			/*
			Property: getMainModule
				Zusammenstellen der Standardmodule (JAPPLO.incModMain)
			*/
			getMainModule: function() {
				DBG.log('JAPPLO.setMainModule');

				var query_exclude = [];

				// generiere Array der nicht einzubindenden Modulgruppen und/oder Einzelmodule anhand des Querystrings
				if (JAPPLO.jsQuery.hasKey('exclude')) {
					query_exclude = JAPPLO.jsQuery.get('exclude').split(',');
					JAPPLO.jsQuery.remove('exclude');
				}

				for (var group in JAPPLO.incModMain) {
					if (!query_exclude.test(group)) {
						var group_path = JAPPLO.incModMain[group].path;

						// Modulgruppe einbinden
						for (var group_modul in JAPPLO.incModMain[group].files) {
							// einzelnes Modul einbinden?
							if (!query_exclude.test(group_modul)) {
								JAPPLO.incModMain[group]['files'][group_modul].each(function(file) {
									var f_id  = JAPPLO._generateId(file);
									var f_src = JAPPLO.jsPath+group_path+file.replace(/\%l/, SITE_CONFIG.language).replace(/\%d/, JAPPLO.fileDebugString);

									JAPPLO.jsAssets.include({
										'i': f_id,
										's': f_src
									});

									//DBG.log('         '+f_src);
								});
							}
						}
					}
				}
			},

			/*
			Property: getMiscModule ()
				Einbindung nutzerspezifischer Module > Querystring (&utl=...,...&bof=...,...&pl=...,...)
			*/
			getMiscModule: function() {
				DBG.log('JAPPLO.setMiscModule');

				var query_mod = [];

				for(var group in JAPPLO.incModUser) {
					if(JAPPLO.jsQuery.hasKey(group)) {
						var query_include = JAPPLO.jsQuery.get(group).split(',');
						var group_path    = JAPPLO.incModUser[group].path;

						query_include.each(function(group_modul){
							if($chk(JAPPLO.incModUser[group].files[group_modul])) {
								JAPPLO.incModUser[group]['files'][group_modul].each(function(file) {
									var f_id  = JAPPLO._generateId(file);
									var f_src = JAPPLO.jsPath+group_path+file.replace(/\%l/, SITE_CONFIG.language).replace(/\%d/, JAPPLO.fileDebugString);

									JAPPLO.jsAssets.include({
										'i': f_id,
										's': f_src
									});
									//DBG.log('         '+f_src);
								});
							}
						});
					}
				}
			},

			/*
			Property: getUserModule
				Zusammenstellen der vom User angegebenen Module.im Querystring.

			Syntax:
				> "&sp=dir/subdir/file.js,dir/subdir/file2.js,"
			*/
			getUserModule: function() {
				if(JAPPLO.jsQuery.hasKey('sp')) {
					DBG.log('JAPPLO.setUserModule');

					var query_include = JAPPLO.jsQuery.get('sp').split(',');
					query_include.each(function(file) {
						var f_id  = JAPPLO._generateId(file);
						var f_src = file.replace(/\%l/, SITE_CONFIG.language).replace(/\%d/, JAPPLO.fileDebugString);

						JAPPLO.jsAssets.include({
							's': f_src,
							'i': f_id
						});
						//DBG.log('         '+f_src);
					});
				}
			},

			/*
			Property: setModule
				Einbinden aller zusammengestellter Js-Files
			*/
			setModule: function() {
				DBG.log('JAPPLO.incAll {files}');

				$each(JAPPLO.jsAssets, function(obj, i) {
					JAPPLO.includeFile(obj);
					/*var f = new Element('script', {
						id      : obj.i,
						src     : obj.s,
						language: 'javascript',
						type    : 'text/javascript'
					}).injectAfter(JAPPLO.lastInclude);

					JAPPLO.lastInclude = f;*/

					var lfd_nr = (i<9) ? '0'+(i+1) : i+1;
					DBG.log('       '+lfd_nr+'. '+obj.s);
				});
			},

			/*
			Property: parseQuerystring
				Gibt einen vorhandenen Querystring als Objekt zurueck

			Arguments:
				url - Aufruf/Querystring der J-applo-Einbindung
			*/
			parseQs: function(url) {
				var query = $pick(url);

				if (query=='')
					return null;

				if (query.indexOf("?")>=0)
					query = query.substring(query.indexOf("?")+1, query.length);

				var pairs = query.match(/^\??(.*)$/)[1].split('#');
				var params = {};
				pairs.each(function(pair) {
					pair            = pair.split('=');
					params[pair[0]] = pair[1];
				});
				return params;
			},

			includeFile: function(o){
				var s = "<script language=\"javascript\" type=\"text/javascript\" src=\""+o.s+"\"";
				//if(o.i)
				//	s+=' id="'+o.i+'"';
				s+="></script>";

				JAPPLO.doc.write(s);
			},

			/*
			Property: _generateId
				Generiert aus einem Dateinamen einen ID-String
			*/
			_generateId: function(s) {
				return s.replace(/\%l/, '').replace(/\%d/, '').replace(/\//, '').replace(/\.js/, '').replace(/\./, '_');
			}
		};
		JAPPLO.start();
	} else
		throw("J'applo requires the object-oriented javascript framework 'MooTools' >= release 1.11 (mootools.net)");
