/**
 * Set the width of an element whose size is undetermined until the page has
 * finished rendering.
 */
var setControlWidth = function(ctrl) {
    // IE's margin calculations are broken anyway, so this is superfluous
    if (YAHOO.env.ua.ie > 0 && YAHOO.env.ua.ie < 7) return;
    
    ctrl.setStyle({width: 'auto', float: 'left'});
    ctrl.setStyle({
        float:       'none',
        width:       ctrl.getWidth() + 2 + 'px',
        marginLeft:  'auto',
        marginRight: 'auto'
    });
};

/**
 * Vertically centre an element within its parent element by setting the top
 * and bottom padding.
 */
verticallyCentre = function(selector) {
    var selected  = Ojay(selector),
        container = selected.parents().at(0),
        offset    = ((container.getHeight() - selected.getHeight()) / 2).floor();
    
    selected.setStyle({
        top: offset < 1 ? '0' : offset + 'px'
    });
};

/**
 * Places the label for a text field within that field, for a simpler
 * and more intuitive interface to e.g. search forms.
 */
var labelInField = function(field) {
    var input = Ojay(field), label = Ojay.Forms.getLabel(field).hide();
    if (!label.node || !input.node) return;
    
    var labelText = label.node.innerHTML.stripTags(),
        inputType = input.node.type || 'text';
    
    // Don't bother setting up the event handlers if the browser can detect
    // the HTML5 placeholder text.
    if ('placeholder' in document.createElement('input') && input.node.placeholder.length > 1) return;
    
    var focus = function() {
        input.removeClass('empty');
        if (input.node.value == labelText) input.node.value = '';
    };
    
    var blur = function() {
        if (input.node.value && input.node.value != labelText) return;
        input.addClass('empty');
        if (inputType == 'text') input.node.value = labelText;
    };
    
    blur();
    
    input.on('focus', focus);
    input.on('blur', blur);
};

/**
 * Adds a non-breaking space between the last two words of a paragraph,
 * removing 'widows' where the last word of the paragraph is on its line
 * alone.
 */
var fixWidows = function(paragraph) {
    paragraph = Ojay(paragraph);
    
    var text = paragraph.node.innerHTML.split(/\s+/),
        last = text.pop();
    
    paragraph.setContent(text.join(' ') + '&nbsp;' + last);
};

/**
 * Adds the class `hovered` to the specified elements.
 */
var makeHoverable = function(els) {
    Ojay(els).on('mouseover', function(button) {
        button.addClass('hovered');
    }).on('mouseout', function(button) {
        button.removeClass('hovered');
    });
};

/**
 * Shows some links in an overlay.
 */
var showLinksInOverlay = function(selector) {
    var links = Ojay(selector);
    
    if (links.length > 0) {
        require('PagedOverlay', function() {
            PagedOverlay.addLinks(links);
        });
    }
};

