var Popup = null;
Event.observe(window, 'load', function(evt){
	Popup = new PopupClass();
});

var PopupClass = Class.create();
Object.extend(PopupClass.prototype, {

    /**
     * base path for ajax requests
     */
    basePath : '',
    
    /**
     * contains all relevant HtmlElements
     */
    obj : null,

	/**
	 * Initializes this instance
	 */
	initialize : function(){
       
        // find and set base path
        this.toolkit = new Toolkit();
        this.basePath = this.toolkit.basePath();

        /**
         * create elements in the following structure an append them to the body
         *
         * div#popupOverlay
         * div#popupWrap
         *     div#popup
         *         div#popupContainer
         *             div#popupIndicator
         *                 img
         *             div#popupHeader.header
         *             div#popupUpdate.main
         */
        this.obj = new Object();
        this.obj.overlay = Builder.node('div', {'id':'popupOverlay'});
        this.obj.wrap = Builder.node('div', {'id':'popupWrap'});
        this.obj.indicator = Builder.node('div', {'id':'popupIndicator'}, [ Builder.node('img', {'src':this.basePath+'img/ajaxindicator-popup.gif'}) ]);
        this.obj.header = Builder.node('div', {'id':'popupHeader'});
        this.obj.update = Builder.node('div', {'class':'main', 'id':'popupUpdate'});
        this.obj.popup = Builder.node('div', {'id':'popup'}, [
        	Builder.node('div', {'id':'popupContainer'}, [
	        	this.obj.indicator,
        		this.obj.header, 
        		this.obj.update
        	])
        ]);
        this.obj.wrap.appendChild(this.obj.popup);
        
        // append to document body
        document.body.appendChild(this.obj.overlay);
        document.body.appendChild(this.obj.wrap);
        
        // make extended elements of these
        this.obj.overlay = $(this.obj.overlay);
        this.obj.wrap = $(this.obj.wrap); 
        this.obj.indicator = $(this.obj.indicator); 
        this.obj.header = $(this.obj.header); 
        this.obj.update = $(this.obj.update); 
        this.obj.popup = $(this.obj.popup); 

		// format 
		this.position();
        this.obj.overlay.setOpacity(0.5);
        this.obj.header.hide();
        this.obj.update.hide();
        this.obj.overlay.hide();
        this.obj.wrap.hide();
        
        // add event observer which calls this.close() on a click outside the div#popup
        Event.observe(this.obj.wrap, 'click', this.onClick.bindAsEventListener(this));
        
        // reposition on resizing the window
        Event.observe(window, 'resize', this.position.bindAsEventListener(this));

	},

	/**
	 * Positions the popup in the viewport center
	 */
	position : function(){
		// center #popup
		var dim = document.viewport.getDimensions();

		// resize popup update div if popup is too big
		if( this.obj.update.getHeight() >= dim.height ){
			this.obj.update.setStyle({'height': (dim.height-100) + 'px'});
		}
		
		// center popup in viewport
		var ml = Math.round((dim.width - this.obj.popup.getWidth()) / 2);
		var mt = Math.round((dim.height - this.obj.popup.getHeight()) / 2);
		this.obj.popup.style.marginLeft = ml + 'px';
		this.obj.popup.style.marginTop = mt + 'px';
		
		
	},

    /**
     * Displays content from an ajax request 
     *
     * @param string url URL to request
     * @param string title for popup 
     */
	ajax : function(url, title){
		var _this = this;
		new Ajax.Updater('popupUpdate', url, {
    	    asynchronous:true, 
    	    evalScripts:true, 
    	    onLoading: function(){
                _this.obj.overlay.show();
                _this.obj.wrap.show();
                _this.obj.indicator.show();
                _this.obj.header.hide();
                _this.obj.update.hide();
                _this.selects(false);
                _this.position();
            },
            onComplete: function(trans){
                _this.addHeader(title);
                _this.obj.overlay.show();
                _this.obj.wrap.show();
                _this.obj.update.show();
                _this.obj.indicator.hide();
                _this.position();
            }
        });
    	
    	return false; // for onclick on anchors
    },

    /**
     * Displays the confirmation dialogue
     *
     */
    confirm : function(url, id, title, options) {
        this.obj.update.update($(id).innerHTML);
        
		this.addHeader(title);
		this.obj.overlay.show();
		this.obj.wrap.show();
		this.obj.update.show();
		this.obj.indicator.hide();
		this.position();
        
        var okButton = Element.down('popupContainer', '.button-ok');
        Element.stopObserving(okButton, 'click');
        
        if( undefined != options && 
        	undefined != options.onOK ){
            Event.observe(okButton, 'click', options.onOK);
        } else {
            Event.observe(okButton, 'click', function(e) {
               document.location = url;
            });
        }
    	
    	return false;
    },

	/**
	 * Hides all select elements in IE6
	 *
	 */ 
	selects : function(on){
		if( navigator.appVersion.match(/MSIE 6\.0/) == null ){
			return false;
		}
		$$('#container select').each( function(elm){
			on ? elm.show() : elm.hide();
		});
	},

    /**
    * Closes the popup and displays a notice
    *
    * @param notice Notice to display
    */
    close : function(notice) {
		this.obj.overlay.hide();
		this.obj.wrap.hide();
		this.obj.header.hide();
		this.obj.update.hide();
		this.obj.indicator.show();
		this.selects(true);
		
		if( notice ){
			this.showNotice(notice);
		}

        return true;
    },
    
    /**
    * Closes the popup
    *
    */
    onClick : function(evt) {
    	if( Event.element(evt) != this.obj.wrap ){
    		return false;
    	}
		Event.stop(evt);
		this.close();
        return true;
    },
    
    /**
    *  Ease the work and automatically add a header
    *
    */
    addHeader : function(title) {
    	// if it is false, dont show a header
    	var showHeader = (title===false) ? false : true;
    	
    	// could be an html element. Try to get node value
    	if( typeof(title) == 'object' ){
			Try.these(
				function() { title = title.firstChild.nodeValue }, // keep this first..
				function() { title = title.value } // since this wont throw an exception
			);
    	}
    	
    	// it is a string
    	var title = (typeof(title) == 'string') ? title : '&nbsp;';
    	
        if( showHeader ){
            this.obj.header.update('<a href="#" onclick="Popup.close();"><span>Schliessen</span></a>' + title);
            this.obj.header.show();
        } else {
        	this.obj.header.hide();
        }
    },

    /**
     * Displays message compose box
     *
     */
    sendMessage : function(toUser, title) {
        var url = this.basePath + 'messages/composeBox/' + toUser;
        this.ajax(url, title);
    	return false;
    },
    

    /**
     * Show message after an action (like SendMesagge) is finished
     *
     */
    showNotice: function(msg) {
    	if( !msg.length ){
    		return false;
    	}
    
    	if( $('flash') ){
    		$('flash').remove();
    	}
    	
        var msgObj = Builder.node('div', {id:'flash', className:'message', style:'display:none'}, msg);
        $('container').appendChild(msgObj);
        
        Element.show(msgObj);
        new Effect.Fade('flash', {duration:2, delay:4});
    }
    
});