function add_thousands(num,separator) {
    separator = arguments.length == 1 ? "," : separator;
    var a = String(Math.abs(num)).replace(/\.\d+$/,"").split("").reverse();
    for(var b = 0; b < a.length; b++)
        if(b && (b % 3 == 0)) a[b] += separator;
    var c = String(num).match(/\.\d+$/);
    return (num >= 0 ? "" : "-") + a.reverse().join("") + (c == null ? "" : c);
}

function GetChartBar(AColor, APrc, IsMD) {
    if (APrc == 0) return '';

    if (IsMD) {
        t = '<div class=gr style="border:1px solid #000; background-color:' + AColor + '; width:' + zoom * APrc + '%;"></div>';
    } else {
        t = '<div class=gr style="background-color:' + AColor + '; width:' + zoom * APrc + '%;"></div>';
    }

    return t;
}

function PopulateGrid(area_id, tip) {
    // which column to fill
    var col = 2;
    var oTable = document.getElementById("oTable");
    var oMap = document.getElementById("oMap");
    var oRow;
    var cand_length = cfg.opponents;

    var t;
    if (area_id == '-') {
        document.getElementById("oAreaName").innerHTML = '';
        document.getElementById("oListTotal").innerHTML = '';
        document.getElementById("oParticipat").innerHTML = '';
        document.getElementById("oParticipatP").innerHTML = '';
        document.getElementById("oVoturi").innerHTML = '';

        if (cfg.has_map == 1) {
           t = '<img src="' + cfg.map_img_root + cfg.district + '_' + cfg.lang + '.gif" width=' +
               cfg.img_width + ' height=' + cfg.img_height + ' alt="' + cfg.imgalt + '">';
           oMap.innerHTML = t;
        }

    } else if (tip == 'area') {
        // alert(area_id);
        var oList = document.getElementById("oAreaList");
        document.getElementById("oAreaName").innerHTML = oList.options[oList.options.selectedIndex].text;
        document.getElementById("oListTotal").innerHTML = add_thousands(area_activity[area_id]['lt']);
        document.getElementById("oParticipat").innerHTML = add_thousands(area_activity[area_id]['p']);
        t = area_activity[area_id]['pp'];
        document.getElementById("oParticipatP").innerHTML = t == 0 ? '-' : add_thousands(t) + '%';
        document.getElementById("oVoturi").innerHTML = add_thousands(area_activity[area_id]['v']);

        var area_filename = oList.options[oList.options.selectedIndex].value;

        var m3px = navigator.userAgent.indexOf('MSIE') ? 'margin-left:3px' : '';
        var m281px = navigator.userAgent.indexOf('MSIE') ? 281 : 280;

        t = '<img width=' + cfg.map_width + ' height=' + cfg.map_height + ' src="' + cfg.map_img_root + '_moldova.gif"><br>' +
            '<img width=' + cfg.map_width + ' height=' + cfg.map_height + ' src="' + cfg.map_img_root + cfg.district + '_r.gif" style="position:absolute; margin-top:-' + m281px + 'px; ' + m3px + '">';

        if (area_filename != 'moldova') {
            t = t + '<img width=225 height=280 src="' + cfg.map_img_root + area_filename + '_b.gif" style="position:absolute; margin-top:-' + m281px + 'px; ' + m3px + '"><br><br>';
        } else {
            t = t + '<br><br>';
        }

        if (cfg.has_map == 1) {
            oMap.innerHTML = t;
        }

    } else if (tip == 'sat') {
        var oList = document.getElementById("oSatList");
        document.getElementById("oAreaName").innerHTML = oList.options[oList.options.selectedIndex].text;
        document.getElementById("oListTotal").innerHTML = add_thousands(sat_activity[area_id]['lt']);
        document.getElementById("oParticipat").innerHTML = add_thousands(sat_activity[area_id]['p']);
        t = sat_activity[area_id]['pp'];
        document.getElementById("oParticipatP").innerHTML = t == 0 ? '-' : add_thousands(t) + '%';
        document.getElementById("oVoturi").innerHTML = add_thousands(sat_activity[area_id]['v']);

        if (cfg.has_map == 1) {
           t = '<img src="' + cfg.map_img_root + cfg.district + '_' + cfg.lang + '.gif" width=' +
               cfg.img_width + ' height=' + cfg.img_height + ' alt="' + cfg.imgalt + '">';
           oMap.innerHTML = t;
        }
    }

    t = 0;
    var s1, s2, v2, vp1, vp2, strGraf;
    for (var i = 0; i < cand_length; i++) {
        oRow = oTable.rows[i+1];

        s1 = add_thousands(curr_area_voturi[i]);

        vp1 = curr_area_voturi_p[i];
        s2 = vp1.toFixed(2);
        strGraf = GetChartBar('#990000', vp1);

        if (area_id != '-') {
            if (tip == 'area') {
                v2 = area_voturi[area_id][i];
                vp2 = area_voturi_p[area_id][i];
            } else {
                v2 = -1;
                vp2 = sat_voturi_p[area_id][i];
            }
            s1 = s1 + '<br>';
            if (v2 != -1) { s1 = s1 + add_thousands(v2) } else { s1 = s1 + '&nbsp;' }

            s2 = s2 + '<br>' + vp2.toFixed(2);
            strGraf = strGraf + GetChartBar('#004888', vp2);

        }
        oRow.cells[ col ].innerHTML = s1;
        oRow.cells[ col+1 ].innerHTML = s2;

        oRow.cells[ col+2 ].innerHTML = strGraf;
    }
}

