/*
highlight v3  !! Modified by Jon Raasch (http://jonraasch.com) to fix IE6 bug !!

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>

*/

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 });
};

jQuery.fn.removeHighlight = function() {
 function newNormalize(node) {
    for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
        var child = children[i];
        if (child.nodeType == 1) {
            newNormalize(child);
            continue;
        }
        if (child.nodeType != 3) { continue; }
        var next = child.nextSibling;
        if (next == null || next.nodeType != 3) { continue; }
        var combined_text = child.nodeValue + next.nodeValue;
        new_node = node.ownerDocument.createTextNode(combined_text);
        node.insertBefore(new_node, child);
        node.removeChild(child);
        node.removeChild(next);
        i--;
        nodeCount--;
    }
 }

 return this.find("span.highlight").each(function() {
    var thisParent = this.parentNode;
    thisParent.replaceChild(this.firstChild, this);
    newNormalize(thisParent);
 }).end();
};


function tablesorterTextExtraction(node) {
return node.innerHTML.replace(/&nbsp;/g, "");
}



// JavaScript Document
(function ($) {
    $.fn.extend({

        truncate: function (options) {
            var defaults = {
                width: 'auto',
                ellipsis: '...',
				less: 'Less'
            };

            var options = $.extend(defaults, options);
            return this.each(function () {
                if (options.width == 'auto') {
                    targetWidth = $(this).width() - 18;
                } else {
                    targetWidth = options.width
                }
                if ($(this).width() > targetWidth) {
                    var nonTruncatedText = $(this).text();
                    var truncatedText = $(this).text();
                    $(this).html('<span class="truncatedText" style="display:inline;"> <span class="ellipsisLink">' + options.ellipsis + '</span></span>');
                    i = 1;
                    while ($('.truncatedText', this).width() < targetWidth) {
                        $('.truncatedText', this).html(truncatedText.substr(0, i) + ' <span class="ellipsisLink">' + options.ellipsis + '</span>');
                        i++;
                    }
                    $(this).html('<span class="truncatedText" style="display:inline;">' + $('.truncatedText', this).html()  + '</span>' 
					+ '<span class="nonTruncatedText" style="display:inline; display: none;">' + nonTruncatedText + ' | <span class="lessLink">' + options.less + '</span></span>');
                }
				
				
				$(".ellipsisLink").click(function(){
					$(".nonTruncatedText", $(this).parent().parent()).show(); 
					$(".truncatedText", $(this).parent().parent()).hide();				
				});
				$(".lessLink").click(function(){
					$(".truncatedText", $(this).parent().parent()).show(); 
					$(".nonTruncatedText", $(this).parent().parent()).hide();				
				});
            });
        }
    });
})(jQuery);

(function ($) {
  // custom css expression for a case-insensitive contains()
  jQuery.expr[':'].Contains = function(a,i,m){
      return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
  };


  function listFilter(header, list) { // header is any element, list is an unordered list
  
    $("#publicationListTextFilter")
      .change( function () {
        var filter = $(this).val();
        if(filter) {
          // this finds all links in a list that contain the input,
          // and hide the ones not containing the input while showing the ones that do
          $("#publicationList li").hide();
$("#publicationList").find("li:Contains(" + filter + ")").show();
        } else {
          $("li", list).show();
        }

$("#numberOfEntries").html($("#publicationList li:visible").size());

  // remove any old highlighted terms
        $('body').removeHighlight();

        // disable highlighting if empty
        if ( filter ) {
            // highlight the new term
            $('body').highlight( filter );
        }


        return false;
      })
    .keyup( function () {
        // fire the above change event after every letter
        $(this).change();
    });
  }


  //ondomready
  $(function () {
    listFilter($("#publicationList"));
  });
}(jQuery));


// JavaScript Document

function sortPublicationsByTitle(sortDescending) {
	var mylist = $('#publicationList');
	var listitems = mylist.children('li').get();
	listitems.sort(function(a, b) {
		var compA = $(".publicationTitle", a).text().toUpperCase();
		var compB = $(".publicationTitle", b).text().toUpperCase();
		return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
	});
	if(sortDescending) {
    	listitems.reverse();
	}
	$.each(listitems, function(idx, itm) {
		mylist.append(itm);
	});
}
function sortPublicationsByYear(sortDescending) {
	var mylist = $('#publicationList');
	var listitems = mylist.children('li').get();
	listitems.sort(function(a, b) {
		var compA = $(".publicationYear", a).text().toUpperCase();
		var compB = $(".publicationYear", b).text().toUpperCase();
		return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
	});
	if(sortDescending) {
    	listitems.reverse();
	}
	$.each(listitems, function(idx, itm) {
		mylist.append(itm);
	});
}
function sortPublicationsByType(sortDescending) {
	var mylist = $('#publicationList');
	var listitems = mylist.children('li').get();
	listitems.sort(function(a, b) {
		var compA = $(".publicationType", a).text().toUpperCase();
		var compB = $(".publicationType", b).text().toUpperCase();
		return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
	});
	if(sortDescending) {
    	listitems.reverse();
	}
	$.each(listitems, function(idx, itm) {
		mylist.append(itm);
	});
}

