var inUploading = false;
var priceFactor = 1;
var stockFactor = 1;

$(function () {

    $(".tax-ratio").inputmask({ 'mask': "9{0,2}[.9{0,2}]", greedy: false });

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


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


    $("#btnUpload").click(function () {
        ajaxFileUpload();
    });

    $("#btnOrderMemo").click(function () {
        $('#errorMessageMemo').html('');
        $('#OrderMemo').removeClass('redBorder');
        if (checkRequired('MemoPanel', 'errorMessageMemo') == false) {
            return;
        }

        $.ajax({
            url: "/Order/AddOrderMemo",
            type: 'POST',
            cache: false,
            dataType: 'json',
            async: false,
            data: { OrderNo: $("#OrderNo").val(), Memo: $("#OrderMemo").val() },
            success: function (result) {
                if (result.code == 0) {
                    $("#OrderMemo").val("");
                    $("<tr><td>" + result.data.Addition1 + "</td><td>" + result.data.Addition2 + "</td><td>" + result.data.Addition3 + "</td></tr>").appendTo($("#dOrderMemo"));
                }
                else {
                    SetErrorMsg("保存失败", "divDetail");
                }
            },
            error: function (e) {
                SetErrorMsg("保存失败", "divDetail");
            }
        });

    });
});
//
function ShowQuotationDetail(id) {
    ClearErrorMsg();
    $("#Id").val(id);
    $.ajax({
        url: "/Order/GetQuotationDetail",
        type: 'POST',
        cache: false,
        data: { Id: id },
        success: function (result) {
            if (result.code == 0) {

                $("#dQuotationName").html(result.data.QuotationName);
                $("#dCustomer").html(result.data.CustomerName);
                $("#dContact").html(result.data.Contact);

                $("#dMarketAmount").html(result.data.MarketAmount);

                $("#dFeeDesign").html(result.data.FeeDesign);
                $("#dFeeDelivery").html(result.data.FeeDelivery);
                $("#dFeeInstallation").html(result.data.FeeInstallation);
                $("#dFeeOther").html(result.data.FeeOther);

                $("#dDiscount").html(result.data.Discount);
                $("#dAmount").html(result.data.Amount);
                $("#dCreatedTime").html(result.data.CreatedTimeString);
                $("#dQuotationDate").html(result.data.QuotationDateString);
                $("#dCreator").html(result.data.Creator);
                $("#dNumber").html(result.data.Number);
                $("#dMemo").html(result.data.Memo);
                $("#dTaxInfo").html(result.data.TaxInfo);
                $("#dHistory").html("");
                $("#dHistory").html(result.data.History);

                var orderDetails = [];

                $(result.data.QuotationDetails).each(function (i, v) {

                    eval("var d=" + v.Detail + ";");
                    orderDetails.push({
                        Id: v.Id,
                        QuotationName: v.QuotationName,
                        Detail: d,
                        DetailText: v.DetailText,
                        Category: v.Category,
                        CategoryName: v.CategoryName,
                        ReportCategory: v.ReportCategory,
                        Number: v.Number,
                        Price: v.Price,
                        MaterialName: v.MaterialName,
                        Amount: v.Amount,
                        Memo: v.Memo,
                        UnitName: v.UnitName,
                    });
                });

                FillQuotationDetailInfo(orderDetails);

                SetDetailDetail(eval("(" + result.data.Detail + ")"));


                $('#divDetail').dialog('open');
            }
            else {
                alert("获取信息失败.");
            }

        },
        error: function (e) {
            alert("获取信息失败.");
        }
    });
}

