/*
	Created by Jason D Brown of Matcha Design for use with UME CMS.
	Copyright © 2010 All Rights Reserved
	
	Options:			Default:	Description:
	-----------------------------------------------------------------------------------------------
	useTipBox			false		Enables a box that reports all errors. Pass in through 'tipBox'.
	useMiniTips			false		Generates tip boxes for each item, assigning them the class(es) specified in 'miniTipClassName'
	miniTipClassName	'mini-tip'	The class name(s) to apply to tip boxes created if 'useMiniTips' is set to true.
	autoDisable			false		Disables the submit button if there are errors. Requires 'autoReport' to be true, and 'submitButton' to be set.
	autoReport			true		Updates error list every time the user blurs a field.
	submitButton		null		The jQuery object of the submit button of the form. Used with 'autoDisable'.
	tipBox				null		The jQuery object of the element to use with 'useTipBox'.
	useLabels			true		Enables use of existing labels instead of (or in addition to) miniTips.
*/
;(function($) {
	$(function() {
		if ($.browser.msie) {
			$('input:radio,input:checkbox').click(function () {
				this.blur();
				this.focus();
			});
		}
	});
	$(function() {
		for(var i=0;i<document.forms.length;i++){
			initCaptchaOnForm(document.forms[i])
		}
		function initCaptchaOnForm(c){
			if(c._CaptchaHookedUp) {
				return;
			}
			if(!c.CaptchaV2) {
				return;
			}
			if(!c.CaptchaHV2) {
				return; 
			}
			var b=6;
			addEventSimple(c.CaptchaV2,"keyup",function(g) {
				if(c.CaptchaV2.previousValue==c.CaptchaV2.value) {
					return;
				}
				c.CaptchaV2.previousValue=c.CaptchaV2.value;
				var d=c.CaptchaHV2.value;
				var f=c.CaptchaV2.value;
				if(f.length!=b) {
					c._CaptchaTextIsInvalid=true;
					return;
				}
				sendRequest("/ValidateCaptcha.ashx?key="+d+"&answer="+f,function(e) {
					c._CaptchaTextIsInvalid=e.responseText=="false";
				});
			});
			c._CaptchaHookedUp=true;
		}
		function captchaIsInvalid(c,b,d) {
			if(c.CaptchaV2.value.trim().length==0) {
				return "- "+b;
			}
			if(c._CaptchaTextIsInvalid) {
				return "- "+d;
			}
			return "";
		}
	});
	$.fn.extend({
		formValidator : function (settings) {
			return this.each(function() {
				defaults = {
					'useTipBox' : false,
					'useMiniTips' : false,
					'miniTipClassName' : 'mini-tip',
					'autoDisable' : false,
					'autoReport' : true,
					'submitButton' : null,
					'tipBox' : null,
					'useLabels' : true
					};
				if(!settings) settings = defaults;
				$.extend(defaults, settings);
				$.debuglog(this.id + '.formValidator()');
				$.debuglog(defaults);
				$.FormValidator_Create(this, defaults);
			});
		},
		formValidatorAddCustomField : function(fieldobj, name, required, regexp) {
			fieldobj.data('validationregexp', regexp);
			return this.each(function() {
				$.FormValidator_AddField($(this), fieldobj, required, 'regexp', name);
			});
		},
		formValidatorAddField : function(fieldobj/*JQ*/, name, required, validationtype) {
			return this.each(function() {
				$.debuglog(this.id + '.formValidatorAddField(fieldobj:' + fieldobj.DOM().id + ", name:"+name+", required:" + required + ", validationtype:" + validationtype+ ')');
				$.FormValidator_AddField($(this), fieldobj, required, validationtype, name);
			});
		},
		formValidatorAddToForm : function(formobj/*JQ*/, name, required, validationtype) {
			return this.each(function() {
				$.debuglog(this.id + '.formValidatorAddToForm(formobj:' + formobj.DOM().id + ", name:"+name+", required:" + required + ", validationtype:" + validationtype+ ')');
				formobj.formValidatorAddField($(this), required, validationtype, name);
			});
		},
		formValidatorClearErrors : function() {
			return this.each(function() {
				$.debuglog(this.id + '.formValidatorClearErrors()');
				var allFields = $(this).data('formValidatorAllFields');
				for(var n=0;n<allFields.length;n++) {
					var set = allFields[n];
					obj = set['field'];
					obj.removeClass('ui-state-error');
					if(obj.data('mylabel')) {
						obj.data('mylabel').html(obj.data('mylabel').data('originalcontents')).removeClass('ui-state-error');
					}
				}
			});
		},
		formValidatorUpdateErrors : function() {
			return this.each(function() {
				$.debuglog(this.id + '.formValidatorUpdateErrors()');
				$.FormValidator_CheckForm(this);
			});
		},
		formValidatorSubmitIfValid : function() {
			return this.each(function() {
				if($(this).data('beensubmitted')) {return;}//{alert('Form has already been submitted. Please wait a moment.'); return;}
				$.debuglog(this.id + '.formValidatorSubmitIfValid()');
				var allFields = $(this).data('formValidatorAllFields');
				for(var n=0;n<allFields.length;n++) {
					var set = allFields[n];
					set['field'].data('formvalidatorbeenused',true);
				}
				if($.FormValidator_CheckForm(this)) {
					if($(this).data('confirmQuestion')) {
						if(confirm($(this).data('confirmQuestion')) == true) {
							$.debuglog("*" + this.id + "submit()*");
							$(this).data('beensubmitted', true);
							if($(this).data('formValidatorSettings')['submitButton']){$(this).data('formValidatorSettings')['submitButton'].DOM().disabled=true;}
							this.submit();
						}
					} else {
						$.debuglog("*" + this.id + "submit()*");
						$(this).data('beensubmitted', true);
						if($(this).data('formValidatorSettings')['submitButton']){$(this).data('formValidatorSettings')['submitButton'].DOM().disabled=true;}
						this.submit();
					}
				}
			});
		},
		report : function() {
			return this.each(function() {
				$.debuglog(this.id+".report()");
			});
		},
		DOM : function() {
			return this.get(0);
		},
		formValidatorAddFirstLastTitle : function() {
			return this.each(function() {
				var me = $(this);
				me.formValidatorAddField($(this.Title), "Please enter your title", false, null);
				me.formValidatorAddField($(this.FirstName), "Please enter your first name", true, null);
				me.formValidatorAddField($(this.LastName), "Please enter your last name", true, null);
			});
		},
		formValidatorAddEmail : function() {
			return this.each(function() {
				var me = $(this);
				me.formValidatorAddField($(this.EmailAddress), "Please enter your email address", true, "email");
			});
		},
		formValidatorAddCaptcha : function() {
			return this.each(function() {
				if(this.CaptchaV2) {
					var me = $(this);
					me.formValidatorAddField($(this.CaptchaV2), "Please enter the correct word verification as seen in the image", true, "captcha");			
				}
			});
		},
		formValidatorAddTypical : function() {
			return this.formValidatorAddFirstLastTitle().formValidatorAddEmail().formValidatorAddCaptcha();
		},
		formValidatorAddPassword : function(pwfield, confirmfield, msg_empty, msg_nomatch, msg_tooshort) {
			return this.each(function() {
				pwfield.data('msg_pwtooshort', msg_tooshort).data('msg_nomatch', msg_nomatch).data('confirmfield', confirmfield);
				confirmfield.data('msg_pwtooshort', msg_tooshort).data('msg_nomatch', msg_nomatch).data('confirmfield', pwfield);
				$.FormValidator_AddField($(this), confirmfield, true, 'password', msg_empty);
				$.FormValidator_AddField($(this), pwfield, true, 'password', msg_empty);
			});
		},
		formValidatorAddRadio : function(list, required, errormessage) {
			return this.each(function() {
				var me = $(this);
				var primary = list[0];
				var others = list.slice(1);
				primary.data('others', others);
				$.each(others, function(index, value) {
					me.formValidatorAddField(value, errormessage, false, null);
					value.removeClass('ui-corner-all');
				});
				me.formValidatorAddField(primary, errormessage, required, 'radio');
				primary.removeClass('ui-corner-all');
			});
		},
		formValidatorAddCreditCard : function() {
			return this.each(function() {
				$.debuglog(this.id + '.formValidatorAddCreditCard()');
				$(this)
				.formValidatorAddField($(this.BillingAddress), "Please enter your billing address", true, null)
				.formValidatorAddField($(this.BillingCity), "Please enter your billing city", true, null)
				.formValidatorAddField($(this.BillingState), "Please enter your billing state", true, null)
				.formValidatorAddField($(this.BillingZip), "Please enter your billing zip/postal code", true, null)
				.formValidatorAddField($(this.BillingCountry), "Please select your billing country", true, null)
				
				.formValidatorAddField($(this.CardName), "Please enter the name on the card", true, null)
				.formValidatorAddField($(this.CardNumber), "Please enter the card number", true, 'creditcard')
				.formValidatorAddField($(this.CardExpiryMonth), "Please select the card's expiration date", true, null)
				.formValidatorAddField($(this.CardExpiryYear), "Please select the card's expiration date", true, null)
				.formValidatorAddField($(this.CardType), "Please select the card type", true, null)
				.formValidatorAddField($(this.CardCCV), "Please enter the card's CVV number", true, null);
			});
		},
		formValidatorAddHomeAddress : function() {
			return this.each(function() {
				$.debuglog(this.id + '.formValidatorAddHomeAddress()');
				$(this)
				.formValidatorAddField($(this.HomeAddress), "Please enter your home address", false, null)
				.formValidatorAddField($(this.HomeCity), "Please enter your home city", false, null)
				.formValidatorAddField($(this.HomeState), "Please enter your home state", false, null)
				.formValidatorAddField($(this.HomeZip), "Please enter your home zip/postal code", false, null)
				.formValidatorAddField($(this.HomeCountry), "Please select your home country", false, null)
			});
		},
		formValidatorAddWorkAddress : function() {
			return this.each(function() {
				$.debuglog(this.id + '.formValidatorAddWorkAddress()');
				$(this)
				.formValidatorAddField($(this.WorkAddress), "Please enter your work address", false, null)
				.formValidatorAddField($(this.WorkCity), "Please enter your work city", false, null)
				.formValidatorAddField($(this.WorkState), "Please enter your work state", false, null)
				.formValidatorAddField($(this.WorkZip), "Please enter your work zip/postal code", false, null)
				.formValidatorAddField($(this.WorkCountry), "Please select your work country", false, null)
			});
		}
	});
	$.debuglog = function(s) {
		$("#log").each(function() {
			$(this).html($(this).html() + s + '<br />');
		});
	};
	$.FormValidator_Create = function(container/*DOM*/, settings/*JSON*/) {
		var me = $(container);/*JQ*/
		var theForm = container;/*DOM*/
		if(settings['submitButton']) {
			settings['submitButton'].button()//addClass("ui-state-default").addClass("ui-corner-all").addClass("ui-button")
			.data('myValidationForm', me)
			.click(function() {
				if(this.DOM) {
					this.data('myValidationForm').formValidatorSubmitIfValid();
				} else {
					$(this).data('myValidationForm').formValidatorSubmitIfValid();
				}
			});
		}
		me.data('formValidatorSettings',settings);
		me.data('formValidatorAllFields',[]);
	};
	$.FormValidator_AddField = function(theForm/*JQ*/, fieldobj/*JQ*/, required/*bool*/, validationtype/*null,'email','captcha'*/, errormessage/*string*/) {
		//US ZIP Code: ^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$
		//Email Address: /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i
		//Phone Number: /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/
		var allFields = theForm.data('formValidatorAllFields');
		if(validationtype == 'email') {
			validationtype = 'regexp';
			fieldobj.data('validationregexp', /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i);
		} else if (validationtype == 'phone') {
			validationtype = 'regexp';
			fieldobj.data('validationregexp', /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/i);
		}
		allFields.push({'field':fieldobj, 'required':required,'validation':validationtype,'msg':errormessage});
		theForm.data('formValidatorAllFields', allFields);
		fieldobj.addClass('ui-corner-all');
		fieldobj.data('myform', theForm);
		if(theForm.data('formValidatorSettings')['useMiniTips']) {
			if(fieldobj.data('mytipbox') == null) {
				fieldobj.wrap('<div style="display:inline-block; border:0px none; padding:0px; margin:0px; position:relative;"></div>');
				fieldobj.parent().append('<div class="' + theForm.data('formValidatorSettings')['miniTipClassName'] + '"></div>');
				fieldobj.data('mytipbox', fieldobj.siblings("div.mini-tip"));
			}
		}
		if(theForm.data('formValidatorSettings')['useLabels']) {
			if(fieldobj.data('mylabel') == null) {
				fieldobj.data('mylabel', $(fieldobj.siblings('label').DOM()));
				fieldobj.data('mylabel').data('originalcontents', fieldobj.data('mylabel').html());
			}
		}
		if(theForm.data('formValidatorSettings')['autoReport']) {
			fieldobj.data('formvalidatorbeenused', false);
			if(fieldobj.DOM().type=="radio") {
				fieldobj.change(function() {
					fieldobj.data('formvalidatorbeenused', true);
					$(this).data('myform').formValidatorUpdateErrors();
				})				
			}
			fieldobj.blur(function() {
				fieldobj.data('formvalidatorbeenused', true);
				$(this).data('myform').formValidatorUpdateErrors();
			}).keyup(function() {
				if(fieldobj.data('formvalidatorbeenused')) {
					if(this.id == "CaptchaV2") {
						var thec = $(this);
						setTimeout(function() {
							thec.data('myform').formValidatorUpdateErrors();
						}, 200);
						setTimeout(function() {
							thec.data('myform').formValidatorUpdateErrors();
						}, 1000);
					} else {
						$(this).data('myform').formValidatorUpdateErrors();
					}
				}
			});
			$.FormValidator_CheckForm(theForm);
		}
	};
	$.FormValidator_CheckForm = function(theForm/*DOM*/) {
		var tips=$(theForm).data('formValidatorTipBox');
		var allFields = $(theForm).data('formValidatorAllFields');
		var why = "";
		for(var n=0;n<allFields.length;n++) {
			var set = allFields[n];
			var fielddom = set['field'].DOM();
			$.debuglog("Checking " + fielddom.id);
			set['field'].removeClass('ui-state-error');
			if(set['field']) {
				if(set['field'].data('formvalidatorbeenused') != false) {
					if(fielddom.value.length > 0 || set['required'] == true) {
						//why += $.FormValidator_dowhy(fielddom, checkEmail(fielddom.value));
						if(set['validation'] == 'captcha') {
							why += $.FormValidator_dowhy(fielddom, captchaIsInvalid(theForm, "captcha", "captcha"),set['msg']);
						} else if(set['validation'] == 'password') {
							var pwconf = set['field'].data('confirmfield');
							if(pwconf.DOM().value != fielddom.value) {
								if(pwconf.data('formvalidatorbeenused')) {
									why += $.FormValidator_dowhy(set['field'], '---', set['field'].data('msg_nomatch'));
								}
							} else if(fielddom.value.length == 0) {
								why += $.FormValidator_dowhy(set['field'], '---', set['msg']);
							} else if(fielddom.value.length < 6) {
								why += $.FormValidator_dowhy(set['field'], '---', set['field'].data('msg_pwtooshort'));
							} else {
								why += $.FormValidator_dowhy(fielddom, "", "");
							}
						} else if(set['validation'] == 'creditcard') {
							fielddom.value.replace(/[ -]+/, "");
							var q = '';
							var cardtype = '';
							var regx = [/^4[0-9]{12}(?:[0-9]{3})?$/,/^5[1-5][0-9]{14}$/,/^3[47][0-9]{13}$/,/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,/^6(?:011|5[0-9]{2})[0-9]{12}$/,/^(?:2131|1800|35\d{3})\d{11}$/];
							var names = ['Visa','MasterCard','American Express', 'Diners Club', 'Discover', 'JCB'];
							var values = [1,2,4,5,7,6];
							for(var i=0;i<regx.length;i++) {
								if(fielddom.value.match(regx[i])) {
									q = values[i];
									cardtype = names[i];
								}
							}
							/* If we know what kind of card it is, let's set that automatically! */
							if(q != '') {
								if(theForm.CardType) {
									var z = false;
									$(theForm.CardType).children().each(function() {
										if(this.value == q) {
											this.selected = true;
											z = true;
										} else {
											this.selected = false;
										}
									});
									if(!z) {
										why += $.FormValidator_dowhy(fielddom, "----", "We don't accept " + cardtype);
									} else {
										why += $.FormValidator_dowhy(fielddom, "", "");
									}
								} else {
									why += $.FormValidator_dowhy(fielddom, "", "");
								}
							} else {
								why += $.FormValidator_dowhy(fielddom, "----", set['msg']);
							}
						} else if(set['validation'] == 'radio' && set['required'] == true) {
							var others = set['field'].data('others');
							var checked = false;
							if(fielddom.checked) {
								checked = true;
							} else {
								$.each(others, function(index, value) {
									if(value.DOM().checked) checked = true;
								});
							}
							if(!checked) {
								why += $.FormValidator_dowhy(fielddom, '---', set['msg']);
								$.each(others, function(index, value) {
									value.addClass('ui-state-error');
								});
							} else {
								why += $.FormValidator_dowhy(fielddom, "", "");
							}
						} else if(set['validation'] == 'regexp') {
							if(!fielddom.value.match(set['field'].data('validationregexp'))) {
								why += $.FormValidator_dowhy(fielddom, set['msg'], set['msg']);
							} else if(fielddom.value.length == 0) {
								why += $.FormValidator_dowhy(fielddom, set['msg'], set['msg']);
							} else {
								why += $.FormValidator_dowhy(fielddom, "", "");
							}
						} else if(set['required'] == true) {
							why += $.FormValidator_dowhy(fielddom, isEmpty(fielddom.value, set['msg']), set['msg']);
						}
					}
				}
			}
		}
		if (why != "") {
			if($(theForm).data('formValidatorSettings')['autoReport'] && $(theForm).data('formValidatorSettings')['autoDisable']) {
				if($(theForm).data('formValidatorSettings')['submitButton']) {
					$(theForm).data('formValidatorSettings')['submitButton'].addClass('ui-disabled').removeClass('ui-state-hover').removeClass('ui-state-active');
					$(theForm).data('formValidatorSettings')['submitButton'].DOM().disabled = true;
				}
			}
			if(tips) $.FormValidator_updateTips(tips,why);
			return false;
		} else {
			if($(theForm).data('formValidatorSettings')['autoReport'] && $(theForm).data('formValidatorSettings')['autoDisable']) {
				if($(theForm).data('formValidatorSettings')['submitButton']) {
					$(theForm).data('formValidatorSettings')['submitButton'].removeClass('ui-disabled');
					$(theForm).data('formValidatorSettings')['submitButton'].DOM().disabled = false;
				}
			}
			return true;
		}
	};
	$.FormValidator_dowhy = function(obj, text, replacetext) {
		var usetext = text.substr(2);
		if(replacetext) {usetext=replacetext;}
		if((text != "") && (text != null)) {
			if($(obj).data('myform').data('formValidatorSettings')['useMiniTips']) {
				if($(obj).data('mytipbox') != null) {
					$(obj).data('mytipbox').text(usetext);
				}
			}
			if($(obj).data('myform').data('formValidatorSettings')['useLabels'] && $(obj).data('mylabel') != null) {
				$(obj).data('mylabel').text(usetext).addClass('ui-state-error');
			} else {
				$(obj).addClass('ui-state-error');
			}
			return usetext + "<br />";
		} else {
			if($(obj).data('myform').data('formValidatorSettings')['useMiniTips']) {
				if($(obj).data('mytipbox') != null) {
					$(obj).data('mytipbox').text('');
				}
			}
			if($(obj).data('myform').data('formValidatorSettings')['useLabels']) {
				if($(obj).data('mylabel') != null) {
					$(obj).data('mylabel').html($(obj).data('mylabel').data('originalcontents')).removeClass('ui-state-error');
				}
			}
		}
		return text;
	};
	$.FormValidator_updateTips = function(tips,t) {
		//alert(t);
		tips.html(t).addClass("ui-state-highlight");//effect("highlight",{},1500);
	};
})(jQuery);
