var PetInsure = {
	DateChooser : {
		ChangeDate:function(d,m,y) {
			var cDay = $(d).value;
			var cMonth = $(m).value;
			var cYear = $(y).value;
			var url = "index.cfm?action=DateChooser_ChangeDate&d="+cDay+"&m="+cMonth+"&y="+cYear;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PetInsure.DateChooser.ChangeDate_onSuccess, onFailure:errFunc});
		},
		ChangeDate_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("dobDay").replace(z.newSelectHTML);
		}
	},
	RetrieveOrder: {
		Validate:function() {
			if($("orderNumber").value.blank() && $("emailAddress").value.blank()) {
				alert("Please enter an order number OR your email address");
				return false;
			} else if(!$("orderNumber").value.blank() && $("dob").value.blank()) {
				alert("Please enter your date of birth with your order number");
				$("dob").focus();
				return false;
			} else if(!$("orderNumber").value.blank() && !PetInsure.RetrieveOrder.ValidateDOB($("dob").value)) {				
				alert("Please enter your date of birth in the format dd/mm/yyyy");
				return false;
			}
			return true;
		},
		ValidateDOB:function(dob) {
			var cDOB = dob.split("/");
			var result = false;
			if(cDOB.length==3) {
				if(isNumeric(cDOB[0]) && isNumeric(cDOB[1]) && isNumeric(cDOB[2]) ) {
					if(cDOB[0]<=31 && cDOB[1]<=12 && cDOB[2].length==4) {
						result = true;
					}
				}
			}
			
			return result;
		}
	},
	CallRequest: {
		ValidateCallRequestForm:function() {
			if($("callRequestName").value.blank()) {
				alert("Please enter your full name");
				PetInsure.HighlightAndFocus("callRequestName");				
				return false;
			}
			if($("callRequestPhoneNumber").value.blank()) {
				alert("Please enter your telephone number");
				PetInsure.HighlightAndFocus("callRequestPhoneNumber");
				return false;
			}
			if($("callRequestBestContactTime").value.blank()) {
				alert("Please enter a time for us to call you");
				PetInsure.HighlightAndFocus("callRequestBestContactTime");
				return false;
			}
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.CallRequest.ValidateCallRequestForm_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "pleaseCallmeForm" ) )});
			return false;
		},
		ValidateCallRequestForm_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.responseHTML);
		}
	},	
	DirectDebit : {
		Validate:function() {
			if($("directDebitSortCode").value.blank() || $("directDebitSortCode").value.length!=6) {
				alert("Please enter the 6 digit direct debit sort code without any punctuation\n\nCorrect Format : 123456\nIncorrect Format: 12-34-56");
				PetInsure.HighlightAndFocus("directDebitSortCode");
				return false;
			}
			if($("directDebitAccountNumber").value.blank() || $("directDebitAccountNumber").value.length!=8) {
				alert("Please enter the 8 digit direct debit account number without any punctuation\n\nCorrect Format : 12345678\nIncorrect Format: 12-34-56-78");
				PetInsure.HighlightAndFocus("directDebitAccountNumber");
				return false;
			}
			if($("directDebitBankName").value.blank()) {
				alert("Please enter the direct debit bank name");
				PetInsure.HighlightAndFocus("directDebitBankName");
				return false;
			}
			if($("directDebitBankAddress").value.blank()) {
				alert("Please enter the direct debit bank address");
				PetInsure.HighlightAndFocus("directDebitBankAddress");
				return false;
			}
			if($("directDebitName").value.blank()) {
				alert("Please enter the account holder name(s)");
				PetInsure.HighlightAndFocus("directDebitName");
				return false;
			}
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.DirectDebit.Validate_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "directDebitForm" ) )});
			return false;
		},
		Validate_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		}		
	},
	WebsiteContact: {
		ValidateWebsiteContactForm:function() {
			if($("websiteContactName").value.blank()) {
				alert("Please enter your full name");
				PetInsure.HighlightAndFocus("websiteContactName");
				return false;
			}
			if($("websiteContactEmailAddress").value.blank()) {
				alert("Please enter your email address");
				PetInsure.HighlightAndFocus("websiteContactEmailAddress");
				return false;
			}
			if($("websiteContactMessage").value.blank()) {
				alert("Please enter your contact message");
				PetInsure.HighlightAndFocus("websiteContactMessage");
				return false;
			}
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.WebsiteContact.ValidateWebsiteContactForm_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "websiteContactForm" ) )});
			return false;
		},
		ValidateWebsiteContactForm_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.responseHTML);
		}
	},	
	Checkout : {
		CalculateCost:function() {
			var rbs = $("petHolder").select("input");
			var total = 0;
			for(i=0;i<rbs.length;i++) {
				if(rbs[i].type=="radio") {
					if(rbs[i].checked) {
						total+=parseFloat(rbs[i].value.split("_")[1]);
					}
				}
			}
			$("overallTotal").update(total.toFixed(2));
			$("totalCost").value = total.toFixed(2);
		},
		ValidateStep6:function() {
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Checkout.ValidateStep6_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "applyOnline_step6Form" ) )});
			return false;
		},
		ValidateStep6_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			if(z.paymentType=="CREDITCARD") {			
				$("formHolder").update(z.formHTML);
			} else {
				document.location="https://www.petinsure.ie/index.cfm?page=payonline&orderId=" + z.orderId + "&ssl=true";
			}
		}
	},
	Application : {
		ChangePlan:function(customerId) {
			var selObjs = $("quoteTable").select("select");
			var planInfo = "";
			for(i=0;i<selObjs.length;i++) {
				planInfo+=selObjs[i].name + "=" + selObjs[i].value;
				if(i!=selObjs.length-1) {
					planInfo+=",";
				}
			}
			var url = "index.cfm?action=Application_ChangePlan&id="+customerId+"&planInfo="+escape(planInfo);
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.ChangePlan_onSuccess, onFailure:errFunc});
		},
		ChangePlan_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("planHolder").update(z.planHTML);
		},
		DeletePet:function(petId,petName,customerId) {
			var confirmation = confirm("Are you sure you want to remove " + petName + " from your quote?");
			if(confirmation) {
				var selObjs = $("quoteTable").select("select");
				var planInfo = "";
				for(i=0;i<selObjs.length;i++) {
					planInfo+=selObjs[i].name + "=" + selObjs[i].value;
					if(i!=selObjs.length-1) {
						planInfo+=",";
					}
				}
				var url = "index.cfm?action=Application_DeletePet&id="+customerId+"&petId="+petId+"&planInfo="+escape(planInfo);;
				new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.DeletePet_onSuccess, onFailure:errFunc});
			}
			return false;
		},
		DeletePet_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("planHolder").update(z.planHTML);
		},	
		PreCheckout:function() {
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.PreCheckout_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "preCheckout" ) )});
			return false;
		},
		PreCheckout_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		},
		Chipped:function(id,yn) {
			if(yn) {
				$("petMicrochipNumberHolder_"+id).show();
				$("petMicrochipNumber_"+id).focus();
			} else {
				$("petMicrochipNumberHolder_"+id).hide();
			}
		},
		PetChipped:function(yn) {
			if(yn) {
				$("petMicrochipNumberHolder").show();
				$("petMicrochipNumber").focus();
			} else {
				$("petMicrochipNumberHolder").hide();
			}
		},
		AddAnotherPet:function(customerId) {
			var url = "index.cfm?action=Application_AddAnotherPet&id="+customerId;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.AddAnotherPet_onSuccess, onFailure:errFunc});
		},
		AddAnotherPet_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		},
		ContinueStep4:function(customerId) {
			var url = "index.cfm?action=Application_ContinueStep4&id="+customerId;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.ContinueStep4_onSuccess, onFailure:errFunc});
		},
		ContinueStep4_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		},
		CancelAddPet:function(customerId) {
			var url = "index.cfm?action=Application_CancelAddPet&id="+customerId;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.CancelAddPet_onSuccess, onFailure:errFunc});
		},
		CancelAddPet_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		},
		ViewQuote:function(customerId) {
			var url = "index.cfm?action=Application_ViewQuote&id="+customerId;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.ViewQuote_onSuccess, onFailure:errFunc});
		},
		ViewQuote_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		},
		ChangePetType:function(obj) {
			var url = "index.cfm?action=Application_ChangePetType&petType="+obj.value;
			new Ajax.Request( url, {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.ChangePetType_onSuccess, onFailure:errFunc});
		},
		ChangePetType_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			switch(z.petType) {
				case "dog":
					$("breedIdHolder").update(z.breedSelectHTML);
					$("petBreedNameHolder").show();
					$("breedIdHolder").show();
					$("petPedigreeHolder").show();
					$("pedigree").checked=true;
				break;
				case "cat":
					$("breedIdHolder").update(z.breedSelectHTML);		
					$("petBreedNameHolder").show();		
					$("breedIdHolder").show();	
					$("petPedigreeHolder").show();
					$("pedigree").checked=true;
				break;
				case "rabbit":
					$("petBreedNameHolder").hide();
					$("breedIdHolder").hide();
					$("petPedigreeHolder").hide();
				break;
			}
		},
		ShowBreed:function() {
			$("petBreedNameHolder").show();
			$("breedIdHolder").show();
		},
		HideBreed:function() {
			$("petBreedNameHolder").hide();
			$("breedIdHolder").hide();
		},
		CheckSelectBreed:function(obj) {
			if(obj.options[obj.selectedIndex].getAttribute("data")=="YES") {
				if(!$("selectBreed")) {
					$("dogBreedId").insert({after:'<div class="selectBreed" id="selectBreed">Your dog is a select breed</div>'});
				}
			} else {
				if($("selectBreed")) {
					$("selectBreed").remove();
				}
			}
		},
		IsDate:function(val) {
			var isDate = false;
			var cDate = val.split("/");	
			if(cDate.length==3) {
				if(cDate[0].length==2 && cDate[1].length==2 && cDate[2].length==4) {
					isDate=true;
				}
			}
			return isDate;
		},
		IsOver18:function(val) {
			var cDate = val.split("/");
			var cYear = cDate[2];
			var cMonth = cDate[1];
			var cDay = cDate[0];
			var DOB=new Date();
			DOB.setFullYear(cYear,cMonth-1,cDay);
			var dateToTest=new Date();
			dateToTest.setDate(dateToTest.getDate()-(18*365));
			if(DOB<dateToTest) {
				return true;
			} else {
				return false;
			}
		},
		ValidateStep1:function() {
			if($("customerFirstName").value.blank()) {
				alert("Please enter your first name");
				PetInsure.HighlightAndFocus("customerFirstName");
				return false;
			}
			if($("customerLastName").value.blank()) {
				alert("Please enter your last name");
				PetInsure.HighlightAndFocus("customerLastName");
				return false;
			}
			if($("customerAddress1").value.blank()) {
				alert("Please enter the first line of your address");
				PetInsure.HighlightAndFocus("customerAddress1");
				return false;
			}
			if($("customerAddress2").value.blank()) {
				alert("Please enter the second line of your address");
				PetInsure.HighlightAndFocus("customerAddress2");
				return false;
			}
			if($("customerCity").value.blank()) {
				alert("Please enter the city where you live");
				PetInsure.HighlightAndFocus("customerCity");
				return false;
			}
			if($("customerCountry").value.blank()) {
				alert("Please enter the country where you live");
				PetInsure.HighlightAndFocus("customerCountry");
				return false;
			}
			if(!$("customerEmailAddress").value.blank()) {
				if(!$("customerEmailAddress").value.isEmail()) {
					alert("Please enter a valid email address");
					PetInsure.HighlightAndFocus("customerEmailAddress");
					return false;
				} 
				if($("customerEmailAddress").value != $("customerEmailAddress2").value) {
					alert("The email address entered and the confirmation email address do not match");
					PetInsure.HighlightAndFocus("customerEmailAddress2");
					return false;
				}			
			}
			if($("customerTelephone").value.blank()) {
				alert("Please enter your telephone number");
				PetInsure.HighlightAndFocus("customerTelephone");
				return false;
			}			
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.ValidateStep1_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "applyOnline_step1Form" ) )});
			return false;
		},
		ValidateStep1_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		},		
		ValidateStep2:function() {			
			if($("pedigree").checked) {
				if($("rb1").checked) {
					if($("catBreedId").value==-1) {
						alert("Please choose the breed of your cat");						
						PetInsure.HighlightAndFocus("petBreedNameHolder");
						return false;
					}
				} else if($("rb2").checked) {
					if($("dogBreedId").value==-1) {
						alert("Please choose the breed of your dog");
						PetInsure.HighlightAndFocus("petBreedNameHolder");
						return false;
					}
				}
			}
			if($("petName").value.blank()) {
				alert("Please enter the name of your pet");
				PetInsure.HighlightAndFocus("petName");
				return false;
			}
			if(!PetInsure.Application.ValidateAge()) {
				return false;
			}			
			if($("yesMicrochipped").checked) {
				if( $("petMicrochipNumber").value.blank() ) {
					alert("Please enter the microchip number of your pet");
					PetInsure.HighlightAndFocus("petMicrochipNumber");
					return false;
				}					
			}		
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.ValidateStep2_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "applyOnline_step2Form" ) )});
			return false;
		},		
		ValidateStep2_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		},
		ValidateAge:function() {
			var cYears = parseInt($("petAgeYears").value);
			var cMonths = parseInt($("petAgeMonths").value);
			var cTotalMonths = (cYears*12)+cMonths;
			if($("pedigree").checked && $("rb2").checked && $("dogBreedId").options[$("dogBreedId").selectedIndex].getAttribute("data")=="YES") {
				if(cTotalMonths>=60 || cTotalMonths < 2) {
					alert("We can only insure pets aged 2 months or older and not older than 5 years if they are select breeds.");
					return false;
				}
			} else {
				if(cTotalMonths>=96 || cTotalMonths < 2) {
					alert("We can only insure pets aged 2 months or older and not older than 7 years");
					return false;
				}
			}
			return true;						
		},
		ValidateStep3:function() {			
			var cPetIdArray = $("petIdList").value.split(",");
			for(i=0;i<cPetIdArray.length;i++) {
				var cPetId = cPetIdArray[i];
				if($("yesMicrochipped_"+cPetId).checked) {
					if( $("petMicrochipNumber_"+cPetId).value.blank() ) {
						PetInsure.HighlightAndFocus("petMicrochipNumber_"+cPetId);
						return false;
					}					
				}
			}
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.ValidateStep3_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "applyOnline_step3Form" ) )});
			return false;
		},
		ValidateStep3_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		},
		ValidateStep4:function() {
			if($("vetName").value.blank()) {
				PetInsure.HighlightAndFocus("vetName");
				return false;
			}
			new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.ValidateStep4_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "applyOnline_step4Form" ) )});
			return false;
		},
		ValidateStep4_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		},
		ValidateStep5:function() {
			if($("declaration").checked && $("termsOfBusiness").checked && $("generalConditions").checked) {
				new Ajax.Request('index.cfm', {asynchronous:true, evalScripts:false, onSuccess:PetInsure.Application.ValidateStep5_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "applyOnline_step5Form" ) )});
			} else {
				alert("Please agree to the declaration, general conditions and terms of business before continuing");
			}			
			return false;
		},
		ValidateStep5_onSuccess:function(t) {
			z = parseJSON(t.responseText);
			$("formHolder").update(z.formHTML);
		}				
	},
	HighlightAndFocus:function(id) {
		new Effect.Highlight(id);
		$(id).focus();
	}
}


