// Add a css selector for javascript dependent initial states.
document.documentElement.className += " hasJS";

function submitStage(stage) {
        if (document.forms[0] && document.forms[0].elements['stage']) {
                document.forms[0].elements['stage'].value = stage;
                document.forms[0].submit();
                return false;
        } else {
                return true;
        }
}

function setupSearchBox(form_name, search_field_name, empty_value, submit_button) {
  showInputHelperMessage(form_name, search_field_name, empty_value, '', false);
  Event.observe(submit_button, 'click', function() {
    resetHelperMessage(form_name, search_field_name, empty_value, '');
    submitForm(form_name);
  });
}

function showInputHelperMessage(form_name, field_name, message, empty_value, reset_on_submit) {
  Event.observe(field_name, 'blur', function() {
    if (this.value == empty_value) {
                        Element.addClassName(field_name, 'empty');
      this.value = message;
    }
  });
  Event.observe(field_name, 'focus', function() {
    if (this.value == message) {
      this.value = '';
                        Element.removeClassName(field_name, 'empty');
    }
  }, true);
  if (reset_on_submit) {
    $(form_name).onsubmit = function(event) {
      resetHelperMessage(form_name, field_name, message, empty_value);
    }
  }
  if ($(field_name).value == empty_value || $(field_name).value == '' || $(field_name).value == message) {
                Element.addClassName(field_name, 'empty');
    $(field_name).value = message;
  } else {
                Element.removeClassName(field_name, 'empty');
  }
}

function resetHelperMessage(form_name, field_name, message, empty_value) {
  if ($(field_name).value == message || $(field_name).value == '') {
    $(field_name).value = empty_value;
  }
}

function showEditPopup(field_name) {
  Element.hide('field_value_' + field_name);
  Element.show('edit_popup_' + field_name);
}

function hideEditPopup(field_name) {
  Element.hide('edit_popup_' + field_name);
  Element.show('field_value_' + field_name);
}

function saveEdit(field_name) {
  Element.hide('edit_popup_' + field_name);
  Element.show('field_value_' + field_name);
  var value = Form.Element.getValue('edit_field_' + field_name);
  updateFlashValue(field_name, value);
}

function cancelEdit(field_name) {
  Element.hide('edit_popup_' + field_name);
  Element.show('field_value_' + field_name);
}

function showEditPopupWithMessage(field_name, message) {
  showEditPopup(field_name);
  showInputHelperMessage('edit_form_' + field_name, 'edit_field_' + field_name, message, $('edit_field_' + field_name).value, false);
}

function resetEditPopupMessage(field_name, message, empty_value) {
  resetHelperMessage('edit_form_' + field_name, 'edit_field_' + field_name, message, empty_value);
}

function updateFlashValue(field_name, value) {
  switch(field_name) {
    case 'title': flashProxy.call('jsUpdateTitle', value);
  }

}

function resetFlash() {
        flashProxy.call('jsReset');
}

function resizeFlash(width, height) {
        window.location = window.location;
}

var currentFlashHeight;
var currentFlashObject = 'flashgenerator';

function hideFlash() {
  if (currentFlashObject != null && $(currentFlashObject) != null) {
    currentFlashHeight = $(currentFlashObject).style.height;
    $(currentFlashObject).style.height = "0px";
        $(currentFlashObject).style.visibility = 'hidden';
  }
}

function showFlash() {
  if (currentFlashObject != null && $(currentFlashObject) != null) {
        $(currentFlashObject).style.visibility = 'visible'
        $(currentFlashObject).style.height = currentFlashHeight;
        }
}

function getValueIfVisible(container_element, element_name, default_value) {
  if ($(container_element)) {
    if (Element.visible(container_element)) {
      return Form.Element.getValue(element_name);
    }
  }
  return default_value;
}

var addObjectFunction = function(record_id, element) {};
var removeObjectFunction = function(record_id, asset_uuid, element) {};
var selectedRecords = [];

