// Namespace
var iOffer = iOffer ? iOffer : {};
iOffer.Ratings = iOffer.Ratings ? iOffer.Ratings : {};

// Return a prototype array of radio buttons for this rating
iOffer.Ratings.get_radio_button_elements = function(id) {
    return $A(['pos', 'neu', 'neg']).inject( $A(), function(array, key) {
        array.push( $('rating_radio_' + key + '_' + id) );
        return array;
    });
};

// Observe the post/neu/neg radio buttons for onclick event
// When clicked slide down comments section. We must also update
// the hidden rating field with the value of this radio button.
iOffer.Ratings.observe_radio_buttons = function(id) {
    var elements = iOffer.Ratings.get_radio_button_elements(id);
    elements.invoke('observe', 'click', function(event) {

        //Update hidden rating field value
        $('rating_value_rating_' +id).value = Event.element(event).value;

        //Eyecandy
        var wrapper = $('comment_wrapper_rating_' + id);
        if (wrapper.style.display == 'none') {
            new Effect.BlindDown(wrapper, {
                duration: 0.75
            });
        }

        new Effect.BlindUp('warning_rating_' + id, {
            duration: 0.75
        });
    });
};

// Cancel the rating of this user/transaction
// Hide comments section and clear out any selected radio button and comment
iOffer.Ratings.cancel = function(id) {
    var wrapper = $('comment_wrapper_rating_' + id);
    new Effect.BlindUp(wrapper, {
        duration : 0.75
    });
    
    var elements = iOffer.Ratings.get_radio_button_elements(id);
    elements.each(function(e) {
        e.checked = false;
    });

    var comment = $('comment_rating_' + id);
    comment.value = '';

    var counter = $('comment_count_rating_' + id);
    counter.innerHTML = '80';
};

// Submit this rating.
// On submit
//  - Add dimmer overlay
//  - Replace submit button with spinner
//  - Remove cancel button
iOffer.Ratings.submit = function(id) {

    if (iOffer.Ratings.check_rating_value(id) != true) {
        if (iOffer.Dom.is_hidden('warning_rating_' + id)) {
            new Effect.BlindDown('warning_rating_' + id, {
                duration: 0.75
            });
        }
        return false;
    }
    
    iOffer.Dom.replace_with_spinner('rating_buttons_rating_' + id, {
        label: 'Rating User... Please wait',
        dim  : 'details_row_rating_' + id
    });

    $('edit_rating_' + id).onsubmit();
};

// Check that this form has a rating value checked
iOffer.Ratings.check_rating_value = function(id) {
    var elements = iOffer.Ratings.get_radio_button_elements(id);
    var pass = false;
    elements.each(function(e) {
        if (e.checked == true) {
            pass = true;
        }
    });
    return pass
};