/**
 * jQuery likes to steal object binding sometimes; this lets us steal it back.
 */
function bind(func, object) {
    var method = func;
    return function() {
        return method.apply(object, arguments);
    };
};

jQuery(function() {
    /**
     * Adding .js to the body allows us to make global styling changes as soon
     * as the DOM is loaded.
     */
    jQuery('body').addClass('js');
    
    /**
     * This line is sheer laziness: it lets us style links that wrap images
     * without having to add the class by hand.
     */
    jQuery('a:has(img)').addClass('imagelink');
    
    /**
     * Give the current element a class to let us style it up. Good for
     * differentiating particular comments or articles on archive pages,
     * if they've been specifically linked to.
     */
    var current = jQuery(window.location.hash);
    if (current) current.addClass('current');
    
    /**
     * Switch the current element around dynamically, i.e. as a user clicks
     * on another comment permalink or date-based permalink.
     */
    jQuery('.date a, .meta a').bind('click', function(clickevent) {
      current.removeClass('current');
      current = jQuery(this.hash);
      current.addClass('current');
    });
    
    /**
     * Search box object with a label and text input field. If the text input has
     * no content, it is filled with the label text, which then vanishes on click.
     */
    var Sbox = function(input, label) {
        this.input = jQuery(input);
        this.label = jQuery(label);
        
        if (this.input.length + this.label.length < 2) return;
        
        this.text = this.label.text();
        
        if (this.input.attr('value').length < 1) {
            this.input.attr('value', this.text);
        }
        
        this.input.click(bind(this.empty, this));
        this.input.blur(bind(this.fill, this));
    };
    
    Sbox.prototype = {
        empty: function() {
            if (this.input.attr('value') === this.text) {
                this.input.attr('value', '');
            }
        },
        
        fill: function() {
            if (this.input.attr('value').length === 0) {
                this.input.attr('value', this.text);
            }
        }
    };
    
    var sbox = new Sbox('#s', '#searchlabel');
});
