/*!
 * jQuery Form Validateion Plugin
 * version: 1.0 (25-APR-2011)
 *
 * Provider: http://www.cnbbr.com/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * Required:
 *		jquery.js --- provider:http://jquery.com/ ; version:v1.3.2 or later
 *		jquery.form.js --- provider:http://www.malsup.com/jquery/form/ ; version:v2.69 or later
 */
;(function($) {	// noflict for $ jquery
	$.fn.cnbbrformvalidator = function(){}
	$.fn.cnbbrformvalidator.isnum = function(oNum){
		  if(!oNum) return false; 
		  var strP=/^\d+(\.\d+)?$/; 
		  if(!strP.test(oNum)) return false; 
		  try{ 
		  if(parseFloat(oNum)!=oNum) return false; 
		  } 
		  catch(ex) 
		  { 
		   return false; 
		  } 
		  return true; 
	}
	$.fn.cnbbrformvalidator.strlength = function(teststrval){
		var teststrlen = 0;
		if(teststrval){teststrlen=teststrval.replace(/[\u4e00-\u9fa5]/g,"**").length;}
		return teststrlen;
	}
	$.fn.cnbbrformvalidator.init = function(){
		$(".bbr_form_listbox").each(function(i){
			var theprompt=$(this).attr("prompt");
			var thepromptobject = $(".bbr_form_prompt_listbox").eq(i);
			$(this).attr("status",false);
			$(this).children('input,select').blur(function(){
				var checkedcount=0;
				var checkedcount_test_result=false;
				var checkedlenrange=$(this).parent().attr("lenrange");
				if($(this).attr("type")=="radio"){checkedlenrange='1';}
				if(checkedlenrange){
					checkedlenrange=checkedlenrange.split(',');
					var checkedmin=parseInt(checkedlenrange[0]);
					var checkedmax=0;
					if(checkedlenrange.length>1){ checkedmax=parseInt(checkedlenrange[1]); }
					$(this).parent().children('input').each(function(){
						if($(this).attr("checked")){
							checkedcount=checkedcount+1;
							$(this).addClass("checkedsuccess");
						}else{
							$(this).removeClass("checkedsuccess");
						}
					});
					$(this).children('option').each(function(){
						if($(this).attr("selected")){
							checkedcount=checkedcount+1;
							$(this).addClass("checkedsuccess");
						}else{
							$(this).removeClass("checkedsuccess");
						}
					});
					if(checkedcount>=checkedmin){ checkedcount_test_result=true; }
					if(checkedmax>0 && checkedcount_test_result){
						if(checkedcount<=checkedmax){
							checkedcount_test_result=true;
						}else{
							checkedcount_test_result=false;
						}
					}
				}else{
					checkedcount_test_result=true;
				}
				if(checkedcount_test_result){
					thepromptobject.removeClass("bbr_form_error");
					thepromptobject.html('');
					thepromptobject.hide();
					$(this).parent().attr("status",true);
				}else{
					if(!theprompt){theprompt='選項錯誤！共需選中'+checkedlenrange+'項';}
					$(this).parent().children('input').each(function(){
						$(this).removeClass("checkedsuccess");
					});
					thepromptobject.addClass("bbr_form_error");
					thepromptobject.html(theprompt);
					thepromptobject.show();
				}
			});
		});
		$(".bbr_form_text").each(function(i){
			var theprompt=$(this).attr("prompt");
			var thepromptobject = $(".bbr_form_prompt_text").eq(i);
			
			$(this).attr("status",false);
			$(this).focus(function(){
				$("#bbr_form_success_"+i).hide();
				$(this).removeClass("inputerror");
				$(this).removeClass("inputsuccess");
				$(this).addClass("selected");
				if(!theprompt){theprompt='請輸入...';}
				thepromptobject.removeClass("bbr_form_error");
				thepromptobject.addClass("bbr_form_prompt");
				thepromptobject.html(theprompt);
				thepromptobject.show();
				
			}).blur(function(){
				$(this).removeClass("selected");
				$.fn.cnbbrformvalidator.validation($(this),i);
				//$("#bbr_form_submit_outer").hide();
			});
		});
		$(".xheditor-mfull").each(function(i){
			$(this).attr("status",false);
		});
	}
	
	$.fn.cnbbrformvalidator.pattern=function(objname){
		var pattern="";
		switch(objname){
			case "bbrinteger":
				pattern="^[0-9]+$";
				break;
			case "bbrstring":
				pattern="^[\\w]+$";
				break;
			case "bbrchinesestring":
				pattern="^[\\u4e00-\\u9fa5]+$";
				break;
			case "bbrdatetime":
				pattern="^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}( [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2})?$";
				break;
			case "bbrmoney":
				pattern="^[\\-]?([1-9][0-9]*|0)(.[0-9]{1,2})?$";
				break;
			case "bbrcolor":
				pattern="^([A-Za-z]+|#[A-Fa-f0-9]{6})+$";
				break;
			case "bbripaddress":
				pattern="^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$";
				break;
			case "bbruemail":
				pattern="^([\\w\\-\\.])+@([\\w-])+\\.[A-Za-z]{2,10}$";
				break;
			case "bbruname":
				pattern="^[\\w\\u4e00-\\u9fa5]{2,20}$";
				break;
			case "unionbbruname":
				pattern="^[\\w]+@[\\w-]{2,10}|[\\w\\u4e00-\\u9fa5]{2,20}$";
				break;
			case "bbrupass":
				pattern="^[a-zA-Z0-9~!@#=_%&:.;<>|\/\\,\\?\\$\\^\\*\\(\\)\\-\\+\\{\\}\\[\\]\\\\]{6,20}$";
				break;
			case "vertifycode":
				pattern="^[A-Za-z0-9]{2,10}$";
				break;
			case "bbrids":
				pattern="^[0-9]+(, [0-9]+)*$";
				break;
		}
		//alert(objname);
		//alert(pattern);
		return pattern;
	}
	
	$.fn.cnbbrformvalidator.validation=function(jqthis,i){
		var theprompt=jqthis.attr("prompt");
		var theerror=jqthis.attr("error");
		var thepromptobject = $(".bbr_form_prompt_text").eq(i);
		var therequired=jqthis.attr("required");
		var theregex=jqthis.attr("regex");
		var thelenrange=jqthis.attr("lenrange");
		var theajaxurl=jqthis.attr("ajaxurl");
		var theajaxerror=jqthis.attr("ajaxerror");
		var theajaxerrorcallback=jqthis.attr("ajaxerrorcallback");
		var theOffset = jqthis.offset();
		var theOuterWidth = jqthis.outerWidth();
		var theInputSuccessContainer = $("<div id=\"bbr_form_success_"+i+"\"></div>");
		if(!theerror){theerror='輸入格式有誤或長度不符['+thelenrange+']';}
		if(jqthis.val()==''){
			if(therequired){
				$("#bbr_form_success_"+i).hide();
				jqthis.removeClass("inputsuccess");
				jqthis.addClass("inputerror");
				thepromptobject.removeClass("bbr_form_prompt");
				thepromptobject.addClass("bbr_form_error");
				thepromptobject.html('必填項，請按提示輸入');
				thepromptobject.show();
				jqthis.attr("status",false);
			}else{
				thepromptobject.hide();
			}
		}else{
			var regex_test_result=false;
			var regExPattern=$.fn.cnbbrformvalidator.pattern(theregex);
			if(regExPattern){
				regExPattern=eval("(/"+regExPattern+"/)");
				if (regExPattern.test(jqthis.val())) regex_test_result=true;
			}else{
				regex_test_result=true;
			}
			var lenrange_test_result=false;
			if(thelenrange){
				var sthisLength=$.fn.cnbbrformvalidator.strlength(jqthis.val());
				thelenrange=thelenrange.split(',');
				var sthisLengthmin=parseInt(thelenrange[0]);
				var sthisLengthmax=0;
				if(thelenrange.length>1){ sthisLengthmax=parseInt(thelenrange[1]); }
				if(sthisLength>=sthisLengthmin){ lenrange_test_result=true; }
				if(sthisLengthmax>0 && lenrange_test_result){
					if(sthisLength<=sthisLengthmax){
						lenrange_test_result=true;
					}else{
						lenrange_test_result=false;
					}
				}
			}else{
				lenrange_test_result=true;
			}
			if(regex_test_result&&lenrange_test_result){
				jqthis.addClass("bbr_form_success");
				thepromptobject.hide();
				
				//ajax:check value
				if(theajaxurl){
					//theajaxurl += theajaxurl.indexOf('?') ? "&" : "?";
					//theajaxurl += "v="+ jqthis.val();
					//alert(theajaxurl);
					$.ajax({url:theajaxurl,data:{v:jqthis.val(),bbr_form_transrndomcode:Math.floor(Math.random()*1000+1)}, type:"get",async:false,success:function (data, textStatus){
						this;
						//alert(data);
						//alert(textStatus); //success or error
						if(textStatus=="success"){
							if(data=="[success]"){
								//alert('succ:'+i+jqthis.val()+data);
								jqthis.attr("status",true);
							}else{
								//alert('[ajaxfailure]:'+data);
								$("#bbr_form_success_"+i).hide();
								jqthis.removeClass("inputsuccess");
								jqthis.addClass("inputerror");
								thepromptobject.removeClass("bbr_form_prompt");
								thepromptobject.addClass("bbr_form_error");
								thepromptobject.html(theajaxerror);
								thepromptobject.show();
								if(theajaxerrorcallback){eval(theajaxerrorcallback);}
								return false;
							}
						}else{
							alert('[ajaxerrorstatus]:'+textStatus);
							if(theajaxerrorcallback){eval(theajaxerrorcallback);}
							return false;
						}
					},error:function(xhr, textStatus, errorThrown){
						this;
						alert("[ajaxurl]:"+theajaxurl+"\n[ajaxerror]:"+xhr.status+' '+errorThrown);
					}});
				}else{
					jqthis.attr("status",true);
				}

			}else{
				$("#bbr_form_success_"+i).hide();
				jqthis.removeClass("inputsuccess");
				jqthis.addClass("inputerror");
				thepromptobject.removeClass("bbr_form_prompt");
				thepromptobject.addClass("bbr_form_error");
				thepromptobject.html(theerror);
				thepromptobject.show();
				jqthis.attr("status",false);
			}
		}
	}

	// prepare the form when the DOM is ready
	$.fn.cnbbrformvalidator.submit=function(jqthis){
		$("#bbr_form_transrndomcode").val(Math.floor(Math.random()*1000+1));
		var options = {
			target:        '#bbr_form_submit_outer',   // target element(s) to be updated with server response
			beforeSubmit:  	$.fn.cnbbrformvalidator.submit.showRequest,  // pre-submit callback
			success:       	$.fn.cnbbrformvalidator.submit.showResponse,  // post-submit callback
			error: 				$.fn.cnbbrformvalidator.submit.showError,  // submit error callback
			// other available options:
			//url:       url         // override for form's 'action' attribute
			//type:      type        // 'get' or 'post', override for form's 'method' attribute
			//dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
			//clearForm: true        // clear all form fields after successful submit
			//resetForm: true        // reset the form after successful submit

			// $.ajax options can be used here too, for example:
			timeout:   30000
		};
		// bind to the form's submit event
		//$('#formlogin').submit(function() {
			// inside event callbacks 'this' is the DOM element so we first
			// wrap it in a jQuery object and then invoke ajaxSubmit
			jqthis.ajaxSubmit(options);

			// !!! Important !!!
			// always return false to prevent standard browser submit and page navigation
			return false;
		//});
	}
	
	//pre-submit validate form elements
	$.fn.cnbbrformvalidator.submit.validatorformelements = function(queryString){
		var errorscount=0;
		//檢測input_text
		$(".bbr_form_text").each(function(i){
			if($(this).attr("required")){
				$(this).blur();
				if(eval($(this).attr("status"))==false){ errorscount=errorscount+1; }
			}
		});
		//檢測checkbox,radio
		$(".bbr_form_listbox").each(function(i){
			if($(this).attr("lenrange")){
				$(this).children('input').each(function(j){
					$(this).blur();
				});
				$(this).children('select').each(function(j){
					$(this).blur();
				});
				if(eval($(this).attr("status"))==false){ errorscount=errorscount+1; }
			}
		});
		//檢測xheditor
		$(".xheditor-mfull").each(function(i){
			var theprompt=$(this).attr("prompt");
			var thelenrange=$(this).attr("lenrange");
			var thepromptobject = $(".bbr_form_prompt_xheditor").eq(i);
			if(thelenrange){
				var lenrange_test_result=true;
				var xheditorhtml=$("#xhe0_iframe").eq(i).contents().find("body").html();
				xheditorhtml=xheditorhtml.replace(/\s/ig,'');
				xheditorhtml=xheditorhtml.replace(/&nbsp;/ig,'');
				xheditorhtml=xheditorhtml.replace(/<P>/ig,'');
				xheditorhtml=xheditorhtml.replace(/<\/P>/ig,'');
				xheditorhtml=xheditorhtml.replace(/<br>/ig,'');
				alert(xheditorhtml);
				var sthisLength=$.fn.cnbbrformvalidator.strlength(xheditorhtml);
				thelenrange=thelenrange.split(',');
				var sthisLengthmin=parseInt(thelenrange[0]);
				var sthisLengthmax=0;
				if(thelenrange.length>1){ sthisLengthmax=parseInt(thelenrange[1]); }
				if(sthisLength<sthisLengthmin){
					lenrange_test_result=false;
					errorscount=errorscount+1;
				}
				if(sthisLengthmax>0 && lenrange_test_result){
					if(sthisLength<=sthisLengthmax){
						$(this).attr("status",true);
					}else{
						lenrange_test_result=false;
						errorscount=errorscount+1;
					}
				}
				if(lenrange_test_result==false){
					if(!theprompt){theprompt='編輯器內容不能為空，請輸入...';}
					thepromptobject.removeClass("bbr_form_prompt");
					thepromptobject.addClass("bbr_form_error");
					thepromptobject.html(theprompt);
					thepromptobject.show();
				}else{
					thepromptobject.hide();
				}
			}else{
				$(this).attr("status",true);
			}
		});
		
		//顯示提交結果框
		$("#bbr_form_submit_outer").show();
		if(errorscount>0){
			$("#bbr_form_submit_outer").html("輸入信息有<span>"+errorscount+"</span>項存在錯誤，請按提示進行檢查！");
			$("#bbr_form_submit_outer").fadeOut(3000);
		}else{
			if($("#bbr_form_debug").val()=='True') {
				$("#bbr_form_submit_outer").html(queryString+"<br/>");
			}
			$("#bbr_form_submit_outer").append("請求處理中，請稍候...<br/>");
		}
		return errorscount;
	}
	
	// pre-submit callback
	$.fn.cnbbrformvalidator.submit.showRequest = function(formData, jqForm, options) {
		// formData is an array; here we use $.param to convert it to a string to display it
		// but the form plugin does this for you automatically when it submits the data
		var queryString = $.param(formData);
		//alert(queryString);
		// jqForm is a jQuery object encapsulating the form element.  To access the
		// DOM element for the form do this:
		// var formElement = jqForm[0];
		// alert('About to submit: \n\n' + queryString);

		var validatorerrorscount = $.fn.cnbbrformvalidator.submit.validatorformelements(queryString);
		
		// here we could return false to prevent the form from being submitted;
		// returning anything other than false will allow the form submit to continue;
		//validatorerrorscount=1;
		
		if(validatorerrorscount>0){
			$("#bbr_form_submit_outer").addClass('bbr_form_submit_outer_failure');
			$(".submitbtn").show();
			return false;
		}else{
			return true;
		}
	}

	// post-submit callback
	$.fn.cnbbrformvalidator.submit.showResponse = function(responseText, statusText, xhr, $form)  {
		// for normal html responses, the first argument to the success callback
		// is the XMLHttpRequest object's responseText property

		// if the ajaxSubmit method was passed an Options Object with the dataType
		// property set to 'xml' then the first argument to the success callback
		// is the XMLHttpRequest object's responseXML property

		// if the ajaxSubmit method was passed an Options Object with the dataType
		// property set to 'json' then the first argument to the success callback
		// is the json data object returned by the server
		
		//alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.');
		//var formredirecturl = $("#redirecturl").val();
		//window.location.href=formredirecturl;
		//alert(responseText);
		$theformsubmitbtn=$form.find('.submitbtn');
		if(responseText.substr(0,9)=='[success]'){
			$("#bbr_form_submit_outer").removeClass('bbr_form_submit_outer_failure');
			$("#bbr_form_submit_outer").addClass('bbr_form_submit_outer_success');
			$("#bbr_form_submit_outer").html(responseText);
		}else if(responseText.substr(0,19)=='[successnoredirect]'){
			responseText=responseText.substr(19);
			$("#bbr_form_submit_outer").removeClass('bbr_form_submit_outer_failure');
			$("#bbr_form_submit_outer").addClass('bbr_form_submit_outer_success');
			$("#bbr_form_submit_outer").html(responseText);
			$("#bbr_form_submit_outer").append('<a onclick="javascript: $(this).parent().hide();$theformsubmitbtn.show();">返回</a>');
		}else{
			$("#bbr_form_submit_outer").removeClass('bbr_form_submit_outer_success');
			$("#bbr_form_submit_outer").addClass('bbr_form_submit_outer_failure');
			$form.find(".submitbtn").show();
			$("#vertifycodeinput").val('');
			$("#vertifycodeimg").click();
			$("#vertifycodeinput").focus();
		}
	}
	
	// post-submit callback with errors
	$.fn.cnbbrformvalidator.submit.showError = function(xhr, textStatus, errorThrown)  {
		alert("[ajaxerror]:"+xhr.status+' '+errorThrown);
		$("#bbr_form_submit_outer").append("表單請求處理出現["+xhr.status+"]錯誤");
	}

	$(document).ready(function() {
		$.fn.cnbbrformvalidator.init();
		$("form[validator='form.cnbbr.com']").submit(function() {
			$("#bbr_form_submit_outer").removeClass('bbr_form_submit_outer_success');
			$("#bbr_form_submit_outer").removeClass('bbr_form_submit_outer_failure');
			$(this).find(".submitbtn").hide();
			if($("#bbr_form_submit_byself").length>0){
				//表單本身的提交方式處理
				var selfvalidatorerrorscount=$.fn.cnbbrformvalidator.submit.validatorformelements('');
				if(selfvalidatorerrorscount>0){
					$("#bbr_form_submit_outer").addClass('bbr_form_submit_outer_failure');
					$(this).find(".submitbtn").show();
					return false;
				}else{
					$("#bbr_form_submit_outer").removeClass('bbr_form_submit_outer_failure');
					$("#bbr_form_submit_outer").addClass('bbr_form_submit_outer_success');
					$("#bbr_form_submit_outer").html("表單提交成功，請切換到新窗口繼續當前操作……");
					return true;
				}
			}else{
				//ajax方式提表單
				$.fn.cnbbrformvalidator.submit($(this));
				return false;
			}
		});
	});
		
})(jQuery);
