function toggleVisibility(container, visible) {
  if (visible) {
    if (!$(container).is(":visible")) {
      $(container).show("blind");
    }
  } else {
    if ($(container).is(":visible")) {
      $(container).hide("blind");
    }
  }
}

function populateReportFilter(data) {
  $("div#report_filters form#apply_report_filters").find(":input[id][id!=report_filter_id]").each(function() {
    var attribute_name = $(this).attr("id").replace("report_filters_", "");

    if (attribute_name.match(/_(day|month|year)$/)) {
      var date_suffix = /_(day|month|year)$/.exec(attribute_name);
      $(this).val(data.report_filter.options[attribute_name.replace(date_suffix[0], "")][date_suffix[1]]);
    } else if (attribute_name.match(/countries_([a-z]+)/)) {
      var country = /countries_([a-z]+)/.exec(attribute_name)[1];
      if ((country == "prompt" && (!$.isArray(data.report_filter.countries) || data.report_filter.options.countries.length == 0)) || $.inArray(country.toUpperCase(), data.report_filter.options.countries) != -1) {
        $(this).attr("checked", true);
        $(this).closest("li").addClass("selected");
      } else {
        $(this).removeAttr("checked");
        $(this).closest("li").removeClass("selected");
      }
    } else {
      $(this).val(data.report_filter.options[attribute_name]);
    }
  });
  $("div#report_filters form#apply_report_filters a#destroy_report_filter").show();
  if (data.report_filter["default"] == true) {
    $("div#report_filters form#apply_report_filters a#update_report_filter").hide();
  } else {
    $("div#report_filters form#apply_report_filters a#update_report_filter").show();
  }
}

function initialisePage() {
  $("body>div#flash:first").delay(500).show("blind", { direction: "vertical" }, 2000).delay(4000).hide("blind", { direction: "vertical" }, 2000);

  $("input[type=checkbox].checkall").click(function() { $(this).parents("form").find("input[type=checkbox]").attr("checked", this.checked); });

  $("select#table_header_list").change(function() { $("select#footer_list").val($(this).val()); });
  $("select#footer_list").change(function() { $("select#table_header_list").val($(this).val()); });

  if (!$.browser.msie || parseInt($.browser.version) >= 8) {
    $("input[type=submit].orange").each(function() {
      var attributes = $.getAttributes($(this));
      attributes["className"] = attributes["class"];
      $.each([ "class", "style", "type" ], function() { delete attributes[this]; });
      $(this).replaceWith($("<button><span><span>" + $(this).val() + "</span></span></button>").attr(attributes));
    });
    $("a.orange").wrapInner("<span><span></span></span>");
  }

  $("#user_administrator").change(function() {
    toggleVisibility($("#user_partner_id").parent(), $(this).val() != "true");
    toggleVisibility($("#user_site_ids").parent(), !($(this).val() == "true" || $("#user_partner_administrator").val() == "true"));
  }).change();

  $("#user_partner_administrator").change(function() {
    toggleVisibility($("#user_site_ids").parent(), !($(this).val() == "true" || $("#user_administrator").val() == "true"));
  }).change();

  $("#organisation_whois_update").click(function() {
    $("#organisation_whois").html("<p>Loading…</p>").load(this.href);
    return false;
  });

  var contactable_textbox_lists = [];
  $("input[type=text].contactable_select").each(function() {
    t = new TextboxList(this, { unique: true,
                                bitsOptions: { editable: { addOnBlur: true } },
                                plugins: { autocomplete: { method: 'binary' } } });
    if ($(this).hasClass("error")) {
      t.getContainer().addClass("error");
    }
    contactable_textbox_lists.push(t);
  });

  var site_id = $('#site_id').val();
  if (site_id && contactable_textbox_lists.length > 0) {
    $.getJSON(Routing.site_contactables_path({ site_id: site_id }), function(data, textStatus) {
      if (textStatus == "success") {
        $.each(contactable_textbox_lists, function() { this.plugins['autocomplete'].setValues(data); });
      }
    });
  }

  $("a.export_popup").open({
    width: 400,
    height: 280,
    left: ($(window).width() - 400) / 2,
    top: ($(window).height() - 180) / 2,
    scrollbars: false,
    directories: false,
    menubar: false,
    toolbar: false,
    status: false,
    resizable: false
  });

  $('a.close_popup').click(function() { window.close(); });

  var refresh_url = $("div.export a#refresh").attr("href");
  if (refresh_url) {
    $.poll(function(retry) {
      $.getJSON(refresh_url.replace(/(\.ajax)?$/, ".json"),
        function(data) {
          if (data["export"].status == 'completed') {
            $("div#status").fadeOut("slow", function() {
              $(this).html('<p id="download"><a class="csv" href="' + refresh_url.replace(/(\.ajax)?$/, ".csv") + '" title="Download the export file">Download</a></p><p><small>After clicking the download link you can close this window.</small></p>').fadeIn("slow");
            });
          } else {
            if (data["export"].status == 'error') {
              $("div#status").fadeOut("slow", function() {
                $(this).html('<p class="error">An error occurred while creating your export.</p>').fadeIn("slow");
              });
            } else {
              $("p#last_checked_at").html("<small>Last checked: " + data["export"].status_last_checked_at_to_s + "</small>").effect("bounce", { times: 3 }, 300);
              retry();
            }
          }
        }
      );
    });
  }

  $("div.pagination.ajax a").click(function(event) {
    var qs = $.deparam.querystring($(this).attr("href"));
    $.bbq.pushState({ page: qs["page"] });
    event.preventDefault();
  });

  $("a.sort.ajax").click(function(event) {
    var qs = $.deparam.querystring($(this).attr("href"));
    $.bbq.pushState({ sort_by: qs["sort_by"], sort_direction: qs["sort_direction"] });
    event.preventDefault();
  });

  $("a.filter.ajax").click(function(event) {
    var url = $(this).attr("href");
    var qs = $.deparam.querystring(url);
    var newUrl = $.param.querystring(url, {
      sort_by: $.bbq.getState("sort_by") || qs["sort_by"],
      sort_direction: $.bbq.getState("sort_direction") || qs["sort_direction"]
    });
    $(this).attr("href", newUrl);
  });

  $('.tipsy').tipsy({gravity: 'w'});

  $("ul.checklist li").each(function() {
    if ($(this).find(":checkbox").attr("checked")) $(this).addClass("selected");
  });

  $("ul.checklist input:checkbox").click(function(e) {
    var listItem = $(this).closest("li");
    listItem.toggleClass("selected", $(this).attr("checked"));
    if ($(this).is(":checked")) {
      if (listItem.hasClass("prompt")) {
        $(this).parents("ul").find("li:not(.prompt) input[type=checkbox]:checked").each(function() {
          $(this).removeAttr("checked");
          $(this).closest("li").removeClass("selected");
        });
      } else {
        var promptCheckbox = $(this).parents("ul").find("li.prompt input[type=checkbox]");
        if (promptCheckbox.is(":checked")) {
          promptCheckbox.removeAttr("checked");
          promptCheckbox.closest("li").removeClass("selected");
        }
      }
    }
  });
}

