var calendar = null;
var bookmark = null;

function flip(hide, show, highlighted_tab) {
  $(hide).hide(); $(show).show();
  $$(".wizard_tabs li").each(function(el) { el.removeClassName('selected'); });
  $(highlighted_tab).addClassName('selected');
}

function initEditor(content_type) {
  tinyMCE.idCounter = 0;
  tinyMCE.execCommand('mceAddControl', true, content_type + "[body]");
};

function killEditor(content_type) {
  tinyMCE.triggerSave(true,true);
  tinyMCE.execCommand( 'mceRemoveControl', true, content_type + "[body]" );
};

function saveTinyMce(id) {
  var ed = tinyMCE.get(id);
  $(id).value = ed.getContent();
};

function charLimit(field, maxLength) {
  var inputLength = field.value.length;
  if(inputLength >= maxLength) field.value = field.value.substring(0, maxLength);
};

function charCounter(field,maxLength,countTarget) {
  var inputLength = field.value.length;
  if(inputLength >= maxLength) {
    field.value = field.value.substring(0,maxLength); 
  };

  countTarget.innerHTML=maxLength-field.value.length;
};

function updateCharacterCount(field) {
  charCounter($(field),200,$('characters_left'));
}

var configDateType = 'us';

function toggleStateAndProvince(address_name) {
  if ($(address_name + '_country').value == 'United States') {
    if (address_name == 'billing_address') {
      if($("shipping_same_as_billing").checked == false) {
        $(address_name+'_state').enable();
      }
    } else {
      $(address_name+'_state').enable();
    };
    
    $(address_name+'_state_container').show();
    $(address_name+'_province').hide();
    $(address_name+'_state_province').disable();
  } else {
    $(address_name+'_state_container').hide();
    
    if (address_name == 'billing_address') {
      if($("shipping_same_as_billing").checked == false) {
        $(address_name+'_state_province').enable();
      }
    } else {
      $(address_name+'_state_province').enable();
    }

    $(address_name+'_province').show();
    $(address_name+'_state').disable();
  }
};

function stateOrProvince(element_id, replacement_html){
  el = $(element_id);
  el.innerHTML = replacement_html;
};

function chooseLayout(layout_id) {
  $$('.theme_layout_preview').each(function(e) {e.removeClassName('current');});
  $(layout_id).addClassName('current');
};

function revealChildTableRows(spanId, rowId) {
  if ($(spanId).hasClassName('expanded')) {
    $(spanId).removeClassName('expanded');
    $(spanId).addClassName('collapsed');
    $(rowId).toggle();
  } else {
    $(spanId).removeClassName('collapsed');
    $(spanId).addClassName('expanded');
    $(rowId).toggle();
  }
};

function toggleArticleSharedCheckBox(){
  if ($F('article_group_id') == '') {  // Removing from article series
    $('shared_checkbox').show();
    $('no_sharing').hide();
    $('article_is_shared').checked = false;
    $('article_series_permissions').hide();
    $('permissions_checkbox').show();
    toggleSharedCheckBoxAccordingToPermissions('article_is_shared');
  } else {  // Setting to article series
    $('shared_checkbox').hide();
    $('no_sharing').show();
    $('permissions_checkbox').hide();
    $('article_series_permissions').show();
    $('no_sharing_permissions').hide();
  }
};

function toggleSharedCheckBoxAccordingToPermissions(shared_checkbox_id, role_everyone_id) {
  role_everyone_id = typeof(role_everyone_id) != 'undefined' ? role_everyone_id : 'role_everyone_assigned_role_ids';
  if($(role_everyone_id).checked == false) {
    $('shared_checkbox').hide();
    $('article_is_shared_1').checked = false;
    $('article_is_shared_0').checked = true;
    $('no_sharing_permissions').show();
  } else {
    $('no_sharing_permissions').hide();
    $('shared_checkbox').show();
  }
};

function AllowOrDisableEveryoneRole(role_everyone_id) {
  if($(role_everyone_id).checked) {
    $(role_everyone_id).value = "everyone";
  } else {
    $(role_everyone_id).value = "";
  }
}

