var orderTemplate = {};
var allCustomer = [];
var isEndPoint = false;
var customerAddress = "";
var isOrderAdd = true;
var orderDetails = [];
var allFactories = [];
var allUnits = [];
var allMaterials = [];
var currentSimpleRow = null;
var divTechnics = null;
var divSimpleTechnics = null;

function constructDetail() {

    orderTemplate = eval($("#OrderTemplate").val());

    if ($("#OrderDetails").val() != null) {
        var oDetails = eval($("#OrderDetails").val());
        $(oDetails).each(function (i, v) {

            eval("var d=" + v.Detail + ";");
            orderDetails.push({
                Id: v.Id,
                OrderName: v.OrderName,
                Detail: d,
                DetailText: v.DetailText,
                Category: v.Category,
                CategoryName: v.CategoryName,
                ReportCategory: v.ReportCategory,
                Number: v.Number,
                StockNumber: v.StockNumber,
                Price: v.Price,
                Amount: v.Amount,
                MaterialId: v.MaterialId,
                MaterialName: FindMaterialName(v.MaterialId),
                PriceUnitId: v.PriceUnitId,
                Memo: v.Memo,
                Technic: v.Technic,
                TechnicText: v.TechnicText == null ? '' : v.TechnicText,
                Guid: newId(),
                FactoryName: ''

            });
        });

        generateDetailTable();
    }

    InitialCategoryDropdown();
}

function InitialCategoryDropdown() {

    $("<option value=''>&nbsp;</option>").appendTo($("#FactoryCategory"));
    for (var i in orderTemplate) {
        $("#FactoryCategory").append("<option value=\"" + orderTemplate[i].id + "\">" + orderTemplate[i].text + "</option>");
    }
}

function newFactory() {
    ClearErrorMsg();
    $("#FactoryName").val("");
    $('#divFactory').dialog('open');
}

