//$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
var msg_error =
    {
        required: "请检查必填项（带红框的字段）。",
        save_failed: "很遗憾，数据保存失败，请稍后重试。",
        invalidChar: '输入包含非法字符： <，>，",\''
    }; 

function clearForm() {
    $("input[type='text']").val("");
    $("select").val("");
    $("textarea").val("");
    $("input[type=checkbox]").prop("checked", false);
}

$(document).ready(function () {

    //$.ajaxSetup({ cache: false });

    $(".radio-off").click(function () {
       
        var radio = $(this).find("input[type=radio]");

        var name = radio.attr('name');
        console.log(name);
        var radios = $("input[name='" + name + "']");
        $(radios).each(function (i,v) {
            $(v).parent().removeClass("radio-off-on");
        })
        $(this).addClass("radio-off-on");
        radio.prop("checked");

        console.log($("input[name='" + name + "']:checked").val());
        
    });
    //$(".error-msg").attr('title', '点击隐藏此消息');
    //$(".error-msg").tooltip();
    //$(".text-date").attr('title', '双击清除');
    //$(".text-date").tooltip();
 
        //$('input').iCheck({
        //    checkboxClass: 'icheckbox_minimal',
        //    radioClass: 'iradio_minimal',
        //    increaseArea: '20%' // optional
        //});
 

    $(".text-date").dblclick(function () {
        $(this).val("");
    });
    $(".text-date-month").dblclick(function () {
        $(this).val("");
    });


    $('.info-msg').click(function (t) {
        $('.info-msg').hide();
    });   

    $('.error-msg').click(function (t) {
        $('.error-msg').hide();
    });
    $(".text-date").attr("readonly", "readonly");   
    $(".text-date").datepicker({ dateFormat: 'yy-mm-dd' });

    $(".text-date-month").attr("readonly", "readonly");
    $(".text-date-month").datepicker({
        dateFormat: 'yy-mm',
        changeMonth: true,
        changeYear: true,

        onClose: function (dateText, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        } 


    });

    $(".btn-search").button({ icons: { primary: "ui-icon-search" } });
    $(".btn-add").button({ icons: { primary: "ui-icon-plus" } });
    $(".btn-delete").button({ icons: { primary: "ui-icon-delete" } });
    $(".btn-payment").button({ icons: { primary: "ui-icon-creditcard" } });
    $(".btn-save").button({ icons: { primary: "ui-icon-save" } });
    $(".btn-print").button({ icons: { primary: "ui-icon-print" } });
    $(".btn-close").button({ icons: { primary: "ui-icon-close" } });
    $(".btn-download").button({ icons: { primary: "ui-icon-download" } });
    $(".btn-restore").button({ icons: { primary: "ui-icon-arrowrefresh-1-s" } });
    $(".btn-remove").button({ icons: { primary: "ui-icon-erase" } });
    
    $(".btn-Toggle1").button({ icons: { primary: "ui-icon-circle-b-plus" } });
    $(".btn-Toggle2").button({ icons: { primary: "ui-icon-circle-b-minus" } });
    $(".btn-help").button({ icons: { primary: "ui-icon-help" } });
    $(".btn-return").button({ icons: { primary: "ui-icon-arrowreturnthick-1-w" } });
    $(".btn-batch").button({ icons: { primary: " ui-icon-grip-dotted-horizontal" } });
    $(".btn-edit").button({ icons: { primary: " ui-icon-pencil" } });    
    $(".main-navigation li").hover(function () {
        var itemwidth = $(this).width(); /* Getting the LI width */
        $(this).prepend("<div class='hover'></div>"); /* Inserting a blank div into within li above the <a> tag*/
        $(this).find("div").fadeIn('10000').css({ 'width': itemwidth }); /* Using the itemwidth for the div to display properly*/
        $(this).find("ul").fadeIn('1000').slideDown('10000').css("display", "block");

    }, function () {
        $(this).find("div").slideUp('1000').fadeOut('1000'); /* sliding up and fading out the hover div */
        $(this).find("div").remove(); /* removing the <div> code from html at every mouseout event*/
        $(this).find("ul").fadeOut('1000'); /* fading out the sub menu */

    });


});

function checkRequired(containerId, errorspanId) {
    $("#" + containerId).find("input").removeClass("redBorder");
    $("#" + containerId).find("select").removeClass("redBorder");
    $("#" + containerId).find("textarea").removeClass("redBorder");

    $("#" + errorspanId).text("");

    var checkResult = "";
    var checkStatus = true;
    
    $("#" + containerId).find("input[type='text'],input[type='password'],select,textarea").each(function (i, val) {

        if ($(val).parent().children(".redStar").length > 0) {
            if ($.trim($(val).val()) == "") {
                $(val).addClass("redBorder");
                checkStatus = false;
            }
        }       
    });

    if (!checkStatus) {
        SetErrorMsg(msg_error.required, containerId);
        return checkStatus;
    }


    $("#" + containerId).find("input[type='text'],input[type='password'],select,textarea").each(function (i, val) {

        if ($.trim($(val).val()).indexOf('<') >= 0
            || $.trim($(val).val()).indexOf('>') >= 0
            || $.trim($(val).val()).indexOf('"') >= 0
            || $.trim($(val).val()).indexOf("'") >= 0) {

            $(val).addClass("redBorder");
            checkStatus = false; 
        }
    });

    if (!checkStatus) {
        SetErrorMsg(msg_error.invalidChar, containerId);
        return checkStatus;
    }  

    return checkStatus;
}