var CreditCard = {
	IsVisa:function(cc) {
		if(((cc.length == 16) || (cc.length == 13)) && (cc.substring(0,1) == 4)) {
			return CreditCard.IsCreditCard(cc);
		} else {
			 return false;
		}
	},
	IsMasterCard:function(cc) {
		var firstdig = cc.substring(0,1);
		var seconddig = cc.substring(1,2);
		if((cc.length == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5))) {
			return CreditCard.IsCreditCard(cc);
		} else {
			return false;
		}
	},
	IsAmericanExpress:function(cc) {
		var firstdig = cc.substring(0,1);
		var seconddig = cc.substring(1,2);
		if((cc.length == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7))) {
			return CreditCard.IsCreditCard(cc);
		} else {
			return false;
		}
	},
	IsLaser:function(cc) {
		if((cc.length == 19) && isNumeric(cc)) {
			return true;
		} else {
			return false;
		}
	},
	IsCreditCard:function(st) {
		if(st.length > 19) {
			return false;
		}		
		var sum = 0; 
		var mul = 1; 
		var l = st.length;
		for(i = 0;i<l;i++) {
			digit = st.substring(l-i-1,l-i);
		    tproduct = parseInt(digit ,10)*mul;
		    if (tproduct >= 10) {
		      sum += (tproduct % 10) + 1;
		    } else {
		      sum += tproduct;
			}
		    if(mul == 1) {
		      mul++;
		    } else {
		      mul--;
			}
		}
		
		if((sum % 10) == 0) {
			return true;
		} else {
			return false;
		}
	}
}

