/*---------------------------------------------------------------------------------*/
  /**
   *  smoothy.cms class with utility functions for smoothy-cms
   */
   
smoothy.cms = 
{
  _panels: {},
  _skip_update_panel: '',
  _text_name: '',
  _site_path: '',
  _site_language: '',
  _ckeditor: null,
  _logged_in : false,
  
  /**
   * smoothy.cms.startMenu()
   */
  startMenu : function()
  {
    if (this._logged_in)
    {
      smoothy.cms.fadeInPanel('menu');
    }
    else
    {
      smoothy.ensureJsScript('libs/ckeditor/ckeditor.js');
      smoothy.cms.login();
    }
  },
  /**
   * smoothy.cms.login();
   */
  login : function()
  {
    dojo.require('dijit.dijit');            
    var dlg = dijit.byId('_login_dialog');
    if (dlg)
    {
      dlg.show();
      return;
    }
    // create if not yet exists
    
    var loginDiv = document.createElement('div');
    loginDiv.id = '_smoothy_cms_login';
    dojo.body().appendChild(loginDiv);       

    smoothy.ajax.responseConnector.subscribeOnce(smoothy.cms.afterLoginDialogResponse);
    smoothy.ajax.updateDomNode('?path=/panels/login', '_smoothy_cms_login', 'cms/default');      
  },
  /**
   *
   */
  afterLoginDialogResponse : function(result)
  {
    if (result == null)
      return;
      
    dojo.require('dojo.parser');
    dojo.require('dijit.Dialog');
    dojo.require('dijit.form.Form');
    dojo.require('dijit.form.Button');
    dojo.require('dijit.form.ValidationTextBox');

    dojo.parser.parse('_start'); // must be outside _login_dialog ? oh well...
    dlg = dijit.byId('_login_dialog');
    if (!dlg)
      alert('_login_dialog not found');

    dojo.connect(dijit.byId('_login_form'), "onSubmit", function(e)
                 { 
                    dojo.stopEvent(e); // stop the form submission event                    
                    if (this.isValid()) // submit the form
                    {     
                      dijit.byId('_login_dialog').hide();                        
                      smoothy.ajax.responseConnector.subscribeOnce(function(result)
                        { 
                          if (result.params.authenticated)
                          {
                            smoothy.cms._logged_in = true;
                            /*var d = dijit.byId('login_dialog');
                            dojo.body().removeChild(d.domNode);
                            d.destroyRecursive(); // safer, kill password :-)*/
                            smoothy.cms.fadeInPanel('menu');      
                            smoothy.requestLastPath(); // to get unpublished version of site
                          }
                          else
                          {
                            dojo.byId('_invalid_login').innerHTML = result.params.invalid_login_gui_text;
                            dijit.byId('_login_dialog').show();
                          }
                        });

                      smoothy.ajax.post('_login_form');
                    } 
                    else // show all invalid fields
                    {
                      this.validate();
                    }
                 });
    dlg.show();
  },
  /**
   * smoothy.cms.logOff();
   */
  logOff : function()
  {
    smoothy.ajax.responseConnector.subscribeOnce(function(result)
                            { 
                              smoothy.cms._logged_in = false;
                              smoothy.cms.fadeOutPanel('menu');
                              smoothy.cms.hidePencils();
    
                              smoothy.requestLastPath(); // to get published version of site
                            });
     
    smoothy.ajax.get('?path=/logout$cms/default&_one_way=true'); 
  },
  /**
   * smoothy.cms.updatePanels();
   */
  updatePanels : function()
  {
    for (var name in this._panels)
    {
      if (this.isPanelVisible(name) && 
          name != this._skip_update_panel)
        this.updatePanel(name); // else alert('invis ' + name);
    }
    this._skip_update_panel = ''; // clear because only once skip
  },
  /**
   * smoothy.cms.addPencilImages();
   */
  addPencilImages : function()
  {
    smoothy.cms.removePencilImages(false); // remove old ones first
    
    var keys = dojo.query('[smoothyCmsKey]');
    keys.forEach(function(node, index, arr)
      {
        var pos = dojo.coords(node, true);
        pos.x -= 10; // center image
        pos.y -= 10;
        
        var cmsKey = dojo.attr(node, 'smoothyCmsKey');
        var cmsPath = dojo.attr(node, 'smoothyCmsPath');
        if (!cmsKey || !cmsPath)
          alert('no key/path found for node');
        
        var pencil = document.createElement('img');
        pencil.src = 'styles/cms/images/pencil_20.png';
        dojo.style(pencil, {
                        opacity: 0,
                        position: 'absolute',
                        left: pos.x + 'px',
                        top: pos.y + 'px',
						zIndex: 29
                      });
        dojo.attr(pencil, 'smoothyPencil', 'true');
        dojo.connect(pencil, 'onclick', function()
          {
            smoothy.cms.startEditing(cmsPath, cmsKey);
          });
        dojo.body().appendChild(pencil);        
      });
      
      var pencils = dojo.query('[smoothyPencil]');
      pencils.forEach(function(node, index, arr)
        {
          dojo.fadeIn({node: node, 
                       duration: dojo.isIE <= 7 ? 500 : 2000 }).play();   
        });   
  },
  /**
   * smoothy.cms.removePencilImages();
   */
  removePencilImages : function(fade)
  {
    var pencils = dojo.query('[smoothyPencil]');
    if (fade)
      pencils.forEach(function(node, index, arr)
      {
        
        dojo.fadeOut({node: node, 
                      duration: dojo.isIE <= 7 ? 500 : 2000,
                      onEnd: function() { dojo.body().removeChild(node); }
                     }).play();
      });
    else
      pencils.forEach(function(node, index, arr)
      {
        dojo.body().removeChild(node);
      });
  },
  /**
   * smoothy.cms.updateAfterNavigation();
   */
  updateAfterNavigation : function()
  { 
    if (smoothy.getCookie('_cms_edit') == 'true') // showPencils
    {
      smoothy.cms.addPencilImages();
    }
    
    smoothy.cms.updatePanels();     
  },  
  /**
   * smoothy.cms.registerPanelForUpdates();
   */
  registerPanelForUpdates : function(name, panel)
  {
    if (name == 'menu') // 1st one, do not update, register callback to updatePanels
    {
      smoothy.ajax.responseConnector.subscribe(function(result)
                                              { 
                                                if (result.style) // no style for _configs... ( TODO unhack)
                                                  smoothy.cms.updateAfterNavigation();
                                              }); 
    }
    else if (name == 'content') // do not update, keep editor alive
    {
    }
    else // add to collection
    {
      this._panels[name] = panel;
    }
  },
  /**
   * smoothy.cms.updatePanel('style')
   * smoothy.cms.updatePanel('layout',  '&template=standard" )
   * smoothy.cms.updatePanel('layout',  '&template=standard", true)
   */
  updatePanel : function(name, params, refresh_site)
  {
    var drag_node = dojo.byId('_smoothy_drag_' + name);
    if (drag_node)
    {    
    	smoothy.setCookie("drag_pos_x", parseFloat(drag_node.style.left));
    	smoothy.setCookie("drag_pos_y", parseFloat(drag_node.style.top));
    }
  
    var url = '?path=/panels/' + name;
    if (params)
      url += params;
    var domid = '_smoothy_cms_' + name;    
    
    if (refresh_site) // after next response: reload complete site
    {
      smoothy.ajax.responseConnector.subscribeOnce(function(result){ smoothy.requestLastPath(); });
      // this will cause an updatePanels which we do not want for this panel, cause it's already updated 1st
      this._skip_update_panel = name;
    } 
    smoothy.ajax.updateDomNode(url, domid, 'cms/default');
  },
  /**
   * smoothy.cms.generateSitemap()
   */
  generateSitemap : function()
  {
    var host = prompt("http host? (e.g. www.mooiverkocht.nl)", window.location.hostname);
    url = "?path=/../../../cms/default/config/output/xmlsitemap&content_type=plain&content_disposition=sitemap.xml";
    if (host)
      url += "&http_host=http://" + host;
    location.href = url;
  },
  /**
   * smoothy.cms.generateRobots()
   */
  generateRobots : function()
  { 
    var host = prompt("http host?", window.location.hostname);
    url = "?path=/../../../cms/default/config/output/robots&content_type=plain&content_disposition=robots.txt";
    if (host)
      url += "&http_host=http://" + host;
    location.href = url;
  },
  /**
   * smoothy.cms.showPencils()
   */
  showPencils : function()
  {
    if (smoothy.getCookie('_cms_edit') != 'true')
    {
      smoothy.setCookie('_cms_edit', 'true');
      smoothy.requestLastPath();
    }
    else
    {
      smoothy.cms.addPencilImages();
    }
  },
  /**
   * smoothy.cms.hidePencils()
   */
  hidePencils : function()
  {
    smoothy.cms.removePencilImages(true);
    smoothy.deleteCookie('_cms_edit');
  },
  /**
   * smoothy.cms.createPanel('menu')
   * smoothy.cms.createPanel('style', function() { alert('style panel ready') });
   */
  createPanel : function(name, onPanelReady)
  {
    var panel = document.createElement('div');
    panel.id = '_smoothy_cms_' + name;
    dojo.body().appendChild(panel);
    
    smoothy.cms.fetchPanel(name, onPanelReady);
    
    this.registerPanelForUpdates(name, panel);
    return panel;
  },
  /**
   * smoothy.cms.fetchPanel('menu'); // default fadeIn
   * smoothy.cms.fetchPanel('style', function(panel) { ... }); // custom behaviour
   */
  fetchPanel : function(name, onPanelReady)
  { 
    var panel = dojo.byId('_smoothy_cms_' + name);
      
    if (!onPanelReady) // default behaviour
      onPanelReady = function(panel) { smoothy.cms.fadeInPanel(name); };

    // fadeIn so make invisible first
    if (!dojo.isIE)
      dojo.style(panel, 'opacity', 0);
    
    smoothy.ajax.responseConnector.subscribeOnce(function(result)
                                                  {
                                                    onPanelReady(panel);
                                                  });
    
    smoothy.ajax.updateDomNode('?path=/panels/' + name, panel.id, 'cms/default');
  },
  /**
   * smoothy.cms.destroyPanel(name)
   */
  destroyPanel : function(name)
  {  
    var panel = dojo.byId('_smoothy_cms_' + name);
    if (panel)
      dojo.body().removeChild(panel);
  },
  /**
   * smoothy.cms.getPanel(name) can be null
   */
  getPanel : function(name)
  {
    return dojo.byId('_smoothy_cms_' + name);
  },
  /**
   * smoothy.cms.ensurePanel(name, onPanelReady)
   * smoothy.cms.ensurePanel('content', function(panel) { ... } )
   *  onPanelReady is either executed directly if the panel exists, or after downloading the panel if it requires fetching
   */
  ensurePanel : function(name, onPanelReady)
  {
    var panel = this.getPanel(name);
    if (panel)
    {
      if (onPanelReady) 
        onPanelReady(panel);
      return;
    }
      
    smoothy.cms.createPanel(name, onPanelReady);
  },
  /**
   * smoothy.cms.fadeInPanel(name)
   * smoothy.cms.fadeInPanel(name, function() { alert('done!') })
   */
  fadeInPanel : function(name, onEnd)
  {
    this.ensurePanel(name, function(panel)
      {
        dojo.style(panel, 'display', '');
        if (dojo.isIE) // poor IE cannot do opacity on transp png...
        {
          if (onEnd) onEnd();
        }
        else
        {
          dojo.fadeIn({node: panel, 
                       duration: 1500,
                       onEnd: onEnd }).play(); 
        }            
      });
  },  
  /**
   * smoothy.cms.fadeOutPanel(name)
   */
  fadeOutPanel : function(name)
  {
    var panel = this.getPanel(name);
    if (panel)
    {
      onEnd = function() { dojo.style(panel, 'display', 'none'); };
      if (dojo.isIE) // poor IE cannot do opacity on transp png...
        onEnd();
      else
        dojo.fadeOut({node: panel,
                      duration: 1000,
                      onEnd: onEnd }).play();
    }
  },
  /**
   * smoothy.cms.showPanel(name)
   */
  showPanel : function(name)
  {
    this.ensurePanel(name, function(panel)
      {
        if (!dojo.isIE)
          dojo.style(panel, 'opacity', 1.0);
        dojo.style(panel, 'display', '');
      });
  },
  /**
   * smoothy.cms.hidePanel(name)
   */
  hidePanel : function(name)
  {
    var panel = this.getPanel(name);
    if (panel)
      dojo.style(panel, 'display', 'none');
  },
  /**
   * smoothy.cms.isPanelVisible(name)
   */
  isPanelVisible : function(name)
  {
    var panel = this.getPanel(name);
    if (!panel)
      return false;
    return dojo.style(panel, 'display') != 'none';
  },
  /**
   * smoothy.cms.modifyEditorButtons()
   */
  modifyEditorButtons : function()
  {
    // enable the save button:
    CKEDITOR.plugins.registered['save']=
      {
         init: function(editor)
         {
            var command = editor.addCommand('save',
               {
                  modes: { wysiwyg: 1, source: 1 },
                  exec: function(editor) { smoothy.cms.saveEditorValue(); }
               }
            );
            editor.ui.addButton('Save', { label: 'Save', command: 'save'});
         }
      };
  },
  /**
   * smoothy.cms.createEditor()
   */
  createEditor : function(width, height, editorDivId)
  {
    if (smoothy.cms._ckeditor != null)
      return;

    smoothy.cms.modifyEditorButtons();
        
    smoothy.cms._ckeditor = CKEDITOR.appendTo(editorDivId, 
      { 
        width: width,
        height: height,
        filebrowserImageBrowseUrl : '?path=/browse/imagebrowse$cms/default'
        /*filebrowserBrowseUrl : '/tests/browse.php',
        filebrowserUploadUrl : '/tests/browse.php?upl',
        filebrowserImageUploadUrl : '/tests/browse.php?type=Images'*/
      } );
  },
  /**
   * smoothy.cms.startEditing('/start/test', 'title')
   */
  startEditing : function(path, text_name)
  {
    smoothy.cms.showWaitCursor(true);
    smoothy.cms.fadeInPanel('content', function() { smoothy.cms.fetchEditorContents(path, text_name); } );
  },
  /**
   * smoothy.cms.fetchEditorContents();
   */
  fetchEditorContents : function(path, text_name)
  {
    if (smoothy.cms._ckeditor == null)
      alert('fetchEditorContents must be called after loading of editor is complete!');
    
	var _call_id = '_fetchEditorContents';
    smoothy.ajax.responseConnector.subscribeId(function(result)
      { 
        // set editor content & save current path & text_name for saving later (see below)
        smoothy.cms._text_name = result.params.text_name;
        smoothy.cms._site_path = result.params.site_path;
        smoothy.cms._site_language = result.params.site_language;
        
        smoothy.cms._ckeditor.setData(result.params.text_value);
        
        smoothy.cms.showWaitCursor(false);
      }, _call_id);

    var params = { path: '/panels/content',
                   site_path: path,
				   _call_id: _call_id,
                   _ajax_response: '',
                   _config: 'cms/default',
                   _cms_text_name: text_name };
    smoothy.ajax.postParams(params);
  },
  /**
   * smoothy.cms.saveEditorValue()
   */
  saveEditorValue : function()
  {
    smoothy.cms.showWaitCursor(true);
    smoothy.ajax.responseConnector.subscribeOnce(function() { smoothy.cms.showWaitCursor(false); });
    
    var text_value = smoothy.cms._ckeditor.getData();
                        
    var params = { path: smoothy.cms._site_path,
                   _cms_text_name: smoothy.cms._text_name, 
                   _cms_text_value: text_value };
                   
    smoothy.ajax.postParams(params); // will refresh site & update     
  },
  /**
   * smoothy.cms.onPageLinkButton(editor)
   */
  onPageLinkButton : function(editor)
  {  
    showUrl('?path=/browse/pagebrowse$cms/default&CKEditor=' + editor.name);
  },
  /**
   * smoothy.cms.onPageSelected(url, text, editorName)
   */
  onPageSelected : function(url, text, editorName)
  {
    var editor = window.opener.CKEDITOR.instances[editorName];
    url = url.replace("\'", "'");
    smoothy.ui.inputDlg({ 
      title: 'Tekst voor link:',
      input: text,
      maxLength: 250,
      onOK: function(input) 
      { 
        editor.insertHtml('<a href="' + url + '");>' + input + '</a>');
        window.close(); 
      }});    
  },
  /**
   * smoothy.cms.onPdfLinkButton(editor)
   */
  onPdfLinkButton : function(editor)
  {  
    showUrl('?path=/browse/documentbrowse$cms/default&CKEditor=' + editor.name);
  },
  /**
   * smoothy.cms.onDocumentSelected(url, editorName)
   */
  onDocumentSelected : function(url, editorName)
  {
    var editor = window.opener.CKEDITOR.instances[editorName];
    var text = url.split('/').pop();
    var icon = '';
    var extension = text.split('.').pop();
    if (extension == 'doc' ||
        extension == 'docx' ||
        extension == 'xls' ||
        extension == 'ppt' ||
        extension == 'htm' ||
        extension == 'html' ||
        extension == 'txt' ||
        extension == 'pdf' ||
        extension == 'odt' ||
        extension == 'xml')
      icon = "<img src='/styles/images/icons/" + extension + "24.png' alt='icon' align='absmiddle'/>";
    smoothy.ui.inputDlg({ 
      title: 'Tekst voor link:',
      input: text, 
      maxLength: 250,
      onOK: function(input) 
      { 
        editor.insertHtml("<a href=\"javascript:showUrl('/" + url + "');\">" + icon + input + '</a>');
        window.close(); 
      }});    
  },
  /**
   * smoothy.cms.showWaitCursor(true);
   * smoothy.cms.showWaitCursor(false);
   */
  showWaitCursor : function(enable)
  {
    var node = dojo.byId('_smoothy_wait_cursor');
    if (node)
      dojo.style(node, 'display', enable ? '' : 'none');
  },
  /**
   * smoothy.cms.publishChanges()
   */
  publishChanges : function()
  {
    smoothy.ui.confirm('Publiceer wijzigingen', 'Weet u zeker dat u alle wijzigingen nu wilt publiceren?', 
      function() 
      { 
        smoothy.ajax.responseConnector.subscribeOnce(function(result)
          {
            smoothy.ui.alert('Uw wijzigingen zijn gepubliceerd');
          });
    
        smoothy.ajax.get('?path=/panels/menu$cms/default&_one_way=true&publish=true');
      }
      );
  }
}