function ShowDetail(id) {
    ClearErrorMsg();
    $("#OrderNo").val(id);
    $.ajax({
        url: "/Order/GetDetail",
        type: 'POST',
        cache: false,
        data: { OrderNo: id },
        success: function (result) {
            if (result.code == 0) {
                $("#dStatus").html(result.data.StatusDescription);

                $("#dPaymentStatus").html(result.data.PaymentStatusDescription);

                $("#dPayment").html(result.data.Payment);

                $("#dOrderNo").html(result.data.OrderNo);
                $("#dOrderName").html(result.data.OrderName);
                $("#dCustomer").html(result.data.CustomerShortName);
                $("#dContact").html(result.data.Contact);
                $("#dTaxInfo").html(result.data.TaxInfo);
                if (result.data.Amount == 0) {
                    result.data.MarketAmount = "--";
                    result.data.Discount = "--";
                    result.data.Paid = "--";
                    result.data.Amount = "--";

                    $(result.data.OrderDetails).each(function (i, v) {
                        v.Price = "--";
                        v.Amount = "--";
                    });
                }

                $("#dIsInvoiced").html(result.data.IsInvoiced ? "已开票" : "未开票");

                $("#dMarketAmount").html(result.data.MarketAmount);

                $("#dFeeDesign").html(result.data.FeeDesign);
                $("#dFeeDelivery").html(result.data.FeeDelivery);
                $("#dFeeInstallation").html(result.data.FeeInstallation);
                $("#dFeeOther").html(result.data.FeeOther);

                $("#dDiscount").html(result.data.Discount);
                $("#dPaid").html(result.data.Paid);
                $("#dAmount").html(result.data.Amount);

                $("#dCreatedTime").html(result.data.CreatedTimeString);
                $("#dTransactionDate").html(result.data.TransactionDateString);
                $("#dCreator").html(result.data.Creator);
                //FillOrderDetailInfo(eval(result.data.OrderTemplate), result.data.Category);
                //SetDetailDetail(eval("(" + result.data.Detail + ")"));
                $("#dNumber").html(result.data.Number);
                $("#dExpectDeliveryDate").html(result.data.ExpectDeliveryDateString);                
                $("#dCompletionDate").html(result.data.CompletionDateString);
                $("#dMemo").html(result.data.Memo);
                $("#dDeliveryType").html(result.data.DeliveryType);
                $("#dDeliveryAddress").html(result.data.DeliveryAddress);

                GenerateWorkFlowSteps(result.data.steps);

                var table = $("#tableFactory");
                table.empty();

                $("#dHistory").html("");
                $("#dHistory").html(result.data.History);

                if (result.data.Factories.length > 0) {
                    $('<thead><tr class="title"><th style="width:160px">外协订单号</th><th style="width:160px">外协商</th></th><th>详细</th></tr></thead>').appendTo(table);
                }
                $.each(result.data.Factories, function () {
                    var tr = $("<tr></tr>");
                    $("<td><a target='_blank' href='/FactoryOrder/FactoryOrderDetailInfo?factoryOrderNo=" + this.FactoryOrderNo + "'>" + this.FactoryOrderNo + "</a></td>").appendTo(tr);
                    $("<td>" + this.FactoryName + "</td>").appendTo(tr);
                    $("<td>" + this.OrderName + "</td>").appendTo(tr);
                    tr.appendTo(table);
                });


                $("#dQueryURL").html("");
                var a = $("<a target='_blank' href='" + result.data.QueryURL + "'>" + result.data.QueryURL + "</a>").appendTo($("#dQueryURL"));
                $("#dOrderMemo").html("");
                for (var r in result.data.OrderMemos) {
                    $("<tr><td>" + result.data.OrderMemos[r].Addition1 + "</td><td>" + result.data.OrderMemos[r].Addition2 + "</td><td>" + result.data.OrderMemos[r].Addition3 + "</td></tr>").appendTo($("#dOrderMemo"));
                }

                var t = $("#tdAttachment");
                t.html("");

                for (var r in result.data.Attachments) {
                    console.log(r);
                    if (result.data.Attachments[r].Addition3 != null && result.data.Attachments[r].Addition3 != "") {                               
                        var a = $("<a class='order-detail-thumbnail' target='_blank'></a>");
                        a.css("background-image", 'url(' + result.data.Attachments[r].Addition3.split("|")[0] + ')');
                        a.attr("href", result.data.Attachments[r].Addition3.split("|")[1]);   
                        a.attr("title", result.data.Attachments[r].ItemText);
                        a.appendTo(t);                          
                    }
                }

                for (var r in result.data.Attachments) {
                    var a = $("<div><img src='" + result.data.Attachments[r].Addition1 + "' alt=''/><a href='#' style='text-decoration:underline;' onclick=\"javascript:return DownLoadFile('" + result.data.Attachments[r].ItemValue + "');\">" + result.data.Attachments[r].ItemText + "</a> (" + result.data.Attachments[r].Addition4  + " " + result.data.Attachments[r].Addition2 + ")</div>");
                    a.appendTo(t);
                }

                var orderDetails = [];

                $(result.data.OrderDetails).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,
                        Price: v.Price,
                        MaterialName: v.MaterialName,
                        Amount: v.Amount,
                        Memo: v.Memo,
                        UnitName: v.UnitName,
                    });
                });

                FillOrderDetailInfo(orderDetails);

                SetDetailDetail(eval("(" + result.data.Detail + ")"));

                SetSpanColor("divDetail");
                SetSpanColor("dDetail");
                $('#divDetail').dialog('open');
                $("#btnClose").focus();
            }
            else {
                alert("获取信息失败.");
            }

        },
        error: function (e) {
            alert("获取信息失败.");
        }
    });
}


