/* Minification failed. Returning unminified contents.
(177,17-18): run-time warning JS1004: Expected ';': d
(179,17-18): run-time warning JS1004: Expected ';': d
(181,17-18): run-time warning JS1004: Expected ';': d
(694,17-18): run-time warning JS1004: Expected ';': d
(696,17-18): run-time warning JS1004: Expected ';': d
 */
/*! jQuery Validation Plugin - v1.10.0 - 9/7/2012
* https://github.com/jzaefferer/jquery-validation
* Copyright (c) 2012 Jörn Zaefferer; Licensed MIT, GPL */(function(e){e.extend(e.fn,{validate:function(t){if(!this.length){t&&t.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return}var n=e.data(this[0],"validator");if(n)return n;this.attr("novalidate","novalidate");n=new e.validator(t,this[0]);e.data(this[0],"validator",n);if(n.settings.onsubmit){this.validateDelegate(":submit","click",function(t){n.settings.submitHandler&&(n.submitButton=t.target);e(t.target).hasClass("cancel")&&(n.cancelSubmit=!0)});this.submit(function(t){function r(){var r;if(n.settings.submitHandler){n.submitButton&&(r=e("<input type='hidden'/>").attr("name",n.submitButton.name).val(n.submitButton.value).appendTo(n.currentForm));n.settings.submitHandler.call(n,n.currentForm,t);n.submitButton&&r.remove();return!1}return!0}n.settings.debug&&t.preventDefault();if(n.cancelSubmit){n.cancelSubmit=!1;return r()}if(n.form()){if(n.pendingRequest){n.formSubmitted=!0;return!1}return r()}n.focusInvalid();return!1})}return n},valid:function(){if(e(this[0]).is("form"))return this.validate().form();var t=!0,n=e(this[0].form).validate();this.each(function(){t&=n.element(this)});return t},removeAttrs:function(t){var n={},r=this;e.each(t.split(/\s/),function(e,t){n[t]=r.attr(t);r.removeAttr(t)});return n},rules:function(t,n){var r=this[0];if(t){var i=e.data(r.form,"validator").settings,s=i.rules,o=e.validator.staticRules(r);switch(t){case"add":e.extend(o,e.validator.normalizeRule(n));s[r.name]=o;n.messages&&(i.messages[r.name]=e.extend(i.messages[r.name],n.messages));break;case"remove":if(!n){delete s[r.name];return o}var u={};e.each(n.split(/\s/),function(e,t){u[t]=o[t];delete o[t]});return u}}var a=e.validator.normalizeRules(e.extend({},e.validator.metadataRules(r),e.validator.classRules(r),e.validator.attributeRules(r),e.validator.staticRules(r)),r);if(a.required){var f=a.required;delete a.required;a=e.extend({required:f},a)}return a}});e.extend(e.expr[":"],{blank:function(t){return!e.trim(""+t.value)},filled:function(t){return!!e.trim(""+t.value)},unchecked:function(e){return!e.checked}});e.validator=function(t,n){this.settings=e.extend(!0,{},e.validator.defaults,t);this.currentForm=n;this.init()};e.validator.format=function(t,n){if(arguments.length===1)return function(){var n=e.makeArray(arguments);n.unshift(t);return e.validator.format.apply(this,n)};arguments.length>2&&n.constructor!==Array&&(n=e.makeArray(arguments).slice(1));n.constructor!==Array&&(n=[n]);e.each(n,function(e,n){t=t.replace(new RegExp("\\{"+e+"\\}","g"),n)});return t};e.extend(e.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusInvalid:!0,errorContainer:e([]),errorLabelContainer:e([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(e,t){this.lastActive=e;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,e,this.settings.errorClass,this.settings.validClass);this.addWrapper(this.errorsFor(e)).hide()}},onfocusout:function(e,t){!this.checkable(e)&&(e.name in this.submitted||!this.optional(e))&&this.element(e)},onkeyup:function(e,t){if(t.which===9&&this.elementValue(e)==="")return;(e.name in this.submitted||e===this.lastActive)&&this.element(e)},onclick:function(e,t){e.name in this.submitted?this.element(e):e.parentNode.name in this.submitted&&this.element(e.parentNode)},highlight:function(t,n,r){t.type==="radio"?this.findByName(t.name).addClass(n).removeClass(r):e(t).addClass(n).removeClass(r)},unhighlight:function(t,n,r){t.type==="radio"?this.findByName(t.name).removeClass(n).addClass(r):e(t).removeClass(n).addClass(r)}},setDefaults:function(t){e.extend(e.validator.defaults,t)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",maxlength:e.validator.format("Please enter no more than {0} characters."),minlength:e.validator.format("Please enter at least {0} characters."),rangelength:e.validator.format("Please enter a value between {0} and {1} characters long."),range:e.validator.format("Please enter a value between {0} and {1}."),max:e.validator.format("Please enter a valid amount you want to donate."),min:e.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function r(t){var n=e.data(this[0].form,"validator"),r="on"+t.type.replace(/^validate/,"");n.settings[r]&&n.settings[r].call(n,this[0],t)}this.labelContainer=e(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||e(this.currentForm);this.containers=e(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var t=this.groups={};e.each(this.settings.groups,function(n,r){e.each(r.split(/\s/),function(e,r){t[r]=n})});var n=this.settings.rules;e.each(n,function(t,r){n[t]=e.validator.normalizeRule(r)});e(this.currentForm).validateDelegate(":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'] ,[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'] ","focusin focusout keyup",r).validateDelegate("[type='radio'], [type='checkbox'], select, option","click",r);this.settings.invalidHandler&&e(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){this.checkForm();e.extend(this.submitted,this.errorMap);this.invalid=e.extend({},this.errorMap);this.valid()||e(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid()},checkForm:function(){this.prepareForm();for(var e=0,t=this.currentElements=this.elements();t[e];e++)this.check(t[e]);return this.valid()},element:function(t){t=this.validationTargetFor(this.clean(t));this.lastElement=t;this.prepareElement(t);this.currentElements=e(t);var n=this.check(t)!==!1;n?delete this.invalid[t.name]:this.invalid[t.name]=!0;this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers));this.showErrors();return n},showErrors:function(t){if(t){e.extend(this.errorMap,t);this.errorList=[];for(var n in t)this.errorList.push({message:t[n],element:this.findByName(n)[0]});this.successList=e.grep(this.successList,function(e){return!(e.name in t)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){e.fn.resetForm&&e(this.currentForm).resetForm();this.submitted={};this.lastElement=null;this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass).removeData("previousValue")},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(e){var t=0;for(var n in e)t++;return t},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return this.size()===0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{e(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(t){}},findLastActive:function(){var t=this.lastActive;return t&&e.grep(this.errorList,function(e){return e.element.name===t.name}).length===1&&t},elements:function(){var t=this,n={};return e(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&t.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in n||!t.objectLength(e(this).rules()))return!1;n[this.name]=!0;return!0})},clean:function(t){return e(t)[0]},errors:function(){var t=this.settings.errorClass.replace(" ",".");return e(this.settings.errorElement+"."+t,this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=e([]);this.toHide=e([]);this.currentElements=e([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)},prepareElement:function(e){this.reset();this.toHide=this.errorsFor(e)},elementValue:function(t){var n=e(t).attr("type"),r=e(t).val();return n==="radio"||n==="checkbox"?e('input[name="'+e(t).attr("name")+'"]:checked').val():typeof r=="string"?r.replace(/\r/g,""):r},check:function(t){t=this.validationTargetFor(this.clean(t));var n=e(t).rules(),r=!1,i=this.elementValue(t),s;for(var o in n){var u={method:o,parameters:n[o]};try{s=e.validator.methods[o].call(this,i,t,u.parameters);if(s==="dependency-mismatch"){r=!0;continue}r=!1;if(s==="pending"){this.toHide=this.toHide.not(this.errorsFor(t));return}if(!s){this.formatAndAdd(t,u);return!1}}catch(a){this.settings.debug&&window.console&&console.log("exception occured when checking element "+t.id+", check the '"+u.method+"' method",a);throw a}}if(r)return;this.objectLength(n)&&this.successList.push(t);return!0},customMetaMessage:function(t,n){if(!e.metadata)return;var r=this.settings.meta?e(t).metadata()[this.settings.meta]:e(t).metadata();return r&&r.messages&&r.messages[n]},customDataMessage:function(t,n){return e(t).data("msg-"+n.toLowerCase())||t.attributes&&e(t).attr("data-msg-"+n.toLowerCase())},customMessage:function(e,t){var n=this.settings.messages[e];return n&&(n.constructor===String?n:n[t])},findDefined:function(){for(var e=0;e<arguments.length;e++)if(arguments[e]!==undefined)return arguments[e];return undefined},defaultMessage:function(t,n){return this.findDefined(this.customMessage(t.name,n),this.customDataMessage(t,n),this.customMetaMessage(t,n),!this.settings.ignoreTitle&&t.title||undefined,e.validator.messages[n],"<strong>Warning: No message defined for "+t.name+"</strong>")},formatAndAdd:function(t,n){var r=this.defaultMessage(t,n.method),i=/\$?\{(\d+)\}/g;typeof r=="function"?r=r.call(this,n.parameters,t):i.test(r)&&(r=e.validator.format(r.replace(i,"{$1}"),n.parameters));this.errorList.push({message:r,element:t});this.errorMap[t.name]=r;this.submitted[t.name]=r},addWrapper:function(e){this.settings.wrapper&&(e=e.add(e.parent(this.settings.wrapper)));return e},defaultShowErrors:function(){var e,t;for(e=0;this.errorList[e];e++){var n=this.errorList[e];this.settings.highlight&&this.settings.highlight.call(this,n.element,this.settings.errorClass,this.settings.validClass);this.showLabel(n.element,n.message)}this.errorList.length&&(this.toShow=this.toShow.add(this.containers));if(this.settings.success)for(e=0;this.successList[e];e++)this.showLabel(this.successList[e]);if(this.settings.unhighlight)for(e=0,t=this.validElements();t[e];e++)this.settings.unhighlight.call(this,t[e],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return e(this.errorList).map(function(){return this.element})},showLabel:function(t,n){var r=this.errorsFor(t);if(r.length){r.removeClass(this.settings.validClass).addClass(this.settings.errorClass);r.attr("generated")&&r.html(n)}else{r=e("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(t),generated:!0}).addClass(this.settings.errorClass).html(n||"");this.settings.wrapper&&(r=r.hide().show().wrap("<"+this.settings.wrapper+"/>").parent());this.labelContainer.append(r).length||(this.settings.errorPlacement?this.settings.errorPlacement(r,e(t)):r.insertAfter(t))}if(!n&&this.settings.success){r.text("");typeof this.settings.success=="string"?r.addClass(this.settings.success):this.settings.success(r,t)}this.toShow=this.toShow.add(r)},errorsFor:function(t){var n=this.idOrName(t);return this.errors().filter(function(){return e(this).attr("for")===n})},idOrName:function(e){return this.groups[e.name]||(this.checkable(e)?e.name:e.id||e.name)},validationTargetFor:function(e){this.checkable(e)&&(e=this.findByName(e.name).not(this.settings.ignore)[0]);return e},checkable:function(e){return/radio|checkbox/i.test(e.type)},findByName:function(t){return e(this.currentForm).find('[name="'+t+'"]')},getLength:function(t,n){switch(n.nodeName.toLowerCase()){case"select":return e("option:selected",n).length;case"input":if(this.checkable(n))return this.findByName(n.name).filter(":checked").length}return t.length},depend:function(e,t){return this.dependTypes[typeof e]?this.dependTypes[typeof e](e,t):!0},dependTypes:{"boolean":function(e,t){return e},string:function(t,n){return!!e(t,n.form).length},"function":function(e,t){return e(t)}},optional:function(t){var n=this.elementValue(t);return!e.validator.methods.required.call(this,n,t)&&"dependency-mismatch"},startRequest:function(e){if(!this.pending[e.name]){this.pendingRequest++;this.pending[e.name]=!0}},stopRequest:function(t,n){this.pendingRequest--;this.pendingRequest<0&&(this.pendingRequest=0);delete this.pending[t.name];if(n&&this.pendingRequest===0&&this.formSubmitted&&this.form()){e(this.currentForm).submit();this.formSubmitted=!1}else if(!n&&this.pendingRequest===0&&this.formSubmitted){e(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=!1}},previousValue:function(t){return e.data(t,"previousValue")||e.data(t,"previousValue",{old:null,valid:!0,message:this.defaultMessage(t,"remote")})}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(t,n){t.constructor===String?this.classRuleSettings[t]=n:e.extend(this.classRuleSettings,t)},classRules:function(t){var n={},r=e(t).attr("class");r&&e.each(r.split(" "),function(){this in e.validator.classRuleSettings&&e.extend(n,e.validator.classRuleSettings[this])});return n},attributeRules:function(t){var n={},r=e(t);for(var i in e.validator.methods){var s;if(i==="required"){s=r.get(0).getAttribute(i);s===""&&(s=!0);s=!!s}else s=r.attr(i);s?n[i]=s:r[0].getAttribute("type")===i&&(n[i]=!0)}n.maxlength&&/-1|2147483647|524288/.test(n.maxlength)&&delete n.maxlength;return n},metadataRules:function(t){if(!e.metadata)return{};var n=e.data(t.form,"validator").settings.meta;return n?e(t).metadata()[n]:e(t).metadata()},staticRules:function(t){var n={},r=e.data(t.form,"validator");r.settings.rules&&(n=e.validator.normalizeRule(r.settings.rules[t.name])||{});return n},normalizeRules:function(t,n){e.each(t,function(r,i){if(i===!1){delete t[r];return}if(i.param||i.depends){var s=!0;switch(typeof i.depends){case"string":s=!!e(i.depends,n.form).length;break;case"function":s=i.depends.call(n,n)}s?t[r]=i.param!==undefined?i.param:!0:delete t[r]}});e.each(t,function(r,i){t[r]=e.isFunction(i)?i(n):i});e.each(["minlength","maxlength","min","max"],function(){t[this]&&(t[this]=Number(t[this]))});e.each(["rangelength","range"],function(){t[this]&&(t[this]=[Number(t[this][0]),Number(t[this][1])])});if(e.validator.autoCreateRanges){if(t.min&&t.max){t.range=[t.min,t.max];delete t.min;delete t.max}if(t.minlength&&t.maxlength){t.rangelength=[t.minlength,t.maxlength];delete t.minlength;delete t.maxlength}}t.messages&&delete t.messages;return t},normalizeRule:function(t){if(typeof t=="string"){var n={};e.each(t.split(/\s/),function(){n[this]=!0});t=n}return t},addMethod:function(t,n,r){e.validator.methods[t]=n;e.validator.messages[t]=r!==undefined?r:e.validator.messages[t];n.length<3&&e.validator.addClassRules(t,e.validator.normalizeRule(t))},methods:{required:function(t,n,r){if(!this.depend(r,n))return"dependency-mismatch";if(n.nodeName.toLowerCase()==="select"){var i=e(n).val();return i&&i.length>0}return this.checkable(n)?this.getLength(t,n)>0:e.trim(t).length>0},remote:function(t,n,r){if(this.optional(n))return"dependency-mismatch";var i=this.previousValue(n);this.settings.messages[n.name]||(this.settings.messages[n.name]={});i.originalMessage=this.settings.messages[n.name].remote;this.settings.messages[n.name].remote=i.message;r=typeof r=="string"&&{url:r}||r;if(this.pending[n.name])return"pending";if(i.old===t)return i.valid;i.old=t;var s=this;this.startRequest(n);var o={};o[n.name]=t;e.ajax(e.extend(!0,{url:r,mode:"abort",port:"validate"+n.name,dataType:"json",data:o,success:function(r){s.settings.messages[n.name].remote=i.originalMessage;var o=r===!0||r==="true";if(o){var u=s.formSubmitted;s.prepareElement(n);s.formSubmitted=u;s.successList.push(n);delete s.invalid[n.name];s.showErrors()}else{var a={},f=r||s.defaultMessage(n,"remote");a[n.name]=i.message=e.isFunction(f)?f(t):f;s.invalid[n.name]=!0;s.showErrors(a)}i.valid=o;s.stopRequest(n,o)}},r));return"pending"},minlength:function(t,n,r){var i=e.isArray(t)?t.length:this.getLength(e.trim(t),n);return this.optional(n)||i>=r},maxlength:function(t,n,r){var i=e.isArray(t)?t.length:this.getLength(e.trim(t),n);return this.optional(n)||i<=r},rangelength:function(t,n,r){var i=e.isArray(t)?t.length:this.getLength(e.trim(t),n);return this.optional(n)||i>=r[0]&&i<=r[1]},min:function(e,t,n){return this.optional(t)||e>=n},max:function(e,t,n){return this.optional(t)||e<=n},range:function(e,t,n){return this.optional(t)||e>=n[0]&&e<=n[1]},email:function(e,t){return this.optional(t)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(e)},url:function(e,t){return this.optional(t)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(e)},date:function(e,t){return this.optional(t)||!/Invalid|NaN/.test(new Date(e))},dateISO:function(e,t){return this.optional(t)||/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/.test(e)},number:function(e,t){return this.optional(t)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(e)},digits:function(e,t){return this.optional(t)||/^\d+$/.test(e)},creditcard:function(e,t){if(this.optional(t))return"dependency-mismatch";if(/[^0-9 \-]+/.test(e))return!1;var n=0,r=0,i=!1;e=e.replace(/\D/g,"");for(var s=e.length-1;s>=0;s--){var o=e.charAt(s);r=parseInt(o,10);i&&(r*=2)>9&&(r-=9);n+=r;i=!i}return n%10===0},equalTo:function(t,n,r){var i=e(r);this.settings.onfocusout&&i.unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){e(n).valid()});return t===i.val()}}});e.format=e.validator.format})(jQuery);(function(e){var t={};if(e.ajaxPrefilter)e.ajaxPrefilter(function(e,n,r){var i=e.port;if(e.mode==="abort"){t[i]&&t[i].abort();t[i]=r}});else{var n=e.ajax;e.ajax=function(r){var i=("mode"in r?r:e.ajaxSettings).mode,s=("port"in r?r:e.ajaxSettings).port;if(i==="abort"){t[s]&&t[s].abort();return t[s]=n.apply(this,arguments)}return n.apply(this,arguments)}}})(jQuery);(function(e){!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener&&e.each({focus:"focusin",blur:"focusout"},function(t,n){function r(t){t=e.event.fix(t);t.type=n;return e.event.handle.call(this,t)}e.event.special[n]={setup:function(){this.addEventListener(t,r,!0)},teardown:function(){this.removeEventListener(t,r,!0)},handler:function(t){var r=arguments;r[0]=e.event.fix(t);r[0].type=n;return e.event.handle.apply(this,r)}}});e.extend(e.fn,{validateDelegate:function(t,n,r){return this.bind(n,function(n){var i=e(n.target);if(i.is(t))return r.apply(i,arguments)})}})})(jQuery);;/**
 * Global JavaScript Object
 *
 * @author      Zone
 * @email           info@zonecontent.com
 * @url             http://www.zonecontent.com/
 * @copyright   Copyright (c) 2012, zonecontent.com. All rights reserved.
 * @version     0.0.1
 */

