var STR_CURRENT_MATCH = null;
var STR_FIXTURES_STATIC;
var STR_MODE = "my";
var STR_RATIO = false;

function _get_params() {
    var tmp = document.location.href.split("?");
    if (tmp.length < 2) {
        return {};
    }

    var params = tmp[1].split("&");
    var result = {};

    for (var i=0; i<params.length; i++) {
        tmp = params[i].split("=");
        result[tmp[0]] = tmp[1];
    }

    return result;
}

// return new tag, default is div
function _new(type) {
    if (type == null) {
        type = "div";
    }
    return document.createElement(type);
}

// print msg into debug div
function _debug(msg) {
    document.getElementById("debug").innerHTML += msg+"<br/>";
}

// clone js object
function _clone(obj){
    if(obj == null || typeof(obj) != 'object') {
        return obj;
    }

    if (obj.length != null) {
        var temp = [];
        for (var i=0; i<obj.length; i++) {
            temp.push(_clone(obj[i]));
        }
        return temp;
    }

    var temp = {};
    for(var key in obj)
        temp[key] = _clone(obj[key]);
    return temp;
}

// create formated div (stupid function)
function tools_cell(parent, width) {
    var cell = document.createElement("div");
    cell.className = "str_cell";
    cell.style.width = width+"px";
    parent.appendChild(cell);
    return cell;
}

// init application
function str_init() {

    STR_FIXTURES = _clone(STR_FIXTURES_STATIC);
    var code = _get_params().code;

    // easter egg
    if (_get_params().ratio == "true") {
        STR_RATIO = true;
    }

    
    if (code != null) {


        while (true) {
            code = code.split("-");
            if (code.length != 3) {
                break;
            }
            var abc = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            var length = code[0];
            var first  = code[1];

            code = code[2].replace(/[^a-zA-Z0-9~]/g, "");;

            var size = parseInt(length)+2;
            if (size < 3) {
                break;
            }

            if (code.length % size != 0) {
                //break;
            }

            var bite; 
            var omi;
            for (var i=0; i<code.length; i+=size) {
                bite = code.substr(i, size);
                omi = parseInt(first)+parseInt(str_decode(abc, bite.substr(0, parseInt(length))));
                STR_FIXTURES["id"+omi].goals = str_decode(abc, bite.substr(parseInt(length), 1))+":"+str_decode(abc, bite.substr(parseInt(length)+1, 1));
            }

            break;
        }
    }

    // init current match
    STR_CURRENT_MATCH = str_get_first_match(1);

    tab_create(STR_RESULT_CONF);
    tab_create(STR_TABLE_CONF);
    sbox_create(STR_SBOX_CONF); //

//    str_select_match(STR_CURRENT_MATCH);
}

// build header
function str_header() {

    var tag;
    tag = document.getElementById("str_home_logo");
    tag.style.backgroundImage = "url(/str/pics/clubs_list/"+STR_FIXTURES[STR_CURRENT_MATCH].homeoti+".gif)"

    tag = document.getElementById("str_home_box");
    tag.innerHTML = STR_FIXTURES[STR_CURRENT_MATCH].home;

    tag = document.getElementById("str_goals_box");
    tag.innerHTML = STR_FIXTURES[STR_CURRENT_MATCH].goals.replace(/:/, " : ");

    tag = document.getElementById("str_away_box");
    tag.innerHTML = STR_FIXTURES[STR_CURRENT_MATCH].away;

    tag = document.getElementById("str_away_logo");
    tag.style.backgroundImage = "url(/str/pics/clubs_list/"+STR_FIXTURES[STR_CURRENT_MATCH].awayoti+".gif)"
}

// user requested next match
function str_next_match() {

    var before = true;
    var next = null;
    for (omi in STR_FIXTURES) {
        if (STR_FIXTURES[omi].mday != STR_FIXTURES[STR_CURRENT_MATCH].mday) {
            continue;
        }
        if (before == true) {
            if (omi == STR_CURRENT_MATCH) {
                before = false;
            }
            continue;
        }

        next = omi;
        break;
    }

    if (next == null) {
        next = str_get_first_match(STR_FIXTURES[STR_CURRENT_MATCH].mday);
    }

    str_select_match(next);
}

// user requested previous match
function str_prev_match() {

    var prev = null;
    for (omi in STR_FIXTURES) {
        if (STR_FIXTURES[omi].mday != STR_FIXTURES[STR_CURRENT_MATCH].mday) {
            continue;
        }
        if (omi == STR_CURRENT_MATCH) {
            break;
        }
        prev = omi;
    }

    if (prev == null) {
        prev = str_get_last_match(STR_FIXTURES[STR_CURRENT_MATCH].mday);
    }

    str_select_match(prev);
}

