jQuery.fn.kuka_slideshow_navigate = function(){
  var data = "";
  var clean_href = function(string){
    return string.split("#")[1];
  };
  
  var loaded = function(event){
    $("#loading").fadeOut(1000, function(){
      $("#"+clean_href(window.location.hash)).fadeIn("slow");
      $("#"+clean_href(data)).fadeOut("slow");
      
    });
  }
  
  this.each(function() {
    if(!window.location.hash.length)  window.location.hash = "#slide_1";
    var to_keep = window.location.hash.split("#")[1];


    $(this).find("li").each(function(){
      if(this.id != to_keep)
        $(this).hide();
        
      else {
        $(this).css("display", "block");
        
        $(this).find("img").each(function(){
          $(this).bind("load", function(){
            $("#loading").fadeOut(2);
            this.onload = function(){};
          })
          this.src = $(this).attr("alt");
        });
      }
    });
    
    $(this).bind("click", function(event){
      if(/next|back/.test(event.target.className)){
        $("#loading").fadeIn("fast");
        
        $("#"+clean_href(event.target.href)+" img").each(function(){
          data = window.location.hash;
          $(this).bind("load", loaded);
          this.src = $(this).attr("alt");
        });
        
      }
    });
  });
};

//  Originaly implemented in Drupal 6

jQuery.fn.fixedTableHeader = function (context) {
  // This breaks in anything less than IE 7. Prevent it from running.
  if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7) {
    return;
  }

  // Keep track of all cloned table headers.
  var headers = [];

  jQuery("thead", this).each(function () {
    // Clone thead so it inherits original jQuery properties.
    var headerClone = jQuery(this).clone(true).insertBefore(this.parentNode).wrap('<table class="sticky-header"></table>').parent().css({
      position: 'fixed',
      top: '0px'
    });

    headerClone = jQuery(headerClone)[0];
    headers.push(headerClone);

    // Store parent table.
    var table = jQuery(this).parent('table')[0];
    headerClone.table = table;
    // Finish initialzing header positioning.
    tracker(headerClone);

    jQuery(table).addClass('sticky-table');
    jQuery(this).addClass('tableHeader-processed');
  });

  // Track positioning and visibility.
  function tracker(e) {
    // Save positioning data.
    var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    if (e.viewHeight != viewHeight) {
      e.viewHeight = viewHeight;
      e.vPosition = jQuery(e.table).offset().top - 4;
      e.hPosition = jQuery(e.table).offset().left;
      e.vLength = e.table.clientHeight - 100;
      // Resize header and its cell widths.
      var parentCell = jQuery('th', e.table);
      jQuery('th', e).each(function(index) {
        var cellWidth = parentCell.eq(index).css('width');
        // Exception for IE7.
        if (cellWidth == 'auto') {
          cellWidth = parentCell.get(index).clientWidth +'px';
        }
        jQuery(this).css('width', cellWidth);
      });
      jQuery(e).css('width', jQuery(e.table).css('width'));
    }
    
    // Track horizontal positioning relative to the viewport and set visibility.
    var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft;
    var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - e.vPosition;
    var visState = (vOffset > 0 && vOffset < e.vLength) ? 'visible' : 'hidden';
    jQuery(e).css({left: -hScroll + e.hPosition +'px', visibility: visState});
  }


  // Track scrolling.
  var tableHeaderOnScroll = function() {
    jQuery(headers).each(function () {
      tracker(this);
    });
  };

  // Only attach to scrollbars once, even if Drupal.attachBehaviors is called
  //  multiple times.
  if (!jQuery('body').hasClass('tableHeader-processed')) {
    jQuery('body').addClass('tableHeader-processed');
    jQuery(window).scroll(tableHeaderOnScroll);
    jQuery(document.documentElement).scroll(tableHeaderOnScroll);
  }


  // Track resizing.
  var time = null;
  var resize = function () {
    // Ensure minimum time between adjustments.
    if (time) {
      return;
    }
    time = setTimeout(function () {
      jQuery('table.sticky-header').each(function () {
        // Force cell width calculation.
        this.viewHeight = 0;
        tracker(this);
      });
      // Reset timer
      time = null;
    }, 250);
  };
  jQuery(window).resize(resize);
};

