/**
* Provides functionality für cEasy on port usage
*
* @package Ceasy_Core
* @author Ralf Glaser
*
*/

cEasy=function() {

	/**
	 * protected members
	 **/
	var that={};
	var _url={
		'print':'http://www.schorndorf.de/ceasy/modules/cms/print.php5',
		'recommend':'http://www.schorndorf.de/ceasy/modules/cms/recommend.php5',
		'icons':'http://www.schorndorf.de/ceasy/etc/icons/core/usage',
		'js':'http://www.schorndorf.de/ceasy/etc/remote/js/core/usage',
		'css':'http://www.schorndorf.de/ceasy/etc/remote/css'
	};
	var _loaded={};
	var _loadCallback={};
	var _printWin;
	var _recommendWin;
	var _curtainDiv=false;
	var _curtainDivCss = {
		'background-color':'#000000',
		'position':'absolute',
		'top':'0px',
		'left':'0px',
		'opacity':0.8,
		'z-index':1000000000
	};
	var _loadingDiv=false;
	var _loadingImageUrl=_url['icons']+'/cEasyJs/loading.gif';
	var _loadingDivCss = {
		'position':'absolute',
		'width':32,
		'height':32,
		'padding':10,
		'z-index':1000000001
	};


	/**
	 * public members
	 **/


	/**
	 * protected methods
	 **/
	// -------------------------------------------------------------------
	_addScript=function (name, url, callback, forceWriteDocument, encoding) {

		encoding= encoding || 'utf-8';
		var writeDocument= forceWriteDocument || false;

		_loadCallback[name]=(callback ? callback : function() {});
		var _scriptId=_generateScriptNodeId(name);
		var _scriptNode;

		if (writeDocument) {

			document.write('<script id="'+_scriptId+'" type="text/javascript" charset="'+encoding+'"></script>');
			_scriptNode=document.getElementById(_scriptId);

		} else {

			_scriptNode=document.createElement('script');
			_scriptNode.setAttribute('type', 'text/javascript');
			_scriptNode.setAttribute('id', _scriptId);
			_scriptNode.setAttribute('charset', encoding);
			var _heads=document.getElementsByTagName('head');
			if (typeof(document.readyState)!='undefined' && typeof(document.attachEvent)!='undefined' && !window.opera) { // append scriptNode after loading to avoid IE7/8 bug: (see http://support.microsoft.com/kb/927917/en and http://blogs.msdn.com/ie/archive/2008/04/23/what-happened-to-operation-aborted.aspx)
				if (document.readyState=='complete') {
					setTimeout(function () {_heads[0].appendChild(_scriptNode);}, 1); // Bugfix for IE: script is not executed unless it is appended with delay (dunno why!?)
				} else {
					var _appendScriptNode=function () {
						if (document.readyState=='complete') {
							_heads[0].appendChild(_scriptNode);
							document.detachEvent('onreadystatechange', _appendScriptNode);
						}
					}
					document.attachEvent('onreadystatechange', _appendScriptNode);
				}
			} else {
				_heads[0].appendChild(_scriptNode);
			}
		}

		if (typeof(_scriptNode.addEventListener)!='undefined') { // w3c

			_scriptNode.addEventListener('load', function () {that.scriptLoaded(name);}, false);

		} else {// IE bugfix: attaching load-event on an script-node won't work in IE, so we use onreadystatechange

			if (_scriptNode.readyState=='complete') {
				that.scriptLoaded(name);
			} else {
				_scriptNode.onreadystatechange=function () {
					if (_scriptNode.readyState=='complete') {
						_scriptNode.onreadystatechange='';
						that.scriptLoaded(name);
					}
				}
			}

		}

		_scriptNode.setAttribute('src', url); // set src AFTER attaching onload-event is important, especially for safari

	}

	// -------------------------------------------------------------------
	_addStyle=function (name, url, forceWriteDocument) {

		var writeDocument= forceWriteDocument || false;

		var _styleId=_generateStyleNodeId(name);

		if (writeDocument) {

			document.write('<link id="'+_scriptId+'" href="'+url+'" type="text/css" rel="stylesheet"></link>');

		} else {

			var _newStyleNode=document.createElement('link');
			_newStyleNode.setAttribute('type', 'text/css');
			_newStyleNode.setAttribute('id', _styleId);
			_newStyleNode.setAttribute('href', url);
			_newStyleNode.setAttribute('rel', 'stylesheet');
			setTimeout(function () { // Bugfix for IE6: append with delay, otherwise style will not be executed in IE6. DO NOT ASK WHY!
				var _heads=document.getElementsByTagName('head');
				try {_heads[0].appendChild(_newStyleNode);} catch (e) {} // this may fail in IE7 if head is not yet closed (see http://support.microsoft.com/kb/927917/en)
			}, 100);

		}

	}

	// -------------------------------------------------------------------
	_generateScriptNodeId=function (name) {

		return 'cEasyScript_'+name.replace(/[^0-9a-zA-Z_]/g, '_');

	}

	// -------------------------------------------------------------------
	_generateStyleNodeId=function (name) {

		return 'cEasyStyle_'+name.replace(/[^0-9a-zA-Z_]/g, '_');

	}

	/**
	 * public methods
	 **/

	// -------------------------------------------------------------------
	that.getUrl=function (name) {

		return _url[name];

	}

	// -------------------------------------------------------------------
	that.scriptLoaded=function (name) {

		var _success=true;

		if (_loaded[name]===0 && _loadCallback[name]) {

			try {
				_loadCallback[name]();
				_success=true;
				_loaded[name]=true;
				_loadCallback[name]=false;
			} catch (e) {
				_success=false;
			}

		}

		return _success;

	}

	// -------------------------------------------------------------------
	that.load=function (name, callback, forceWriteDocument) {

		name=(name.toLowerCase()=='jquery' ? 'jQuery' : name);
		name=(name.toLowerCase()=='ceasy.popupimg' ? 'cEasy.popupImg' : name);
		name=(name.toLowerCase()=='ceasy.popupiframe' ? 'cEasy.popupIframe' : name);
		name=(name.toLowerCase()=='datepicker' ? 'datepicker' : name);
		name=(name.toLowerCase()=='prototype' ? 'prototype' : name);
		name=(name.toLowerCase()=='scriptaculous' ? 'scriptaculous' : name);
		name=(name.toLowerCase()=='lightbox' ? 'lightbox' : name);

		if (_loaded[name]) {

			if (callback) callback();

		} else if (_loaded[name]===0) {

			window.setTimeout(function() {
				that.load(name, callback, forceWriteDocument);
			}, 500);

		} else {

			_loaded[name]=0;

			if (name=='jQuery') {

				_addScript(name, _url['js']+'/jquery.js', callback, forceWriteDocument);

			} else if (name=='prototype') {

				_addScript(name, _url['js']+'/prototype.js', callback, forceWriteDocument);

			} else if (name=='scriptaculous') {

				this.load('prototype', function () {
					_addScript(name, _url['js']+'/scriptaculous.js', callback);  // no not call with forceWriteDocument, it won't work correctly when called by a callback
				}, forceWriteDocument);

			} else if (name=='lightbox') {

				this.load('scriptaculous', function () {
					_addScript(name, _url['js']+'/lightbox.js', callback);  // no not call with forceWriteDocument, it won't work correctly when called by a callback
				}, forceWriteDocument);

			} else if (name=='cEasy.popupImg') {

				this.load('jQuery', function () {
					_addScript(name, _url['js']+'/ceasy/cEasy.p0pupImg.js', callback); // no not call with forceWriteDocument, it won't work correctly when called by a callback
				}, forceWriteDocument);

			} else if (name=='cEasy.popupIframe') {

				this.load('jQuery', function () {
					_addScript(name, _url['js']+'/ceasy/cEasy.p0pupIframe.js', callback); // no not call with forceWriteDocument, it won't work correctly when called by a callback
				}, forceWriteDocument);

			} else if (name=='datepicker') {

				this.load('jQuery', function () {
					_addStyle(name, _url['css']+'/jquery/jquery-ui.datepicker.css', false); // no not call with forceWriteDocument, it won't work correctly when called by a callback
					_addScript(name, _url['js']+'/jquery-ui.datepicker.js', callback); // no not call with forceWriteDocument, it won't work correctly when called by a callback
				}, forceWriteDocument);

			}

		}

	}

	// -------------------------------------------------------------------
	that.print=function (useWin, width, height) {

		useWin= (useWin===false ? false : true);
		width= width || 680;
		height= height || 500;

		if (useWin) {
			_printWin=window.open(this.getUrl('print')+location.search, 'cEasyPrintWin', 'top=10, left=10, width='+width+', height='+height+', status=no, resizable=yes, scrollbars=yes');
			_printWin.focus();
		} else {
			that.popupIframe(this.getUrl('print')+location.search, width, height);
		}

	};

	// -------------------------------------------------------------------
	that.recommend=function (useWin, width, height) {

		width= width || 600;
		height= height || 600;

		if (useWin) {
			_recommendWin=window.open(this.getUrl('recommend')+location.search, 'cEasyRecommendWin', 'top=10, left=10, width='+width+', height='+height+', status=no, resizable=yes, scrollbars=yes');
			_recommendWin.focus();
		} else {
			that.popupIframe(this.getUrl('recommend')+location.search, width, height);
		}

	};

	// -------------------------------------------------------------------
	that.showCurtain=function (bindEvents, doNotShowLoadingDiv) {

		doNotShowLoadingDiv= doNotShowLoadingDiv || false;

		this.load('jQuery', function () {

			if (doNotShowLoadingDiv) {
				if (_loadingDiv) {
					_loadingDiv.hide();
				}
			} else {

				if (_loadingDiv) {
					_loadingDiv.show();
				} else {
					/* firefox-opacity-hack:
					 * ---------------------
					 * It is no good idea to append imgDiv and loadingDiv to this.curtainDiv, cause then imgDiv would inherit
					 * opacity of this.curtainDiv (at least in FF) and there is no way to restore none-opacity for imgDiv.
					 * So we append imgDiv and loadingDiv to body
					 */
					_loadingDiv=jQuery('<div id="cEasyLoadingDiv"><img src="'+_loadingImageUrl+'" /></div>').css(_loadingDivCss).appendTo('body');
				}

			}

			if (_curtainDiv) {
				_curtainDiv.show();
			} else {
				_curtainDiv=jQuery('<div id="cEasyOverlayDiv"></div>').css(_curtainDivCss).appendTo('body');
			}
			that.refitCurtain(true);

			if (bindEvents) {
				for (var i=0; i < bindEvents.length; i++) {
					_curtainDiv.bind(bindEvents[i]['type'], bindEvents[i]['func']);
				}
			}

		});

	}

	// -------------------------------------------------------------------
	that.refitCurtain=function (doNotHideLoadingDiv) {

		doNotHideLoadingDiv= doNotHideLoadingDiv || false;
		_curtainDiv.css({ // refit size
			'width':jQuery(document).width(),
			'height':jQuery(document).height()
		});
		if (_loadingDiv) {
			_loadingDiv.css({ // refit position
				'left':jQuery('html').scrollLeft()+Math.floor((jQuery(window).width()-32)/2)-10,
				'top':jQuery('html').scrollTop()+Math.floor((jQuery(window).height()-32)/2)-10
			});
			if (!doNotHideLoadingDiv) {
				_loadingDiv.hide();
			}
		}

	}

	// -------------------------------------------------------------------
	that.hideCurtain=function (unbindEvents) {

		if (typeof('jQuery')!='undefined') {

			if (_loadingDiv) {
				_loadingDiv.hide();
			}
			if (_curtainDiv) {
				_curtainDiv.fadeOut();
			}
			if (unbindEvents) {
				for (var i=0; i < unbindEvents.length; i++) {
					_curtainDiv.unbind(unbindEvents[i]['type'], unbindEvents[i]['func']);
				}
			}

		}

	}

	// -------------------------------------------------------------------
	that.popupImg=function (url, groupClass) { // dummy that does load implementation and replaces itself

		var _name='cEasy.popupImg';
		if (_loaded[_name] || _loaded[_name]===0) {
			alert('Beim Nachladen der Funktion »'+_name+'« ist ein Fehler aufgetreten');
			this.hideCurtain([{
				'type':'click.loadPopupImg',
				'func':null
			}]);
		} else {
			this.showCurtain([{
				'type':'click.loadPopupImg',
				'func':function () {
					that.hideCurtain([{
						'type':'click.loadPopupImg',
						'func':null
					}]);
				}
			}]);
			this.load(_name, function () {
				that.popupImg(url, groupClass);
			});
		}
	}

	// -------------------------------------------------------------------
	that.popupIframe=function (url, width, height, callback) { // dummy that does load implementation and replaces itself

		var _name='cEasy.popupIframe';
		if (_loaded[_name] || _loaded[_name]===0) {
			alert('Beim Nachladen der Funktion »'+_name+'« ist ein Fehler aufgetreten');
			this.hideCurtain([{
				'type':'click.loadPopupIframe',
				'func':null
			}]);
		} else {
			this.showCurtain([{
				'type':'click.loadPopupIframe',
				'func':function () {
					that.hideCurtain([{
						'type':'click.loadPopupIframe',
						'func':null
					}]);
				}
			}]);
			this.load(_name, function () {
			 	that.popupIframe(url, width, height, callback);
			});
		}
	}


	that.load('jQuery', false, true);


	return that;

}();

function cEasyPrint() { // deprecated (for backward-compatibility only)
	return cEasy.print();
}

function cEasyRecommend() { // deprecated (for backward-compatibility only)
	return cEasy.recommend();
}



