(function ($) {

  Drupal.behaviors.slidemenu = {
    attach: function(context, settings) {
	  	var $container = $('#slidemenu');
	  	var $trigger = $('#content');
	  	
	  	// adjust the position of the slidemenu every time the window gets resized
	  	$(window).resize(function() {
	  	  adjustContainerPosition($container);
	  	});
	  	
	  	// adjust the position of the slidemenu on page load
	  	adjustContainerPosition($container);

	  	// configure and start sticky plugin
	  	$.stickyBar($container, {'showClose' : false, 'divBase' : $trigger});
	  	
	  	// function centers the slidemenu container element dynamically
	  	function adjustContainerPosition($element) {
		  w = $(document).width();
  		  l = ((w - $element.width()) / 2) - 3;
  		  if (navigator.userAgent.indexOf('MSIE 9.0') > 0) l -= 5;
  		  $element.css('left', l);
	  	}
	  	
	  }
    };

})(jQuery);;
(function ($) {

  Drupal.behaviors.moremenu = {
    attach: function(context, settings) {
	  	
	  	$('.more')
		  	.mouseenter(function() {
		  		var l = $(this).position().left;
		  		var t = $(this).position().top + $(this).height() - 25;
			  	$('.dropdown-menu')
			  		.css({
			  				'left': l,
			  				'top': t
			  		})
			  		//.fadeIn('fast');
			  		.show();
		  	})
		  	.mouseleave(function(event) {
		  		// Just Don't hide if mouse leaves on the bottom of the element
		  		var top = parseInt($(this).position().top);
		  		var bottom = top + $(this).height();
		  		var left = parseInt($(this).position().left);
		  		var right = left + $(this).width();
		  		if (event.pageY <= top || ((event.pageY < bottom) && (event.pageX <= left || event.pageX >= right))) {
		  			$('.dropdown-menu').hide();//fadeOut('slow');
		  		}
		  	});
	  	
	  	$('.moresublink').each(function(index) {
	  		var selecta = '#sub' + $(this).attr('rel') + '.dropdown-submenu';
	  		$(this)
	  		  .mouseenter(function() {
	  			var l = $(this).parent().position().left +  $(this).width() + 'px';
			    var t = $(this).position().top + $(this).parent().position().top + 'px';
			    $(selecta).css({
				      'position': 'absolute',
					  'left': l,
					  'top': t
					}).show();
	  		  })
			  .mouseleave(function(event) {
			    var left = $(this).position().left + $(this).parent().position().left;
			  	var right = left + $(this).width();
			  	if (event.pageX <= right) {
			  	  $(selecta).hide();
			  	}
			  });
	  	});
	  	
	  	$('.dropdown-menu')
		  	.mouseenter(function() {
		  		// keep hover css for mainmenu item 
		  		// while hovering the submenu items
		  		$('.more a').css('color','#9BA0CA');
		  	})
		  	.mouseleave(function(event) {
		  		$('.more a').css('color','white');
		  		if (hideIsNecessary(event, $(this))) {
		  			$('.dropdown-menu').hide();//fadeOut('slow');
		  		}
		  	});
	  	
	  	$('.dropdown-submenu')
		  	.mouseenter(function() {
		  		// keep hover css for mainmenu item 
		  		// while hovering the submenu items
		  		$('.more a').css('color','#9BA0CA');
		  	})
		  	.mouseleave(function() {
		  		$('.more a').css('color','white');
		  		$('.dropdown-submenu').hide();
		  	});
	  	
	  	function hideIsNecessary(ev, $element) {
	  	   // Don't hide the moremenu tree if mouse slides into a submenu
    	  l = $element.position().left;
    	  if (ev.pageX >= l) {
    		  return false;
    	  }
  		  return true;
	  	}
	  	
	  }
    };

})(jQuery);
;
/*
* jQuery stickyBar Plugin
* Copyright (c) 2010 Brandon S. <antizeph@gmail.com>
* Version: 1.1.2 (09/14/2010)
* http://plugins.jquery.com/project/stickyBar
* 
* Usage (simple):      $.stickyBar(div);
* Usage (advanced):    $.stickyBar(divTarget, {'showClose' : true, 'divBase' : divBase});
* 
* Notes:    divTarget is the div you want to be stickied (and by default is also divBase).
*           divBase is the target to scroll past to invoke stickyBar.
*           showClose displays a small 'x' that closes stickyBar
*/
(function($){
    $.fn.stickyBar = function(o){
        $.stickyBar(o);
    }

    $.stickyBar = function(divTarget, options){
        var defaults = {
            'divBase'   : '',
            'showClose' : false
        };
        settings = $.extend(defaults, options);

        var wrapped = 0; //initial value
        
        //if divBase is a defined option, set the stickyBarTop value to it, otherwise, use divTarget
        divTargetBase = (settings.divBase) ? divTargetBase = settings.divBase : divTargetBase = divTarget;
         
        // original code below
        //var stickyBarTop = $(divTargetBase).offset().top;
        
        // consider the margin of the preceding element
        //var stickyBarTop = $(divTargetBase).offset().top - (parseInt($("#context-menu").css('margin-bottom')) * 2);
        //var stickyBarTop = $(divTargetBase).offset().top - 50;
        var stickyBarTop = $(divTargetBase).offset().top - (parseInt($("#context-menu").css('margin-bottom')));


        $(window).scroll(function(){
            var scrollPos = $(window).scrollTop();

            if (scrollPos > stickyBarTop){
        	//if (scrollPos > 230){
            	$('.dropdown-menu').hide();
                if (wrapped == 0){ 
                	$(divTarget).fadeIn('slow');
                    $(divTarget).wrap('<div class="sticky">');
                    $(".sticky").css({
                                'position'    : "fixed",
                                'top'         : "0",
                                'left'        : "0",
                                'width'       : "100%",
                                'z-index'     : "9999"
                            });
                    wrapped = 1;
                    if (settings.showClose){
                        $(".sticky").append('<div class="stickyClose" style="left:95%;position:absolute;color:#fff;top:0;left:98%;cursor:pointer">x</div>');
                        $(".stickyClose").click(function(){
                            $(".sticky").slideUp('slow');
                            setTimeout(function(){
                                $(divTarget).unwrap();
                                $(".stickyClose").remove();
                            },400);
                            wrapped = 2; //won't happen again on the page until a refresh
                        });
                    }

                }
            } else {
            	$(divTarget).slideUp('normal');
                if (wrapped == 1){
                    $(divTarget).unwrap();
                    $(".stickyClose").remove();
                    wrapped = 0;
                }
            }
        });
    };
}) (jQuery);;
// HTML Truncator for jQuery
// by Henrik Nyh <http://henrik.nyh.se> 2008-02-28.
// Free to modify and redistribute with credit.