$(function () {

    divTechnics = $("#popOrderDetail #divTechnics");
    divSimpleTechnics = $("#divPopTechnic .divTechnics");

    widthUnit = $("#WidthUnit").val();

    if ($("#OrderNo").val() != "") {
        isOrderAdd = false;
        $(".c-fa").remove();
        $("#popOrderDetail td").removeAttr("colspan");
        $("#tdTechnic").removeClass("w360");
    }

    $(".select2").select2();

    $.blockUI({ message: '<h5>加载中...</h5>' });
    $.ajax({
        url: "/Order/GetJsonCustomerFactoryPriceUnit?orderNo=" + $("#OrderNo").val(),
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        success: function (result) {
            $.unblockUI();

            allFactories = result.factories;
            allUnits = result.priceUnits;

            for (var i in result.customers) {
                allCustomer.push({ label: result.customers[i].ItemText, value: result.customers[i].ItemValue });
            }

            allMaterials = result.materials;
            FillMaterialDdl(allMaterials);
        },
        error: function (e) {
            $.unblockUI();
        }
    });

    try {
        $('#txtCustomer').autocomplete({
            source: allCustomer,
            select: function (a, b, c) {
                $("#CustomerNo").val(b.item.value);
                $('#CustomerNo').change();
            },
            close: function (envent, ui) {
                $('#txtCustomer').val("");
            }
        });
    }
    catch (e) {
    }

    constructDetail();
    generateDetailTable();

    $("#Category").append("<option value=''>请选择业务类型</option>");
    for (var i in orderTemplate) {
        $("#Category").append("<option value=\"" + orderTemplate[i].id + "\">" + orderTemplate[i].text + "</option>");
    }

    $(".number,.amount,.price").each(function () {

        if ($(this).val() == "0") {
            $(this).val("");
        }
    });

    if (isOrderAdd) {
        $("#trPrePaid").css("display", '');
        if ($("#ShowSimpleFactoryItem").val() == "1") {
            $("#tr-factory").css("display", '');
        }

        if ($("#ShowRightFactoryItem").val() == "0") {
            $(".c-fa").remove();
        }
    }


    if (($("#WorkFlowNo").val() == "" && !isOrderAdd) || (isOrderAdd && $("#EnableWorkFlow").val() == "1")) {
        $("#trWorkFlow").css("display", '');
    }
    else {
        $("#trWorkFlow").css("display", 'none');
    }

    $(".text-date").attr("readonly", "readonly");
    $(".text-date").datepicker({ dateFormat: 'yy-mm-dd' });

    $(".amount").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false });
    $(".number").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false });
    $(".price").inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });


    $('#ContactNo').change(function () {
        if ($('#ContactNo').val() != "") {
            $("#Contact").val($("#ContactNo").find("option:selected").text());
        }
    });

    if ($("#HideFactory").val().toLowerCase() == "true") {

        $("#tr-factory").css("display", 'none');
        $(".c-fa").remove();
    }


    $("#WorkFlowNo").change(function () {
        if ($("#WorkFlowNo").val() == "") {
            $("#divWorkFlow").hide();
            return;
        }
        else {
            $("#divWorkFlowUserId").css("display", "inline-block");
            $("#divWorkFlow").css("display", "inline-block");
        }

        $("#WorkFlowStepNo").empty();
        $("#WorkFlowStepNo").append("<option></option>");
        $("#WorkFlowUserId").empty();
        $("#WorkFlowUserId").append("<option></option>");

        $.ajax({
            url: "/Order/GetWorkFlowNextSteps",
            type: 'GET',
            cache: false,
            dataType: 'json',
            async: false,
            data: { WorkFlowNo: $("#WorkFlowNo").val(), WorkFlowStepNo: "0" },
            success: function (result) {
                if (result.code == 0) {
                    for (var r in result.data) {
                        $("#WorkFlowStepNo").append("<option value='" + result.data[r].ItemValue + "'>" + result.data[r].ItemText + "</option>");
                    }
                }
                else {
                    alert("获取数据失败，请稍后再试");
                }
            },
            error: function (e) {

            }
        });
    });

    $("#btnNewFactory,#aNewFactory").click(function () {
        newFactory();
    });

    $("#WorkFlowStepNo").change(function () {

        if (!$("#WorkFlowStepNo").val()) {
            return;
        }

        $("#WorkFlowUserId").empty();
        $("#WorkFlowUserId").append("<option></option>");

        isEndPoint = false;

        $.ajax({
            url: "/Order/GetWorkFlowStepUsers",
            type: 'GET',
            cache: false,
            dataType: 'json',
            async: false,
            data: { WorkFlowNo: $("#WorkFlowNo").val(), WorkFlowStepNo: $("#WorkFlowStepNo").val() },
            success: function (result) {
                if (result.code == 0) {
                    isEndPoint = result.isEndPoint == "1" ? true : false;;
                    for (var r in result.data) {
                        $("#WorkFlowUserId").append("<option value='" + result.data[r].ItemValue + "'>" + result.data[r].ItemText + "</option>");
                    }
                    if (isEndPoint) {
                        $("#divWorkFlowUserId").css("display", "none");
                    }
                    else {
                        $("#divWorkFlowUserId").css("display", "inline-block");
                    }
                }
                else {
                }
            },
            error: function (e) {
            }
        });
    });

    $("#popOrderDetail #MaterialId").change(function () {

        var materialId = $(this).val();

        if (materialId) {

            $.ajax({
                url: "/Order/GetCustomerPrice",
                type: 'GET',
                cache: false,
                data: { CustomerNo: $('#CustomerNo').val(), MaterialId: materialId },
                success: function (result) {
                    if (result.code == 0) {
                        $("#popOrderDetail #PriceUnitId").val(result.unit);

                        getSailPrice(materialId, result.price);

                        SetPopTechnics(result.technics);
                    }
                },
                error: function (e) {
                    getSailPrice(materialId, 0);
                }
            });

            QueryFactoryPrice();

        }
        else {
            divTechnics.empty();
        }
    });

    $('#CustomerNo').change(function () {
        if ($('#CustomerNo').val() == "") {
            $("#DeliveryAddress").val("");
            return;
        }

        $.ajax({
            url: "/Order/GetContactAndPaymentType",
            type: 'GET',
            cache: false,
            data: { customerNo: $('#CustomerNo').val() },
            success: function (result) {

                customerAddress = result.CustomerAddress;


                if (isOrderAdd) {
                    $("#PrePaidPaymentType").val(result.PaymentType);
                }

                $("#DeliveryAddress").val(result.CustomerAddress);

                $("#ContactNo").empty();
                $("#Contact").val("");

                $("#ContactNo").append("<option></option>");
                var mainContactId = "";
                for (var r in result.Data) {
                    if (result.Data[r].IsMain) {
                        mainContactId = result.Data[r].Id;
                    }
                    $("#ContactNo").append("<option value='" + result.Data[r].Id + "'>" + result.Data[r].Name + " " + result.Data[r].Phone + "</option>");
                }
                $("#ContactNo").val(mainContactId);

                $("#ContactNo").change();
            },
            error: function (e) {
            }
        });
    });

    $("#popOrderDetail #FactoryNo").change(function () {
        if ($("#FactoryNumber").val() == "") {
            $("#FactoryNumber").val($("#popOrderDetail #Number").val());
        }
        QueryFactoryPrice();
    });

    $('#divPriceTip').dialog({
        width: 400,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#popOrderDetail').dialog({
        width: 1000,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divCustomer').dialog({
        width: 500,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divContact').dialog({
        width: 500,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divFactory').dialog({
        width: 500,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divPopTechnic').dialog({
        width: 500,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });


    $('#btnSaveFactory').click(function () {
        if (checkRequired('divFactory', 'errorMessage') == false) {
            return;
        }

        $.ajax({
            url: "/Customer/AddFactory",
            type: 'POST',
            cache: false,
            data: {
                FactoryName: $("#FactoryName").val()
            },
            success: function (result) {
                if (result.code == 0) {

                    $('#divFactory').dialog('close');

                    var ddls = $(".FactoryNo");
                    var newF = { ItemValue: result.data, ItemText: $("#FactoryName").val() };
                    allFactories.push(newF);
                    $(ddls).each(function (i, v) {
                        $("<option value='" + newF.ItemValue + "'>" + newF.ItemText + "</option>").appendTo(v);
                    });

                    $("#popOrderDetail #FactoryNo").val(result.data);
                }
                else {
                    SetErrorMsg(result.message, "divFactory");
                }
            },
            error: function (e) {
                SetErrorMsg("创建外协商失败，可能是您的权限不足", "divFactory");
            }
        });

    });

    $('#btnCancelCustomer').click(function () {
        $('#divCustomer').dialog('close');
    });

    $('#btnSaveCustomer').click(function () {

        if (checkRequired('divCustomer', 'errorMessage') == false) {
            return;
        }

        $.ajax({
            url: "/Customer/Add",
            type: 'POST',
            cache: false,
            data: {
                CanLogin: false,
                CustomerFullName: $("#CustomerFullName").val(),
                CustomerShortName: $("#CustomerFullName").val(),
                UseBalanceFirst: false
            },
            success: function (result) {
                if (result.code == 0) {
                    $('#divCustomer').dialog('close');
                    $("<option value='" + result.data + "'>" + $("#CustomerFullName").val() + "</option>").appendTo($("#CustomerNo"));
                    $("#CustomerNo").val(result.data);
                }
                else {
                    SetErrorMsg(result.message, "divCustomer");
                }
            },
            error: function (e) {
                SetErrorMsg("添加客户失败，可能是您的权限不足", "divCustomer");
            }
        })
    });

    $('#divPriceHistory').dialog({
        width: 900,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divPriceHistoryFactory').dialog({
        width: 900,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#btnCancel').click(function () {

        synConfirm("确定要放弃修改吗？", function () {
            window.history.go(-1);
        });

    });

    $('#btnSave').click(function () {

        ClearErrorMsg();

        if ($("#CustomerNo").val() == "") {
            $("#CustomerNo").addClass("redBorder");
            return SetErrorMsg('请选择客户');
        }

        if (checkRequired('divOrder', 'errorMessage') == false) {
            return;
        }

        if (orderDetails.length == 0) {
            return SetErrorMsg("请至少添加一个订单明细。")
        }

        if ($("#PrePaid").val() && !isNaN($("#PrePaid").val())) {
            if (!$("#PrePaidPaymentType").val()) {
                $("#PrePaidPaymentType").addClass("redBorder");
                return SetErrorMsg_Required();
            }
        }

        if ($("#trWorkFlow").css("display") != "none") {
            if ($("#WorkFlowNo").val() == "") {
                $("#WorkFlowNo").addClass("redBorder");
                return SetErrorMsg_Required();
            }

            if ($("#WorkFlowStepNo").val() == "") {
                $("#WorkFlowStepNo").addClass("redBorder");
                return SetErrorMsg_Required();
            }
            if (!isEndPoint) {
                if ($("#WorkFlowUserId").val() == "") {
                    $("#WorkFlowUserId").addClass("redBorder");
                    return SetErrorMsg_Required();
                }
            }
        }

        if (!$("#OrderNo").val()) {
            var checkResult = true;
            var tbody = $("#simpleOrderTr tr");

            tbody.each(function (i, v) {

                if (!$(v).find("#FactoryNo").val()) {
                    $(v).find("#FactoryNo").parent().addClass("redBorder");
                    factoryNeed = true;
                    checkResult = false;
                }

                //if (!$(v).find("#FactoryCategoryId").val()) {
                //    $(v).find("#FactoryCategoryId").addClass("redBorder");
                //    checkResult = false;
                //}

                //if (!$(v).find("#FactoryOrderName").val()) {
                //    $(v).find("#FactoryOrderName").addClass("redBorder");
                //    checkResult = false;
                //}

                //if (!$(v).find("#PriceUnitId").val()) {
                //    $(v).find("#PriceUnitId").addClass("redBorder");
                //    checkResult = false;
                //}

                if (!$(v).find("#Amount").val()) {
                    $(v).find("#Amount").addClass("redBorder");
                    checkResult = false;
                }

                //if (!$(v).find("#Number").val()) {
                //    $(v).find("#Number").addClass("redBorder");
                //    checkResult = false;
                //}

                //if (!$(v).find("#Price").val()) {
                //    $(v).find("#Price").addClass("redBorder");
                //    checkResult = false;
                //}
            });

            if (!checkResult) {
                return SetErrorMsg_Required();
            }

            checkResult = true;
            tbody.each(function (i, v) {

                var unit = $(v).find("#ValuationType").val();
                if (unit == "1") {
                    if (!$(v).find("#Area").val()) {
                        $(v).find("#Area").addClass("redBorder");
                        SetErrorMsg("计价方式为面积计价时，必须填写面积");
                        checkResult = false;
                        return false;
                    }
                }
                else if (unit == "2") {
                    if (!$(v).find("#Width").val()) {
                        $(v).find("#Width").addClass("redBorder");
                        SetErrorMsg("计价方式为长度时，必须填写宽度");
                        checkResult = false;
                        return false;
                    }
                }
                else if (unit == "4") {
                    if (!$(v).find("#Width").val() || !$(v).find("#Height").val() || !$(v).find("#Number").val()) {
                        $(v).find("#Width").addClass("redBorder");
                        $(v).find("#Height").addClass("redBorder");
                        $(v).find("#Number").addClass("redBorder");
                        SetErrorMsg("计价方式为周长时，必须填写宽度，高度和数量");
                        checkResult = false;
                        return false;
                    }
                }

            });

            if (!checkResult) {
                return;
            }
        }
        // deep colone array and its element,
        // slice can not works here, since elements of the array is object too.
        //var orderDetailsClone = orderDetails.slice();
        var orderDetailsClone = JSON.parse(JSON.stringify(orderDetails));

        $(orderDetailsClone).each(function (i, v) {
            v.Detail = JSON.stringify(v.Detail);
        });

        $.blockUI({ message: '<h5>保存中，请稍候...</h5>' });

        if (isOrderAdd) {

            var orderFactories = GetOrderFactories();

            $.ajax({
                url: "/Order/Add",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetailsClone), orderFactories: JSON.stringify(orderFactories) },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        location.href = "/Order/Index";
                    }
                    else if (result.code == 1) {
                        SetErrorMsg(result.message);
                    }
                    else if (result.code == 9) {
                        location.href = "/MySpace/Index";
                    }
                    else {
                        return SetErrorMsg_Save_Failed();
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    return SetErrorMsg_Save_Failed();
                }
            });

        }
        else {
            var additonMessage = "";

            $.ajax({
                url: "/Order/Update",
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: { BasicInfo: GetBasicInfo(), orderDetails: JSON.stringify(orderDetailsClone) },
                success: function (result) {
                    $.unblockUI();
                    if (result.code == 0) {
                        if ($("#BackURL").val() == "") {
                            location.href = '/MySpace/UnProcessedOrder';
                        }
                        else {
                            location.href = $("#BackURL").val();
                        }
                    }
                    else if (result.code == 1) {
                        SetErrorMsg(result.message);
                    }
                    else {
                        return SetErrorMsg_Save_Failed();
                    }
                },
                error: function (e) {
                    $.unblockUI();
                    return SetErrorMsg_Save_Failed();
                }
            });
        }
    });

    if ($('#CustomerNo').val() != "") {
        $.ajax({
            url: "/Order/GetContactAndPaymentType",
            type: 'GET',
            cache: false,
            async: false,
            data: { customerNo: $('#CustomerNo').val() },
            success: function (result) {
                if (result != null) {
                    $("#hDeliveryAddress").val(result.CustomerAddress);
                    $("#ContactNo").append("<option></option>");

                    for (var r in result.Data) {
                        $("#ContactNo").append("<option value='" + result.Data[r].Id + "'>" + result.Data[r].Name + " " + result.Data[r].Phone + "</option>");
                    }
                }
                else {
                }
            },
            error: function (e) {
            }
        });
    }

    $('#Category').change(function () {
        CategoryChange();
        $("#popOrderDetail #MaterialId").val("");
        $("#popOrderDetail #MaterialId").change();
        resetPriceFactor();
    });

    $("#popOrderDetail #Price").keyup(function () {
        PopUpPriceChange();
    }).blur(function () {
        PopUpPriceChange();
    }).change(function () {
        PopUpPriceChange();
    });

    $("#popOrderDetail #Number").keyup(function () {
        PopUpPriceChange();
    }).blur(function () {
        PopUpPriceChange();
    }).change(function () {
        PopUpPriceChange();
    });

    $("#popOrderDetail #Amount").keyup(function () {
        PopUpAmountChange();
    }).blur(function () {
        PopUpAmountChange();
    });

    $("#popOrderDetail #FactoryAmount").keyup(function () {
        PopUpFactoryAmountChange();
    }).blur(function () {
        PopUpFactoryAmountChange();
    });

    $('#btnNewFactoryDetail').click(function () {
        addFactoryOrderDetailRow(null);
    });

    $('#btnCopyFactoryDetail').click(function () {
        copyFactoryDetail(null);
    });

    $('#btnDeleteFactoryDetail').click(function () {
        deleteFactoryDetail();
    });


    $("#FactoryPrice").keyup(function () {
        FactoryPriceChange();
    }).blur(function () {
        FactoryPriceChange();
    }).change(function () {
        FactoryPriceChange();
    });

    $("#FactoryNumber").keyup(function () {
        FactoryPriceChange();
    }).blur(function () {
        FactoryPriceChange();
    }).change(function () {
        FactoryPriceChange();
    });

    $("#MarketAmount").keyup(function () { calcRealAmount(); }).blur(function () { calcRealAmount(); }).change(function () { calcRealAmount(); });
    $("#Discount").keyup(function () { calcRealAmount(); }).blur(function () { calcRealAmount(); }).change(function () { calcRealAmount(); });
    $("#FeeInstallation,#FeeDelivery,#FeeDesign,#FeeOther").keyup(function () { calcMarketAmount(); }).blur(function () { calcMarketAmount(); }).change(function () { calcMarketAmount(); });

    $("#TaxType,#TaxRatio").change(function () {
        calcRealAmount();
    });

    if ($("#TaxType").val() == "") {
        $("#TaxRatio").attr("readonly", true);
    }

    if (!$("#OrderNo").val()) {
        if ($("#WorkFlowNo option").length > 1) {
            $('#WorkFlowNo')[0].selectedIndex = 1;
            $('#WorkFlowNo').change();
        }
    }

    // for quick create
    if (isOrderAdd) {
        calcMarketAmount();
    }
});

