function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            oldonload();
            func();
        }
    }
}

function doc_id(id) {
    return document.getElementById(id);
}

function makeHttpRequest(url, callback_function, return_json, post_data) {
    var xmlHttp, response;
    try {
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if (!xmlHttp) return;
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
            if (return_json) {
                try {
                    response = eval('(' + xmlHttp.responseText + ')');
                } catch (e) {
                    alert('There was an error: ' + e + '\nResponse: ' + xmlHttp.responseText);
                }
            } else {
                response = xmlHttp.responseText;
            }
            callback_function(response);
        }
    };
    if (post_data) {
        xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.send(post_data);
    } else {
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
}

var stars = new Array();
var star_images = new Array();

function init_rate_file() {
    for (var i = 1; i <= 5; i++) {
        stars[i] = doc_id("rate_" + i);
        star_images[i] = stars[i].src;
        stars[i].style.cursor = "pointer";
        stars[i].title = i;
        stars[i].onmouseover = function () {
            star_hover(this.title);
        };
        stars[i].onmouseout = clear_stars;
        stars[i].onclick = function () {
            rate_file(this.title);
        };
    }
}
function star_hover(star_id) {
    for (i = 1; i <= star_id; i++) stars[i].src = "/images/star.png";
}
function clear_stars() {
    for (i = 1; i <= 5; i++) stars[i].src = star_images[i];
}
function rate_file(rating) {
    function back_function(server_r) {
        doc_id("file_rating").innerHTML = "Thanks for voting!";
    }
    makeHttpRequest("/rate/" + fid + "/" + rating + "/", back_function, false);
}
addLoadEvent(init_rate_file);