function enableInlinePreviewSelectors(record_id) {
  if (selectedRecords.include(record_id)) {
    $$('.preview_select_button').each(function(el) { Element.hide(el); });
  } else {
                $$('.preview_select_button').each(function(el) { Element.show(el); });
        }
}

function activateFindForAssignment() {
        addObjectFunction = function(record_id, element) { addBundle(record_id, element) };
}

function addBundle(record_id, indicator_element) {
        showActivityIndicator(indicator_element, "Loading...");
        new Ajax.Updater({success:'assignment_bundle',failure:'error_blind'}, add_bundle_url,
                                                                         {method: 'get', asynchronous: true, evalScripts: true,
                                                                                parameters: ("record_id=" + record_id),
                                                                                onComplete: function() {
                                                                                        hideActivityIndicator(indicator_element);
                                                                                        closeLightbox('find_content_lightbox');
                                                                                }})
}

function activateFindForAttachment() {
        addObjectFunction = function(record_id, element) { addForAttachment(record_id, element) };
}

function addForAttachment(record_id, indicator_element) {
showActivityIndicator(indicator_element, "Loading...");
  new Ajax.Updater({success: 'attached_content', failure: 'error_blind'}, attach_record_url,
                   {method: 'get', asynchronous: true, evalScripts: true,
                    parameters: ("record_id=" + record_id),
                    onComplete: function() {
                      hideActivityIndicator(indicator_element);
                      closeLightbox('find_content_lightbox');
                    }})
}

function selectSearchSection(section) {
  $('section').value = section;
  submitForm('search_form');
}

function selectSortOrder(sort_order, direction) {
  $('order_field').value = sort_order;
  $('order_direction_field').value = direction;
  submitForm('search_form');
}

function submitForm(id) {
  form = $(id);
  if (form.onsubmit) {
    form.onsubmit();
  } else {
    form.submit();
  }
}


function updateTaxonomyRangeDisplay() {
        var id = 'taxonomy_list';
        var el = $(id);

        var select = $('prop_property_range');
        var value = select.options[select.selectedIndex].value;

        if(value != 'TaxonomyRange') {
                Element.hide(id);
        } else {
                Element.show(id);
        }
}
function setDefaultLicenceTypeIfNeeded(category) {
    if(category == 'own'){
        if(!$('own_licence_type_reuse_magicstudio').checked
           && !($('own_licence_type_fallback') != null && $('own_licence_type_fallback').checked)
           && !$('own_licence_type_no_reuse').checked
           && !$('own_licence_type_reuse_cc').checked )
            $('own_licence_type_reuse_magicstudio').checked = true;
    } else if(category == 'other'){
        if(!$('other_licence_type_reuse_magicstudio').checked
           && !$('other_licence_type_reuse_cc').checked )
            $('other_licence_type_reuse_magicstudio').checked = true;
    }
}

function showLicenceOption(option) {
    licence_types = ['own', 'other', 'no_copyright_restrictions', 'public_domain']
    licence_types.each(function (o) {
      element_id = "licence_" + o + "_fields";
      if ($(element_id) != null) {
        if (option == o) {
          Element.show("licence_" + o + "_fields");
        } else {
          Element.hide("licence_" + o + "_fields");
        }
      }
  });
}

/*window.onresize = function() {
  repositionAllActivityIndicators();
}

function repositionAllActivityIndicators() {
  $$('.balloon').each(function (el) {
    if (el.id != 'activity_indicator') {
      indicator_id = el.id;
    }
  })
}*/

function showActivityIndicator(element_id, title) {
  if (title == null) {
    title = 'Loading...';
  }
  indicator_id = 'activity_indicator_' + element_id;
  if ($(indicator_id)) {
  } else {
    new_indicator_el = $('activity_indicator').cloneNode(true);
    new_indicator_el.id = indicator_id;
    document.body.appendChild(new_indicator_el);
    positionActivityIndicator(element_id);
    Element.show(indicator_id);
  }

}

