/*!
 * 
 * @author Jens Raabe <jens@raabe-berlin.de>
 */
JRCmsInit = new Class ({
	Implements: [Options],

	options: {
		jr_lang: 'de',									// language use for texts
		jr_langTxt: {},									// help texts
		jr_srcpath: 'src/',							// used for files
		jr_pluginpath: 'src/plugins/',	// plugin path
		jr_histDebug:false,							//ajax history debugging
		jr_debug: false,								// act/deact debugging window (true=1/false=0 or level 0..3)
		jr_refreshVMenu: true,					// permanent refresh of vertical menu (true/false)
		jr_backupDB: false,							// backup yes/no (true/false)
		jr_userLevel: '000',						// user level init, supplied by CONFIG.PHP
		jr_loginload: 'All',						// 'home' reload main only or 'All' complete reload
		jr_LogoutOnUnload: false,				// 

		//do not change, for internal usage
		jr_divMain: 'divMain',
		jr_tasklst: ['ajax', 'alink', 'apage', 'aeditor', 'js'],
		jr_methods: new Array(),				// holds all classes, methods
		jr_imgCache: new Array(),				// for pre-loaded images
		jr_dbischanged: false,					//flag to identify relevant changes
		jr_base64: false,								//Base64 codeing true/false of parameter
		jr_user_pw: true,								//true userid = pw
		//jr_initLoc: '2201',							//init routine
		jr_initLoc: '1001',							//init routine
		jr_initParam: new Object(),
		//jr_initParam: {xh:1,xv:-1,cssid:1},	// hx, vx, css set in init sequence
		jr_maintLevel: '444',						// userlevel used while reloading
		jr_maintLoc: '1001',						//maintanance initi routine
		jr_maintParam: new Object(),	// hx, vx, css
		//jr_maintParam: {xh:2,xv:-1,cssid:2},	// hx, vx, css set in init sequence
		jr_projURL: 'localhost',				// supplied by CONFIG.PHP
		jr_ie_version: 0,								//IE version determined during startup
		jr_ie_bug: false,								//special processing for IE required
		jr_lowspeed: false,							//indicating a low speed line
		
		//jr_pluginlst: [],
		//list of plugins [class, initialize, styles, userlevel, compressed]
		jr_pluginlst: [['JRCmsSpeed',true,false,'0',true]
									,['JRCmsCSS',true,false,'200',true]
									 ,['JRCmsMenu',true,false,'200',true]
									 ,['JRCmsUser',true,false,'200',true]
									 ,['JRCmsEditor',true,false,'200',true]
									 ,['JRCmsImgShow',true,true,'0',false]
									 ],
		
		//SlideShow options
		//types: Standard, Lightbox, Kenburns, AutoScrolling, PushShow, Flash, FoldShow
		//types option is used to load the scripts and styles
		jr_slideshow_types : ['Lightbox', 'Kenburns', 'PushShow', 'Flash', 'FoldShow'],

		//Editor options
		jr_xinha : 'xinha/XinhaCore.js',
		jr_xinhaconf: 'xinha/my_config.js',
		jr_myXinhaArea : [{"myXinhaTextarea":{"width":"620px","height":"405px","type":"page"},
											"myXinhaScheduleTxt":{"width":"78ex","height":"150px","type":"simple"},
											"myXinhaReportsTxt":{"width":"100ex","height":"320px","type":"middle"}}],

		//Ticker options
		jr_tickerOn: false,
		jr_tknewslist: new Array(),
		jr_tknewslist: [['Wir überarbeiten die Seiten ... / Currently under revision ...','http://www.raabe-berlin.de']],
		jr_tkperiod: 80
	},

	getClassId: function() {
		return 0;
	},

	/**
	 * Constructor: initialize
	 * Creates an instance of the JRCmsInit class.
	 *
	 * @param array options
	 * @access public
	 */
	initialize: function(userlevel){	
		
		this.options.jr_userLevel = userlevel;
		this.options.jr_initParam = JSON.decode('{"xh":1,"xv":-1,"cssid":1}');
		this.options.jr_maintParam = JSON.decode('{"xh":5,"xv":14,"cssid":14}');

		//check for browser to prepare special handling
		if(Browser.Engine.trident) {
			var searchString = "MSIE";
			var index = navigator.appVersion.indexOf(searchString);
			this.options.jr_ie_version = parseFloat(navigator.appVersion.substring(index+searchString.length+1));
		
			//special processing for IE less version 7?
			if(this.options.jr_ie_version < 7) {
				//set global flag
				this.options.jr_ie_bug = true;
			}
		}
	
		//preload images
		this.preLoadImages();
		//internationalization		
		this.retrieveHelpTxt('lang/', (this.options.jr_lang+'.i18n'));
		//scripts to be loaded
		this.importScripts(this.options.jr_pluginlst, userlevel);
	},
	
	/**
	 * load the given java script files in the DOM table
	 * as well as styles declarations
	 *
	 * @param array files
	 * @access public
	 */
	importScripts: function(files,userlevel) {
		try {
			//1. load styles
			files.each(function(item, index){
				if(userlevel >= item[3] && item[2]) {
					var src = this.options.jr_pluginpath+item[0].toLowerCase()+"/css/"+item[0].toLowerCase()+".css";
					var css = new Asset.css(src);
				}
			}.bind(this));
		} catch (err) {
			alert("JRCmsInit.importScripts  error: "+err);
		}
	},
	
	/**
	 * pre-load images to show first page complete
	 * 
	 * @access public
	 */
	preLoadImages: function() {
		try{
			var param = 'a=pldimg';
			var req = new Request({
				url: 'src/jrcms.php',
				method: 'post',
				async: false,
				link: 'chain',	// requests will be chained to prevent wrong init sequence
				onSuccess: function(txt){
					var imglst = JSON.decode(txt);
					var imagelst = imglst.img;	// for debugging
					if ($type(imagelst) == 'array') {
						this.options.jr_imgCache[0] = new Object();
						imagelst.each(function(img, index){
							this.options.jr_imgCache[0][index] = new Image();
							this.options.jr_imgCache[0][index].src = img;
							this.options.jr_imgCache[1] = index+1;
						}.bind(this))
					}
				}.bind(this)
			});
			req.send(param);
		} catch(err) {
			alert("Error in jrCmsInit.preLoadImages: "+err);
		}
	},
	
	/**
	 * internationalization by loading i18n constants
	 * calling by	path :	'lang', fname: this.options.jr_lang+'.i18n'
	 *
	 * @access public
	 */
	retrieveHelpTxt: function(path, fname) {
		//retrieve help text (doesn't function original *js files with IE)
		try{
			var req = new Request({
				url: path + fname,
				method: 'get',
				evalScripts: false,
				evalResponse: false,
				async: true,
				link: 'chain',	// requests will be chained to prevent wrong init sequence
				onSuccess: function(txt){
					eval("this.options.jr_langTxt = "+txt);
				}.bind(this)
			});
			req.setHeader('Content-Type', 'text/plain; charset=utf-8');
			req.send();
		} catch(err) {
			alert("Error in jrCmsInit.retrieveHelpTxt: "+err);
		}
	}
	
});

