var LinksDialog = Class.create({
  initialize: function(element, pages, sections, committees, sharedResources) {
    this.element = $(element);
    this.pages = pages;
    this.sections = sections;
    this.committees = committees;
    this.sharedResources = sharedResources;
    this.content = this.element.down('.dialog_border.content');
    this.buildDialog();
  },
  show: function() {
    window.PageEditor.execCommand('createlink', 'http://fiat_placeholder/');
    var link = $$('a[href*="fiat_placeholder"]').first();
    if (!link) {
      var html = '<a href="http://fiat_placeholder/">fiat_placeholder</a>';
      if (Prototype.Browser.IE)
        Selection().getRange().pasteHTML(html);
      else
        window.PageEditor.execCommand('insertHtml', html);
      var link = $$('a[href*="fiat_placeholder"]').first();
    }
    if (link.innerHTML.include('fiat_placeholder')) {
      link.innerHTML = 'Link Text';
      this.inserted_fiat_placeholder = link;
    }
    this.range = Selection().getRange();
    this.element.open();
  },
  buildDialog: function() {
    this.content.insert(new Element("h2").update("Create Link"));
    this.tabs = new Element("td", {className: 'tabs'});
    this.panels = new Element("td", {className: 'content'});
    this.content.insert(new Element("table").insert(new Element('tbody').insert(new Element("tr").insert(this.tabs).insert(this.panels))));
    this.buildExistingPagesPanel();
    this.buildNewPagePanel();
    this.buildExternalSitePanel();
    this.buildEmailLinkPanel();
    this.buildSharedResourcesPanel();
    this.selectTab(this.tabs.down('.tab'));
    this.createButtons();
  },
  buildExistingPagesPanel: function() {
    this.pagesPanel = this.createPanel('pages', 'Select an Existing Page', 'Existing Page', function(content) {
      this.pages.each(function(page) {
        var element = new Element("div", {className: 'page'}).update(page.name);
        element.observe("mouseover", element.addClassName.bind(element, 'hover'));
        element.observe("mouseout", element.removeClassName.bind(element, 'hover'));
        element.observe("click", this.selectPage.bind(this, page, element));
        content.insert(element);
      }.bind(this));
    }.bind(this));
  },
  buildNewPagePanel: function() {
    this.newPagePanel = this.createPanel('new_page', 'Create a New Page', 'New Page', function(content) {
      var urlGenerator = function() {
        var page_title = $('linker_page_title').value.toLowerCase().gsub(/\W+/, '_');
        var sectionObj = this.sections.detect(function(section) { return section.id == $('linker_page_section_id').value});
        var urlField = $('linker_page_url');
        urlField.value = (sectionObj ? sectionObj.url + "/" : "") + page_title;
      }
      var updateMembersOnly = function() {
        var section = this.sections.detect(function(section) { return section.id == $('linker_page_section_id').value });
        var checkbox = $('linker_page_members_only');
        checkbox.checked = checkbox.disabled = section && section.members_only;
      }
      
      var table = new Element('tbody');
      var tr = new Element('tr');
      tr.insert(new Element('td', {className: 'label'}).insert(new Element('label', {'for': 'linker_page_title'}).update('Title:')));
      tr.insert(new Element('td').insert(new Element('input', {id: 'linker_page_title', name: 'page[title]', size: 30, type: 'text'}).observe('blur', urlGenerator.bind(this)).observe('change', urlGenerator.bind(this))));
      table.insert(tr);
      tr = new Element('tr');
      tr.insert(new Element('td', {className: 'label'}).insert(new Element('label', {'for': 'linker_page_url'}).update('Url:')));
      tr.insert(new Element('td').insert(new Element('input', {id: 'linker_page_url', name: 'page[url]', size: 30, type: 'text'})));
      table.insert(tr);
      tr = new Element('tr');
      tr.insert(new Element('td', {className: 'label'}).insert(new Element('label', {'for': 'linker_page_section_id'}).update('Select Section:')));
      var select = new Element('select', {id: 'linker_page_section_id', name: 'page[section_id]'}).observe('change', urlGenerator.bind(this)).observe('change', updateMembersOnly.bind(this));
      select.insert(new Element('option', {value: ''}).update('New Section'));
      this.sections.each(function(section) { 
        var option = new Element('option', {value: section.id}).update(section.title)
        if (section.id == window.current_section)
          option.setAttribute('selected', 'selected');
        select.insert(option) 
      });
      tr.insert(new Element('td').insert(select));
      table.insert(tr);
      tr = new Element('tr');
      tr.insert(new Element('td', {className: 'label'}).insert(new Element('label', {'for': 'linker_page_committee_id'}).update('Select Committee:')));
      select = new Element('select', {id: 'linker_page_committee_id', name: 'page[committee_id]'});
      this.committees.each(function(committee) { select.insert(new Element('option', {value: committee.id}).update(committee.name));});
      tr.insert(new Element('td').insert(select));
      table.insert(tr);
      tr = new Element('tr');
      tr.insert(new Element('td'));
      tr.insert(new Element('td').insert(new Element('input', {id: 'linker_page_members_only', type: 'checkbox', name: 'page[members_only]', value: '1', style: 'width:auto'})).insert(new Element("input", {type: 'hidden', name: 'page[members_only]', value: '0'})).insert(new Element("label", {'for': 'linker_page_members_only'}).update("Members-Only")));
      table.insert(tr);
      tr = new Element('tr');
      tr.insert(new Element('td'));
      tr.insert(new Element('td').insert(new Element('input', {id: 'linker_page_show_navigation', type: 'checkbox', name: 'page[show_navigation]', value: '1', style: 'width:auto', checked: 'checked'})).insert(new Element('input', {type: 'hidden', name: 'page[show_navigation]', value: '0'})).insert(new Element('label', {'for': 'linker_page_show_navigation'}).update("Show Navigation")));
      table.insert(tr);
      content.insert(new Element('form').insert(new Element('input', {type: 'hidden', name: 'authenticity_token', value: window._token})).insert(new Element("table", {className: 'dialog_form_table', id: 'new_link_popup_table', style: 'height: auto'}).insert(table)));
    }.bind(this), function() {
      new Ajax.Request(Routes.pages(), {parameters: this.lastTab.panel.down('form').serialize(), method: 'post'});
      this.currentUrl = $('linker_page_url').value;
    });
  },
  buildExternalSitePanel: function() {
    this.externalSitePanel = this.createPanel('external_site', 'Link to an External Site', 'External Site', function(content) {
      var table = new Element('tbody');
      var tr = new Element('tr');
      tr.insert(new Element('td', {className: 'label'}).insert(new Element('label', {'for': 'external_page_url'}).update('Url:')));
      tr.insert(new Element('td').insert(new Element('input', {id: 'external_page_url', name: 'external_page_url', size: 30, type: 'text', value: 'http://'})));
      table.insert(tr);
      content.insert(new Element('form', {onsubmit: 'return false'}).insert(new Element("table", {className: 'dialog_form_table', id: 'new_link_popup_table', style: 'height: auto; padding: 10px'}).insert(table)));
    }, function() {
      var url = $('external_page_url').value
      this.currentUrl = url.include('http://') || url.include('https://') ? Routes.external(encodeURIComponent(url)) : url;
    });
  },
  buildEmailLinkPanel: function() {
    this.emailLinkPanel = this.createPanel('email_link', 'Link to an Email Address', 'Email', function(content) {
      var table = new Element('tbody');
      var tr = new Element('tr');
      tr.insert(new Element('td', {className: 'label'}).insert(new Element('label', {'for': 'email_address'}).update('Email:')));
      tr.insert(new Element('td').insert(new Element('input', {id: 'email_address', name: 'email_address', size: 30, type: 'text'})));
      table.insert(tr);
      content.insert(new Element('form', {onsubmit: 'return false'}).insert(new Element("table", {className: 'dialog_form_table', id: 'new_link_popup_table', style: 'height: auto; padding: 10px'}).insert(table)));
    }, function(element) {
      element.setAttribute('mail', $('email_address').value.replace('@', '__at__').replace('.', '__dot__'));
      this.currentUrl = 'javascript:void(0)';
    });
  },
  buildSharedResourcesPanel: function() {
    this.sharedResourcesPanel = this.createPanel('shared_resources', 'Link to a Shared Resource', 'Resource', function(content) {
      this.sharedResources.each(function(sharedResource) {
        var createSharedResource = function(index, sharedResource) {
          var element = new Element("div", {className: 'shared_resource', style: 'padding-left: ' + (10 * index + 2) + 'px'}).update(sharedResource.name);
          element.insert({top: new Element('img', {src: sharedResource.type == 'File' ? '/images/icon_file.png' : '/images/icon_directory.png'})})
          if (sharedResource.members_only)
            element.insert(new Element('img', {src: '/images/icon_lock.png', style: 'float: right'}));
          element.observe("mouseover", element.addClassName.bind(element, 'hover'));
          element.observe("mouseout", element.removeClassName.bind(element, 'hover'));
          if (sharedResource.type == 'File')
            element.observe("click", this.selectResource.bind(this, sharedResource, element));
          content.insert(element);
          if (sharedResource.children && sharedResource.children.length != 0)
            sharedResource.children.each(createSharedResource.curry(index + 1));
        }.bind(this);
        createSharedResource(0, sharedResource)
      }.bind(this));
    }.bind(this), function(element) {
    });
  },
  createPanel: function(id, title, tabName, content, submitAction) {
    var panel = new Element("div", {className: 'panel'}).hide();
    panel.insert(new Element("div", {className: 'title'}).update(title));
    var panelContent = new Element("div", {className: 'panel-content', id: id});
    content(panelContent);
    panel.insert(panelContent)
    panel.submitAction = submitAction || Prototype.emptyFunction;
    this.panels.insert(panel);
    this.createTab(panel, tabName);
    return panel;
  },
  createTab: function(panel, tabName) {
    var tab = new Element("div", {className: 'tab'}).update(tabName)
    tab.panel = panel
    tab.observe('click', this.selectTab.bind(this, tab));
    tab.observe('mouseover', tab.addClassName.bind(tab, 'hover'));
    tab.observe('mouseout', tab.removeClassName.bind(tab, 'hover'));
    this.tabs.insert(tab);
  },
  selectTab: function(tab) {
    if (this.lastTab != undefined) {
      this.lastTab.removeClassName('active');
      this.lastTab.panel.hide();
    }
    tab.addClassName('active');
    tab.panel.show();
    this.lastTab = tab;
  },
  selectPage: function(page, element) {
    if (this.selectedPage)
      this.selectedPage.removeClassName('selected');
    element.addClassName('selected');
    this.currentUrl = page.url;
    this.selectedPage = element;
  },
  selectResource: function(resource, element) {
    if (this.selectedResource)
      this.selectedResource.removeClassName('selected');
    element.addClassName('selected');
    this.currentUrl = Routes.sharedFile(resource.url);
    this.selectedResource = element;
  },
  createButtons: function() {
    var container = new Element("div", {className: 'dialog_buttons'});
    this.cancelButton = new Element('img', {src: '/images/cancel_button.png'});
    this.cancelButton.observe('click', this.cancel.bind(this));
    container.insert(this.cancelButton);
    this.okButton = new Element('img', {src: '/images/ok_button.png'});
    this.okButton.observe('click', this.ok.bind(this));
    container.insert(this.okButton);
    this.content.insert(container);
  },
  cancel: function() {
    if (this.range) {
      Selection().setRange(this.range);
      window.PageEditor.execCommand('unlink');
      if (this.inserted_fiat_placeholder) {
        if (this.inserted_fiat_placeholder.parentNode)
          this.inserted_fiat_placeholder.remove();
        else
          window.PageEditor.execCommand('delete');
        this.inserted_fiat_placeholder = null;
      }
      if (this.range.detach)
        this.range.detach();
      this.range = null;
    }
    this.element.close();
  },
  ok: function() {
    var link = $$('a[href*="fiat_placeholder"]').first();
    this.lastTab.panel.submitAction.bind(this)(link);
    if (!this.currentUrl || this.currentUrl == '')
      return this.cancel();
    link.href = this.currentUrl.slice(0, 1) == '/' || this.currentUrl.include('http://') || this.currentUrl.include('https://') || this.currentUrl.include('javascript:') ? this.currentUrl : '/' + this.currentUrl;
    this.element.close();
    if (this.range) {
      Selection().setRange(this.range);
      if (this.range.detach)
        this.range.detach();
      this.range = null;
    }
  }
})