var ThemeList = {
  search: function() {
    $$("tr.adventist_forge_theme").each( function(t) {
      if (t.getElementsBySelector('h3')[0].innerHTML.toLowerCase().include($F('search').toLowerCase()) || 
        t.getElementsBySelector('p')[0].innerHTML.toLowerCase().include($F('search').toLowerCase())) {
        t.show();
      } else {
        t.hide();
      }
    });
  },
  
  showAll: function() {
    $$("tr.adventist_forge_theme").each( function(t) { t.show(); });
  }
};

// This needs to be here for everything

// Correct tiny mce relative url upload issue
document.observe('dom:loaded',function() {
  $$('img').each( function(img) {
    if(img.src.startsWith('user_uploads') || img.src.startsWith('images')) {
      return img.src = '/' + match[0];
    }
  });
});

function checkExistingMemberships(user_id, message, auth_token){
  var site_name = $('site_name').value;
  if ($$('.site td:first-child').any(function(e) { return e.innerHTML.strip() == site_name; })) {
    $('error_message').innerHTML = message;
    $('error_message').show();
  } else if(user_id == 'newuser') {
    new Ajax.Request('/console/users/add_site', {method: 'post', parameters:{ name: site_name, user_id: user_id, 'authenticity_token': auth_token }});
  } else {
    new Ajax.Request('/console/users/add_site', {method: 'post', parameters:{ name: site_name, user_id: user_id, 'authenticity_token': auth_token }});
  }
}

function removeHiddenFieldFor(site) {
  var id = site.split('_')[1];
  var elem = $$('input[value='+id+']');
  elem.each(function(e) { e.remove(); });
}

function popUpBoxer(content, content_type) {
  if (!$('boxer_overlay')){
    boxer = new Boxer();
    boxer.addContent(content);
    initEditor(content_type);
  }
}

function createCalendar(input, options) {
  Event.observe(input, 'click', function(e) {
    var source = Event.element(e);

    if(!calendar) {
      calendar = new scal('calendar-container', input, options);
    } else {
      calendar.updateelement = $(input);
    }

    var date = new Date($F(input).gsub('-', '/'));
    calendar.setCurrentDate(isNaN(date) ? new Date() : date);

    if (source = $(source)) {
      Position.clone($(source), 'calendar-container', {setWidth: false, setHeight: false, offsetLeft: source.getWidth() + 2});
    }

    calendar.openCalendar();
    calendar.cells.invoke("observe", "click", function(cell){ this.toggleCalendar(); }.bind(calendar));
  });
}

function addNoWarnToTinyMCE(){ 
  $$('table.mceLayout a').each(function(e){ e.writeAttribute({rel: 'nowarn'}); });
}

function customexecCommand(editor_id, elm, command, user_interface, value){

  switch(command){
    case "HiliteColorMenu":
      TinyMCE_AdvancedTheme._hideMenus(editor_id);

      // Create color layer
      var ml = new TinyMCE_Layer(editor_id + '_bcMenu');

      if (!ml.exists())
        ml.create('div', 'mceMenu', document.body, TinyMCE_AdvancedTheme._getColorHTML(editor_id, 'theme_advanced_background_colors', 'HiliteColor'));

      tinyMCE.switchClass(editor_id + '_backcolor', 'mceMenuButtonFocus');
      ml.moveRelativeTo(document.getElementById(editor_id + "_backcolor"), 'bl');

      ml.moveBy(tinyMCE.isMSIE && !tinyMCE.isOpera ? -1 : 1, -1);

      if (tinyMCE.isOpera)
        ml.moveBy(0, -2);

      ml.show();
      addNoWarnToTinyMCE();
    return true;
    
    case "forecolorMenu":
      TinyMCE_AdvancedTheme._hideMenus(editor_id);

      // Create color layer
      var ml = new TinyMCE_Layer(editor_id + '_fcMenu');

      if (!ml.exists())
        ml.create('div', 'mceMenu', document.body, TinyMCE_AdvancedTheme._getColorHTML(editor_id, 'theme_advanced_text_colors', 'forecolor'));

      tinyMCE.switchClass(editor_id + '_forecolor', 'mceMenuButtonFocus');
      ml.moveRelativeTo(document.getElementById(editor_id + "_forecolor"), 'bl');

      ml.moveBy(tinyMCE.isMSIE && !tinyMCE.isOpera ? -1 : 1, -1);

      if (tinyMCE.isOpera)
        ml.moveBy(0, -2);

      ml.show();
      addNoWarnToTinyMCE();
    return true;
  }
  return false; //Pass to next handler in chain
}

