
/*以下为Ajax辅助工具*/
function AjaxResult(data) {
	this.success = function() {
		return (data['ajax_code'] == 0);
	};

	this.getCode = function() {
		return data['code'];
	};

	this.getMsg = function() {
		return unicode2GB(data['msg']);
	};

	this.getData = function() {
		return data['data'];
	};
	this.getMsg2 = function() {
		return unicode2GB(data['msg2']);
	};
}

function getAjaxResult(data, type) {
	try {
		eval('content=' + data + ';');
	} catch (e) {
		var content = [];
		content['ajax_code'] = 0;
		content['data'] = data;
		if (1 != type || data.indexOf('<b>Fatal error</b>') > -1) {
			content['ajax_code'] = -1;
			content['msg'] = data;
		}
	}
	// 如果是json_encode编码过的数据，则content应该是对象，
	// 如果eval抛出异常，则content为数组，如果content既不是
	// 对象也不是数组，则说明返回的是页面数据
	if(!isObject(content) && !isArray(content)) {
		var content = [];
		content['ajax_code'] = 0;
		content['data'] = data;		
		if (1 != type || data.indexOf('<b>Fatal error</b>') > -1) {
			content['ajax_code'] = -1;
			content['msg'] = data;
		}
	}
	
	return new AjaxResult(content);
}

jQuery.getEx = function(url, func, data_type) {
	if (!data_type) {
		data_type = 0;
	}

	jQuery.ajax( {
		type: "GET",
		url: url,
		cache: false,
		success : function(data) {
			var ajax_result = getAjaxResult(data, data_type);
			func(ajax_result);
			return true;
		}
	});
}

jQuery.postEx = function(url, postdata, callback, data_type) {
	if (!data_type) {
		data_type = 0;
	}
	
	jQuery.ajax( {
		type: "POST",
		data: postdata,
		url: url,
		cache: false,
		// async :false,
		success : function(data) {
			var ajax_result = getAjaxResult(data, data_type);
			if ('function' == typeof (callback)) {
				callback(ajax_result);
			}
			return true;
		}
	});
}

jQuery.fn.submitEx = function(url, func, date_type) {
	var form = this.serialize();
	jQuery.postEx(url, form, function(data) {
		func(data);
	}, date_type);
}

//var obj = document.createElement("script");
//obj.src = "/common/view/ajaxfileupload.js";
jQuery.submitExUpload = function(url, secureuri, fileElementId, dataType, func) {
	$.ajaxFileUpload( {
		url :url,
		secureuri :secureuri,
		fileElementId :fileElementId,
		dataType :'json',
		success : function(data) {
			var ajax_result = new AjaxResult(data);
			func(ajax_result);
		},
		error : function(data) {
			var content = [];
			content['ajax_code'] = -1;
			content['msg'] = '您上传的文件不存在';
			var ajax_result = new AjaxResult(content);
			func(ajax_result);
		}
	})
}

/**
 * 提交Ajax请求，并显示请求的结果信息
 */
jQuery.getAndShowMsg = function(url, error_id, success_id, postdata, callback) {
	if ('' == error_id) {
		error_id = 'ajax_result';
	}
	if ('' == success_id) {
		success_id = 'ajax_result';
	}
	
	// 清除之前的提示信息
	$('#' + error_id).empty();
	$('#' + error_id).removeClass();
	$('#' + success_id).empty();
	$('#' + success_id).removeClass();
	
	jQuery.postEx(url, postdata, function(data){
		if ('function' == typeof (callback)) {
			callback(data);
		}
		if (data.success()) {
			showSuccessMsg(success_id, data.getMsg());
		} else {
			showErrorMsg(error_id, data.getMsg());
		}
		
		return true;
	});
}

/**
 * 提交Ajax请求，并显示请求的结果信息
 */
jQuery.getExAndShow = function(url, id, postdata, callback) {
	jQuery.getAndShowMsg(url, id, id, postdata, callback);
}

/**
 * 提交Ajax请求，如果成功则关闭窗口并提示，如果失败则提示失败信息。
 */