var node = null;
var drag_last_x = 0;
var drag_last_y = 0;
var drag_last_z = 30;

function drag_start(event, node_id)
{
	drag_node = document.getElementById(node_id);
  if (!drag_node)
    return;
  drag_last_x = happy_browser_clientX(event);
  drag_last_y = happy_browser_clientY(event);
  drag_node.style.zIndex = ++drag_last_z;
      
  happy_browser_addEventListener("mousemove", drag_move, true);
  happy_browser_addEventListener("mouseup",   drag_release, true);
  happy_browser_stopPropagation(event);
  happy_browser_preventDefault(event);
}

function drag_move(event)
{
  var drag_x = happy_browser_clientX(event);
  var drag_y = happy_browser_clientY(event);
  var dx = drag_x - drag_last_x;
  var dy = drag_y - drag_last_y;
  drag_last_x = drag_x;
  drag_last_y = drag_y;
  if (Math.abs(dx) > 2000 || Math.abs(dy) > 2000) // ignore
    return;
  
  move_node(drag_node, dx, dy);
  happy_browser_stopPropagation(event);
  happy_browser_preventDefault(event);
}

function drag_release(event)
{
  happy_browser_removeEventListener("mousemove", drag_move, true);
  happy_browser_removeEventListener("mouseup",   drag_release, true);
}