function ajaxFileUpload() {
    ClearErrorMsg();

    if ($("#fileToUpload").val() == "") {
        SetErrorMsg("请选择上传文件", "divAttachment");
        return;
    }

    var point = $("#fileToUpload").val().lastIndexOf(".");
    var type = $("#fileToUpload").val().substr(point).toLowerCase();

    if (type == ".exe" || type == ".bat" || type == ".msi") {
        SetErrorMsg("文件类型不允许", "divAttachment");
        return;
    }
    $("#loading").show();

    $.ajaxFileUpload({
        url: '/Order/FileUpload',
        secureuri: false,
        fileElementId: 'fileToUpload',
        data: { OrderNo: $("#OrderNo").val() },
        dataType: 'json',
        success: function (d, status) {
            var data = JSON.parse(d);
            data = data.Data;
            if (data.code == "1") {
                $("#divAttachment input").removeAttr("disabled");
                inUploading = false;
                SetErrorMsg(data.message, "divAttachment");
                $("#loading").hide();
            }
            else if (data.code == "0") {
                $("#divAttachment input").removeAttr("disabled");
                inUploading = false;
                $("#loading").hide();
                alert("上传成功！");
                $('#divAttachment').dialog('close');
            }
        },
        error: function (data, status, e) {
            $("#divAttachment input").removeAttr("disabled");
            inUploading = false;
            SetErrorMsg("上传时发生错误", "divAttachment");
            $("#loading").hide();
        }
    });

    $("#divAttachment input").attr("disabled", "disabled");
    inUploading = true;
    return false;
}

function ShowAttachment(OrderNo) {
    ClearErrorMsg();
    $("#OrderNo").val(OrderNo);

    $.ajax({
        url: "/Order/GetOrderAttachments",
        type: 'GET',
        cache: false,
        data: { OrderNo: $("#OrderNo").val() },
        success: function (result) {
            if (result.code == 0) {
                $("#dAttachment").html("");

                if (result.data.length > 0) {
                    for (var r in result.data) {
                        var tr = $("<tr id='" + result.data[r].ItemValue + "'></tr>");
                        var td = $("<td style='text-align: center;'></td>");
                        var image = $("<img src='" + result.data[r].Addition1 + "' alt=''>");
                        image.appendTo(td);
                        td.appendTo(tr);
                        td = $("<td></td>");
                        td.html(result.data[r].ItemText);
                        td.appendTo(tr);
                        td = $("<td></td>");
                        td.html(result.data[r].Addition3 + " MB");
                        td.appendTo(tr);
                        td = $("<td></td>");
                        td.html(result.data[r].Addition2);
                        td.appendTo(tr);
                        td = $("<td></td>");
                        var tno = result.data[r].ItemValue;
                        var t = $("<a href='#' onclick=\"javascript:return DownLoadFile('" + tno + "');\">下载</a>");
                        t.appendTo(td);

                        t = $("<a href='#' style='margin-left:5px;' onclick=\"javascript:return DeleteFile('" + tno + "','" + result.data[r].ItemText + "');\">删除</a>");

                        t.appendTo(td);
                        td.appendTo(tr);

                        tr.appendTo($("#dAttachment"));
                    }
                }
                $('#divAttachment').dialog('open');
            }
            else {
                alert("获取信息失败.");
            }

        },
        error: function (e) {
            alert("获取信息失败.");
        }
    });
}

