var counter     = 10;
var scroll_selector = "scroll_up";
var scroll_ul   = null;
var sf_suffix   = "";
var li_link     = false;

$(document).ready(function(){
  
  if ($("#list_selector").klikselect({autoSubmit:"#preselect", width:"198px"}).length > 0) {
    adapt_spalte(2);
    
    $("#preselect").submit(function(ev) {
      var action = $(this).attr("action");  
      location.href =  action.substring(0, action.lastIndexOf("/")) + "/" +  $("#list_selector").val() + sf_suffix;
      ev.preventDefault();
    });
  }
  
  if ($("#monat_selector").klikselect({autoSubmit:"#preselect", width:"90px"}).length > 0) {
      adapt_spalte(2);
      $("#ort_selector").klikselect({autoSubmit:"#preselect", width:"150px", className:"klikSelect2"});
      var additional_class = section_name != "theaterverlag"
                             ? "" : " clear";
      $("#jahr_selector").klikselect({autoSubmit:"#preselect", width:"90px", className:"klikSelect2" + additional_class});
      $("#kategorie_selector").klikselect({autoSubmit:"#preselect", width:"150px"});
  }
  
  if ($("#news_kopf").length > 0) {
    adapt_spalte(1);
  }
  
  $("a.merken").click(function(ev) {
    var bild = $(this).find("img");
    bild.attr("src", "/images/loading.gif");
    jQuery.ajax({
          url: $(this).attr("href"),
          type: "POST",
          success: function(r) {
                      if (r != "") {
                        var merkzettel_zaehler = $("#merkzettel_zaehler");
                        if (merkzettel_zaehler.length == 0) {
                          $("#service_navigation").after('<div id="merkzettel_zaehler">1</div>');
                        }
                        else {
                          merkzettel_zaehler.html(r);
                        }
                        bild.attr("src", "/images/ok.png");
                      }
                      window.setTimeout(function(){bild.attr("src", "/images/blind.gif");}, 1000);
                   }
          });  
    ev.preventDefault();
  });
  
  $("a.rezex_link").click(function(ev) {
    var current_obj = $(this);
    var alert_text = "Ist im Rezensionsexemplare-Formular bereits angeklickt! Auswahl wieder entfernen";
    var default_text = "Rezensionsexemplar im Bestell-Formular anklicken";
    var bild = current_obj.find("img");
    bild.attr("src", "/images/loading.gif");
    jQuery.ajax({
          url: current_obj.attr("href"),
          type: "POST",
          success: function(r) {
                      if (r == 1) {
                        bild.attr("src", "/images/ok.png");
                        current_obj.addClass("okay").attr("title", alert_text);
                        $("p.icons").append('<span id="rezexhinweis">Hinweis:<br />Bitte das Formular unter <a href="/presse/service/rezensionen">&raquo;Service &rsaquo; Rezen&shy;sions&shy;exemplare&laquo;</a> abschicken, um die Bestellung ab&shy;zu&shy;schlie&szlig;en</span>');
                      }
                      else {
                        $("#rezexhinweis").remove();
                        bild.attr("src", "/images/blind.gif");
                        current_obj.addClass("okay").attr("title", default_text);
                      }
                   }
          });
    ev.preventDefault();
  });
  
  $("div.merkzettel_eintrag img.entfernen").click(function(ev) {
    if (!confirm(really)) {
      ev.preventDefault();
    }
  });

  if ($("#stimmen p").length > 1) {
    $('#stimmen').cycle({ speed:700, timeout:9000, containerResize: 1, fx:'scrollDown' });
    $("#alle_stimmen").click(function(ev) { 
      $('#stimmen').cycle("destroy").css({"position":"static","overflow":"auto","height":"auto"});
      $("#stimmen p").removeAttr("style").css({"margin-bottom":"9px"}).show();
      $(this).remove();
      ev.preventDefault();
    });
  }

  $('.autor_text').jTruncate({  
     length: 200,  
     minTrail: 0,  
     moreText: "",  
     lessText: "",  
     ellipsisText: " ..."
  });
  $(".aufzu").click(function(ev) {
    $(this).parent().parent().find("div.bild_spalte div.zusatzinfos").toggle();
    $(this).siblings("p.stimme, p.alles").toggle();
    $(this).siblings("p.autor_text").find("span.truncate_ellipsis, span.truncate_more").toggle();
    $(this).toggleClass("auf").toggleClass("zu");
    ev.preventDefault();
  });
  
  if ($("#related_books_selector").klikselect({ autoSubmit:"#auch_erhaeltlich_als", width:"137px"}).length > 0) {
    $("#auch_erhaeltlich_als").submit(function(ev) {
      location.href =  $("#related_books_selector").val();
      ev.preventDefault();
    });
  }
      
	$("#scroll_up, #scroll_down").click(function(ev) {
    scroll_selector = $(this).attr("id");
    if (iphad != true) { scroll_div(); }
    else { counter = 10; scroll_div_iphad(); }
    ev.preventDefault();
  });

  if (iphad != true) {
    $("#mosaik img:not(.neu_icon), #zufallsbild img, #spalte2_rechts.aktuell .bild_spalte img, #thumbnails img").tooltipp({ tip_data_attr: "alt" });
    var api = null;
    $('#spalte2_inhalt').each(function(){
			scroll_ul = $(this).jScrollPane({ showArrows:$(this).is('.arrow') });
			api = $(this).data('jsp');
			var throttleTimeout;
			$(window).bind('resize', function() {
					if ($.browser.msie) {
						// IE fires multiple resize events while you are dragging the browser window which
						// causes it to crash if you try to update the scrollpane on every one. So we need
						// to throttle it to fire a maximum of once every 50 milliseconds...
						if (!throttleTimeout) {
							throttleTimeout = setTimeout(function() {
                                            api.reinitialise();
                                            throttleTimeout = null;
                                          },50);
						}
          } else {
              api.reinitialise();
          }
			});
			var current_li =  $("ul#spalte2_inhalt.kursiv li.current");
			if (current_li.length > 0) {
			  if (location.href.indexOf("nach_autoren") > -1
			      || location.href.indexOf("katalog/genre") > -1
			      || location.href.indexOf("katalog/hoerbuecher") > -1
			      || location.href.indexOf("mediathek/leseproben") > -1
			      || location.href.indexOf("mediathek/hoerproben") > -1) {
          var offset1 = current_li.offset();
          var current_li_parent = current_li.parents("li");
          var offset2 = current_li_parent.offset();
          if (offset1.top - offset2.top < $(".jspContainer").height() - 20) {
            api.scrollToElement(current_li_parent, true);
          }
          else {
            api.scrollToElement(current_li, false);
          }
        }
        else {
          api.scrollToElement(current_li, true);
        }
		  }
		});
		
  }
  else {
    var current_li =  $("ul#spalte2_inhalt.kursiv li.current");
		if (current_li.length > 0) {
		  var current_ul = $("ul#spalte2_inhalt.kursiv");
		  var offset_ul = current_ul.offset();
      var offset1 = current_li.offset();
		  if (location.href.indexOf("nach_autoren") > -1
		        || location.href.indexOf("katalog/genre") > -1
			      || location.href.indexOf("katalog/hoerbuecher") > -1
			      || location.href.indexOf("mediathek/leseproben") > -1
			      || location.href.indexOf("mediathek/hoerproben") > -1) {
          var current_li_parent = current_li.parents("li");
          var offset2 = current_li_parent.offset();
          if ((offset1.top - offset2.top + current_li.height()) < current_ul.height()) {
            current_ul.scrollTop(offset2.top - offset_ul.top);
          }
          else {
            current_ul.scrollTop(offset1.top - offset_ul.top + 9 - current_ul.height() + current_li.height());
          }
        }
        else {
          current_ul.scrollTop(offset1.top - offset_ul.top);
        }
		}
  }
});