// user selected match
function str_select_match(omi) {
    STR_CURRENT_MATCH = omi;
    str_header();

    // update results
    var selected = document.getElementById("str_result_"+omi);
    for (var i=0; i<selected.parentNode.childNodes.length; i++) {
        if (selected.parentNode.childNodes[i].omi) {
            selected.parentNode.childNodes[i].className = "str_result_row";
            if (selected.parentNode.childNodes[i].omi == omi) {
                selected.parentNode.childNodes[i].childNodes[3].innerHTML = STR_FIXTURES[omi].goals;
            }
        }
    }
    selected.className = "str_result_row_active";

    // rebuild table
    tab_select_by_user(STR_TABLE_CONF, "my_table");
}

// user selected match day
function str_set_mday(mday) {
    STR_CURRENT_MATCH = str_get_first_match(mday);
    tab_select_by_user(STR_RESULT_CONF, STR_MODE+"_results");
    tab_select_by_user(STR_TABLE_CONF, STR_MODE+"_table");
    str_header();
}

// return first match of mday
function str_get_first_match(mday) {
    for (var key in STR_FIXTURES) {
        if (STR_FIXTURES[key].mday != mday) {
            continue;
        }
        return key;
        break;
    }
}

// return last match of mday
function str_get_last_match(mday) {
    var last = null;
    for (var omi in STR_FIXTURES) {
        if (STR_FIXTURES[omi].mday != mday) {
            continue;
        }
        last = omi;
    }
    return last;
}

// build my results table
function str_my_results() {
    STR_MODE = "my";
    return str_results(STR_FIXTURES);
}

// build real results table
function str_real_results() {
    STR_MODE = "real";
    return str_results(STR_FIXTURES_STATIC);
}

// build results table
function str_results(fixtures) {

    var container = document.createElement("div");

    var row = null;
    var cell = null;

    var mday = fixtures[STR_CURRENT_MATCH].mday;

    for (var omi in fixtures) {
        if (fixtures[omi].mday != mday) {
            continue;
        }

        // one row per match
        row = document.createElement("div");
        row.id = "str_result_"+omi;
        row.omi = omi;
        if (omi == STR_CURRENT_MATCH) {
            row.className = "str_result_row_active";
        } else {
            row.className = "str_result_row";
        }
        row.onmouseover = function () { if (this.className!="str_result_row_active") this.className="str_result_row_mover";};
        row.onmouseout  = function () { if(this.omi != STR_CURRENT_MATCH) { this.className="str_result_row";}};
        row.onclick     = function () { str_select_match(this.omi)};
        container.appendChild(row);

        // date
        cell = tools_cell(row, 65);
        cell.style.paddingLeft = "12px";
        cell.innerHTML = fixtures[omi].start;

        // home team name
        cell = tools_cell(row, 82);
        cell.innerHTML = fixtures[omi].home;
        cell.style.textAlign = "right";

        // home logo
        cell = tools_cell(row, 28);
        cell.style.marginLeft = "12px";
        cell.style.marginRight = "12px";
        cell.style.height = "28px";
        cell.style.backgroundImage = "url(/str/pics/clubs_list/"+fixtures[omi].homeoti+".gif)";

        // goals
        cell = document.createElement("div");
        cell.className = "str_goals";
        cell.style.marginTop = "3px";
        cell.style.lineHeight = "20px";
        cell.style.height = "20px";
        cell.style.backgroundImage = "url(/str/pics/score.gif)";
        cell.innerHTML = fixtures[omi].goals;
        row.appendChild(cell);

        // away logo
        cell = tools_cell(row, 28);
        cell.style.marginLeft = "12px";
        cell.style.marginRight = "12px";
        cell.style.height = "28px";
        cell.style.backgroundImage = "url(/str/pics/clubs_list/"+fixtures[omi].awayoti+".gif)";

        // away team name
        cell = tools_cell(row, 82);
        cell.innerHTML = fixtures[omi].away;
        cell.style.textAlign = "left";

        // link box 
        row = document.createElement("div");
        row.className = "str_linkbox";
        container.appendChild(row);

        // if report exists
        if (fixtures[omi].report) {

            // make box clickable
            row.style.cursor = "pointer";
            row.onclick = new Function("document.location.href='"+fixtures[omi].report+"';");
            row.style.position = "relative";
        
            // display icon
            var icon = document.createElement("div");
            icon.className = "str_icon_report";
            row.appendChild(icon);
        }

        cell = document.createElement("div");
        cell.style.clear = "both";
        container.appendChild(cell);

    }
    return container;
}

