/**
* 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 = new Class({
    
    Implements: [ Options, Events ],
    tunnel: null,
    type: 0,

	options: {
		pageRequest: '',
		loadingElement: 'loading', // this is also the controller
		apiURL: 'api/api.php?',
		contentArea: 'content',
		defaultController: 'show:page:aktuell',
		fetchLinks: true,
		requestTimer: 0
	},
	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.loadingElement = (options.loadingElement?options.loadingElement:this.options.loadingElement);

		this.pageRequest = (options.pageRequest)?options.pageRequest:(window.location.hash.length > 1?window.location.hash.substr(1):this.defaultController);

		this.loadingStatus = false;
		this.tinyStarted = 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;

		this.requestTimer = (options.requestTimer?options.requestTimer:this.options.requestTimer);
		this.periodical = null;
		
		this.notification = new Roar({
			//position: 'lowerRight'
		});
		
		this.calendar = new Roar({
			position: 'upperLeft',
			duration: 0, 
			container: 'content',
			onShow: function( item ) {
				item.store('roar:offset'); // offset loeschen da wir nur immer 1 roar haben
				
				//wir wollen nur 1 anzeigen alle anderen verschwinden automatisch beim oeffnen des naechsten.
				
				if ( freshFramework.calendar.items.length > 1 ) {
					for ( i = 0; i < (freshFramework.calendar.items.length - 1); i++) {
						this.remove( freshFramework.calendar.items[i] );
					} 
				}
				
			}
		});

		if (options.fetchLinks || this.options.fetchLinks) this.fetchLinks();
		this.savedContent = '';
		this.build();
	},
	build: function() {
		$clear(this.periodical);
		if ($('nav') && this.requestTimer > 0) this.periodical = this.jsonRequest.periodical(this.requestTimer * 1000, this);
		
		this.getContent();
	},
	fetchLinks: function() {
		// Fetch all Links
		$$("a[href*=#]").removeEvents();
		$each( $$("a[href*=#]"), function( item, index ) {
			item.addEvent('click', this.getContent.bindWithEvent(this, item.hash ) );
		}, this );

	},
	jsonRequest: function() {
		// this Request is especially for the NAV
		if ($('nav') && this.requestTimer > 0 ) {
			var _this = this;
			if (request) request.cancel();
			var request = new Request.JSON({
				url: _this.apiURL + 'type=json&user:periodicalRequest:' + freshFramework.pageRequest + ':' + $time(),
				method: 'get',
				onComplete: function(jObj) {
					if (jObj.error) {
						$clear(_this.periodical);
					} else {
						// Setup the NAV

						if (jObj.docTitle) {
							document.title = jObj.docTitle;
						}
						_this.fetchLinks();
					}
				}
			}).send();
		}
	},
	reloadNav: function() {
		if ($('nav')) {
			var ajax = new Request({
				method: 'get', 
				data: 'user:buildNav',
				update: $('nav'),
				onComplete: function() {
					freshAccordion = new Accordion($$('h3.toggler_left'), $$('div.element_left'), {
						start: 'first-open',
						onActive: function(item) { $(item).setStyle('background', 'url(images/h3_active.png) left no-repeat'); },
						onBackground: function(item) { $(item).setStyle('background', 'url(images/h3_inactive.png) left no-repeat'); }
						
					}).display(0);
				}
			}).get(this.apiURL + 'type=html');
		}
	},
	evalRequest: function(vars) {
		var _this = this;

		this.AJAXrequest = new Request({
			method: 'get',
			data: vars,
			evalResponse: true
		}).get(this.apiURL + 'type=eval');
	},
	updateTiny: function( vars ) {
		var _this = this;

		this.AJAXrequest = new Request({
			method: 'get',
			data: vars,
			onComplete: function( ret ) {
				if ( _this.tinyInstance ) {
					_this.tinyInstance.setProgressState(0);
					_this.tinyInstance.setContent( ret );
				}
			}
		}).get(this.apiURL + 'type=eval');
	},
	clearCalendar: function() {
		if ( this.calendar.items.length > 0 ) {
			this.calendar.remove( this.calendar.items[0] );
			if ( this.calendar.items.length > 0 ) this.clearCalendar();
		}
	},
	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;
			}
			
			if ( this.calendar.items.length > 0 ) {
				this.clearCalendar(); 
			}

			this.throwLoading();

			var _this = this;

			this.AJAXrequest = new Request({
				method: 'get',
				data: _this.pageRequest,
				onComplete: function(retData) {
					if (retData == 'error') {
						_this.getContent(null, '#error');
					}
					else if(retData == 'htmlerror') {
						_this.getContent(null, '#error:html');
					}
					else {
						_this.content.innerHTML = retData;
						_this.fetchLinks();
					}
					_this.throwLoading();
					_this.handleSpecials();
					_this.jsonRequest(); // refresh NAV
					if ( _this.pageRequest.indexOf('login') > -1 ) {
						_this.reloadNav();
					}
				}
			}).get(this.apiURL + 'type=html');
		}
	},
    calDel: function ( id ) {
        var _this = this;
        
        new Request({
            method: 'post',
            evalResponse: true,
            data: 'action=calDel&id=' + id,
            onFailure: function() {
                _this.notification.alert('Fehler beim Loeschen', 'Es ist ein Fehler beim Loeschen aufgetreten!');
            }
        }).post( _this.apiURL );
        return true;
    },
	handleSpecials: function() { // specials for the page
		// normal tips
		$$('.tipps').removeEvents();
		var toolTips = new Tips($$('.tipps'), {
			className: 'ctool'
		});

		// init tiny
		if ( $( 'frm_inh' ) &&  $('tiny_wysiwyg') && $('frm_id') && !this.tinyStarted && $( 'lbl_save' ) ) {
			tinyMCE.execCommand("mceAddControl", true, 'tiny_wysiwyg');
			this.tinyStarted = true;
			this.tinyInstance = tinyMCE.get('tiny_wysiwyg');
			this.tinyInstance.setProgressState( 1 );
			this.updateTiny( 'admin:content:fetch:' + $( 'frm_id' ).value );
		
			// save button for tiny
			$( 'lbl_save' ).addEvent( 'click', function( e ) {
				
				this.tinyInstance.setProgressState( 1 );
				var _this = this;
				
				$('tiny_wysiwyg').value = this.tinyInstance.getContent(); // load the tiny into the textarea
				
				new Request({
					method: 'post',
					evalResponse: true,
					data: 'action=saveContent&id=' + $( 'frm_id' ).value + '&' + $( 'frm_inh' ).toQueryString(),
					onFailure: function() {
						_this.tinyInstance.setProgressState( 0 );
						_this.notification.alert('Fehler beim Speichern', 'Es ist ein Fehler beim Speichern aufgetreten!');
					},
					onComplete: function() {
						_this.tinyInstance.setProgressState( 0 );
					}
				}).post( _this.apiURL );
				
			}.bind( this ));
		}

        if ( $( 'frm_caladd' ) ) {

            $( 'lbl_save' ).addEvent( 'click', function( e ) {

                var _this = this;

                new Request({
                    method: 'post',
                    evalResponse: true,
                    data: 'action=calAdd&' + $( 'frm_caladd' ).toQueryString(),
                    onFailure: function() {
                        _this.notification.alert('Fehler beim Laden', 'Es ist ein Fehler beim Laden der Aktion aufgetreten!' );
                    }
                }).post( _this.apiURL );
                
            }.bind( this ) );


        }

		/**
		* Handle AJAX Forms
		*/
		if ($('frm_loggedout')) {
			// logout successfull
			freshAccordion.display(0);
			freshAccordion.togglers[ freshAccordion.togglers.length - 1 ].destroy();
			freshAccordion.elements[ freshAccordion.elements.length - 1 ].destroy();
		}

		if ($('frm_login')) { // handle login form
			$('frm_login').addEvent('submit', function(e) {
				new Event(e).stop();
				this.throwLoading();
				var _this = this;
				
				$('frm_login').set('send', {
					method: 'post',
					url: 'api/api.php',
					onComplete: function(resp) {
						_this.throwLoading();	
						if (!resp || resp == '' || resp == 'false') {
							$('frm_log').innerHTML = '<p>Benutzername oder Passwort ist falsch</p>';
						} else {
							_this.notification.alert('Eingeloggt!', 'Sie haben sich erfolgreich angemeldet!');
							_this.reloadNav();
							_this.getContent(null, '#' + _this.pageRequest);
						}
					}
				});
				
				$('frm_login').send();
				
			}.bind(this));
		}
		
		if ($('frm_userEdit')) {
				$('frm_userEdit').addEvent('submit', function(e) {
					new Event(e).stop();
					$(this.loadingElement).setStyle('display', 'block');
					$('frm_userEdit').set( 'send', {
						url: 'api/api.php',
						evalResponse: true
					}).send();
				}.bind(this));
			}
			
			if ($('frm_groupName')) {
				$('frm_groupName').addEvent('keydown', function(e) {
					event = new Event(e);
					if (event.key == 'enter') {
						event.stop();
						var gid = $('frm_groupName').name.substr(3);
						if ($('frm_groupName').value.length > 0) {
							$(this.loadingElement).setStyle('display', 'block');
							this.evalRequest('admin:users:setGroupName:' + gid + ':' + escape($('frm_groupName').value));
						} else this.notification.alert('Fehler', 'Der Gruppenname kann nicht leer sein.');
					}
				}.bind(this));
			}
			
			if ($('frm_newUser')) {
				$('frm_newUser').addEvent('keydown', function(e) {
					event = new Event(e);
					if (event.key == 'enter') {
						event.stop();
						if ($('frm_newUser').value.length > 0) {
							$(this.loadingElement).setStyle('display', 'block');
							this.evalRequest('admin:users:addUser:' + escape($('frm_newUser').value));
						} else this.notification.alert('Fehler', 'Der Benutzername kann nicht leer sein.');
					}
				}.bind(this));
			}
			
			
			if ($('frm_newGroup')) {
				$('frm_newGroup').addEvent('keydown', function(e) {
					event = new Event(e);
					if (event.key == 'enter') {
						event.stop();
						if ($('frm_newGroup').value.length > 0) {
							$(this.loadingElement).setStyle('display', 'block');
							this.evalRequest('admin:users:addGroup:' + escape($('frm_newGroup').value));
						} else this.notification.alert('Fehler', 'Der Gruppenname kann nicht leer sein.');
					}
				}.bind(this));
			}

	},
	throwLoading: function() {
		if (this.loadingElement == null) {
			//alert('loading div not avalible');
		} else {
			if ($(this.loadingElement) != 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'));
			}
		}
	},
	setLoadingStatus: function(state) {
		this.loadingStatus = state;
	},
	switchGroup: function(direction, userID, groupID, groupTitle) {

		var fromDiv = (direction == 'asg') ? 'avg_' + groupID : 'asg_' + groupID;
		var insideDiv = (direction == 'asg') ? 'assignedGroups' : 'avalibleGroups';
		var toDiv = (direction == 'asg') ? 'asg_' + groupID : 'avg_' + groupID;
		var toDirection = (direction == 'asg') ? 'avg' : 'asg';

		if (direction == 'asg') {
			this.evalRequest('admin:users:attachGroup:' + userID + ':' + groupID);
		} else {
			this.evalRequest('admin:users:detachGroup:' + userID + ':' + groupID);
		}

		if ( $(fromDiv) ) $(fromDiv).remove();

		var newEl = new Element('p').setProperty('id', toDiv).injectInside(insideDiv);
		var newA = new Element('a').setProperties({
			onclick: '$(freshFramework.loadingElement).setStyle(\'display\', \'block\'); freshFramework.switchGroup(\'' + toDirection + '\', ' + userID + ', ' + groupID + ', \'' + groupTitle + '\'); return false;'
		}).setStyle('cursor', 'pointer').setHTML(groupTitle).injectInside(newEl);
	}
});