function positionActivityIndicator(element_id) {
  indicator_id = 'activity_indicator_' + element_id;
  var pos = position($(element_id));
  var width = $(element_id).offsetWidth;
  x = pos[0];
  y = pos[1];
  moveElement(indicator_id, x + width - 10, y - 30);
}

function hideActivityIndicator(element_id) {
  indicator_id = 'activity_indicator_' + element_id;
  if ($(indicator_id)) {
    Element.remove(indicator_id);
  }
}

function position(element) {
  var curleft = curtop = 0;
  if (element.offsetParent) {
    curleft = element.offsetLeft;
    curtop = element.offsetTop;
    while (element = element.offsetParent) {
      curleft += element.offsetLeft;
      curtop += element.offsetTop;
    }
  }
  return [curleft, curtop];
}

function moveElement(el, x, y) {
  el = $(el);
  el.style.left = x + "px";
  el.style.top = y + "px";
}

function getScrolledY() {
  if (document.body.scrollTop) {
    return document.body.scrollTop;
  } else {
    return window.pageYOffset;
  }
}

function toggleAdvancedSearchOptions(auto_submit, move_button) {
  if (!Element.visible('advanced')) {
                if ($('advanced_summary') != null) {
                        Element.hide('advanced_summary');
                        Element.show('advanced');
                } else {
            Element.removeClassName('advanced_toggle_link', 'contracted');
            Effect.BlindDown('advanced', {duration:0.4});
                }
                if (move_button) {
                        Element.hide('submit_search');
                }
  } else {
    if (auto_submit) {
      showActivityIndicator('search_form');
    }
                if ($('advanced_summary') == null) {
            Element.addClassName('advanced_toggle_link', 'contracted');
                }
                resetAdvancedFilters();
    if (auto_submit) {
      submitForm('search_form');
    } else {
                        if ($('advanced_summary') == null) {
              Effect.BlindUp('advanced', {duration:0.4, afterFinish: function() {
                                        if (move_button) {
                                                Element.show('submit_search');
                                        }
                                }});
                        } else {
                                Element.hide('advanced');
                                Element.show('advanced_summary');
                                if (move_button) {
                                        Element.show('submit_search');
                                }
                        }
    }
  }
}

function resetAdvancedFilters() {
        $$('.advanced_select').each(function(el) {
    chooseSelectOption(el, '');
  });
}

function toggleBundleChoice() {
  if (Form.Element.getValue('new')) {
                if (!Element.visible('new_bundle')) {
      Element.show('new_bundle');
    }
  } else {
    if (Element.visible('new_bundle')) {
      Element.hide('new_bundle');
    }
  }
}

function toggleAssignmentFields(effects) {
  toggleFields('assignment_true', 'assignment_fields', effects);
}

function toggleFields(form_element_id, field_container_id, effects) {
  toggleElement(Form.Element.getValue(form_element_id), field_container_id, effects);
}

function toggleElement(visible, element_id, effects) {
  if (visible && !Element.visible(element_id)) {
    if (effects) {
      new Effect.BlindDown(element_id, {duration: 0.2});
    } else {
      Element.show(element_id);
    }
  } else if (!visible && Element.visible(element_id)) {
    if (effects) {
      new Effect.BlindUp(element_id, {duration: 0.2});
    } else {
      Element.hide(element_id)
    }
  }
}

function toggleMakePublicFields(show, effects) {
  toggleElement(show, 'public_fields', effects);
  if ($('licence_fields')) {
    toggleElement(show, 'licence_fields', effects);
  }
}

function toggleMetadataFields() {
  if (Form.Element.getValue('enable_metadata_edit')) {
    Element.show('metadata_fields');
  } else {
    Element.hide('metadata_fields');
  }
}

function showErrorBlind() {
  $$('select').each(function (el) {
    Element.hide(el);
  });
  Element.show('error_blind_holder');
  Element.addClassName('error_blind_holder', 'disable_cover');
  new Effect.Appear('error_blind', {duration: 0.3});
}