function changeTwoDecimal(x) {
    var f_x = parseFloat(x);
    console.log(x);
    if (isNaN(f_x)) {        
        return x;
    }
    var f_x = Math.round(x * 100) / 100;
    return f_x;
}

function changeFourDecimal(x) {
    var f_x = parseFloat(x);
    console.log(x);
    if (isNaN(f_x)) {        
        return x;
    }
    var f_x = Math.round(x * 10000) / 10000;
    return f_x;
}

function FixTwoDecimal(x) {
    var f_x = x;
    if (isNaN(f_x)) {
        return x;
    }
    var f_x = Math.round(x * 100) / 100;
    return f_x;
}

function FixFourDecimal(x) {
    var f_x = x;
    if (isNaN(f_x)) {
        return x;
    }
    var f_x = Math.round(x * 10000) / 10000;
    return f_x;
}



function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
} 

function GenerateWorkFlowSteps(data) {

    var tBody = $("#tdWorkFlow");
    tBody.empty();

    var tr, td, a;
    
    $(data).each(function (i, v) {
        tr = $("<tr></tr>");
        td = $("<td>" + v.StepName + "</td>");
        td.appendTo(tr);
        td = $("<td>" + v.UserName + "</td>");
        td.appendTo(tr);

        td = $("<td>" + (data[i].DateTime ? data[i].DateTime : "") + "</td>");
        td.appendTo(tr); 
        tr.appendTo(tBody);
    }); 
    
}

if (typeof JSON == 'undefined') {
    $('head').append($("<script type='text/javascript' src='/Scripts/json2.js'>"));
}

function FillOrderDetailInfo(orderDetails) {

    var tBody = $("#tableDetail");
    tBody.empty();

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

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

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

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

        td = $("<td></td>").html(v.UnitName);
        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); 
        
        td = $("<td></td>").html(v.DetailText);
        td.appendTo(tr);

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

        tr.appendTo(tBody);
    }); 
}

function FillFactoryOrderDetailInfo(orderDetails) {

    var tBody = $("#tableDetail");
    tBody.empty();

    var tr, td, a;
    console.log(orderDetails);
    $(orderDetails).each(function (i, v) {
        tr = $("<tr id='" + v.Guid + "'></tr>");
        td = $("<td></td>").html(v.OrderName);
        td.appendTo(tr);

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

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

        td = $("<td></td>").html(v.UnitName);
        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);

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

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

        tr.appendTo(tBody);
    });
}

function FillQuotationDetailInfo(orderDetails) {

    var tBody = $("#tableDetail");
    tBody.empty();

    var tr, td, a;
    console.log(orderDetails);
    $(orderDetails).each(function (i, v) {
        tr = $("<tr id='" + v.Guid + "'></tr>");
        td = $("<td></td>").html(v.QuotationName);
        td.appendTo(tr);

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

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

        td = $("<td></td>").html(v.UnitName);
        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);

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

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

        tr.appendTo(tBody);
    });
}

function SetDetailDetail(obj) {  
    console.log(obj);
    var objNew = obj; 
    for (var i in objNew) {
         
        if ($('[id="' + i + '"]').length > 0) {
            $('[id="' + i + '"]').val(objNew[i]);
        }       
    }
}
 
function DateDiff(sDate1, sDate2) { 
      var oDate1, oDate2, iDays;  
    oDate1 = new Date(sDate1) ;    
    oDate2 = new Date(sDate2); 
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24);
    return iDays;
}

function TdRowOverOut(table) {    
    $("#" + table + " tr td").mouseover(function () {        
        if ($(this).parent().hasClass("totalTd")) {
            return;
        }
        $(this).parent().find("td").addClass("td-over");             
    });

    $("#" + table + " tr td").mouseout(function () {
        if ($(this).parent().hasClass("totalTd")) {
            return;
        }
        $(this).parent().find("td").removeClass("td-over");        
    });
}


function TdRowOverOutWithSpan(table) {   

    $("#" + table + " tr td").mouseover(function () {
        var trId = $(this).parent().attr("id");        
       $("#tOrder tr[id='" + trId + "']").find("td").addClass("td-over");
    });

    $("#" + table + " tr td").mouseout(function () {
        var trId = $(this).parent().attr("id");
        $("#tOrder tr[id='" + trId + "']").find("td").removeClass("td-over");   
    });
}

