if (!window.console) {
  var console = {
    log:function() {
    },
    info:function() {
    },
    debug:function() {
    },
    error:function() {
    }};
}

$.fn.increment = function(by) {
  return this.each(function() {
    var newValue = parseInt($(this).html()) + (by || 1);
    $(this).html(newValue);
  });
};
$.fn.decrement = function(by) {
  return $(this).increment(0 - (by || 1));
};
$.fn.exists = function() {
  return $(this).length > 0;
};

var GA = new function() {
  this.track = function(fake_url) {
    if (typeof(pageTracker) !== 'undefined') {
      _gaq.push(['_trackPageview', fake_url]);
    }
  };
};

var ReplaceSubmitWithLink = new function() {
  var self = this;
  self.replace = function(selector) {
    $(selector).find('input[type=submit].replace').each(function() {
      $(this).after("<a href=\"#" + $(this).attr('name') + "\" class=\"button submit_form\">" + $(this).val() + "</a>");
      $(this).hide();
    });

    $(selector).find('a.submit_form').click(function() {
      if ($(this).is('.disabled_button')) {
        return false;
      }
      $(this).addClass('disabled_button');
      if ($(this).html() == 'Save') {
        $(this).html('Saving...');
      }
      if ($(this).html() == 'Add user') {
        $(this).html('Adding user...');
      }
      $(this).parents('form').eq(0).trigger('submit');
      return false;
    });
  };
  $(function() {
    self.replace('body');
  });
};

var ModalOverlay = new function() {
  $(function() {
    $('a.open-modal').click(function() {
      $('div.modal_overlay').hide();
      var rel = $(this).attr('rel');
      var parts = rel.split('#');
      var modalId = parts[0];
      var modal = $("div#" + modalId);
      if (modal.length == 0) {
        return true;
      }
      modal.show();
      modal.trigger('open');
      if (parts.length > 1) {
        MultiTabModal.showTab(modal, parts[1]);
      }
      return false;
    });

    $('div.modal_overlay').bind('close', function() {
      $('div.modal_overlay').hide().trigger('closed');
    });
    $('div.modal_overlay, a.modal_overlay-close').click(function() {
      $('div.modal_overlay').trigger('close');
      return false;
    });

    $('div.modal_overlay div.box div.inner').click(function(e) {
      e.stopPropagation();
    });

    var img1 = new Image();
    var img2 = new Image();
    var img3 = new Image();
    var img4 = new Image();
    var img5 = new Image();
    var img6 = new Image();
    img1.src = "/images/newex/modal-bottom.png";
    img2.src = "/images/newex/modal-top.png";
    img3.src = "/images/newex/modal-check.png";
    img4.src = "/images/newex/switch-off.gif";
    img5.src = "/images/newex/switch-on.gif";
    img6.src = "/images/newex/modal-top-no-x.png";
  });
};

var MultiTabModal = new function() {
  var self = this;
  self.showTab = function(modal, tabLinkId) {
    modal.find('div.settings ul.modal').hide();
    modal.find('ul.nav a.selected').removeClass('selected');
    modal.find('#' + tabLinkId).addClass('selected');
    var panelId = tabLinkId.replace(/Select/, '');
    $('#' + panelId).show();
  };
  $(function() {
    $('div.modal_overlay div.settings ul.modal').hide();
    $('div.modal_overlay ul.nav a.selected').each(function() {
      var currentModal = $(this).closest('div.modal_overlay');
      self.showTab(currentModal, $(this).attr('id'));
    });
    $('div.modal_overlay ul.nav a').click(function() {
      var currentModal = $(this).closest('div.modal_overlay');
      self.showTab(currentModal, $(this).attr('id'));
    });
  });
};

