var activeThumb, thumbTimer, dropdownTimer, rotateTimer, storyTextOffset;

Image1 = new Image(1, 1);
Image1.src = "http://www.askjolenestatic.com/img/dropdown_edge.png";

$(document).ready(function () {

  highlightLabels();

  if ($("div#story_text").length > 0) {
    storyTextOffset = $("div#story_text").position().top + 50;
  }

  $("div.dropdown, div.advanced_dropdown, label").disableSelection();

  if ($("div#advanced_options").is(':visible')) {
    $("div.advanced_dropdown").addClass("activedropdown");
  }

  $("h1#logo").click(function () {
    location.href = 'http://www.askjolene.com/';
  });

  /**
   * Topmenu
   *
   */
  $("ul#top_menu li").hover(function () {
    $(this).addClass("topmenu_hover");
  },
  function () {
    $(this).removeClass("topmenu_hover");
  });
  $("ul#top_menu li").click(function () {
    location.href = $("a", this).attr("href");
    return false;
  });

  /**
   * Icons in thumb
   *
   */

  $("a.thumb_icon_report").click(function () {
    reportModal($(this).attr("href"));
    return false;
  });
  $("a.thumb_icon_remember").click(function () {
    window.open($(this).attr("href"), "bookmarkwindow");
    return false;
  });

  /**
   * Rollover thumbs
   *
   */
  $("td#movies_results_td div.thumbcontainer, td#galleries_results_td div.thumbcontainer, td#directory_results_td div.thumbcontainer, div#content_suggestions div.thumbcontainer").hover(function () {
    activeThumb = $(this).attr("id").substr(3);
    if (activeThumb != '') {
      thumbLoop(activeThumb, 2, null);
    }
    $("div.thumb_icons", this).show();
  },
  function () {
    window.clearTimeout(thumbTimer);
    activeThumb = null;
    var thisThumb = $(this).attr("id").substr(3);
    var thisUrl = "http://thumbs.askjolenestatic.com/" + thisThumb.replace("_", "/") + "t.jpg";
    $("img.thumb", this).attr("src", thisUrl);
    $("div.thumb_icons", this).hide();
  });

  /**
   * Search option dropdowns
   *
   */
  $("div.dropdown_options").each(function () {
    $(this).prepend("<div class=\"top_left\"></div><div class=\"top_right\"></div>").append("<div class=\"bottom_left\"></div><div class=\"bottom_right\"></div>");
  });

  $("div.dropdown").hover(function () {
    $(this).addClass("activedropdown");
  },
  function () {
    if ($("div.dropdown_options", this).is(':visible')) {
      var elem = this;
      dropdownTimer = window.setTimeout(function () {
        $("div.dropdown_options", elem).hide();
        $(elem).removeClass("activedropdown");
      },
      250);
    }
    else {
      $("div.dropdown_options", this).hide();
      $(this).removeClass("activedropdown");
    }
  }).click(function () {
    if ($("div.dropdown_options", this).is(':visible')) {
      $("div.dropdown_options", this).hide();
    }
    else {
      $(this).addClass("activedropdown");
      $("div.dropdown_options", this).show();

      if ($("div.dropdown_options", this).width() < $(this).width()) {
        $("div.dropdown_options", this).width($(this).width());
      }

      /* The following stupid hack is courtesy of IE6 */
      halfWidth = Math.ceil($("div.dropdown_options", this).width() / 2);
      $("div.dropdown_options div", this).css("width", halfWidth);

    }
  });
  $("div.dropdown_options").mouseenter(function () {
    window.clearTimeout(dropdownTimer);
  });

  /**
   * Advanced search
   *
   */
  $("div.advanced_dropdown").hover(function () {
    $(this).addClass("activedropdown");
  },
  function () {
    if (!$("div#advanced_options").is(':visible')) {
      $("div.advanced_dropdown").removeClass("activedropdown");
    }
  }).click(function () {
    if ($("div#advanced_options").is(':visible')) {
      closeAdvancedPanel();
    }
    else {
      openAdvancedPanel();
    }
    return false;
  });

  /**
   * Advanced search dropdowns
   *
   */
  $("table#advanced_options_table a").click(function () {
    dropdownAction = $(this).attr("class").split("_");
    $("#" + dropdownAction[0] + "_dropdown span").html($(this).html());
    $("#" + dropdownAction[0]).val(dropdownAction[1]);
    $("div.dropdown").removeClass("activedropdown");
    $(".dropdown_options").hide();
    return false;
  });

  /**
   * Search box dropdown (language for cams)
   *
   */
  $("div.search_options a").click(function () {
    dropdownAction = $(this).attr("class").split("_");
    $("#" + dropdownAction[0] + "_dropdown strong").html($(this).html());
    $("#" + dropdownAction[0]).val(dropdownAction[1]);
    $("strong").removeClass("activedrop");
    $(".dropdown_options").hide();

    if (!$("div#advanced_options").is(':visible')) {
      $("div#advanced_options input").remove();
    }

    $("#searchbox_top").submit();
  });

  // Highlight label of active options
  $("form#searchbox_top div.search_options input").click(function () {
    highlightLabels();
  });

  /**
   * Focus searchbox on homepage
   *
   */
  if ($("input.home_qr").length) {
    $("#searchbox_home input.home_qr").focus();
  }

  /**
   * Aavoid the submit.x and submit.y stuff that an image button insists on sending along
   *
   */
  $("form.searchbox input.q_submit").click(function () {
    if (!$("div#advanced_options").is(':visible')) {
      $("div#advanced_options input").remove();
    }

    $("#" + this.form.id).submit();
    return false;
  });

  /**
   * Hover function story "bladwijzer"
   *
   */
  $("div#story_text").hover(function () {
    $(this).addClass("active");
  },
  function () {
    $(this).removeClass("active");
  });
  $("div#story_text").mousemove(function (e) {
    $("div#story_text").css({
      backgroundPosition: "0px " + (e.pageY - storyTextOffset) + "px"
    });
  });

  /**
   * Voting
   *
   */
  $(".map_element").hover(function () {
    var vote = $(this).attr("alt").split("_");
    $("#vote_wrapper").css("background-image", "url('/img/rating_big_" + vote[0] + ".png')");
  },
  function () {
    $("#vote_wrapper").css("background-image", "url('/img/rating_big_" + $("#vote_wrapper img").attr("alt") + ".png')");
  });

  // Register a vote
  $("area.map_element").click(function () {
    var vote = $(this).attr("alt").split("_");
    $.post("/storyvote.php", {
      vote: vote[0],
      storyid: vote[1]
    });
    $("#vote_wrapper").fadeOut("fast", function () {
      $("#thanks_for_voting").fadeIn("fast");
    });
  });

  // Automcomplete
  if ($("input.home_qr").length) {
    $("input.home_qr").autocomplete({
      serviceUrl: "/autocomplete.php",
      params: { s:'movies' }
      
    });
  }
  if ($("form#searchbox_top input.qr").length) {
    $("form#searchbox_top input.qr").autocomplete({
      serviceUrl: "/autocomplete.php",
      params: { s:$("body").attr("class") }
    });
  }
  
  // Tourpage clicks
  if($("#tourpage").length) {
    $("#tourpage").click( function() {
      window.open($("div.tourpage_text a", this).attr("href"));
      return false;
    });
  }

  // Make textad block clickable
  $(".sponsor_textad").click( function() {
    window.open($("a", this).attr("href"));
    return false;
  });
});

