function enableElement(name, check) {
    var obj = document.getElementById(name);
    obj.disabled = check;
}

function enableElementEx(name, check) {
    var obj = document.getElementById(name);

    if (obj == null) {
        return;
    }

    obj.disabled = check;
    if (check == true) {
        obj.style.backgroundColor = "#cccccc";
        obj.style.backgroundImage = "none";
    } else {
        obj.style.backgroundColor = "#fff";
        obj.style.backgroundImage = 'url(/flylimits/flylimits/images/bg-input-text.gif)';
    }
}

// z(ne)viditelneni prvku
function showElement(name, show) {
    var obj = document.getElementById(name);

    if (obj.style.display == 'none' || obj.style.display == '') {
        d = 'block';
    } else {
        d = 'none';
        h = '0px';
    }

    obj.style.display = d;
}

// otevre javascriptove okno
function otevriOkno(nazev, parametry, window_name, width, height) {
    msg = window.open(nazev + '?' + parametry, window_name, 'toolbar=yes,menubar=yes,location=yes,directories=no, scrollbars=yes,resizable=yes,status=yes,width=' + width + ',height=' + height + ',top=50,left=50')
}

// otevre popup urceny primo pro WebAdmin
function openAdminPopup(nazev, parametry, width, height, window_name) {
    //alert (parametry);
    msg = window.open('templates/popups/' + nazev + '?' + parametry, window_name, 'toolbar=no,menubar=no,location=no,directories=no, scrollbars=no,resizable=no,status=no,width=' + width + ',height=' + height + ',top=100,left=100')
}

function setCheckboxes(the_form, do_check) {
    var elts = (typeof(document.forms[the_form].elements['check[]']) != 'undefined')
        ? document.forms[the_form].elements['check[]']
        : document.forms[the_form].elements['check[]'];
    /*var elts=document.forms.formlist.elements;
     for (var i = 0; i < elts.length; i++) {
     alert(document.forms.formlist.elements[i].name);
     }*/
    var elts_cnt = (typeof(elts.length) != 'undefined')
        ? elts.length
        : 0;

    if (elts_cnt) {
        for (var i = 0; i < elts_cnt; i++) {
            elts[i].checked = do_check;
        } // end for
    } else {
        elts.checked = do_check;
    } // end if... else

    return true;
}

// zobrazi zvolenou kartu ve formulari
function setCard(cardID, cardCount) {
    // projede vsechny zalozky
    for (var i = 1; i <= cardCount; i++) {
        var cardName = 'tab' + i; // nazev zalozky
        var cardDivName = 'karta' + i; // nazev zalozkoveho divu

        var card = document.getElementById(cardName);
        var div = document.getElementById(cardDivName);

        // pokud je aktualni zalozka ta kterou chceme oznacit nastavi se viditelny styl
        if (i == cardID) {
            card.className = "tab-on";
            div.style.display = 'block';
        } else {
            card.className = "tab-off";
            div.style.display = 'none';
        }
    }

    // nastaveni id karty pro znovuvraceni do formulare
    var cardIDHidden = document.getElementById('card_id');
    cardIDHidden.value = cardID;
}