var InlineEditingSettings = new function() {
  $(function() {

    var enable_buttons = function(el) {
      $('span.cancel_option a', el).click(function() {
        el.removeClass('editing');
        el.removeClass('has_error');
        el.find('p.error').remove();
        restore_html(el.find('span.fields'));
      });
      $('a.submit_this_form', el).click(function() {
        var serialized = el.find('input, select').serialize();
        el.trigger('submitting');
        $.ajax({
          type: 'PUT',
          url: el.parents('form').attr('action'),
          data: serialized,
          success: function() {
            el.trigger('success');
            el.trigger('revert');
          },
          error: function(xhr) {
            var json = xhr.responseText;
            var errorMessage = '';
            if (json) {
              var data = $.parseJSON(json);
              errorMessage = data.errors.join(',');
            }
            el.trigger('error', [errorMessage]);
          }
        });
        return false;
      });
    };

    var save_html = function(el) {
      el.data('stored_html', el.html());
    };

    var restore_html = function(el) {
      var stored_html = el.data('stored_html');
      if (stored_html != '') {
        el.html(el.data('stored_html'));
        blank_stored_html(el);
      }
      enable_buttons(el.parents('div.inline_editable').eq(0));
    };

    var blank_stored_html = function(el) {
      el.data('stored_html', '');
    };

    $('div.inline_editable').each(function() {
      var inlineEditableItem = $(this);
      $('span.fields', inlineEditableItem).each(function() {
        var jq_obj = $(this);
        if ( jq_obj.find('a.button').length == 0 ) {
          jq_obj.append('<a href="#" class="submit_this_form button">Save</a><span class="cancel_option">or <a href="#">cancel</a></span>');
        } else {
          jq_obj.append('<span class="cancel_option">or <a href="#">cancel</a></span>');
        }
      });
      $('span.values>a', inlineEditableItem).click(function() {
        inlineEditableItem.parents('form').find('.form_group.editing').trigger('revert');
        save_html(inlineEditableItem.find('span.fields'));
        inlineEditableItem.addClass('editing');
        inlineEditableItem.find('input').first().focus();
        return false;
      });
      inlineEditableItem.bind('revert', function() {
        inlineEditableItem.find('.submit_this_form').html('Save');
        inlineEditableItem.find('.cancel_option').show();
        blank_stored_html(inlineEditableItem.find('span.fields'));
        $(this).removeClass('editing');
      });
      inlineEditableItem.bind('submitting', function() {
        inlineEditableItem.removeClass('has_error');
        inlineEditableItem.find('p.error').remove();
        inlineEditableItem.find('.submit_this_form').html('Saving...');
        inlineEditableItem.find('.cancel_option').hide();
      });
      inlineEditableItem.bind('error', function(event, errorMessage) {
        inlineEditableItem.addClass('has_error');
        inlineEditableItem.find('.submit_this_form').html('Save');
        inlineEditableItem.find('.cancel_option').show();
        inlineEditableItem.append('<p class="error">' + errorMessage + '</p>');
      });
      // Blank / regenerate HTML to remove saved browser state of inputs
      save_html(inlineEditableItem.find('span.fields'));
      restore_html(inlineEditableItem.find('span.fields'));
    });
    $('#AppNameInlineEdit').bind('success', function() {
      var newAppName = $(this).find('input').val();
      $('.current_app_name').html(newAppName);
    });
    $('#AppOwnerInlineEdit').bind('success', function() {
      window.location.reload();
    });
    $('#UserTimezoneInlineEdit').bind('success', function() {
      $(this).find('.values a').html($(this).find('select option:selected').html());
    });
    $('#UserEmailInlineEdit').bind('success', function() {
      $(this).find('.values a').html($(this).find('input').val());
    });
    $('#UserSmsInlineEdit').bind('success', function() {
      $(this).find('.values a').html("+" + $(this).find('select option:selected').html() + " " + $(this).find('input').val());
    });
  });
};

var ShowModalOnPageLoad = new function() {
  $(function() {
    var modalName = null;
    if (modalName = window.location.toString().split('#modal_')[1])
    {
      $('#' + modalName).show();
    }
  });
};

var TeamMembers = new function() {
  var self = this;
  self.bindToRemoveLinks = function() {
    $('div#ConfigModal a.delete-permission, div#ConfigModal a.delete-invite').click(function(e) {
      $(this).parents('tr').remove();
      $.ajax({type: 'DELETE', url: $(this).attr('href'), data: {}});
      return false;
    });
  };
  self.bindToAdminCheckboxes = function() {
    $('form#EditPermission input[type=checkbox]').click(function() {
      $.ajax({type: 'PUT', url: $(this).parents('form').attr('action'), data: $(this).parents('form').serialize()});
      return true;
    });
  };
  $(function() {
    track_inputs_on_this_form($('div#ConfigModal form#invite_user_form'));
    $('div#ConfigModal form#invite_user_form').submit(function(e) {
      $.ajax({type: 'POST', url: $(this).attr('action'), data: $(this).serialize(),
        success: function(resp) {
          recover_form_from_success($('div#ConfigModal form#invite_user_form'));
          $('#invite_user_error_message').hide();
          $('#AppTeam').replaceWith(resp);
          self.bindToRemoveLinks();
          $('#username_or_email').val('');
        },
        error: function(xhr, textStatus, errorThrow) {
          recover_form_from_errors($('div#ConfigModal form#invite_user_form'));
          $('#username_or_email').val('');
          var json = xhr.responseText;
          var jsonObject = window["eval"]("(" + json + ")");
          var error_message = jsonObject.error_message;
          $('#invite_user_error_message').html(error_message).show();
        }
      });
      return false;
    });
    self.bindToRemoveLinks();
    self.bindToAdminCheckboxes();
  });
};

