/************* Class for TextEditor **************/
ClassTextEditor = Class.create();
ClassTextEditor.prototype = {

  initialize:function(boxParams, onComplete, textXML, fontList, ID) {

    $('theTextEditorObject').hide();
    $('TextEditorDialog').hide();

    this.textEditorFieldWidth   = boxParams.trw;
    this.textEditorFieldHeight  = boxParams.trh;
    this.textImagePercentHeight = boxParams.oh;
    this.textImagePercentHeight = boxParams.oh;
    this.bgColor                = boxParams.color;
    this.textBoxID              = boxParams.id;
    this.textImageID            = ID;
    this.textContentXML         = textXML;
    this.textFontList           = fontList
    this.textImageOnComplete    = onComplete;
    this.formated_str           = '';
    this.str                    = '';
    this.textWindow;

    if (($$('#LayoutTemplatesText .LayoutTemplate').length > 0) && boxParams.type != 'text')
      this.showTextEditorDialog();
    else
      this.showTextEditor();
  },

  getTextEditor:function(movieName) {

    var textContainer = $(movieName);

    if (navigator.appName.indexOf('Microsoft') != -1) {
      var flashObj = textContainer.getElementsByTagName("object")[0];
    }
    else {
      var flashObj = textContainer.getElementsByTagName("embed")[0];
    }

    flashObj.setSizeMM(this.textEditorFieldWidth, this.textEditorFieldHeight);
    flashObj.setText(this.textContentXML, this.textFontList);
  },

  showTextEditor:function() {

    $('TextEditorDialog').hide();
    $('theTextEditorObject').show();

     this.textWindow = new BorderboxB();
    this.textWindow.showAsPopup('TextEditorWindow', true);

    this.showTextEditorSWF();
  },

  showTextEditorSWF:function() {

    $('theTextEditorObject').show();
    $('TextEditorDialog').hide();

    var textObject = $$('#TextEditorWindow .textObject')[0];
    var theTextEditorObject = $('theTextEditor');
    textObject.appendChild(theTextEditorObject);
    theTextEditorObject.show();

    // flashfilm neu laden
    if (navigator.appName.indexOf('Microsoft') != -1) {
      textObject.innerHTML = textObject.innerHTML;
    }
  },


  showTextEditorDialog:function() {

    $('TextEditorDialog').show();

     this.textWindow = new BorderboxB();
    this.textWindow.showAsPopup('TextEditorWindow', true);

  },

  close:function() {
    $('TextEditorWindow').parentNode.hide();
  }
}

/************* Texteditor-Callbackfunktionen-Flash **************/
function exportHtmlText(formated_str, str) {

  var onComplete = function(AjaxResponse) {
    var XMLDoc = AjaxResponse.responseXML;
    if (textID = XMLDoc.getElementsByTagName('text_id')[0]) {
      FOA.textEditor.textImageID = textID.firstChild.data;
      FOA.textEditor.textImageOnComplete();
    }
  };

  FOA.textEditor.str          = str;
  FOA.textEditor.formated_str = formated_str;

  TextTools.saveText(FOA.textEditor.textImageID,
                     FOA.textEditor.formated_str,
                     FOA.textEditor.str,
                     FOA.textEditor.textEditorFieldWidth,
                     FOA.textEditor.textEditorFieldHeight,
                     FOA.textEditor.bgColor,
                     onComplete);
}

function onTextEditorInit() {
  FOA.textEditor.getTextEditor('theTextEditor');
}

/************* Class for ProjectPreloader **************/
var contentPreloader = Class.create();
contentPreloader.prototype = {

  initialize:function(content) {
    $('projectEditorContent').style.visibility = "visible";
    this.content = content;
  },

  projectPreloader:function() {

    var loadContent = new Array();

    $A(this.content).each(function(c) {
      if (c.hasChildNodes()) {
        if (!c.firstChild.complete) {
          loadContent.push(c);
        }
      }
    });

    var max     = loadContent.length;
    var counter = 0;

    if (max > 5) {

       $A(loadContent).each(function(c) {

        c.firstChild.onload = function() {
          counter++;
          percent = Math.round(counter / max * 100);
          $('PreloaderCounterEditor').update(percent);

          this.style.display = 'block';

          // Breite des Statusbalkens setzen
          Element.setStyle('progressbarEditor', { width: (Math.round(percent / 100 * 330)) + 'px' });

          if (counter == max) {
            var timer = 1000;
            if (max < 10) {
              var timer = 0;
            }
            setTimeout(function() {
              if ((typeof FOA.overlayContext != 'undefined')
              && (typeof FOA.overlayContext.closeOverlay != 'undefined')) {
                FOA.overlayContext.closeOverlay();
              }
            },timer);
          }
        }
      });
    }
    else {
       // Breite des Statusbalkens setzen
       Element.setStyle('progressbarEditor', { width: 330 + 'px' });
       $('PreloaderCounterEditor').update(100);
       setTimeout(function() {
         $('PreloaderCounterEditor').update(100);
         if ((typeof FOA.overlayContext != 'undefined')
         && (typeof FOA.overlayContext.closeOverlay != 'undefined')) {
           FOA.overlayContext.closeOverlay();
         }
       },1000);
    }
  }
}

