var numberPositionSeparator = ',';
var numberFractionSeparator = '.';
var numberPositionRegexp = new RegExp(',', 'g');
var numberFractionRegexp = new RegExp('\\.', 'g');
function setNumberFormat(positionSeparator, fractionSeparator) {
    numberPositionSeparator = positionSeparator;
    numberFractionSeparator = fractionSeparator;
    if (numberPositionSeparator == '.') {
        numberPositionRegexp = new RegExp('\\.', 'g');
    } else {
        numberPositionRegexp = new RegExp(numberPositionSeparator, 'g');
    }
    
    if (numberFractionSeparator == '.') {
        numberFractionRegexp = new RegExp('\\.', 'g');
    } else {
        numberFractionRegexp = new RegExp(numberFractionSeparator, 'g');
    }
}

function switchInvoiceAction(ele1Id, ele2Id) {
    var ele1 = document.getElementById(ele1Id);
    var ele2 = document.getElementById(ele2Id);

    if (ele1 && ele2) {
        ele1.style.display = 'none';
        ele2.style.display = 'block';
    }
}

function getParentElement(parent, name) {
    if (name.toLowerCase() == parent.nodeName.toLowerCase()) {
        return parent;

    } else if (parent.parentNode) {
        return getParentElement(parent.parentNode, name);

    } else {
        return false;
    }
}

function checkThemAll(initEle) {
    var table = getParentElement(initEle, 'table');
    if (table) {
    
        if (initEle.checked) {
            $('tbody > tr:invisible > td > input:checkbox', table).removeAttr('checked');
            $('tbody > tr:visible > td > input:checkbox', table).attr('checked', 'true');
        } else {
            $('tbody > tr > td > input:checkbox', table).removeAttr('checked');
        }
    }
}

function showServiceIcons(container) {
    
    var row = getParentElement(container, 'tr');
    if (row) {
        var tbody = getParentElement(row, 'tbody');
        if ($('tr', tbody).length == 4) {
            return;
        }
    }
    
    var divs = container.getElementsByTagName('div');
    for (var i = 0; i < divs.length; i++) {
        if ('service_icon' == divs[i].className) {
            divs[i].style.display = 'block';
        }
    }
}

function hideServiceIcons(container) {
    var divs = container.getElementsByTagName('div');
    for (var i = 0; i < divs.length; i++) {
        if ('service_icon' == divs[i].className) {
            divs[i].style.display = 'none';
        }
    }
}

function switchDependencies(switcher) {
    var container = getParentElement(switcher, 'form');
    var divs = container.getElementsByTagName('div');
    var id;

    for (var i = 0; i < divs.length; i++) {
        id = divs[i].getAttribute('id');
        if (id && -1 != id.indexOf(switcher.getAttribute('id') + '_dep_')) {
            divs[i].style.display = switcher.checked ? 'block' : 'none';
        }
    }
}

function getClassName(ele, exeptClassName) {
    var classes = ele.className.split(' ');
    var className = '';

    for (var i = 0; i < classes.length; i++) {
        if (exeptClassName != classes[i]) {
            className += (className.length > 0 ? ' ' : '') + classes[i];
        }
    }

    return className;
}

function formSwitchLabel(formEle, defaultValue) {
    var elem = $(formEle);
    elem.removeClass('default');
    
    if (elem.val() == '') {
        elem.val(defaultValue);
    }
    
    if (elem.val() == defaultValue) {
        elem.addClass('default');
    }
    
}

function formEditElement(formEle, defaultValue, clearDefault) {
    formEle.className = getClassName(formEle, 'default');
    if (defaultValue == formEle.value && clearDefault) {
        formEle.value = '';
    }
}

function removeDefaultValues(fields) {
    var ele = null;
    for (var i = 0; i < fields.length; i++) {
        ele = document.getElementById(fields[i][0]);
        if (ele && ele.value == fields[i][1]) {
            ele.value = '';
        }
    }
}

function getFormErrorEle(cell) {
    var elems = cell.getElementsByTagName('div');
    for (var i = 0; i < elems.length; i++) {
        if ('form_error' == elems[i].className) {
            return elems[i];
        }
    }
    return false;
}

function parseValue(ele, error, message) {
    var errorEle = getFormErrorEle(getParentElement(ele, 'td'));
    if (errorEle) {
        errorEle.innerHTML = message;
        if (error) {
            errorEle.style.display = 'block';
            $(ele.parentNode).addClass('error');
        } else { 
            errorEle.style.display = 'none';
            $(ele.parentNode).removeAttr('class');
            $(ele.parentNode).addClass('input');
        }
    }
    
    //if (error)
    
    return !error;
}