// nastavi checkoby prav podle prednastavenych hodnot
function setPrivPreset() {
    var role = document.getElementById('priv');

    if (role.value == "1") { // user
        document.getElementById('users_r').checked = 0;
        document.getElementById('users_w').checked = 0;
        document.getElementById('users_a').checked = 0;
        document.getElementById('users_d').checked = 0;
        document.getElementById('fl_arpts_list_r').checked = 0;
        document.getElementById('fl_arpts_list_w').checked = 0;
        document.getElementById('fl_arpts_list_a').checked = 0;
        document.getElementById('fl_arpts_list_d').checked = 0;
    } else if (role.value == "3") { // group admin
        document.getElementById('users_r').checked = 0;
        document.getElementById('users_w').checked = 0;
        document.getElementById('users_a').checked = 0;
        document.getElementById('users_d').checked = 0;
        document.getElementById('fl_arpts_list_r').checked = 1;
        document.getElementById('fl_arpts_list_w').checked = 1;
        document.getElementById('fl_arpts_list_a').checked = 1;
        document.getElementById('fl_arpts_list_d').checked = 1;
    } else if (role.value == "4") { // admin
        document.getElementById('users_r').checked = 1;
        document.getElementById('users_w').checked = 1;
        document.getElementById('users_a').checked = 1;
        document.getElementById('users_d').checked = 1;
        document.getElementById('fl_arpts_list_r').checked = 1;
        document.getElementById('fl_arpts_list_w').checked = 1;
        document.getElementById('fl_arpts_list_a').checked = 1;
        document.getElementById('fl_arpts_list_d').checked = 1;
    }
}

function checkDutyType() {
    var duty = document.getElementById('duty_type').value;

    // FLT-BC
    if (duty == 1) {
        enableElementEx('break_on', false);
        enableElementEx('break_off', false);
    } else {
        enableElementEx('break_on', true);
        enableElementEx('break_off', true);
        document.getElementById('break_on').value = '';
        document.getElementById('break_off').value = '';
    }

    // FLT-BC
    if (duty == 1) {
        enableElementEx('destination_dep', false);
        enableElementEx('destination_1', false);
        enableElementEx('destination_2', false);
        enableElementEx('destination_3', false);
        enableElementEx('destination_4', false);
        enableElementEx('destination_5', false);
        enableElementEx('destination_6', false);
        enableElementEx('destination_7', false);
        enableElementEx('block_hours_today', false);
        //		enableElementEx('cat', false);
    } else if (duty == 2) {
        enableElementEx('destination_dep', false);

        var acLimit = document.getElementById('settings_flt_max_landing_ac').value;
        for (var i=1; i<8; i++) {
            if (i<=acLimit) {
                enableElementEx('destination_'+i, false);
            } else {
                enableElementEx('destination_'+i, true);
                document.getElementById('destination_'+i).value = '';
            }
        }
        enableElementEx('block_hours_today', false);
    } else if (duty == 3) {
        enableElementEx('destination_dep', false);

        var dcLimit = document.getElementById('settings_flt_max_landing_dc').value;
        for (var i=1; i<8; i++) {
            if (i<=dcLimit) {
                enableElementEx('destination_'+i, false);
            } else {
                enableElementEx('destination_'+i, true);
                document.getElementById('destination_'+i).value = '';
            }
        }
        enableElementEx('block_hours_today', false);
    } else {
        enableElementEx('destination_dep', true);
        enableElementEx('destination_1', true);
        enableElementEx('destination_2', true);
        enableElementEx('destination_3', true);
        enableElementEx('destination_4', true);
        enableElementEx('destination_5', true);
        enableElementEx('destination_6', true);
        enableElementEx('destination_7', true);
        enableElementEx('block_hours_today', true);
        //		enableElementEx('cat', true);

        document.getElementById('destination_dep').value = '';
        document.getElementById('destination_1').value = '';
        document.getElementById('destination_2').value = '';
        document.getElementById('destination_3').value = '';
        document.getElementById('destination_4').value = '';
        document.getElementById('destination_5').value = '';
        document.getElementById('destination_6').value = '';
        document.getElementById('destination_7').value = '';
        document.getElementById('block_hours_today').value = '';
        //		document.getElementById('cat').value='';
    }

    // pokud neni vybrana zadna sluzba
    if (duty == 0) {
        enableElementEx('duty_on', true);
        enableElementEx('duty_off', true);
        document.getElementById('duty_on').value = '';
        document.getElementById('duty_off').value = '';
    } else {
        enableElementEx('duty_on', false);
        enableElementEx('duty_off', false);
    }
}