function DeleteFile(no, name) {
    ClearErrorMsg();

    if (inUploading) {
        return false;
    }

    synConfirm('确定删除附件 ' + name + ' 吗？', function () {
        $.ajax({
            url: "/Order/DeleteAttachment",
            type: 'GET',
            cache: false,
            data: { FileNo: no, OrderNo: $("#OrderNo").val() },
            success: function (result) {
                if (result.code == 0) {
                    $("#tAttachment").find("tr[id=" + result.FileNo + "]").remove();
                }
                else {
                    alert("删除失败.");
                }

            },
            error: function (e) {
                alert("删除失败.");
            }
        });
    });
}

function DownLoadFile(no) {
    ClearErrorMsg();
    if (inUploading) {
        return false;
    }

    location.href = "/Order/DownLoadAttachment?FileNo=" + no;
}

function PopUpPriceChange() {

    var price = $("#popOrderDetail #Price").val();
    var number = $("#popOrderDetail #Number").val();

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

function CalcPopUpStockNumber() {
    var number = $("#popOrderDetail #Number").val();
  
    if (number && !isNaN(number)) {
        number = FixTwoDecimal(parseFloat(number) * stockFactor);
    }
    else if (number == "0") {
        number = 0;
    }
    else {
        number = 1*stockFactor;
    }    
   
    $("#popOrderDetail #StockNumber").val(number);
}

function CalcSimpleStockNumber(v) {
    var number = $(v).find("#Number").val();
    var area = $(v).find("#Area").val();
    var width = $(v).find("#Width").val();
    var height = $(v).find("#Height").val();
    var valuationType = $(v).find("#ValuationType").val();
    var stockNumber = number;


    if (valuationType == "1") {
        if (area && !isNaN(area)) {
            stockNumber = FixTwoDecimal(parseFloat(area));
        }
    }
    else if (valuationType == "2") {
        if (width && !isNaN(width)) {
            stockNumber = FixTwoDecimal(parseFloat(number) * parseFloat(width));
        }
    }
    else if (valuationType == "4") {
        if (width && !isNaN(width) && height && !isNaN(height)) {
            if (widthUnit == "m") {
                stockNumber = FixTwoDecimal(parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height)));
            }
            else if (widthUnit == "cm") {
                stockNumber = FixTwoDecimal(parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height)) / 100.0);
            }
            else if (widthUnit == "mm") {
                stockNumber = FixTwoDecimal(parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height)) / 1000.0);
            }
        }
    }
    else {
        if (number && !isNaN(number)) {
            stockNumber = FixTwoDecimal(parseFloat(number));
        }
    }

    if (stockNumber == "0") {
        stockNumber = 0;
    }
    else if (stockNumber == "") {
        stockNumber = 1;
    }

    $(v).find("#StockNumber").val(stockNumber);

}

function SimplePriceChange(v) {
    var price, number, amount,  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)) {            
            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);                        s
                    }
                    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);     
    }

    calcSimpleRealAmount();
}

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

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

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

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