function move_node(node, dx, dy)
{
  if (node.style.left)
    node.style.left = (parseFloat(node.style.left) + dx) + "px";
  if (node.style.right)
    node.style.right = (parseFloat(node.style.right) - dx) + "px";
  node.style.top = (parseFloat(node.style.top) + dy) + "px";
}

function bring_to_front(event, node_id)
{
	drag_node = document.getElementById(node_id);
  if (!drag_node)
    return;
  drag_node.style.zIndex = ++drag_last_z;
}

var panel_timer = null;
var panel_hidden_x = -200.0;
var panel_shown_x = -1.0;
var panel_node = null;

function show_panel_animation(node_id) 
{
  if (panel_timer) // already running
    stop_panel_animation();
    
	panel_node = document.getElementById(node_id);
  if (!panel_node)
    return;   
  
  panel_timer = setInterval(animate_panel_right, 20);
}

function hide_panel_animation(node_id) 
{
  if (panel_timer) // already running
    stop_panel_animation();
    
	panel_node = document.getElementById(node_id);
  if (!panel_node)
    return;   
  
  panel_timer = setInterval(animate_panel_left, 20);
}

function stop_panel_animation() 
{
  if (panel_timer)
  {
    clearInterval(panel_timer);
    panel_timer = null;
  }
}

function get_sin_factor(scale, domain, t) 
{
  return scale*(Math.sin(2.0*Math.PI*t/domain - 0.5*Math.PI) + 1.0);
}

function animate_panel_right() 
{
  var x = parseFloat(panel_node.style.left);
  if (x < panel_shown_x) // move right
  {
    move_node(panel_node, 1.0+4*get_sin_factor(3.0, panel_shown_x - panel_hidden_x, x - panel_hidden_x), 0);
  }
  else
  {
    stop_panel_animation();
  }
}

function animate_panel_left() 
{
  var x = parseFloat(panel_node.style.left);
  if (x > panel_hidden_x) // move left
  {
    move_node(panel_node, -1.0-get_sin_factor(3.0, panel_shown_x - panel_hidden_x, x - panel_hidden_x), 0);
  }
  else
  {
    stop_panel_animation();
  }
}

