﻿var browser = false;
var todayCurs;
var globalStandard;
var globalSchemeLicence;
var globalStageShop;
var globalProductArray = new Array();
var globalSpecaTable;
var globalLicenceLevel;
var gloablListDiscsDiv;

// Стартовый метод. Тащит курс валюты, также выделяет закладку стандартных продуктов при 1ой загрузки.
function StartUp() {

    globalSchemeLicence = document.getElementById('SchemeLicence').value;    
    globalStageShop = document.getElementById('StageShop').value;

    if (globalStageShop == 'SelectProduct') {
        if (globalSchemeLicence != 'AcademicCSA') {
            globalStandard = document.getElementById('standardHidden').value;
            StandardBookmarkHover(bookmarkStandard, bookmarkExtensive);
        }
        // Дизаблим кнопку далее.
        button = document.getElementById('Next');
        button.disabled = true;
    }
    if (globalSchemeLicence == "Goverment") {
        globalLicenceLevel = document.getElementById('GovermentLevel').value;
    }
    gloablListDiscsDiv = document.getElementById('ListDiscs');
    globalSpecaTable = document.getElementById('SpecaTable');

    browser = IsFireFoxBrowser();
    
    //Курс валюты.
    var hiddenCurs = document.getElementById('curs');
    todayCurs = parseFloat(hiddenCurs.value.replace(',','.'));
}

// Изменение картинки + на -, при открытии списка
function HoverImage(id) {

    var name = 'plus' + id;
    var obj = document.getElementById(name);
    var display = document.getElementById(id);

    if (display.style.display == 'none' || display.style.display == '') {
        if (obj.src.substring(obj.src.length - 9, obj.src.lenght) != 'minus.gif') {
            obj.src = obj.src.substring(0, obj.src.length - 9) + "plus2.gif";
        }
    }
}

// Изменение картинки - на +, при скрытии списка
function UnhoverImage(id) {

    var name = 'plus' + id;
    var obj = document.getElementById(name);
    var display = document.getElementById(id);

    if (display.style.display == 'none' || display.style.display == '') {
        if (obj.src.substring(obj.src.length - 9, obj.src.lenght) != 'minus.gif') {
            obj.src = obj.src.substring(0, obj.src.length - 9) + "plus1.gif";
        }
    }
}

// Скрытие и открытие списка при клике на группу.
function GetProductsByGroupId(groupId) {

    var tableID = 'groupID' + groupId;
    var table = document.getElementById(tableID);
    var imageID = 'plusgroupID' + groupId;
    var objImage = document.getElementById(imageID);

    if (table.style.display == 'none' || table.style.display == '') {
        table.style.display = 'block';
        objImage.src = objImage.src.substring(0, objImage.src.length - 9) + "minus.gif";

        if (table.rows.length == 0) {
            GetGroupBox(groupId);
        }
	}
	else
	{
	    table.style.display = 'none';
		objImage.src = objImage.src.substring(0, objImage.src.length-9) + "plus1.gif";
	}
}

// Получаем список боксов выбранной группы.
function GetGroupBox(id) {
    
    request = GetRequest();
    switch (globalSchemeLicence) {
        case 'Box':
            {
                var url = "/Api/GetBoxesByGroup.aspx?Group=" + id + "&Standard=" + globalStandard;
            } break;
        case 'OVS':
            {
                var url = "/Api/GetOVSesByGroup.aspx?Group=" + id + "&Standard=" + globalStandard;
            } break;
        case 'OVL':
            {
                var url = "/Api/GetOVLesByGroup.aspx?Group=" + id + "&Standard=" + globalStandard;
            } break;
        case 'AcademicCSA':
            {
                var url = "/Api/GetACSAesByGroup.aspx?Group=" + id + "&Standard=0";
            } break;
        case 'AcademicOLP':
            {
                var url = "/Api/GetAOLPesByGroup.aspx?Group=" + id + "&Standard=" + globalStandard;
            } break;
        case 'Goverment':
            {
                var url = "/Api/GetGovermentesByGroup.aspx?Group=" + id + "&Standard=" + globalStandard + "&Level=" + globalLicenceLevel;
            } break;
        case 'OLP':
            {
                var url = "/Api/GetOLPesByGroup.aspx?Group=" + id + "&Standard=" + globalStandard;
            } break;
    }

    if (globalSchemeLicence == 'Goverment') {
        var params = 'Group=' + id + '&Standard=' + globalStandard + '&Level=' + globalLicenceLevel;
    }
    else {
        var params = 'Group=' + id + '&Standard=' + globalStandard;
    }
    request.open('POST', url, false);
    if (browser) {
        request.send(params);
        request.onreadystatechange = processBoxGroup();
    }
    else {
        // Setup a function for the server to run when it's done
        request.onreadystatechange = processBoxGroup;
        // Send the request
        request.send(null);
    } 
}