/*!
 * Generic Class used for debugging, the methods could by
 * implemented by other classes as well, but they using 
 * the same window for output
 * TODO extension for file usage.
 *
 * @author Jens Raabe <jens@raabe-berlin.de>
 */
JRCmsLog = new Class ({
	Implements: [Options],

	options: {
		jr_debug: false,
		jr_debugColor: 'black',				// color of debugging output
		jr_debugFont: '12px',					// font size of debbuging output
		jr_debugWidth: '800px',				// debugging window width
		jr_debugHeight: '150px'				// debuggind window height
	},
	
	getClassId: function() {
		return 0;
	},

	/**
	 * Constructor: initialize
	 * Creates an instance of the JRCmsLog class.
	 *
	 * @param array options
	 * @access public
	 */
	initialize: function(options){	
		
		this.setOptions(options);
		
		//set up the debugging window
		this.crlog();

	},
	
	/**
	 * creates the log window
	 *
	 * @param none
	 * @access public
	 */
	crlog: function(){
		var logwindow = $('logWin');
		if (!logwindow && this.options.jr_debug){
			// set up the logging window
			var logDiv = new Element('div', {
										id: 'logWin',
										styles: {
											display: this.options.jr_debug ? 'block' : 'none',
											width: this.options.jr_debugWidth,
											height: this.options.jr_debugHeight,
											margin: 'auto',
											marginTop: '20px',
											padding: '5px',
											backgroundColor: 'transparent',
											overflow: 'auto',
											border: '1px solid '+ this.options.jr_debugColor,
											fontFamily: 'verdana, helvetica, serif',
											fontSize: this.options.jr_debugFont,
											color: this.options.jr_debugColor
										}});
			$$('body').grab(logDiv);
		}
	},

	/**
	 * Public method: put
	 * Write an entry in the log window
	 *
	 * @param string logtxt
	 * @access public
	 */
	put: function(logtxt, level){
		var logwindow = new Object, content = new String;
		var logging = false;
		try {
			logwindow = $('logWin');
			//convert control parameter
			if (level == undefined) level = 1;
			if (isNaN(this.options.jr_debug)) logging = (this.options.jr_debug)?(1):(0)
			else logging = this.options.jr_debug;
			
			if ((level <= logging) && (logging > 0) && logwindow) {
				var t = new Date();
				var stamp = t.getHours()+':'+
					((t.getMinutes()<10)?('0'+t.getMinutes()):(t.getMinutes()))+','+
					((t.getSeconds()<10)?('0'+t.getSeconds()):(t.getSeconds()))+'.'+
					((t.getMilliseconds()<100)
						?(((t.getMilliseconds()<10)?('00'+t.getMilliseconds()):('0'+t.getMilliseconds())))
						:(t.getMilliseconds()))+'   |';
				content = stamp + logtxt + "<br />" + logwindow.innerHTML;
				logwindow.innerHTML = content;
			}
		} catch(err) {
			alert('Error in jrCMSLog.log: '+err); 
		}
	}, 
	
	/**
	 * Public method: resetLog
	 * Clean the log
	 *
	 * @param none
	 * @access public
	 */
	logReset: function() {
		var logwindow = $('logWin');
		if (logwindow) {
			logwindow.innerHTML = "";
		}
	}
})