var macmillan;

(function ($) {

    macmillan = {

        /* CONSTANTS
        ----------------------------------------------------------------------------- */

        CONSTANTS: {
            /* Global */
            ALERT_FALLBACK: false,
            HTML_SNIPPETS_URL: $('body').data('snippets-url')

            /* Appended */
            // HTML_SNIPPETS
        },

        //Global animation effects
        animation: {
            speed: 350,
            easing: 'linear'
        },

        /* FUNCTIONS
                - init()
                    define_console_log();
                    load_html_snippets();
                    placeholder_fallback();
                    init_file_upload();
                    init_donation_type_interraction();
                    init_custom_forms();
                    jquery_validate_submit();
                    init_overlay_popup();
                    init_waypoints();
                    prevent_default_on_disabled();
                    
        ----------------------------------------------------------------------------- */

        init: function () {

            // Initial setup
            macmillan.define_console_log();
            macmillan.load_html_snippets();
            macmillan.placeholder_fallback();
            macmillan.init_file_upload();
            macmillan.init_donation_type_interraction();
            macmillan.init_custom_forms();
            macmillan.init_js_radio_toggle();
            macmillan.init_overlay_popup();
          // macmillan.init_waypoints();
            macmillan.prevent_default_on_disabled();

            // init plugins
            $('.scrollpanels').scrollPanels();
            $('.slider').macmillan('slider');
            $('.calculator').macmillan('calculator');
            $('.sync_amount').macmillan('sync_amount');

        },

        /* ----------------------------------------------------------------------------- */

        /* Define console.log */
        define_console_log: function () {
            if (typeof console === 'undefined' || typeof console.log === 'undefined') {
                /*globals console:true*/
                console = {};
                if (macmillan.CONSTANTS.ALERT_FALLBACK) {
                    console.log = function (msg) {
                        alert(msg);
                    };
                } else {
                    console.log = function () { };
                }
            }
        },

        /* Load HTML snippets */
        load_html_snippets: function () {
            $.ajax({
                url: macmillan.CONSTANTS.HTML_SNIPPETS_URL,
                datatype: 'text/html',
                async: false,
                success: function (data) {
                    macmillan.CONSTANTS.HTML_SNIPPETS = data;
                }
            });
        },

        /* Placeholder fallback */
        placeholder_fallback: function () {
            /*globals Modernizr:true*/
            if (!Modernizr.input.placeholder) {
                $('[placeholder]').focus(function () {
                    var input = $(this);
                    if (input.val() === input.attr('placeholder')) {
                        input.val('').removeClass('placeholder');
                    }
                }).blur(function () {
                    var input = $(this);
                    if (input.val() === '') {
                        input.val(input.attr('placeholder')).addClass('placeholder');
                    }
                }).blur();
                $('form').submit(function () {
                    $('[placeholder]', this).each(function () {
                        var input = $(this);
                        if (input.val() === input.attr('placeholder')) {
                            input.val('').removeClass('placeholder');
                        }
                    });
                });
            }
        },

        init_file_upload: function () {

            $('fieldset .upload').each(function (i) {

                var $this = $(this),
                realInput = $this.find('input.form-file')
                .css({
                    left: '-9999em',
                    position: 'absolute'
                }),
                fakeInput = $this.find('div.fakefile input'),
                fakeTrigger = $this.find('div.fakefile a.button');

                fakeInput.add(fakeTrigger).on('click', function () {
                    realInput.click();
                });

                if (realInput.hasClass('error')) {
                    fakeInput.addClass('error');
                }

                realInput.change(function () {
                    var str = "";
                    str = $(this).val();
                    fakeInput.val(str);
                }).change();
            });
        },
        init_donation_type_interraction: function () {
            setTimeout(function() {
                $('input[name="Donation.DonationType"]').each(function () {
                    if ($("label[for='" + $(this).attr("id") + "']").hasClass('ui-state-active')) {
                        $("label[for='" + $(this).attr("id") + "']").removeClass('ui-state-active');
                    }
                });

                var checkedElementId = $('input[name="Donation.DonationType"]').filter(":checked").attr("id");
                $("label[for='" + checkedElementId + "']").addClass('ui-state-active');

                $('input[name="Donation.Payment.Amount"]').val(function () {
                    return ($(this).val() == 0 ? "" : $(this).val().replace(".00", ""));
                });
    
                if ($('input[name="Donation.DonationType"]').filter(":checked").val() == 'OneOff') {
                    $('.org-detail').removeClass('hidden');
                }
            }, 500);

            let donationTypeElements = document.querySelectorAll('.payment-option-label');

            let defaultTab = sessionStorage.getItem('donationTab') ? sessionStorage.getItem('donationTab') : 'one-off';
            
            let donationTypeRadios = document.querySelector('.donationTypeRadios');

            if(donationTypeRadios) {
                defaultTab == 'one-off' ? donationTypeRadios.classList.remove('hidden') : donationTypeRadios.classList.add('hidden');
            }

            if($('.mobileAmountSelector').css('display') == 'none') {
                donationTypeRadios.classList.remove('hidden');
            }

            Array.prototype.forEach.call(donationTypeElements, function(type) {
                type.addEventListener('click', function(event) {
                    $("#IsOnBehalfOfOrganisation_true").prop('checked', false);
                    $("label[for='IsOnBehalfOfOrganisation_true']").removeClass('ui-state-active');
   
                    $("#IsOnBehalfOfOrganisation_false").prop('checked', true);
                    $("label[for='IsOnBehalfOfOrganisation_false']").addClass('ui-state-active');

                    if (event.target.getAttribute('data-option') == 'one-off') {
                        
                        document.querySelector('.donationTypeRadios').classList.remove('hidden');

                        $('.org-detail').removeClass('hidden');
                        if (!$("label[for='IsOnBehalfOfOrganisation_true']").attr('aria-pressed') == false 
                            || !$("label[for='IsOnBehalfOfOrganisation_false']").attr('aria-pressed') == true) {
                            $('.gift-toggle-content').removeClass('hidden');
                            $('.gift-toggle-content').attr('style', 'display:block;');
                        }
                        macmillan.utils.setReversedRadioToggles();
                        macmillan.utils.setRequiredTaxPayer(true);
                    } else if (event.target.getAttribute('data-option') == 'regular') {
                        document.querySelector('.donationTypeRadios').classList.add('hidden');
                        $('.org-detail').addClass('hidden');
                        $('.gift-toggle-content').removeClass('hidden');
                        $('.gift-toggle-content').show();
                        macmillan.utils.setRequiredTaxPayer(true);
                        // set the default values for the organization
                    } else if (event.target.getAttribute('data-option') == 'Event') {
                        $('.org-detail').removeClass('hidden'); macmillan.utils.removeReversedRadioToggles();
                        $('.gift-toggle-content').addClass('hidden');
                        $('.gift-toggle-content').attr('style', 'display:none');
                        macmillan.utils.setRequiredTaxPayer(false);
                    }
                    $('input[name="Donation.Payment.Amount"]').keyup(function () {
                        macmillan.utils.setGiftAidMessage(this.value);
                    })
                    macmillan.utils.setGiftAidMessage($('input[name="Donation.Payment.Amount"]').val());
                });
            });
            $('input[name="Donation.DonationType"][type="radio"]').change(function () {
                // reset the value for on behalf of an organisation when the value of the donation type changes
                 $("#IsOnBehalfOfOrganisation_true").prop('checked', false);
                 $("label[for='IsOnBehalfOfOrganisation_true']").removeClass('ui-state-active');

                 $("#IsOnBehalfOfOrganisation_false").prop('checked', true);
                 $("label[for='IsOnBehalfOfOrganisation_false']").addClass('ui-state-active');

                if (this.value == 'OneOff') {
                    sessionStorage.setItem('donationRadio', 'OneOff');
                    $('.org-detail').removeClass('hidden');
                    if (!$("label[for='IsOnBehalfOfOrganisation_true']").attr('aria-pressed') == false 
                        || !$("label[for='IsOnBehalfOfOrganisation_false']").attr('aria-pressed') == true) {
                        // enable the gift aid box only if the IsOnBehalfOfOrganisation is not set to true
                        $('.gift-toggle-content').removeClass('hidden');
                        $('.gift-toggle-content').attr('style', 'display:block;');
                    }
                    macmillan.utils.setReversedRadioToggles();
                    macmillan.utils.setRequiredTaxPayer(true);
                } else if (this.value == 'Regular') {
                    sessionStorage.setItem('donationRadio', 'regular');
                    $('.org-detail').addClass('hidden');
                    $('.gift-toggle-content').removeClass('hidden');
                    $('.gift-toggle-content').show();
                    macmillan.utils.setRequiredTaxPayer(true);
                    // set the default values for the organization
                } else if (this.value == 'Event') {
                    sessionStorage.setItem('donationRadio', 'Event');
                    $('.org-detail').removeClass('hidden'); macmillan.utils.removeReversedRadioToggles();
                    $('.gift-toggle-content').addClass('hidden');
                    $('.gift-toggle-content').attr('style', 'display:none');
                    macmillan.utils.setRequiredTaxPayer(false);
                }
                setTimeout(function() {
                    $('#DonationTypeAndAmount')[0] ? $('#DonationTypeAndAmount').validate().element('#Donation_Payment_Amount') : $('form.wbcmform').validate().element('#Donation_Payment_Amount');
                    macmillan.utils.setGiftAidMessage($('input[name="Donation.Payment.Amount"]').val());
                }, 400);
            });

            $('input[name="Donation.Payment.Amount"]').keyup(function () {
                macmillan.utils.setGiftAidMessage(this.value);
            });
        },
        init_custom_forms: function () {
            /* Custom form elements  */
            $(".custom-radio input").button({
                icons: {
                    primary: 'radio_sprite'
                }
            });
            $(".custom-checkbox input").button({
                icons: {
                    primary: 'checkbox_sprite'
                }
            });
        },

        init_js_radio_toggle: function () {
            // used in conjunction with custom radio buttons
            var $container = $('.container');
            var $toggle_wrapper = $container.find($('.js-toggle'));
            var $trigger_open = $toggle_wrapper.find($('.js-toggle-open'));
            var $trigger_closed = $toggle_wrapper.find($('.js-toggle-closed'));

            // js-toggle-options uses custon radio buttons
            var $options_wrapper = $container.find($('.js-toggle-options'));
            var $options_triggerlist = $options_wrapper.find($('.js-option-trigger'));
            var $options_contentlist = $options_wrapper.find($('.js-option-content'));

            var animating = false;

            // close all content boxes that aren't checked open
            $trigger_closed.find('.ui-button').each(function () {
                // override the animation check
                var override = true;
                if ($(this).hasClass('ui-state-active')) {
                    toggle_closed($(this).closest('div.row'), override);
                }
            });

            // $('.ui-state-active').removeClass('ui-state-active');

            // set initial open option
            $options_triggerlist.find('.ui-button').each(function () {
                ($(this).hasClass('ui-state-active'))
                ? toggle_options($(this).closest('.js-option-trigger').index())
                : '';
            });

            // setup the handers 
            // send the root node to the required process
            $trigger_open.on('click', '.ui-button', function () {
                toggle_open($(this).closest('div.row'));
            });
            $trigger_closed.on('click', ' .ui-button', function () {
                toggle_closed($(this).closest('div.row'));
            });
            $trigger_open.on('focus', 'input', function () {
                toggle_open($(this).closest('div.row'));
            });
            $trigger_closed.on('focus', 'input', function () {
                toggle_closed($(this).closest('div.row'));
            });

            $options_wrapper.on('click', '.ui-button', function () {
                var index = $(this).closest('.js-option-trigger').index();
                toggle_options(index);
            });
            $options_wrapper.on('focus', 'input', function () {
                var index = $(this).closest('.js-option-trigger').index();
                toggle_options(index);
            });

            function toggle_open($rootnode, override) {
                if (animating !== true || override !== '') {
                    animating = true;
                    // select the associated content, show and make it required
                    $rootnode.next('.js-toggle-content')
                    .removeClass('hidden')
                    .slideDown({
                        complete: function () {
                          //  $(this).find('input, select').prop('required', 'required');
                            animating = false;
                        }
                    });
                }
                return false;
            }

            function toggle_closed($rootnode, override) {
                if (animating !== true || override !== '') {
                    animating = true;
                    $rootnode.next('.js-toggle-content')
                    .slideUp({
                        complete: function () {
                            $(this).addClass('hidden');
                            animating = false;
                        }
                    })
                 //   .find('input, select').removeProp('required', 'required');
                }
                return false;
            }

            function toggle_options(index) {
                // close all
                $options_contentlist.addClass('hidden');
                // open selected
                $options_contentlist.eq(index).removeClass('hidden');
            }

        },

        init_overlay_popup: function () {

            var $container = $('.container');
            var $popups = $container.find($('.popup'));
            var $overlay = $container.find($('div#overlay'))
            .on('click', closeAll);

            // bind the handler to the main content
            $container.on('click', 'a.question', function (e) {
                $(this).parents('label').siblings('.popup')
                .removeClass('hidden')
                .on('click', '.close', closeAll);
                $overlay.removeClass('hidden');
                e.preventDefault();
            });

            // close the overlay and all popups
            function closeAll(e) {
                $overlay.addClass('hidden');
                $popups.addClass('hidden');
                e.preventDefault();
            };

        },

     

        prevent_default_on_disabled: function () {

            $('.disabled').on('click', function(e) {
                e.preventDefault();
                return false;
            });
        }

    };

    /* ----------------------------------------------------------------------------- */

    //  This function allows us to use VB style string.format on snippets
    //  to replace placeholders {0}, {1}, etc with values.

    String.prototype.format = function () {                                          //function to allow templates to have placeholders for values
        var args = arguments;                                                         //EG:       somestring = "this is {0} an example {1} to show {2} formats"
        return this.replace('%7B', '{').replace('%7D', '}').replace(/{(\d+)}/g, function (match, number) {                     //          somestring.format(value1,value2,value3,etc)
            return typeof args[number] != 'undefined'                                   //RETURNS:  "this is value1 an example value2 to show value3 formats"
            ? args[number]
            : match
            ;
        });
    };

    /* ----------------------------------------------------------------------------- */


    $(function () {
        macmillan.init();
    });

})(jQuery);
;/*
+------------------------------------------------------------------------------+
|                                              
|  Jquery Plugin: macmillan plugin library 1.0
|
|  File Written By: 
|  - Dominic da Costa @ Zone
|  - http://www.thisiszone.com
|            

+------------------------------------------------------------------------------+

This is the base plugin that will initialize the appropriate methods within the Donations library.
Each method lives in its own extension and will have its own properties & methods

e.g.

    For the calculator method, there is a file called jquery.macmillan.calculator.
    Within that plugin there is all the logic to handle the calculation of tax based on user input
    To initialize the method on a selector, you simply call :
    
    $('.selector').macmillan('calculator');

+------------------------------------------------------------------------------+
 */
   
