$(function() {
    $('.reload').click(function () {
        location.reload();
    });
});




(function() {

   

    //jQuery validator的信息提示设置,把英文转换成中文
    $.validator.setDefaults({
        errorPlacement: function (error, element) {
            error.appendTo(element.parent());
        },
        errorElement: "span",
        errorClass: 'kq-font kq-alert'
    });
    jQuery.validator.messages = {
        required: "此项为必填项.",
        remote: "请检查字段.",
        email: "请输入正确的Email地址.",
        url: "请输入正确的Url地址.",
        date: "请输入正确的日期.",
        dateISO: "请输入正确的日期 (ISO).",
        number: "请输入正确的数字.",
        digits: "只能输入数字.",
        creditcard: "必须输入合法的信用卡号.",
        equalTo: "两次输入的数据不相同.",
        accept: "请输入拥有合法后缀名的字符串.",
        maxlength: $.validator.format("请输入一个长度最多是 {0} 的字符串."),
        minlength: $.validator.format("请输入一个长度最少是 {0} 的字符串"),
        rangelength: $.validator.format("输入长度必须介于 {0} 和 {1} 之间的字符串(汉字算一个字符)."),
        range: $.validator.format("输入值必须介于 {0} 和 {1} 之间."),
        max: $.validator.format("输入值不能大于 {0}."),
        min: $.validator.format("输入值不能小于 {0}.")
    }

    jQuery.validator.addMethod('letterAndNumber', function (value, element, params) {
        return /^\w+$/.test(value);
    }, "只能使得数字或字母,或数字字母的组合");
    jQuery.validator.addMethod('checkIdCardNo', function (value, element, params) {
        return this.optional(element) || (/^(\d{14}|\d{17})(\d|[xX])$/.test($.trim(value)));
    }, "请输入合法的身份证号码");
    jQuery.validator.addMethod('mobileNo', function (value, element, params) {
        return this.optional(element) || (/^\d{11}$/.test($.trim(value)));
    }, "请输入合法的手机号");
    jQuery.validator.addMethod('digitsNo', function (value, element, params) {
        return this.optional(element) || (/^\d+$/.test($.trim(value)));
    }, "请输入合法的数字");
})();



    Date.prototype.Format = function (formatStr) {
        var str = formatStr;
        var Week = ['日', '一', '二', '三', '四', '五', '六'];
        var month = this.getMonth() + 1;

        str = str.replace(/yyyy|YYYY/, this.getFullYear());
        str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

        str = str.replace(/MM/, month > 9 ? month.toString() : '0' + month);
        str = str.replace(/M/g, month);

        str = str.replace(/w|W/g, Week[this.getDay()]);

        str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
        str = str.replace(/d|D/g, this.getDate());

        str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
        str = str.replace(/h|H/g, this.getHours());
        str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
        str = str.replace(/m/g, this.getMinutes());

        str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
        str = str.replace(/s|S/g, this.getSeconds());

        return str;
    };

   


function getBirth(value) {
    if (!value) {
        return "";
    }
    var year = "1900";
    var month = "1";
    var day = "1";
    if (value.length == 15) {
        year = "19" + value.substr(6, 2);
        month = value.substr(8, 2);
        day = value.substr(10, 2);
    } else if (value.length == 18) {
        year = value.substr(6, 4);
        month = value.substr(10, 2);
        day = value.substr(12, 2);
    } else {
        return "";
    }
    newDate = new Date(year, month - 1, day);
    if (newDate.toString() == "NaN") {
        return "";
    } else {
        return year + "-" + month + "-" + day;
    }
}

function getSex(value) {
    if (!value) {
        return "";
    } else if (value.length == 15) {
        return parseInt(value.substr(14, 1), 10) % 2 ? "男" : "女";
    } else if (value.length == 18) {
        return parseInt(value.substr(16, 1), 10) % 2 ? "男" : "女";
    } else {
        return "";
    }
}

