/* =============================================================================
 * GRID CMS
 * =============================================================================
 * version: 0.1
 * author: Hannes Kleindienst
 * requires: prototype, scriptaculous
 * =============================================================================
 */

/**
 * ############################################################################
 * ############################################################################
 * CMS
 * ############################################################################
 * ############################################################################
 */
var GridCms = Class.create();
GridCms.prototype = {

  /**
   * Constructor
   * 
   */
  initialize: function() {

    // create a loger object
    this.logger = new YAHOO.widget.LogReader(null, { 
      width: "400px", 
      height: "30em", 
      newestOnTop: true, 
      footerEnabled: false,
      draggable: true
    });
    this.logger.hide();
    
    // define version
    this.version = 'GRIDcms Javascript 0.5';
    
    // setup other class members
    this.prefix = "";
    this.element = null;
    this.user = null;
    this.contentTag = 'grid_content';
    
  },

  setup : function (prefix, oProp) {

    // first LOG output
    YAHOO.log('setting up CMS object with ' + prefix + ' prefix','grid','gridcms.js');

    // define prfix
    this.prefix = prefix;

    // create user
    this.user = new GridUser (this, oProp);

  // prepare class members
  //    this.contentTag = oProp.contentTag;
  //    this.contentTag = 'grid_content';

  },


  // =========================================================================
  // Initialise DOM elements
  // =========================================================================
  

  // =========================================================================
  // Getters and Setters
  // =========================================================================

  getUser: function() {
    return this.user;
  },
  

  // =========================================================================
  // ELEMENT MANAGEMENT
  // =========================================================================
  
  getElement : function () {
    if (this.element==null) {
      this.element = new GridElement(this)
    }
    return this.element;
  },
  
  createElement : function (elementtype, attributes) {
    var e = this.getElement();
    e.create(elementtype, attributes);
  },
  
  addUpload : function (id) {
    // get element reference
    var e = this.getElement();
    // submit dialog
    var dlg = e.getDialog();
    // set callback
    dlg.callback = { 
      success: function(o) {
        e.show(id,'edit',false);
      },
      failure: function(o) {
        alert("Submission failed: " + o.status);
      } 
    };
    // set action to "update"
    $('gridcms_dlg_element_form_action').value='update';
    // submit the dialog in order to have the modifications stored
    // (... but not saved)
    dlg.submit();
  },

  addUpload2 : function(idelement,attcode,counter,url) {
    var p = $("gridcms_dlg_element_"+idelement+"_"+attcode);
    var d = document.createElement("div");
    d.innerHTML = "<input type=\"file\" meta_id=\"cms_" + attcode + "\" name=\"" + attcode + "."+counter+"\" />" +
    "&nbsp;&nbsp;<img onclick=\"this.hide(); gridcms.addUpload2(" + idelement + ",'" + attcode + "'," + (counter+1) + ",'"+url+"')\" src=\""+url+"media/buttons/ele_add.gif\"><br/>";
    p.appendChild(d);
  },

  deleteUpload : function (id, attribute, fileid) {
    // get element reference
    var e = this.getElement();
    // submit dialog
    var dlg = e.getDialog();
    // set callback
    dlg.callback = { 
      success: function(o) {
        e.deleteUpload(id,attribute,fileid);
      },
      failure: function(o) {
        alert("Submission failed: " + o.status);
      } 
    };
    // set action to "update"
    $('gridcms_dlg_element_form_action').value='update';
    // submit the dialog in order to have the modifications stored
    // (... but not saved)
    dlg.submit();    
  },

  addRelation : function (id, attribute, elementtype, attgroup) {
    // get element reference
    var e = this.getElement();
    // submit dialog
    var dlg = e.getDialog();
    // set callback
    dlg.callback = { 
      success: function(o) {
        e.addRelation(id,attribute,elementtype, attgroup);
      },
      failure: function(o) {
        alert("Submission failed: " + o.status);
      } 
    };
    // set action to "update"
    $('gridcms_dlg_element_form_action').value='update';
    // submit the dialog in order to have the modifications stored
    // (... but not saved)
    dlg.submit();    
  },

  deleteRelation : function (id, attribute, relid) {
    // get element reference
    var e = this.getElement();
    // submit dialog
    var dlg = e.getDialog();
    // set callback
    dlg.callback = { 
      success: function(o) {
        e.deleteRelation(id,attribute,relid);
      },
      failure: function(o) {
        alert("Submission failed: " + o.status);
      } 
    };
    // set action to "update"
    $('gridcms_dlg_element_form_action').value='update';
    // submit the dialog in order to have the modifications stored
    // (... but not saved)
    dlg.submit();    
  },

  moveRelation : function (id, attribute, relid, dir) {
    var e = this.getElement();
    e.moveRelation(id,attribute,relid,dir);
  },

  searchRelation : function (inputid) {
    var searchtext = $(inputid).value;
    $(inputid+"_result").innerHtml = "Search for '" + searchtext + "'";
  },

  showElement : function (id, mode, attgroup) {
    if (!attgroup) {
      attgroup = "_first";
    }
    var e = this.getElement();
    e.show(id, mode, false, attgroup);
  },

  showElementAttributes : function (allgroups, group) {
    var groups = allgroups.split(',');
    for (var ii = 0, len = groups.length; ii < len; ++ii) {
      var item = groups[ii];
      if ($('gridcms_element_attgroup_'+item)) {
        $('gridcms_element_attgroup_'+item).hide()
      }
    }
    if ($('gridcms_element_attgroup_'+group)) {
      $('gridcms_element_attgroup_'+group).show()
    }

  },
    
  loadElement : function (id, mode) {
    var e = this.getElement();
    e.show(id, mode, true);
  },
    
  deleteElement : function (id) {
    var e = this.getElement();
    var success = e.trash(id);
  },

  setWorkflowStatus : function (id, status) {
    var e = this.getElement();
    e.setWorkflowStatus(id,status);
  },

  updateElement : function () {
    var e = this.getElement();
    var d = e.getDialog();
    if (d) {
      if ($("gridcms_dlg_element_form_action")) {
        $("gridcms_dlg_element_form_action").value = "update";
        d.submit();
      }
    }
  },

  // =========================================================================
  // SEARCH
  // =========================================================================

  search : function (tag, sort) {
    
    // base definition
    var cgi = this.prefix + "/cms/search?";
    // element ... if not set, all elementtypes will be searched
    if ($(tag+'_elementtype')) {
      cgi += "&elementtype="+$(tag+'_elementtype').value;
    }
    // element types ... search several element types
    if ($(tag+'_elementtypes')) {
      cgi += "&elementtypes="+$(tag+'_elementtypes').value;
    }
    // sort field either as argument or defined in HTML
    if (sort) {
      cgi += "&sort=";      
    } else if ($(tag+'_sort')) {
      cgi += "&sort="+$(tag+'_sort').value;
    }
    // table columns ... if not defined, used based on element type
    if ($(tag+'_tablecols')) {
      cgi += "&tablecols="+$(tag+'_tablecols').value;
    }
    // output format
    if ($(tag+'_format')) {
      cgi += "&format="+$(tag+'_format').value;
    }
    // where clause
    if ($(tag+'_sql')) {
      cgi += "&sql="+$(tag+'_sql').value;
    }
    
    var ids = $(tag).value.split(',');
    for (var ii = 0, len = ids.length; ii < len; ++ii) {
      var item = ids[ii];
      if ($(tag+'_'+item)) {
        cgi += "&"+item+"="+$(tag+'_'+item).value;        
      }
    }
    
    // create AJAX request
    new Ajax.Request( cgi, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        $(tag+"_results").innerHTML = transport.responseText;
      }
    });    
  },
  
  // =========================================================================
  // Log access
  // =========================================================================

  showLog: function () {
    this.logger.show();
  },
  
  hideLog: function () {
    this.logger.hide();
  },
  
  // =========================================================================
  // Views
  // =========================================================================
  
  viewManage: function (container, cms, type) {

    // check if container exists
    var containerTag = $(container);
    if ( ! containerTag ) {
      alert ("HTML Tag '" + container + "' does not exist!");
    }    
    containerTag.innerHTML = "";

    // check cms reference
    if (!cms) {
      cms = this;
    }

    var tabs = new YAHOO.widget.TabView();
    
    var hClickGroup = function (e) {
      cms._viewManageGroup();
    };
    var hClickUser = function (e) {
      cms._viewManageUser();
    };
    var hClickTrash = function (e) {
      cms._viewManageTrash();
    };
	
    tabs.addTab( new YAHOO.widget.Tab({
      label: 'Benutzer',
      content: '<div id="cms_manage_user"></div>'
    }));
    
    tabs.addTab( new YAHOO.widget.Tab({
      label: 'Gruppen',
      content: '<div id="cms_manage_group"></div>',
      active: true
    }));

    tabs.addTab( new YAHOO.widget.Tab({
      label: 'Papierkorb',
      content: '<div id="cms_manage_trash"></div>',
      active: true
    }));

    // weitere Tabs:
    // - Zugriffslog
    // - Datenbankoperationen
    
    tabs.getTab(0).addListener('click',hClickUser.bind(this));
    tabs.getTab(1).addListener('click',hClickGroup.bind(this));
    tabs.getTab(2).addListener('click',hClickTrash.bind(this));
    
    tabs.appendTo(container);

    if (type=='user') {
      cms._viewManageUser();
    } else if (type=='group') {
      cms._viewManageGroup();
    } else if (type=='trash') {
      cms._viewManageTrash();
    } else {
      YAHOO.log('Unknown management type ' + type ,'grid','gridcms.js');
    }
    
    YAHOO.log('application tabs created','grid','egar.js');

  },
  
  _viewManageGroup : function () {
    // create AJAX request
    new Ajax.Request( this.prefix + "/cms/user?action=listeditgroups", {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        $('cms_manage_group').innerHTML = "<p>Gruppenverwaltung</p>" +
        "<button onclick=\"gridcms.user.createGroup(0)\">neu</button>";
        $('cms_manage_group').innerHTML += transport.responseText;
      }
    });
  },
  
  _viewManageUser : function () {
    // create AJAX request
    new Ajax.Request( this.prefix + "/cms/user?action=listeditusers", {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        $('cms_manage_user').innerHTML = "<p>Benutzerverwaltung</p>" +
        transport.responseText;
      }
    });
  },

  _viewManageTrash : function () {
    // base definition
    var cgi = this.prefix + "/cms/search?trash=true";
    // create AJAX request
    new Ajax.Request( cgi, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        $('cms_manage_trash').innerHTML = "<p>Papierkorb</p>" +
        transport.responseText;
      }
    });
  },


  // =========================================================================
  // Utility methods
  // =========================================================================

  reload: function () {
    
    document.location.reload();

  /*/
    // get current URL
    var url0  = document.URL;
    // check if the reload parameter is already contained and remove if required
    var i0 = url0.indexOf("reload=");
    var i1 = url0.indexOf("&",i0);
    // create url
    var url = url0.substring(0,i0);
    if (i1>=0) {
      url += url0.substring(i1+1,url0.length-1);
    }
    // check if last character is ?
    var concat = "?";
    if (url.indexOf('?')>=0) {
      concat = "&";
    }
    if (url.substring(url.length-1,url.length)=='?') {
      concat = "";
    } else if (url.substring(url.length-1,url.length)=='&') {
      concat = "";
    }
    location.href = url + concat + "reload="+Math.round(Math.random()*1000000000);
     */
  },
  
  onButtonClick : function (action, value) {
    if (action=="editgroup") {
      this.user.editGroup(value);
    } else if (action=="creategroup") {
      this.user.createGroup();
    } else if (action=="deletegroup") {
      this.user.deleteGroup(value);
    } else if (action=="createuser") {
      this.user.createUser();
    } else if (action=="edituser") {
      this.user.editUser(value);
    } else if (action=="showElementEdit") {
      this.showElement(value,'edit');
    } else if (action=="showElementView") {
      this.showElement(value,'view');
    } else if (action=="showElementMeta") {
      this.showElement(value,'meta');
    } else if (action=="showElementTrash") {
      this.showElement(value,'trash');
    } else if (action=="deleteElement") {
      this.deleteElement(value);
    } else {
      alert(action + " -> ID = " + value);
    }
  },

  createDialog : function () {
    var tDlg = $('gridcms_dlg');
    if (!tDlg) {
      // create dialog
      tDlg = $(document.createElement('div'));
      tDlg.id = "gridcms_dlg";
      tDlg.setStyle({
        zIndex: "300"
      });
      tDlg.hide();
      document.body.appendChild(tDlg);
    } else {
      tDlg.hide();
    }    
    return tDlg;
  },
  
  // =========================================================================
  // ABOUT METHODS
  // =========================================================================

  getVersion: function () {
    return this.version;
  }
  
};