jQuery.getAndCloseWindow = function(url, error_id, success_id, win_id, postdata, callback) {
	jQuery.getAndShowMsg(url, error_id, success_id, postdata, function(data){
		if ('function' == typeof (callback)) {
			callback(data);
		}
		
		if (data.success()) {
			closeWindow(win_id);
		}
	});
}

/**
 * 提交Ajax请求，如果成功则弹出窗口，如果失败则提示失败信息
 */
jQuery.getExAndPop = function(url, id, title, pop_id, postdata, callback) {
	if ('' == id)
		id = 'ajax_result';
	
	jQuery.postEx(url, postdata, function(ajax_result){
		$('#' + id).empty();
		$('#' + id).removeClass();
		if (ajax_result.success()) {
			openWindow(title, ajax_result.getData(), pop_id, '');
			$('#' + id).empty();
			$('#' + id).removeClass();
		} else {
			showErrorMsg(id, ajax_result.getMsg());
		}
		if ('function' == typeof (callback)) {
			callback(ajax_result);
		}
	}, 1);
}



function unicode2GB(str) {
	str += '';
	str = str.replace(/(\\u)(\w{4})/gi, function($0) {
		return (String.fromCharCode(parseInt((escape($0).replace(
				/(%5Cu)(\w{4})/g, "$2")), 16)));
	});

	str = str.replace(/(&#x)(\w{4});/gi, function($0) {
		return String.fromCharCode(parseInt(escape($0).replace(
				/(%26%23x)(\w{4})(%3B)/g, "$2"), 16));
	});

	return str;
}
String.prototype.length_cn = function() {
	var noteLen = this.match(/[^\r|\n| -~]/g) == null ? this.replace(
			/[\r|\n]/g, "").length : this.replace(/[\r|\n]/g, "").length
			+ this.match(/[^\r|\n| -~]/g).length;
	return noteLen;
}
$(document)
		.ready(
				function() {
					$("form:not([action])").submit( function() {
						return false;
					});

					var html = '<div id="loadingdiv" class="shadow" style="display:none;"><div class="erro_load2">页面正在加载中....</div></div>';
					$('body').append(html);

					if (!$("#ajaxiframeBg").attr('id')) {
						var html = '';
						html = '<iframe id="ajaxframe" width="100%" height="100%" frameborder="0" style="filter: alpha(opacity = 0); opacity: 0;"></iframe>';
						var tmp = jQuery("<div id='ajaxiframeBg' style='display:none;z-index:2000;position:absolute'/>");
						tmp.append(html);
						$("body").append(tmp);
					}
					$("#ajaxiframeBg").css("display", "block");
					$("#ajaxiframeBg").css("left", "0px");
					$("#ajaxiframeBg").css("top", "0px");

					$("#ajaxiframeBg").hide();

					$('#loadingdiv')
							.ajaxSend(
									function() {
										var v_height = $(window).height();
										var v_width = $(window).width();

										$('#loadingdiv')
												.css(
														'left',
														(document.documentElement.scrollLeft
																+ v_width / 2 - $(
																'#loadingdiv')
																.width() / 2) + 'px');
										$('#loadingdiv')
												.css(
														'top',
														(document.documentElement.scrollTop
																+ v_height / 2 - $(
																'#loadingdiv')
																.height() / 2) + 'px');
										$("#ajaxiframeBg")
												.css(
														"height",
														document.documentElement.scrollHeight
																+ "px");
										$("#ajaxiframeBg")
												.css(
														"width",
														document.documentElement.scrollWidth
																+ "px");

										$('#ajaxframe').show();
										$("#ajaxiframeBg").show();
										$('#loadingdiv').show();
									});
					$('#loadingdiv').ajaxComplete( function() {
						$('#loadingdiv').hide();
						$('#ajaxframe').hide();
						$("#ajaxiframeBg").hide();
					});
					$('#loadingdiv').ajaxError( function() {
						$('#loadingdiv').hide();
						$("#ajaxiframeBg").hide();
						$('#ajaxframe').hide();
					});
				});

