/**
* Framework
*
* @version		1.0
*
* @license		GNU Lesser General Public License
* @author		Gerrit Böttcher <gerrit.boettcher [at] gmail.com>
* @copyright	2007 fresh frames GmbH & Co. KG <http://www.freshframes.com>
*/

var Framework = {};

Framework.Base = new Class({
	options: {
		pageRequest: '',
		notificationElement: 'notification',
		loadingElement: 'loading', // this is also the controller
		apiURL: 'api/api.php?',
		contentArea: 'content',
		defaultController: 'portal',
		scrollDiv: ''
	},
	initialize: function(options) {
		if (!options) options = {}; // prevent js errors

		if (options.defaultController) this.options.defaultController = options.defaultController; // this must be set at first
		this.defaultController = this.options.defaultController;

		this.notificationElement = (options.notificationElement?options.notificationElement:this.options.notificationElement);
		if (!$(this.notificationElement)) this.notificationElement = null;

		this.loadingElement = (options.loadingElement?options.loadingElement:this.options.loadingElement);
		if ($(this.loadingElement) && $(this.loadingElement + '_content')) {
			this.loadingElementContent = this.loadingElement + '_content';
		} else {
			this.loadingElement = null;
			this.loadingElementContent = null;
		}


		this.pageRequest = (options.pageRequest)?options.pageRequest:(window.location.hash.length > 1?window.location.hash.substr(1):this.defaultController);

		this.loadingStatus = false;
		this.notifyStatus = false;

		this.apiURL = (options.apiURL?options.apiURL:this.options.apiURL);

		this.content = (options.contentArea?options.contentArea:this.options.contentArea);
		if ($(this.content)) this.content = $(this.content);
		else this.content = null;

		if ($('cssSection')) this.currentCSS = $('cssSection');
		else this.currentCSS = null;

		this.scrollDiv = (options.scrollDiv?options.scrollDiv:this.options.scrollDiv);
		if ($(this.scrollDiv)) {
			this.scrollDiv = $(this.scrollDiv);
			this.scrollDivTop = this.scrollDiv.getStyle('top').toInt();
		} else this.scrollDiv = null;

		this.fetchLinks();
		this.savedContent = '';
		this.build();
	},
	build: function() {
		window.addEvent('scroll', this.scroll.bindWithEvent(this));
		//this.getLoadingTemplate();
	},
	fetchLinks: function() {
		// Fetch all Links
		$$("a[href*=#]").removeEvents();
		$each( $$("a[href*=#]"), function( item, index ) {
			item.addEvent('click', this.getContent.bindWithEvent(this, item.hash ) );
		}, this );
		//$$("a[href*=#]").addEvent('click', this.getContent.bindWithEvent(this, this.href));
	},
	getLoadingTemplate: function() {
		if (this.loadingElement == null) alert('Loading div not avalible');
		else {
			var _this = this;
			this.AJAXrequest = new Ajax(this.apiURL + 'type=html', {
				method: 'get',
				data: _this.loadingElement,
				onComplete: function(retData) {
					$(_this.loadingElementContent).innerHTML = retData;
					_this.fetchLinks();
					_this.getContent();
				}
			}).request();
		}
	},
	getContent: function() {
		if (this.content == null) alert('Content div not avalible');
		else {
			if (this.getContent.arguments.length > 0) {
				if (this.getContent.arguments.length > 1) {
					this.pageRequest = this.getContent.arguments[1].length > 1?this.getContent.arguments[1].substr(1):this.defaultController;
				} else this.pageRequest = this.defaultController;
			}

			this.throwLoading();

			var _this = this;

			this.AJAXrequest = new Ajax(this.apiURL + 'type=html', {
				method: 'get',
				data: _this.pageRequest,
				onComplete: function(retData) {
					if (retData == 'error') {
						_this.throwNotification('Ung&uuml;ltiger Befehl');
						_this.getContent(null, '#error');
					}
					else if(retData == 'htmlerror') {
						_this.throwNotification('Ung&uuml;ltiger Aufruf');
						_this.getContent(null, '#error');
					}
					else {
						var firstLine = retData.indexOf("\n");
						var useCSS = retData.substr(0, firstLine);

						_this.switchCSS(useCSS);
						_this.content.innerHTML = retData.substr(firstLine);
						_this.fetchLinks();
					}
					_this.throwLoading();
					_this.handleSpecials();
				}
			}).request();
		}
	},
	handleSpecials: function() { // this is special code only for betanet!
		// save tiny
		if (this.content.innerHTML.indexOf('id="tiny_wysiwyg"') > 0) {
			this.setupTiny();
			this.savedContent = $('tiny_wysiwyg').value;
		}

		if ($('frm_login')) { // handle login form
			
			$('frm_login').addEvent('submit', function(e) {
				new Event(e).stop();
				this.throwLoading();
				var _this = this;
				$('frm_login').send({
					onComplete: function(resp) {
						_this.throwLoading();
						if (resp == 'false') {
							$('frm_log').innerHTML = 'Benutzername oder Passwort ist falsch';
						} else {
							_this.getContent(null, '#' + _this.pageRequest);
						}
					}
				});

			}.bind(this));

			$('frm_username').addEvent('focus', function() {
				if (this.value == 'Benutzername') {
					this.selectionStart = 0;
					this.selectionEnd = this.value.length;
				}
			});

			$('frm_password').addEvent('focus', function() {
				if (this.value == '********') {
					this.selectionStart = 0;
					this.selectionEnd = this.value.length;
				}
			});
		}
	},
	throwNotification: function(text) {
		if (this.notificationElement == null) alert('Notify div not avalible');
		else {
			if (!this.notifyStatus) {
				this.notifyStatus = true;

				if (this.throwNotification.arguments.length > 1) {
					dura = this.throwNotification.arguments[1];
				} else dura = 3000;

				this.fxNotify = $(this.notificationElement).effects({duration: 3000, transition: Fx.Transitions.Quart.easeOut});

				$(this.notificationElement).setStyle('opacity', 0);
				$(this.notificationElement).setStyle('display', 'block');
				$(this.notificationElement).innerHTML = text;
				if (dura == 0) {
					this.fxNotify.start({
					'opacity': .9
					});
				} else {
					var _this = this;
					this.fxNotify.start({
					'opacity': .9
					}).chain(function(){
						this.start.delay(dura, this, {
						'opacity': 0
						});
					}).chain(function() {
						_this.notifyStatus = false;
					});
				}
			}
		}
	},
	throwLoading: function() {
		if (this.loadingElement == null) alert('loading div not avalible');
		else {
			if ($(this.loadingElement) != false && $(this.loadingElementContent) != false) {
				this.setLoadingStatus((this.loadingStatus == true?false:true));
				$(this.content).setStyle('display', (this.loadingStatus == true?'none':'block'));
				$(this.loadingElement).setStyle('display', (this.loadingStatus == true?'block':'none'));
				$(this.loadingElementContent).setStyle('display', (this.loadingStatus == true?'block':'none'));
			} else alert("Folgende DIV-Elemente fehlen:\n" + this.loadingElement + " & " + this.loadingElementContent);
		}
	},
	setLoadingStatus: function(state) {
		this.loadingStatus = state;
	},
	switchCSS: function(usefile) {
		if (this.currentCSS != null) {
			if (this.currentCSS) this.currentCSS.remove();
			new Asset.css('css/' + usefile + '.css', {id: 'cssSection'});
			this.currentCSS = $('cssSection');
		}
	},
	setupTiny: function() {
		tinyMCE.execCommand("mceAddControl", true, 'tiny_wysiwyg');
	},
	kill: function() {
		alert(tinyMCE.get('tiny_wysiwyg'));
		var tinyValue = $('tiny_wysiwyg').value;
		if (freshFramework.savedContent != tinyValue) {
			return "Änderungen wirklich verwerfen?";
		} else {
			return freshFramework.savedContent + "\n\nvs\n\n" + tinyValue;
		}
	},
	clickHandle: function(e) {
		//alert('click');
		/*var allElements = $('content').getChildren();
		$each ( allElements, function(item, index) {
		if (e.target === item) {
		alert('Im content geklickt');
		}
		});*/
		//alert(allElements + "\n\nTarget: " + e.target);
		//alert(e.target + "\n" + e.target.id + " | " + e.target.className);
	},
	scroll: function(event) {
		event = new Event(event);
		if (this.scrollDiv != null) {
			if (window.getScrollTop() > this.scrollDivTop) { /* scroll */
				this.scrollDiv.setStyle('top', window.getScrollTop());
			} else if(window.getScrollTop() < this.scrollDivTop) {
				if (this.scrollDiv.getStyle('top').toInt() != this.scrollDivTop) { /* reset */
					this.scrollDiv.setStyle('top', this.scrollDivTop);
				}
			}
		}
	}
});

Framework.Base.implement(new Events);
Framework.Base.implement(new Options);