function thumbLoop(thisThumb, counter, setURL) {
  if (setURL != null) {
    $("div#tmb" + thisThumb + " img.thumb").attr("src", setURL);
  }

  var newUrl = "http://lw-tube.llestatic.com/rot/" + thisThumb.replace("_", "/") + "_" + counter + "t.jpg";

  var img = new Image();

  var startTime = new Date().getTime();

  $(img).load(function () {
    if (thisThumb == activeThumb) {
      counter++;
      var myDelay = 500 - (new Date().getTime() - startTime);
      if (myDelay < 1 || setURL == null) myDelay = 1;
      thumbTimer = window.setTimeout("thumbLoop('" + thisThumb + "', " + counter + ", '" + newUrl + "')", myDelay);
    }
  }).error(function () {
    if (counter == 1) {
      activeThumb = null;
    }
    if (thisThumb == activeThumb) {
      thumbTimer = window.setTimeout("thumbLoop('" + thisThumb + "', 1)", 500);
    }
  }).attr('src', newUrl);
}

function closeAdvancedPanel() {
  $("input#adv").val("0");
  $("div#advanced_options").hide();
}

function openAdvancedPanel() {
  $("div#advanced_options").show();
  $("input#adv").val("1");
}

function reportModal(reportInfo) {
  var searchType = $("#s").val();

  $("div#report").load("/view_report.php", {
    reportinfo: reportInfo,
    searchtype: searchType
  },
  function () {

    $("#close_report").hover(function () {
      $(this).addClass("active");
    },
    function () {
      $(this).removeClass("active");

    }).click(function () {
      $("#report").hide();
    });

    $("#report_cancel").click(function () {
      $("#report").hide();
    });

    jQuery(document).bind('click', checkCloseReportModal);

    var reportTop = ($(window).height() / 2) - ($("#report").height() / 2);
    var reportLeft = ($(window).width() / 2) - ($("#report").width() / 2);

    $("#report").css({
      'top': reportTop,
      'left': reportLeft
    });
    $("#report").show();

    $("#report_form").live("submit", function () {
      $.ajax({
        url: "/submit_report.php",
        data: $("#report_form").serialize(),
        success: closeReportModal,
        error: closeReportModal
      });

      return false;
    });
  });
}

function closeReportModal() {
  var wrapperHeight = $("#report_wrapper").height();
  $("#thanks").height(wrapperHeight);
  $("#report_wrapper").hide();
  $("#thanks").show();
  setTimeout(function () {
    $("#report").fadeOut("slow");
  },
  1500);
}

// Close report modal when user clicks outside of it
function checkCloseReportModal(e) {
  var target = jQuery(e.target);
  if (target.is('div#report') || target.parents('div#report').length) {
    return;
  }

  $("div#report").hide();
  jQuery(document).unbind('click', checkCloseReportModal);

  return false;
}

function highlightLabels() {
  $("form#searchbox_top div.search_options input").each(function () {
    if ($("#" + $(this).attr("id") + ":checked").length > 0) {
      $("form#searchbox_top div.search_options label[for=" + $(this).attr("id") + "]").addClass("option_on");
    }
    else {
      $("form#searchbox_top div.search_options label[for=" + $(this).attr("id") + "]").removeClass("option_on");
    }
  });
}

// Avoid dropdown items being selected
jQuery.fn.extend({
    disableSelection : function() {
        this.each(function() {
            this.onselectstart = function() { return false; };
            this.unselectable = "on";
            jQuery(this).css('-moz-user-select', 'none');
        });
    }
});
