var results_rows;
var results_weights = [];
var results_country_names = [];
var results_country_flags = [];
var product_order = [];

var top_score_count = 10;

function init()
{
    var ads_div = $("products_div");
    for(var i=0; i<ads_div.getElementsByTagName("div").length; ++i)
    { product_order.push(i); }
    product_order.sort(randomSort);
    ad_div = Element("div");
    ad_div.className = "product_div";
    document.getElementsByTagName("body")[0].insertBefore(ad_div, $("intro_header"));
    var h3 = Element("h3");
    h3.appendChild(TextNode("A Real\u00a0Man has:"));
    ad_div.appendChild(h3);
    var p = Element("p");
    p.setAttribute("id", "product_link_image");
    ad_div.appendChild(p);
    var p = Element("p");
    p.setAttribute("id", "product_link");
    ad_div.appendChild(p);
    var p = Element("p");
    p.setAttribute("id", "product_desc");
    ad_div.appendChild(p);
    var p = Element("p");
    p.setAttribute("id", "product_nav");
    var a = Element("a");
    a.setAttribute("start_point", "0");
    a.appendChild(TextNode("See something else"));
    addEvent(a, "click", product_nav);
    p.appendChild(a);
    ad_div.appendChild(p);
    product_nav(true);

    results_rows = $("results_table").getElementsByTagName("tr");
    for(var i=1; i<results_rows.length; ++i)
    {
        var weight = results_rows[i].getElementsByTagName("select")[0];
        var name_spans = results_rows[i].getElementsByTagName("span");
        var imgs = results_rows[i].getElementsByTagName("img");
        if(weight && name_spans.length > 0 && imgs.length > 0)
        {
            var name = name_spans[0].firstChild ? name_spans[0].firstChild.nodeValue : "";
            results_weights.push(weight);
            results_country_names.push(name);
            results_country_flags.push(imgs[1].getAttribute("src"));
        }
        else
        { alert("error"); return; }
    }

    var instruction_div = $("instructions");
    var p = Element("p");
    p.appendChild(TextNode("Changes to the ratings take effect immediately."));
    p.appendChild(Element("br"));
    p.appendChild(TextNode("Scroll back up here to see the new results."));
    instruction_div.appendChild(p);

    var custom_link_p = $("custom_link_p");
    var button_length = custom_link_p.getElementsByTagName("button").length;
    if(button_length == 0)
    {
        removeChildren(custom_link_p);
        var button = Element("button");
        button.appendChild(TextNode("a"));
        button.style.visibility = "hidden";
        custom_link_p.appendChild(button);
    }

    if(location.href.match(/custom=\d/))
    { recompute_scores(); }
}

function product_nav(first_run)
{
    var from_link = this.tagName && this.tagName.toUpperCase() == "A";
    var reverse = from_link && this.getAttribute("reverse") == "1";
    var i = from_link && this.getAttribute("start_point").toString().match(/^\d+$/) ? parseInt(this.getAttribute("start_point")) : -1;

    if(reverse)
    { --i; }
    else
    { ++i; }
    i = i % product_order.length;

    if(i < 0)
    { i += product_order.length; }

    var div = $("products_div").getElementsByTagName("div")[product_order[i]];
    var product_name = div.getAttribute("product_name");

    var img_p = $("product_link_image");
    removeChildren(img_p);
    var img_a = Element("a");
//    img_a.target = "_blank";
    var img = Element("img");
    img.setAttribute("src", div.getAttribute("product_img"));
    img_a.appendChild(img);
    img_a.setAttribute("href", div.getAttribute("product_link"));
    img_p.appendChild(img_a);

    var p = $("product_link");
    removeChildren(p);
    var a = Element("a");
//    a.target = "_blank";
    a.setAttribute("href", div.getAttribute("product_link"));
    a.appendChild(TextNode(div.getAttribute("product_name")));
    p.appendChild(a);

    var desc_p = $("product_desc");
    removeChildren(desc_p);
    desc_p.appendChild(TextNode(div.getAttribute("product_desc")));

    if(!first_run || isEvent(first_run))
    {
        var nav_p = $("product_nav");
        removeChildren(nav_p);

        var a_left = Element("a");
        addEvent(a_left, "click", product_nav);
        a_left.setAttribute("reverse", "1");
        a_left.setAttribute("start_point", i);
        a_left.appendChild(TextNode("Back"));
        nav_p.appendChild(a_left);

        nav_p.appendChild(TextNode(" "));
        nav_p.appendChild(TextNode("\u00a0\u00a0\u00a0"));
        nav_p.appendChild(TextNode(" "));

        var a_right = Element("a");
        addEvent(a_right, "click", product_nav);
        a_right.setAttribute("start_point", i);
        a_right.appendChild(TextNode("Next"));
        nav_p.appendChild(a_right);
    }
}

function switch_games()
{
    var code = get_code();
    var year = this.getAttribute("year");

    location.href = "/?custom="+code+"&year="+year+"#results";
}