function TdRowOverOutSpecify(table) {
    $("#" + table + " tr.specify td").mouseover(function () {
        $(this).parent().find("td").addClass("td-over");        
    });

    $("#" + table + " tr.specify td").mouseout(function () {
        $(this).parent().find("td").removeClass("td-over");        
    });
}
function FormatFieldsName(name) {
    name = name.replace(/\(/g, "");
    name = name.replace(/\)/g, "");
    return name;
}

function SelectAll() {
    var chk;
    
    if ($("#chkAll").prop("checked")) {
        chk = true;
    }
    else {
        chk = false;
    }

    $(".list table").find("input[type=checkbox]").each(function (i, val) {    
        $(val).prop("checked", chk);
    });
}

function SelectOne() {
    var allSelected = true;
    $(".list table").find("input[type=checkbox]").each(function (i, val) {
        if ($(val).prop("checked") == false) {
            allSelected = false;
        }
    });
    $("#chkAll").prop("checked", allSelected);
}

function GetSelectedId() {
    var result = "";
    $(".list table").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {
            if ($(val).parent().parent().attr("id") != undefined) {
                result = $(val).parent().parent().attr("id");
            }
        }
    });

    return result;
}

function GetSelectedIds() {
    var result = "";
    $(".list table").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {
            if ($(val).parent().parent().attr("id") != undefined) {
                result = result + $(val).parent().parent().attr("id") + ",";
            }
        }
    });

    return result;
}

function SelectedNumber() {
    var i = 0;
    $(".list table tbody").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {
            i++;
        }
    });

    return i;
}

function ClearErrorMsg(container) {
    if (container) {
        $("#" + container).find('.error-msg').each(function (v, val) {
            $(val).html('');
            $(val).hide();
        });   

        $("#" + container).find('.info-msg').each(function (v, val) {            
            $(val).hide();
        });
    }
    else {
        $('.error-msg').html('');
        $('.error-msg').hide();
        
        $('.info-msg').hide();        
    }    
    $(".redBorder").removeClass("redBorder");
}

function SetErrorMsg_Save_Failed(container) {
    SetErrorMsg(msg_error.save_failed, container);
}

function SetErrorMsg_Required(container) {
    SetErrorMsg(msg_error.required, container);
}

function SetErrorMsg(message, container) {
    if (container) {
        $("#" + container).find('.error-msg').each(function (v, val) {
            $(val).html(message);
            $(val).show();
            return false;
        });
    }
    else {
        $(".error-msg").each(function (v, val) {
            $(val).html(message);
            $(val).show();
            return false;
        });     
    }
}


function SetInfoMsg(message, container) {
    if (container) {
        $("#" + container).find('.info-msg').each(function (v, val) {
            $(val).html(message);
            $(val).show();
            return false;
        });
    }
    else {
        $(".info-msg").each(function (v, val) {
            $(val).html(message);
            $(val).show();
            return false;
        });
    }
}

function GetSelectedName(index,isHyperLink) {
    var result = "";
    $(".list table").find("input[type=checkbox]").each(function (v, val) {
        if ($(val).prop("checked")) {
            if (isHyperLink) {
                if ($(val).parent().parent().attr("id") != undefined) {
                    result = $(val).parent().parent().find("td:eq(" + index + ")").find("a").html();
                }
            }
            else {
                if ($(val).parent().parent().attr("id") != undefined) {
                    result = $(val).parent().parent().find("td:eq(" + index + ")").html();
                }
            }
            
        }
    });

    return result;
}


function IsEmail(email) {
    var pattern = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    return pattern.test(email);
}

function IsMobile(mobile) {
    var reg = /^1[2|3|4|5|6|7|8|9][0-9]\d{8}$/;
    //alert(mobile);
    //alert(reg.test(mobile));
    return reg.test(mobile);
}


function alert(messa) {
    if($("#dialogalert").length==0){
        $("body").append('<div id="dialogalert"></div>');
    }

    $("#dialogalert").dialog({
        autoOpen:false,
        title:'提示',
        model: true,
        width:360,       
        buttons:{
            '关闭':function(){
                $(this).dialog('close');
            }
        } 
    });
    $("#dialogalert").html(messa);
    $("#dialogalert").dialog('open');

    $("#dialogalert").parent().css("position", "absolute");
    $("#dialogalert").parent().css("top", "300px");

}


function synConfirm(mess,callback) {
    if($("#dialogconfirm").length==0)  {
        $("body").append('<div id="dialogconfirm"></div>');
    }
    
    $("#dialogconfirm").dialog({
        autoOpen: false,
        title: '提示',
        model: true,
        width: 360,
        buttons: {
            '確定': function () {
                callback();
                $(this).dialog('close');
            },
            '取消': function () {
                $(this).dialog('close');
            }
        }
    });

    $("#dialogconfirm").html(mess);
    $("#dialogconfirm").dialog('open');
}
    
