var Popup = {

    /**
     * Remembers Popup has been initialized
     */
    _init : false,

    /**
     * Container that popup html elements will be appended to
     */
    container : null,

    /**
     * Contains html content
     */
    content : $A(),

    /**
     * base path for ajax requests
     */
    basePath : '',

    /**
     * Store submission message here
     */
    submitMsg : $A,

    /**
    * Close the popup
    *
    */
    close : function(notice) {
        try{
            $('overlay').hide();
            $('popup').remove();
            
            if( notice ){
                Popup.showNotice(notice);
            }
            
        }catch(x){}
        
        return false;
    },
    
    showOverlay : function() {
        $('overlay').show();
        
        if (navigator.appName.indexOf('Explorer') != -1) {
          $('overlay').style.paddingTop = '200px';
        } else {
          $('overlay').style.display = 'table';
        }
        
    },

	/**
	 * Gets the base path
	 *
	 */
	getBasePath : function() {
		try{
			var p = $A(document.getElementsByTagName('script')).findAll( function(s) {
			  return (s.src && s.src.match(/popup\.js$/i))
			}).first();
			p = p.src;
			p = p.replace(/js\/popup\.js$/i,'');
			p = p.replace(document.location.protocol + '//' + document.location.host, '');
		} catch(x) {}
        return p;
	},

    /**
     * Initializes the PopUp. Adds html elements to document and registers event observers.
     *
     */
    init : function() {
        if( Popup._init ){
            return;
        }
        Popup._init = true;
        
        // Needed to fix height behaviour of IE6
        if (navigator.appVersion.indexOf('MSIE 6') != -1) {
            $('container').scrollTo();
        }
       
        // find and set base path
        Popup.basePath = Popup.getBasePath();

        // set container        
        Popup.container = document.body;
        
        // create an overlay
        var overlay = Builder.node('div', {id:'overlay', style:'display:none'});
        
        // append to document
        Popup.container.appendChild(overlay);
        
        // add event observer which calls Popup.close() on a click outside the div#popup
        Event.observe(overlay, 'click', function(evt){
            if( Event.element(evt) == $('popup') || Event.element(evt) == overlay ){
                Event.stop(evt);
                
                if ($('swfButtons')) {
                  $('swfButtons').show();
                }
                
                Popup.close();
            }
        });
    },
    
    /**
    *  Ease the work and automatically add a header
    *
    */
    addHeader : function(title) {
        if (typeof(title) == 'string') {
            $('popupContainer').insert({top:'<div class="header"><a href="#" onclick="Popup.close();"><span>Schließen</span></a>' + title + '</div>'});
        }
    },

    /**
     * Displays message compose box
     *
     */
    sendMessage : function(toUser, title) {
        Popup.init();
        
        var url = Popup.basePath + 'messages/composeBox/' + toUser;
        Popup.ajax(url, title);
    	
    	return false;
    },
    
    /**
     * Displays the confirmation dialogue
     *
     */
    confirm : function(url, id, title, message, options) {
        Popup.init();

        try {
            Popup.content['confirm'] = $(id).innerHTML;
            $(id).remove();
        } catch(x) {}
        
        $('overlay').update('<div id="popup"><div class="container" id="popupContainer">' + Popup.content['confirm'] + '</div></div>');
        Popup.addHeader(title);
        
        new Draggable('popupContainer', { handle: 'header' });
        
        Popup.showOverlay();
        
        var okButton = Element.down('popupContainer', '.button-ok');
        Element.stopObserving(okButton, 'click');
        
        if (typeof(message) != 'undefined') {
          $('popupContainer').down('p').innerHTML = message;
        }

        if (undefined != options) {
          if (undefined != options.onOK) {
            Event.observe(okButton, 'click', options.onOK);
          } else if ((undefined != options.mode) && (options.mode == 'submit')) {
            return true;
          }
        } else {
            Event.observe(okButton, 'click', function(e) {
               document.location = url;
            });
        }
    	
    	return false;
    },
	
	productDeleteConfirm : function(url, id, title, message, options) {
        Popup.init();

        try {
            Popup.content['confirm'] = $(id).innerHTML;
            $(id).remove();
        } catch(x) {}
        
        $('overlay').update('<div id="popup"><div class="container" id="popupContainer">' + Popup.content['confirm'] + '</div></div>');
        Popup.addHeader(title);
        
        new Draggable('popupContainer', { handle: 'header' });
        
        Popup.showOverlay();
        
        var okButton = Element.down('popupContainer', '.button-ok');
        Element.stopObserving(okButton, 'click');
        
        if (typeof(message) != 'undefined') {
          $('popupContainer').down('p').innerHTML = message;
        }

        if (undefined != options) {
          if (undefined != options.onOK) {
            Event.observe(okButton, 'click', options.onOK);
          } else if ((undefined != options.mode) && (options.mode == 'submit')) {
            return true;
          }
        } else {
            Event.observe(okButton, 'click', function(e) {
               //document.location = url;
			   $('productListAction').value = 'delete_product';
			   $('Product').submit();
            });
        }
    	
    	return false;
    },
    
    formIndicatorInsert : function(id, formId, index, delay) {
      $(id).insert({bottom:'<p>'+Popup.submitMsg[index]+'</p>'});
      
      if (index < (Popup.submitMsg.length - 1)) {
        window.setTimeout("Popup.formIndicatorInsert('" + id + "', '" + formId + "', " + (index+1) + ", " + delay + ")", delay);
      } else {
        $(formId).submit();
      }
    },
    
    formIndicator : function(obj, msg, delay) {
        delay = delay * 1000;
        Popup.init();
        $('overlay').update('<div id="popup"><div class="container" id="popupContainer"><div class="main indicator_large"><div><img src="/img/ajaxindicator_large.gif" alt="" /></div><div id="submitMsg"></div></div></div></div>');
        Popup.submitMsg = msg;
        Popup.formIndicatorInsert('submitMsg', obj.id, 0, Math.round(delay / msg.length));
        Popup.showOverlay();
        return false;
    },
    
    display : function(html) {
        Popup.init();
        
        $('overlay').update('<div id="popup"><div class="container" id="popupContainer">' + html + '</div></div>');
        
        Popup.showOverlay();
    },

    /**
     * 
     *
     */
    ajax : function(url, title){
       Popup.init();
       
       // Create ajaxindicator image
       $('overlay').update('<div id="popup"><img src="' + Popup.basePath + 'img/ajaxindicator-popup.gif" alt="Loading" /></div>');
       
    	new Ajax.Request(url, {
    	    asynchronous:true, 
    	    evalScripts:true, 
    	    onLoading: function(){
                Popup.showOverlay();
            },
            onComplete: function(trans){
                $('overlay').update('<div id="popup"><div class="container" id="popupContainer"><div class="main" id="popupUpdate">' + trans.responseText + '</div></div></div>');
                
                Popup.addHeader(title);
                
                $('popup').show();
            }
        });
    	
    	return false;
       
    },
    
    /**
     * Show message after an action (like SendMesagge) is finished
     *
     */
    showNotice: function(msg) {
        var msgLayer = Builder.node('div', {id:'flash', className:'message', style:'display:none'}, ['' + msg + '']);
        $('container').appendChild(msgLayer);
        
        Element.show(msgLayer);
        new Effect.Fade('flash', {duration:2, delay:4});
    }
}