// Namespace
var Cushy = {
  // Send debugging to firebug if its running.
  warn:  function (message) {Try.these(function () {console.warn(message)})},
  error: function (message) {Try.these(function () {console.error(message)})},

  load: function() {
    // load all
    Cushy.Users.load();
    Cushy.Editors.load();
    Cushy.Sites.load();
    Cushy.Pages.load();

    Cushy._default_locale = 'en';
    Cushy._validators = [];

    // Scriptolicious animation on user messages.
    $$('.message').each(function (m) { new Effect.BlindDown(m) });

    // Flash font black magic to replace larger fonts with flash versions of the same text.
    var h1s = new Font('Font.Volkswagen2.swf', {sizeAdjust:+16, tags:'h1'});
    h1s.replace();
    var h2s = new Font('Font.Volkswagen2.swf', {sizeAdjust:+5, tags:'h2', classFilter:'fancy'});
    h2s.replace();

    // Add validation support to all forms
    $$('form').each(function(f) {
      Cushy._validators[f.id] = new Validation(f);
      // add upload hint to file fields
      var fileFields = Form.getInputs(f, 'file');
      fileFields.each(function(field) {
        Event.observe(field, 'change', function(e) {
          field.previous().innerHTML = 'File will be uploaded upon publish';
          field.previous().addClassName('uploadPending');
        });
      });
    });

    // Highlight specific elements where needed
    $$('.highlight').each(
      function(f) {
        f.insert( {
            top: new Element("img", { src: '/images/icons/highlight_indicator.gif', 'class': 'highlightIndicator' })
        } )
      }
    );

    // Convert textareas to fckeditor fields
    $$('.fckeditor').each(this.fckeditor);

    // Applies the loading spinner to buttons that need it (on click)
    $$('.showLoadingStatus').each(
      function(e) {
        Event.observe(e, 'mousedown', function(ev) {
          var icon = e.firstDescendant();
          icon.src = '/images/loading_mini.gif';
          e.blur();
          return true;
        });
      }
    );

    // Watch for form changes.
    Cushy.ChangeWatcher.start();

    // Add an event to check for form changes.
    Event.observe(window, 'beforeunload', function(e) {
      if (Cushy.ChangeWatcher.changed() && !Cushy.ChangeWatcher.submitted()) {
        // This triggers some kind of built in browser check to ask the user if
        // they want to navigate away.
        Event.stop(e);
        return false;
      }
      return true;
    });
  },
  validatorFor: function(name) {
    return Cushy._validators[name]
  },
  spinner: function(el) {
    el.update(new Element('img', {src: '/images/loading.gif'}));
  },
  countdownRedirect: function(counter, href) {
    var current = counter.innerHTML
    if (current > 0) {
      counter.innerHTML = current - 1;
      setTimeout("Cushy.countdownRedirect($('" + counter.id + "'), '" + href + "')", 1000);
    }
    else {
      document.location.href = href;
    }
    return true;
  },
  setLocale: function(locale) {
    Cushy._locale = locale;
  },
  getLocale: function() {
    if (Cushy._locale == null)
      return Cushy._default_locale;
    else
      return Cushy._locale;
  },
  freezeContentHeight: function() {
    var container = $('content');
    var containerHeight = container.getHeight();
    container.setStyle({ height: containerHeight+'px' });
  },
  thawContentHeight: function() {
    var container = $('content');
    container.setStyle({ height: 'auto' });
  },
  fckeditor: function(e) {
    if(e.rows == 1) { // single line
      var defaultHeight = '30';
    }
    else {
      var defaultHeight = '200';
    }
    var oFCKeditor = new FCKeditor(e.id, '100%', defaultHeight, 'Default');
    oFCKeditor.BasePath                           = '/javascripts/';
    oFCKeditor.Config['CustomConfigurationsPath'] = fckCustomConfigurationPath + "?" + ( new Date() * 1 ); // path defined in the view as it is specific to a site, as different sites can have different configurations
    oFCKeditor.Config['DefaultLanguage']          = Cushy.getLocale();
    if($('site_base_url')) {
      oFCKeditor.Config['BaseHref'] = $('site_base_url').value;
    }
    oFCKeditor.ReplaceTextarea();
  }
};