/* ==================================================================== */
/* jrCMS: init sequence                                                 */
/* ==================================================================== */

//(1) provide global usable function pool
window.jrCmsRshSource = new JRCmsRshSource({rsh_debugMode:true});
//(2) intialize options as well as load files depending on userlevel
window.jrCmsInit = new JRCmsInit(ulevel);	
//take over some settings from global provided variables (PHP)
jrCmsInit.options.jr_lang = jrlang;
jrCmsInit.options.jr_projURL = projURL;
jrCmsInit.options.jr_userLevel = ulevel;

//start up is splitted to improve stability
window.addEvent("domready",function(){

		//(3) init debugging
		window.jrCmsLog = new JRCmsLog(jrCmsInit.options);
		jrCmsLog.put('I>> ========== jrCMS Init Sequence started     ==============');
		jrCmsLog.put("C:I>> jrLog initialized");
		if(jrCmsInit.options.jr_imgCache[1] > 0) jrCmsLog.put("C:I>> "+jrCmsInit.options.jr_imgCache[1]+" Images pre-loaded");
		if(jrCmsInit.options.jr_ie_bug) jrCmsLog.put("C:I>> Special compatibility mode for IE"+jrCmsInit.options.jr_ie_version);
		
		//(4) instantiation of core functionality
		window.jrCMS = new JRCmsCore(jrCmsInit.options, 'jrCMS');
		
		//(5) activation of history functionality (back button)
		window.jrCmsRsh = new JRCmsRsh(jrCmsInit.options);
		jrCmsLog.put("H:I>> jrCmsRsh initialized");
		//(6) plugins will be loaded and instantiated
		var jrclasses = jrCmsInit.options.jr_pluginlst;
		jrclasses.each(function(item, index){
			//todo: we need a better solution for userlevel check
			if(jrCmsInit.options.jr_userLevel >= item[3] && item[1]) {
				var src = jrCmsInit.options.jr_pluginpath+item[0].toLowerCase()+"/"+item[0].toLowerCase();
				src+=((item[4])?(".cmp.js"):(".js"));
				var obj = item[0].toLowerCase();
				obj = obj.substr(0,2) + item[0].substr(2);
				//for loading the asset functionality is used
				var js = new Asset.javascript(src, {
					onload: function() {
						//while loaded we try to instantiate the class
						var initstr = 'window.'+obj+'= new '+item[0]+'(jrCmsInit.options,\''+obj+'\')';
						eval(initstr);
						if((index+1)>=jrclasses.length){
							//the initial loading and instantiation is finished
							jrCmsLog.put("I>> ========== jrCMS Init Sequence is finished ============");
							//(7) now call the first content by using the reload function
							var initCall = function(){
								jrCMS.reloadPage('home');
							};
							if (window.location.hash == "") initCall.delay(100);
						}
					}
				});
			}
		}.bind(this));
});

window.onunload = function() {
	// control end of image show
	if($type(window.jrCmsMyImgShow)) jrCmsMyImgShow.destroy();
	// start async DB backup
	if(jrCmsInit.options.jr_dbischanged) jrCMS.backup();
	// logout
	if(jrCmsInit.options.jr_LogoutOnUnload) jrCmsLog.putout('out');
};