(function( $ ){
 
    $.fn.macmillan = function(method) {
        
        // Method calling logic
        if ( macmillan.methods[method] ) {
            return macmillan.methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return macmillan.methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on macmillan' );
        }    

    };    
   
})( jQuery );;/*
+------------------------------------------------------------------------------+
|                                              
|  Jquery Plugin: $donate.calculator 1.0
|
|  File Written By: 
|  - Dominic da Costa @ Zone
|  - http://www.thisiszone.com
|                                                
+------------------------------------------------------------------------------+
 */
(function ($) {
    
    macmillan.methods = macmillan.methods || {};

    //+-----------------------------------------------------------------+

    macmillan.methods.calculator = function() {
  
        //+-----------------------------------------------------------------+
     
        return this.each(function() {
     
            var $settings={
                'currency':'£',
                'rate':'25'
            };
        
            var $calculator = $(this);
           
            $.extend($settings, $calculator.data());                             //update the settings with the Data options set
     
            
            var $output = {
                amount : $calculator.find('.output .amount'),
                cost : $calculator.find('.output .cost'),
                relief : $calculator.find('.output .relief'),
                received : $calculator.find('.output .received') 
            }
            
            var $input ={
                amount : $calculator.find('input[name=amount]'),
                rate : $calculator.find('input[name=rate]')
            }
            
            
            // set the event handlers
            $input.amount.on('change keyup',amount_handler);
            $input.rate.on('change',rate_handler);
                
            //+-------------------------------------------------------------+
            
            function calculate(value, rate){
               
                //we use .toFixed(2) to force 2 decimal places on values
                var $value = (typeof value !== 'undefined') && ( isNaN( value ) != true ) ? value : 0,
                $rate = (typeof rate !== 'undefined') ? rate : $settings.rate;
                
                var $relief = ($value * ($rate/100)).toFixed(2),
                $cost = ($value - $relief).toFixed(2);
                    
                var $received = ($value - (- $relief)).toFixed(2);
                    
                if($output.amount){
                    $output.amount.text($settings.currency + Number($value).toFixed(2)); 
                }
               
                if($output.cost){
                    $output.cost.text($settings.currency + $cost );
                }
               
                if($output.relief){
                    $output.relief.text($settings.currency + $relief )
                }
               
                if($output.received){ 
                    $output.received.text($settings.currency + $received )
                }
                
               
            };

            function amount_handler() {

                var $this = $(this);
                calculate(  $this.val(), $input.rate.val());
            };
            
            function rate_handler() {

                var $this = $(this);
                calculate(  $input.amount.val(), $this.val());
            };
           
        });
    
    };


})(jQuery);
;/*
+------------------------------------------------------------------------------+
|                                              
|  Jquery Plugin: sync-amount 1.0
|
|  File Written By: 
|  - Dominic da Costa @ Zone
|  - http://www.thisiszone.com
|                                                
+------------------------------------------------------------------------------+
This plugin keeps several elements in sync, based on the amount field for various donation forms and calculators.
The principal is based around updating all elements mrked with a '.sync_amount' class wheneve any of them change.
 */