/**
 * 更新fckeditor控件iframe内容至隐藏表单域中 使用ajax提交表单信息时，在表单提交之前调用，解决提交内容为空的问题
 */
function updateFckEditor() {
	for (i = 0; i < parent.frames.length; ++i) {
		if (parent.frames[i].FCK) {
			parent.frames[i].FCK.UpdateLinkedField();
		}
	}
}
function FCKeditor_OnComplete( editorInstance )
{
	var oEditor = FCKeditorAPI.GetInstance(editorInstance.Name) ;	oEditor.Focus();
}
function getFckValue(value) {
	return value.replace(/(&nbsp; *)|<br type=\"_moz\" \/>|(<br \/>)*/g, '');
}

function Add2Favorite(){
	if (document.all)	window.external.AddFavorite(document.location.href,document.title);
	else if (window.sidebar)	window.sidebar.addPanel(window.document.title,document.location.href,'');
} 
/**
 * 取得表格(table)下所有input、select元素的id及类型
 * 
 * @param string
 *            table_id 表格id
 * @return array 返回元素id及类型([{id, type}])
 */
function getTableElemIds(table_id) {
	var input = '#' + table_id + ' input';
	var select = '#' + table_id + ' select';
	var selector = input + ',' + select;
	var i = 0;
	var ids = [];
	$(selector).each( function() {
		var id = $(this).attr('id');
		var type = $(this).attr('type');
		ids[i] = {};
		ids[i].id = id;
		ids[i].type = type;
		++i;
	})

	return ids;
}

/**
 * 根据id将一组input、select元素的值拷贝至另一组input、select元素
 * 两组元素的id必须相对应，具有不同前缀的相同id，如r_name:a_name
 * 
 * @param array
 *            ids 源元素组id及类型
 * @param string
 *            s_prefix 源元素组的id前缀
 * @param string
 *            d_prefix 目的元素组的id前缀
 * @return
 */
function copyValuesById(ids, s_prefix, d_prefix) {
	var length = ids.length;
	for ( var i = 0; i < length; ++i) {
		var type = ids[i].type;
		var s_id = ids[i].id;
		var d_id = d_prefix + s_id.substring(s_prefix.length, s_id.length);
		if (''==s_id) continue;
		if (type == 'text') {
			$('#' + d_id).val($('#' + s_id).val());
		} else {
			$('#' + d_id).val($('#' + s_id).val());
		}
	}
}

// This function used to append an error message after the input filed.
// tagType is the type of input fileds such as <input <textarea
// tagName is the name of the input filed.
// msg is the respond message.
function appendErrorNote(tagType, tagName, msg) {
	var err = '<span class="error_note erro-stop" >' + msg + '</span>';
	if ($(tagType + "[name=" + tagName + "]")) {
		$(tagType + "[name=" + tagName + "]").parent().append(err);
	} else {
		$(tagType + "[name=" + tagName + "]").parent().append(err);
	}

}
// clearn the error tag
function clearErrorNote() {
	$('span.erro-stop').css("display", "none");
}

// clear the result message.
function clearResultTag(divId) {
	$("#" + divId).html('');
	$("#" + divId).removeClass();
}

// return the lenth of chinese characters
function length_cn(note) {
	var noteLen = note.match(/[^\r|\n| -~]/g) == null ? note.replace(
			/[\r|\n]/g, "").length : note.replace(/[\r|\n]/g, "").length
			+ note.match(/[^\r|\n| -~]/g).length;
	return noteLen;
}

function isObject(test) {  
	return (typeof test == 'object' && test.constructor==Object);  
}

function isArray(test) {  
	return (typeof test == 'object' && test.constructor==Array);  
}

function isString(str) {
	return (typeof str=='string')&&str.constructor==String;
}

/**
 * 自动等高
 */
(function($) {
	$.fn.equalHeights = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			if($(this).height() > tallest) {
				tallest = $(this).height();
			}
		});
		if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			$(this).height(tallest).css("overflow","auto");
		});
	}
})(jQuery);


/**
 * 以下为表单验证函数
 */