function getAge(value) {
    var UUserCard = value;
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
    if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
        age++;
    }
    return age;
}

//统一的ajax异常报错
//$(document).ajaxError(function (e, jqxhr, settings, exception) {
//    if (console) { console.error("AJAX网络请求出错：" + exception); }
//});

var OTP = {
    checkAmount: function (amount) {
        return /^[+]?(([1-9]\d*[.]?)|(0[.]?))(\d{0,2})?$/.test($.trim(amount));
    },
    convertToUppper: function (currencyDigits) {
        // Constants:
        var MAXIMUM_NUMBER = 99999999999.99;
        // Predefine the radix characters and currency symbols for output:
        var CN_ZERO = "零";
        var CN_ONE = "壹";
        var CN_TWO = "贰";
        var CN_THREE = "叁";
        var CN_FOUR = "肆";
        var CN_FIVE = "伍";
        var CN_SIX = "陆";
        var CN_SEVEN = "柒";
        var CN_EIGHT = "捌";
        var CN_NINE = "玖";
        var CN_TEN = "拾";
        var CN_HUNDRED = "佰";
        var CN_THOUSAND = "仟";
        var CN_TEN_THOUSAND = "万";
        var CN_HUNDRED_MILLION = "亿";
        var CN_SYMBOL = "人民币";
        var CN_DOLLAR = "元";
        var CN_TEN_CENT = "角";
        var CN_CENT = "分";
        var CN_INTEGER = "整";

        // Variables:
        var integral; // Represent integral part of digit number.
        var decimal; // Represent decimal part of digit number.
        var outputCharacters; // The output result.
        var parts;
        var digits, radices, bigRadices, decimals;
        var zeroCount;
        var i, p, d;
        var quotient, modulus;

        // Validate input string:
        currencyDigits = currencyDigits.toString();
        if (currencyDigits == "") {
            alert("Empty input!");
            return "";
        }
        if (currencyDigits.match(/[^,.\d]/) != null) {
            alert("Invalid characters in the input string!");
            return "";
        }
        if ((currencyDigits).match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
            alert("Illegal format of digit number!");
            return "";
        }

        // Normalize the format of input digits:
        currencyDigits = currencyDigits.replace(/,/g, ""); // Remove comma delimiters.
        currencyDigits = currencyDigits.replace(/^0+/, ""); // Trim zeros at the beginning.
        // Assert the number is not greater than the maximum number.
        if (Number(currencyDigits) > MAXIMUM_NUMBER) {
            alert("Too large a number to convert!");
            return "";
        }

        // Process the coversion from currency digits to characters:
        // Separate integral and decimal parts before processing coversion:
        parts = currencyDigits.split(".");
        if (parts.length > 1) {
            integral = parts[0];
            decimal = parts[1];
            // Cut down redundant decimal digits that are after the second.
            decimal = decimal.substr(0, 2);
        }
        else {
            integral = parts[0];
            decimal = "";
        }
        // Prepare the characters corresponding to the digits:
        digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);
        radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
        bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
        decimals = new Array(CN_TEN_CENT, CN_CENT);
        // Start processing:
        outputCharacters = "";
        // Process integral part if it is larger than 0:
        if (Number(integral) > 0) {
            zeroCount = 0;
            for (i = 0; i < integral.length; i++) {
                p = integral.length - i - 1;
                d = integral.substr(i, 1);
                quotient = p / 4;
                modulus = p % 4;
                if (d == "0") {
                    zeroCount++;
                }
                else {
                    if (zeroCount > 0) {
                        outputCharacters += digits[0];
                    }
                    zeroCount = 0;
                    outputCharacters += digits[Number(d)] + radices[modulus];
                }
                if (modulus == 0 && zeroCount < 4) {
                    outputCharacters += bigRadices[quotient];
                }
            }
            outputCharacters += CN_DOLLAR;
        }
        // Process decimal part if there is:
        if (decimal != "") {
            for (i = 0; i < decimal.length; i++) {
                d = decimal.substr(i, 1);
                if (d != "0") {
                    outputCharacters += digits[Number(d)] + decimals[i];
                }
            }
        }
        // Confirm and return the final output string:
        if (outputCharacters == "") {
            outputCharacters = CN_ZERO + CN_DOLLAR;
        }
        if (decimal == "") {
            outputCharacters += CN_INTEGER;
        }
        outputCharacters = outputCharacters;
        return outputCharacters;
    }
}