function ScrollArea(tip, k) {
    var oList;

    if (tip == 'area') {
        oList = document.getElementById("oAreaList");
        // document.getElementById("oSatList").options.selectedIndex = 0; // uncoment when data will be av
    } else {
        oList = document.getElementById("oSatList");
        document.getElementById("oAreaList").options.selectedIndex = 0;
    }

    var i = oList.options.selectedIndex + k;
    if ((k == -1 && i == -1) || (k == 1 && i >= oList.options.length)) { return; }

    oList.options.selectedIndex = i;
    // var cand_id = oCandidatList.options[oCandidatList.options.selectedIndex].value;

    RefreshGrid(tip);
}

function RefreshGrid(tip) {
    if (isRefreshing) return;
    // if (document.getElementById("oCandToLeft").disabled) return;

    var oList = tip == 'area' ? oList = document.getElementById("oAreaList")
                              : oList = document.getElementById("oSatList");
    var area_id = oList.options[oList.options.selectedIndex].value;

    sel_area_id = area_id;
    sel_area_tip = tip;

    RefreshLegend();

    if (IsBestFit) zoom = CalcZoomFactor(sel_area_id, sel_area_tip);

    PopulateGrid(sel_area_id, sel_area_tip);
}


/*
function ChangeArea(oList, tip) {
    var area_id = oList.options[oList.options.selectedIndex].value;

    var oSecondList;
    if (tip == 'area') {
        oSecondList = document.getElementById("oSatList");
    } else {
        oSecondList = document.getElementById("oAreaList");
    }
    oSecondList.options.selectedIndex = 0;

    sel_area_id = area_id;
    sel_area_tip = tip;

    PopulateGrid(area_id, tip);
    RefreshLegend(oList);
} */


function setButtonState(bt, is_on) {
    if (is_on) {
        bt.disabled = false;
        bt.className = 'bt';
    } else {
        bt.disabled = true;
        bt.className = 'bt0';
    }
}

function RefreshLegend() {
    isRefreshing = 1;
    var divLegend = document.getElementById("oLegend");
    var oList = sel_area_tip == 'area' ? document.getElementById("oAreaList")
                                       : document.getElementById("oSatList");
    var i = oList.options.selectedIndex;

    if (cfg.sat_data == 1) {
        var oOtherList = sel_area_tip == 'area' ? document.getElementById("oSatList")
                                                : document.getElementById("oAreaList");
        oOtherList.options.selectedIndex = 0;
    }

    if (sel_area_tip == 'area') {
        setButtonState(document.getElementById("oPrevArea"), i != 0);
        setButtonState(document.getElementById("oNextArea"), i != oList.options.length-1);

        if (cfg.sat_data == 1) {
          setButtonState(document.getElementById("oPrevSat"), false);
          setButtonState(document.getElementById("oNextSat"), true);

          document.getElementById("oSatDiv").style.color = '#666';
          document.getElementById("oAreaDiv").style.color = '#004888';
        }
    } else {
        setButtonState(document.getElementById("oPrevSat"), i != 0);
        setButtonState(document.getElementById("oNextSat"), i != oList.options.length-1);

        setButtonState(document.getElementById("oPrevArea"), false);
        setButtonState(document.getElementById("oNextArea"), true);

        document.getElementById("oSatDiv").style.color = '#004888';
        document.getElementById("oAreaDiv").style.color = '#666';
    }


    if (i == 0) {
        divLegend.innerHTML = legend;
        if (cfg.sat_data == 1) {
            document.getElementById("oSatDiv").style.color = 'gray';
            document.getElementById("oAreaDiv").style.color = 'gray';
        }
    } else {
        var uri = oList.options[i].value == 'moldova' ? 'total'
                                                      : oList.options[i].value;
        if (sel_area_tip == 'area') {
        divLegend.innerHTML = '&nbsp;<font style="background-color:#c8000c">&nbsp;&nbsp;</font> <span id="oConc1">' + area_title + '</span><p></p>&nbsp;<font style="background-color:#004888">&nbsp;&nbsp;</font> <span id="oConc2"><a href="../' + uri + '/">' + oList.options[i].text + '</a></span><br><br>';
        } else {
        divLegend.innerHTML = '&nbsp;<font style="background-color:#c8000c">&nbsp;&nbsp;</font> <span id="oConc1">' + total_str + '</span><p></p>&nbsp;<font style="background-color:#004888">&nbsp;&nbsp;</font> <span id="oConc2">' + oList.options[i].text + '</span><br><br>';
        }
    }
    isRefreshing = 0;
}

function CalcZoomFactor() {
    var n = curr_area_voturi_p.length;
    var max_v = 0;

    for (var i = 0; i < n; i++) {
        if (curr_area_voturi_p[i] > max_v) max_v = curr_area_voturi_p[i];

        if (sel_area_id != '-') {
            if (sel_area_tip == 'area') {
                t = area_voturi_p[sel_area_id][i];
            } else {
                t = sat_voturi_p[sel_area_id][i];
            }
            if (t > max_v) max_v = t;
        }
    }

    // alert(max_v);
    return 100 / max_v;
}

function ToggleBestFit() {
    var oBt = document.getElementById("oBestFitButton");
    IsBestFit = ! IsBestFit;

    if (IsBestFit) {
        zoom = CalcZoomFactor();
        oBt.innerHTML = '-'; // lang_res['small_str'];
    } else {
        zoom = 1;
        oBt.innerHTML = '+'; // lang_res['large_str'];
    }
    RefreshGrid(sel_area_tip);
}

function fnInit() {
    // PopulateGrid('-', 1);
    // RefreshLegend();
    RefreshGrid('area');
}