function DrawWorkFlowCanvas(canvasId,data) {
    var canvas = document.getElementById(canvasId);    
    if (canvas == null || data == null) {
        return;
    }
     
    var context = canvas.getContext("2d");
    context.clearRect(0, 0, canvas.width, canvas.height);  
    var ix = 5;
    var iy = 0;
    var iw = 74;
    var ih = 100;
    var iiw = 34;
    var iih = 100;
    iy = iih;

    for (var i in data.Steps) {
        context.beginPath();
        data.Steps[i].xs = ix;
        data.Steps[i].xe = data.Steps[i].xs + iw;
        data.Steps[i].ys = iy;
        data.Steps[i].ye = data.Steps[i].ys + ih;
        if (data.Steps[i].IsSystemReserved) {
            context.fillStyle = "#2aaf59"; //"#0000FF";
            data.Steps[i].width = iw;
        }
        else {
            context.fillStyle = "#2aaf59";
            data.Steps[i].width = iw;
        }
        data.Steps[i].height = ih;
        data.Steps[i].xc = ix + iw / 2;
        data.Steps[i].yc = iy + ih / 2;

        context.fillRect(data.Steps[i].xs, data.Steps[i].ys, data.Steps[i].width, data.Steps[i].height);
        context.fillStyle = "rgb(255,255,255)";
        context.font = "normal bold 14px Arial";
        context.textBaseline = 'top';
        var length = context.measureText(data.Steps[i].WorkFlowStepName).width;

        if (length > 140) {
            context.font = "normal bold 12px Arial";
            var j = parseInt(data.Steps[i].WorkFlowStepName.length / 3);
            var part1 = data.Steps[i].WorkFlowStepName.substr(0, j);
            var part2 = data.Steps[i].WorkFlowStepName.substr(j, j);
            var part3 = data.Steps[i].WorkFlowStepName.substr(2 * j, data.Steps[i].WorkFlowStepName.length - 2 * j);
            context.fillText(part1, data.Steps[i].xs + 5, data.Steps[i].ys + 25);
            context.fillText(part2, data.Steps[i].xs + 5, data.Steps[i].ys + 45);
            context.fillText(part3, data.Steps[i].xs + 5, data.Steps[i].ys + 65);

        }
        else if (length > 70) {
            var j = parseInt(data.Steps[i].WorkFlowStepName.length / 2);
            var part1 = data.Steps[i].WorkFlowStepName.substr(0, j);
            var part2 = data.Steps[i].WorkFlowStepName.substr(j, data.Steps[i].WorkFlowStepName.length - j);
            context.fillText(part1, data.Steps[i].xs + 5, data.Steps[i].ys + 30);
            context.fillText(part2, data.Steps[i].xs + 5, data.Steps[i].ys + 50);
        }
        else {
            context.fillText(data.Steps[i].WorkFlowStepName, data.Steps[i].xs + (70 - length) / 2, data.Steps[i].ys + 40);
        }
        ix = ix + data.Steps[i].width + iiw;
        iy = iy;
    }

    for (var i = 0; i < data.Steps.length; i++) {
        data.Steps[i].next = [];
        data.Steps[i].previous = [];
        data.Steps[i].nextspan = [];
        data.Steps[i].previousspan = [];
        for (var j in data.Steps[i].FollowUps) {

            var index = GetIndexByStepNo(data, data.Steps[i].FollowUps[j].OptionValue);

            if (index == i + 1) {
                data.Steps[i].next.push({ xs: data.Steps[i].xe, xe: data.Steps[index].xs, ys: 150, ye: 150 });
            }
            else if (index == i - 1) {
                data.Steps[i].previous.push({ xs: data.Steps[i].xs, xe: data.Steps[index].xe, ys: 150, ye: 150 });
            }
            else if (index > i + 1) {
                data.Steps[i].nextspan.push({ xs: data.Steps[i].xc + 10, xe: data.Steps[index].xc - 10 });
            }
            else {
                data.Steps[i].previousspan.push({ xs: data.Steps[i].xc - 10, xe: data.Steps[index].xc + 10 });
            }
        }
    }

    var color = [];
    var colorIndex = 0;
    color.push('rgb(0,0,255)');
    color.push('rgb(0,175,255)');
    color.push('rgb(0,140,140)');

    var topinterval = 25;
    var bottominterval = 25;
    context.lineWidth = 1;
    for (var i = 0; i < data.Steps.length; i++) {
        if (i < data.Steps.length - 1 &&
            data.Steps[i + 1].previous.length == 1 &&
            data.Steps[i].next.length > 0) {
            data.Steps[i].next[0].ys = 140;
            data.Steps[i].next[0].ye = data.Steps[i].next[0].ys;
            data.Steps[i + 1].previous[0].ys = 160;
            data.Steps[i + 1].previous[0].ye = data.Steps[i + 1].previous[0].ys;
        }

        if (data.Steps[i].next.length > 0) {
            context.beginPath();
            context.strokeStyle = color[colorIndex % 3];
            colorIndex++;
            context.moveTo(data.Steps[i].next[0].xs, data.Steps[i].next[0].ys);
            context.lineTo(data.Steps[i].next[0].xe, data.Steps[i].next[0].ye);
            context.stroke();
            context.moveTo(data.Steps[i].next[0].xe, data.Steps[i].next[0].ye);
            context.lineTo(data.Steps[i].next[0].xe - 12, data.Steps[i].next[0].ye - 6);
            context.stroke();
            context.moveTo(data.Steps[i].next[0].xe, data.Steps[i].next[0].ye);
            context.lineTo(data.Steps[i].next[0].xe - 12, data.Steps[i].next[0].ye + 6);
            console.log("x");
            context.stroke();
        }


        if (i < data.Steps.length - 1 && data.Steps[i + 1].previous.length > 0) {
            context.beginPath();
            context.strokeStyle = color[colorIndex % 3];
            colorIndex++;
            context.moveTo(data.Steps[i + 1].previous[0].xs, data.Steps[i + 1].previous[0].ys);
            context.lineTo(data.Steps[i + 1].previous[0].xe, data.Steps[i + 1].previous[0].ye);
            context.stroke();
            context.moveTo(data.Steps[i + 1].previous[0].xe, data.Steps[i + 1].previous[0].ye);
            context.lineTo(data.Steps[i + 1].previous[0].xe + 12, data.Steps[i + 1].previous[0].ye - 6);
            context.stroke();
            context.moveTo(data.Steps[i + 1].previous[0].xe, data.Steps[i + 1].previous[0].ye);
            context.lineTo(data.Steps[i + 1].previous[0].xe + 12, data.Steps[i + 1].previous[0].ye + 6);
            context.stroke();
        }

        if (data.Steps[i].nextspan.length > 0) {

            for (var k in data.Steps[i].nextspan) {
                context.beginPath();
                context.strokeStyle = color[colorIndex % 3];
                colorIndex++;
                context.moveTo(data.Steps[i].xc, 100);
                context.lineTo(data.Steps[i].xc, 100 - topinterval);
                context.lineTo(data.Steps[i].nextspan[k].xe, 100 - topinterval);
                context.lineTo(data.Steps[i].nextspan[k].xe, 100);
                context.lineTo(data.Steps[i].nextspan[k].xe - 6, 100 - 12);
                context.moveTo(data.Steps[i].nextspan[k].xe, 100);
                context.lineTo(data.Steps[i].nextspan[k].xe + 6, 100 - 12);
                context.stroke();
                topinterval = topinterval + 15;
            }
        }

        if (data.Steps[i].previousspan.length > 0) {
            for (var k in data.Steps[i].previousspan) {
                context.beginPath();
                context.strokeStyle = color[colorIndex % 3];
                colorIndex++;
                context.moveTo(data.Steps[i].previousspan[k].xs, 200);
                context.lineTo(data.Steps[i].previousspan[k].xs, 200 + bottominterval);
                context.lineTo(data.Steps[i].previousspan[k].xe, 200 + bottominterval);
                context.lineTo(data.Steps[i].previousspan[k].xe, 200);
                context.lineTo(data.Steps[i].previousspan[k].xe - 6, 200 + 12);
                context.moveTo(data.Steps[i].previousspan[k].xe, 200);
                context.lineTo(data.Steps[i].previousspan[k].xe + 6, 200 + 12);
                context.stroke();
                bottominterval = bottominterval + 15;
            }
        }
    }
}