/************* Class for ProjectEditor **************/
function PageEditor(user_id, project_id, format, cover, surface, page_width, page_height, page_count, cover_color, linen_color, leather_color, page_color, show_page, product_type, xml_layout, firstStart, projectOptions, cup_height) {
  var _AjaxRequestFile   = '/interfaces/project_properties.php';
  var _AjaxLoaderImage  = 'http://www2.fotoalbum.de/mandants/root/gfx/waiting.gif?1236782233';
  var _Format           = format;
  var _LayoutWidth       = 31;
  var _LayoutHeight     = 44;
  var _BackgroundCover   = '/interfaces/getPhotobookCover.php?CoverImage=' + product_type + '_' + format;
  var _xmlLayout        = xml_layout;

  // Quality werden in den layout-XMLs festgelegt
  // Formel: Größe in cm * 200 dpi / 2,54 = Maß in Pixel;
  // Maß in Pixel * 2,54 / 200 dpi = Größe in cm --> 1cm hat dann 78,74 dpi
  this.mandantName         = FOA.Mandant.mandant_short_name;
  this.textModul           = $('mediaList_text')
  this.browserIndex        = navigator.userAgent.toLowerCase().indexOf('msie');
  this.productType         = product_type;
  this.bestQuality         = 7.874; // Maß in mm
  this.mediumQuality       = 3.937; // Maß in mm
  this.page_cover_last     = 0;
  this.firstStart          = firstStart;
  this.defaultPageColor    = page_color;
  this.userID              = user_id;
  this.projectID           = project_id;
  this.showPage             = show_page;
  this.PageCount            = parseInt(page_count);
  this.CoverColor          = cover_color;
  this.SpecialCoverColor   = $H({ linen_color_spine: linen_color, linen_color_full: linen_color, leather_color_spine: leather_color, leather_color_full: leather_color });
  this.Cover               = cover;
  this.Surface             = surface;
  this.projectOptions       = projectOptions;
  this.Pages               = 0;
  this.minPageNr           = 0;
  this.maxPageNr           = 0;
  this.firstPage           = 0;
  this.maxPages             = 0;
  this.Pagefactor          = 4;
  this.Previewfactor        = 0.2;
  this.Layoutfactor        = 0.15;
  this.PreviewHeight        = 0;
  this.PreviewWidth        = 0;
  this.DesktopWidth         = 0;
  this.DesktopHeight       = 0;
  this.CoverWidth           = parseFloat(page_width);
  this.CoverHeight         = parseFloat(page_height);
  this.PageWidth            = parseFloat(page_width);
  this.PageHeight          = parseFloat(page_height);
  this.CupHeight           = parseFloat(cup_height);
  this.SpineWidth           = 0;
  this.activePageNr         = '';
  this.activeBox           = '';
  this.lastActiveBox       = '';
  this.lastPage             = '';
  this.ToolbarFunction     = '';
  this.ToolbarCursor       = '';
  this.CBPositionX          = 0;
  this.CBPositionY          = 0;
  this.dropedBox           = new Array(); // [0] = type, [1] = ID, [2] = BoxID
  this.bgCoverSize         = new Array();  // [0] = left, [1]= right
  this.CBObjects            = new Hash();
  this.desktopPages        = new Array();
  this.desktopPageNames    = new Array();
  this.previewPageNames    = new Array();
  this.PreviewCB           = new Array();
  this.DropZonesPreview     = new Array();
  this.DropZonesDesktop     = new Array();
  this.qualityCheck         = new Object();
  this.Numbers             = new Object();
  this.Page                 = new Array();
  this.ricoDraggables      = new Hash();
  this.borderLayouts       = new Hash();
  this.activePreview        = 0;
  this.qualityInfo          = false;
  this.scrollXOffset        = 1;
  this.initScroll          = false;
  this.PreviewPageWidth     = 0;
  this.PageSide            = '';
  this.showPreviewStart     = 0;
  this.showPreviewEnd       = 6;
  this.stopCurrentDrag     = new Object();
  this.allContentDrags     = new Object();
  this.projectXML          = new Array();
  this.Bleed               = 0;
  this.bleedHorizontal     = 0;
  this.bleedVertical       = 0;
  this.observer            = new ObserverHandler();
  this.bgColors            = { text:'#b2b2b2', calendar:'#9a9a9a', logo:'#333333' };
  this.changeLayoutRange   = { from:0, to:0 };

  // USE Setter Functions to set PageEditor ClassVariables from a ChildClass
  this.setScroll = function(bool, firstPage) {
    this.initScroll = bool;
    this.firstPage  = firstPage;
  }
  this.setPreviewPageWidth = function(arg) {
    this.PreviewPageWidth = arg;
  }
  this.setPageSide = function(arg) {
    this.PageSide = arg;
  }
  this.setActiveSide = function(arg) {
    this.activePageNr = arg;
  }
  this.setActiveBox = function(arg) {
    this.activeBox = arg;
  }
  this.setLastActiveBox = function(arg) {
    this.lastActiveBox = arg;
  }

  this.getProjectParam = function() {
    var dataObject = {
        page_count: this.PageCount
    };
    return dataObject;
  }

  this.checkValidImageType = function(type) {

    imgType = false;

    switch (type) {
      case 'all'   :
      case 'image' :
      case 'logo'  :
        imgType = true;
      break;
    }

    return imgType;
  }

  this.handleDropZone = function(BoxNumber, DropZoneID) {

    var dropZone;
    if ((dropZone = $(DropZoneID))
     && dropZone.getAttribute('type') != 'calendar'
     && dropZone.getAttribute('type') != 'brand') {
      // bilder Gallery
      dndMgr.registerDropZone( new CustomDropzone(DropZoneID,{
          acceptName: 'imageBox',
          completion: function(element) {
            project.dropedBox[0] = 'image';
            project.dropedBox[1] = element.id;
            project.dropedBox[2] = DropZoneID;
            project.lastPage = parseInt(project.getActivePage('PhotobookPage', 'PhotobookDesktop').split('_')[1]);
            project.setContentBox(DropZoneID, element.id, element.className);
          }
      }));

      if (this.textModul) {
        dndMgr.registerDropZone( new CustomDropzone(DropZoneID,{
            acceptName: 'textGalleryItem',
            completion: function(element) {
              var textID = element.id.split('_')[1];
              project.initTextEditor($(DropZoneID), textID);
            }
        }));
      }
    }
  }

  this.getBoxSize = function(PercentWidth, PercentHeight) {

    var boxSize = new Array();

    if (this.desktopPages['Right'] < 1) {
      boxSize[0] = this.roundValue((PercentWidth  * this.CoverWidth  * this.Pagefactor / 100), 8);
      boxSize[1] = this.roundValue((PercentHeight * this.CoverHeight * this.Pagefactor / 100), 8);
    }
    else {
      boxSize[0] = this.roundValue((PercentWidth  * this.PageWidth   * this.Pagefactor / 100), 8);
      boxSize[1] = this.roundValue((PercentHeight * this.PageHeight  * this.Pagefactor / 100), 8);
    }

    return boxSize;
  }

  this.getBoxSizeMM = function(PercentWidth, PercentHeight) {

    var boxSize = new Array();

    boxSize[0]  = this.roundValue((parseFloat(PercentWidth)  / 100 * this.PageWidth), 3);
    boxSize[1]  = this.roundValue((parseFloat(PercentHeight) / 100 * this.PageHeight), 3);

    return boxSize;
  }

  this.getBoxCenterPosition = function (oldX, oldY, oldW, oldH, newW, newH) {

    var oldCenterX = (Math.abs(oldX) * this.PageWidth)  + (oldW / 2);
    var oldCenterY = (Math.abs(oldY) * this.PageHeight) + (oldH / 2);
    var newCenterX = (Math.abs(oldX) * this.PageWidth)  + (newW / 2);
    var newCenterY = (Math.abs(oldY) * this.PageHeight) + (newH / 2);
    var newX       = this.roundValue(((oldX * this.PageWidth)  + oldCenterX - newCenterX), 6);
    var newY       = this.roundValue(((oldY * this.PageHeight) + oldCenterY - newCenterY), 6);
    newX           = (newX > 0) ? newX : 0;
    newY           = (newY > 0) ? newY : 0;

    return new Array((newX / this.PageWidth  * 100), (newY / this.PageHeight * 100));
  }

  this.boxRegionFit = function(ContenBox, PercentWidth, PercentHeight, contentRatio) {
    // neue optimale Boxgröße(wird über den Inhalt definiert)
    var newPercentSize = new Array();

    if (PercentWidth > PercentHeight) {
      var realBoxWidth  = PercentWidth  * this.PageWidth  / 100;
      var realBoxHeight = realBoxWidth  / contentRatio;
      newPercentSize[0] = PercentWidth;
      newPercentSize[1] = realBoxHeight / this.PageHeight * 100;
    }
    else {
      var realBoxHeight = PercentHeight * this.PageHeight / 100;
      var realBoxWidth  = realBoxHeight * contentRatio;
      newPercentSize[0] = realBoxWidth  / this.PageWidth  * 100;
      newPercentSize[1] = PercentHeight;
    }

    if ((newPercentSize[1] > PercentHeight) && (newPercentSize[0] == PercentWidth)) {
      var realBoxHeight = PercentHeight * this.PageHeight / 100;
      var realBoxWidth  = realBoxHeight * contentRatio;
      newPercentSize[0] = realBoxWidth  / this.PageWidth  * 100;
      newPercentSize[1] = PercentHeight;
    }

    Element.setStyle(ContenBox, { width:   newPercentSize[0]  + '%' });
    Element.setStyle(ContenBox, { height:  newPercentSize[1]  + '%' });
    ContenBox.setAttribute('floatWidth',   newPercentSize[0]);
    ContenBox.setAttribute('floatHeight',  newPercentSize[1]);

    // Box neu ausrichten
    var newPosition = this.getBoxCenterPosition((parseFloat(ContenBox.getAttribute('positionLeft')) / 100),
                                                (parseFloat(ContenBox.getAttribute('positionTop'))  / 100),
                                                (PercentWidth  * this.PageWidth  / 100),
                                                (PercentHeight * this.PageHeight / 100),
                                                (newPercentSize[0] * this.PageWidth  / 100),
                                                (newPercentSize[1] * this.PageHeight / 100));

    Element.setStyle(ContenBox, { left: newPosition[0] + '%' });
    Element.setStyle(ContenBox, { top:  newPosition[1] + '%' });
    ContenBox.setAttribute('positionLeft', newPosition[0]);
    ContenBox.setAttribute('positionTop' , newPosition[1]);

    return newPercentSize;
  }

  // füllt alle LogoBoxen mit neuem Inhalt
  this.setLogoContent = function(cio) {

    var pageBoxes  = $$('#PreviewListeTemplate .Preview .ContentBox');
    var xml_data   = '';

    $A(pageBoxes).each(function(oneBox) {
      if (oneBox.getAttribute('permission') == 'logo') {
        boxID = oneBox.id.split('ContentBox')[1];

        // neues ContentObjekt anlegen
        this.CBObjects[boxID]     = Object.clone(cio);
        this.CBObjects[boxID].CB  = boxID;

        // die Preview aktualisieren
        var imgID            = 'PreviewImage' + boxID + '_imageBox_' + this.CBObjects[boxID].ID;
        var newImage        = this.setContent(oneBox, boxID, imgID);
        newImage.src        = this.CBObjects[boxID].getImageSrc('Preview');

        if (oneBox.firstChild) {
          oneBox.replaceChild(newImage, oneBox.firstChild);
        }
        else {
          oneBox.appendChild(newImage);
        }
        xml_data += this.getXMLDataFromPage(oneBox.parentNode, oneBox.parentNode.id.split('_')[1]);
      }
    }.bind(this));

    // alle geänderten ProjectParts speichern
    if (xml_data != '') {
      this.saveProject('saveAllProjectParts', { xml_data: ('<parts>' + xml_data + '</parts>') });
    }
  }

  /* zentrale Funktion für Content
    owner : user, pool, formblitz
    Type  : image, text, calendar, brand, logo(formblitz) -> bestimmt das Verhalten einer Box(definiert im Layout-XML)
  */
  this.newContentImage = function(Owner, origImageWidth, origImageHeight, view, boxID, ContenBox, Type, ID, alpha) {

    var boxID           = boxID.split('ContentBox')[1];
    var PercentWidth   = parseFloat(ContenBox.getAttribute('floatWidth'));
    var PercentHeight   = parseFloat(ContenBox.getAttribute('floatHeight'));
    var boxSize        = this.getBoxSize(PercentWidth, PercentHeight);

    if (this.checkValidImageType(Type)) {
      var cio = Object.extend(new ImageObjekt(Owner, ID, origImageWidth, origImageHeight),
                              new ContentObjekt(Type, boxID, (this.Previewfactor/this.Pagefactor), boxSize[0], boxSize[1], PercentWidth, PercentHeight));

      if (alpha) {
        cio.Alpha = alpha;
      }
    }

    // get the image-propertys by boxsize
    cio.setImageSize(boxSize[0], boxSize[1]);
    this.CBObjects[boxID] = cio;

    if (Type == 'logo') {
      this.setLogoContent(cio);
    }
  }

  this.setContentBox = function(DropZoneID, ContentID, ContentClass) {

    var ContenBox;

    // dropped from FolderImage
    if ((ContenBox = $(ContentID)) && ContenBox.firstChild) {
      var ContenBox  = $(DropZoneID);
      var Owner     = ContentClass.split(' ')[1];
    }
    // droped from EditorImage
    else {
      var ContenBox        = $(DropZoneID);
      var DragBox         = $(ContentID).parentNode;
      var DragZoneID      = DragBox.id;
      var dragID          = DragZoneID.split('ContentBox')[1];
      var dropID          = DropZoneID.split('ContentBox')[1];

      // onDrop auf dragBox
      if (dragID == dropID) {
        return;
      }

      if (this.CBObjects[dragID]) {
        var ContentClass_1  = ContenBox.parentNode.parentNode.className;
        var imageID_1       = ContentClass_1 + 'image' + dropID + '_imageBox_' + this.CBObjects[dragID].ID;
        var origwidth_1     = this.CBObjects[dragID].origwidth;
        var origheight_1    = this.CBObjects[dragID].origheight;
        var rotate_1        = this.CBObjects[dragID].Alpha;
        var owner_1         = this.CBObjects[dragID].owner;
        var type_1          = this.CBObjects[dragID].Type;
        var id_1            = this.CBObjects[dragID].ID;

        if (this.CBObjects[dropID]) {
          var setDragBox      = true;
          var ContentClass_2  = DragBox.parentNode.parentNode.className;
          var imageID_2       = ContentClass_2 + 'image' + dragID + '_imageBox_' + this.CBObjects[dropID].ID;
          var origwidth_2     = this.CBObjects[dropID].origwidth;
          var origheight_2    = this.CBObjects[dropID].origheight;
          var rotate_2        = this.CBObjects[dropID].Alpha;
          var owner_2         = this.CBObjects[dropID].owner;
          var type_2          = this.CBObjects[dropID].Type;
          var id_2            = this.CBObjects[dropID].ID;

          // für texte gibt es das noch nicht
          if (type_1 == 'text' || type_2 == 'text') {
            return;
          }
        }
        else {
          var setDragBox = false;
        }

        // dropped Image
        var newImageWidth        = parseInt(ContenBox.style.width);
        var newImageHeight      = parseInt(ContenBox.style.height);
        this.dropedBox[1]       = imageID_1;
        this.dropedBox[2]       = DropZoneID;
        this.newContentImage(owner_1, origwidth_1, origheight_1, ContentClass_1, DropZoneID, ContenBox, type_1, id_1, rotate_1);
        var newImage             = new Image();
        newImage.setAttribute('id', imageID_1);

        // changed
        this.deregisterRicoDrag(dragID, true);
        this.ricoDraggables[dropID] = newImage;
        project.addContentToDOM(ContenBox, newImage, dropID, ContentClass_1);

        if (setDragBox) {
          // dragged Image
          newImageWidth        = parseInt(DragBox.style.width);
          newImageHeight      = parseInt(DragBox.style.height);
          this.dropedBox[1]   = imageID_2;
          this.dropedBox[2]   = DragZoneID;
          this.newContentImage(owner_2, origwidth_2, origheight_2, ContentClass_2, DragZoneID, DragBox, type_2, id_2, rotate_2);
          newImage             = new Image();
          newImage.setAttribute('id', imageID_2);

          // changed
          this.deregisterRicoDrag(dragID, true);
          this.ricoDraggables[dragID] = newImage;

          if (ContentClass_1 == 'Preview') {
            project.addContentToDOM($('PreviewContentBox' + dragID), newImage, dragID, 'Preview');
          } else {
            project.addContentToDOM(DragBox, newImage, dragID, ContentClass_2);
          }
        }
        else {
          // es wurde ein bild verschoben
          this.deleteImage(DragBox);
          var deletBoxContent = $(this.getView() + 'ContentBox' + dragID);

          while(deletBoxContent.hasChildNodes()) {
            deletBoxContent.removeChild(deletBoxContent.firstChild);
          }

          this.CBObjects.remove(dragID);
          this.handlePage(deletBoxContent.parentNode, true, true);
          this.handlePage($(this.getView() + 'ContentBox' + dropID).parentNode, true, true);
          this.setDesktopContentBox();
        }
      }

      return;
    }

    var ContentClass    = ContenBox.parentNode.parentNode.className;
    var BoxID            = DropZoneID.split('ContentBox')[1];
    var newImage         = new Image();
    var newImageWidth    = parseInt(ContenBox.style.width);
    var newImageHeight  = parseInt(ContenBox.style.height);

    newImage.setAttribute('id', ContentClass + 'image' + BoxID + '_' + ContentID);

    Element.setStyle(newImage, { zIndex: 1 });
    Element.setStyle(newImage, { position: 'absolute' });
    Element.setStyle(newImage, { left: 0 });
    Element.setStyle(newImage, { top: 0 });

    var imageID = ContentID.split('_')[1];
    var type    = FOA.galleryItemList[imageID].ty ? FOA.galleryItemList[imageID].ty : 'image';

    // wenn nur ein bestimmter Type zugelassen wird
    var permission;
    var permissionType;
    if ((permissionType = ContenBox.getAttribute('permission')) && (permissionType != 'null') && (permissionType != type)) {
      return;
    }

    // wenn breite und höhe schon in gallery bereitstehen
    if (FOA.galleryItemList[imageID].w) {
      var origImageWidth   = FOA.galleryItemList[imageID].w;
      var origImageHeight   = FOA.galleryItemList[imageID].h;
      project.qualityCheck = new Object();
      project.newContentImage(Owner, origImageWidth, origImageHeight, ContentClass, DropZoneID, ContenBox, type, imageID, 0);
      project.addContentToDOM(ContenBox, newImage, BoxID, ContentClass);
    }
    // sonst image-properties aus db holen
    else {
      var onCompleteFunction = function(AjaxResponse) {

        var XMLDoc             = AjaxResponse.responseXML;
        var origImage          = XMLDoc.getElementsByTagName('image')[0];
        var origImageWidth    = parseInt(origImage.getAttribute('width'));
        var origImageHeight    = parseInt(origImage.getAttribute('height'));
        project.qualityCheck  = new Object();

        project.newContentImage(Owner, origImageWidth, origImageHeight, ContentClass, DropZoneID, ContenBox, type, imageID, 0);
        project.addContentToDOM(ContenBox, newImage, BoxID, ContentClass);
      };

      var AjaxObject = new Ajax.Request(
                            _AjaxRequestFile, {
                              method: 'post',
                              parameters: 'action=imageSize'
                                        + '&id=' + ContentID.split('_')[1]
                                        + '&owner=' + Owner,
                              onComplete: onCompleteFunction.bind(this)
                            });
    }
  }

  this.addContentToDOM = function(ContenBox, newImage, BoxID, ContentClass) {

    if (ContenBox.firstChild) {

      newImage.src = this.CBObjects[BoxID].getImageSrc(ContentClass);
      ContenBox.replaceChild(newImage, ContenBox.firstChild);

      if (ContentClass == 'Photobook') {
        this.deregisterContentDrag(BoxID);
        this.registerContentDrag(newImage, BoxID);
      }
    }
    else {
      newImage.src   = this.CBObjects[BoxID].getImageSrc(ContentClass);
      ContenBox.appendChild(newImage);
    }

    this.imagePreloader(ContenBox, newImage, BoxID);

    // refresh Layout
    project.handlePage(ContenBox.parentNode, true, true);
    project.setDesktopContentBox();
    // refresh DesktopDropZones
    if (ContentClass == 'Preview') {
      project.setDropZoneDesktop();
      project.setDesktopContentBox();
    }
    // set activstatus Desktop
    project.setDesktopActiveBox($('PhotobookContentBox' + BoxID));
    // set quality-ligth for Desktop / Preview
    project.setQualityLight(ContenBox, BoxID);
  }

  this.setQualityLight = function(ContenBox, BoxID) {

    if (this.qualityCheck[BoxID]) {

      var qualityLight = getElementsByClass(this.qualityCheck[BoxID].className, ContenBox, 'div');

      if (this.qualityInfo == false && this.qualityCheck[BoxID].className == 'lightbad') {
        contentPosition = Position.page(ContenBox);

        var mousePos = {
          posX: contentPosition[0],
          posY: contentPosition[1]
        }

        var myBox = new BorderboxB();
        myBox.showAsPopup('warningMenu');

        getElementsByClass('Message', $('warningMenu'))[0].firstChild.data = getElementsByClass('messageQuality', $('warningMenu'))[0].firstChild.data;
         myBox.position(mousePos.posX, mousePos.posY);

         this.qualityInfo = true;
      }

      $A(qualityLight).each(function(ql) {
        ContenBox.removeChild(ql);
      })
      if (this.qualityCheck[BoxID] != 'no') {
        if (lightClone = this.qualityCheck[BoxID].cloneNode(true)) {
          ContenBox.appendChild(lightClone);
        }
      }
    }
  }

  this.checkQuality = function(CB, CBID) {

    if (this.CBObjects[CBID] && (this.CBObjects[CBID].quality == 'medium' || this.CBObjects[CBID].quality == 'bad')) {

      var light = document.createElement('div');

      light = this.setQualityLightPosition(light, CBID, CB);

      Element.setStyle(light, { zIndex: 10 });
      Element.setStyle(light, { position: 'absolute' });
      Element.addClassName(light, 'light' + this.CBObjects[CBID].quality);

      // set light
      if (CB.hasChildNodes() && (typeof(CB.childNodes[1]) != 'undefined')) {
        CB.replaceChild(light, CB.childNodes[1]);
      }
      else {
        CB.appendChild(light);
      }

      this.qualityCheck[CBID] = light;
    }
    else {
      // unset light
      var qualityLight = getElementsByClass('lightmedium', CB, 'div');
      qualityLight = qualityLight.concat(getElementsByClass('lightbad', CB, 'div'));

      $A(qualityLight).each(function(ql) {
        CB.removeChild(ql);
      })
      this.qualityCheck[CBID] = 'no';
    }
  }

  this.registerRicoDrag = function(e, BoxID) {
   if (!this.ricoDraggables[BoxID]) {
       dndMgr.registerDraggable(new CustomDraggable('imageBox', e));
       this.ricoDraggables[BoxID] = e;
    }
  }

  this.deregisterRicoDrag = function(BoxID, all) {
    if (this.ricoDraggables[BoxID] && this.ricoDraggables[BoxID].id) {
      dndMgr.deregisterDraggable(this.ricoDraggables[BoxID].id);
      this.ricoDraggables.remove(BoxID);
    }
    if (!all) {
      this.observer.unsetAllObserver(this.allContentDrags[BoxID].id);
    }
  }

  this.registerContentDrag = function(e, BoxID) {
    this.observer.setObserver(e, 'mousedown', project.dragContent.bind(e));
    this.allContentDrags[BoxID] = e;
  }

  this.deregisterContentDrag = function(BoxID) {
    if (this.ricoDraggables[BoxID] && this.ricoDraggables[BoxID].id) {
      dndMgr.deregisterDraggable(this.ricoDraggables[BoxID].id);
      this.ricoDraggables.remove(BoxID);
    }
    if (this.allContentDrags[BoxID]) {
      this.observer.unsetAllObserver(this.allContentDrags[BoxID].id)
    }
  }

  this.deregisterAllDrags = function() {
    $H(this.allContentDrags).each(function(drag) {
      this.deregisterContentDrag(drag.key);
    }.bind(this));
    this.allContentDrags = new Object;
  }

  this.scaleContent = function(El, content, ContentID, posLeft, posTop, BoxWidth, BoxHeight) {

    var page      = content.parentNode;
    var newWidth  = project.roundValue(parseFloat(El.style.width), 8);
    var newHeight = project.roundValue(parseFloat(El.style.height), 8);

    project.CBObjects[ContentID].setImageSize(newWidth, newHeight);
    project.CBObjects[ContentID].setImagePosition(posLeft, posTop, BoxWidth, BoxHeight);

    El.src = project.CBObjects[ContentID].getImageSrc();

    El.onload = function(ContentID, page, content) {
      project.qualityCheck = new Object();
      project.checkQuality(content, ContentID);
      project.handlePage(page, true, false);
      project.setQualityLight(content, ContentID);

      project.boxBugFixer(content);

    }.bind(El, ContentID, page, content)
  }

  this.stopDragContent = function() {

    Event.stopObserving(document, 'mouseup', project.stopCurrentDrag);

    if (this.parentNode == null) {
      var El = $(this.id);
    } else {
      var El = this;
    }

    if (El == null)
      return;

    var ContentID = El.parentNode.id.split('ContentBox')[1];

    if (!project.CBObjects[ContentID])
      return;

    var posLeft   = parseInt(El.style.left);
    var posTop     = parseInt(El.style.top);

    var BoxWidth   = project.CBObjects[ContentID].OffsetWidth;
    var BoxHeight = project.CBObjects[ContentID].OffsetHeight;

    project.CBPositionX   = posLeft;
    project.CBPositionY   = posTop;
    currentDragElement     = '';

    if (project.ToolbarFunction == 'position') {

      var oldLeft = project.CBObjects[ContentID].Left;
      var oldTop  = project.CBObjects[ContentID].Top;

      project.CBObjects[ContentID].setImagePosition(posLeft, posTop, BoxWidth, BoxHeight);
      // hat sich die position verändert?
      if ((oldLeft != project.CBObjects[ContentID].Left) || (oldTop != project.CBObjects[ContentID].Top)) {
        if (project.CBObjects[ContentID].Type == 'logo') {
          project.setLogoContent(project.CBObjects[ContentID]);
        }
      }
    }
    if ((project.ToolbarFunction == 'plus') || (project.ToolbarFunction == 'minus')) {
      if (!El.style.width || !El.style.height) {
        return false;
      }
      project.scaleContent(El, El.parentNode, ContentID, posLeft, posTop, BoxWidth, BoxHeight);
    }
  }

  this.dragContent = function() {

    var ContentID = this.parentNode.id.split('ContentBox')[1];

    if (project.CBObjects[ContentID].Type == 'text') {
      return false;
    }

    if (project.ToolbarFunction == 'position'
      || project.ToolbarFunction == 'minus'
      || (project.ToolbarFunction == 'plus'
      && project.CBObjects[ContentID].quality != 'bad')) {

      project.deregisterRicoDrag(ContentID, true);

      // init position
      var BoxWidth   = project.CBObjects[ContentID].OffsetWidth;
      var BoxHeight = project.CBObjects[ContentID].OffsetHeight;

      this.style.position   = 'absolute';
      this.style.left       = project.CBObjects[ContentID].Left * BoxWidth   + 'px';
      this.style.top         = project.CBObjects[ContentID].Top   * BoxHeight + 'px';
      currentDragElement     = this;

      var drag = new transformationHandler(this, BoxWidth, BoxHeight, project.ToolbarFunction, project.CBObjects[ContentID]);

      project.stopCurrentDrag = project.stopDragContent.bind(this);

      document.onmouseup = project.stopCurrentDrag;
    }
    else {
      var drag = new Object;
    }
  }

  this.checkContentXInside = function(_X, contentWidth, AreaWidth) {
    // flush the Image with LeftBorder
    if (_X >= 0) {
      _X = 0;
    }
    // flush the Image with RightBorder
    if (((_X + contentWidth) <= AreaWidth) && _X < 0) {
      _X -= ((contentWidth + _X) - AreaWidth);
    }
    return _X
  }

  this.checkContentYInside = function(_Y, contentHeight, AreaHeight) {
    // flush the Image with TopBorder
    if (_Y >= 0) {
      _Y = 0;
    }
    // flush the Image with BottomBorder
    if (((_Y + contentHeight) <= AreaHeight) && _Y < 0) {
      _Y -= ((contentHeight + _Y) - AreaHeight);
    }
    return _Y
  }

  this.rotateContent = function(e, alpha) {

    if (e.firstChild) {
      var ContentID = e.id.split('ContentBox')[1];
      if (this.CBObjects[ContentID].Type == 'text')
        return;

      var BoxWidth   = this.CBObjects[ContentID].OffsetWidth;
      var BoxHeight = this.CBObjects[ContentID].OffsetHeight;

      Element.setStyle(e.firstChild, { visibility:'hidden'});
      Element.setStyle(e, { background: '#FEFEFE url(' + _AjaxLoaderImage + ') ' + Math.round(BoxWidth/2) + 'px ' + Math.round(BoxHeight/2) + 'px no-repeat'});
      this.boxBugFixer(e);

      // absoluten Bildoffset zur Box ermitteln
      var leftOffset = Math.abs(this.CBObjects[ContentID].Left * BoxWidth);
      var topOffset  = Math.abs(this.CBObjects[ContentID].Top  * BoxHeight);

      var newCenter_X = 0;
      var newCenter_Y = 0;

      // berechne Verschiebung zum gedrehten Bildmittelpunkt im Verhältniss zur Box
      if ((this.CBObjects[ContentID].Left < 0) || (this.CBObjects[ContentID].Top < 0)) {
        if (alpha == 90) {
          var newCenter_Y = -1 * ((leftOffset + (this.CBObjects[ContentID].OffsetWidth / 2)) - (this.CBObjects[ContentID].OffsetHeight / 2));
          var newCenter_X = -1 * ((this.CBObjects[ContentID].Height - (topOffset + (this.CBObjects[ContentID].OffsetHeight / 2))) - (this.CBObjects[ContentID].OffsetWidth / 2));
        }
        else {
          var newCenter_Y = -1 * ((this.CBObjects[ContentID].Width - (leftOffset + (this.CBObjects[ContentID].OffsetWidth / 2))) - (this.CBObjects[ContentID].OffsetHeight / 2));
          var newCenter_X = -1 * ((topOffset + (this.CBObjects[ContentID].OffsetHeight / 2)) - (this.CBObjects[ContentID].OffsetWidth / 2));
        }
      }

      // falls der scale wert bei 1 liegt neu einpassen
      if ((this.CBObjects[ContentID].scale == 1) || (BoxWidth > this.CBObjects[ContentID].Height) || (BoxHeight > this.CBObjects[ContentID].Width)) {

        Element.setStyle(e.firstChild, { top: 0});
        Element.setStyle(e.firstChild, { left: 0});

        this.CBObjects[ContentID].setImageRotation(alpha);
        this.CBObjects[ContentID].setImageSize(BoxWidth, BoxHeight);

        if (((newCenter_Y + this.CBObjects[ContentID].Height) < BoxHeight)) {
          newCenter_Y = 0;
        }

        if (((newCenter_X + this.CBObjects[ContentID].Width) < BoxWidth)) {
          newCenter_X = 0;
        }

        this.CBObjects[ContentID].setImagePosition(newCenter_X, newCenter_Y, BoxWidth, BoxHeight);

        Element.setStyle(e.firstChild, { width: ''});
        Element.setStyle(e.firstChild, { height: ''});
         Element.setStyle(e.firstChild, { width: this.CBObjects[ContentID].Width });
        Element.setStyle(e.firstChild, { height: this.CBObjects[ContentID].Height });

      }
      // sonst um den Mittelpunkt drehen
      else {
        this.CBObjects[ContentID].setImageRotation(alpha);
        this.CBObjects[ContentID].setImageSize(this.CBObjects[ContentID].Height, this.CBObjects[ContentID].Width);

        if (((newCenter_Y + this.CBObjects[ContentID].Height) < BoxHeight)) {
          newCenter_Y = 0;
        }

        if (((newCenter_X + this.CBObjects[ContentID].Width) < BoxWidth)) {
          newCenter_X = 0;
        }

        this.CBObjects[ContentID].setImagePosition(newCenter_X, newCenter_Y, BoxWidth, BoxHeight);

         Element.setStyle(e.firstChild, { width: this.CBObjects[ContentID].Width + 'px' });
        Element.setStyle(e.firstChild, { height: this.CBObjects[ContentID].Height + 'px' });
        Element.setStyle(e.firstChild, { top:  (this.CBObjects[ContentID].Top  * 100) + '%'});
        Element.setStyle(e.firstChild, { left: (this.CBObjects[ContentID].Left * 100) + '%'});
      }

      // preloader
      e.firstChild.onload = function(ContentID, oldWidth, oldHeight) {

        Element.setStyle(e.firstChild, { visibility:'visible'});

        if (project.browserIndex >= 0) {
          e.style.backgroundImage = '';
          e.style.backgroundColor = '';
        }
        else {
          Element.setStyle(e, { backgroundImage:''});
          Element.setStyle(e, { backgroundColor:''});
          e.style.border = '';
        }

        project.boxBugFixer(e.parentNode);

        // set quality-ligth for Desktop / Preview
        project.qualityCheck = new Object();
        project.checkQuality(e, ContentID);
        project.handlePage(e.parentNode, true, false);
        project.setQualityLight(e, ContentID);

      }.bind(e.firstChild, ContentID, this.CBObjects[ContentID].Width, this.CBObjects[ContentID].Height)

      e.firstChild.src = this.CBObjects[ContentID].getImageSrc();
    }
  }

  this.rightMouseContetxtMenu = function(e, evt) {

    Event.stop(evt);

    var contentBox = e.parentNode;
    // BorderBox erstellen
    var myBox = new BorderboxDrag();
    myBox.showAsPopup('rightMouseContetxtMenu');
    myBox.makeDraggable('Borderbox' + contentBox.id);
    myBox.position(Event.pointerX(evt), Event.pointerY(evt));

    // Links mit Eventhandlern versehen
    var deleteImage   = getElementsByClass('delete',   myBox.borderBox, 'a')[0];
    var rotateImageR  = getElementsByClass('rotate_r', myBox.borderBox, 'a')[0];
    var rotateImageL  = getElementsByClass('rotate_l', myBox.borderBox, 'a')[0];

    deleteImage.onclick = (function(evt, e, cb) {
      Event.stop(evt);
      project.deleteImage(cb, e);
      myBox.hide();
    }).bindAsEventListener(this, e, contentBox);
    rotateImageL.onclick = (function(evt, e, cb) {
      Event.stop(evt);
      project.rotateContent(cb, -90);
      myBox.hide();
    }).bindAsEventListener(this, e, contentBox);
    rotateImageR.onclick = (function(evt, e, cb) {
      Event.stop(evt);
      project.rotateContent(cb, 90);
      myBox.hide();
    }).bindAsEventListener(this, e, contentBox);
  }

  this.showColorPicker = function(evt) {
    // BorderBox erstellen
    var myBox = new BorderboxDrag();
    myBox.showAsPopup('ColorPickerMenu', true);
    myBox.makeDraggable('BorderboxColorPickerMenu');
    myBox.position(Event.pointerX(evt), Event.pointerY(evt));
  }

  this.showCalendarStyleContext = function(evt, box) {
     // BorderBox erstellen
    var myBox = new BorderboxDrag();
    myBox.showAsPopup('CalendarStyleMenu', true);
    myBox.makeDraggable('BorderboxCalendarStyleMenu');
    myBox.position(Event.pointerX(evt), Event.pointerY(evt));

    var changeStyleButton = $('calendarStyleChangeButton');
    changeStyleButton.onclick = function(evt, el, box) {
                                  Event.stop(evt);
                                  var selectStyles                   = el.parentNode.getElementsByTagName('select')[0];
                                  this.projectOptions.calendar_style = selectStyles.options[selectStyles.selectedIndex].value;
                                  var previewPage                    = $('PreviewPage_' + this.desktopPages['Left']);
                                  project.handlePage(previewPage, true, false);
                                  this.saveProject('saveProjectAttributes', {calendar_style: this.projectOptions.calendar_style});
                               }.bindAsEventListener(this, changeStyleButton, box);
  }

  this.initTextEditor = function(el, externTextID) {

    var pageNr     = this.desktopPages[this.PageSide];
    var type       = el.getAttribute('type');
    var permission = el.getAttribute('permission');

    // wenn nur ein der Type: Text zugelassen wird oder der texteditor bereits geöffnet ist
    if ((type && permission && (type != 'text') && (permission != 'null'))
     || ($('TextEditorWindow').style.display == 'block')) {
      return;
    }

    // textBoxOffset   : Renderausmaße für das Textbild im Projekteditor
    // textAreaEditor  : Textfeldausmaße des Texteditors
    // textPercent     : Textbildgröße in % (zur Box)
    var boxPercentWidth   = parseFloat(el.getAttribute('floatWidth'));
    var boxPercentHeight  = parseFloat(el.getAttribute('floatHeight'));
    var boxSizeMM         = project.getBoxSizeMM(boxPercentWidth, boxPercentHeight);
    var boxID             = el.id.split('ContentBox')[1];

    var boxParams = { ow    : parseInt(el.offsetWidth),  // boxoffsetwidth
                      oh    : parseInt(el.offsetHeight), // boxoffsetheight
                      pw    : boxPercentWidth,           // boxpercentwidth
                      ph    : boxPercentHeight,          // boxpercentheight
                      trw   : boxSizeMM[0],              // textEditorFieldWidth
                      trh   : boxSizeMM[1],              // textEditorFieldHeight
                      tpw   : 100,                       // textpercentheight
                      tph   : 100,                       // textpercentwidth
                      color : this.Page[pageNr].color,   // seitenfarbe
                      id    : boxID,
                      type  : type
                    };

    // was nach dem schliessen des Texteditorfensters passiert...
    var onTextEditorClose = function(boxID, boxParams) {

      var box     = $('PhotobookContentBox' + boxID);
      var boxSize = project.getBoxSize(boxParams.pw, boxParams.ph);

      var cio = Object.extend(new TextObjekt('user', FOA.textEditor.textImageID, boxParams.color),
                              new ContentObjekt('text', boxID, (project.Previewfactor/project.Pagefactor), boxSize[0], boxSize[1], boxParams.pw, boxParams.ph))

      project.CBObjects[boxID] = cio;

      // textBild einhängen
      var textImage  = new Image();
      textImage.id   = 'PhotobookImage_Image' + boxID + '_imageBox_' + FOA.textEditor.textImageID;
      textImage.src  = cio.getImageSrc(box.parentNode.parentNode.className);

      while(box.hasChildNodes()) {
        box.removeChild(box.firstChild);
      }

      box.appendChild(textImage);
      project.imagePreloader(box, textImage, boxID);
      FOA.textEditor.close();
      project.handlePage(box.parentNode, true, true);

    }.bind(null, boxID, boxParams);

    // text laden(wenn möglich mit übergebener)
    if (externTextID) {
      TextTools.getTextByID(externTextID, boxParams, onTextEditorClose);
    }
    // oder ID des boxinhalts
    else if (project.CBObjects[boxID] && (project.CBObjects[boxID].Type == 'text')) {
      TextTools.getUserText(project.CBObjects[boxID].ID, boxParams, onTextEditorClose);
    }
    // sonst ohne text starten
    else {
      FOA.textEditor = new ClassTextEditor(
        boxParams,
        onTextEditorClose,
        '<P ALIGN="LEFT"><FONT FACE="Linux Libertine" SIZE="48" COLOR="#000000" LETTERSPACING="0" KERNING="0"></FONT></P>',
        ['Linux Libertine'],
        '');
    }
  }

  this.deleteImage = function(box, e) {

    if (box.id) {
      var boxID = box.id.split('ContentBox')[1];

      while(box.hasChildNodes()) {
        box.removeChild(box.firstChild);
      }
      //box.className = 'ContentBox';
      this.boxBugFixer(box);
      this.handlePage(box.parentNode, true, true);
      this.CBObjects.remove(boxID);
    }
  }

  this.setDesktopBoxStyle = function(box) {

    var type    = box.getAttribute('type');
    var bgColor = (Element.getStyle(box, 'background-color'));

    if (type && !box.hasChildNodes()) {
      switch (type) {
        case 'image':
          if (box.getAttribute('permission') == 'logo') {
            Element.setStyle(box, { background: this.bgColors.logo + ' url(' + 'http://www10.fotoalbum.de/mandants/root/gfx/editor_box_logo_bg.gif?1236782233) no-repeat' });
          }
          else {
            Element.setStyle(box, { background: bgColor + ' url(' + 'http://www8.fotoalbum.de/mandants/root/gfx/editor_box_image_bg.gif?1236782233) no-repeat' });
          }
        break;
        case 'text':
          Element.setStyle(box, { background: this.bgColors.text + ' url(' + 'http://www8.fotoalbum.de/mandants/root/gfx/editor_box_text_bg.gif?1236782233) no-repeat' });
        break;
      }
    }
  }

  this.setDesktopContentBox = function() {

    var desktop   = $('PhotobookDesktop');
    var DesktopCB = getElementsByClass('ContentBox', desktop, 'div');
    DesktopCB     = DesktopCB.concat(getElementsByClass('ContentBox_active', $('PhotobookDesktop'), 'div'));

    for (var i = 0; i < DesktopCB.length; i++) {
      // ausgenommen sind FOA-logos
      if ((DesktopCB[i].getAttribute('type') != 'brand')) {
        var CBID = DesktopCB[i].id.split('Photobook')[1];

        this.setDesktopBoxStyle(DesktopCB[i]);

        if (DesktopCB[i].hasChildNodes() && dndMgr.dragElement == null) {
          DesktopCB[i].firstChild.oncontextmenu = function(evt) {
            this.rightMouseContetxtMenu(Event.element(evt), evt);
            return false;
          }.bindAsEventListener(this);
        }

        DesktopCB[i].onmouseover = function(e, CBID) {
          // set active status
          if (!dndMgr.whileDragging){
            this.setDesktopActiveBox(e);
          }

          this.activeBox = CBID;
          var boxID      = CBID.split('ContentBox')[1];

          if (e.hasChildNodes() && dndMgr.dragElement == null && this.CBObjects[boxID]) {
            // Image - Handling
            if (this.checkValidImageType(this.CBObjects[boxID].Type)) {
              switch (this.ToolbarFunction) {
                case 'plus':
                case 'minus':
                case 'rotate_left':
                case 'rotate_right':
                case 'select':
                  this.handleCursor(this.ToolbarCursor, this.ToolbarFunction, false);
                   this.deregisterRicoDrag(boxID, true);
                break;
                case 'position':
                  this.handleCursor(this.ToolbarCursor, this.ToolbarFunction, false);
                  this.deregisterRicoDrag(boxID, true);
                break;
                case 'switch':
                   this.handleCursor(this.ToolbarCursor, this.ToolbarFunction, false);
                  this.registerRicoDrag(e.firstChild, boxID);
                break;
              }
            }
            // Text - Handling
            if (this.CBObjects[boxID].Type == 'text') {
              var tmp = this.ToolbarFunction;
              var tmp2 = this.ToolbarCursor;

              this.handleCursor(toolbar_cursor_texteditor, 'texteditor', false);

              if (this.ToolbarFunction == 'switch') {
               this.registerRicoDrag(e.firstChild, boxID);
              }
              else {
               this.deregisterRicoDrag(boxID, true);
              }

              this.ToolbarFunction = tmp;
              this.ToolbarCursor   = tmp2;
            }
          }
          // text ist überall möglich
           if (e.getAttribute('type') == 'text' || this.ToolbarFunction == 'texteditor') {
             var tmp = this.ToolbarFunction;
             var tmp2 = this.ToolbarCursor;

             this.handleCursor(toolbar_cursor_texteditor, 'texteditor', false);
             this.deregisterRicoDrag(boxID, true);

             this.ToolbarFunction = tmp;
             this.ToolbarCursor   = tmp2;
          }

        }.bind(this, DesktopCB[i], CBID);

        DesktopCB[i].onmouseup = function(evt, e) {
          switch (this.ToolbarFunction) {
            case 'rotate_right':
            case 'rotate_left':
              if (e.hasChildNodes()) {
                e.firstChild.oncontextmenu = function(evt) {
                  project.rightMouseContetxtMenu(Event.element(evt), evt);
                  return false;
                }.bindAsEventListener(this);

                if (Event.isLeftClick(evt)) {
                  var angle = 90;
                  if (this.ToolbarFunction == 'rotate_left') {
                    angle = -90;
                  }
                  project.rotateContent(e, angle);
                }
              }
            break;
            case 'texteditor':
              if (e.getAttribute('type') == 'calendar') {
                this.showCalendarStyleContext(evt, e);
              }
              else {
                project.initTextEditor(e);
              }
            break;
          }
          if(e.getAttribute('type') == 'text') {
            project.initTextEditor(e);
          }
        }.bindAsEventListener(this, DesktopCB[i]);

        this.unsetPreviewActiveBox(CBID);
      }
    }
    this.boxBugFixer(desktop);
  }

  // IE6 ausnahme
  this.boxBugFixer = function(box) {
    if (this.browserIndex >= 0) {
      var BoxClone = box;
      box.parentNode.replaceChild(BoxClone, box);
    }
  }

  this.unsetDesktopActiveBox  = function(activeCB) {

    if (!activeCB) {
      activeCB = getElementsByClass('ContentBox_active', $('PhotobookDesktop'), 'div');
      if ((activeCB = getElementsByClass('ContentBox_active', $('PhotobookDesktop'), 'div')) && activeCB[0]) {
        activeCB = activeCB[0];
      }
      else {
        activeCB = false;
      }
    }

    if (activeCB) {
      if (this.browserIndex >= 0) {
        activeCB.style.removeAttribute('border','false');
      }
      else {
        activeCB.style.border = '';
      }

      activeCB.style.left    = activeCB.getAttribute('positionLeft') + '%';
      activeCB.style.top     = activeCB.getAttribute('positionTop') + '%';
      activeCB.className      = 'ContentBox';

      this.boxBugFixer(activeCB);
    }
  }

  this.unsetAllPreviewActiveBoxes = function(Nr) {
    var activeCB = getElementsByClass('ContentBox_active', $('PreviewPage_' + Nr), 'div');

    if (activeCB.length > 0) {
      if (activeCB[0].id) {
        if (this.browserIndex >= 0) {
          activeCB[0].style.removeAttribute('border','false');
        }
        else {
          activeCB[0].style.border = '';
        }

        activeCB[0].style.cursor  = 'auto';
        activeCB[0].style.backgroundImage = '';
        activeCB[0].className     = 'ContentBox';
        var BoxClone               = activeCB[0];
        this.boxBugFixer(activeCB[0]);
      }
    }
  }

  this.unsetPreviewActiveBox = function(CBID) {
    // achtung der ie6 macht hier noch was falsch
    var box;
    if (box = $('Preview' + CBID)) {
      Element.setStyle(box, { backgroundImage : '',
                              cursor          : 'auto',
                              border          : '' });

      box.className = 'ContentBox';
      this.boxBugFixer(box);
    }
  }

  this.setDesktopActiveBox  = function(e) {

    if (!e)
     return;

    var setStyle            = true;
    var elementClassName     = e.className;

    var activeCB            = getElementsByClass('ContentBox_active', $('PhotobookDesktop'), 'div');

    if (activeCB.length > 0) {
      if (e.id == activeCB[0].id) {
        setStyle = false;
      }
      else {
        this.unsetDesktopActiveBox(activeCB[0]);
      }
    }

    if (setStyle) {
      if (this.browserIndex >= 0) {
        e.style.removeAttribute('border','false');
      }
      else {
        e.style.border = '';
      }

      e.style.left   = (parseFloat(e.style.left) - (1 / parseInt(e.parentNode.style.width)   * 100)) + '%';
      e.style.top   = (parseFloat(e.style.top)   - (1 / parseInt(e.parentNode.style.height)   * 100)) + '%';
      e.className   = elementClassName + '_active';
      this.boxBugFixer(e);
    }
  }

  this.setDropZonePreview = function(PreviewCB) {
    if (this.DropZonesPreview.length > 0) {
      for (var i = 0; i < PreviewCB.childNodes.length; i++) {
        dndMgr.deregisterDropZone(PreviewCB.childNodes[i].id);
        project.handleDropZone(this.DropZonesPreview.length, PreviewCB.childNodes[i].id);
      }
    }
  }

  this.setDropZoneDesktop  = function() {

    for (var i = 0; i < this.DropZonesDesktop.length; i++) {
      dndMgr.deregisterDropZone(this.DropZonesDesktop[i]);
    }

    this.DropZonesDesktop = Array();

    var DesktopCB = getElementsByClass('ContentBox', $('PhotobookDesktop'), 'div');
    DesktopCB = DesktopCB.concat(getElementsByClass('ContentBox_active', $('PhotobookDesktop'), 'div'));
    for (var i = 0; i < DesktopCB.length; i++) {
      this.DropZonesDesktop[this.DropZonesDesktop.length] = DesktopCB[i].id;
      this.handleDropZone(i, DesktopCB[i].id);
    }

  }

  this.scrollFunk = function(ScrollBox, change) {

    if (this.initScroll == true) {
      ScrollBox       = $(ScrollBox);
      var start       = this.firstPage;
      var dz_index     = 0;

      if (ScrollBox.scrollLeft != this.scrollXOffset || change){

        var previewBoxWidth     = Element.getDimensions(ScrollBox).width;
        this.showPreviewEnd     = Math.floor((ScrollBox.scrollLeft + previewBoxWidth) / this.PreviewPageWidth);

        if (this.showPreviewEnd > this.maxPages) {
          this.showPreviewEnd = this.maxPages;
        }

        this.showPreviewStart = this.showPreviewEnd - (Math.ceil(previewBoxWidth / this.PreviewPageWidth));

        if (this.showPreviewStart == -1) {
          this.showPreviewStart = 0;
        }

        // unregister Dropzones from Previewlist
        for (var i = 0; i < this.DropZonesPreview.length; i++) {
          dndMgr.deregisterDropZone(this.DropZonesPreview[i]);
        }

        for (var i = this.showPreviewStart; i <= (this.showPreviewEnd + 1); i++) {
          if (this.PreviewCB[(i * this.Pages) + start]) {
            for (var j = 0; j < this.PreviewCB[(i * this.Pages) + start].length; j++) {
              this.DropZonesPreview[dz_index] = this.PreviewCB[(i * this.Pages) + start][j];
              dz_index++;
              project.handleDropZone(dz_index , this.PreviewCB[(i * this.Pages) + start][j]);
            }
          }
          if (this.PreviewCB[(i * this.Pages)] && (this.Pages == 2)) {
            for (var j = 0; j < this.PreviewCB[(i * this.Pages)].length; j++) {
              this.DropZonesPreview[dz_index] = this.PreviewCB[(i * this.Pages)][j];
              dz_index++;
              project.handleDropZone (dz_index, this.PreviewCB[(i * this.Pages)][j]);
            }
          }
        }
      }
      this.scrollXOffset = ScrollBox.scrollLeft;
    }
  }

  this.setActivePage = function(e) {
    // set activeClass for PreviewPage / PhotobookPage
    var elementClassName = e.className;

    if (e.parentNode.id == 'PhotobookDesktop') {
      var elementClass = getElementsByClass(elementClassName + '_active', e.parentNode, 'div');
    }
    else {
      var elementClass = getElementsByClass(elementClassName + '_active', e.parentNode.parentNode.parentNode, 'div');
    }

    if (elementClassName.search(/_active/) == -1) {

      for (var i = 0; i < elementClass.length; i++) {
        elementClass[i].className = elementClassName;
        this.boxBugFixer(elementClass[i]);
      }

      e.className = elementClassName + '_active';
      this.boxBugFixer(e);
    }

    // set cover
    if (e.parentNode.className == 'Preview'){
      this.setDropZoneDesktop();

      var pageNr = parseInt(this.desktopPages['Left']);
      this.setColor(pageNr, false, this.Page[pageNr].type, 'Left');

      if (this.desktopPages['Right']){
        var pageNr = parseInt(this.desktopPages['Right']);
        this.setColor(pageNr, false, this.Page[pageNr].type, 'Right');
      }
    }

    return e;
  }

  this.getActivePage = function(cssClass, SearchNode) {

    var activePage = getElementsByClass(cssClass + '_active', $(SearchNode), 'div');

    if (activePage[0]) {
      return activePage[0].id;
    } else {
      return false;
    }
  }

  this.changePage = function(e) {

    if (this.PageCount > 1) {
      this.handlePage(e, true, true);
    }

    this.setDesktopContentBox();

    if ($(this.activeBox)) {
      this.setDesktopActiveBox($(this.activeBox));
    }
  }

  this.setPageLayout = function(Layout, factor, placeHolder, PageNumber, content, PageType) {

    // layoutID für Formatwechsel merken
    if (Layout.className == 'BookPage' && Layout.id != 'LayTemp') {
      this.Page[PageNumber].layoutID = Layout.id.split('_')[1];
    }
    // clone Layoutbox(Bookpage_LayoutID) and replace the PageTarget
    if (PageNumber == undefined) {
      PageNumber = this.desktopPages[this.PageSide];
    }

    factor               = factor;
    var PageTargetClone = Layout.cloneNode(true);
    var LayoutID         = Layout.id;
    var PageTarget      = $(placeHolder);
    var PageClass        = PageTarget.className;
    var PageParent      = PageTarget.parentNode.id;

    // give contentboxes distinct IDs
    for (var i = 0; i < PageTargetClone.childNodes.length; i++) {
      var newID = PageTargetClone.childNodes[i].id.split('_');

      if (newID[0] != 'ContentBox') {
        // PreviewCB -> DesktopCB
        var CBID  = '_' + newID[1] + '_' + newID[2] + '_' + newID[3];
        var setID = PageTarget.parentNode.className + 'ContentBox' + CBID;
      }
      else {
        // LayoutCB -> PreviewCB
        var CBID  = '_' + PageNumber + '_' + newID[1] + '_' + newID[2];
        var setID = PageTarget.parentNode.className + newID[0] + CBID;
      }
      // notice Preview-Contentbox-IDs
      if (PageTarget.parentNode.className == 'Preview') {
        if (this.PreviewCB[PageNumber]) {
          if (PageTargetClone.childNodes.length < this.PreviewCB[PageNumber].length) {
            this.PreviewCB[PageNumber] = new Array();
          }
        }
        if (!this.PreviewCB[PageNumber]) {
          this.PreviewCB[PageNumber]   = new Array();
        }
        this.PreviewCB[PageNumber][i] = setID;
      }
      PageTargetClone.childNodes[i].id = setID;
    }

    // if you want to set the PageTarget
    if (LayoutID != '') {
      PageTargetClone.setAttribute('id', placeHolder);
      Element.removeClassName(PageTargetClone, PageTargetClone.className);

      if (PageTarget.className == PageClass + '_active') {
        Element.addClassName(PageTargetClone, PageClass + '_active');
      }
      else {
        Element.addClassName(PageTargetClone, PageClass);
      }
    }

    // replace the PageTarget
    $(PageParent).replaceChild(PageTargetClone, PageTarget);

    var setPage = $(placeHolder);

    setPage.onclick = function() {
      project.lastPage = parseInt(project.getActivePage('PhotobookPage', 'PhotobookDesktop').split('_')[1]);
      project.changePage(this);
    };

    setPage.onmouseout = function() {
      var activeCB = getElementsByClass('ContentBox_active', $('PhotobookDesktop'), 'div');
      $A(activeCB).each(function(acb) {
         project.unsetDesktopActiveBox(acb);
      });
    };
    this.setPageStyle(setPage, factor, PageClass, PageNumber, this.CupHeight);

    // set the PageContent
    if (setPage.hasChildNodes()) {
      for (var i = 0; i < setPage.childNodes.length; i++) {
        if (setPage.childNodes[i].className == 'ContentBox' || setPage.childNodes[i].className == 'ContentBox_active') {
           this.setPageContent(setPage, setPage.childNodes[i], PageNumber, PageClass);
        }
      }
    }

    // set the BoxContent
    if (content) {
      $H(content).each(function(c) {
        var boxID            = c.value.split('Content')[1];
        var box              = $(PageType + 'ContentBox' + boxID);
        var imgID            = PageType + 'image' + boxID + '_imageBox_' + this.CBObjects[boxID].ID;
        var img             = this.setContent(box, boxID, imgID);
        img.src             = this.CBObjects[boxID].getImageSrc(PageType);
        box.appendChild(img);
        this.imagePreloader(box, img, boxID);
        this.checkQuality(box, boxID);
        // !!!Element.setStyle(box, { backgroundColor: 'transparent'});
      }.bind(this))
    }
  }

  this.setContent = function(box, boxID, ID, OffsetWidth, OffsetHeight) {
    if (box.parentNode.parentNode.className == 'Photobook') {
      var OffsetWidth   = this.CBObjects[boxID].OffsetWidth;
      var OffsetHeight = this.CBObjects[boxID].OffsetHeight;
    }
    else {
      var OffsetWidth   = (parseFloat(box.getAttribute('floatWidth'))  * parseInt(box.parentNode.style.width)  / 100);
      var OffsetHeight = (parseFloat(box.getAttribute('floatHeight')) * parseInt(box.parentNode.style.height) / 100);
    }

    var newImage = document.createElement('img');
    newImage.id  = ID;

    Element.setStyle(newImage, { position : 'absolute',
                                 left     : (this.CBObjects[boxID].Left * OffsetWidth) + 'px',
                                 top      : (this.CBObjects[boxID].Top   * OffsetHeight) + 'px' });
    return newImage;
  }

  this.imagePreloader = function(ContenBox, newImage, BoxID) {

    // show preloder
    Element.setStyle(ContenBox, { background: '#FEFEFE url(' + _AjaxLoaderImage + ') ' + '48% 48% no-repeat'});

    // onload
    newImage.onload = function() {
      if (ContenBox.getAttribute('type') == 'calendar') {
        Element.setStyle(this, { display:'block'});
        Element.setStyle(this, { visibility:'visible'});
      }
      Element.setStyle(this, { visibility:'visible'});
      Element.setStyle(ContenBox, { background: ''});
      Element.setStyle(ContenBox, { backgroundColor: 'transparent'});
    }

    if (ContenBox.getAttribute('type') != 'calendar') {
      project.checkQuality(ContenBox, BoxID);
    }
  }

  this.setPageContent = function(page, box, number, cssClass) {

    var Nr        = parseInt(number);
    var newWidth   = box.getAttribute('floatWidth');
    var newHeight  = box.getAttribute('floatHeight');
    var newTop    = box.getAttribute('positionLeft');
    var newLeft    = box.getAttribute('positionTop');

    var z = 1;
    if (z = box.getAttribute('z')) {
      Element.setStyle(box, { zIndex: z });
    }

    box.style.width  = newWidth   + '%';
    box.style.height = newHeight  + '%';
    box.style.left    = newTop     + '%';
    box.style.top    = newLeft     + '%';

    if (box.firstChild) {
      // !!!Element.setStyle(box, { backgroundColor: 'transparent'});
    }

    this.setCanvasBorder(page);

    if ((typeof this.Page[Nr].no_image == 'undefined')
    && ((box.getAttribute("type") == 'calendar' && Nr > 0)
     || (box.getAttribute("type") == 'brand'))) {

      var cssBoxColor             = Element.getStyle(box, 'backgroundColor');
      var defaultImage             = new Image();
      defaultImage.style.display   = 'none';

      defaultImage.onload = function(box) {
        this.style.display = 'block';
      }

      // on first project load: box offset dosent exist
      var defaultImageWidth    = Math.ceil(parseInt(page.style.width)  * newWidth / 100);
      var defaultImageHeight  = Math.ceil(parseInt(page.style.height) * newHeight / 100);
      this.imagePreloader(box, defaultImage);

      var imageParameter = '/interfaces/getPNGOnBG.php?type=' + box.getAttribute('type')
                           + '&color=' + this.Page[Nr].color
                           + '&size=' + defaultImageWidth  + 'x' + defaultImageHeight;

      switch (box.getAttribute('type')) {
        case 'calendar':
        // Parameter für Images-Kalendarien
        imageParameter += '&year='  + this.projectOptions.year
                        + '&item='  + this.Numbers[Nr].id
                        + '&month=' + this.Numbers[Nr].month;

        var size = this.getBoxSizeMM(box.getAttribute('floatWidth'), box.getAttribute('floatHeight'));
        // kalendarium in mm + Schriftart
        if (this.projectOptions.calendar_style && this.projectOptions.calendar_style != '') {
          imageParameter += '&format='  + _Format
                         +  '&style='   + this.projectOptions.calendar_style
                         +  '&lang='    + this.projectOptions.calendar_lang
                         +  '&size_mm=' + size[0] + 'x' + size[1];
        }
        break;
      }

      defaultImage.src = imageParameter;

      if (box.firstChild) {
        box.replaceChild(defaultImage, box.firstChild);
      }
      else {
        box.appendChild(defaultImage);
      }

      // Falls das Bild aus Cache kommt, wird onload oft nicht ausgelöst. Hier wird 'nachgeholfen'
      if (box.getAttribute('type') == 'brand') {
        defaultImage.style.display = 'block';
      }
    }
    else if (box.firstChild) {
      var cbID = box.id.split('ContentBox')[1];

      if (!this.CBObjects[cbID])
        return;

      if (box.firstChild.id.split('imageBox_')[1]) {
        var imgID = page.parentNode.className + 'image' + cbID + '_imageBox_' + box.firstChild.id.split('imageBox_')[1];
      }

      var newImage   = this.setContent(box, cbID, imgID);
      newImage.src   = this.CBObjects[cbID].getImageSrc(page.parentNode.className);
      box.replaceChild(newImage, box.firstChild);
      this.imagePreloader(box, newImage, cbID);

      // register DesktopDraggable
      if (this.allContentDrags[cbID]) {
        this.deregisterContentDrag(cbID);
        this.registerContentDrag($('PhotobookContentBox' + cbID).firstChild, cbID);
      }
      else {
        if ($('PhotobookContentBox' + cbID)) {
          this.registerContentDrag($('PhotobookContentBox' + cbID).firstChild, cbID);
        }
      }
    }
  }

  this.handleCursor = function(toolbar_cursor, toolbar_function, cssCursor) {

    if (this.activeBox != this.lastActiveBox) {
      this.ToolbarCursor    = toolbar_cursor;
      this.ToolbarFunction = toolbar_function;
      // assign cursor to active Box
      if (this.activeBox != '') {
        if (cssCursor) {
          var ActiveBox = $('Photobook' + this.activeBox);
          if (ActiveBox) {
            ActiveBox.style.cursor = toolbar_cursor;
            this.boxBugFixer(ActiveBox);
          }
        }
        else {
          var ActiveBox = $('Photobook' + this.activeBox);
          if (ActiveBox) {
            ActiveBox.style.cursor = 'url(' + toolbar_cursor + '),pointer';
            this.boxBugFixer(ActiveBox);
          }
        }
      }
      this.lastActiveBox = this.activeBox;
    }
  }

  this.setPageColor = function(page, color, Nr, desktop, setContentColor) {
    // falls ein farbiges Hintergrundbild gezeigt werden soll
    if (desktop && this.Page[Nr].bg_image && this.Page[Nr].bg_image == 1) {

      var bg = 'transparent url(' + _BackgroundCover
           + '&size='  + this.bgCoverSize[0] + 'x' + (this.DesktopHeight + this.Page[Nr].bg_h)
           + '&color=' + this.getCoverColor(this.Page[Nr].color, page, Nr)
           + ') ' + this.Page[Nr].bg_x + 'px ' + this.Page[Nr].bg_y + 'px no-repeat';

      var photobookFrame = $('PhotobookFrame');
      Element.setStyle(photobookFrame, { background: bg });
      if ((browserType == 'ie') && (browserVersion > 6)) {
        this.boxBugFixer(photobookFrame);
      }
    }
    // sonst die farbe
    else {
      Element.setStyle(page, { background: '#' + this.getCoverColorPreview(color, Nr) });
      if ((browserType == 'ie') && (browserVersion > 6)) {
        this.boxBugFixer(page);
      }
    }
    // falls ein defaultBild in der farbe angepasst werden muss
    if (setContentColor) {
      this.setDefaultImageColor(page, Nr, color);
    }
  }

  this.getCoverColorPreview = function (returnColor, Nr) {
    // wenn dem Cover andere spezielle Farben zugewiesen werden sollen
    var colorTypeMode;
    if ((colorTypeMode = this.Page[Nr].color_mode) && colorTypeMode == 'full') {
      $H(this.SpecialCoverColor).each(function(aCoverColorType) {
        returnColor = aCoverColorType.value;
      });
    }
    return returnColor;
  }

  this.setColor = function(Nr, newColor, type, side) {

    if (!Nr && Nr != 0) {
      Nr = this.activePageNr;
    }

    // Umschlagseiten bei Büchern bekommen keine Farben
    if (this.Page[Nr].layoutID && this.Page[Nr].layoutID == 'Empty') {
      return false;
    }

    Nr = parseInt(Nr);

    // Farbe speichern
    if (newColor && this.Page[Nr].type == type) {
      this.Page[Nr].color = newColor;
      if (this.Page[Nr].type == 'cover'){
        // speicher die cover-Farbe
        var dataObject = { cover_color: newColor };
        this.saveProject('saveProjectAttributes', dataObject);
        // speicher die Color in den CoverParts
        if (project.pageType == 'single' || project.pageType == 'one') {
          this.safeDataFromPage($(this.previewPageNames['Left'] + Nr), Nr);
        }
        else {
          this.Page[-1].color = newColor;
          this.Page[-2].color = newColor;
          this.safeDataFromPage($('PreviewPageLeft_-2'), -2);
          this.safeDataFromPage($('PreviewPageRight_-1'), -1);
        }
      }
    }

    // wenn die Farbe des covers geändert wird
    if (newColor && (type == 'cover')) {
      // setzte die preview
      var previewCoverPage = '';
      // für doppelseiten preview
      if (previewCoverPage = $(this.previewPageNames['Right'] + this.page_cover_last)) {
        this.setPageColor(previewCoverPage, this.Page[Nr].color, this.page_cover_last, false, true);
        if (previewCoverPage = $(this.previewPageNames['Left'] + (this.page_cover_last-1))) {
          this.setPageColor(previewCoverPage, this.Page[Nr].color, (this.page_cover_last-1), false, true);
          // setzte das cover im desktop
          if (desktopCoverPage = $(project.getActivePage('PhotobookPage', 'PhotobookDesktop'))) {
            this.setPageColor(desktopCoverPage, this.Page[Nr].color, this.desktopPages[this.PageSide], true, false);
          }
        }
      }
      // für einfache preview
      else {
        if (previewCoverPage = $(this.previewPageNames['Left'] + this.page_cover_last)) {
          this.setPageColor(previewCoverPage, this.Page[Nr].color, Nr, false, true);
        }
      }
      // für doppelseiten desktop
      if (desktopCoverPage = $(this.desktopPageNames['Right'] + this.page_cover_last)) {
        this.setPageColor(desktopCoverPage, this.Page[Nr].color, Nr, true, true);
        if (desktopCoverPage = $(this.desktopPageNames['Left'] + (this.page_cover_last-1))) {
          this.setPageColor(desktopCoverPage, this.Page[Nr].color, Nr, true, true);
        }
      }
      // für einfachen desktop
      else {
        if (desktopCoverPage = $(this.desktopPageNames['Left'] + (this.page_cover_last))) {
          this.setPageColor(desktopCoverPage, this.Page[Nr].color, Nr, true, true);
        }
      }
    }
    // wenn eine Farbe auf einer Seite geändert wird
    else {
      // setze die preview
      var previewPage = '';
      if (previewPage = $(this.previewPageNames[side] + Nr)) {
        this.setPageColor(previewPage, this.Page[Nr].color, Nr, false, true);
      }
      // setze den desktop
      var desktopPage = '';
      if (desktopPage = $(this.desktopPageNames[side] + Nr)) {
        this.setPageColor(desktopPage, this.Page[Nr].color, Nr, true, true);
      }
    }
  }

  this.setDefaultImageColor = function(page, Nr, color) {
    if (page) {
      $A(page.childNodes).each(function(element) {
        if (element.nodeType == Node.ELEMENT_NODE && element.getElementsByTagName('img').length > 0) {
          if (element.getAttribute('type') == 'calendar') {
            var imgTag = element.getElementsByTagName('img')[0];
            imgTag.src = imgTag.src.replace(/color=[A-Fa-f0-9]{6}/, 'color=' + color);
          } else if (element.id) {
            var boxID = element.id.split('ContentBox')[1];
            if (this.CBObjects[boxID] && this.CBObjects[boxID].Type == 'text') {
              var view = page.className.split('Page')[0];
              this.CBObjects[boxID].bgColor = color;
              element.firstChild.src = this.CBObjects[boxID].getImageSrc(view);
            }
          }
        }
      }.bind(this));
    }
  }

  this.setContentDefaultSize = function(ContentID) {

    var contentSize = new Array();
    var boxSize     = this.getBoxSize(this.CBObjects[ContentID].PercentWidth, this.CBObjects[ContentID].PercentHeight);

    this.CBObjects[ContentID].setImageSize(boxSize[0], boxSize[1]);
    this.CBObjects[ContentID].Top   = 0;
    this.CBObjects[ContentID].Left = 0;

    contentSize[0] = this.roundValue(this.CBObjects[ContentID].ImagePercentWidth, 8);
    contentSize[1] = this.roundValue(this.CBObjects[ContentID].ImagePercentHeight, 8);

    return contentSize;
  }

  this.getXMLDataFromPage = function(page, Nr) {

    var onePage = '';
    var pageNr  = parseInt(Nr);

    if (onePage = this.Page[parseInt(pageNr)]) {
      var pageColor = onePage.color;
    } else {
      var pageColor = '';
    }

    var layoutID  = this.Page[Nr].layoutID ? this.Page[Nr].layoutID : '';
    var pageCB     = page.childNodes;
    var XMLString = '<' + this.Page[pageNr].type + ' number="' + pageNr + '" layout_id="' + layoutID + '" color="' + pageColor + '" >';

    $A(page.childNodes).each(function(aBox) {

      var ContentID = aBox.id.split('ContentBox')[1];
      var floatTop  = this.roundValue((aBox.getAttribute('positionTop') / 100), 8);
      var floatLeft = this.roundValue((aBox.getAttribute('positionLeft') / 100), 8);

      if (aBox.className == 'ContentBox' || aBox.className == 'ContentBox_active') {

        var addBoxParams = '';

        // falls es einen zIndex gibt
        if (aBox.getAttribute('z')) {
          addBoxParams += ' z="' + aBox.getAttribute('z') + '"';
        }
        // falls es einen bleed gibt (spezielle canvas-layouts)
        if (aBox.getAttribute('bleedWidth')) {
          addBoxParams += ' bleedwidth="' + aBox.getAttribute('bleedWidth') + '"';
          addBoxParams += ' bleedheight="' + aBox.getAttribute('bleedWidth') + '"';
        }
        // falls es KalendarAttribute gibt
        if (aBox.getAttribute('type') == 'calendar') {
          addBoxParams += ' year="' + project.Numbers[pageNr].year + '"';
          addBoxParams += ' month="' + project.Numbers[pageNr].month + '"';
        }
        if (aBox.getAttribute('type')) {
          addBoxParams += ' type="' + (this.CBObjects[ContentID] ? this.CBObjects[ContentID].Type : aBox.getAttribute('type')) + '"';
        }
        if (aBox.getAttribute('permission')) {
          addBoxParams += ' permission="' + aBox.getAttribute('permission') + '"';
        }

        XMLString += '<box id="' + ContentID   + '"'
                   + ' top="'    + floatTop    + '"'
                   + ' left="'   + floatLeft   + '"'
                   + ' width="'  + this.roundValue((parseFloat(aBox.getAttribute('floatWidth')) / 100), 7) + '"'
                   + ' height="' + this.roundValue((parseFloat(aBox.getAttribute('floatHeight')) / 100), 7) + '"'
                   + addBoxParams + '>';

        // content
        if (this.CBObjects[ContentID] && aBox.getAttribute('type') != 'calendar') {
          if (this.checkValidImageType(this.CBObjects[ContentID].Type)) {

            var contentSize = new Array();
            contentSize[0]  = this.roundValue(this.CBObjects[ContentID].ImagePercentWidth, 8);
            contentSize[1]  = this.roundValue(this.CBObjects[ContentID].ImagePercentHeight, 8);

            // bei 0-Werten(width, height): Bild zurücksetzen
            if (contentSize[0] == 0 || contentSize[1] == 0) {
              contentSize = this.setContentDefaultSize(ContentID);
            }

            XMLString += '<content id="'    + this.CBObjects[ContentID].ID         + '"'
                       + ' owner="'         + this.CBObjects[ContentID].owner      + '"'
                       + ' offset_y="'      + this.CBObjects[ContentID].Top        + '"'
                       + ' offset_x="'      + this.CBObjects[ContentID].Left       + '"'
                       + ' width="'         + contentSize[0] + '"'
                       + ' height="'        + contentSize[1] + '"'
                       + ' alpha="'         + this.CBObjects[ContentID].Alpha      + '"'
                       + ' origwidth="'     + this.CBObjects[ContentID].origwidth  + '"'
                       + ' origheight="'    + this.CBObjects[ContentID].origheight + '"/>';
          }

          if (this.CBObjects[ContentID].Type == 'text') {
            XMLString += '<content id="'    + this.CBObjects[ContentID].ID    + '"'
                       + ' owner="'         + this.CBObjects[ContentID].owner + '"/>';
          }
        }
        XMLString += '</box>';
      }
    }.bind(this));

    XMLString += '</' + this.Page[pageNr].type + '>';

    return XMLString;
  }

  this.getDataFromActivePage = function() {
    // für aktive Seiten den AktiveStyle zurücksetzen
    this.unsetDesktopActiveBox();

    activePage    = $(this.getActivePage('PhotobookPage', 'PhotobookDesktop'));
    activePageNr  = activePage.id.split('_')[1];

    return { parts_number : activePageNr,
             xml_data     : this.getXMLDataFromPage(activePage, activePageNr) };
  }

  this.safeDataFromPage = function(page, Nr) {
    // für aktive Seiten den AktiveStyle zurücksetzen
    this.unsetDesktopActiveBox();

    // create the dataObject for REQUEST
    var dataObject = {
      parts_number: Nr,
      xml_data: this.getXMLDataFromPage(page, Nr)
    };

    this.saveProject('saveProjectParts', dataObject);
  }

  this.saveProject = function(act, dataObject) {

    if (this.projectOptions.view == 'public') {
      return;
    }

    if (dataObject) {
      dataObject.windowToken = windowToken;
    }

    switch (act) {
      case 'saveProject':
        // save attributes requires a data-object
        var parameter = 'action=saveProject&' + ($H(dataObject).toQueryString());
      break;
      case 'saveProjectParts':
        // save attributes requires a data-object
        var parameter = 'action=saveProjectParts&' + ($H(dataObject).toQueryString());
      break;
      case 'saveAllProjectParts':
        // save attributes requires a data-object
        var parameter = 'action=saveAllProjectParts&' + ($H(dataObject).toQueryString());
      break;
      case 'saveProjectAttributes':
        // save attributes requires a data-object
        var parameter = 'action=saveProjectAttributes&' + ($H(dataObject).toQueryString());
      break;
      // Speichern des aktuellen Fotobuch-Stands
      case 'saveAll':
        if (project.pageType == 'single' || project.pageType == 'one') {
          this.safeDataFromPage($('PhotobookPage_' + this.desktopPages['Left']), this.desktopPages['Left']);
        }
        else {
          this.safeDataFromPage($(this.desktopPageNames['Left'] + this.desktopPages['Left']), this.desktopPages['Left']);
          this.safeDataFromPage($(this.desktopPageNames['Right'] + this.desktopPages['Right']), this.desktopPages['Right']);
        }
        return;
      break;
    }

    var AjaxObject = new Ajax.Request(
                          _AjaxRequestFile, {
                            method: 'post',
                            parameters: parameter,
                            on403: UserAssignTools.login
                          });
  }

  this.roundValue  = function runde(x, n) {

    var e = Math.pow(10, n);
    var k = (Math.ceil(x * e) / e).toString();

    if (k.indexOf('.') == -1) {
      k += '.';
    }
    k += e.toString().substring(1);

    return parseFloat(k.substring(0, k.indexOf('.') + n+1));
  }

  this.setProjectSizeFactor  = function() {

    if (this.browserIndex >= 0) {
      var maxStageWidth = this.maxStageWidth-30;
    } else {
      var maxStageWidth = this.maxStageWidth;
    }

    if ((this.PageWidth >= this.PageHeight)) {
      this.Pagefactor = this.roundValue(maxStageWidth / (this.PageWidth * this.Pages), 8);

      if ((this.Pagefactor * this.PageHeight) > this.maxStageHeight) {
        this.Pagefactor = this.roundValue((this.maxStageHeight / this.PageHeight), 8);
      }
      this.Previewfactor  = this.roundValue((this.maxPreviewWidth / this.PageWidth), 8);
      this.Layoutfactor   = this.roundValue((this.maxPreviewHeight / this.PageWidth), 8);
    }
    else {
      this.Pagefactor = this.roundValue(this.maxStageHeight / (this.PageHeight), 8);

      if ((this.Pagefactor * this.PageWidth) > maxStageWidth) {
        this.Pagefactor = this.roundValue((this.PageWidth / maxStageWidth), 8);
      }
      this.Previewfactor  = this.roundValue((this.maxPreviewHeight / this.PageHeight), 8);
      this.Layoutfactor   = this.roundValue((this.maxLayoutHeight / this.PageHeight), 8);
    }

    // fix layout-bug calendar: mergin boxes
    if ((this.browserIndex >= 0) && project.pageType == 'single') {
      this.Previewfactor  = this.roundValue((parseFloat(this.Previewfactor) + 0.01), 8);
      this.Layoutfactor   = this.roundValue((parseFloat(this.Layoutfactor) + 0.01), 8);

      var layList = getElementsByClass('projectLayoutList');
        $A(layList).each(function(ll) {
          ll.style.height = (this.PageHeight * this.Layoutfactor + 30) + 'px';
      }.bind(this))
    }

    this.PreviewWidth    = this.PageWidth  * this.Previewfactor;
    this.PreviewHeight    = this.PageHeight * this.Previewfactor;
    this.bleedVertical   = this.roundValue((this.Bleed * 100 / this.PageHeight), 8);
    this.bleedHorizontal = this.roundValue((this.Bleed * 100 / this.PageWidth), 8);
  }

  // @todo do we need BookpageEmpty??

  this.setPageSize = function(PageWidth, PageHeight, FloatWidth, FloatHeight) {

    var BookPage      =  $('BookPage');
    var BookPageEmpty  =  $('BookPage_Empty');

    var BookPageSize  = new Array();
    BookPageSize[0]    = Math.floor(PageWidth   * this.Layoutfactor);
    BookPageSize[1]    = Math.floor(PageHeight * this.Layoutfactor);

    BookPage.setAttribute('floatWidth', FloatWidth);
    BookPage.setAttribute('floatHeight', FloatHeight);
    BookPageEmpty.setAttribute('floatWidth', FloatWidth);
    BookPageEmpty.setAttribute('floatHeight', FloatHeight);

    BookPage.style.width    = BookPageSize[0] + 'px';
    BookPage.style.height   = BookPageSize[1] + 'px';
    BookPageEmpty.style.width    = BookPageSize[0] + 'px';
    BookPageEmpty.style.height   = BookPageSize[1] + 'px';

    return BookPageSize;
  }

  this.changeLayout = function(cio, oldBoxWidth, oldBoxHeight, oldContentWidth, oldContentHeight, oldContentOffsetX, oldContentOffsetY) {

    var newBoxWidth       = project.roundValue(((cio.PercentWidth  / 100) * this.PageWidth), 6);
    var newBoxHeight      = project.roundValue(((cio.PercentHeight / 100) * this.PageHeight), 6);
    var origwidth         = cio.origwidth;
    var origheight        = cio.origheight;

    // wenn das bild gedreht wurde
    if (cio.Alpha == 90 || cio.Alpha == -90 || cio.Alpha == 270 || cio.Alpha == -270) {
      temp       = origwidth;
      origwidth  = origheight;
      origheight = temp;
    }

    var ratioContent = project.roundValue((origwidth   / origheight)   ,6);
    var ratioBox     = project.roundValue((newBoxWidth / newBoxHeight) ,6);
    var ratioOldBox  = project.roundValue((oldBoxWidth / oldBoxHeight) ,6);

    // SKALIERUNG
    var scale = 1;

    // ist der Content bereits skaliert
    if ((oldContentWidth > 1) && (oldContentHeight > 1)) {
      // kleinere Wert ist unser neuer scaleFaktor
      if (oldContentWidth < oldContentHeight) {
        scale = oldContentWidth;
      }
      else {
        scale = oldContentHeight;
      }
    }

    // Seitenverhaeltnis der Ausgabe kleiner als Bildseitenverhaeltnis
    // => Hoehe anpassen, Breite steht dann ueber
    if (ratioBox < ratioContent) {
      var newContentWidth  = project.roundValue(((origwidth / (origheight / newBoxHeight)) / newBoxWidth * scale), 6);
      var newContentHeight = 1 * scale;
    }
    // ansonten: => Breite anpassen, Hoehe steht ueber
    else {
      var newContentWidth  = 1 * scale;
      var newContentHeight = project.roundValue(((origheight / (origwidth / newBoxWidth)) / newBoxHeight * scale), 6);
    }

    // POSITIONIERUNG
    var offsetCenterX          = project.roundValue(((Math.abs(oldContentOffsetX) * oldBoxWidth)   + (oldBoxWidth / 2)), 6);
    var offsetCenterY          = project.roundValue(((Math.abs(oldContentOffsetY) * oldBoxHeight)  + (oldBoxHeight / 2)), 6);
    var offsetNewContentWidth  = project.roundValue((newContentWidth  * newBoxWidth),   6);
    var offsetNewContentHeight = project.roundValue((newContentHeight * newBoxHeight),  6);
    var offsetOldContentWidth  = project.roundValue((oldContentWidth  * oldBoxWidth),   6);
    var offsetOldContentHeight = project.roundValue((oldContentHeight * oldBoxHeight),  6);

    var valX        = project.roundValue((project.roundValue((offsetNewContentWidth * offsetCenterX), 6) / offsetOldContentWidth), 6);
    var valY        = project.roundValue((project.roundValue((offsetNewContentHeight * offsetCenterY), 6) / offsetOldContentHeight), 6);
    var tempWidth   = project.roundValue((newBoxWidth / 2), 6)
    var tempHeight  = project.roundValue((newBoxHeight / 2), 6)
    var valDiffX    = project.roundValue((valX - tempWidth), 6);
    var valDiffY    = project.roundValue((valY - tempHeight), 6);

    var newContentOffsetX  = project.roundValue(((valDiffX) / newBoxWidth * -1), 6);
    var newContentOffsetY  = project.roundValue(((valDiffY) / newBoxHeight * -1), 6);

    // befindet sich das Bild wirklich im Bildausschnitt
    if ((project.roundValue((newContentWidth * newBoxWidth), 2) < project.roundValue((newBoxWidth + (Math.abs(newContentOffsetX) * newBoxWidth)), 2)) || (newContentOffsetX > 0)) {
      newContentOffsetX = 0;
    }

    if ((project.roundValue((newContentHeight * newBoxHeight), 2) < project.roundValue((newBoxHeight + (Math.abs(newContentOffsetY) * newBoxHeight)), 2)) || (newContentOffsetY > 0)) {
      newContentOffsetY = 0;
    }

    var content = {
      x: newContentOffsetX,
      y: newContentOffsetY,
      w: newContentWidth,
      h: newContentHeight
    };

    return content;
  }

  this.changeLayoutBoxContent = function(layoutBox, oldContent, newCBID) {

    var layWidth      = parseFloat(layoutBox.getAttribute('floatWidth'));
    var layBoxWidth   = parseFloat(layoutBox.parentNode.getAttribute('floatWidth'));
    var layHeight     = parseFloat(layoutBox.getAttribute('floatHeight'));
    var layBoxHeight  = parseFloat(layoutBox.parentNode.getAttribute('floatHeight'));
    var boxSize       = this.getBoxSize(layWidth, layHeight)

    // die alten Werte merken
    var oldBoxWidth       = (oldContent.PercentWidth  / 100) * project.PageWidth;
    var oldBoxHeight      = (oldContent.PercentHeight / 100) * project.PageHeight;
    var oldContentWidth   = oldContent.ImagePercentWidth;
    var oldContentHeight  = oldContent.ImagePercentHeight;
    var oldContentOffsetX = oldContent.Left;
    var oldContentOffsetY = oldContent.Top;

    // setze Box neu
    project.CBObjects[newCBID]               = Object.clone(oldContent);
    project.CBObjects[newCBID].CB            = newCBID;
    project.CBObjects[newCBID].OffsetWidth   = boxSize[0];
    project.CBObjects[newCBID].OffsetHeight  = boxSize[1];
    project.CBObjects[newCBID].Left           = 0;
    project.CBObjects[newCBID].Top           = 0;
    project.CBObjects[newCBID].PercentWidth  = parseFloat(layoutBox.getAttribute('floatWidth'));
    project.CBObjects[newCBID].PercentHeight = parseFloat(layoutBox.getAttribute('floatHeight'));

    // den content an die Box neu anpassen
    // für Texte (Dummywerte)
    if (project.CBObjects[newCBID].Type == 'text') {
      var content = { x: 0, y: 0, w: 1, h: 1 };
    }
    // für Bilder
    else {
      var content = project.changeLayout(project.CBObjects[newCBID], oldBoxWidth, oldBoxHeight, oldContentWidth, oldContentHeight, oldContentOffsetX, oldContentOffsetY);
    }

    // setze Bild neu
    if (content.w > content.h) {
      newScale = content.h;
    }
    else {
      newScale = content.w;
    }
    //
    project.CBObjects[newCBID].setImageSize(project.CBObjects[newCBID].OffsetWidth, project.CBObjects[newCBID].OffsetHeight, newScale);
    project.CBObjects[newCBID].Left = content.x;
    project.CBObjects[newCBID].Top  = content.y;

    return 'Content' + newCBID;
  }

  this.changeLayoutBoxes = function(PageNr, layout) {

    var layoutBoxes   = getElementsByClass('ContentBox', layout, 'div');
    var contentNodes  = new Object();
    var oldCBObjects  = new Hash();

    // hole alle Objekte einer Seite
    $H(this.CBObjects).each(function(cio) {
      var cioPageNr = parseInt(cio.value.CB.split('_')[1]);
      var cioBoxNr  = parseInt(cio.value.CB.split('_')[3]);
      if (cioPageNr == PageNr) {
        oldCBObjects[cio.value.CB] = cio.value;
      }
    });

    // layoutBoxen durchlaufen und Content zuordnen
    $A(layoutBoxes).each(function(oneBox) {

      var layoutID = oneBox.id.split('_');
      var newCBID  = '_' + PageNr + '_' + layoutID[1] + '_' + layoutID[2];

      // wenn der InhaltsTyp vorgegeben ist
      // suche Inhalt
      var content    = false;
      var permission = false;
      var setContent = true;

      // content aus dem Layout
      if (oneBox.firstChild) {
        // neues contentObjekt anlegen
        var imageID           = oneBox.firstChild.id.split('_')[2];
        var ContenBox         = $('PhotobookContentBox' + newCBID);
        var ContentClass      = ContenBox.parentNode.parentNode.className;
        var Owner             = oneBox.firstChild.getAttribute('owner');
        var origImageWidth    = parseFloat(oneBox.firstChild.getAttribute('origwidth'));
        var origImageHeight    = parseFloat(oneBox.firstChild.getAttribute('origheight'));
        var boxType           = ContenBox.getAttribute('type');

        project.newContentImage(Owner, origImageWidth, origImageHeight, ContentClass, ('PhotobookContentBox' + newCBID), ContenBox, boxType, imageID, 0);
      }
      else {
        if (oneBox.getAttribute('type') != 'calendar') {
          if ((permission = oneBox.getAttribute('permission')) && permission != 'null') {
            $H(oldCBObjects).each(function(oneContentObject) {
              var imgType; // text, logo, image
              if (setContent && (oneContentObject.value.Type == permission)) {
                if (content = project.changeLayoutBoxContent(oneBox, oneContentObject.value, newCBID)) {
                  contentNodes[newCBID] = content;
                  setContent = false;
                }
                $H(oldCBObjects).remove(oneContentObject.key);
                if (oneContentObject.key != newCBID) {
                  $H(project.CBObjects).remove(oneContentObject.key);
                }
              }
            });
          }
          // oder nimm das nächste aus der Liste
          else {
            var next = $H(oldCBObjects).keys();
            if (next.length > 0) {
              if (content = project.changeLayoutBoxContent(oneBox, oldCBObjects[next[0]], newCBID)) {
                contentNodes[newCBID] = content;
              }
              $H(oldCBObjects).remove(next[0]);
              if (next[0] != newCBID) {
                $H(project.CBObjects).remove(next[0]);
                $H(contentNodes).remove(next[0]);
              }
            }
          }
        }
      }
    });

    return contentNodes;
  }

  this.setLayoutByUser = function(layout) {

    var PageNr      = this.desktopPages[this.PageSide];
    var layout      = this.handlePage(layout, false, true);
    var desktop     = this.getActivePage('PhotobookPage', 'PhotobookDesktop');
    var preview     = this.getActivePage('PreviewPage', 'PreviewListeTemplate');
    var desktopPage = $(desktop);
    var previewPage = $(preview);

    // festes layout nehmen wenn vorgeschrieben
    if (this.Page[PageNr].layout && this.Page[PageNr].fixLayout == 1) {
      //layout = $('BookPage_' + this.Page[PageNr].layout);
      return;
    }

    var layoutRange = this.changeLayoutRange.from + this.changeLayoutRange.to;

    // Layoutwechsel für mehrere Seiten
    if (layoutRange > 0) {
      var previeList   = ($('PreviewListeTemplate'))
      var previewPages = getElementsByClass('PreviewPage', previeList, 'div');
      previewPages     = previewPages.concat(getElementsByClass('PreviewPage_active', previeList, 'div'));
      var xml_data     = '';

      if ((layoutRange > 0) && (PageNr > this.changeLayoutRange.from) && (PageNr <= this.changeLayoutRange.to)) {
        $A(previewPages).each(function (onePage) {
          var previewPageNr = parseInt(onePage.id.split('_')[1]);
          if (previewPageNr > this.changeLayoutRange.from && previewPageNr <= this.changeLayoutRange.to) {
            var contentNodes = this.changeLayoutBoxes(previewPageNr, layout);
            this.setPageLayout(layout, this.Previewfactor, onePage.id, previewPageNr, contentNodes, 'Preview');
            var getOnePage = $(onePage.id);
            xml_data += this.getXMLDataFromPage(getOnePage, previewPageNr);
          }
        }.bind(this));
      }
      // alle geänderten ProjectParts speichern
      if (xml_data != '') {
        this.saveProject('saveAllProjectParts', { xml_data: ('<parts>' + xml_data + '</parts>') });
      }
    }

    // einseitiger Layoutwechsel mit Desktop
    if (this.getNoLayout(this.desktopPages[this.PageSide], layout)) {
      var contentNodes = this.changeLayoutBoxes(PageNr, layout);
      this.setPageLayout(layout, this.Pagefactor, desktop, PageNr, contentNodes, 'Photobook');
      this.handlePage($(desktopPage.id), true, true);
      this.scrollFunk('PreviewListeTemplate',true);
      this.setDropZoneDesktop();
      this.setDesktopContentBox();
      this.showCanvasBorder(layout);
    }
  }

  this.setLayoutPage = function(LayoutClone, LayoutName, BookPageWidth, LayoutListePage, ID, disp) {

    LayoutClone.style.width        = BookPageWidth + 'px';
    LayoutClone.childNodes[0].id   = 'BookPage_' + LayoutName;
    LayoutClone.childNodes[1].id   = 'BookTextID_' + ID;
    LayoutClone.id                 = 'LayoutTemplate_' + ID;
    LayoutClone.onclick           = this.setLayoutByUser.bind(this, LayoutClone);

    // Name des Layout setzen
    LayoutClone.getElementsByTagName('p')[0].firstChild.data = LayoutName;
    var newLayout = LayoutListePage.appendChild(LayoutClone);
    newLayout.show();
  }

  this.setLayoutBoxSizeConverter = function(boxValue, unit, pageValue) {
    if (unit == 'mm') {
      boxValue = this.roundValue((boxValue / pageValue * 100), 6);
    }
    return boxValue;
  }

  this.setLayoutBoxContent = function(layoutBox, content, layoutID, LayoutPageSize) {

    if (this.checkValidImageType(content.getAttribute('type'))) {

      var newContent  = new Image();
      var w           = LayoutPageSize[0] * parseFloat(content.getAttribute('width'))  / 100;
      var h           = LayoutPageSize[1] * parseFloat(content.getAttribute('height')) / 100;
      var contentID   = content.getAttribute('id');
      newContent.id   = 'LayoutImage_' + layoutID + '_' + contentID;

      $A(content.attributes).each(function(oneAttribute) {
        if (oneAttribute.nodeName != 'width' && oneAttribute.nodeName != 'height' && oneAttribute.nodeName != 'id') {
          newContent.setAttribute(oneAttribute.nodeName, oneAttribute.nodeValue);
        }
      });

      newContent.src = ImageTools.getStaticImageURLByOwner(content.getAttribute('owner'), FOA.User.id, contentID, content.getAttribute('type'), w, h, ('&enlarge=true&rotate=' + content.getAttribute('alpha')));
      layoutBox.appendChild(newContent);
    }

    return layoutBox;
  }

  this.setLayoutBox = function(XML, ContentBox, SubBookPage, i, j, unit) {

    var ContentBoxClone = ContentBox.cloneNode(true);
    ContentBoxClone.id   = ('ContentBox_' + i + '_' + j);
    var newContentBox   = SubBookPage.appendChild(ContentBoxClone);
    var CBWidth          = this.setLayoutBoxSizeConverter(parseFloat(XML.getAttribute('width')),       unit, this.PageWidth);
    var CBHeight        = this.setLayoutBoxSizeConverter(parseFloat(XML.getAttribute('height')),      unit, this.PageHeight);
    var CBX              = this.setLayoutBoxSizeConverter(parseFloat(XML.getAttribute('x')),  unit, this.PageWidth);
    var CBY              = this.setLayoutBoxSizeConverter(parseFloat(XML.getAttribute('y')),  unit, this.PageHeight);
    var bleedWidth      = this.setLayoutBoxSizeConverter(parseFloat(XML.getAttribute('bleedwidth')),  unit, this.PageWidth);
    var bleedHeight     = this.setLayoutBoxSizeConverter(parseFloat(XML.getAttribute('bleedheight')), unit, this.PageHeight);
    var type            = XML.getAttribute('type');
    var permission      = XML.getAttribute('permission');
    var z               = XML.getAttribute('z');

    var grey    = 200 - (j * 15);
    var bgColor = 'rgb(' + grey + ',' + grey + ',' + grey + ')';

    if (type && !newContentBox.hasChildNodes()) {
      switch (type) {
        case 'text':
          Element.setStyle(newContentBox, { background: this.bgColors.text + ' url(' + 'http://www8.fotoalbum.de/mandants/root/gfx/icon_layout_text.gif?1236782233)' });
        break;
        case 'all':
          Element.setStyle(newContentBox, { background: bgColor });
        break;
        case 'calendar':
          Element.setStyle(newContentBox, { background: this.bgColors.calendar });
        break;
      }
    }
    if (permission) {
      switch (permission) {
        case 'logo':
          Element.setStyle(newContentBox, { background: this.bgColors.logo });
        break;
      }
    }

    this.setLayoutBoxSize(newContentBox, CBWidth, CBHeight, CBX, CBY, type, z, bleedWidth, bleedHeight, type, permission);

    return newContentBox;
  }

  this.setLayoutBoxSize = function(Box, CBWidth, CBHeight, CBX, CBY, type, z, bleedWidth, bleedHeight, type, permission) {

    Box.setAttribute('floatWidth',     CBWidth);
    Box.setAttribute('floatHeight',   CBHeight);
    Box.setAttribute('positionLeft',  CBX);
    Box.setAttribute('positionTop',   CBY);
    Box.setAttribute('type',           type);
    Box.setAttribute('permission',     permission);

    if (z) {
      Box.setAttribute('z', z);
    }

    if (bleedWidth) {
      Box.setAttribute('bleedWidth', bleedWidth);
      Box.setAttribute('bleedHeight', bleedHeight);
    }

    Box.style.width     = Math.ceil(CBWidth)  + '%';
    Box.style.height     = Math.ceil(CBHeight)  + '%';
    Box.style.left      = CBX       + '%';
    Box.style.top        = CBY       + '%';
    Box.style.display   = 'block';
    Box.style.position   = 'absolute';
  }

  this.buildPageContent = function(Nr, Layout, newPreviewPage, factor, XMLPage, show) {

    var page = XMLPage.firstChild;
    Nr       = parseInt(Nr);

    if (page.tagName == 'cover') {
      var stageWidth  = this.CoverWidth;
      var stageHeight  = this.CoverHeight;
    }
    else if (page.tagName == 'page') {
      var stageWidth  = this.PageWidth;
      var stageHeight  = this.PageHeight;
    }
    // Weder Cover noch Page ?
    else {
      this.setPageLayout(Layout, factor, newPreviewPage, Nr);
      return;
    }
    // set Page
    var LayTemp  = $('BookPage_Empty').cloneNode(true);
    LayTemp.id  = 'LayTemp';
    // set LayoutID
    if (page.getAttribute('layout_id')) {
      this.Page[Nr].layoutID = page.getAttribute('layout_id');
    }
    // set Color
    if (page.getAttribute('color')) {
      this.Page[Nr].color = page.getAttribute('color');
    }
    else if (page.tagName == 'cover') {
      this.Page[Nr].color = this.CoverColor;
    }

    var contentBox     = page.getElementsByTagName('box');
    var SubBookPage   = $(newPreviewPage);
    var contentNodes  = Object();

    // set ContentBoxes
    for (var j = 0; j < contentBox.length; j++) {

      var ContentBoxClone = $('ContentBox').cloneNode(true);
      var tempID          = contentBox[j].getAttribute('id').split('_');
      ContentBoxClone.id   = 'ContentBox_' + tempID[2] + '_' + tempID[3];
      var newContentBox   = LayTemp.appendChild(ContentBoxClone);
      var CBHeight        = this.roundValue((parseFloat(contentBox[j].getAttribute('height')) * 100), 8);
      var CBWidth          = this.roundValue((parseFloat(contentBox[j].getAttribute('width'))   * 100), 8);
      var CBX              = this.roundValue((parseFloat(contentBox[j].getAttribute('left'))   * 100), 8);
      var CBY              = this.roundValue((parseFloat(contentBox[j].getAttribute('top'))     * 100), 8);
      var type            = contentBox[j].getAttribute('type');
      var permission      = contentBox[j].getAttribute('permission');
      var z               = contentBox[j].getAttribute('z');
      var bleedWidth      = parseFloat(contentBox[j].getAttribute('bleedwidth'));
      var bleedHeight     = parseFloat(contentBox[j].getAttribute('bleedheight'));

      this.setLayoutBoxSize(newContentBox, CBWidth, CBHeight, CBX, CBY, type, z, bleedWidth, bleedHeight, type, permission);

      //Ausnahme für erste Seite Formblitz-DATEBOOK
      if (_Format == 'DATEBOOK' && Nr == 1) {
        if (project.Page[Nr].layout && project.Page[Nr].fixLayout && (project.Page[Nr].fixLayout == 1)) {
          if (j > 0) {
            break;
          }
          if (contentBox.length > 2) {
            LayTemp = $('BookPage_cover').cloneNode(true);
            break;
          }
        }
      }
      // set Content
      if (contentBox[j].getElementsByTagName('content')[0]) {

        var content       = contentBox[j].getElementsByTagName('content')[0];
        var PercentWidth  = parseFloat(content.getAttribute('width'));
        var PercentHeight  = parseFloat(content.getAttribute('height'));
        var BoxWidth       = this.roundValue((parseFloat(contentBox[j].getAttribute('width')) * this.Pagefactor * stageWidth), 8);
        var BoxHeight     = this.roundValue((parseFloat(contentBox[j].getAttribute('height')) * this.Pagefactor * stageHeight), 8);
        var boxID          = contentBox[j].getAttribute('id');

        // unterscheidung des Type(Image, Text)
        if (this.checkValidImageType(type)) {
          var cio = Object.extend(new ImageObjekt(content.getAttribute('owner'), content.getAttribute('id'), parseFloat(content.getAttribute('origwidth')), parseFloat(content.getAttribute('origheight'))),
                                  new ContentObjekt(type, boxID, (this.Previewfactor/this.Pagefactor), BoxWidth, BoxHeight, CBWidth, CBHeight));

          // get the image-propertys by boxsize
          cio.Left        = project.roundValue(parseFloat(content.getAttribute('offset_x')), 10);
          cio.Top          = project.roundValue(parseFloat(content.getAttribute('offset_y')), 10);
          cio.Alpha       = parseFloat(content.getAttribute('alpha'));

          if (PercentWidth > PercentHeight) {
            newScale = PercentHeight;
          }
          else {
            newScale = PercentWidth;
          }

          cio.setImageSize(BoxWidth, BoxHeight, newScale);

        } else if (type == 'text') {
          var cio = Object.extend(new TextObjekt('user', content.getAttribute('id'), this.Page[Nr].color),
                                  new ContentObjekt(type, boxID, (this.Previewfactor/this.Pagefactor), BoxWidth, BoxHeight, CBWidth, CBHeight));

        }

        this.CBObjects[boxID] = cio;
        contentNodes[boxID]   = 'Content' + boxID;
      }
    }

    this.setPageLayout(LayTemp, factor, newPreviewPage, Nr, contentNodes, show);
  };

  this.showTab = function(e, El, tabMenuList) {

    if (e) {
      Event.stop(e);
      El.blur();
    }

    for (var i=0; i<tabMenuList.length; i++) {
      Element.setStyle($(tabMenuList[i].id.split('_')[1]), { display: 'none'});
      tabMenuList[i].setAttribute('class', '');
      tabMenuList[i].setAttribute('className', '');
    }
    var showTab = $(El.id.split('_')[1]);

    Element.setStyle(showTab, { display: 'block'});
    El.setAttribute('class', 'active');
    El.setAttribute('className', 'active');

    if (showForm = showTab.getElementsByTagName('form')[0]) {
      $A(Form.getElements(showForm)).each(function (f){
        Element.setStyle(f, { visibility: 'visible'});
      });
    }
  }

   this.setToolbarActive = function(e, El) {

    Event.stop(e);
    El.blur();

    var tools = $('PhotobookToolbar').getElementsByTagName('a');
    $A(tools).each(function(t) {
      var activeClass;
      if (activeClass = t.id.split('toolbar_')[1]) {
        t.className = activeClass;
      }
    });

    El.className = El.id;
  }

  this.setObserver = function() {

    // projectFormular
    var formButtonProjectEditor;
    if (formButtonProjectEditor = $('formButtonProjectEditor')) {
      this.observer.setObserver(formButtonProjectEditor, 'click', FOA.formValidator.start.bindAsEventListener(FOA.formValidator));
    }

    // Tabs menu
    var tabMenuList = $('projectPalette').getElementsByTagName('li');
    for (var i=0; i < tabMenuList.length; i++) {
      this.observer.setObserver(tabMenuList[i], 'click', this.showTab.bindAsEventListener(this, tabMenuList[i], tabMenuList));
    }

    // toolbar
    this.observer.setObserver($('toolbar_colorpicker'),
                                    'click',
                                    function(e) {
                                         Event.stop(e);
                                         project.showColorPicker(e);
                                    }.bindAsEventListener(this));

    var toolTextElement;
    if (toolTextElement = $('toolbar_texteditor')) {
      this.observer.setObserver(toolTextElement,
                                      'click',
                                      function(e) {
                                           this.setLastActiveBox('');
                                           this.handleCursor(toolbar_cursor_texteditor,'texteditor',false);
                                           this.setToolbarActive(e, Event.element(e));
                                      }.bindAsEventListener(this));
    }
    this.observer.setObserver($('toolbar_zoom_plus'),
                                    'click',
                                    function(e) {
                                         this.setLastActiveBox('');
                                         this.handleCursor(toolbar_cursor_plus,'plus',false);
                                         this.setToolbarActive(e, Event.element(e));
                                    }.bindAsEventListener(this));
    this.observer.setObserver($('toolbar_zoom_minus'),
                                    'click',
                                    function(e) {
                                         project.setLastActiveBox('');
                                         project.handleCursor(toolbar_cursor_minus,'minus',false);
                                         this.setToolbarActive(e, Event.element(e));
                                    }.bindAsEventListener(this));
    this.observer.setObserver($('toolbar_rotate_left'),
                                    'click',
                                    function(e) {
                                         project.setLastActiveBox('');
                                         project.handleCursor(toolbar_cursor_left,'rotate_left',false);
                                         this.setToolbarActive(e, Event.element(e));
                                    }.bindAsEventListener(this));
    this.observer.setObserver($('toolbar_rotate_right'),
                                    'click',
                                    function(e) {
                                         project.setLastActiveBox('');
                                         project.handleCursor(toolbar_cursor_right,'rotate_right',false);
                                         this.setToolbarActive(e, Event.element(e));
                                    }.bindAsEventListener(this));
    this.observer.setObserver($('toolbar_position'),
                                  'click',
                                    function(e) {
                                         project.setLastActiveBox('');
                                         project.handleCursor(toolbar_cursor_position,'position',false);
                                         this.setToolbarActive(e, Event.element(e));
                                    }.bindAsEventListener(this));
    this.observer.setObserver($('toolbar_select'),
                                    'click',
                                    function(e) {
                                         project.setLastActiveBox('');
                                         project.handleCursor(toolbar_cursor_switch,'switch',false);
                                         this.setToolbarActive(e, Event.element(e));
                                    }.bindAsEventListener(this));

    // speichern
    this.observer.setObserver($('safeProjectLink'),
                                    'click',
                                    function(evt) {

                                        Event.stop(evt);

                                        var myBox = new BorderboxB();
                                        myBox.showAsPopup('warningMenu');
                                        var buttonPos = (Position.cumulativeOffset($('safeProjectLink')));

                                        getElementsByClass('Message', $('warningMenu'))[0].firstChild.data = getElementsByClass('messageSafe', $('warningMenu'))[0].firstChild.data;
                                        myBox.position(buttonPos[0], buttonPos[1]);

                                        project.saveProject('saveAll');
                                        setTimeout(function() {
                                          myBox.hide();
                                        },2000);
                                    }.bindAsEventListener(this));
    // Projektkopie speichern unter...
    var copyProjectLink = $('copyProjectLink');
    this.observer.setObserver(copyProjectLink,
                              'click',
                              function(evt) {

                                Event.stop(evt);

                                var buttonPos = (Position.cumulativeOffset(copyProjectLink));
                                var myBox     = new BorderboxB();
                                myBox.showAsPopup('copyProjectConfirm');
                                myBox.position(buttonPos[0], buttonPos[1]);

                                var confirmBox    = $("copyProjectConfirm");
                                var linkConfirm   = confirmBox.getElementsByTagName("a")[0];
                                var inputNameEl   = confirmBox.getElementsByTagName("input")[0];
                                inputNameEl.value = FOA.Project.formAttributes.name;

                                // Daten zum speichern des aktuellen ProjectParts mitgeben
                                this.unsetDesktopActiveBox();
                                var activePageData  = this.getDataFromActivePage();

                                linkConfirm.onclick = (function(evt) {
                                  Event.stop(evt);
                                  myBox.hide.call(myBox);
                                  var projectName = inputNameEl.value;
                                  ProjectTools.copyProject(this.projectID, projectName, activePageData.parts_number, activePageData.xml_data,
                                    function(transport) {
                                      XMLDoc = transport.responseXML;
                                      var result;
                                      if ((result = XMLDoc.getElementsByTagName('result')) && (result[0].firstChild.data == "success")) {
                                        location.href = "/myproducts/" + this.productType + "Editor/?project_id=" + XMLDoc.getElementsByTagName('project_id')[0].firstChild.data;
                                      }
                                   }.bind(this));
                                }).bindAsEventListener(this);
                              }.bindAsEventListener(this));
    // toolTips
    var toolTip         = new ClassToolTip($('toolTip'), 'toolTipsEditor', $('page'));
    var toolBarElements = $$('#PhotobookToolbar a');
    $A(toolBarElements).each(function(oneElement){
      this.observer.setObserver(oneElement,
                      'mouseover',
                      toolTip.showToolTip.bindAsEventListener(toolTip));
      this.observer.setObserver(oneElement,
                      'mouseout',
                      toolTip.hideToolTip.bindAsEventListener(toolTip));
    }.bind(this));

    // speichern und bestellen
    var orderButton = '';
    if (orderButton = $('orderButton')) {
      this.observer.setObserver(orderButton,
                        'mouseup',
                        function(evt){
                          Event.stop(evt);
                          //project.saveProject('saveAll');
                        }.bindAsEventListener(this));
    }

    if ($('toolbar_step_forward') && $('toolbar_step_backward')) {
      this.observer.setObserver($('toolbar_step_forward'),  'click', function() { project.setNextPage(-1); });
      this.observer.setObserver($('toolbar_step_backward'), 'click', function() { project.setNextPage(+1); });
    }
  }

  this.getAllProjectPages = function() {

    var onCompleteFunction = function(AjaxResponse) {
      var XMLDoc        = AjaxResponse.responseXML;
      var allParts     = XMLDoc.getElementsByTagName('part');
      for (i=0; i<allParts.length; i++) {
        this.projectXML[parseInt(allParts[i].getAttribute('number'))] = allParts[i];
      }
      this.init('BookPage_2', 0, 1);
      this.saveProject('saveProjectAttributes', this.getProjectParam());
    };

    var AjaxObject = new Ajax.Request(
                          _AjaxRequestFile, {
                            method: 'post',
                            parameters: 'action=getAllProjectPages'
                                      + '&windowToken=' + windowToken,
                            onComplete: onCompleteFunction.bind(this)
                          });
  }

  this.fitLayoutToProjectSize = function(contentBoxes) {

    $A(contentBoxes).each(function(cb){

      var CBHeight    = parseFloat(cb.getAttribute('height'));
      var CBWidth      = parseFloat(cb.getAttribute('width'));
      var CBX          = parseFloat(cb.getAttribute('x'));
      var CBY          = parseFloat(cb.getAttribute('y'));
      var bleedTop    = parseFloat(cb.getAttribute('bleedtop'));
      var bleedLeft   = parseFloat(cb.getAttribute('bleedleft'));
      var bleedWidth  = parseFloat(cb.getAttribute('bleedwidth'));
      var bleedHeight = parseFloat(cb.getAttribute('bleedheight'));

      var xBleed      = this.roundValue((this.bleedHorizontal * 2 * bleedWidth), 8);
      var yBleed      = this.roundValue((this.bleedVertical   * 2 * bleedHeight), 8);

      cb.setAttribute('width',      (CBWidth  - xBleed));
      cb.setAttribute('height',     (CBHeight - yBleed));
      cb.setAttribute('y', (CBY + (parseFloat(this.bleedVertical)   - (bleedTop  * yBleed))));
      cb.setAttribute('x', (CBX + (parseFloat(this.bleedHorizontal) - (bleedLeft * xBleed))));

    }.bind(this))

    return contentBoxes;
  }

  this.setProjectOptions = function(Options) {

    $A(Options).each(function(opt){
      if (opt.hasChildNodes()) {
        // resolution
        var resolutionOption = '';
        if ((resolutionOption = opt.getElementsByTagName('resolution')) && resolutionOption[0]) {
          project.bestQuality   = parseFloat(resolutionOption[0].getAttribute('best_quality'));
          project.mediumQuality = parseFloat(resolutionOption[0].getAttribute('medium_quality'));
        }
        // bleedoptionen
        var bleedOption = '';
        if ((bleedOption = opt.getElementsByTagName('bleed')) && bleedOption[0]) {

          project.Bleed = parseFloat(bleedOption[0].firstChild.data);
          // derzeit den Bleed für links, rechts, oben unten nehmen(gleichmäßig)
          project.CoverWidth  += (2 * project.Bleed);
          project.CoverHeight  += (2 * project.Bleed);
          project.PageWidth   += (2 * project.Bleed);
          project.PageHeight   += (2 * project.Bleed);
        }
        // changeLayoutRange --> wenn mehr als eine Seite beim layoutwechsel berücksichtigt werden sollen
        var changeLayoutRangeElement;
        if ((changeLayoutRangeElement = opt.getElementsByTagName('changeLayoutRange')) && changeLayoutRangeElement[0]) {
          project.changeLayoutRange.from = parseInt(changeLayoutRangeElement[0].getAttribute('from'));
          project.changeLayoutRange.to   = parseInt(changeLayoutRangeElement[0].getAttribute('to'));
        }
        // coveroptionen
        var coverOption = '';
        if (project.Cover && (coverOption = opt.getElementsByTagName(project.Cover)) && coverOption[0]) {

          var from     = parseInt(coverOption[0].getAttribute('part_number_from'));
          var to       = parseInt(coverOption[0].getAttribute('part_number_to'));
          var co       = new Object();
          co.bg_image  = parseInt(coverOption[0].getAttribute('bg_image'));
          co.bg_x      = parseInt(coverOption[0].getAttribute('bg_position_x'));
          co.bg_y      = parseInt(coverOption[0].getAttribute('bg_position_y'));
          co.bg_h      = parseInt(coverOption[0].getAttribute('bg_addheight'));
          co.color     = project.CoverColor;
          co.type      = 'cover';

          project.page_cover_last = to;

          // setzte alle CoverPages
          if (from == to) {
            project.Page[from] = Object.clone(co);
          }
          else {
            for (var i=from; i<=to; i++) {
              project.Page[i] = Object.clone(co);
            }
          }
          // gibt es spezielle materialien (darf editiert werden?)
          var surface = '';
          if (surface = coverOption[0].getElementsByTagName(project.Surface)) {
            var surfaceParams = '';
            if (surface[0] && (surfaceParams = surface[0].getElementsByTagName('surface'))) {
              $A(surfaceParams).each(function(aSurface) {
                // seitennummer
                var nr = parseInt(aSurface.getAttribute('number'));
                // gibte es spezielle Farben (leinen)
                var colorType;
                if (colorType = aSurface.getAttribute('color_type')) {
                  project.Page[nr].color_type = colorType;
                  // wenn ja wie sollen sie angezeigt werden
                  var colorMode;
                  if (colorMode = aSurface.getAttribute('color_mode')) {
                    project.Page[nr].color_mode = colorMode;
                  }
                }
                // darf sich darauf ein image befinden
                var displayImage;
                if (displayImage = aSurface.getAttribute('no_image')) {
                  project.Page[nr].no_image = true;
                }
              });
            }
            var emptySurface = '';
            if (surface[0] && (emptySurface = surface[0].getElementsByTagName('empty'))) {
              $A(emptySurface).each(function(aEmptySurface) {
                var nr = parseInt(aEmptySurface.getAttribute('number'));
                project.Page[nr].empty = true;
              });
            }
          }
          // darf das cover editiert werden?
          else {
            var emptyCover = '';
            if (emptyCover = coverOption[0].getElementsByTagName('empty')) {
              $A(emptyCover).each(function(aCover) {
                var nr = parseInt(aCover.getAttribute('number'));
                project.Page[nr].empty = true;
              });
            }
          }
        }
        // schriftarten von kalendarien
        var calendarStyleList = '';
        if ((calendarStyleList = opt.getElementsByTagName('calendarstyles')) && calendarStyleList[0]) {
          if ((calendarStyles = calendarStyleList[0].getElementsByTagName('style'))) {

            var calendarStyleSelection = $$('#CalendarStyleMenu .stylelist')[0];
            // clear Stylelist
            while (calendarStyleSelection.hasChildNodes()) {
              calendarStyleSelection.removeChild(calendarStyleSelection.firstChild);
            }

            var o = 0;
            $A(calendarStyles).each(function(aStyle) {
              var styleName = aStyle.getAttribute('name');
              // der Name ergibt sich aus der Sprache
              $A(aStyle.getElementsByTagName('lang')).each(function(oneLangItem) {
                if (oneLangItem.getAttribute('name') == project.projectOptions.calendar_lang) {
                  calendarStyleSelection.options[o] = new Option(oneLangItem.firstChild.data, aStyle.getAttribute('name'));
                  if (project.projectOptions.calendar_style == oneLangItem.firstChild.data) {
                    calendarStyleSelection.options[o].selected = true;
                  }
                  o++;
                }
              });
            });
          }
        }
        // pageoptionen
        var pageOption = '';
        if ((pageOption = opt.getElementsByTagName('page')) && pageOption[0]) {
          // leere seiten(umschlag) einrechnen
          var countEmptyPages = 0;
          var emptyPages = '';
          if (emptyPages = pageOption[0].getElementsByTagName('empty')) {
            countEmptyPages = emptyPages.length;
          }
          // seitenspanne
          var pageStart = parseInt(pageOption[0].getAttribute('start_nr'));
          var pageEnd   = project.PageCount + pageStart + countEmptyPages ;
          // für fotobücher in der init überschreiben
          project.maxPages = pageEnd;

          var bg_image = parseInt(pageOption[0].getAttribute('bg_image'));
          var bg_x = pageOption[0].getAttribute('bg_position_x') ? parseInt(pageOption[0].getAttribute('bg_position_x')) : 0;
          var bg_y = pageOption[0].getAttribute('bg_position_y') ? parseInt(pageOption[0].getAttribute('bg_position_y')) : 0;
          var bg_h = pageOption[0].getAttribute('bg_addheight')  ? parseInt(pageOption[0].getAttribute('bg_addheight'))  : 0;

          // setzte alle Pages
          for (var p=pageStart; p < pageEnd; p++) {
            if (!project.Page[p]) {
              project.Page[p] = { bg_image : bg_image,
                                  bg_x     : bg_x,
                                  bg_y     : bg_y,
                                  bg_h     : bg_h,
                                  color    : project.defaultPageColor,
                                  type     : 'page' };
            }
          }
          // seiten mit einem default Layout
          var layoutPages = '';
          if (layoutPages = pageOption[0].getElementsByTagName('layoutpage')) {
            $A(layoutPages).each(function(aLayoutPage) {
              var nr = parseInt(aLayoutPage.getAttribute('number'));
              project.Page[nr].layout = aLayoutPage.getAttribute('layout');
              var fixLayout;
              if (fixLayout = aLayoutPage.getAttribute('fix')) {
                project.Page[nr].fixLayout = parseInt(fixLayout);
              }
            });
          }
          // seitennamen (calendar)
          var pagesNames = '';
          if ((pageNames = pageOption[0].getElementsByTagName('names'))) {
            if (pageNames[0]) {
              var names = '';
              if ((names = pageNames[0].getElementsByTagName('name'))) {

                var add_month = 0;
                var start_month;

                if ((start_month = parseInt(project.projectOptions.start_month)) && (start_month > 1)) {
                  add_month = start_month;
                }

                var start_nr    = parseInt(start_month);
                var add_month   = 0;
                var objectPage  = new Object();

                $A(names).each(function(aName) {
                  var nr = parseInt(aName.getAttribute('number'));

                  objectPage[nr] = { name   : aName.firstChild.data,
                                     type   : aName.getAttribute('type'),
                                     id     : aName.getAttribute('id'),
                                     month  : aName.getAttribute('month'),
                                     year   : parseInt(project.projectOptions.year)
                                   }
                });

                project.Numbers = Object.clone(objectPage);

                // falls Monat 1 nicht Januar ist: neu sortieren
                if (start_nr > 1) {
                  $H(objectPage).each(function(aPage) {
                    var nr = parseInt(aPage.key);
                    // erste seite(cover)
                    if (nr == 1) {
                      // verweise auf das Bild für zwei darauffolgende Jahre
                      objectPage[1].month = 13;
                    }
                    // seiten monate
                    if (nr > 1) {
                      var temp_month = (nr + start_nr - 1) % 14;

                      if (temp_month > start_nr) {
                        temp_month--;
                      }
                      else {
                        temp_month++;
                        objectPage[temp_month + 1].year++;
                      }
                      project.Numbers[nr] = objectPage[temp_month + 1];
                    }
                  });
                }

                // den defaultwert für die Jahreszahl des Kalendar aus den ProjectOptions nachtragen
                if (typeof project.projectOptions.year != 'undefined') {
                  project.Numbers[1].name = project.projectOptions.year;
                  // mit darauffolgendem Jahr
                  if (start_nr > 1) {
                    project.Numbers[1].name = project.Numbers[1].year + '/' + sprintf('%02d', (parseInt(project.Numbers[1].year) - 1999));
                  }
                }
              }
            }
          }
        }
      }
    });
  }

  this.showHideLayoutList = function(id, LayoutType) {
    var layouts = $$('#LayoutTemplates' + LayoutType + ' .projectLayoutList');
    $A(layouts).each(function(oneLayout) {
      oneLayout.hide();
    });
    $('LayoutListeTemplate' + LayoutType + id).show();
  }

  this.newLayoutList = function (LayoutType, nr, listName, LayoutListeTemplate, LayoutButtonList, showInList) {

    // gibt es die Liste(Kategorie) schon
    if ($(listName + nr))
     return $(listName + nr);

    nr                         = parseInt(nr);
    var LayListeTemp           = document.createElement('div');
    LayListeTemp.className     = 'projectLayoutList';
    LayListeTemp.id            = listName + nr;
    LayListeTemp.style.display = 'none';

    if (showInList && nr > 0) {

      var layButton = document.createElement('a');
      layButton.appendChild(document.createTextNode(nr));

      this.observer.setObserver(layButton,
                                'click',
                                function(evt) {
                                  Event.stop(evt);
                                  project.showHideLayoutList(nr, LayoutType);
                                  var layoutButtons = LayoutButtonList.getElementsByTagName('a');
                                  $A(layoutButtons).each(function(oneButton) {
                                    Element.removeClassName(oneButton, 'active');
                                  });
                                  Element.addClassName(this, 'active');

                                }.bindAsEventListener(layButton));

      LayoutButtonList.appendChild(layButton);

    }

    LayoutListeTemplate.appendChild(LayListeTemp);

    return $(listName + nr);
  }

  this.newLayoutCategorie = function (LayoutsList, LayoutPageSize, Unit) {

    var LayoutListeTemplate;
    var LayoutButtonList;
    var LayoutListeID;

    var LayoutListeTemplateImage   = $('LayoutTemplates');
    var LayoutButtonListImage      = $$('#LayoutTemplates .layoutButton')[0];
    var LayoutListeIDImage         = 'LayoutListeTemplate';
    var LayoutListeTemplateText    = $('LayoutTemplatesText');
    var LayoutButtonListText       = $$('#LayoutTemplatesText .layoutButton')[0];
    var LayoutListeIDText          = 'LayoutListeTemplateText';

    var LayoutType            = '';
    var LayoutTemplate         = $('LayoutTemplate');
    var ContentBox            =  $('ContentBox');

    var layIndex = 1;

    // neues Layout anlegen
    $A(LayoutsList).each(function(oneLayout) {

      LayoutType      = '';
      var layout_id   = layIndex;
      var layoutBoxes = oneLayout.getElementsByTagName('item');

      // es wird nach item.type und item.length kategorisiert
      var lt;
      var layoutItemsCount = 0;
      $A(layoutBoxes).each(function(oneLayoutItem) {
        if ((lt = oneLayoutItem.getAttribute('type')) && (lt == 'text')) {
          LayoutType = 'Text';
        }
        if (oneLayoutItem.getAttribute('type') == 'image' || oneLayoutItem.getAttribute('type') == 'all')
          layoutItemsCount++;
      }.bind(this));

      if (LayoutType == 'Text') {
        LayoutListeTemplate  = LayoutListeTemplateText;
        LayoutButtonList     = LayoutButtonListText;
        LayoutListeID        = LayoutListeIDText;
      }
      else {
        LayoutListeTemplate  = LayoutListeTemplateImage;
        LayoutButtonList     = LayoutButtonListImage;
        LayoutListeID        = LayoutListeIDImage;
      }

      // neue LayoutCategorie anlegen
      lay = this.newLayoutList(LayoutType, layoutItemsCount, LayoutListeID, LayoutListeTemplate, LayoutButtonList, true);

      // auf LayoutAttribute eingehen
      var layoutBleed;
      if ((layoutBleed = oneLayout.getAttribute('bleed')) && (layoutBleed == 1)) {
         this.borderLayouts[('LayoutTemplate_' + layout_id)] = 'LayoutTemplate_' + layout_id;
        layoutBoxes = this.fitLayoutToProjectSize(layoutBoxes);
      }

      // setze die LayoutSeite
      this.setLayoutPage(LayoutTemplate.cloneNode(true), layout_id, LayoutPageSize[0], lay, layIndex, 'block');
      var SubBookPage = $('BookPage_' + layout_id);
      layIndex++;

      // layoutBoxen auf Layoutseite anlegen
      var boxIndex = 1;
      $A(layoutBoxes).each(function(oneLayoutBox) {
        // setze die LayoutBox
        var newLayoutBox = this.setLayoutBox(oneLayoutBox, ContentBox, SubBookPage, layout_id, boxIndex, Unit);
        // gibts default Inhalte
        var layoutContent;
        if ((layoutContent = oneLayoutBox.getElementsByTagName('content')) && layoutContent[0]) {
          this.setLayoutBoxContent(newLayoutBox, layoutContent[0], layout_id, LayoutPageSize);
        }
        boxIndex++;
      }.bind(this));
    }.bind(this));
  }

  this.getProjectXML = function (initProject, pages) {

    this.Pages                = pages;
    this.maxPages             = this.PageCount;

    var onCompleteFunction =  function(AjaxResponse) {

      var XMLDoc            = AjaxResponse.responseXML;
      var Layout            = XMLDoc.getElementsByTagName('layoutlist')[0];
      var Options          = Layout.getElementsByTagName('option');
      var LayoutsList       = Layout.getElementsByTagName('layouts');
      var Spine             = Layout.getElementsByTagName('spine');
      var Unit             = Layout.getAttribute('scaleunit') ? Layout.getAttribute('scaleunit') : 'percent';

      if (Options) {
        // die einstellungen sind im XML zu machen(farbe, hintergrundbild... für cover und page)
        project.setProjectOptions(Options);
      }

      if (Spine[0]) {
        this.SpineWidth = parseFloat(Spine[0].getAttribute('width'));
      }

      this.setProjectSizeFactor();

      // set the Pagesize
      LayoutPageSize = this.setPageSize(this.PageWidth, this.PageHeight, this.PageWidth, this.PageHeight);

      // clear LayoutLists
      var oldLayoutList = getElementsByClass('projectLayoutList');
      $A(oldLayoutList).each(function(ol) {
        if (ol.parentNode.hasChildNodes()){
          ol.parentNode.removeChild(ol);
        }
      });

      // clear LayoutButtonLists
      var LayoutButtonLists = getElementsByClass('layoutButton');
      $A(LayoutButtonLists).each(function(LayoutButtonList) {
        if (LayoutButtonList.hasChildNodes()){
          while(LayoutButtonList.hasChildNodes()) {
            LayoutButtonList.removeChild(LayoutButtonList.firstChild);
          }
        }
      });

      this.newLayoutCategorie(LayoutsList[0].getElementsByTagName('layout'), LayoutPageSize, Unit);

      $$('#LayoutTemplates .projectLayoutList')[0].show();

      // wenn Textlayouts vorhanden sind, anzeigen.
      var LayoutListeTemplateText;
      if ((LayoutListeTemplateText = $$('#LayoutTemplatesText .projectLayoutList')) && LayoutListeTemplateText.length > 0) {
        LayoutListeTemplateText[0].show();
        $('show_LayoutTemplatesText').show();
      }

      if (initProject) {
        this.setProjectView();
        this.getAllProjectPages();
        this.setObserver();
      }
    };

    var AjaxObject = new Ajax.Request(
                          _AjaxRequestFile, {
                            method: 'post',
                            parameters: 'action=layout'
                                      + '&layout='      + _xmlLayout
                                      + '&project_id='  + project_id,
                            onComplete: onCompleteFunction.bind(this)
                          });
  }

  this.setProjectView = function () {
    if (this.projectOptions.view == 'public') {
      // die view auf public-modus beschränken
      $A($$('.private')).each(function(oneItem) {
        oneItem.hide();
      });
      // gibt es Buttons einen Projecttransfer
      $A($$('#projectEditorContent .projectTransfer')).each(function(oneItem) {
        oneItem.show();
        oneItem.onclick = function(evt) {
          Event.stop(evt);
          ProjectTools.transferPublicProjectToUser(this.projectID);
        }.bindAsEventListener(this);
      }.bind(this));
    }
  }

  this.destruct = function () {
    // unset all observer
    this.observer.unsetAll();
  }
}