// Originaly by http://www.learningjquery.com/2007/09/animated-scrolling-with-jquery-12

jQuery.fn.animateScrolling = function(){
  jQuery(this).click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
    && location.hostname == this.hostname && this.hash) {
      var $target = jQuery(this.hash);
      $target = $target.length && $target || jQuery('[name=' + this.hash.slice(1) +']');
      if ($target.length) {
        var targetOffset = $target.offset().top;
        jQuery('html,body').animate({scrollTop: targetOffset}, 600);
       return false;
      }
    }
  });
};

jQuery.fn.pageSplit = function() {
  if(this.length == 0) return this;
  
  var navi_paging = ["<li class='back'><a href='#back'>"+t("Back")+"</a></li>"];
  var total = this.length;
  var current = (window.location.hash.indexOf(t("page_")) > -1) ? window.location.hash.split("_")[1] : "1";
  var previous;
  var preventAnchor;
  
  var css = function(number){
    if(number+1 == 1) return "first";
    if(number+1 == total) return "last";
    return "";
  };
  
  var showActive = function(current, setHash){
    
    if(previous){
      jQuery('html,body').animate({scrollTop: jQuery(previous).offset().top}, 600, function(){
        jQuery(previous).hide();
        jQuery("#"+t("page_")+current).show();
        previous = jQuery("#"+t("page_")+current);
        if(setHash) window.location.hash = t("page_")+current;
      });
    } else {
      jQuery("#"+t("page_")+current).show();
      previous = jQuery("#"+t("page_")+current);
    }
    
    if(preventAnchor) {
      window.scrollTo(0, window.jQuery(window.location.hash).offset().top);
      preventAnchor = undefined;
    }
    
    
    jQuery("#navi_paging span").hide();
    jQuery("#navi_paging a").show();
    jQuery("#navi_paging a[href~='#"+t("page_")+current+"']").hide().prev().show();

    if(current == 1) jQuery("#navi_paging .back a").hide();
    if(current == total) jQuery("#navi_paging .next a").hide();
  };
  
  this.each(function(index){
    var elements = [];
    var prevSiblings = jQuery(this).prevAll();
    if(jQuery(prevSiblings).filter(window.location.hash).length
    && window.location.hash.indexOf(t("page_")) == -1){
      current = index+1;
      preventAnchor = true;
    }
    
    for (var i=0; i < prevSiblings.length; i++) {
      elements.push(prevSiblings[i]);
      if(prevSiblings[i].className == "page_break" || prevSiblings[i].className == "page_keep") break;
    };

    jQuery(elements.reverse()).wrapAll("<div class='page' id='"+t("page_")+(index+1)+"' style='display:none;'></div>");
    navi_paging.push('<li class="'+css(index)+'"><span>'+(index+1)+'</span><a href="#'+t("page_")+(index+1)+'">'+(index+1)+'</a></li>');
  });

  navi_paging.push("<li class='next'><a href='#next'>"+t("Next")+"</a></li>");

  jQuery("#navi_footer").before('<ol id="navi_paging"></ol>');
  
  jQuery("#navi_paging").append(navi_paging.join("")).click(function(e) {
    if(e.target.href) {
      var target = e.target.href.split("#")[1];
      
      if(target == "next"){
        current++;
        showActive(current, true);
      }

      if(target == "back"){
        current--;
        showActive(current, true);
      }

      if(target.indexOf(t("page_")) > -1){
        showActive(current = target.split("_")[1]);
      }

      // return false;
    }
  });
  
  showActive(current);
  
  return this;
};