// this method is used to draw workflow canvas
function GetIndexByStepNo(data, step) {
    for (var i = 0; i < data.Steps.length; i++) {
        if (data.Steps[i].WorkFlowStepNo == step) {
            return i;
        }
    }
    return 0;
}

function CheckNull(value) {
    return value == null ? "" : value;
}

function logout() {
    synConfirm("确定要退出吗？", function () {
        location.href = "/Account/Logout";
    });
}

function setOperationBtns() {
    $(".operation-btns button")
        .button({
            text: false,
            icons: {
                primary: "ui-icon-triangle-1-s"
            }
        })
        .click(function () {            
           
            if (!$(this).parent().next().is(":hidden")) {
                $(this).parent().next().hide();
                return;
            }

            $(".operation-btns ul").hide();
            var menu = $(this).parent().next().show().position({
                my: "left top",
                at: "left bottom",
                of: this
            });
            $(document).one("click", function () {
                menu.hide();
            });
            return false;
        })
        .parent()
        .buttonset()
        .next()
        .hide()
        .menu();

    $(".operation-btns").parent().css("text-align", "center"); 
    $(".operation-btns").css("display", "block");
}

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;
}

// jquery's clone can not automatically copy the original object's value, so rewrite it.
(function (original) {
    jQuery.fn.clone = function () {
        var result = original.apply(this, arguments),
            my_textareas = this.find('textarea').add(this.filter('textarea')),
            result_textareas = result.find('textarea').add(result.filter('textarea')),
            my_selects = this.find('select').add(this.filter('select')),
            result_selects = result.find('select').add(result.filter('select'));
        for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
        for (var i = 0, l = my_selects.length; i < l; ++i) {
            for (var j = 0, m = my_selects[i].options.length; j < m; ++j) {
                if (my_selects[i].options[j].selected === true) {
                    result_selects[i].options[j].selected = true;
                }
            }
        }
        return result;
    };
})(jQuery.fn.clone);