function recompute_scores()
{
    var games_select_table = $("games_select");
    var games_cells = games_select_table.getElementsByTagName("td");
    for(var i=0; i<games_cells.length; ++i)
    {
        var year = games_cells[i].getAttribute("year");
        var games_links = games_cells[i].getElementsByTagName("a");
        for(var j=0; j<games_links.length; ++j)
        {
            games_links[j].removeAttribute("href");
            games_links[j].setAttribute("year", year);
            addEvent(games_links[j], "click", switch_games);
        }
    }

    var country_scores = [];

    for(var i=0; i<results_weights.length; ++i)
    {
        var weight = parseInt(results_weights[i].value, 10) != 0 ? parseInt(results_weights[i].value, 10) : 0;
        var magnitude = Math.abs(weight);

        var score = weight != 0 ?
            weight/magnitude*Math.pow(1.5, magnitude)-1 :
            0;

        var country_name = results_country_names[i];

        if(country_name.length > 0)
        {
            if(!country_scores[country_name])
            {
                country_scores[country_name] = [];
                country_scores[country_name]["name"] = country_name;
                country_scores[country_name]["score"] = 0;
                country_scores[country_name]["flag"] = results_country_flags[i];
            }
            country_scores[country_name]["score"] += score;
        }
    }

    var computed_results = [];
    for(var i in country_scores)
    { computed_results.push(country_scores[i]); }
    computed_results.sort(resultSort);

    for(var i=1; i<=top_score_count; ++i)
    {
        var row = $("place_"+i+"_row");
        var score_row = $("place_"+i+"_score_row");
        removeChildren(row);
        removeChildren(score_row);

        if(computed_results[i-1])
        {
            var score = computed_results[i-1]["score"];
            score = Math.round(score*100)/100;

            var img = Element("img");
            img.setAttribute("width", 16);
            img.setAttribute("height", 11);
            img.setAttribute("alt", "");
            img.setAttribute("src", computed_results[i-1]["flag"]);
            row.appendChild(img);
            row.appendChild(TextNode(" "));
            row.appendChild(TextNode(computed_results[i-1]["name"]));
            score_row.appendChild(TextNode(score));
        }
    }

    var custom_label_span = $("custom_results");
    if(custom_label_span.childNodes.length == 0)
    {
        custom_label_span.appendChild(TextNode("Customized "));
        var span = $("return_to_default");
        var a = Element("a");
        addEvent(a, "click", revert);
//         a.setAttribute("href", "/?year="+get_year()+"#results");
        a.appendChild(TextNode("Revert to default"));
        span.appendChild(a);
    }

    var custom_link_p = $("custom_link_p");
    removeChildren(custom_link_p);
    var button = Element("button");
    button.appendChild(TextNode("Create a link to these results"));
    addEvent(button, "click", create_link);
    custom_link_p.appendChild(button);
}

function revert()
{
    location.replace("/?year="+get_year()+"&rand="+Math.floor(Math.random()*100000)+"#results");
}

function create_link()
{
    var code = get_code();
    if(code.length == 0)
    { return; }

    var custom_link_p = $("custom_link_p");
    removeChildren(custom_link_p);
    var a = Element("a");
    a.appendChild(TextNode("Link to these results"));
    a.setAttribute("href", "/?custom="+code+"&year="+get_year());
    custom_link_p.appendChild(a);
}

function get_code()
{
    var xmlHttp;

    if(window.XMLHttpRequest)
    {
        try
        { xmlHttp = new XMLHttpRequest(); }
        catch(e)
        { xmlHttp = false; }
    }

    //ActiveX
    else if(window.ActiveXObject)
    {
        try
        { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch(e)
        {
            try
            { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch(e)
            { xmlHttp = false; }
        }
    }

    if(!xmlHttp)
    { return; }

    var table = $("results_table");
    var tbody = table.getElementsByTagName("tbody")[0];
    var rows = tbody.getElementsByTagName("tr");
    var custom_array = [];
    for(var i=0; i<rows.length; ++i)
    {
        var menu = rows[i].getElementsByTagName("select")[0];
        var event = menu.getAttribute("id");
        var score = menu.value;
        custom_array.push(event+":"+score);
    }
    var custom_string = custom_array.join("::");
    var string_id = "";

    xmlHttp.open("GET", "generate_link.xml.pl?string="+encodeURIComponent(custom_string), false);
    xmlHttp.send(null);
    if(xmlHttp.status == 200 && xmlHttp.responseXML)
    {
        var root = xmlHttp.responseXML.getElementsByTagName("root")[0];
        string_id = root.getAttribute("string_id");
    }
    else
    {
        alert("Error connecting to server");
    }

    return string_id;
}

function get_year()
{
    var games_header = $("games_header");
    var year = parseInt(games_header.firstChild.nodeValue, 10);

    return year;
}

function resultSort(a, b)
{
    if(a["score"] > b["score"])
    { return -1; }

    else if(a["score"] < b["score"])
    { return 1; }

    else
    {
        if(a["name"] < b["score"])
        { return -1; }
        else if(a["name"] > b["score"])
        { return 1; }
    }

    return 0;
}

function randomSort()
{
    return (Math.round(Math.random())-0.5);
}

function removeChildren(object)
{
    if(object)
    {
        while(object.firstChild)
        { object.removeChild(object.firstChild); }
    }
}
function addEvent(obj, evType, fn)
{
    if (obj.addEventListener)
    { obj.addEventListener(evType, fn, false); }
    else
    { obj.setAttribute("on"+evType, fn); }
}
function Element(text)
{ return document.createElement(text); }
function TextNode(text)
{ return document.createTextNode(text); }
function $()
{
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++)
    {
        var element = arguments[i];
        if (typeof element == "string")
        { element = document.getElementById(element); }
        if (arguments.length == 1)
        { return element; }
        elements.push(element);
    }
    return elements;
}
function isEvent(o)
{
    return o && "undefined" != typeof Event && o.eventPhase;
}
