function do_show_review_entry_popup(definition_id, target_id, redirect) {
    popup.hidePopup('login_form_layer');
    $('#add_review_entry').load("/reviews/new_entry/" + definition_id + "/" + target_id + "/",
        {'ajax': 1},
        function() {
            $('#add_review_entry_form').prepend('<input type="hidden" name="ajax" value="1" />');
            if (redirect) {
                $('#add_review_entry_form').prepend('<input type="hidden" name="redirect" value="'+redirect+'" />');
            }
            $('#add_review_entry_submit').removeAttr('onclick');
            submitFun = function() {
                $('#add_review_entry_submit').attr('disabled', 'disabled');
                popup.submitPopup('add_review_entry');
                return false;
            };
            $('#add_review_entry_submit').click(submitFun);
            $('#add_review_entry_form').submit(submitFun);
            repaint_stars();
            popup.showPopup('add_review_entry');
            $('#add_review_entry_close_btn').click(function() {
                if ($('#user_has_logged_in').val() != 0) {
                    window.location.reload(false);
                } else {
                    revertLoginFormBehaviour()
                }
            });
        });
}

function show_review_entry_popup(definition_id, target_id, redirect) {
    if ($('#user_id').val() != 'None') {
        $.getJSON('/reviews/ajax_check_can_user_add_review/', {}, function(result) {
            if(result) {
                do_show_review_entry_popup(definition_id, target_id, redirect);
            } else {
                $.ajax({
                        type: "POST",
                        url: "/ajax_add_session_message/",
                        dataType: "json",
                        data: {
                            message: $("#only_extended_can_review_message").val(),
                            message_type: "notice"},
                        complete: function() {
                            document.location = "/accounts/edit/?extended=1";
                        }
                });
            }
        });
    } else {
        g_did = definition_id;
        g_tid = target_id;
        g_redir = redirect;
        alterLoginFormBehaviour();
        popup.showPopup('login_form_layer');
    }
}

function loginDone(user_id) {
    //popup.hidePopup('login_form_layer');
    show_review_entry_popup(g_did, g_tid, g_redir);
}

function show_report_abuse_popup(reviewentry_id) {
    $('#moderation').remove(); // remove moderation box layer if it's already anywhere on page
    $('#report_abuse_boxlayer_container').load("/reviews/report_abuse/", {'ajax': 1, 'reviewentry_id': reviewentry_id},
        function () {
            // popup.showModerationPopup('reviewentry', reviewentry_id);
            popup.showPopup('moderation');
        }
    );
}

function repaint_stars() {
    $(".ratings_box").each(function(i) {
        rating = $(this).find('.ratings_value').html();
        scale = $(this).find('.ratings_scale').html();
        w1 = FULL_STAR_WIDTH * scale;
        full = Math.round(rating);
        if (full > rating) {
            full -= 1 // roundup
        }
        half = Math.round((Math.round(rating - full) * 50) / 50);
        w2 = full * FULL_STAR_WIDTH + half * HALF_STAR_WIDTH;
        $(this).find('.ratings_stars').html('<div class="stars_grey" style="width:' + w1 + 'px"><div class="stars_red" style="width:' + w2 + 'px"></div></div>')
    });
    $(".ratings_box_big").each(function(i) {
        rating = $(this).find('.ratings_value').html();
        scale = $(this).find('.ratings_scale').html();
        w1 = FULL_STAR_BIG_WIDTH * scale;
        full = Math.round(rating);
        if (full > rating) {
            full -= 1; // roundup
        }
        half = Math.round((Math.round(rating - full) * 50) / 50);
        w2 = full * FULL_STAR_BIG_WIDTH + half * HALF_STAR_BIG_WIDTH;
        $(this).find('.ratings_stars').html('<div class="stars_grey stars_grey_big" style="width:' + w1 + 'px"><div class="stars_red stars_red_big" style="width:' + w2 + 'px"></div></div>');
    });
    $(".ratings_questions_box").each(function(i) {
        rating = $(this).find('.ratings_value').html();
        scale = $(this).find('.ratings_scale').html();
        w1 = FULL_STAR_WIDTH * scale;
        full = Math.round(rating);
        if (full > rating) {
            full -= 1; // roundup
        }
        half = Math.round((Math.round(rating - full) * 50) / 50);
        w2 = full * FULL_STAR_WIDTH + half * HALF_STAR_WIDTH;
        $(this).find('.ratings_normal').html('<div class="ratings_content" style="width:' + w1 + 'px"><div class="ratings_color" style="width:' + w2 + 'px"></div></div>');
    });
}

