/*

This script facilitates tracking whether or not an element has focus. It is not an ideal solution,
but it does work across browsers and test environments. The need for such a solution was prompted
by HtmlUnit not supporting document.activeElement, which all major browsers now support. HtmlUnit
being the underlying technology used by Akephalos (in Cucumber via Capybara), this was a problem.

Focus Tracking can be used by calling FocusTracking.initialize once the dom is loaded and then by
calling $(element_id).has_focus().

This script is currently dependent on Prototype, but could be easily adapted for any JavaScript library.

*/

var FocusTracking = {};

FocusTracking.attribute = 'has-focus'; FocusTracking.auto_focus_class_name = 'auto-focus';

FocusTracking.focusable_elements = function () {

return $$('input[type=text], input[type=password], input[type=submit], input[type=button], input[type=checkbox], input[type=radio], textarea, button, select');

}

FocusTracking.initialize = function () {

var elements = FocusTracking.focusable_elements();
elements.each(
        function (element)
        {
                if (element.readAttribute(FocusTracking.attribute) == null)
                {
                        // if the element already has the focus tracking pieces, leave it alone...only initialize it if
                        // it isn't there so we don't miss saving some changes.
                        Object.extend(element, FocusTracking.Element);
                        element.writeAttribute(FocusTracking.attribute, 'false');
                        element.observe('focus', element.got_focus);
                        element.observe('blur', element.lost_focus);
                }
        }
);

}

FocusTracking.auto_focus = function (class_name) {

class_name = class_name == undefined || class_name == null ? FocusTracking.auto_focus_class_name : class_name;
var elements = $$('.' + class_name);
if (elements.length > 0)
{
        element = elements.first();
        element.activate();
}

}

FocusTracking.Element = {};

FocusTracking.Element.has_focus = function () {

return this.readAttribute(FocusTracking.attribute) == 'true';

}

FocusTracking.Element.got_focus = function () {

this.writeAttribute(FocusTracking.attribute, 'true');

}

FocusTracking.Element.lost_focus = function () {

this.writeAttribute(FocusTracking.attribute, 'false');

}