(function ($) {
    
    macmillan.methods = macmillan.methods || {};

    //+-----------------------------------------------------------------+

    macmillan.methods.sync_amount = function() {
  
        //+-----------------------------------------------------------------+
     
        return this.each(function() {
            
            var $input = $(this);
            
            // set the event handlers
            $(document).on('sync_amount_changed',sync_amount_handler);
            $input.on('click change keyup',amount_handler);
           
            //+-------------------------------------------------------------+
            
            function sync_amount_handler(e){
               
                if($input.val()!==e.amount && $input.data('amount') == undefined){
                
                    $input.val(e.amount);
                    $input.trigger('change');
                }
                
            };
            
            function amount_handler(e){
                
                var $this = $(this);
                
                //validate value
                var $value = $this.data('amount') || $this.val();
                $value = (typeof $value !== 'undefined') && ( isNaN( $value ) != true ) ? $value : 0;
               
                //trigger the event to sync the amount
                var event = $.Event("sync_amount_changed");
                event.amount = $value;
                $input.trigger(event);
                
                e.preventDefault();
                
            }
           
        });
    
    };


})(jQuery);
;/*
+------------------------------------------------------------------------------+
|                                              
|  Jquery Plugin: $donate.calculator 1.0
|
|  File Written By: 
|  - Dominic da Costa @ Zone
|  - http://www.thisiszone.com
|                                                
+------------------------------------------------------------------------------+
 */