// Парсим список боксов выбранной группы.
function processBoxGroup() {

    var arrayBox = new Array();
    var Boxes = new Array();
    var array = new Array();
    var exit = false;
    if (request.readyState != 4) {
        return;
    }
    else {
        var str = request.responseText;
        arrayBox = str.split("<br>");
        for (i = 0; i < arrayBox.length - 1; i++) {
            array = arrayBox[i].split(";");
            array[4] = array[4].replace(",", ".");
            var box = new Object();
            var check = 0;
            for (j = 0; j < array.length; j++) {
                if (array[j] == null)
                    check++;
            }
            if (check == 0) {              
                box.ID = array[0];
                box.PartNumber = array[1];
                // box.Language = array[2];
                box.PartDesc = array[3];
                box.StartPrice = parseFloat(array[4]);
                box.GroupId = array[5];
                if (globalSchemeLicence != 'Box') {
                    if (array[7] != '1') {
                        array[7] = array[7].replace(",", ".");
                        box.PromoPrice = parseFloat(array[7]);
                    }
                    else {
                        box.PromoPrice = parseFloat(array[7]);
                    }
                }
                if (globalSchemeLicence == 'AcademicCSA') {
                    box.User = array[8];
                }
                /*
                else if (globalSchemeLicence == 'AcademicOLP' || globalSchemeLicence == 'Goverment') {
                    box.SA = array[9];
                }*/
                Boxes.push(box);
                exit = true;
            }
        }
    }
    if (exit == true) {
        WriteBoxGroup(Boxes, globalSchemeLicence);
    }
}