String.prototype.isEmail = function () { 
	var rx = new RegExp("\\w+([-+.\’]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); 
	var matches = rx.exec(this); 
	return (matches != null && this == matches[0]); 
}

function isNumeric(x) { 
	var y=parseInt(x); 
	if (isNaN(y)) {
	   return false; 
	} else {
		return true;
	}
} 

function LoadingAjax(txt) {
	if(typeof(txt)=="undefined") {
		txt = "Loading...";
	}
	return "<div class='ajaxMsg' id='widgetAjaxMsg'> "+txt+"</div>";
}

function parseJSON( json ){
	var o = eval('(' + json + ')');
	if( o.redirectURL )
	{
		document.location = o.redirectURL;
		return;
	}
	if( $("message") != null ) new Element.remove( "message" );
	if( o.errMsg )
	{
		if( o.errMsgTitle == null ) o.errMsgTitle = "Error";
		if( o.errMsgTimer == null ) o.errMsgTimer = 5000;
		tw.ShowMessage( o.errMsgTitle, o.errMsg, "error", o.errMsgTimer, o.errMsgPosition );
		return o;
	}
	if( o.msgTitle || o.msg )
	{
		if( o.msgTimer == null ) o.msgTimer = 5000;
		tw.ShowMessage( o.msgTitle, o.msg, o.msgClass, o.msgTimer, o.msgPosition );
	}
	return o;
}

var errFunc = function(t) {
	var win = window.open("", "win", "width=1024,height=700,resizable=yes,scrollbars=yes,status=no"); // a window object
	win.document.open("text/html", "replace");
	win.document.write( "<html><body style='margin:0'><div style='border-bottom:1px solid #222;background:#666;padding:10px;'><h1 style='color:#FFF;margin:0;padding:0;'>Digital Crew Ajax Error</h1></div><div style='padding:10px;'>"+t.responseText.replace(/^\s+|\s+$/, '') + "</div></body></html>" );
	win.document.close();
	win.focus();
}