function hideErrorBlind() {
  $$('select').each(function (el) {
    Element.show(el);
  });
  new Effect.Fade('error_blind', {duration: 0.3, afterFinish: function() {
    Element.removeClassName('error_blind_holder', 'disable_cover');
    Element.update('error_blind', '');
    Element.hide('error_blind_holder');
  }});
}

var currentTaxonTags = [];
function selectTaxonTag(taxonomy_id, tag_id, url, select_id, first) {
  if (tag_id != 0 && !currentTaxonTags.include(tag_id)) {
    showActivityIndicator(select_id);
    new Ajax.Updater('current_taxonomy_tags_' + taxonomy_id, url,
                    { method: 'get', asynchronous: true, evalScripts: true, insertion: Insertion.Bottom,
                      parameters: ("taxon_id=" + tag_id + "&first=" + first),
                      onComplete: function() {
                                                                                                currentTaxonTags.push(tag_id);
                        hideActivityIndicator(select_id);
                        new Effect.Highlight('current_tags');
                      }
                    });
  }
}

function parseXML(xml_string) {
  if (window.ActiveXObject) {
    var doc=new ActiveXObject("Microsoft.XMLDOM");
    doc.async="false";
    doc.loadXML(xml_string);
    return doc;
  } else {
    var parser = new DOMParser();
    return parser.parseFromString(xml_string, "text/xml");
  }
}

function chooseFilteredSelectOption(select_el, filter_regexp) {
  options = $A(select_el.options);
  regexp_flags = "i"; // ignore case
  re = new RegExp('^' + filter_regexp, regexp_flags);
  selected_index = -1;
  for(i=0;i<options.length;i++){
    opt = options[i];
    if (re.test(opt.text) ) { selected_index = i; break;};
  };
  if (selected_index != -1) {
    select_el.selectedIndex = selected_index;
  }
}

function chooseSelectOption(select_id, option_value) {
  select = $(select_id);
  options = $A(select.options);
  selected_index = -1;
  options.each(function(opt, i) {
    if (opt.value == option_value) { selected_index = i };
  });
  if (selected_index != -1) {
    select.selectedIndex = selected_index;
  }
}

function isIE(version) {
  var arVersion = navigator.appVersion.split("MSIE");
  var bVersion = parseFloat(arVersion[1]);
        if (version != null) {
          return bVersion == version;
        } else {
                return bVersion > 0;
        }
}

function setActive(element, enabled) {
  element = $(element);
        if (element) {
          if (enabled) {
            if (element.hasClassName('inactive')) {
              element.removeClassName('inactive');
            }
          } else {
            if (!element.hasClassName('inactive')) {
              element.addClassName('inactive');
            }
          }
        }
}

// Table cell select for embedded find
function selectObjectToggle(checkbox_id) {
        checkbox = $(checkbox_id);
        checkbox.checked = !checkbox.checked;
}
function initLoneClick() {
        $$('.lone_click_object').each(function(el) {
                Event.observe(el, 'click', function(event) {
                        event.stopPropagation();
          }, true);
        });
}

function expandElement(element_id) {
        collapsed = $$('#' + element_id + ' .collapsed')[0];
        expanded = $$('#' + element_id + ' .expanded')[0];
        expanded.show();
        collapsed.hide();
}

var carouselResourceSizes = null;
var carouselPosition = 0;

function scrollCarousel(count, disableButtons) {
        newPosition = carouselPosition + count;
        if (newPosition <= 0) {
                newPosition = 0;
                if (disableButtons) {
                        Element.hide('previous_resource_link');
                }
        } else if (newPosition >= carouselSize - 1 ) {
                newPosition = carouselSize - 1;
                if (disableButtons) {
                        Element.hide('next_resource_link');
                }
        }
        if (newPosition < carouselSize - 1) {
                if (disableButtons) {
                        Element.show('next_resource_link');
                }
        }
        if (newPosition > 0) {
                if (disableButtons) {
                        Element.show('previous_resource_link');
                }
        }

        offset = count * -202;
        // alert("count=" + count + ", old=" + carouselPosition + ", new=" + newPosition);
        if (carouselResourceSizes != null) {
                offset = 0
                if (count < 0) {
                        for (i = newPosition; i < carouselPosition; i++) {
                                offset += carouselResourceSizes[i];
                        }
                } else {
                        for (i = carouselPosition; i < newPosition; i++) {
                                offset -= carouselResourceSizes[i];
                        }
                }
        }
        // alert("offset=" + offset);
        carouselPosition = newPosition;
        new Effect.Move('carousel_scroller', {x:offset, y: 0, mode: 'relative', duration: 0.2, queue:'end'});
}