var SettingsDisplay = new function() {
  function handle_errors(xhr, textStatus, errorThrow, error_box_selector) {
    var json = xhr.responseText;
    if (json) {
      var jsonObject = window["eval"]("(" + json + ")");
      var errors = jsonObject.errors;
      var errorNotificationDiv = $(error_box_selector);
      var list = errorNotificationDiv.children('ul');
      list.empty();
      $.each(errors, function(error) {
        list.append("<li>" + errors[error] + "</li>");
      });
      errorNotificationDiv.show();
    }
  }

  function handle_services_form(formselector) {
    $(formselector).livequery('submit', function(e) {
      $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: "script",
        success: function(resp) {
          $('#ModalGroupServices').html(resp);
        },
        error: function(xhr, textStatus, errorThrow) {
          recover_form_from_errors($(formselector));
          handle_errors(xhr, textStatus, errorThrow, formselector + ' div.error_notification')
        }
      });
      return false;
    });
  }

  $(function() {
    handle_services_form('div#ConfigModal ul#ModalGroupServices form#twitter_services_form');
    handle_services_form('div#ConfigModal form#lighthouse_services_form');
    handle_services_form('div#ConfigModal form#campfire_services_form');
    handle_services_form('div#ConfigModal form#campfire_services_removal_form');
    handle_services_form('div#ConfigModal form#webhook_services_form');
    handle_services_form('div#ConfigModal form#webhook_services_removal_form');

    $('div#ConfigModal form#edit-notifications-form').submit(function() {
      $.post($(this).attr('action'), $(this).serialize());
      return false;
    });

    $('div.submit_on_change').click(function() {
      $(this).parents('form').trigger("submit");
      return false;
    });
  });
};

var LightswitchControl = new function() {
  $(function() {
    $('div.lightswitch').each(function(i) {
      var lightSwitch = $(this);
      var state = 'false';

      if (lightSwitch.find('input[type=radio]').length > 0) {
        state = lightSwitch.find('input:checked').val();
      } else {
        if (lightSwitch.find('input:checked').length > 0) {
          state = 'true';
        }
      }

      if (state == 'true') {
        lightSwitch.removeClass('is_off');
        lightSwitch.addClass('is_on');
      } else {
        lightSwitch.removeClass('is_on');
        lightSwitch.addClass('is_off');
        lightSwitch.parents('li').eq(0).addClass('hide_dl');
      }
    });

    $('div.lightswitch').click(function() {
      var lightSwitch = $(this);
      var state = '';
      if (lightSwitch.find('input[type=radio]').length > 0) {
        state = lightSwitch.find('input:checked').val();
        lightSwitch.find('input[type=radio]').each(function() {
          if ($(this).val() == state) {
            $(this).attr('checked', '');
          } else {
            $(this).attr('checked', 'checked');
          }
          $(this).change();
        });
      } else {
        if (lightSwitch.find('input:checked').length > 0) {
          // state is true, make false
          lightSwitch.find('input[type=checkbox]').attr('checked', '');
          state = 'off';
        } else {
          // state is false, make true
          lightSwitch.find('input[type=checkbox]').attr('checked', 'checked');
          state = 'on';
        }
        $(this).change();
      }

      lightSwitch.removeClass('is_on');
      lightSwitch.removeClass('is_off');

      if (state == 'true') {
        lightSwitch.addClass('is_off');
      } else {
        lightSwitch.addClass('is_on');
      }
      lightSwitch.parents('li').eq(0).toggleClass('hide_dl');
      $(this).parents('form').trigger("submit");
      return false;
    });


    $('div.lightswitch_submit_on_false').click(function() {
      var lightSwitch = $(this);
      if (lightSwitch.find('input:checked').val() == 'false') {
        $(this).parents('form').trigger("submit");
      }
    });

    $('div.lightswitch_submit_on_change').click(function() {
      $(this).parents('form').trigger("submit");
      return false;
    });
  })
};