$.extend({
    popAlter: function (options) {
        var settings = {
            title: options.title || '系统提示',
            content: '确认执行此操作吗？',
            hideCancelBtn: false,
            okCallback: null,
            eventSource: null,
            timeout: 5000,
            showButtons: true,
            Buttons: []
        };


        $('#sysmodal').remove();

        settings = $.extend(settings, options);

        var butstring = "";

        $.each(settings.Buttons, function(i, n) {
            butstring = butstring + '<a href="javascript:" class="btn btn-primary ok-click green" id="btn-ok" OprVal="' + n.Val + '">' + n.Name + '</a>';
        });

        var contentHtml = [
              '<div class="modal fade bs-example-modal-lg in" id="sysmodal" style="margin-top: 0px;width: auto; top: 3%;" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">',
              '<div class="modal-dialog modal-lg" >',
                  '<div class="modal-content" >',
                      '<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"></span></button>',
                          '<h4 class="modal-title" id="myModalLabel" style="text-align: left;margin-left: 16px;">' + settings.title + '</h4>',
                      '</div>',
                      '<div class="modal-body" style="max-height:440px; overflow-y:auto;">',
                          '<div class="tips">' + settings.content + '</div>',
                      '</div>',
                      '<div class="modal-footer" style="display:' + (settings.showButtons?"block":"none")+ ';">',
                    '<a href="#" class="btn btn-default cancelbtn" data-dismiss="modal" aria-hidden="true">关闭</a>' + butstring + '</div>',
                  '</div>',
              '</div>',
             '</div>'].join('\n');

        var _popModel = $("#sysmodal");
        //    function modalFadeOut(popModal) {
        //        if (popModal) {
        //            //setTimeOut(popModal.modal('toggle'),);
        //            setTimeout(function () {
        //                popModal.modal('toggle');
        //            }, settings.timeout);
        //        }
        //}
        function logicFunc(popModal) {
            if (settings.hideCancelBtn) {
                popModal.find(".cancelbtn").hide();
            }
            if (settings.okCallback && $.isFunction(settings.okCallback)) {
                popModal.find(".ok-click").unbind("click").click(function () {
                    settings.okCallback($(this).attr('OprVal'));
                });
            }
            popModal.modal();
            // modalFadeOut(popModal);
        }
        if (_popModel.length > 0) {
            _popModel.find(".modal-title").text(settings.title).end().find(".tips").text(settings.content);
            logicFunc(_popModel);
        } else {
            $("body").append($(contentHtml));
          
            logicFunc($("#sysmodal"));
        }

    },
    //包装jQuery.ajax,方便向JsonResult提交Json数据
    postJson: function (url, data, success) {
        $.ajax({
            type: 'POST',
            url: url,
            cache: false,
            data: JSON.stringify(data),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8'
        }).done(function (retData) {
            success(retData);
        });
    }

});

$.fn.extend({
    trimVal: function () {
        return $.trim($(this).val());
    },
    checkIdCardNo: function () {
        var v = $(this).trimVal();
        return (/^(\d{14}|\d{17})(\d|[xX])$/.test($.trim(v)));
    },
    Amount: function () {
        return /^[+]?(([1-9]\d*[.]?)|(0[.]?))(\d{0,2})?$/.test($.trim($(this).val()));
    }
});




