/**
 * 身份证号码验证
*
 */
function isIdCardNo(num) {

	var factorArr = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1);
	var parityBit=new Array("1","0","X","9","8","7","6","5","4","3","2");
	var varArray = new Array();
	var intValue;
	var lngProduct = 0;
	var intCheckDigit;
	var intStrLen = num.length;
	var idNumber = num;
	// initialize
	if ((intStrLen != 15) && (intStrLen != 18)) {
		return false;
	}
	// check and set value
	for(i=0;i<intStrLen;i++) {
		varArray[i] = idNumber.charAt(i);
		if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
			return false;
		} else if (i < 17) {
			varArray[i] = varArray[i] * factorArr[i];
		}
	}
	
	if (intStrLen == 18) {
		//check date
		var date8 = idNumber.substring(6,14);
		if (isDate8(date8) == false) {
			return false;
		}
		// calculate the sum of the products
		for(i=0;i<17;i++) {
			lngProduct = lngProduct + varArray[i];
		}
		// calculate the check digit
		intCheckDigit = parityBit[lngProduct % 11];
		// check last digit
		if (varArray[17] != intCheckDigit) {
			return false;
		} 
	}
	else{ //length is 15
		//check date
		var date6 = idNumber.substring(6,12);
		if (isDate6(date6) == false) {
			return false;
		}
	}
	return true;

}


//jquery validate 组件
(function($) {
	
	platformValidateDefault={//默认配置
		errorElement: 'span', //default input error message container
        errorClass: 'error', // default input error message class
        focusInvalid: false, // do not focus the last invalid input
        ignore: "",
		highlight: function (element) { // hightlight error inputs
			$(element).closest('div').addClass("f_error");
			//$(element).closest('.help-inline').removeClass('ok'); // display OK icon
			//$(element).closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
		},
		
		unhighlight: function (element) { // revert the change dony by hightlight
			//$(element).closest('.control-group').removeClass('error'); // set error class to the control group
			$(element).closest('div').removeClass("f_error");
		},
		submitHandler: function (form) {
			form.submit();
		}
	};
	$.extend($.fn, {
		platformValidate:function(options){//校验方法
			if ( $(this[0]).is('form')) {
				var settings = $.extend( true, {},platformValidateDefault, options );
				var validator=this.validate(settings);
				return validator;
			}else{
				
			}
		}
	});
	
	//字母数字
	jQuery.validator.addMethod("alnum", function(value, element) {
	 return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value);
	 }, "只能包括英文字母和数字");
	
	// 汉字
	jQuery.validator.addMethod("chcharacter", function(value, element) {
	 var tel = /^[\u4e00-\u9fa5]+$/;
	 return this.optional(element) || (tel.test(value));
	 }, "请输入汉字");
	
	// 身份证号码验证 
	jQuery.validator.addMethod("idcardno", function(value, element) {
	 return this.optional(element) || isIdCardNo(value); 
	 }, "请正确输入身份证号码");
	
	// 手机号码验证
	jQuery.validator.addMethod("mobile", function(value, element) {
	 var length = value.length;
	 return this.optional(element) || (length == 11 && /^(((1[0-9]{2}))+\d{8})$/.test(value));
	 }, "手机号码格式错误!");

	// 电话号码验证
	jQuery.validator.addMethod("phone", function(value, element) {
	 var tel = /^(\d{3,4}-?)?\d{7,9}$/;
	 return this.optional(element) || (tel.test(value));
	 }, "电话号码格式错误!");

}(jQuery));


//dataTable 组件
(function($) {
	
	platformDataTableDefault={//默认配置
			"bDestory": true,
			"bLengthChange": false,// 每页显示的记录数
			"bServerSide" : true,//服务端处理分页
			"bProcessing": false,//当datatable获取数据时候是否显示正在处理提示信息
			"bPaginate" : true,//是否分页
			"bFilter" : false,//关闭搜索
			"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
	        	oSettings.jqXHR = $.ajax( {
	              "dataType": 'json',
	              "type": "POST",
	              "url": sSource,
	              "data": aoData,
	              "success": fnCallback
	            } );
			},
			"sServerMethod" : "POST",
			"iDisplayStart" : 0,
			"iDisplayLength" : 10,//每页显示6条记录
			"sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",//定义DataTable布局的一个强大属性
			"sPaginationType" : "bootstrap",//分页样式
			"oLanguage" : {//语言国际化
				"oPaginate" : {
				"sProcessing" : "正在加载中......",
				"sFirst": "首页",
				"sPrevious" : "上一页",
				"sNext": "下一页",
				"sLast": "末页"},
				"sSearch": "搜索",
				"sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
				"sEmptyTable": "没有查询到数据！",
				"sInfoEmpty": "当前显示0 条，共 _TOTAL_ 条记录"
			},
			"aoColumnDefs" : [ { 'sDefaultContent' : '',  'aTargets': [ '_all' ] } ]
	};
	$.extend($.fn, {
		platformDataTable:function(options){//校验方法
			if ( $(this[0]).is('table')) {
				var settings = $.extend( true, {},platformDataTableDefault, options );
				var dataTable=this.dataTable(settings);
				return dataTable;
			}else{
				
			}
		}
	});
}(jQuery));