var PageResizer = new function() {
  var self = this;
  self.resizeMainPanel = function() {
    var mainPanel = $('div#MainPanel');
    if (mainPanel.length == 0) {
      return;
    }
    var top = mainPanel[0].offsetTop;
    var offset = mainPanel[0].offsetHeight - mainPanel.height();
    var height = $('div#Main').height() - 20 - top - offset;
    mainPanel.height(height);
    // Reposition system notification_mailer
    $('div#SystemNotification').each(function(i) {
      $(this).css({'right': Math.ceil($('body')[0].offsetWidth - ( $('div#Exceptional').offset().left + $('div#Exceptional')[0].offsetWidth )) + 18 });
    });
  };
  $(function() {
    $(window).resize(function() {
      self.resizeMainPanel();
    });
    self.resizeMainPanel();
  });
};

var SystemNotifications = new function() {
  var self = this;
  self.closeSystemNotifications = function() {
    $('div#SystemNotification').remove();
  };
  $(function() {
    $('div#SystemNotification div.inner a.closer').click(function() {
      $.ajax({type: 'GET', url: $(this).attr('href'), data: $(this).serialize()});
      self.closeSystemNotifications();
      return false;
    });
  });
};

var ValidForms = new function() {
  var self = this;
  self.hasErrors = function(form) {
    var seenError = false;
    $('textarea.validate-not-blank', form).each(function() {
      if (self.isBlank($(this))) {
        seenError = true;
        $(this).addClass('validation-error');
      }
    });
    return seenError;
  };
  self.isBlank = function(input) {
    return $.trim(input.val()) == '';
  };
  $(function() {
    $('form.validate-before-submit').submit(function() {
      if (!self.hasErrors($(this))) {
        $(this).trigger('submit-when-valid');
      }
      return false;
    });
    $('form.validate-before-submit textarea.validate-not-blank').keyup(function() {
      if (!self.isBlank($(this)))
        $(this).removeClass('validation-error');
    });
  });
};

var SupportForm = new function() {
  $(function() {
    $('#support-form').bind('submit-when-valid', function() {
      $.post($(this).attr('action'), $(this).serialize(), function() {
        $('#support-thanks').show();
        $('#SupportEnter').hide();
      });
    });
    $('#SupportModal').bind('open', function() {
      $('#SupportModal #feedback_message').focus();
    });
    $('#SupportModal').bind('closed', function() {
      $('#feedback_message').val('').removeClass('validation-error');
      $('#SupportEnter').show();
      $('#support-thanks').hide();
    });
  });
};

var CommentForm = new function() {
  $(function() {
    $('form#new_comment').submit(function() {
      var errorId = $(this).attr('action').match(/error_id=([0-9]+)/)[1];
      $.post($(this).attr('action'), $(this).serialize(), function(html) {
        $('#comments').append(html);
        $('#comment_count_error_' + errorId).increment();
        $('#new_comment a.submit_form').removeClass('disabled_button');
        $('#comment_comment').val('').removeClass('validation-error');
      }, 'html');
      return false;
    });
  });
};

var NewAppForm = new function() {
  $(function() {
    $('form#NewAppInlineForm').submit(function() {
      $.ajax({ type: 'POST', url: $(this).attr('action'),
        data: $(this).serialize(), dataType: 'json',
        success: function(json) {
          $('#app_name').val('');
          $('#NewAppApiKey').html(json.api_key);
          $('#NewAppDashboardLink').attr('href', '/apps/' + json.id);
          $('#NewAppStep1').hide();
          $('#NewAppStep2').show();
          $('#NewAppModal').addClass('instructions');
          $('div.modal_overlay').unbind('close');
        },
        error: function(xhr, textStatus, errorThrow) {
          $('#NewAppInlineForm a.submit_form').removeClass('disabled_button');
          $('#NewAppError').show();
        }
      });
      return false;
    });
  });
};