function clearForm() {
    var saving = document.getElementById('saving');
    saving.style.display = 'block';

    document.getElementById('duty_type').value = 0;
    document.getElementById('duty_on').value = '';
    document.getElementById('duty_off').value = '';
    document.getElementById('break_on').value = '';
    document.getElementById('break_off').value = '';
    document.getElementById('block_hours_today').value = '';
    document.getElementById('destination_dep').value = '';
    document.getElementById('destination_1').value = '';
    document.getElementById('destination_2').value = '';
    document.getElementById('destination_3').value = '';
    document.getElementById('destination_4').value = '';
    document.getElementById('destination_5').value = '';
    document.getElementById('destination_6').value = '';
    document.getElementById('destination_7').value = '';
    //document.getElementById('cat').value=0;
    document.getElementById('comments').value = '';
    document.getElementById('form').submit();
}

function submitForm() {
    var duty_on = document.getElementById('duty_on').value;
    var duty_off = document.getElementById('duty_off').value;
    var break_on = document.getElementById('break_on').value;
    var break_off = document.getElementById('break_off').value;
    var block_hours = document.getElementById('block_hours_today').value;

    // kontrola formatu datumu
    var check = checkTime(duty_on);
    var check1 = checkTime(duty_off);
    var check2 = checkTime(break_on);
    var check3 = checkTime(break_off);
    var check4 = checkTime(block_hours);

    // kontrola ktere pole jsou vyplnena
    if (duty_on.length == 0 && duty_off.length == 0 && (break_on.length != 0 || break_off.length != 0)) {
        var check_break = 0;
    } else {
        var check_break = 1;
    }

    // kontrola formatu casu pro pulnoc, musi byt 00:00
    var check_midnight_format = checkMidnightTimeFormat(duty_on);
    var check_midnight_format1 = checkMidnightTimeFormat(duty_off);
    var check_midnight_format2 = checkMidnightTimeFormat(break_on);
    var check_midnight_format3 = checkMidnightTimeFormat(break_off);

    if (check == 1 && check1 == 1 && check2 == 1 && check3 == 1 && check4 == 1) {
        if (check_break == 1) {
            if (check_midnight_format == 1 && check_midnight_format1 == 1 && check_midnight_format2 == 1 && check_midnight_format3 == 1) {
                var saving = document.getElementById('saving');
                saving.style.display = 'block';

                document.getElementById('form').submit();
            } else {
                alert('Use one of these time formats 00:00, 00.00 or 00,00 for midnight instead of 24:00, 24.00 or 24,00, please!');
            }
        } else {
            alert('Please fill in Duty ON and Duty OFF times!');
        }
    } else {
        alert('Please use one of these time formats: xx:xx, xx,xx or xx.xx!');
    }
}

function checkTime(tm) {
    var go = 1;

    var delim1 = tm.indexOf(':');
    var delim2 = tm.indexOf('.');
    var delim3 = tm.indexOf(',');

    if (delim1 == -1 && delim2 == -1 && delim3 == -1) {
        go = 0;
    }

    // pokud neni zadany zadny datum
    if (tm.length == 0) {
        go = 1;
    }

    return go;
}

// time format for midnight should be 00:00 not 24:00
function checkMidnightTimeFormat(time) {
    if (time == "24:00" || time == "24,00" || time == "24.00") {
        return 0;
    } else {
        return 1;
    }
}

// hodiny
function MakeArrayday(size) {
    this.length = size;
    for (var i = 1; i <= size; i++)
        this[i] = "";
    return this;
}
function MakeArraymonth(size) {
    this.length = size;
    for (var i = 1; i <= size; i++)
        this[i] = "";
    return this;
}

var hours;
var minutes;
var seconds;
var timer = null;
function sClock() {
    hours = 12;
    minutes = 59;
    seconds = 58;
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
    timer = setInterval("work();", 1000);
}

