/*
 *  Das ganze mit Prototype realisiert
 *  ACHTUNG!! Es muss vorher die Datei prototype.js mit dem <script> tag inkludiert werden.
 *
 */
var loadingWindow = Class.create({
  initialize: function() 
  {
    this.disableDiv = new Element('div', { id:'disableDiv' });
    this.disableDiv.insert( {top: new Element('img', { id:'loadingGif', src:'pics/site/loading.gif', style:'position:absolute; z-index:11; border:0px;' } ) });
    this.disableDiv.addClassName('blankdiv');                              
  },
  createLoadingWindow: function( elementID )
  {
    var elHeight = $( elementID ).getHeight();
    if( !$('disableDiv') ) {                              
      pageHuelle = $( elementID ).insert( { top: this.disableDiv } );
      $('disableDiv').setStyle( { height:elHeight + 'px' } );
      $('disableDiv').down('img').setStyle( { top:elHeight*0.3 + 'px' } );
    }
  },
  disableLoadingWindow: function()
  {
    if( $('disableDiv') ) $('disableDiv').remove();
  }
});
                       
var messageBox = Class.create({
  /* #############################################################################################################################*/
  initialize: function() 
  /* #############################################################################################################################*/
  {
    var width, height, dim, left, top;
    /* Dimensionen des Documents holen */
    dim = document.viewport.getDimensions();
    width = dim.width;
    height = dim.height;
    /* MessageBox erstellen */
    left = Math.floor(width/2)-225 + 'px';
    top = Math.floor(height/2)-120 + 'px';
    this.messageBox = new Element('div', { id:'messageBox', style:'position:absolute; left:'+left+'; top:'+top+'; z-index:5;' });
    
    left = Math.floor(width/2)-150 + 'px';
    top = Math.floor(height/2) + 'px';
    this.yesDiv = new Element('div', { id:'yesDiv', style:'position:absolute; left:'+left+'; top:'+top+'; z-index:6;' });
    this.yesDiv.insert('Ja');

    left = Math.floor(width/2)+90 + 'px';
    top = Math.floor(height/2) + 'px';
    this.noDiv = new Element('div', { id:'noDiv', style:'position:absolute; left:'+left+'; top:'+top+'; z-index:6;' });
    this.noDiv.insert('Nein');
                           
    left = Math.floor(width/2)-40 + 'px';
    top = Math.floor(height/2) + 'px';
    this.okDiv = new Element('div', { id:'okDiv', style:'position:absolute; left:'+left+'; top:'+top+'; z-index:6;' })
    this.okDiv.insert('Ok');
    this.disablePage = new Element('div', { id:'disablePage', style:'position:absolute; width:100%; height:100%; left:0px; top:0px; z-index:4;' });
  },
  /* #############################################################################################################################*/
  createMessageBox: function( type, message, yesFkt, noFkt )
  /* #############################################################################################################################*/                         
  {
    window.scrollTo(0, 0);
    /* Zuerst alte Box loeschen */
    if( $('disablePage') ) $('disablePage').remove();
    if( $('messageBox') ) $('messageBox').remove();
    if( $('noDiv') ) $('noDiv').remove();
    if( $('yesDiv') ) $('yesDiv').remove();
    if( $('okDiv') ) $('okDiv').remove();
    document.body.style.overflow = "Visible";                           
    /* Anschliessend neue erstellen */
    document.body.appendChild( this.messageBox );

    this.messageBox.update('').insert({ top: message });

    switch( type ) {
      case 'yesno': {
        if( yesFkt ) this.yesDiv.onclick=yesFkt; else this.yesDiv.onclick=this.disableMessageBox;
        document.body.appendChild( this.yesDiv );
        if( noFkt ) this.noDiv.onclick=noFkt; else this.noDiv.onclick=this.disableMessageBox;
        document.body.appendChild( this.noDiv );
      } 
      break; 
      default: {
        this.messageBox.onclick=this.disableMessageBox;
        this.okDiv.onclick=this.disableMessageBox;
        document.body.appendChild( this.okDiv ); 
      } 
      break; 
    }

    document.body.appendChild( this.disablePage );
    document.body.style.overflow = "Hidden";                          
  },
  /* #############################################################################################################################*/
  disableMessageBox: function()
  /* #############################################################################################################################*/                         
  {
    if( $('disablePage') ) $('disablePage').remove();
    if( $('messageBox') ) $('messageBox').remove();

    if( $('noDiv') ) $('noDiv').remove();
    if( $('yesDiv') ) $('yesDiv').remove();
    if( $('okDiv') ) $('okDiv').remove();
    document.body.style.overflow = "Visible";    
  }                         
});
                       