function thumbs_clicked(o, up_down) {
    review_entry_id = $(o).children(".review_entry_id")[0].value;
    if (review_entry_id) {
        $.getJSON("/reviews/submit_thumbs/" + review_entry_id + "/" + up_down + "/");

        $("#thumbs_down_" + review_entry_id).removeClass('thumbs_down_active');
        $("#thumbs_down_" + review_entry_id).unbind('click');
        $("#thumbs_down_" + review_entry_id).click(function() { return false; });
        $("#thumbs_up_" + review_entry_id).removeClass('thumbs_up_active');
        $("#thumbs_up_" + review_entry_id).unbind('click');
        $("#thumbs_up_" + review_entry_id).click(function() { return false; });

        $("#thumbs_" + up_down + "_" + review_entry_id + "_val").text(parseInt($("#thumbs_" + up_down + "_" + review_entry_id + "_val").text()) + 1);

        thumbs_down = parseInt($("#thumbs_down_" + review_entry_id + "_val").text());
        thumbs_up = parseInt($("#thumbs_up_" + review_entry_id + "_val").text());
        $("#thumbs_up_" + review_entry_id + "_pc").text(Math.round(100*thumbs_up/(thumbs_up+thumbs_down)));
        $("#thumbs_down_" + review_entry_id + "_pc").text(Math.round(100*thumbs_down/(thumbs_up+thumbs_down)));
        $("#thumbs_up_" + review_entry_id + "_val").parent().removeClass('up_open');
        $("#thumbs_down_" + review_entry_id + "_val").parent().removeClass('down_open');
    }
}

function submit_anonymous_rating(form, callback) {
    // prevent form from multiple concurrent submits
    if ($(form).data('submit_lock')) {
        return;
    }
    $(form).data('submit_lock', true);
    var data = $(form).find('.your_opinion .review_box input').serialize();
    var full_form_id = $(form).attr('id').replace('add_simple_review_entry_', 'add_review_entry_');
    $(form).data('submit_lock', true);
    $.post($(form).attr('action').replace('new_entry', 'new_rating'), data, 
        function(data) {
            var widget_id = full_form_id.replace('add_review_entry_', 'ratings_box_');
            var widgets = $('.' + widget_id + ', .widget_' + widget_id);
            widgets.each(function() {
                var widget = this;
                $(widget).find('.average').text('(' + data['avg'].toFixed(1) + ' out of ' + data['count'] + ')');
                $(widget).find('.ratings_value').text(data['avg']);
            });
            repaint_stars();
            if (callback) {
                callback();
            }
            $(form).removeData('submit_lock');
        },
        'json');
    return false;
}

function submit_review_entry(e) {
    var form = this;
    var hint = 'Write a review, speak your mind.';
    var body = $(form).find('textarea[name=body]');
    $(form).find('.submit_button').attr('disabled', 'disabled');
    if (body.val() == hint) {
        body.val('');
    }
    $('.errors_box').remove();
    data = $(form).serialize();
    $.post(
        $(form).attr('action'),
        data,
        function(data) {
            if (data.result) {
                location.reload(true);
            } else {
                $.each(data['errors'], function(i, v) {
                    var errors = $('<div class="errors_box">');
                    $.each(v, function(i1, v1) {
                        var error = $('<div class="error">');
                        error.append(v1)
                        errors.append(error);
                    });
                    $(form).find('[name='+i+']:first').after(errors);
                });
                $(form).find('.submit_button').removeAttr('disabled');
            }
        },
        'json');
    return false;
}

function reviews_alter_login(form_id) {
    loginDone = function() {
        if('toolbar_call' in window) {
            toolbar_call();
        }
        $('#'+form_id).submit();
        popup.hidePopup('login_form_layer');
        setTimeout(function() {popup.hidePopup('login_form_layer');}, 500); // some stray popup, I don't know where it comes from, so just hide it....
    };
    if(!$('#login_form_layer').length) {
        $('#'+form_id).submit();
    } else {
        alterLoginFormBehaviour();
        popup.showPopup('login_form_layer');
    }    
}

function attach_star_hints(widget) {
    if (!widget) widget = $(document);
    widget.find('div.star-rating').mouseover(function(){
        var hint = '';
        var tip = $(this).parents('.survey_list').find('.rating_hint');
        var value = $(this).find('a').attr('title');
        switch(value) {
            case '1': hint = 'Poor'; 
                      break;
            case '2': hint = 'Fair'; 
                      break;
            case '3': hint = 'Good'; 
                      break;
            case '4': hint = 'Very Good'; 
                      break;
            case '5': hint = 'Excellent'; 
                      break;
            default:  hint = '';
        }
        tip[0].data = tip[0].data || tip.html();
        tip.html(hint || value);
    });
    widget.find('div.star-rating').mouseout(function(){
        var tip = $(this).parents('.survey_list').find('.rating_hint');
        tip.html(tip[0].data || '');
    });
}

$(document).ready(function() {
    $(".thumbs_down_active").click(function() {
        thumbs_clicked(this, "down");
        return false;
    });
    $(".thumbs_up_active").click(function() {
        thumbs_clicked(this, "up");
        return false;
    });
    repaint_stars();
});