(function ($) {
    macmillan.methods = macmillan.methods || {};
    //+-----------------------------------------------------------------+

    macmillan.methods.slider = function() {
        return this.each(function () {
            var $settings = {
                'currency': '£'
            };

            var isFromCampaign = $('#FromCampaign').val() == 'true' ? true : false;

            var $slider = $(this);

            $.extend($settings, $slider.data()); //update the settings with the Data options set

            var $wrapper = $slider.find('.wrapper');
            var $controls = $slider.find('.controls');
            var $bar = $slider.find('.bar');
            var $triggers = $bar.find('.trigger');

            var $panels = $slider.find('.panel');
            var $panels_filtered = undefined;

            var $btn_donate = $slider.find(".set-donation");

            var $filters = $slider.find(".filters input[type='radio']");
            var $is_animating = false;

            var $active_panel;
            var $active_index;
            var $active_trigger;

            let defaultDontationAmountPosition = 2;
            
            let desktop = typeof window.orientation !== 'undefined' ? false : true;

            //bind the events
            $('#Donation_Payment_Amount').on('change keyup', amount_handler);
            $btn_donate.on('click', set_amount);
            $controls.on('click', set_amount);
            $filters.on('change', function() {
                desktop ? filter_panels() : null;
            });

            //apply the filters to the active filter option
            desktop ? filter_panels() : null;

            //+----------------------------------------------------------------------+

            function filter_panels(e) {
                var $this;

                //if this was triggered from a click event 
                if (!e || typeof e == 'undefined' || e.length == 0) {
                    // if one of the donation type radio button is checked
                    if ($filters.is(':checked')) {
                        $filters.each(function () {
                            if ($(this).attr('checked') === 'checked') {
                                $this = $(this);
                            }
                        });
                    } else {
                        $this = $filters.first(":checked");
                    }
                }
                else {
                    $this = $(this);
                }
                $panels_filtered = $panels.siblings('.' + $this.val());

                set_triggers();
                set_amount('default');
                set_active();
            }

            function set_triggers() {
                //set prev/next
                $controls.append('<a href="#prev" class="trigger prev">previous</a><a href="#next" class="trigger next">next</a>');
                var $prev = $controls.find('.prev');
                var $next = $controls.find('.next');

                //get the template for the trigger from the snippets
                var $tmpl = '<li class="trigger" data-amount="{0}">{1}{0}</li>';

                //remove any previous triggers
                $triggers.remove();                                                                                 //remove the counters if not necessary

                //re-populate the triggers based on the filtered panels
                var $counter;
                var $len = $panels_filtered.length;

                for($counter = 0; $counter < $len; $counter++) {
                    var $panel = $($panels_filtered.get($counter));
                    var $value = $panel.get(0).getAttribute('data-amount');
                    var $trigger = $($tmpl.format($value, $settings.currency));

                    $bar.append($trigger);
                }

                //refresh the triggers
                $triggers = $bar.find('.trigger');

                // set the event handlers
                $triggers.on('click', prevnext);
                $prev.on('click', prevnext);
                $next.on('click', prevnext);

                // Check for initial active panel
                $active_panel = $panels_filtered.first('.active') || $panels_filtered.first();
                $active_index = $active_panel.index() > $panels_filtered.length-1 ? 2 : $active_panel.index();
                $active_trigger = $triggers.get($active_index);

                //trigger the change event for the input field
                //this is to update the slider to show the entered value
            }

            function set_active(e) {
                if (!e || typeof e == 'undefined' || e.length == 0) {
                    if(isFromCampaign) {
                        var payinAmount = $active_panel.data('amount');
                        
                        var donationAmounts = []
                        
                        $panels_filtered.each(function(i) {
                            donationAmounts.push($panels_filtered[i].getAttribute('data-amount'));
                        })

                        var closest = donationAmounts.reduce(function(prev, curr) {
                            return (Math.abs(curr - payinAmount) < Math.abs(prev - payinAmount) ? curr : prev);
                        });

                        $panels_filtered.each(function(i) {
                            if($panels_filtered[i].getAttribute('data-amount') == closest) {
                                $active_index = i;
                            }
                        })
                    }else {
                        $active_index = defaultDontationAmountPosition;
                        
                        setTimeout(function() {
                            triggers = document.getElementsByClassName('trigger active');
                            document.querySelector('#Donation_Payment_Amount').value = triggers[0].getAttribute('data-amount');
                        }, 300)
                    }
                } else {
                    //validate the index
                    $active_index = Math.max($active_index, 0);
                    $active_index = Math.min($active_index, ($panels_filtered.length - 1));
                }

                $is_animating = true;

                //set the active trigger
                $active_trigger = $triggers.eq($active_index);
                $active_trigger.addClass('active').siblings().removeClass('active');

                //set the active panel
                $active_panel = $panels_filtered.eq($active_index);
                $wrapper.height($active_panel.outerHeight(true));
                $active_panel.addClass('active').siblings().removeClass('active');

                //animate the controls
                var leftPosition;
                if ($active_trigger.position() === null) {
                    leftPosition = 0;
                } else {
                    leftPosition = $active_trigger.position().left
                }
                $controls.animate(
                    {
                        left: leftPosition
                    },
                    macmillan.animation.speed,
                    macmillan.animation.easing,
                    function () {
                        $is_animating = false;

                        $controls.find('.prev').removeClass('disabled');
                        $controls.find('.next').removeClass('disabled');

                        $controls.find('.prev').addClass($active_panel.prev().length == 0 ? 'disabled' : '');
                        $controls.find('.next').addClass($active_panel.next().length == 0 ? 'disabled' : '');
                    }
                );
                set_amount();
            }

            function prevnext(e) {
                e.preventDefault();

                var $this = $(this);

                if ($this.hasClass('disabled') || $controls.hasClass('disabled')) {
                    return;
                }
                if (!$is_animating) {
                    if ($this.hasClass('prev')) {
                        --$active_index;
                    } else if ($this.hasClass('next')) {
                        ++$active_index;
                    } else {
                        $active_index = $this.index();
                    }
                }
                set_active(e);
                set_amount('prevNext');
                $('#DonationTypeAndAmount')[0] ? $('#DonationTypeAndAmount').validate().element('#Donation_Payment_Amount') : $('form.wbcmform').validate().element('#Donation_Payment_Amount');
                macmillan.utils.setGiftAidMessage($('input[name="Donation.Payment.Amount"]').val());
            }

            function set_amount(eventTarget) {
                var $value = $active_panel.get(0).getAttribute('data-amount');
                $value = (typeof $value !== 'undefined') && (isNaN($value) != true) ? $value : 0;

                if(eventTarget == 'default') {
                    if(isFromCampaign) {
                        $('#Donation_Payment_Amount').attr('value', $('#Donation_Payment_Amount').val());
                        $active_panel.data('amount', $('#Donation_Payment_Amount').val());
                    }else {
                        $('#Donation_Payment_Amount').attr('value', $('.triggers').find('.trigger')[2].getAttribute('data-amount'));
                    }
                }else if(eventTarget == 'prevNext') {
                    $('#Donation_Payment_Amount').attr('value', $value);
                }else {
                    $('#Donation_Payment_Amount').attr('value', $('#Donation_Payment_Amount').val());
                }

                macmillan.utils.setGiftAidMessage($('#Donation_Payment_Amount').val());
            }

            function amount_handler(e) {
                e.preventDefault();

                var $this = $(this);

                //validate value
                var $value = $this.val();
                $value = (typeof $value !== 'undefined') && (isNaN($value) != true) ? $value : 0;

                var $i;
                var $length = $triggers.length;

                if($('.paymentOptionContainer').css('display') == 'none') {    
                    if ($value <= $panels_filtered.first().data('amount')) {
                        $active_index = 0;
                    } else if ($value >= $panels_filtered.last().data('amount')) {
                        $active_index = $length - 1;
                    } else {
                        for ($i = 0; $i < $length; $i++) {
                            if ($panels_filtered.eq($i).data('amount') >= $value) {
                                $active_index = $i;
                                break;
                            }
                        }
                    }
                }
                desktop ? set_active(e) : null;                
            }
        });
    };
})(jQuery);;/**
 * Gallery jQuery Plugin
 *
 * @author      Zone
 * @email           info@zonecontent.com
 * @url             http://www.zonecontent.com/
 * @copyright   Copyright (c) 2012, zonecontent.com. All rights reserved.
 * @version     0.0.1
 */

var accordion;

(function ($) {
    accordion = {
    
        /* CONSTANTS
        ----------------------------------------------------------------------------- */
            
        /* VARIABLES
        ----------------------------------------------------------------------------- */
        
        /* FUNCTIONS
                - init(selector)
        ----------------------------------------------------------------------------- */
    
        init: function(selector) {
            
            $(selector).each(function() {
                var $this = $(this);
                var $container = $this;

                var $activeelement = $('.accordion-btn.active', $container);
                
                        // Loop through each accordion button
                        $('.accordion-btn', $this).each(function($container) {
                            var $this = $(this);
                            var $content = $this.next();
                            var $contentHeight = $content.height();
                            $container = $this.parent(selector);
                            
                            if ($('.maskedaccordion .accordion-btn.open').length) {
                                        $this.find('.button').addClass('hiddenopacity');
                                    } else {
                                    }

                            // Add the icon
                            $('<span class="iconwrapper"><span class="icon"></span></span>').prependTo($this);
                            
                            $('.mainaccordion .accordion-btn.open')
                                .find('.iconwrapper').addClass('hiddenopacity');

                            // Click event
                            $('.accordionclose').bind("click", function(event){
                                event.preventDefault();
                                if($this.parents('.maskedaccordion, .mainaccordion').length){
                                    $this.find('.button').removeClass('hiddenopacity');
                                    $this.find('.iconwrapper').removeClass('hiddenopacity');
                                }
                                $this.parents('.accordion-btn').removeClass('open');
                                $(this).hide();
                                $this.parents('.mainaccordion, .maskedaccordion')
                                    .find('.accordion-container .accordion-content')
                                        .not($this.siblings())
                                        .animate({
                                            height: 0
                                        });
                                $this.parents('.accordion-btn').next().animate({
                                    height: 0
                                });
                            });
                            
                            $this.bind("click", function(event){

                                var $closebutton = $this.parent().find('.accordion-content .accordionclose');

                                    event.preventDefault();

                                    if ($this.hasClass('open')) {
                                        if($this.parents('.maskedaccordion, .mainaccordion').length){
                                            $this.find('.button').removeClass('hiddenopacity');
                                            $this.find('.iconwrapper').removeClass('hiddenopacity');
                                        }

                                        $this.removeClass('open');

                                        $closebutton.hide();
                                        $this.next().animate({
                                            height: '0'
                                        }, function(){
                                            
                                        });
                                    } else {
                                        $closebutton.hide();
                                        $this.addClass('open');
                                            if($this.parents('.maskedaccordion, .mainaccordion').length){
                                                $this.find('.button').addClass('hiddenopacity');
                                                $this.find('.iconwrapper').addClass('hiddenopacity');
                                            }
                                        $this.next().animate({
                                            height: ($contentHeight -1)
                                        }, function(){
                                            $closebutton.show();
                                        });
                                        if($this.parents('.mainaccordion, .maskedaccordion').length){
                                            $this.parents('.mainaccordion, .maskedaccordion').find('.accordion-container .accordion-btn')
                                                .not($this)
                                                .removeClass('open');
                                            $this.parents('.mainaccordion, .maskedaccordion').find('.accordion-container .accordion-content').not($this.siblings()).animate({
                                                height: 0
                                            });
                                            $this.parents('.mainaccordion, .maskedaccordion').find('.accordion-container .accordion-btn').not($this).find('.button').removeClass('hiddenopacity');
                                            $this.parents('.mainaccordion, .maskedaccordion').find('.accordion-container .accordion-btn').not($this).find('.iconwrapper').removeClass('hiddenopacity');
                                        } else {
                                            $this.siblings('.accordion-btn').removeClass('open');
                                            $this.siblings('.accordion-btn').next().animate({
                                                height: 0
                                            });
                                        }
                                    }
                            });
                            
                        });

                        // Show active item open or show first item open
                        // For the case of FAQs none should start open

                        if ($('.accordion-btn.active', $container).length > 0) {
                            $activeelement = $('.accordion-btn.active', $container);
                            accordion.close_all($activeelement);
                        } else {
                            $activeelement = $('.accordion-btn:first', $container);
                            accordion.close_all($activeelement);
                        }
                });
            },

        close_all: function( $activeelement ) {
            // If the startclosed class is present
            if($activeelement.parents('.startclosed').length){
                $activeelement.parents('.mainaccordion, .maskedaccordion').find('.accordion-container .accordion-content').animate({
                        height: 0
                    });
                    $activeelement.parents('.maskedaccordion').find('.accordion-container .accordion-content').animate({
                        height: 0
                    });
            } else {
                if($activeelement.parents('.mainaccordion, .maskedaccordion').length){
                    $activeelement.addClass('open');
                    $activeelement.parents('.mainaccordion, .maskedaccordion').find('.accordion-container .accordion-content').not($activeelement.next()).animate({
                        height: 0
                    });
                    $activeelement.parents('.maskedaccordion').find('.accordion-container .accordion-content').animate({
                        height: 0
                    });
                } else {
                    $activeelement.addClass('open');
                    $activeelement.next().siblings('.accordion-content').animate({
                        height: 0
                    });
                }

            }

        }
        
    };
    $(window).load(function(){
        accordion.init('.accordion');
        });
    //$(function() { accordion.init('.accordion'); });
})(jQuery);