var InfiniteScroll = new function() {
  var self = this;
  self.currentPage = 1;
  self.totalPages = 2;
  self.currentPaginationRequest = null;
  self.addMoreResults = function(html) {
    var appended = $(html).appendTo('#exception_list');
    MultiExceptionSelect.applyBehaviourToExceptions(appended);
    LargeClickTargets.linkEntireBlockToDetailsPage(appended);
    $('#more-link-technology-loading').hide();
    $('#more-link-technology-loading').stop();
    if (self.currentPage < self.totalPages) {
      $('a#more-link-technology-link').show();
    }
  };
  self.bind = function() {
    $('#more-link-technology').bind('more-me', function() {
      if (self.currentPaginationRequest != null) {
        return;
      }
      if (self.currentPage == self.totalPages) {
        return;
      }
      self.currentPage++;
      $('#more-link-technology-loading').show();
      PulsatingPanda.pulsate('#more-link-technology-loading');
      $('#more-link-technology-link').hide();
      var pageHref = $('#more-link-technology a').attr('href');
      pageHref = pageHref.replace(/page=\d+/, "page=" + self.currentPage);
      self.currentPaginationRequest = $.get(pageHref, {format:'js'}, function(data) {
        self.addMoreResults(data);
        self.currentPaginationRequest = null;
      }, "html");
    });
    $('#MainPanel').scroll(function() {
      var totalHeightOfItemsLoaded = $('#MainPanel form').outerHeight();
      var lowestVisiblePixel = $(this).scrollTop() + $(this).height();
      var halfHeightOfScrollPane = $(this).height() / 2;
      var nearlyAtTheBottom = lowestVisiblePixel + halfHeightOfScrollPane >= totalHeightOfItemsLoaded;
      if (nearlyAtTheBottom) {
        $('#more-link-technology').trigger('more-me');
      }
    });
  };
  $(function() {
    self.bind();
    $('#MainPanel').trigger('scroll');
    $('a#more-link-technology-link').click(function() {
      $('#more-link-technology').trigger('more-me');
      return false;
    });
  });
};
var LargeClickTargets = new function() {
  var self = this;
  self.linkEntireBlockToDetailsPage = function(exceptionLis) {
    $(exceptionLis).click(function(e) {
      e.stopPropagation();
      var exceptionLink = $(this).find('h2 a');
      if (exceptionLink.data('events') && exceptionLink.data('events').click) {
        exceptionLink.trigger('click');
      } else {
        location.href = exceptionLink.attr('href');
      }
    });
  };
  $(function() {
    self.linkEntireBlockToDetailsPage($('ul.app_list li.app, ul#exception_list li.error'));
    // Special cases for single exceptions
    $('ul.single_exception>li').unbind('click');
  });
};

var MultiExceptionSelect = new function() {
  var self = this;
  self.applyBehaviourToExceptions = function(exceptionLis) {
    $('input.select-exception', exceptionLis).change(function(e) {
      if ($(this).is(':checked')) {
        $(this).parents('li').eq(0).addClass('selected');
      } else {
        $(this).parents('li').eq(0).removeClass('selected');
        $('.fixed_row input.select_all').attr('checked', '');
      }
      $('#exception_list').trigger('selection-changed');
    });
    $('input.select-exception', exceptionLis).trigger('change');
    $('input.select-exception', exceptionLis).click(function(e) {
      e.stopPropagation();
    });
    $("div.checkbox_wrapper", exceptionLis).click(function(e) {
      e.stopPropagation();
      var checked = $(this).find(":checked");
      if (checked.length > 0) {
        checked.attr('checked', '');
      } else {
        $(this).find("input[type=checkbox]").attr('checked', 'checked');
      }
      $(this).find("input[type=checkbox]").change();
      return false;
    });
  };
  $(function() {
    $('#exception_list').bind('selection-changed', function() {
      var checked = $(':checked.select-exception');
      if (checked.length < 1) {
        $('div.exception_actions a').addClass('disabled_button');
      } else {
        $('div.exception_actions a').removeClass('disabled_button');
      }
      SelectedExceptions.updateNumberSelected();
    });
    self.applyBehaviourToExceptions($("#exception_list li.error"));
    $('ul.single_exception>li input.select-exception').unbind('change');
    $('ul.single_exception>li input.select-exception').attr('checked', 'checked');
    $("ul.single_exception>li>div.checkbox_wrapper").unbind('click');
    $('ul.single_exception>li').addClass('selected');
    $('#exception_list').trigger('selection-changed');
  });
};

