/**
 * 留言本
 * 
 * @author linxs@35.cn
 */
(function($) {
	$.fn.cavanFeedback = function(o) {
		// 默认参数
		o = $.extend({
			key: null,
			message: {
				msg_default: "谢谢您宝贵的留言，站点管理员将会尽快联系您。",
				err_mail: "电子邮件格式不正确。",
				err_input: "输入超过20个字符。",
				err_code: "验证码输入有误。",
				err_message: "请输入留言内容。",
				err_message1: "输入超过100个字符。"
			}
		}, o || {});

		// 插件扩展
		return this.each(function() {
			var form = $(this);

			o.key = "cookie_" + form.attr('id');

			// 验证码
			createSafeCode(form);
			$(".safecode_con", form).css("cursor", "pointer").click(function() {
				createSafeCode(form);
			});

			// 邮件主体
			$(".emailbody", form)
			.focus(function() {
				if ($(this).val() == o.message.msg_default) {
					$(this).val("");
				}
			})
			.blur(function() {
				if ($(this).val() == "") {
					$(this).val(o.message.msg_default);
				}
			});

			// 验证表单
			form.submit(function() {
				// Input
				var falg = false;
				$("#input", form).each(function(i) {
					if (strLen($(this).val()) > 20) {
						falg = $(this);
						return false;
					}
				});
				if (falg) {
					alert(o.message.err_input);
					falg.select();
					return false;	
				}
				
				// Email
				var useremail = $(".useremail", form);
				if (!(useremail.val() == "" || isEmail(useremail.val()))) {
					alert(o.message.err_mail);
					useremail.select();
					return false;
				}
				
				// Body
				var emailbody = $(".emailbody", form);
				if (emailbody.val() == '') {
					emailbody.val(o.message.msg_default);
					return false;
				} else if (emailbody.val() == o.message.msg_default) {
					alert(o.message.err_message);
					emailbody.focus();
					return false;
				} else if (strLen(emailbody.val()) > 100) {
					alert(o.message.err_message1);
					emailbody.select();
					return false;
				}
				
				// Safecode
				var safecode = $(".safecode", form);
				if (RequestCookies(o.key, form) != safecode.val()) {
					alert(o.message.err_code);
					safecode.select();
					return false;
				}
				
				var btnsubmit = $(":submit", form);
				btnsubmit.attr("disabled", true);
				$.ajax({
					type: "POST",
					url: $(this).attr("action"),
					data: $(this).formSerialize(),
					success: function(msg) {
						alert(msg);
						document.getElementById(form.attr("id")).reset();
						btnsubmit.attr("disabled", false);
						createSafeCode(form);
					}
				});
				
				return false;
			});
		});
		
		// 计算文本的字节数
		function strLen(content) {
			var length = 0;
			if (content != '' && content != undefined) {
				content = content.replace(/^\s+|\s+$/g, ''); 
				for (i = 0; i < content.length; i++) {
					if(content.charCodeAt(i) > 256) {   
						length += 2;
					} else {
						length += 1;
					}
				}
			}

			return length;
		}
		
		// 生成验证码
		function createSafeCode(form) {
			var code = Math.ceil(Math.random()*10000);
			while(code < 1000) {
				code = Math.ceil(Math.random()*10000);
			}
			
			$(".safecode_val", form).html(code);
			ResponseCookies(o.key, code, form);
		}

		// EMAIL格式验证
		function isEmail(value) {
			try {
				var pattern=/^(([a-z A-Z \-_ 0-9]+)@[a-z A-Z \-_ 0-9]+\.([a-z A-Z]+(\.)?)?[a-z A-Z]+)$/;
				return pattern.test(value);
			} catch(e) {
				return false;
			}
		};

		// 生成COOKIE
		function ResponseCookies(cookieName, cookieValue, form) {
			$(".safecode", form).data(cookieName, cookieValue);
		}

		// 取得COOKIE
		function RequestCookies(cookieName, form) {
			return $(".safecode", form).data(cookieName);
		}
	};
	
	/// --- ///
	
	/**
	 * formToArray() gathers form element data into an array of objects that can
	 * be passed to any of the following ajax functions: $.get, $.post, or load.
	 * Each object in the array has both a 'name' and 'value' property.  An example of
	 * an array for a simple login form might be:
	 *
	 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
	 *
	 * It is this array that is passed to pre-submit callback functions provided to the
	 * ajaxSubmit() and ajaxForm() methods.
	 */
	$.fn.formToArray = function(semantic) {
		var a = [];
		if (this.length == 0) return a;
	
		var form = this[0];
		var els = semantic ? form.getElementsByTagName('*') : form.elements;
		if (!els) return a;
		for(var i=0, max=els.length; i < max; i++) {
			var el = els[i];
			var n = el.name;
			if (!n) continue;
	
			if (semantic && form.clk && el.type == "image") {
				// handle image inputs on the fly when semantic == true
				if(!el.disabled && form.clk == el)
					a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
				continue;
			}
	
			var v = $.fieldValue(el, true);
			if (v && v.constructor == Array) {
				for(var j=0, jmax=v.length; j < jmax; j++)
					a.push({name: n, value: v[j]});
			}
			else if (v !== null && typeof v != 'undefined')
				a.push({name: n, value: v});
		}
	
		if (!semantic && form.clk) {
			// input type=='image' are not found in elements array! handle them here
			var inputs = form.getElementsByTagName("input");
			for(var i=0, max=inputs.length; i < max; i++) {
				var input = inputs[i];
				var n = input.name;
				if(n && !input.disabled && input.type == "image" && form.clk == input)
					a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
		}
		return a;
	};
	
	/**
	 * Serializes form data into a 'submittable' string. This method will return a string
	 * in the format: name1=value1&amp;name2=value2
	 */
	$.fn.formSerialize = function(semantic) {
		//hand off to jQuery.param for proper encoding
		return $.param(this.formToArray(semantic));
	};
	
	/**
	 * Returns the value of the field element.
	 */
	$.fieldValue = function(el, successful) {
		var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
		if (typeof successful == 'undefined') successful = true;
	
		if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
			(t == 'checkbox' || t == 'radio') && !el.checked ||
			(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
			tag == 'select' && el.selectedIndex == -1))
				return null;
	
		if (tag == 'select') {
			var index = el.selectedIndex;
			if (index < 0) return null;
			var a = [], ops = el.options;
			var one = (t == 'select-one');
			var max = (one ? index+1 : ops.length);
			for(var i=(one ? index : 0); i < max; i++) {
				var op = ops[i];
				if (op.selected) {
					var v = op.value;
					if (!v) // extra pain for IE...
						v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
					if (one) return v;
					a.push(v);
				}
			}
			return a;
		}
		return el.value;
	};
})(jQuery);