;/*
+------------------------------------------------------------------------------+
|                                              
|  Jquery Plugin: $wrapperls 1.00
|
|  File Written By:                                  
|  - Dominic da Costa
|  - http://www.zonecontent.com
|                                                
+------------------------------------------------------------------------------+
 */(function(e){e.fn.scrollPanels=function(){return this.each(function(){function h(){e.extend(f,r.data());f.scrollitems=parseInt(f.scrollitems);o.append(e(macmillan.CONSTANTS.HTML_SNIPPETS).find("#scrollpanels .controls").html());var t=o.find(".prev"),n=o.find(".next"),i=o.find(".playpause");if(f.scrollinfinite){t.bind("click",v);n.bind("click",v);f.slideshowcounters?p():u.remove()}else{p();if(f.scrolltype=="fade"){t.bind("click",m).addClass("disabled");n.bind("click",m)}else{t.bind("click",d).addClass("disabled");n.bind("click",d)}}if(f.slideshow){E();i.bind("click",g);i.click()}else i.remove();s.length<=f.scrollitems&&o.addClass("disabled");a.addClass("active")}function p(){var t=e(macmillan.CONSTANTS.HTML_SNIPPETS).find("#scrollpanels .counters").html();if(s.length<=1||u.length==0)u.remove();else{var n=0;for(var r=0;r<=s.length-f.scrollitems;r+=f.scrollitems){u.children().get(n)==undefined&&u.append(e(t.format(n)));n++}if(f.bindhover)if(f.scrolltype=="fade"){u.find("a").bind("click",m);u.find("a").bind("mouseenter",m)}else{u.find("a").bind("click",d);u.find("a").bind("mouseenter",d)}else f.scrolltype=="fade"?u.find("a").bind("click",m):u.find("a").bind("click",d);var i=u.find(".active");i.length!=0&&i.click()}}function d(n){if(o.hasClass("disabled")){n.preventDefault();return}if(!t){t=!0;var r=e(this),c,h,p,d={};if(f.scrollmove=="auto"){r.hasClass("prev")?c=a.prev().outerWidth(!0):c=a.outerWidth(!0);c=c}else c=f.scrollmove;if(r.hasClass("prev")){h=a.prevAll().slice(f.scrollitems-1,f.scrollitems);d.left="+="+c*f.scrollitems}else if(r.hasClass("next")){h=a.nextAll().slice(f.scrollitems-1,f.scrollitems);d.left="-="+c*f.scrollitems}else{var v=r.index()*f.scrollitems;h=s.eq(v);p=Math.abs(a.index()-v);c=(a.index()-v<=0?"-=":"+=")+(p*c).toString();d.left=c}if(h.length==0)t=!1;else{a.removeClass("active");a=h;a.addClass("active");i.animate(d,l.speed,l.easing,function(){t=!1;u.find("a").removeClass("active");u.find("a:eq("+a.index()/f.scrollitems+")").addClass("active");o.find(".prev").removeClass("disabled");o.find(".next").removeClass("disabled");o.find(".prev").addClass(a.prev().length==0||a.prevAll().length<f.scrollitems?"disabled":"");o.find(".next").addClass(a.next().length==0||a.nextAll().length<f.scrollitems?"disabled":"")})}}n.preventDefault()}function v(n){if(o.hasClass("disabled")){n.preventDefault();return}if(!t){t=!0;var r=e(this),s;f.scrollmove=="auto"?s=a.outerWidth(!0):s=f.scrollmove;l.next={},l.prev={};l.prev.left="-="+s;l.next.left="+="+s;if(r.hasClass("prev")){i.find(".panel:last").prependTo(i);a.removeClass("active");a=i.find(".panel:first");a.addClass("active");i.animate(l.prev,0).animate(l.next,l.speed,l.easing,function(){t=!1})}else i.animate(l.prev,l.speed,l.easing,function(){a.appendTo(i);a.removeClass("active");a=i.find(".panel:first");a.addClass("active");i.animate(l.next,0,function(){t=!1})})}n.preventDefault()}function m(n){if(o.hasClass("disabled")){n.preventDefault();return}if(!t){t=!0;var r=e(this),i;if(r.hasClass("prev"))i=a.prev();else if(r.hasClass("next"))i=a.next();else{var f=r.index();i=s.eq(f)}if(i.length==0||a.index()==i.index())t=!1;else{i.animate({opacity:1},0);u.find("a").removeClass("active");u.find("a:eq("+i.index()+")").addClass("active");a.animate({opacity:0},l.speed,l.easing,function(){a.removeClass("active");a=i;a.addClass("active");t=!1;o.find(".prev").removeClass("disabled");o.find(".next").removeClass("disabled");o.find(".prev").addClass(a.prev().length==0?"disabled":"");o.find(".next").addClass(a.next().length==0?"disabled":"");a.trigger("change")})}}n.preventDefault()}function g(t){t.preventDefault();$playpause=e(this);$playpause.find("i").removeClass("icon-pause icon-play");n?w():y()}function y(){var e=o.find(".playpause");e.find("i").addClass("icon-pause");n=!0;clearInterval(c.scroll);c.scroll=setInterval(S,c.timer)}function b(){var e=o.find(".playpause");e.find("i").addClass("icon-play");n=!1;clearInterval(c.scroll)}function w(){b();scroll=0}function E(){c.progress=0}function S(){if(c.progress<100)c.progress++;else if(c.progress==100){E();var e=o.find(".next");e.hasClass("disabled")&&u.first().find("a").click();e.click()}}var t=!1,n=!1,r=e(this),i=r.find(".wrapper"),s=i.find(".panel"),o=r.find(".controls"),u=r.find(".counters"),a=s.first(),f={scrollmove:"auto",scrollinfinite:!1,scrollitems:"1",scrolltype:"scroll",slideshow:!1,slideshowcounters:!1},l={speed:200,easing:"linear"},c={progress:0,timer:30};h()})}})(jQuery);;/**
 * Gallery jQuery Plugin
 *
 * @author		Zone
 * @email			info@zonecontent.com
 * @url				http://www.zonecontent.com/
 * @copyright	Copyright (c) 2012, zonecontent.com. All rights reserved.
 * @version		0.0.1
 */

var shari_arison;
var gallery;

(function ($) {
	gallery = {
	
		/* CONSTANTS
		----------------------------------------------------------------------------- */
	
		CONSTANTS: {
			MAXSETS: 5,
			ANIMATE_TIME: 500
		},
	
		/* FUNCTIONS
				- init(selector)
					- format_gallery(container, reset)
						- unformat(container)
						- get_group_length(container, item_width)
						- set_dimensions(container, item_width)
					- init_controls(container, reset)
						- remove_controls(container)
						- page(event)
							- update_state(active)
						- scroll(event)
		----------------------------------------------------------------------------- */
		
		init: function(selector) {
			$(selector).each(function() {
				var container = $(this);
				container.addClass('gallery-container-js');
				
				/* Init markup */
				$('.gallery-wrapper', container).after($('.gallery-controls', shari_arison.CONSTANTS.HTML_SNIPPETS));
				$('.gallery-wrapper > ul', container).wrap('<div class="gallery-window"></div>');
				
				/* Calls to init format & controls */
				$(window).load(function() {
					gallery.format(container);
					gallery.init_controls(container);
				});
				
				/* Bind Smart Resize (Modern Browsers only at the moment [! LT IE 9]) */
				if (!($.browser.msie && parseInt($.browser.version, 10) < 9)) {
					$(window).bind('smartresize.arison-gallery', function() {
						gallery.format(container, 'reset');
						gallery.init_controls(container, 'reset');
					});
				}
			});
		},
		
		/* Format gallery contents */
		format: function(container, reset) {
			/* Reset if previously formatted */
			if (reset === 'reset') {
				gallery.unformat(container);
			}
			
			/* Set variables */
			var item_width = $('.gallery-window > ul > li:first-child', container).width();
			var set_length = gallery.get_set_length(container, item_width);
			var set = {};
			var list = $('<ul />');
			
			/* Create list */
			while ((set = $('ul li:lt(' + set_length + ')', container).remove()).length) {
				list.append('<li />');
				$('<ul />').append(set).appendTo($(list).children('li:last-child'));
			}
			
			/* Replace list */
			$('.gallery-window > ul', container).replaceWith(list);
			
			/* Set gallery dimensions */
			gallery.set_dimensions(container, item_width);
		},
		
		/* Unformat gallery contents */
		unformat: function(container) {
			var list = $('.gallery-window > ul > li > ul > li', container);
			$('.gallery-window > ul > li', container).remove().append(list);
			$('.gallery-window > ul', container).append(list);
		},
		
		/* Return set length */
		get_set_length: function(container, item_width) {
			var container_width = container.width();
			var row_count = 1;
			var row_length = Math.floor(container_width / item_width);
			var total_length = $('ul li', container).length;
			var set_count = Math.ceil(total_length / (row_length * row_count));
			
			if (set_count > gallery.CONSTANTS.MAXSETS) {
				while (set_count > gallery.CONSTANTS.MAXSETS) {
					row_count += 1;
					set_count = Math.ceil(total_length / (row_length * row_count));
				}
			}
			
			return row_length * row_count;
		},
		
		/* Set dimensions */
		set_dimensions: function(container, item_width) {
			var container_width = container.width();
			$('.gallery-window', container).width(container_width);
			$('.gallery-window > ul > li', container).width(container_width);

			var horizontal_length = Math.floor(container_width / item_width);
			var margin = (container_width - (horizontal_length * item_width)) / (horizontal_length - 1);
			
			var margin_side = 'margin-right';
			if (!shari_arison.CONSTANTS.SITE_DIRECTION_LTR) {
				margin_side = 'margin-left';
			}
			
			$('.gallery-window > ul > li > ul > li', container).css(margin_side, margin + 'px');
			$('.gallery-window > ul > li', container).width(container_width + margin);
		},
		
		/* Init controls */
		init_controls: function(container, reset) {
			/* Remove controls if reset */
			if (reset === 'reset') {
				gallery.remove_controls(container);
			}
			
			/* Create controls */
			$('.gallery-window > ul > li', container).each(function() {
				var index = $(this).index();
				$('.gallery-controls .next', container).before('<a href="" class="page">' + (index + 1) + '</a>');
			});
			
			/* Bind controls */
			$('.gallery-controls a.page:first', container).addClass('active');
			$('.gallery-controls a.page', container).bind('click', gallery.page);
			
			if (!reset) {
				$('.gallery-controls a.previous, .gallery-controls a.next', container).bind('click', gallery.scroll);
			}
			
			/* Update control active state */
			gallery.update_state($('.gallery-controls a.page:first', container));
		},
		
		/* Remove controls */
		remove_controls: function(container) {
			$('.gallery-controls .page', container).remove();
		},
		
		/* Paging elements */
		page: function(event) {
			event.preventDefault();
			
			/* Init variables */
			var $this = $(this);
			var container = $this.parents('.gallery-container');
			if (!$this.hasClass('active')) {
				if (!container.hasClass('animating')) {
					container.addClass('animating');
					
					/* Get indexes */
					var current_index = $('.page', $this.parent()).index($this.siblings('a.active'));
					var index = $('.page', $this.parent()).index($this);
					gallery.update_state($this);
					
					/* Init variables */
					var width = container.width();
					var animation = {};
					var margin = 0;
					var amount = 0;
					
					/* Create animation options LTR & RTL */
					if (shari_arison.CONSTANTS.SITE_DIRECTION_LTR) {
						margin = parseInt($('.gallery-window > ul > li > ul > li:first-child', container).css('margin-right').replace('px', ''), 10);
						amount = (width + margin) * (index - current_index);
						animation.left = '-=' + amount;
					} else {
						margin = parseInt($('.gallery-window > ul > li > ul > li:first-child', container).css('margin-left').replace('px', ''), 10);
						amount = (width + margin) * (index - current_index);
						animation.right = '-=' + amount;
					}
					
					/* Animate gallery */
					$('.gallery-window > ul', container).animate(animation, gallery.CONSTANTS.TIME, 'swing', function() {
						container.removeClass('animating');
					});
				}
			}
		},
		
		/* Update active index & disabled states */
		update_state: function(active) {
			var index = $('.page', active.parent()).index(active);
			var length = $('a.page', active.parent()).length;
			var previous = active.siblings('a.previous').removeClass('previous-disabled');
			var next = active.siblings('a.next').removeClass('next-disabled');
			
			active.siblings().removeClass('active');
			active.addClass('active');
			
			if ((index + 1) === 1) {
				previous.addClass('previous-disabled');
			}
			if ((index + 1) === length) {
				next.addClass('next-disabled');
			}
		},
		
		/* Scrolling elements */
		scroll: function(event) {
			event.preventDefault();
			var $this = $(this);
			var length = $this.siblings('a.page').length;
			var index = $this.siblings('a.page').index($this.siblings('a.active'));
			
			if ($this.hasClass('previous') && !$this.hasClass('previous-disabled')) {
				$('a.page:eq(' + (index - 1) + ')', $this.parent()).click();
			}
			if ($this.hasClass('next') && !$this.hasClass('next-disabled')) {
				$('a.page:eq(' + (index + 1) + ')', $this.parent()).click();
			}
		}
		
	};

	$(function() { gallery.init('.gallery-container'); });
})(jQuery);;/*!
jQuery Waypoints - v1.1.7
Copyright (c) 2011-2012 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/jquery-waypoints/blob/master/MIT-license.txt
https://github.com/imakewebthings/jquery-waypoints/blob/master/GPL-license.txt
*/

