$(document).ready(function () {

    // table sort
    $('.t-sort').each(function () {
        var par = $(this);

        if (par.hasClass('t-sort_awards')) {
            par.tablesorter({
                cssHeader: 'th-sort',
                cssAsc: 'sort-up',
                cssDesc: 'sort-down',
                headers: {
                    8: {sorter: false}
                }
            });
        }

        if (par.hasClass('t-sort_users')) {
            par.tablesorter({
                cssHeader: 'th-sort',
                cssAsc: 'sort-up',
                cssDesc: 'sort-down',
                headers: {
                    3: {sorter: false}
                }
            });
        }

        if (par.hasClass('t-sort_pages')) {
            par.tablesorter({
                cssHeader: 'th-sort',
                cssAsc: 'sort-up',
                cssDesc: 'sort-down',
                headers: {
                    1: {sorter: false},
                    4: {sorter: false}
                }
            });
        }
    });


    // form_reward_filter
    $('.form_reward').each(function () {
        var $filter = $('.form_reward_filter'),
            lastFilter = $filter.find('input:checked').val();

        $filter.on('click', 'button', function () {
            var $input = $(this).find('input'),
                value = $input.val();

            if (value != lastFilter) {
                lastFilter = value;
                document.location.href = '/reward/' + (value != 'None' ? '?status=' + value : '');
            }
        });
    });


    // browser_form_reward_filter
    $('.browser_form_reward').each(function () {
        var $filter = $('.browser_form_reward_filter'),
            lastFilter = $filter.find('input:checked').val();

        $filter.on('click', 'button', function () {
            var $input = $(this).find('input'),
                value = $input.val();

            if (value != lastFilter) {
                lastFilter = value;
                document.location.href = '/reward/browser/' + (value != 'None' ? '?status=' + value : '');
            }
        });
    });


    // form_vulnerability
    $('.form_vulnerability').each(function () {
        var $form = $(this),
            $tbody = $form.find('.form_vulnerability_list'),
            $template = $form.find('.form_vulnerability_template'),
            $form_tr = $form.find('.form_vulnerability_form'),
            _name = '.form_vulnerability_name',
            _points = '.form_vulnerability_points',
            _save = '.form_vulnerability_save',
            _edit = '.form_vulnerability_edit',
            _cancel = '.form_vulnerability_cancel',
            csrf = $form.find('[name=csrfmiddlewaretoken]').prop('value');

        $form_tr.find(':text').on('keyup', function (e) {
            if (e.keyCode == 13) {
                $form_tr.find(_save).click();
            }
        });
        
        $tbody.on('click', _edit, function (e) {
            e.stopPropagation();
            e.preventDefault();

            $tbody.find('TR').show();
            var $tr = $(this).closest('tr').hide();
            $form_tr
                .insertAfter($tr)
                .data('id', $tr.data('id'))
                .find(_name).val($tr.find('TD').eq(0).text()).end()
                .find(_points).val($tr.find('TD').eq(1).text()).end()
                .find(_cancel).show();
            $('.input').each(function () {
                if ($(this).find('.input__input')[0].value) {
                    $(this).addClass('input_state_filled').removeClass('input_state_empty');
                } else {
                    $(this).addClass('input_state_empty').removeClass('input_state_filled');
                }
            });
            console.log($tr.data('id'))
        });

        $tbody.on('click', _cancel, function (e) {
            e.stopPropagation();
            e.preventDefault();

            $tbody.find('TR').show();

            $form_tr
                .data('id', null)
                .appendTo($tbody)
                .find(_name).val("").end()
                .find(_points).val("").end()
                .find(_cancel).hide();
        });

        $tbody.on('click', _save, function (e) {
            e.stopPropagation();
            e.preventDefault();

            var $tr = $(this).closest('TR'),
                id = $tr.data('id'),
                name = $tbody.find(_name).val(),
                points = $tbody.find(_points).val();

            console.log(id, name, points);

            if (name != '' && points != '') {
                var url = id ? ('/vulnerability/edit/' + id + '/') : '/vulnerability/create/',
                    data = new FormData();

                data.append('name', name);
                data.append('points', points);

                $.ajax({
                    url: url,
                    data: data,
                    type: 'POST',
                    processData: false,
                    contentType: false,
                    headers: {
                        "X-CSRFToken": csrf
                    }
                    })
                    .done(function (data) {
                        if (!id) {
                            var $tr = $template.clone()
                                .removeClass('form_vulnerability_template')
                                .removeClass('template')
                                .insertBefore($form_tr);
                        }else{
                            var $tr = $form_tr.prev();
                        }
                        $tr.attr('data-id', data.id);
                        $tr.find('.pk').val(data.id);
                        $tr.find('TD').eq(0).text(name);
                        $tr.find('TD').eq(1).text(points);

                        $form_tr.find(_cancel).click();
                    })
                    .error(function (data) {
                        console.error(data)
                    });
            } else {
                // validation error
            }
        });

    });


    // form_badge
    $('.form_badge').each(function () {
        var $form = $(this),
            $save = $form.find('.form_badge_save'),
            $type = $form.find('.form_badge_type'),
            $image = $form.find('.form_badge_image');

        $type.on('click refresh', '.check', function () {
            var checked = $(this).hasClass('checked');
            $type.find('.js-select').css({
                visibility: !checked ? 'hidden' : 'visible'
            });
        });
        $type.find('.check').trigger('refresh');

        $image.on('change', ':file', function () {
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $image.find('.badge__img').empty()
                        .append('<img src="' + e.target.result + '">');
                };
                reader.readAsDataURL(this.files[0]);
            }
        });

    });

    $('.form_reward_edit').each(function () {
        var $form = $(this),
            $del = $form.find('.form_reward_edit_del');

        $del.click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            csrf = $form.find('[name=csrfmiddlewaretoken]').prop('value');
            $.ajax({
                url: '.',
                type: 'DELETE',
                processData: false,
                contentType: false,
                headers: {
                    "X-CSRFToken": csrf
                }
            })
            .done(function (data) {
                window.location.replace('/reward/')
            })
            .error(function (data) {
                window.location.replace('/reward/')
                console.error(data)
            });

        });
    });


    // form-hof
    $('.form-hof').each(function () {
        var $form = $(this),
            $date = $form.find('.form-hof_date'),
            $select = $date.find('SELECT'),
            year = parseInt("2010", 10), //$select.data('from-year'),
            month = 0,
            sel_year = $select.data('year'),
            sel_month = $select.data('month'),
            cur_year = (new Date()).getFullYear(),
            cur_month = (new Date()).getMonth(),
            MMM = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
            months = [];

        while (year < cur_year || (year == cur_year && month <= cur_month)) {
            var cur = (year == sel_year && month == sel_month - 1);
            months.push({
                year: year,
                month: month,
                mmm: MMM[month],
                cur: cur
            });
            if (month < 11) {
                month += 1;
            }  else {
                month = 0;
                year += 1;
            }
        }

        months.reverse();

        $.each(months, function (index, month) {
            $select.append('<option' + (month.cur ? ' selected' : '') + ' data-month="' + (1 + month.month) + '" data-year="' + month.year + '">' + month.mmm + ' ' + month.year + '</option>');
        });

        $date.addClass('js-select').show();
        app.jsSelectInit($date);
        
        $select.on('change', function () {
            var option = $(this).find(':selected');
            document.location.href = '/hall-of-fame/' + option.data('year') + '/' + option.data('month') + '/';
        });


//   		$select.find('option').each(function() {
//			var cl = $(this).is(':selected') ? 'cur ' : '';
//			$('<li class="' + cl + '"><span>' + $(this).text() + '</span></li>').appendTo($date.find('.js-select__body'));
//		});

    });

}); // dom ready