var lightBoxLight = Class.create({
  /* #############################################################################################################################*/
  initialize: function() 
  /* #############################################################################################################################*/
  {
    var width, height, dim, left, top;
    /* Zuerst alte Box loeschen */
    this.disablelightBox();                          
                           
    /* Dimensionen des Documents holen */
    dim = document.viewport.getDimensions();
    width = dim.width;
    height = dim.height;
    /* MessageBox erstellen */
    left = Math.floor(width/2)-500 + 'px';
    top = Math.floor(height/2)-420 + 'px';
    this.disablePage = new Element('div', { id:'disablePage', style:'position:absolute; width:100%; height:100%; left:0px; top:0px; z-index:4;' });
    this.lightbox = new Element('div', { id:'lightbox', style:'position:absolute; left:'+left+'; top:'+top+'; z-index:5;' });
    this.lightpic = new Element('img', { id:'lightboximg', style:'position:absolute; left:0; top:0; z-index:6; cursor:pointer;' });
  },
  /* #############################################################################################################################*/
  createLightBox: function( picUrl )
  /* #############################################################################################################################*/                         
  {
    window.scrollTo(0, 0);

    /* Zuerst alte Box loeschen */
    this.disablelightBox();                           
    /* Anschliessend neue erstellen */
    document.body.appendChild( this.lightbox );

    this.lightpic.src='';
    this.lightpic.src = picUrl;
    this.lightbox.insert( this.lightpic );
    Event.observe( this.lightbox, 'click', this.disablelightBox );
    /* Hoehe mit PHP vorgeben und dann mit lightbox anzeigen! */
    var imgHeight = $('lightboximg').getHeight();
    var imgWidth = $('lightboximg').getWidth();
    /*var imgScale = floor(imgWidth / imgHeight);
    var newHeight = 1000 * imgScale;*/
    $('lightboximg').width = 1000;
    $('lightboximg').height = 800;
    //alert( imgHeight );
    //alert( imgWidth );
    //alert( picUrl );

    document.body.appendChild( this.disablePage );
    document.body.style.overflow = "Hidden";                          
  },
  /* #############################################################################################################################*/
  disablelightBox: function()
  /* #############################################################################################################################*/                         
  {
    if( $('disablePage') ) $('disablePage').remove();
    if( $('lightbox') ) $('lightbox').remove();
    if( $('lightboximg') ) $('lightboximg').remove();
    document.body.style.overflow = "Visible";    
  }                         
});

