/*---------------------------------------------------------------------------------*/
  /**
   *  smoothy.cms class with utility functions for smoothy-cms
   */
   
smoothy.cms = 
{
  _panels: {},
  _skip_update_panel: '',
  _text_name: '',
  _site_path: '',
  _site_language: '',
  _editorLoaded: false,
  _doInOnComplete: null,
  
  /**
     * smoothy.cms.login();
     */
  login : function()
  {
     dojo.require('dojo.parser');
     dojo.require('dijit.Dialog');
     dojo.require('dijit.form.Form');
     dojo.require('dijit.form.Button');
     dojo.require('dijit.form.ValidationTextBox');
     
     var dlg = dijit.byId('_login_dialog');
     if (!dlg) // create if not yet exists
     {
       dojo.parser.parse('_start'); // must be outside _login_dialog ? oh well...
       dlg = dijit.byId('_login_dialog');

       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)
                              {
                                /*var d = dijit.byId('login_dialog');
                                dojo.body().removeChild(d.domNode);
                                d.destroyRecursive(); // safer, kill password :-)*/
                                smoothy.cms.fetchPanel('menu');                                
                              }
                              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.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 key = dojo.attr(node, 'smoothyCmsKey');
        
        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'
                      });
        dojo.attr(pencil, 'smoothyPencil', 'true');
        dojo.connect(pencil, 'onclick', function()
          {
            smoothy.cms.startEditing(smoothy.getCookie('prev_path'), key);
          });
        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.startMenu()
     */
  startMenu : function()
  {
    dojo.require('dijit.dijit');
    
    smoothy.cms.fadeInPanel('menu');
    
     var dlg = dijit.byId('_login_dialog');
     if (dlg) // if user cancelled login, show it again
       dlg.show();
  },
  /**
     * 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')
     */
  createPanel : function(name)
  {
    var panel = document.createElement('div');
    panel.id = '_smoothy_cms_' + name;
    dojo.body().appendChild(panel);
    
    smoothy.cms.fetchPanel(name);
    
    this.registerPanelForUpdates(name, panel);
    return panel;
  },
  /**
     * smoothy.cms.fetchPanel('menu')
     * smoothy.cms.fetchPanel('style')
     */
  fetchPanel : function(name)
  { 
    var panel = dojo.byId('_smoothy_cms_' + name);
    
    // fadeIn so make invisible first
    dojo.style(panel, 'opacity', 0);
    smoothy.ajax.responseConnector.subscribeOnce(function(result)
                                                {
                                                  smoothy.cms.fadeInPanel(name); 
                                                });
    
    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)
     */
  ensurePanel : function(name)
  {
    var panel = this.getPanel(name);
    if (panel)
      return panel;
      
    return smoothy.cms.createPanel(name);
  },
  /**
     * smoothy.cms.fadeInPanel(name)
     * smoothy.cms.fadeInPanel(name, function() { alert('done!') })
     */
  fadeInPanel : function(name, onEnd)
  {
    var panel = this.ensurePanel(name);
    if (panel)
    {
      if (false && dojo.style(panel, 'display') == '') // already visible: no fadeIn delay wanted
      {
        if (onEnd)
          onEnd();
      }
      else
      {
        dojo.style(panel, 'display', '');
        dojo.fadeIn({node: panel, 
                     duration: dojo.isIE <= 7 ? 500 : 2000,
                     onEnd: onEnd}).play(); 
                     // poor IE cannot do opacity on transp png: make wait time shorter, TODO ok in IE 8 ?
      }
    }
  },  
  /**
     * smoothy.cms.fadeOutPanel(name)
     */
  fadeOutPanel : function(name)
  {
    var panel = this.getPanel(name);
    if (panel)
      dojo.fadeOut({node: panel,
                    duration: dojo.isIE <= 7 ? 500 : 2000,
                    onEnd: function(){dojo.style(panel, 'display', 'none');}}).play();
  },
  /**
     * smoothy.cms.showPanel(name)
     */
  showPanel : function(name)
  {
    var panel = this.ensurePanel(name);
    dojo.style(panel, 'opacity', 255);
    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.createEditor()
     */
  createEditor : function()
  {
    fckeditor = new FCKeditor('cms_editor');
    fckeditor.BasePath = '/libs/fckeditor/';
    //fckeditor.ToolbarSet = 'Concept';
    fckeditor.Width = '800px'
    fckeditor.Height = '612px';
    dojo.byId('editor_div').innerHTML = fckeditor.CreateHtml();
  },
  /**
     * smoothy.cms.startEditing('/start/test', 'title')
     */
  startEditing : function(path, text_name)
  {
    smoothy.cms.showWaitCursor(true);
    smoothy.cms.fadeInPanel('content');
    if (smoothy.cms._editorLoaded) 
    {
      smoothy.cms.fetchEditorContents(path, text_name);
    }
    else
    {
      smoothy.cms._doInOnComplete = { path: path, text_name: text_name };
    }
  },
  /**
     * smoothy.cms.fetchEditorContents();
     */
  fetchEditorContents : function(path, text_name)
  {
    if (!smoothy.cms._editorLoaded) 
      alert('fetchEditorContents must be called after loading of editor is complete!');
      
    smoothy.ajax.responseConnector.subscribeOnce(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;
        
        FCKeditorAPI.GetInstance('cms_editor').SetHTML(result.params.text_value);
        
        smoothy.cms.showWaitCursor(false);          
      });

    var params = { path: '/panels/content',
                   site_path: path,
                   _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 = FCKeditorAPI.GetInstance('cms_editor').GetXHTML(true);
                        
    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.showWaitCursor(true);
     * smoothy.cms.showWaitCursor(false);
     */
  showWaitCursor : function(enable)
  {
    var node = dojo.byId('_smoothy_wait_cursor');
    if (node)
      dojo.style(node, 'display', enable ? '' : 'none');
  }
}

function FCKeditor_OnComplete(editorInstance)
{
  smoothy.cms._editorLoaded = true;
  if (smoothy.cms._doInOnComplete) // still waiting: set text now
  {
    smoothy.cms.fetchEditorContents(smoothy.cms._doInOnComplete.path,
                                    smoothy.cms._doInOnComplete.text_name);
  }
}

var node = null;
var drag_last_x = 0;
var drag_last_y = 0;
var drag_last_z = 1;

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();
  }
}