// This is a work around for a IE7 specific error for sortables.  This should override prototype's
// default cumulativeOffset method.
Element.addMethods({
  cumulativeOffset: function(element) {
  var valueT = 0, valueL = 0;
  do {
    valueT += element.offsetTop  || 0;
    valueL += element.offsetLeft || 0;
    
    if ( element.parentNode == undefined ) {
      element = null;
    } else {
      element = element.offsetParent;
    }
  } while (element);
  return Element._returnOffset(valueL, valueT);
}
});

// ======================
// = EXPERO REDESIGN JS =
// ======================
function ajaxUpdater(class_name, method) {
  if(method == null) { method = 'get'; };
  $$("." + class_name).each(function(el) {
    el.stopObserving('click');
    el.observe('click', function(ev) {
      rowId = this.up().up().id;
      indexRowSelector(rowId);
      ev.stop();
      new Ajax.Request(el, { method: method });
    });
  });
}

function userStatusObservers(){
  statusObserver('membership', 'approve_membership_button', 'active');
  statusObserver('membership', 'pending_membership_button', 'pending');
  statusObserver('membership', 'disable_membership_button', 'disabled');  
}

function statusObservers(content_type){
  statusObserver(content_type, 'archive_content_button', 'archived');
  statusObserver(content_type, 'draft_content_button', 'draft');
  statusObserver(content_type, 'approve_content_button', 'approved'); 
  statusObserver(content_type, 'publish_content_button', 'published'); 
}

function statusObserver(content_type, class_name, status){
  $$('.'+ class_name).each(function(el){
    el.observe('click', function(ev){
      ev.stop();
   
      if($(content_type + '_body') != undefined) { 
        tinyMCE.triggerSave(); 
      }

      var stat = $(content_type +'_status');
      if(stat != undefined) { stat.value = status; }
      var form = $(content_type + '_edit_form');
      new Ajax.Request(form.action, {
        parameters: form.serialize()
      });
    });
  });
}
function statusObserverNoAjax(content_type, class_name, status) {
  $$('.'+ class_name).each(function(el){
    el.observe('click', function(ev){
      if($(content_type + '_body') != undefined) { 
        tinyMCE.triggerSave(); 
      }
      var stat = $(content_type +'_status');
      if(stat != undefined) { stat.value = status; }
    });
  });
}

function link_to_close_dialog(class_name){
  $$('.' + class_name).each(function(el){
    el.observe('click', function(ev){
      ev.stop();
      window.parent.Dialog.closeInfo();
    });
  });
}

function close_dialog_with_callback(class_name, callback){
  $$('.' + class_name).each(function(el){
    el.observe('click', function(ev){
      ev.stop();
      if(window.parent[callback] != undefined) {
        window.parent[callback]();
      }
      window.parent.Dialog.closeInfo();
    });
  });
}

function lightboxifyLink(class_name, h, w){
  $$('.' + class_name).each(function(el){
    el.observe('click', function(ev){
      ev.stop();
      if(!el.hasClassName('disabled')){
        Dialog.alert('', {url: el.href, width: w, height: h});
        }
    });
  });
}

function lightboxifyLinkById(id, h, w){
  var el = $(id);
  el.observe('click', function(ev){
    ev.stop();
    if(!el.hasClassName('disabled')){
      Dialog.alert('', {url: el.href, width: w, height: h});
    }
  });
  
}

