window.gacc = window.gacc || {};

gacc.initOverlay = function(root) {
    if (!root)
        root = $('body');

    if ($('#overlay').length) {
        root.append($('#overlay'));
        return;
    }

    root.append('<div id="overlay-cover" style="display: none;"></div>');
    root.append('<div id="overlay" class="dialog-wrapper" style="display: none;"><div id="overlay-wrapper" class="dialog"><a href="#" class="close"></a><div id="overlay-content"></div></div></div>');
    $('#overlay .close, #overlay .cancel-link, #overlay-cover').live('click', function() {
        gacc.hideOverlay();
        return false;
    });
};

gacc.showOverlay = function(elem, root) {
    gacc.initOverlay(root);

    if (elem) {
        $('#overlay-content').append(elem);
    }

    $('#overlay-cover').show();
    $('#overlay').show();
    if ($('#overlay-cover').height() < $('body').height()) {
        $('#overlay-cover').height($('body').height());
    }

    $('#overlay').css('left', ($('body').width() - $('#overlay').width()) / 2);
    $('#overlay').css('top', $('body').get(0).scrollTop + ($(window).height() - $('#overlay').height()) / 2);
};

gacc.showOverlayTop = function(elem, root) {
    gacc.initOverlay(root);

    if (elem) {
        $('#overlay-content').append(elem);
    }

    $('#overlay-cover').show();
    $('#overlay').show();
    if ($('#overlay-cover').height() < $('body').height()) {
        $('#overlay-cover').height($('body').height());
    }

    $('#overlay').css('left', ($('body').width() - $('#overlay').width()) / 2);
    $('#overlay').css('top', $('body').get(0).scrollTop);
};

gacc.hideOverlay = function() {
    $('#overlay-cover').hide();
    $('#overlay').hide();
};

gacc.isIE7 = false;

gacc.initDropdowns = function(selector) {
    var x = 0;

    selector.each(function() {
        if (! $(this).attr('id')) {
            $(this).attr('id', '_sel' + x);
            x++;
        }
    });

    selector.msDropDown().data("dd");
}

// validates month
gacc.isMonthValid = function(value) {
    return (value >= 1 && value <= 12);
}

// validates year
gacc.isYearValid = function(value) {
    return (value > 1950 && value < 2050);
}

// validates date in format "MM/YYYY"
gacc.validateMonth = function() {
    var val = $(this).val().split("/");

    // check month
    if (! gacc.isMonthValid(parseInt(val[0], 10))) {
        alert('Zadejte prosím platný měsíc');
        $(this).data('hasError', true);
        var t = $(this);
        setTimeout(function() { t.focus(); }, 100);

        return false;
    }
    
    // check year
    if (! gacc.isYearValid(parseInt(val[1], 10))) {
        alert('Zadejte prosím platný rok');
        $(this).data('hasError', true);
        var t = $(this);
        setTimeout(function() { t.focus(); }, 100);

        return false;
    }

    $(this).data('hasError', false);
}

// validates date in format "DD.MM"
gacc.validateDate = function(val) {
    if (! val || typeof(val) != 'string') {
        val = $(this).val();
    }

    if (! val || ! val.match(/^[0-9]{2}\.[0-9]{2}\.$/)) {
        return;
    }

    val = val.split(".");

    var day = parseInt(val[0], 10);
    var month = parseInt(val[1], 10);

    // check day
    if (day < 1 || day > 31 || ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) || (month == 2 && day > 29)) {
        alert('Zadejte prosím platný den');
        $(this).data('hasError', true);
        var t = $(this);
        setTimeout(function() { t.focus(); }, 100);

        return false;
    }

    // check month
    if (! gacc.isMonthValid(month)) {
        alert('Zadejte prosím platný měsíc');
        $(this).data('hasError', true);
        var t = $(this);
        setTimeout(function() { t.focus(); }, 100);

        return false;
    }

    $(this).data('hasError', false);
}

// validates date in format "DD.MM.YYYY"
gacc.validateDateLong = function() {
    var val = $(this).val();
    if (!val) {
        return;
    }

    if (gacc.validateDate.call($(this), val.substr(0,6)) === false) {
        return false;
    }

    var val = $(this).val().split(".");
    if (! gacc.isYearValid(parseInt(val[2], 10))) {
        alert('Zadejte prosím platný rok');
        $(this).data('hasError', true);
        var t = $(this);
        setTimeout(function() { t.focus(); }, 100);

        return false;
    }

    $(this).data('hasError', false);
}