function twoDigit(_v) {
    if (_v < 10)_v = "0" + _v;
    return _v;
}

function work() {
    if (!document.layers && !document.all && !document.getElementById) return;
    var runTime = new Date();
    var dn = "AM";
    var shours = hours;
    var sminutes = minutes;
    var sseconds = seconds;
    if (shours >= 12) {
        dn = "PM";
        shours -= 12;
    }
    if (!shours) shours = 12;
    sminutes = twoDigit(sminutes);
    sseconds = twoDigit(sseconds);
    shours = twoDigit(shours);
    movingtime = "" + shours + ":" + sminutes + ":" + sseconds + "" + dn;
    if (document.getElementById)
        document.getElementById("footer-lr").innerHTML = movingtime;
    else if (document.layers) {
        document.layers.footer - lr.document.open();
        document.layers.footer - lr.document.write(movingtime);
        document.layers.footer - lr.document.close();
    }
    else if (document.all)
        clock.innerHTML = movingtime;

    if (++seconds > 59) {
        seconds = 0;
        if (++minutes > 59) {
            minutes = 0;
            if (++hours > 23) {
                hours = 0;
            }
        }
    }
}

function addCompanyAirport() {

    $.post(
        "/flylimits/content/jquery.php",
        {
            functionName: 'get_airports'
        },
        function(data) {
            $("#airports-list").append(data);
            return false;
        }
    );
}

function removeCompanyAirport(id) {

    $.post(
        "/flylimits/content/jquery.php",
        {
            functionName: 'remove_airport',
            id: id
        },
        function(data) {
            //					alert($("#airport-"+id).attr("id"));
            $("#airport-" + id).remove();
            return false;
        }
    );
}

function loadDuty(dutyID) {
    $.post(
        "/flylimits/content/jquery.php",
        {
            functionName: 'load_duty',
            id: dutyID
        },
        function(data) {
            $("#duty_type").val(data.duty_type);
            checkDutyType();
            $("#duty_on").val(data.duty_on);
            $("#duty_off").val(data.duty_off);
            $("#break_on").val(data.break_on);
            $("#break_off").val(data.break_off);
            $("#block_hours_today").val(data.block_hours_today);
            $("#destination_dep").val(data.destination_dep);
            $("#destination_1").val(data.destination_1);
            $("#destination_2").val(data.destination_2);
            $("#destination_3").val(data.destination_3);
            $("#destination_4").val(data.destination_4);
            $("#destination_5").val(data.destination_5);
            $("#destination_6").val(data.destination_6);
            $("#destination_7").val(data.destination_7);
            $("#comments").val(data.comments);
            return false;
        },
        'json'
    );
}

function openGraphsSortingDialog() {

    $.post(
        "/flylimits/content/jquery.php",
        {
            functionName: 'load_graph_sort_users',
            groupId: $("#id_fl_users_groups").val()
        },
        function(data) {
            $("#graph-sort-content").html(data.template);
            $.fancybox(
                $("#graph-sort-content").html(),
                {
                    'autoDimensions'    : false,
                    'width'                 : 350,
                    'height'                : 'auto',
                    'hideOnOverlayClick' : false,
                    'onComplete'    :    function() {
                        $("#graph-sort-content").html('');
                        $("#graph-sort-list").attr('id', 'graph-sort-list-1');
                        $("#graph-sort-save").attr('id', 'graph-sort-save-1');
                        $("#graph-sort-list-1").sortable();
                        $("#graph-sort-list-1").disableSelection();

                        $("#graph-sort-save-1").click(function() {
                            $.fancybox.showActivity();
                            var usersList = $("#graph-sort-list-1").sortable("serialize");
                            $.post(
                                "/flylimits/content/jquery.php",
                                {
                                    functionName: 'save_graph_sort_users',
                                    usersList: usersList,
                                    groupId: $("#id_fl_users_groups").val()
                                },
                                function(data) {
                                    // reload graph with new sort
                                    var imgSrc = $("#graph-img").attr('src');
                                    $("#graph-img").attr('src', imgSrc + '&test=1');
                                    $.fancybox.close();
                                    return false;
                                },
                                'json'
                            );
                        });
                    }
                }
            );

        },
        'json'
    );
}