//Ajax重新load控件数据
//tables--datatable对象
//data--存放查询条件的json数组
function drawTable(tables,data){
    var oSettings = tables.fnSettings();
    oSettings.fnServerData = function ( sSource, aoData, fnCallback, oSettings ) {
    	for(var i=0;i<data.length;i++){
    		aoData.push(data[i]);
    	}
        oSettings.jqXHR = $.ajax( {
			"dataType": 'json',
			"type": "POST",
			"url": sSource,
			"data": aoData,
			"success": fnCallback
		} );
    };
    //tables.fnClearTable(0);
    tables.fnDraw();
}

/**
 * alertStyle: alert-success 正确  绿色
 *             alert-danger  错误  红色
 *             alert-warning 警告  黄色
 *             alert-info    信息  蓝色
 * promptContent:提示内容
 * outTime：消失时间
 */
function platformAlert(type,promptContent,autoclose, callback){
	if(type == "alert-success"){
		type="success";
	}else if(type == "alert-danger"){
		type="error";
	}else if(type == "alert-warning"){
		type="error";
	}else if(type == "alert-info"){
		type = "info";
	}
	type=type==null||type==""?"st-info":"st-"+type;
	autoclose=autoclose==null||autoclose==""?5000:autoclose;
	var position="top-right";
	$.sticky(promptContent, {autoclose : autoclose, position:position, type: type },callback);
}

/**
 * 成功信息提示  绿色
 * @param promptContent
 */
function platformSuccess(promptContent,callback){
	platformAlert("success",promptContent, 5000000, callback);
}

/**
 * 错误信息提示   红色
 * @param promptContent
 */
function platformDanger(promptContent, callback){
	platformAlert("error",promptContent, 5000, callback);
}


/**
 * 信息提示   蓝色
 * @param promptContent
 */
function platformInfo(promptContent, callback){
	platformAlert("info",promptContent, 5000, callback);
}

/**
 * 预览图标
 */
function previewIcon(file,iconview,icon) {
	var MAXWIDTH = 400;
	var MAXHEIGHT = 400;
	var div = document.getElementById(iconview);
	if (file.files && file.files[0]) {
		div.innerHTML = '<img id=' + icon +'>';
		var img = document.getElementById(icon);
		img.onload = function() {
			var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT,img.offsetWidth, img.offsetHeight);
			img.width = rect.width;
			img.height = rect.height;
			img.style.marginLeft = rect.left + 'px';
			img.style.marginTop = rect.top + 'px';
		}
		var reader = new FileReader();
		reader.onload = function(evt) {
			img.src = evt.target.result;
		}
		reader.readAsDataURL(file.files[0]);
	} else {
		var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
		file.select();
		var src = document.selection.createRange().text;
		div.innerHTML = '<img id=imghead>';
		var img = document.getElementById('imghead');
		img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
		var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
		status = ('rect:' + rect.top + ',' + rect.left + ',' + rect.width + ',' + rect.height);
		div.innerHTML = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;margin-left:"+rect.left+"px;"+sFilter+src+"\"'></div>";
	}
}

/**
 *Img缩放参数
 **/
function clacImgZoomParam(maxWidth, maxHeight, width, height) {
	var param = {top : 0,left : 0,width : width,height : height};
	if (width > maxWidth || height > maxHeight) {
		rateWidth = width / maxWidth;
		rateHeight = height / maxHeight;
		if (rateWidth > rateHeight) {
			param.width = maxWidth;
			param.height = Math.round(height / rateWidth);
		} else {
			param.width = Math.round(width / rateHeight);
			param.height = maxHeight;
		}
	}
	param.left = Math.round((maxWidth - param.width) / 2);
	param.top = Math.round((maxHeight - param.height) / 2);
	return param;
}