function checkMailFormat(mail) {
	return (/^\w[\w.]+@[\w]+(.\w{2,})+$/.test(mail));
}

function checkDnsFormat(dns) {
	if (dns.length > 100) {
		return false;
	}
	return (/^[0-9a-zA-Z]+[0-9a-zA-Z\.-]*\.[0-9a-zA-Z]{2,4}$/.test(dns));
}

function checkMailDomainFormat(domain) {
	if (length_cn(domain) > 67) {
		return false;
	}
	return (/(?!^([wW][wW][wW]\.)\S*$)^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})*\.[0-9a-zA-Z]{2,4}$/.test(domain));
}

function checkDomainFormat(domain) {
	if (length_cn(domain) > 67) {
		return false;
	}
	return (/^[0-9a-zA-Z\u4E00-\u9FA5]+[0-9a-zA-Z\.-\u4E00-\u9FA5]*\.[0-9a-zA-Z\u4E00-\u9FA5]{2,4}$/.test(domain));
}

function checkVhostFormat(username) {
        if (length_cn(username)>32 || length_cn(username)<1) { 
                return false;
        }
        return (/^[a-zA-Z][0-9a-zA-Z-]+$/.test(username));
}

/**
 * 检查是否为Ascii字符(33～126之间的所有字符，不包含空格)
 * @param str
 * @return
 */
function checkAscii(str) {
	return (/^[\x21-\x7e]*$/.test(str));
}

function checkMailPasswd(str) {
	if (!/^[0-9a-zA-Z]*$/.test(str)) {
		return false;
	}
	if (!(/[0-9]/.test(str) && /[a-z]/.test(str) && /[A-Z]/.test(str))) {
		return false;
	}
	if (/^Aa123456$/.test(str)) {
		return false;
	}
	return true;
}
function checkVeriPassword(str) {
if (/(?![^a-zA-Z]*$)(?![^0-9]*$)(?![^\!\#\$\%\(\)\*\+\,\-\.\/\:\=\?\@\[\]\^\_\`\{\|\}\~]*$)^[a-zA-Z0-9\!\#\$\%\(\)\*\+\,\-\.\/\:\=\?\@\[\]\^\_\`\{\|\}\~]{8,16}$/.test(str)) 
	return true;
else return false;	
}

function checkPwdFormat(str) {
	return (/[;'\\<>"&]/.test(str));
}
function checkNumber(str) {
	return (/^[0-9]*$/.test(str));
}

function checkImageFileSize(id, limit) {
	if (!limit) {
		limit = 1024;
	}

	var src = $('#' + id).val();
	if (src == '') {
		return false;
	}

	var img = new Image();
	img.src = src;
	if (img.fileSize > limit * 1024) {
		return false;
	}

	return true;
}

function checkImageFileType(src, type) {
	if (!type) {
		type = '.gif,.jpg,.png,.jpeg,.bmp';
	}
	var ext = src.substr(src.lastIndexOf('.')).toLowerCase();
	return type.indexOf(ext) >= 0;
}

function checkImageFile(id, type, limit) {
	if (!limit) {
		limit = 1024;
	}
	if (!type) {
		type = '.gif,.jpg,.png,.jpeg,.bmp';
	}

	var src = $('#' + id).val();
	if (src == '') {
		return '请选择要上传的图片';
	}

	if (!checkImageFileType(src, type)) {
		return '上传的图片只能为.gif、.jpg、.png、.jpeg、.bmp格式的文件';
	}

	var img = new Image();
	img.src = 'file:///'+src;
//	alert(img.fileSize);
	
	if (img.fileSize > limit * 1024) {
		return '图片大小不能超过1M';
	}
	
	return true;
}

/**
 * 更新会员资金余额信息(仅客户端系统有效)
 */
function updateMemberAccount() {
	if ($('#member_account').attr('id')) {
		var url = '/?pac=chain_client&pme=getMemberAccount';
		jQuery.getEx(url, function(data) {
			if (data.success()) {
				data = data.getData();
				var account = data['account']+'元';
				$('#member_account').html(account);
			}
		});
	}
}