(function($) {

  var trailing_whitespace = true;

  $.fn.truncate = function(options) {

    var opts = $.extend({}, $.fn.truncate.defaults, options);
    
    $(this).each(function() {

      var content_length = $.trim(squeeze($(this).text())).length;
      if (content_length <= opts.max_length)
        return;  // bail early if not overlong

      var actual_max_length = opts.max_length - opts.more.length - 3;  // 3 for " ()"
      var truncated_node = recursivelyTruncate(this, actual_max_length);
      var full_node = $(this).hide();

      truncated_node.insertAfter(full_node);
      
      findNodeForMore(truncated_node).append(' (<a href="#show more content">'+opts.more+'</a>)');
      findNodeForLess(full_node).append(' (<a href="#show less content">'+opts.less+'</a>)');
      
      truncated_node.find('a:last').click(function() {
        truncated_node.hide(); full_node.show(); return false;
      });
      full_node.find('a:last').click(function() {
        truncated_node.show(); full_node.hide(); return false;
      });

    });
  }

  // Note that the " (…more)" bit counts towards the max length – so a max
  // length of 10 would truncate "1234567890" to "12 (…more)".
  $.fn.truncate.defaults = {
    max_length: 100,
    more: '…more',
    less: 'less'
  };

  function recursivelyTruncate(node, max_length) {
    return (node.nodeType == 3) ? truncateText(node, max_length) : truncateNode(node, max_length);
  }

  function truncateNode(node, max_length) {
    var node = $(node);
    var new_node = node.clone().empty();
    var truncatedChild;
    node.contents().each(function() {
      var remaining_length = max_length - new_node.text().length;
      if (remaining_length == 0) return;  // breaks the loop
      truncatedChild = recursivelyTruncate(this, remaining_length);
      if (truncatedChild) new_node.append(truncatedChild);
    });
    return new_node;
  }

  function truncateText(node, max_length) {
    var text = squeeze(node.data);
    if (trailing_whitespace)  // remove initial whitespace if last text
      text = text.replace(/^ /, '');  // node had trailing whitespace.
    trailing_whitespace = !!text.match(/ $/);
    var text = text.slice(0, max_length);
    // Ensure HTML entities are encoded
    // http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
    text = $('<div/>').text(text).html();
    return text;
  }

  // Collapses a sequence of whitespace into a single space.
  function squeeze(string) {
    return string.replace(/\s+/g, ' ');
  }
  
  // Finds the last, innermost block-level element
  function findNodeForMore(node) {
    var $node = $(node);
    var last_child = $node.children(":last");
    if (!last_child) return node;
    var display = last_child.css('display');
    if (!display || display=='inline') return $node;
    return findNodeForMore(last_child);
  };

  // Finds the last child if it's a p; otherwise the parent
  function findNodeForLess(node) {
    var $node = $(node);
    var last_child = $node.children(":last");
    if (last_child && last_child.is('p')) return last_child;
    return node;
  };

})(jQuery);
;
(function ($) {

  Drupal.behaviors.ElfReadmore = {
    attach: function (context) {

      // See https://github.com/henrik/jquery.truncator.js for documentation.
	  var opt = {};
	  opt.max_length = 470;
	  opt.more = 'mehr lesen';
	  opt.less = 'weniger';
      $('div.field-name-field-elf-content-body .field-items').truncate(opt);
    }
  };

  Drupal.behaviors.ElftriggerAddThis = {
    attach: function (context) {
      // Trigger the addThis toolbox inside the colorbox.
      if (context == '#cboxLoadedContent') {
        // Extract the share url from the open graph properties.
        var share_url = $("meta[property='og:url']", context).attr('content');
        addthis.toolbox('.addthis_toolbox', null, {url : share_url});
        addthis.counter('.addthis_counter', null, {url : share_url});
      }
    }
  };

  Drupal.behaviors.Elftransify = {
    attach: function (context) {
      //$('body').transify();
    }
  };

  Drupal.behaviors.NoMehr = {
    attach: function (context) {
      // prevent clicking on the mehr link directly.
      $('li.more a', context).click(function (event) {
        return false;
      });
    }
  };
  
  // corrects the position of the share widgets to get them inline with the continue link
  Drupal.behaviors.ShareWidgetPosition = {};
  Drupal.behaviors.ShareWidgetPosition.attach = function (context) {
	var htmlstr = $('.continue-to').html();
	htmlstr.replace(' ', '');
    if ($('.continue-to').length > 0 && htmlstr != '') {
   	  $('.addthis_toolbox').css({'position':'relative','top':'16px'});
      $('.node .addthis_toolbox').css({'position':'relative','top':'30px'});
    }
  };
  
  // This bevavior allows exit of an overlay using the browsers back button
  Drupal.behaviors.OverlayBack = {};
  Drupal.behaviors.OverlayBack.attach = function (context) {
	  
    //$('.view-elf-view-sub-modelle a.colorbox-load, .node-modell a.colorbox-load').each(function(index) {
	$('.view-elf-view-sub-modelle a.colorbox-load').each(function(index) {
      $(this).click(function() {
        var cur_uri = window.location.href;
        cur_uri = removeHash(cur_uri);
        var id = $(this).attr('alt');
        window.location.href = cur_uri + '#' + id;
      });
    });
    
    $(window).hashchange(function(){
      //console.log(window.location.hash);
      if (window.location.hash == '') {
    	$.colorbox.close();
      }
      /* this would handle back and forward button clicks inside the overlay but does not yet work
      else {
        console.log(window.location.hash);
        console.log(window.location.href);
        var hash = window.location.hash;
        var uri = 'http://elfenmetall.localhost/langcode/84/node/' + hash.substr(1, hash.length);
        console.log(uri);
        $.colorbox({inline:true, href:uri});
      }
      */
    });
    
    // remove the hash if the user closes the colorbox normally
    $(document).bind('cbox_closed', function(){
      window.location.hash = null;
    });
    
    // function removes any hash from the given uri
    function removeHash(uri) {
      if (uri.indexOf('#') != -1) {
        fragments = uri.split('#');
        uri = fragments[0];
      }
      return uri;
    }
    
  };

})(jQuery);;
(function ($) {

Drupal.behaviors.initColorboxDefaultStyle = {
  attach: function (context, settings) {
    $(document).bind('cbox_complete', function () {
      // Only run if there is a title.
      if ($('#cboxTitle:empty', context).length == false) {
        setTimeout(function () { $('#cboxTitle', context).slideUp() }, 1500);
        $('#cboxLoadedContent img', context).bind('mouseover', function () {
          $('#cboxTitle', context).slideDown();
        });
        $('#cboxOverlay', context).bind('mouseover', function () {
          $('#cboxTitle', context).slideUp();
        });
      }
      else {
        $('#cboxTitle', context).hide();
      }
    });
  }
};

})(jQuery);
;
/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);;