function scroll_div_iphad() {
  var top_val = $("#spalte2_inhalt").scrollTop();
  var diff    =  top_val + (scroll_selector == "scroll_up" ? -12 : 12); 
  $("#spalte2_inhalt").scrollTop(diff);
  if (counter > 0) {
    counter--;
    setTimeout("scroll_div_iphad()", 40);
  }
}

function scroll_div() {
  var api  = scroll_ul.data('jsp');
  var diff =  scroll_selector == "scroll_up" ? -110 : 110;
  api.scrollByY(diff, true);
}

function resize_spalte(nr) {
  var neue_hoehe = $(window).height() - (nr == 2 ? 219 : 210);
  $("ul#spalte2_inhalt").height(neue_hoehe);
}

function adapt_spalte(nr) {
    resize_spalte(nr);
    if ($.browser.msie && parseInt($.browser.version) < 8) {
      $("#preselect ul.dropDown").css('z-index', 1000);
      $("ul#spalte2_inhalt").css({'z-index':-1, 'position':'relative'});
      $("#spalte2_inhalt div.jspContainer").css('z-index', 110);
      $("#spalte2_inhalt div.jspPane").css('z-index', 120);
      $("#spalte2_inhalt li").css('z-index', 130);
    }
    $(window).resize(function() { resize_spalte(nr); });
    $("#spalte2_inhalt li").each(function() {
      var current_element = $(this);
      if (current_element.find("ul").length == 0) {
        current_element.click(function(ev) {
          if (!li_link) {
            location.href = current_element.find("a").attr("href");
          }
          ev.preventDefault();
        }).css({"cursor":"pointer"});
      }
    });
}

function nw(url, breite, hoehe) {
var w = breite ? breite : 900;
var h = hoehe ? hoehe : 697;
var f = window.open(url, "neues_fenster", "width=" + w + ",height=" + h + ",top=20,left=90,resizable=yes,status=yes,scrollbars=yes,location=yes,toolbar=no,menubar=yes");
f.focus();
}
