// Hack to automagically send the authenticity token with all JQuery AJAX requests
// From http://henrik.nyh.se/2008/05/rails-authenticity-token-with-jquery
// Also see http://www.viget.com/extend/ie-jquery-rails-and-http-oh-my
// And http://pastie.org/540207 (added in Sep '09)

(function($) {

  $(document).ajaxSend(function(event, request, settings) { //Set request headers globally

    request.setRequestHeader("Accept", "text/javascript");
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    if (settings.type.toUpperCase() == 'GET' || typeof(AUTH_TOKEN) == "undefined") return;
    // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
    settings.data = settings.data || "";
    settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
  });

})(jQuery);

// MonAssoc specifics

var Monassoc = {
  init: function() {
    Monassoc.add_js_class_to_body();
    Monassoc.activate_help_overlay();
    Monassoc.activate_search_box();
    Monassoc.activate_subtabs();
    Monassoc.openid_choice();
    Monassoc.make_flash_appear();
    Monassoc.track_marketing_links_to_front_site();
    Monassoc.Utilities.textInputDynamicValue('#sidebar input[type="text"]');
    Monassoc.Calendar.init();
  },
  add_js_class_to_body: function() {
    $("body").addClass("js_enabled");
  },
  activate_help_overlay: function() {
    var button = $("#topbar .help a"),
        button_icon = button.children("img"),
        button_icon_src = button_icon.attr("src"),
        help_overlay = $("#help_overlay"),
        help_overlay_content = help_overlay.children().hide(),
        help_overlay_title = $('#help_overlay_title'),
        help_overlay_close_button = $("#help_overlay_close_button"),
        document_height = $(document).height(),
        closeHelp = function(){
          help_overlay.fadeOut(200, function(){
            if(AUTO_SHOW_HELP){
              $.post("/help_seen.json");
              help_overlay_title.text("Aide à l'utilisation de votre site web");
              help_overlay_close_button.attr("src","/images/help/overlay/header_button/close.png");
            }
          });
          return false;
        };
    button
      .click(function(e){
        e.preventDefault();
        help_overlay.fadeIn(200, function(){
          help_overlay_content.fadeIn(300);
        });
      })
      .hover(
        function(){
          button_icon.attr("src", "/images/help/button/hover.png");
        },
        function(){
          button_icon.attr("src", button_icon_src);
        }
      );
    help_overlay.height(document_height);
    help_overlay_content
      .find("h1 a")
      .click(closeHelp);
    help_overlay.click(function(e){
      if(!$(e.target).is("#help_overlay")) return;
      closeHelp();
    });
    if(AUTO_SHOW_HELP){
      help_overlay_title.text("Bienvenue sur votre nouveau site web !");
      help_overlay_close_button.attr("src","/images/help/overlay/header_button/first_use.png");
      button.click();
    }
  },
  activate_search_box: function() {

    var
      topbar_form = $("#search form"),
      topbar_form_label = topbar_form.find("label").text(),
      inputs = topbar_form.find("input"),
      // TODO: change URL path with choosed color scheme
      arrow_path = "/themes/lightblue/images/topbar/search/arrow/",
      default_search_arrow = arrow_path + "inactive.png",
      active_search_arrow = arrow_path + "active.png";

    function toggle_form(){
      topbar_form
        .toggle()
        .prev()
          .children("img")
            .attr("src", topbar_form.is(":visible") ? active_search_arrow : default_search_arrow)
          .end()
        .parent()
          .toggleClass("active");
      inputs
        .slice(0,1)
          .focus();
      return false;
    }

    topbar_form
      .hide()
      .before(
        $.create("a")
          .attr("href","#")
          .text(topbar_form_label)
          .append(
            $.create("img").attr({src: default_search_arrow, alt: ""})
          )
          .click(toggle_form)
      );

    $(document).click(function(e){
      if(topbar_form.is(":visible") && $(e.target).is(":not(#search form *)")) toggle_form();
    });

  },
  activate_subtabs: function(){
    var
      activeClass = "active",
      edit_tabs = $("#edit_tabs"),
      tab_links = edit_tabs.find("a"),
      sections = edit_tabs.nextAll(),
      make_tab_link_active = function(tab_link) {
        tab_link.addClass(activeClass).attr("title","Onglet courant");
      },
      focus_on_first_field = function() {
        $(this).find("label+*").eq(0).focus()
      },
      activate_tab = function(url) {
        if (!url || url.length<2 || !$(url).size()) {
          url = tab_links.eq(0).attr("href");
          if(url == undefined)
            return;
        }
        // window.location = url;
        // window.location = "#";
        if ($(url).is(":visible")) {
          focus_on_first_field.call($(url));
          return;
        }
        tab_links.removeClass(activeClass).removeAttr("title");
        sections.hide();
        make_tab_link_active($("a[href="+url+"]"));
        $(url).fadeIn(250, focus_on_first_field);
      };
    make_tab_link_active(tab_links.eq(0));
    sections.not(":first").hide();
    tab_links
      .click(function(e){
        e.preventDefault();
        var
          clicked_link = $(this),
          url = clicked_link.attr("href");
        activate_tab(url);
      });
    activate_tab(window.location.hash);
  },
  openid_choice: function(){
    if($('#openid_choice').size() > 0)
      openid.init('user_session[openid_identifier]');
  },
  make_flash_appear: function(){
    $("#flash")
      .children()
        .append(
          $.create("a")
            .attr("href","#")
            .text("Masquer")
            .click(function(e){
              e.preventDefault();
              $(this).parents().eq(1).slideUp(400);
            })
        )
      .end()
      .hide()
      .slideDown(250);
  },
  track_marketing_links_to_front_site: function(){
    //  google analytics multiple domain tracking, with campaign tracking
    $("a.marketing").click(function(){
      var destination = this.href+"?utm_source=monassoc_site&utm_medium="+this.id;
      monassocTracker._link(destination);
      return false;
    });
  }
}

Monassoc.Calendar = {
  init: function(){
    Monassoc.Calendar.activate_event_hovering();
  },
  activate_event_hovering: function(){
    var
      cell_events = $("#calendar td > div"),
      activeClass = "active";
    cell_events
      .hide()
      .parent()
        .hover(
          function(){
            var
              tooltip = $(this).children("div"),
              date = tooltip.prev(),
              date_position = date.position();
            cell_events.hide();
            date.addClass(activeClass);
            tooltip
              .css({
                "left": date_position.left + 7,
                "bottom": date_position.top + 40
              })
              .fadeIn(($.support.opacity) ? 150 : 0);
          },
          function(){
            $(this)
              .children("div")
                .fadeOut(($.support.opacity) ? 300 : 0)
                .prev()
                  .removeClass(activeClass);
          }
        );
  }
}

Monassoc.Utilities = {
  textInputDynamicValue: function(input_selector, text_to_use, def_class){
    if (text_to_use == undefined) text_to_use = 'title';
    if (def_class == undefined) def_class = 'hint';
    $(input_selector).each(function() {
      var dynamic_value
      switch (text_to_use) {
        case 'title' :
          dynamic_value = $(this).attr('title');
          break;
        case 'value' :
          dynamic_value = $(this).attr('value');
          break;
        default :
          dynamic_value = text_to_use;
      }
      $(this).attr('value', dynamic_value).addClass(def_class)
      .focus(function() {
        if (this.value == dynamic_value) {
          this.value = '';
          $(this).removeClass(def_class);
        }
      })
      .blur(function() {
        if (this.value == '') {
          this.value = dynamic_value;
          $(this).addClass(def_class);
        };
      });
    });
  }
}

$(Monassoc.init);