// user changed score
function str_change_score(change, delta) {

    if (STR_MODE != "my") {
        return;
    }

    var leave = change*-1+1;

    var goals = STR_FIXTURES[STR_CURRENT_MATCH].goals.split(":");
    if (isNaN(goals[change])) {
        goals = [0,0];
    }
    var update = parseInt(goals[change]);
    update += delta;
    if (update < 0) {
        update = 0;
    }
    if (update > 20) {
        update = 20;
    }
    goals[change] = update;
    STR_FIXTURES[STR_CURRENT_MATCH].goals = goals[0]+":"+goals[1];
    str_select_match(STR_CURRENT_MATCH);
}

// build real table
function str_real_table() {
    var table = str_get_real_table(STR_FIXTURES[STR_CURRENT_MATCH].mday);
    return str_table(table, "real");
}

// build my table
function str_my_table() {
    var table = str_get_my_table(STR_FIXTURES[STR_CURRENT_MATCH].mday);
    return str_table(table, "my");
}

// build table
function str_table(table, mode) {

    var row;
    var cell;
    var current;

    var container = document.createElement("div");
    var pos = 1;

    row = _new();
    row.className = "str_table_row";
    container.appendChild(row);

    cell = _new();
    cell.className = "str_table_cell";
    cell.style.width = "30px";
    row.appendChild(cell);

    cell = _new();
    cell.className = "str_table_cell";
    cell.style.width = "30px";
    cell.style.fontWeight = "bold";
    cell.innerHTML = "Platz";
    row.appendChild(cell);

    cell = _new();
    cell.className = "str_table_cell";
    cell.style.width = "82px";
    cell.style.fontWeight = "bold";
    cell.innerHTML = "Team";
    row.appendChild(cell);

    cell = _new();
    cell.className = "str_table_cell";
    cell.style.width = "30px";
    cell.style.fontWeight = "bold";
    cell.innerHTML = "Sp.";
    row.appendChild(cell);

    cell = _new();
    cell.className = "str_table_cell";
    cell.style.width = "30px";
    cell.style.fontWeight = "bold";
    cell.innerHTML = "Pkt.";
    row.appendChild(cell);

    cell = _new();
    cell.className = "str_table_cell";
    cell.style.width = "30px";
    cell.style.fontWeight = "bold";
    cell.innerHTML = "Diff.";
    row.appendChild(cell);

    cell = _new();
    cell.className = "str_table_cell";
    cell.style.width = "30px";
    cell.style.fontWeight = "bold";
    cell.innerHTML = "Tore";
    row.appendChild(cell);

    var counter = 0;

    for (var i=0; i<table.length; i++) {

        for (var j=0; j<table[i].length; j++) {

            counter++;

            current = table[i][j];

            row = _new();
            row.id = "str_table_id"+current.oti;
            row.oti = current.oti;

            reg = new RegExp("#"+counter+"#");
            if (str_lines.match(reg)) {
                row.className = "str_table_row_line";
            } else {
                row.className = "str_table_row";
            }

            if (STR_FIXTURES[STR_CURRENT_MATCH].homeoti == current.oti) {
                row.className = "str_table_row_active";
            }
            if (STR_FIXTURES[STR_CURRENT_MATCH].awayoti == current.oti) {
                row.className = "str_table_row_active";
            }

            cell = _new();
            cell.className = "str_table_cell";
            if (current.last != null) {
                cell.style.position = "relative";
                var arrow = document.createElement("div");
                if (pos > current.last) {
                      arrow.className = "str_arrow_down";
                }
                if (pos < current.last) {
                      arrow.className = "str_arrow_up";
                }
                cell.appendChild(arrow);
            }
            row.appendChild(cell);

            cell = _new();
            cell.className = "str_table_cell";
            if (j == 0) {
                cell.innerHTML = pos;
            }
            row.appendChild(cell);

            cell = _new();
            cell.className = "str_table_cell";
            cell.style.width = "82px";
            cell.style.textAlign = "left";
            cell.innerHTML = current.name;
            if (STR_TABLE_MODS["id_"+current.oti] != null) {
                if (STR_TABLE_MODS["id_"+current.oti].mark != null) {
                    cell.innerHTML = current.name+STR_TABLE_MODS["id_"+current.oti].mark;
                }
            }
            row.appendChild(cell);

            cell = _new();
            cell.className = "str_table_cell";
            cell.innerHTML = current.played;
            row.appendChild(cell);

            cell = _new();
            cell.className = "str_table_cell";
            cell.innerHTML = current.score;
            row.appendChild(cell);

            cell = _new();
            cell.className = "str_table_cell";
            cell.innerHTML = current.diff;
            row.appendChild(cell);

            cell = _new();
            cell.className = "str_table_cell";
            cell.innerHTML = current.goals.join(":");
            row.appendChild(cell);

            if (STR_RATIO) {
                var a = current.goals[0];
                var b = current.goals[1];
                var ratio = "-";
                if ((a != "-") && (b != "-")) {
                    if (b != 0) {
                        ratio = Math.round(a * 100 / b) / 100;
                    }
                }
                cell = _new();
                cell.className = "str_table_cell";
                cell.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;"+ratio;
                row.appendChild(cell);
            }

            container.appendChild(row);
        }
        pos += table[i].length;
    }
    return container;
}

