﻿//AjaxWithPost与AjaxWithGet是联系WCF的两种方式。js端传的参数都是一样的。无需特别处理。
//wcfmethod     必填    需要访问的方法。如：var mymethod = "../WCF/FinanceAccountService.svc/SaveFinanceAccountToProfile"
//jsonstr       可选    提交的数据。
//wcfsuccess    可选    成功后回调的方法。
//wcferror      可选    失败后回调的方法。
//usegif        可选    提交时是否播放等待动画，true/false。默认为播放。
//wcftimeout    可选    提交的超时限制。默认为5秒。
function AjaxWithPost(wcfmethod, jsonstr, wcfsuccess, wcferror, usegif, wcftimeout) {
    var wcfdata = "";
    if (wcfmethod == undefined)
        alert("WCFUrl未定义！");
    if (wcfsuccess == undefined) {
        wcfsuccess = function() { };
    }
    if (wcferror == undefined) {
        wcferror = function() { };
    }
    if (jsonstr == undefined || jsonstr == "") {
        wcfdata = "";
    } else if (typeof (jsonstr) == "object") {
        wcfdata = JSON.stringify(jsonstr);
    } else {
        wcfdata = jsonstr;
    }
    if (wcftimeout == undefined) {
        wcftimeout = 5000;
    }
    if (usegif == undefined || usegif == true || usegif.toString().toLowerCase == "true") {
        wcfgifstart();
    }
	
	$.ajax({
		type: "POST",
		contentType: "application/json",
		url: wcfmethod,
		data: wcfdata,
		cache: false,
		dataType: 'json',
		processData: true,
		timeout: wcftimeout,
		success: function(res) {
			if (usegif == undefined || usegif == true || usegif.toString().toLowerCase == "true")
			{ wcfgifstop(); }
			wcfsuccess(JSON.parse(res));
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			if (usegif == undefined || usegif == true || usegif.toString().toLowerCase == "true")
			{ wcfgifstop(); }
			if (typeof (wcferror) == "function") {
				wcferror(XMLHttpRequest, textStatus, errorThrown);
			} else {
				alert("异常:" + XMLHttpRequest.responseText);
			}
		}
	});
}



function AjaxWithGet(wcfmethod, jsonstr, wcfsuccess, wcferror, usegif, wcftimeout) {
    var wcfdata = "";
    if (wcfmethod == undefined)
        alert("WCFUrl未定义！");
    if (wcfsuccess == undefined) {
        wcfsuccess = function() { };
    }
    if (wcferror == undefined) {
        wcferror = function() { };
    }
    if (jsonstr == undefined || jsonstr == "") {
        wcfdata = "";
    } else if (typeof (jsonstr) == "object") {
        wcfdata = "jsonstr=" + JSON.stringify(jsonstr);
    } else {
        wcfdata = jsonstr;
    }
    if (wcftimeout == undefined) {
        wcftimeout = 5000;
    }
    if (usegif == undefined || usegif == true || usegif.toString().toLowerCase == "true") {
        wcfgifstart();
    }
	
	$.ajax({
		type: "GET",
        contentType: "application/json",
		url: wcfmethod,
		data: wcfdata,
		cache: false,
		dataType: 'json',
		processData: true,
		timeout: wcftimeout,
		success: function(res) {
			if (usegif == undefined || usegif == true || usegif.toString().toLowerCase == "true")
			{ wcfgifstop(); }
			wcfsuccess(JSON.parse(res));
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			if (usegif == undefined || usegif == true || usegif.toString().toLowerCase == "true")
			{ wcfgifstop(); }
			if (typeof (wcferror) == "function") {
				wcferror(XMLHttpRequest, textStatus, errorThrown);
			} else {
				alert("异常:" + XMLHttpRequest.responseText);
			}
		}
	});
}