function FactoryPriceChange() {
    var price = $("#popOrderDetail #FactoryPrice").val();
    var number = $("#popOrderDetail #FactoryNumber").val();

    if (price && number && !isNaN(price) && !isNaN(number)) {
        $("#popOrderDetail #FactoryAmount").val(FixTwoDecimal(parseFloat(price) * parseFloat(number) * priceFactor));
    }
    else {
        $("#popOrderDetail #FactoryAmount").val("");
    }
}

function GetBasicInfo() {
    var result = {};
    result.OrderNo = $("#OrderNo").val();
    result.CustomerNo = $("#CustomerNo").val();
    result.ContactNo = $("#ContactNo").val();
    result.Contact = $("#Contact").val();
    result.TransactionDate = $("#TransactionDate").val();
    result.DeliveryType = $("#DeliveryType").val();
    result.DeliveryAddress = $("#DeliveryAddress").val();
    result.MarketAmount = $("#MarketAmount").val();

    result.FeeInstallation = $("#FeeInstallation").val();
    result.FeeDelivery = $("#FeeDelivery").val();
    result.FeeDesign = $("#FeeDesign").val();
    result.FeeOther = $("#FeeOther").val();

    result.Discount = $("#Discount").val();
    result.RealAmount = $("#RealAmount").val();
    result.ExpectDeliveryDate = $("#ExpectDeliveryDate").val();
    result.WorkFlowNo = $("#WorkFlowNo").val();
    result.WorkFlowStepNo = $("#WorkFlowStepNo").val();
    result.WorkFlowUserId = $("#WorkFlowUserId").val();
    result.Memo = $("TextArea[id='Memo']").val();
    result.TemplateNo = $("#TemplateNo").val();
    result.IsInvoiced = $("#IsInvoiced").prop("checked");

    result.TaxType = $("#TaxType").val();
    result.TaxRatio = $("#TaxRatio").val();
    result.TaxAmount = $("#TaxAmount").val();
    result.FeeTax = $("#FeeTax").val();

    result.WidthUnit = $("#WidthUnit").val();

    if ($("#PrePaid").val() && !isNaN($("#PrePaid").val())) {
        result.PrePaid = $("#PrePaid").val();
        result.PrePaidPaymentType = $("#PrePaidPaymentType").val();
        result.PrePaidMemo = $("#PrePaidMemo").val();
    }

    return JSON.stringify(result);
}

function GetDetailDetail() {
    var result = {};

    var guid = $("#popOrderDetail #Guid").val();
    result.Guid = guid == "" ? newId() : guid;
    result.Id = $("#popOrderDetail #Id").val() == "" ? "0" : $("#Id").val();
    result.OrderName = $("#popOrderDetail #OrderName").val();
    result.Category = $("#popOrderDetail #Category").val();
    result.ReportCategory = $("#popOrderDetail #ReportCategory").val();
    result.Number = $("#popOrderDetail #Number").val();
    result.StockNumber = $("#popOrderDetail #StockNumber").val();
    result.Price = $("#popOrderDetail #Price").val();
    result.Amount = $("#popOrderDetail #Amount").val();
    result.Memo = $("#popOrderDetail #Memo").val();
    result.MaterialId = $("#popOrderDetail #MaterialId").val();
    result.MaterialName = $("#popOrderDetail #MaterialId").find("option:selected").text();
    result.PriceUnitId = $("#popOrderDetail #PriceUnitId").val();

    result.FactoryNo = $("#popOrderDetail #FactoryNo").val();
    result.FactoryName = GetFactoryName($("#popOrderDetail #FactoryNo").val());
    result.FactoryPrice = $("#popOrderDetail #FactoryPrice").val();
    result.FactoryNumber = $("#popOrderDetail #FactoryNumber").val();
    result.FactoryAmount = $("#popOrderDetail #FactoryAmount").val();
    result.FactoryMemo = $("#popOrderDetail #FactoryMemo").val();
    result.Technic = JSON.stringify(GetPopSelectedTechnics());
    result.TechnicText = GetPopSelectedTechnicsText();
    result.Detail = {};

    var id;
    $("#tableDetail").find("input[id^='f']").each(function (i, t) {
        id = t.id.replace(/\(/g, "");
        id = id.replace(/\)/g, "");

        eval("result.Detail['" + t.id + "']='" + $(t).val() + "';");
    });
    $("#tableDetail").find("textarea[id^='f']").each(function (i, t) {
        id = t.id.replace(/\(/g, "");
        id = id.replace(/\)/g, "");
        console.log("result.Detail['" + t.id + "']='" + $(t).val() + "';");
        eval("result.Detail['" + t.id + "']='" + $(t).val() + "';");
    });
    $("#tableDetail").find("select[id^='f']").each(function (i, t) {
        id = t.id.replace(/\(/g, "");
        id = id.replace(/\)/g, "");
        eval("result.Detail['" + t.id + "']='" + $(t).val() + "';");
    });

    result.DetailText = GetDetailDetailText();

    formatOrderDetailObj(result);

    return result;
}

function GetDetailDetailText() {
    var result = "";
    $("#tableDetail").find("input[id^='f'],select[id^='f'],textarea[id^='f']").each(function (i, t) {
        if ($(t).val() != '') {
            result = result + $(t).parent().prev().html() + ": " + $(t).val() + ", ";
        }
    });
    if (result.length > 2) {
        result = result.substr(0, result.length - 2);
    }
    return result;
}