function toggleSharingPermissions(el, confirmation_msg){
  if (el.id.include('assigned_role_ids__everyone')){
    //enable sharing radio buttons
    
    $$('.sharing_radio_button').each(function(el){
      el.enable();
    });
    $$('.sharing_span').each(function(el){
      el.removeClassName('disabled');
    });

  } else {
    // alert user that restricted content cannot be shared
    // disable sharing radio buttons
    if ($$('.sharing_radio_button').first().disabled == false) {
      if (confirmation_msg) {
        confirmation = confirm(confirmation_msg);
      } else {
        confirmation = true;
      }
      if (confirmation) {
        $$('.sharing_radio_button').each(function(el){
          if(el.id.include('_is_shared_0')){
            el.checked = true;
          }
          el.disable();
        });
        $$('.sharing_span').each(function(el){
          el.addClassName('disabled');
        });

      } else {
        permission_radio_buttons.first().checked = true;
      }
    }
  }
  
  toggleSharingDownload(detectChecked('.sharing_radio_button'));
}

function detectChecked(group) {
  return $$(group).detect(function(e){ return e.checked });
}

function toggleSharingDownload(el) {
  if (el) {
    var enable = (el.value != '0');
    $$('.downloadable_check_box').each(function(e){
      if (enable) {
        e.enable();
      } else {
        e.checked = false;
        e.disable();
      }
    });

    $$('.downloadable_span').each(function(e){
      if (enable) {
        e.removeClassName('disabled');
      } else {
        e.addClassName('disabled');
      }
    });
  }
}

function tinySaveCallback(el, html, body) {
  html = tinySrcCheck(el, html, body);
  html = tinyIframeSrcCheck(el, html, body);
  return html;
}

function tinySrcCheck(el, html, body) {
  return html.gsub(/src="(.+?)"/, function(match) { 
    if (match[1].startsWith('/') || match[1].startsWith('http://') || match[1].startsWith('https://'))
      return match[0];
    else
      return 'src="/'+match[1]+'" alt';
  });
}

function tinyIframeSrcCheck(el, html, body) {
  return html.gsub(/src="(.+?)"/, function(match) {
    return 'src="'+match[1].gsub(/amp;/,'')+'"';
  });
}