function str_reset_current() {
    var current = STR_FIXTURES[STR_CURRENT_MATCH].mday;
    for (key in STR_FIXTURES) {
        if (STR_FIXTURES[key].mday == current) {
            STR_FIXTURES[key] = _clone(STR_FIXTURES_STATIC[key]);
        }
    }
    tab_select_by_user(STR_RESULT_CONF, STR_MODE+"_results");
    tab_select_by_user(STR_TABLE_CONF, STR_MODE+"_table");
    str_header();
}

function str_reset_all() {
    STR_FIXTURES = _clone(STR_FIXTURES_STATIC);
    tab_select_by_user(STR_RESULT_CONF, STR_MODE+"_results");
    tab_select_by_user(STR_TABLE_CONF, STR_MODE+"_table");
    str_header();
}

function str_display_layer() {
    document.getElementById('str_blabla').style.display='none';
    document.getElementById('str_form').style.display='block';
}

function str_send() {

    var send_name = document.getElementById("str_send_name").value;
    var rec_name = document.getElementById("str_rec_name").value;
    var send_email = document.getElementById("str_send_email").value;
    var rec_email = document.getElementById("str_rec_email").value;

    var url = "/str/send.php?league="+STR_LEAGUEID+"&send_name="+send_name+"&rec_name="+rec_name+"&send_email="+send_email+"&rec_email="+rec_email+"&code="+str_encode_my_table();

    xhr_post(url);
}

function str_close() {
    document.getElementById('str_blabla').style.display='block';
    document.getElementById('str_form').style.display='none';
}

function str_sent(data) {
    str_close();
}

function str_encode_my_table() {
    var min = 99999999;
    var max = 0;

    for (key in STR_FIXTURES) {
        min = (STR_FIXTURES[key].omi.substr(2) < min) ? STR_FIXTURES[key].omi.substr(2) : min;
        max = (STR_FIXTURES[key].omi.substr(2) > max) ? STR_FIXTURES[key].omi.substr(2) : max;
    }
    
    var delta = max-min;
    var length = 2;
    if (delta > 3844) {
        length++;
    }
    if (delta > 238328) {
        length++;
    }

    var abc = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    var encoded = length+"-"+min+"-";
    var goals;

    for (key in STR_FIXTURES) {
        goals = STR_FIXTURES[key].goals.split(":");
        encoded += str_encode(abc, length, STR_FIXTURES[key].omi.substr(2) - min)+""+str_encode(abc, 1, goals[0])+""+str_encode(abc, 1, goals[1]);
    }

    return encoded;
}

function str_encode(abc, format, number) {

    // if we try to encode something which ist not a number, we return the string ~ format
    // times.
    if (isNaN(number)) {
      return new Array(format+1).join('~');
    }

    var encoded = "";
    var factor;
    var current;
    var length = abc.length;
    for (var j=format-1; j>=0; j--) {
        factor = Math.pow(length, j);
        current = Math.floor(number / factor);
        number -= current * factor;
        encoded += ""+abc.substr(current, 1);
    }
    return encoded;
}

function str_decode(abc, string) {

    // if the string only consists of ~ then return -.
    if (string.match(/^~*$/)) {
      return '-';
    }

    var num = 0;
    var length = abc.length;
    for (var i = string.length-1; i>=0; i--) {
        num += abc.indexOf(string.substr(i, 1)) * Math.pow(length, string.length-1-i);
    }

    return num;
}

function str_swapto(league) {
    switch (league) {
        case 51:
            document.location.href = "/de/liga2/spieltagsrechner/index.php";
            break;
        case 52:
            document.location.href = "/de/liga/spieltagsrechner/index.php";
            break;
    }
}