jQuery.fn.tooltip = function(){
  this.each(function(index){
    jQuery("#wrapper").before('<div class="tooltip box" id="tooltip_'+index+'"><div class="pointer">&nbsp;</div><div class="content">'+(this.title)+'</div></div>');
    
    jQuery(this).removeAttr("title");
    
    jQuery(this).bind("mouseover", function(e){
      var position = jQuery(this).offset();
      var windowHeight  = window.innerHeight || 
                          document.documentElement.clientHeight;
      var pageYOffset   = window.pageYOffset
                      || document.documentElement.scrollTop
                      || document.body.scrollTop
                      || 0;
      var pageHeight    = document.height 
                        || window.height 
                        || document.body.scrollHeight;
      var pageBottomY = pageYOffset + windowHeight;
      
      jQuery("#tooltip_"+index).css({
        top: position.top+15,
        left: position.left-8
      }).fadeIn("fast");
      
    }).bind("mouseout", function(){
      
      jQuery("#tooltip_"+index).fadeOut("fast");
      
    });

  });
};

jQuery.fn.pageBookmark = function(){
  this.bind("click", function(){    
    if(this.className == "bookmarked"){
      var number  = jQuery(this).next().find(".number");
      var value  = Number(number.text());
      if(value-1 == 0){ 
        number.parent().fadeOut("fast", function(){
          number.text(value-1);
        });
      } else {
        number.text(value-1);
      }
      this.className = "bookmark";
    } else {
      var number  = jQuery(this).next().fadeIn("fast").find(".number");
      var value  = Number(number.text());
      number.text(value+1);
      this.className = "bookmarked";
    }
    return false;
  });
};

jQuery.fn.liveSearch = function(){
  this.bind("focus", function(){
    if(this.value == t("Search")) this.value = "";
  });
  
  this.bind("keydown", function(e){
    if(e.keyCode == 40){
      console.log("key down pushed");
    }
    if(e.keyCode == 38){
      console.log("key up pushed");
    }
  });
  
  this.bind("blur", function(){
    if(this.value == "") this.value = t("Search");
  });
};

jQuery.fn.fullScreen = function(){
  this.bind("click", function(){
    
  });
};

jQuery.fn.tableNavi = function(){
  var current;
  
  var toggle = function(element){
    current.hide();
    element.show();
    current = element;
  };
  
  var getHash = function(element){
    return element.href.split("#")[1];
  };
  this.find("li:not(.download) a").each(function(){
    
    
    if(this.className.indexOf("active") == -1){
      jQuery("#"+getHash(this)).hide();
    } else {
      current = jQuery("#"+getHash(this));
    }
    
    jQuery(this).click(function(){
      if(current[0] != jQuery("#"+getHash(this))[0]){
        toggle(jQuery("#"+getHash(this)));
        jQuery(this).parents("ul").find(".active").removeClass("active");
        jQuery(this).addClass("active");
      }
      
      return false;
    });
  });
};

jQuery.fn.popUp = function(){
  this.each(function(index){
    jQuery(this).bind("click", function(){
      window.open(this.href, "window_"+index, jQuery(this).attr("rel"));
      return false;
    });
  });
};

jQuery.fn.aaa = function(){
  this.bind("click", function(){
    var current = Number(jQuery("html").css("font-size").replace(/px|pt/, ""));
    

    if(this.className == "smaller"){
      jQuery("html").css("font-size", 10);
      return false;
    }
    
    jQuery("html").css("font-size", current+1);
    return false;
  });
};

jQuery(function(){
  jQuery("table thead :first-child").addClass("entity5000");
  jQuery("table tr td:first-child").addClass("entity5000");
  
  jQuery(".zwischenschlag-leere-spalten-").addClass("zwischenschlag");
  // jQuery('table:not(.not_hover)').tableHover(
  //     {rowClass: 'row_hover', 
  //     colClass: 'col_hover', 
  //     cellClass: 'cell_hover', 
  //     clickClass: 'cell_click', 
  //     ignoreCols: "space"}).fixedTableHeader();  
  var tables = jQuery('table:not(.not_hover)');
  
  if(jQuery.browser.msie && jQuery.browser.version < 7) {
    tables.tableHover(
      {rowClass: 'row_hover',
      ignoreCols: "zwischenschlag"});
  }

  if(jQuery.browser.msie){
    var width = 60;
    jQuery("table thead td:not(.zwischenschlag, .zwischenschlag-leere-spalten-), table thead th").each(function(){
      var _this = jQuery(this);
      var colspan = _this.attr("colspan") || 1;
      _this.width(colspan*width);
    });
  }

  // tables.fixedTableHeader();
  
});