// Выпадающий список продуктов группы.
function WriteBoxGroup(boxes) {

    var table = document.getElementById('groupID' + boxes[0].GroupId);
    if (table.rows.length == 0) {
        for (i = 0; i < boxes.length; i++) {
            var row = table.insertRow(table.rows.length);
            row.setAttribute("height", "19px");
            row.setAttribute("id", "productRow" + boxes[i].ID);   

            var cell = row.insertCell(-1);
            cell.setAttribute("width", "10px");

            cell = row.insertCell(-1);
            cell.setAttribute("class", "refShopProduct");
            cell.setAttribute("width", "400px");
            cell.setAttribute("id", boxes[i].ID);
            if (globalSchemeLicence == 'AcademicCSA') {
                cell.innerHTML = ""
                + "<input id=\"chbox" + boxes[i].ID + "\" onclick=\"javascript:ChangeBox('" + boxes[i].ID + "')\" type=\"checkbox\" name=\"chbox"
                + boxes[i].ID + "\" /><a class=\"refShopProduct\" style=\"color:#83807B\" onclick=\"javascript:AddProductToSpecification('" + boxes[i].ID + "')\"> "
                + boxes[i].PartDesc + "<span style=\"color:#000000\">   (" + boxes[i].User + ")</span></a>";
            }
            else {
                cell.innerHTML = ""
                + "<input id=\"chbox" + boxes[i].ID + "\" onclick=\"javascript:ChangeBox('" + boxes[i].ID + "')\" type=\"checkbox\" name=\"chbox"
                + boxes[i].ID + "\" /><a class=\"refShopProduct\" style=\"color:#83807B\" onclick=\"javascript:AddProductToSpecification('" + boxes[i].ID + "')\"> "
                + boxes[i].PartDesc + "</a>";
            }
                
            cell = row.insertCell(-1);
            cell.setAttribute("width", "120px");
            cell.setAttribute("align", "right");
            var str = (boxes[i].StartPrice);
            cell.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span id=\"spanUSA" + boxes[i].ID + "\" style=\"color:#339900; font-size:12px\">$ " + DivisionSpace(str) + "</span>";
            cell = row.insertCell(-1);
            cell.setAttribute("width", "130px");
            cell.setAttribute("align", "right");
            str *= todayCurs;
            cell.innerHTML += "<span id=\"spanRUS" + boxes[i].ID + "\" style=\"color:#DF0000; font-size:12px\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + DivisionSpace(str) + " p.</span>";

            if (globalSchemeLicence != 'Box') {
                // У нас есть промо-цена.
                if (boxes[i].PromoPrice != '1') {

                    cell = row.insertCell(-1);
                    cell.setAttribute("width", "90px");
                    cell.setAttribute("align", "right");
                    cell.setAttribute("class", "refShopProduct");
                    cell.innerHTML = "<span style=\"color:#2062b4; font-size:12px\">Промо-цена: </span>";

                    cell = row.insertCell(-1);
                    cell.setAttribute("width", "110px");
                    cell.setAttribute("align", "right");
                    str = (boxes[i].PromoPrice);
                    cell.innerHTML = "<span style=\"color:#339900; font-size:12px\">$ " + DivisionSpace(str) + "</span>";

                    cell = row.insertCell(-1);
                    cell.setAttribute("width", "120px");
                    cell.setAttribute("align", "center");
                    str *= todayCurs;
                    cell.innerHTML = "<span style=\"color:#DF0000; font-size:12px\">" + DivisionSpace(str) + " p.</span>";

                }
                else {

                    cell = row.insertCell(-1);
                    cell.setAttribute("width", "100px");
                    cell.setAttribute("align", "right");
                    cell.innerHTML = "&nbsp;";

                    cell = row.insertCell(-1);
                    cell.setAttribute("width", "100px");
                    cell.setAttribute("align", "right");
                    cell.innerHTML = "&nbsp;";

                    cell = row.insertCell(-1);
                    cell.setAttribute("width", "130px");
                    cell.setAttribute("align", "center");
                    cell.innerHTML = "&nbsp;";

                }
            }
        } 
    }
}

// Добавление бокса в спеку, по клике по ссылке
function AddProductToSpecification(id) {

    var name = 'chbox' + id;
    var objcheck = document.getElementById(name);
    var obj = document.getElementById(id);
    var price = document.getElementById('productRow' + id);
    if (objcheck.checked == false) {
        price.style.fontWeight = 'bold';
        obj.style.fontWeight = 'bold';
        objcheck.checked = true;
        GeneratSpecification(id);
    }
    else if (objcheck.checked == true) {
        obj.style.fontWeight = 'normal';
        price.style.fontWeight = 'normal';
        objcheck.checked = false;
        DeleteSpecification(id,price)
    }
}

// Добавление бокса в спеку, по клике по галочке
function ChangeBox(id) {

    var name = 'chbox' + id;
    var objcheck = document.getElementById(name);
    var obj = document.getElementById(id);
    var price = document.getElementById('productRow' + id);
    
    if (objcheck.checked == true) {
        obj.style.fontWeight = 'bold';
        price.style.fontWeight = 'bold';
        GeneratSpecification(id);
    }
    else if (objcheck.checked == false) {
        obj.style.fontWeight = 'normal';
        price.style.fontWeight = 'normal';
        DeleteSpecification(id, price);
    }
}

// Создание позиции бокса при клике на галочку, по виду продукта.
function GeneratSpecification(id) {
    var numberBox;

    GetBox(id);
    
    SumSpeca();
    BoxNextEnable();
}

