

Hint = Class.create();
Hint.prototype = {
  text: null,
  textField: null,
  applied: false,
  
  initialize: function(textField, hintText, setOnBlur) {
    this.textField = textField;
    this.text = hintText;
    this.textField.hint = this;
    
    Event.observe(this.textField, 'focus', this.unset.bindAsEventListener(this));
    if (setOnBlur == null || setOnBlur == "true") {
      Event.observe(this.textField, 'blur', this.set.bindAsEventListener(this));
    }
    
    Event.observe(window, 'unload', Hint.prototype.unset.bind(this));
    
    if (this.textField.form.onsubmitWithoutHint == undefined) {
      this.textField.form.onsubmitWithoutHint = this.textField.form.onsubmit;
      this.textField.form.onsubmit = function(event) {
        $(this).getInputs('text').each(function(field) {
          if (field.hint) { field.hint.unset(); }
        });
        return $(this).onsubmitWithoutHint();
      };
    }
    
    this.set();
  },
  
  set: function(event) {
    if (this.textField.value == '') {
      this.applied = true;
      Element.setStyle(this.textField, { color: '#888888' });
      this.textField.value = this.text;
    }
  },
  
  unset: function(event) {
    if (this.applied) {
      this.textField.value = '';
      Element.setStyle(this.textField, { color: 'black' });
      this.applied = false;
    }
  }
};

Element.addMethods({
  safelyReplace: function(element, content) {
    element = $(element);
    if (element != null) {
      Element.replace(element, content);
    }
    return element;
  }
});

Element.addMethods('input', {
  toggleValue: function(element) {
    element = $(element);
    if (element != null) {
      element.value = ($F(element) == "0" || $F(element) == "false") ? "1" : "0";
    }
  }
});

function attemptToCopy(linkElement, containerDomId, text) {
  var container = $(containerDomId);
  var linkElement = $(linkElement);
  
  if (linkElement && container) {
    $(containerDomId).value = text;
    container.show().focus();
    linkElement.siblings().each(function(e) { if (e.hasClassName('active')) { e.removeClassName('active').addClassName('muted'); } })
    linkElement.addClassName('active').removeClassName('muted');
  }
}

function makeFormDisableable(formId, initialDisabledState) {
    var form = $(formId);
    
    if (form.onsubmitWithoutDisabling == undefined) {
      form.onsubmitWithoutDisabling = form.onsubmit;

      form.onsubmit = function(event) {
        if ($(this).isSubmitDisabled) return false;
        $(this).disableSubmit();
        return $(this).onsubmitWithoutDisabling();
      }
      form.disableSubmit = function() { 
          var formId = $(this).id;
          $(this).isSubmitDisabled = true; 
          $(this).select('a').each(function(anchor) { 
              if (anchor.hasClassName(formId + '-button')) anchor.addClassName('buttony-disabled'); 
          })
      }
      form.enableSubmit = function() {
          var formId = $(this).id;
          $(this).isSubmitDisabled = false;
          $(this).select('a').each(function(anchor) {
              if (anchor.hasClassName(formId + '-button')) anchor.removeClassName('buttony-disabled');
          })
      }
    }

    if (initialDisabledState) form.disableSubmit();
}

function clearForm(formId) {
  var form = $(formId);
  if (form) {
    form.getElements().each(
      function(field) {
        if (field.name != 'authenticity_token') { field.clear(); } // don't remove the CSRF token!
      }
    );
    form.select('input[type="checkbox"]', 'input[type="radio"]').each(
      function(field) {
        field.checked = false;
      }
    );
    form.findFirstElement().focus();
    form.enableSubmit();
  }
}

function updateAllCheckboxes(element, check) {
  element.select('input[type="checkbox"]').each(
    function(checkbox) {
  	  checkbox.checked = check;
    }
  );
}

function uncheckSpecificCheckbox(box) {
  if (box) { // when selecting which collaborator, we use this function to uncheck the share with public, which can not be there if the vault doesn't share publicly
    box.checked = false;
  }
}

function uncheckAllButSpecificCheckbox(box) {
  var checked = box.checked;
  updateAllCheckboxes(box.form, false);
  box.checked = checked;
}

function showIfChecked(checkbox, element) {
  var element = $(element);
  if (element && checkbox) {
    if (checkbox.checked) {
      $(element).show();
    } else {
      $(element).hide();
    }
  }
}

function toggleCollapsible(blockId, focusInputId) {
  var block = $(blockId);
  if (!block.hasClassName('disabled')) {
    block.toggleClassName('collapsible-open').toggleClassName('collapsible-closed');
    if (focusInputId != null && block.hasClassName('collapsible-open')) $(focusInputId).focus();
  }
}

function showEditPanel(domIdBase, formId) {
  $(domIdBase + '-show').hide(); 
  $(domIdBase + '-edit').show(); 
  if ($(formId) && $(formId).findFirstElement()) $(formId).focusFirstElement();
}

