// INIT
// XXX Switch to jQuery tooltip plugin
jQuery(function() {
    jQuery('#help_message').detach().appendTo(document.body);
});

jQuery('.help').live('mouseover', function(event) {
    var $help_message = jQuery('#help_message');
    if ($help_message.hasClass('hide')) {
        $help_message
            .html(this.title)
            .css({ left: event.pageX + 'px', top: event.pageY + 15 + 'px', width: '225px', 'z-index': 1105 })
            .removeClass('hide');
    }
}).live('mouseout', function() {
    jQuery('#help_message').addClass('hide');
});

// Functions & Data
// XXX Sketchy AJAX-style error handling
function parseRegistration(picURL) {
    var $form = jQuery('#register_form form'),
        params = {
            city_or_zip: jQuery('#autocomplete').val()
        };

    jQuery('#processing').show();
    jQuery('#submit').attr('disabled', 'disabled');

    // Sucks that I have to concat strings, but jquery doesn't do form serialisation to an object
    jQuery.post($form.attr('action'), $form.serialize() + '&' + jQuery.param(params), function(data) {
        // Errors?
        if (data.status == 'fail') {
            // Display errors
            jQuery.each(data.fields, function(name, field) {
                jQuery('#' + name + '_error_message').remove();
                if (field.error) {
                    jQuery('#' + name).after(
                        jQuery('<span id="' + name + '_error_message" title="' + field.error + '" class="help"><img src="' + picURL + 'q_button.gif" style="position: relative;left: 3px;top: 2px;" /></span>')
                    );
                    if (name == 'date_of_birth') {
                        jQuery('#year, #month, #day').addClass('error');
                    }
                }
                else {
                    jQuery('#' + name).removeClass('error');
                    if (name == 'date_of_birth') {
                        jQuery('#year, #month, #day').removeClass('error');
                    }
                }
            });

            jQuery('#processing').hide();
            jQuery('#submit').attr('disabled', '');
        }
        else if (data.status == 'fraud_affiliate') {
            window.location.assign(data.url);
        }
        else {
            window.location.assign(data.login_url);
        }
    }, "json");
}