/*
Waypoints is a small jQuery plugin that makes it easy to execute a function
whenever you scroll to an element.

GitHub Repository: https://github.com/imakewebthings/jquery-waypoints
Documentation and Examples: http://imakewebthings.github.com/jquery-waypoints

Changelog:
	v1.1.7
		- Actually fix the post-load bug in Issue #28 from v1.1.3.
	v1.1.6
		- Fix potential memory leak by unbinding events on empty context elements.
	v1.1.5
		- Make plugin compatible with Browserify/RequireJS. (Thanks @cjroebuck)
	v1.1.4
		- Add handler option to give alternate binding method. (Issue #34)
	v1.1.3
		- Fix cases where waypoints are added post-load and should be triggered
		  immediately. (Issue #28)
	v1.1.2
		- Fixed error thrown by waypoints with triggerOnce option that were
		  triggered via resize refresh.
	v1.1.1
		- Fixed bug in initialization where all offsets were being calculated
		  as if set to 0 initially, causing unwarranted triggers during the
		  subsequent refresh.
		- Added onlyOnScroll, an option for individual waypoints that disables
		  triggers due to an offset refresh that crosses the current scroll
		  point. (All credit to @knuton on this one.)
	v1.1
		- Moved the continuous option out of global settings and into the options
		  object for individual waypoints.
		- Added the context option, which allows for using waypoints within any
		  scrollable element, not just the window.
	v1.0.2
		- Moved scroll and resize handler bindings out of load.  Should play nicer
		  with async loaders like Head JS and LABjs.
		- Fixed a 1px off error when using certain % offsets.
		- Added unit tests.
	v1.0.1
		- Added $.waypoints('viewportHeight').
		- Fixed iOS bug (using the new viewportHeight method).
		- Added offset function alias: 'bottom-in-view'.
	v1.0
		- Initial release.
	
Support:
	- jQuery versions 1.4.3+
	- IE6+, FF3+, Chrome 6+, Safari 4+, Opera 11
	- Other versions and browsers may work, these are just the ones I've looked at.
*/