function SimpleAmountChange(v) {

    var price, number, amount, width, area, valuationType;

    price = ""
    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 = $(v).find("#Amount").val();

    if (amount && !isNaN(amount) && number && !isNaN(number)) {

        if (valuationType == "1") {
            if (area && !isNaN(area)) {
                price = FixFourDecimal(parseFloat(amount) / parseFloat(area));
            }
        }
        else if (valuationType == "2") {

            if (width && !isNaN(width)) {
                price = FixFourDecimal(parseFloat(amount) / parseFloat(number) / parseFloat(width));
            }
        }
        else if (valuationType == "4") {
            if (width && !isNaN(width) && height && !isNaN(height)) {

                if (widthUnit == "m") {
                    price = FixFourDecimal(parseFloat(amount) / (parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height))));
                }
                else if (widthUnit == "cm") {
                    price = FixFourDecimal(parseFloat(amount) / (parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height))) * 100);
                }
                else if (widthUnit == "mm") {
                    price = FixFourDecimal(parseFloat(amount) / (parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height))) * 1000);
                }
            }
        }
        else {
            price = FixFourDecimal(parseFloat(amount) / parseFloat(number));
        }

        $(v).find("#Price").val(price);

    }
    else {
        $(v).find("#Price").val("");
    }
}

function calculateTax(orderAmount, taxType, eleTaxRatioId, eleTaxAmountId, eleTaxFeeId, eleTotalAmountId) {
     
    var eleTaxAmount = $("#" + eleTaxAmountId), eleTaxFee = $("#" + eleTaxFeeId), eleTaxRatio = $("#" + eleTaxRatioId), eleTotalAmount = $("#" + eleTotalAmountId);
    var taxAmount = '', taxFee = '', realAmount = 0, taxRatio = eleTaxRatio.val();

    if (taxType == "") {
        eleTaxAmount.val("");
        eleTaxFee.val("");
        eleTaxRatio.val("");
        eleTaxRatio.attr("readonly", true);
    }
    else {
        eleTaxRatio.removeAttr("readonly");
    }

    if (!(taxRatio && !isNaN(taxRatio))) {
        eleTaxAmount.val("");
        eleTaxFee.val("");
        return;
    }


    taxRatio = FixFourDecimal(taxRatio / 100);
    switch (taxType) {
        case "1":
            taxFee = FixTwoDecimal(1 / (1 + taxRatio) * orderAmount * taxRatio);
            taxAmount = FixTwoDecimal(orderAmount - taxFee);
            realAmount = orderAmount;
            break;
        case "2":
            taxFee = FixTwoDecimal(orderAmount * taxRatio);
            taxAmount = orderAmount;
            realAmount = FixTwoDecimal(orderAmount + taxFee);
            break;
        case "3":
            taxFee = FixTwoDecimal(orderAmount * taxRatio);
            taxAmount = orderAmount;
            realAmount = orderAmount;
            break;
        default:
            realAmount = orderAmount;
            break;
    }

    console.log(orderAmount);
    console.log(realAmount);
    eleTaxAmount.val(taxAmount);
    eleTaxFee.val(taxFee);
    eleTotalAmount.val(realAmount);
}

function calcRealAmount() {

    if ($("#TaxType").length > 0) {
        var detailTotalAmount = 0;

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

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

        calculateTax(detailTotalAmount, $("#TaxType").val(), "TaxRatio", "TaxAmount", "FeeTax", "MarketAmount");
    }

    if ($("#Discount").val() && !isNaN($("#Discount").val())) {

        if ($("#MarketAmount").val() && !isNaN($("#MarketAmount").val())) {
            $("#RealAmount").val(FixTwoDecimal(parseFloat($("#MarketAmount").val()) - parseFloat($("#Discount").val())));
        }
        else {
            $("#RealAmount").val("");
        }
    }
    else {
        $("#RealAmount").val($("#MarketAmount").val());
    }
}