function GetBox(id, option) {

    request = GetRequest();
    switch (globalSchemeLicence) {
        case 'Box':
            {
                var url = "/Api/GetBox.aspx?ID=" + id;
            } break;
        case 'OVS':
            {
                var url = "/Api/GetOVS.aspx?ID=" + id;
            } break;
        case 'OVL':
            {
                var url = "/Api/GetOVL.aspx?ID=" + id;
            } break;
        case 'AcademicCSA':
            {
                var url = "/Api/GetAcademicCSA.aspx?ID=" + id;
            } break;
        case 'AcademicOLP':
            {
                var url = "/Api/GetAcademicOLP.aspx?ID=" + id;
            } break;
        case 'Goverment':
            {
                var url = "/Api/GetGoverment.aspx?ID=" + id + "&Level=" + globalLicenceLevel;
            } break;
        case 'OLP':
            {
                var url = "/Api/GetOLP.aspx?ID=" + id;
            } break;
    }
    if (globalSchemeLicence == 'Goverment') {
        var params = 'ID=' + id + '&Level=' + globalLicenceLevel;
    }
    else {
        var params = 'ID=' + id;
    }
    request.open('POST', url, false);
    if (browser) {
        request.send(params);
        switch (option) {
            case 'Language':
                {
                    request.onreadystatechange = processChangeLanuage();
                } break;
            case 'addSA':
                {
                    request.onreadystatechange = processOLPaddSA();
                } break;
            default:
                {
                    request.onreadystatechange = processBox();
                }
        }
    }
    else {
        switch (option) {
            case 'Language':
                {
                    request.onreadystatechange = processChangeLanuage;
                } break;
            case 'addSA':
                {
                    request.onreadystatechange = processOLPaddSA;
                } break;
            default: 
                {
                    request.onreadystatechange = processBox;
                }
        }
        // Send the request
        request.send(null);
    }
}

// Парсим Box
function processBox() {

    var box = new Object();
    if (request.readyState != 4) return;
    else {

        var str = request.responseText;
        var array = new Array();
        array = str.split(";");
        
        var check = 0;
        for (j = 0; j < array.length; j++) {
            if (array[j] == null)
                check++;
        }
        if (check == 0) {
            array[4] = array[4].replace(",", ".");
            
            box.ID = array[0];
            box.PartNumber = array[1];
            box.Language = array[2];
            box.PartDesc = array[3];
            box.StartPrice = parseFloat(array[4]);
            // OVS, AcademicCSA
            if (globalSchemeLicence != 'Box') {
                if (array[6] != 1) {
                    array[6] = array[6].replace(",", ".");
                    box.StartPrice = parseFloat(array[6]);
                }
                box.DiscGroup = array[5];
            }
            
            box.Number = 1;
            SetToSpeca(box);
        }
    }
}

// Добавляем выбранный продукт в спеку.
function SetToSpeca(box) {

    // В глобальный массив добавляем продукт.
    globalProductArray.push(box);
    
    var n = globalSpecaTable.rows.length - 1;
    var row = globalSpecaTable.insertRow(n);

    row.setAttribute("height", "44px");
    row.setAttribute("class", "SpecaTableRowProduct");
    row.setAttribute("id","productRow" + box.ID);
    row.style.backgroundColor = "White";

    // PartNumber
    var cell = row.insertCell(-1);
    cell.style.textAlign = 'center';
    cell.setAttribute("height", "44px");
    cell.style.backgroundImage = 'url("/images/speca_product_left.png")';
    cell.innerHTML = box.PartNumber;

    // PartDesc
    cell = row.insertCell(-1);
    cell.style.paddingLeft = '10px';
    cell.innerHTML = box.PartDesc;
    
    // Language
    cell = row.insertCell(-1);
    cell.style.textAlign = 'center';
    cell.innerHTML = box.Language;
    cell.style.color = "#003399";

    // StartPrice
    cell = row.insertCell(-1);
    cell.style.textAlign = 'center';
    cell.style.color = "#003399";
    var price = box.StartPrice;
    cell.innerHTML = DivisionSpace(price);

    // Number
    cell = row.insertCell(-1);
    cell.style.textAlign = 'center';
    cell.setAttribute("align", "center");
    cell.innerHTML = '<input id="boxNumber' + box.ID + '" onchange="javascript:QuantityOfBox(\'' + box.ID + '\',\'' + price + '\')" type="text" style="width:40px; text-align:center" value="1"/></input>';

    // Расчет суммы позиции в долларах
    cell = row.insertCell(-1);
    cell.style.textAlign = 'center';
    cell.setAttribute('id', 'SumPrice' + box.ID);

    var sumprice = box.StartPrice;
    cell.innerHTML = DivisionSpace(sumprice);
    cell.style.color = "#003399";

    // Расчет суммы позиции в рублях
    cell = row.insertCell(-1);
    cell.style.textAlign = 'center';
    cell.style.backgroundImage = 'url("/images/speca_product_right.png")';
    cell.style.color = "#003399";
    cell.setAttribute('id', 'RusSumPrice' + box.ID);
    
    var rusSumPrice = sumprice * todayCurs;
    cell.innerHTML = DivisionSpace(rusSumPrice);
}