(function($, wp, wps, window, undefined){
	'$:nomunge';
	
	var $w = $(window),
	
	// Keeping common strings as variables = better minification
	eventName = 'waypoint.reached',
	
	/*
	For the waypoint and direction passed in, trigger the waypoint.reached
	event and deal with the triggerOnce option.
	*/
	triggerWaypoint = function(way, dir) {
		way.element.trigger(eventName, dir);
		if (way.options.triggerOnce) {
			way.element[wp]('destroy');
		}
	},
	
	/*
	Given a jQuery element and Context, returns the index of that element in the waypoints
	array.  Returns the index, or -1 if the element is not a waypoint.
	*/
	waypointIndex = function(el, context) {
		if (!context) return -1;
		var i = context.waypoints.length - 1;
		while (i >= 0 && context.waypoints[i].element[0] !== el[0]) {
			i -= 1;
		}
		return i;
	},
	
	// Private list of all elements used as scrolling contexts for waypoints.
	contexts = [],
	
	/*
	Context Class - represents a scrolling context.  Properties include:
		element: jQuery object containing a single HTML element.
		waypoints: Array of waypoints operating under this scroll context.
		oldScroll: Keeps the previous scroll position to determine scroll direction.
		didScroll: Flag used in scrolling the context's scroll event.
		didResize: Flag used in scrolling the context's resize event.
		doScroll: Function that checks for crossed waypoints. Called from throttler.
	*/
	Context = function(context) {
		$.extend(this, {
			element: $(context),
			oldScroll: 0,
			
			/*
			List of all elements that have been registered as waypoints.
			Each object in the array contains:
				element: jQuery object containing a single HTML element.
				offset: The window scroll offset, in px, that triggers the waypoint event.
				options: Options object that was passed to the waypoint fn function.
			*/
			'waypoints': [],
			
			didScroll: false,
			didResize: false,
	
			doScroll: $.proxy(function() {
				var newScroll = this.element.scrollTop(),
				
				// Are we scrolling up or down? Used for direction argument in callback.
				isDown = newScroll > this.oldScroll,
				that = this,

				// Get a list of all waypoints that were crossed since last scroll move.
				pointsHit = $.grep(this.waypoints, function(el, i) {
					return isDown ?
						(el.offset > that.oldScroll && el.offset <= newScroll) :
						(el.offset <= that.oldScroll && el.offset > newScroll);
				}),
				len = pointsHit.length;
				
				// iOS adjustment
				if (!this.oldScroll || !newScroll) {
					$[wps]('refresh');
				}

				// Done with scroll comparisons, store new scroll before ejection
				this.oldScroll = newScroll;

				// No waypoints crossed? Eject.
				if (!len) return;

				// If several waypoints triggered, need to do so in reverse order going up
				if (!isDown) pointsHit.reverse();

				/*
				One scroll move may cross several waypoints.  If the waypoint's continuous
				option is true it should fire even if it isn't the last waypoint.  If false,
				it will only fire if it's the last one.
				*/
				$.each(pointsHit, function(i, point) {
					if (point.options.continuous || i === len - 1) {
						triggerWaypoint(point, [isDown ? 'down' : 'up']);
					}
				});
			}, this)
		});
		
		// Setup scroll and resize handlers.  Throttled at the settings-defined rate limits.
		$(context).bind('scroll.waypoints', $.proxy(function() {
			if (!this.didScroll) {
				this.didScroll = true;
				window.setTimeout($.proxy(function() {
					this.doScroll();
					this.didScroll = false;
				}, this), $[wps].settings.scrollThrottle);
			}
		}, this)).bind('resize.waypoints', $.proxy(function() {
			if (!this.didResize) {
				this.didResize = true;
				window.setTimeout($.proxy(function() {
					$[wps]('refresh');
					this.didResize = false;
				}, this), $[wps].settings.resizeThrottle);
			}
		}, this));
		
		$w.load($.proxy(function() {
			/*
			Fire a scroll check, should the page be loaded at a non-zero scroll value,
			as with a fragment id link or a page refresh.
			*/
			this.doScroll();
		}, this));
	},
	
	/* Returns a Context object from the contexts array, given the raw HTML element
	for that context. */
	getContextByElement = function(element) {
		var found = null;
		
		$.each(contexts, function(i, c) {
			if (c.element[0] === element) {
				found = c;
				return false;
			}
		});
		
		return found;
	},
	
	// Methods exposed to the effin' object 
	methods = {
		/*
		jQuery.fn.waypoint([handler], [options])
		
		handler
			function, optional
			A callback function called when the user scrolls past the element.
			The function signature is function(event, direction) where event is
			a standard jQuery Event Object and direction is a string, either 'down'
			or 'up' indicating which direction the user is scrolling.
			
		options
			object, optional
			A map of options to apply to this set of waypoints, including where on
			the browser window the waypoint is triggered. For a full list of
			options and their defaults, see $.fn.waypoint.defaults.
			
		This is how you register an element as a waypoint. When the user scrolls past
		that element it triggers waypoint.reached, a custom event. Since the
		parameters for creating a waypoint are optional, we have a few different
		possible signatures. Let’s look at each of them.

		someElements.waypoint();
			
		Calling .waypoint with no parameters will register the elements as waypoints
		using the default options. The elements will fire the waypoint.reached event,
		but calling it in this way does not bind any handler to the event. You can
		bind to the event yourself, as with any other event, like so:

		someElements.bind('waypoint.reached', function(event, direction) {
		   // make it rain
		});
			
		You will usually want to create a waypoint and immediately bind a function to
		waypoint.reached, and can do so by passing a handler as the first argument to
		.waypoint:

		someElements.waypoint(function(event, direction) {
		   if (direction === 'down') {
		      // do this on the way down
		   }
		   else {
		      // do this on the way back up through the waypoint
		   }
		});
			
		This will still use the default options, which will trigger the waypoint when
		the top of the element hits the top of the window. We can pass .waypoint an
		options object to customize things:

		someElements.waypoint(function(event, direction) {
		   // do something amazing
		}, {
		   offset: '50%'  // middle of the page
		});
			
		You can also pass just an options object.

		someElements.waypoint({
		   offset: 100  // 100px from the top
		});
			
		This behaves like .waypoint(), in that it registers the elements as waypoints
		but binds no event handlers.

		Calling .waypoint on an existing waypoint will extend the previous options.
		If the call includes a handler, it will be bound to waypoint.reached without
		unbinding any other handlers.
		*/
		init: function(f, options) {
			// Register each element as a waypoint, add to array.
			this.each(function() {
				var cElement = $.fn[wp].defaults.context,
				context,
				$this = $(this);

				// Default window context or a specific element?
				if (options && options.context) {
					cElement = options.context;
				}

				// Find the closest element that matches the context
				if (!$.isWindow(cElement)) {
					cElement = $this.closest(cElement)[0];
				}
				context = getContextByElement(cElement);

				// Not a context yet? Create and push.
				if (!context) {
					context = new Context(cElement);
					contexts.push(context);
				}
				
				// Extend default and preexisting options
				var ndx = waypointIndex($this, context),
				base = ndx < 0 ? $.fn[wp].defaults : context.waypoints[ndx].options,
				opts = $.extend({}, base, options);
				
				// Offset aliases
				opts.offset = opts.offset === "bottom-in-view" ?
					function() {
						var cHeight = $.isWindow(cElement) ? $[wps]('viewportHeight')
							: $(cElement).height();
						return cHeight - $(this).outerHeight();
					} : opts.offset;

				// Update, or create new waypoint
				if (ndx < 0) {
					context.waypoints.push({
						'element': $this,
						'offset': null,
						'options': opts
					});
				}
				else {
					context.waypoints[ndx].options = opts;
				}
				
				// Bind the function if it was passed in.
				if (f) {
					$this.bind(eventName, f);
				}
				// Bind the function in the handler option if it exists.
				if (options && options.handler) {
					$this.bind(eventName, options.handler);
				}
			});
			
			// Need to re-sort+refresh the waypoints array after new elements are added.
			$[wps]('refresh');
			
			return this;
		},
		
		
		/*
		jQuery.fn.waypoint('remove')
		
		Passing the string 'remove' to .waypoint unregisters the elements as waypoints
		and wipes any custom options, but leaves the waypoint.reached events bound.
		Calling .waypoint again in the future would reregister the waypoint and the old
		handlers would continue to work.
		*/
		remove: function() {
			return this.each(function(i, el) {
				var $el = $(el);
				
				$.each(contexts, function(i, c) {
					var ndx = waypointIndex($el, c);

					if (ndx >= 0) {
						c.waypoints.splice(ndx, 1);

						if (!c.waypoints.length) {
							c.element.unbind('scroll.waypoints resize.waypoints');
							contexts.splice(i, 1);
						}
					}
				});
			});
		},
		
		/*
		jQuery.fn.waypoint('destroy')
		
		Passing the string 'destroy' to .waypoint will unbind all waypoint.reached
		event handlers on those elements and unregisters them as waypoints.
		*/
		destroy: function() {
			return this.unbind(eventName)[wp]('remove');
		}
	},
	
	/*
	Methods used by the jQuery object extension.
	*/
	jQMethods = {
		
		/*
		jQuery.waypoints('refresh')
		
		This will force a recalculation of each waypoint’s trigger point based on
		its offset option and context. This is called automatically whenever the window
		(or other defined context) is resized, new waypoints are added, or a waypoint’s
		options are modified. If your project is changing the DOM or page layout without
		doing one of these things, you may want to manually call this refresh.
		*/
		refresh: function() {
			$.each(contexts, function(i, c) {
				var isWin = $.isWindow(c.element[0]),
				contextOffset = isWin ? 0 : c.element.offset().top,
				contextHeight = isWin ? $[wps]('viewportHeight') : c.element.height(),
				contextScroll = isWin ? 0 : c.element.scrollTop();
				
				$.each(c.waypoints, function(j, o) {
					/* $.each isn't safe from element removal due to triggerOnce.
					Should rewrite the loop but this is way easier. */
					if (!o) return;

					// Adjustment is just the offset if it's a px value
					var adjustment = o.options.offset,
					oldOffset = o.offset;
					
					// Set adjustment to the return value if offset is a function.
					if (typeof o.options.offset === "function") {
						adjustment = o.options.offset.apply(o.element);
					}
					// Calculate the adjustment if offset is a percentage.
					else if (typeof o.options.offset === "string") {
						var amount = parseFloat(o.options.offset);
						adjustment = o.options.offset.indexOf("%") ?
							Math.ceil(contextHeight * (amount / 100)) : amount;
					}

					/* 
					Set the element offset to the window scroll offset, less
					all our adjustments.
					*/
					o.offset = o.element.offset().top - contextOffset
						+ contextScroll - adjustment;

					/*
					An element offset change across the current scroll point triggers
					the event, just as if we scrolled past it unless prevented by an
					optional flag.
					*/
					if (o.options.onlyOnScroll) return;

					if (oldOffset !== null && c.oldScroll > oldOffset && c.oldScroll <= o.offset) {
						triggerWaypoint(o, ['up']);
					}
					else if (oldOffset !== null && c.oldScroll < oldOffset && c.oldScroll >= o.offset) {
						triggerWaypoint(o, ['down']);
					}
					/* For new waypoints added after load, check that down should have
					already been triggered */
					else if (!oldOffset && c.element.scrollTop() > o.offset) {
						triggerWaypoint(o, ['down']);
					}
				});
				
				// Keep waypoints sorted by offset value.
				c.waypoints.sort(function(a, b) {
					return a.offset - b.offset;
				});
			});
		},
		
		
		/*
		jQuery.waypoints('viewportHeight')
		
		This will return the height of the viewport, adjusting for inconsistencies
		that come with calling $(window).height() in iOS. Recommended for use
		within any offset functions.
		*/
		viewportHeight: function() {
			return (window.innerHeight ? window.innerHeight : $w.height());
		},
		
		
		/*
		jQuery.waypoints()
		
		This will return a jQuery object with a collection of all registered waypoint
		elements.

		$('.post').waypoint();
		$('.ad-unit').waypoint(function(event, direction) {
		   // Passed an ad unit
		});
		console.log($.waypoints());
		
		The example above would log a jQuery object containing all .post and .ad-unit
		elements.
		*/
		aggregate: function() {
			var points = $();
			$.each(contexts, function(i, c) {
				$.each(c.waypoints, function(i, e) {
					points = points.add(e.element);
				});
			});
			return points;
		}
	};

	
	/*
	fn extension.  Delegates to appropriate method.
	*/
	$.fn[wp] = function(method) {
		
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		}
		else if (typeof method === "function" || !method) {
			return methods.init.apply(this, arguments);
		}
		else if (typeof method === "object") {
			return methods.init.apply(this, [null, method]);
		}
		else {
			$.error( 'Method ' + method + ' does not exist on jQuery ' + wp );
		}
	};
	
	
	/*
	The default options object that is extended when calling .waypoint. It has the
	following properties:
	
	context
		string | element | jQuery*
		default: window
		The context defines which scrollable element the waypoint belongs to and acts
		within. The default, window, means the waypoint offset is calculated with relation
		to the whole viewport.  You can set this to another element to use the waypoints
		within that element.  Accepts a selector string, *but if you use jQuery 1.6+ it
		also accepts a raw HTML element or jQuery object.
	
	continuous
		boolean
		default: true
		If true, and multiple waypoints are triggered in one scroll, this waypoint will
		trigger even if it is not the last waypoint reached.  If false, it will only
		trigger if it is the last waypoint.
		
	handler
		function
		default: undefined
		An alternative way to bind functions to the waypoint, without using the function
		as the first argument to the waypoint function.

	offset
		number | string | function
		default: 0
		Determines how far the top of the element must be from the top of the browser
		window to trigger a waypoint. It can be a number, which is taken as a number
		of pixels, a string representing a percentage of the viewport height, or a
		function that will return a number of pixels.
		
	onlyOnScroll
		boolean
		default: false
		If true, this waypoint will not trigger if an offset change during a refresh
		causes it to pass the current scroll point.
		
	triggerOnce
		boolean
		default: false
		If true, the waypoint will be destroyed when triggered.
	
	An offset of 250 would trigger the waypoint when the top of the element is 250px
	from the top of the viewport. Negative values for any offset work as you might
	expect. A value of -100 would trigger the waypoint when the element is 100px above
	the top of the window.

	offset: '100%'
	
	A string percentage will determine the pixel offset based on the height of the
	window. When resizing the window, this offset will automatically be recalculated
	without needing to call $.waypoints('refresh').

	// The bottom of the element is in view
	offset: function() {
	   return $.waypoints('viewportHeight') - $(this).outerHeight();
	}
	
	Offset can take a function, which must return a number of pixels from the top of
	the window. The this value will always refer to the raw HTML element of the
	waypoint. As with % values, functions are recalculated automatically when the
	window resizes. For more on recalculating offsets, see $.waypoints('refresh').
	
	An offset value of 'bottom-in-view' will act as an alias for the function in the
	example above, as this is a common usage.
	
	offset: 'bottom-in-view'
	
	You can see this alias in use on the Scroll Analytics example page.

	The triggerOnce flag, if true, will destroy the waypoint after the first trigger.
	This is just a shortcut for calling .waypoint('destroy') within the waypoint
	handler. This is useful in situations such as scroll analytics, where you only
	want to record an event once for each page visit.
	
	The context option lets you use Waypoints within an element other than the window.
	You can define the context with a selector string and the waypoint will act within
	the nearest ancestor that matches this selector.
	
	$('.something-scrollable .waypoint').waypoint({
	   context: '.something-scrollable'
	});
	
	You can see this in action on the Dial Controls example.
	
	The handler option gives authors an alternative way to bind functions when
	creating a waypoint.  In place of:
	
	$('.item').waypoint(function(event, direction) {
	   // make things happen
	});
	
	You may instead write:
	
	$('.item').waypoint({
	   handler: function(event, direction) {
	      // make things happen
	   }
	});
	
	*/
	$.fn[wp].defaults = {
		continuous: true,
		offset: 0,
		triggerOnce: false,
		context: window
	};
	
	
	
	
	
	/*
	jQuery object extension. Delegates to appropriate methods above.
	*/
	$[wps] = function(method) {
		if (jQMethods[method]) {
			return jQMethods[method].apply(this);
		}
		else {
			return jQMethods['aggregate']();
		}
	};
	
	
	/*
	$.waypoints.settings
	
	Settings object that determines some of the plugin’s behavior.
		
	resizeThrottle
		number
		default: 200
		For performance reasons, the refresh performed during resizes is
		throttled. This value is the rate-limit in milliseconds between resize
		refreshes. For more information on throttling, check out Ben Alman’s
		throttle / debounce plugin.
		http://benalman.com/projects/jquery-throttle-debounce-plugin/
		
	scrollThrottle
		number
		default: 100
		For performance reasons, checking for any crossed waypoints during a
		scroll event is throttled. This value is the rate-limit in milliseconds
		between scroll checks. For more information on throttling, check out Ben
		Alman’s throttle / debounce plugin.
		http://benalman.com/projects/jquery-throttle-debounce-plugin/
	*/
	$[wps].settings = {
		resizeThrottle: 200,
		scrollThrottle: 100
	};
	
	$w.load(function() {
		// Calculate everything once on load.
		$[wps]('refresh');
	});
})(jQuery, 'waypoint', 'waypoints', window);
;