function CategoryChange() {

    var table = $("#tableDetail");
    table.find("tr").remove();

    var k = 0;
    var tr;
    var td;

    var cms = null;
    for (var i in orderTemplate) {

        if (orderTemplate[i].id == $('#Category').val()) {

            $('#divPriceTip').find("#divPriceText").html("");
            if (orderTemplate[i].priceTip != undefined) {
                $('#divPriceTip').find("#divPriceText").html(orderTemplate[i].priceTip.replace(/\n/g, '<br>'));
            }

            if ($.trim($('#divPriceTip').find("#divPriceText").html()) == "") {
                $('#divPriceTip').find("#divPriceText").html("没有发现价格信息!<br/>请在“系统配置->订单模板配置”中进行设置。");
            }

            $("#ReportCategory").val(orderTemplate[i].reportCategory);

            for (var j = 0; j < orderTemplate[i].fields.length; j++) {
                k = k + 1;
                if (k % 3 == 1) {
                    tr = $("<tr></tr>")
                }

                td = $("<td class='label'>" + orderTemplate[i].fields[j].label + "</td>");

                td.appendTo(tr);

                td = $("<td class='value'></td>");
                var fieldId = "f" + orderTemplate[i].id + orderTemplate[i].fields[j].id;

                fieldId = fieldId.replace(/\(/g, "");
                fieldId = fieldId.replace(/\)/g, "");

                if (orderTemplate[i].fields[j].type == 1) {
                    var textbox = $("<input type='text' id='" + fieldId + "' />");
                    if (orderTemplate[i].fields[j].formular != undefined
                        && orderTemplate[i].fields[j].formular != "") {
                        //textbox.attr("readonly", "readonly");
                        textbox.addClass("formular");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }
                    if (orderTemplate[i].fields[j].isPriceFactor != undefined
                        && orderTemplate[i].fields[j].isPriceFactor) {
                        textbox.addClass("isPriceFactor");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }
                    if (orderTemplate[i].fields[j].isStockFactor != undefined
                        && orderTemplate[i].fields[j].isStockFactor) {
                        textbox.addClass("isStockFactor");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }

                    textbox.appendTo(td);
                }
                else if (orderTemplate[i].fields[j].type == 2) {
                    // dropdown list
                    var ddl = $("<select id='" + fieldId + "'></select>");
                    for (var s in orderTemplate[i].fields[j].options) {
                        ddl.append("<option value=\"" + orderTemplate[i].fields[j].options[s] + "\">" + orderTemplate[i].fields[j].options[s] + "</option>");
                    }
                    if (orderTemplate[i].fields[j].isPriceFactor != undefined
                        && orderTemplate[i].fields[j].isPriceFactor) {
                        ddl.addClass("isPriceFactor");
                    }
                    if (orderTemplate[i].fields[j].isStockFactor != undefined
                        && orderTemplate[i].fields[j].isStockFactor) {
                        ddl.addClass("isStockFactor");
                    }
                    ddl.appendTo(td);
                }
                else if (orderTemplate[i].fields[j].type == 3) {
                    var textbox = $("<textarea id='" + fieldId + "'></textarea>");
                    if (orderTemplate[i].fields[j].formular != undefined
                        && orderTemplate[i].fields[j].formular != "") {
                        //textbox.attr("readonly", "readonly");                      
                        textbox.addClass("formular");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }
                    if (orderTemplate[i].fields[j].isPriceFactor != undefined
                        && orderTemplate[i].fields[j].isPriceFactor) {
                        textbox.addClass("isPriceFactor");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }
                    if (orderTemplate[i].fields[j].isStockFactor != undefined
                        && orderTemplate[i].fields[j].isStockFactor) {
                        textbox.addClass("isStockFactor");
                        textbox.inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                    }

                    textbox.appendTo(td);
                    td.attr("colspan", "5");
                    k = k + 2;
                }


                if (orderTemplate[i].fields[j].isRequired) {
                    $("<span class='redStar'> *</span>").appendTo(td);
                }

                td.appendTo(tr);

                console.log(orderTemplate[i].fields);
                console.log(j + 1);
                if (j < orderTemplate[i].fields.length - 1 && orderTemplate[i].fields[j + 1].type == 3) {
                    // the next is memo
                    if (k % 3 == 1) {
                        td.attr("colspan", "5");
                        k = k + 2;
                    }
                    else if (k % 3 == 2) {
                        td.attr("colspan", "3");
                        k = k + 1;
                    }

                }

                if (k % 3 == 0) {
                    tr.appendTo(table);
                }
            }

            if (k % 3 == 1) {
                td.attr("colspan", "5");
                tr.appendTo(table);
            }
            else if (k % 3 == 2) {
                td.attr("colspan", "3");
                tr.appendTo(table);
            }

            cms = orderTemplate[i].MaterialCategory;
            break;
        }
    }

    FilterMaterialDdl(cms, $("#popOrderDetail #MaterialId"));

    $("#tableDetail").find(".formular").each(function (i, e) {
        for (var i in orderTemplate) {
            if (orderTemplate[i].id == $('#Category').val()) {

                for (var j in orderTemplate[i].fields) {
                    var fieldId = FormatFieldsName("f" + orderTemplate[i].id + orderTemplate[i].fields[j].id);

                    if (fieldId == $(this).attr("id")) {
                        var formular = orderTemplate[i].fields[j].formular;
                        var fieldPrefix = FormatFieldsName("#f" + orderTemplate[i].id);

                        var condiateFields = formular.replace(/\+/g, "*").replace(/\-/g, "*").replace(/\//g, "*").replace(/\(/g, "*").replace(/\)/g, "*")
                            .replace(/\=/g, "*").replace(/\?/g, "*").replace(/\:/g, "*").replace(/\"/g, "*").replace(/\'/g, "*")
                            .replace(/\>/g, "*").replace(/\</g, "*").replace(/\!/g, "*").split("*");


                        var fields = [];

                        $(condiateFields).each(function (vv, v) {
                            $(orderTemplate[i].fields).each(function (x, y) {
                                if (v == y.id) {
                                    fields.push(v);
                                }
                            });
                        });

                        for (var s in fields) {
                            fields[s] = fields[s].replace(/\(/g, "");
                            fields[s] = fields[s].replace(/\)/g, "");

                            if ($(fieldPrefix + fields[s])[0].type != 'select-one') {
                                $(fieldPrefix + fields[s]).inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
                            }

                            $(fieldPrefix + fields[s]).change(function () {
                                var canCalculate = true;
                                for (var s in fields) {
                                    var fieldValue = $(fieldPrefix + fields[s]).val();
                                }
                                if (canCalculate) {
                                    var cresult = 1;
                                    var cresultString = formular;

                                    for (var s in fields) {
                                        var reg = "/" + fields[s] + "/g";

                                        var fieldValue = $(fieldPrefix + fields[s]).val();

                                        cresultString = cresultString.replace(eval(reg), fieldValue)

                                        //cresult = cresult * parseFloat(fieldValue);
                                    }

                                    try {
                                        eval("cresult=" + cresultString);
                                        console.log(cresultString);
                                        $(e).val(FixFourDecimal(cresult));
                                        $(e).change();
                                    }
                                    catch (ee) {

                                    }
                                }
                                else {
                                    $(e).val("");
                                    $(e).change();
                                }
                            });
                        }
                    }
                }
            }
        }
    });


    $("#tableDetail").find(".isPriceFactor").change(function (i, e) {

        var result = 1;
        var canCalculate = true;
        $("#tableDetail").find(".isPriceFactor").each(function (ii, ee) {
            var v = $(ee).val();
            if (v == "" || isNaN(v)) {
                canCalculate = false;
                return;
            }
            else {
                result = result * parseFloat(v);
            }
        });

        priceFactor = result;
        $("#Price").change();
    });

    $("#tableDetail").find(".isStockFactor").change(function (i, e) {

        var result = 1;
        var canCalculate = true;
        $("#tableDetail").find(".isStockFactor").each(function (ii, ee) {
            var v = $(ee).val();
            if (v == "" || isNaN(v)) {
                canCalculate = false;
                return;
            }
            else {
                result = result * parseFloat(v);
            }
        });

        stockFactor = result;
        $("#Price").change();
    });

}

function OpenPriceTip() {
    if (!$("#Category").val()) {
        alert("请选择业务类型");
    }
    else {
        $('#divPriceTip').dialog('open');
    }
}

function addDetail() {
    ClearErrorMsg();

    divTechnics.empty();

    $("#Guid").val("");
    $("#Id").val("");
    $("#ReportCategory").val();
    $("#Category option:first").prop("selected", 'selected');
    $('#popOrderDetail input[type=text]').val("");
    $('#popOrderDetail select').val("");
    $('#popOrderDetail textarea').val("");
    $('#popOrderDetail').dialog('open');

    $("#popOrderDetail #FactoryNo").val("").select2();
    $("#popOrderDetail #Category").val("").select2();

    CategoryChange();

    resetPriceFactor();

    $("#popOrderDetail #MaterialId").val("");
    $("#popOrderDetail #MaterialId").change();
    FilterMaterialDdl(null, $("#popOrderDetail #MaterialId"));
}

function CalculatePrice() {
    var amount = $("#popOrderDetail #Amount").val();
    var number = $("#popOrderDetail #Number").val();

    if (!isNaN(amount) && !isNaN(number)) {
        $("#popOrderDetail #Price").val(FixFourDecimal(parseFloat(amount) / parseFloat(number)));
    }
}

function CalculatePriceFactory() {
    var amount = $("#popOrderDetail #FactoryAmount").val();
    var number = $("#popOrderDetail #FactoryNumber").val();

    if (!isNaN(amount) && !isNaN(number)) {
        $("#popOrderDetail #FactoryPrice").val(FixFourDecimal(parseFloat(amount) / parseFloat(number)));
    }
}

function newId() {
    var guid = "g";
    for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
            guid += "";
    }
    return guid;
}

function saveDetail() {
    ClearErrorMsg("popOrderDetail");

    if (!checkRequired("popOrderDetail")) {
        return;
    }

    var factoryInfoCheck = true;
    if ($("#popOrderDetail #FactoryNo").val()) {

        if (!$("#FactoryAmount").val()) {
            $("#FactoryAmount").addClass("redBorder");
            factoryInfoCheck = false;

        }
    }

    if (!factoryInfoCheck) {

        SetErrorMsg("请填写外协金额。如果不需要外协加工，请不要填写任何外协信息。", "popOrderDetail");
        return;
    }

    if ($("#FactoryNumber").val() != "" || $("#FactoryPrice").val() != "" || $("#FactoryAmount").val() != "" || $("#FactoryMemo").val() != "") {
        if ($("#popOrderDetail #FactoryNo").val() == "") {
            SetErrorMsg("请选择外协商。如果不需要外协加工，请不要填写任何外协信息。", "popOrderDetail");
            return;
        }
    }

    CalcPopUpStockNumber();

    var detail = GetDetailDetail();

    var detailExisted = false;
    for (var i = 0; i < orderDetails.length; i++) {
        if (orderDetails[i].Guid == detail.Guid) {
            orderDetails[i] = detail;
            detailExisted = true;
            break;
        }
    }
    if (!detailExisted) {
        orderDetails.push(detail);
    }

    generateDetailTable();
    calcMarketAmount();


    $("#popOrderDetail").dialog("close");
}

function generateDetailTable() {
    var tBody = $("#tbodyDetail");
    tBody.empty();

    var tr, td, a;

    $(orderDetails).each(function (i, v) {
        tr = $("<tr id='" + v.Guid + "'></tr>");

        td = $("<td>" + v.Category + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.OrderName + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.MaterialName + "</td>");
        td.appendTo(tr);

        td = $("<td>" + getUnitNameById(v.PriceUnitId) + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.TechnicText + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.DetailText + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Memo + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Number + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Price + "</td>");
        td.appendTo(tr);

        td = $("<td>" + v.Amount + "</td>");
        td.appendTo(tr);

        if (isOrderAdd) {
            td = $("<td>" + v.FactoryName + "</td>");
            td.appendTo(tr);
        }

        td = $("<td></td>");
        a = $("<a href='#' onclick='editDetail(this)'>编辑</a>")
        a.appendTo(td);
        a = $("<a style='margin-left:10px' href='#' onclick='deleteDetail(this)'>删除</a>")
        a.appendTo(td);
        td.appendTo(tr);
        tr.appendTo(tBody);
    });
}

function editDetail(t) {
    ClearErrorMsg();

    $('#popOrderDetail input[type=text]').val("");
    $('#popOrderDetail textarea').val("");

    var guid = $($(t).parent().parent()).attr("id");
    $("#Guid").val(guid);

    $(orderDetails).each(function (i, v) {
        if (guid == v.Guid) {
            $("#popOrderDetail #OrderName").val(v.OrderName);
            $("#popOrderDetail #Category").val(v.Category).select2();
            $("#popOrderDetail #Number").val(v.Number);
            $("#popOrderDetail #StockNumber").val(v.StockNumber);
            $("#popOrderDetail #Price").val(v.Price);
            $("#popOrderDetail #Amount").val(v.Amount);
            $("#popOrderDetail #Memo").val(v.Memo);
            $("#popOrderDetail #Id").val(v.Id);
            $("#popOrderDetail #MaterialId").val(v.MaterialId).select2();
            $("#popOrderDetail #PriceUnitId").val(v.PriceUnitId);
            $("#popOrderDetail #FactoryNo").val(v.FactoryNo).select2();
            //$("#popOrderDetail #FactoryNo").val(v.FactoryNo).trigger("change");             
            $("#popOrderDetail #FactoryNumber").val(v.FactoryNumber);
            $("#popOrderDetail #FactoryPrice").val(v.FactoryPrice);
            $("#popOrderDetail #FactoryAmount").val(v.FactoryAmount);
            $("#popOrderDetail #FactoryMemo").val(v.FactoryMemo);

            CategoryChange();
            SetDetailDetail(v.Detail);
            resetPriceFactor();

            if (v.MaterialId > 0) {
                SetPopDetailMaterialTechnics(v.MaterialId);
            }

            return false;
        }
    });

    $('#popOrderDetail').dialog('open');
}

function deleteDetail(t) {
    ClearErrorMsg();
    $('#popOrderDetail input[type=text]').val("");

    var guid = $($(t).parent().parent()).attr("id");


    for (var i = 0; i < orderDetails.length; i++) {
        if (orderDetails[i].Guid == guid) {
            orderDetails.splice(i, 1);
            break;
        }
    }

    generateDetailTable();
    calcMarketAmount();
}

function calcMarketAmount() {
    var MarketAmount = 0;

    $(orderDetails).each(function (i, v) {
        MarketAmount += parseFloat(v.Amount);
    });

    if ($("#FeeInstallation").val() && !isNaN($("#FeeInstallation").val())) {
        MarketAmount += parseFloat($("#FeeInstallation").val());
    }
    if ($("#FeeDelivery").val() && !isNaN($("#FeeDelivery").val())) {
        MarketAmount += parseFloat($("#FeeDelivery").val());
    }
    if ($("#FeeDesign").val() && !isNaN($("#FeeDesign").val())) {
        MarketAmount += parseFloat($("#FeeDesign").val());
    }
    if ($("#FeeOther").val() && !isNaN($("#FeeOther").val())) {
        MarketAmount += parseFloat($("#FeeOther").val());
    }

    $("#MarketAmount").val(FixTwoDecimal(MarketAmount));

    calcRealAmount();
}



function OpenPriceHistory() {

    var tbody = $("#priceHistoryList");
    tbody.empty();

    $.ajax({
        url: "/Order/GetOrderHistoryByCategoryAndCustomer",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        data: { CustomerNo: $("#CustomerNo").val(), CategoryNo: $("#Category").val() },
        success: function (result) {
            if (result.code == 0) {
                $('#divPriceHistory').dialog('open');

                var tr;
                var td;

                for (var r in result.data) {

                    tr = $("<tr></tr>");

                    td = $("<td></td>");
                    td.html(result.data[r].CustomerShortName);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].TransactionDateString);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].Category);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].DetailText);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].Price);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].Memo);
                    td.appendTo(tr);

                    tr.appendTo(tbody);
                }
            }
            else {
            }
        },
        error: function (e) {
        }
    });
}