var uploadglobal = {
    viewPath: 'http://file.OPT.com/optupload/',
    initFileJson: '[]',
    save: function (listBox, dataName) {
        var data = [];
        $('li', listBox).each(function () {
            data.push($(this).data('options'));
        });
        $('input[name=' + dataName + ']').val(JSON.stringify(data));
    },
    setItem: function (filejson, listBox, dataName) {
        var that = this;
        var item = $('<li></li>')
            .html(filejson.LocalName)
            .data('options', filejson)
            .bind('del', function () {
                $(this).popover('destroy').remove();
                that.save(listBox);
            });
        if (/(.)+\.(jpg|png|gif|jpeg)$/.test(filejson.LocalName)) {
            item.popover({
                html: true,
                content: '<img src="' + uploadglobal.viewPath + filejson.Name + '" style="width:150px;height:130px;"/>',
                placement: 'top',
                trigger: 'hover'
            })
        }
        $('<button type="button" class="close">&times;</button>')
        .click(function () {
            var parent = $(this).parents('li')[0];
            $(parent).trigger('del');
        }).appendTo(item);
        item.appendTo(listBox);
        this.save(listBox, dataName);
    },
    getFilesByIds: function (ids) {
        $.post('/upload/getfilesbyids', { ids: ids }, function (d) {
            if (!d || d.length == 0) {
                return;
            }
            var fileJsonArr = d;
            if (fileJsonArr && fileJsonArr.length > 0) {
                $(fileJsonArr).each(function (i, v) {
                    //that.setItem(v, listBox, dataName);
                    var item = $('<li></li>')
                 .html(v.LocalName)
                 .data('options', v)
                 .on('del', function () {
                     $(this).popover('destroy').remove();
                     that.save('#' + dataName + 'uploadul', dataName);
                 });
                    if (/(.)+\.(jpg|png|gif|jpeg)$/.test(v.LocalName)) {
                        item.popover({
                            html: true,
                            content: '<img src="' + uploadglobal.viewPath + v.Name + '" style="width:150px;height:130px;"/>',
                            placement: 'top',
                            trigger: 'hover'
                        })
                    }
                    $('<button type="button" class="close">&times;</button>')
                    .click(function () {

                        var parent = $(this).parents('li')[0];
                        $(parent).trigger('del');
                    }).appendTo(item);
                    ulcontainer.append(item);
                });
            }
        });
    },
    initData: function (dataName, parentContainer, fileJsonArrStr) {

        // var ulcontainer = $('<ul id="' + dataName + 'uploadul" ></ul>');
        var that = this;
        //if (!fileJsonArrStr || fileJsonArrStr.length == 0) {
        //  ulcontainer.push('</ul>');
        // return ulcontainer;
        // }
        $.post('/upload/getfilesbyids', { ids: fileJsonArrStr }, function (d) {
            //var fileJsonArr = d;
            if (d && d.length > 0) {
                $("#" + dataName).val(d);
                var fileJsonArr = eval("(" + d + ")");
                var ulcontainer = parentContainer.find("ul");
                $(fileJsonArr).each(function (i, v) {
                    //that.setItem(v, listBox, dataName);
                    var item = $('<li></li>')
                 .html(v.LocalName)
                 .data('options', v)
                 .on('del', function () {
                     $(this).popover('destroy').remove();
                     that.save('#' + dataName + 'uploadul', dataName);
                 });
                    if (/(.)+\.(jpg|png|gif|jpeg)$/.test(v.LocalName)) {
                        item.popover({
                            html: true,
                            content: '<img src="' + uploadglobal.viewPath + v.Name + '" style="width:150px;height:130px;"/>',
                            placement: 'top',
                            trigger: 'hover'
                        })
                    }
                    $('<button type="button" class="close">&times;</button>')
                    .click(function () {
                        var parent = $(this).parents('li')[0];
                        $(parent).trigger('del');
                    }).appendTo(item);
                    ulcontainer.append(item);
                });
                //$("#" + parentContainer).append(ulcontainer);
                // return ulcontainer;
            }
        });
        //var fileJsonArr = eval("(" + fileJsonArrStr + ")");
        //if (fileJsonArr && fileJsonArr.length > 0) {
        //    $(fileJsonArr).each(function (i, v) {
        //        //that.setItem(v, listBox, dataName);
        //        var item = $('<li></li>')
        //     .html(v.LocalName)
        //     .data('options', v)
        //     .on('del', function () {
        //         $(this).popover('destroy').remove();
        //         that.save('#'+dataName+'uploadul',dataName);
        //     });
        //        if (/(.)+\.(jpg|png|gif|jpeg)$/.test(v.LocalName)) {
        //            item.popover({
        //                html: true,
        //                content: '<img src="' + uploadglobal.viewPath + v.Name + '" style="width:150px;height:130px;"/>',
        //                placement: 'top',
        //                trigger: 'hover'
        //            })
        //        }
        //        $('<button type="button" class="close">&times;</button>')
        //        .click(function () {
        //            debugger;
        //            var parent = $(this).parents('li')[0];
        //            $(parent).trigger('del');
        //        }).appendTo(item);
        //        ulcontainer.append(item);
        //    });
        //}
        //ulcontainer.push('</ul>');
        //return ulcontainer;
        //this.save(listBox, dataName);
    },
    UploadUI: function (hidfilename, cate, form, parentcontainer, filesjson) {



        var templateui = $(
           // '<form id="' + hidfilename + 'form" name="' + hidfilename + 'form" method="post" enctype="multipart/form-data">' +
            '<span>' +
            '<input type="hidden" id="' + hidfilename + '" name="' + hidfilename + '" value=\'[]\'/>' +
            '<input type="file" id="' + hidfilename + 'file" name="' + hidfilename + 'file" onchange="uploadglobal.AttachUpload(\'' + hidfilename + 'uploadul\',\'' + hidfilename + 'file\',' + cate + ',\'' + form + '\',\'' + hidfilename + '\');" />' +
            '</span>' +
            '<span class="uploading">正在上传，请稍候...</span>' +
            '<ul id="' + hidfilename + 'uploadul" ></ul>'
            );
        // '</form>'); 

        $("#" + parentcontainer).append(templateui);
        if (!filesjson || filesjson.length <= 0) {
            return;
        }
        this.initData(hidfilename, $("#" + parentcontainer), filesjson);

        //templateui.append(this.initData(hidfilename, filesjson))
        //  '<ul id="' + hidfilename + 'uploadul" ></ul>';
        //this.initData(hidfilename, filesjson);
        //return templateui;
    }, AttachUpload: function (repath, uppath, cate, form, dataName) {

        var that = this;
        var submitUrl = "/upload/Uploader?cate=" + cate + "&rnd=" + new Date() + "&UpFilePath=" + uppath;
        var fileval = $("#" + uppath).val();
        if (!fileval) {
            return false;
        }
      
        //开始提交
        $("#" + form).ajaxSubmit({
            beforeSubmit: function (formData, jqForm, options) {
                //隐藏上传按钮
                $("#" + uppath).parent().hide();
                //显示LOADING图片
                $("#" + uppath).parent().nextAll(".uploading").eq(0).show();
            },
            success: function (data, textStatus) {
                if (data.Id > 0) {
                    var listBox = $("#" + repath);
                    that.setItem(data, listBox, dataName);
                } else {
                    alert(data.error);
                }
                $("#" + uppath).parent().show();
                $("#" + uppath).parent().nextAll(".uploading").eq(0).hide();
            },
            error: function (data, status, e) {
                alert("上传失败，错误信息：" + e);
                $("#" + uppath).parent().show();
                $("#" + uppath).parent().nextAll(".uploading").eq(0).hide();
            },
            url: submitUrl,
            type: "post",
            dataType: "json",
            timeout: 600000
        });
    }
};