var fileUpload = Class.create({
  ID_KEY         : 'APC_UPLOAD_PROGRESS',
  statusUrl      : 'modules/site/status.inc.php',
  form           : null, // HTML form element
  status         : null, // HTML Element wo der Upload Status sichtbar wird
  statusTemplate : null, // Prototype Template Objekt
  idElement      : null, // Element in dem die APC Upload ID steht
  iframe         : null, // iframe we create that form will submit to
  retFkt         : null,
  monitorFkt     : null,
  statusBar      : null,
  statusBarBack  : null,
  fileUploadResponse : null,

  initialize : function(form, status, uploadResponse, retFkt, element)
  {
    var i;
    /* Form initialisieren und den Submit Button ueberwachen */
    this.form = $(form);
    this.form.observe('submit', this._onFormSubmit.bindAsEventListener(this));
    /* verstecktes iframe erstellen */
    this.iframe = new Element('iframe', { name : '_upload_frame', height : '300', width: '800' }).hide();
    //$(element).insert( this.iframe );
    /* form Submit zum iframe eintragen */
    this.form.appendChild(this.iframe);
    this.form.target = this.iframe.name;

    /* initialize the APC ID element so we can write a value to it later */
    this.idElement = $(form).getInputs( null, this.ID_KEY )[0];
    var id = this.generateId();
    this.idElement.value = id;

    this.status = $( status );
    this.fileUploadResponse = $( uploadResponse );
    this.fileUploadResponse.hide();
    /* Returnfunktion aufrufen die bei beendigung des Uploads aufgerufen wird! */
    this.retFkt = retFkt;
  },
  generateId : function()
  {
    var rnd, now, ret;
    /* Zufallszahl generieren */
    rnd = Math.random();                /* <- ergibt eine Kommazahl bsp 0.2382737329 */
    rnd = Math.floor( rnd * 100000 );   /* ergibt eine Ganzzahl     */
    /* Zeit auslesen */
    var now = new Date();
    now = now.getTime();
    ret = now + rnd;
    return ret;
  },
  _onFormSubmit : function( e )
  {
    //this.form.disable();
    this.status.descendants().invoke('remove');
    this.status.appendChild( new Element('div', { style:'background-color:#ffffff; width:400px; height:15px; border:1px solid #000000; line-height:15px;' }) );
    this.status.down('div').appendChild( new Element('div', { style:'background-color:#EE5C00; width:0px; height:15px; line-height:15px;' }) );
    this.statusBar = this.status.down('div').down('div');
    this.status.descendants().invoke('show');
    this._monitorUpload( this.idElement.value );
  },
  _monitorUpload : function( id )
  {
    var options = {
                    parameters : { id: id },
                    onSuccess  : this._onMonitorSuccess.bind(this),
                    frequency  : 2,
                    decay      : 0.5
                  };
    this.monitorFkt = new Ajax.PeriodicalUpdater( this.fileUploadResponse, this.statusUrl, options );
  },
  _onMonitorSuccess : function( transport )
  {
    var XHR = transport.responseText.evalJSON();
    var widthPt = Math.ceil(XHR.percent*4);
    if( XHR.percent > 4 ) this.statusBar.update( Math.ceil(XHR.percent) + ' %' );
    this.statusBar.setStyle({ width: widthPt+'px' });
    if( XHR.finished ) {
      this.monitorFkt.stop();
      this.retFkt( transport );
    } 
  }
});              
                       
var MainLoadWindow = new loadingWindow();                        
                       
function showPageFromDB( pageID, subID, useHistory )
{
  var pageid;
  if( pageID == "" ) pageid = 'home'; else pageid = pageID;
  if( (subID == "") || (subID == null) ) subID = null;
  if( (useHistory == "") || (useHistory == null) ) useHistory = false;

  loadDynamic( subID, pageid, null, null, null, useHistory );
}