/**
 * ############################################################################
 * ############################################################################
 * GRID USER
 * ############################################################################
 * ############################################################################
 */
var GridUser = Class.create();
GridUser.prototype = {

  /**
   * Constructor
   * 
   */
  initialize: function(cms, oProp) {

    // reference to cms
    this.cms = cms;
    
    // username
    this.username = ''
    
    // group membership
    this.groups = new Hash();
    
    YAHOO.log('initialisation of USER object done','grid','gridcms.js');
      
  },
  
  // =========================================================================
  // Authentication
  // =========================================================================
  
  addLogin: function(fLoginSuccess, fLoginFailure, tagid) {
    $(tagid).innerHTML = '<label for="username">Benutzerkennung:</label><input id="cms_login_username" type="textbox" name="username" />' +
  '<label for="password">Passwort:</label><input id="cms_login_password_clear" type="password" name="password0" />' +
  '<input type="hidden" id="cms_login_password" name="password" value="" />' +
  '<input type="hidden" name="action" value="login" />' +
  '<button>login</button>';
  },
  
  showLogin: function(fLoginSuccess, fLoginFailure) {
    var tLogin = this.cms.createDialog();
    tLogin.innerHTML = '<div class="hd">Anmelden</div>' +
    '<div class="bd">' +
    '<form method="POST" action="' + this.cms.prefix + '/cms/user">' +
    '<label for="username">Benutzerkennung:</label><input id="cms_login_username" type="textbox" name="username" />' +
    '<label for="password">Passwort:</label><input id="cms_login_password_clear" type="password" name="password0" />' +
    '<input type="hidden" id="cms_login_password" name="password" value="" />' +
    '<input type="hidden" name="gridaction" value="login" />' +
    '</form>' +
    '</div>';
    tLogin.show();
    // Instantiate the Dialog
    this.dlgLogin = new YAHOO.widget.Dialog(tLogin, 
    {
      width : "30em",
      zIndex: 300,
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      buttons: [ 
      {
        text:"Anmelden",
        handler: function() {
          $('cms_login_password').value = MD5($('cms_login_password_clear').value);
          $('cms_login_password_clear').value = '';
          // this refers to the dialog object
          YAHOO.log('Sending login','grid','gridcms.js');
          this.submit();
        },
        isDefault: true
      },

      {
        text:"Abbrechen",
        handler: function() {
          $('cms_login_password_clear').value = '';
          $('cms_login_password').value = '';
          $('cms_login_username').value = '';
          // this refers to the dialog object
          YAHOO.log('Login cancelled','grid','gridcms.js');
          this.cancel();
        }
      }
      ]  
    });

    // Validate the entries in the form to require that both first and last name are entered
    this.dlgLogin.validate = function() {
      var data = this.getData();
      if (data.username == "" || data.password == "") {
        alert("Please enter username and password");
        return false;
      } else {
        return true;
      }
    };

    // Wire up the success and failure handlers
    this.dlgLogin.callback = {
      success: function(o) {
        YAHOO.log(o.responseText,'grid','gridcms.js');
        if (fLoginSuccess) {
          if (o.responseText!='login successful') {
            alert(o.responseText);
          }
          fLoginSuccess();
        }
      },
      failure: function(o) {
        alert("Submission failed: " + o.status);
        if (fLoginFailure) {
          fLoginFailure();
        }
      }
    };
        
    // Render the Dialog
    this.dlgLogin.render();
    this.dlgLogin.show();

  },


  logout: function(fAfterLogout) {
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/user?action=logout", {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        YAHOO.log(transport.responseText,'grid','gridcms.js');
        if (fAfterLogout) {
          fAfterLogout();
        }
      }
    });
  },
  

  // =========================================================================
  // EDIT User
  // =========================================================================
  
  editUser: function(iduser) {
    // check iduser
    if (!iduser) {
      iduser = "";
    }
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/user?action=edituser&iduser="+iduser, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._editUserDialog(transport.responseText);
      }.bind(this)
    });
  },
  
  createUser: function() {
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/user?action=createuser", {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._editUserDialog(transport.responseText);
      }.bind(this)
    });
  },

  _editUserDialog : function (frm) {

    // save reference to viewManage function
    var f_viewManage = this.cms.viewManage;
    var contentTag = this.cms.contentTag;
    var l_cms = this.cms;

    var tDlg = this.cms.createDialog();
    tDlg.innerHTML = '<div class="hd">Benutzer bearbeiten</div>' +
    '<div class="bd">' +
    '<form method="POST" action="'+this.cms.prefix+'/cms/user">' +
    frm +
    '<input type="hidden" name="action" value="saveuser" />' +
    '</form>' +
    '</div>';
    tDlg.show();
    
    // Instantiate the Dialog
    var dlg = new YAHOO.widget.Dialog(tDlg, 
    {
      width : "30em",
      zIndex: 300,
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      buttons: [ 
      {
        text:"Speichern",
        handler: function() {
          // this refers to the dialog object
          if ($('cms_user_pwd1').value != '') {
            $('cms_user_pwd').value = MD5($('cms_user_pwd1').value);
            $('cms_user_pwd1').value = '';
            $('cms_user_pwd2').value = '';
          }
          YAHOO.log('Saving user data','grid','gridcms.js');
          this.submit();
        },
        isDefault: true
      },

      {
        text:"Abbrechen",
        handler: function() {
          // this refers to the dialog object
          $('cms_user_pwd').value = '';
          $('cms_user_pwd1').value = '';
          $('cms_user_pwd2').value = '';
          YAHOO.log('Editing user cancelled','grid','gridcms.js');
          this.cancel();
        }
      }
      ],
      validate : function() {
        var data = this.getData();
        if (data.pwd1 != data.pwd2) {
          alert("Passwords do not match!");
          return false;
        } else {
          return true;
        }
      },
      callback : {
        success: function(o) {
          YAHOO.log(o.responseText,'grid','gridcms.js');
          f_viewManage(contentTag, l_cms, 'user');
        //        if (fLoginSuccess) {
        //          fLoginSuccess();
        //        }
        },
        failure: function(o) {
          alert("Submission failed: " + o.status);
        //        if (fLoginFailure) {
        //          fLoginFailure();
        //        }
        } 
      }      
    });

    // Validate the entries in the form to require that both first and last name are entered
    //    dlg.validate = function() {
    //      var data = this.getData();
    //      if (data.pwd1 != data.pwd2) {
    //        alert("Passwords do not match!");
    //        return false;
    //      } else {
    //        return true;
    //      }
    //    };

    // Wire up the success and failure handlers
    //    dlg.callback = { success: function(o) {
    //        YAHOO.log(o.responseText,'grid','gridcms.js');
    //        //        if (fLoginSuccess) {
    //        //          fLoginSuccess();
    //        //        }
    //      },
    //      failure: function(o) {
    //        alert("Submission failed: " + o.status);
    //        //        if (fLoginFailure) {
    //        //          fLoginFailure();
    //        //        }
    //      } };
        
    // Render the Dialog
    dlg.render();
    dlg.show();

  },

  // =========================================================================
  // EDIT Group
  // =========================================================================

  editGroup: function(idgroup) {
    // check iduser
    if (!idgroup) {
      idgroup = "";
    }
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/user?action=editgroup&idgroup="+idgroup, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._editGroupDialog(transport.responseText);
      }.bind(this)
    });
  },
  
  createGroup: function() {
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/user?action=creategroup", {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._editGroupDialog(transport.responseText);
      }.bind(this)
    });
  },

  deleteGroup: function(id) {
    var tDlg = this.cms.createDialog();
    tDlg.innerHTML = '<div class="hd">Gruppe löschen</div>' +
    '<div class="bd">' +
    '<form method="POST" action="'+this.cms.prefix+'/cms/user">' +
    'Gruppe wirklich löschen?' +
    '<input type="hidden" name="action" value="deletegroup" />' +
    '<input type="hidden" name="idgroup" value="' + id + '" />' +
    '</form>' +
    '</div>';
    tDlg.show();
    
    // Instantiate the Dialog
    var dlg = new YAHOO.widget.Dialog(tDlg, 
    {
      width : "30em",
      zIndex: 300,
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      buttons: [ 
      {
        text:"Löschen",
        handler: function() {
          // this refers to the dialog object
          YAHOO.log('Deleting group with ID = ' + id,'grid','gridcms.js');
          this.submit();
        },
        isDefault: true
      },

      {
        text:"Abbrechen",
        handler: function() {
          // this refers to the dialog object
          YAHOO.log('Deleting group cancelled','grid','gridcms.js');
          this.cancel();
        }
      }
      ]  
    });

    // Wire up the success and failure handlers
    dlg.callback = {
      success: function(o) {
        YAHOO.log(o.responseText,'grid','gridcms.js');
      },
      failure: function(o) {
        alert("Submission failed: " + o.status);
      }
    };
        
    // Render the Dialog
    dlg.render();
    dlg.show();
  },
  

  _editGroupDialog : function (frm) {

    // save reference to viewManage function
    var f_viewManage = this.cms.viewManage;
    var contentTag = this.cms.contentTag;
    var l_cms = this.cms;

    var tDlg = this.cms.createDialog();
    tDlg.innerHTML = '<div class="hd">Gruppe bearbeiten</div>' +
    '<div class="bd">' +
    '<form method="POST" action="'+this.cms.prefix+'/cms/user">' +
    frm +
    '<input type="hidden" name="action" value="savegroup" />' +
    '</form>' +
    '</div>';
    tDlg.show();
    
    // Instantiate the Dialog
    var dlg = new YAHOO.widget.Dialog(tDlg, 
    {
      width : "30em",
      zIndex: 300,
      fixedcenter : true,
      visible : false, 
      constraintoviewport : true,
      buttons: [ 
      {
        text:"Speichern",
        handler: function() {
          // this refers to the dialog object
          YAHOO.log('Saving group data','grid','gridcms.js');
          this.submit();
        },
        isDefault: true
      },

      {
        text:"Abbrechen",
        handler: function() {
          // this refers to the dialog object
          YAHOO.log('Editing group cancelled','grid','gridcms.js');
          this.cancel();
        }
      }
      ]  
    });

    // Wire up the success and failure handlers
    dlg.callback = {
      success: function(o) {
        YAHOO.log(o.responseText,'grid','gridcms.js');
        f_viewManage(contentTag, l_cms, 'group');
      },
      failure: function(o) {
        alert("Submission failed: " + o.status);
      }
    };
        
    // Render the Dialog
    dlg.render();
    dlg.show();

  },
  
  // =========================================================================
  // ABOUT METHODS
  // =========================================================================

  getVersion: function () {
    return this.cms.getVersion();
  }
  
};