var SelectAllExceptions = new function() {
  var self = this;
  self.change = function(select_all) {
    if (select_all) {
      $('ul#exception_list input.select-exception').each(function(i) {
        if (! (  $(this).is(':checked') )) {
          $(this).attr('checked', 'checked');
          $(this).change();
        }
      });
    } else {
      $('ul#exception_list input.select-exception').each(function(i) {
        if ($(this).is(':checked')) {
          $(this).attr('checked', '');
          $(this).change();
        }
      });
    }
  };
  $(function() {
    $('.fixed_row input.select_all').change(function() {
      SelectAllExceptions.change($(this).is(':checked'));
    });
    $('.fixed_row input.select_all').parents('form').eq(0).click(function(e) {
      var selectAllInput = $(this).find('input.select_all');
      if (e.target == selectAllInput[0]) {
        return;
      }
      if (selectAllInput.is(':checked')) {
        selectAllInput.attr('checked', '');
      } else {
        selectAllInput.attr('checked', 'checked');
      }
      selectAllInput.change();
    });
  });
};

var StateSwitcher = new function() {
  var self = this;
  self.changeStateTo = function(state) {
    GA.track('/exceptions/stateSwitcher/' + state);
    $('#state-switcher').find('a:first').appendTo('#state-switcher .contents');
    $('#state-switcher .contents').find('a.' + state).prependTo('#state-switcher');
    $('#state-switcher .contents').find('a.four_oh_fours').appendTo('#state-switcher .contents');
  };
};
var SelectedExceptions = new function() {
  var self = this;
  self.selectedIds = function() {
    var ids = [];
    $('#exception_list li.selected').each(function(index, item) {
      ids.push($(item).attr('id').replace(/\D*/, ''));
    });
    return ids;
  };
  self.showNoExceptionsIfEmptyList = function() {
    if (!$('#exception_list li:visible').exists()) {
      $('#exception_list').hide();
      $('#EmptyErrorsList').show();
      $('#FixedRow').hide();
      $('#MainPanel').removeClass('has_fixed_row');
    }
  };
  self.selectedErrorOptions = function() {
    options = {};
    if ($('.fixed_row input.select_all').is(':checked')) {
      options['state'] = /ignored$/.test(window.location.href) ? 'ignored' : (/closed$/.test(window.location.href) ? 'closed' : 'open' );
      var searchQ = $.trim($('#q').val());
      if (searchQ !== '') {
        options['q'] = searchQ;
      }
    } else {
      options['error_ids'] = self.selectedIds().join(',');
    }
    return options;
  };
  self.selectedIdString = function() {
    return self.selectedIds().join(',');
  };
  self.numberSelected = function() {
    var ids = self.selectedIds();
    var changeBy = ids.length;
    if ($('.fixed_row input.select_all').is(':checked')) {
      if ($('#SearchHits').exists()) {
        changeBy = parseInt($('#SearchHits').html())
      } else {
        changeBy = parseInt($('#state-switcher a:first .count').html())
      }
    }
    return changeBy;
  };
  self.updateNumberSelected = function () {
    var num = self.numberSelected();
    if (num === 0)
      message = '';
    else {
      var message;
      if ($('#SearchHits').exists()) {
        message = num == 1 ? (num + " search result selected") : (num + ' search results selected');
      } else {
        message = num == 1 ? (num + " exception selected") : (num + ' exceptions selected');
      }
      if ($('.fixed_row input.select_all').is(':checked')) {
        message = "All " + message;
      }
    }
    $('#SelectedErrorsCount').html(message);
  };
  self.updateSwitcherCounts = function (changedTo) {
    var changeBy = self.numberSelected();

    $('#state-switcher a:first span.count').decrement(changeBy);
    $('#state-switcher a.' + changedTo + ' span.count').increment(changeBy);
  };
  self.handleSingleExceptionChange = function(changeTo) {
    GA.track('/exceptions/stateChange/single/' + changeTo);
    // change the state switcher?? change the buttons available, etc..
    $('#ExceptionStateChanger').removeClass('state_open').removeClass('state_closed').removeClass('state_ignored');
    $('#ExceptionStateChanger').addClass('state_' + changeTo);
    StateSwitcher.changeStateTo(changeTo);
    $('div.exception_actions a').addClass('disabled_button');
    $('#exception_list li.selected').removeClass('state_open').removeClass('state_closed').removeClass('state_ignored');
    $('#exception_list li.selected').addClass('state_' + changeTo);
    setTimeout(function() {
      $('div.exception_actions a').removeClass('disabled_button');
    }, 500);
    self.showNoExceptionsIfEmptyList();
  };
  self.handleBulkChange = function(changeTo) {
    GA.track('/exceptions/stateChange/bulk/' + changeTo);
    var ids = self.selectedIds();
    self.updateSwitcherCounts(changeTo);
    if ($('#exception_list').hasClass('single_exception')) {
      self.handleSingleExceptionChange(changeTo);
    } else {
      $('#exception_list li.selected input').attr('checked', '');
      $('#exception_list li.selected').removeClass('selected');
      $('#exception_list').trigger('selection-changed');
      $('#MainPanel').trigger('scroll');
      $.each(ids, function() {
        $("#error_" + this).fadeTo(500, 0, function() {
          $(this).slideUp(500, function() {
            self.showNoExceptionsIfEmptyList();
          });
        });
      });
    }

  };
  $(function() {
    $('a#selected-exceptions-close, a#selected-exceptions-reopen, a#selected-exceptions-ignore').click(function() {
      if (!$(this).hasClass('disabled_button')) {
        $.post($(this).attr('href'), self.selectedErrorOptions());
        $(this).trigger('click-when-enabled');
      }
      return false;
    });
    $('a#selected-exceptions-close').bind('click-when-enabled', function() {
      self.handleBulkChange('closed');
    });
    $('a#selected-exceptions-reopen').bind('click-when-enabled', function() {
      self.handleBulkChange('open');
    });
    $('#selected-exceptions-ignore').bind('click-when-enabled', function() {
      self.handleBulkChange('ignored');
    });
  });
};

