function remove() {
    if(confirm("Вы уверены? Восстановить объявление невозможно.")) {
        return true;
    }

    return false;
}

function changeAutoRe(url, id, chk) {
    chk.disabled = true;
    chk.className += "";

    $("#auto_re_idle_" + id).show();

    $.get(url + "?aid=" + id + "&re=" + (chk.checked ? '1' : '0'), function(data) {
        if(data == "ERROR")
            alert("Не получилось сохранить выш выбор, попробуйте обновить страницу и сделать его еще раз.");

        chk.disabled = false;
        chk.className += "";

        $("#auto_re_idle_" + id).hide();
    });
}

function ruEnding(num, v1, v2, v5) {
    var mod = num % 10;
    var cond = Math.floor((num % 100) / 10) != 1;

    if(mod == 1 && cond) {
        return v1;
    } else if (mod >= 2 && mod <= 4 && cond || v5 === null) {
        return v2;
    } else {
        return v5;
    }
}

function FieldCounter(fieldIDs, spanID, max) {

    this.fields = [];

    for(var i = 0, ic = fieldIDs.length; i < ic; ++ i) {
        this.fields.push($("#" + fieldIDs[i]));
    }

    this.span = $("#" + spanID);
    this.max = max;

    this.calc = function(event) {
        var val = this.max; // :)
        for(var i = 0, ic = this.fields.length; i < ic; ++ i) {
            val -= this.fields[i].attr("value") ? this.fields[i].attr("value").length : 0;
        }

        if(val < 0) {
            val = -1 * val;
            this.span.html(", <span style=\"color:red\">" + val + " " + ruEnding(val, "лишний", "лишних", null) + "</span>");
        } else {
            this.span.html(", " + ruEnding(val, "остался", "осталось", null) + " " + val);
        }
    };

    this.calc();

    var THIS = this;
    for(var i = 0, ic = this.fields.length; i < ic; ++ i) {
        this.fields[i].keyup(function(event) {
            THIS.calc(event);
        });
    }
}

function initFormFocus(form) {
    $(form).find("input:text,input:password").each(function(index) {
        if($(this).val().length == 0) {
            $(this).focus();
            return false;
        }
    });
}

/**
 * Аналог PHP'шной функции «number_format»
 *
 * @param number
 * @param decimals
 * @param dec_point
 * @param thousands_sep
 */
function numberFormat(number, decimals, dec_point, thousands_sep)
{
    //
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)

    var i, j, kw, kd, km, minus = '';

    if (number < 0) {
        minus = '-';
        number *= -1;
    }

    if (isNaN(decimals = Math.abs(decimals))) {
        decimals = 2;
    }

    if (dec_point == undefined) {
        dec_point = ',';
    }

    if (thousands_sep == undefined) {
        thousands_sep = '.';
    }

    i = parseInt(number = (+number || 0).toFixed(decimals)) + '';

    if ((j = i.length) > 3) {
        j = j % 3;
    } else {
        j = 0;
    }

    km = (j ? i.substr(0, j) + thousands_sep : '');
    kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
    kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : '');

    return minus + km + kw + kd;
}

function getFloatFromFormatted(str)
{
    return Math.ceil(parseFloat(str.replace(/[^\-\d]/g, '')));
}

$(function() {
    var
        $bEditForm = null,
        $bEdit     = [
            // _set-price.phtml
            $('#w_price'),
            $('#w_amountMaxPerDay'),
            $('#w_viewsMaxPerDay'),

            // edit-rotation-add.phtml
            $('#w_amount'),
            $('#w_viewsMax')
        ];

    initFormFocus($("form.autofocus"));

    // Инициализируем поиск по комментариям в баннерке
    $(document).bind('statsLoadedEvt', function() {
        var
            comments      = {},
            commentIdx    = null,
            moneyAmount   = 0,
            moneyDiscount = 0,
            $totalNumber  = $('#total-number'),
            $totalMoney   = $('#total-money'),
            $visibleRows  = null,
            $comment      = $('#statComment'),
            commentVal    = $comment.size() > 0
                ? $.trim($comment.val())
                : '',
            /**
             * Заполняем массив с комментариямиы
             */
            fillCommens = function() {
                $('tr[id]', '.account_log').each(function() {
                    var $self = $(this);

                    comments[$self.attr('id').split('-')[2]] = $('.rotation-statistics-comment', $self).text();
                });
            };

        fillCommens();

        // Ищем только если непустая строка поиска
        if (commentVal.length > 0) {
            for (commentIdx in comments) {
                if (null == comments[commentIdx]
                    || typeof(comments[commentIdx]) == 'undefined'
                    || (comments[commentIdx].search(commentVal) == -1)) {
                    $('#rotation-statistics-' + commentIdx).hide();
                }
            }

            // Пересчитываем счетчики
            $visibleRows = $('tr[id]:visible', '.account_log');
            if ($visibleRows.size() > 0) {
                // Общее количество размещений
                $totalNumber.html(
                    '<strong>' + $visibleRows.size() + '</strong> ' +
                    ruEnding($visibleRows.size(), 'размещение', 'размещения', 'размещений')
                );

                // Суммы
                $visibleRows.each(function() {
                    var
                        classes = $(this).attr('class').split(' '),
                        temp = [];

                    for (var i = 0; i < classes.length; i++) {
                        temp = classes[i].split('-');
                        if (temp[1] == 'amount') {
                            moneyAmount += parseFloat(temp[2]);
                        } else if (temp[1] == 'discount') {
                            moneyDiscount += parseFloat(temp[2])
                        }
                    }
                });

                // Обновляем надписи
                if (moneyDiscount > 0) {
                    $totalMoney.html(
                        '<strong>' + numberFormat(Math.round(moneyAmount), 0, '.', ' ') +
                        ' тг</strong>, с учётом скидок <strong>' +
                        numberFormat(Math.round(moneyAmount - moneyDiscount), 0, '.', ' ') +
                        ' тг</strong>'
                    );
                } else {
                    $totalMoney.html(
                        '<strong>' + numberFormat(Math.round(moneyAmount), 0, '.', ' ') +
                        ' тг</strong>'
                    );
                }
            }
        }
    }).trigger('statsLoadedEvt');

    // Форматирование цен и количества показов в форме баннерки
    for (var idx in $bEdit) {
        if (typeof($bEdit[idx]) != 'undefined' && $bEdit[idx].size() > 0) {
            // Форматируем число после загрузки страницы
            $bEdit[idx].val(numberFormat(getFloatFromFormatted($bEdit[idx].val()), 0, '.', ' '));

            // Форматируем число, после ввода цифры в поле
            $bEdit[idx].keyup(function(e) {
                var $self = $(this);

                $self.val(numberFormat(getFloatFromFormatted($self.val()), 0, '.', ' '));

                return true;
            });

            if (!$bEditForm) {
                $bEditForm = $($bEdit[idx].parents('form').get(0));
            }
        }
    }

    // Перед отправкой формы форматированные цифры переводим в обычные
    if ($bEditForm && $bEditForm.size() > 0) {
        $bEditForm.submit(function() {
            for (var idx in $bEdit) {
                if (typeof($bEdit[idx]) != 'undefined' && $bEdit[idx].size() > 0) {
                    $bEdit[idx].val(parseInt(getFloatFromFormatted($bEdit[idx].val())));
                }
            }

            return true;
        });
    }
});