// Расчет общей стоимости спеки
function SumSpeca() {

    var vat = document.getElementById('VAT');
    var vatRus = document.getElementById('VATRus');
    var sum = 0;
    var rusSum = 0;

    // Для простоты расчета итоговых сумм, я использую массив arrayCost, т.к. в нем просто надо просуммировать цены
    for (i = 0; i < globalProductArray.length; i++) {
        int1 = parseFloat(globalProductArray[i].StartPrice) * globalProductArray[i].Number;
        sum += MyPrecision(int1);
        int2 = parseFloat(globalProductArray[i].StartPrice) * globalProductArray[i].Number * todayCurs;
        rusSum += MyPrecision(int2);
    }
    // Итог в долларах
    var sumspeca = document.getElementById('SumSpeca');
    sum = MyPrecision(sum);
    sumspeca.innerHTML = DivisionSpace(sum);

    // Итог в рублях
    var RusSumSpeca = document.getElementById('RusSumSpeca');
    rusSum = MyPrecision(rusSum);
    RusSumSpeca.innerHTML = DivisionSpace(rusSum);

    // Расчет НДС
    if (globalSchemeLicence == "Box") {
        vat.innerHTML = DivisionSpace(VAT(sum));
        vatRus.innerHTML = DivisionSpace(VAT(rusSum));
        //Записываем сумму спеки в скрытое поле, чтобы потом получить его в счете
        var hiddenRusSumSpeca = document.getElementById('RusSumSpecaHidden');
        hiddenRusSumSpeca.value = rusSum;
    }
    if (globalSpecaTable.rows.length == 2) {
        sumspeca.innerHTML = "0,00";
        RusSumSpeca.innerHTML = "0,00";
        vat.innerHTML = "0,00";
        vatRus.innerHTML = "0,00";
    }
}

// Расчет НДС
function VAT(number) {
    return MyPrecision(number / 118 * 18);
}

// Метод для расчета итоговой суммы 1 позиции в спеке
function QuantityOfBox(id, price) {

    var button = document.getElementById('Next');
    button.disabled = false;
    // Расчет суммы в долларах
    var productRow = document.getElementById('productRow' + id);
    var boxNumber = document.getElementById('boxNumber' + id);
    
    // Общее количество боксов
    var AllNumberOfBox = 0;
    var number = boxNumber.value;

    if (number > 0) {
        var n;
        // Поиск нашего элемента в массиве globalProductArray для замены количества
        if (globalStageShop == 'SelectProduct') {
            for (i = 0; i < globalProductArray.length; i++) {
                if (globalProductArray[i].ID == id) {
                    globalProductArray[i].Number = boxNumber.value;
                }
                AllNumberOfBox += parseInt(globalProductArray[i].Number);
            }
            if (AllNumberOfBox >= 1000) {
                alert('На Ваш заказ будут предоставлены особые ценовые условия, обратитесь в отдел продаж.');
                button.disabled = true;
            }
            if (globalSchemeLicence == 'Box') {
                if (number >= 100) {
                    alert('На Ваш заказ будут предоставлены особые ценовые условия, обратитесь в отдел продаж.');
                    button.disabled = true;
                }
            }
            SumSpeca();
        }
        else if (globalStageShop == 'Options') {
            //Заменяем количество в массиве arrayOLP
            for (j = 0; j < globalProductArray.length; j++) {
                if (globalProductArray[j].ID == id) {
                    globalProductArray[j].Number = boxNumber.value;
                    break;
                }
            }
            ConversingSum();
        }

        
        // Пересчет суммы позиции в долларах
        var sum = document.getElementById('SumPrice' + id);
        price = price.toString().replace(",", ".");
        price = parseFloat(price);
        var multi = number * price;
        sum.innerHTML = DivisionSpace(multi);

        // Пересчет суммы позиции в рублях
        var russum = document.getElementById('RusSumPrice' + id);
        russum.innerHTML = DivisionSpace(multi * todayCurs);
    }

    // Удаляем из спецификации, и убираем галочку
    if (number == 0) {
        button.disabled = false;

        if (globalStageShop == 'SelectProduct') {
            // находим галочку
            var objcheck = document.getElementById('chbox' + id);
            var obj = document.getElementById(id);
            // изменяем галочку и шрифт
            if (objcheck.checked == true) {
                obj.style.fontWeight = 'normal';
                objcheck.checked = false;
            }
            productRow.style.fontWeight = 'normal';

            DeleteSpecification(id, productRow);
            SumSpeca();
        }
        if (globalStageShop == 'Options') {
            DeleteSpecification(id, productRow);
            for (i = 0; i < globalProductArray.length; i++) {
                if (globalProductArray[i].ID == id) {
                    globalProductArray.splice(i, 1);
                    break;
                }
            }
            ConversingSum();
        }
    }
    if (number < 0) {
        alert('Введите число большее нуля!');
        button.disabled = true;
    }

    if (isNaN(number) == true) {
        alert('Введите число!');

        button.disabled = true;
    }
    // если ввели число с плавающей точкой.
    var string = number.toString();
    // число с плавающей точкой
    if (string.indexOf('.', 0) != -1) {
        alert('Введите целое число!');
        button.disabled = true;
    }
}