function OpenPriceHistoryFactory() {

    var tbody = $("#priceHistoryListFactory");
    tbody.empty();

    $.ajax({
        url: "/FactoryOrder/GetOrderHistoryByCategoryAndFactory",
        type: 'GET',
        cache: false,
        dataType: 'json',
        async: false,
        data: { FactoryNo: $("#popOrderDetail #FactoryNo").val(), CategoryNo: $("#Category").val() },
        success: function (result) {
            if (result.code == 0) {
                $('#divPriceHistoryFactory').dialog('open');

                var tr;
                var td;

                for (var r in result.data) {

                    tr = $("<tr></tr>");

                    td = $("<td></td>");
                    td.html(result.data[r].FactoryName);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].TransactionDateString);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].Category);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].DetailText);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].Price);
                    td.appendTo(tr);

                    td = $("<td></td>");
                    td.html(result.data[r].Memo);
                    td.appendTo(tr);

                    tr.appendTo(tbody);
                }
            }
            else {
            }
        },
        error: function (e) {
        }
    });
}

function newCustomer() {
    ClearErrorMsg();
    $("#CustomerFullName").val("");
    $('#divCustomer').dialog('open');
}

function newContact() {

    if (!$("#CustomerNo").val()) {
        return alert("请先选择客户");
    }

    $("#ContactName").val("");
    $("#Phone").val("");
    $("#tdCustomerName").text($("#CustomerNo").find("option:selected").text());

    ClearErrorMsg();
    $('#divContact').dialog('open');
}

function SaveContact() {

    if (checkRequired('divContact', 'errorMessage') == false) {
        return;
    }

    var data = {};
    data.CustomerNo = $("#CustomerNo").val();
    data.ContactName = $("#ContactName").val();

    if ($("#Phone").val().substr(0, 1) == "1") {
        data.Mobile = $("#Phone").val();
    }
    else {
        data.Phone = $("#Phone").val();
    }

    $.ajax({
        url: "/Contact/Add",
        type: 'POST',
        cache: false,
        data: data,
        success: function (result) {
            if (result.code == 0) {
                $('#divContact').dialog('close');
                $("<option value='" + result.data.ContactNo + "'>" + result.data.ContactName + " " + $("#Phone").val() + "</option>").appendTo($("#ContactNo"));
                $("#ContactNo").val(result.data.ContactNo);

                $("#Contact").val($("#ContactName").val() + " " + $("#Phone").val());
            }
            else {
                SetErrorMsg(result.message, "divContact");
            }
        },
        error: function (e) {
            SetErrorMsg("添加联系人失败，可能是您的权限不足", "divContact");
        }
    })
}

function FillMaterialDdl(data) {
    var selMaterial = $("#popOrderDetail #MaterialId");
    $("<option value=''>&nbsp;</option>").appendTo(selMaterial);
    var optGroup, opt;
    $(data).each(function (i, v) {

        optGroup = $("<optgroup></optgroup>").attr("data-id", v.Id);
        optGroup.attr("label", v.Name);

        $(v.List).each(function (i, v) {
            opt = $("<option></option>");
            opt.text(v.Name);
            opt.attr("value", v.Id);
            opt.appendTo(optGroup);
        });

        optGroup.appendTo(selMaterial);

    });
}

