function transform_target_string(target_string) {
    return target_string.replace('__', '.').replace('___', ':');
}

function transform_target_data(target_data) {
    return target_data.replace('.', '__').replace(':', '___');
}

function get_count_text(count) {
    if (count == 1) {
        txt = " reader likes ";
    } else {
        txt = " readers like ";
    }
    txt += "this.";
    return txt;
}

function get_span_from_target(target_text) {
    return $("#like_info_" + transform_target_data(target_text));
}

function show_like_login(target_data) {
    id_string = "#like_login_" + transform_target_data(target_data);
    $(id_string).show();
}

function toggle_like_text(target_text, has_liked, can_like) {
    var the_link = $("<a></a>");
    the_link.attr("href", "#");
    var form_data = {"target": target_text};
    var id_string = transform_target_data(target_text);
    the_link.click(function(e) {
        e.preventDefault();
        $.post("/likes/toggle/", form_data, function(data) {
            if (!data.error) {
                toggle_like_text(target_text, data.has_liked, data.can_like)
                var sel = "#like_count_" + id_string;
                var count_elem = $(sel);
                count_elem.html('<span class="like-count">' + data.count + '</span>' + get_count_text(data.count));
            } else {
                if (data.login_required) {
                    show_like_login(target_text);
                } else {
                    the_span.text("Looks like something bad happened - please reload the page");
                }
            }
        }, "json");
    });
    the_link.text("Like it!");
    if (can_like) {
        if (has_liked) {
            the_link.text("Unlike it!");
        }
    }
    var the_span = get_span_from_target(target_text);
    the_span.html(the_link);
}

function initial_likes() {
    var target_map = {"target": []};
    $(".like_span").each(function() {
        var the_span = $(this);
        target_map["target"].push(
            transform_target_string(the_span.attr("id").replace("like_info_", ""))
        )
    })
    $.post('/likes/check/', target_map, function(data) {
        $.each(data, function(idx, item) {
            if (!item.error) {
                toggle_like_text(item.target, item.has_liked, item.can_like);
            } else {
                var the_span = get_span_from_target(item.target);
                the_span.text("Looks like something bad happened - please reload the page.");
           }
        });
    }, 'json');
};

