$.extend({
    getUrlVars: function(){
        var vars = [], hash;
        
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1, (window.location.href.indexOf('#') != -1)?window.location.href.indexOf('#'):window.location.href.length).split('&');
        for(var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function(name){
        return $.getUrlVars()[name];
    }
});

$(document).ready(function(){
    $("#surname").autocomplete("xht/index.html", {minChars: 2,
          max: 8,
          cacheLength: 1,
          matchSubset: false,
          selectFirst: false,
          formatItem: function(data, i, n, value) {
            return "<div style='text-align:left'><div style='float:right'>" + data[1] + "</div>" + data[0] + "</div>";
          },
          formatResult: function(data, value) {
            return value.split("|")[0];
          }
    });
       
    $("#publications #publicationviewtabs").hide();
    
    pubheading = $("#publications h2:first");
    pubheading.addClass("plus");
    
    pubheading.click(function(event){
        $(this).next("#publicationviewtabs").slideToggle("fast");

        var id = $.getUrlVar('id');
        if($(this).hasClass("plus")) {
            $(this).addClass("minus");
            $(this).removeClass("plus");
            $.cookie('showPubs', id+',expanded');  
        } else {
            $(this).addClass("plus");
            $(this).removeClass("minus");
            $.cookie('showPubs', id+',collapsed');  
        }

        return false;
    });
    
    $("#publicationviewtabs").tabs({
        ajaxOptions: {
            error: function(xhr, status, index, anchor) {
                $(anchor.hash).html("Couldn't load the publications list at this time. We'll try to fix this as soon as possible.");
            }
        }
    });
    
    var showPubs = $.cookie('showPubs');
    var id = $.getUrlVar('id');
    if (showPubs == id+',expanded') {  
        pubheading.next("#publicationviewtabs").slideToggle("fast");
        pubheading.addClass("minus");
        pubheading.removeClass("plus"); 
    };  
});