// validates time in format "HH:MM"
gacc.validateTime = function() {
    var val = $(this).val();
    if (!val) {
        return;
    }

    val = val.split(":");

    var hour = parseInt(val[0], 10);
    var minute = parseInt(val[1], 10);
    
    if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
        alert('Zadejte prosím platný čas');
        $(this).data('hasError', true);
        var t = $(this);
        setTimeout(function() { t.focus(); }, 100);

        return false;
    }

    $(this).data('hasError', false);
}

gacc.validationEnter = function(e) {
    if (e.keyCode == 13) {
        // enter to submit form
        $(this).trigger('blur');
        
        return ! $(this).data('hasError');
    }
}

// creates form fields for new registration
gacc.attnNewEventsCounter = 1;
gacc.attnCanEdit = true;

gacc.attnCheckNewEvent = function() {
    if (!gacc.attnCanEdit) {
        // no permissions for editing
        return;
    }

    // check if it is last row
    if ($(this).parent().next('div').length) {
        return;
    }

    // check if both fields (date and time) are populated
    if (! $(this).parent().find('input:eq(0)').val() || ! $(this).parent().find('input:eq(1)').val()) {
        // not populated, do not create new form fields
        return;
    }

    // create new form fields
    var div = $(document.createElement('div'));

    // clone form controls
    var fieldDate = $(this).parent().find('input:eq(0)').clone();
    var fieldTime = $(this).parent().find('input:eq(1)').clone();
    var fieldType = $(this).parent().find('select').clone();

    // change name and id attributes
    fieldDate.attr('name', 'Date_' + gacc.attnNewEventsCounter);
    fieldTime.attr('name', 'Time_' + gacc.attnNewEventsCounter);
    fieldType.attr('name', 'Reg_' + gacc.attnNewEventsCounter);

    fieldType.attr('id', '_selgen' + gacc.attnNewEventsCounter);

    // clear values
    fieldDate.val('');
    fieldTime.val('');
    fieldType.val('');

    // append controls to the div
    div.append(fieldDate);
    div.append(fieldTime);
    div.append(fieldType);

    // append div to the table
    $(this).parent().parent().append(div);

    // set masks and graphic selectbox
    gacc.setDateMask(div.find('input:even'));
    gacc.setTimeMask(div.find('input:odd'));
    gacc.initDropdowns(fieldType.parent().find('select'));

    gacc.attnNewEventsCounter++;
}

gacc.setDateMask = function(selector) {
    selector.mask('99.99.');
}

gacc.setTimeMask = function(selector) {
    selector.mask('99:99');
}

$(document).ready(function(){
    // first example
    if ($('#browser').length) {
        $("#browser").treeview();
    }

    // IE7 fixes
    gacc.isIE7 = ($.browser.msie && parseInt($.browser.version, 10) === 7);

    // center login
    if ($('#login').length) {
        $('#login').css('margin-top', -$('#login').height() / 2);
    }
    
    // image dropdowns
    gacc.initDropdowns($('.imagecombo'));
    
    // month filter
    $('input.month-picker').mask('99/9999');
    $('input.month-picker').blur(gacc.validateMonth);

    $('input.date-picker').mask('99.99.9999');
    $('input.date-picker').blur(gacc.validateDateLong);

    $('.attn .date').each(function() {
        gacc.setDateMask($(this).find('input:even'));
        $(this).find('input:even').live('blur', gacc.validateDate);
        $(this).find('input:even').live('blur', gacc.attnCheckNewEvent);

        gacc.setTimeMask($(this).find('input:odd'));
        $(this).find('input:odd').live('blur', gacc.validateTime);
        $(this).find('input:odd').live('blur', gacc.attnCheckNewEvent);
    });

    $('input').live('keypress', gacc.validationEnter);

    $('form').submit(function() {
        var inputs = $(this).find('input');
        var l = inputs.length;
        for (var i = 0; i<l; i++) {
            if ($(inputs[i]).data('hasError')) {
                alert('Položka obsahuje neplatnou hodnotu, opravte ji.');
                $(inputs[i]).focus();

                return false;
            }
        }
    });

});