function loadDynamic( pars, pageid, callBackFkt, element, loadElement, useHistory )
{
  var scripts, Parameters;
  var MsgBox = new messageBox();
  var LoadWin = new loadingWindow();
  if( (pageid == "")  || (pageid == null) ) pageid = 'home';
  if( (element != '') || (element != null) ) scripts = true; else scripts = false;
  if( (pars == '')    || (pars == null) ) Parameters = { pageid: '' }; else Parameters = pars; 
  if( (loadElement == '') || (loadElement == null) ) loadElement = 'pageausgabe';
  if( (useHistory == '') || (useHistory == null) ) useHistory = false;
  
  LoadWin.createLoadingWindow( loadElement );
  Parameters.pageid = pageid;
  if( useHistory )
  {
    new Ajax.History.Request('kernel/site/getPagePath.php', {
      history: { cache: false, id: 'history' },
      parameters: Parameters,
      evalScripts: scripts,
      evalJSON: true,
      onComplete: function(originalRequest){
        var XHR, receiver;
        if (originalRequest.responseText.isJSON()) {
          XHR = originalRequest.responseText.evalJSON();
          if (XHR.access) {
            switch (XHR.access) {
              case 'expired': /*showPageFromDB( 'logout', null, false );*/
                LoadWin.disableLoadingWindow(loadElement);
                break;
              case 'noaccess':{
                MsgBox.createMessageBox('', 'Kein Zugriff!', null, null);
                LoadWin.disableLoadingWindow(loadElement);
                showPageFromDB('home', null, false);
                break;
              }
            }
          }
          else {
            if (XHR.loaderror) {
              if (XHR.showerror) 
                MsgBox.createMessageBox('', XHR.msg, null, null);
            }
            LoadWin.disableLoadingWindow(loadElement);
            if (callBackFkt) 
              callBackFkt(XHR);
          }
        }
        else {
          if (receiver = $(element)) {
            LoadWin.disableLoadingWindow(loadElement);
            receiver.update(originalRequest.responseText);
            if (callBackFkt) 
              callBackFkt(pars);
          }
          else {
            LoadWin.disableLoadingWindow(loadElement);
            if (callBackFkt) {
              callBackFkt(originalRequest.responseText);
            }
            else {
              $('pageausgabe').update(originalRequest.responseText);
            }
          }
        }
      }
    });
  }
  else
  {
    new Ajax.Request('kernel/site/getPagePath.php', {
      parameters: Parameters,
      evalScripts: scripts,
      evalJSON: true,
      onComplete: function(originalRequest){
        var XHR, receiver;
        if (originalRequest.responseText.isJSON()) {
          XHR = originalRequest.responseText.evalJSON();
          if (XHR.access) {
            switch (XHR.access) {
              case 'expired': /*showPageFromDB( 'logout', null, false );*/
                LoadWin.disableLoadingWindow(loadElement);
                break;
              case 'noaccess':{
                MsgBox.createMessageBox('', 'Kein Zugriff!', null, null);
                LoadWin.disableLoadingWindow(loadElement);
                showPageFromDB('home', null, false);
                break;
              }
            }
          }
          else {
            if (XHR.loaderror) {
              if (XHR.showerror) 
                MsgBox.createMessageBox('', XHR.msg, null, null);
            }
            LoadWin.disableLoadingWindow(loadElement);
            if (callBackFkt) 
              callBackFkt(XHR);
          }
        }
        else {
          if (receiver = $(element)) {
            LoadWin.disableLoadingWindow(loadElement);
            receiver.update(originalRequest.responseText);
            if (callBackFkt) 
              callBackFkt(pars);
          }
          else {
            LoadWin.disableLoadingWindow(loadElement);
            if (callBackFkt) {
              callBackFkt(originalRequest.responseText);
            }
            else {
              $('pageausgabe').update(originalRequest.responseText);
            }
          }
        }
      }
    });    
  }
}

function loadPagePathFromDB( pageID, subID, callbackFkt )
{
  var data;
  if( (pageID == "") || (pageID == null) )  
    data = {}; 
  else 
    data = { pageid: pageID };
  /* Per Ajax und mittels pageid den Pfad zum File geben */
  new Ajax.Request( 'kernel/site/getPagePath.php', {
        parameters: data,
        method:     "post",
        onComplete: function( originalRequest ) { 
                      var XHR = originalRequest.responseText.evalJSON();
                      if( ((XHR.s_status == 'login')&&(XHR.status == 'true')) || ((XHR.s_status == 'logout')&&(XHR.status == 'true')) ) {
                        if( callbackFkt == null ) return XHR.pagepath; else callbackFkt( originalRequest );
                      } else {
                        AccessExceptionHandler( XHR ); } },
        onException:function( originalRequest ) { alert('Kann Seite nicht auslesen! Exception!'); },
        onFailure:  function( originalRequest ) { alert('Kann Seite nicht auslesen! Failure!'); }              
      }); 
}
                       