Cushy.ChangeWatcher = {
  changed: function() {
    return Cushy.ChangeWatcher._changes;
  },
  submitted: function() {
    return Cushy.ChangeWatcher._submitted;
  },
  triggerChange: function() {
    Cushy.ChangeWatcher._changes = true;
  },
  triggerSubmit: function() {
    Cushy.ChangeWatcher._submitted = true;
  },
  // Add some onchange events to all the elements we care about.
  start: function() {
    Cushy.ChangeWatcher._changes = false;
    Cushy.ChangeWatcher._submitted = false;
    $$('form.watch_changes').each(function(f) {
      Form.getElements(f).each(function(i) { Event.observe(i, 'change', Cushy.ChangeWatcher.triggerChange) });
    });
    $$('form.watch_changes div.editorContain').each(function(d) {
      if (d.down(1) && d.down(1).contentWindow) {
        Event.observe(d.down(1).contentWindow.document, 'keypress', Cushy.ChangeWatcher.triggerChange)
      }
      else {
        Event.observe(d, 'keypress', Cushy.ChangeWatcher.triggerChange)
      }
    });
    // If the form is submitted, remove the unload warning.
    $$('form.watch_changes').each(function(f) {
      Event.observe(f, 'submit', Cushy.ChangeWatcher.triggerSubmit);
    });
  },
  // Stop all the observers that were started in start(). You would want to do
  // this to relieve the browser of that overhead if you have already seen a
  // change.
  stop: function() {
    $$('form.watch_changes').each(function(f) {
      Form.getElements(f).each(function(i) { Event.stopObserving(i, 'change', Cushy.ChangeWatcher.triggerChange) });
    });
    $$('form.watch_changes div.editorContain').each(function(d) {
      if (d.down(1) && d.down(1).contentWindow) {
        Event.stopObserving(d.down(1).contentWindow.document, 'keypress', Cushy.ChangeWatcher.triggerChange)
      }
      else {
        Event.stopObserving(d, 'keypress', Cushy.ChangeWatcher.triggerChange)
      }
    });
  }
};