function wcfgifstart() {
    var $body = $('body');
//	var _sW = $body.attr('scrollWidth');
//	var _cW = document.documentElement.clientWidth;
	var _sH = $body.attr('scrollHeight');
	var _cH = document.documentElement.clientHeight;
	var $objBg = $('<div class="LoadingBgDiv"></div>').height(_sH < _cH ? _cH : _sH);
	var $obj = $('<div class="LoadingDiv">正在提交，请稍后......</div>');
	$body.append($objBg).append($obj);
}
function wcfgifstop(){
    $('div.LoadingDiv').remove();
	$('div.LoadingBgDiv').remove();
}

function IsResult(strResult) {
    var Regex = /^\{[ ]*("Error"|'Error'):[ ]*('[^']*'|"[^"]*")[ ]*\}$/g;
    return !Regex.test(strResult);
}
function IsSuccess(strResult) {
    var Regex = /^\{[ ]*("Success"|'Success'):[ ]*('[^']*'|"[^"]*")[ ]*\}$/g;
    return Regex.test(strResult);
}

//****************************************************//
//一些检查的公用方法。
//****************************************************//

function formatNumber(nData, opts) {
    opts = $.extend({},
    {
        decimalSeparator: ".",
        thousandsSeparator: ",",
        decimalPlaces: 0,
        round: true,
        prefix: "",
        suffix: "",
        defaulValue: 0
    }, opts);
    if (!(typeof (nData) === 'number' && isFinite(nData))) {
        nData *= 1;
    }
    if (typeof (nData) === 'number' && isFinite(nData)) {
        var bNegative = (nData < 0);
        var sOutput = nData + "";
        var sDecimalSeparator = (opts.decimalSeparator) ? opts.decimalSeparator : ".";
        var nDotIndex;
        if (typeof (opts.decimalPlaces) === 'number' && isFinite(opts.decimalPlaces)) {
            // Round to the correct decimal place
            var nDecimal, nDecimalPlaces = opts.decimalPlaces;
            if (opts.round) {
                nDecimal = Math.pow(10, nDecimalPlaces);
                sOutput = Math.round(nData * nDecimal) / nDecimal + "";
            } else {
                nDecimal = Math.pow(10, (nDecimalPlaces + 1));
                sOutput = Math.floor(Math.round(nData * nDecimal) / 10) / (nDecimal / 10) + "";
            }
            nDotIndex = sOutput.lastIndexOf(".");
            if (nDecimalPlaces > 0) {
                // Add the decimal separator
                if (nDotIndex < 0) {
                    sOutput += sDecimalSeparator;
                    nDotIndex = sOutput.length - 1;
                }
                // Replace the "."
                else if (sDecimalSeparator !== ".") {
                    sOutput = sOutput.replace(".", sDecimalSeparator);
                }
                // Add missing zeros
                while ((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {
                    sOutput += "0";
                }
            }
        }
        if (opts.thousandsSeparator) {
            var sThousandsSeparator = opts.thousandsSeparator;
            nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);
            nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;
            var sNewOutput = sOutput.substring(nDotIndex);
            var nCount = -1;
            for (var i = nDotIndex; i > 0; i--) {
                nCount++;
                if ((nCount % 3 === 0) && (i !== nDotIndex) && (!bNegative || (i > 1))) {
                    sNewOutput = sThousandsSeparator + sNewOutput;
                }
                sNewOutput = sOutput.charAt(i - 1) + sNewOutput;
            }
            sOutput = sNewOutput;
        }
        // Prepend prefix
        sOutput = (opts.prefix) ? opts.prefix + sOutput : sOutput;
        // Append suffix
        sOutput = (opts.suffix) ? sOutput + opts.suffix : sOutput;
        return sOutput;

    } else {
        return opts.defaulValue;
    }
}
function formatCurrency(num, opts) {
    opts = $.extend({},
    {
        decimalSeparator: ".",
        thousandsSeparator: ",",
        decimalPlaces: 2,
        round: true,
        prefix: "",
        suffix: "",
        defaulValue: 0
    }, opts);
    return formatNumber(num, opts);
}

function formatPrecent(num, opts) {
    opts = $.extend({},
    {
        decimalSeparator: ".",
        thousandsSeparator: "",
        decimalPlaces: 2,
        prefix: "",
        suffix: "",
        defaulValue: 0
    }, opts);
    return formatNumber(num, opts);
}

function unformat(val, opts) {
    opts = $.extend({},
    {
        formatter: "number",
        decimalSeparator: ".",
        thousandsSeparator: ",",
        prefix: "",
        suffix: "",
        defaulValue: 0
    }, opts);
    var ret, formatType = opts.formatter;
    if (formatType !== 'undefined' && typeof(formatType) === 'string') {
        var stripTag = eval("/" + opts.thousandsSeparator + "/g");
        switch (formatType) {
            case 'integer':
                ret = val.replace(stripTag, '');
                break;
            case 'number':
                ret = val.replace(opts.decimalSeparator, '.').replace(stripTag, "");
                break;
            case 'currency':
                ret = val.replace(opts.decimalSeparator, '.').replace(opts.prefix, '').replace(opts.suffix, '').replace(stripTag, '');
                break;
        }
    }
    return ret;
}
function unformatCurrency(num, opts) {
    opts = $.extend({},
    {
        formatter: "currency",
        decimalSeparator: ".",
        thousandsSeparator: ",",
        decimalPlaces: 2,
        prefix: "",
        suffix: "",
        defaulValue: 0
    }, opts);
    return unformat(num, opts);
}

//将数字金额进行千位分隔
function formatNum(num) {
    num = "" + num + "";
    var digit = num.indexOf("."); // 取得小数点的位置 
    var int = num.substr(0, digit); // 取得小数中的整数部分 
    var i;
    var mag = new Array();
    var word;
    if (num.indexOf(".") == -1) { // 整数时 
        i = num.length; // 整数的个数 
        while (i > 0) {
            word = num.substring(i, i - 3); // 每隔3位截取一组数字 
            i -= 3;
            mag.unshift(word); // 分别将截取的数字压入数组 
        }
        return mag;
    } else { // 小数时 
        i = int.length; // 除小数外，整数部分的个数 
        while (i > 0) {
            word = int.substring(i, i - 3); // 每隔3位截取一组数字 
            i -= 3;
            mag.unshift(word);
        }
        return mag + num.substring(digit);
    }
}


;(function($) {
    $.htmlEncode = function(value) {
        return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
    };
    $.htmlDecode = function(value) {
        if (value == '&nbsp;' || value == '&#160;') { value = ""; }
        return !value ? value : String(value).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"');
    };
})(jQuery); 


  
//限制TextArea框内容长度
function getInputLength(val) {
    var len = 0;
    for (var i = 0; i < val.length; i++) {
        if (val.charCodeAt(i) >= 0x4e00 && val.charCodeAt(i) <= 0x9fa5) {
            len += 2;
        } else {
            len++;
        }
    }
    return len;
}
function ImposeInputMaxLength(obj, MaxLength) {
    return (getInputLength($(obj).val()) < MaxLength);
}
function ImposePasteMaxLength(obj, MaxLength) {
    var val = $(obj).val();
    var len = getInputLength(val);
    if (len > MaxLength) $(obj).val(val.substring(0, MaxLength));
}

//****************************************************//
//重写了Date对象的prototype,扩展了增加日期的方法
//****************************************************//
Date.prototype.Format = function(fmt) {
    //author: meizz 
    var o =
    {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
Date.prototype.addDays = function(d) {
    this.setDate(this.getDate() + d);
    return this;
};
Date.prototype.addWeeks = function(w) {
    this.addDays(w * 7);
    return this;
};
Date.prototype.addMonths = function(m) {
    var d = this.getDate();
    this.setMonth(this.getMonth() + m);

    if (this.getDate() < d) this.setDate(0);
    return this;
};
Date.prototype.addYears = function(y) {
    var m = this.getMonth();
    this.setFullYear(this.getFullYear() + y);

    if (m < this.getMonth()) this.setDate(0);
    return this;
};
String.prototype.ToDate = function() {
    return new Date(this.replace(/-/g, '/'));
};
String.prototype.JsonToDate = function() {
    return new Date(parseInt(this.replace("/Date(", "").replace(")/", ""), 10));
};

function JsonDateFormat(date, newformat) {
    return (date.JsonToDate()).Format(newformat || "yyyy-mm-dd");
}

//****************************************************//
//重写了Array对象的prototype,扩展了增加数组的方法
//****************************************************//
Array.prototype.indexOf=function(substr,start){ 
	var ta,rt,d='\0'; 
	if(start!=null){ta=this.slice(start);rt=start;}else{ta=this;rt=0;} 
	var str=d+ta.join(d)+d,t=str.indexOf(d+substr+d); 
	if(t==-1)return -1;rt+=str.slice(0,t).replace(/[^\0]/g,'').length; 
	return rt; 
}; 
Array.prototype.lastIndexOf=function(substr,start){ 
	var ta,rt,d='\0'; 
	if(start!=null){ta=this.slice(start);rt=start;}else{ta=this;rt=0;} 
	ta=ta.reverse();var str=d+ta.join(d)+d,t=str.indexOf(d+substr+d); 
	if(t==-1)return -1;rt+=str.slice(t).replace(/[^\0]/g,'').length-2; 
	return rt; 
}; 
Array.prototype.replace=function(reg,rpby){ 
	var ta=this.slice(0),d='\0'; 
	var str=ta.join(d);str=str.replace(reg,rpby); 
	return str.split(d); 
}; 
Array.prototype.search=function(reg){ 
	var ta=this.slice(0),d='\0',str=d+ta.join(d)+d,regstr=reg.toString(); 
	reg=new RegExp(regstr.replace(/\/((.|\n)+)\/.*/g,'\0$1\0'),regstr.slice(regstr.lastIndexOf('/')+1)); 
	t=str.search(reg);if(t==-1)return -1;return str.slice(0,t).replace(/[^\0]/g,'').length; 
}; 
Array.prototype.remove=function(reg){
	return this.removeAt(this.indexOf(reg));
};
Array.prototype.removeAt=function(index){
	if (index >= this.length || index < 0) return this;
	return this.splice(index,1);
};



function HTMLEncode(html) {
    if (html == '' || html == null || html == 'undefined') return '';
    var temp = document.createElement("div");
    //temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
    //var output = temp.innerHTML;
    $(temp).text(html);
    var output = $(temp).html();
    temp = null;
    return output;
}

function HTMLDecode(text) {
    if (text == '' || text == null || text == 'undefined') return '';
    var temp = document.createElement("div");
    //temp.innerHTML = text;
    $(temp).html(text);
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
}

function formatNotes(strNotes) {
    return strNotes.replace(/,/g, "，").replace(/'/g, "’");
}
function onNotesBlur(obj) {
    obj.value = formatNotes(obj.value);
}

function vErr(o, s) {
    alert(s);
    if (o) o.focus();
    return false;
}
function sErr(o, s) {
    alert(s);
    if (o) { o.focus(); o.select(); }
    return false;
}
function TestNum(obj) {
    var str = /^[0-9]*[0-9][0-9]*$/;
    var Num = obj.value;
    if (!str.test(Num)) {
        return sErr(obj, "该数值必须为正整数！例：8");
    }
    return true;
}
function IsNum(obj) {
    var str = /^-?[0-9]*[0-9][0-9]*$/;
    var Num = obj.value;
    if (!str.test(Num)) {
        return sErr(obj, "该数值必须为整数！例：8、-3");
    }
    return true;
}
function IsDigit(obj) {
    var str = /^-?\d+(\.\d+)?$/;
    var Num = obj.value;
    if (!str.test(Num)) {
        return sErr(obj, "该数值必须为数字！例：8.0");
    }
    return true;
}
function IsPhone(obj) {
    //var reg = /^((([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?|(13|15)[0-9]{9})+$/ig;
    var reg = /^(0[0-9]{10,11}|(13|15|18)[0-9]{9})+$/ig;
    var str = obj.value;
    if (!reg.test(str)) { return sErr(obj, '不是有效的电话或手机号码！\n\r例：02088450440、13877708888'); }
    return true;
}