function FindMaterialName(id) {

    var result = "";

    $(allMaterials).each(function (i, v) {

        $(v.List).each(function (x, y) {

            if (y.Id == id) {
                result = y.Name;
                return false;
            }
        });

    });

    return result;
}

function resetPriceFactor() {
    var result = 1;
    var canCalculate = true;
    $("#tableDetail").find(".isPriceFactor").each(function (ii, ee) {
        var v = $(ee).val();
        if (v == "" || isNaN(v)) {
            canCalculate = false;
            return;
        }
        else {
            result = result * parseFloat(v);
        }
    });

    priceFactor = result;

    result = 1;
    canCalculate = true;
    $("#tableDetail").find(".isStockFactor").each(function (ii, ee) {
        var v = $(ee).val();
        if (v == "" || isNaN(v)) {
            canCalculate = false;
            return;
        }
        else {
            result = result * parseFloat(v);
        }
    });

    stockFactor = result;
}

function getSailPrice(materialId, price) {

    var realPrice = 0;
    $(allMaterials).each(function (i, v) {
        $(v.List).each(function (x, y) {
            if (materialId == y.Id) {
                realPrice = price ? price : y.SailPrice;
                $("#popOrderDetail #hiddenSailPrice").val(realPrice);
                $("#popOrderDetail #PriceUnitId").val(y.PriceUnitId);
                $("#popOrderDetail #Price").val(realPrice == 0 ? "" : realPrice);
                $("#popOrderDetail #Price").change();
                return false;
            }
        });
    });
}

function getFactoryPrice(materialId, price) {

    var realPrice = 0;

    $(allMaterials).each(function (i, v) {

        $(v.List).each(function (x, y) {
            if (y.Id == materialId) {

                realPrice = price ? price : y.FactoryPrice;
                $("#popOrderDetail #hiddenFactoryPrice").val(realPrice);

                var totalPrice = realPrice + GetPopTechnicFactoryPrice();
                $("#popOrderDetail #FactoryPrice").val(totalPrice == 0 ? "" : totalPrice);
                $("#popOrderDetail #FactoryPrice").change();
                return false;
            }
        });

    });
}

function getUnitNameById(id) {
    var unitName = "";
    $(allUnits).each(function (i, v) {
        if (id == v.ItemValue) {
            unitName = v.ItemText;
            return false;
        }
    });

    return unitName;
}

function QueryFactoryPrice() {

    var materialId = $("#popOrderDetail #MaterialId").val();
    if ($('#popOrderDetail #FactoryNo').val()) {

        if (materialId) {
            $.ajax({
                url: "/FactoryOrder/GetFactoryPrice",
                type: 'GET',
                cache: false,
                data: { FactoryNo: $('#popOrderDetail #FactoryNo').val(), MaterialId: materialId },
                success: function (result) {
                    if (result.code == 0) {
                        getFactoryPrice(materialId, result.price);
                    }
                    else {
                        getFactoryPrice(materialId, 0);
                    }

                },
                error: function (e) {
                    getFactoryPrice(materialId, 0);
                }
            });
        }
        else {

        }
    }
    else {
        $("#FactoryNumber").val("");
        $("#FactoryPrice").val("");
        $("#FactoryAmount").val("");
        $("#FactoryMemo").val("");
    }
}

function GetFactoryName(factoryNo) {
    var result = "";
    $(allFactories).each(function (i, v) {
        if (v.ItemValue == factoryNo) {
            result = v.ItemText;
            return false;
        }
    });

    return result;
}

function addFactoryOrderDetailRow(rowData) {

    if (rowData == null) {
        rowData = {
            Id: '0',
            OrderName: '',
            MaterialId: '',
            PriceUnitId: '',
            Width: '',
            Height: '',
            Amount: '',
            Number: '',
            Area: '',
            Price: '',
            DetailText: '',
            FactoryNo: '',
            Price: '',
            Category: '',
            Memo: '',
            TechnicText: '',
            Technic: '[]'
        };
    }

    var tBody = $("#simpleOrderTr");
    var tr, td, input, select, hidden;

    tr = $("<tr></tr>");

    var hiddenId = $("<input type='hidden' id='Id'></input>").val(rowData.Id);
    var hiddenTechnic = $("<input type='hidden' id='hiddenTechnic'></input>").val(rowData.Technic);
    var hiddenFactoryPrice = $("<input type='hidden' id='hiddenFactoryPrice'></input>").val("0");
    td = $("<td></td>");
    hiddenId.appendTo(td);
    hiddenTechnic.appendTo(td);
    hiddenFactoryPrice.appendTo(td);
    td.appendTo(tr);

    select = $("<select id='FactoryNo' class='FactoryNo select2'></select>");
    $("<option value=''>&nbsp;</option>").appendTo(select);
    $(allFactories).each(function (i, v) {
        $("<option value='" + v.ItemValue + "'>" + v.ItemText + "</option>").appendTo(select);
    });
    td = $("<td class='col-factory'></td>");
    select.appendTo(td);
    td.appendTo(tr);

    select = $("#FactoryCategory").clone();
    select.attr("id", "FactoryCategoryId");
    select.addClass("select2");

    select.val(rowData.FactoryCategory);

    td = $("<td></td>");
    select.appendTo(td);

    td.appendTo(tr);

    input = $("<input type='text' id='FactoryOrderName' value='" + rowData.OrderName + "'></input>");
    td = $("<td></td>");
    $("<input type='hidden' id='FactoryReportCategory'></input>").appendTo(td);
    input.appendTo(td);
    td.appendTo(tr);

    td = $("<td></td>");
    select = $("#popOrderDetail #MaterialId").clone();
    select.attr("id", "MaterialId");
    select.val(rowData.MaterialId);
    select.appendTo(td);
    td.appendTo(tr);

    td = $("<td></td>");
    hidden = $("<input type='hidden' id='ValuationType' />");
    select = $("<select id='PriceUnitId'></select>");

    $("<option value=''>&nbsp;</option>").appendTo(select);
    $(allUnits).each(function (i, v) {
        if (v.ItemValue == rowData.PriceUnitId) {
            $("<option selected value='" + v.ItemValue + "'>" + v.ItemText + "</option>").appendTo(select);
            hidden.val(findValuationTypeByUnit(rowData.PriceUnitId));
        }
        else {
            $("<option value='" + v.ItemValue + "'>" + v.ItemText + "</option>").appendTo(select);
        }
    });
    hidden.appendTo(td);
    select.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Technic' readonly='readonly' value='" + rowData.TechnicText + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Width' class='width' value='" + rowData.Width + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Height' class='width' value='" + rowData.Height + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Number' class='number' value='" + rowData.Number + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Area' class='width' value='" + rowData.Area + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Price' class='price' value='" + rowData.Price + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Amount' class='amount' value='" + rowData.Amount + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    input = $("<input type='text' id='Memo' value='" + rowData.Memo + "'></input>");
    td = $("<td></td>");
    input.appendTo(td);
    td.appendTo(tr);

    tr.appendTo(tBody);

    bindEvents();
}

function copyFactoryDetail() {
    var trs = $("#simpleOrderTr .tr-selected");
    if ($(trs).length == 0) {
        alert("请先选择要复制的行");
        return;
    }

    var tr = trs.clone();

    var td = tr.find("td:eq(1)");
    var sel = td.find("select");
    td.empty();
    $(sel).appendTo(td);

    var td2 = tr.find("td:eq(2)");
    var sel2 = td2.find("select");
    td2.empty();
    $(sel2).appendTo(td2);

    var td4 = tr.find("td:eq(4)");
    var sel4 = td4.find("select");
    td4.empty();
    $(sel4).appendTo(td4);

    $(tr).appendTo($("#simpleOrderTr"));

    $($("#simpleOrderTr tr").last()).attr("id", "0");
    $($("#simpleOrderTr tr").last()).removeClass("tr-selected");

    bindEvents();

}

function deleteFactoryDetail() {

    var trs = $("#simpleOrderTr .tr-selected");
    if ($(trs).length == 0) {
        alert("请先选择要删除的行");
        return;
    }

    $(trs).remove();

    calcRealAmount();
}