// Удаление позиции из спеки
function DeleteSpecification(id, productRow) {

    // var productRow = document.getElementById('productRow' + id);
	// Удаляем выбранный элемент из массива
	for (i = 0; i < globalProductArray.length; i++) {
	    if(globalProductArray[i].ID == id){
	        globalProductArray.splice(i, 1);
	        break;
	    }
	}
	// Удаляем следующую стоку
	if (globalStageShop == 'SelectProduct') {
	    for (i = 0; i < globalSpecaTable.rows.length; i++) {
	        if (globalSpecaTable.rows[i].id == productRow.id) {
	            globalSpecaTable.deleteRow(i);
	            break;
	        }
	    }
	}
	// Удаляем следующую стоку
	else if (globalStageShop == 'Options') {
	    var n = 0;
	    for (i = 0; i < globalSpecaTable.rows.length; i++) {
	        if (globalSpecaTable.rows[i].id == productRow.id) {
	            globalSpecaTable.deleteRow(i);
	            globalSpecaTable.deleteRow(i);
	            break;
	        }
	    }
	}
	if (globalSpecaTable.rows.length == 2) {
	    BoxNextDisable();
	}
}

// Отправка массива спеки на нех страницу
function SendSpeca() {
    var hasErrors = 0;
    var button = document.getElementById('Next');

    var hidden = document.getElementById('SpecaArray');
    hidden.value = '';

    var form = document.getElementById('SpecaForm');

    if (globalStageShop == 'SelectProduct') {
        if (globalSchemeLicence == 'Box') {
            for (i = 0; i < globalProductArray.length; i++) {
                hidden.value += globalProductArray[i].ID + '|' + globalProductArray[i].PartNumber + '|' + globalProductArray[i].PartDesc + '|' +
                                + globalProductArray[i].Number + '|' + globalProductArray[i].StartPrice + '|';
            }
        }
        else {
            for (i = 0; i < globalProductArray.length; i++) {
                hidden.value += globalProductArray[i].ID + '|' + globalProductArray[i].Number + '|' + globalProductArray[i].StartPrice + '|';
            }
        }
    }
    else if (globalStageShop == 'Options') {
        hidden.value = "";
        for (i = 0; i < globalProductArray.length; i++) {
            hidden.value += globalProductArray[i].ID + '|' + globalProductArray[i].Number + '|' + globalProductArray[i].StartPrice + '|';
        }
        hidden = document.getElementById('SpecaDisc');
        hidden.value = '';
        for (i = 0; i < arrayDisc.length; i++) {
            hidden.value += arrayDisc[i].DiscId + '|' + arrayDisc[i].Number + '|';
        }
    }
    if (hasErrors == 0) {

        form.submit();
    }
}