function loadAjaxContent(url) {
  var qs = $.deparam.querystring(url);
  var newUrl = $.param.querystring(
    $.param.fragment(url, "#", 2), {
      page: $.bbq.getState("page") || qs["page"],
      sort_by: $.bbq.getState("sort_by") || qs["sort_by"],
      sort_direction: $.bbq.getState("sort_direction") || qs["sort_direction"],
      format: "ajax"
      }
    ).replace(/#$/, '');

  $("#ajax_content").mask("Loading…");
  $('html, body').attr("scrollTop", 0);

  $("#ajax_content").load(newUrl, function(responseText, textStatus, xmlHttpRequest) {
    if (textStatus == "success") {
      initialisePage();
    } else {
      if (xmlHttpRequest.readyState !== 0 && xmlHttpRequest.status !== 0) {
        $("#ajax_content").html('<p class="error">An error occurred while processing your request.</p>');
      }
    }
    $("#ajax_content").unmask();
  });
}

$(document).ready(function() {
  initialisePage();

  $("div#report_filters form#apply_report_filters select#report_filter_id").change(function() {
    if ($(this).val()) {
      $("div#report_filters form#apply_report_filters h3 span").show();
      $.getJSON(
        Routing.formatted_site_report_filter_path({
          site_id: $("#report_filters_site_id").val(),
          id: $(this).val(),
          format: "json"
        }),
        function(data) {
          populateReportFilter(data);
          $("div#report_filters form#apply_report_filters h3 span").hide();
        }
      )
    } else {
      $("div#report_filters form#apply_report_filters a#update_report_filter, div#report_filters form#apply_report_filters a#destroy_report_filter").hide();
    }
  });
  $("div#report_filters form#apply_report_filters select#report_filter_id").trigger("change");

  $("div#report_filters form#apply_report_filters :input[id!=report_filter_id]").change(function() {
    $("div#report_filters form#apply_report_filters select#report_filter_id").val("");
    $("div#report_filters form#apply_report_filters a#update_report_filter, div#report_filters form#apply_report_filters a#destroy_report_filter").hide();
  });

  $("div#report_filters form#apply_report_filters a#update_report_filter").click(function(event) {
    event.preventDefault();

    var params = { _method: "PUT", report_filter: { "default": 1 } };
    params[authenticityTokenName] = authenticityTokenValue;

    $("div#report_filters form#apply_report_filters h3 span").show();

    $.post(
      Routing.formatted_site_report_filter_path({
        site_id: $("#report_filters_site_id").val(),
        id: $("div#report_filters form#apply_report_filters select#report_filter_id").val(),
        format: "json"
      }),
      params,
      function(data) {
        $("div#report_filters form#apply_report_filters h3 span").hide();
        $("div#report_filters form#apply_report_filters a#update_report_filter").hide();
      }
    );
  });

  $("div#report_filters form#apply_report_filters a#destroy_report_filter").click(function(event) {
    event.preventDefault();

    if (confirm("Are you sure you want to delete this report filter?")) {
      var params = { _method: "DELETE" };
      params[authenticityTokenName] = authenticityTokenValue;
      var reportFilterSelect = $("div#report_filters form#apply_report_filters select#report_filter_id");
      $("div#report_filters form#apply_report_filters h3 span").show();

      $.post(
        Routing.formatted_site_report_filter_path({
          site_id: $("#report_filters_site_id").val(),
          id: reportFilterSelect.val(),
          format: "json"
        }),
        params,
        function(data) {
          $("div#report_filters form#apply_report_filters h3 span").hide();
          reportFilterSelect.find("option[value=" + reportFilterSelect.val() + "]").remove();
          reportFilterSelect.val("");
          $("div#report_filters form#apply_report_filters a#update_report_filter, div#report_filters form#apply_report_filters a#destroy_report_filter").hide();
        }
      );
    }
  });

  $("div#report_filters a#save_report_filter").click(function(event) {
    event.preventDefault();
    $("div#report_filters form#new_report_filter").slideToggle();
  });

  $("div#report_filters form#new_report_filter").submit(function() {
    $("div#report_filters form#new_report_filter h3 span").show();
    $(this).find("#report_filter_options_as_params").val($(this).siblings("#apply_report_filters").serialize());
    $.ajax({
      type: "POST",
      url: $(this).attr("action"),
      data: $(this).serialize(),
      success: function(data) {
        var reportFilterSelect = $("div#report_filters form#apply_report_filters select#report_filter_id");
        if (reportFilterSelect.find("option[value=" + data.report_filter.id + "]").length == 0) {
          $(new Option(data.report_filter.name, data.report_filter.id)).appendTo(reportFilterSelect);
          Array.prototype.sort.call(reportFilterSelect.find("option"), function(a,b) { return $(a).text() > $(b).text() ? 1 : -1; }).appendTo(reportFilterSelect);
        }
        reportFilterSelect.val(data.report_filter.id);
        populateReportFilter(data);
        $("div#report_filters form#new_report_filter h3 span").hide();
        $("div#report_filters form#new_report_filter").slideToggle();
        $("div#report_filters form#apply_report_filters").trigger("submit");
      },
      error: function(request) {
        $("div#report_filters form#new_report_filter h3 span").hide();
        $.each($.parseJSON(request.responseText), function(index, message) {
          var input = $("div#report_filters form#new_report_filter").find("input[id=report_filter_" + message[0] + "]");
          if (input.length) {
            input.addClass("error");
            input.parents("dl").find("label[for=" + input.attr("id") + "]").addClass("error");
          }
        });
      }
    });
    return false;
  });

  $("a.toggle_report_filters").click(function(event) {
    event.preventDefault();

    var container = $("div#report_filters");
    var cookieValue = 0;

    if (container.is(":visible")) {
      container.hide("blind");
      $(this).text("Show report filters");
    } else {
      container.show("blind");
      $(this).text("Hide report filters");
      cookieValue = 1;
    }
    $.cookie("revelations_site_" + $("#report_filters_site_id").val() + "_" + $(this).attr("id"), cookieValue, { expires: 3650, path: "/" })
  });

  $("select#report_filters_from_day,select#report_filters_from_month,select#report_filters_from_year").change(function() {
    $("input#report_filters_period_value").val("");
  });

  $("textarea.ueditor").uEditor({
    containerClass: "ueditor",
    toolbarItems: [ "bold", "italic", "link", "unorderedlist", "orderedlist", "htmlsource" ],
    stylesheet: "/stylesheets/ueditor.css?wtf=" + encodeURIComponent(Math.round(new Date().getTime() / 1000))
  });

  var ajax_url = $("#ajax_url").val();
  if (ajax_url) {
    $(window).bind('hashchange', function(e) { loadAjaxContent(document.location.toString()); });
    loadAjaxContent(ajax_url);
  }
});