/**
 * ############################################################################
 * ############################################################################
 * GRID ELEMENT
 * ############################################################################
 * ############################################################################
 */
var GridElement = Class.create();
GridElement.prototype = {

  /**
   * Constructor
   * 
   */
  initialize: function(cms, oProp) {
    
    YAHOO.log('initialising element object','grid','gridcms.js');

    // reference to cms
    this.cms = cms;
    
    // init element dialog
    this.tDialog = $('gridcms_dlg_element');
    if (!this.tDialog) {
      // create dialog
      this.tDialog = $(document.createElement('div'));
      this.tDialog.id = "gridcms_dlg_element";
      document.body.appendChild(this.tDialog);
    }
    this.tDialog.innerHTML = '<div class="hd">Element</div>' +
    '<div class="bd">' +
    '<form id="gridcms_dlg_element_form" method="POST" action="'+this.cms.prefix+'/cms/element">' +
    '</form>' +
    '</div>';
    // Instantiate the Dialog
    this.dialog = new YAHOO.widget.Dialog(this.tDialog, 
    {
      width : "40em",
      zIndex: 300,
      fixedcenter : false,
      visible : false, 
      modal: false,
      constraintoviewport : true
    });

    // init relation search dialog
    this.tRelationSearchDialog = $('gridcms_dlg_relationsearch');
    if (!this.tRelationSearchDialog) {
      // create dialog
      this.tRelationSearchDialog = $(document.createElement('div'));
      this.tRelationSearchDialog.id = "gridcms_dlg_relationsearch";
      document.body.appendChild(this.tRelationSearchDialog);
    }
    this.tRelationSearchDialog.innerHTML = '<div class="hd">Relation Search</div>' +
    '<div class="bd">' +
    '<form id="gridcms_dlg_relationsearch_form" method="POST" action="'+this.cms.prefix+'/cms/element">' +
    '</form>' +
    '</div>';
    // Instantiate the Dialog
    this.RelationSearchDialog = new YAHOO.widget.Dialog(this.tRelationSearchDialog,
    {
      width : "40em",
      zIndex: 300,
      fixedcenter : false,
      visible : false,
      modal: false,
      constraintoviewport : true
    });

    YAHOO.log('element object initialised','grid','gridcms.js');
      
  },
  
  getDialog : function () {
    return this.dialog;
  },
  
  _showElementDialog : function (html,mode,callback) {
    
    YAHOO.log('setting up dialog','grid','gridcms.js');
    
    // define content
    $('gridcms_dlg_element_form').innerHTML = html;

    // define buttons
    var buttons = [];
    if (mode=="edit" || mode=="manage") {
      buttons = [ 
      {
        text:"Speichern",
        handler: function() {
          YAHOO.log('Saving element','grid','gridcms.js');
          this.submit();
        },
        isDefault: true
      },

      {
        text:"Abbrechen",
        handler: function() {
          // this refers to the dialog object
          YAHOO.log('Element cancelled','grid','gridcms.js');
          this.cancel();
        }
      }
      ];      
    } else if (mode=="trash") {
      buttons = [ 
      {
        text:"Löschen",
        handler: function() {
          YAHOO.log('Moving element to trash','grid','gridcms.js');
          this.submit();
        },
        isDefault: true
      },

      {
        text:"Abbrechen",
        handler: function() {
          // this refers to the dialog object
          YAHOO.log('Trash cancelled','grid','gridcms.js');
          this.cancel();
        }
      }
      ];            
    } else {
      buttons = [ 
      {
        text:"Ok",
        handler: function() {
          this.cancel();
        },
        isDefault: true
      }
      ];
    }
    this.dialog.cfg.queueProperty("buttons", buttons);

    // Validate the entries in the form to require that both first and last name are entered
    this.dialog.validate = function() {
      var data = this.getData();
      if (false) {
        alert("info");
        return false;
      } else {
        return true;
      }
    };

    // Wire up the success and failure handlers
    this.dialog.callback = { 
      success: function(o) {
        if (callback) {
          callback();
        }
      },
      failure: function(o) {
        alert("Submission failed: " + o.status);
      },
      upload: function(o) {
        if (callback) {
      //          callback();
      }
      } 
    };
    
    // Render and show the Dialog
    this.dialog.render();
    this.dialog.show();
  },
  
  // =========================================================================
  // CREATE
  // =========================================================================

  load : function (id, mode, callback) {
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/element?action=load&mode="+mode+"&meta_id="+id, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._showElementDialog(transport.responseText, mode, "_first", callback);
      }.bind(this)
    });    
  },
  
  create : function (elementtype, attributes, callback) {
    // check for attributes
    if (!attributes) attributes = ""
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/element?action=create&elementtype="+elementtype+"&"+attributes, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._showElementDialog(transport.responseText, "edit", "_first", callback);
      }.bind(this)
    });    
  },

  addRelation : function (id, attribute, elementtype, attgroup, callback) {
    // check if attgroup is defined
    if (!attgroup) {
      attgroup="_first";
    }
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/element?action=addrelation&meta_id="+id+"&attribute="+attribute+"&elementtype="+elementtype+"&attgroup="+attgroup, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._showElementDialog(transport.responseText, "edit", attgroup, callback);
      }.bind(this)
    });
  },

  deleteRelation : function (id, attribute, relid, attgroup, callback) {
    // check if attgroup is defined
    if (!attgroup) {
      attgroup="_first";
    }
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/element?action=deleterelation&meta_id="+id+"&attribute="+attribute+"&relationid="+relid+"&attgroup="+attgroup, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._showElementDialog(transport.responseText, "edit", attgroup, callback);
      }.bind(this)
    });
  },

  moveRelation : function (id, attribute, relid, dir, attgroup, callback) {
    // check if attgroup is defined
    if (!attgroup) {
      attgroup="_first";
    }
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/element?action=moverelation&meta_id="+id+"&attribute="+attribute+"&relationid="+relid+"&direction="+dir+"&attgroup="+attgroup, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._showElementDialog(transport.responseText, "edit", attgroup, callback);
      }.bind(this)
    });
  },

  deleteUpload : function (id, attribute, fileid, attgroup, callback) {
    // check if attgroup is defined
    if (!attgroup) {
      attgroup="_first";
    }
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/element?action=deletefile&meta_id="+id+"&attribute="+attribute+"&fileid="+fileid+"&attgroup="+attgroup, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._showElementDialog(transport.responseText, "edit", attgroup, callback);
      }.bind(this)
    });
  },

  setWorkflowStatus : function (id, status, attgroup, callback) {
    // check if attgroup is defined
    if (!attgroup) {
      attgroup="_first";
    }
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/element?action=setworkflowstatus&meta_id="+id+"&status="+status+"&attgroup="+attgroup, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._showElementDialog(transport.responseText, "view", attgroup, callback);
      }.bind(this)
    });
  },


  show : function (id, mode, forceload, attgroup, callback) {
    // define action
    var action = "show";
    if (forceload) {
      action = "load";
    }
    if (!attgroup) {
      attgroup="_first";
    }
    // create AJAX request
    new Ajax.Request( this.cms.prefix + "/cms/element?action="+action+"&mode="+mode+"&meta_id="+id+"&attgroup="+attgroup, {
      method: "get",
      onComplete: function(transport) {
        // parse XML and select the "room" element
        this._showElementDialog(transport.responseText, mode, attgroup, callback);
      }.bind(this)
    });    
  },

  // =========================================================================
  // ABOUT METHODS
  // =========================================================================

  getVersion: function () {
    return this.cms.getVersion();
  }
  
};

// create CMS object
gridcms = new GridCms ();