function openExportDialog(orientation) {

    $.post(
        "/flylimits/content/jquery.php",
        {
            functionName: 'load_export_users'
        },
        function(data) {
            $("#graph-sort-content").html(data.template);
            hidePopupMenu();

            $.fancybox(
                $("#graph-sort-content").html(),
                {
                    'autoDimensions'    : false,
                    'width'                 : 350,
                    'height'                : 'auto',
                    'hideOnOverlayClick' : false,
                    'onComplete'    :    function() {
                        $("#graph-sort-content").html('');
                        $("#export-pdf-orientation").val(orientation);

                        // set form action for csv export
                        if (orientation == 'csv') {
                            $("#export-pdf-form").attr('action', '/flylimits/content/fl_export_csv_from_cache.php');
                        }

                        $("#export-button").click(function() {
                            $("#export-pdf-form").submit();
                            $.fancybox.close();
                        });
                    }
                }
            );

        },
        'json'
    );
}

function exportDialogCheckAll(state) {
    $(".export-users-checkbox").each(function() {
        this.checked = state;
    });
}

function showPopupMenu(menuPosition, x, y) {
    var menuIsVisible = $("#menu-popup").css("display");

    if (menuIsVisible == 'block') {
        $("#menu-popup").fadeOut('fast');
        return true;
    }

    var buttonPosition = $("#ftl-backup-button").position();
    var menuTop = buttonPosition.top + 30;
    var menuLeft = buttonPosition.left - 80;

    $("#overlay").fadeIn('fast');

    $("#menu-popup").css('top', menuTop + 'px');
    $("#menu-popup").css('left', menuLeft + 'px');
    $("#menu-popup").css('z-index', 1000);
    $("#menu-popup").fadeIn('fast');
}

function hidePopupMenu() {
    $("#menu-popup").fadeOut('fast');
    return true;
}

var mouse_is_inside = false;
$(document).ready(
    function() {
        $(".tooltip-popup").tipTip({
            maxWidth: "auto",
            edgeOffset: 3,
            delay: 200,
            defaultPosition: 'right'
        });

        $('#ftl-backup-button').hover(function() {
            mouse_is_inside = true;
        }, function() {
            mouse_is_inside = false;
        });

        $("body").mouseup(function() {
            if (! mouse_is_inside) $('#menu-popup').hide();
        });

        var optionsEST = {
            utc: true
        }
        $('#flt_time_utc').jclock(optionsEST);
        var optionsEST = {
            utc: false
        }
        $('#flt_time_local').jclock(optionsEST);

        $("#company-users").css('height', $(window).height()-160);

        // odeslani formulare s filtrovanim pro grafy podle spolecnosti, pozice, typu grafu...
        $("#id_fl_users_groups, #users_position, #graph-type").change(function() {
            $("#graphs-filter-form").submit();
        });

            // nacist znovu razeni v grafu
        $("#graph_sort").change(function() {
            var sortType = $("#graph_sort").val();

            // save sort setting

            $.post(
                "/flylimits/content/jquery.php",
                {
                    functionName: 'save_graph_sort_settings',
                    sortType: sortType
                },
                function(data) {
                    if (data.changed == 1 && sortType != "pers") {
                        // reload graph with new sort

                        var imgSrc = $("#graph-img").attr('src');
                        $("#graph-img").attr('src', imgSrc + '&test=1');
                    } else if (data.changed == 1 && sortType == "pers") {
                        openGraphsSortingDialog();
                    }
                    //					window.location.reload();
                    return false;
                },
                'json'
            );
        });
    }
);