function copy(inElement) {
  if (inElement.createTextRange) {
    var range = inElement.createTextRange();
    if (range && BodyLoaded==1)
      range.execCommand('Copy');
  } else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="/flash/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.innerHTML)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}

function copyLinks(){
  $$('.copy').each(function(el, idx){
    el.observe('click', function(ev) {
      ev.stop();
      copy(el.up().previous());
    });
  });
}


var TableSort = Class.create({
  initialize: function(tableSelector){
    this.selector = tableSelector;
    this.mapper   = [];
    this.refresh();

    $$(tableSelector).each(function(table){
      var headers = table.select('table.index_header th');
      var tbody   = table.select('table.index_content tbody')[0];
      var tbodyRows = table.select('tbody tr');

      headers.each(function(el, idx){
        el.stopObserving('click');
        var self = this;
        self.sort = false;
        el.observe('click', function(ev) {
          ev.stop();

          function ascSort(arr) {
            self.sort = false;
            return arr.sortBy(function(el) { return el.innerHTML.replace(/<[^>]+>/g, "").toLowerCase().strip(); });
          }

          function descSort(arr) {
            var newArray = ascSort(arr).reverse();
            self.sort = true;
            return newArray;
          }

          var sorted = (self.sort ? ascSort(this.mapper[idx]) : descSort(this.mapper[idx]));
          var pinned = [];
          sorted.each(function(el, idx) {
            var tr = el.up();
            var pin = tr.down('td').down('a.pin');
            if(pin && pin.hasClassName('pinned')) {
              pinned.push(tr);
            } else {
              tbody.insert({top: tr});
            }
          });
          pinned.each(function(el) { tbody.insert({ top: el }); });
        }.bind(this));
      }.bind(this));
    }.bind(this));
  },
  
  refresh: function(){
    this.mapper = []
    $$(this.selector).each(function(table){
      var headers = table.select('table.index_header th');
      var rows    = table.select('table.index_content td').reject(function(el) { return el.hasClassName('ignore' ); }).inGroupsOf(headers.length);

      headers.length.times(function(n){
        this.mapper.push([]);
        rows.each(function(row) {
          this.mapper[n].push(row[n]);
        }.bind(this));
      }.bind(this));
    }.bind(this))
  }
})

function tabToggle(li, idx){
  var sections = $$('.tab-section');
  $$('.tab-links').invoke('removeClassName', 'selected');
  li.addClassName('selected');
  sections.invoke('hide');
  sections[idx].show();
}

function widgetTabsInit(){
  var lis = $$('#widget_config_tabs_list li');
  $$('a.toggle-link').each(function(el){
    el.observe('click', function(ev){
      lis.each(function(li){
        li.removeClassName('selected');
      });
      this.up('li').addClassName('selected');
      $$('.lightboxContent').each(function(lbEl){
        lbEl.hide();
      });
      $(this.id.gsub('_link', '')).show();
    });
  });
  lis[0].addClassName('selected');
}

function initIndexTableAjax(classMatcher){
  // initialize the sorting of non-action columns
  table_sorter = new TableSort('div.index_table_wrapper');

  // initialize table hover & selected row highlighting
  initIndexHovers(classMatcher);
}

document.observe('dom:loaded',function() {
  // initialize the filtering of table content
  initIndexFilters('.index_table_wrapper');
});

function initIndexHovers(classMatcher) {
  var table = $$('table.index_content').first();

  table.observe('mouseout', function(ev) {
    var tr = Event.element(ev).up('tr');
    if (tr)
      tr.select('td').invoke('removeClassName', 'row-hover');
  });

  table.observe('mouseover', function(ev) {
    var tr = Event.element(ev).up('tr');
    if (tr)
      tr.select('td').invoke('addClassName', 'row-hover');
  });

  table.observe('click', function(ev) {
    var tr = Event.element(ev).up('tr');

    tr.adjacent('.selected').each(function(e) {
      e.removeClassName('selected'); 
      e.select('td.selected').invoke('removeClassName', 'selected');
    });

    tr.addClassName('selected');
    tr.select('td').invoke('addClassName', 'selected');

    // Not clicking a link or a child of a link. If we are, then we simply let the link event fire.
    if(!Event.element(ev).match('a') && (Event.element(ev).up('a') == null)) {
      showLink = tr.down('td a.' + classMatcher + '');
      new Ajax.Request(showLink, {method:'get'});
    }
  });
}

function indexRowSelector(rowId){
  $$('table.index_content tbody tr td.selected').each(function(td){
    td.removeClassName('selected');
  });
  $$('tr#'+rowId+' td').each(function(td){
    td.addClassName('selected');
  });
}

function initIndexFilters(tableSelector) {
  if ($$(tableSelector)[0] == undefined) {
    if (!($$('.filter-form')[0] == undefined)) {
      $$('.filter-form')[0].hide();
    }
  } else {
    $$('.filter-form')[0].show();
    $('filter_index_submit').observe('click', function(ev) {
      ev.stop();
      filterIndex();
      return false;
    });
    $('filter_reset_submit').observe('click', function(ev) {
      ev.stop();
      filterIndex(true);
      return false;
    });
  }
}

function filterIndex(reset){
  if(reset==true) {
    var terms = [];
    $('filter_search').setValue('');
  } else {
    var terms = $('filter_search').value.toLowerCase().split(" ");
  }
  
  var rows = $$('table.index_content tbody tr');
  
  rows.each(function(tr) {
    var hide = false;
    terms.each(function(term) {
      trContent = tr.innerHTML.replace(/<[^>]+>/g, "").toLowerCase();
      if(trContent.indexOf(term)<0) {
        hide = true;
      }
    });
    
    if (hide == true) {
      tr.hide();
      tr.select('td').each(function(el){el.addClassName('ignore')});
    } else { 
      tr.show();
      tr.select('td').each(function(el){el.removeClassName('ignore')});
    }
  });
}


/* TinyMCE paste from word */
function convertWord(type, content) {
  switch (type) {
    // Gets executed before the built in logic performs it's cleanups
    case "before":
      break;

    // Gets executed after the built in logic performs it's cleanups
    case "after":
      content = content.replace(/<(!--)([\s\S]*)(--)>/gi, "");
      break;
  }
  return content;
}

function initializeSWFUploader(options) {
  var link = $('chooser-link');

  swfu = new SWFUpload({
    upload_url: options['upload_url'],
    callbackUrl: options['callbackUrl'].unescapeHTML(),
    file_post_name: options['file_post_name'],

    flash_url : '/flash/swfupload.swf',
    allowed_filesize : 2230720, // 30 MB
    allowed_filetypes : '*.*',
    custom_settings : {
      progressTarget : "list"
    },

    // Button settings
    button_placeholder_id : "spanButtonPlaceHolder",
    button_window_mode    : SWFUpload.WINDOW_MODE.TRANSPARENT,
    button_cursor         : SWFUpload.CURSOR.HAND,
    button_height         : link.getHeight(),
    button_width          : link.getWidth(),

    // The event handler functions are defined in handlers.js
    swfupload_loaded_handler      : swfUploadLoaded,
    file_queued_handler           : fileQueued,
    file_queue_error_handler      : fileQueueError,
    upload_start_handler          : uploadStart,
    upload_progress_handler       : uploadProgress,
    upload_error_handler          : uploadError,
    upload_success_handler        : uploadSuccess,
    upload_complete_handler       : uploadComplete,
    queue_complete_handler        : queueComplete, // Queue plugin event

    // SWFObject settings
    minimum_flash_version         : "9.0.28",
    swfupload_pre_load_handler    : swfUploadPreLoad,
    swfupload_load_failed_handler : swfUploadLoadFailed
  });
}

function insertMCELink(html_id, text) {
  tinyMCE.execInstanceCommand(html_id, 'mceInsertContent', false, text);
  if(bookmark) { tinyMCE.activeEditor.selection.moveToBookmark(bookmark); }
}

function populateUnionDropdown() {
  new Ajax.Request('/unions', { method: 'get', parameters: { division_id: $('division_id').value } });
}

function populateLocalFieldDropdown() {
  new Ajax.Request('/local_fields', { method: 'get', parameters: { union_id: $('union_id').value } });
}

function highlightMenu(menu_id, key) {
  var link = $('menu-' + menu_id + '-key-' + key);
  if (link) {
    link.addClassName('active');
  }
}

function enableTreeNav(menu_id) {
  $$('#' + menu_id + ' li.expandable > a').each(function(e){
    e.observe('click', function(ev){
      ev.stop();
      var parent = this.up();
      expandTreeNav(parent);
    })
  })
  
  var active = $$('#' + menu_id + ' a[href=' + location.pathname + location.search + ']').last();
  if (!active) {
    active = $$('#' + menu_id + ' a').select(function(a) {
      return location.href.startsWith(a.href);
    }).first();
  }
  if (active) {
    var li = active.up()
    li.addClassName('active');
    if (li.hasClassName('expandable')) {
      expandTreeNav(li);
    } else if (li.hasClassName('nested-menu-item')) {
      expandTreeNav($(li.up().up().id.gsub('-secondary', '')));
    }
  }
  
}

function expandTreeNav(obj) {
  if (obj) {
    var secondary = $(obj.id + '-secondary');
    if (secondary) {
      if (obj.hasClassName('expandable')) {
        secondary.show();
        obj.addClassName('expanded-menu');
        obj.removeClassName('expandable');
      } else {
        secondary.hide();
        obj.addClassName('expandable');
        obj.removeClassName('expanded-menu');
      }
    }
  }
  
}