function hideEditPanel(domIdBase) {
  $(domIdBase + '-edit').hide();
  $(domIdBase + '-show').show();
}

function setDetailsVisibility(domIdBase, recordId, visibility) {
  if(visibility == 'show') {
    $(domIdBase + '-' + recordId + '-showDetails').hide();
    $(domIdBase + '-' + recordId + '-hideDetails').show();
    $(domIdBase + '-' + recordId + '-details').show();
  }
  else {
    $(domIdBase + '-' + recordId + '-showDetails').show();
    $(domIdBase + '-' + recordId + '-hideDetails').hide();
    $(domIdBase + '-' + recordId + '-details').hide();
  }
}

function showAllDetails(domClassBase) {
  $$('.' + domClassBase + '-showDetails').each(
    function(element) {
      element.hide();
    }
  );
  $$('.' + domClassBase + '-hideDetails', '.' + domClassBase + '-details').each(
    function(element) {
      element.show();
    }
  );
}

function reflowAlternatingRowClasses(parentElementId) {
  var parentElement = $(parentElementId);
  if (parentElement) {
    var rowElements = parentElement.select('tr').toArray();
    for (var i = 0; i < rowElements.length; i++) {
      rowElements[i].removeClassName('alt');
      if (i%2 == 1) rowElements[i].addClassName('alt');
    }
  }
}

function insertGlobalMessage(message) {
  if (!$('globalMessages')) {
    var enclosing = new Element('div', { id: 'globalMessages' });
    new Insertion.Top($('content-inner'), enclosing);
  }
  
  var parsedMessage = new Element('div').update(message).down();
  if ($(parsedMessage.readAttribute('id'))) {
    $(parsedMessage.readAttribute('id')).replace(message);
  } else {
    new Insertion.Top($('globalMessages'), message);
  }
}

function removeGlobalMessage(domId) {
  if ($('globalMessages')) {
    if ($(domId)) { Element.remove(domId) }
    if ($$('#globalMessages .globalMessage').length == 0) {
      Element.remove('globalMessages');
    }
  }
}

function downloadExportClicked() {
    Effect.Fade('export_progress_message');
    reenableSearchPage();
    return true;
}

function reenableSearchPage() {
  if ($('export_options_link') && $('disabled_export_options_link')) {
    Element.show('export_options_link');
    Element.hide('disabled_export_options_link');
  }
  if ($('mine_search_form')) $('mine_search_form').enableSubmit();
  if ($('export_options_form')) $('export_options_form').enableSubmit();
}

function removeAssociatedModel(link) {
  $(link).up('.associated-model').hide();
  var hiddenFields = $(link).up('.associated-model').select('input[type=hidden]');
  hiddenFields.detect(function(element) { return element.name.indexOf("[_destroy]") >= 0; }).value = '1';
}

function addAssociatedModel(link, template) {
  var newId = new Date().getTime();
  var templateWithNewId = template.replace(/NEW_RECORD/g, newId);
  $(link).up('.associated-model').insert({before: templateWithNewId});
}

function updateTitleAndPageHeader(name, nameForTitle) {
  if (typeof nameForTitle == 'undefined') nameForTitle = name;
  
  document.title = nameForTitle + ' - Collaborative Drug Discovery';
  $('pageHeader').down('h1 .title').update(name);
}

function openMiniApp(url, windowName) {
  miniApp = window.open(url, windowName, "resizable=1,width=800,height=600");
	miniApp.focus();
}

function getRadioButtonGroupValue(formID, radioGroup) {
  var checked = $(formID).getInputs('radio', radioGroup).find(function(input) { return input.checked; });
  return (checked) ? $F(checked) : null;
}

function normalizeUrl(url) {
  if (url == null || url.trim().length == 0) {
    return normalizePath(url);
  }
  
  // remove query string, then split the first part
  var parts = url.split("?").first().split("/");
  
  if (["http:", "https:"].include(parts.first())) {
    return normalizePath("/" + parts.slice(3).join("/"));
  } else {
    return normalizePath(url); // maybe already a path
  }
}

function normalizePath(path) {
  if (path == null) {
    return null;
  }
  
  var parts = path.split("/");
  
  if (parts.all(function(part) { return part.blank(); })) {
    return "/";
  } else if (parts.last().blank()) {
    parts.pop(); // remove trailing slash
  }
  
  return parts.map(
    function(element) {
      // !isNaN is a nice substitute for writing our own isNumber
      return (element.strip().length == 0 || isNaN(element)) ? element : "N";
    }
  ).join("/");
}

Pollers = {
  active: {},
  
  start: function(name, callback, frequency) {
    this.stop(name);
    this.active[name] = new PeriodicalExecuter(callback, frequency);
  },

  stop: function(name) {
    if (this.active[name]) {
      this.active[name].stop();
      delete this.active[name];
    }
  }
};