function SetSpanColor(container) {

    var spans;
    if (container) {
        spans = $("#" + container).find("span");
    }
    else {
        spans = $("span");
    }


    $(spans).each(function (i, val) {
        var text = $(val).html();
        
        if (text == "未支付") {
            $(val).css("color", "#FF0000");
        }
        else if (text == "部分支付") {
            $(val).css("color", "#000000");
        }
        else if (text == "已支付") {
            $(val).css("color", "#288a51");
        }
        else if (text == "未审核") {
            $(val).css("color", "#ff0000");
        }
        else if (text == "已审核") {
            $(val).css("color", "#288a51");
        }
        else if (text == "已开票") {
            $(val).css("color", "#000000");
        }
        else if (text == "未开票") {
            $(val).css("color", "#FF0000");
        }
        else if (text == "未完工") {
            $(val).css("color", "#FF0000");
        }
        else if (text == "已完工") {
            $(val).css("color", "#288a51");
        }
        else if (text == "已完成") {
            $(val).css("color", "#288a51");
        }
        else if (text == "已分配") {
            $(val).css("color", "#288a51");
        }
        else if (text == "未分配") {
            $(val).css("color", "#FF0000");
        }
        else if (text == "可用") {
            $(val).css("color", "#288a51");
        }
        else if (text == "已禁用") {
            $(val).css("color", "#FF0000");
        }
    });
}

// order edit
function FilterMaterialDdl(categoryIds, ddlMaterial) {
   
    ddlMaterial.find("optgroup").show();

    ddlMaterial.find("optgroup").attr("data-v", "1");
    ddlMaterial.find("option").attr("data-v", "1");

    if (categoryIds == undefined || categoryIds == null || categoryIds.length == 0) {
        ddlMaterial.select2();
        return;
    }

    var currentGroup;

    if (ddlMaterial.val()) {
        currentGroup = ddlMaterial.find("option[value='" + ddlMaterial.val() + "']").parent();
    }

    ddlMaterial.find("optgroup").attr("data-v", "0");
    ddlMaterial.find("option").attr("data-v", "0");

    $(ddlMaterial.find("optgroup")).each(function (i, v) {
        $(categoryIds).each(function (x, y) {            
            if (y.Id == $(v).attr("data-id")) {
                $(v).attr("data-v", "1");
                $(v).find("option").attr("data-v", "1");
            }
        });
    });

    if (currentGroup) {
        currentGroup.show();
    }    

    ddlMaterial.find("option:first").attr("data-v", "1");

    ddlMaterial.select2();
} 

// 拖图开单
function addDetailByFileName(fileName) {

    var trs = $("#simpleOrderTr tr");

    if (trs.length != 0) {
        var tr = trs[trs.length - 1];
        if (isDetailTrHasNoValue(tr)) {
            $(tr).remove();
        }

        var rowData = analyzeFileName(fileName);
        addOrderDetailRow(rowData);

        $("#simpleOrderTr tr:last").find("#Width").change();
        if (!rowData.Amount) {
           $("#simpleOrderTr tr:last").find("#PriceUnitId").change();
        }
         
    }
}

function ParseWidthUnit(value, unit) {
    unit = unit.trim();
    var baseUnitFactor = 1000;
    switch (widthUnit) {
        case 'm':
            baseUnitFactor = 1000;
            break;
        case 'cm':
            baseUnitFactor = 10;
            break;
        case 'mm':
            baseUnitFactor = 1;
            break;
    }

    var unitFactor = 1000;
    switch (unit) {
        case '米':
        case 'm':
            unitFactor = 1000;
            break;
        case '厘米':
        case 'cm':
            unitFactor = 10;
            break;
        case '毫米':
        case 'mm':
            unitFactor = 1;
            break;
    }

    value = FixFourDecimal(parseFloat(value) * unitFactor / baseUnitFactor);
    return value;
}