var sitemapContainerShowTimoutID;

function showSitemapContainer() {
    $("#postHeader .sitemapContainer").show();
}

function hideSitemapContainer() {
    $("#postHeader .sitemapContainer").hide();
}



$(document).ready(function () {
    
$('#publicationListButtons').show();
    //$("#publicationList .publicationDetailsLink").hide(); 
    //$("#publicationList .publicationContributors").truncate(); 
/*
    $("#publicationList li").hover(
      function(){$(".publicationDetailsLink", this).show();},
      function(){$(".publicationDetailsLink", this).hide();}
    ); 

   $("#showAllContributors").click(function(){
       $(".publicationContributors .truncatedText").hide();
       $(".publicationContributors .nonTruncatedText").show();
   });
   $("#showTruncatedContributors").click(function(){
       $(".publicationContributors .truncatedText").show();
       $(".publicationContributors .nonTruncatedText").hide();
   });
*/
  $("#sortPublicationsByYear").click(function () {
    if ($("#publicationList").hasClass('sortedByYearAscending')) {
        sortPublicationsByYear(true);
        $("#publicationList").removeClass('sortedByYearAscending');
        $("#publicationList").addClass('sortedByYearDescending');
        $('.publicationListButtonTD').removeClass('publicationListButtonTDDescending');
        $('.publicationListButtonTD').removeClass('publicationListButtonTDAscending');
        $('#sortPublicationsByYearTD').addClass('publicationListButtonTDDescending');
    } else {
        sortPublicationsByYear(false);
        $('.publicationListButtonTD').removeClass('publicationListButtonTDDescending');
        $('.publicationListButtonTD').removeClass('publicationListButtonTDAscending');
        $("#publicationList").addClass('sortedByYearAscending');
        $("#publicationList").removeClass('sortedByYearDescending');
        $('#sortPublicationsByYearTD').addClass('publicationListButtonTDAscending');
    }
});


$("#sortPublicationsByTitle").click(function () {
    if ($("#publicationList").hasClass('sortedByTitleAscending')) {
        sortPublicationsByTitle(true);
        $('.publicationListButtonTD').removeClass('publicationListButtonTDDescending');
        $('.publicationListButtonTD').removeClass('publicationListButtonTDAscending');
        $("#publicationList").removeClass('sortedByTitleAscending');
        $("#publicationList").addClass('sortedByTitleDescending');
        $('#sortPublicationsByTitleTD').addClass('publicationListButtonTDDescending');

    } else {
        sortPublicationsByTitle(false);
        $('.publicationListButtonTD').removeClass('publicationListButtonTDDescending');
        $('.publicationListButtonTD').removeClass('publicationListButtonTDAscending');
        $("#publicationList").addClass('sortedByTitleAscending');
        $("#publicationList").removeClass('sortedByTitleDescending');
        $('#sortPublicationsByTitleTD').addClass('publicationListButtonTDAscending');
    }

});


$("#sortPublicationsByType").click(function () {

    if ($("#publicationList").hasClass('sortedByTypeAscending')) {
        sortPublicationsByType(true);
        $('.publicationListButtonTD').removeClass('publicationListButtonTDDescending');
        $('.publicationListButtonTD').removeClass('publicationListButtonTDAscending');
        $('#sortPublicationsByTypeTD').addClass('publicationListButtonTDDescending');
        $("#publicationList").removeClass('sortedByTypeAscending');
        $("#publicationList").addClass('sortedByTypeDescending');
    } else {
        sortPublicationsByType(false);
        $('.publicationListButtonTD').removeClass('publicationListButtonTDDescending');
        $('.publicationListButtonTD').removeClass('publicationListButtonTDAscending');
        $('#sortPublicationsByTypeTD').addClass('publicationListButtonTDAscending');
        $("#publicationList").addClass('sortedByTypeAscending');
        $("#publicationList").removeClass('sortedByTypeDescending');
    }

});
sortPublicationsByYear(true);
$("#publicationList").addClass('sortedByYearDescending');

    $("input, textarea").focus(

    function () {
        // only select if the text has not changed
        if (this.value == this.defaultValue) {
            this.select();
        }
    })
    if (document.location.hash != '') {
        $("#overviewBoxContent-overview").hide();
    }

    if (document.location.hash == "#facility") {
        $("#overviewBoxContent-facility").show();
        $("#overviewBoxSelector-facility").addClass("active");
    } else if (document.location.hash == "#how-does-it-work") {
        $("#overviewBoxContent-how-does-it-work").show();
        $("#overviewBoxSelector-how-does-it-work").addClass("active");
    } else if (document.location.hash == "#research") {
        $("#overviewBoxContent-research").show();
        $("#overviewBoxSelector-research").addClass("active");
    } else if (document.location.hash == "#organisation") {
        $("#overviewBoxContent-organisation").show();
        $("#overviewBoxSelector-organisation").addClass("active");
    } else {
        $("#overviewBoxContent-overview").show();
        $("#overviewBoxSelector-overview").addClass("active");

    }

  $("#ikcTable").tablesorter({
        sortList: [
            [1,1]
        ],
textExtraction: tablesorterTextExtraction,

 headers: { 
            // assign the secound column (we start counting zero) 
            3: { 
                // disable it by setting the property sorter to false 
                sorter: false 
            }
 }
    
    }); 
	
   $("#ikc").tablesorter({
        sortList: [
            [3, 0]
        ],
        headers: {
           
        }
    }); 

    $("#memberProfiles").tablesorter({
        sortList: [
            [0, 0]
        ],
        headers: {
            // assign the secound column (we start counting zero) 
            3: {
                // disable it by setting the property sorter to false 
                sorter: false
            },
            // assign the third column (we start counting zero) 
            4: {
                // disable it by setting the property sorter to false 
                sorter: false
            }
        }
    });
    //collapseTocBox()
    $("div.image + div.image").prev().addClass("image-in-row");
    $("h2 + div.image").addClass("image-in-row-first");
    $("p + div.image").addClass("image-in-row-first");
    $("div.image + p").prev().addClass("image-in-row-last");
    $("div.image + h2").prev().addClass("image-in-row-last");
    $("div.image + table").prev().addClass("image-in-row-last");


    $(".colorbox").colorbox({
        current: "{current}/{total}",
        transition: "none",
        width: "75%"
    });

/*
    jQuery(document).bind('cbox_complete', function (event, msg) {
        $('#colorbox').click(function () {
            $.fn.colorbox.close()
        })
    });
*/ 
    $("#jobOffersTable").tablesorter({
        sortList: [
            [3, 0]
        ]
    });



    $("#postHeader .sitemap").hover(function () {
        sitemapContainerShowTimoutID = window.setTimeout(showSitemapContainer, 300);
    }, function () {
        window.clearTimeout(sitemapContainerShowTimoutID);
        $("#postHeader .sitemapContainer").hide();
    });
    $("#menu a").click(function (e) {

        url = $(this).attr("href");
        if (url != "" && url != "#") {
            document.location.href = url;
            e.stopPropagation();
        }
    });


    $(".teaser").click(function () {
        var teaserLinkUrl = $(".teaserLink", this).attr("href");
        if (teaserLinkUrl) document.location.href = $(".teaserLink", this).attr("href");
    });


    $(".teaser").mouseover(function () {
        $(this).addClass("highlighted");
    }).mouseout(function () {
        $(this).removeClass("highlighted");
    });


    $(".teaserLink").click(function (event) {
        document.location.href = $(this).attr("href");
        event.stopPropagation();
        // do something
        return false;
    });

    $("table.highlightable tr.teaser").mouseover(function () {
        var teaserLinkUrl = $(".teaserLink", this).attr("href");
        if (teaserLinkUrl) {
            $("td", this).addClass("highlighted");
        }
    }).mouseout(function () {
        $("td", this).removeClass("highlighted");
    });
    $("table.highlightable tr.teaser").click(function () {
        if ($("a.teaserLink", this)) {
            $("a.teaserLink", this).click();
        }
    });

    $("td.highlightable").mouseover(function () {
        $(this).addClass("highlighted");
    }).mouseout(function () {
        $(this).removeClass("highlighted");
    });



    $("ul.highlightable li").mouseover(function () {
        $(this).addClass("highlighted");
    });




    $("#overviewBoxSelector-next").click(function (e) {


        $(".overviewBoxSelector").removeClass("active");

        if (document.location.hash == "#facility") {

            showOverviewbox("how-does-it-work");

        } else if (document.location.hash == "#how-does-it-work") {

            showOverviewbox("research");

        } else if (document.location.hash == "#research") {

            showOverviewbox("organisation");

        } else if (document.location.hash == "#organisation") {

            showOverviewbox("overview");

        } else {

            showOverviewbox("facility");

        }
        e.stopPropagation();
        return false;

    });



    $("#overviewBoxSelectionList a").each(function () {
        $(this).click(function (e) {
            var id = $(this).attr("id").substr(20);
            if (id.indexOf("next") == -1) {

                showOverviewbox(id);
                e.stopPropagation();
                return false;
            };
        });
    });





    $("ul.highlightable li").mouseover(function () {
        $(this).addClass("highlighted");
    }).mouseout(function () {

        $(this).removeClass("highlighted");
    });


    $("a.email-address").each(function () {
        emailAddress = $(this).attr("href");
        emailAddress = emailAddress.replace(/\(at\)/, "@");
        $(this).attr("href", emailAddress);
    });



    $(".contentBox .contentBoxTitle").click(function (e) {
        $(".contentBoxBody", $(this).parent()).toggle();
        return false;


    });

    $(".contentBoxClosed .contentBoxBody").hide();

    $('.moreLink').hide(); 


});


function showOverviewbox(id) {

    $(".overviewBoxSelector").removeClass("active");
    $("#overviewBoxSelector-" + id).addClass("active");
    $(".overviewBoxContent").hide();
    $("#overviewBoxContent-" + id).fadeIn("fast");
    document.location.hash = id;

};
