(function() {
  jQuery.noConflict();
  var $j = jQuery;

  $j(document).ready(function() {
      // Make enter key on input elements fire the click event of the closest submit button.
      $j('input,select,textarea').keypress(function(e) {
        if (e.which != 13) return;

        var root = $j(this).parent();
        while (root.length > 0) {
          var button = root.find('button');
          if (button.length > 0) {
            button[0].click();
            return false;
          }
          root = root.parent();
        }
      });

      // Don't even try if the browser is older than IE6
      if ($j.browser.msie && $j.browser.version < 6) return;

      // Setup the foldable question lists
      faqList.init();

      //Setup search
      $j("div.search").handleSearch();

      // Hide the comment fields until they're needed.
      $j(".pageComments #postList").hide();
      $j(".pageComments #editPost").hide();
      $j(".pageComments #postComments").togglePostForm();
      $j(".pageComments #postEdit").togglePostForm();

      if ($j("#postEdit").hasClass("notvalid")) {
          $j(".pageComments .notvalid #editPost").show();

          var pscroll = $j(".pageComments .notvalid #editPost").offset().top;
          $j('html,body').animate({ scrollTop: pscroll }, 1000);
      }

      // Animate the anchor links
      $j('a[href*=#]:not(a.no-jump) and not(a[href=#])').click(function() {
          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var $target = $j(this.hash);
              $target = $target.length && $target || $j('[name=' + this.hash.slice(1) +']');
              if ($target.length) {
                  var targetOffset = $target.offset().top;
                  $j('html,body').animate({scrollTop: targetOffset}, 600, "swing");
                  return false;
              }
          }

          return false;
      });

      toolBox.init();
      locationChooser.init();
  });

  /*************************************************
  * Page toolbox
  *************************************************/
  var toolBox = {
      init: function() {
          $j("a.printTool").click(function() { return false; });
          $j("a.listenTool").click(function() { return false; });
          $j("a.rssTool").click(function() { return false; });

          $j(".shareBox").addClass("popup");
          $j(".rssFeeds").addClass("popup");

          // show print and share when js is used
          $j("li.share").show();
          $j("li.print").show();

          // make the share link toggle the share links and hide other functions
          $j(".popupContainer > a.shareTool").click(function() {
              var $popup = $j(this).parent().parent().nextAll(".shareBox");
              if ($popup.is(":visible")) {
                  if ($popup.next("fieldset").is(":visible")) {
                      $popup.next("fieldset").slideUp();
                  }
                  $popup.slideUp();
              }
              else {
                  // hide readspeaker and rss
                  $j(this).parent().parent().next(".rs_div").children().children().remove();
                  $j(this).parent().parent().next(".rs_div").hide();
                  $j(this).parent().parent().nextAll(".rssFeeds").hide();
                  $popup.slideDown();
              }
          });

          // hide other functions when clicking read speaker
          $j(".readspeaker_button").click(function() {
              // hide share and emailForm and rss
              $j(this).parent("ul").nextAll("fieldset").slideUp();
              $j(this).parent("ul").nextAll(".shareBox").slideUp();
              $j(this).parent("ul").nextAll(".rssFeeds").hide();
          });

          // make the rss link toggle the rss links
          $j(".popupContainer > a.rssTool").click(function() {
              var $popup = $j(this).parent().parent().nextAll(".rssFeeds");
              if ($popup.is(":visible")) {
                  $popup.slideUp(); // varför körs inte denna?
                  $popup.hide();
              }
              else {
                  // hide share and emailForm and readspeak
                  $j(this).parent().parent().nextAll(".shareBox").slideUp();
                  $j(this).parent().parent().nextAll("fieldset").slideUp();
                  $j(this).parent().parent().next(".rs_div").children().children().remove();
                  $j(this).parent().parent().next(".rs_div").hide();
                  $popup.slideDown();
              }
          });

          // Hide the email fields, and setup the email button to toggle them.
          $j("fieldset.emailForm ol li.submit input").click(toolBox.sendMail);
          var $emailLink = $j(".shareBox a.share.email");
          $emailLink.click(function() {
              var $emailForm = $j(this).parent().parent().next("fieldset");
              if ($emailForm.is(":visible")) {
                  $emailForm.slideUp();
              }
              else {
                  $emailForm.slideDown();
              }
          });

          // Make the social buttons hide the email fields.
          $j(".shareBox a.share:not(a.email)").click(function() {
              $j(this).parent().parent().next("fieldset").slideUp();
              window.open($j(this).attr("href"), "Share", "toolbar=0,status=0,width=786,height=556");
              return false;
          });

          // Set up print link
          $j(".toolbox a.printTool").click(function() {
              window.print();
              return false;
          });
      },

      /*************************************************
      * Displays the share toolbox
      *************************************************/
      easeIn: function(timerControl, easeBox) {
          timerControl.stopTime();
          var position = easeBox.position();
          easeBox.stop(true)
              .animate({ opacity: "show"/*, left: position.left + 30*/ }, 100, function() {
                  $j(this).show()
                      .css({ opacity: "" });
              });
      },

      /*************************************************
      * Hides the share toolbox
      *************************************************/
      easeOut: function(easeBox, callback) {
          var position = easeBox.position();
          easeBox
              .stop(true)
              .animate({ opacity: "hide"/*, left:position.left - 30*/ }, 100, function() {
                  $j(this)
                      .hide()
                      .css({ opacity: "" });
                  callback.call();
              });
      },

      /*************************************************
      * Hides the share box after a delay.
      *************************************************/
      timedEaseOut: function(timerControl, easeBox, interval, callback) {
          timerControl.stopTime().oneTime(interval, function() {
              toolBox.easeOut(easeBox, callback);
          });
      },

      /*************************************************
      * Sends the sharing mail via ajax call.
      *************************************************/
      sendMail: function() {
          var $this = $j(this);
          var currentUrl = window.location.href;
          var $form = $this.parent().parent().parent("fieldset");
          var link = currentUrl;

          if ($form.parent().parent().hasClass("faqContent")) {
              link = currentUrl + $form.parent().parent().prev("h3").children("a").attr("href");
          }
          var fromVal = $form.children("ol").children(".from").children("input").val();
          var emailVal = $form.children("ol").children(".email").children("input").val();
          var messageVal = $form.children("ol").children(".message").children("textarea").val();

          $j.ajax({
              type: "POST",
              url: currentUrl,
              data: ({
                  method: "sendMail",
                  from: fromVal,
                  email: emailVal,
                  message: messageVal,
                  link: link
              }),
              datatype: "html",
              success: function(data) {
                  if (data != "") {
                      $form.children(".formError").html(data).show();
                  }
                  else {
                      $form.children(".formError").hide();
                      $form.slideUp();
                      // empty the form
                      $form.children("ol").children(".from").children("input").val("");
                      $form.children("ol").children(".email").children("input").val("");
                      $form.children("ol").children(".message").children("textarea").val("");
                  }
              },
              error: function() {
                  // TODO:
                  $this.parent("fieldset").hide().next(".share-error").show();
              }
          });
          return false;
      }
  };

  /*************************************************
  * Foldable question lists
  *************************************************/
  var faqList = {
      init: function() {
          $j("#content .faqItem .faqContent").hide();

          var url = document.location.href;
          if (url.match("#")) {
              $j("#content #" + url.split("#")[1] + ".faqItem .faqContent").show();
              var pscroll = $j("#content #" + url.split("#")[1] + ".faqItem .faqContent").parent("li").offset().top;
              $j('html,body').animate({ scrollTop: pscroll }, 1000);
          }



          // Setup the visibility toggle functions.
          $j("#content .faqItem > h3").toggle(function() {
              $j(this).parent().addClass("selected");
              $j(this).parent().children(".faqContent").slideDown();
              $j(this).children("a").addClass("active");
              $j(this).parent().children(".faqContent").children(".toolbox").children(".shareBox").hide();
              $j(this).parent().children(".faqContent").children(".toolbox").children(".emailForm").hide();
              return false;
          },
          function() {
              $j(this).parent().removeClass("selected");
              $j(this).parent().children(".faqContent").slideUp();
              $j(this).children("a").removeClass("active");
          });

          // Make the question print button hide all the other questions before
          // showing the browser print dialog.
          $j(".faqContent .toolbox a.printTool").click(function() {
              $j(".faqItem").addClass("noPrint");
              $j(".faqTopic > a").addClass("noPrint");
              $j(this).parents(".faqItem").removeClass("noPrint");
              window.print();
              return false;
          });
      }
  };

  /*************************************************
  * Location Chooser
  *************************************************/
  var locationChooser = {
      /*************************************************
      * Init the location chooser data.
      * Convert the unsorted list to a dropdown box.
      *************************************************/
      init: function() {
          // Create paragraph that wraps the select
          var pElm = $j(document.createElement("p"));

          // Create a label for the select
          if($j(".selectable h3").attr("title")) {
              var labelElm = $j(document.createElement("label"));
              labelElm.text($j(".selectable h3").attr("title"));
              pElm.prepend(" ").prepend(labelElm);
          }

          // Render the select element and attach change event.
          pElm.insertBefore(".selectable").append($j(".selectable").renderSelect("selectMunicipality"));
          $j("#selectMunicipality").change(function() {
              locationChooser.change($j(this), null);
              });

          // Set the label for the created dropdown.
          if(labelElm){
              labelElm.attr("for", $j("#selectMunicipality").attr("id"));
          }
      },

      /*************************************************
      * Called when the current item in the location is changed.
      * Update the current location.
      *************************************************/
      change: function(elem) {
          var selElm = elem.find("option:selected");
          if(selElm.val() == elem.find("option.no-choice").val()) {
              locationChooser.clear(selElm.val());
          } else {
              locationChooser.load(selElm.val());
          }
      },

      /*************************************************
      * Clear the current location.
      *************************************************/
      clear: function(href) {
          document.location.href = href;
      },

      /*************************************************
      * Set the current location.
      *************************************************/
      load: function(href) {
          document.location.href = href;
      }
     };

     /*************************************************
     * Search.
     *************************************************/
     jQuery.fn.handleSearch = function() {
     	if (this.size() > 0) {
          // div.search
          var cont = this;

          cont.find("ul li div.mapcanvas").each(function() {
              $j(this).parent("li").addClass("with-map");
              //              $(this).parent("dl").parent("dd").prev("dt").addClass("with-map");
              //              $(this).parent("dl").parent("dd").next("dd.date").addClass("with-map");
              //              $(this).css("margin-top", "-" + $(this).parent("dl").parent("dd").prev("dt").height() + "px");

              //              var lastDD = $(this).parent("dl").parent("dd").next("dd.date").next("dd.cached-search-result");
              //              var allHeight = $(this).parent("dl").parent("dd").prev("dt").height() + $(this).parent("dl").parent("dd").height() + lastDD.height();
              //              if ($(this).height() > allHeight) {
              //                  lastDD.height(lastDD.height() + $(this).height() - allHeight);
              //              }
          });
     	}
     	return this;
     };

  /*************************************************
  * Convert an unsorted list to a select element.
  *************************************************/
  jQuery.fn.renderSelect = function(selectId) {
      // Create elements
      var selElm = $j(document.createElement("select"));

      selElm.attr("id", selectId);

      // Append default option
      var firstOptionElm = $j(document.createElement("option"));
      firstOptionElm.attr("value", $j(".no-location", this).attr("href"));
      firstOptionElm.append(this.find(".first-choice").text());
      firstOptionElm.addClass("no-choice");
      firstOptionElm.appendTo(selElm);

      // Loop through links in ul
      this.find(".region").each(function() {
          // Create option group
          var optGrpElm = $j(document.createElement("optgroup"));
          $j(optGrpElm).attr("label", $j("p", this).text());

          $j("a", this).each(function() {
              var optElm = $j(document.createElement("option"));

              // Add attributes and append to group
              optElm.attr("value", $j(this).attr("href")).append($j(this).text());
              if($j(this).hasClass("selected")) optElm.get(0).selected = true;
              if($j(this).hasClass("disabled")) optElm.addClass("disabled");

              optElm.appendTo(optGrpElm);
          });

          optGrpElm.appendTo(selElm);
      });

      // Remove holder
      this.remove();

      return selElm;
  };

  jQuery.fn.togglePostForm = function() {
      if (this.size() > 0) {
          this.children("a").toggle(function() {
              $j(this).addClass("active");
              $j(this).parent().children("fieldset").show();
              $j(this).parent().children("ul").show();
              return false;
          }, function() {
              $j(this).removeClass("active");
              $j(this).parent().children("fieldset").hide();
              $j(this).parent().children("ul").hide();
              $j(this).removeClass("active");
          });
      }
      return this;
  };

  jQuery.fn.log = function(msg) {
      if (console) console.log("%s: %o", msg, this);
      return this;
  };

  jQuery.scrollWindow = function(target, callback){
    jQuery.scrollTo(target, 600, {easing:'swing', axis:'y', onAfter: callback});
  };
})();