function analyzeFileName(fileName) {
    var rowData = {
        Id: '0',
        Category: '',
        CategoryName: '',
        ReportCategory: '',
        OrderName: '',
        FactoryOrderName:'',
        MaterialId: '',
        PriceUnitId: '',
        Width: '',
        Height: '',
        Amount: '',
        Number: '',
        Area: '',
        Price: '',
        DetailText: '',
        FactoryNo: '',
        FactoryPrice: '',
        FactoryAmount: '',
        Memo: '',
        StockNumber: null,
        TechnicText: '',
        Technic: '[]'
    };

    //fileName = "大武汉 名片 张经理名片 15根 单价20.jpg";

    var lastDot = fileName.lastIndexOf(".");
    if (lastDot > 0) {
        fileName = fileName.substr(0, lastDot);        
    }

    var clientNameOk = false;
    var numberOk = false;
    var priceOk = false;
    var amountOk = false;
    var widthOk = false;
    var heightOk = false;
    var categoryOk = false;
    var unitOk = false;

    // 单价金额
    var reg = null;
    var match = null;

    // 单价12
    reg = /单价[:|：]?\d+\.?\d*/ig;
    if (fileName.match(reg) && fileName.match(reg).length > 0) {
        match = fileName.match(reg)[0].replace(/单价[:|：]?/ig, '');
        rowData.Price = match;
        priceOk = true;
        fileName = fileName.replace(reg, '');
    }

    // 金额12
    reg = /金额[:|：]?\d+\.?\d*/ig;
    if (fileName.match(reg) && fileName.match(reg).length > 0) {
        match = fileName.match(reg)[0].replace(/金额[:|：]?/ig, '');
        rowData.Amount = match;
        amountOk = true;
        fileName = fileName.replace(reg, '');
    }

    // 宽高数量单位
    var whUnit = null;

    // 宽12cm
    reg = /宽[:|：]?\d+\.?\d*[毫|厘|m|c]?[米|m]?/ig;
    var reg1 = /[毫|厘|m|c]?[米|m]?/ig;
    var reg2 = /\d+\.?\d*/;

    if (fileName.match(reg) && fileName.match(reg).length > 0) {
        match = fileName.match(reg)[0].replace(/宽[:|：]?/ig, '');
        whUnit = match.replace(reg2, '');
        match = match.replace(reg1, '');

        rowData.Width = match;
        widthOk = true;
        fileName = fileName.replace(reg, '');
    }

    // 高12cm
    reg = /高[:|：]?\d+\.?\d*[毫|厘|m|c]?[米|m]?/ig;
    if (fileName.match(reg) && fileName.match(reg).length > 0) {
        match = fileName.match(reg)[0].replace(/高[:|：]?/ig, '');
        whUnit = match.replace(reg2, '');
        match = match.replace(reg1, '');
        rowData.Height = match;
        heightOk = true;
        fileName = fileName.replace(reg, '');
    }

    if (widthOk) {
        rowData.Width = ParseWidthUnit(rowData.Width, whUnit);
    }
    if (heightOk) {
        rowData.Height = ParseWidthUnit(rowData.Height, whUnit);
    }

    // 尺寸12*12cm
    if (!widthOk) {
        reg = /尺寸[:|：]?\d+\.?\d*[毫|厘|m|c]?[米|m]?×\d+\.?\d*[毫|厘|m|c]?[米|m]?/ig;
        if (fileName.match(reg) && fileName.match(reg).length > 0) {
            match = fileName.match(reg)[0].replace(/尺寸[:|：]?/ig, '');
            var whUnits = match.replace(reg2, '');
            whUnits = whUnits.replace(reg2, '');
            whUnits = whUnits.split("×");
            if (whUnits[1].trim() != "") {
                whUnit = whUnits[1];
            }
            else if (whUnits[0].trim() != "") {
                whUnit = whUnits[0];
            }

            match = match.replace(reg1, '');

            var chiCun = match.split("×");
            rowData.Width = chiCun[0];
            rowData.Height = chiCun[1];

            if (whUnit) {                
                rowData.Width = ParseWidthUnit(rowData.Width, whUnit);
                rowData.Height = ParseWidthUnit(rowData.Height, whUnit);
            }
            widthOk = true;
            heightOk = true;

            heightOk = true;
            fileName = fileName.replace(reg, '');
        }
    }

    if (widthOk && heightOk) {
        $(allUnits).each(function (i, v) {         
            if (v.ItemText == "平米" || v.ItemText == "平方米" || v.ItemText == "平方" || v.ItemText =="㎡") {
                rowData.PriceUnitId = v.ItemValue;
            }
        });
    }

    // 数量12盒
    $(allUnits).each(function (i, v) {
        reg = eval("/数量[:|：]?\\d+\\.?\\d*?" + v.ItemText + "/ig");
        if (fileName.match(reg) && fileName.match(reg).length > 0) {
            rowData.PriceUnitId = v.ItemValue;
            match = fileName.match(reg)[0].replace(/数量[:|：]?/ig, '');
            match = match.replace(v.ItemText, '');
            console.log(match);
            rowData.Number = match;
            fileName = fileName.replace(reg, '');
            numberOk = true;
            return false;
        }
    });

    // 数量12
    if (!numberOk) {
        reg = eval("/数量[:|：]?\\d+\\.?\\d*?/ig");
        if (fileName.match(reg) && fileName.match(reg).length > 0) {

            match = fileName.match(reg)[0].replace(/数量[:|：]?/ig, '');
            rowData.Number = match;
            fileName = fileName.replace(reg, '');
            numberOk = true;
        }
    }

    var parts = [];

    var sc1 = 0; //seperator count
    var sc2 = 0; //_
    var sc3 = 0; //-

    if (fileName.match(eval("/ /ig"))) {
        sc1 = fileName.match(eval("/ /ig")).length;
    }
    if (fileName.match(eval("/_/ig"))) {
        sc2 = fileName.match(eval("/_/ig")).length;
    }
    if (fileName.match(eval("/-/ig"))) {
        sc3 = fileName.match(eval("/-/ig")).length;
    }

    if (sc1 > (sc2 > sc3 ? sc2 : sc3)) {
        parts = fileName.split(' ');
    }
    else if (sc2 > (sc1 > sc3 ? sc1 : sc3)) {
        parts = fileName.split('_');
    }
    else if (sc3 > (sc2 > sc1 ? sc2 : sc1)) {
        parts = fileName.split('-');
    }
    else {
        parts = fileName.split(' ');
    }    
 
    //"12盒"
    if (!numberOk) {
        $(parts).each(function (x, y) {
            if (!y) {
                return true;
            }
            $(allUnits).each(function (i, v) {
                reg = eval("/\\d+\\.?\\d*?" + v.ItemText + "/ig");
                if (y.match(reg) && y.match(reg).length > 0) {
                    match = y.match(reg)[0];
                    rowData.PriceUnitId = v.ItemValue;
                    match = match.replace(v.ItemText, '');
                    rowData.Number = match;                   
                    parts[x] = parts[x].replace(reg, '');
                    numberOk = true;
                    return false;
                }
            });
        });
    }

    if (!numberOk) {
        rowData.Number = 1;
    }
    
    // 名片
    $(parts).each(function (x, y) {
        if (!y) {
            return true;
        }
        $("#Category option").each(function (i, v) {
            reg = eval("/" + $(v).text() + "/ig");
            if (y.trim() == $(v).text()) {
                match = y.match(reg)[0];
                rowData.Category = match;                
                parts[x] = parts[x].replace(reg, '');
                categoryOk = true;
                return false;
            }
        });
    });

    // 客户或外协  
    $(parts).each(function (x, y) {
        if (!y) {
            return true;
        }
        if ($("#CustomerNo option").length > 0) {
            $("#CustomerNo option").each(function (i, v) {

                if (y.trim() == $(v).text()) {                  

                    $("#CustomerNo").val($(v).val());
                    parts[x] = parts[x].replace(reg, '');
                    clientNameOk = true;
                    return false;
                }
            });
        }
        if ($("#FactoryNo option").length > 0) {
            $("#FactoryNo option").each(function (i, v) {
              
                if (y.trim() == $(v).text())  {
                    $("#FactoryNo").val($(v).val()).trigger("change");                    
                    parts[x] = parts[x].replace(reg, '');
                    clientNameOk = true;
                  
                    return false;
                }
            });
        }
   
    });

    // 订单名称    
    rowData.OrderName = '';
    rowData.FactoryOrderName = '';   
 
    $(parts).each(function (x, y) {      
        if (y.trim()) {
            rowData.OrderName =  y.trim();
            rowData.FactoryOrderName = y.trim();
            return false;
        }
    });

    return rowData;

}