// Выбираем вид плательщика, физик или юрик.
function TypeOfPayer() {
    var select = document.getElementById('payerselect');
    if (select.value == "naturalperson") {
        var table = document.getElementById('payerTableNatural');
        table.style.display = "block";
        table = document.getElementById('payerTableLegal');
        table.style.display = "none";
    }
    else if (select.value == "legalperson") {
        var table = document.getElementById('payerTableLegal');
        table.style.display = "block";
        table = document.getElementById('payerTableNatural');
        table.style.display = "none";
    }
    else if (select.value == "all") {
        var table = document.getElementById('payerTableNatural');
        table.style.display = "none";
        table = document.getElementById('payerTableLegal');
        table.style.display = "none";
    }
}

// Отправка данных, сабмит формы.
function SendIncoiceInfo() {
    var form = document.getElementById('SendPersonInfo');
    form.submit();
}

// Согласие с офертой в боксах.
function Acceptcheckbox(id, buttonname) {
    var checkbox = document.getElementById(id);
    var button = document.getElementById(buttonname);

    var reference = document.getElementById('referenceInvoice');
    if (checkbox.checked == true) {
        button.disabled = false
    }
    else {
        button.disabled = true;
        reference.innerHTML = "&nbsp;";
        GLOBAL = 0;
    }
}

// Заносим реквизиты в скрытые поля формы, при оформлении счета в коробках.
var GLOBAL = 0;
function SendAccount(name) {
    if (GLOBAL == 0) {
        GLOBAL = 1;
        var lname = document.getElementById('LastName');
        var fname = document.getElementById('FirstName');
        var pantronymic = document.getElementById('Patronymic');
        var phone = document.getElementById('Phone');
        var email = document.getElementById('email2');
        var Fax = document.getElementById('Fax');
        var City = document.getElementById('City');
        var ZIP = document.getElementById('ZIP');
        var Address = document.getElementById('Address');
        var TIN = document.getElementById('TIN');

        var hasErrors = 0;
        if (lname.value.length == 0) {
            hasErrors = 1;
        }
        else {
            var elem = document.getElementById('HiddenLastName');
            elem.value = lname.value;
        }
        if (fname.value.length == 0) {
            hasErrors = 1;
        }
        else {
            var elem = document.getElementById('HiddenFirstName');
            elem.value = fname.value;
        }
        if (pantronymic.value.length == 0) {
            hasErrors = 1;
        }
        else {
            var elem = document.getElementById('HiddenPatronymic');
            elem.value = pantronymic.value;
        }
        if (phone.value.length == 0) {
            hasErrors = 1;
        }
        else {
            var elem = document.getElementById('HiddenPhone');
            elem.value = phone.value;
        }
        if (email.value.length == 0) {
            hasErrors = 1;
        }
        else {
            var elem = document.getElementById('HiddenEmail');
            if (IsEmail(email) == true)
                elem.value = email.value;
            else {
                hasErrors = 1;
            }
        }
        if (hasErrors == 1) {
            alert("Вы ввели не все данные.");
            GLOBAL = 0;
        }
        else {
            var table = document.getElementById('referenceInvoice');
            var HiddenFax = document.getElementById('HiddenFax');
            var HiddenCity = document.getElementById('HiddenCity');
            var HiddenZIP = document.getElementById('HiddenZIP');
            var HiddenAddress = document.getElementById('HiddenAddress');
            var HiddenTIN = document.getElementById('HiddenTIN');
            HiddenFax.value = Fax.value;
            HiddenCity.value = City.value;
            HiddenZIP.value = ZIP.value;
            HiddenAddress.value = Address.value;
            HiddenTIN.value = TIN.value;

            table.innerHTML = "<a class=\"refShopProduct\" style=\"cursor:default\" onclick=\"javascript:SendIncoiceInfo()\" target=\"_blank\">Перейти&nbsp;к&nbsp;печатной&nbsp;форме&nbsp;договора.</a>";
        }
    }
}