$(function () {
    $(".bar").each(function (i, val) {
        var progress = parseInt($(val).text(), 10);
        $(val).text('');
        $(val).progressbar({
            value: progress
        });
    });
    $("#showall tr:gt(0)").hover(function () {
        $(this).css("backgroundColor", "#AAD3F2");
    }, function () {
        $(this).css("backgroundColor", "white");
    });

    var a = $("select[name='brackets0name\\[\\]']");
    var b = a.size();
    $("#brackets0_randomfill").click(function () {
        var c = [];
        for (var d = 1; d <= b; ++d) {
            c[d] = d
        }
        c.sort(function () {
            return (Math.round(Math.random()) - 0.5)
        });
        for (d = 0; d < b; ++d) {
            a.get(d).selectedIndex = c[d]
        }
    });
    $("#brackets0_del").click(function () {
        for (var c = 0; c < b; ++c) {
            a.get(c).selectedIndex = 0
        }
    });
    $(".brackets_team").live({
        'mouseover': function () {
            var teamName = $(".left", this).text();
            var editMode = $("select", this).length;
            if (!editMode && teamName.length) {
                $(".brackets_team:contains("+teamName+")").addClass("brackets_team_hover");
            }
        },
        'mouseout': function () {
            $(".brackets_team").removeClass("brackets_team_hover");
        }
    });
    $(".brackets select").change(function () {
        var f = $(this).attr("name");
        var j = parseInt(/\d/.exec(f));
        var e = /\D+/.exec(f);
        var d = parseInt($("select[name='" + f + "']").index(this));
        var i = (d % 2 == 0) ? d + 1 : d - 1;
        var c = Math.floor(d / 2);
        var h = [
        [parseInt($("select[name^='" + e + j + "name']:eq(" + d + ")").val()), parseInt($("select[name^='" + e + j + "score']:eq(" + d + ")").val())],
        [parseInt($("select[name^='" + e + j + "name']:eq(" + i + ")").val()), parseInt($("select[name^='" + e + j + "score']:eq(" + i + ")").val())]
        ];
        if ((h[0][1] != 0 || h[1][1] != 0) && h[0][0] != 0 && h[1][0] != 0) {
            var g = $("select[name^='" + e + (j + 1) + "name']:eq(" + c + ")");
            g.val((h[0][1] > h[1][1]) ? h[0][0] : h[1][0]);
            g.trigger("change");
        }
    })

    var
    i = 0,
    tabs = $("#tabs"),
    context = $("div:not('ui-tabs-hide')", tabs);

    function destroyDialogBoxes(selector) {
        $(selector).remove();
    }
    function loadTabTeams() {
        tabs.tabs("load", 4);
    }
    function getNumPlayers() {
        return $("div[class^='player']", context).length;
    }
    function editBoxDialog(link) {
        context = $("#editBox");
        context.dialog({
            open: function(event, ui) {
                $.post(
                    link.attr("href"),
                    function(data) {
                        context.html(data);
                        setI(getNumPlayers());
                    });
            },
            close: function(event, ui) {
                destroyDialogBoxes("#editBox");
                destroyDialogBoxes(".dialogTeam");
                loadTabTeams();
            },
            modal: true,
            resizable: false,
            draggable: false,
            minWidth: 800,
            minHeight: 200,
            title: link.attr('title'),
            position: ['center', 100]
        });
    }
    function check() {
        var nutnychHracu = parseInt($(".nutnych", context).html(), 10);
        var a = $("input[name='name']", context).val().trim(),
        b = $("input[name='contact']", context).val().trim();
        if (a == "" || b == "") {
            alert("Vyplňte název týmu a nějaký kontakt na Vás.");
            return false
        }
        if (i < nutnychHracu) {
            alert("Pro tento turnaj je potřeba zapsat alespoň " + nutnychHracu + " hráčů.");
            return false
        }
        var settings = [
        ["p_name", "Vyplňte jména všech hráčů"],
        ["p_steamid", "Vyplňte Steam ID všech hráčů"],
        ["p_guid", "Vyplňte X-Ray GUID všech hráčů"]
        ];
        for (j = 1; j <= i; ++j) {
            for (var key in settings) {
                a = $("input[class='" + settings[key][0] + j +"']");
                var val = a.val().trim();
                if (val == "") {
                    a.focus();
                    alert(settings[key][1] + " !");
                    return false
                }
                if (key == 1 && !val.match(/^(STEAM_)?\d:\d:\d+$/) && !val.match(/^\d{16,}$/)) {
                    a.focus();
                    alert("Vyplňte všechny Steam ID korektně (Steam ID nebo Steam Community ID) !");
                    return false
                }
                if (key == 2 && val.length != 40 && !parseInt(val, 10)) {
                    a.focus();
                    alert("X-Ray GUID musí být přesně 40 znaků dlouhé nebo X-Ray ID musí být číslo !");
                    return false
                }
            }
        }
        return true
    }
    function setI(a) {
        var zadanychEl = $(".zadanych", context);
        var nutnychHracu = parseInt($(".nutnych", context).html(), 10);
        i = a;
        if (i < nutnychHracu) {
            zadanychEl.html(i).css("color", "red");
            $("input[type='submit']").prop("disabled", true);
        } else {
            zadanychEl.html(i).css("color", "green");
            $("input[type='submit']").prop("disabled", false);
        }
    }
    $(".dialogTeam").live('loaded', function() {
        var dialogBox = $(this);
        dialogBox.prev().click(function(e) {
            e.preventDefault();
            e = e || window.event;
            if (dialogBox.dialog("isOpen")) {
                dialogBox.dialog("close");
            } else {
                var posx = e.pageX - window.scrollX;
                var posy = e.pageY - window.scrollY;
                dialogBox.dialog("option", "position", [posx + 10, posy + 10]);
                dialogBox.dialog("open");
            }
        });
        dialogBox.dialog({
            autoOpen: false,
            resizable: false,
            minWidth: 250,
            minHeight: 100
        });
    });
    $(".team_add").live("click", function (e) {
        e.preventDefault();
        var hraciEl = $(".hraci", context);
        var nutnychHracu = parseInt($(".nutnych", context).html(), 10);
        if (i == 0) {
            hraciEl.html("");
        }
        if (i < nutnychHracu + 1) {
            ++i;
            hraciEl.append("<div class='player" + i + "'><h3>Hráč č." + i + "</h3><span>Jméno</span><input class='p_name" + i + "' name='p_name[]' size='20'><br><span>Steam ID</span><input title='1) Steam ID <b>0:0:123456789</b><br>2) Steam Community ID <b>76461198007025382</b>' class='p_steamid" + i + "' name='p_steamid[]' size='20'><br><span>XAC ID</span><input title='1) X-Ray GUID (Centra GUID)<br><b>000001208f0baede1b58-<br>-8e1d070a0e6fedfeafde</b><br>2) X-Ray ID <b>43152</b>' class='p_guid" + i + "' name='p_guid[]' size='20'></div>");
        }
        setI(i);
    });
    $(".team_remove").live("click", function (e) {
        e.preventDefault();
        if (i > 0) {
            $(".player" + (i--), context).remove();
            !i && $(".hraci", context).html('<div class="info red">Nebyli zapsáni žádní hráči</div>');
            setI(i);
        }
    });
    $("#teamRegSave").live('click', function (e) {
        e.preventDefault();
        if (check()) {
            $(this).prop("disabled", true);
            $.post(
                "team-reg-"+$(".tourid", context).val()+".html",
                $("#checkReg").serialize(),
                function(data) {
                    $("#ui-tabs-2").html(data);
                    setI(0);
                });
        }
    });
    $("#teamEditSave").live('click', function (e) {
        e.preventDefault();
        if (check()) {
            var submit = $(this);
            submit.prop("disabled", true);
            $.post(
                "team-edit-"+$(".tourid", context).val()+"-"+$(".id", context).val()+".html",
                $("#checkEdit").serialize(),
                function(data) {
                    context.html(data);
                    setI(getNumPlayers());
                    submit.prop("disabled", false);
                });
        }
    });
    $(".teamEdit").live('click', function(e) {
        e.preventDefault();
        editBoxDialog($(this));
    });
    $(".teamDel").live('click', function(e) {
        e.preventDefault();
        if (confirm("Opravdu chete smazat tento tým z turnaje?")) {
            editBoxDialog($(this));
        }
    });
    
    $(":input").live('focusin', function() {
        $(this).css("borderColor","#0b89ba");
    }).live('focusout', function() {
        $(this).css("borderColor","#999797");
    });

    tabs.tabs({
        'spinner': 'Načítám',
        'select': function(event, ui) {
            destroyDialogBoxes(".dialogTeam");
        },
        'load': function(event, ui) {
            context = $("#tabs div:not('ui-tabs-hide')");
            setI(getNumPlayers());
            $(".dialogTeam").trigger("loaded");
        }
    });
    
    $("#t_register,#t_registere,#t_start").datetimepicker({
      dateFormat: 'yy-mm-dd',
  
      ampm: false,
      timeFormat: 'hh:mm:ss',
      
      timeOnlyTitle: 'Vybrat čas',
      timeText: 'Čas',
      hourText: 'Hodina',
      minuteText: 'Minuta',
      secondText: 'Sekunda',
      currentText: 'Nyní',
      closeText: 'Zavřít'
  });
});