var PulsatingPanda = new function() {
  var self = this;
  self.pulseIn = function(selector) {
    $(selector).fadeTo(500, 1, function () {
      self.pulsate(this);
    });
  };
  self.pulsate = function(selector) {
    $(selector).fadeTo(500, 0.25, function () {
      self.pulseIn(this);
    });
  };
};

var RevealLongDesc = new function() {
  $(function() {
    $('a.reveal_long_desc').click(function(e) {
      var header = $(this).parents('h2').eq(0);
      if (header.is('h2[longdesc]')) {
        header.html(header.attr('longdesc'));
        header.attr('longdesc', '');
      }
      return false;
    });
  });
};


var NotificationSettings = new function() {
  $(function() {
    var AjaxRunning = false;
    $('form .inline_checkbox input[type=checkbox]').click(function() {
      if (!AjaxRunning) {
        var element = $(this);
        $.ajax({type: 'PUT', url: $(this).parents('form').attr('action'), data: $(this).parents('.form_group').find('input').serialize(),
          beforeSend: function() {
            AjaxRunning = true;
            element.attr('disabled', 'disabled');
            element.parents('div.form_group').addClass('ajax');
          },
          complete: function() {
            if (element.attr('id')=='user_notifications_off') {
              if (element.is(':checked')) {
                $("#NotificationsDisabledMessage").show();
              } else {
                $("#NotificationsDisabledMessage").hide();
              };
            };
            element.removeAttr('disabled');
            element.parents('div.form_group').removeClass('ajax');
            AjaxRunning = false;
          }
        });
        return true;
      } else {
        return false;
      }
    });
  });
};

var UserConfig = new function() {
	$(function() {
    $('a.send_test_sms').click(function(e) {
			var element = $(this);
      $.ajax({url: $(this).attr('href'),
      beforeSend: function() {
				element.parents('span').addClass('ajax');
      },
      complete: function() {
				element.parents('span').removeClass('ajax');
      },
			success: function () {
				element.parents('span').html('Sent!');
			},
			error: function(xhr) {
        var json = xhr.responseText;
        var errorMessage = '';
        if (json) {
          var data = $.parseJSON(json);
          errorMessage = data.error;
	        element.parents('span').html('Error - ' + errorMessage);
        } else {
					element.parents('span').html('Error sending test message');
				}
      }
			});
      return false;
    });
	})
};


var OccurrencePaging = new function() {
  $(function() {
    $('ul.occurrence_pages').each(function() {
      var counter = 0;
      $(this).children('li').each(function(i) {
        $(this).addClass('page_' + i);
        counter = i;
      });
      $(this).children('.page_' + counter).each(function() {
        $(this).addClass('last_page');
      });
    });

    $('ul.occurrence_pages>li.page_0').each(function() {
      $(this).addClass('first_page');
    });

    $('ul.occurrence_pages>li div.paging span.prev a').click(function() {
      var cur_page = $(this).parents('li').eq(0);
      if (cur_page.is('.first_page')) {
        return false;
      }
      cur_page.hide();
      cur_page.prev('li').show();
      return false;
    });

    $('ul.occurrence_pages>li div.paging span.next a').click(function() {
      var cur_page = $(this).parents('li').eq(0);
      if (cur_page.is('.last_page')) {
        return false;
      }
      cur_page.hide();
      cur_page.next('li').show();
      return false;
    });
  });
};

