/* Local jQuery Adaptations
--------------------------------------------------------------------------------*/

/* jQuery Plugins
--------------------------------------------------------------------------------*/
// Add hover support
jQuery.fn.BMaddHover = function() {
    this.hover(
        function() { $(this).addClass('over'); },
        function() { $(this).removeClass('over'); }
    );
    return this;
};

// Make enter act like a tab
jQuery.fn.BMfixEnter = function() {
    this.find(':text').live('keypress', function(evt) {
        if (evt.keyCode === 13) {
            var i = $.inArray(this, this.form.elements);
            var f = $(this.form.elements).slice(i+1);
            f.filter(':text:enabled:first').focus();
            return false;
        }
    });
    return this;
};

// Create popup with default settings
jQuery.fn.BMpopup = function(param) {
    if (!param) param = {};
    if (!param.maxHeight) param.maxHeight = '90%';
    if (!param.maxWidth) param.maxWidth = '90%';
    this.not('form').colorbox(param);
    this.find(':submit').live('click', function() {
        var q = $(this.form).add(this).BMserialize();
        param.href = this.form.action + '?' + q;
        $.fn.colorbox(param);
        return false;
    });
    return this;
};

// Better form serialization
jQuery.fn.BMserialize = function() {
    return $.map(this, function(elem) {foo.click(function(evt) { evt.which = stopPropagation() })
        if (elem.tagName.toLowerCase() === 'form') {
            return $(elem).serialize();
        } else if (elem.name && elem.value) {
            return elem.name + '=' + elem.value;
        }
    }).join('&');
};

// Add zebra striping
jQuery.fn.BMzebra = function(pattern) {
    if (!pattern) pattern = 'even';
    this.filter(':nth-child(' + pattern + ')').addClass('high1');
    return this;
};


/* Default Page Actions
--------------------------------------------------------------------------------*/
jQuery(document).ready(function() {
    // Enable link popups
    $('a.popup').BMpopup();

    // Enable shopping cart popups
    $('a.cart, form.cart').BMpopup({
        'iframe': true,
        'height': '480px',
        'width': '640px'
    });

    // Enable form clearing buttons
    $(':button.clearForm').click(function() {
        $(':file, :password, :text, textarea', this.form).val('');
        $(':checked', this.form).attr('checked', false);
        $(':selected', this.form).attr('selected', false);
    });

    // Enable print buttons
    $('a.print, :button.print').click(function() {
        window.print();
    });

    // Focus default form field
    $(':input.default').focus();
});