Array.prototype.remove=function(s){
  for(i=0;i<this .length;i++){
    if(s==this[i]) this.splice(i, 1);
  }
}

function switchElement(element_id, visible) {
        el = $(element_id)
        if (visible && !el.visible()) {
                Effect.Appear(el, {duration: 0.2});
        } else if (!visible && el.visible()) {
                Effect.Fade(el, {duration:0.2});
        }
}

var visibleHelpSection = null;
var visibleHelpQuestion = null;
function showHelpSection(id) {
  id = "section_" + id;
  if (visibleHelpSection != null && visibleHelpSection != id) {
    Element.hide(visibleHelpSection);
  }
  Element.show(id);
  visibleHelpSection = id;
}

function showHelpQuestion(section_id, question_id) {
  question_id = "question_" + section_id + "_" + question_id;
  showHelpSection(section_id);
  if (visibleHelpQuestion != null && visibleHelpQuestion != question_id) {
    Element.hide(visibleHelpQuestion);
  }
  Element.show(question_id);
  visibleHelpQuestion = question_id;
        Element.scrollTo(question_id);
}

function showCurrentHelpQuestion() {
        current_question = window.location.hash;
        if (current_question != null && current_question != "") {
                qs = current_question.split('_');
                showHelpQuestion(qs[1], qs[2]);
        }
}

var actionMenuActive = false;
function showObjectActions(container_element) {
        if (!actionMenuActive && !container_element.hasClassName('active')) {
                container_element.addClassName('active');
                container_element.select('.object_actions').each(function(actions_el) {
                  Element.show(actions_el);
                });
        }
}

function hideObjectActions(container_element) {
        if (!actionMenuActive &&(container_element.hasClassName('active') || container_element.hasClassName('menu_active'))) {
                container_element.removeClassName('active');
                container_element.removeClassName('menu_active');
                if (!container_element.hasClassName('menu_visible')) {
                        container_element.select('.object_actions').each(function(actions_el) {
                          Element.hide(actions_el);
                        });
                }
        }
}

function toggleMenu(button_id, url, menu_id, container_id) {
   
        if (active_menu_id != null) {
                if (active_menu_id == menu_id) {
                        // menu is already active; close it
                        closeMenu(true);
                        return;
                } else {
                        // another menu is active; close it and open this one
                        closeMenu(false);
                }
        }
        new Ajax.Updater('popup_menu_container', url,
                                                                         {asynchronous:true, evalScripts:true,
                                                                                onComplete:function(request){
                                                                                        hideActivityIndicator(button_id);
                                                                                        showMenu(menu_id, button_id, $(container_id).hasClassName('tile'));
                                                                                },
                                                                                onLoading:function(request) {
                                                                                        $(container_id).addClassName('menu_active');
                                                                                        actionMenuActive = true;
                                                                                        showActivityIndicator(button_id);
                                                                                }
                                                                         });
}

function toggleSelectVisibility(visible) {
        selects = document.getElementsByTagName('select');
        for(i = 0; i < selects.length; i++) {
                if (visible) {
                        Element.show(selects[i]);
                } else {
                        Element.hide(selects[i]);
                }
        }
}

function showCheckedResourcesButton() {
        Element.show('checked_resources_menu_button');
        Element.show('clear_checked_records_button');
        Effect.Pulsate('actions_label', {duration: 0.6, pulses: 2});
}

function createCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days*24*60*60*1000));
                var expires = "; expires="+ date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
}

function eraseCookie(name) {
        createCookie(name,"",-1);
}