function bindEvents() {

    $("#simpleOrderDetail .price").inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
    $("#simpleOrderDetail .width").inputmask({ 'mask': "9{0,9}[.9{0,4}]", greedy: false });
    $("#simpleOrderDetail .amount").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false });
    $("#simpleOrderDetail .number").inputmask({ 'mask': "9{0,9}[.9{0,2}]", greedy: false }); 

    // select a row
    $("#simpleOrderDetail td").unbind("click").click(function () {
        $("#simpleOrderDetail .tr-selected").removeClass("tr-selected");
        $(this).parent().addClass("tr-selected");
    });

    $("#simpleOrderDetail #FactoryCategoryId").unbind("change").change(function () {
        FactoryCategoryChange(this);
    });

    $("#simpleOrderDetail #MaterialId,#simpleOrderDetail #FactoryNo").unbind("change").change(function () {
        FactoryMaterialChange(this);
    });

    $("#simpleOrderDetail #PriceUnitId").unbind("change").change(function () {
        UnitChange(this);
    });

    $("#simpleOrderDetail #Width,#simpleOrderDetail #Height,#simpleOrderDetail #Number").unbind("change").change(function () {
        WidthHeightChange(this);
    });

    $("#simpleOrderDetail #Price,#simpleOrderDetail #Area,#simpleOrderDetail #FactoryPrice").unbind("change").change(function () {
        SimplePriceChange($(this).parent().parent());
    });

    //$("#simpleOrderDetail #Amount").unbind("keyup").keyup(function () {
    //    //SimpleAmountChange($(this).parent().parent());
    //});
    //$("#simpleOrderDetail #Amount").unbind("blur").blur(function () {
    //    //SimpleAmountChange($(this).parent().parent());
    //});
    $("#simpleOrderDetail #Amount").unbind("change").change(function () {
        SimpleAmountChange($(this).parent().parent());
    });

    // when the column is narrow,it is usefual to show the tip
    $("#simpleOrderDetail #OrderName,#simpleOrderDetail #Memo,#simpleOrderDetail #Technic").hover(function () {
        $(this).attr("title", $(this).val());
    });

    $("#simpleOrderDetail #Technic").unbind("click").click(function () {
        SetSimpleMaterialTechnics($(this));
    });

    $(".select2").select2();
}

function FactoryCategoryChange(c) {

    $(c).parent().parent().find("#MaterialId").val("");

    var cv = $(c).val();
    var reportCategory;
    var cms = null;
    if (cv) {
        $(orderTemplate).each(function (i, v) {
            if (v.id == cv) {
                $(c).parent().parent().find("#FactoryReportCategory").val(v.reportCategory);
                cms = v.MaterialCategory;
                return false;
            }
        });
    }

    FilterMaterialDdl(cms, $(c).parent().parent().find("#MaterialId"));

    $(c).parent().parent().find("#MaterialId").change();
}

function UnitChange(u) {
    var unitId = $(u).val();
    if (unitId) {
        $(allUnits).each(function (i, v) {
            if (v.ItemValue == unitId) {
                $(u).parent().parent().find("#ValuationType").val(v.Addition1);
                return false;
            }
        });
    }
    else {
        $(u).parent().parent().find("#ValuationType").val("3");
    }

    SimplePriceChange($(u).parent().parent());
}

function SimplePriceChange(v) {
    var price, number, amount, stockNumber, width, height, area, factoryAmount, valuationType;

    price = $(v).find("#Price").val();
    number = $(v).find("#Number").val();
    area = $(v).find("#Area").val();
    width = $(v).find("#Width").val();
    height = $(v).find("#Height").val();
    valuationType = $(v).find("#ValuationType").val();
    amount = "";


    if (number && !isNaN(number)) {
        if (price && !isNaN(price)) {
            console.log(valuationType);
            if (valuationType == "1") {
                if (area && !isNaN(area)) {
                    amount = FixTwoDecimal(parseFloat(price) * parseFloat(area));

                }
            }
            else if (valuationType == "2") {

                if (width && !isNaN(width)) {
                    amount = FixTwoDecimal(parseFloat(price) * parseFloat(number) * parseFloat(width));

                }
            }
            else if (valuationType == "4") {
                if (width && !isNaN(width) && height && !isNaN(height)) {
                    if (widthUnit == "m") {
                        amount = FixTwoDecimal(parseFloat(price) * parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height)));

                    }
                    else if (widthUnit == "cm") {
                        amount = FixTwoDecimal(parseFloat(price) * parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height)) / 100.0);

                    }
                    else if (widthUnit == "mm") {
                        amount = FixTwoDecimal(parseFloat(price) * parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height)) / 1000.0);

                    }
                }
            }
            else {
                amount = FixTwoDecimal(parseFloat(price) * parseFloat(number));

            }
        }

        $(v).find("#Amount").val(amount);
    }


}

function WidthHeightChange(input) {
    var row = $(input).parent().parent();

    var width = parseFloat(row.find("#Width").val());
    var height = parseFloat(row.find("#Height").val());
    var valuationType = row.find("#ValuationType").val();
    var number = parseFloat(row.find("#Number").val());
    if (valuationType == "1" && !isNaN(width) && !isNaN(height) && !isNaN(number)) {
        if (widthUnit == "m") {
            row.find("#Area").val(changeFourDecimal(width * height * number));
        }
        else if (widthUnit == "cm") {
            row.find("#Area").val(changeFourDecimal(width * height * number / 10000.0));
        }
        else if (widthUnit == "mm") {
            row.find("#Area").val(changeFourDecimal(width * height * number / 1000000.0));
        }
    }

    SimplePriceChange(row);
}



function GetOrderFactories() {
    var result = [];
    $("#simpleOrderTr tr").each(function (i, v) {
        var factoryNo = $(v).find("#FactoryNo").val();

        var d = {
            FactoryNo: factoryNo,
            MaterialId: $(v).find("#MaterialId").val(),
            Number: $(v).find("#Number").val(),
            Price: $(v).find("#Price").val(),
            Amount: $(v).find("#Amount").val(),
            Category: $(v).find("#FactoryCategoryId").val(),
            ReportCategory: $(v).find("#FactoryReportCategory").val(),
            OrderName: $(v).find("#FactoryOrderName").val(),
            Detail: JSON.stringify(GetFactoryDetailObject(v)),
            DetailText: GetFactoryDetailText(v),
            PriceUnitId: $(v).find("#PriceUnitId").val(),
            TemplateId: $("#TemplateId").val(),
            Memo: $(v).find("#Memo").val(),
            Technic: $(v).find("#hiddenTechnic").val(),
            TechnicText: $(v).find("#Technic").val()
        };

        formatOrderDetailObj(d);
        result.push(d);
    });

    return result;
}

function GetFactoryDetailObject(tr) {
    var result = {};
    result.Width = $(tr).find("#Width").val();
    result.Height = $(tr).find("#Height").val();
    result.Area = $(tr).find("#Area").val();
    result.PriceUnitId = $(tr).find("#PriceUnitId").val();

    return result;
}

function GetFactoryDetailText(tr) {
    var result = "";
    var obj = GetFactoryDetailObject(tr);
    if (obj.Width) {
        result += "宽: " + obj.Width + widthUnit + ", ";
    }
    if (obj.Height) {
        result += "高: " + obj.Height + widthUnit + ", ";
    }
    if (obj.Area) {
        result += "面积: " + obj.Area + "㎡, ";
    }

    if (result.length > 0) {
        result = result.substr(0, result.length - 2);
    }

    return result;
}

function FactoryMaterialChange(m) {

    var materialId = $(m).parent().parent().find("#MaterialId").val();

    $(m).parent().parent().find("#hiddenTechnic").val("[]");
    $(m).parent().parent().find("#Technic").val("");

    if (materialId) {

        if ($(m).parent().parent().find('#FactoryNo').val()) {

            $.ajax({
                url: "/FactoryOrder/GetFactoryPrice",
                type: 'GET',
                cache: false,
                data: { FactoryNo: $(m).parent().parent().find('#FactoryNo').val(), MaterialId: materialId },
                success: function (result) {
                    if (result.code == 0) {
                        getSimpleFactoryLocalPrice(m, materialId, result.price);
                    }
                    else {
                        getSimpleFactoryLocalPrice(m, materialId, 0);
                    }

                },
                error: function (e) {
                    getSimpleFactoryLocalPrice(m, materialId, 0);
                }
            });
        }
        else {
            getSimpleFactoryLocalPrice(m, materialId, 0);
        }
    }
}

function getSimpleFactoryLocalPrice(m, materialId, price) {

    var tr = $(m).parent().parent();
    var realPrice = 0;

    $(allMaterials).each(function (i, v) {

        $(v.List).each(function (x, y) {

            if (y.Id == materialId) {
                tr.find("#PriceUnitId").val(y.PriceUnitId);
                tr.find("#ValuationType").val(y.PriceType);

                realPrice = price == 0 ? y.FactoryPrice : price;

                tr.find("#hiddenFactoryPrice").val(realPrice);

                var totalPrice = realPrice + GetTotalTechnicPrice(m);
                tr.find("#Price").val(totalPrice == 0 ? "" : totalPrice);

                WidthHeightChange(m);
                return false;
            }
        });

    });
}

function setSimpleFactoryPrice(m) {

    var tr = $(m).parent().parent();
    var realPrice = 0;

    var technicPrice = GetTotalTechnicPrice(m);

    var totalPrice = parseFloat(tr.find("#hiddenFactoryPrice").val()) + technicPrice;

    tr.find("#Price").val(totalPrice == 0 ? "" : totalPrice);

    WidthHeightChange(m);
}

function GetTotalTechnicPrice(m) {
    var totalTechnicPrice = 0;
    var selecteTechnics = $(m).parent().parent().find("#hiddenTechnic").val();

    $(JSON.parse(selecteTechnics)).each(function (i, v) {
        totalTechnicPrice += parseFloat(v.FactoryPrice);
    });

    return totalTechnicPrice;
}

function getUnitNameById(id) {
    var unitName = "";
    $(allUnits).each(function (i, v) {
        if (id == v.ItemValue) {
            unitName = v.ItemText;
            return false;
        }
    });

    return unitName;
}