function parseNumber(value) {
    var result = value.replace(/[a-z!ав-эя\s!"'#№\$:_;\(\)\{\}\|\[\]\?\&\*+=~%\^@\-]/gi, '')
        .replace(/[юЮбБ><\/\\]/gi, '.')
        //.replace(/[юЮбБ><\.\/\\]/gi, '')
        .replace(numberPositionRegexp, '')
        .replace(numberFractionRegexp, '.')
        .replace(/^[0]{2,}/, '')
        .replace('.', ',')
        .replace(/\./g, '')
        .replace(',', '.');
    return result;
    
}

function checkFieldNumber(field) {
    if (field.value == '') {
        return false;
    }
    return parseValue(field, !checkNumber(field.value), '');
}

function checkNumber(value) {
    var temp = parseNumber(value).replace(',', '.');
    var number = parseFloat(temp);
    return !isNaN(number) && temp == number;
}

function checkFieldInt(field) {
    if (field.value == '') {
        return false;
    }
    return parseValue(field, !checkInt(field.value), 'Только цифрами');
}

function checkInt(value) {
    var number = parseInt(value);
    return !isNaN(number) && value == number;
}

function checkFieldDate(field, errorMsgId, lang) {
    lang = lang || 'en';
    var result = parseValue(field, !checkDate(field.value, lang), 'Упс, дата не распознана');
    if (result) {
        
        if (!errorMsgId) {
            errorMsgId = 'invoice_date_error_message';
        }
        
        $(getParentElement(field, 'table')).removeClass('error');
        $('#' + errorMsgId).hide();
    }
    return result;
}

function checkDate(value, lang) {
    return stringToDate(value, lang);
}

function stringToDate(value, lang) {
    lang = lang || 'en';
    
    value = value.replace(/^\s+/, '')
        .replace(/\s+$/, '')
        .replace(/[\.,]/g, '')
        .toLowerCase();

    var now = new Date();
    var todayNoon = Date.UTC(
        now.getFullYear(), now.getMonth(), now.getDate(),
        12, 0, 0, 0
    );

    switch (value) {
        case 'day before yesterday':
        case 'позавчера':   return new Date(todayNoon - 1000 * 60 * 60 * 24 * 2);
        
        case 'yesterday':
        case 'gestern':
        case 'вчера':
            return new Date(todayNoon - 1000 * 60 * 60 * 24);
        
        case 'today':
        case 'heute':
        case 'сегодня':
            return new Date(todayNoon);
        
        case 'tomorrow':
        case 'morgen':
        case 'завтра':
            return new Date(todayNoon + 1000 * 60 * 60 * 24);
            
        case 'day after tomorrow':
        case 'послезавтра': return new Date(todayNoon + 1000 * 60 * 60 * 24 * 2);
    }

    var match = /^([0-9]{1,2})[.\/\-]([0-9]{1,2})(?:[.\/\-]([0-9]{2,4}))?$/.exec(value);
    if (match) {
        var day = parseInt(parseNumber(match[1]));
        var month = parseInt(parseNumber(match[2]));
        var year = match[3] ? parseInt(parseNumber(match[3])) : now.getFullYear();

        if (30 >= year) year += 2000;
        else if (100 > year) year += 1900;

        if (isDate(year, month, day)) {
            return new Date(year, month - 1, day, 12, 0, 0);
        }
    }

    match = /^([0-9]{4})[.\/\-]([0-9]{1,2})[.\/\-]([0-9]{1,2})$/.exec(value);
    if (match) {
        var day = parseInt(parseNumber(match[3]));
        var month = parseInt(parseNumber(match[2]));
        var year = parseInt(parseNumber(match[1]));

        if (30 >= year) year += 2000;
        else if (100 > year) year += 1900;

        if (isDate(year, month, day)) {
            return new Date(year, month - 1, day, 12, 0, 0);
        }
    }

    var day = 0;
    var month = 0;
    var year = 0;

    match = /([0-9]{2,4}) ?(года|г\.|г)/.exec(value);
    if (match) {
        year = parseInt(parseNumber(match[1]));
        
        if (30 >= year) year += 2000;
        else if (100 > year) year += 1900;
        
        value = value.replace(/([0-9]{2,4}) ?(года|г\.|г)/, '');
        value = value.replace(/^\s+/, '').replace(/\s+$/, '');
    }

    switch (lang) {
        case 'de':
        case 'ru':
            var dayIndex = 0;
            var monthIndex = 1;
            break;
            
        default:
            var dayIndex = 1;
            var monthIndex = 0;
        
    }
    var date = value.split(' ');
    if (
            1 < date.length &&
            4 > date.length &&
            !(3 == date.length && 0 < year)
    ) {
        day = parseInt(parseNumber(date[dayIndex]));
        month = guessMonth(date[monthIndex], lang);
        
        if (date[2]) year = parseInt(parseNumber(date[2]));
        else if (0 == year) year = now.getFullYear();
        
        if (isDate(year, month, day)) {
            return new Date(year, month - 1, day, 12, 0, 0);
        }
    }

    return false;
}

function isDate(year, month, day) {
    return 0 < day && 32 > day && 0 < month && 13 > month && 1970 < year && 2030 > year;
}

function guessMonth(value, lang) {
    lang = lang || 'en';
    value = value.toLowerCase();

    var months = {
        'en': [
            ['January']
            , ['February']
            , ['March']
            , ['April']
            , ['May']
            , ['June']
            , ['July']
            , ['August']
            , ['September']
            , ['October']
            , ['November']
            , ['December']
        ]
        , 'ru': [
            ['Январь', 'Января', 'Январе']
            , ['Февраль', 'Февраля', 'Феврале']
            , ['Март', 'Марта', 'Марте']
            , ['Апрель', 'Апреля', 'Апреле']
            , ['Май', 'Мая', 'Мае']
            , ['Июнь', 'Июня', 'Июне']
            , ['Июль', 'Июля', 'Июле']
            , ['Август', 'Августа', 'Августе']
            , ['Сентябрь', 'Сентября', 'Сентябре']
            , ['Октябрь', 'Октября', 'Октябре']
            , ['Ноябрь', 'Ноября', 'Ноябре']
            ,['Декабрь', 'Декабря', 'Декабре']
        ]
        , 'de': [
            ['Januar']
            , ['Februar']
            , ['März']
            , ['April']
            , ['Mai']
            , ['Juni',]
            , ['Juli']
            , ['August']
            , ['September']
            , ['Oktober']
            , ['November']
            , ['Dezember']
        ]
    }

    var reg = new RegExp('^' + value);
    for (var i = 0; i < months[lang].length; i++) {
        for (var j = 0; j < months[lang][i].length; j++) {
            if (reg.test(months[lang][i][j].toLowerCase())) {
                return i + 1;
            }
        }
    }

    return false;
}

function roundNumber(number) {
    return Math.round(number * 100) / 100;
}

function recountInvoiceValues(inputEle, isDefaultAvailable, lang) {
    lang = lang || 'en';
    var row = getParentElement(inputEle, 'tr');
    if (row) {
        var inputs = row.getElementsByTagName('input');
        switch (lang) {
            case 'ru':
                recountInvoiceValuesRu(inputEle, isDefaultAvailable, inputs);
                break;
                
            case 'de':
                recountInvoiceValuesDe(inputEle, isDefaultAvailable, inputs);
                break;
                
            default:
                recountInvoiceValuesEn(inputEle, isDefaultAvailable, inputs);
                break;
        }
        countInvoiceAmount(inputEle);
    }
}

function recountInvoiceValuesEn(inputEle, isDefaultAvailable, inputs) {
    var fieldCount = 0;

    if (5 == inputs.length) {
        for (var i = 0; i < inputs.length; i++) {
            if (checkNumber(inputs[i].value)) {
                fieldCount++;
            }
        }
    }

    if (1 < fieldCount) {
        var quantityEle = inputs[3];
        var isQuantity = inputEle == quantityEle;
        var quantity = parseFloat(parseNumber(quantityEle.value).replace(',', '.'));
        if (isNaN(quantity) || quantity < 0) quantity = 0;

        var priceEle = inputs[2];
        var isPrice = inputEle == priceEle;
        var price = parseFloat(parseNumber(priceEle.value).replace(',', '.'));
        if (isNaN(price) || price < 0) price = 0;

        var amountEle = inputs[4];
        var isAmount = inputEle == amountEle;
        var amount = parseFloat(parseNumber(amountEle.value).replace(',', '.'));
        if (isNaN(amount) || amount < 0) amount = 0;
        
        if (isQuantity) {
            quantity = roundNumber(quantity);

            if (quantity == 0) {
                if (price != 0 && amount != 0) {
                    quantity = roundNumber(amount / price);
                }
            } else if (price != 0) {
                amount = roundNumber(quantity * price);
            } else if (amount != 0) {
                price = roundNumber(amount / quantity);
            }
        } else if (isPrice) {
            price = roundNumber(price);

            if (price == 0) {
                if (quantity != 0 && amount != 0) {
                    price = roundNumber(amount / quantity);
                }
            } else if (quantity != 0) {
                amount = roundNumber(quantity * price);
            } else if (amount != 0) {
                quantity = roundNumber(amount / price);
            }
        } else if (isAmount) {
            amount = roundNumber(amount);

            if (amount == 0) {
                if (quantity != 0 && price != 0) {
                    amount = roundNumber(quantity * price);
                }
            } else if (quantity != 0) {
                price = roundNumber(amount / quantity);
            } else if (price != 0) {
                quantity = roundNumber(amount / price);
            }
        }

        quantityEle.value = convertSumToHumanReadable(String(quantity));
        checkFieldNumber(quantityEle);

        if (isDefaultAvailable && defaultInvoiceItemQuantity) {
            formSwitchLabel(quantityEle, defaultInvoiceItemQuantity);
        }

        priceEle.value = convertSumToHumanReadable(String(price));
        checkFieldNumber(priceEle);

        if (isDefaultAvailable && defaultInvoiceItemPrice) {
            formSwitchLabel(priceEle, defaultInvoiceItemPrice);
        }

        amountEle.value = convertSumToHumanReadable(String(amount));
        checkFieldNumber(amountEle);

        if (isDefaultAvailable && defaultInvoiceItemAmount) {
            formSwitchLabel(amountEle, defaultInvoiceItemAmount);
        }
    }
}

function recountInvoiceValuesDe(inputEle, isDefaultAvailable, inputs) {
    var fieldCount = 0;

    if (5 == inputs.length) {
        for (var i = 0; i < inputs.length; i++) {
            if (checkNumber(inputs[i].value)) {
                fieldCount++;
            }
        }
    }

    if (1 < fieldCount) {
        var quantityEle = inputs[1];
        var isQuantity = inputEle == quantityEle;
        var quantity = parseFloat(parseNumber(quantityEle.value).replace(',', '.'));
        if (isNaN(quantity) || quantity < 0) quantity = 0;

        var priceEle = inputs[3];
        var isPrice = inputEle == priceEle;
        var price = parseFloat(parseNumber(priceEle.value).replace(',', '.'));
        if (isNaN(price) || price < 0) price = 0;

        var amountEle = inputs[4];
        var isAmount = inputEle == amountEle;
        var amount = parseFloat(parseNumber(amountEle.value).replace(',', '.'));
        if (isNaN(amount) || amount < 0) amount = 0;
        
        var tax = parseInt($(getParentElement(inputs[1], 'tr').getElementsByTagName('select')[0]).val());
        
        if (isQuantity) {
            quantity = roundNumber(quantity);

            if (quantity == 0) {
                if (price != 0 && amount != 0) {
                    quantity = roundNumber(amount / price);
                }
            } else if (price != 0) {
                amount = roundNumber(quantity * price);
            } else if (amount != 0) {
                price = roundNumber(amount / quantity);
            }
        } else if (isPrice) {
            price = roundNumber(price);

            if (price == 0) {
                if (quantity != 0 && amount != 0) {
                    price = roundNumber(amount / quantity);
                }
            } else if (quantity != 0) {
                amount = roundNumber(quantity * price);
            } else if (amount != 0) {
                quantity = roundNumber(amount / price);
            }
        } else if (isAmount) {
            amount = roundNumber(amount);

            if (amount == 0) {
                if (quantity != 0 && price != 0) {
                    amount = roundNumber(quantity * price);
                }
            } else if (quantity != 0) {
                price = roundNumber(amount / quantity);
            } else if (price != 0) {
                quantity = roundNumber(amount / price);
            }
        } else {
            // isTax
            amount = price * quantity; 
        }
        
        amount += amount * tax / 100;

        quantityEle.value = convertSumToHumanReadable(String(quantity));
        checkFieldNumber(quantityEle);

        if (isDefaultAvailable && defaultInvoiceItemQuantity) {
            formSwitchLabel(quantityEle, defaultInvoiceItemQuantity);
        }

        priceEle.value = convertSumToHumanReadable(String(price));
        checkFieldNumber(priceEle);

        if (isDefaultAvailable && defaultInvoiceItemPrice) {
            formSwitchLabel(priceEle, defaultInvoiceItemPrice);
        }

        amountEle.value = convertSumToHumanReadable(String(amount));
        checkFieldNumber(amountEle);

        if (isDefaultAvailable && defaultInvoiceItemAmount) {
            formSwitchLabel(amountEle, defaultInvoiceItemAmount);
        }
    }
}

function recountInvoiceValuesRu(inputEle, isDefaultAvailable, inputs) {
    var fieldCount = 0;

    if (4 == inputs.length) {
        for (var i = 0; i < inputs.length; i++) {
            if (checkNumber(inputs[i].value)) {
                fieldCount++;
            }
        }
    }

    if (1 < fieldCount) {
        var quantityEle = inputs[1];
        var isQuantity = inputEle == quantityEle;
        var quantity = parseFloat(parseNumber(quantityEle.value).replace(',', '.'));
        if (isNaN(quantity) || quantity < 0) quantity = 0;

        var priceEle = inputs[2];
        var isPrice = inputEle == priceEle;
        var price = parseFloat(parseNumber(priceEle.value).replace(',', '.'));
        if (isNaN(price) || price < 0) price = 0;

        var amountEle = inputs[3];
        var isAmount = inputEle == amountEle;
        var amount = parseFloat(parseNumber(amountEle.value).replace(',', '.'));
        if (isNaN(amount) || amount < 0) amount = 0;

        if (isQuantity) {
            quantity = roundNumber(quantity);

            if (quantity == 0) {
                if (price != 0 && amount != 0) {
                    quantity = roundNumber(amount / price);
                }
            } else if (price != 0) {
                amount = roundNumber(quantity * price);
            } else if (amount != 0) {
                price = roundNumber(amount / quantity);
            }
        } else if (isPrice) {
            price = roundNumber(price);

            if (price == 0) {
                if (quantity != 0 && amount != 0) {
                    price = roundNumber(amount / quantity);
                }
            } else if (quantity != 0) {
                amount = roundNumber(quantity * price);
            } else if (amount != 0) {
                quantity = roundNumber(amount / price);
            }
        } else if (isAmount) {
            amount = roundNumber(amount);

            if (amount == 0) {
                if (quantity != 0 && price != 0) {
                    amount = roundNumber(quantity * price);
                }
            } else if (quantity != 0) {
                price = roundNumber(amount / quantity);
            } else if (price != 0) {
                quantity = roundNumber(amount / price);
            }
        }

        quantityEle.value = convertSumToHumanReadable(String(quantity));
        checkFieldNumber(quantityEle);

        if (isDefaultAvailable && defaultInvoiceItemQuantity) {
            formSwitchLabel(quantityEle, defaultInvoiceItemQuantity);
        }

        priceEle.value = convertSumToHumanReadable(String(price));
        checkFieldNumber(priceEle);

        if (isDefaultAvailable && defaultInvoiceItemPrice) {
            formSwitchLabel(priceEle, defaultInvoiceItemPrice);
        }

        amountEle.value = convertSumToHumanReadable(String(amount));
        checkFieldNumber(amountEle);

        if (isDefaultAvailable && defaultInvoiceItemAmount) {
            formSwitchLabel(amountEle, defaultInvoiceItemAmount);
        }
    }
}

function countInvoiceAmount(someChild) {
    var tbodyEle = getParentElement(someChild, 'tbody');
    var amountEle = document.getElementById('invoice_amount');

    if (tbodyEle && amountEle) {
        var invoiceAmount = 0;
        var rows = tbodyEle.getElementsByTagName('tr');

        for (var i = 0; i < rows.length; i++) {
            var inputs = rows[i].getElementsByTagName('input');
            var itemAmount = 0;

            if (inputs.length > 1) {
                itemAmount = parseFloat(parseNumber(inputs[inputs.length - 1].value).replace(',', '.'));
                if (isNaN(itemAmount)) itemAmount = 0;
            }

            invoiceAmount += itemAmount;
        }

        $('#invoice_amount_without_nds, #invoice_amount_no_vat').text(convertSumToHumanReadable(roundNumber(invoiceAmount)));
        if ($('#is_nds').attr('checked')
                && $('#is_nds_above_1').attr('checked')
        ) {
            invoiceAmount += invoiceAmount * $('#tax_value').val() / 100;
        }
        invoiceAmount = roundNumber(invoiceAmount);
        amountEle.innerHTML = convertSumToHumanReadable(invoiceAmount);
    }
}

function convertSumToHumanReadable(str, options) {
    
    if (str == '') {
        str = '0';
    }
    
    options = $.extend(
        {
            showRubles: true
            , colorFormatting: false
            , positionSeparator: ','
            , hideFraction: true
        },
        options || {}
    );
    
    str += '';
    
    str = str.replace(numberPositionRegexp, '');
    
    if (options.hideFraction
        && (parseFloat(str) == parseInt(str))
    ) {
        var int = String(parseInt(str));
        var real = '';
    }  else {
        var pos;
        var int = str;
        var real = '00';
        if ((pos = str.indexOf('.')) >= 0) {
            int = str.substr(0, pos);
            real = str.substr(pos+1);
        } else if ((pos = str.indexOf(',')) >= 0) {
            int = str.substr(0, pos);
            real = str.substr(pos+1);
        }
        
        if (real.length == 1) {
            real += '0';
        }
        real = numberFractionSeparator + real;
    }
    
    var len = int.length;
    var counter = 0;
    var res = '';
    for (var i = len - 1; i >= 0; i--) {
        if ( (counter == 2) && (i != 0) ) {
            res = numberPositionSeparator + int.charAt(i) + res;
            counter = -1;
        } else {
            res = int.charAt(i) + res;
        }
        counter++;
    }
    
    if (options['colorFormatting']) {
        res += '<span class="number">' + real + '</span>';
    } else {
        res += real;
    }
    
    return res;
}

function recountInvoiceItems(tbodyEle) {
    if (tbodyEle) {
        var itemsCount = 0;
        var rows = tbodyEle.getElementsByTagName('tr');

        for (var i = 0; i < rows.length; i++) {
            var cols = rows[i].getElementsByTagName('td');

            if (0 < cols.length && 'number' == cols[0].className) {
                var spansEle = cols[0].getElementsByTagName('span');
                if (0 < spansEle.length) {
                    spansEle[0].innerHTML = ++itemsCount;
                }
            }
        }
    }
}

function removeInvoiceItem(ele, rowOffset) {
    rowOffset = rowOffset || 3;
    var row = getParentElement(ele, 'tr');
    
    if (row) {
        var tbody = getParentElement(row, 'tbody');
        
        /*if ($('tr', tbody).length == 4) {
            return;
        }*/
        
        row.parentNode.removeChild(row);

        if (tbody) {
            recountInvoiceItems(tbody);
            setLastInvoiceItem(tbody, rowOffset);
            countInvoiceAmount(tbody.firstChild);
        }
    }
}

function setLastInvoiceItem(ele, rowOffset) {
    rowOffset = rowOffset || 3;
    var parent = ele;

    if ('tbody' != parent.nodeName.toLowerCase()) {
        parent = getParentElement(parent, 'tbody');
    }

    if ('tbody' == parent.nodeName.toLowerCase()) {
        var trElems = parent.getElementsByTagName('tr');
        for (var i = 0; i < trElems.length; i++) {
            trElems[i].className = trElems.length - rowOffset == i ? 'last_item' : '';
        }
    }
}

function appendInvoiceItem(ele, isAuth, lang, options) {
    
    lang = lang || 'en';
    isAuth = isAuth || false;
    
    var row = getParentElement(ele, 'tr');
    if (row && 'last_item' == row.className) {

        var isError = false;
        var inputElems = row.getElementsByTagName('input');

        for (var i = 0; i < inputElems.length; i++) {
            if ('text' == inputElems[i].getAttribute('type')) {
                if (-1 != inputElems[i].className.indexOf('number')) {
                    if (checkNumber(inputElems[i].value)) {
                        continue;
                    }
                } else if (-1 != inputElems[i].className.indexOf('int')) {
                    if (checkInt(inputElems[i].value)) {
                        continue;
                    }
                } else if ('' != inputElems[i].value) {
                    continue;
                } else if (inputElems[i].className  == '') {
                    continue;
                }

                isError = true;
                break;
            }
        }

        if (!isError) {
            var addInvoiceBtn = document.getElementById('add_invoice');
            if (addInvoiceBtn) addInvoiceItem(addInvoiceBtn, isAuth, lang, options);
        }
    }
}

function addInvoiceItem(ele, isAuth, lang, options) {

    isAuth = isAuth || false;
    var row = getParentElement(ele, 'tr');
    if (row) {
    
        switch (lang) {
            case 'ru':
                var newRow = createInvoiceRowRu(row, isAuth, options);
                var rowOffset = 2;
                break;
                
            case 'de':
                var newRow = createInvoiceRowDe(row, isAuth, options);
                var rowOffset = 2;
                break;
                
            default:
                var newRow = createInvoiceRowEn(row, isAuth, options);
                var rowOffset = 2;
        }

        row.parentNode.insertBefore(newRow, row);
        setLastInvoiceItem(ele, rowOffset);
        
        toggleDeleteInvoiceRowButton($('#invoice_foreign tbody tr').not('tr:last'), 'invoice_foreign');
        
        if (lang == 'en') {
            toggleDeleteInvoiceRowButton(
                $('#invoice_foreign tbody tr').not('tr:last')
                , 'invoice_foreign'
            );
        }
        
        if (isAuth) {
            // TODO: сделать автокомплит
            addAutocompleteToInvoiceItem(false);
            addAutocompleteToInvoiceDescription(false);
        }
        
        /*addTabHandler(td5, isAuth);*/
    }
}

function createInvoiceRowEn(row, isAuth, options) {
    var newRow = document.createElement('tr');
    
    var itemsCount = 1;
    var tbodyEle = getParentElement(row, 'tbody');
    if (tbodyEle) {
        itemsCount = tbodyEle.getElementsByTagName('tr').length - 2;
    }
    
    if (!isAuth) {
        var appendInvoice = 'appendInvoiceItem(this, false, \'en\');';
    } else {
        var appendInvoice = 'appendInvoiceItem(this, true, \'en\');';
    }
    
    var td1 = document.createElement('td');
    td1.innerHTML = 
        '<input type="text" size="255"onfocus="' + appendInvoice
        + '" onblur="' + appendInvoice + '" onkeyup="' + appendInvoice
        + '" name="item_names[]" />';
    td1.className = 'item_en';  
    
    var td2 = document.createElement('td');
    td2.innerHTML =
        '<input type="text" size="255" onfocus="' + appendInvoice
        + '" onblur="' + appendInvoice + '" onkeyup="' + appendInvoice
        + '" name="item_descriptions[]" />';
    td2.className = 'description_en';
    
    var td3 = document.createElement('td');
    td3.innerHTML =
        '<input type="text" class="number" onfocus="formatInvoiceItemElem(this)"'
        + ' onblur="formatInvoiceItemElem(this, true); if (checkFieldNumber(this)) {'
        + 'recountInvoiceValues(this, false, \'en\'); '+ appendInvoice + ' }"'
        + ' name="item_prices[]" />';
    td3.className = 'price_en';
    
    var td4 = document.createElement('td');
    td4.innerHTML =
        '<input type="text" class="number default" onfocus="$(this).css(\'color\', \'black\').css(\'font-style\', \'normal\'); formatInvoiceItemElem(this)"'
        + ' onblur="formatInvoiceItemElem(this, true); if (checkFieldNumber(this)) {'
        + 'recountInvoiceValues(this, false, \'en\'); '+ appendInvoice + ' }"'
        + ' name="item_quantities[]" value="1" />';
    td4.className = 'quantity_en';
        
    var td5 = document.createElement('td');
    td5.innerHTML =
        '<input type="text" class="number" onfocus="formatInvoiceItemElem(this)"'
        + ' onblur="formatInvoiceItemElem(this, true); if (checkFieldNumber(this)) {'
        + 'recountInvoiceValues(this, false, \'en\'); '+ appendInvoice + ' }"'
        + ' name="item_amounts[]" />';
    td5.className = 'amount_en';
    
    newRow.appendChild(td1);
    newRow.appendChild(td2);
    newRow.appendChild(td3);
    newRow.appendChild(td4);
    newRow.appendChild(td5);
    
    return newRow;
}

function createInvoiceRowDe(row, isAuth, options) {
    
    options = $.extend({
            includeTax: false
            , noTaxMsg: 'N/A'
        }
        , options || {}
    );
    
    var newRow = document.createElement('tr');
    
    var itemsCount = 1;
    var tbodyEle = getParentElement(row, 'tbody');
    if (tbodyEle) {
        itemsCount = tbodyEle.getElementsByTagName('tr').length - 2;
    }
    
    if (!isAuth) {
        var appendInvoice = 'appendInvoiceItem(this, false, \'de\');';
    } else {
        var appendInvoice = 'appendInvoiceItem(this, true, \'de\', {includeTax:'
            + options.includeTax + ', noTaxMsg:\'' + options.noTaxMsg + '\'});';
    }
    
    var td1 = document.createElement('td');
    td1.innerHTML = 
        '<input type="text" size="255"onfocus="' + appendInvoice
        + '" onblur="' + appendInvoice + '" onkeyup="' + appendInvoice
        + '" name="item_names[]" />';
    td1.className = 'item_de';  
    
    var td2 = document.createElement('td');
    td2.innerHTML =
        '<input type="text" class="number default" onfocus="$(this).css(\'color\', \'black\').css(\'font-style\', \'normal\'); formatInvoiceItemElem(this)"'
        + ' onblur="formatInvoiceItemElem(this, true); if (checkFieldNumber(this)) {'
        + 'recountInvoiceValues(this, false, \'de\'); '+ appendInvoice + ' }"'
        + ' name="item_quantities[]" value="1" />';
    td2.className = 'quantity_de';
    
    var td3 = document.createElement('td');
    td3.innerHTML =
        '<input type="text" size="255" onfocus="' + appendInvoice
        + '" onblur="' + appendInvoice + '" onkeyup="' + appendInvoice
        + '" name="item_descriptions[]" />';
    td3.className = 'description_de';
    
    var td4 = document.createElement('td');
    if (options.includeTax) {
         td4.innerHTML =
            '<select name="item_taxes[]" onchange="recountInvoiceValues(this, false, \'de\');">'
            + '<option value="19">19%</option><option value="7">7%</option><option value="0" selected="true">'
            + options.noTaxMsg + '</option></select>'
    } else {
        td4.innerHTML = '<select name="item_taxes[]"><option value="0" selected="true">0</option></select>';
        td4.style.display = 'none';
    } 
    td4.className = 'tax_de';
    
    var td5 = document.createElement('td');
    td5.innerHTML =
        '<input type="text" class="number" onfocus="formatInvoiceItemElem(this)"'
        + ' onblur="formatInvoiceItemElem(this, true); if (checkFieldNumber(this)) {'
        + 'recountInvoiceValues(this, false, \'de\'); '+ appendInvoice + ' }"'
        + ' name="item_prices[]" />';
    td5.className = 'price_de';
    
    var td6 = document.createElement('td');
    td6.innerHTML =
        '<input type="text" class="number" onfocus="formatInvoiceItemElem(this)"'
        + ' onblur="formatInvoiceItemElem(this, true); if (checkFieldNumber(this)) {'
        + 'recountInvoiceValues(this, false, \'de\'); '+ appendInvoice + ' }"'
        + ' name="item_amounts[]"/>';
    td6.className = 'amount_en';
    td6.style.display = 'none';
    
    newRow.appendChild(td1);
    newRow.appendChild(td2);
    newRow.appendChild(td3);
    newRow.appendChild(td4);
    newRow.appendChild(td5);
    newRow.appendChild(td6);
    
    return newRow;
}

function createInvoiceRowRu(row, isAuth, options) {
    var newRow = document.createElement('tr');
    newRow.onmouseover = function () { showServiceIcons(newRow); }
    newRow.onmouseout = function () { hideServiceIcons(newRow); }

    var itemsCount = 1;
    var tbodyEle = getParentElement(row, 'tbody');
    if (tbodyEle) {
        itemsCount = tbodyEle.getElementsByTagName('tr').length - 2;
    }

    if (!isAuth) {
        var appendInvoice = 'appendInvoiceItem(this, false, \'ru\')';
        var spacerStyle = 'remove_invoice not_auth';
    } else {
        var appendInvoice = 'appendInvoiceItem(this, true, \'ru\')';
        var spacerStyle = 'remove_invoice';
    }

    var td1 = document.createElement('td');
    td1.innerHTML = 
        '<input type="text" size="255"onfocus="' + appendInvoice
        + '" onblur="' + appendInvoice + '" onkeyup="' + appendInvoice
        + '" name="item_names[]" />';
    td1.className = 'item_ru';  
    
    var td2 = document.createElement('td');
    td2.innerHTML =
        '<input type="text" class="number default" onfocus="$(this).css(\'color\', \'black\').css(\'font-style\', \'normal\'); formatInvoiceItemElem(this)"'
        + ' onblur="formatInvoiceItemElem(this, true); if (checkFieldNumber(this)) {'
        + 'recountInvoiceValues(this, false, \'ru\'); '+ appendInvoice + ' }"'
        + ' name="item_quantities[]" value="1" />';
    td2.className = 'quantity_ru';
    
    var td3 = document.createElement('td');
    td3.innerHTML =
        '<input type="text" class="number" onfocus="formatInvoiceItemElem(this)"'
        + ' onblur="formatInvoiceItemElem(this, true); if (checkFieldNumber(this)) {'
        + 'recountInvoiceValues(this, false, \'ru\'); '+ appendInvoice + ' }"'
        + ' name="item_prices[]" />';
    td3.className = 'price_ru';
    
    var td4 = document.createElement('td');
    td4.innerHTML =
        '<input type="text" class="number" onfocus="formatInvoiceItemElem(this)"'
        + ' onblur="formatInvoiceItemElem(this, true); if (checkFieldNumber(this)) {'
        + 'recountInvoiceValues(this, false, \'ru\'); '+ appendInvoice + ' }"'
        + ' name="item_amounts[]"/>';
    td4.className = 'amount_ru';
    
    newRow.appendChild(td1);
    newRow.appendChild(td2);
    newRow.appendChild(td3);
    newRow.appendChild(td4);
    
    return newRow;
}

function addTabHandler(invoiceItem, isAuth) {
    $('input[name^=item_amounts]', invoiceItem).each(function() {
        $(this).keydown(function(event) {
            if (event.keyCode == 9) {
                var parent = getParentElement(this, 'tr');
                if ($(parent).hasClass('last_item')) {
                    addInvoiceItem(document.getElementById('add_invoice'), isAuth);
                    $('tr.last_item textarea').each(function() {
                        this.focus();
                    });
                    return false;
                }
            }
        })
    });
}

function elementPosition(ele) {
    this.x = ele.offsetLeft;
    this.y = ele.offsetTop;
    this.ele = ele;

    while (this.ele.offsetParent != null) {
        this.ele = this.ele.offsetParent;
        this.x += this.ele.offsetLeft;
        this.y += this.ele.offsetTop;
    }
}

function addEvent(ele, type, func) {
    if (ele.addEventListener) {
        ele.addEventListener(type, func, false);
    } else if (ele.attachEvent) {
        ele.attachEvent('on' + type, func);
    }
}

function removeEvent(ele, type, func) {
    if (ele.removeEventListener) {
        ele.removeEventListener(type, func, false);

    } if (ele.detachEvent) {
        ele.detachEvent('on' + type, func);
    }
}

function cancelEvent(e) {
    var evt = e ? e : window.event;
    evt.cancelBubble = true;
}

function showPopupForm(btn, formId, hideFunc, e) {
    if (e) cancelEvent(e);

    var formEle = document.getElementById(formId);
    if (formEle) {
        $(formEle).fadeIn('fast');
        
        var bodyWidth = parseInt(document.getElementsByTagName('body')[0].offsetWidth);
        var formWidth = parseInt(formEle.offsetWidth);
        var pstn = new elementPosition(btn);
        var left = formWidth + pstn.x > bodyWidth ? bodyWidth - formWidth - 10 : pstn.x;

        formEle.style.left = left + 'px';
        formEle.style.top = pstn.y + btn.offsetHeight + 5 + 'px';

        if (e) {
            addEvent(formEle, 'click', cancelEvent);
            addEvent(document, 'click', hideFunc);
        }
        
    }
}

function hideAuthForm() {
    hideForm('auth_form_');
}

function hideRecommendForm() {
    hideForm('recommend_form_');
}

function hideRemindForm() {
    hideForm('remind_form');
}

function hideEmailForm() {
    hideForm('email_form_');
    hideForm('notify_form_');
}

function hideForm(id) {
    $('#' + id).fadeOut('fast');
}

function showAuthForm(btn, e) {
    showPopupForm(btn, 'auth_form', hideAuthForm, e);
}

function showRemindForm(btn, e) {
    showPopupForm(btn, 'remind_form', hideRemindForm, e);
}

function showEmailForm(btn, action, e) {
    var actionEle = document.getElementById('email_form_action');
    if (actionEle) actionEle.value = action;

    var labelEle = document.getElementById('email_form_header');
    if (labelEle) {
        if ('email' == action) {
            labelEle.innerHTML = 'Отправить по email';

        } else if ('notify' == action) {
            labelEle.innerHTML = 'Напомнить по email';
        }
    }

    $('#send_email_form').hide();
    showPopupForm(btn, 'send_email_form', hideEmailForm, e);
}

function checkEmailForm(errorMsg) {
    var email = trimEmail($('#email').val());
    $('#email').val(email);
    
    if (!validateEmail(email)) {
        
        $('#email_form_container').attr('class', 'container_error');
        $('#email_form_error_text').text(errorMsg);
        $('#email_form_error_text').show();
        return false;
    }
    
    $('#email_form_container').attr('class', 'container');
    $('#email_form_error_text').text('');
    
    return true;
}

function checkEmailRemindForm(errorMsg) {
    var email = trimEmail($('#email_remind').val());
    $('#email_remind').val(email);
    
    if (!validateEmail(email)) {
        
        $('#remind_form_container').attr('class', 'container_error');
        $('#remind_form_error_text').text(errorMsg);
        $('#remind_form_error_text').show();
        return false;
    }
    
    $('#remind_form_container').attr('class', 'container');
    $('#remind_form_error_text').text('');
    
    return true;
}

function validateEmail(value) {
    return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}

function loadFirstInvoicePreview(containerId) {
    $('#' + containerId).load(
        '/ajax/first-invoice-preview'
        , {}
        , hideLoadingBar
    );
}

function loadFirstInvoiceForm(containerId, invoiceId) {
    $('#' + containerId).load(
        '/ajax/first-invoice-form/'
        , {}
        , hideLoadingBar
    );
}

function submitFirstInvoiceForm(containerId, invoiceId) {
    showLoadingBar();
    $('#' + containerId).load(
        '/ajax/first-invoice-form/' + invoiceId + '?' + $('#first_invoice_form').serialize(),
        {},
        hideLoadingBar
    );
}

function cancelFirstInvoiceForm(containerId, invoiceId) {
    showLoadingBar();
    $('#' + containerId).load(
        '/ajax/first-invoice-preview/?id=' + invoiceId,
        {},
        hideLoadingBar
    );
}

var timeout;

function downloadInvoice(id) {
    var ele = document.getElementById('downloader');
    if (ele) ele.src = '/download/invoice/' + id + '/';
}

function initDownloadInvoice(id) {
    window.setTimeout(function() {downloadInvoice(id)}, 3000);
}

function downloadUri(uri) {
    var ele = document.getElementById('downloader');
    if (ele) ele.src = '/download/uri/?uri=' + encodeURI(uri);
}

function initDownloadUri(uri) {
    window.setTimeout(function() {downloadUri(uri)}, 3000);
}

function initDownloadInvoice(uri) {
    window.setTimeout(function()
        {
            window.location.href = '/download/uri/?uri=' + encodeURI(uri);
        },
        3000
    );
}

function onFakePasswordFocus(defaultValue) {
    var passwordEle = document.getElementById('auth_password');
    passwordEle.style.display = 'block';
    formEditElement(passwordEle, defaultValue, true);
    passwordEle.focus();

    var fakeEle = document.getElementById('auth_password_fake');
    fakeEle.style.display = 'none';
}

function onPasswordBlur(defaultValue) {
    var passwordEle = document.getElementById('auth_password');
    var fakeEle = document.getElementById('auth_password_fake');

    if (
        '' == passwordEle.value ||
        passwordEle.value == defaultValue
    ) {
        passwordEle.value = '';
        passwordEle.style.display = 'none';
        fakeEle.style.display = 'block';
    }
    
}


/*** Loading bar
*********************************************************/
var loadings = 0;

function showLoadingBar() {
    if (loadings == 0) {
        waitCursor(true);
    }
    loadings++;
}

function hideLoadingBar() {
    loadings--;
    if (loadings == 0) {
        waitCursor(false);
    }
}

function waitCursor(isOn) {
    var bodyEle = document.getElementsByTagName('body');
    if (bodyEle) {
        var className = getClassName(bodyEle[0], 'wait');
        if (isOn) className += ('' == className ? '' : ' ') + 'wait';
        bodyEle[0].className = className;
    }
}

function toggleActionString(checkboxElem) {
    
    $('#confirmation_').hide();
    $('#confirmation_error_').hide();
    
    checkboxEmel = false || checkboxElem;
    
    if (checkboxElem && !checkboxElem.checked) {
        var tr = $(getParentElement(checkboxElem, 'tr'));
        tr.css('background-color', 'white');
        $('.fadeout1,.fadeout2,.fadeout3', tr).css('background-color', 'white');
        
        setHoverForInvoiceRow(tr, '#F1F6FF', 'white');
    }
    
    var actionStr = $('tr.action');
    if (actionStr) {
        var flags = $('table.data > tbody > tr > td > input:checked');
        
        if (flags.length == 0) {
            
            flags = $('table.data > tbody > tr > td > input:checkbox');
            
            actionStr.fadeOut('fast');
            $('div.action span:first').fadeOut('fast');
            $('#mainChecker').removeAttr('checked');
            
            flags.each(function() {
                var tr = $(getParentElement(this, 'tr'));
                tr.css('background-color', 'white');
                $('.fadeout1,.fadeout2,.fadeout3', tr).css('background-color', 'white');
                
                setHoverForInvoiceRow(tr, '#F1F6FF', 'white');
            });
            
        } else if (flags.length == 1) {
            if (flags[0].id && (flags[0].id = 'mainChecker')) {
                actionStr.fadeOut('fast');
                $('div.action span:first').fadeOut('fast');
                $('#mainChecker').removeAttr('checked');
                
                flags.each(function() {
                    var tr = $(getParentElement(this, 'tr'));
                    tr.css('background-color', 'white');
                    $('.fadeout1,.fadeout2,.fadeout3', tr).css('background-color', 'white');
                    
                    setHoverForInvoiceRow(tr, '#F1F6FF', 'white');
                });
                
            } else {
                $('div.action span:first').fadeIn('fast');
                actionStr.show();
                
                flags.each(function() {
                    var tr = $(getParentElement(this, 'tr'));
                    tr.css('background-color', '#feffdc');
                    $('.fadeout1,.fadeout2,.fadeout3', tr).css('background-color', '#feffdc');
                    
                    setHoverForInvoiceRow(tr, '#F1F6FF', '#feffdc');
                });

            }
        } else {
            $('div.action span:first').fadeIn('fast');
            actionStr.show();
            
            flags.each(function() {
                var tr = $(getParentElement(this, 'tr'));
                tr.css('background-color', '#feffdc');
                $('.fadeout1,.fadeout2,.fadeout3', tr).css('background-color', '#feffdc');
                
                setHoverForInvoiceRow(tr, '#F1F6FF', '#feffdc');
            });
            
        }
    }
    
    adjustFooter();
    
    /*var parentTr = getParentElement(checkboxElem, 'tr');
    if (checkboxElem.checked) {
        $(parentTr).css('background-color', 'red');
    } else {
        $(parentTr).css('background-color', 'white');
    }*/
    
}

function invoicesSorter(tableId) {
    
    var tableObj = document.getElementById(tableId);
                    
    this.nullValue = -1000000; // нужно, чтобы помещать пустые значения в самый верх
    
    this.rowsPointer = {
        number: 1,
        company: 2,
        items: 3,
        sum: 5,
        status: 6,
        date: 7,
        period: 4,
        stopped: 9,
        regular_sum: 7,
        creation_date: 8,
        regular_date: 8
    };
    
    this.tBody = tableObj.tBodies[0];
    this.rowsLen = this.tBody.childNodes.length;
    
    // индексируем строки, чтобы учитывать их при сортировке
    this.upperActionRow = this.tBody.childNodes[0];
    this.lowerActionRow = this.tBody.childNodes[this.rowsLen - 1];
    
    this.isSortingStarted = false;
    this.sortOrder = {
        'number' : true,
        'company': true,
        'sum': true,
        'items' : true,
        'status': true,
        'date': false,
        'period': true,
        'stopped': true,
        'regular_sum': true,
        'creation_date': false,
        'regular_date': false
    }
    
    this.headColumnNames = {
        'invoice_number_row': $('#invoice_number_row').text(),
        'invoice_company_row': $('#invoice_company_row').text(),
        'invoices_name_row': $('#invoices_name_row').text(),
        'invoice_date_row': $('#invoice_date_row').text(),
        'invoice_sum_row': $('#invoice_sum_row').text(),
        'invoice_status_row': $('#invoice_status_row').text(),
        'invoice_period_row': $('#invoice_period_row').text(),
        'invoice_stopped_row': $('#invoice_stopped_row').text(),
        'invoice_regular_sum_row': $('#invoice_regular_sum_row').text()
    };
    
    for(var i = 1; i < (this.rowsLen - 1); i++) {
        this.getUniqueID(this.tBody.childNodes[i], i);
    }
    
    this.sortedBy = {
        rowId: '',
        sortBy: ''
    }

}

invoicesSorter.prototype.reInit = function(reverseSortFlag) {

    var flag = reverseSortFlag || false;
    
    this.rowsLen = this.tBody.childNodes.length;
    this.upperActionRow = this.tBody.childNodes[0];
    this.lowerActionRow = this.tBody.childNodes[this.rowsLen - 1];
    this.isSortingStarted = false;
    
    for(var i = 1; i < (this.rowsLen - 1); i++) {
        this.getUniqueID(this.tBody.childNodes[i], i);
    }
    
    if (flag) {
        this.sortOrder[this.sortedBy.sortBy] = !this.sortOrder[this.sortedBy.sortBy];
        this.sortBy(this.sortedBy.rowId, this.sortedBy.sortBy);
    }
}

invoicesSorter.prototype.getUniqueID = function(robj, pos) {
    if(!robj.runiqueID) {
        robj.runiqueID = pos;
    }
    return robj.runiqueID;
}

invoicesSorter.prototype.sortBy = function (rowId, sortBy) {

    if (this.isSortingStarted) {
        return;
    }

    this.isSortingStarted = true;
    
    this.sortedBy.rowId = rowId;
    this.sortedBy.sortBy = sortBy;
    
    if(this.rowsLen > 3) {
        
        var dataCol = new Array();
        var val = false;
        
        for(var i = 1; i<this.rowsLen; i++) {
            
            var rowObj = this.tBody.childNodes[i];
            if ( (rowObj == this.upperActionRow) || (rowObj == this.lowerActionRow) ) {
                continue;
            }
            
            /*if ( ($(rowObj).attr('class') == 'first') || ($(rowObj).attr('class') == 'last') ) {
                $(rowObj).removeAttr('class');
                
            }*/
            
            if(!rowObj.tagName) continue; // пропускаем текстовые ноды (FF)
            var colObj = rowObj.childNodes[this.rowsPointer[sortBy]];
            if (sortBy == 'company') {
                val = $('span.__company', rowObj).text();
            } else {
                val = $(colObj).text();
            }
            
            var obj = [val,
                       rowObj.runiqueID,
                       rowObj];
            dataCol.push(obj);
        }
        
        switch (sortBy) {
            case 'number':
                dataCol.sort(this.invoiceNumberSort)
                break;
                
            case 'company':
                dataCol.sort(this.sortString);
                break;
            
            case 'items':
                dataCol.sort(this.sortString);
                break;
                
            case 'sum':
            case 'regular_sum':
                dataCol.sort(this.sortFormattedSum);
                break;
                
            case 'date':
            case 'stopped':
            case 'creation_date':
            case 'regular_date':
                dataCol.sort(this.numberSort);
                break;
            
            case 'status':
                dataCol.sort(this.statusSort);
                break;
                
            case 'period':
                dataCol.sort(this.periodSort);
                break;
            
            default:
                break;
        }
        
        if( this.sortOrder[sortBy] == false ) {
            dataCol.reverse();
        }
        
        this.sortOrder[sortBy] = !this.sortOrder[sortBy];
        
        // восстанавливаем строки в таблицу в нужном (отсортированном) порядке
        var l = dataCol.length;
        
        this.tBody.appendChild(this.upperActionRow);
        
        for(var i = 0; i < l; i++) {
            this.tBody.appendChild(dataCol[i][2]);
        }
        
        this.tBody.appendChild(this.lowerActionRow);
        
        var rows = $('tr:visible', this.tBody).not('.action');
        rows.removeClass('first');
        rows.removeClass('last');
        rows.filter(':first').addClass('first');
        rows.filter(':last').addClass('last');
        
        this.markRow(rowId, sortBy);
    }
    
    this.isSortingStarted = false;
}

invoicesSorter.prototype.markRow = function(rowId, sortBy) {
    
    if (this.sortOrder[sortBy] == false) {
        var imgSrc = '/f/images/invoice_arrow_down.gif';
    } else {
        var imgSrc = '/f/images/invoice_arrow_up.gif';
    }

    var links = $('table.data > thead > tr > td > a');

    for (var i = 0; i < links.length; i++) {
        
        var link = $(links[i]);
        if (link.attr('id') != rowId) {
            link.text(this.headColumnNames[link.attr('id')]);
        }
    }

    $(('#' + rowId)).html(this.headColumnNames[rowId] + '<img src="' + imgSrc + '" />');

}

invoicesSorter.prototype.periodSort = function(a, b) {
    
    var str1 = String(a[0]);
    var str2 = String(b[0]);
    
    if (str1 == 'Месяц') {
        var x = 0;
    } else if (str1 == 'Год') {
        var x = 1;
    } else {
        var x = 2;
    }
    
    if (str2 == 'Месяц') {
        var y = 0;
    } else if (str2 == 'Год') {
        var y = 1;
    } else {
        var y = 2;
    }
    
    var result = x > y ? 1: -1;
    return result;
}

invoicesSorter.prototype.sortString = function(a, b) {
    
    var x = String(a).toUpperCase();
    var y = String(b).toUpperCase();
    
    var result = 0;
    result = x > y ? 1 : -1;
    
    return result;
}

invoicesSorter.prototype.sortFormattedSum = function(a, b) {
    
    var sum1 = 0.0;
    var sum2 = 0.0;
    
    var matches = a[0].match(/\'([^\']+)/);
    
    if (matches) {
        var value = matches[1].replace(',', '.');
        sum1 = parseFloat(value);
    } else {
        if (a[0].match(/^([0-9 ,]+)$/)) {
            sum1 = a[0].replace(',', '.');
            while (sum1.indexOf(' ') >= 0) {
                sum1 = sum1.replace(' ', '');
            }
        }
        sum1 = parseFloat(sum1);
    }
    
    var matches = b[0].match(/\'([^\']+)/);
    if (matches) {
        var value = matches[1].replace(',', '.');
        sum2 = parseFloat(value);
    } else {
        if (b[0].match(/^([0-9 ,]+)$/)) {
            sum2 = b[0].replace(',', '.');
            while (sum2.indexOf(' ') >= 0) {
                sum2 = sum2.replace(' ', '');
            }
        }
        sum2 = parseFloat(sum2);
    }
    
    return sum1 - sum2;
}

invoicesSorter.prototype.invoiceNumberSort = function(a, b) {
    
    a = new String(a);
    b = new String(b);
    
    var num1 = parseFloat(a);
    var num2 = parseFloat(b);

    var res = 0;
    if (num1 && num2) {
        res = num1 - num2;
        if (!res) {
            var s1 = a.match(/([^0-9]+)/);
            var s2 = b.match(/([^0-9]+)/);

            if (s1 && s2) {
                var str1 = a.substr(a.indexOf(s1[0]));
                var str2 = b.substr(b.indexOf(s2[0]));

                res = str1 < str2 ? -1 : 1;
            } else if (s1 && !s2) {
                res = 1;
            } else if (!s1 && s2) {
                res = -1;
            }
        }
    } else {
        res = a < b ? -1 : 1;
    }
    
    return res;
}

invoicesSorter.prototype.numberSort = function(a, b) {
    a = parseFloat(a);
    b = parseFloat(b);
    
    if (isNaN(a)) {
        a = 0;
    }
    
    if (isNaN(b)) {
        b = 0;
    }
    
    return a - b;
}

invoicesSorter.prototype.statusSort = function(st1, st2) {

    /*var statuses = {
        'просрочен': 0,
        'отправлен': 1,
        '': 2,
        'оплачен': 3
    };*/
    
    switch (st1[0]) {
        case 'просрочен':
            st1 = 0;
            break;
            
        case 'отправлен':
            st1 = 1;
            break;
            
        case 'оплачен':
            st1 = 3;
            break;
        
        default:
            st1 = 2;
            break;
    }
    
    switch (st2[0]) {
        case 'просрочен':
            st2 = 0;
            break;
            
        case 'отправлен':
            st2 = 1;
            break;
            
        case 'оплачен':
            st2 = 3;
            break;
        
        default:
            st2 = 2;
            break;
    }

    return st1 - st2;
}

function renderInvoiceTbl(currentPage, invoicesPerPage) {
    
    // currentPage [1..n]
    
    var table = document.getElementById('invoices_tbl');
    
    var tBody = table.tBodies[0];
    if (!tBody) {
        return;
    }
    
    var totalRows = tBody.rows.length - 2;
    if (totalRows < 1) {
        return;
    }
    
    var totalPages = Math.ceil(totalRows / invoicesPerPage);
    if (currentPage > totalPages) {
        currentPage = 1;
    }
    
    var firstRow = $('table.data > tbody > tr.first');
    var lastRow = $('table.data > tbody > tr.last');
    
    var lowerActionRow = $('table.data > tbody > tr.action')[1];
    
    /*var counter = 0;
    for (var i = 1; i < invoicesPerPage; i++) {
        
    }*/
}

function invoicesPaginator(
    invoicesTblId
    , invoicesFilterId
    , invoicesPerPage
    , totalPages
    , showAllInvoicesMsg
    , showNumberInvoicesMsg
    , showedResultsMsg
) {
    
    this.pages = totalPages || 0;
    
    this.invoicesFilter = $('#' + invoicesFilterId);
    this.filterType = this.invoicesFilter.val();
    this.invoicesPerPage = invoicesPerPage;
    this.currentPage = 1;
    
    this.showAllInvoicesMsg = showAllInvoicesMsg || '';
    this.showNumberInvoicesMsg = showNumberInvoicesMsg || '';
    this.showedResultsMsg = showedResultsMsg || '';
    
    this.table = document.getElementById(invoicesTblId);
    this.tBody = this.table.tBodies[0];
    if (!this.tBody) {
        return;
    }
    
    this.totalRows = this.tBody.rows.length - 2;
    
    //this.totalPages = Math.ceil(this.totalRows / parseInt(this.invoicesPerPage));
    this.totalPages = {
        '0': Math.ceil(this.totalRows / parseInt(this.invoicesPerPage)), // все счета
        '1': Math.ceil($('tr#1', this.tBody).length / parseInt(this.invoicesPerPage)), // просроченные
        '2': Math.ceil($('tr#2', this.tBody).length / parseInt(this.invoicesPerPage)), // оплаченные
        '3': Math.ceil($('tr#3', this.tBody).length / parseInt(this.invoicesPerPage)), // отправленные
        '4': Math.ceil($('tr#4', this.tBody).length / parseInt(this.invoicesPerPage)), // не отправленные
        '5': Math.ceil($('tr[act_id!=0]', this.tBody).length / parseInt(this.invoicesPerPage)), // закрытые актом
        '6': Math.ceil($('tr[act_id=0]', this.tBody).length / parseInt(this.invoicesPerPage)) // не закрытые актом
    };
    $(this.table).show();
    this.render();
    
}

invoicesPaginator.prototype.reInit = function() {
    this.totalRows = this.tBody.rows.length - 2;
    this.totalPages = {
            '0': Math.ceil(this.totalRows / parseInt(this.invoicesPerPage)), // все счета
            '1': Math.ceil($('tr#1', this.tBody).length / parseInt(this.invoicesPerPage)), // просроченные
            '2': Math.ceil($('tr#2', this.tBody).length / parseInt(this.invoicesPerPage)), // оплаченные
            '3': Math.ceil($('tr#3', this.tBody).length / parseInt(this.invoicesPerPage)), // отправленные
            '4': Math.ceil($('tr#4', this.tBody).length / parseInt(this.invoicesPerPage)), // не отправленные
            '5': Math.ceil($('tr[act_id!=0]', this.tBody).length / parseInt(this.invoicesPerPage)), // закрытые актом
            '6': Math.ceil($('tr[act_id=0]', this.tBody).length / parseInt(this.invoicesPerPage)) // не закрытые актом
    };
    $(this.table).show();
    this.render();
}

invoicesPaginator.prototype.setFilter = function() {

    this.filterType = this.invoicesFilter.val();

    this.currentPage = 1;
    this.render();
}

invoicesPaginator.prototype.render = function() {

    var stopIndex = this.currentPage * this.invoicesPerPage;
    var counter = 0;
    var isSelected = false;
    var index = 1;
    
    for (index = 1; ( (counter < stopIndex) && (index < this.totalRows + 1) ); index++) {
    
    	if (index > this.tBody.rows.length) break;
    	
        var row = $(this.tBody.rows[index]);
        if (row.attr('class') == 'action') {
            break;
        }
        
        row.removeAttr('class');
        if ( (this.filterType == 6) && (row.attr('act_id') != '0')) {
        	row.hide();
            $('td > input', row).removeAttr('checked');
        } else if ( (this.filterType == 5) && (row.attr('act_id') == '0')) {
        	row.hide();
            $('td > input', row).removeAttr('checked');
        } else if ( (this.filterType > 0) && (this.filterType < 5) && (row.attr('id') != this.filterType) ) {
        	row.hide();
            $('td > input', row).removeAttr('checked');
        } else {
            if ($('td > input:checked', row).length) {
                isSelected = true;
            }
            row.show();
            counter++;
        }
        
    }

    if (this.filterType == '0') {
        var length = $('tr', this.tBody).not('.action,.invisible').length;
    } else {
        var length = $('tr#' + this.filterType, this.tBody).length;
    }
    
    if ((counter + 1) != length) {
        $('tr:gt(' + (index - 1) + ')', this.tBody).hide();
    } else {
        $('tr:eq(' + (index) + ')', this.tBody).show();
    }
    
    $('tr:visible', this.tBody).not('.action').removeClass('first').removeClass('last');
    $('tr:visible', this.tBody).not('.action').filter(':first').addClass('first');
    $('tr:visible', this.tBody).not('.action').filter(':last').addClass('last');
    
    if (isSelected) {
        $('tr.action').show();
    } else {
        $('tr.action').hide();
    }
    
    if (!this.pages) {
        if (this.currentPage >= this.totalPages[this.filterType]) {
            $('#show_more_invoices').hide();
            var paginatorTop = $('#paginator_top');
            if (paginatorTop) {
                paginatorTop.hide();
                $('#invoices_paginator').css('top', '0');
            }
        } else if ( (this.totalPages[this.filterType] - this.currentPage) == 1 ) {
            $('#show_more_invoices').show();
            $('#show_more_invoices').text(this.showAllInvoicesMsg);
        } else {
            $('#show_more_invoices').show();
            $('#show_more_invoices').text(
                this.showNumberInvoicesMsg.replace('%d', this.invoicesPerPage)
            );
        }
    } else if (this.pages == 1) {
        var paginatorTop = $('#paginator_top');
        if (paginatorTop) {
            paginatorTop.hide();
            $('#invoices_paginator').css('top', '0');
        }
    }
    
    var searchResults = $('#searchResults');
    if (searchResults) {
        if (length == 0) {
            $('#searchResults').text('');
        } else {
            if (this.currentPage >= this.totalPages[this.filterType]) {
                var showedResults = length;
            } else {
                var showedResults = this.currentPage * this.invoicesPerPage;
            }
            $('#searchResults').text(
                this.showedResultsMsg.replace('%d', showedResults).replace('%l', length)
            );
        }
    }
    
    
}

invoicesPaginator.prototype.showMore = function(isRegular, isSearch) {
    this.currentPage++;
    if (isSearch) {
        this.render();
    } else {
        var paginator = this;
        var url = isRegular ? '/regular/' : '/invoices/';
        $.ajax({
            url: url + 'page',
            data: {
                page: this.currentPage
            },
            type: 'POST',
            timeout: 15000,
            async: false,
            success: function(data) {
                if ( (data == '') ) {
                    setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                } else {
                    var insertAfter = $('#invoices_tbl > tbody > tr.invisible');
                    if (insertAfter.length) {
                        insertAfter.after(data);
                    } else {
                        $('#invoices_tbl > tbody > tr.action').filter(':first').after(data);
                    }
                    renderInvoiceItemTdText();
                    setInvoiceItemTdSize();
                    var sortRow = window.sorter.sortedBy.rowId;
                    var sortBy = window.sorter.sortedBy.sortBy;
                    window.sorter = new invoicesSorter('invoices_tbl');
                    window.sorter.sortBy(sortRow, sortBy);
                    paginator.reInit();
                    $('#invoices_tbl > tbody > tr[changed=true]').each(function() {
                        setHoverForInvoiceRow(this, '#F1F6FF', 'white');
                        $(this).removeAttr('changed');
                        if ($('td[stop_date]', this).text() != '') {
                            $('#invoice_stopped_row').show();
                        }
                    });
                    adjustFooter();
                    if (paginator.pages == paginator.currentPage) {
                        $('#show_more_invoices').hide();
                        var paginatorTop = $('#paginator_top');
                        if (paginatorTop) {
                            paginatorTop.hide();
                            $('#invoices_paginator').css('top', '0');
                        }
                    }
                }
            },
            error: function() {
                setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
            }
        });
    }
}

function submitSearchForm() {
    
    var searchString = $('#searchString').val();
    if (searchString != '') {
        window.location.href = '/invoices/?search=' + searchString;
    }
    return false;
}

function displayEmailForm(btn, action, e, marginTop, marginLeft) {
    
    if (marginTop){}
    else {
        marginTop = 0;
    }
    
    if (marginLeft){}
    else {
        marginLeft = 0;
    }
    
    var actionEle = document.getElementById('email_form_action');
    if (actionEle) actionEle.value = action;
    
    displayPopupForm(btn, action, hideEmailForm, e, marginTop, marginLeft);
}

function displayPopupForm(btn, type, hideFunc, e, marginTop, marginLeft, callback) {
    if (e) cancelEvent(e);
    
    var callBackFunc = callback || false;
    
    var formEle = document.getElementById(type + '_form_');
    if (!formEle) {
        formEle = document.getElementById(type);
    }
    if (formEle) {
        $(formEle).fadeIn('fast');
        var bodyWidth = parseInt(document.getElementsByTagName('body')[0].offsetWidth);
        var formWidth = parseInt(formEle.offsetWidth);
        
        /*var corner = document.getElementById(type + '_form');*/
        var pointer = document.getElementById(type + '_pointer');

        var linkPos = new elementPosition(btn);
        var formPos = new elementPosition(formEle);
        var pointerPos = new elementPosition(pointer);
                
        var x = linkPos.x - pointerPos.x;
        var y = linkPos.y - pointerPos.y;
        if ($.browser.opera == false) {
            x -= 1;
            y -= 1;
        }
        
        formEle.style.left = formPos.x + x + marginLeft + 'px';
        formEle.style.top = formPos.y + y + marginTop + 'px';
        
        if (e) {
            addEvent(formEle, 'click', cancelEvent);
            addEvent(document, 'click', hideFunc);
        }
        
        $(document).keyup(function(e) {
            if (e.which == 27) {
                hideFunc();
            }
        });
        
        /*$('input', formEle).keypress(function(e) {
            if (e.which == 13) {
                return false;
            }
        });*/
        
        if (callback) {
            callback();
        }
    }
}

function hoverIE6(expression, hoverClass) {
    $(expression).hover(function() {
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    });
}


(function($) {
/*
Jquery Color Fade Plugin
------------------------
REQUIREMENTS:
- Jquery 1.3.2 or higher
- Jquery UI 1.7.2 or higher
Creates a color fade technique made popular by 37signals' Yellow Fade Technique
USAGE:
color_fade({from:"yellow",to"white",speed:500})
- from : color that element will fade from
- to : color that element will fade to
- speed : the speed of the animation
*/
    
    $.fn.color_fade = function(opts, callback) {
        callback = false || callback;
        opts = $.extend({from:"yellow",to:"white",speed:500}, opts || {});
      
            $(this).css('background-color', opts['from']);
      
            if (callback) {
                $(this).animate(
                        { backgroundColor:opts['from'] },
                        { duration: opts['speed'],
                            complete: function(){
                            $(this).animate(
                                    { backgroundColor: opts['to'] },
                                    { duration: opts['speed'],
                                        complete: function() {
                                            callback();
                                        }
                                    }
                            ); 
                        }
                        }
                );
            } else {
                $(this).animate(
                        { backgroundColor:opts['from'] },
                        { duration: opts['speed'],
                            complete: function(){
                            $(this).animate({backgroundColor: opts['to']}, opts['speed'])
                        } });
            }
        
    }
})(jQuery);

function setInvoiceItemTdSize(rowId) {
    var table = $('table.data > tbody');
    $('tr > td > div.div1', table).css('display', 'none');
    var width = $('#invoice_name_row').width();
    $('tr > td > div.div1', table).css('width', width + 'px');
    $('tr > td > div.div1', table).css('display', 'block');
    
    var divs = $('tr > td.company > div', table);
    divs.css('display', 'none');
    width = $('#invoice_companies_row').width();
    divs.css('width', width + 'px');
    $('div.company', divs).css('width', (width - 90) + 'px');
    divs.show();
    
}

function setInvoiceCompanyTdSize(rowId) {
    $('table.data > tbody > tr > td > div[company]').css('display', 'none');
    var width = $('#' + rowId).width();
    $('table.data > tbody > tr > td > div[company]').css('width', width + 'px');
    $('table.data > tbody > tr > td > div[company]').css('display', 'block');
}

function renderInvoiceItemTdText() {
    $('table.data > tbody > tr > td > div.div1').each(function() {
        $(this).css('display', 'block');
        if ($(this).text() == '') {
            $(this).text(' ');
        }
    });
    $('table.data > tbody > tr > td > div[company]').each(function() {
        $(this).css('display', 'block');
        if ($(this).text() == '') {
            $(this).text(' ');
        }
    });
}

function getDayCounter(elem, lang) {
    var value = $(elem).val();
    value = parseInt(parseNumber(value));
    if (!value) {
        $(elem).addClass('error');
        $('#overdue_error').show();
    } else {
        $(elem).removeClass('error');
        $(elem).val(value);
        $('#overdue_error').hide();
    }
    value = new String(value);
    
    value += ''; 
    if (value == '') {
        return '';
    }
    value = new String(value);
    
    if (lang == 'ru') {
        var result = 'день';
        var lastDigit = parseInt(value.substring(value.length - 1));
        value = parseInt(value);
        if ( (value >= 11) && (value <= 14) ) {
            result = 'дней';
        } else if ( (lastDigit > 1) && (lastDigit < 5) ) {
            result = 'дня';
        } else if ( (lastDigit == 0) || ( (lastDigit > 4) && (lastDigit <= 9) ) ) {
            result = 'дней';
        }
    } else if (lang == 'en') {
        if (value == '1') {
            var result = 'day';
        } else {
            var result = 'days';
        }
    } else if (lang == 'de') {
        if (value == '1') {
            var result = 'tag';
        } else {
            var result = 'tage';
        }
    }
        
    return result;
}

function emailInvoiceRequest(emailElem, emailForm) {
    
    showLoadingBar();
    $('#email_form_').hide();
    var post = {email: emailElem.val()};
    $.ajax({
        url: '/ajax/email-invoice-request',
        data: post,
        type: 'POST',
        timeout: 15000,
        success: function(data) {},
        error: function() {}
    });
    $('#send_email_btn').hide();
    $('#email_sended').fadeIn('slow');
}

function printInvoiceRequest() {
    $.ajax({
        url: '/ajax/print-invoice-request',
        type: 'POST',
        timeout: 15000,
        async: false,
        success: function(data) {
            window.location.href = data.pathToPdf;
        },
        error: function() {
            alert(SERVER_ERROR_MESSAGE);
        },
        dataType: 'json'
    });
}

function Blocker(id) {
    this.isset = true;
    this.descriptor = $('#' + id);
    var blocker = this;
    $(window).resize(function() {
        blocker.resize();
    });
}

Blocker.prototype.resize = function() {
    this.descriptor.height($(window).height());
}

Blocker.prototype.show = function() {
    this.resize();
    this.descriptor.show();
}

Blocker.prototype.hide = function() {
    this.descriptor.hide();
}

function setHoverForInvoiceRow(tr, color1, color2) {
    $(tr).hover(
        function() {
            $(this).css('background-color', color1);
            $('.fadeout1,.fadeout2,.fadeout3', $(this)).css('background-color', color1);
        },
        function() {
            $(this).css('background-color', color2);
            $('.fadeout1,.fadeout2,.fadeout3', $(this)).css('background-color', color2);
        }
    );
}

function highlightInvoices(invoices) {
    if ( (typeof invoices != 'object') || !invoices.length ) {
        /* если не заданы IDшники, ты выборка идет по tr с changed=true */
        var invoices = $('#invoices_tbl > tbody > tr[changed=true], #invoices_tbl > tbody > tr[changed=true] div[fadeout]');
        var query = '$(\'#invoices_tbl > tbody > tr[changed=true], #invoices_tbl > tbody > tr[changed=true] div[fadeout]\').animate({backgroundColor: \'white\'}, \'slow\')';
        invoices.css('background-color', '#fec864');
        setTimeout(
            function() {
                invoices.animate(
                    {
                        backgroundColor: 'white'
                    },
                    'slow'
                );
            },
            2000
        );
        invoices.removeAttr('changed');
    } else {
    
        var query = '$(\'';
        for (var i = 0; i < invoices.length; i++) {
            var invoice = $('tr[invoice_id=' + invoices[i] + ']');
            
            invoice.css('background-color', '#fec864');
            $('div[fadeout]', invoice).css('background-color', '#fec864');
            invoice.trId = 'tr[invoice_id=' + invoices[i] + ']';
            query += invoice.trId + ',' + invoice.trId + ' div[fadeout],';
        }
        
        query += 'tr[invoice_id=unused]\').animate({backgroundColor: \'white\'}, \'slow\')';
        setTimeout(query, 2000);
    }
}

function daysBetween(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms);
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY);

}

function displayLoginForm(btn, event) {
    try{zoomOut();}catch (e){;}
    hideRemindForm();
    displayPopupForm(
        btn,
        'auth',
        hideAuthForm,
        event,
        0,
        0,
        function() { 
            $('#auth_login').focus();
        }
    );
    return false;
}

function adjustFooter(marginBottom) {
    var margin = marginBottom || 34;
    
    var footer = $('#footer');
    if (footer) {
        footer.hide();
        var windowHeight = $(window).height();
        var documentHeight = $(document).height();
        
        if (documentHeight > windowHeight) {
            footer.css('position', 'relative')
                .css('top', '0px');
        } else {
            footer.css('top', (windowHeight - margin) + 'px')
                .css('position', 'absolute');
        }
        
        footer.show();
    }
}

function adjustFooterOnSearchPage() {
    var footer = $('#footer');
    var windowHeight = $(window).height();
    var documentHeight = $(document).height();
    if (documentHeight > windowHeight) {
        var height = $('#search_bottom').offset().top + $('#search_bottom').height();
    } else {
        var height = windowHeight;
    }
    footer.css('top', height + 'px')
        .css('position', 'absolute');
    footer.show();
}

function adjustAmount() {
    var sumTdPos = $('table.invoice > thead > tr > td.sum').offset();
    var offset = Math.ceil($(document).width() - sumTdPos.left - 94);
    if ($.browser.msie && $.browser.version.substring(0, 1) == '6') {
        offset -= 20;
    }
    $('#amount').css('padding-right', offset + 'px');
}

function trim(value) {
    return value.replace(/^[ ]+/, '').replace(/[ ]+$/, '');
}

function trimEmail(value) {
    return value.replace(/^[ ]+/, '').replace(/[ ]+$/, '').replace('<', '').replace('>', '');
}

function checkRegistrationForm(useYandexMetrika) {
    
    var yandexMetrika = useYandexMetrika || false;
    
    var form = document.forms.registrationForm;
    var noErrors = true;
    
    var email = $(form.email);
    email.val(trim(email.val()));
    email.removeClass('error');
    
    if (email.val() == '') {
        email.addClass('error');
        $('#email_error').text(EMPTY_EMAIL_ERROR_MESSAGE);
    } else if (!validateEmail(email.val())) {
        $('#email_error').text(INVALID_EMAIL_ERROR_MESSAGE);
        email.addClass('error');
        noErrors = false;
    } else {
        
        waitCursor(true);
        $.ajax({
            url: '/ajax/check-email-existance',
            async: false,
            data: {
                email: email.val()
            },
            error: function() {
                alert(SERVER_ERROR_MESSAGE);
            },
            success: function(data, textStatus) {
                try {
                    var json = eval('(' + data + ')');
                    if (json.status == 'OK') {
                        $('#email_error').text('');
                    } else if (json.status == 'EMAIL_EXISTS') {
                        $('#email_error').text(EMAIL_EXISTS_EROR_MESSAGE);
                        email.addClass('error');
                        noErrors = false;
                    } else if (json.status == 'INVALID_EMAIL') {
                        $('#email_error').text(INVALID_EMAIL_ERROR_MESSAGE);
                        email.addClass('error');
                        noErrors = false;
                    }
                } catch (e) {
                    alert(SERVER_ERROR_MESSAGE);
                }
            }
        });
        waitCursor(false);
        
    }
    
    var password = $(form.password);
    password.removeClass('error');
    
    if (password.val() == '') {
        $('#password_error').text(EMPTY_PASSWORD_ERROR_MESSAGE);
        password.addClass('error');
        noErrors = false;
    } else {
        password.removeClass('error');
        $('#password_error').text('');
    }
    
    if (noErrors && yandexMetrika) {
        try {
            window.yaCounter147630.reachGoal('Регистрация нового пользователя');
        } catch (e) {}
    }
    
    return noErrors;
}

function checkSaveWithPasswordForm(useYandexMetrika
    , emailErrorMsg
    , passwordErrorMsg
    , userErrorMsg
) {
    var yandexMetrika = useYandexMetrika || false;
    var yandexMetrikaError = false;
    
    var form = document.forms.saveWithPassordForm;
    var noError = true;
    
    var errorDiv = $('#auth_form_input');
    errorDiv.removeClass('error');
    
    var email = $(form.email);
    email.removeClass('error');
    email.val(trim(email.val()));
    
    var password = $(form.password);
    password.removeClass('error');
    
    if (email.val() == '') {
        errorDiv.addClass('error');
        email.addClass('error');
        password.addClass('error');
        $('#error_message').text(emailErrorMsg);
        email.focus();
        return false;
    } else if (!validateEmail(email.val())) {
        errorDiv.addClass('error');
        email.addClass('error');
        password.addClass('error');
        $('#error_message').text(emailErrorMsg);
        email.focus();
        return false;
    }
    
    waitCursor(true);
    $.ajax({
        url: '/ajax/check-email-existance',
        async: false,
        data: {
            email: email.val()
        },
        error: function() {
            alert(SERVER_ERROR_MESSAGE);
            yandexMetrikaError = true;
        },
        success: function(data, textStatus) {
            try {
                var json = eval('(' + data + ')');
                if (json.status == 'OK') {
                    $('#error_message').text('');
                } else if (json.status == 'EMAIL_EXISTS') {
                    $('#error_message').text(userErrorMsg);
                    errorDiv.addClass('error');
                    email.addClass('error');
                    password.addClass('error');
                    email.focus();
                    noError = false;
                } else if (json.status == 'INVALID_EMAIL') {
                    $('#error_message').text(emailErrorMsg);
                    errorDiv.addClass('error');
                    email.addClass('error');
                    password.addClass('error');
                    email.focus();
                    noError = false;
                }
            } catch (e) {
                alert(SERVER_ERROR_MESSAGE);
                yandexMetrikaError = true;
            }
        }
    });
    waitCursor(false);
    if (!noError) {
        return false;
    }
    
    if (password.val() == '') {
        $('#error_message').text(passwordErrorMsg);
        errorDiv.addClass('error');
        email.addClass('error');
        password.addClass('error');
        password.focus();
        return false;
    }
    
    $('#error_message').text('');
    
    if (yandexMetrika && !yandexMetrikaError) {
        try {
            window.yaCounter147630.reachGoal('Сохранение счета с паролем');
        } catch (e) {}
    }
    
    return true;
}

function deleteSelectedInvoices(
    isRegular
    , message
    , confirmationMessageOne
    , confirmationMessageTwo
) {
    
    var regularFlag = isRegular || false;
    if (regularFlag) {
        var url = '/regular/delete';
    } else {
        var url = '/invoices/delete';
    }
    
    var invoices = $('table.data > tbody > tr > td > input:checked');
    if (invoices.length == 0) {
        return;
    } else {
        var infoTr = new getParentElement(invoices[0], 'tr');
        var invoiceNumber = $('td.invoice_number_row', infoTr).text();
        var companyType = $('td.company > div[company] > div.company_type', infoTr).text();
        if (companyType.length != 1) {
            companyType += ' ';
        }
        var company = $('td.company > div[company] > div.company', infoTr).text();
        
        var query = '';
        for (var i = 0; i < invoices.length; i++) {
            query += 'id[]=' + encodeURIComponent(invoices[i].value) + '&';
        }
        
        if (invoices.length == 1) {
            info = confirmationMessageOne.replace('%d', invoiceNumber)
                .replace('%o', companyType)
                .replace('%c', company);
        } else {
            info = confirmationMessageTwo.replace('%n', invoices.length)
                .replace('%s', getInvoiceForHuman(invoices.length, LANG))
                .replace('%d', invoiceNumber)
                .replace('%o', companyType)
                .replace('%c', company);
        }
        if (window.confirm(info)) {
            
            waitCursor(true);
            var isError = false;
            $.ajax({
                url: url,
                data: query,
                async: false,
                timeout: 30000,
                error: function() {
                setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                },
                success: function(data, textStatus) {
                    try {
                        var json = eval('(' + data + ')');
                        if (json.status == 'OK') {
                            
                            for (var i = 0; i < json.deletedIds.length; i++) {
                                $('table.data > tbody > tr:has(td > input[value=' + json.deletedIds[i] + '])').remove();
                            }
                            if ($('#invoices_tbl > tbody > tr[invoice_id]').length == 0) {
                                window.location.href = '/invoices';
                            } else {
                                window.sorter.reInit();
                                window.paginator.reInit();
                                toggleActionString();
                                setConfirmation('confirmation_', message);
                            }
                            
                        } else {
                            setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                        }
                    } catch (e) {
                        setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                    }
                }
            });
            waitCursor(false);
        }
    }
}

function getInvoiceForHuman(count, lang) {
    lang = lang || 'en';
    if (lang == 'ru') {
        var str = String(count);
        var lastDigit = str.substr(str.length - 1, 1);
        if (lastDigit == '0') {
            var result = 'счетов';
        } else if ( (count >= 11) && (count <= 14) ) {
            var result = 'счетов';
        } else if (lastDigit == '1') {
            var result = 'счет';
        } else if ( (lastDigit >= '2') && (lastDigit <= '4') ) {
            var result = 'счета';
        } else {
            var result = 'счетов';
        }
    } else if (lang == 'de') {
        if (count == 1) {
            var result = 'Rechnung';
        } else {
            var result = 'Rechnungen';
        }
    } else {
        if (count == 1) {
            var result = 'invoice';
        } else {
            var result = 'invoices';
        }
    }
    return result;
}   

function setConfirmation(containerId, message) {
    $('div.action > span').hide();
    $('tr.action').hide();
    var container = $('#' + containerId);
    container.html(message);
    container.fadeIn('fast');
}

function duplicateInvoices(isRegular, message, errorMessage) {
    errporMessage = errorMessage || '';
    var regularFlag = isRegular || false;
    if (regularFlag) {
        var url = '/regular/duplicate';
    } else {
        var url = '/invoices/duplicate';
    }
    var invoices = $('table.data > tbody > tr > td > input:checked');
    if (invoices.length == 0) {
        return;
    } else {
        var query = '';
        
        for (var i = 0; i < invoices.length; i++) {
            query += 'id[]=' + encodeURIComponent(invoices[i].value) + '&';
        }
        
        waitCursor(true);
        $.ajax({
            url: url,
            data: query,
            async: false,
            timeout: 30000,
            error: function() {
                setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
            },
            success: function(data, textStatus) {
                try {
                    if ( (data == '') || (data.indexOf('invoice_id="') == -1) ) {
                        setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                    } else {
                        $('#invoices_tbl input[type=checkbox]').removeAttr('checked');
                        toggleActionString();
                        var insertAfter = $('#invoices_tbl > tbody > tr.invisible');
                        if (insertAfter.length) {
                            insertAfter.after(data);
                        } else {
                            $('#invoices_tbl > tbody > tr.action').filter(':first').after(data);
                        }
                        renderInvoiceItemTdText();
                        setInvoiceItemTdSize();
                        var sortRow = window.sorter.sortedBy.rowId;
                        var sortBy = window.sorter.sortedBy.sortBy;
                        window.sorter = new invoicesSorter('invoices_tbl');
                        window.sorter.sortBy(sortRow, sortBy);
                        var counter = 0;
                        var pos = -1;
                        while ( (pos = data.indexOf('<tr', pos + 1)) >= 0) {
                            counter++;
                        }
                        if (data.indexOf('is-able-to-create-new-invoices=false') >= 0) {
                            $('#create_new_invoice_btn_disabled').show();
                            $('#create_new_invoice_btn_enabled').hide();
                            $('#billing_notification').show();
                            $('#duplicate_btn_1').empty();
                            $('#duplicate_btn_2').empty();
                            $('#green_line').show();
                        }
                        if (counter == invoices.length) {
                            setConfirmation('confirmation_', message);
                        } else {
                            setConfirmation(
                                'confirmation_',
                                errorMessage.replace('%d', counter)
                                    .replace('%s', getInvoiceForHuman(counter, LANG))
                                    .replace('%n', invoices.length)
                            );
                        }
                        $('#invoices_tbl > tbody > tr[changed=true]').each(function() {
                            setHoverForInvoiceRow(this, '#F1F6FF', 'white');
                        });
                        highlightInvoices(false);
                    }
                } catch (e) {
                    setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                }
            }
        });
        waitCursor(false);
    }       
}

function appendInvoiceToInvoicesTable(invoice) {
    var tBody = document.getElementById('invoices_tbl').tBodies[0];
    tBody.appendChild(invoice);
}

function setInvoicesAsPayed(message, payedStatus) {
    var invoices = $('table.data > tbody > tr > td > input:checked');
    if (invoices.length == 0) {
        return;
    } else {
        var query = '';
        for (var i = 0; i < invoices.length; i++) {
            query += 'id[]=' + encodeURIComponent(invoices[i].value) + '&';
        }
        waitCursor(true);
        $.ajax({
            url: '/invoices/set-payed',
            data: query,
            async: true,
            timeout: 30000,
            error: function() {
                setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
            },
            success: function(data, textStatus) {
                try {
                    var json = eval('(' + data + ')');
                    for (var i = 0; i < json.ids.length; i++) {
                        var invoice = $('#invoices_tbl > tbody > tr[invoice_id=' + json.ids[i] + ']');
                        invoice.attr('changed', 'true').attr('id', '2');
                        $('td[class^=status]', invoice).attr('class', 'status_payed').text(payedStatus);
                        $('input:checked', invoice).removeAttr('checked');
                    }
                    toggleActionString();
                    setConfirmation('confirmation_', message);
                    window.sorter.reInit();
                    highlightInvoices(false);
                } catch (e) {
                    setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                }
            }
        });
        waitCursor(false);
    }
}

function printSelectedInvoices() {
    var invoices = $('table.data > tbody > tr > td > input:checked');
    if (invoices.length == 0) {
        return;
    } else if (invoices.length == 1) {
        window.location.href = '/download/invoice?id=' + encodeURIComponent(invoices[0].value);
    } else {
        var query = '';
        for (var i = 0; i < invoices.length; i++) {
            query += 'id[]=' + encodeURIComponent(invoices[i].value) + '&';
        }
        
        waitCursor(true);
        $.ajax({
            url: '/invoices/print',
            data: query,
            async: false,
            timeout: 30000,
            error: function() {
                setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
            },
            success: function(data, textStatus) {
                try {
                    var json = eval('(' + data + ')');
                    if (json.status == 'OK') {
                        initDownloadInvoice(json.url);
                    } else {
                        setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                    }
                } catch (e) {
                    setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                }
            }
        });
        waitCursor(false);
    }
}

/*function displayNoInvoicesMessage() {
    $('div.show_invoices, div.search_invoices, #invoices_tbl, #invoices_paginator, #paginator_top, div.action').hide();
    $('#no_invoices').show();
}*/

function sendInvoiceByEmail(email, invoiceId, mode) {
	mode = mode || 'invoices';
	var url = (mode == 'act') ? '/act/email' : '/invoices/email';
	var copyToMyself = $('#copy_to_myself').attr('checked');
    $.ajax({
        url: url,
        data: {
            email: email,
            invoiceId: invoiceId,
            notify: 'false',
            copyToMyself: copyToMyself
        },
        type: 'POST'
    });
    var form = $('#email_invoice');
    var height = form.height();
    form.hide();
    $('#send_email_form').css('background', 'transparent')
        .css('border', '0px')
        .css('height', height + 2 + 'px');
    $('#email_sent').fadeIn('fast');
}

function notifyInvoiceByEmail(email, invoiceId) {
    $.ajax({
        url: '/invoices/email',
        data: {
            email: email,
            invoiceId: invoiceId,
            notify: 'true'
        },
        type: 'POST'
    });
    var form = $('#notify_invoice');
    var height = form.height();
    form.hide();
    $('#remind_email_form').css('background', 'transparent')
        .css('border', '0px')
        .css('height', height + 2 + 'px');
    $('#email_notified').fadeIn('fast');
}

function toggleEmailOption(selectId, emailOptionId) {
    var select = $('#' + selectId);
    var emailOption = $('#' + emailOptionId);
    if (select.val() == '0') {
        emailOption.hide();
    } else {
        emailOption.show();
    }
}

function markAsPayed(isPayed, invoiceId) {
    
    var query = 'id[]=' + invoiceId;
    if (isPayed == false) {
        query += '&isPayed=false';
        var itemToHide = $('#set_not_payed');
        var itemToShow = $('#set_payed');
    } else {
        var itemToHide = $('#set_payed');
        var itemToShow = $('#set_not_payed');
    }
    
    $.ajax({
        url: '/invoices/set-payed',
        data: query,
        async: true,
        timeout: 30000,
        error: function() {
            alert(SERVER_ERROR_MESSAGE);
        },
        success: function(data, textStatus) {
            try {
                var json = eval('(' + data + ')');
                if (json.ids) {
                    itemToHide.hide();
                    itemToShow.show();
                    if (isPayed) {
                        $('#invoice_info').addClass('invoice_info_payed');
                    } else {
                        $('#invoice_info').removeClass('invoice_info_payed');
                    }
                }
            } catch (e) {
                alert(SERVER_ERROR_MESSAGE);
            }
        }
    });
}

function stopRegularInvoices(message) {
    var invoices = $('table.data > tbody > tr > td > input:checked');
    if (invoices.length == 0) {
        return;
    } else {
        var query = '';
        for (var i = 0; i < invoices.length; i++) {
            query += 'id[]=' + encodeURIComponent(invoices[i].value) + '&';
        }
        
        
        waitCursor(true);
        $.ajax({
            url: '/regular/stop',
            data: query,
            async: false,
            timeout: 30000,
            error: function() {
                setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
            },
            success: function(data, textStatus) {
                try {
                    var json = eval('(' + data + ')');
                    if (!json.ids.length) {
                        throw 'error';
                    }
                    
                    for (var i = 0; i < json.ids.length; i++) {
                        var invoice = $('#invoices_tbl > tbody > tr[invoice_id=' + json.ids[i] + ']');
                        invoice.attr('changed', 'true').attr('id', '2');
                        $('td[stop_date]', invoice).text(json.time);
                        $('td[stop_date_human]', invoice).text(json.timeHuman);
                        $('input:checked', invoice).removeAttr('checked');
                    }
                    toggleActionString();
                    setConfirmation('confirmation_', message);
                    window.sorter.reInit();
                    showStoppedColumn();
                    highlightInvoices(false);
                        
                    
                } catch (e) {
                    setConfirmation('confirmation_error_', SERVER_ERROR_MESSAGE);
                }
            }
        });
        waitCursor(false);
    }
}

function addAutocompleteToInvoiceDescription(elemId) {
    elemId = elemId || false;
    if (!elemId) {
        var elems = $('#invoice_foreign > tbody > tr > td[class^=description_] > input');
    } else {
        var elems = $('#' + elemId);
    }
    
    elems.autocomplete('/invoices/autocomplete-description', {
        cacheLength: 100,
        max: 7,
        highlight: false
    });
}

function addAutocompleteToInvoiceItem(elemId) {
    
    elemId = elemId || false;
    if (!elemId) {
        var elems = $('#invoice_foreign > tbody > tr > td[class^=item_] > input');
    } else {
        var elems = $('#' + elemId);
    }
    
    elems.autocomplete('/invoices/autocomplete-item', {
        cacheLength: 100,
        max: 7,
        highlight: false
    });
}

function chooseTariff(id) {
    $('#tariff_id').val(id);
    $('#tariff_form').submit();
}

function removeHoverFromInvoice(id) {
    $(window.invoice).hover(function() {}, function() {});
}

function makeHoverForInvoice(id) {
    $(window.invoice).hover(function() {
            $(this).css('background', '#F1F6FF');
        },
        function() {
            $(this).css('background', 'white');
        }
    );
}

function showStoppedColumn() {
    var table = $('#invoices_tbl');
    $('td.is_active > a, td.is_active > span', table).show();
}

function togglePrintInvoiceCheckbox(elem) {
    if ($(elem).attr('checked')) {
        $('#print_invoice').hide();
    } else {
        $('#print_invoice').show();
    }
}

function togglePaymentPeriod(id) {
    if (id == 1) {
        var toShow = $('#pay_period');
        var toHide = $('#amount');
    } else {
        var toShow = $('#amount');
        var toHide = $('#pay_period');
    }
    toShow.removeAttr('disabled');
    toHide.attr('disabled', true);
}

function checkPaymentForm() {
    
    var result = true;
    
    if ($('#period_radio_2').attr('checked') == true) {
        var value = $('#amount').val();
        var amount = parseFloat(parseNumber(value).replace(',', '.'));
        if (!checkNumber(value) || (amount < 0.01)) {
            $('#amount').addClass('error');
            result = false
        } else {
            
            $('#amount').removeClass('error');
        }
    }
    return result;
}

function highlightItemLink(id, highlight) {
    if (highlight) {
        $('#' + id).addClass('underline');
    } else {
        $('#' + id).removeClass('underline');
    }
}

function refreshInvoiceAmount(lang) {
    $('tr.last_item > td input:first').attr('id', 'refresh');
    recountInvoiceValues(document.getElementById('refresh'), false, lang);
}
         
function toggleSignatureInput(selector, id, inputId) {
    var text = selector.options[selector.selectedIndex].innerHTML;
    if (selector.selectedIndex == (selector.options.length - 1)) {
        $('#' + id).hide();
        $('#' + inputId).hide();
    } else {
        $('#' + id).show();
        $('#' + inputId).show();
    }
}

function toggleAccountantSignature(checkbox) {
    if ($(checkbox).attr('checked')) {
        $('#acc_type').hide();
        $('#accountant_signature_input').hide();
        $('#ceo_is_accountant').css('margin-left', '3px');
        $('#stamp_line').css('margin-top', '29px');
    } else {
        $('#acc_type').show();
        $('#accountant_signature_input').show();
        $('#ceo_is_accountant').css('margin-left', '0');
        $('#stamp_line').css('margin-top', '9px');
    }
}

function showAccFile() {
    $('#change_acc_link').hide();
    $('#change_acc_name').show();
    $('#acc_file').show();
    $('#acc_file_description').show();
}

function showCeoFile() {
    $('#change_ceo_link').hide();
    $('#change_ceo_name').show();
    $('#ceo_file').show();
    $('#ceo_file_description').show();
}

function showStampFile() {
    $('#change_stamp_link').hide();
    $('#change_stamp_name').show();
    $('#stamp_file').show();
    $('#stamp_file_description').show();
}

function NdsPopupForm(id, isNds, isNdsAbove, switcherElemId, radio, savedElemId) {
    this.isNds = isNds;
    this.isNdsAbove = isNdsAbove;
    this.instance = $('#' + id);
    
    this.switcher = $('#' + switcherElemId);
    if (this.isNds) {
        this.switcher.attr('checked', 'true');
    }
    this.radio1 = $('#' + radio + '_1');
    this.radio2 = $('#' + radio + '_2');
    
    if (this.isNdsAbove == 1) {
        this.radio2.removeAttr('checked');
        this.radio1.attr('checked', 'true');
    } else {
        this.radio1.removeAttr('checked');
        this.radio2.attr('checked', 'true');
    }
    
    this.savedElem = $('#' + savedElemId);
    
    this.dependentElems = Array('is_nds_dep_1', 'is_nds_dep_2');
    switchDependenciesNew(this.switcher, this.dependentElems);
}

NdsPopupForm.prototype.show = function(btn, event) {
    displayPopupForm(
        btn,
        'nds_popup',
        function() {window.ndsPopup.cancel();},
        event,
        11,
        0
    );
    return false;
}

function switchDependenciesNew(switcher, arrayOfDependentElems) {
    
    for (var i in arrayOfDependentElems) {
        if (switcher.attr('checked')) {
            $('#' + arrayOfDependentElems[i]).show();
        } else {
            $('#' + arrayOfDependentElems[i]).hide();
        }
    }       
}

NdsPopupForm.prototype.saveNdsSettings = function() {
    this.savedElem.val('1');
    if (this.switcher.attr('checked')) {
        this.isNds = 1;
    } else {
        this.isNds = 0;
    }
    if (this.radio1.attr('checked')) {
        this.isNdsAbove = 1;
    } else {
        this.isNdsAbove = 2;
    }
    this.instance.fadeOut('fast');
    
    // recount invoice total amount
    countInvoiceAmount(
        document.getElementById('invoice_foreign').getElementsByTagName('input')[3]
    );
    
    return false;
}

NdsPopupForm.prototype.cancel = function() {
    this.instance.fadeOut('fast');
    if (this.isNds) {
        this.switcher.attr('checked', true);
    } else {
        this.switcher.removeAttr('checked');
    }
    switchDependenciesNew(this.switcher, this.dependentElems);
    if (this.isNdsAbove == 1) {
        this.radio2.removeAttr('checked');
        this.radio1.attr('checked', 'true');
    } else {
        this.radio1.removeAttr('checked');
        this.radio2.attr('checked', 'true');
    }
}

function formatInvoiceItemElem(item, isEdited) {
    isEdited = isEdited || false;
    if (item.value != '') {
        var val = parseNumber(item.value);
        if (!isEdited) {
            val = val.replace(',', '.');
        }
        item.value = val;
    }
}

function preventMultipleFormSubmit(submitBtn) {
    /*$(submitBtn).attr('disabled', 'true');*/
}

function changeInvoiceType(selector, location) {
    switch ($(selector).val()) {
        case '1':
            var type = 'ru';
            break;
        case '2':
            var type = 'us';
            break;
        case '3':
            var type = 'de';
            break;
            
        default:
            alert(SERVER_ERROR_MESSAGE);
            return false;
    }
    
    window.location.href = '/' + location + '/' + type;
}

function toggleDeleteInvoiceRowButton(rows, tableId) {
    var btn = $('#delete_invoice_row');
    btn.mouseover(function() {
        btn.show();
    }).mouseout(function() {
        btn.hide();
    });
    rows.mouseover(function() {
        if ($('#' + tableId + ' > tbody > tr').not('tr:last').length != 1) {
            var offset = $(this).offset();
            btn.css('top', offset.top);
            btn.show();
            var row = this;
            $('a', btn).unbind('click');
            $('a', btn).click(function() {
                removeInvoiceItem(row, 2);
                btn.hide();
            });
        }
    }).mouseout(function() {
        btn.hide();
    });
}

function CurrencyPopupForm() {
    this.handler = $('#currency_popup_form_');
    this.pointerSymbol = $('#currency_pointer_symbol');
    this.headerSymbol = $('#currency_popup_symbol');
    this.selector = $('#currency_selector');
    this.oldCurrency = this.selector.val();
}

CurrencyPopupForm.prototype.show = function(btn, event) {
    displayPopupForm(
        btn,
        'currency_popup',
        function() {window.currencyPopup.cancel();},
        event,
        -10,
        -235
    );
    return false;
}

CurrencyPopupForm.prototype.close = function() {
    this.handler.fadeOut('fast');
    return false;
}

CurrencyPopupForm.prototype.save = function() {
    var text = $('option:selected', this.selector).text();
    var reg = /(\()([^\)]+)(\))/;
    text = reg.exec(text)[2];
    if (text == 'руб.') {
        
        $('#currency_symbol_right span, #currency_symbol_right_1 span').text('руб.');
        $('#currency_symbol_right, #currency_symbol_right_1').show();
        $('#currency_symbol_left, #currency_symbol_left_1').hide();
    } else {
        $('#currency_symbol_right, #currency_symbol_right_1').hide();
        $('#currency_symbol_left span, #currency_symbol_left_1 span').text(text);
        $('#currency_symbol_left, #currency_symbol_left_1').show();
    }
    this.oldCurrency = this.selector.val();
    return this.close();
}

CurrencyPopupForm.prototype.cancel = function() {
    this.selector.val(this.oldCurrency);
    return this.close();
}

function showInvoiceDescription(btn, textareaId) {
    $(btn).unbind('click')
        .css('color', 'black')
        .css('text-decoration', 'none')
        .removeAttr('href');
    $('#' + textareaId).show();
    $('#description_helper').show();
}

function UsVatPopupForm(id, valueElemId) {
    this.id = id;
    this.instance = $('#' + id);
    this.valueElem = $('#' + valueElemId);
    this.initialValue = this.valueElem.val();
}

UsVatPopupForm.prototype.show = function(btn, event) {
    var popup = this;
    displayPopupForm(
        btn
        , this.id
        , function() {}
        , event
        , -4
        , 1
    );
    return false;
}

UsVatPopupForm.prototype.cancel = function() {
    this.valueElem.val(this.initialValue);
    this.close();
}

UsVatPopupForm.prototype.save = function() {
    var value = parseNumber(this.valueElem.val());
    if (value < 0) {
        value = -value;
    }
    this.initialValue = value;
    this.valueElem.val(value);
    this.close();
    return false;
}

UsVatPopupForm.prototype.close = function() {
    this.updateInvoiceAmount();
    this.instance.fadeOut('fast');
}

UsVatPopupForm.prototype.updateInvoiceAmount = function() {
    if (!this.initialValue || (this.initialValue <= 0)) {
        $('#wrap_total').show();
        $('#wrap_subtotal').hide();
        $('#wrap_full_total').hide();
        $('#is_nds').val(0);
        $('#is_nds').removeAttr('checked');
        $('#is_nds_above_1').removeAttr('checked');
    } else {
        $('#is_nds').val(1).attr('checked', true);
        $('#is_nds_above_1').attr('checked', true);
        $('#tax_value').val(this.initialValue);
        $('#wrap_total').hide();
        $('#wrap_subtotal').show();
        $('#wrap_full_total').show();
    }
    refreshInvoiceAmount('en');
}

function switchRuCompany(elem, kpp_label, type1, type2) {
    if ($('option[selected]', elem).text() == 'ИП') {
        $(kpp_label).text(type2);
    } else {
        $(kpp_label).text(type1);
    }
}

function initRequisites(switcherElem, availableIds) {
    if (window.location.href.search(/#[a-z]{2}$/) != -1) {
        var type = window.location.href.substr(
            window.location.href.lastIndexOf('#') + 1
        );
        for (var id in availableIds) {
            if (type == availableIds[id]) {
                for (var i = 0; i < switcherElem.length; i++) {
                    if (switcherElem[i].value == id.substr(4)) {
                        switcherElem.selectedIndex = i;
                        break;
                    }
                } 
                break;
            }
        }
    }
    switchRequisites(switcherElem, availableIds);
}

function switchRequisites(switcherElem, availableIds) {
    var requisitesId = 'req_' + $(switcherElem).val();
    for (var id in availableIds) {
        if (requisitesId != id) {
            $('#' + id).hide();
        }
    }
    $('#' + requisitesId).show();
    $('#country_label').val(availableIds[requisitesId]);
    if (window.location.href.search(/#[a-z]{2}$/) != -1) {
        window.location.href = window.location.href.replace(
            /#[a-z]{2}$/
            , '#' + availableIds[requisitesId]
        );
    } else {
        window.location.href += '#' + availableIds[requisitesId];
    }
}

function checkRequisites(reqTypes, switcherElem) {
    return true;
}

function createAct() {
	var invoices = $('table.data > tbody > tr > td > input:checked');
    if (invoices.length == 0) return;
    	
    var query = '';
    for (var i = 0; i < invoices.length; i++) {
        query += 'id[]=' + encodeURIComponent(invoices[i].value) + '&';
    }
    window.location.href = '/act/create/?' + query;
}

function switchItem(item1Id, item2Id) {
	$('#' + item1Id).hide();
	$('#' + item2Id).show();
}

function saveActDescription(btn, formId, descriptionTextId) {
	btn = $(btn);
	btn.attr('disabled', 'true');
	var form = document.getElementById(formId);
	$.ajax({
		url: form.action,
        data: $(form).serialize(),
        type: 'POST',
        timeout: 15000,
        async: false,
        success: function(data) {
			btn.removeAttr('disabled');
			if (data == 'OK') {
				$('#' + descriptionTextId + ' > span').text(form.description.value);
			}
			switchItem(formId, descriptionTextId);
		},
		error: function(data) {
			alert(SERVER_CONNECTION_ERROR);
			btn.removeAttr('disabled');
			switchItem(formId, descriotionTextId);
		}
	});
	return false;
}