Cushy.Sites = {
  load: function() {
    // Not in the sites area?
    if ($$('body.sites').size() == 0)
      return;

    // Populate the ftp server field based on the url of the site.
    if ($('site_url')) {
      Event.observe($('site_url'), 'blur', function() {
        var url = $('site_url').value;
        var el = $('ftp_host');
        if (url && el && el.value.blank())
          el.value = url.sub(/^(ht|f)tp:\/\//, '')
        return true;
      });
    }
    // Setup events on the img to toggle the pages area on/off
    $$('a.showHidePages').each(function(x) { Event.observe(x, 'click', Cushy.Sites.showHidePage);});

    return;
  },
  setPath: function(ele, path) {
    $$('#ftp_tree_root .selected').each(function(x) { x.removeClassName('selected') });
    $('path').value = path;
    $('upload_root').innerHTML = path;
    if (path != '') $('upload_root').innerHTML += '/'
    if (ele) ele.up().addClassName('selected');
  },
  advancedSettingsToggle: function() {
    container = $('advanced_site_settings')
    if (container.visible()) {
      $('advanced_site_settings_show').show();
      $('advanced_site_settings_hide').hide();
      container.hide();
    }
    else {
      $('advanced_site_settings_show').hide();
      $('advanced_site_settings_hide').show();
      container.show();
    }
  },
  advancedWysiwygSettingsToggle: function() {
    container = $('advanced_wysiwyg_settings')
    if (container.visible()) {
      $('advanced_wysiwyg_settings_show').show();
      $('advanced_wysiwyg_settings_hide').hide();
      container.hide();
    }
    else {
      $('advanced_wysiwyg_settings_show').hide();
      $('advanced_wysiwyg_settings_hide').show();
      container.show();
    }
  },
  customPathToggle: function(sel) {
    option = $A(sel.options).find(function(opt) { return opt.selected });
    if (option.value == 'custom')
      $('upload_path').show();
    else
      $('upload_path').hide();
  },
  showHidePage: function(e) {
    var tbody = $("sitePages_" + this.id.split("_")[1]);
    if (tbody.visible())
      tbody.hide();
    else
      tbody.show();
  }
};

Cushy.Pages = {
  load: function() {
    // Not in the pages area?
    if ($$('body.pages').size() == 0)
      return;


    // Where pages specific JS would go...
    return;
  }
};

Cushy.Users = {
  load: function() {
    // Not in the users area?
    if ($$('body.users').size() == 0)
      return;

    if ($$('body.create').size() > 0)
      setTimeout("Cushy.countdownRedirect($('counter'), $('redirect').href)", 1000);

    // Add clienteditor to subdomains if input is single word
    if ($('designer_subdomain'))
      Event.observe($('designer_subdomain'), 'blur', Cushy.Users.setSubdomain);

    // Where users specific JS would go...
    return;
  },
  setSubdomain: function() {
    container = $('designer_subdomain')
    if (container) {
      if (!container.value.match(/\./)) {
        container.value += '.clienteditor.com'
      }
    }
  }
};

Cushy.Editors = {
  load: function() {
    // Not in the editors area?
    if ($$('body.editors').size() == 0)
      return;

    // Site checkboxes are named site_#, so i don't know a nice way to grab them
    // all. But we need to group up the pages with each site. This JS is very
    // specific to the design of the page unfortunately.
    $$('li.folder').each(function(folder) {
      var pages = $A(folder.getElementsByTagName('input'));
      var site  = pages.shift();

      // Don't do anything for sites with no pages.
      if (pages.size() == 0) return

      // Add event to the site checkbox, which sets all the pages underneath to
      // be the same as the site.
      Event.observe(site, 'click', function(e) {
        pages.each(function(page) { page.checked = site.checked })
      });

      // Add event to all pages.
      pages.each(function(page) {
        Event.observe(page, 'click', function(e) {
          // If you tick all pages, the site should get ticked.
          if (page.checked) {
            var count = 0;
            pages.each(function(x) {
              if (x.checked) {
                count++;
              }
            });
            if (count == pages.size()) {
              site.checked = true;
            }
          }
          // If you untick a page, make sure the site is unticked.
          else {
            site.checked = false;
          }
        });
      });
    });

    // Where editors specific JS would go...
    return;
  }
};

// Stuff specific to the FtpTree thinger in the sites section.
Cushy.Sites.FtpTree = {
  initTree: function(remote_address, form_name) {
    if (!Cushy.validatorFor(form_name).validate())
      return false;
    Cushy.Sites.setPath(null, '');
    $('ftp_tree_root_container').style.display = 'block';
    var ele = $('ftp_tree_root');
    new Ajax.Updater(ele, remote_address, {
      asynchronous: true,
      evalScripts:  true,
      parameters:   Form.serialize(form_name),
      onFailure:    function(request) {
        ele.addClassName('message');
        ele.addClassName('issue');
      },
      onLoading:    function(request) {
        Cushy.spinner(ele);
        ele.removeClassName('message');
        ele.removeClassName('issue');
      },
      onSuccess:    function(request) {
        ele.removeClassName('message');
        ele.removeClassName('issue');
      }
    });
    return false;
  },
  toggleDir: function(dir_id, path, remote_address, form_name) {
    var dir = $(dir_id);
    Cushy.Sites.setPath(dir, path);
    if (dir && dir.empty()) {
      new Ajax.Updater(dir, remote_address, {
        asynchronous: true,
        evalScripts:  true,
        parameters:   Form.serialize(form_name),
        onLoading:    function(request) {Cushy.spinner(dir)},
        onFailure:    function(request) {Cushy.Sites.setPath(null, '')}
      });
    }
    else if (dir) {
      dir.toggle();
    }
    return false;
  }
};

// Stuff specific to the FtpTree thinger in the pages section.
Cushy.Pages.FtpTree = {
  toggleDir: function(dir_id, remote_address) {
    var dir = $(dir_id);
    if (dir && dir.empty()) {
      new Ajax.Updater(dir, remote_address, {
        asynchronous: true,
        evalScripts:  true,
        method:       'get',
        onLoading:    function(request) {Cushy.spinner(dir)}
      });
    }
    else if (dir) {
      dir.toggle();
    }
    return false;
  },
  toggleFile: function(file_id, path) {
    var current_path = $('page_path').value
    var new_url_path = path

    if (current_path.blank()) {
      if (!$('page_url').value.endsWith('/'))
        $('page_url').value += '/'
      $('page_url').value += new_url_path
    }
    else {
      $('page_url').value = $('page_url').value.sub(current_path, new_url_path);
    }

    $$('#ftp_tree_root .selected').each(function(x) { x.toggleClassName('selected') });
    $(file_id).toggleClassName('selected');

    $('page_path').value = path;
  }
};

document.observe('dom:loaded', function() { Cushy.load() });

// Crazy FCKeditor API onload trigger
function FCKeditor_OnComplete( editorInstance ) {
  var editorTextArea = $(editorInstance.Name);
  if(editorTextArea.rows == 1) { // single line - hide the toolbar
    editorInstance.ToolbarSet.Collapse();
    editorInstance.EditorWindow.parent.document.getElementById("xExpandHandle").style.display = "none";
    editorInstance.SetHTML(editorInstance.GetHTML()); // hack way of refreshing the auto-height stuff
  }
}