var ExceptionDetailsExpander = new function() {
  $(function() {
    $('ul.exception_details>li>a.expander').click(function() {
      $(this).hide();
      var spans = $(this).find('span');
      var expanderLi = $(this).parents('li').first();
      expanderLi.addClass('expanded');

      var expander_type = "";
      var classes = expanderLi[0].className.split(" ");
      for (var i = 0; i < classes.length; i++) {
        if (classes[i].match(/^ga\_/)) {
          expander_type = classes[i].replace(/^ga\_/, '');
        }
      }
      GA.track('/exceptions/expanders/' + expander_type + '/open');

      $('div#Main div#MainPanel').toggleClass('expander_shuffle'); // To get around a manky Safari bug :(
      $(window).trigger('resize');
      return false;
    });
  });
};

var ServicesTab = new function() {
  var self = this;

  self.displayPane = function( selector, back_link ) {
    $('#AddedServices').hide();
    $('#ServicesPanes').show();
    $('#ServicesPanes>div').hide();
    $(selector + ' a.back_link').attr('href', back_link );
    $(selector).show();
  };

  $(function() {
    $('#AddedServices a.more_link, #ServicesPanes a.more_link').livequery('click', function() {
      var jq_obj = $(this);
      self.displayPane( jq_obj.attr('href'), '#' + jq_obj.parents('div.pane').eq(0).attr('id') );
      return false;
    });
    $('#ServicesPanes a.back_link').livequery('click', function() {
      var jq_obj = $(this);
      var selector = jq_obj.attr('href');
      if ( selector == '#AddedServices' ) {
        $('#ServicesPanes').hide();
        $('#AddedServices').show();
      } else {
        $('#ServicesPanes>div').hide();
        $(selector).show();
      }
      return false;
    });
    $('#AddService a.button').livequery('click', function() {
      self.displayPane( $('#ServicePicker').val(), '#AddedServices' );
      return false;
    });
  });
};

$(function() {
  $('a.switch_visible_forms').click(function() {
    $('div.switchable_form').hide();
    $($(this).attr('href')).show();
    return false;
  });

  // Fix checkbox and radio issues in IE
  if ($.browser.msie) {
    $('input[type=checkbox],input[type=radio]').click(function () {
      this.blur();
      this.focus();
    });
  }

  $('#MainPanel').focus(); // gives keyboard focus to the innned scroll pane so that up/down etc work

//      $('#ConfigModal').show();
  //  MultiTabModal.showTab($('#ConfigModal'), 'SelectModalGroupTeam');
});

function track_inputs_on_this_form(form_el) {
  form_el.find('a.submit_form').addClass('disabled_button');
  form_el.find('input,textarea').keydown(function(e) {
    $(this).parents('form').find('a.submit_form').each(function(i) {
      $(this).removeClass('disabled_button');
      if ($(this).html() == "Saved") {
        $(this).html('Save');
      }
      if ($(this).html() == "User added") {
        $(this).html('Add user');
      }
    });
  });
  form_el.find('input[type=radio],input[type=checkbox],select').change(function(e) {
    $(this).parents('form').find('a.submit_form').each(function(i) {
      $(this).removeClass('disabled_button');
      if ($(this).html() == "Saved") {
        $(this).html('Save');
      }
      if ($(this).html() == "User added") {
        $(this).html('Add user');
      }
    });
  });
}


function recover_form_from_success(form_el) {
  form_el.find('a.disabled_button').each(function(i) {
    if ($(this).html() == 'Saving...') {
      $(this).html('Saved');
    }
    if ($(this).html() == 'Adding user...') {
      $(this).html('User added');
    }
  });
}

function recover_form_from_errors(form_el) {
  form_el.find('a.disabled_button').each(function(i) {
    if ($(this).html() == 'Saving...') {
      $(this).html('Save');
    }
    if ($(this).html() == 'Adding user...') {
      $(this).html('Add user');
    }
    $(this).removeClass('disabled_button');
  });
}