function CreateTechnicDiv(v) {
    var div = $("<div></div>").attr("title", "销售价: " + v.SailPrice + " 外协价: " + v.FactoryPrice).attr("data-id", v.TechnicId).attr("data-sprice", v.SailPrice).attr("data-fprice", v.FactoryPrice).attr("data-name", v.Name).html(v.Name).click(function () {
        if ($(this).hasClass("selected")) {
            $(this).removeClass("selected");
        }
        else {
            $(this).addClass("selected");
        }
        PopTechnicChanged();
    });

    return div;
}

function CreateSimpleTechnicDiv(v) {
    var div = $("<div></div>").attr("title", "外协价: " + v.FactoryPrice).attr("data-id", v.TechnicId).attr("data-sprice", v.SailPrice).attr("data-fprice", v.FactoryPrice).attr("data-name", v.Name).html(v.Name).click(function () {
        if ($(this).hasClass("selected")) {
            $(this).removeClass("selected");
        }
        else {
            $(this).addClass("selected");
        }
    });

    return div;
}

function SetPopTechnics(technics) {

    var guid = $("#Guid").val();

    divTechnics.empty();

    $(technics).each(function (i, v) {
        console.log(divTechnics);
        CreateTechnicDiv(v).appendTo(divTechnics);
    });
}

function SetPopDetailMaterialTechnics(materialId) {

    divTechnics.empty();

    if (!materialId) {
        return;
    }

    $.ajax({
        url: "/Order/GetMaterialTechnicsWithCFPrice",
        type: 'GET',
        cache: false,
        data: { MaterialId: materialId, CustomerNo: $("#CustomerNo").val(), FactoryNo: $("#popOrderDetail #FactoryNo").val() },
        success: function (result) {
            if (result.code == 0) {

                var guid = $("#Guid").val();

                $(result.technics).each(function (i, v) {
                    CreateTechnicDiv(v).appendTo(divTechnics);
                });

                $(orderDetails).each(function (i, v) {
                    if (guid == v.Guid) {

                        if (v.Technic != "" && v.Technic != null) {
                            $(JSON.parse(v.Technic)).each(function (i, v) {
                                var tc = $(divTechnics).find("div[data-id='" + v.TechnicId + "']");
                                if (tc.length == 0) {
                                    CreateTechnicDiv(v).appendTo(divTechnics);
                                }
                                else {
                                    tc.addClass("selected");
                                }
                            });
                        }
                        return false;
                    }
                });

                if (result.cPrice) {
                    $("#popOrderDetail #hiddenSailPrice").val(result.cPrice);
                }
                else {
                    $("#popOrderDetail #hiddenSailPrice").val(getPriceFromLocal(materialId));
                }

                if (result.fPrice) {
                    $("#popOrderDetail #hiddenFactoryPrice").val(result.fPrice);
                }
                else {
                    $("#popOrderDetail #hiddenFactoryPrice").val(getFactoryPriceFromLocal(materialId));
                }

            }
        },
        error: function (e) {
        }
    });
}

function SetSimpleMaterialTechnics(input) {

    currentSimpleRow = $(input).parent().parent();

    divSimpleTechnics.empty();
    $("#divPopTechnicNoData").hide();
    $("#divPopTechnic #btnSaveTechnic").show();

    var materialId = currentSimpleRow.find("#MaterialId").val();

    if (!materialId) {
        alert("请先选择材料");
        return;
    }

    $.ajax({
        url: "/Order/GetMaterialTechnicsWithCFPrice",
        type: 'GET',
        cache: false,
        data: { MaterialId: materialId, FactoryNo: $(currentSimpleRow).find("#FactoryNo").val() },
        success: function (result) {
            if (result.code == 0) {

                var guid = $("#Guid").val();

                divSimpleTechnics.empty();

                $(result.technics).each(function (i, v) {
                    CreateSimpleTechnicDiv(v).appendTo(divSimpleTechnics);
                });

                var selecteTechnics = $(currentSimpleRow).find("#hiddenTechnic").val();
                console.log(selecteTechnics);
                $(JSON.parse(selecteTechnics)).each(function (i, v) {
                    var tc = $(divSimpleTechnics).find("div[data-id='" + v.TechnicId + "']");
                    if (tc.length == 0) {
                        CreateSimpleTechnicDiv(v).appendTo(divSimpleTechnics);
                    }
                    else {
                        tc.addClass("selected");
                    }
                });

                if (result.fPrice) {
                    $(currentSimpleRow).find("#hiddenFactoryPrice").val(result.fPrice);
                }
                else {
                    $(currentSimpleRow).find("#hiddenFactoryPrice").val(getFactoryPriceFromLocal(materialId));
                }

                if (divSimpleTechnics.find("div").length == 0) {
                    $("#divPopTechnicNoData").show();
                    $("#divPopTechnic #btnSaveTechnic").hide();
                }

                $("#divPopTechnic").dialog("open");
            }
        },
        error: function (e) {
        }
    });
}

function SaveSimpleTechnics() {
    currentSimpleRow.find("#hiddenTechnic").val(JSON.stringify(GetSimpleSelectedTechnics()));
    currentSimpleRow.find("#Technic").val(GetSimpleSelectedTechnicsText());

    setSimpleFactoryPrice(currentSimpleRow.find("#Technic"));

    $("#divPopTechnic").dialog("close");
}

function GetPopTechnicSailPrice() {
    var technicPrices = 0;

    $(divTechnics.find("div")).each(function (i, v) {
        if ($(v).hasClass("selected")) {
            technicPrices += FixFourDecimal($(v).attr("data-sprice"));
        }
    });

    return technicPrices;
}

function GetPopTechnicFactoryPrice() {
    var technicFactoryPrices = 0;

    $(divTechnics.find("div")).each(function (i, v) {
        if ($(v).hasClass("selected")) {
            technicFactoryPrices += FixFourDecimal($(v).attr("data-fprice"));
        }
    });

    return technicFactoryPrices;
}

function PopTechnicChanged() {

    var totalPrice = parseFloat($("#popOrderDetail #hiddenSailPrice").val()) + GetPopTechnicSailPrice();
    $("#popOrderDetail #Price").val(totalPrice == 0 ? "" : totalPrice);
    $("#popOrderDetail #Price").change();

    if ($("#popOrderDetail #FactoryNo").val()) {
        totalPrice = parseFloat($("#popOrderDetail #hiddenFactoryPrice").val()) + GetPopTechnicFactoryPrice();
        $("#popOrderDetail #FactoryPrice").val(totalPrice == 0 ? "" : totalPrice);
        $("#popOrderDetail #FactoryPrice").change();
    }

}

function GetPopSelectedTechnics() {

    var selectedTechnics = [];
    $(divTechnics.find("div")).each(function (i, v) {
        if ($(v).hasClass("selected")) {
            selectedTechnics.push({
                TechnicId: $(v).attr("data-id"),
                Name: $(v).attr("data-name"),
                SailPrice: $(v).attr("data-sprice"),
                FactoryPrice: $(v).attr("data-fprice"),
            });
        }
    });

    return selectedTechnics;
}

function GetPopSelectedTechnicsText() {

    var selectedTechnics = [];
    $(divTechnics.find("div")).each(function (i, v) {
        if ($(v).hasClass("selected")) {
            selectedTechnics.push($(v).attr("data-name"));
        }
    });

    return selectedTechnics.join(", ");
}


function GetSimpleSelectedTechnics() {

    var selectedTechnics = [];
    $(divSimpleTechnics.find("div")).each(function (i, v) {
        if ($(v).hasClass("selected")) {
            selectedTechnics.push({
                TechnicId: $(v).attr("data-id"),
                Name: $(v).attr("data-name"),
                SailPrice: $(v).attr("data-sprice"),
                FactoryPrice: $(v).attr("data-fprice"),
            });
        }
    });

    return selectedTechnics;
}

function GetSimpleSelectedTechnicsText() {

    var selectedTechnics = [];
    $(divSimpleTechnics.find("div")).each(function (i, v) {
        if ($(v).hasClass("selected")) {
            selectedTechnics.push($(v).attr("data-name"));
        }
    });

    return selectedTechnics.join(", ");
}

function getPriceFromLocal(materialId) {

    var price = 0;
    $(allMaterials).each(function (i, v) {
        $(v.List).each(function (x, y) {
            if (materialId == y.Id) {
                price = y.SailPrice;
                return false;
            }
        });
    });

    return price;
}

function getFactoryPriceFromLocal(materialId) {
    var price = 0;
    $(allMaterials).each(function (i, v) {

        $(v.List).each(function (x, y) {
            if (y.Id == materialId) {
                price = y.FactoryPrice;
                return false;
            }
        });
    });

    return price;
}

// fix issue: select2 cannot search in jQuery UI.
(function ($) {
    $.widget("ui.dialog", $.ui.dialog, {
        open: function () {

            return this._super();
        },
        _allowInteraction: function (event) {
            return !!$(event.target).is(".select2-search__field") || this._super(event);
        }
    });
})(jQuery);