function isDetailTrHasNoValue(tr) {
    var hasNoValue = true;

    var input = $(tr).find("input");
    $(input).each(function (i, v) {
        if ($(v).val() && $(v).val() != "0" && $(v).val() != "[]" && $(v).val() != "{}") {
            hasNoValue = false;
            return false;
        }
    });

    var input = $(tr).find("select");
    $(input).each(function (i, v) {
        if ($(v).val() && $(v).val() != "0" && $(v).val() != "[]" && $(v).val() != "{}") {
            hasNoValue = false;
            return false;
        }
    });

    return hasNoValue;
}

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


function setDueDay() {  
    var tds = $(".due-day");
    $(tds).each(function (i, v) {
        var dueDay = parseInt($(v).attr("data-due"));
        if (!isNaN(dueDay)) {
            console.log(dueDay);
            if (dueDay > 9) {
                $(v).html("9<sup>+</sup>天");
                $(v).attr("title", dueDay + "天");
                $(v).addClass("due-day-1");
            }
            else if (dueDay >= 1) {
                $(v).text(dueDay + "天");
                $(v).addClass("due-day-1");
            }
            else if (dueDay == 0) {
                $(v).text("到期");
                $(v).attr("title", "今日到期");
                $(v).addClass("due-day-2");
            }
            else {
                $(v).text("超时");
                $(v).attr("title", dueDay + "天");
                $(v).addClass("due-day-3");
            }
        }
    });
}


function NewTr() {
    return $("<tr></tr>");
}

function NewTd() {
    return $("<td></td>");
}

function NewTextbox() {
    return $("<input type='text' />")
}

function NewCheckbox() {
    return $("<input type='checkbox' />")
}