function calcSimpleRealAmount() {

    var marketAmount = 0, rowAmount;

    $("#simpleOrderTr tr").each(function (i, v) {
        rowAmount = $(v).find("#Amount").val();
        
        if (rowAmount && !isNaN(rowAmount)) {
            marketAmount += parseFloat(rowAmount);
        }
    });

    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(marketAmount);

    if ($("#TaxType").length > 0) {        
        calculateTax(marketAmount, $("#TaxType").val(), "TaxRatio", "TaxAmount", "FeeTax", "MarketAmount");
    }
    if ($("#Discount").val() && !isNaN($("#Discount").val())) {

        if ($("#MarketAmount").val() && !isNaN($("#MarketAmount").val())) {
            $("#RealAmount").val(FixTwoDecimal(parseFloat($("#MarketAmount").val()) - parseFloat($("#Discount").val())));
        }
        else {
            $("#RealAmount").val("");
        }
    }
    else {
        $("#RealAmount").val($("#MarketAmount").val());
    }
}

function formatOrderDetailObj(obj) {
   
    if (obj.Category == null) {
        obj.Category = "";
        obj.ReportCategory = "";
    }

    if (obj.OrderName != undefined && obj.OrderName == null) {
        obj.OrderName = "";
    }
    if (obj.FactoryOrderName != undefined && obj.FactoryOrderName == null) {
        obj.FactoryOrderName = "";
    }
    if (obj.FactoryCategory != undefined && obj.FactoryCategory == null) {
        obj.FactoryCategory = "";
        obm.FactoryReportCategory = "";
    }

    if (obj.QuotationName != undefined && obj.QuotationName == null) {
        obj.QuotationName = "";
    }

    if (obj.Number == "" || obj.Number == null) {
        if (obj.Amount != "" && !isNaN(obj.Amount)) {
            obj.Number = 1;
            obj.Price = obj.Amount;
            formatDetailObj(obj);
        }
    }

    if (obj.Price == "" || obj.Price == null) {
        obj.Price = 0;
    }

    if (obj.FactoryNumber != undefined && (obj.FactoryNumber == "" || obj.FactoryNumber == null)) {
        if (obj.FactoryAmount != "" && !isNaN(obj.FactoryAmount)) {
            obj.FactoryNumber = 1;
            obj.FactoryPrice = obj.FactoryAmount;
        }
    }

    if (obj.FactoryNo && obj.FactoryPrice != undefined && (obj.FactoryPrice == "" || obj.FactoryPrice == null)) {
        obj.FactoryPrice = 0;
    }    
}

function SimpleAmountChange(v) {

    var price, number, amount, width, area, valuationType;

    price = ""
    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 = $(v).find("#Amount").val();

    if (amount && !isNaN(amount) && number && !isNaN(number)) {

        if (valuationType == "1") {
            if (area && !isNaN(area)) {
                price = FixFourDecimal(parseFloat(amount) / parseFloat(area));
            }
        }
        else if (valuationType == "2") {

            if (width && !isNaN(width)) {
                price = FixFourDecimal(parseFloat(amount) / parseFloat(number) / parseFloat(width));
            }
        }
        else if (valuationType == "4") {
            if (width && !isNaN(width) && height && !isNaN(height)) {

                if (widthUnit == "m") {
                    price = FixFourDecimal(parseFloat(amount) / (parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height))));
                }
                else if (widthUnit == "cm") {
                    price = FixFourDecimal(parseFloat(amount) / (parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height))) * 100);
                }
                else if (widthUnit == "mm") {
                    price = FixFourDecimal(parseFloat(amount) / (parseFloat(number) * 2 * (parseFloat(width) + parseFloat(height))) * 1000);
                }
            }
        }
        else {
            price = FixFourDecimal(parseFloat(amount) / parseFloat(number));
        }

        $(v).find("#Price").val(price);

    }
    else {
        $(v).find("#Price").val("");
    }
}

function formatDetailObj(obj) {

    return;
    //if (obj.Detail && obj.PriceUnitId) {
      
    //    var dObj = obj.Detail;
    //    if (dObj.Area != undefined) {
    //        dObj.Area = 1;
    //    }
    //    obj.Detail = JSON.stringify(dObj);
    //}
}