/* Minification failed. Returning unminified contents.
(4253,8891-8892): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: i
(4253,8914-8915): run-time error JS1294: Strict-mode does not allow ++ or -- on certain objects: i
 */
/// <reference path="jquery-1.5.1.js" />

/*!
** Unobtrusive Ajax support library for jQuery
** Copyright (C) Microsoft Corporation. All rights reserved.
*/

/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global window: false, jQuery: false */

(function ($) {
    var data_click = "unobtrusiveAjaxClick",
        data_validation = "unobtrusiveValidation";

    function getFunction(code, argNames) {
        var fn = window, parts = (code || "").split(".");
        while (fn && parts.length) {
            fn = fn[parts.shift()];
        }
        if (typeof (fn) === "function") {
            return fn;
        }
        argNames.push(code);
        return Function.constructor.apply(null, argNames);
    }

    function isMethodProxySafe(method) {
        return method === "GET" || method === "POST";
    }

    function asyncOnBeforeSend(xhr, method) {
        if (!isMethodProxySafe(method)) {
            xhr.setRequestHeader("X-HTTP-Method-Override", method);
        }
    }

    function asyncOnSuccess(element, data, contentType) {
        var mode;

        if (contentType.indexOf("application/x-javascript") !== -1) {  // jQuery already executes JavaScript for us
            return;
        }

        mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase();
        $(element.getAttribute("data-ajax-update")).each(function (i, update) {
            var top;

            switch (mode) {
            case "BEFORE":
                top = update.firstChild;
                $("<div />").html(data).contents().each(function () {
                    update.insertBefore(this, top);
                });
                break;
            case "AFTER":
                $("<div />").html(data).contents().each(function () {
                    update.appendChild(this);
                });
                break;
            default:
                $(update).html(data);
                break;
            }
        });
    }

    function asyncRequest(element, options) {
        var confirm, loading, method, duration;

        confirm = element.getAttribute("data-ajax-confirm");
        if (confirm && !window.confirm(confirm)) {
            return;
        }

        loading = $(element.getAttribute("data-ajax-loading"));
        duration = element.getAttribute("data-ajax-loading-duration") || 0;

        $.extend(options, {
            type: element.getAttribute("data-ajax-method") || undefined,
            url: element.getAttribute("data-ajax-url") || undefined,
            beforeSend: function (xhr) {
                var result;
                asyncOnBeforeSend(xhr, method);
                result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments);
                if (result !== false) {
                    loading.show(duration);
                }
                return result;
            },
            complete: function () {
                loading.hide(duration);
                getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(this, arguments);
            },
            success: function (data, status, xhr) {
                asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
                getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(this, arguments);
            },
            error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"])
        });

        options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });

        method = options.type.toUpperCase();
        if (!isMethodProxySafe(method)) {
            options.type = "POST";
            options.data.push({ name: "X-HTTP-Method-Override", value: method });
        }

        $.ajax(options);
    }

    function validate(form) {
        var validationInfo = $(form).data(data_validation);
        return !validationInfo || !validationInfo.validate || validationInfo.validate();
    }

    $(document).on("click", "a[data-ajax=true]", function (evt) {
        evt.preventDefault();
        asyncRequest(this, {
            url: this.href,
            type: "GET",
            data: []
        });
    });

    $(document).on("click", "form[data-ajax=true] input[type=image]", function (evt) {
        var name = evt.target.name,
            $target = $(evt.target),
            form = $target.parents("form")[0],
            offset = $target.offset();

        $(form).data(data_click, [
            { name: name + ".x", value: Math.round(evt.pageX - offset.left) },
            { name: name + ".y", value: Math.round(evt.pageY - offset.top) }
        ]);

        setTimeout(function () {
            $(form).removeData(data_click);
        }, 0);
    });

    $(document).on("click", "form[data-ajax=true] :submit", function (evt) {
        var name = evt.target.name,
            form = $(evt.target).parents("form")[0];

        $(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);

        setTimeout(function () {
            $(form).removeData(data_click);
        }, 0);
    });

    $(document).on("submit", "form[data-ajax=true]", function (evt) {
        var clickInfo = $(this).data(data_click) || [];
        evt.preventDefault();
        if (!validate(this)) {
            return;
        }
        asyncRequest(this, {
            url: this.action,
            type: this.method || "GET",
            data: clickInfo.concat($(this).serializeArray())
        });
    });
}(jQuery));;
/**
 * jQuery Validation Plugin 1.9.0
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2011 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($) {

$.extend($.fn, {
	// http://docs.jquery.com/Plugins/Validation/validate
	validate: function( options ) {

		// if nothing is selected, return nothing; can't chain anyway
		if (!this.length) {
			options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" );
			return;
		}

		// check if a validator for this form was already created
		var validator = $.data(this[0], 'validator');
		if ( validator ) {
			return validator;
		}

		// Add novalidate tag if HTML5.
		this.attr('novalidate', 'novalidate');

		validator = new $.validator( options, this[0] );
		$.data(this[0], 'validator', validator);

		if ( validator.settings.onsubmit ) {

			var inputsAndButtons = this.find("input, button");

			// allow suppresing validation by adding a cancel class to the submit button
			inputsAndButtons.filter(".cancel").click(function () {
				validator.cancelSubmit = true;
			});

			// when a submitHandler is used, capture the submitting button
			if (validator.settings.submitHandler) {
				inputsAndButtons.filter(":submit").click(function () {
					validator.submitButton = this;
				});
			}

			// validate the form on submit
			this.submit( function( event ) {
				if ( validator.settings.debug )
					// prevent form submit to be able to see console output
					event.preventDefault();

				function handle() {
					if ( validator.settings.submitHandler ) {
						if (validator.submitButton) {
							// insert a hidden input as a replacement for the missing submit button
							var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
						}
						validator.settings.submitHandler.call( validator, validator.currentForm );
						if (validator.submitButton) {
							// and clean up afterwards; thanks to no-block-scope, hidden can be referenced
							hidden.remove();
						}
						return false;
					}
					return true;
				}

				// prevent submit for invalid forms or custom submit handlers
				if ( validator.cancelSubmit ) {
					validator.cancelSubmit = false;
					return handle();
				}
				if ( validator.form() ) {
					if ( validator.pendingRequest ) {
						validator.formSubmitted = true;
						return false;
					}
					return handle();
				} else {
					validator.focusInvalid();
					return false;
				}
			});
		}

		return validator;
	},
	// http://docs.jquery.com/Plugins/Validation/valid
	valid: function() {
        if ( $(this[0]).is('form')) {
            return this.validate().form();
        } else {
            var valid = true;
            var validator = $(this[0].form).validate();
            this.each(function() {
				valid &= validator.element(this);
            });
            return valid;
        }
    },
	// attributes: space seperated list of attributes to retrieve and remove
	removeAttrs: function(attributes) {
		var result = {},
			$element = this;
		$.each(attributes.split(/\s/), function(index, value) {
			result[value] = $element.attr(value);
			$element.removeAttr(value);
		});
		return result;
	},
	// http://docs.jquery.com/Plugins/Validation/rules
	rules: function(command, argument) {
		var element = this[0];

		if (command) {
			var settings = $.data(element.form, 'validator').settings;
			var staticRules = settings.rules;
			var existingRules = $.validator.staticRules(element);
			switch(command) {
			case "add":
				$.extend(existingRules, $.validator.normalizeRule(argument));
				staticRules[element.name] = existingRules;
				if (argument.messages)
					settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
				break;
			case "remove":
				if (!argument) {
					delete staticRules[element.name];
					return existingRules;
				}
				var filtered = {};
				$.each(argument.split(/\s/), function(index, method) {
					filtered[method] = existingRules[method];
					delete existingRules[method];
				});
				return filtered;
			}
		}

		var data = $.validator.normalizeRules(
		$.extend(
			{},
			$.validator.metadataRules(element),
			$.validator.classRules(element),
			$.validator.attributeRules(element),
			$.validator.staticRules(element)
		), element);

		// make sure required is at front
		if (data.required) {
			var param = data.required;
			delete data.required;
			data = $.extend({required: param}, data);
		}

		return data;
	}
});

// Custom selectors
$.extend($.expr[":"], {
	// http://docs.jquery.com/Plugins/Validation/blank
	blank: function(a) {return !$.trim("" + a.value);},
	// http://docs.jquery.com/Plugins/Validation/filled
	filled: function(a) {return !!$.trim("" + a.value);},
	// http://docs.jquery.com/Plugins/Validation/unchecked
	unchecked: function(a) {return !a.checked;}
});

// constructor for validator
$.validator = function( options, form ) {
	this.settings = $.extend( true, {}, $.validator.defaults, options );
	this.currentForm = form;
	this.init();
};

$.validator.format = function(source, params) {
	if ( arguments.length == 1 )
		return function() {
			var args = $.makeArray(arguments);
			args.unshift(source);
			return $.validator.format.apply( this, args );
		};
	if ( arguments.length > 2 && params.constructor != Array  ) {
		params = $.makeArray(arguments).slice(1);
	}
	if ( params.constructor != Array ) {
		params = [ params ];
	}
	$.each(params, function(i, n) {
		source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
	});
	return source;
};

$.extend($.validator, {

	defaults: {
		messages: {},
		groups: {},
		rules: {},
		errorClass: "error",
		validClass: "valid",
		errorElement: "label",
		focusInvalid: true,
		errorContainer: $( [] ),
		errorLabelContainer: $( [] ),
		onsubmit: true,
		ignore: ":hidden",
		ignoreTitle: false,
		onfocusin: function(element, event) {
			this.lastActive = element;

			// hide error label and remove error class on focus if enabled
			if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
				this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
				this.addWrapper(this.errorsFor(element)).hide();
			}
		},
		onfocusout: function(element, event) {
			if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
				this.element(element);
			}
		},
		onkeyup: function(element, event) {
			if ( element.name in this.submitted || element == this.lastElement ) {
				this.element(element);
			}
		},
		onclick: function(element, event) {
			// click on selects, radiobuttons and checkboxes
			if ( element.name in this.submitted )
				this.element(element);
			// or option elements, check parent select in that case
			else if (element.parentNode.name in this.submitted)
				this.element(element.parentNode);
		},
		highlight: function(element, errorClass, validClass) {
			if (element.type === 'radio') {
				this.findByName(element.name).addClass(errorClass).removeClass(validClass);
			} else {
				$(element).addClass(errorClass).removeClass(validClass);
			}
		},
		unhighlight: function(element, errorClass, validClass) {
			if (element.type === 'radio') {
				this.findByName(element.name).removeClass(errorClass).addClass(validClass);
			} else {
				$(element).removeClass(errorClass).addClass(validClass);
			}
		}
	},

	// http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
	setDefaults: function(settings) {
		$.extend( $.validator.defaults, settings );
	},

	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.",
		accept: "Please enter a value with a valid extension.",
		maxlength: $.validator.format("Please enter no more than {0} characters."),
		minlength: $.validator.format("Please enter at least {0} characters."),
		rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
		range: $.validator.format("Please enter a value between {0} and {1}."),
		max: $.validator.format("Please enter a value less than or equal to {0}."),
		min: $.validator.format("Please enter a value greater than or equal to {0}.")
	},

	autoCreateRanges: false,

	prototype: {

		init: function() {
			this.labelContainer = $(this.settings.errorLabelContainer);
			this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
			this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
			this.submitted = {};
			this.valueCache = {};
			this.pendingRequest = 0;
			this.pending = {};
			this.invalid = {};
			this.reset();

			var groups = (this.groups = {});
			$.each(this.settings.groups, function(key, value) {
				$.each(value.split(/\s/), function(index, name) {
					groups[name] = key;
				});
			});
			var rules = this.settings.rules;
			$.each(rules, function(key, value) {
				rules[key] = $.validator.normalizeRule(value);
			});

			function delegate(event) {
				var validator = $.data(this[0].form, "validator"),
					eventType = "on" + event.type.replace(/^validate/, "");
				validator.settings[eventType] && validator.settings[eventType].call(validator, this[0], event);
			}
			$(this.currentForm)
			       .validateDelegate("[type='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", delegate)
				.validateDelegate("[type='radio'], [type='checkbox'], select, option", "click", delegate);

			if (this.settings.invalidHandler)
				$(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/form
		form: function() {
			this.checkForm();
			$.extend(this.submitted, this.errorMap);
			this.invalid = $.extend({}, this.errorMap);
			if (!this.valid())
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			this.showErrors();
			return this.valid();
		},

		checkForm: function() {
			this.prepareForm();
			for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
				this.check( elements[i] );
			}
			return this.valid();
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/element
		element: function( element ) {
			element = this.validationTargetFor( this.clean( element ) );
			this.lastElement = element;
			this.prepareElement( element );
			this.currentElements = $(element);
			var result = this.check( element );
			if ( result ) {
				delete this.invalid[element.name];
			} else {
				this.invalid[element.name] = true;
			}
			if ( !this.numberOfInvalids() ) {
				// Hide error containers on last error
				this.toHide = this.toHide.add( this.containers );
			}
			this.showErrors();
			return result;
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/showErrors
		showErrors: function(errors) {
			if(errors) {
				// add items to error list and map
				$.extend( this.errorMap, errors );
				this.errorList = [];
				for ( var name in errors ) {
					this.errorList.push({
						message: errors[name],
						element: this.findByName(name)[0]
					});
				}
				// remove items from success list
				this.successList = $.grep( this.successList, function(element) {
					return !(element.name in errors);
				});
			}
			this.settings.showErrors
				? this.settings.showErrors.call( this, this.errorMap, this.errorList )
				: this.defaultShowErrors();
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/resetForm
		resetForm: function() {
			if ( $.fn.resetForm )
				$( this.currentForm ).resetForm();
			this.submitted = {};
			this.lastElement = null;
			this.prepareForm();
			this.hideErrors();
			this.elements().removeClass( this.settings.errorClass );
		},

		numberOfInvalids: function() {
			return this.objectLength(this.invalid);
		},

		objectLength: function( obj ) {
			var count = 0;
			for ( var i in obj )
				count++;
			return count;
		},

		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 {
					$(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
					.filter(":visible")
					.focus()
					// manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
					.trigger("focusin");
				} catch(e) {
					// ignore IE throwing errors when focusing hidden elements
				}
			}
		},

		findLastActive: function() {
			var lastActive = this.lastActive;
			return lastActive && $.grep(this.errorList, function(n) {
				return n.element.name == lastActive.name;
			}).length == 1 && lastActive;
		},

		elements: function() {
			var validator = this,
				rulesCache = {};

			// select all valid inputs inside the form (no submit or reset buttons)
			return $(this.currentForm)
			.find("input, select, textarea")
			.not(":submit, :reset, :image, [disabled]")
			.not( this.settings.ignore )
			.filter(function() {
				!this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);

				// select only the first element for each name, and only those with rules specified
				if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
					return false;

				rulesCache[this.name] = true;
				return true;
			});
		},

		clean: function( selector ) {
			return $( selector )[0];
		},

		errors: function() {
			return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext );
		},

		reset: function() {
			this.successList = [];
			this.errorList = [];
			this.errorMap = {};
			this.toShow = $([]);
			this.toHide = $([]);
			this.currentElements = $([]);
		},

		prepareForm: function() {
			this.reset();
			this.toHide = this.errors().add( this.containers );
		},

		prepareElement: function( element ) {
			this.reset();
			this.toHide = this.errorsFor(element);
		},

		check: function( element ) {
			element = this.validationTargetFor( this.clean( element ) );

			var rules = $(element).rules();
			var dependencyMismatch = false;
			for (var method in rules ) {
				var rule = { method: method, parameters: rules[method] };
				try {
					var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );

					// if a method indicates that the field is optional and therefore valid,
					// don't mark it as valid when there are no other rules
					if ( result == "dependency-mismatch" ) {
						dependencyMismatch = true;
						continue;
					}
					dependencyMismatch = false;

					if ( result == "pending" ) {
						this.toHide = this.toHide.not( this.errorsFor(element) );
						return;
					}

					if( !result ) {
						this.formatAndAdd( element, rule );
						return false;
					}
				} catch(e) {
					this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
						 + ", check the '" + rule.method + "' method", e);
					throw e;
				}
			}
			if (dependencyMismatch)
				return;
			if ( this.objectLength(rules) )
				this.successList.push(element);
			return true;
		},

		// return the custom message for the given element and validation method
		// specified in the element's "messages" metadata
		customMetaMessage: function(element, method) {
			if (!$.metadata)
				return;

			var meta = this.settings.meta
				? $(element).metadata()[this.settings.meta]
				: $(element).metadata();

			return meta && meta.messages && meta.messages[method];
		},

		// return the custom message for the given element name and validation method
		customMessage: function( name, method ) {
			var m = this.settings.messages[name];
			return m && (m.constructor == String
				? m
				: m[method]);
		},

		// return the first defined argument, allowing empty strings
		findDefined: function() {
			for(var i = 0; i < arguments.length; i++) {
				if (arguments[i] !== undefined)
					return arguments[i];
			}
			return undefined;
		},

		defaultMessage: function( element, method) {
			return this.findDefined(
				this.customMessage( element.name, method ),
				this.customMetaMessage( element, method ),
				// title is never undefined, so handle empty string as undefined
				!this.settings.ignoreTitle && element.title || undefined,
				$.validator.messages[method],
				"<strong>Warning: No message defined for " + element.name + "</strong>"
			);
		},

		formatAndAdd: function( element, rule ) {
			var message = this.defaultMessage( element, rule.method ),
				theregex = /\$?\{(\d+)\}/g;
			if ( typeof message == "function" ) {
				message = message.call(this, rule.parameters, element);
			} else if (theregex.test(message)) {
				message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters);
			}
			this.errorList.push({
				message: message,
				element: element
			});

			this.errorMap[element.name] = message;
			this.submitted[element.name] = message;
		},

		addWrapper: function(toToggle) {
			if ( this.settings.wrapper )
				toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
			return toToggle;
		},

		defaultShowErrors: function() {
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow = this.toShow.add( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], 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 $(this.errorList).map(function() {
				return this.element;
			});
		},

		showLabel: function(element, message) {
			var label = this.errorsFor( element );
			if ( label.length ) {
				// refresh error/success class
				label.removeClass( this.settings.validClass ).addClass( this.settings.errorClass );

				// check if we have a generated label, replace the message then
				label.attr("generated") && label.html(message);
			} else {
				// create label
				label = $("<" + this.settings.errorElement + "/>")
					.attr({"for":  this.idOrName(element), generated: true})
					.addClass(this.settings.errorClass)
					.html(message || "");
				if ( this.settings.wrapper ) {
					// make sure the element is visible, even in IE
					// actually showing the wrapped element is handled elsewhere
					label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
				}
				if ( !this.labelContainer.append(label).length )
					this.settings.errorPlacement
						? this.settings.errorPlacement(label, $(element) )
						: label.insertAfter(element);
			}
			if ( !message && this.settings.success ) {
				label.text("");
				typeof this.settings.success == "string"
					? label.addClass( this.settings.success )
					: this.settings.success( label );
			}
			this.toShow = this.toShow.add(label);
		},

		errorsFor: function(element) {
			var name = this.idOrName(element);
    		return this.errors().filter(function() {
				return $(this).attr('for') == name;
			});
		},

		idOrName: function(element) {
			return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
		},

		validationTargetFor: function(element) {
			// if radio/checkbox, validate first element in group instead
			if (this.checkable(element)) {
				element = this.findByName( element.name ).not(this.settings.ignore)[0];
			}
			return element;
		},

		checkable: function( element ) {
			return /radio|checkbox/i.test(element.type);
		},

		findByName: function( name ) {
			// select by name and filter by form for performance over form.find("[name=...]")
			var form = this.currentForm;
			return $(document.getElementsByName(name)).map(function(index, element) {
				return element.form == form && element.name == name && element  || null;
			});
		},

		getLength: function(value, element) {
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				return $("option:selected", element).length;
			case 'input':
				if( this.checkable( element) )
					return this.findByName(element.name).filter(':checked').length;
			}
			return value.length;
		},

		depend: function(param, element) {
			return this.dependTypes[typeof param]
				? this.dependTypes[typeof param](param, element)
				: true;
		},

		dependTypes: {
			"boolean": function(param, element) {
				return param;
			},
			"string": function(param, element) {
				return !!$(param, element.form).length;
			},
			"function": function(param, element) {
				return param(element);
			}
		},

		optional: function(element) {
			return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch";
		},

		startRequest: function(element) {
			if (!this.pending[element.name]) {
				this.pendingRequest++;
				this.pending[element.name] = true;
			}
		},

		stopRequest: function(element, valid) {
			this.pendingRequest--;
			// sometimes synchronization fails, make sure pendingRequest is never < 0
			if (this.pendingRequest < 0)
				this.pendingRequest = 0;
			delete this.pending[element.name];
			if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) {
				$(this.currentForm).submit();
				this.formSubmitted = false;
			} else if (!valid && this.pendingRequest == 0 && this.formSubmitted) {
				$(this.currentForm).triggerHandler("invalid-form", [this]);
				this.formSubmitted = false;
			}
		},

		previousValue: function(element) {
			return $.data(element, "previousValue") || $.data(element, "previousValue", {
				old: null,
				valid: true,
				message: this.defaultMessage( element, "remote" )
			});
		}

	},

	classRuleSettings: {
		required: {required: true},
		email: {email: true},
		url: {url: true},
		date: {date: true},
		dateISO: {dateISO: true},
		dateDE: {dateDE: true},
		number: {number: true},
		numberDE: {numberDE: true},
		digits: {digits: true},
		creditcard: {creditcard: true}
	},

	addClassRules: function(className, rules) {
		className.constructor == String ?
			this.classRuleSettings[className] = rules :
			$.extend(this.classRuleSettings, className);
	},

	classRules: function(element) {
		var rules = {};
		var classes = $(element).attr('class');
		classes && $.each(classes.split(' '), function() {
			if (this in $.validator.classRuleSettings) {
				$.extend(rules, $.validator.classRuleSettings[this]);
			}
		});
		return rules;
	},

	attributeRules: function(element) {
		var rules = {};
		var $element = $(element);

		for (var method in $.validator.methods) {
			var value;
			// If .prop exists (jQuery >= 1.6), use it to get true/false for required
			if (method === 'required' && typeof $.fn.prop === 'function') {
				value = $element.prop(method);
			} else {
				value = $element.attr(method);
			}
			if (value) {
				rules[method] = value;
			} else if ($element[0].getAttribute("type") === method) {
				rules[method] = true;
			}
		}

		// maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
		if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
			delete rules.maxlength;
		}

		return rules;
	},

	metadataRules: function(element) {
		if (!$.metadata) return {};

		var meta = $.data(element.form, 'validator').settings.meta;
		return meta ?
			$(element).metadata()[meta] :
			$(element).metadata();
	},

	staticRules: function(element) {
		var rules = {};
		var validator = $.data(element.form, 'validator');
		if (validator.settings.rules) {
			rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
		}
		return rules;
	},

	normalizeRules: function(rules, element) {
		// handle dependency check
		$.each(rules, function(prop, val) {
			// ignore rule when param is explicitly false, eg. required:false
			if (val === false) {
				delete rules[prop];
				return;
			}
			if (val.param || val.depends) {
				var keepRule = true;
				switch (typeof val.depends) {
					case "string":
						keepRule = !!$(val.depends, element.form).length;
						break;
					case "function":
						keepRule = val.depends.call(element, element);
						break;
				}
				if (keepRule) {
					rules[prop] = val.param !== undefined ? val.param : true;
				} else {
					delete rules[prop];
				}
			}
		});

		// evaluate parameters
		$.each(rules, function(rule, parameter) {
			rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
		});

		// clean number parameters
		$.each(['minlength', 'maxlength', 'min', 'max'], function() {
			if (rules[this]) {
				rules[this] = Number(rules[this]);
			}
		});
		$.each(['rangelength', 'range'], function() {
			if (rules[this]) {
				rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
			}
		});

		if ($.validator.autoCreateRanges) {
			// auto-create ranges
			if (rules.min && rules.max) {
				rules.range = [rules.min, rules.max];
				delete rules.min;
				delete rules.max;
			}
			if (rules.minlength && rules.maxlength) {
				rules.rangelength = [rules.minlength, rules.maxlength];
				delete rules.minlength;
				delete rules.maxlength;
			}
		}

		// To support custom messages in metadata ignore rule methods titled "messages"
		if (rules.messages) {
			delete rules.messages;
		}

		return rules;
	},

	// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
	normalizeRule: function(data) {
		if( typeof data == "string" ) {
			var transformed = {};
			$.each(data.split(/\s/), function() {
				transformed[this] = true;
			});
			data = transformed;
		}
		return data;
	},

	// http://docs.jquery.com/Plugins/Validation/Validator/addMethod
	addMethod: function(name, method, message) {
		$.validator.methods[name] = method;
		$.validator.messages[name] = message != undefined ? message : $.validator.messages[name];
		if (method.length < 3) {
			$.validator.addClassRules(name, $.validator.normalizeRule(name));
		}
	},

	methods: {

		// http://docs.jquery.com/Plugins/Validation/Methods/required
		required: function(value, element, param) {
			// check if dependency is met
			if ( !this.depend(param, element) )
				return "dependency-mismatch";
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				// could be an array for select-multiple or a string, both are fine this way
				var val = $(element).val();
				return val && val.length > 0;
			case 'input':
				if ( this.checkable(element) )
					return this.getLength(value, element) > 0;
			default:
				return $.trim(value).length > 0;
			}
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/remote
		remote: function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";

			var previous = this.previousValue(element);
			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			previous.originalMessage = this.settings.messages[element.name].remote;
			this.settings.messages[element.name].remote = previous.message;

			param = typeof param == "string" && {url:param} || param;

			if ( this.pending[element.name] ) {
				return "pending";
			}
			if ( previous.old === value ) {
				return previous.valid;
			}

			previous.old = value;
			var validator = this;
			this.startRequest(element);
			var data = {};
			data[element.name] = value;
			$.ajax($.extend(true, {
				url: param,
				mode: "abort",
				port: "validate" + element.name,
				dataType: "json",
				data: data,
				success: function(response) {
					validator.settings.messages[element.name].remote = previous.originalMessage;
					var valid = response === true;
					if ( valid ) {
						var submitted = validator.formSubmitted;
						validator.prepareElement(element);
						validator.formSubmitted = submitted;
						validator.successList.push(element);
						validator.showErrors();
					} else {
						var errors = {};
						var message = response || validator.defaultMessage( element, "remote" );
						errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
						validator.showErrors(errors);
					}
					previous.valid = valid;
					validator.stopRequest(element, valid);
				}
			}, param));
			return "pending";
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/minlength
		minlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) >= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/maxlength
		maxlength: function(value, element, param) {
			return this.optional(element) || this.getLength($.trim(value), element) <= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/rangelength
		rangelength: function(value, element, param) {
			var length = this.getLength($.trim(value), element);
			return this.optional(element) || ( length >= param[0] && length <= param[1] );
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/min
		min: function( value, element, param ) {
			return this.optional(element) || value >= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/max
		max: function( value, element, param ) {
			return this.optional(element) || value <= param;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/range
		range: function( value, element, param ) {
			return this.optional(element) || ( value >= param[0] && value <= param[1] );
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/email
		email: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			return this.optional(element) || /^((([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(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/url
		url: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
			return this.optional(element) || /^(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(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/date
		date: function(value, element) {
			return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/dateISO
		dateISO: function(value, element) {
			return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/number
		number: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/digits
		digits: function(value, element) {
			return this.optional(element) || /^\d+$/.test(value);
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/creditcard
		// based on http://en.wikipedia.org/wiki/Luhn
		creditcard: function(value, element) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			// accept only spaces, digits and dashes
			if (/[^0-9 -]+/.test(value))
				return false;
			var nCheck = 0,
				nDigit = 0,
				bEven = false;

			value = value.replace(/\D/g, "");

			for (var n = value.length - 1; n >= 0; n--) {
				var cDigit = value.charAt(n);
				var nDigit = parseInt(cDigit, 10);
				if (bEven) {
					if ((nDigit *= 2) > 9)
						nDigit -= 9;
				}
				nCheck += nDigit;
				bEven = !bEven;
			}

			return (nCheck % 10) == 0;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/accept
		accept: function(value, element, param) {
			param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
			return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i"));
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/equalTo
		equalTo: function(value, element, param) {
			// bind to the blur event of the target in order to revalidate whenever the target field is updated
			// TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
			var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() {
				$(element).valid();
			});
			return value == target.val();
		}

	}

});

// deprecated, use $.validator.format instead
$.format = $.validator.format;

})(jQuery);

// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
;(function($) {
	var pendingRequests = {};
	// Use a prefilter if available (1.5+)
	if ( $.ajaxPrefilter ) {
		$.ajaxPrefilter(function(settings, _, xhr) {
			var port = settings.port;
			if (settings.mode == "abort") {
				if ( pendingRequests[port] ) {
					pendingRequests[port].abort();
				}
				pendingRequests[port] = xhr;
			}
		});
	} else {
		// Proxy ajax
		var ajax = $.ajax;
		$.ajax = function(settings) {
			var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
				port = ( "port" in settings ? settings : $.ajaxSettings ).port;
			if (mode == "abort") {
				if ( pendingRequests[port] ) {
					pendingRequests[port].abort();
				}
				return (pendingRequests[port] = ajax.apply(this, arguments));
			}
			return ajax.apply(this, arguments);
		};
	}
})(jQuery);

// provides cross-browser focusin and focusout events
// IE has native support, in other browsers, use event caputuring (neither bubbles)

// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
;(function($) {
	// only implement if not provided by jQuery core (since 1.4)
	// TODO verify if jQuery 1.4's implementation is compatible with older jQuery special-event APIs
	if (!jQuery.event.special.focusin && !jQuery.event.special.focusout && document.addEventListener) {
		$.each({
			focus: 'focusin',
			blur: 'focusout'
		}, function( original, fix ){
			$.event.special[fix] = {
				setup:function() {
					this.addEventListener( original, handler, true );
				},
				teardown:function() {
					this.removeEventListener( original, handler, true );
				},
				handler: function(e) {
					arguments[0] = $.event.fix(e);
					arguments[0].type = fix;
					return $.event.handle.apply(this, arguments);
				}
			};
			function handler(e) {
				e = $.event.fix(e);
				e.type = fix;
				return $.event.handle.call(this, e);
			}
		});
	};
	$.extend($.fn, {
		validateDelegate: function(delegate, type, handler) {
			return this.bind(type, function(event) {
				var target = $(event.target);
				if (target.is(delegate)) {
					return handler.apply(target, arguments);
				}
			});
		}
	});
})(jQuery);
;
/// <reference path="jquery-1.5.1.js" />
/// <reference path="jquery.validate.js" />

/*!
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/

/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */

(function ($) {
    var $jQval = $.validator,
        adapters,
        data_validation = "unobtrusiveValidation";

    function setValidationValues(options, ruleName, value) {
        options.rules[ruleName] = value;
        if (options.message) {
            options.messages[ruleName] = options.message;
        }
    }

    function splitAndTrim(value) {
        return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
    }

    function getModelPrefix(fieldName) {
        return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
    }

    function appendModelPrefix(value, prefix) {
        if (value.indexOf("*.") === 0) {
            value = value.replace("*.", prefix);
        }
        return value;
    }

    function onError(error, inputElement) {  // 'this' is the form element
        var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
            replaceAttrValue = container.attr("data-valmsg-replace"),
            replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;

        container.removeClass("field-validation-valid").addClass("field-validation-error");
        error.data("unobtrusiveContainer", container);

        if (replace) {
            container.empty();
            error.removeClass("input-validation-error").appendTo(container);
        }
        else {
            error.hide();
        }
    }

    function onErrors(form, validator) {  // 'this' is the form element
        var container = $(this).find("[data-valmsg-summary=true]"),
            list = container.find("ul");

        if (list && list.length && validator.errorList.length) {
            list.empty();
            container.addClass("validation-summary-errors").removeClass("validation-summary-valid");

            $.each(validator.errorList, function () {
                $("<li />").html(this.message).appendTo(list);
            });
        }
    }

    function onSuccess(error) {  // 'this' is the form element
        var container = error.data("unobtrusiveContainer"),
            replaceAttrValue = container.attr("data-valmsg-replace"),
            replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;

        if (container) {
            container.addClass("field-validation-valid").removeClass("field-validation-error");
            error.removeData("unobtrusiveContainer");

            if (replace) {
                container.empty();
            }
        }
    }

    function validationInfo(form) {
        var $form = $(form),
            result = $form.data(data_validation);

        if (!result) {
            result = {
                options: {  // options structure passed to jQuery Validate's validate() method
                    errorClass: "input-validation-error",
                    errorElement: "span",
                    errorPlacement: $.proxy(onError, form),
                    invalidHandler: $.proxy(onErrors, form),
                    messages: {},
                    rules: {},
                    success: $.proxy(onSuccess, form)
                },
                attachValidation: function () {
                    $form.validate(this.options);
                },
                validate: function () {  // a validation function that is called by unobtrusive Ajax
                    $form.validate();
                    return $form.valid();
                }
            };
            $form.data(data_validation, result);
        }

        return result;
    }

    $jQval.unobtrusive = {
        adapters: [],

        parseElement: function (element, skipAttach) {
            /// <summary>
            /// Parses a single HTML element for unobtrusive validation attributes.
            /// </summary>
            /// <param name="element" domElement="true">The HTML element to be parsed.</param>
            /// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
            /// validation to the form. If parsing just this single element, you should specify true.
            /// If parsing several elements, you should specify false, and manually attach the validation
            /// to the form when you are finished. The default is false.</param>
            var $element = $(element),
                form = $element.parents("form")[0],
                valInfo, rules, messages;

            if (!form) {  // Cannot do client-side validation without a form
                return;
            }

            valInfo = validationInfo(form);
            valInfo.options.rules[element.name] = rules = {};
            valInfo.options.messages[element.name] = messages = {};

            $.each(this.adapters, function () {
                var prefix = "data-val-" + this.name,
                    message = $element.attr(prefix),
                    paramValues = {};

                if (message !== undefined) {  // Compare against undefined, because an empty message is legal (and falsy)
                    prefix += "-";

                    $.each(this.params, function () {
                        paramValues[this] = $element.attr(prefix + this);
                    });

                    this.adapt({
                        element: element,
                        form: form,
                        message: message,
                        params: paramValues,
                        rules: rules,
                        messages: messages
                    });
                }
            });

            jQuery.extend(rules, { "__dummy__": true });

            if (!skipAttach) {
                valInfo.attachValidation();
            }
        },

        parse: function (selector) {
            /// <summary>
            /// Parses all the HTML elements in the specified selector. It looks for input elements decorated
            /// with the [data-val=true] attribute value and enables validation according to the data-val-*
            /// attribute values.
            /// </summary>
            /// <param name="selector" type="String">Any valid jQuery selector.</param>
            $(selector).find(":input[data-val=true]").each(function () {
                $jQval.unobtrusive.parseElement(this, true);
            });

            $("form").each(function () {
                var info = validationInfo(this);
                if (info) {
                    info.attachValidation();
                }
            });
        }
    };

    adapters = $jQval.unobtrusive.adapters;

    adapters.add = function (adapterName, params, fn) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
        /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
        /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
        /// mmmm is the parameter name).</param>
        /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
        /// attributes into jQuery Validate rules and/or messages.</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        if (!fn) {  // Called with no params, just a function
            fn = params;
            params = [];
        }
        this.push({ name: adapterName, params: params, adapt: fn });
        return this;
    };

    adapters.addBool = function (adapterName, ruleName) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
        /// the jQuery Validate validation rule has no parameter values.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
        /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
        /// of adapterName will be used instead.</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        return this.add(adapterName, function (options) {
            setValidationValues(options, ruleName || adapterName, true);
        });
    };

    adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
        /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
        /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
        /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
        /// have a minimum value.</param>
        /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
        /// have a maximum value.</param>
        /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
        /// have both a minimum and maximum value.</param>
        /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
        /// contains the minimum value. The default is "min".</param>
        /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
        /// contains the maximum value. The default is "max".</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
            var min = options.params.min,
                max = options.params.max;

            if (min && max) {
                setValidationValues(options, minMaxRuleName, [min, max]);
            }
            else if (min) {
                setValidationValues(options, minRuleName, min);
            }
            else if (max) {
                setValidationValues(options, maxRuleName, max);
            }
        });
    };

    adapters.addSingleVal = function (adapterName, attribute, ruleName) {
        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
        /// the jQuery Validate validation rule has a single value.</summary>
        /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
        /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
        /// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
        /// The default is "val".</param>
        /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
        /// of adapterName will be used instead.</param>
        /// <returns type="jQuery.validator.unobtrusive.adapters" />
        return this.add(adapterName, [attribute || "val"], function (options) {
            setValidationValues(options, ruleName || adapterName, options.params[attribute]);
        });
    };

    $jQval.addMethod("__dummy__", function (value, element, params) {
        return true;
    });

    $jQval.addMethod("regex", function (value, element, params) {
        var match;
        if (this.optional(element)) {
            return true;
        }

        match = new RegExp(params).exec(value);
        return (match && (match.index === 0) && (match[0].length === value.length));
       });

    adapters.addSingleVal("accept", "exts").addSingleVal("regex", "pattern");
    adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
    adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
    adapters.add("equalto", ["other"], function (options) {
        var prefix = getModelPrefix(options.element.name),
            other = options.params.other,
            fullOtherName = appendModelPrefix(other, prefix),
            element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];

        setValidationValues(options, "equalTo", element);
    });
    adapters.add("required", function (options) {
        // jQuery Validate equates "required" with "mandatory" for checkbox elements
        if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
            setValidationValues(options, "required", true);
        }
    });
    adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
        var value = {
            url: options.params.url,
            type: options.params.type || "GET",
            data: {}
        },
            prefix = getModelPrefix(options.element.name);

        $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
            var paramName = appendModelPrefix(fieldName, prefix);
            value.data[paramName] = function () {
                return $(options.form).find(":input[name='" + paramName + "']").val();
            };
        });

        setValidationValues(options, "remote", value);
    });

       $jQval.addMethod("mustbetrue", function (value, element, param) {
       	// check if dependency is met
       	if (!this.depend(param, element))
       		return "dependency-mismatch";
       	return element.checked;
       });
       adapters.add("mustbetrue", function (options) {
       	setValidationValues(options, "mustbetrue", true);
       });


    $(function () {
        $jQval.unobtrusive.parse(document);
    });
}(jQuery));;
/* Modernizr 2.5 (Custom Build) | MIT & BSD
* Build: http://www.modernizr.com/download/#-fontface-backgroundsize-borderimage-borderradius-boxshadow-flexbox-hsla-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-cssgradients-cssreflections-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-input-inputtypes-localstorage-postmessage-sessionstorage-websockets-websqldatabase-webworkers-geolocation-inlinesvg-smil-svg-svgclippaths-touch-webgl-shiv-mq-cssclasses-addtest-prefixed-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load
*/
window.Modernizr = function (a, b, c) { function C(a) { j.cssText = a } function D(a, b) { return C(n.join(a + ";") + (b || "")) } function E(a, b) { return typeof a === b } function F(a, b) { return !! ~("" + a).indexOf(b) } function G(a, b) { for (var d in a) if (j[a[d]] !== c) return b == "pfx" ? a[d] : !0; return !1 } function H(a, b, d) { for (var e in a) { var f = b[a[e]]; if (f !== c) return d === !1 ? a[e] : E(f, "function") ? f.bind(d || b) : f } return !1 } function I(a, b, c) { var d = a.charAt(0).toUpperCase() + a.substr(1), e = (a + " " + p.join(d + " ") + d).split(" "); return E(b, "string") || E(b, "undefined") ? G(e, b) : (e = (a + " " + q.join(d + " ") + d).split(" "), H(e, b, c)) } function K() { e.input = function (c) { for (var d = 0, e = c.length; d < e; d++) u[c[d]] = c[d] in k; return u.list && (u.list = !!b.createElement("datalist") && !!a.HTMLDataListElement), u } ("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")), e.inputtypes = function (a) { for (var d = 0, e, f, h, i = a.length; d < i; d++) k.setAttribute("type", f = a[d]), e = k.type !== "text", e && (k.value = l, k.style.cssText = "position:absolute;visibility:hidden;", /^range$/.test(f) && k.style.WebkitAppearance !== c ? (g.appendChild(k), h = b.defaultView, e = h.getComputedStyle && h.getComputedStyle(k, null).WebkitAppearance !== "textfield" && k.offsetHeight !== 0, g.removeChild(k)) : /^(search|tel)$/.test(f) || (/^(url|email)$/.test(f) ? e = k.checkValidity && k.checkValidity() === !1 : /^color$/.test(f) ? (g.appendChild(k), g.offsetWidth, e = k.value != l, g.removeChild(k)) : e = k.value != l)), t[a[d]] = !!e; return t } ("search tel url email datetime date month week time datetime-local number range color".split(" ")) } var d = "2.5", e = {}, f = !0, g = b.documentElement, h = "modernizr", i = b.createElement(h), j = i.style, k = b.createElement("input"), l = ":)", m = {}.toString, n = " -webkit- -moz- -o- -ms- ".split(" "), o = "Webkit Moz O ms", p = o.split(" "), q = o.toLowerCase().split(" "), r = { svg: "http://www.w3.org/2000/svg" }, s = {}, t = {}, u = {}, v = [], w, x = function (a, c, d, e) { var f, i, j, k = b.createElement("div"), l = b.body, m = l ? l : b.createElement("body"); if (parseInt(d, 10)) while (d--) j = b.createElement("div"), j.id = e ? e[d] : h + (d + 1), k.appendChild(j); return f = ["&#173;", "<style>", a, "</style>"].join(""), k.id = h, m.innerHTML += f, m.appendChild(k), g.appendChild(m), i = c(k, a), l ? k.parentNode.removeChild(k) : m.parentNode.removeChild(m), !!i }, y = function (b) { var c = a.matchMedia || a.msMatchMedia; if (c) return c(b).matches; var d; return x("@media " + b + " { #" + h + " { position: absolute; } }", function (b) { d = (a.getComputedStyle ? getComputedStyle(b, null) : b.currentStyle)["position"] == "absolute" }), d }, z = function () { function d(d, e) { e = e || b.createElement(a[d] || "div"), d = "on" + d; var f = d in e; return f || (e.setAttribute || (e = b.createElement("div")), e.setAttribute && e.removeAttribute && (e.setAttribute(d, ""), f = E(e[d], "function"), E(e[d], "undefined") || (e[d] = c), e.removeAttribute(d))), e = null, f } var a = { select: "input", change: "input", submit: "form", reset: "form", error: "img", load: "img", abort: "img" }; return d } (), A = {}.hasOwnProperty, B; !E(A, "undefined") && !E(A.call, "undefined") ? B = function (a, b) { return A.call(a, b) } : B = function (a, b) { return b in a && E(a.constructor.prototype[b], "undefined") }, Function.prototype.bind || (Function.prototype.bind = function (b) { var c = this; if (typeof c != "function") throw new TypeError; var d = slice.call(arguments, 1), e = function () { if (this instanceof e) { var a = function () { }; a.prototype = c.prototype; var f = new a, g = c.apply(f, d.concat(slice.call(arguments))); return Object(g) === g ? g : f } return c.apply(b, d.concat(slice.call(arguments))) }; return e }); var J = function (c, d) { var f = c.join(""), g = d.length; x(f, function (c, d) { var f = b.styleSheets[b.styleSheets.length - 1], h = f ? f.cssRules && f.cssRules[0] ? f.cssRules[0].cssText : f.cssText || "" : "", i = c.childNodes, j = {}; while (g--) j[i[g].id] = i[g]; e.touch = "ontouchstart" in a || a.DocumentTouch && b instanceof DocumentTouch || (j.touch && j.touch.offsetTop) === 9, e.csstransforms3d = (j.csstransforms3d && j.csstransforms3d.offsetLeft) === 9 && j.csstransforms3d.offsetHeight === 3, e.generatedcontent = (j.generatedcontent && j.generatedcontent.offsetHeight) >= 1, e.fontface = /src/i.test(h) && h.indexOf(d.split(" ")[0]) === 0 }, g, d) } (['@font-face {font-family:"font";src:url("https://")}', ["@media (", n.join("touch-enabled),("), h, ")", "{#touch{top:9px;position:absolute}}"].join(""), ["@media (", n.join("transform-3d),("), h, ")", "{#csstransforms3d{left:9px;position:absolute;height:3px;}}"].join(""), ['#generatedcontent:after{content:"', l, '";visibility:hidden}'].join("")], ["fontface", "touch", "csstransforms3d", "generatedcontent"]); s.flexbox = function () { return I("flexOrder") }, s["flexbox-legacy"] = function () { return I("boxDirection") }, s.canvas = function () { var a = b.createElement("canvas"); return !!a.getContext && !!a.getContext("2d") }, s.canvastext = function () { return !!e.canvas && !!E(b.createElement("canvas").getContext("2d").fillText, "function") }, s.webgl = function () { try { var d = b.createElement("canvas"), e; e = !(!a.WebGLRenderingContext || !d.getContext("experimental-webgl") && !d.getContext("webgl")), d = c } catch (f) { e = !1 } return e }, s.touch = function () { return e.touch }, s.geolocation = function () { return !!navigator.geolocation }, s.postmessage = function () { return !!a.postMessage }, s.websqldatabase = function () { return !!a.openDatabase }, s.indexedDB = function () { return !!I("indexedDB", a) }, s.hashchange = function () { return z("hashchange", a) && (b.documentMode === c || b.documentMode > 7) }, s.history = function () { return !!a.history && !!history.pushState }, s.draganddrop = function () { var a = b.createElement("div"); return "draggable" in a || "ondragstart" in a && "ondrop" in a }, s.websockets = function () { for (var b = -1, c = p.length; ++b < c; ) if (a[p[b] + "WebSocket"]) return !0; return "WebSocket" in a }, s.rgba = function () { return C("background-color:rgba(150,255,150,.5)"), F(j.backgroundColor, "rgba") }, s.hsla = function () { return C("background-color:hsla(120,40%,100%,.5)"), F(j.backgroundColor, "rgba") || F(j.backgroundColor, "hsla") }, s.multiplebgs = function () { return C("background:url(https://),url(https://),red url(https://)"), /(url\s*\(.*?){3}/.test(j.background) }, s.backgroundsize = function () { return I("backgroundSize") }, s.borderimage = function () { return I("borderImage") }, s.borderradius = function () { return I("borderRadius") }, s.boxshadow = function () { return I("boxShadow") }, s.textshadow = function () { return b.createElement("div").style.textShadow === "" }, s.opacity = function () { return D("opacity:.55"), /^0.55$/.test(j.opacity) }, s.cssanimations = function () { return I("animationName") }, s.csscolumns = function () { return I("columnCount") }, s.cssgradients = function () { var a = "background-image:", b = "gradient(linear,left top,right bottom,from(#9f9),to(white));", c = "linear-gradient(left top,#9f9, white);"; return C((a + "-webkit- ".split(" ").join(b + a) + n.join(c + a)).slice(0, -a.length)), F(j.backgroundImage, "gradient") }, s.cssreflections = function () { return I("boxReflect") }, s.csstransforms = function () { return !!I("transform") }, s.csstransforms3d = function () { var a = !!I("perspective"); return a && "webkitPerspective" in g.style && (a = e.csstransforms3d), a }, s.csstransitions = function () { return I("transition") }, s.fontface = function () { return e.fontface }, s.generatedcontent = function () { return e.generatedcontent }, s.video = function () { var a = b.createElement("video"), c = !1; try { if (c = !!a.canPlayType) c = new Boolean(c), c.ogg = a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ""), c.h264 = a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ""), c.webm = a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, "") } catch (d) { } return c }, s.audio = function () { var a = b.createElement("audio"), c = !1; try { if (c = !!a.canPlayType) c = new Boolean(c), c.ogg = a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ""), c.mp3 = a.canPlayType("audio/mpeg;").replace(/^no$/, ""), c.wav = a.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ""), c.m4a = (a.canPlayType("audio/x-m4a;") || a.canPlayType("audio/aac;")).replace(/^no$/, "") } catch (d) { } return c }, s.localstorage = function () { try { return localStorage.setItem(h, h), localStorage.removeItem(h), !0 } catch (a) { return !1 } }, s.sessionstorage = function () { try { return sessionStorage.setItem(h, h), sessionStorage.removeItem(h), !0 } catch (a) { return !1 } }, s.webworkers = function () { return !!a.Worker }, s.applicationcache = function () { return !!a.applicationCache }, s.svg = function () { return !!b.createElementNS && !!b.createElementNS(r.svg, "svg").createSVGRect }, s.inlinesvg = function () { var a = b.createElement("div"); return a.innerHTML = "<svg/>", (a.firstChild && a.firstChild.namespaceURI) == r.svg }, s.smil = function () { return !!b.createElementNS && /SVGAnimate/.test(m.call(b.createElementNS(r.svg, "animate"))) }, s.svgclippaths = function () { return !!b.createElementNS && /SVGClipPath/.test(m.call(b.createElementNS(r.svg, "clipPath"))) }; for (var L in s) B(s, L) && (w = L.toLowerCase(), e[w] = s[L](), v.push((e[w] ? "" : "no-") + w)); return e.input || K(), e.addTest = function (a, b) { if (typeof a == "object") for (var d in a) B(a, d) && e.addTest(d, a[d]); else { a = a.toLowerCase(); if (e[a] !== c) return e; b = typeof b == "function" ? b() : b, g.className += " " + (b ? "" : "no-") + a, e[a] = b } return e }, C(""), i = k = null, function (a, b) { var c = function (a, c, d) { var e, f, g = b.body || (e = c.insertBefore(b.createElement("body"), c.firstChild)); return g.insertBefore(a, g.firstChild), a.hidden = !0, f = (d ? d(a, null) : a.currentStyle).display === "none", g.removeChild(a), e && c.removeChild(e), f } (b.createElement("a"), b.documentElement, a.getComputedStyle), d = function (a) { return a.innerHTML = "<x-element></x-element>", a.childNodes.length === 1 } (b.createElement("a")), e = Date.call, f = "abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video", g = a.html5 || {}; g = { elements: typeof g.elements == "object" ? g.elements : (g.elements || f).split(" "), shivCSS: g.shivCSS !== !1, shivMethods: g.shivMethods !== !1, shivDocument: function (a) { if (!d && !a.documentShived) { var b = a.createElement, f = a.createDocumentFragment; for (var h = 0, i = g.elements, j = i.length; h < j; ++h) e.call(b, a, i[h]); a.createElement = function (c) { var d = e.call(b, a, c); return g.shivMethods && d.canHaveChildren && !d.xmlns && !d.tagUrn && g.shivDocument(d.document), d }, a.createDocumentFragment = function () { var b = e.call(f, a); return g.shivMethods ? g.shivDocument(b) : b } } var k = a.getElementsByTagName("head")[0]; if (g.shivCSS && !c && k) { var l = a.createElement("p"); l.innerHTML = "x<style>article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio{display:none}canvas,video{display:inline-block;*display:inline;*zoom:1}[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}mark{background:#FF0;color:#000}</style>", k.insertBefore(l.lastChild, k.firstChild) } return a.documentShived = !0, a } }, g.type = "default", a.html5 = g, g.shivDocument(b) } (this, b), e._version = d, e._prefixes = n, e._domPrefixes = q, e._cssomPrefixes = p, e.mq = y, e.hasEvent = z, e.testProp = function (a) { return G([a]) }, e.testAllProps = I, e.testStyles = x, e.prefixed = function (a, b, c) { return b ? I(a, b, c) : I(a, "pfx") }, g.className = g.className.replace(/(^|\s)no-js(\s|$)/, "$1$2") + (f ? " js " + v.join(" ") : ""), e } (this, this.document), function (a, b, c) { function C(a) { return !a || a == "loaded" || a == "complete" || a == "uninitialized" } function D(a, c, d, g, h, j) { var l = b.createElement("script"), m; g = g || B.errorTimeout, l.src = a; for (i in d) l.setAttribute(i, d[i]); c = j ? F : c || k, l.onreadystatechange = l.onload = function () { !m && C(l.readyState) && (m = 1, c(), l.onload = l.onreadystatechange = null) }, e(function () { m || (m = 1, c(1)) }, g), h ? l.onload() : f.parentNode.insertBefore(l, f) } function E(a, c, d, g, h, i) { var j = b.createElement("link"), l, m; g = g || B.errorTimeout, c = i ? F : c || k, j.href = a, j.rel = "stylesheet", j.type = "text/css"; for (m in d) j.setAttribute(m, d[m]); h || (f.parentNode.insertBefore(j, f), e(c, 0)) } function F() { var a = h.shift(); j = 1, a ? a.t ? e(function () { (a.t == "c" ? B.injectCss : B.injectJs)(a.s, 0, a.a, a.x, a.e, 1) }, 0) : (a(), F()) : j = 0 } function G(a, c, d, g, i, k, l) { function s(b) { if (!p && C(o.readyState)) { r.r = p = 1, !j && F(), o.onload = o.onreadystatechange = null; if (b) { a == "object" && e(function () { n.removeChild(o) }, 50); for (var d in y[c]) y[c].hasOwnProperty(d) && y[c][d].onload() } } } l = l || B.errorTimeout; var o = {}, p = 0, q = 0, r = { t: d, s: c, e: i, a: k, x: l }; y[c] === 1 && (q = 1, y[c] = [], o = b.createElement(a)), o.src = o.data = c, o.width = o.height = "0", o.onerror = o.onload = o.onreadystatechange = function () { s.call(this, q) }, h.splice(g, 0, r), a == "object" && (q || y[c] === 2 ? (n.insertBefore(o, m ? null : f), e(s, l)) : y[c].push(o)) } function H(a, b, c, d, e) { return j = 0, b = b || "j", v(a) ? G(b == "c" ? s : r, a, b, this.i++, c, d, e) : (h.splice(this.i++, 0, a), h.length == 1 && F()), this } function I() { var a = B; return a.loader = { load: H, i: 0 }, a } var d = b.documentElement, e = a.setTimeout, f = b.getElementsByTagName("script")[0], g = {}.toString, h = [], j = 0, k = function () { }, l = "MozAppearance" in d.style, m = l && !!b.createRange().compareNode, n = m ? d : f.parentNode, o = a.opera && g.call(a.opera) == "[object Opera]", p = !!b.attachEvent, q = "webkitAppearance" in d.style, r = l ? "object" : "img", s = p ? "script" : r, t = Array.isArray || function (a) { return g.call(a) == "[object Array]" }, u = function (a) { return Object(a) === a }, v = function (a) { return typeof a == "string" }, w = function (a) { return g.call(a) == "[object Function]" }, x = [], y = {}, z = { timeout: function (a, b) { return b.length && (a.timeout = b[0]), a } }, A, B; B = function (a) { function f(a) { var b = a.split("!"), c = x.length, d = b.pop(), e = b.length, f = { url: d, origUrl: d, prefixes: b }, g, h, i; for (h = 0; h < e; h++) i = b[h].split("="), g = z[i.shift()], g && (f = g(f, i)); for (h = 0; h < c; h++) f = x[h](f); return f } function g(a) { return a.split(".").pop().split("?").shift() } function h(a, b, d, e, h) { var i = f(a), j = i.autoCallback, k = g(i.url); if (i.bypass) return; b && (b = w(b) ? b : b[a] || b[e] || b[a.split("/").pop().split("?")[0]] || F); if (i.instead) return i.instead(a, b, d, e, h); y[i.url] ? i.noexec = !0 : y[i.url] = 1, d.load(i.url, i.forceCSS || !i.forceJS && "css" == g(i.url) ? "c" : c, i.noexec, i.attrs, i.timeout), (w(b) || w(j)) && d.load(function () { I(), b && b(i.origUrl, h, e), j && j(i.origUrl, h, e), y[i.url] = 2 }) } function i(a, b) { function m(a, d) { if (!a) !d && i(); else if (v(a)) d || (f = function () { var a = [].slice.call(arguments); g.apply(this, a), i() }), h(a, f, b, 0, c); else if (u(a)) { j = function () { var b = 0, c; for (c in a) a.hasOwnProperty(c) && b++; return b } (); for (l in a) a.hasOwnProperty(l) && (!d && ! --j && (w(f) ? f = function () { var a = [].slice.call(arguments); g.apply(this, a), i() } : f[l] = function (a) { return function () { var b = [].slice.call(arguments); a.apply(this, b), i() } } (g[l])), h(a[l], f, b, l, c)) } } var c = !!a.test, d = c ? a.yep : a.nope, e = a.load || a.both, f = a.callback || k, g = f, i = a.complete || k, j, l; m(d, !!e), e && m(e) } var b, d, e = this.yepnope.loader; if (v(a)) h(a, 0, e, 0); else if (t(a)) for (b = 0; b < a.length; b++) d = a[b], v(d) ? h(d, 0, e, 0) : t(d) ? B(d) : u(d) && i(d, e); else u(a) && i(a, e) }, B.addPrefix = function (a, b) { z[a] = b }, B.addFilter = function (a) { x.push(a) }, B.errorTimeout = 1e4, b.readyState == null && b.addEventListener && (b.readyState = "loading", b.addEventListener("DOMContentLoaded", A = function () { b.removeEventListener("DOMContentLoaded", A, 0), b.readyState = "complete" }, 0)), a.yepnope = I(), a.yepnope.executeStack = F, a.yepnope.injectJs = D, a.yepnope.injectCss = E } (this, this.document), Modernizr.load = function () { yepnope.apply(window, [].slice.call(arguments, 0)) };
;
//****NOTE*****: SEE THIS NOTE REGARDING the 404
//http://code.google.com/p/geo-location-javascript/issues/detail?id=48

// Copyright 2007, Google Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Sets up google.gears.*, which is *the only* supported way to access Gears.
//
// Circumvent this file at your own risk!
//
// In the future, Gears may automatically define google.gears.* without this
// file. Gears may use these objects to transparently fix bugs and compatibility
// issues. Applications that use the code below will continue to work seamlessly
// when that happens.

(function() {
  // We are already defined. Hooray!
  if (window.google && google.gears) {
    return;
  }

  var factory = null;

  // Firefox
  if (typeof(GearsFactory)!= 'undefined') {
    factory = new GearsFactory();
  } else {
    // IE
    try {
      factory = new ActiveXObject('Gears.Factory');
      // privateSetGlobalObject is only required and supported on IE Mobile on
      // WinCE.
      if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
        factory.privateSetGlobalObject(this);
      }
    } catch (e) {
      // Safari
      if ((typeof(navigator.mimeTypes) != 'undefined')
           && navigator.mimeTypes["application/x-googlegears"]) {
        factory = document.createElement("object");
        factory.style.display = "none";
        factory.width = 0;
        factory.height = 0;
        factory.type = "application/x-googlegears";
        document.documentElement.appendChild(factory);
        if(factory && (typeof(factory.create) == 'undefined')) {
          // If NP_Initialize() returns an error, factory will still be created.
          // We need to make sure this case doesn't cause Gears to appear to
          // have been initialized.
          factory = null;
        }
      }
    }
  }

  // *Do not* define any objects if Gears is not installed. This mimics the
  // behavior of Gears defining the objects in the future.
  if (!factory) {
    return;
  }

  // Now set up the objects, being careful not to overwrite anything.
  //
  // Note: In Internet Explorer for Windows Mobile, you can't add properties to
  // the window object. However, global objects are automatically added as
  // properties of the window object in all browsers.
  if (!window.google) {
    google = {};
  }

  if (!google.gears) {
    google.gears = {factory: factory};
  }
})();

//
//geo-location-javascript v0.4.8
//http://code.google.com/p/geo-location-javascript/
//
//Copyright (c) 2009 Stan Wiechers
//Licensed under the MIT licenses.
//
//Revision: $Rev: 81 $: 
//Author: $Author: whoisstan $:
//Date: $Date: 2012-04-17 17:50:53 -0400 (Tue, 17 Apr 2012) $:    
//
var bb_success;
var bb_error;
var bb_blackberryTimeout_id=-1;

function handleBlackBerryLocationTimeout()
{
	if(bb_blackberryTimeout_id!=-1)
	{
		bb_error({message:"Timeout error", code:3});
	}
}
function handleBlackBerryLocation()
{
		clearTimeout(bb_blackberryTimeout_id);
		bb_blackberryTimeout_id=-1;
        if (bb_success && bb_error)
        {
                if(blackberry.location.latitude==0 && blackberry.location.longitude==0)
                {
                        //http://dev.w3.org/geo/api/spec-source.html#position_unavailable_error
                        //POSITION_UNAVAILABLE (numeric value 2)
                        bb_error({message:"Position unavailable", code:2});
                }
                else
                {  
                        var timestamp=null;
                        //only available with 4.6 and later
                        //http://na.blackberry.com/eng/deliverables/8861/blackberry_location_568404_11.jsp
                        if (blackberry.location.timestamp)
                        {
                                timestamp=new Date(blackberry.location.timestamp);
                        }
                        bb_success({timestamp:timestamp, coords: {latitude:blackberry.location.latitude,longitude:blackberry.location.longitude}});
                }
                //since blackberry.location.removeLocationUpdate();
                //is not working as described http://na.blackberry.com/eng/deliverables/8861/blackberry_location_removeLocationUpdate_568409_11.jsp
                //the callback are set to null to indicate that the job is done

                bb_success = null;
                bb_error = null;
        }
}

var geo_position_js=function() {

        var pub = {};
        var provider=null;
		var u="undefined";

		pub.showMap = function(latitude,longitude)
		{
			if(typeof(blackberry)!=u)
			{
				blackberry.launch.newMap({"latitude":latitude*100000,"longitude":-longitude*100000});
			}
			else
			{
				window.location="http://maps.google.com/maps?q=loc:"+latitude+","+longitude;
			}
		}


        pub.getCurrentPosition = function(success,error,opts)
        {
                provider.getCurrentPosition(success, error,opts);
        }
		

        pub.init = function()
        {			
                try
                {
                        if (typeof(geo_position_js_simulator)!=u)
                        {
                                provider=geo_position_js_simulator;
                        }
                        else if (typeof(bondi)!=u && typeof(bondi.geolocation)!=u)
                        {
                                provider=bondi.geolocation;
                        }
                        else if (typeof(navigator.geolocation)!=u)
                        {
                                provider=navigator.geolocation;
                                pub.getCurrentPosition = function(success, error, opts)
                                {
                                        function _success(p)
                                        {
                                                //for mozilla geode,it returns the coordinates slightly differently
                                                if(typeof(p.latitude)!=u)
                                                {
                                                        success({timestamp:p.timestamp, coords: {latitude:p.latitude,longitude:p.longitude}});
                                                }
                                                else
                                                {
                                                        success(p);
                                                }
                                        }
                                        provider.getCurrentPosition(_success,error,opts);
                                }
                        }
                        else if(typeof(window.blackberry)!=u && blackberry.location.GPSSupported)
                        {

                                // set to autonomous mode
								if(typeof(blackberry.location.setAidMode)==u)
								{
	                                return false;									
								}
								blackberry.location.setAidMode(2);
                                //override default method implementation
                                pub.getCurrentPosition = function(success,error,opts)
                                {
										//alert(parseFloat(navigator.appVersion));
                                        //passing over callbacks as parameter didn't work consistently
                                        //in the onLocationUpdate method, thats why they have to be set
                                        //outside
                                        bb_success=success;
                                        bb_error=error;
                                        //function needs to be a string according to
                                        //http://www.tonybunce.com/2008/05/08/Blackberry-Browser-Amp-GPS.aspx
										if(opts['timeout'])  
										{
										 	bb_blackberryTimeout_id=setTimeout("handleBlackBerryLocationTimeout()",opts['timeout']);
										}
										else
										//default timeout when none is given to prevent a hanging script
										{
											bb_blackberryTimeout_id=setTimeout("handleBlackBerryLocationTimeout()",60000);
										}										
										blackberry.location.onLocationUpdate("handleBlackBerryLocation()");
                                        blackberry.location.refreshLocation();
                                }
                                provider=blackberry.location;				
                        }
					 	else if(typeof(window.google)!="undefined" && typeof(google.gears)!="undefined")
                        {
                                provider=google.gears.factory.create('beta.geolocation');
                                pub.getCurrentPosition = function(successCallback, errorCallback, options)
                                {
                                        function _successCallback(p)
                                        {
                                                if(typeof(p.latitude)!="undefined")
                                                {
                                                        successCallback({timestamp:p.timestamp, coords: {latitude:p.latitude,longitude:p.longitude}});
                                                }
                                                else
                                                {
                                                        successCallback(p);
                                                }
                                        }
                                        provider.getCurrentPosition(_successCallback,errorCallback,options);
                                }

                        }
                        else if ( typeof(Mojo) !=u && typeof(Mojo.Service.Request)!="Mojo.Service.Request")
                        {
                                provider=true;
                                pub.getCurrentPosition = function(success, error, opts)
                                {

                                parameters={};
                                if(opts)
                                {
                                         //http://developer.palm.com/index.php?option=com_content&view=article&id=1673#GPS-getCurrentPosition
                                         if (opts.enableHighAccuracy && opts.enableHighAccuracy==true)
                                         {
                                                parameters.accuracy=1;
                                         }
                                         if (opts.maximumAge)
                                         {
                                                parameters.maximumAge=opts.maximumAge;
                                         }
                                         if (opts.responseTime)
                                         {
                                                if(opts.responseTime<5)
                                                {
                                                        parameters.responseTime=1;
                                                }
                                                else if (opts.responseTime<20)
                                                {
                                                        parameters.responseTime=2;
                                                }
                                                else
                                                {
                                                        parameters.timeout=3;
                                                }
                                         }
                                }


                                 r=new Mojo.Service.Request('palm://com.palm.location', {
                                        method:"getCurrentPosition",
                                            parameters:parameters,
                                            onSuccess: function(p){success({timestamp:p.timestamp, coords: {latitude:p.latitude, longitude:p.longitude,heading:p.heading}});},
                                            onFailure: function(e){
                                                                if (e.errorCode==1)
                                                                {
                                                                        error({code:3,message:"Timeout"});
                                                                }
                                                                else if (e.errorCode==2)
                                                                {
                                                                        error({code:2,message:"Position unavailable"});
                                                                }
                                                                else
                                                                {
                                                                        error({code:0,message:"Unknown Error: webOS-code"+errorCode});
                                                                }
                                                        }
                                            });
                                }

                        }
                        else if (typeof(device)!=u && typeof(device.getServiceObject)!=u)
                        {
                                provider=device.getServiceObject("Service.Location", "ILocation");

                                //override default method implementation
                                pub.getCurrentPosition = function(success, error, opts)
                                {
                                        function callback(transId, eventCode, result) {
                                            if (eventCode == 4)
                                                {
                                                error({message:"Position unavailable", code:2});
                                            }
                                                else
                                                {
                                                        //no timestamp of location given?
                                                        success({timestamp:null, coords: {latitude:result.ReturnValue.Latitude, longitude:result.ReturnValue.Longitude, altitude:result.ReturnValue.Altitude,heading:result.ReturnValue.Heading}});
                                                }
                                        }
                                        //location criteria
                                    var criteria = new Object();
                                criteria.LocationInformationClass = "BasicLocationInformation";
                                        //make the call
                                        provider.ILocation.GetLocation(criteria,callback);
                                }
                        }

                }
                catch (e){ 
					if(typeof(console)!=u)
					{
						console.log(e);
					}
					return false;
				}
                return  provider!=null;
        }


        return pub;
}();;
/*
 * jQuery Templating Plugin
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */
(function( jQuery, undefined ){
	var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
		newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];

	function newTmplItem( options, parentItem, fn, data ) {
		// Returns a template item data structure for a new rendered instance of a template (a 'template item').
		// The content field is a hierarchical array of strings and nested items (to be
		// removed and replaced by nodes field of dom elements, once inserted in DOM).
		var newItem = {
			data: data || (parentItem ? parentItem.data : {}),
			_wrap: parentItem ? parentItem._wrap : null,
			tmpl: null,
			parent: parentItem || null,
			nodes: [],
			calls: tiCalls,
			nest: tiNest,
			wrap: tiWrap,
			html: tiHtml,
			update: tiUpdate
		};
		if ( options ) {
			jQuery.extend( newItem, options, { nodes: [], parent: parentItem } );
		}
		if ( fn ) {
			// Build the hierarchical content to be used during insertion into DOM
			newItem.tmpl = fn;
			newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem );
			newItem.key = ++itemKey;
			// Keep track of new template item, until it is stored as jQuery Data on DOM element
			(stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
		}
		return newItem;
	}

	// Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
	jQuery.each({
		appendTo: "append",
		prependTo: "prepend",
		insertBefore: "before",
		insertAfter: "after",
		replaceAll: "replaceWith"
	}, function( name, original ) {
		jQuery.fn[ name ] = function( selector ) {
			var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems,
				parent = this.length === 1 && this[0].parentNode;

			appendToTmplItems = newTmplItems || {};
			if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
				insert[ original ]( this[0] );
				ret = this;
			} else {
				for ( i = 0, l = insert.length; i < l; i++ ) {
					cloneIndex = i;
					elems = (i > 0 ? this.clone(true) : this).get();
					jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
					ret = ret.concat( elems );
				}
				cloneIndex = 0;
				ret = this.pushStack( ret, name, insert.selector );
			}
			tmplItems = appendToTmplItems;
			appendToTmplItems = null;
			jQuery.tmpl.complete( tmplItems );
			return ret;
		};
	});

	jQuery.fn.extend({
		// Use first wrapped element as template markup.
		// Return wrapped set of template items, obtained by rendering template against data.
		tmpl: function( data, options, parentItem ) {
			return jQuery.tmpl( this[0], data, options, parentItem );
		},

		// Find which rendered template item the first wrapped DOM element belongs to
		tmplItem: function() {
			return jQuery.tmplItem( this[0] );
		},

		// Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
		template: function( name ) {
			return jQuery.template( name, this[0] );
		},

		domManip: function( args, table, callback, options ) {
			// This appears to be a bug in the appendTo, etc. implementation
			// it should be doing .call() instead of .apply(). See #6227
			if ( args[0] && args[0].nodeType ) {
				var dmArgs = jQuery.makeArray( arguments ), argsLength = args.length, i = 0, tmplItem;
				while ( i < argsLength && !(tmplItem = jQuery.data( args[i++], "tmplItem" ))) {}
				if ( argsLength > 1 ) {
					dmArgs[0] = [jQuery.makeArray( args )];
				}
				if ( tmplItem && cloneIndex ) {
					dmArgs[2] = function( fragClone ) {
						// Handler called by oldManip when rendered template has been inserted into DOM.
						jQuery.tmpl.afterManip( this, fragClone, callback );
					};
				}
				oldManip.apply( this, dmArgs );
			} else {
				oldManip.apply( this, arguments );
			}
			cloneIndex = 0;
			if ( !appendToTmplItems ) {
				jQuery.tmpl.complete( newTmplItems );
			}
			return this;
		}
	});

	jQuery.extend({
		// Return wrapped set of template items, obtained by rendering template against data.
		tmpl: function( tmpl, data, options, parentItem ) {
			var ret, topLevel = !parentItem;
			if ( topLevel ) {
				// This is a top-level tmpl call (not from a nested template using {{tmpl}})
				parentItem = topTmplItem;
				tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
				wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
			} else if ( !tmpl ) {
				// The template item is already associated with DOM - this is a refresh.
				// Re-evaluate rendered template for the parentItem
				tmpl = parentItem.tmpl;
				newTmplItems[parentItem.key] = parentItem;
				parentItem.nodes = [];
				if ( parentItem.wrapped ) {
					updateWrapped( parentItem, parentItem.wrapped );
				}
				// Rebuild, without creating a new template item
				return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
			}
			if ( !tmpl ) {
				return []; // Could throw...
			}
			if ( typeof data === "function" ) {
				data = data.call( parentItem || {} );
			}
			if ( options && options.wrapped ) {
				updateWrapped( options, options.wrapped );
			}
			ret = jQuery.isArray( data ) ? 
				jQuery.map( data, function( dataItem ) {
					return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
				}) :
				[ newTmplItem( options, parentItem, tmpl, data ) ];
			return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
		},

		// Return rendered template item for an element.
		tmplItem: function( elem ) {
			var tmplItem;
			if ( elem instanceof jQuery ) {
				elem = elem[0];
			}
			while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
			return tmplItem || topTmplItem;
		},

		// Set:
		// Use $.template( name, tmpl ) to cache a named template,
		// where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
		// Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.

		// Get:
		// Use $.template( name ) to access a cached template.
		// Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
		// will return the compiled template, without adding a name reference.
		// If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
		// to $.template( null, templateString )
		template: function( name, tmpl ) {
			if (tmpl) {
				// Compile template and associate with name
				if ( typeof tmpl === "string" ) {
					// This is an HTML string being passed directly in.
					tmpl = buildTmplFn( tmpl )
				} else if ( tmpl instanceof jQuery ) {
					tmpl = tmpl[0] || {};
				}
				if ( tmpl.nodeType ) {
					// If this is a template block, use cached copy, or generate tmpl function and cache.
					tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML ));
				}
				return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
			}
			// Return named compiled template
			return name ? (typeof name !== "string" ? jQuery.template( null, name ): 
				(jQuery.template[name] || 
					// If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) 
					jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; 
		},

		encode: function( text ) {
			// Do HTML encoding replacing < > & and ' and " by corresponding entities.
			return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
		}
	});

	jQuery.extend( jQuery.tmpl, {
		tag: {
			"tmpl": {
				_default: { $2: "null" },
				open: "if($notnull_1){_=_.concat($item.nest($1,$2));}"
				// tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
				// This means that {{tmpl foo}} treats foo as a template (which IS a function). 
				// Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
			},
			"wrap": {
				_default: { $2: "null" },
				open: "$item.calls(_,$1,$2);_=[];",
				close: "call=$item.calls();_=call._.concat($item.wrap(call,_));"
			},
			"each": {
				_default: { $2: "$index, $value" },
				open: "if($notnull_1){$.each($1a,function($2){with(this){",
				close: "}});}"
			},
			"if": {
				open: "if(($notnull_1) && $1a){",
				close: "}"
			},
			"else": {
				_default: { $1: "true" },
				open: "}else if(($notnull_1) && $1a){"
			},
			"html": {
				// Unecoded expression evaluation. 
				open: "if($notnull_1){_.push($1a);}"
			},
			"=": {
				// Encoded expression evaluation. Abbreviated form is ${}.
				_default: { $1: "$data" },
				open: "if($notnull_1){_.push($.encode($1a));}"
			},
			"!": {
				// Comment tag. Skipped by parser
				open: ""
			}
		},

		// This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
		complete: function( items ) {
			newTmplItems = {};
		},

		// Call this from code which overrides domManip, or equivalent
		// Manage cloning/storing template items etc.
		afterManip: function afterManip( elem, fragClone, callback ) {
			// Provides cloned fragment ready for fixup prior to and after insertion into DOM
			var content = fragClone.nodeType === 11 ?
				jQuery.makeArray(fragClone.childNodes) :
				fragClone.nodeType === 1 ? [fragClone] : [];

			// Return fragment to original caller (e.g. append) for DOM insertion
			callback.call( elem, fragClone );

			// Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
			storeTmplItems( content );
			cloneIndex++;
		}
	});

	//========================== Private helper functions, used by code above ==========================

	function build( tmplItem, nested, content ) {
		// Convert hierarchical content into flat string array 
		// and finally return array of fragments ready for DOM insertion
		var frag, ret = content ? jQuery.map( content, function( item ) {
			return (typeof item === "string") ? 
				// Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
				(tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) :
				// This is a child template item. Build nested template.
				build( item, tmplItem, item._ctnt );
		}) : 
		// If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. 
		tmplItem;
		if ( nested ) {
			return ret;
		}

		// top-level template
		ret = ret.join("");

		// Support templates which have initial or final text nodes, or consist only of text
		// Also support HTML entities within the HTML markup.
		ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) {
			frag = jQuery( middle ).get();

			storeTmplItems( frag );
			if ( before ) {
				frag = unencode( before ).concat(frag);
			}
			if ( after ) {
				frag = frag.concat(unencode( after ));
			}
		});
		return frag ? frag : unencode( ret );
	}

	function unencode( text ) {
		// Use createElement, since createTextNode will not render HTML entities correctly
		var el = document.createElement( "div" );
		el.innerHTML = text;
		return jQuery.makeArray(el.childNodes);
	}

	// Generate a reusable function that will serve to render a template against data
	function buildTmplFn( markup ) {
		return new Function("jQuery","$item",
			"var $=jQuery,call,_=[],$data=$item.data;" +

			// Introduce the data as local variables using with(){}
			"with($data){_.push('" +

			// Convert the template into pure JavaScript
			jQuery.trim(markup)
				.replace( /([\\'])/g, "\\$1" )
				.replace( /[\r\t\n]/g, " " )
				.replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
				.replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,
				function( all, slash, type, fnargs, target, parens, args ) {
					var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect;
					if ( !tag ) {
						throw "Template command not found: " + type;
					}
					def = tag._default || [];
					if ( parens && !/\w$/.test(target)) {
						target += parens;
						parens = "";
					}
					if ( target ) {
						target = unescape( target ); 
						args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : "");
						// Support for target being things like a.toLowerCase();
						// In that case don't call with template item as 'this' pointer. Just evaluate...
						expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target;
						exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
					} else {
						exprAutoFnDetect = expr = def.$1 || "null";
					}
					fnargs = unescape( fnargs );
					return "');" + 
						tag[ slash ? "close" : "open" ]
							.split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" )
							.split( "$1a" ).join( exprAutoFnDetect )
							.split( "$1" ).join( expr )
							.split( "$2" ).join( fnargs ?
								fnargs.replace( /\s*([^\(]+)\s*(\((.*?)\))?/g, function( all, name, parens, params ) {
									params = params ? ("," + params + ")") : (parens ? ")" : "");
									return params ? ("(" + name + ").call($item" + params) : all;
								})
								: (def.$2||"")
							) +
						"_.push('";
				}) +
			"');}return _;"
		);
	}
	function updateWrapped( options, wrapped ) {
		// Build the wrapped content. 
		options._wrap = build( options, true, 
			// Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
			jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()]
		).join("");
	}

	function unescape( args ) {
		return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
	}
	function outerHtml( elem ) {
		var div = document.createElement("div");
		div.appendChild( elem.cloneNode(true) );
		return div.innerHTML;
	}

	// Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
	function storeTmplItems( content ) {
		var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
		for ( i = 0, l = content.length; i < l; i++ ) {
			if ( (elem = content[i]).nodeType !== 1 ) {
				continue;
			}
			elems = elem.getElementsByTagName("*");
			for ( m = elems.length - 1; m >= 0; m-- ) {
				processItemKey( elems[m] );
			}
			processItemKey( elem );
		}
		function processItemKey( el ) {
			var pntKey, pntNode = el, pntItem, tmplItem, key;
			// Ensure that each rendered template inserted into the DOM has its own template item,
			if ( (key = el.getAttribute( tmplItmAtt ))) {
				while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { }
				if ( pntKey !== key ) {
					// The next ancestor with a _tmplitem expando is on a different key than this one.
					// So this is a top-level element within this template item
					// Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment.
					pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0;
					if ( !(tmplItem = newTmplItems[key]) ) {
						// The item is for wrapped content, and was copied from the temporary parent wrappedItem.
						tmplItem = wrappedItems[key];
						tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode], null, true );
						tmplItem.key = ++itemKey;
						newTmplItems[itemKey] = tmplItem;
					}
					if ( cloneIndex ) {
						cloneTmplItem( key );
					}
				}
				el.removeAttribute( tmplItmAtt );
			} else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) {
				// This was a rendered element, cloned during append or appendTo etc.
				// TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
				cloneTmplItem( tmplItem.key );
				newTmplItems[tmplItem.key] = tmplItem;
				pntNode = jQuery.data( el.parentNode, "tmplItem" );
				pntNode = pntNode ? pntNode.key : 0;
			}
			if ( tmplItem ) {
				pntItem = tmplItem;
				// Find the template item of the parent element. 
				// (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
				while ( pntItem && pntItem.key != pntNode ) { 
					// Add this element as a top-level node for this rendered template item, as well as for any
					// ancestor items between this item and the item of its parent element
					pntItem.nodes.push( el );
					pntItem = pntItem.parent;
				}
				// Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
				delete tmplItem._ctnt;
				delete tmplItem._wrap;
				// Store template item as jQuery data on the element
				jQuery.data( el, "tmplItem", tmplItem );
			}
			function cloneTmplItem( key ) {
				key = key + keySuffix;
				tmplItem = newClonedItems[key] = 
					(newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true ));
			}
		}
	}

	//---- Helper functions for template item ----

	function tiCalls( content, tmpl, data, options ) {
		if ( !content ) {
			return stack.pop();
		}
		stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
	}

	function tiNest( tmpl, data, options ) {
		// nested template, using {{tmpl}} tag
		return jQuery.tmpl( jQuery.template( tmpl ), data, options, this );
	}

	function tiWrap( call, wrapped ) {
		// nested template, using {{wrap}} tag
		var options = call.options || {};
		options.wrapped = wrapped;
		// Apply the template, which may incorporate wrapped content, 
		return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item );
	}

	function tiHtml( filter, textOnly ) {
		var wrapped = this._wrap;
		return jQuery.map(
			jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ),
			function(e) {
				return textOnly ?
					e.innerText || e.textContent :
					e.outerHTML || outerHtml(e);
			});
	}

	function tiUpdate() {
		var coll = this.nodes;
		jQuery.tmpl( null, null, null, this).insertBefore( coll[0] );
		jQuery( coll ).remove();
	}
})( jQuery );
;
/*! Backstretch - v2.0.4 - 2013-06-19
* http://srobbin.com/jquery-plugins/backstretch/
* Copyright (c) 2013 Scott Robbin; Licensed MIT */

;(function ($, window, undefined) {
  'use strict';

  /* PLUGIN DEFINITION
   * ========================= */

  $.fn.backstretch = function (images, options) {
    // We need at least one image or method name
    if (images === undefined || images.length === 0) {
      $.error("No images were supplied for Backstretch");
    }

    /*
     * Scroll the page one pixel to get the right window height on iOS
     * Pretty harmless for everyone else
    */
    if ($(window).scrollTop() === 0 ) {
      window.scrollTo(0, 0);
    }

    return this.each(function () {
      var $this = $(this)
        , obj = $this.data('backstretch');

      // Do we already have an instance attached to this element?
      if (obj) {

        // Is this a method they're trying to execute?
        if (typeof images == 'string' && typeof obj[images] == 'function') {
          // Call the method
          obj[images](options);

          // No need to do anything further
          return;
        }

        // Merge the old options with the new
        options = $.extend(obj.options, options);

        // Remove the old instance
        obj.destroy(true);
      }

      obj = new Backstretch(this, images, options);
      $this.data('backstretch', obj);
    });
  };

  // If no element is supplied, we'll attach to body
  $.backstretch = function (images, options) {
    // Return the instance
    return $('body')
            .backstretch(images, options)
            .data('backstretch');
  };

  // Custom selector
  $.expr[':'].backstretch = function(elem) {
    return $(elem).data('backstretch') !== undefined;
  };

  /* DEFAULTS
   * ========================= */

  $.fn.backstretch.defaults = {
      centeredX: true   // Should we center the image on the X axis?
    , centeredY: true   // Should we center the image on the Y axis?
    , duration: 5000    // Amount of time in between slides (if slideshow)
    , fade: 0           // Speed of fade transition between slides
  };

  /* STYLES
   * 
   * Baked-in styles that we'll apply to our elements.
   * In an effort to keep the plugin simple, these are not exposed as options.
   * That said, anyone can override these in their own stylesheet.
   * ========================= */
  var styles = {
      wrap: {
          left: 0
        , top: 0
        , overflow: 'hidden'
        , margin: 0
        , padding: 0
        , height: '100%'
        , width: '100%'
        , zIndex: -999999
      }
    , img: {
          position: 'absolute'
        , display: 'none'
        , margin: 0
        , padding: 0
        , border: 'none'
        , width: 'auto'
        , height: 'auto'
        , maxHeight: 'none'
        , maxWidth: 'none'
        , zIndex: -999999
      }
  };

  /* CLASS DEFINITION
   * ========================= */
  var Backstretch = function (container, images, options) {
    this.options = $.extend({}, $.fn.backstretch.defaults, options || {});

    /* In its simplest form, we allow Backstretch to be called on an image path.
     * e.g. $.backstretch('/path/to/image.jpg')
     * So, we need to turn this back into an array.
     */
    this.images = $.isArray(images) ? images : [images];

    // Preload images
    $.each(this.images, function () {
      $('<img />')[0].src = this;
    });    

    // Convenience reference to know if the container is body.
    this.isBody = container === document.body;

    /* We're keeping track of a few different elements
     *
     * Container: the element that Backstretch was called on.
     * Wrap: a DIV that we place the image into, so we can hide the overflow.
     * Root: Convenience reference to help calculate the correct height.
     */
    this.$container = $(container);
    this.$root = this.isBody ? supportsFixedPosition ? $(window) : $(document) : this.$container;

    // Don't create a new wrap if one already exists (from a previous instance of Backstretch)
    var $existing = this.$container.children(".backstretch").first();
    this.$wrap = $existing.length ? $existing : $('<div class="backstretch"></div>').css(styles.wrap).appendTo(this.$container);

    // Non-body elements need some style adjustments
    if (!this.isBody) {
      // If the container is statically positioned, we need to make it relative,
      // and if no zIndex is defined, we should set it to zero.
      var position = this.$container.css('position')
        , zIndex = this.$container.css('zIndex');

      this.$container.css({
          position: position === 'static' ? 'relative' : position
        , zIndex: zIndex === 'auto' ? 0 : zIndex
        , background: 'none'
      });
      
      // Needs a higher z-index
      this.$wrap.css({zIndex: -999998});
    }

    // Fixed or absolute positioning?
    this.$wrap.css({
      position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute'
    });

    // Set the first image
    this.index = 0;
    this.show(this.index);

    // Listen for resize
    $(window).on('resize.backstretch', $.proxy(this.resize, this))
             .on('orientationchange.backstretch', $.proxy(function () {
                // Need to do this in order to get the right window height
                if (this.isBody && window.pageYOffset === 0) {
                  window.scrollTo(0, 1);
                  this.resize();
                }
             }, this));
  };

  /* PUBLIC METHODS
   * ========================= */
  Backstretch.prototype = {
      resize: function () {
        try {
          var bgCSS = {left: 0, top: 0}
            , rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth()
            , bgWidth = rootWidth
            , rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHeight()
            , bgHeight = bgWidth / this.$img.data('ratio')
            , bgOffset;

            // Make adjustments based on image ratio
            if (bgHeight >= rootHeight) {
                bgOffset = (bgHeight - rootHeight) / 2;
                if(this.options.centeredY) {
                  bgCSS.top = '-' + bgOffset + 'px';
                }
            } else {
                bgHeight = rootHeight;
                bgWidth = bgHeight * this.$img.data('ratio');
                bgOffset = (bgWidth - rootWidth) / 2;
                if(this.options.centeredX) {
                  bgCSS.left = '-' + bgOffset + 'px';
                }
            }

            this.$wrap.css({width: rootWidth, height: rootHeight})
                      .find('img:not(.deleteable)').css({width: bgWidth, height: bgHeight}).css(bgCSS);
        } catch(err) {
            // IE7 seems to trigger resize before the image is loaded.
            // This try/catch block is a hack to let it fail gracefully.
        }

        return this;
      }

      // Show the slide at a certain position
    , show: function (newIndex) {

        // Validate index
        if (Math.abs(newIndex) > this.images.length - 1) {
          return;
        }

        // Vars
        var self = this
          , oldImage = self.$wrap.find('img').addClass('deleteable')
          , evtOptions = { relatedTarget: self.$container[0] };

        // Trigger the "before" event
        self.$container.trigger($.Event('backstretch.before', evtOptions), [self, newIndex]); 

        // Set the new index
        this.index = newIndex;

        // Pause the slideshow
        clearInterval(self.interval);

        // New image
        self.$img = $('<img />')
                      .css(styles.img)
                      .bind('load', function (e) {
                        var imgWidth = this.width || $(e.target).width()
                          , imgHeight = this.height || $(e.target).height();
                        
                        // Save the ratio
                        $(this).data('ratio', imgWidth / imgHeight);

                        // Show the image, then delete the old one
                        // "speed" option has been deprecated, but we want backwards compatibilty
                        $(this).fadeIn(self.options.speed || self.options.fade, function () {
                          oldImage.remove();

                          // Resume the slideshow
                          if (!self.paused) {
                            self.cycle();
                          }

                          // Trigger the "after" and "show" events
                          // "show" is being deprecated
                          $(['after', 'show']).each(function () {
                            self.$container.trigger($.Event('backstretch.' + this, evtOptions), [self, newIndex]);
                          });
                        });

                        // Resize
                        self.resize();
                      })
                      .appendTo(self.$wrap);

        // Hack for IE img onload event
        self.$img.attr('src', self.images[newIndex]);
        return self;
      }

    , next: function () {
        // Next slide
        return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0);
      }

    , prev: function () {
        // Previous slide
        return this.show(this.index === 0 ? this.images.length - 1 : this.index - 1);
      }

    , pause: function () {
        // Pause the slideshow
        this.paused = true;
        return this;
      }

    , resume: function () {
        // Resume the slideshow
        this.paused = false;
        this.next();
        return this;
      }

    , cycle: function () {
        // Start/resume the slideshow
        if(this.images.length > 1) {
          // Clear the interval, just in case
          clearInterval(this.interval);

          this.interval = setInterval($.proxy(function () {
            // Check for paused slideshow
            if (!this.paused) {
              this.next();
            }
          }, this), this.options.duration);
        }
        return this;
      }

    , destroy: function (preserveBackground) {
        // Stop the resize events
        $(window).off('resize.backstretch orientationchange.backstretch');

        // Clear the interval
        clearInterval(this.interval);

        // Remove Backstretch
        if(!preserveBackground) {
          this.$wrap.remove();          
        }
        this.$container.removeData('backstretch');
      }
  };

  /* SUPPORTS FIXED POSITION?
   *
   * Based on code from jQuery Mobile 1.1.0
   * http://jquerymobile.com/
   *
   * In a nutshell, we need to figure out if fixed positioning is supported.
   * Unfortunately, this is very difficult to do on iOS, and usually involves
   * injecting content, scrolling the page, etc.. It's ugly.
   * jQuery Mobile uses this workaround. It's not ideal, but works.
   *
   * Modified to detect IE6
   * ========================= */

  var supportsFixedPosition = (function () {
    var ua = navigator.userAgent
      , platform = navigator.platform
        // Rendering engine is Webkit, and capture major version
      , wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ )
      , wkversion = !!wkmatch && wkmatch[ 1 ]
      , ffmatch = ua.match( /Fennec\/([0-9]+)/ )
      , ffversion = !!ffmatch && ffmatch[ 1 ]
      , operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ )
      , omversion = !!operammobilematch && operammobilematch[ 1 ]
      , iematch = ua.match( /MSIE ([0-9]+)/ )
      , ieversion = !!iematch && iematch[ 1 ];

    return !(
      // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
      ((platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1  || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534) ||
      
      // Opera Mini
      (window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]") ||
      (operammobilematch && omversion < 7458) ||
      
      //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
      (ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533) ||
      
      // Firefox Mobile before 6.0 -
      (ffversion && ffversion < 6) ||
      
      // WebOS less than 3
      ("palmGetResource" in window && wkversion && wkversion < 534) ||
      
      // MeeGo
      (ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1) ||
      
      // IE6
      (ieversion && ieversion <= 6)
    );
  }());

}(jQuery, window));;
//*MODIFIED With Name Space for Destroy Method*//
/////////////////////////////////////////////////////////////////
//https://github.com/davatron5000/FitText.js/issues/66
////////////////////////////////////////////////////////////////

//*MODIFIED Resize*//
/////////////////////////////////////////////////////////////////
//http://stackoverflow.com/questions/11533945/fittext-will-only-work-when-window-is-resized
////////////////////////////////////////////////////////////////




/*global jQuery */
/*!
* FitText.js 1.2
*
* Copyright 2011, Dave Rupert http://daverupert.com
* Released under the WTFPL license
* http://sam.zoy.org/wtfpl/
*
* Date: Thu May 05 14:23:00 2011 -0600
*/

(function( $ ){

  $.fn.fitText = function( kompressor, options ) {

    // Setup options
    var compressor = kompressor || 1,
        settings = $.extend({
          'minFontSize' : Number.NEGATIVE_INFINITY,
          'maxFontSize' : Number.POSITIVE_INFINITY,
          'id' : 'global'
        }, options);

    return this.each(function(){

      // Store the object
      var $this = $(this);

      // Resizer() resizes items based on the object width divided by the compressor * 10
      var resizer = function () {
        $this.css('font-size', Math.max(Math.min($this.width() / (compressor*10), parseFloat(settings.maxFontSize)), parseFloat(settings.minFontSize)));
      };

      // Call once to set.
      //resizer();
		$(window).load(function(){
			resizer();
		});

      // Call on resize. Opera debounces their resize by default.
      //$(window).on('resize.fittext orientationchange.fittext', resizer);
	  $(window).on('resize.fittext.' + settings.id + ' orientationchange.fittext.' + settings.id, resizer);


    });

  };

})( jQuery );
;
/* Coded by Ramswaroop */
(function(e){e.easing["jswing"]=e.easing["swing"];e.extend(e.easing,{def:"easeOutQuad",swing:function(t,n,r,i,s){return e.easing[e.easing.def](t,n,r,i,s)},easeInQuad:function(e,t,n,r,i){return r*(t/=i)*t+n},easeOutQuad:function(e,t,n,r,i){return-r*(t/=i)*(t-2)+n},easeInOutQuad:function(e,t,n,r,i){if((t/=i/2)<1)return r/2*t*t+n;return-r/2*(--t*(t-2)-1)+n},easeInCubic:function(e,t,n,r,i){return r*(t/=i)*t*t+n},easeOutCubic:function(e,t,n,r,i){return r*((t=t/i-1)*t*t+1)+n},easeInOutCubic:function(e,t,n,r,i){if((t/=i/2)<1)return r/2*t*t*t+n;return r/2*((t-=2)*t*t+2)+n},easeInQuart:function(e,t,n,r,i){return r*(t/=i)*t*t*t+n},easeOutQuart:function(e,t,n,r,i){return-r*((t=t/i-1)*t*t*t-1)+n},easeInOutQuart:function(e,t,n,r,i){if((t/=i/2)<1)return r/2*t*t*t*t+n;return-r/2*((t-=2)*t*t*t-2)+n},easeInQuint:function(e,t,n,r,i){return r*(t/=i)*t*t*t*t+n},easeOutQuint:function(e,t,n,r,i){return r*((t=t/i-1)*t*t*t*t+1)+n},easeInOutQuint:function(e,t,n,r,i){if((t/=i/2)<1)return r/2*t*t*t*t*t+n;return r/2*((t-=2)*t*t*t*t+2)+n},easeInSine:function(e,t,n,r,i){return-r*Math.cos(t/i*(Math.PI/2))+r+n},easeOutSine:function(e,t,n,r,i){return r*Math.sin(t/i*(Math.PI/2))+n},easeInOutSine:function(e,t,n,r,i){return-r/2*(Math.cos(Math.PI*t/i)-1)+n},easeInExpo:function(e,t,n,r,i){return t==0?n:r*Math.pow(2,10*(t/i-1))+n},easeOutExpo:function(e,t,n,r,i){return t==i?n+r:r*(-Math.pow(2,-10*t/i)+1)+n},easeInOutExpo:function(e,t,n,r,i){if(t==0)return n;if(t==i)return n+r;if((t/=i/2)<1)return r/2*Math.pow(2,10*(t-1))+n;return r/2*(-Math.pow(2,-10*--t)+2)+n},easeInCirc:function(e,t,n,r,i){return-r*(Math.sqrt(1-(t/=i)*t)-1)+n},easeOutCirc:function(e,t,n,r,i){return r*Math.sqrt(1-(t=t/i-1)*t)+n},easeInOutCirc:function(e,t,n,r,i){if((t/=i/2)<1)return-r/2*(Math.sqrt(1-t*t)-1)+n;return r/2*(Math.sqrt(1-(t-=2)*t)+1)+n},easeInElastic:function(e,t,n,r,i){var s=1.70158;var o=0;var u=r;if(t==0)return n;if((t/=i)==1)return n+r;if(!o)o=i*.3;if(u<Math.abs(r)){u=r;var s=o/4}else var s=o/(2*Math.PI)*Math.asin(r/u);return-(u*Math.pow(2,10*(t-=1))*Math.sin((t*i-s)*2*Math.PI/o))+n},easeOutElastic:function(e,t,n,r,i){var s=1.70158;var o=0;var u=r;if(t==0)return n;if((t/=i)==1)return n+r;if(!o)o=i*.3;if(u<Math.abs(r)){u=r;var s=o/4}else var s=o/(2*Math.PI)*Math.asin(r/u);return u*Math.pow(2,-10*t)*Math.sin((t*i-s)*2*Math.PI/o)+r+n},easeInOutElastic:function(e,t,n,r,i){var s=1.70158;var o=0;var u=r;if(t==0)return n;if((t/=i/2)==2)return n+r;if(!o)o=i*.3*1.5;if(u<Math.abs(r)){u=r;var s=o/4}else var s=o/(2*Math.PI)*Math.asin(r/u);if(t<1)return-.5*u*Math.pow(2,10*(t-=1))*Math.sin((t*i-s)*2*Math.PI/o)+n;return u*Math.pow(2,-10*(t-=1))*Math.sin((t*i-s)*2*Math.PI/o)*.5+r+n},easeInBack:function(e,t,n,r,i,s){if(s==undefined)s=1.70158;return r*(t/=i)*t*((s+1)*t-s)+n},easeOutBack:function(e,t,n,r,i,s){if(s==undefined)s=1.70158;return r*((t=t/i-1)*t*((s+1)*t+s)+1)+n},easeInOutBack:function(e,t,n,r,i,s){if(s==undefined)s=1.70158;if((t/=i/2)<1)return r/2*t*t*(((s*=1.525)+1)*t-s)+n;return r/2*((t-=2)*t*(((s*=1.525)+1)*t+s)+2)+n},easeInBounce:function(t,n,r,i,s){return i-e.easing.easeOutBounce(t,s-n,0,i,s)+r},easeOutBounce:function(e,t,n,r,i){if((t/=i)<1/2.75){return r*7.5625*t*t+n}else if(t<2/2.75){return r*(7.5625*(t-=1.5/2.75)*t+.75)+n}else if(t<2.5/2.75){return r*(7.5625*(t-=2.25/2.75)*t+.9375)+n}else{return r*(7.5625*(t-=2.625/2.75)*t+.984375)+n}},easeInOutBounce:function(t,n,r,i,s){if(n<s/2)return e.easing.easeInBounce(t,n*2,0,i,s)*.5+r;return e.easing.easeOutBounce(t,n*2-s,0,i,s)*.5+i*.5+r}});e.fn.animatescroll=function(t){var n=e.extend({},e.fn.animatescroll.defaults,t);if(typeof n.onScrollStart=="function"){n.onScrollStart.call(this)}if(n.element=="html,body"){var r=this.offset().top;e(n.element).stop().animate({scrollTop:r-n.padding},n.scrollSpeed,n.easing)}else{e(n.element).stop().animate({scrollTop:this.offset().top-this.parent().offset().top+this.parent().scrollTop()-n.padding},n.scrollSpeed,n.easing)}setTimeout(function(){if(typeof n.onScrollEnd=="function"){n.onScrollEnd.call(this)}},n.scrollSpeed)};e.fn.animatescroll.defaults={easing:"swing",scrollSpeed:800,padding:0,element:"html,body"}})(jQuery);
// Sticky Plugin v1.0.2 for jQuery
// =============
// Author: Anthony Garand
// Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
// Improvements by Leonardo C. Daronco (daronco)
// Created: 2/14/2011
// Date: 16/04/2015
// Website: http://labs.anthonygarand.com/sticky
// Description: Makes an element on the page stick on the screen as you scroll
//       It will only set the 'top' and 'position' of your element, you
//       might need to adjust the width in some cases.

(function($) {
    var slice = Array.prototype.slice; // save ref to original slice()
    var splice = Array.prototype.splice; // save ref to original slice()

  var defaults = {
      topSpacing: 0,
      bottomSpacing: 0,
      className: 'is-sticky',
      wrapperClassName: 'sticky-wrapper',
      center: false,
      getWidthFrom: '',
      widthFromWrapper: true, // works only when .getWidthFrom is empty
      responsiveWidth: false
    },
    $window = $(window),
    $document = $(document),
    sticked = [],
    windowHeight = $window.height(),
    scroller = function() {
      var scrollTop = $window.scrollTop(),
        documentHeight = $document.height(),
        dwh = documentHeight - windowHeight,
        extra = (scrollTop > dwh) ? dwh - scrollTop : 0;

      for (var i = 0; i < sticked.length; i++) {
        var s = sticked[i],
          elementTop = s.stickyWrapper.offset().top,
          etse = elementTop - s.topSpacing - extra;

        if (scrollTop <= etse) {
          if (s.currentTop !== null) {
            s.stickyElement
              .css({
                'width': '',
                'position': '',
                'top': ''
              });
            s.stickyElement.parent().removeClass(s.className);
            s.stickyElement.trigger('sticky-end', [s]);
            s.currentTop = null;
          }
        }
        else {
          var newTop = documentHeight - s.stickyElement.outerHeight()
            - s.topSpacing - s.bottomSpacing - scrollTop - extra;
          if (newTop < 0) {
            newTop = newTop + s.topSpacing;
          } else {
            newTop = s.topSpacing;
          }
          if (s.currentTop != newTop) {
            var newWidth;
            if ( s.getWidthFrom ) {
                newWidth = $(s.getWidthFrom).width() || null;
            }
            else if(s.widthFromWrapper) {
                newWidth = s.stickyWrapper.width();
            }
            if ( newWidth == null ) {
                newWidth = s.stickyElement.width();
            }
            s.stickyElement
              .css('width', newWidth)
              .css('position', 'fixed')
              .css('top', newTop);

            s.stickyElement.parent().addClass(s.className);

            if (s.currentTop === null) {
              s.stickyElement.trigger('sticky-start', [s]);
            } else {
              // sticky is started but it have to be repositioned
              s.stickyElement.trigger('sticky-update', [s]);
            }

            if (s.currentTop === s.topSpacing && s.currentTop > newTop || s.currentTop === null && newTop < s.topSpacing) {
              // just reached bottom || just started to stick but bottom is already reached
              s.stickyElement.trigger('sticky-bottom-reached', [s]);
            } else if(s.currentTop !== null && newTop === s.topSpacing && s.currentTop < newTop) {
              // sticky is started && sticked at topSpacing && overflowing from top just finished
              s.stickyElement.trigger('sticky-bottom-unreached', [s]);
            }

            s.currentTop = newTop;
          }
        }
      }
    },
    resizer = function() {
      windowHeight = $window.height();

      for (var i = 0; i < sticked.length; i++) {
        var s = sticked[i];
        var newWidth = null;
        if ( s.getWidthFrom ) {
            if ( s.responsiveWidth === true ) {
                newWidth = $(s.getWidthFrom).width();
            }
        }
        else if(s.widthFromWrapper) {
            newWidth = s.stickyWrapper.width();
        }
        if ( newWidth != null ) {
            s.stickyElement.css('width', newWidth);
        }
      }
    },
    methods = {
      init: function(options) {
        var o = $.extend({}, defaults, options);
        return this.each(function() {
          var stickyElement = $(this);

          var stickyId = stickyElement.attr('id');
          var stickyHeight = stickyElement.outerHeight();
          var wrapperId = stickyId ? stickyId + '-' + defaults.wrapperClassName : defaults.wrapperClassName
          var wrapper = $('<div></div>')
            .attr('id', wrapperId)
            .addClass(o.wrapperClassName);

          stickyElement.wrapAll(wrapper);

          var stickyWrapper = stickyElement.parent();

          if (o.center) {
            stickyWrapper.css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"});
          }

          if (stickyElement.css("float") == "right") {
            stickyElement.css({"float":"none"}).parent().css({"float":"right"});
          }

          stickyWrapper.css('height', stickyHeight);

          o.stickyElement = stickyElement;
          o.stickyWrapper = stickyWrapper;
          o.currentTop    = null;

          sticked.push(o);
        });
      },
      update: scroller,
      unstick: function(options) {
        return this.each(function() {
          var that = this;
          var unstickyElement = $(that);

          var removeIdx = -1;
          var i = sticked.length;
          while ( i-- > 0 )
          {
            if (sticked[i].stickyElement.get(0) === that)
            {
                splice.call(sticked,i,1);
                removeIdx = i;
            }
          }
          if(removeIdx != -1)
          {
            unstickyElement.unwrap();
            unstickyElement
              .css({
                'width': '',
                'position': '',
                'top': '',
                'float': ''
              })
            ;
          }
        });
      }
    };

  // should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
  if (window.addEventListener) {
    window.addEventListener('scroll', scroller, false);
    window.addEventListener('resize', resizer, false);
  } else if (window.attachEvent) {
    window.attachEvent('onscroll', scroller);
    window.attachEvent('onresize', resizer);
  }

  $.fn.sticky = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.sticky');
    }
  };

  $.fn.unstick = function(method) {
    if (methods[method]) {
      return methods[method].apply(this, slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method ) {
      return methods.unstick.apply( this, arguments );
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.sticky');
    }

  };
  $(function() {
    setTimeout(scroller, 0);
  });
})(jQuery);
;

// $(".selector").disable(true|false)
//
//      same thing as $(".selector").attr("disable", true|false)
//      but looks nicer, and (more importantly) will disable
//      autocombos, buttons and datepickers, which need to 
//      be called differently.
//
//      Also, by giving a reason ($(el).disable("myReason", true))
//      the element will remain disabled until those reasons
//      have been removed ($(el).disable("myReason", false))
//      and there are no more reasons to be disabled.
//
(function ($) {

    $.fn.disable = function (reason, d) {
        // default to true
        d = (d != false);

        if (reason === true || reason === false) {
            // only one parameter specified, use it as the 
            // disable flag
            d = reason;
            reason = null;
        }

        return this.each(function () {
            if ($(this).attr("type") == "hidden")
                return true;

            var reasons = $(this).data("disable.reasons");
            if (reasons == null)
                reasons = [];

            var reasonIdx = (reason && reasons ? $.inArray(reason, reasons) : -1);

            if (!d) {
                if (reasonIdx >= 0) {
                    $(this).data("disable.reasons", reasons);
                    reasons.splice(reasonIdx, 1);
                }

                // we're enabling, but there are still reasons to keep it disabled
                if (reasons.length)
                    return true;
            }

            if (d) {
                // disabling, add this reason to the rest
                if (reason && reasonIdx == -1)
                    reasons.push(reason);

                $(this).data("disable.reasons", reasons);
            }

            
            $(this).attr("disabled", d);

            if ($(this).data("button")) {
                $(this).button(d ? "disable" : "enable");
            }

            if ($(this).data("datepicker")) {
                $(this).datepicker(d ? "disable" : "enable");
            }

            if ($(this).data("autocombo")) {
                $(this).autocombo("option", "disabled", d);
            }


        });

    };

})(jQuery);

;
/*!
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
// 
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub       - http://github.com/cowboy/jquery-hashchange/
// Source       - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified)   - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
// 
// About: License
// 
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
// 
// About: Examples
// 
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
// 
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
// 
// About: Support and Testing
// 
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
// 
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
//                   Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests      - http://benalman.com/code/projects/jquery-hashchange/unit/
// 
// About: Known issues
// 
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
// 
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
// 
// Also note that should a browser natively support the window.onhashchange 
// event, but not report that it does, the fallback polling loop will be used.
// 
// About: Release History
// 
// 1.3   - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
//         "removable" for mobile-only development. Added IE6/7 document.title
//         support. Attempted to make Iframe as hidden as possible by using
//         techniques from http://www.paciellogroup.com/blog/?p=604. Added 
//         support for the "shortcut" format $(window).hashchange( fn ) and
//         $(window).hashchange() like jQuery provides for built-in events.
//         Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
//         lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
//         and <jQuery.fn.hashchange.src> properties plus document-domain.html
//         file to address access denied issues when setting document.domain in
//         IE6/7.
// 1.2   - (2/11/2010) Fixed a bug where coming back to a page using this plugin
//         from a page on another domain would cause an error in Safari 4. Also,
//         IE6/7 Iframe is now inserted after the body (this actually works),
//         which prevents the page from scrolling when the event is first bound.
//         Event can also now be bound before DOM ready, but it won't be usable
//         before then in IE6/7.
// 1.1   - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
//         where browser version is incorrectly reported as 8.0, despite
//         inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0   - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
//         window.onhashchange functionality into a separate plugin for users
//         who want just the basic event & back button support, without all the
//         extra awesomeness that BBQ provides. This plugin will be included as
//         part of jQuery BBQ, but also be available separately.

(function($,window,undefined){
  '$:nomunge'; // Used by YUI compressor.
  
  // Reused string.
  var str_hashchange = 'hashchange',
    
    // Method / object references.
    doc = document,
    fake_onhashchange,
    special = $.event.special,
    
    // Does the browser support window.onhashchange? Note that IE8 running in
    // IE7 compatibility mode reports true for 'onhashchange' in window, even
    // though the event isn't supported, so also test document.documentMode.
    doc_mode = doc.documentMode,
    supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
  
  // Get location.hash (or what you'd expect location.hash to be) sans any
  // leading #. Thanks for making this necessary, Firefox!
  function get_fragment( url ) {
    url = url || location.href;
    return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
  };
  
  // Method: jQuery.fn.hashchange
  // 
  // Bind a handler to the window.onhashchange event or trigger all bound
  // window.onhashchange event handlers. This behavior is consistent with
  // jQuery's built-in event handlers.
  // 
  // Usage:
  // 
  // > jQuery(window).hashchange( [ handler ] );
  // 
  // Arguments:
  // 
  //  handler - (Function) Optional handler to be bound to the hashchange
  //    event. This is a "shortcut" for the more verbose form:
  //    jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
  //    all bound window.onhashchange event handlers will be triggered. This
  //    is a shortcut for the more verbose
  //    jQuery(window).trigger( 'hashchange' ). These forms are described in
  //    the <hashchange event> section.
  // 
  // Returns:
  // 
  //  (jQuery) The initial jQuery collection of elements.
  
  // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
  // $(elem).hashchange() for triggering, like jQuery does for built-in events.
  $.fn[ str_hashchange ] = function( fn ) {
    return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
  };
  
  // Property: jQuery.fn.hashchange.delay
  // 
  // The numeric interval (in milliseconds) at which the <hashchange event>
  // polling loop executes. Defaults to 50.
  
  // Property: jQuery.fn.hashchange.domain
  // 
  // If you're setting document.domain in your JavaScript, and you want hash
  // history to work in IE6/7, not only must this property be set, but you must
  // also set document.domain BEFORE jQuery is loaded into the page. This
  // property is only applicable if you are supporting IE6/7 (or IE8 operating
  // in "IE7 compatibility" mode).
  // 
  // In addition, the <jQuery.fn.hashchange.src> property must be set to the
  // path of the included "document-domain.html" file, which can be renamed or
  // modified if necessary (note that the document.domain specified must be the
  // same in both your main JavaScript as well as in this file).
  // 
  // Usage:
  // 
  // jQuery.fn.hashchange.domain = document.domain;
  
  // Property: jQuery.fn.hashchange.src
  // 
  // If, for some reason, you need to specify an Iframe src file (for example,
  // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
  // do so using this property. Note that when using this property, history
  // won't be recorded in IE6/7 until the Iframe src file loads. This property
  // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
  // compatibility" mode).
  // 
  // Usage:
  // 
  // jQuery.fn.hashchange.src = 'path/to/file.html';
  
  $.fn[ str_hashchange ].delay = 50;
  /*
  $.fn[ str_hashchange ].domain = null;
  $.fn[ str_hashchange ].src = null;
  */
  
  // Event: hashchange event
  // 
  // Fired when location.hash changes. In browsers that support it, the native
  // HTML5 window.onhashchange event is used, otherwise a polling loop is
  // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
  // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
  // compatibility" mode), a hidden Iframe is created to allow the back button
  // and hash-based history to work.
  // 
  // Usage as described in <jQuery.fn.hashchange>:
  // 
  // > // Bind an event handler.
  // > jQuery(window).hashchange( function(e) {
  // >   var hash = location.hash;
  // >   ...
  // > });
  // > 
  // > // Manually trigger the event handler.
  // > jQuery(window).hashchange();
  // 
  // A more verbose usage that allows for event namespacing:
  // 
  // > // Bind an event handler.
  // > jQuery(window).bind( 'hashchange', function(e) {
  // >   var hash = location.hash;
  // >   ...
  // > });
  // > 
  // > // Manually trigger the event handler.
  // > jQuery(window).trigger( 'hashchange' );
  // 
  // Additional Notes:
  // 
  // * The polling loop and Iframe are not created until at least one handler
  //   is actually bound to the 'hashchange' event.
  // * If you need the bound handler(s) to execute immediately, in cases where
  //   a location.hash exists on page load, via bookmark or page refresh for
  //   example, use jQuery(window).hashchange() or the more verbose 
  //   jQuery(window).trigger( 'hashchange' ).
  // * The event can be bound before DOM ready, but since it won't be usable
  //   before then in IE6/7 (due to the necessary Iframe), recommended usage is
  //   to bind it inside a DOM ready handler.
  
  // Override existing $.event.special.hashchange methods (allowing this plugin
  // to be defined after jQuery BBQ in BBQ's source code).
  special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
    
    // Called only when the first 'hashchange' event is bound to window.
    setup: function() {
      // If window.onhashchange is supported natively, there's nothing to do..
      if ( supports_onhashchange ) { return false; }
      
      // Otherwise, we need to create our own. And we don't want to call this
      // until the user binds to the event, just in case they never do, since it
      // will create a polling loop and possibly even a hidden Iframe.
      $( fake_onhashchange.start );
    },
    
    // Called only when the last 'hashchange' event is unbound from window.
    teardown: function() {
      // If window.onhashchange is supported natively, there's nothing to do..
      if ( supports_onhashchange ) { return false; }
      
      // Otherwise, we need to stop ours (if possible).
      $( fake_onhashchange.stop );
    }
    
  });
  
  // fake_onhashchange does all the work of triggering the window.onhashchange
  // event for browsers that don't natively support it, including creating a
  // polling loop to watch for hash changes and in IE 6/7 creating a hidden
  // Iframe to enable back and forward.
  fake_onhashchange = (function(){
    var self = {},
      timeout_id,
      
      // Remember the initial hash so it doesn't get triggered immediately.
      last_hash = get_fragment(),
      
      fn_retval = function(val){ return val; },
      history_set = fn_retval,
      history_get = fn_retval;
    
    // Start the polling loop.
    self.start = function() {
      timeout_id || poll();
    };
    
    // Stop the polling loop.
    self.stop = function() {
      timeout_id && clearTimeout( timeout_id );
      timeout_id = undefined;
    };
    
    // This polling loop checks every $.fn.hashchange.delay milliseconds to see
    // if location.hash has changed, and triggers the 'hashchange' event on
    // window when necessary.
    function poll() {
      var hash = get_fragment(),
        history_hash = history_get( last_hash );
      
      if ( hash !== last_hash ) {
        history_set( last_hash = hash, history_hash );
        
        $(window).trigger( str_hashchange );
        
      } else if ( history_hash !== last_hash ) {
        location.href = location.href.replace( /#.*/, '' ) + history_hash;
      }
      
      timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
    };
    
///--> 06/2015 Removed IE 6-8 Support
    
    return self;
  })();
  
})(jQuery,this);
;
/*//////////////////////////////////////////////////////////

	-=Plugin Manifest=-
	
	POSSIBLE/ZAAZ
	
	1.	Console Log Wrapper			Updated:	05/2015
	2.	Table Sorter				Updated:	06/2015
	3.	jCarousel
	4.	Bootstrap Tabs
	5.	Mouse Over Detection
	6.	JQuery Cookie
	
	KBHIT
	
	1.	JQuery Toggles				Included:	03/2014 (approx)
	2.	Prevent Double Submit		Included:	03/2014 (approx)
	3. 	LockFixed					Included:	11/2014
	4.	JGestures					Included:	02/2015
	5. 	Enquire						Included:	03/2015
	6. 	JQuery UI Touch Punch		Included:	04/2015
	7. 	Tab Visibility Manager		Included:	05/2015
	8. 	JReject						Included:	05/2015
	9.	noUISlider					Included:	06/2015
	10.	wNumb						Included:	06/2015

////////////////////////////////////////////////////////////*




/*
 *
 *	05/20/2010
 *	http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
 *	usage: log('inside coolFunc',this,arguments);
 *
 */
window.log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments))}};




/*
 * 
 * TableSorter 2.0 - Client-side table sorting with ease!
 * Version 2.0.5b
 * @requires jQuery v1.2.3
 * 
 * Copyright (c) 2007 Christian Bach
 * Examples and docs at: http://tablesorter.com
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 */
(function($){$.extend({tablesorter:new
function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",cssChildRow:"expand-child",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,sortLocaleCompare:true,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'/\.|\,/g',onRenderHeader:null,selectorHeaders:'thead th',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}if(table.tBodies.length==0)return;var rows=table.tBodies[0].rows;if(rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,rows,-1,i);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,rows,rowIndex,cellIndex){var l=parsers.length,node=false,nodeValue=false,keepLooking=true;while(nodeValue==''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex);nodeValue=trimAndGetNodeText(table.config,node);if(table.config.debug){log('Checking if value was empty on row:'+rowIndex);}}else{keepLooking=false;}}for(var i=1;i<l;i++){if(parsers[i].is(nodeValue,table,node)){return parsers[i];}}return parsers[0];}function getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex){return rows[rowIndex].cells[cellIndex];}function trimAndGetNodeText(config,node){return $.trim(getElementText(config,node));}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=$(table.tBodies[0].rows[i]),cols=[];if(c.hasClass(table.config.cssChildRow)){cache.row[cache.row.length-1]=cache.row[cache.row.length-1].add(c);continue;}cache.row.push(c);for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c[0].cells[j]),table,c[0].cells[j]));}cols.push(cache.normalized.length);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){var text="";if(!node)return"";if(!config.supportsTextContent)config.supportsTextContent=node.textContent||false;if(config.textExtraction=="simple"){if(config.supportsTextContent){text=node.textContent;}else{if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){text=node.childNodes[0].innerHTML;}else{text=node.innerHTML;}}}else{if(typeof(config.textExtraction)=="function"){text=config.textExtraction(node);}else{text=$(node).text();}}return text;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){var pos=n[i][checkCell];rows.push(r[pos]);if(!table.config.appender){var l=r[pos].length;for(var j=0;j<l;j++){tableBody[0].appendChild(r[pos][j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false;var header_index=computeTableHeaderCellIndexes(table);$tableHeaders=$(table.config.selectorHeaders,table).each(function(index){this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(table.config.sortInitialOrder);this.count=this.order;if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(checkHeaderOptionsSortingLocked(table,index))this.order=this.lockedOrder=checkHeaderOptionsSortingLocked(table,index);if(!this.sortDisabled){var $th=$(this).addClass(table.config.cssHeader);if(table.config.onRenderHeader)table.config.onRenderHeader.apply($th);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function computeTableHeaderCellIndexes(t){var matrix=[];var lookup={};var thead=t.getElementsByTagName('THEAD')[0];var trs=thead.getElementsByTagName('TR');for(var i=0;i<trs.length;i++){var cells=trs[i].cells;for(var j=0;j<cells.length;j++){var c=cells[j];var rowIndex=c.parentNode.rowIndex;var cellId=rowIndex+"-"+c.cellIndex;var rowSpan=c.rowSpan||1;var colSpan=c.colSpan||1
var firstAvailCol;if(typeof(matrix[rowIndex])=="undefined"){matrix[rowIndex]=[];}for(var k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])=="undefined"){firstAvailCol=k;break;}}lookup[cellId]=firstAvailCol;for(var k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])=="undefined"){matrix[k]=[];}var matrixrow=matrix[k];for(var l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}return lookup;}function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function checkHeaderOptionsSortingLocked(table,i){if((table.config.headers[i])&&(table.config.headers[i].lockedOrder))return table.config.headers[i].lockedOrder;return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){return(v.toLowerCase()=="desc")?1:0;}else{return(v==1)?1:0;}}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(table.config.parsers[c].type=="text")?((order==0)?makeSortFunction("text","asc",c):makeSortFunction("text","desc",c)):((order==0)?makeSortFunction("numeric","asc",c):makeSortFunction("numeric","desc",c));var e="e"+i;dynamicExp+="var "+e+" = "+s;dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";if(table.config.debug){benchmark("Evaling expression:"+dynamicExp,new Date());}eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function makeSortFunction(type,direction,index){var a="a["+index+"]",b="b["+index+"]";if(type=='text'&&direction=='asc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+a+" < "+b+") ? -1 : 1 )));";}else if(type=='text'&&direction=='desc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+b+" < "+a+") ? -1 : 1 )));";}else if(type=='numeric'&&direction=='asc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+a+" - "+b+"));";}else if(type=='numeric'&&direction=='desc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+b+" - "+a+"));";}};function makeSortText(i){return"((a["+i+"] < b["+i+"]) ? -1 : ((a["+i+"] > b["+i+"]) ? 1 : 0));";};function makeSortTextDesc(i){return"((b["+i+"] < a["+i+"]) ? -1 : ((b["+i+"] > a["+i+"]) ? 1 : 0));";};function makeSortNumeric(i){return"a["+i+"]-b["+i+"];";};function makeSortNumericDesc(i){return"b["+i+"]-a["+i+"];";};function sortText(a,b){if(table.config.sortLocaleCompare)return a.localeCompare(b);return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){if(table.config.sortLocaleCompare)return b.localeCompare(a);return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$.data(this,"tablesorter",config);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){$this.trigger("sortStart");var $cell=$(this);var i=this.column;this.order=this.count++%2;if(this.lockedOrder)this.order=this.lockedOrder;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){var me=this;setTimeout(function(){me.config.parsers=buildParserCache(me,$headers);cache=buildCache(me);},1);}).bind("updateCell",function(e,cell){var config=this.config;var pos=[(cell.parentNode.rowIndex-1),cell.cellIndex];cache.normalized[pos[0]][pos[1]]=config.parsers[pos[1]].format(getElementText(config,cell),cell);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){return/^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g,'')));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLocaleLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if (c.dateFormat == "pt") {s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");} else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}var $tr,row=-1,odd;$("tr:visible",table.tBodies[0]).each(function(i){$tr=$(this);if(!$tr.hasClass(table.config.cssChildRow))row++;odd=(row%2==0);$tr.removeClass(table.config.widgetZebra.css[odd?0:1]).addClass(table.config.widgetZebra.css[odd?1:0])});if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);




/*!
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function (g) { var q = { vertical: !1, rtl: !1, start: 1, offset: 1, size: null, scroll: 3, visible: null, animation: "normal", easing: "swing", auto: 0, wrap: null, initCallback: null, setupCallback: null, reloadCallback: null, itemLoadCallback: null, itemFirstInCallback: null, itemFirstOutCallback: null, itemLastInCallback: null, itemLastOutCallback: null, itemVisibleInCallback: null, itemVisibleOutCallback: null, animationStepCallback: null, buttonNextHTML: "<div></div>", buttonPrevHTML: "<div></div>", buttonNextEvent: "click", buttonPrevEvent: "click", buttonNextCallback: null, buttonPrevCallback: null, itemFallbackDimension: null }, m = !1; g(window).bind("load.jcarousel", function () { m = !0 }); g.jcarousel = function (a, c) { this.options = g.extend({}, q, c || {}); this.autoStopped = this.locked = !1; this.buttonPrevState = this.buttonNextState = this.buttonPrev = this.buttonNext = this.list = this.clip = this.container = null; if (!c || c.rtl === void 0) this.options.rtl = (g(a).attr("dir") || g("html").attr("dir") || "").toLowerCase() == "rtl"; this.wh = !this.options.vertical ? "width" : "height"; this.lt = !this.options.vertical ? this.options.rtl ? "right" : "left" : "top"; for (var b = "", d = a.className.split(" "), f = 0; f < d.length; f++) if (d[f].indexOf("jcarousel-skin") != -1) { g(a).removeClass(d[f]); b = d[f]; break } a.nodeName.toUpperCase() == "UL" || a.nodeName.toUpperCase() == "OL" ? (this.list = g(a), this.clip = this.list.parents(".jcarousel-clip"), this.container = this.list.parents(".jcarousel-container")) : (this.container = g(a), this.list = this.container.find("ul,ol").eq(0), this.clip = this.container.find(".jcarousel-clip")); if (this.clip.size() === 0) this.clip = this.list.wrap("<div></div>").parent(); if (this.container.size() === 0) this.container = this.clip.wrap("<div></div>").parent(); b !== "" && this.container.parent()[0].className.indexOf("jcarousel-skin") == -1 && this.container.wrap('<div class=" ' + b + '"></div>'); this.buttonPrev = g(".jcarousel-prev", this.container); if (this.buttonPrev.size() === 0 && this.options.buttonPrevHTML !== null) this.buttonPrev = g(this.options.buttonPrevHTML).appendTo(this.container); this.buttonPrev.addClass(this.className("jcarousel-prev")); this.buttonNext = g(".jcarousel-next", this.container); if (this.buttonNext.size() === 0 && this.options.buttonNextHTML !== null) this.buttonNext = g(this.options.buttonNextHTML).appendTo(this.container); this.buttonNext.addClass(this.className("jcarousel-next")); this.clip.addClass(this.className("jcarousel-clip")).css({ position: "relative" }); this.list.addClass(this.className("jcarousel-list")).css({ overflow: "hidden", position: "relative", top: 0, margin: 0, padding: 0 }).css(this.options.rtl ? "right" : "left", 0); this.container.addClass(this.className("jcarousel-container")).css({ position: "relative" }); !this.options.vertical && this.options.rtl && this.container.addClass("jcarousel-direction-rtl").attr("dir", "rtl"); var j = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null, b = this.list.children("li"), e = this; if (b.size() > 0) { var h = 0, i = this.options.offset; b.each(function () { e.format(this, i++); h += e.dimension(this, j) }); this.list.css(this.wh, h + 100 + "px"); if (!c || c.size === void 0) this.options.size = b.size() } this.container.css("display", "block"); this.buttonNext.css("display", "block"); this.buttonPrev.css("display", "block"); this.funcNext = function () { e.next() }; this.funcPrev = function () { e.prev() }; this.funcResize = function () { e.resizeTimer && clearTimeout(e.resizeTimer); e.resizeTimer = setTimeout(function () { e.reload() }, 100) }; this.options.initCallback !== null && this.options.initCallback(this, "init"); !m && /Safari/i.test(navigator.userAgent) && /Apple/i.test(navigator.vendor) ? (this.buttons(!1, !1), g(window).bind("load.jcarousel", function () { e.setup() })) : this.setup() }; var f = g.jcarousel; f.fn = f.prototype = { jcarousel: "0.2.8" }; f.fn.extend = f.extend = g.extend; f.fn.extend({ setup: function () { this.prevLast = this.prevFirst = this.last = this.first = null; this.animating = !1; this.tail = this.resizeTimer = this.timer = null; this.inTail = !1; if (!this.locked) { this.list.css(this.lt, this.pos(this.options.offset) + "px"); var a = this.pos(this.options.start, !0); this.prevFirst = this.prevLast = null; this.animate(a, !1); g(window).unbind("resize.jcarousel", this.funcResize).bind("resize.jcarousel", this.funcResize); this.options.setupCallback !== null && this.options.setupCallback(this) } }, reset: function () { this.list.empty(); this.list.css(this.lt, "0px"); this.list.css(this.wh, "10px"); this.options.initCallback !== null && this.options.initCallback(this, "reset"); this.setup() }, reload: function () { this.tail !== null && this.inTail && this.list.css(this.lt, f.intval(this.list.css(this.lt)) + this.tail); this.tail = null; this.inTail = !1; this.options.reloadCallback !== null && this.options.reloadCallback(this); if (this.options.visible !== null) { var a = this, c = Math.ceil(this.clipping() / this.options.visible), b = 0, d = 0; this.list.children("li").each(function (f) { b += a.dimension(this, c); f + 1 < a.first && (d = b) }); this.list.css(this.wh, b + "px"); this.list.css(this.lt, -d + "px") } this.scroll(this.first, !1) }, lock: function () { this.locked = !0; this.buttons() }, unlock: function () { this.locked = !1; this.buttons() }, size: function (a) { if (a !== void 0) this.options.size = a, this.locked || this.buttons(); return this.options.size }, has: function (a, c) { if (c === void 0 || !c) c = a; if (this.options.size !== null && c > this.options.size) c = this.options.size; for (var b = a; b <= c; b++) { var d = this.get(b); if (!d.length || d.hasClass("jcarousel-item-placeholder")) return !1 } return !0 }, get: function (a) { return g(">.jcarousel-item-" + a, this.list) }, add: function (a, c) { var b = this.get(a), d = 0, p = g(c); if (b.length === 0) for (var j, e = f.intval(a), b = this.create(a) ; ;) { if (j = this.get(--e), e <= 0 || j.length) { e <= 0 ? this.list.prepend(b) : j.after(b); break } } else d = this.dimension(b); p.get(0).nodeName.toUpperCase() == "LI" ? (b.replaceWith(p), b = p) : b.empty().append(c); this.format(b.removeClass(this.className("jcarousel-item-placeholder")), a); p = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null; d = this.dimension(b, p) - d; a > 0 && a < this.first && this.list.css(this.lt, f.intval(this.list.css(this.lt)) - d + "px"); this.list.css(this.wh, f.intval(this.list.css(this.wh)) + d + "px"); return b }, remove: function (a) { var c = this.get(a); if (c.length && !(a >= this.first && a <= this.last)) { var b = this.dimension(c); a < this.first && this.list.css(this.lt, f.intval(this.list.css(this.lt)) + b + "px"); c.remove(); this.list.css(this.wh, f.intval(this.list.css(this.wh)) - b + "px") } }, next: function () { this.tail !== null && !this.inTail ? this.scrollTail(!1) : this.scroll((this.options.wrap == "both" || this.options.wrap == "last") && this.options.size !== null && this.last == this.options.size ? 1 : this.first + this.options.scroll) }, prev: function () { this.tail !== null && this.inTail ? this.scrollTail(!0) : this.scroll((this.options.wrap == "both" || this.options.wrap == "first") && this.options.size !== null && this.first == 1 ? this.options.size : this.first - this.options.scroll) }, scrollTail: function (a) { if (!this.locked && !this.animating && this.tail) { this.pauseAuto(); var c = f.intval(this.list.css(this.lt)), c = !a ? c - this.tail : c + this.tail; this.inTail = !a; this.prevFirst = this.first; this.prevLast = this.last; this.animate(c) } }, scroll: function (a, c) { !this.locked && !this.animating && (this.pauseAuto(), this.animate(this.pos(a), c)) }, pos: function (a, c) { var b = f.intval(this.list.css(this.lt)); if (this.locked || this.animating) return b; this.options.wrap != "circular" && (a = a < 1 ? 1 : this.options.size && a > this.options.size ? this.options.size : a); for (var d = this.first > a, g = this.options.wrap != "circular" && this.first <= 1 ? 1 : this.first, j = d ? this.get(g) : this.get(this.last), e = d ? g : g - 1, h = null, i = 0, k = !1, l = 0; d ? --e >= a : ++e < a;) { h = this.get(e); k = !h.length; if (h.length === 0 && (h = this.create(e).addClass(this.className("jcarousel-item-placeholder")), j[d ? "before" : "after"](h), this.first !== null && this.options.wrap == "circular" && this.options.size !== null && (e <= 0 || e > this.options.size))) j = this.get(this.index(e)), j.length && (h = this.add(e, j.clone(!0))); j = h; l = this.dimension(h); k && (i += l); if (this.first !== null && (this.options.wrap == "circular" || e >= 1 && (this.options.size === null || e <= this.options.size))) b = d ? b + l : b - l } for (var g = this.clipping(), m = [], o = 0, n = 0, j = this.get(a - 1), e = a; ++o;) { h = this.get(e); k = !h.length; if (h.length === 0) { h = this.create(e).addClass(this.className("jcarousel-item-placeholder")); if (j.length === 0) this.list.prepend(h); else j[d ? "before" : "after"](h); if (this.first !== null && this.options.wrap == "circular" && this.options.size !== null && (e <= 0 || e > this.options.size)) j = this.get(this.index(e)), j.length && (h = this.add(e, j.clone(!0))) } j = h; l = this.dimension(h); if (l === 0) throw Error("jCarousel: No width/height set for items. This will cause an infinite loop. Aborting..."); this.options.wrap != "circular" && this.options.size !== null && e > this.options.size ? m.push(h) : k && (i += l); n += l; if (n >= g) break; e++ } for (h = 0; h < m.length; h++) m[h].remove(); i > 0 && (this.list.css(this.wh, this.dimension(this.list) + i + "px"), d && (b -= i, this.list.css(this.lt, f.intval(this.list.css(this.lt)) - i + "px"))); i = a + o - 1; if (this.options.wrap != "circular" && this.options.size && i > this.options.size) i = this.options.size; if (e > i) { o = 0; e = i; for (n = 0; ++o;) { h = this.get(e--); if (!h.length) break; n += this.dimension(h); if (n >= g) break } } e = i - o + 1; this.options.wrap != "circular" && e < 1 && (e = 1); if (this.inTail && d) b += this.tail, this.inTail = !1; this.tail = null; if (this.options.wrap != "circular" && i == this.options.size && i - o + 1 >= 1 && (d = f.intval(this.get(i).css(!this.options.vertical ? "marginRight" : "marginBottom")), n - d > g)) this.tail = n - g - d; if (c && a === this.options.size && this.tail) b -= this.tail, this.inTail = !0; for (; a-- > e;) b += this.dimension(this.get(a)); this.prevFirst = this.first; this.prevLast = this.last; this.first = e; this.last = i; return b }, animate: function (a, c) { if (!this.locked && !this.animating) { this.animating = !0; var b = this, d = function () { b.animating = !1; a === 0 && b.list.css(b.lt, 0); !b.autoStopped && (b.options.wrap == "circular" || b.options.wrap == "both" || b.options.wrap == "last" || b.options.size === null || b.last < b.options.size || b.last == b.options.size && b.tail !== null && !b.inTail) && b.startAuto(); b.buttons(); b.notify("onAfterAnimation"); if (b.options.wrap == "circular" && b.options.size !== null) for (var c = b.prevFirst; c <= b.prevLast; c++) c !== null && !(c >= b.first && c <= b.last) && (c < 1 || c > b.options.size) && b.remove(c) }; this.notify("onBeforeAnimation"); if (!this.options.animation || c === !1) this.list.css(this.lt, a + "px"), d(); else { var f = !this.options.vertical ? this.options.rtl ? { right: a } : { left: a } : { top: a }, d = { duration: this.options.animation, easing: this.options.easing, complete: d }; if (g.isFunction(this.options.animationStepCallback)) d.step = this.options.animationStepCallback; this.list.animate(f, d) } } }, startAuto: function (a) { if (a !== void 0) this.options.auto = a; if (this.options.auto === 0) return this.stopAuto(); if (this.timer === null) { this.autoStopped = !1; var c = this; this.timer = window.setTimeout(function () { c.next() }, this.options.auto * 1E3) } }, stopAuto: function () { this.pauseAuto(); this.autoStopped = !0 }, pauseAuto: function () { if (this.timer !== null) window.clearTimeout(this.timer), this.timer = null }, buttons: function (a, c) { if (a == null && (a = !this.locked && this.options.size !== 0 && (this.options.wrap && this.options.wrap != "first" || this.options.size === null || this.last < this.options.size), !this.locked && (!this.options.wrap || this.options.wrap == "first") && this.options.size !== null && this.last >= this.options.size)) a = this.tail !== null && !this.inTail; if (c == null && (c = !this.locked && this.options.size !== 0 && (this.options.wrap && this.options.wrap != "last" || this.first > 1), !this.locked && (!this.options.wrap || this.options.wrap == "last") && this.options.size !== null && this.first == 1)) c = this.tail !== null && this.inTail; var b = this; this.buttonNext.size() > 0 ? (this.buttonNext.unbind(this.options.buttonNextEvent + ".jcarousel", this.funcNext), a && this.buttonNext.bind(this.options.buttonNextEvent + ".jcarousel", this.funcNext), this.buttonNext[a ? "removeClass" : "addClass"](this.className("jcarousel-next-disabled")).attr("disabled", a ? !1 : !0), this.options.buttonNextCallback !== null && this.buttonNext.data("jcarouselstate") != a && this.buttonNext.each(function () { b.options.buttonNextCallback(b, this, a) }).data("jcarouselstate", a)) : this.options.buttonNextCallback !== null && this.buttonNextState != a && this.options.buttonNextCallback(b, null, a); this.buttonPrev.size() > 0 ? (this.buttonPrev.unbind(this.options.buttonPrevEvent + ".jcarousel", this.funcPrev), c && this.buttonPrev.bind(this.options.buttonPrevEvent + ".jcarousel", this.funcPrev), this.buttonPrev[c ? "removeClass" : "addClass"](this.className("jcarousel-prev-disabled")).attr("disabled", c ? !1 : !0), this.options.buttonPrevCallback !== null && this.buttonPrev.data("jcarouselstate") != c && this.buttonPrev.each(function () { b.options.buttonPrevCallback(b, this, c) }).data("jcarouselstate", c)) : this.options.buttonPrevCallback !== null && this.buttonPrevState != c && this.options.buttonPrevCallback(b, null, c); this.buttonNextState = a; this.buttonPrevState = c }, notify: function (a) { var c = this.prevFirst === null ? "init" : this.prevFirst < this.first ? "next" : "prev"; this.callback("itemLoadCallback", a, c); this.prevFirst !== this.first && (this.callback("itemFirstInCallback", a, c, this.first), this.callback("itemFirstOutCallback", a, c, this.prevFirst)); this.prevLast !== this.last && (this.callback("itemLastInCallback", a, c, this.last), this.callback("itemLastOutCallback", a, c, this.prevLast)); this.callback("itemVisibleInCallback", a, c, this.first, this.last, this.prevFirst, this.prevLast); this.callback("itemVisibleOutCallback", a, c, this.prevFirst, this.prevLast, this.first, this.last) }, callback: function (a, c, b, d, f, j, e) { if (!(this.options[a] == null || typeof this.options[a] != "object" && c != "onAfterAnimation")) { var h = typeof this.options[a] == "object" ? this.options[a][c] : this.options[a]; if (g.isFunction(h)) { var i = this; if (d === void 0) h(i, b, c); else if (f === void 0) this.get(d).each(function () { h(i, this, d, b, c) }); else for (var a = function (a) { i.get(a).each(function () { h(i, this, a, b, c) }) }, k = d; k <= f; k++) k !== null && !(k >= j && k <= e) && a(k) } } }, create: function (a) { return this.format("<li></li>", a) }, format: function (a, c) { for (var a = g(a), b = a.get(0).className.split(" "), d = 0; d < b.length; d++) b[d].indexOf("jcarousel-") != -1 && a.removeClass(b[d]); a.addClass(this.className("jcarousel-item")).addClass(this.className("jcarousel-item-" + c)).css({ "float": this.options.rtl ? "right" : "left", "list-style": "none" }).attr("jcarouselindex", c); return a }, className: function (a) { return a + " " + a + (!this.options.vertical ? "-horizontal" : "-vertical") }, dimension: function (a, c) { var b = g(a); if (c == null) return !this.options.vertical ? b.outerWidth(!0) || f.intval(this.options.itemFallbackDimension) : b.outerHeight(!0) || f.intval(this.options.itemFallbackDimension); else { var d = !this.options.vertical ? c - f.intval(b.css("marginLeft")) - f.intval(b.css("marginRight")) : c - f.intval(b.css("marginTop")) - f.intval(b.css("marginBottom")); g(b).css(this.wh, d + "px"); return this.dimension(b) } }, clipping: function () { return !this.options.vertical ? this.clip[0].offsetWidth - f.intval(this.clip.css("borderLeftWidth")) - f.intval(this.clip.css("borderRightWidth")) : this.clip[0].offsetHeight - f.intval(this.clip.css("borderTopWidth")) - f.intval(this.clip.css("borderBottomWidth")) }, index: function (a, c) { if (c == null) c = this.options.size; return Math.round(((a - 1) / c - Math.floor((a - 1) / c)) * c) + 1 } }); f.extend({ defaults: function (a) { return g.extend(q, a || {}) }, intval: function (a) { a = parseInt(a, 10); return isNaN(a) ? 0 : a }, windowLoaded: function () { m = !0 } }); g.fn.jcarousel = function (a) { if (typeof a == "string") { var c = g(this).data("jcarousel"), b = Array.prototype.slice.call(arguments, 1); return c[a].apply(c, b) } else return this.each(function () { var b = g(this).data("jcarousel"); b ? (a && g.extend(b.options, a), b.reload()) : g(this).data("jcarousel", new f(this, a)) }) } })(jQuery);

/*! jCarousel - v0.3.1 - 2014-04-26
* http://sorgalla.com/jcarousel
* Copyright (c) 2014 Jan Sorgalla; Licensed MIT */
//(function (t) { "use strict"; var i = t.jCarousel = {}; i.version = "0.3.1"; var s = /^([+\-]=)?(.+)$/; i.parseTarget = function (t) { var i = !1, e = "object" != typeof t ? s.exec(t) : null; return e ? (t = parseInt(e[2], 10) || 0, e[1] && (i = !0, "-=" === e[1] && (t *= -1))) : "object" != typeof t && (t = parseInt(t, 10) || 0), { target: t, relative: i } }, i.detectCarousel = function (t) { for (var i; t.length > 0;) { if (i = t.filter("[data-jcarousel]"), i.length > 0) return i; if (i = t.find("[data-jcarousel]"), i.length > 0) return i; t = t.parent() } return null }, i.base = function (s) { return { version: i.version, _options: {}, _element: null, _carousel: null, _init: t.noop, _create: t.noop, _destroy: t.noop, _reload: t.noop, create: function () { return this._element.attr("data-" + s.toLowerCase(), !0).data(s, this), !1 === this._trigger("create") ? this : (this._create(), this._trigger("createend"), this) }, destroy: function () { return !1 === this._trigger("destroy") ? this : (this._destroy(), this._trigger("destroyend"), this._element.removeData(s).removeAttr("data-" + s.toLowerCase()), this) }, reload: function (t) { return !1 === this._trigger("reload") ? this : (t && this.options(t), this._reload(), this._trigger("reloadend"), this) }, element: function () { return this._element }, options: function (i, s) { if (0 === arguments.length) return t.extend({}, this._options); if ("string" == typeof i) { if (s === void 0) return this._options[i] === void 0 ? null : this._options[i]; this._options[i] = s } else this._options = t.extend({}, this._options, i); return this }, carousel: function () { return this._carousel || (this._carousel = i.detectCarousel(this.options("carousel") || this._element), this._carousel || t.error('Could not detect carousel for plugin "' + s + '"')), this._carousel }, _trigger: function (i, e, r) { var n, l = !1; return r = [this].concat(r || []), (e || this._element).each(function () { n = t.Event((s + ":" + i).toLowerCase()), t(this).trigger(n, r), n.isDefaultPrevented() && (l = !0) }), !l } } }, i.plugin = function (s, e) { var r = t[s] = function (i, s) { this._element = t(i), this.options(s), this._init(), this.create() }; return r.fn = r.prototype = t.extend({}, i.base(s), e), t.fn[s] = function (i) { var e = Array.prototype.slice.call(arguments, 1), n = this; return "string" == typeof i ? this.each(function () { var r = t(this).data(s); if (!r) return t.error("Cannot call methods on " + s + " prior to initialization; " + 'attempted to call method "' + i + '"'); if (!t.isFunction(r[i]) || "_" === i.charAt(0)) return t.error('No such method "' + i + '" for ' + s + " instance"); var l = r[i].apply(r, e); return l !== r && l !== void 0 ? (n = l, !1) : void 0 }) : this.each(function () { var e = t(this).data(s); e instanceof r ? e.reload(i) : new r(this, i) }), n }, r } })(jQuery), function (t, i) { "use strict"; var s = function (t) { return parseFloat(t) || 0 }; t.jCarousel.plugin("jcarousel", { animating: !1, tail: 0, inTail: !1, resizeTimer: null, lt: null, vertical: !1, rtl: !1, circular: !1, underflow: !1, relative: !1, _options: { list: function () { return this.element().children().eq(0) }, items: function () { return this.list().children() }, animation: 400, transitions: !1, wrap: null, vertical: null, rtl: null, center: !1 }, _list: null, _items: null, _target: null, _first: null, _last: null, _visible: null, _fullyvisible: null, _init: function () { var t = this; return this.onWindowResize = function () { t.resizeTimer && clearTimeout(t.resizeTimer), t.resizeTimer = setTimeout(function () { t.reload() }, 100) }, this }, _create: function () { this._reload(), t(i).on("resize.jcarousel", this.onWindowResize) }, _destroy: function () { t(i).off("resize.jcarousel", this.onWindowResize) }, _reload: function () { this.vertical = this.options("vertical"), null == this.vertical && (this.vertical = this.list().height() > this.list().width()), this.rtl = this.options("rtl"), null == this.rtl && (this.rtl = function (i) { if ("rtl" === ("" + i.attr("dir")).toLowerCase()) return !0; var s = !1; return i.parents("[dir]").each(function () { return /rtl/i.test(t(this).attr("dir")) ? (s = !0, !1) : void 0 }), s }(this._element)), this.lt = this.vertical ? "top" : "left", this.relative = "relative" === this.list().css("position"), this._list = null, this._items = null; var i = this._target && this.index(this._target) >= 0 ? this._target : this.closest(); this.circular = "circular" === this.options("wrap"), this.underflow = !1; var s = { left: 0, top: 0 }; return i.length > 0 && (this._prepare(i), this.list().find("[data-jcarousel-clone]").remove(), this._items = null, this.underflow = this._fullyvisible.length >= this.items().length, this.circular = this.circular && !this.underflow, s[this.lt] = this._position(i) + "px"), this.move(s), this }, list: function () { if (null === this._list) { var i = this.options("list"); this._list = t.isFunction(i) ? i.call(this) : this._element.find(i) } return this._list }, items: function () { if (null === this._items) { var i = this.options("items"); this._items = (t.isFunction(i) ? i.call(this) : this.list().find(i)).not("[data-jcarousel-clone]") } return this._items }, index: function (t) { return this.items().index(t) }, closest: function () { var i, e = this, r = this.list().position()[this.lt], n = t(), l = !1, o = this.vertical ? "bottom" : this.rtl && !this.relative ? "left" : "right"; return this.rtl && this.relative && !this.vertical && (r += this.list().width() - this.clipping()), this.items().each(function () { if (n = t(this), l) return !1; var a = e.dimension(n); if (r += a, r >= 0) { if (i = a - s(n.css("margin-" + o)), !(0 >= Math.abs(r) - a + i / 2)) return !1; l = !0 } }), n }, target: function () { return this._target }, first: function () { return this._first }, last: function () { return this._last }, visible: function () { return this._visible }, fullyvisible: function () { return this._fullyvisible }, hasNext: function () { if (!1 === this._trigger("hasnext")) return !0; var t = this.options("wrap"), i = this.items().length - 1; return i >= 0 && !this.underflow && (t && "first" !== t || i > this.index(this._last) || this.tail && !this.inTail) ? !0 : !1 }, hasPrev: function () { if (!1 === this._trigger("hasprev")) return !0; var t = this.options("wrap"); return this.items().length > 0 && !this.underflow && (t && "last" !== t || this.index(this._first) > 0 || this.tail && this.inTail) ? !0 : !1 }, clipping: function () { return this._element["inner" + (this.vertical ? "Height" : "Width")]() }, dimension: function (t) { return t["outer" + (this.vertical ? "Height" : "Width")](!0) }, scroll: function (i, s, e) { if (this.animating) return this; if (!1 === this._trigger("scroll", null, [i, s])) return this; t.isFunction(s) && (e = s, s = !0); var r = t.jCarousel.parseTarget(i); if (r.relative) { var n, l, o, a, h, u, c, f, d = this.items().length - 1, _ = Math.abs(r.target), p = this.options("wrap"); if (r.target > 0) { var v = this.index(this._last); if (v >= d && this.tail) this.inTail ? "both" === p || "last" === p ? this._scroll(0, s, e) : t.isFunction(e) && e.call(this, !1) : this._scrollTail(s, e); else if (n = this.index(this._target), this.underflow && n === d && ("circular" === p || "both" === p || "last" === p) || !this.underflow && v === d && ("both" === p || "last" === p)) this._scroll(0, s, e); else if (o = n + _, this.circular && o > d) { for (f = d, h = this.items().get(-1) ; o > f++;) h = this.items().eq(0), u = this._visible.index(h) >= 0, u && h.after(h.clone(!0).attr("data-jcarousel-clone", !0)), this.list().append(h), u || (c = {}, c[this.lt] = this.dimension(h), this.moveBy(c)), this._items = null; this._scroll(h, s, e) } else this._scroll(Math.min(o, d), s, e) } else if (this.inTail) this._scroll(Math.max(this.index(this._first) - _ + 1, 0), s, e); else if (l = this.index(this._first), n = this.index(this._target), a = this.underflow ? n : l, o = a - _, 0 >= a && (this.underflow && "circular" === p || "both" === p || "first" === p)) this._scroll(d, s, e); else if (this.circular && 0 > o) { for (f = o, h = this.items().get(0) ; 0 > f++;) { h = this.items().eq(-1), u = this._visible.index(h) >= 0, u && h.after(h.clone(!0).attr("data-jcarousel-clone", !0)), this.list().prepend(h), this._items = null; var g = this.dimension(h); c = {}, c[this.lt] = -g, this.moveBy(c) } this._scroll(h, s, e) } else this._scroll(Math.max(o, 0), s, e) } else this._scroll(r.target, s, e); return this._trigger("scrollend"), this }, moveBy: function (t, i) { var e = this.list().position(), r = 1, n = 0; return this.rtl && !this.vertical && (r = -1, this.relative && (n = this.list().width() - this.clipping())), t.left && (t.left = e.left + n + s(t.left) * r + "px"), t.top && (t.top = e.top + n + s(t.top) * r + "px"), this.move(t, i) }, move: function (i, s) { s = s || {}; var e = this.options("transitions"), r = !!e, n = !!e.transforms, l = !!e.transforms3d, o = s.duration || 0, a = this.list(); if (!r && o > 0) return a.animate(i, s), void 0; var h = s.complete || t.noop, u = {}; if (r) { var c = a.css(["transitionDuration", "transitionTimingFunction", "transitionProperty"]), f = h; h = function () { t(this).css(c), f.call(this) }, u = { transitionDuration: (o > 0 ? o / 1e3 : 0) + "s", transitionTimingFunction: e.easing || s.easing, transitionProperty: o > 0 ? function () { return n || l ? "all" : i.left ? "left" : "top" }() : "none", transform: "none" } } l ? u.transform = "translate3d(" + (i.left || 0) + "," + (i.top || 0) + ",0)" : n ? u.transform = "translate(" + (i.left || 0) + "," + (i.top || 0) + ")" : t.extend(u, i), r && o > 0 && a.one("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd", h), a.css(u), 0 >= o && a.each(function () { h.call(this) }) }, _scroll: function (i, s, e) { if (this.animating) return t.isFunction(e) && e.call(this, !1), this; if ("object" != typeof i ? i = this.items().eq(i) : i.jquery === void 0 && (i = t(i)), 0 === i.length) return t.isFunction(e) && e.call(this, !1), this; this.inTail = !1, this._prepare(i); var r = this._position(i), n = this.list().position()[this.lt]; if (r === n) return t.isFunction(e) && e.call(this, !1), this; var l = {}; return l[this.lt] = r + "px", this._animate(l, s, e), this }, _scrollTail: function (i, s) { if (this.animating || !this.tail) return t.isFunction(s) && s.call(this, !1), this; var e = this.list().position()[this.lt]; this.rtl && this.relative && !this.vertical && (e += this.list().width() - this.clipping()), this.rtl && !this.vertical ? e += this.tail : e -= this.tail, this.inTail = !0; var r = {}; return r[this.lt] = e + "px", this._update({ target: this._target.next(), fullyvisible: this._fullyvisible.slice(1).add(this._visible.last()) }), this._animate(r, i, s), this }, _animate: function (i, s, e) { if (e = e || t.noop, !1 === this._trigger("animate")) return e.call(this, !1), this; this.animating = !0; var r = this.options("animation"), n = t.proxy(function () { this.animating = !1; var t = this.list().find("[data-jcarousel-clone]"); t.length > 0 && (t.remove(), this._reload()), this._trigger("animateend"), e.call(this, !0) }, this), l = "object" == typeof r ? t.extend({}, r) : { duration: r }, o = l.complete || t.noop; return s === !1 ? l.duration = 0 : t.fx.speeds[l.duration] !== void 0 && (l.duration = t.fx.speeds[l.duration]), l.complete = function () { n(), o.call(this) }, this.move(i, l), this }, _prepare: function (i) { var e, r, n, l, o = this.index(i), a = o, h = this.dimension(i), u = this.clipping(), c = this.vertical ? "bottom" : this.rtl ? "left" : "right", f = this.options("center"), d = { target: i, first: i, last: i, visible: i, fullyvisible: u >= h ? i : t() }; if (f && (h /= 2, u /= 2), u > h) for (; ;) { if (e = this.items().eq(++a), 0 === e.length) { if (!this.circular) break; if (e = this.items().eq(0), i.get(0) === e.get(0)) break; if (r = this._visible.index(e) >= 0, r && e.after(e.clone(!0).attr("data-jcarousel-clone", !0)), this.list().append(e), !r) { var _ = {}; _[this.lt] = this.dimension(e), this.moveBy(_) } this._items = null } if (l = this.dimension(e), 0 === l) break; if (h += l, d.last = e, d.visible = d.visible.add(e), n = s(e.css("margin-" + c)), u >= h - n && (d.fullyvisible = d.fullyvisible.add(e)), h >= u) break } if (!this.circular && !f && u > h) for (a = o; ;) { if (0 > --a) break; if (e = this.items().eq(a), 0 === e.length) break; if (l = this.dimension(e), 0 === l) break; if (h += l, d.first = e, d.visible = d.visible.add(e), n = s(e.css("margin-" + c)), u >= h - n && (d.fullyvisible = d.fullyvisible.add(e)), h >= u) break } return this._update(d), this.tail = 0, f || "circular" === this.options("wrap") || "custom" === this.options("wrap") || this.index(d.last) !== this.items().length - 1 || (h -= s(d.last.css("margin-" + c)), h > u && (this.tail = h - u)), this }, _position: function (t) { var i = this._first, s = i.position()[this.lt], e = this.options("center"), r = e ? this.clipping() / 2 - this.dimension(i) / 2 : 0; return this.rtl && !this.vertical ? (s -= this.relative ? this.list().width() - this.dimension(i) : this.clipping() - this.dimension(i), s += r) : s -= r, !e && (this.index(t) > this.index(i) || this.inTail) && this.tail ? (s = this.rtl && !this.vertical ? s - this.tail : s + this.tail, this.inTail = !0) : this.inTail = !1, -s }, _update: function (i) { var s, e = this, r = { target: this._target || t(), first: this._first || t(), last: this._last || t(), visible: this._visible || t(), fullyvisible: this._fullyvisible || t() }, n = this.index(i.first || r.first) < this.index(r.first), l = function (s) { var l = [], o = []; i[s].each(function () { 0 > r[s].index(this) && l.push(this) }), r[s].each(function () { 0 > i[s].index(this) && o.push(this) }), n ? l = l.reverse() : o = o.reverse(), e._trigger(s + "in", t(l)), e._trigger(s + "out", t(o)), e["_" + s] = i[s] }; for (s in i) l(s); return this } }) }(jQuery, window);




/* ========================================================
 * bootstrap-tab.js v2.0.0
 * http://twitter.github.com/bootstrap/javascript.html#tabs
 * ========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================== */

!function(t){"use strict";var a=function(a){this.element=t(a)};a.prototype={constructor:a,show:function(){var a,e,n=this.element,s=n.closest("ul:not(.dropdown-menu)"),i=n.attr("data-target");i||(i=n.attr("href"),i=i&&i.replace(/.*(?=#[^\s]*$)/,"")),n.parent("li").hasClass("active")||(a=s.find(".active a").last()[0],n.trigger({type:"show",relatedTarget:a}),e=t(i),this.activate(n.parent("li"),s),this.activate(e,e.parent(),function(){n.trigger({type:"shown",relatedTarget:a})}))},activate:function(a,e,n){function s(){i.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),a.addClass("active"),o?(a[0].offsetWidth,a.addClass("in")):a.removeClass("fade"),a.parent(".dropdown-menu")&&a.closest("li.dropdown").addClass("active"),n&&n()}var i=e.find("> .active"),o=n&&t.support.transition&&i.hasClass("fade");o?i.one(t.support.transition.end,s):s(),i.removeClass("in")}},t.fn.tab=function(e){return this.each(function(){var n=t(this),s=n.data("tab");s||n.data("tab",s=new a(this)),"string"==typeof e&&s[e]()})},t.fn.tab.Constructor=a,t(function(){t("body").on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(a){t(this).hasClass("useLink")||a.preventDefault(),t(this).tab("show")})})}(window.jQuery);




/*
 *
 *	http://stackoverflow.com/questions/1273566/how-do-i-check-if-the-mouse-is-over-an-element-in-jquery
 *	$(...).isMouseOver()
 *	for checking if the mouse is over the element(s)
 *
 */

(function ($) {
	jQuery.mlp = { x: 0, y: 0 }; // Mouse Last Position

	$(document).mousemove(function (e) {
		jQuery.mlp = { x: e.pageX, y: e.pageY }
	});

	function notNans(value) {
		if (isNaN(value)) {
			return 0;
		} else {
			return value
		}
	}
	$.fn.isMouseOver = function () {
		var result;
		this.eq(0).each(function () {
			var offSet = $(this).offset();
			var w = Number($(this).width())
            + notNans(Number($(this).css("padding-left").replace("px", "")))
            + notNans(Number($(this).css("padding-right").replace("px", "")))
            + notNans(Number($(this).css("border-right-width").replace("px", "")))
            + notNans(Number($(this).css("border-left-width").replace("px", "")));
			var h = Number($(this).height())
            + notNans(Number($(this).css("padding-top").replace("px", "")))
            + notNans(Number($(this).css("padding-bottom").replace("px", "")))
            + notNans(Number($(this).css("border-top-width").replace("px", "")))
            + notNans(Number($(this).css("border-bottom-width").replace("px", "")));
			if (offSet.left < jQuery.mlp.x && offSet.left + w > jQuery.mlp.x
             && offSet.top < jQuery.mlp.y && offSet.top + h > jQuery.mlp.y) {
				result = true;
			} else {
				result = false;
			}
		});
		return result;
	};
})(jQuery);




/*jshint eqnull:true */
/*!
* jQuery Cookie Plugin v1.2
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2011, Klaus Hartl
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.opensource.org/licenses/GPL-2.0
*/
(function ($, document, undefined) {

    var pluses = /\+/g;

    function raw(s) {
        return s;
    }

    function decoded(s) {
        return decodeURIComponent(s.replace(pluses, ' '));
    }

    $.cookie = function (key, value, options) {

        // key and at least value given, set cookie...
        if (value !== undefined && !/Object/.test(Object.prototype.toString.call(value))) {
            options = $.extend({}, $.cookie.defaults, options);

            if (value === null) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
				encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path ? '; path=' + options.path : '',
				options.domain ? '; domain=' + options.domain : '',
				options.secure ? '; secure' : ''
			].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || $.cookie.defaults || {};
        var decode = options.raw ? raw : decoded;
        var cookies = document.cookie.split('; ');
        for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
            if (decode(parts.shift()) === key) {
                return decode(parts.join('='));
            }
        }

        return null;
    };

    $.cookie.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key, options) !== null) {
            $.cookie(key, null, options);
            return true;
        }
        return false;
    };

})(jQuery, document);






/**
@license jQuery Toggles v2.0.5
Copyright 2013 Simon Tabor - MIT License
https://github.com/simontabor/jquery-toggles / http://simontabor.com/labs/toggles
*/
$.fn['toggles'] = function(options) {
  options = options || {};

  // extend default opts with the users options
  var opts = $.extend({
    'drag': true, // can the toggle be dragged
    'click': true, // can it be clicked to toggle
    'text': {
      'on': 'ON', // text for the ON position
      'off': 'OFF' // and off
    },
    'on': false, // is the toggle ON on init
    'animate': 250, // animation time
    'transition': 'ease-in-out', // animation transition,
    'checkbox': null, // the checkbox to toggle (for use in forms)
    'clicker': null, // element that can be clicked on to toggle. removes binding from the toggle itself (use nesting)
    'width': 50, // width used if not set in css
    'height': 20, // height if not set in css
    'type': 'compact' // defaults to a compact toggle, other option is 'select' where both options are shown at once
  },options);

  var selectType = (opts['type'] == 'select');

  // ensure these are jquery elements
  opts['checkbox'] = $(opts['checkbox']); // doesnt matter for checkbox

  if (opts['clicker']) opts['clicker'] = $(opts['clicker']); // leave as null if not set

  // use native transitions if possible
  var transition = 'margin-left '+opts['animate']+'ms '+opts['transition'];
  var transitions = {
    '-webkit-transition': transition,
    '-moz-transition': transition,
    'transition': transition
  };

  // for resetting transitions to none
  var notransitions = {
    '-webkit-transition': '',
    '-moz-transition': '',
    'transition': ''
  };

  // this is the actual toggle function which does the toggling
  var doToggle = function(slide, width, height, state) {
    var active = slide.toggleClass('active').hasClass('active');

    if (state === active) return;

    var inner = slide.find('.toggle-inner').css(transitions);

    slide.find('.toggle-off').toggleClass('active');
    slide.find('.toggle-on').toggleClass('active');

    // toggle the checkbox, if there is one
    opts['checkbox'].prop('checked',active);

    if (selectType) return;

    var margin = active ? 0 : -width + height;

    // move the toggle!
    inner.css('margin-left',margin);

    // ensure the toggle is left in the correct state after animation
    setTimeout(function() {
      inner.css(notransitions);
      inner.css('margin-left',margin);
    },opts['animate']);

  };

  // start setting up the toggle(s)
  return this.each(function() {
    var toggle = $(this);

    var height = toggle.height();
    var width = toggle.width();

    // if the element doesnt have an explicit height/width in css, set them
    if (!height || !width) {
      toggle.height(height = opts.height);
      toggle.width(width = opts.width);
    }

    var div = '<div class="toggle-';
    var slide = $(div+'slide">'); // wrapper inside toggle
    var inner = $(div+'inner">'); // inside slide, this bit moves
    var on = $(div+'on">'); // the on div
    var off = $(div+'off">'); // off div
    var blob = $(div+'blob">'); // the grip toggle blob

    var halfheight = height/2;
    var onoffwidth = width - halfheight;

    // set up the CSS for the individual elements
    on
      .css({
        height: height,
        width: onoffwidth,
        textAlign: 'center',
        textIndent: selectType ? '' : -halfheight,
        lineHeight: height+'px'
      })
      .html(opts['text']['on']);

    off
      .css({
        height: height,
        width: onoffwidth,
        marginLeft: selectType ? '' : -halfheight,
        textAlign: 'center',
        textIndent: selectType ? '' : halfheight,
        lineHeight: height+'px'
      })
      .html(opts['text']['off'])
      .addClass('active');

    blob.css({
      height: height,
      width: height,
      marginLeft: -halfheight
    });

    inner.css({
      width: width * 2 - height,
      marginLeft: selectType ? 0 : -width + height
    });

    if (selectType) {
      slide.addClass('toggle-select');
      toggle.css('width', onoffwidth*2);
      blob.hide();
    }

    // construct the toggle
    toggle.html(slide.html(inner.append(on,blob,off)));

    // when toggle is fired, toggle the toggle
    slide.on('toggle', function(e,active) {

      // stop bubbling
      if (e) e.stopPropagation();

      doToggle(slide,width,height);
      toggle.trigger('toggle',!active);
    });

    // setup events for toggling on or off
    toggle.on('toggleOn', function() {
      doToggle(slide, width, height, false);
    });
    toggle.on('toggleOff', function() {
      doToggle(slide, width, height, true);
    });

    if (opts['on']) {

      // toggle immediately to turn the toggle on
      doToggle(slide,width,height);
    }

    // if click is enabled and toggle isn't within the clicker element (stops double binding)
    if (opts['click'] && (!opts['clicker'] || !opts['clicker'].has(toggle).length)) {

      // bind the click, ensuring its not the blob being clicked on
      toggle.on('click touchstart',function(e) {
        e.stopPropagation();

        if (e.target !=  blob[0] || !opts['drag']) {
          slide.trigger('toggle', slide.hasClass('active'));
        }
      });
    }

    // setup the clicker element
    if (opts['clicker']) {
      opts['clicker'].on('click touchstart',function(e) {
        e.stopPropagation();

        if (e.target !=  blob[0] || !opts['drag']) {
          slide.trigger('toggle', slide.hasClass('active'));
        }
      });
    }

    // we're done with all the non dragging stuff
    if (!opts['drag'] || selectType) return;

    // time to begin the dragging parts/blob clicks
    var diff;
    var slideLimit = (width - height) / 4;

    // fired on mouseup and mouseleave events
    var upLeave = function(e) {
      toggle.off('mousemove touchmove');
      slide.off('mouseleave');
      blob.off('mouseup touchend');

      var active = slide.hasClass('active');

      if (!diff && opts.click && e.type !== 'mouseleave') {

        // theres no diff so nothing has moved. only toggle if its a mouseup
        slide.trigger('toggle', active);
        return;
      }

      if (active) {

        // if the movement enough to toggle?
        if (diff < -slideLimit) {
          slide.trigger('toggle',active);
        } else {

          // go back
          inner.animate({
            marginLeft: 0
          },opts.animate/2);
        }
      } else {

        // inactive
        if (diff > slideLimit) {
          slide.trigger('toggle',active);
        } else {

          // go back again
          inner.animate({
            marginLeft: -width + height
          },opts.animate/2);
        }
      }

    };

    var wh = -width + height;

    blob.on('mousedown touchstart', function(e) {

      // reset diff
      diff = 0;

      blob.off('mouseup touchend');
      slide.off('mouseleave');
      var cursor = e.pageX;

      toggle.on('mousemove touchmove', blob, function(e) {
        diff = e.pageX - cursor;
        var marginLeft;
        if (slide.hasClass('active')) {

          marginLeft = diff;

          // keep it within the limits
          if (diff > 0) marginLeft = 0;
          if (diff < wh) marginLeft = wh;
        } else {

          marginLeft = diff + wh;

          if (diff < 0) marginLeft = wh;
          if (diff > -wh) marginLeft = 0;

        }

        inner.css('margin-left',marginLeft);
      });

      blob.on('mouseup touchend', upLeave);
      slide.on('mouseleave', upLeave);
    });


  });

};


/*
 *	http://stackoverflow.com/questions/2830542/prevent-double-submission-of-forms-in-jquery
 *	jQuery plugin to prevent double submission of forms
 */

jQuery.fn.preventDoubleSubmission = function() {
	$(this).on('submit',function(e){
		var $form = $(this);
		if ($form.data('submitted') === true) {
			e.preventDefault();
		} else {
			$form.data('submitted', true);
			$('input[type="submit"]',$(this)).addClass('disabled');
		}
	});
	return this;
};


/*!
 * jQuery lockfixed plugin
 * http://www.directlyrics.com/code/lockfixed/
 *
 * Copyright 2012 Yvo Schaap
 * Released under the MIT license
 * http://www.directlyrics.com/code/lockfixed/license.txt
 *
 * Date: Sat Feb 8 2014 12:00:01 GMT
 */
(function(e,p){e.extend({lockfixed:function(a,b){b&&b.offset?(b.offset.bottom=parseInt(b.offset.bottom,10),b.offset.top=parseInt(b.offset.top,10)):b.offset={bottom:100,top:0};if((a=e(a))&&a.offset()){var n=a.css("position"),c=parseInt(a.css("marginTop"),10),l=a.css("top"),g=a.offset().top,h=!1;if(!0===b.forcemargin||navigator.userAgent.match(/\bMSIE (4|5|6)\./)||navigator.userAgent.match(/\bOS ([0-9])_/)||navigator.userAgent.match(/\bAndroid ([0-9])\./i))h=!0;e(window).bind("scroll resize orientationchange load lockfixed:pageupdate",
a,function(k){if(!h||!document.activeElement||"INPUT"!==document.activeElement.nodeName){var d=0,d=a.outerHeight();k=a.outerWidth();var m=e(document).height()-b.offset.bottom,f=e(window).scrollTop();"fixed"!=a.css("position")&&(g=a.offset().top,c=parseInt(a.css("marginTop"),10),l=a.css("top"));f>=g-(c?c:0)-b.offset.top?(d=m<f+d+c+b.offset.top?f+d+c+b.offset.top-m:0,h?a.css({marginTop:parseInt((c?c:0)+(f-g-d)+2*b.offset.top,10)+"px"}):a.css({position:"fixed",top:b.offset.top-d+"px",width:k+"px"})):
a.css({position:n,top:l,width:k+"px",marginTop:(c?c:0)+"px"})}})}}})})(jQuery);


/**
 * jGestures: a jQuery plugin for gesture events
 * Copyright 2010-2011 Neue Digitale / Razorfish GmbH
 * Copyright 2011-2012, Razorfish GmbH
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * @copyright Razorfish GmbH
 * @author martin.krause@razorfish.de
 * @version 0.90-shake
 * @requires jQuery JavaScript Library v1.4.2 - http://jquery.com/- Copyright 2010, John Resig- Dual licensed under the MIT or GPL Version 2 licenses. http://jquery.org/license
 */
(function(c){c.jGestures={};c.jGestures.defaults={};c.jGestures.defaults.thresholdShake={requiredShakes:10,freezeShakes:100,frontback:{sensitivity:10},leftright:{sensitivity:10},updown:{sensitivity:10}};c.jGestures.defaults.thresholdPinchopen=0.05;c.jGestures.defaults.thresholdPinchmove=0.05;c.jGestures.defaults.thresholdPinch=0.05;c.jGestures.defaults.thresholdPinchclose=0.05;c.jGestures.defaults.thresholdRotatecw=5;c.jGestures.defaults.thresholdRotateccw=5;c.jGestures.defaults.thresholdMove=20;c.jGestures.defaults.thresholdSwipe=100;c.jGestures.data={};c.jGestures.data.capableDevicesInUserAgentString=["iPad","iPhone","iPod","Mobile Safari"];c.jGestures.data.hasGestures=(function(){var k;for(k=0;k<c.jGestures.data.capableDevicesInUserAgentString.length;k++){if(navigator.userAgent.indexOf(c.jGestures.data.capableDevicesInUserAgentString[k])!==-1){return true}}return false})();c.hasGestures=c.jGestures.data.hasGestures;c.jGestures.events={touchstart:"jGestures.touchstart",touchendStart:"jGestures.touchend;start",touchendProcessed:"jGestures.touchend;processed",gesturestart:"jGestures.gesturestart",gestureendStart:"jGestures.gestureend;start",gestureendProcessed:"jGestures.gestureend;processed"};jQuery.each({orientationchange_orientationchange01:"orientationchange",gestureend_pinchopen01:"pinchopen",gestureend_pinchclose01:"pinchclose",gestureend_rotatecw01:"rotatecw",gestureend_rotateccw01:"rotateccw",gesturechange_pinch01:"pinch",gesturechange_rotate01:"rotate",touchstart_swipe13:"swipemove",touchstart_swipe01:"swipeone",touchstart_swipe02:"swipetwo",touchstart_swipe03:"swipethree",touchstart_swipe04:"swipefour",touchstart_swipe05:"swipeup",touchstart_swipe06:"swiperightup",touchstart_swipe07:"swiperight",touchstart_swipe08:"swiperightdown",touchstart_swipe09:"swipedown",touchstart_swipe10:"swipeleftdown",touchstart_swipe11:"swipeleft",touchstart_swipe12:"swipeleftup",touchstart_tap01:"tapone",touchstart_tap02:"taptwo",touchstart_tap03:"tapthree",touchstart_tap04:"tapfour",devicemotion_shake01:"shake",devicemotion_shake02:"shakefrontback",devicemotion_shake03:"shakeleftright",devicemotion_shake04:"shakeupdown"},function(l,k){jQuery.event.special[k]={setup:function(){var r=l.split("_");var o=r[0];var m=r[1].slice(0,r[1].length-2);var p=jQuery(this);var q;var n;if(!p.data("ojQueryGestures")||!p.data("ojQueryGestures")[o]){q=p.data("ojQueryGestures")||{};n={};n[o]=true;c.extend(true,q,n);p.data("ojQueryGestures",q);if(c.hasGestures){switch(m){case"orientationchange":p.get(0).addEventListener("orientationchange",a,false);break;case"shake":case"shakefrontback":case"shakeleftright":case"shakeupdown":case"tilt":p.get(0).addEventListener("devicemotion",b,false);break;case"tap":case"swipe":case"swipeup":case"swiperightup":case"swiperight":case"swiperightdown":case"swipedown":case"swipeleftdown":case"swipeleft":p.get(0).addEventListener("touchstart",h,false);break;case"pinchopen":case"pinchclose":case"rotatecw":case"rotateccw":p.get(0).addEventListener("gesturestart",e,false);p.get(0).addEventListener("gestureend",i,false);break;case"pinch":case"rotate":p.get(0).addEventListener("gesturestart",e,false);p.get(0).addEventListener("gesturechange",f,false);break}}else{switch(m){case"tap":case"swipe":p.bind("mousedown",h);break;case"orientationchange":case"pinchopen":case"pinchclose":case"rotatecw":case"rotateccw":case"pinch":case"rotate":case"shake":case"tilt":break}}}return false},add:function(n){var m=jQuery(this);var o=m.data("ojQueryGestures");o[n.type]={originalType:n.type};return false},remove:function(n){var m=jQuery(this);var o=m.data("ojQueryGestures");o[n.type]=false;m.data("ojQueryGestures",o);return false},teardown:function(){var r=l.split("_");var o=r[0];var m=r[1].slice(0,r[1].length-2);var p=jQuery(this);var q;var n;if(!p.data("ojQueryGestures")||!p.data("ojQueryGestures")[o]){q=p.data("ojQueryGestures")||{};n={};n[o]=false;c.extend(true,q,n);p.data("ojQueryGestures",q);if(c.hasGestures){switch(m){case"orientationchange":p.get(0).removeEventListener("orientationchange",a,false);break;case"shake":case"shakefrontback":case"shakeleftright":case"shakeupdown":case"tilt":p.get(0).removeEventListener("devicemotion",b,false);break;case"tap":case"swipe":case"swipeup":case"swiperightup":case"swiperight":case"swiperightdown":case"swipedown":case"swipeleftdown":case"swipeleft":case"swipeleftup":p.get(0).removeEventListener("touchstart",h,false);p.get(0).removeEventListener("touchmove",g,false);p.get(0).removeEventListener("touchend",j,false);break;case"pinchopen":case"pinchclose":case"rotatecw":case"rotateccw":p.get(0).removeEventListener("gesturestart",e,false);p.get(0).removeEventListener("gestureend",i,false);break;case"pinch":case"rotate":p.get(0).removeEventListener("gesturestart",e,false);p.get(0).removeEventListener("gesturechange",f,false);break}}else{switch(m){case"tap":case"swipe":p.unbind("mousedown",h);p.unbind("mousemove",g);p.unbind("mouseup",j);break;case"orientationchange":case"pinchopen":case"pinchclose":case"rotatecw":case"rotateccw":case"pinch":case"rotate":case"shake":case"tilt":break}}}return false}}});function d(k){k.startMove=(k.startMove)?k.startMove:{startX:null,startY:null,timestamp:null};var l=new Date().getTime();var m;var n;if(k.touches){n=[{lastX:k.deltaX,lastY:k.deltaY,moved:null,startX:k.screenX-k.startMove.screenX,startY:k.screenY-k.startMove.screenY}];m={vector:k.vector||null,orientation:window.orientation||null,lastX:((n[0].lastX>0)?+1:((n[0].lastX<0)?-1:0)),lastY:((n[0].lastY>0)?+1:((n[0].lastY<0)?-1:0)),startX:((n[0].startX>0)?+1:((n[0].startX<0)?-1:0)),startY:((n[0].startY>0)?+1:((n[0].startY<0)?-1:0))};n[0].moved=Math.sqrt(Math.pow(Math.abs(n[0].startX),2)+Math.pow(Math.abs(n[0].startY),2))}return{type:k.type||null,originalEvent:k.event||null,delta:n||null,direction:m||{orientation:window.orientation||null,vector:k.vector||null},duration:(k.duration)?k.duration:(k.startMove.timestamp)?l-k.timestamp:null,rotation:k.rotation||null,scale:k.scale||null,description:k.description||[k.type,":",k.touches,":",((n[0].lastX!=0)?((n[0].lastX>0)?"right":"left"):"steady"),":",((n[0].lastY!=0)?((n[0].lastY>0)?"down":"up"):"steady")].join("")}}function a(l){var k=["landscape:clockwise:","portrait:default:","landscape:counterclockwise:","portrait:upsidedown:"];c(window).triggerHandler("orientationchange",{direction:{orientation:window.orientation},description:["orientationchange:",k[((window.orientation/90)+1)],window.orientation].join("")})}function b(r){var k;var t=jQuery(window);var o=t.data("ojQueryGestures");var m=c.jGestures.defaults.thresholdShake;var n=o.oDeviceMotionLastDevicePosition||{accelerationIncludingGravity:{x:0,y:0,z:0},shake:{eventCount:0,intervalsPassed:0,intervalsFreeze:0},shakeleftright:{eventCount:0,intervalsPassed:0,intervalsFreeze:0},shakefrontback:{eventCount:0,intervalsPassed:0,intervalsFreeze:0},shakeupdown:{eventCount:0,intervalsPassed:0,intervalsFreeze:0}};var q={accelerationIncludingGravity:{x:r.accelerationIncludingGravity.x,y:r.accelerationIncludingGravity.y,z:r.accelerationIncludingGravity.z},shake:{eventCount:n.shake.eventCount,intervalsPassed:n.shake.intervalsPassed,intervalsFreeze:n.shake.intervalsFreeze},shakeleftright:{eventCount:n.shakeleftright.eventCount,intervalsPassed:n.shakeleftright.intervalsPassed,intervalsFreeze:n.shakeleftright.intervalsFreeze},shakefrontback:{eventCount:n.shakefrontback.eventCount,intervalsPassed:n.shakefrontback.intervalsPassed,intervalsFreeze:n.shakefrontback.intervalsFreeze},shakeupdown:{eventCount:n.shakeupdown.eventCount,intervalsPassed:n.shakeupdown.intervalsPassed,intervalsFreeze:n.shakeupdown.intervalsFreeze}};var p;var s;var l;for(k in o){switch(k){case"shake":case"shakeleftright":case"shakefrontback":case"shakeupdown":p=[];s=[];p.push(k);if(++q[k].intervalsFreeze>m.freezeShakes&&q[k].intervalsFreeze<(2*m.freezeShakes)){break}q[k].intervalsFreeze=0;q[k].intervalsPassed++;if((k==="shake"||k==="shakeleftright")&&(q.accelerationIncludingGravity.x>m.leftright.sensitivity||q.accelerationIncludingGravity.x<(-1*m.leftright.sensitivity))){p.push("leftright");p.push("x-axis")}if((k==="shake"||k==="shakefrontback")&&(q.accelerationIncludingGravity.y>m.frontback.sensitivity||q.accelerationIncludingGravity.y<(-1*m.frontback.sensitivity))){p.push("frontback");p.push("y-axis")}if((k==="shake"||k==="shakeupdown")&&(q.accelerationIncludingGravity.z+9.81>m.updown.sensitivity||q.accelerationIncludingGravity.z+9.81<(-1*m.updown.sensitivity))){p.push("updown");p.push("z-axis")}if(p.length>1){if(++q[k].eventCount==m.requiredShakes&&(q[k].intervalsPassed)<m.freezeShakes){t.triggerHandler(k,d({type:k,description:p.join(":"),event:r,duration:q[k].intervalsPassed*5}));q[k].eventCount=0;q[k].intervalsPassed=0;q[k].intervalsFreeze=m.freezeShakes+1}else{if(q[k].eventCount==m.requiredShakes&&(q[k].intervalsPassed)>m.freezeShakes){q[k].eventCount=0;q[k].intervalsPassed=0}}}break}l={};l.oDeviceMotionLastDevicePosition=q;t.data("ojQueryGestures",c.extend(true,o,l))}}function h(l){var k=jQuery(l.currentTarget);k.triggerHandler(c.jGestures.events.touchstart,l);if(c.hasGestures){l.currentTarget.addEventListener("touchmove",g,false);l.currentTarget.addEventListener("touchend",j,false)}else{k.bind("mousemove",g);k.bind("mouseup",j)}var n=k.data("ojQueryGestures");var m=(l.touches)?l.touches[0]:l;var o={};o.oLastSwipemove={screenX:m.screenX,screenY:m.screenY,timestamp:new Date().getTime()};o.oStartTouch={screenX:m.screenX,screenY:m.screenY,timestamp:new Date().getTime()};k.data("ojQueryGestures",c.extend(true,n,o))}function g(t){var v=jQuery(t.currentTarget);var s=v.data("ojQueryGestures");var q=!!t.touches;var l=(q)?t.changedTouches[0].screenX:t.screenX;var k=(q)?t.changedTouches[0].screenY:t.screenY;var r=s.oLastSwipemove;var o=l-r.screenX;var n=k-r.screenY;var u;if(!!s.oLastSwipemove){u=d({type:"swipemove",touches:(q)?t.touches.length:"1",screenY:k,screenX:l,deltaY:n,deltaX:o,startMove:r,event:t,timestamp:r.timestamp});v.triggerHandler(u.type,u)}var m={};var p=(t.touches)?t.touches[0]:t;m.oLastSwipemove={screenX:p.screenX,screenY:p.screenY,timestamp:new Date().getTime()};v.data("ojQueryGestures",c.extend(true,s,m))}function j(r){var v=jQuery(r.currentTarget);var x=!!r.changedTouches;var u=(x)?r.changedTouches.length:"1";var p=(x)?r.changedTouches[0].screenX:r.screenX;var o=(x)?r.changedTouches[0].screenY:r.screenY;v.triggerHandler(c.jGestures.events.touchendStart,r);if(c.hasGestures){r.currentTarget.removeEventListener("touchmove",g,false);r.currentTarget.removeEventListener("touchend",j,false)}else{v.unbind("mousemove",g);v.unbind("mouseup",j)}var m=v.data("ojQueryGestures");var y=(Math.abs(m.oStartTouch.screenX-p)>c.jGestures.defaults.thresholdMove||Math.abs(m.oStartTouch.screenY-o)>c.jGestures.defaults.thresholdMove)?true:false;var B=(Math.abs(m.oStartTouch.screenX-p)>c.jGestures.defaults.thresholdSwipe||Math.abs(m.oStartTouch.screenY-o)>c.jGestures.defaults.thresholdSwipe)?true:false;var A;var t;var n;var l;var k;var q;var w=["zero","one","two","three","four"];var s;for(A in m){t=m.oStartTouch;n={};p=(x)?r.changedTouches[0].screenX:r.screenX;o=(x)?r.changedTouches[0].screenY:r.screenY;l=p-t.screenX;k=o-t.screenY;q=d({type:"swipe",touches:u,screenY:o,screenX:p,deltaY:k,deltaX:l,startMove:t,event:r,timestamp:t.timestamp});s=false;switch(A){case"swipeone":if(x===false&&u==1&&y===false){break}if(x===false||(u==1&&y===true&&B===true)){s=true;q.type=["swipe",w[u]].join("");v.triggerHandler(q.type,q)}break;case"swipetwo":if((x&&u==2&&y===true&&B===true)){s=true;q.type=["swipe",w[u]].join("");v.triggerHandler(q.type,q)}break;case"swipethree":if((x&&u==3&&y===true&&B===true)){s=true;q.type=["swipe",w[u]].join("");v.triggerHandler(q.type,q)}break;case"swipefour":if((x&&u==4&&y===true&&B===true)){s=true;q.type=["swipe",w[u]].join("");v.triggerHandler(q.type,q)}break;case"swipeup":case"swiperightup":case"swiperight":case"swiperightdown":case"swipedown":case"swipeleftdown":case"swipeleft":case"swipeleftup":if(x&&y===true&&B===true){s=true;q.type=["swipe",((q.delta[0].lastX!=0)?((q.delta[0].lastX>0)?"right":"left"):""),((q.delta[0].lastY!=0)?((q.delta[0].lastY>0)?"down":"up"):"")].join("");v.triggerHandler(q.type,q)}break;case"tapone":case"taptwo":case"tapthree":case"tapfour":if((y!==true&&s!==true)&&(w[u]==A.slice(3))){q.description=["tap",w[u]].join("");q.type=["tap",w[u]].join("");v.triggerHandler(q.type,q)}break}var z={};v.data("ojQueryGestures",c.extend(true,m,z));v.data("ojQueryGestures",c.extend(true,m,z))}v.triggerHandler(c.jGestures.events.touchendProcessed,r)}function e(l){var k=jQuery(l.currentTarget);k.triggerHandler(c.jGestures.events.gesturestart,l);var m=k.data("ojQueryGestures");var n={};n.oStartTouch={timestamp:new Date().getTime()};k.data("ojQueryGestures",c.extend(true,m,n))}function f(l){var k=jQuery(l.currentTarget);var p,m,r,o;var q=k.data("ojQueryGestures");var n;for(n in q){switch(n){case"pinch":p=l.scale;if(((p<1)&&(p%1)<(1-c.jGestures.defaults.thresholdPinchclose))||((p>1)&&(p%1)>(c.jGestures.defaults.thresholdPinchopen))){m=(p<1)?-1:+1;o=d({type:"pinch",scale:p,touches:null,startMove:q.oStartTouch,event:l,timestamp:q.oStartTouch.timestamp,vector:m,description:["pinch:",m,":",((p<1)?"close":"open")].join("")});k.triggerHandler(o.type,o)}break;case"rotate":p=l.rotation;if(((p<1)&&(-1*(p)>c.jGestures.defaults.thresholdRotateccw))||((p>1)&&(p>c.jGestures.defaults.thresholdRotatecw))){m=(p<1)?-1:+1;o=d({type:"rotate",rotation:p,touches:null,startMove:q.oStartTouch,event:l,timestamp:q.oStartTouch.timestamp,vector:m,description:["rotate:",m,":",((p<1)?"counterclockwise":"clockwise")].join("")});k.triggerHandler(o.type,o)}break}}}function i(l){var k=jQuery(l.currentTarget);k.triggerHandler(c.jGestures.events.gestureendStart,l);var n;var o=k.data("ojQueryGestures");var m;for(m in o){switch(m){case"pinchclose":n=l.scale;if((n<1)&&(n%1)<(1-c.jGestures.defaults.thresholdPinchclose)){k.triggerHandler("pinchclose",d({type:"pinchclose",scale:n,vector:-1,touches:null,startMove:o.oStartTouch,event:l,timestamp:o.oStartTouch.timestamp,description:"pinch:-1:close"}))}break;case"pinchopen":n=l.scale;if((n>1)&&(n%1)>(c.jGestures.defaults.thresholdPinchopen)){k.triggerHandler("pinchopen",d({type:"pinchopen",scale:n,vector:+1,touches:null,startMove:o.oStartTouch,event:l,timestamp:o.oStartTouch.timestamp,description:"pinch:+1:open"}))}break;case"rotatecw":n=l.rotation;if((n>1)&&(n>c.jGestures.defaults.thresholdRotatecw)){k.triggerHandler("rotatecw",d({type:"rotatecw",rotation:n,vector:+1,touches:null,startMove:o.oStartTouch,event:l,timestamp:o.oStartTouch.timestamp,description:"rotate:+1:clockwise"}))}break;case"rotateccw":n=l.rotation;if((n<1)&&(-1*(n)>c.jGestures.defaults.thresholdRotateccw)){k.triggerHandler("rotateccw",d({type:"rotateccw",rotation:n,vector:-1,touches:null,startMove:o.oStartTouch,event:l,timestamp:o.oStartTouch.timestamp,description:"rotate:-1:counterclockwise"}))}break}}k.triggerHandler(c.jGestures.events.gestureendProcessed,l)}})(jQuery);


/*!
 * enquire.js v2.1.2 - Awesome Media Queries in JavaScript
 * Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/enquire.js
 * License: MIT (http://www.opensource.org/licenses/mit-license.php)
 */
!function(a,b,c){var d=window.matchMedia;"undefined"!=typeof module&&module.exports?module.exports=c(d):"function"==typeof define&&define.amd?define(function(){return b[a]=c(d)}):b[a]=c(d)}("enquire",this,function(a){"use strict";function b(a,b){var c,d=0,e=a.length;for(d;e>d&&(c=b(a[d],d),c!==!1);d++);}function c(a){return"[object Array]"===Object.prototype.toString.apply(a)}function d(a){return"function"==typeof a}function e(a){this.options=a,!a.deferSetup&&this.setup()}function f(b,c){this.query=b,this.isUnconditional=c,this.handlers=[],this.mql=a(b);var d=this;this.listener=function(a){d.mql=a,d.assess()},this.mql.addListener(this.listener)}function g(){if(!a)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!a("only all").matches}return e.prototype={setup:function(){this.options.setup&&this.options.setup(),this.initialised=!0},on:function(){!this.initialised&&this.setup(),this.options.match&&this.options.match()},off:function(){this.options.unmatch&&this.options.unmatch()},destroy:function(){this.options.destroy?this.options.destroy():this.off()},equals:function(a){return this.options===a||this.options.match===a}},f.prototype={addHandler:function(a){var b=new e(a);this.handlers.push(b),this.matches()&&b.on()},removeHandler:function(a){var c=this.handlers;b(c,function(b,d){return b.equals(a)?(b.destroy(),!c.splice(d,1)):void 0})},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){b(this.handlers,function(a){a.destroy()}),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var a=this.matches()?"on":"off";b(this.handlers,function(b){b[a]()})}},g.prototype={register:function(a,e,g){var h=this.queries,i=g&&this.browserIsIncapable;return h[a]||(h[a]=new f(a,i)),d(e)&&(e={match:e}),c(e)||(e=[e]),b(e,function(b){d(b)&&(b={match:b}),h[a].addHandler(b)}),this},unregister:function(a,b){var c=this.queries[a];return c&&(b?c.removeHandler(b):(c.clear(),delete this.queries[a])),this}},new g});


/*!
 * jQuery UI Touch Punch 0.2.3
 *
 * Copyright 2011–2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.bind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.unbind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}(jQuery);


/*
Stay In Sync - GSAP Sync Helper

@version: 	1.0
@author:	Jonathan Marzullo
@contact: 	jonathanfever@gmail.com

This plugin will listen when switching between browser tabs using the 
HTML5 Visibility API. And will also listen for browser window focus 
and blur events. Add your code to pause and resume when leaving and 
returning to your webpage.

In case you find this class useful (especially in commercial projects)
I am not totally unhappy for a small donation to my PayPal account
jonathanfever@gmail.com

Copyright (c) 2014 Jonathan Marzullo

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

USAGE:
// Stay In Sync (GSAP Sync Helper)
$(window).TabWindowVisibilityManager({
    onFocusCallback: function(){
            
           // tween resume() code goes here	                

    },
    onBlurCallback: function(){
           
           // tween pause() code goes here	

    }
});
*/
(function($){var vis=function(){var stateKey,eventKey,keys={hidden:"visibilitychange",webkitHidden:"webkitvisibilitychange",mozHidden:"mozvisibilitychange",msHidden:"msvisibilitychange"};for(stateKey in keys)if(stateKey in document){eventKey=keys[stateKey];break}return function(c){if(c)document.addEventListener(eventKey,c);return!document[stateKey]}}();$.fn.TabWindowVisibilityManager=function(options){var defaults={onFocusCallback:function(){},onBlurCallback:function(){}};var o=$.extend(defaults,options);var notIE= document.documentMode===undefined,isChromium=window.chrome;this.each(function(){vis(function(){if(vis())setTimeout(function(){o.onFocusCallback()},300);else o.onBlurCallback()});if(notIE&&!isChromium)$(window).on("focusin",function(){setTimeout(function(){o.onFocusCallback()},300)}).on("focusout",function(){o.onBlurCallback()});else if(window.addEventListener){window.addEventListener("focus",function(event){setTimeout(function(){o.onFocusCallback()},300)},false);window.addEventListener("blur",function(event){o.onBlurCallback()}, false)}else{window.attachEvent("focus",function(event){setTimeout(function(){o.onFocusCallback()},300)});window.attachEvent("blur",function(event){o.onBlurCallback()})}});return this}})(jQuery);


/*
* jReject (jQuery Browser Rejection Plugin)
* Version 1.1.0
* URL: http://jreject.turnwheel.com/
* Description: jReject is a easy method of rejecting specific browsers on your site
* Author: Steven Bower (TurnWheel Designs) http://turnwheel.com/
* Copyright: Copyright (c) 2009-2014 Steven Bower under dual MIT/GPLv2 license.
*/
(function($){$.reject=function(options){var opts=$.extend(true,{reject:{all:false,msie:6},display:[],browserShow:true,browserInfo:{chrome:{text:'Google Chrome',url:'http://www.google.com/chrome/',},firefox:{text:'Mozilla Firefox',url:'http://www.mozilla.com/firefox/'},safari:{text:'Safari',url:'http://www.apple.com/safari/download/'},opera:{text:'Opera',url:'http://www.opera.com/download/'},msie:{text:'Internet Explorer',url:'http://www.microsoft.com/windows/Internet-explorer/'}},header:'Did you know that your Internet Browser is out of date?',paragraph1:'Your browser is out of date, and may not be compatible with '+'our website. A list of the most popular web browsers can be '+'found below.',paragraph2:'Just click on the icons to get to the download page',close:true,closeMessage:'By closing this window you acknowledge that your experience '+'on this website may be degraded',closeLink:'Close This Window',closeURL:'#',closeESC:true,closeCookie:false,cookieSettings:{path:'/',expires:0},imagePath:'./images/',overlayBgColor:'#000',overlayOpacity:0.8,fadeInTime:'fast',fadeOutTime:'fast',analytics:false},options);if(opts.display.length<1){opts.display=['chrome','firefox','safari','opera','msie'];}if($.isFunction(opts.beforeReject)){opts.beforeReject();}if(!opts.close){opts.closeESC=false;}var browserCheck=function(settings){var layout=settings[$.layout.name],browser=settings[$.browser.name];return!!(settings['all']||(browser&&(browser===true||$.browser.versionNumber<=browser))||settings[$.browser.className]||(layout&&(layout===true||$.layout.versionNumber<=layout))||settings[$.os.name]);};if(!browserCheck(opts.reject)){if($.isFunction(opts.onFail)){opts.onFail();}return false;}if(opts.close&&opts.closeCookie){var COOKIE_NAME='jreject-close';var _cookie=function(name,value){if(typeof value!='undefined'){var expires='';if(opts.cookieSettings.expires!==0){var date=new Date();date.setTime(date.getTime()+(opts.cookieSettings.expires*1000));expires="; expires="+date.toGMTString();}var path=opts.cookieSettings.path||'/';document.cookie=name+'='+encodeURIComponent((!value)?'':value)+expires+'; path='+path;return true;}else{var cookie,val=null;if(document.cookie&&document.cookie!==''){var cookies=document.cookie.split(';');var clen=cookies.length;for(var i=0;i<clen;++i){cookie=$.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){var len=name.length;val=decodeURIComponent(cookie.substring(len+1));break;}}}return val;}};if(_cookie(COOKIE_NAME)){return false;}}var html='<div id="jr_overlay"></div><div id="jr_wrap"><div id="jr_inner">'+'<h1 id="jr_header">'+opts.header+'</h1>'+(opts.paragraph1===''?'':'<p>'+opts.paragraph1+'</p>')+(opts.paragraph2===''?'':'<p>'+opts.paragraph2+'</p>');var displayNum=0;if(opts.browserShow){html+='<ul>';for(var x in opts.display){var browser=opts.display[x];var info=opts.browserInfo[browser]||false;if(!info||(info['allow']!=undefined&&!browserCheck(info['allow']))){continue;}var url=info.url||'#';html+='<li id="jr_'+browser+'"><div class="jr_icon"></div>'+'<div><a href="'+url+'">'+(info.text||'Unknown')+'</a>'+'</div></li>';++displayNum;}html+='</ul>';}html+='<div id="jr_close">'+(opts.close?'<a href="'+opts.closeURL+'">'+opts.closeLink+'</a>'+'<p>'+opts.closeMessage+'</p>':'')+'</div>'+'</div></div>';var element=$('<div>'+html+'</div>');var size=_pageSize();var scroll=_scrollSize();element.bind('closejr',function(){if(!opts.close){return false;}if($.isFunction(opts.beforeClose)){opts.beforeClose();}$(this).unbind('closejr');$('#jr_overlay,#jr_wrap').fadeOut(opts.fadeOutTime,function(){$(this).remove();if($.isFunction(opts.afterClose)){opts.afterClose();}});var elmhide='embed.jr_hidden, object.jr_hidden, select.jr_hidden, applet.jr_hidden';$(elmhide).show().removeClass('jr_hidden');if(opts.closeCookie){_cookie(COOKIE_NAME,'true');}return true;});var analytics=function(url){if(!opts.analytics){return false;}var host=url.split(/\/+/g)[1];try{ga('send','event','External','Click',host,url);}catch(e){try{_gaq.push(['_trackEvent','External Links',host,url]);}catch(e){}}};var openBrowserLinks=function(url){analytics(url);window.open(url,'jr_'+Math.round(Math.random()*11));return false;};element.find('#jr_overlay').css({width:size[0],height:size[1],background:opts.overlayBgColor,opacity:opts.overlayOpacity});element.find('#jr_wrap').css({top:scroll[1]+(size[3]/4),left:scroll[0]});element.find('#jr_inner').css({minWidth:displayNum*100,maxWidth:displayNum*140,width:$.layout.name=='trident'?displayNum*155:'auto'});element.find('#jr_inner li').css({background:'transparent url("'+opts.imagePath+'background_browser.gif")'+'no-repeat scroll left top'});element.find('#jr_inner li .jr_icon').each(function(){var self=$(this);self.css('background','transparent url('+opts.imagePath+'browser_'+(self.parent('li').attr('id').replace(/jr_/,''))+'.gif)'+' no-repeat scroll left top');self.click(function(){var url=$(this).next('div').children('a').attr('href');openBrowserLinks(url);});});element.find('#jr_inner li a').click(function(){openBrowserLinks($(this).attr('href'));return false;});element.find('#jr_close a').click(function(){$(this).trigger('closejr');if(opts.closeURL==='#'){return false;}});$('#jr_overlay').focus();$('embed, object, select, applet').each(function(){if($(this).is(':visible')){$(this).hide().addClass('jr_hidden');}});$('body').append(element.hide().fadeIn(opts.fadeInTime));$(window).bind('resize scroll',function(){var size=_pageSize();$('#jr_overlay').css({width:size[0],height:size[1]});var scroll=_scrollSize();$('#jr_wrap').css({top:scroll[1]+(size[3]/4),left:scroll[0]});});if(opts.closeESC){$(document).bind('keydown',function(event){if(event.keyCode==27){element.trigger('closejr');}});}if($.isFunction(opts.afterReject)){opts.afterReject();}return true;};var _pageSize=function(){var xScroll=window.innerWidth&&window.scrollMaxX?window.innerWidth+window.scrollMaxX:(document.body.scrollWidth>document.body.offsetWidth?document.body.scrollWidth:document.body.offsetWidth);var yScroll=window.innerHeight&&window.scrollMaxY?window.innerHeight+window.scrollMaxY:(document.body.scrollHeight>document.body.offsetHeight?document.body.scrollHeight:document.body.offsetHeight);var windowWidth=window.innerWidth?window.innerWidth:(document.documentElement&&document.documentElement.clientWidth?document.documentElement.clientWidth:document.body.clientWidth);var windowHeight=window.innerHeight?window.innerHeight:(document.documentElement&&document.documentElement.clientHeight?document.documentElement.clientHeight:document.body.clientHeight);return[xScroll<windowWidth?xScroll:windowWidth,yScroll<windowHeight?windowHeight:yScroll,windowWidth,windowHeight];};var _scrollSize=function(){return[window.pageXOffset?window.pageXOffset:(document.documentElement&&document.documentElement.scrollTop?document.documentElement.scrollLeft:document.body.scrollLeft),window.pageYOffset?window.pageYOffset:(document.documentElement&&document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop)];};})(jQuery);(function($){$.browserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;if(!r.opera){r.version=(c.exec(i)||[x,x,x,x])[3];}else{r.version=window.opera.version();}if(/safari/.test(r.name)){var safariversion=/(safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/;var res=safariversion.exec(i);if(res&&res[3]&&res[3]<400){r.version='2.0';}}else if(r.name==='presto'){r.version=($.browser.version>9.27)?'futhark':'linear_b';}if(/msie/.test(r.name)&&r.version===x){var ieVersion=/rv:(\d+\.\d+)/.exec(i);r.version=ieVersion[1];}r.versionNumber=parseFloat(r.version,10)||0;var minorStart=1;if(r.versionNumber<100&&r.versionNumber>9){minorStart=2;}r.versionX=(r.version!==x)?r.version.substr(0,minorStart):x;r.className=r.name+r.versionX;return r;};a=(/Opera|Navigator|Minefield|KHTML|Chrome|CriOS/.test(a)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['CriOS','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.browser=$.extend((!z)?$.browser:{},c(a,/(camino|chrome|crios|firefox|netscape|konqueror|lynx|msie|trident|opera|safari)/,[['trident','msie']],/(camino|chrome|crios|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|rv|safari)(:|\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|trident|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone|ipad)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.browser.name,$.browser.className,$.layout.name,$.layout.className].join(' '));}};$.browserTest(navigator.userAgent);}(jQuery));


/*
 * noUiSlider: lightweight JavaScript range slider
 * noUiSlider - 8.0.1 - 2015-06-29 19:11:22
 * http://refreshless.com/nouislider/
 */
!function(a){"function"==typeof define&&define.amd?define([],a):"object"==typeof exports?module.exports=a(require("jquery")):window.noUiSlider=a()}(function(){"use strict";function a(a){return a.filter(function(a){return this[a]?!1:this[a]=!0},{})}function b(a,b){return Math.round(a/b)*b}function c(a){var b=a.getBoundingClientRect(),c=a.ownerDocument,d=c.defaultView||c.parentWindow,e=c.documentElement,f=d.pageXOffset;return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(f=0),{top:b.top+d.pageYOffset-e.clientTop,left:b.left+f-e.clientLeft}}function d(a){return"number"==typeof a&&!isNaN(a)&&isFinite(a)}function e(a){var b=Math.pow(10,7);return Number((Math.round(a*b)/b).toFixed(7))}function f(a,b,c){k(a,b),setTimeout(function(){l(a,b)},c)}function g(a){return Math.max(Math.min(a,100),0)}function h(a){return Array.isArray(a)?a:[a]}function j(a){var b=a.split(".");return b.length>1?b[1].length:0}function k(a,b){a.classList?a.classList.add(b):a.className+=" "+b}function l(a,b){a.classList?a.classList.remove(b):a.className=a.className.replace(new RegExp("(^|\\b)"+b.split(" ").join("|")+"(\\b|$)","gi")," ")}function m(a,b){a.classList?a.classList.contains(b):new RegExp("(^| )"+b+"( |$)","gi").test(a.className)}function n(a,b){return 100/(b-a)}function o(a,b){return 100*b/(a[1]-a[0])}function p(a,b){return o(a,a[0]<0?b+Math.abs(a[0]):b-a[0])}function q(a,b){return b*(a[1]-a[0])/100+a[0]}function r(a,b){for(var c=1;a>=b[c];)c+=1;return c}function s(a,b,c){if(c>=a.slice(-1)[0])return 100;var d,e,f,g,h=r(c,a);return d=a[h-1],e=a[h],f=b[h-1],g=b[h],f+p([d,e],c)/n(f,g)}function t(a,b,c){if(c>=100)return a.slice(-1)[0];var d,e,f,g,h=r(c,b);return d=a[h-1],e=a[h],f=b[h-1],g=b[h],q([d,e],(c-f)*n(f,g))}function u(a,c,d,e){if(100===e)return e;var f,g,h=r(e,a);return d?(f=a[h-1],g=a[h],e-f>(g-f)/2?g:f):c[h-1]?a[h-1]+b(e-a[h-1],c[h-1]):e}function v(a,b,c){var e;if("number"==typeof b&&(b=[b]),"[object Array]"!==Object.prototype.toString.call(b))throw new Error("noUiSlider: 'range' contains invalid value.");if(e="min"===a?0:"max"===a?100:parseFloat(a),!d(e)||!d(b[0]))throw new Error("noUiSlider: 'range' value isn't numeric.");c.xPct.push(e),c.xVal.push(b[0]),e?c.xSteps.push(isNaN(b[1])?!1:b[1]):isNaN(b[1])||(c.xSteps[0]=b[1])}function w(a,b,c){return b?void(c.xSteps[a]=o([c.xVal[a],c.xVal[a+1]],b)/n(c.xPct[a],c.xPct[a+1])):!0}function x(a,b,c,d){this.xPct=[],this.xVal=[],this.xSteps=[d||!1],this.xNumSteps=[!1],this.snap=b,this.direction=c;var e,f=[];for(e in a)a.hasOwnProperty(e)&&f.push([a[e],e]);for(f.sort(function(a,b){return a[0]-b[0]}),e=0;e<f.length;e++)v(f[e][1],f[e][0],this);for(this.xNumSteps=this.xSteps.slice(0),e=0;e<this.xNumSteps.length;e++)w(e,this.xNumSteps[e],this)}function y(a,b){if(!d(b))throw new Error("noUiSlider: 'step' is not numeric.");a.singleStep=b}function z(a,b){if("object"!=typeof b||Array.isArray(b))throw new Error("noUiSlider: 'range' is not an object.");if(void 0===b.min||void 0===b.max)throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");a.spectrum=new x(b,a.snap,a.dir,a.singleStep)}function A(a,b){if(b=h(b),!Array.isArray(b)||!b.length||b.length>2)throw new Error("noUiSlider: 'start' option is incorrect.");a.handles=b.length,a.start=b}function B(a,b){if(a.snap=b,"boolean"!=typeof b)throw new Error("noUiSlider: 'snap' option must be a boolean.")}function C(a,b){if(a.animate=b,"boolean"!=typeof b)throw new Error("noUiSlider: 'animate' option must be a boolean.")}function D(a,b){if("lower"===b&&1===a.handles)a.connect=1;else if("upper"===b&&1===a.handles)a.connect=2;else if(b===!0&&2===a.handles)a.connect=3;else{if(b!==!1)throw new Error("noUiSlider: 'connect' option doesn't match handle count.");a.connect=0}}function E(a,b){switch(b){case"horizontal":a.ort=0;break;case"vertical":a.ort=1;break;default:throw new Error("noUiSlider: 'orientation' option is invalid.")}}function F(a,b){if(!d(b))throw new Error("noUiSlider: 'margin' option must be numeric.");if(a.margin=a.spectrum.getMargin(b),!a.margin)throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.")}function G(a,b){if(!d(b))throw new Error("noUiSlider: 'limit' option must be numeric.");if(a.limit=a.spectrum.getMargin(b),!a.limit)throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.")}function H(a,b){switch(b){case"ltr":a.dir=0;break;case"rtl":a.dir=1,a.connect=[0,2,1,3][a.connect];break;default:throw new Error("noUiSlider: 'direction' option was not recognized.")}}function I(a,b){if("string"!=typeof b)throw new Error("noUiSlider: 'behaviour' must be a string containing options.");var c=b.indexOf("tap")>=0,d=b.indexOf("drag")>=0,e=b.indexOf("fixed")>=0,f=b.indexOf("snap")>=0;a.events={tap:c||f,drag:d,fixed:e,snap:f}}function J(a,b){if(a.format=b,"function"==typeof b.to&&"function"==typeof b.from)return!0;throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.")}function K(a){var b,c={margin:0,limit:0,animate:!0,format:V};b={step:{r:!1,t:y},start:{r:!0,t:A},connect:{r:!0,t:D},direction:{r:!0,t:H},snap:{r:!1,t:B},animate:{r:!1,t:C},range:{r:!0,t:z},orientation:{r:!1,t:E},margin:{r:!1,t:F},limit:{r:!1,t:G},behaviour:{r:!0,t:I},format:{r:!1,t:J}};var d={connect:!1,direction:"ltr",behaviour:"tap",orientation:"horizontal"};return Object.keys(d).forEach(function(b){void 0===a[b]&&(a[b]=d[b])}),Object.keys(b).forEach(function(d){var e=b[d];if(void 0===a[d]){if(e.r)throw new Error("noUiSlider: '"+d+"' is required.");return!0}e.t(c,a[d])}),c.pips=a.pips,c.style=c.ort?"top":"left",c}function L(a,b,c){var d=a+b[0],e=a+b[1];return c?(0>d&&(e+=Math.abs(d)),e>100&&(d-=e-100),[g(d),g(e)]):[d,e]}function M(a){a.preventDefault();var b,c,d=0===a.type.indexOf("touch"),e=0===a.type.indexOf("mouse"),f=0===a.type.indexOf("pointer"),g=a;return 0===a.type.indexOf("MSPointer")&&(f=!0),d&&(b=a.changedTouches[0].pageX,c=a.changedTouches[0].pageY),(e||f)&&(b=a.clientX+window.pageXOffset,c=a.clientY+window.pageYOffset),g.points=[b,c],g.cursor=e||f,g}function N(a,b){var c=document.createElement("div"),d=document.createElement("div"),e=["-lower","-upper"];return a&&e.reverse(),k(d,U[3]),k(d,U[3]+e[b]),k(c,U[2]),c.appendChild(d),c}function O(a,b,c){switch(a){case 1:k(b,U[7]),k(c[0],U[6]);break;case 3:k(c[1],U[6]);case 2:k(c[0],U[7]);case 0:k(b,U[6])}}function P(a,b,c){var d,e=[];for(d=0;a>d;d+=1)e.push(c.appendChild(N(b,d)));return e}function Q(a,b,c){k(c,U[0]),k(c,U[8+a]),k(c,U[4+b]);var d=document.createElement("div");return k(d,U[1]),c.appendChild(d),d}function R(b,d){function e(a,b,c){if("range"===a||"steps"===a)return N.xVal;if("count"===a){var d,e=100/(b-1),f=0;for(b=[];(d=f++*e)<=100;)b.push(d);a="positions"}return"positions"===a?b.map(function(a){return N.fromStepping(c?N.getStep(a):a)}):"values"===a?c?b.map(function(a){return N.fromStepping(N.getStep(N.toStepping(a)))}):b:void 0}function n(b,c,d){var e=N.direction,f={},g=N.xVal[0],h=N.xVal[N.xVal.length-1],i=!1,j=!1,k=0;return N.direction=0,d=a(d.slice().sort(function(a,b){return a-b})),d[0]!==g&&(d.unshift(g),i=!0),d[d.length-1]!==h&&(d.push(h),j=!0),d.forEach(function(a,e){var g,h,l,m,n,o,p,q,r,s,t=a,u=d[e+1];if("steps"===c&&(g=N.xNumSteps[e]),g||(g=u-t),t!==!1&&void 0!==u)for(h=t;u>=h;h+=g){for(m=N.toStepping(h),n=m-k,q=n/b,r=Math.round(q),s=n/r,l=1;r>=l;l+=1)o=k+l*s,f[o.toFixed(5)]=["x",0];p=d.indexOf(h)>-1?1:"steps"===c?2:0,!e&&i&&(p=0),h===u&&j||(f[m.toFixed(5)]=[h,p]),k=m}}),N.direction=e,f}function o(a,b,c){function e(a){return["-normal","-large","-sub"][a]}function f(a,b,c){return'class="'+b+" "+b+"-"+h+" "+b+e(c[1],c[0])+'" style="'+d.style+": "+a+'%"'}function g(a,d){N.direction&&(a=100-a),d[1]=d[1]&&b?b(d[0],d[1]):d[1],i.innerHTML+="<div "+f(a,"noUi-marker",d)+"></div>",d[1]&&(i.innerHTML+="<div "+f(a,"noUi-value",d)+">"+c.to(d[0])+"</div>")}var h=["horizontal","vertical"][d.ort],i=document.createElement("div");return k(i,"noUi-pips"),k(i,"noUi-pips-"+h),Object.keys(a).forEach(function(b){g(b,a[b])}),i}function p(a){var b=a.mode,c=a.density||1,d=a.filter||!1,f=a.values||!1,g=a.stepped||!1,h=e(b,f,g),i=n(c,b,h),j=a.format||{to:Math.round};return J.appendChild(o(i,d,j))}function q(){return H["offset"+["Width","Height"][d.ort]]}function r(a,b){void 0!==b&&(b=Math.abs(b-d.dir)),Object.keys(S).forEach(function(c){var d=c.split(".")[0];a===d&&S[c].forEach(function(a){a(h(C()),b,s(Array.prototype.slice.call(R)))})})}function s(a){return 1===a.length?a[0]:d.dir?a.reverse():a}function t(a,b,c,e){var f=function(b){return J.hasAttribute("disabled")?!1:m(J,U[14])?!1:(b=M(b),a===T.start&&void 0!==b.buttons&&b.buttons>1?!1:(b.calcPoint=b.points[d.ort],void c(b,e)))},g=[];return a.split(" ").forEach(function(a){b.addEventListener(a,f,!1),g.push([a,f])}),g}function u(a,b){var c,d=b.handles||I,e=!1,f=100*(a.calcPoint-b.start)/q(),g=d[0]===I[0]?0:1;if(c=L(f,b.positions,d.length>1),e=z(d[0],c[g],1===d.length),d.length>1){if(e=z(d[1],c[g?0:1],!1)||e)for(i=0;i<b.handles.length;i++)r("slide",i)}else e&&r("slide",g)}function v(a,b){var c=H.getElementsByClassName(U[15]),d=b.handles[0]===I[0]?0:1;c.length&&l(c[0],U[15]),a.cursor&&(document.body.style.cursor="",document.body.removeEventListener("selectstart",document.body.noUiListener));var e=document.documentElement;e.noUiListeners.forEach(function(a){e.removeEventListener(a[0],a[1])}),l(J,U[12]),r("set",d),r("change",d)}function w(a,b){var c=document.documentElement;if(1===b.handles.length&&(k(b.handles[0].children[0],U[15]),b.handles[0].hasAttribute("disabled")))return!1;a.stopPropagation();var d=t(T.move,c,u,{start:a.calcPoint,handles:b.handles,positions:[K[0],K[I.length-1]]}),e=t(T.end,c,v,{handles:b.handles});if(c.noUiListeners=d.concat(e),a.cursor){document.body.style.cursor=getComputedStyle(a.target).cursor,I.length>1&&k(J,U[12]);var f=function(){return!1};document.body.noUiListener=f,document.body.addEventListener("selectstart",f,!1)}}function x(a){var b,e,g=a.calcPoint,h=0;return a.stopPropagation(),I.forEach(function(a){h+=c(a)[d.style]}),b=h/2>g||1===I.length?0:1,g-=c(H)[d.style],e=100*g/q(),d.events.snap||f(J,U[14],300),I[b].hasAttribute("disabled")?!1:(z(I[b],e),r("slide",b),r("set",b),r("change",b),void(d.events.snap&&w(a,{handles:[I[h]]})))}function y(a){var b,c;if(!a.fixed)for(b=0;b<I.length;b+=1)t(T.start,I[b].children[0],w,{handles:[I[b]]});a.tap&&t(T.start,H,x,{handles:I}),a.drag&&(c=[H.getElementsByClassName(U[7])[0]],k(c[0],U[10]),a.fixed&&c.push(I[c[0]===I[0]?1:0].children[0]),c.forEach(function(a){t(T.start,a,w,{handles:I})}))}function z(a,b,c){var e=a!==I[0]?1:0,f=K[0]+d.margin,h=K[1]-d.margin,i=K[0]+d.limit,j=K[1]-d.limit;return I.length>1&&(b=e?Math.max(b,f):Math.min(b,h)),c!==!1&&d.limit&&I.length>1&&(b=e?Math.min(b,i):Math.max(b,j)),b=N.getStep(b),b=g(parseFloat(b.toFixed(7))),b===K[e]?!1:(a.style[d.style]=b+"%",a.previousSibling||(l(a,U[17]),b>50&&k(a,U[17])),K[e]=b,R[e]=N.fromStepping(b),r("update",e),!0)}function A(a,b){var c,e,f;for(d.limit&&(a+=1),c=0;a>c;c+=1)e=c%2,f=b[e],null!==f&&f!==!1&&("number"==typeof f&&(f=String(f)),f=d.format.from(f),(f===!1||isNaN(f)||z(I[e],N.toStepping(f),c===3-d.dir)===!1)&&r("update",e))}function B(a){var b,c,e=h(a);for(d.dir&&d.handles>1&&e.reverse(),d.animate&&-1!==K[0]&&f(J,U[14],300),b=I.length>1?3:1,1===e.length&&(b=1),A(b,e),c=0;c<I.length;c++)r("set",c)}function C(){var a,b=[];for(a=0;a<d.handles;a+=1)b[a]=d.format.to(R[a]);return s(b)}function D(){U.forEach(function(a){a&&l(J,a)}),J.innerHTML="",delete J.noUiSlider}function E(){var a=K.map(function(a,b){var c=N.getApplicableStep(a),d=j(String(c[2])),e=R[b],f=100===a?null:c[2],g=Number((e-c[2]).toFixed(d)),h=0===a?null:g>=c[1]?c[2]:c[0]||!1;return[h,f]});return s(a)}function F(a,b){S[a]=S[a]||[],S[a].push(b),"update"===a.split(".")[0]&&I.forEach(function(a,b){r("update",b)})}function G(a){var b=a.split(".")[0],c=a.substring(b.length);Object.keys(S).forEach(function(a){var d=a.split(".")[0],e=a.substring(d.length);b&&b!==d||c&&c!==e||delete S[a]})}var H,I,J=b,K=[-1,-1],N=d.spectrum,R=[],S={};if(J.noUiSlider)throw new Error("Slider was already initialized.");return H=Q(d.dir,d.ort,J),I=P(d.handles,d.dir,H),O(d.connect,J,I),y(d.events),d.pips&&p(d.pips),{destroy:D,steps:E,on:F,off:G,get:C,set:B}}function S(a,b){if(!a.nodeName)throw new Error("noUiSlider.create requires a single element.");var c=K(b,a),d=R(a,c);d.set(c.start),a.noUiSlider=d}var T=window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"},U=["noUi-target","noUi-base","noUi-origin","noUi-handle","noUi-horizontal","noUi-vertical","noUi-background","noUi-connect","noUi-ltr","noUi-rtl","noUi-dragable","","noUi-state-drag","","noUi-state-tap","noUi-active","","noUi-stacking"];x.prototype.getMargin=function(a){return 2===this.xPct.length?o(this.xVal,a):!1},x.prototype.toStepping=function(a){return a=s(this.xVal,this.xPct,a),this.direction&&(a=100-a),a},x.prototype.fromStepping=function(a){return this.direction&&(a=100-a),e(t(this.xVal,this.xPct,a))},x.prototype.getStep=function(a){return this.direction&&(a=100-a),a=u(this.xPct,this.xSteps,this.snap,a),this.direction&&(a=100-a),a},x.prototype.getApplicableStep=function(a){var b=r(a,this.xPct),c=100===a?2:1;return[this.xNumSteps[b-2],this.xVal[b-c],this.xNumSteps[b-c]]},x.prototype.convert=function(a){return this.getStep(this.toStepping(a))};var V={to:function(a){return a.toFixed(2)},from:Number};return{create:S}});


/*
 * JavaScript Number & Money formatting
 * http://refreshless.com/wnumb/
 */ 
(function(){function r(b){return b.split("").reverse().join("")}function s(b,f,c){if((b[f]||b[c])&&b[f]===b[c])throw Error(f);}function v(b,f,c,d,e,p,q,k,l,h,n,a){q=a;var m,g=n="";p&&(a=p(a));if("number"!==typeof a||!isFinite(a))return!1;b&&0===parseFloat(a.toFixed(b))&&(a=0);0>a&&(m=!0,a=Math.abs(a));b&&(p=Math.pow(10,b),a=(Math.round(a*p)/p).toFixed(b));a=a.toString();-1!==a.indexOf(".")&&(b=a.split("."),a=b[0],c&&(n=c+b[1]));f&&(a=r(a).match(/.{1,3}/g),a=r(a.join(r(f))));m&&k&&(g+=k);d&&(g+=d);
m&&l&&(g+=l);g=g+a+n;e&&(g+=e);h&&(g=h(g,q));return g}function w(b,f,c,d,e,h,q,k,l,r,n,a){var m;b="";n&&(a=n(a));if(!a||"string"!==typeof a)return!1;k&&a.substring(0,k.length)===k&&(a=a.replace(k,""),m=!0);d&&a.substring(0,d.length)===d&&(a=a.replace(d,""));l&&a.substring(0,l.length)===l&&(a=a.replace(l,""),m=!0);e&&a.slice(-1*e.length)===e&&(a=a.slice(0,-1*e.length));f&&(a=a.split(f).join(""));c&&(a=a.replace(c,"."));m&&(b+="-");b=Number((b+a).replace(/[^0-9\.\-.]/g,""));q&&(b=q(b));return"number"===
typeof b&&isFinite(b)?b:!1}function x(b){var f,c,d,e={};for(f=0;f<h.length;f+=1)c=h[f],d=b[c],void 0===d?e[c]="negative"!==c||e.negativeBefore?"mark"===c&&"."!==e.thousand?".":!1:"-":"decimals"===c?0<d&&8>d&&(e[c]=d):"encoder"===c||"decoder"===c||"edit"===c||"undo"===c?"function"===typeof d&&(e[c]=d):"string"===typeof d&&(e[c]=d);s(e,"mark","thousand");s(e,"prefix","negative");s(e,"prefix","negativeBefore");return e}function u(b,f,c){var d,e=[];for(d=0;d<h.length;d+=1)e.push(b[h[d]]);e.push(c);return f.apply("",
e)}function t(b){if(!(this instanceof t))return new t(b);"object"===typeof b&&(b=x(b),this.to=function(f){return u(b,v,f)},this.from=function(f){return u(b,w,f)})}var h="decimals thousand mark prefix postfix encoder decoder negativeBefore negative edit undo".split(" ");window.wNumb=t})();










;


$(function () {
	MyKB.init();
});

var postLoginURL = "";

var MyKB = {

    optisRegistered: false,

    init: function () {
        /*to call reveal modal box 
        Use following on <a href="">
		 
        <a href="" data-reveal-id="login-dialog">
		 
        to call via code 
		 
        $('#login-dialog').foundation('reveal', 'open');
		 
        * */


        $.validator.unobtrusive.adapters.addBool("mandatory", "required");

        MyKB.initPlaceholderSupport();


        $("#create-account").click(function () {
            $('#login-dialog .close-reveal-modal').trigger('click.modalEvent');

            MyKB.populateRegistrationDropDowns();

            MyKB.afterLogin = function () {
                $('#registered-confirm-dialog #confirm-message').html("You can now save communities and floor plans to your MyKB profile.");
                $('#registered-confirm-dialog').foundation('reveal', 'open');
                dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-New' });
                console.info('GTM-MKB001 event: pushedVPV, virtualPageview: /MyKb-New');
            };
        });

        $("#have-account").click(function () {
            $('#register-dialog .close-reveal-modal').trigger('click.modalEvent');
            //$('#login-dialog').foundation('reveal', 'open');
            if ($.isFunction(MyKB.afterLogin)) {
                var cached_function = MyKB.afterLogin;
                MyKB.afterLogin = function () {                    
                    cached_function.apply(this);
                };
            } else {
                MyKB.afterLogin = function () {
                    $(this).closest(".reveal-modal").find(".close-reveal-modal").trigger('click.modalEvent');
                    location.href = App.Url("/My-KB");
                };
            }            
            dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Return' });
            console.info('GTM-MKB002 event: pushedVPV, virtualPageview: /MyKb-Return');          
        });

        $("#create-broker-account").click(function () {
            $("#IsBroker").val("true");
            $("#switch-account-type").text("Home Buyers Sign Up Here");
            $('#login-dialog .close-reveal-modal').trigger('click.modalEvent');

            MyKB.populateRegistrationDropDowns();

            MyKB.afterLogin = function () {
                $('#registered-confirm-dialog #confirm-message').html("You can now save communities and floor plans to your MyKB profile.");
                $('#registered-confirm-dialog').foundation('reveal', 'open');
                dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-New' });
                console.info('GTM-MKB003 event: pushedVPV, virtualPageview: /MyKb-New');
            };
        });



		////TOGGLE UI Element
		// With options (defaults shown below)
		$('.broker-toggle').toggles({
		    drag: true, // can the toggle be dragged
		    click: true, // can it be clicked to toggle
		    text: {
		      on: 'YES', // text for the ON position
		      off: 'NO' // and off
		    },
		    on: false, // is the toggle ON on init
		    animate: 250, // animation time
		    transition: 'ease-in-out', // animation transition,
		    checkbox: null, // the checkbox to toggle (for use in forms)
		    clicker: null, // element that can be clicked on to toggle. removes binding from the toggle itself (use nesting)
		    width: 60, // width used if not set in css
		    height: 25, // height if not set in css
		    type: 'compact' // if this is set to 'select' then the select style toggle will be used
		});
	
	
		// Getting notified of changes, and the new state:
		$('.broker-toggle').on('toggle', function (e, active) {
		    if (active) {
		        $('input#IsBroker').val('true');
		        $('#reg-title').addClass('broker');
		        $('#reg-title h3').html('Create a <span class="pre">MyKB</span> Broker Profile');
	            dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'KB Broker', 'eventAction': 'Click', 'eventLabel': 'BrokersSignUpHere:' + window.location.pathname });
	            console.info('GTM-MKB004 event: pushedEvent, eventAction: Click, eventCategory: KB Broker, eventLabel: BrokersSignUpHere:' + window.location.pathname);
		    } else {
		        $('input#IsBroker').val('false');
		        $('#reg-title').removeClass('broker');
		        $('#reg-title h3').html('Create a <span class="pre">MyKB</span> Profile');
	            dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'My KB', 'eventAction': 'Click', 'eventLabel': 'HomeBuyersSignUpHere:' + window.location.pathname });
	            console.info('GTM-MKB005 event: pushedEvent, eventAction: Click, eventCategory: My KB, eventLabel: HomeBuyersSignUpHere:' + window.location.pathname);
		    }
		});




        $("#broker-create").click(function (e) {
            if ($("#mykb").attr("data-logged-in") == "True") {
                location.href = App.Url("/My-KB/");
                return;
            }	        
            $('.broker-toggle').toggles({on: true});			        
            $("#IsBroker").val("true");
            $('#reg-title').addClass('broker');
	        $('#reg-title h3').html('Create a <span class="pre">MyKB</span> Broker Profile');
            $('#register-dialog').foundation('reveal', 'open');
            e.preventDefault();
            dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Create' });
            console.info('GTM-MKB006 event: pushedVPV, virtualPageview: /MyKb-Create');
        });

        $("#homebuyer-create").click(function (e) {
            if ($("#mykb").attr("data-logged-in") == "True") {
                location.href = App.Url("/My-KB/");
                return;
            }
            $('.broker-toggle').toggles({ on: false });
            $('#reg-title h3').html('Create a <span class="pre">MyKB</span> Profile');
            $('#register-dialog').foundation('reveal', 'open');
            e.preventDefault();
            dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Create' });
            console.info('GTM-MKB007 event: pushedVPV, virtualPageview: /MyKb-Create');
        });

        //BEGIN FACEBOOK LOGIN/REGISTER ///////////
        //var FB_app_id = "239739552770716"; //production
        //var FB_app_id = "285358881518854"; //staging
        var FB_redir_url = $("base").attr("href");

        $("#facebook-login").click(function () {
            console.log('ID: ' + FB_APP_ID);
            $('#login-dialog .close-reveal-modal').trigger('click.modalEvent');
            var url = "https://www.facebook.com/dialog/oauth/?scope=email&client_id=" + FB_APP_ID + "&redirect_uri=" + FB_redir_url + "My-KB/FacebookLogin";
            var windowSize = "width=1024,height=525,scrollbars=no";
            window.open(url, 'popup', windowSize);
            return false;
        });

        $("#facebook-register").click(function () {
            $('#login-dialog .close-reveal-modal').trigger('click.modalEvent');
            var url = "https://www.facebook.com/dialog/oauth/?scope=email&client_id=" + FB_APP_ID + "&redirect_uri=" + FB_redir_url + "My-KB/FacebookLogin";
            var windowSize = "width=1024,height=525,scrollbars=no";
            window.open(url, 'popup', windowSize);
            return false;
        });
        


        // forgot password
        //
        $(".forgot-password-link").click(function () {
            $('#login-dialog .close-reveal-modal').trigger('click.modalEvent');
            $('#forgot-password-dialog').foundation('reveal', 'open');
            return false;
        });


        $(".close-button").click(function () {
            $(this).closest(".reveal-modal").find(".close-reveal-modal").trigger('click.modalEvent');
        });

        $(".mykb-button").click(function () {
            $(this).closest(".reveal-modal").find(".close-reveal-modal").trigger('click.modalEvent');
            location.href = App.Url("/My-KB");
        });





        $("#mykb, .mykb.mtab").click(function (e) {
            if (!($(this).hasClass("logout"))) {
                e.preventDefault();
                if ($(this).attr("data-login-url")) {
                    location.href = $(this).attr("data-login-url");
                    return false;
                }

                if ($(this).attr("data-logged-in") === "True") {
                    location.href = App.Url("/My-KB/");
                    return false;
                }

                var registered = $.cookie('ExistingUser');
                if (registered != null) {
                    $('#login-dialog').foundation('reveal', 'open');
                    dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Login' });
                    console.info('GTM-MKB007 event: pushedVPV, virtualPageview: /MyKb-Login');
                    return false;
                }
                else {
                    $('#register-dialog').foundation('reveal', 'open');
                    MyKB.populateRegistrationDropDowns();
                    dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Create' });
                    console.info('GTM-MKB008 event: pushedVPV, virtualPageview: /MyKb-Create');
                    return false;
                }

                $('#login-dialog').foundation('reveal', 'open');
                dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Login' });
                console.info('GTM-MKB009 event: pushedVPV, virtualPageview: /MyKb-Login');
                return false;

                MyKB.afterLogin = function () { location.href = App.Url("/My-KB/"); };
            }
            else {
                location.href = App.Url("/My-KB/Logout");
            }
        });



        $("#save-community").change(function() {
            var id = $(this).val();
            if ($("#mykb").attr("data-logged-in") == "True") {
                try {
                    ewt.track({ name: communityName, type: 'savefloorplan' });
                    console.info('GTM-MKB010 ewt.track - name: ' + communityName + ', type: savefloorplan');
                }
                catch (err) {
                }
                MyKB.saveCommunity(id);
                return false;
            }

            // not logged in, set the afterLogin callback and prompt the user
            // to log in.
            MyKB.afterLogin = function () {
                try {
                    ewt.track({ name: communityName, type: 'savefloorplan' });
                    console.info('GTM-MKB011 ewt.track - name: ' + communityName + ', type: savefloorplan');
                }
                catch (err) {
                }
                MyKB.saveCommunity(id);
            };

            var registered = $.cookie('ExistingUser');
            if (registered != null) {
                $('#login-dialog').foundation('reveal', 'open');
                dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Login' });
                console.info('GTM-MKB012 event: pushedVPV, virtualPageview: /MyKb-Login');
                return false;
            }
            else {
                $('#register-dialog').foundation('reveal', 'open');
                MyKB.populateRegistrationDropDowns();
                dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Create' });
                console.info('GTM-MKB013 event: pushedVPV, virtualPageview: /MyKb-Create');
                return false;
            }
        });




		//Community & Floor Plan Page - Compare Floor Plans
        //$("#save-floor-plan, .compareFP-btn").click(function(){
        $("#save-floor-plan").on('click', function () {
            
            
            
            var id = $(this).data("floorplanid");
            var numItems = parseInt($("#compare-bar").data('saved-plans'));
			
			
			
			
			if($(this).hasClass("active")){
                //Deactivate
                numItems--;
                if($("#mykb").attr("data-logged-in") == "True"){
                    $.post(App.Url("/My-KB/DeleteFloorPlan"), { floorPlanId: id });
		            }else{
		            $.post(App.Url("/My-KB/TempDeleteFloorPlan"), { planID: id });
		            }               
                $(this).removeClass("active");
                if(numItems <= 0){$("#compare-infobar, #sortbar").removeClass("active");}
            }else{
                //Activate
                numItems++;
                if($("#mykb").attr("data-logged-in") == "True"){
                    $.post(App.Url("/My-KB/AddFloorPlan"), { floorPlanId: id });
	                }else{
	                $.post(App.Url("/My-KB/TempSaveFloorPlan"), { planID: id });
	                }
                $(this).addClass("active");
                $("#compare-infobar, #sortbar").addClass("active");
            }
			$("#compare-bar").data('saved-plans',numItems);
			if(numItems > 0){
            	$(".fp-counter").text(numItems);
            }else{
	            $(".fp-counter").text('no');
            }
			$(".fp-ordinal").text(((numItems == 1) ? '' : 's'));
			
			
			console.log('f '+numItems);
			
			          
        });




		//Login to MyKB & Compare
        $(".compare-button").click(function () {
            if ($("#mykb").attr("data-logged-in") == "True") {
                location.href = App.Url("/My-KB#floorplans");
                return false;
            }
            // not logged in, set the afterLogin callback and prompt the user to log in.
            MyKB.afterLogin = function () {
                MyKB.saveFloorPlans();
                postLoginURL = ("/My-KB#floorplans");
            };
            var registered = $.cookie('ExistingUser');
            if (registered != null) {
                $('#login-dialog').foundation('reveal', 'open');
                dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Login' });
                console.info('GTM-MKB034 event: pushedVPV, virtualPageview: /MyKb-Login');
                return false;
            }
            else {
                $('#register-dialog').foundation('reveal', 'open');
                MyKB.populateRegistrationDropDowns();
                dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Create' });
                console.info('GTM-MKB035 event: pushedVPV, virtualPageview: /MyKb-Create');
                return false;
            }
        });




        $("#updates").click(function () {
            if ($("#mykb").attr("data-logged-in") == "True") {
                $("#community-updates-dialog").foundation('reveal', 'open');
                return false;
            }

            // not logged in..
            MyKB.afterLogin = function (isNewReg) {
                if (isNewReg) {
                    $("#community-updates-dialog h2").text("Thank you for Registering");
                }

                $("#community-updates-dialog").foundation('reveal', 'open');
            };

            var registered = $.cookie('ExistingUser');
            if (registered != null) {
                $('#login-dialog').foundation('reveal', 'open');
                dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Login' });
                console.info('GTM-MKB018 event: pushedVPV, virtualPageview: /MyKb-Login');
                return false;
            }
            else {
                $('#register-dialog').foundation('reveal', 'open');
                MyKB.populateRegistrationDropDowns();
                dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Create' });
                console.info('GTM-MKB019 event: pushedVPV, virtualPageview: /MyKb-Create');
                return false;
            }
        });



        $("a.map").click(function () {
            openDrivingDirectionsMap("", $(this).attr("data-end-address"));
            return false;
        });


        $("#alerts form").submit(function () {
            if ($(this).valid()) {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#alerts form .submit').val("Saved!");
                    }
                });
            }
            return false;
        });

        $("#alerts :password").change(function () {
            $("#PasswordChanged").val("true");
        });

        $("#alerts :input").change(function () {
            $("#alerts form .submit").val("Save");
        });

        $(".community-subscribe-cb").change(function () {
            var el = $(this);

            if ($(this).is(":checked")) {
                MyKB.addCommunitySub($(this).attr("data-id"), new function () {
                    el.closest(".community-listing")
						.find(".info")
						.clone()
						.append("<a href='#' class='remove-region' data-id='" + el.attr("data-id") + "'>Remove</a>")
						.appendTo(".updates")
						.wrap("<div class='update-cell' />");
                });
            }
            else {
                MyKB.deleteCommunitySub($(this).attr("data-id"), new function () {
                    $(".updates [data-id='" + el.attr("data-id") + "']").closest(".update-cell").remove();
                });
            }
        });
        $("#recentcommunities .remove-saved-community").click(function () {
            var ele = $(this);
            $.post(App.Url("/My-KB/DeleteRecentCommunity"), { communityId: $(this).attr("data-id") }, function () {
                ele.closest(".community-listing").hide('slow');
            });

            return false;
        });
        $("#savedcommunities .remove-saved-community").click(function () {
            var ele = $(this);
            $.post(App.Url("/My-KB/DeleteCommunity"), { communityId: $(this).attr("data-id") }, function () {
                ele.closest(".community-listing").hide('slow');
            });

            return false;
        });
        $("#OffersByPhone").click(function () {
            var ele = $(this);
            var phone = $("#Phone").val();

            if (phone == "") {
                ele.removeAttr('checked');
                $("#phonechkerror").show();
            }
            else {
                $("#phonechkerror").hide();
            }
        });

        $(".remove-saved-floor-plan").click(function () {
            var ele = $(this);
            $.post(App.Url("/My-KB/DeleteFloorPlan"), { floorPlanId: $(this).attr("data-id") }, function () {


			if($(ele).parent().hasClass('active') && $('.compare-panel').length > 1){
				$('#compare-slider .compare-panel:first-child .click-to-pin').trigger("click");
			}

        	$(ele).parent().remove();
        	
        	if($('.compare-panel').length == 0){
				$('#compare-viewer, .compare-info').removeClass('yes-fp').addClass('no-fp');
			}else if($('.compare-panel').length == 2 || $('.compare-panel').length == 1){
				$('#compare-add-msg').show();
			}
			
			
			if($('#compare-viewer').hasClass('compare-panes-2')){
				$('#compare-viewer').removeClass('compare-panes-2').addClass('compare-panes-1');
			}	
			if($('#compare-viewer').hasClass('compare-panes-3')){
				$('#compare-viewer').removeClass('compare-panes-3').addClass('compare-panes-2');
			}
			if($('#compare-viewer').hasClass('compare-panes-4')){
				$('#compare-viewer').removeClass('compare-panes-4').addClass('compare-panes-3');
			}
			if($('#compare-viewer').hasClass('compare-panes-5')){
				$('#compare-viewer').removeClass('compare-panes-5').addClass('compare-panes-4');
			}
			if($('#compare-viewer').hasClass('compare-panes-6') && $('.compare-panel').length == 5){
				$('#compare-viewer').removeClass('compare-panes-6').addClass('compare-panes-5');
			}			
			




            });

            return false;
        });

        $(".remove-community").click(function () {
            var ele = $(this);
            $.post(App.Url("/My-KB/DeleteCommunitySubscription"), { communityId: $(this).attr("data-id") }, function () {
                ele.closest(".update-cell").hide('slow');
            });

            return false;
        });

        $(".remove-region").click(function () {
            var ele = $(this);
            $.post(App.Url("/My-KB/DeleteRegionSubscription"), { communityId: $(this).attr("data-id") }, function () {
                ele.closest(".update-cell").hide('slow');
            });

            return false;
        });


        $("#Password").focus(
            function () {
                var pass = $('<input class="field-1" data-val="true" data-val-required="The Password field is required." id="Password" name="Password" placeholder="Password" type="Password" />');
                $(this).replaceWith(pass);
                pass.focus();
            }
        );

        $("#RegPassword").focus(
            function () {
                var pass = $('<input class="field-1" data-val="true" data-val-required="The Password field is required." id="RegPassword" name="Password" placeholder="Password" type="Password" />');
                $(this).replaceWith(pass);
                pass.focus();
            }
        );

        // show mykb login if ?login is in the query string
        if (location.href.indexOf('?login') > 0 || location.href.indexOf("&login") > 0) {
            $("#mykb").click();

            console.log("currentRegion:" + currentRegion);
            console.log("currentCommunity:" + currentCommunity);
            

        }

       



            




    },

    addCommunitySub: function (id, callback) {
        $.post(App.Url("/My-KB/AddCommunitySubscription"), { communityId: id }, callback);
    },

    deleteCommunitySub: function (id, callback) {
        $.post(App.Url("/My-KB/DeleteCommunitySubscription"), { communityId: id }, callback);
    },

    showValidationErrors: function (el, errors) {
        el.empty();
        $.each(errors, function (i, error) {
            if (error[1] != "")
                el.append("<li>" + error + "</li>");
        });
    },

    saveCommunity: function (id) {
        var url = $("#save-community").is(":checked") ? "/My-KB/AddCommunity" : "/My-KB/DeleteCommunity";

        $.post(App.Url(url), { communityId: id }, function (data) {
            $("#save-community").prop("checked", data.IsSaved);
            if(data.IsSaved){
	            $('label[for="save-community"]').text("Community Saved");
	            $('#save-community-btn i').attr("class","icon-star");
			} else {
				$('label[for="save-community"]').text("Save this Community");
				$('#save-community-btn i').attr("class","icon-star-empty");
			}        
        });
    },

    saveFloorPlan: function (id) {
        if ($("#mykb").attr("data-logged-in") == "True") {
            var url = $("#save-floor-plan").is(":checked") ? "/My-KB/AddFloorPlan" : "/My-KB/DeleteFloorPlan";
            $.post(App.Url(url), { floorPlanId: id }, function (data) {
                $("#save-floor-plan").prop("checked", data.IsSaved);
                $("label[for=save-floor-plan]").text(data.IsSaved ? "Saved" : "Save Floor Plan");
            });
        }
        else {
            var url = $("#save-floor-plan").is(":checked") ? "/My-KB/TempSaveFloorPlan" : "/My-KB/TempDeleteFloorPlan";
            $.post(App.Url(url), { planId: id }, function (data) {
                $("#save-floor-plan").prop("checked", data.IsSaved);
                $("label[for=save-floor-plan]").text(data.IsSaved ? "Saved" : "Save Floor Plan");
            });
        }
    },

    saveFloorPlans: function() {
        var url = "/My-KB/AddFloorPlans";
        var executeURL = App.Url(url);
        $.post(App.Url(url), function () {
            location.href = App.Url("/My-KB#floorplans");
        });
        console.info('Posted To Account');
    },

    initPlaceholderSupport: function () {
        if (!Modernizr.input.placeholder) {
            $('[placeholder]').focus(function () {
                var input = $(this);
                if (input.val() == input.attr('placeholder')) {
                    input.val('');
                    input.removeClass('placeholder');
                }
            }).blur(function () {
                var input = $(this);
                if (input.val() == '' || input.val() == input.attr('placeholder')) {
                    input.addClass('placeholder');
                    input.val(input.attr('placeholder'));
                }
            }).blur();
            $('[placeholder]').parents('form').submit(function () {
                $(this).find('[placeholder]').each(function () {
                    var input = $(this);
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                });
            });

        }
    },

    populateRegistrationDropDowns: function () {
        if (typeof currentRegion === 'undefined') {
            return;
        }

        if (currentRegion != "") {
            $('#RegionList').val(currentRegion);
            $("#RegionList").val(currentRegion).change();
            initialRegion = "";
            }

        

    }

};



// called when we get status: 200 OK from 
// a login call
function loginSuccess(response) {
	if (!response.IsValid) {
		// login failed, hopefully with errors
		// display those errors in the validation summary

		MyKB.showValidationErrors($("#login-form .validation-summary"), response.Errors);
		return;
	}

    //Check cookie here.
	var cookieEnabled = (navigator.cookieEnabled) ? true : false;

	if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
	    document.cookie = "testcookie";
	    cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
	}
	if (!cookieEnabled) {
	    $("#login-form .validation-summary").append("<li>Cookies must be enabled to log in.</li>");
	    return;
	}

	// login successful..
	//$("#login-dialog").dialog("close");
	$('#login-dialog .close-reveal-modal').trigger('click.modalEvent');
	$("#mykb").attr("data-logged-in", "True");
	dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-Return' });
	console.info('GTM-MKB020 event: pushedVPV, virtualPageview: /MyKb-Return');
	
	if ($.isFunction(MyKB.afterLogin)) {
		MyKB.afterLogin(false);
		MyKB.afterLogin = null;
	}
	if (postLoginURL != "") {
	    //location.href = App.Url(postLoginURL);
	    postLoginURL = "";
	}
	else {
	    location.href = App.Url("/My-KB");
	}
}

// called when we get status: 200 OK from 
// a registration 
function registrationSuccess(response) {
	if (!response.IsValid) {
		// login failed, hopefully with errors
		// display those errors in the validation summary
		MyKB.showValidationErrors($("#register-form .validation-summary"), response.Errors);
		return;
	}

	// registration successful..
    $('#register-dialog .close-reveal-modal').trigger('click.modalEvent');
    $('#registered-confirm-dialog #confirm-message').html("You can now save communities and floor plans to your MyKB profile.");
    $('#registered-confirm-dialog').foundation('reveal', 'open');
	//$("#register-dialog").dialog("close");
    $("#mykb").attr("data-logged-in", "True");

    if ($("#IsBroker").val() == "true") {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'KB Broker', 'eventAction': 'Click', 'eventLabel': 'BrokerRegister:my-kb-new:' + window.location.pathname });
        console.info('GTM-MKB021 event: pushedEvent, eventAction: Click, eventCategory: KB Broker, eventLabel: BrokerRegister:my-kb-new:' + window.location.pathname);
    } else {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'My KB', 'eventAction': 'Click', 'eventLabel': 'Register:my-kb-new:' + window.location.pathname });
        console.info('GTM-MKB022 event: pushedEvent, eventAction: Click, eventCategory: My KB, eventLabel: Register:my-kb-new:' + window.location.pathname);
    }
    dataLayer.push({ 'event': 'pushedRegister' });
    console.info('GTM-MKB023 event: pushedRegister');
    dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/MyKb-New' });
    console.info('GTM-MKB024 event: pushedVPV, virtualPageview: /MyKb-New');

	if ($.isFunction(MyKB.afterLogin)) {
		MyKB.afterLogin(true);
		MyKB.afterLogin = null;
	}

}

function fbLoginSuccess(response) {
    if (!response.IsValid) {
        // login failed, hopefully with errors
        // display those errors in the validation summary
        MyKB.showValidationErrors($("#login_facebook .validation-summary"), response.Errors);
        return;
    }

    // login successful..
    window.close();
}

function fbRegistrationSuccess(response) {
	if (!response.IsValid) {
		// login failed, hopefully with errors
		// display those errors in the validation summary
	    MyKB.showValidationErrors($("#register_facebook .validation-summary"), response.Errors);
		return;
	}

    dataLayer.push({ 'event': 'pushedFacebookRegister' });
    console.info('GTM-MKB025 event: pushedFacebookRegister');

    if ($("#IsBroker").val() == "true") {
	    dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'KB Broker', 'eventAction': 'Click', 'eventLabel': 'BrokerRegister with Facebook:/my-kb-new:' + window.location.pathname });
	    console.info('GTM-MKB026 event: pushedEvent, eventAction: Click, eventCategory: KB Broker, eventLabel: BrokerRegister with Facebook:/my-kb-new:' + window.location.pathname);
    } else {
	    dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'My KB', 'eventAction': 'Click', 'eventLabel': 'Register with Facebook:/my-kb-new:' + window.location.pathname });
	    console.info('GTM-MKB027 event: pushedEvent, eventAction: Click, eventCategory: My KB, eventLabel: BrokerRegister with Facebook:/my-kb-new:' + window.location.pathname);
    }

	// registration successful..
    //$("#confirm").show();
    //$("#registerform").hide();

    window.opener.loggedInViaFacebook("register");
    window.close();
}


function forgotPasswordSuccess(response) {
	if (!response.IsValid) {
		// login failed, hopefully with errors
		// display those errors in the validation summary
		MyKB.showValidationErrors($("#forgot-password-form .validation-summary"), response.Errors);
		return;
	}

	$("#forgot-password-form .prompt").hide();
	$("#forgot-password-form .success").show();
}

function subscribeSuccess(response) {
	$('#community-updates-dialog').foundation('reveal', 'close');
}


function ajaxFailure(response, status, data) {
    $(".validation-summary").removeClass("validation-summary-valid").addClass("validation-summary-errors");
	$(".validation-summary ul")
		.empty()
		.append("<li>A server error occurred. Please try again later.</li>");
}

function loggedInViaFacebook(action) {
	$("#mykb").attr("data-logged-in", "True");

	if ($.isFunction(MyKB.afterLogin)) {
		MyKB.afterLogin(false);
		MyKB.afterLogin = null;
    }

    //if (action != "register") {
    //    location.href = App.Url("/My-KB");
    //}

	location.href = App.Url("/My-KB");
}

//contact-cms-support

function ContactCMSSuccess(response) {
    if (!response.IsValid) {
        // login failed, hopefully with errors
        // display those errors in the validation summary
        MyKB.showValidationErrors($("#contactCMS-form .validation-summary ul"), response.Errors);
        return;
    }

    $("#contact-cms").hide();
    $("#contact-cms-response").show();
}

//contact-sales 

function ContactUsSuccess(response) {
	if (!response.IsValid) {
		// login failed, hopefully with errors
		// display those errors in the validation summary
		MyKB.showValidationErrors($("#contactUs-form .validation-summary ul"), response.Errors);
		return;
	}
	
	$("#contact-sales").hide();
	$("#contact-sales-response").show();
	dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'Contact Us-Contact Sales:Submit' });
	console.info('GTM-MKB028 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: Contact Us-Contact Sales:Submit');
	dataLayer.push({ 'event': 'pushedContactSales' });
	console.info('GTM-MKB029 event: pushedContactSales');
	dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/contact-sales/thank-you' });
	console.info('GTM-MKB030 event: pushedVPV, virtualPageview: /contact-sales/thank-you');
}

//contact-warranty

function ContactWarrantySuccess(response) {
    if (!response.IsValid) {
        MyKB.showValidationErrors($("#contactWarranty-form .validation-summary ul"), response.Errors);
        return;
    }

    $("#contact-warranty").hide();
    $("#contact-warranty-response").show();
    dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'Contact Us-Warranty Services:Submit' });
    console.info('GTM-MKB031 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: Contact Us-Warranty Services:Submit');
    dataLayer.push({ 'event': 'pushedContactWarranty' });
    console.info('GTM-MKB032 event: pushedContactWarranty');
    dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/warranty-services/thank-you' });
    console.info('GTM-MKB033 event: pushedVPV, virtualPageview: /warranty-services/thank-you');
}

//community landing contact

function LandingContactUsSuccess(response) {
    if (!response.IsValid) {
        MyKB.showValidationErrors($("#landingcontactUs-form .validation-summary ul"), response.Errors);
        return;
    }

    $("#contact-form").hide();
    $("#contact-response").show();

};



$(function () {

//----- Start Google Analytics Tags ----------------------//

    //-----Navigation--------

    $("#container #badge a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Header Link', 'eventAction': 'Click', 'eventLabel': 'KB Home Logo:' + window.location.pathname });
    	console.info('GTM-ANT001 event: pushedEvent, eventAction: Click, eventCategory: Header Link, eventLabel: KB Home Logo:' + window.location.pathname);
    });

    $(".community .bList .listing").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Sub Navigation', 'eventAction': 'Click', 'eventLabel': 'Communities & Floor Plans:Select Location:Recently Viewed:' + $(this).data('tracking') });
    	console.info('GTM-ANT002 event: pushedEvent, eventAction: Click, eventCategory: Sub Navigation, eventLabel: Communities & Floor Plans:Select Location:Recently Viewed:' + $(this).data('tracking'));
    });

    $("#nav .builtToOrderSection").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Navigation', 'eventAction': 'Click', 'eventLabel': $(this).data('tracking') });
    	console.info('GTM-ANT003 event: pushedEvent, eventAction: Click, eventCategory: Navigation, eventLabel: ' + $(this).data('tracking'));
    });


    $("#nav .section-02 a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Navigation', 'eventAction': 'Click', 'eventLabel': $(this).data('tracking') + window.location.pathname });
    	console.info('GTM-ANT004 event: pushedEvent, eventAction: Click, eventCategory: Navigation, eventLabel: ' + $(this).data('tracking') + window.location.pathname);
    });

    $("#nav .mykb a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Navigation', 'eventAction': 'Click', 'eventLabel': 'MY KB:' + window.location.pathname });
    	console.info('GTM-ANT005 event: pushedEvent, eventAction: Click, eventCategory: Navigation, eventLabel: MY KB:' + window.location.pathname);
    });

    //top nav & home flyout
    $(".navBox, .navBoxHome").on( "click", ".counties .county1, .countiesHome .county1, .states .single-region, .statesHome .single-region", function() {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Sub Navigation', 'eventAction': 'Click', 'eventLabel': 'Find a Location:' + $(this).data('tracking') + ':' + window.location.pathname });
    	console.info('GTM-ANT006 event: pushedEvent, eventAction: Click, eventCategory: Sub Navigation, eventLabel: Find a Location:' + $(this).data('tracking') + ':' + window.location.pathname);
    });


    //recently viewed menu 
    $("#recentlyviewedmenu .recentviewed .recent").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Sub Navigation', 'eventAction': 'Click', 'eventLabel': 'Communities & Floor Plans:Select Location:Recently Viewed:' + $(this).data('tracking') });
    	console.info('GTM-ANT007 event: pushedEvent, eventAction: Click, eventCategory: Sub Navigation, eventLabel: Communities & Floor Plans:Select Location:Recently Viewed:' + $(this).data('tracking'));
    });


    $("#recentlyviewedmenu .recentviewed .inner #comNamesSel").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Sub Navigation', 'eventAction': 'Click', 'eventLabel': 'Communities & Floor Plans:Select Location:Recently Viewed:Area Map:' + $(this).text() + ':' + window.location.pathname });
    	console.info('GTM-ANT008 event: pushedEvent, eventAction: Click, eventCategory: Sub Navigation, eventLabel: Communities & Floor Plans:Select Location:Recently Viewed:Area Map:' + $(this).text() + ':' + window.location.pathname);
    });



    //build to order
    $("#recentlyviewedmenu .bto a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Sub Navigation', 'eventAction': 'Click', 'eventLabel': 'Built to Order:' + $(this).text() + ':' + window.location.pathname });
    	console.info('GTM-ANT009 event: pushedEvent, eventAction: Click, eventCategory: Sub Navigation, eventLabel: Built to Order:' + $(this).text() + ':' + window.location.pathname);
    });






    //------- Home---------


    //Flyout nav
    $(".navBoxHome .countiesHome .county1").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Hero', 'eventAction': 'Click', 'eventLabel': 'Find a Location:' + $(this).data('tracking') + ':' + window.location.pathname });
    	console.info('GTM-ANT010 event: pushedEvent, eventAction: Click, eventCategory: Hero, eventLabel: Find a Location:' + $(this).data('tracking') + ':' + window.location.pathname);
    });

    //body content
    $("#home .aside-2").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Hero', 'eventAction': 'Click', 'eventLabel': $(this).data('tracking') + ':' + window.location.pathname });
    	console.info('GTM-ANT011 event: pushedEvent, eventAction: Click, eventCategory: Hero, eventLabel: ' + $(this).data('tracking') + ':' + window.location.pathname);
    });

    //finance mortgage calculator
    $("#finance #mCalculator #submitRate").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Right Rail Promo', 'eventAction': 'Click', 'eventLabel': 'Mortgage Calculator:/financing' });
    	console.info('GTM-ANT012 event: pushedEvent, eventAction: Click, eventCategory: Right Rail Promo, eventLabel: Mortgage Calculator:/financing');
    });

    //For brokers
    $("#finance #broker-create").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Right Rail Promo', 'eventAction': 'Click', 'eventLabel': 'Sign up for my KB Broker - Create Account://for-brokers' });
    	console.info('GTM-ANT013 event: pushedEvent, eventAction: Click, eventCategory: Right Rail Promo, eventLabel: Sign up for my KB Broker - Create Account://for-brokers');
    });

    $("#finance #homebuyer-create").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Right Rail Promo', 'eventAction': 'Click', 'eventLabel': 'Sign up for my KB - Create Account://for-homebuyers' });
        console.info('GTM-ANT014 event: pushedEvent, eventAction: Click, eventCategory: Right Rail Promo, eventLabel: Sign up for my KB - Create Account://for-homebuyers');
    });


    //------- contact us----------
    //Moved tagging to MyKB.js so tags are fired after form submit success
    //$("#contact-sales #ContactSalesSubmit").click(function () {
    //    dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'Contact Us-Contact Sales:Submit' });
    //    console.info('GTM-ANT014 event: pushedEvent, eventAction: , eventCategory: , eventLabel: Contact Us-Contact Sales:Submit');
    //});

    //$("#contact-warranty #ContactWarrantySubmit").click(function () {
    //    dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'Contact Us-Warranty Services:Submit' });
    //    console.info('GTM-ANT015 event: pushedEvent, eventAction: , eventCategory: , eventLabel: Contact Us-Warranty Services:Submit');
    //});

    $("#contact-warranty-response #ReturnToRequestForm").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'Contact Us-Warranty Services:Return to Request Form' });
    	console.info('GTM-ANT016 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: Contact Us-Warranty Services:Return to Request Form');
    });

    //-------Region Map------------

    //view nearby region
    $(".aside-01 .nearby .region").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Left Rail Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Map:Communities Nearby:' + $(this).data('tracking') + ':' + window.location.pathname });
    	console.info('GTM-ANT017 event: pushedEvent, eventAction: Click, eventCategory: Left Rail Link, eventLabel: KB-Community Map:Communities Nearby:' + $(this).data('tracking') + ':' + window.location.pathname);
    });

    //Flyout nav
    $("#mapnav .countiesHome .county1").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Left Rail Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Map:Change Locations:Find a Location:' + $(this).data('tracking') + ':' + window.location.pathname });
    	console.info('GTM-ANT018 event: pushedEvent, eventAction: Click, eventCategory: Left Rail Link, eventLabel: KB-Community Map:Change Locations:Find a Location:' + $(this).data('tracking') + ':' + window.location.pathname);
    });

    //-------Community-------------

    //Gallery arrows
    $(".community-gallery .controls .next").click(function () {
        communityName = $(".community-gallery .carousel").data('tracking');
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Next Arrow', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Photo-' + $(".community-gallery .controls .count").text() + ':' + communityName });
	    console.info('GTM-ANT019 event: pushedEvent, eventAction: Click, eventCategory: Next Arrow, eventLabel: KB-Community Page:Photo-' + $(".community-gallery .controls .count").text() + ':' + communityName);
    });

    $(".community-gallery .controls .prev").click(function () {
        communityName = $(".community-gallery .carousel").data('tracking');
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Back Arrow', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Photo-' + $(".community-gallery .controls .count").text() + ':' + communityName });
    	console.info('GTM-ANT020 event: pushedEvent, eventAction: Click, eventCategory: Back Arrow, eventLabel: KB-Community Page:Photo-' + $(".community-gallery .controls .count").text() + ':' + communityName);
    });



    //promo1
    $(".communityContent .cta-01 a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Promo', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Included at no extra cost:' + $(this).data('tracking') });
    	console.info('GTM-ANT021 event: pushedEvent, eventAction: Click, eventCategory: Body Promo, eventLabel: KB-Community Page:Included at no extra cost:' + $(this).data('tracking'));
    });


    //promo2
    $(".communityContent .cta-02 a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Promo', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Discover the Benefits of EPG:' + $(this).data('tracking') });
    	console.info('GTM-ANT022 event: pushedEvent, eventAction: Click, eventCategory: Body Promo, eventLabel: KB-Community Page:Discover the Benefits of EPG:' + $(this).data('tracking'));
    });


    //quick move in
    $("#link_quickmovein .detail-02").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:View Quick Move-In Homes in this Community:' + $(this).data('tracking') });
    	console.info('GTM-ANT023 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:View Quick Move-In Homes in this Community:' + $(this).data('tracking'));
    });


    //vist quick move in sales office
    $("#quickmovein .details link_salesoffice").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Quick Move-In:Visit Sales Office:' + $(this).data('tracking') });
    	console.info('GTM-ANT024 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:Quick Move-In:Visit Sales Office:' + $(this).data('tracking'));
    });

    //explore other communities
    $("#explore").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Left Rail Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Explore Other Communities:' + window.location.pathname });
    	console.info('GTM-ANT025 event: pushedEvent, eventAction: Click, eventCategory: Left Rail Link, eventLabel: KB-Community Page:Explore Other Communities:' + window.location.pathname);
    });

    //community updates
    $(".communityContent #updates").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Left Rail Link', 'eventAction': 'Click', 'eventLabel': 'Get Community Updates:Link:' + $(this).data('tracking') });
    	console.info('GTM-ANT026 event: pushedEvent, eventAction: Click, eventCategory: Left Rail Link, eventLabel: Get Community Updates:Link:' + $(this).data('tracking'));
    });

    //community update submit
    $("#container #community-updates-dialog #register-form .button").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Overlay', 'eventAction': 'Click', 'eventLabel': 'Get Community Updates:Submit:' + $(this).data('tracking') });
    	console.info('GTM-ANT027 event: pushedEvent, eventAction: Click, eventCategory: Overlay, eventLabel: Get Community Updates:Submit:' + $(this).data('tracking'));
    });


    //view details
    $(".list-info .col-01 .push-event").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:View Details:' + $(this).data('tracking') });
    	console.info('GTM-ANT028 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:View Details:' + $(this).data('tracking'));
    });


    //sidebar nav items
    $("#nav-page #tab_floorplans").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Sidebar Navigation', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Floor plans & Details' + $(this).data('tracking') });
        console.info('GTM-ANT029 event: pushedEvent, eventAction: Click, eventCategory: Sidebar Navigation, eventLabel: KB-Community Page:Floor plans & Details' + $(this).data('tracking'));
		dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': $(this).data('tracking') });
	    console.info('GTM-ANT030 event: pushedVPV, virtualPageview: ' + $(this).data('tracking'));
    });

    $("#nav-page #tab_neighborhood").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Sidebar Navigation', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Explore the neighborhood' + $(this).data('tracking') });
        console.info('GTM-ANT031 event: pushedEvent, eventAction: Click, eventCategory: Sidebar Navigation, eventLabel: KB-Community Page:Explore the neighborhood' + $(this).data('tracking'));
		dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': $(this).data('tracking') + '/Explore-the-neighborhood' });
    	console.info('GTM-ANT032 event: pushedVPV, virtualPageview: ' + $(this).data('tracking') + '/Explore-the-neighborhood');
    });

    $("#nav-page #tab_salesoffice").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Sidebar Navigation', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Sales office & Directions' + $(this).data('tracking') });
        console.info('GTM-ANT033 event: pushedEvent, eventAction: Click, eventCategory: Sidebar Navigation, eventLabel: KB-Community Page:Sales office & Directions' + $(this).data('tracking'));
		dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': $(this).data('tracking') + '/Sales-office-&-Directions' });
    	console.info('GTM-ANT034 event: pushedVPV, virtualPageview: ' + $(this).data('tracking') + '/Sales-office-&-Directions');
    });

    $("#link_quickmovein").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:View Quick Move-In Homes in this Community' + $(this).data('tracking') });
        console.info('GTM-ANT035 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:View Quick Move-In Homes in this Community' + $(this).data('tracking'));
		dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': $(this).data('tracking') + '/Quick-move-in-homes' });
    	console.info('GTM-ANT036 event: pushedVPV, virtualPageview: ' + $(this).data('tracking') + '/Quick-move-in-homes');
    });


    //save
    $("#social-01 #save-community").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Left Rail Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Save to my KB:' + $(this).data('tracking') });
    	console.info('GTM-ANT037 event: pushedEvent, eventAction: Click, eventCategory: Left Rail Link, eventLabel: KB-Community Page:Save to my KB:' + $(this).data('tracking'));
    });

    $("#social-02 #save-floor-plan, .floorplan-row .compare-fp-button").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Save Floorplan:' + $(this).data('tracking') });
    	console.info('GTM-ANT038 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:Save Floorplan:' + $(this).data('tracking'));
    });



    //------Floor plan-------------


    //print
    $("#social-02 .print").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Print:' + $(this).data('tracking') });
    	console.info('GTM-ANT039 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:Print:' + $(this).data('tracking'));
    });

    //get driving directions in floor plan
    $(".communityContent #FloorPlanOfficeMapDirections").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Driving Directions:' + $(this).data('tracking') });
    	console.info('GTM-ANT040 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page w/Home Plan:Driving Directions:' + $(this).data('tracking'));
    });

    //get driving directions -sales office
    $("#salesoffice #office1MapDirections ").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB Community Page:Driving Directions:' + $(this).data('tracking') + ':' + window.location.pathname });
    	console.info('GTM-ANT041 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB Community Page:Driving Directions:' + $(this).data('tracking') + ':' + window.location.pathname);
    });


    //email us
    $("#floorplans .mod-01 .emailUs").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Right Rail Promo', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Email Us:' + $('#content').data('tracking') });
    	console.info('GTM-ANT042 event: pushedEvent, eventAction: Click, eventCategory: Right Rail Promo, eventLabel: KB-Community Page w/Home Plan:Email Us:' + $('#content').data('tracking'));
    });



    //floor plan mortgage calculator
    $("#floorplans #mCalculator #submitRate").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Right Rail Promo', 'eventAction': 'Click', 'eventLabel': 'Mortgage Calculator:' + $(this).data('tracking') });
    	console.info('GTM-ANT043 event: pushedEvent, eventAction: Click, eventCategory: Right Rail Promo, eventLabel: Mortgage Calculator:' + $(this).data('tracking'));
    });


    //learn about financing
    $("#mCalculator .cta").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Right Rail Promo', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Learn About Financing:' + $(this).data('tracking') });
    	console.info('GTM-ANT044 event: pushedEvent, eventAction: Click, eventCategory: Right Rail Promo, eventLabel: KB-Community Page w/Home Plan:Learn About Financing:' + $(this).data('tracking'));
    });


    //explore design studio
    $("#floorplans .col-02 .mod-02 a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Right Rail Promo', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Explore the Design Studio:' + $(this).data('tracking') });
    	console.info('GTM-ANT045 event: pushedEvent, eventAction: Click, eventCategory: Right Rail Promo, eventLabel: KB-Community Page w/Home Plan:Explore the Design Studio:' + $(this).data('tracking'));
    });

    //virtual tour
    $("#floorplans #virtualTour").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Virtual Home Tour:' + $('#content').data('tracking') });
    	console.info('GTM-ANT046 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page w/Home Plan:Virtual Home Tour:' + $('#content').data('tracking'));
    });


    //interactive floor plan
    $("#floorplans #interactFloorPlan").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Interactive Floor Plan:' + $('#content').data('tracking') });
    	console.info('GTM-ANT047 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page w/Home Plan:Interactive Floor Plan:' + $('#content').data('tracking'));
    });

    //exterior option photos

    $("#floorplans #gallery-02 .imgPrev").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Back Arrow', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Exterior Options:' + $('#content').data('tracking') });
    	console.info('GTM-ANT048 event: pushedEvent, eventAction: Click, eventCategory: Back Arrow, eventLabel: KB-Community Page w/Home Plan:Exterior Options:' + $('#content').data('tracking'));
    });


    $("#floorplans #gallery-02 .imgNext").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Next Arrow', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Exterior Options:' + $('#content').data('tracking') });
    	console.info('GTM-ANT049 event: pushedEvent, eventAction: Click, eventCategory: Next Arrow, eventLabel: KB-Community Page w/Home Plan:Exterior Options:' + $('#content').data('tracking'));
    });

    //Other floor plans

    $("#floorplans #gallery-04 #circCarousel a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Other Floor Plans:' + $('#content').data('tracking') });
    	console.info('GTM-ANT050 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page w/Home Plan:Other Floor Plans:' + $('#content').data('tracking'));
    });

    $("#floorplans #gallery-04 .jcarousel-container .jcarousel-prev").on('click', function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Back arrow', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Other Floor Plans' + $('#content').data('tracking') });
    	console.info('GTM-ANT051 event: pushedEvent, eventAction: Click, eventCategory: Back arrow, eventLabel: KB-Community Page w/Home Plan:Other Floor Plans' + $('#content').data('tracking'));
    });

    $("#floorplans #gallery-04 .jcarousel-container .jcarousel-next").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Next arrow', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Other Floor Plans' + $('#content').data('tracking') });
    	console.info('GTM-ANT052 event: pushedEvent, eventAction: Click, eventCategory: Next arrow, eventLabel: KB-Community Page w/Home Plan:Other Floor Plans' + $('#content').data('tracking'));
    });

    //Floor plans list
    $("#floorplans #back-01").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page w/Home Plan:Floor Plans List:' + window.location.pathname });
    	console.info('GTM-ANT053 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page w/Home Plan:Floor Plans List:' + window.location.pathname);
    });

    //promos

    $("#floorplans #cta-01 .cta-button").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:' + $(this).attr('alt') + ':' + $('#content').data('tracking') });
    	console.info('GTM-ANT054 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:' + $(this).attr('alt') + ':' + $('#content').data('tracking'));
    });

    $("#floorplans #cta-02 .cta-button").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:' + $(this).attr('alt') + ':' + $('#content').data('tracking') });
    	console.info('GTM-ANT055 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:' + $(this).attr('alt') + ':' + $('#content').data('tracking'));
    });

    $("#floorplans #cta-02 .cta-link").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:' + $(this).attr('url') + ':' + $('#content').data('tracking') });
    	console.info('GTM-ANT056 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:' + $(this).attr('url') + ':' + $('#content').data('tracking'));
    });

    //---------sales office - directions

    $(".tab-content #salesoffice .sendAQuestion").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:Send Us a Question:' + $('#content').data('tracking') });
    	console.info('GTM-ANT057 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Community Page:Send Us a Question:' + $('#content').data('tracking'));
    });



    // ----- build to order----------

    $("#bto .about a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': $(this).text() + ':/built-to-order' });
    	console.info('GTM-ANT058 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: ' + $(this).text() + ':/built-to-order');
    });


    //-------design studio--------



    //-----------efficiency and sustainability------------

    $("#epg .content .box a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Sidebar Navigation', 'eventAction': 'Click', 'eventLabel': 'Built to Order-Energy Efficient Homes:' + $(this).text() + ':/energy-efficient-homes' });
    	console.info('GTM-ANT059 event: pushedEvent, eventAction: Click, eventCategory: Sidebar Navigation, eventLabel: Built to Order-Energy Efficient Homes:' + $(this).text() + ':/energy-efficient-homes');
    });

    $("#epg .content #reports a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Footer Links', 'eventAction': 'Click', 'eventLabel': 'Built to Order-Energy Efficient Homes:Download PDFs:' + $(this).text() + ':/energy-efficient-homes' });
    	console.info('GTM-ANT060 event: pushedEvent, eventAction: Click, eventCategory: Footer Links, eventLabel: Built to Order-Energy Efficient Homes:Download PDFs:' + $(this).text() + ':/energy-efficient-homes');
    });



    //--------------quick move in---------------
    $("#quickmovein .details").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Quick Move In Page:Visit Sales Office:' + $(this).data('tracking') });
    	console.info('GTM-ANT061 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Quick Move In Page:Visit Sales Office:' + $(this).data('tracking'));
    });


    $("#QuickMoveIn .details").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'KB-Quick Move In Page:Visit Sales Office:' + $(this).data('tracking') });
	    console.info('GTM-ANT062 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: KB-Quick Move In Page:Visit Sales Office:' + $(this).data('tracking'));
    });

    $("#qmihead #Area").click(function () {
        if ($(this).val() != "") {
            dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Quick Move-In Dropdowns', 'eventAction': 'Click', 'eventLabel': 'KB-Quick Move In Page:' + $(this).find("option:selected").text() });
            console.info('GTM-ANT063 event: pushedEvent, eventAction: Click, eventCategory: Quick Move-In Dropdowns, eventLabel: KB-Quick Move In Page:' + $(this).find("option:selected").text());
        }
    });

    $("#qmihead #Region").click(function () {
        if ($(this).val() != "") {
            dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Quick Move-In Dropdowns', 'eventAction': 'Click', 'eventLabel': 'KB-Quick Move In Page:' + $(this).find("option:selected").text() });
            console.info('GTM-ANT064 event: pushedEvent, eventAction: Click, eventCategory: Quick Move-In Dropdowns, eventLabel: KB-Quick Move In Page:' + $(this).find("option:selected").text());
        }
    });

    //--------get community updates overlay----------
    $("community-updates-dialog .button").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Overlay', 'eventAction': 'Click', 'eventLabel': 'Get Community Updates:Submit:' + $(this).data('tracking') });
    	console.info('GTM-ANT065 event: pushedEvent, eventAction: Click, eventCategory: Overlay, eventLabel: Get Community Updates:Submit:' + $(this).data('tracking'));
    });

    //--------My kb---------

    $(".mykbTabs #SavedCommnunites").click(function () {
        dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/my-kb' });
    	console.info('GTM-ANT066 event: pushedVPV, virtualPageview: /my-kb');
    });

    $(".mykbTabs #SavedFloorPlans").click(function () {
        dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': $(this).text().replace(/ /gi, "-") });
    	console.info('GTM-ANT067 event: pushedVPV, virtualPageview: ' + $(this).text().replace(/ /gi, "-"));
    });
    
    $(".mykbTabs #RecentlyViewedCommunities").click(function () {
        dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': $(this).text().replace(/ /gi, "-") });
    	console.info('GTM-ANT068 event: pushedVPV, virtualPageview: ' + $(this).text().replace(/ /gi, "-"));
    });

    $(".mykbTabs #SettingsUpdates").click(function () {
        dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': '/my-kb/' + $(this).text().replace(/ /gi, "-") });
    	console.info('GTM-ANT069 event: pushedVPV, virtualPageview: /my-kb/' + $(this).text().replace(/ /gi, "-"));
    });

    //saved communities

    $(".mykbTabs .community-listing .info .title").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'My KB Home Saved Communities-Compare Communities:' + $(this).text() });
    	console.info('GTM-ANT070 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: My KB Home Saved Communities-Compare Communities:' + $(this).text());
    });


    $(".mykbTabs .community-listing .info-links").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'My KB Home Saved Communities-Compare Communities:' + $(this).data('tracking') + ':' + $(this).text() });
    	console.info('GTM-ANT071 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: My KB Home Saved Communities-Compare Communities:' + $(this).data('tracking') + ':' + $(this).text());
    });


    //savedfloor plans

    $(".mykbTabs .floor-plan-listing .floorPlan").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'My KB Home Saved Floor Plans-Compare Home Designs:' + $(this).text() });
	    console.info('GTM-ANT072 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: My KB Home Saved Floor Plans-Compare Home Designs:' + $(this).text());
    });


    $(".mykbTabs .floor-plan-listing .salesOffice").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'My KB Home Saved Floor Plans-Compare Home Designs:' + $(this).data('tracking') + ':' + $(this).text() });
	    console.info('GTM-ANT073 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: My KB Home Saved Floor Plans-Compare Home Designs:' + $(this).data('tracking') + ':' + $(this).text());
    });

    //settings
    $(".mykbTabs #MyKbSettingsForm .submit").click(function () {
        //get checked items
        var checkedItems = "";
        $("input[@class='updatesBy']:checked").each(function () {
            checkedItems += $(this).attr("Id") + ':';
        });
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'My KB Home Settings & Updates:' + checkedItems });
    	console.info('GTM-ANT074 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: My KB Home Settings & Updates:' + checkedItems);
    });


    //---log out

    $(".mykbHero .logout-area a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Body Link', 'eventAction': 'Click', 'eventLabel': 'Logout:' + window.location.pathname });
	    console.info('GTM-ANT075 event: pushedEvent, eventAction: Click, eventCategory: Body Link, eventLabel: Logout:' + window.location.pathname);
    });




    //---Footer
    $("#footer .section .aside-01 a").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Footer Links', 'eventAction': 'Click', 'eventLabel': $(this).text() + ':' + window.location.pathname });
	    console.info('GTM-ANT076 event: pushedEvent, eventAction: Click, eventCategory: Footer Links, eventLabel: ' + $(this).text() + ':' + window.location.pathname);
    });


    //social links
    $("#footer .section .aside-02 li a img").click(function () {
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Footer Link', 'eventAction': 'Click', 'eventLabel': 'Social Link:' + $(this).attr('alt') + ':' + window.location.pathname });
	    console.info('GTM-ANT077 event: pushedEvent, eventAction: Click, eventCategory: Footer Links, eventLabel: Social Link:' + $(this).attr('alt') + ':' + window.location.pathname);
    });

    
    //---promo pages---


    //--add this to any promo area from the cms
    $(".promoTracking a").click(function () {
        //use data-tracking if it exists other wise use text
        var trackingData = $(this).attr("data-tracking");
        if (!trackingData) {
            trackingData =  $(this).text() + ':' + window.location.pathname;
        }
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Promo link', 'eventAction': 'Click', 'eventLabel': 'LinkFromPromoContent: ' + trackingData });
	    console.info('GTM-ANT078 event: pushedEvent, eventAction: Click, eventCategory: Promo link, eventLabel: LinkFromPromoContent: ' + trackingData);
    });


	//--Community Promo Header
    $("#cta-01 a").click(function () {
        //use data-tracking if it exists other wise use text
        var trackingData = $(this).attr("data-tracking");
        if (!trackingData) {
            trackingData =  $(this).text() + ':' + window.location.pathname;
        }
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Promo link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:SmallPromo-' + trackingData });
	    console.info('GTM-ANT079 event: pushedEvent, eventAction: Click, eventCategory: Promo link, eventLabel: KB-Community Page:SmallPromo-' + trackingData);
    });


	//--Community Promo Plan Rows
    $("#cta-02 a").click(function () {
        //use data-tracking if it exists other wise use text
        var trackingData = $(this).attr("data-tracking");
        if (!trackingData) {
            trackingData =  $(this).text() + ':' + window.location.pathname;
        }
        dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Promo link', 'eventAction': 'Click', 'eventLabel': 'KB-Community Page:BodyPromo-' + trackingData });
	    console.info('GTM-ANT080 event: pushedEvent, eventAction: Click, eventCategory: Promo link, eventLabel: KB-Community Page:BodyPromo-' + trackingData);
    });


    //All external links - this will track all links leaving the site

    $("a").on('click',function(e){
        	var url = $(this).attr("href");
        	if (e.currentTarget.host != window.location.host && !$(this).hasClass('outbound-no-push')) {
        	    dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Outbound Links', 'eventAction': 'Click', 'eventLabel': e.currentTarget.host + ':' + url });
	            console.info('GTM-ANT081 event: pushedEvent, eventAction: Click, eventCategory: Outbound Links, eventLabel: ' + e.currentTarget.host + ':' + url);
            	}
        	});
        	
        	
    //---mobile site tagging---
        	

	$('[data-ga-cat]').on('click', clickEvent);   
    
	// data-ga-label can contain replacement tokens:
	//	{t}: the link text
	//	{h}: the link's href
	//  {u}: the page url

	function clickEvent() {
		var label = $(this).data('ga-label') || '';
		label = label.replace('{t}', $(this).text());
		label = label.replace('{h}', $(this).attr('href'));
		push($(this).data('ga-cat'), 'Click', label);
		}

	function push(urlOrCat, action, label) {
		if (label) {
			label = label.replace('{u}', window.location.pathname);
		}
        // if there is a click action use push click event
		if (action) {
		    dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': urlOrCat, 'eventAction': 'Click', 'eventLabel': label });
		    console.info('GTM-MOB001 event: pushedEvent, eventAction: Click, eventCategory: ' + urlOrCat +', eventLabel: ' + label);
		}
        // other wise its a page view
		else {
		    dataLayer.push({ 'event': 'pushedVPV', 'virtualPageview': urlOrCat });
		    console.info('GTM-MOB002 event: pushedVPV, virtualPageview: ' + urlOrCat);
		}
		}     	






       	
        	

//----- End Google Analytics Tags ----------------------//


});


;


$(function () {
    App.init();

    $(".flip").on("click", function () { return false; });
    $('body').css("display", "block");
});


var App = {

    init: function () {
        // Placeholder text for search bar.
        var searchContent = 'Search';
        $('.section-03 input').each(function (i, element) {
            element.value = searchContent;
        }).focus(function () {
            if (this.value == searchContent) {
                this.value = '';
            }
        }).blur(function () {
            if (!this.value) {
                this.value = searchContent;
            }
        });

        $('.section-03 input, #mSearchbar').keypress(function (e) {
            if (e.which == 13) {
                var search = $(this).val();
                var domain = window.location.host;
                location.assign("http://" + domain + "/search/?q=" + search.replace(/[<>&?*.()]/g, ""));
            }
        });

        $('.goSearch').click(function () {
            var search = $(this).prev('input').val();
            var domain = window.location.host;
            location.assign("http://" + domain + "/search/?q=" + search.replace(/[<>&?*.()]/g, ""));
        });

        $('#nav-page li a').click(function () {

            // Placeholder text for search bar.
            var searchContent = '';
            $('input#office1StartDirections ').each(function (i, element) {
                element.value = searchContent;
            }).focus(function () {
                if (this.value == searchContent) {
                    this.value = '';
                }
            }).blur(function () {
                if (!this.value) {
                    this.value = searchContent;
                }
            });

        });

        $("#link_quickmovein").click(function () {
            var $active = $("ul.tabs").find('> .active');
            $active.removeClass('active');
            $("#floorplans").removeClass('active');
            $("#quickmovein").addClass('active');
            $('html,body').animate({ scrollTop: $("#quickmovein").offset().top }, 'fast');
            return false;
        });

        $("#link_quickmovein_sales").click(function () {
            var $active = $("ul.tabs").find('> .active');
            $active.removeClass('active');
            $("#salesoffice").removeClass('active');
            $("#quickmovein").addClass('active');
            return false;
        });

        //fire init for navigation functionality
        App.navFunctions.init();

        App.galleryFunctions.init();
        App.mortgageCalc.init();
        App.tablesorter.init();
        App.contactSearchFunctions.init();
        App.pressReleases.init();
        App.communities.init();

    },

    // called as the last thing after page loads
    postInit: function () {

        ///--> moved hashchange to MyKB View

    },

    navFunctions: {

        communitySelector: null,

        init: function () {
            var mainComSlideFunc = App.navFunctions.closeAllNav;

            /* copy communities nav to home nav */
            $("div.statesHome").append($("div.states ul").clone());
            $("div.countiesHome").append($("div.counties ul").clone());


            /* Nav animations */
            //COMMUNITES & FLOORPLANS CLICK
            $('li.communities > a').click(function (e) {
                App.navFunctions.customizeSlide();
                $('.recentviewed').slideDown();

                //show floor plans in community
                var communityLength = $(".community ul.bList").children().length
                if (communityLength > 0) {
                    $(".community").css({ 'height': ($('.community ul .listing').outerHeight() * 2) + 28 });
                    $('.community').fadeIn('fast').animate({ 'width': '230px' }, {
                        duration: 200, queue: false, ease: "easeOutCubic",
                        complete: function () {
                            $('.community ul').fadeIn('fast');
                            $('.community a').click(function () {
                                $('.community ul').fadeOut('fast', function () {
                                    $('.community').animate({ 'width': '0' }, { duration: 200, queue: false, ease: "linear", complete: function () { $('.recentviewed').slideUp(); } }).fadeOut('fast');
                                });
                            });
                        }
                    });
                    App.navFunctions.communitySelector = $(this).attr('class');
                    //return false;
                }





                //Bind a document click to click anywhere close the nav. 
                $(document).bind('click', function () {
                    App.navFunctions.closeAllNav();
                    $(this).unbind('click');
                });

                return false;
            });

            $('.bto li a').click(function () {
                // TODO Fire off page action. 
                App.navFunctions.customizeSlide();

                //Bind a document click to click anywhere close the nav. 
                $(document).bind('click', function () {
                    //App.navFunctions.closeAllNav();
                    $('.bto').slideUp();
                    $(this).unbind('click');
                });

            });
            
 

            //close nav on click.
            $('.counties li a, .countiesHome li a').click(function () {
                App.navFunctions.countiesClose(mainComSlideFunc);
                $(document).bind('click', function () {
                    App.navFunctions.closeAllNav();
                    $(this).unbind('click');
                });
            });

            // Recent viewed clicked
            $('#nav .recent').click(function () {
                App.navFunctions.countiesClose();
                //				var communityLength = $(".community ul.bList").children().length
                //				if (communityLength > 0) {
                //					$(".community").css({ 'height': ($('.community ul .listing').height() * 2) + 15 });
                //					$('.community').fadeIn('fast').animate({ 'width': '200px' }, { duration: 200, queue: false, ease: "easeOutCubic",
                //						complete: function () {
                //							$('.community ul').fadeIn('fast');
                //							$('.community a').click(function () {
                //								$('.community ul').fadeOut('fast', function () {
                //									$('.community').animate({ 'width': '0' }, { duration: 200, queue: false, ease: "linear", complete: function () { $('.recentviewed').slideUp(); } }).fadeOut('fast');
                //								});
                //							});
                //						}
                //					});
                //					App.navFunctions.communitySelector = $(this).attr('class');
                //					return false;
                //				}
            });

            $('#comNames').click(function () {
                App.navFunctions.communityClose();
                $('.community').stop(true, true);
                $('.bto').slideUp();
                $('.bto').stop(true, true);

                // Fade in states ul
                $('.states').fadeIn('fast').animate({ 'width': '114px' }, {
                    duration: 200, queue: false, ease: "easeOutCubic",
                    complete: function () {
                        //set height of navbox to ensure proper spacing
                        $(".navBox").css({ 'height': $('.states').height() + 20 });
                        $('.states li a').click(function () {
                            if ($(this).attr('href') != '#') {
                                return true;
                            }
                            var state = $(this).attr('data-state');
                            $('.counties >ul').hide();
                            var selCounty = $('.counties >ul[data-for-state="' + state + '"]');
                            selCounty.show();
                            $('.counties').fadeIn('fast').animate({ 'width': '185px' }, { duration: 200, queue: false, ease: "easeOutCubic" });
                            return false;
                        });
                    }
                });
                App.navFunctions.communitySelector = $(this).attr('id');
                return false;
            });


            $('#comNamesHome').click(function () {
                App.navFunctions.communityClose();
                $('.community').stop(true, true);
                $('.bto').slideUp();
                $('.bto').stop(true, true);

                // Fade in states ul
                $('.statesHome').fadeIn('fast').animate({ 'width': '114px' }, {
                    duration: 200, queue: false, ease: "easeOutCubic",
                    complete: function () {
                        //set height of navbox to ensure proper spacing
                        $(".navBoxHome").css({ 'height': $('.statesHome').height() + 20 });
                        $('.statesHome li a').click(function () {
                            if ($(this).attr('href') != '#') {
                                return true;
                            }
                            var state = $(this).attr('data-state');
                            $('.countiesHome >ul').hide();
                            var selCounty = $('.countiesHome >ul[data-for-state="' + state + '"]');
                            selCounty.show();
                            $('.countiesHome').fadeIn('fast').animate({ 'width': '185px' }, { duration: 200, queue: false, ease: "easeOutCubic" });
                            return false;
                        });
                    }
                });
                App.navFunctions.communitySelector = $(this).attr('id');
                $(document).bind('click', function () {
                    App.navFunctions.closeAllNav();
                    $(this).unbind('click');
                });
                return false;
            });

            $('#comNamesStateHome').click(function () {
                App.navFunctions.communityClose();

                var state = $(this).attr('data-state');
                $('#stateHomeCounties >ul').hide();
                var selCounty = $('#stateHomeCounties >ul[data-for-state="' + state + '"]');
                selCounty.show();
                $('#stateHomeCounties').fadeIn('fast').animate({ 'width': '185px' }, { duration: 200, queue: false, ease: "easeOutCubic" });
                return false;

                App.navFunctions.communitySelector = $(this).attr('id');
                $(document).bind('click', function () {
                    App.navFunctions.closeAllNav();
                    $(this).unbind('click');
                });
                return false;
            });


            $('.community a').click(function () {
                // TODO Fire off page action. 
                App.navFunctions.communityClose(mainComSlideFunc);
            });

            //BUILT TO ORDER CLICK
            $('li.custom a.builtToOrderSection').click(function (e) {

                App.navFunctions.closeAllNav();

                $('.bto').slideDown();

                $(document).bind('click', function () {
                    //App.navFunctions.closeAllNav();
                    $('.bto').slideUp();
                    $(this).unbind('click');
                });

                return false;
            });




            $('a#action-menu').click(function () {
                $(this).parent().children('.action-dropdown').toggle();
                return false;
            });




        },
        //Slide communities and floorplans link back up.
        comSlide: function () {
            $('.recentviewed').slideUp();

            if ($('.community ul').is('visible')) {
                $('.community ul').fadeOut('fast', function () {
                    $('.community').animate({ 'width': '0' }, { duration: 200, queue: false, ease: "linear", complete: function () { $('.recentviewed').slideUp(); } }).fadeOut('fast');
                });
            }
        },
        closeAllNav: function () {
            if (App.navFunctions.communitySelector == 'recent') {
                App.navFunctions.communityClose(App.navFunctions.comSlide);
            } else if (App.navFunctions.communitySelector == 'comNames' || App.navFunctions.communitySelector == 'comNamesHome' || App.navFunctions.communitySelector == 'comNamesStateHome') {
                App.navFunctions.countiesClose(App.navFunctions.comSlide);
            } else { App.navFunctions.communityClose(App.navFunctions.comSlide); }
        },



        //Slide built to order
        customizeSlide: function () { $('.bto').slideUp(); },

        countiesClose: function (func) {

            $('.counties, .countiesHome').animate({ 'width': '0' }, {
                duration: 200, queue: false, ease: "linear",
                complete: function () {
                    $('.states, .statesHome').animate({ 'width': '0' }, {
                        duration: 200, queue: false, ease: "linear",
                        complete: func
                    }).fadeOut();
                    $(".navBox, .navBoxHome").css({ 'height': '0' });
                }
            }).fadeOut();
            App.navFunctions.communitySelector = null;
        },


        communityClose: function (func) {
            $('.community ul').fadeOut('fast', function () {
                $('.community').animate({ 'width': '0' }, { duration: 200, queue: false, ease: "linear", complete: func }).fadeOut('fast');

            });
            App.navFunctions.communitySelector = null;
        }
    },


    galleryFunctions: {

        open: false,
        scroll: false,
        init: function () {

            $('#gallery #target').click(App.galleryFunctions.clickImage);


            $(window).scroll(function () {
                App.galleryFunctions.scroll = true;
                App.galleryFunctions.clickImage();
            });
            //App.galleryFunctions.clickImage()
        },
        clickImage: function (nav) {

            //commented out to remove gallery expansion
            /*
            if (App.galleryFunctions.scroll) {
            $('#nav').animate({ 'margin-top': '0' });
            $('.carousel').animate({ 'height': '640' })
            App.galleryFunctions.open = false;
            } else {
            if (!App.galleryFunctions.open || nav == 'left') {
            $('#nav').animate({ 'margin-top': '-100' });
            $('.carousel').animate({ 'height': '800' })
            App.galleryFunctions.open = true;
            } else if (App.galleryFunctions.open || !scroll) {
            $('#nav').animate({ 'margin-top': '0' });
            $('.carousel').animate({ 'height': '640' })
            App.galleryFunctions.open = false;
            }
            }
            App.galleryFunctions.scroll = false;

            */
        }


    },
    mortgageCalc: {


        init: function () {



            try {
                //temporary - switch back to fixed number later
                //var mortgageAmount = $('#mCalculator b').html().replace(/[Amount:$, ]/g, '');
                var mortgageAmount = $('#mCalculator #amount').val().replace(/[Amount:$, ]/g, '');
                var mortgageRate = $('#rate').val().replace('%', '');
            } catch (err) {

                App.mortgageCalc.financePage();
                return false;

            }

            var downpay = 0;
            var showDisclaimer = '';

            //temporary - switch back to fixed number later
            //var monthly_payment = App.mortgageCalc.calculate_payment(mortgageAmount, downpay, mortgageRate, taxes, insurance, annualtax, fha, cll)

            $('#submitRate').click(function () {
                $(".error").hide();

                showDisclaimer = $.cookie('calc_disclaimer');

                if (showDisclaimer != 'false') {
                    $("#calculatordisclaimer").show();
                    $.cookie('calc_disclaimer', 'false');
                }

                mortgageAmount = $('#amount').val().replace('$', '').replace(/,/g, '');
                downpay = $('#downpayment').val().replace('$', '').replace(/,/g, '');
                mortgageRate = $('#rate').val().replace('%', '');

                if ($.isNumeric(downpay) == false) {
                    $("#dperr").show();
                }

                if ($.isNumeric(mortgageRate) == false) {
                    $("#rateerror").show();
                }

                if ((downpay != "") && (parseInt(downpay) <= parseInt(mortgageAmount))) {
                    //temporary - switch back to fixed number later
                    //monthly_payment = App.mortgageCalc.calculate_payment(mortgageAmount, downpay, mortgageRate, taxes, insurance, annualtax, fha, cll)
                    monthly_payment = App.mortgageCalc.find_payment((mortgageAmount - downpay), mortgageRate);
                    try {
                        ewt.track({ name: communityName, type: 'calculator' });
                        console.info('GTM-SCR003 ewt.track - name: ' + communityName + ', type: savefloorplan');
                    }
                    catch (err) {
                    }
                }
                else {
                    monthly_payment = '$0';
                }
                $('#total-mortgage span').html(monthly_payment)

            });

            $("#closedisclaimer").click(function () {
                $("#calculatordisclaimer").hide();
            });

        },


        financePage: function () {

            try {
                var mortgageAmount = $('#mCalculator #amount').val().replace(/[Amount:$, ]/g, '');
                var mortgageRate = $('#rate').val().replace('%', '');
            } catch (err) {
                return false;
            }

            var downpay = 0;

            var monthly_payment = App.mortgageCalc.find_payment((mortgageAmount - downpay), mortgageRate)





            $('#submitRate').click(function () {
                $(".error").hide();

                mortgageAmount = $('#amount').val().replace('$', '').replace(/,/g, '');
                downpay = $('#downpayment').val().replace('$', '').replace(/,/g, '');
                mortgageRate = $('#rate').val().replace('%', '');

                if (($.isNumeric(downpay) == false) || ($.isNumeric(mortgageAmount) == false)) {
                    $(".error").show();
                }

                if ((downpay != "") && (parseInt(downpay) <= parseInt(mortgageAmount))) {
                    monthly_payment = App.mortgageCalc.find_payment((mortgageAmount - downpay), mortgageRate)
                }
                else {
                    monthly_payment = '$0';
                }
                $('.total span').html(monthly_payment)
            });

        },



        find_payment: function (PR, IN) {
            PR = PR;
            IN = (IN / 100) / 12;
            var PE = 30 * 12

            var PAY = (PR * IN) / (1 - Math.pow(1 + IN, -PE))
            return '$' + App.mortgageCalc.numFormat(Math.ceil(PAY));
        },
        numFormat: function (amount) {
            var delimiter = ",";
            var i = parseInt(amount);
            if (isNaN(i)) { return ''; }
            var origi = i;  // store original to check sign
            i = Math.abs(i);

            var minus = '';
            if (origi < 0) { minus = '-'; } // sign based on original

            var n = new String(i);
            var a = [];

            while (n.length > 3) {
                var nn = n.substr(n.length - 3);
                a.unshift(nn);
                n = n.substr(0, n.length - 3);
            }

            if (n.length > 0) { a.unshift(n); }

            n = a.join(delimiter);

            amount = minus + n;

            return amount;
        },

        calculate_payment: function (P, DP, IN, TR, IR, AAT, FHA, CONF) {
            PR = (P - DP);
            IN = (IN / 100) / 12;
            var PE = 30 * 12
            var MI = App.mortgageCalc.mortgage_insurance(P, FHA, CONF)

            var PI = (PR * IN) / (1 - Math.pow(1 + IN, -PE))
            var M = ((PR * MI) / 12)
            var T = (P * TR / 100 / 12)
            var I = (P * IR / 100 / 12)
            var AT = (AAT / 12)
            var PAY = PI + M + T + I + AT

            return '$' + App.mortgageCalc.numFormat(Math.ceil(PAY));
        },

        mortgage_insurance: function (price, fha, conf) {
            var rate = 0;

            if ((price * .965 * (1 + 0.01)) <= fha) {
                rate = 0.0115;
            }
            else if ((price * .95) <= conf) {
                rate = 0.0094;
            }
            else if ((price * .90) <= conf) {
                rate = 0.0062;
            }

            return rate;
        }
    },


    tablesorter: {

        init: function () {
            try {
                $("#saved-floorplans").tablesorter();
            } catch (err) {
                return false;
            }
        }

    },

    tablesorterBroker: {

        init: function () {
            try {
                $("#broker-communities").tablesorter();
                $("#broker-communities").trigger("update");
            } catch (err) {
                return false;
            }
        }

    },

    contactSearchFunctions: {
        init: function () {
            $('select#area').change(function () {
                var state = $('select#area').val();
                $('.region_info').hide(); //hide the region info if we're switching states
                $("#region option.region").remove(); //remove all the regions
                $('select#hidden_regions option.region_' + state).clone().appendTo('#region'); //grab the regions for this state and add them to the list
            });
            $('select#region').change(function () {
                var region = $('select#region').val();
                $('.region_info').hide();
                $('#region_info_' + region).show();
            });

            $('select#area2').change(function () {
                var state = $('select#area2').val();
                $('.contact_info').hide(); //hide the region info if we're switching states
                $('.contact_info_' + state).show();
            });

            //for broker page
            $('select#area3').change(function () {
                var state = $('select#area3').val();
                $('.state_info').hide(); //hide the state info if we're switching states
                $('.region_info').show(); //show the region info if we're switching states
                $('.area_name_region').hide();
                $('.area_name_state').show();
                $('#state_info_' + state).show();

                $("#region3 option.region").remove(); //remove all the regions
                $('select#hidden_regions3 option.region_' + state).clone().appendTo('#region3'); //grab the regions for this state and add them to the list
                //tracking for state
                dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Filter Dropdown', 'eventAction': 'Click', 'eventLabel': 'Area of Interest - Select State:' + state + ':/for-brokers' });
                console.info('GTM-SCR001 event: pushedEvent, eventAction: Click, eventCategory: Filter Dropdown, eventLabel: Area of Interest - Select State:' + state + ':/for-brokers');
            });
            $('select#region3').change(function () {
                var state = $('select#area3').val();
                var region = $('select#region3').val();
                if (region != "") {
                    $('.region_info').hide();
                    $('.area_name_region').hide();
                    $('.area_name_state').hide();
                    $('.region_info').hide();
                    $('.region_info_' + region).show();
                    $('.area_name_' + region).show();
                    //tracking for area
                    dataLayer.push({ 'event': 'pushedEvent', 'eventCategory': 'Filter Dropdown', 'eventAction': 'Click', 'eventLabel': 'Area of Interest - Select Region:' + region + ':/for-brokers' });
                    console.info('GTM-SCR002 event: pushedEvent, eventAction: Click, eventCategory: Filter Dropdown, eventLabel: Area of Interest - Select Region:' + region + ':/for-brokers');
                }
                else //show all regions
                {
                    $('.area_name_region').hide();
                    $('.area_name_state').show();
                    $('.region_info').show(); //show the region info if it's all regions
                }
            });
        }
    },

    pressReleases: {
        init: function () {

            $("#prArchiveTabs .tabs2 a").click(function () {
                var activeYear = $(this).text();
                $("#prArchiveTabs .tab-content2 .press-release").hide();
                $("#prArchiveTabs .press-release[data-year='" + activeYear + "']").show();
            });

            $("#prArchiveTabs li.active a").click();
        }

    },

    communities: {
        init: function () {
            // if the current page doesn't contain a section with the id of the hash 
            // link (i.e. $("#neighborhoods")), then redirect to the community page.
            //$("#nav-page li a").click(function () {
            //    if (!$($(this).attr("href")).length) {
            //        location.href = $(this).closest("ul").attr("data-community") + $(this).attr("href");
            //    }
            //});
        }
    },

    Url: function (path) {
        return (APP_PATH || '') + (path[0] != '/' ? '/' : '') + path;
    }



}





//---------- sales office and directions


var googleMapsUrl = "http://maps.google.com/maps";


$(function () {

    //address 1   
    //$("#office1MapDirections").click(function (e) {
    //	e.preventDefault();
    //	start = $("#office1StartDirections").val();
    //	end = $("#office1EndDirections").val();
    //	openDrivingDirectionsMap(start, end);
    //});

    //address 2
    //$("#office2MapDirections").click(function (e) {
    //	e.preventDefault();
    //	start = $("#office2StartDirections").val();
    //	end = $("#office2EndDirections").val();
    //	openDrivingDirectionsMap(start, end);
    //});
    //address 3

    //$("#office3MapDirections").click(function (e) {
    //	e.preventDefault();
    //	start = $("#office3StartDirections").val();
    //	end = $("#office3EndDirections").val();
    //	openDrivingDirectionsMap(start, end);
    //});

    //---------- Floor plan sales office and directions

    //$("#FloorPlanOfficeMapDirections").click(function (e) {
    //	e.preventDefault();
    //	start = $("#FloorPlanDrivingStart").val();
    //	end = $("#FloorPlanDrivingEnd").val();
    //	openDrivingDirectionsMap(start, end);
    //});

});


//---------- map directions

//open google maps
function openDrivingDirectionsMap(start, end) {
    if (window.viewingDevice != "Desktop") {
        if (geo_position_js.init()) {
            setTimeout(function () { geo_position_js.getCurrentPosition(geolocSuccess, geolocFail) }, 0);
        }
    }
    function geolocFail(p) {
        console.log("geolocFail");
        window.open(googleMapsUrl + "?saddr=" + start + "&daddr=" + end);
    }

    function geolocSuccess(p) {
        geoTargetted = true;
        var lat = p.coords.latitude;
        var lng = p.coords.longitude;
        window.open(googleMapsUrl + "?saddr=" + lat + "+" + lng + "&daddr=" + end);
    }

}


//------ page backgrounds from cms

function initCmsPageBg(image) {
    //TODO: use app url here
    imagePath = App.Url("/assets/images/" + image);
    $(".bg-CmsPage").css("background-image", "url(" + imagePath + ")");
}

// Page scripts
$(function () {

    $("#community-sort").change(function () {
        $("option:selected", $(this)).each(function () {
            var sortValue = $(this).val();
            SortRegion(sortValue);
            return false;
        });
    });

    $("#floorplan-sort").change(function () {
        $("option:selected", $(this)).each(function () {
            var sortValue = $(this).val();
            SortFloorPlan(sortValue);
            return false;
        });
    });

    $("#qmi-local-sort").change(function () {
        $("option:selected", $(this)).each(function () {
            var sortValue = $(this).val();
            SortQMILocal(sortValue);
            return false;
        });
    });

});









//Correct Dollar Notation (Used by Mortgage Calculator)
function commaSeparateNumber(val) {
    while (/(\d+)(\d{3})/.test(val.toString())) {
        val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
    }
    return val;
}
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}



//QMI Warranty Disclaimer (per Legal)
function addLegal() {
    var rVal = " (see KB Home Limited Warranty for full details.)";
    var wArray = {
        "Builder warranty": "Builder warranty" + rVal,
        "10-Year Limited Warranty": "10-Year Limited Warranty" + rVal,
        "Builder's limited warranty": "Builder's limited warranty" + rVal,
        "10-yr. warranty": "10-yr. warranty" + rVal,
        "10 year limited warranty": "10 year limited warranty" + rVal,
        "10-Year Warranty": "10-Year Warranty" + rVal,
        "10-year KB Home Limited Warranty": "10-Year Limited Warranty" + rVal,
        "new home warranty": "10-Year Limited Warranty" + rVal
    };
    $('.qmi-row .description').each(function () {
        var dText = $(this).html();
        for (var key in wArray) {
            dText = dText.replace(key, wArray[key]);
        }
        $(this).html(dText);
    });
}


//Completely Remove Hash from URL
function removeHash() {
    history.pushState("", document.title, window.location.pathname + window.location.search);
}


//Open Mobile Nav Tab
function openNavTab_m(id) {
    $('.tab-pane, .accordion-navigation').removeClass('active');
    $(id).parent().addClass('active');
    $(id).addClass('active');
}


//Toggle Nav Top Button
function toggleNavTop() {
    var wHeight = parseInt($(window).height() + 200);
    var cHeight = parseInt($(document).height());
    if (cHeight > wHeight) {
        $('#navTop').show();
    } else {
        $('#navTop').hide();
    }
}


//Media Query Matching
var mediaQuery = '';
$(function () {
    enquire.register("screen and (max-width:40em)", {
        match: function () {
            mediaQuery = 'SML';
            console.info('Media Query: SML');
        }
    });
    enquire.register("screen and (min-width:40.05em) and (max-width: 64em)", {
        match: function () {
            mediaQuery = 'MED';
            console.info('Media Query: MED');
        }
    });
    enquire.register("screen and (min-width: 64.063em)", {
        match: function () {
            mediaQuery = 'LRG';
            console.info('Media Query: LRG');
        }
    });
});




// commnunity and floor plan gallery
$(function () {

    //set gallery image size on load
    if ($("#gallery .orbit > .slideBanner img").height() < 200) {
        $("#gallery .orbit").css("min-height", 800);
    } else {
        $("#gallery .orbit").css("min-height", function () { return $("#gallery .orbit > .slideBanner img").height() });
    }

    //resize gallery image
    $(window).resize(function () {
        $("#gallery .orbit").css("min-height", function () { return $("#gallery .orbit > .slideBanner img").height() });
    });

    $('.regionContent').delay(2000).animate({ marginTop: [0, 'easeInSine'] }, 2000, function () {
        $('.controls').fadeIn('slow');
        // The gallery pinterst pins are for the Community Slideshow images
        $("#gallery .pinterest").fadeIn("slow");
    });


    /*Global JQuery Functions*/

    //--Functions








    //Set iPad inital zoom
    var zoom = document.documentElement.clientWidth / window.innerWidth;


    function zPinch() {
        $(".lockfixed").addClass('zoomed');
        //iPad zoom detection
        var zoomNew = document.documentElement.clientWidth / window.innerWidth;
        if (zoomNew <= zoom) {
            $(".lockfixed").removeClass('zoomed');
        }
    }

    $(document).bind('pinch', zPinch);






    //--Window Resize
    window.addEventListener('resize', function () {


        //--LockFixed Adjustments - set the width of the div when window resizes

        //fluid box width
        if ($(window).width() > 640) {
            var $box = $('.lockfixed');
            $box.width($box.parent().outerWidth());
        }

        //window measurements
        var bHeight = $('.lockfixed .inner').outerHeight();
        var wHeight = $(window).height();

        if ($(window).width() < 641 || wHeight <= bHeight) { /*Window Width = 641*/
            $(".lockfixed").addClass('static');
        } else {
            $(".lockfixed").removeClass('static');
        }




    });

    //--DOM Ready
    $(document).ready(function () {


        //--LockFixed
        //$.lockfixed(".lockfixed",{offset: {top: 0, bottom: 100}});
        $('.lockfixed').sticky({ topSpacing: 0, bottomSpacing: 100 });


        //--Correct iOS mis-identifying tel links
        $('.sqft a').contents().unwrap();


        //--Correct Initial iPad Zoom
        if (zoom > 1) {
            $(".lockfixed").addClass('zoomed');
        } else {
            $(".lockfixed").removeClass('zoomed');
        }


        //--Prevent iOS form Zooming
        var $viewportMeta = $('meta[name="viewport"]');
        $('input, select, textarea').bind('focus blur', function (event) {
            $viewportMeta.attr('content', 'width=device-width,initial-scale=1,maximum-scale=' + (event.type == 'blur' ? 10 : 1));
        });





        options = {
            // Specifies which browsers/versions will be blocked
            reject: {
                all: false, // Covers Everything (Nothing blocked)
                msie: 8 // Covers MSIE <= 6 (Blocked by default)
                /*
                * Many possible combinations.
                * You can specify browser (msie, chrome, firefox)
                * You can specify rendering engine (geko, trident)
                * You can specify OS (Win, Mac, Linux, Solaris, iPhone, iPad)
                *
                * You can specify versions of each.
                * Examples: msie9: true, firefox8: true,
                *
                * You can specify the highest number to reject.
                * Example: msie: 9 (9 and lower are rejected.
                *
                * There is also "unknown" that covers what isn't detected
                * Example: unknown: true
                */
            },
            display: [], // What browsers to display and their order (default set below)
            browserShow: true, // Should the browser options be shown?
            browserInfo: { // Settings for which browsers to display
                chrome: {
                    // Text below the icon
                    text: 'Google Chrome',
                    // URL For icon/text link
                    url: 'http://www.google.com/chrome/',
                    // (Optional) Use "allow" to customized when to show this option
                    // Example: to show chrome only for IE users
                    // allow: { all: false, msie: true }
                },
                firefox: {
                    text: 'Mozilla Firefox',
                    url: 'http://www.mozilla.com/firefox/'
                },
                safari: {
                    text: 'Safari',
                    url: 'http://www.apple.com/safari/download/'
                },
                opera: {
                    text: 'Opera',
                    url: 'http://www.opera.com/download/'
                },
                msie: {
                    text: 'Internet Explorer',
                    url: 'http://www.microsoft.com/windows/Internet-explorer/'
                }
            },

            // Pop-up Window Text
            header: 'Did you know that your Internet Browser is out of date?',

            paragraph1: 'Your browser is out of date, and may not display all features of this and other websites.',

            paragraph2: 'Click on an icon to download the latest browser version.',

            // Allow closing of window
            close: true,

            // Message displayed below closing link
            closeMessage: 'Your experience on this website may be degraded if you continue.',
            closeLink: 'Close This Window',
            closeURL: '#',

            // Allows closing of window with esc key
            closeESC: true,

            // Use cookies to remmember if window was closed previously?
            closeCookie: true,
            // Cookie settings are only used if closeCookie is true
            cookieSettings: {
                // Path for the cookie to be saved on
                // Should be root domain in most cases
                path: '/',
                // Expiration Date (in seconds)
                // 0 (default) means it ends with the current session
                expires: 0
            },

            // Path where images are located
            imagePath: '/Content/images/',
            // Background color for overlay
            overlayBgColor: '#000',
            // Background transparency (0-1)
            overlayOpacity: 0.8,

            // Fade in time on open ('slow','medium','fast' or integer in ms)
            fadeInTime: 'fast',
            // Fade out time on close ('slow','medium','fast' or integer in ms)
            fadeOutTime: 'fast',

            // Google Analytics Link Tracking (Optional)
            // Set to true to enable
            // Note: Analytics tracking code must be added separately
            analytics: false
        };
        $.reject(options);







    });












    ////
});;
/*
 * Foundation Responsive Library
 * http://foundation.zurb.com
 * Copyright 2014, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/

(function ($, window, document, undefined) {
  'use strict';

  var header_helpers = function (class_array) {
    var i = class_array.length;
    var head = $('head');

    while (i--) {
      if(head.has('.' + class_array[i]).length === 0) {
        head.append('<meta class="' + class_array[i] + '" />');
      }
    }
  };

  header_helpers([
    'foundation-mq-small',
    'foundation-mq-small-only',
    'foundation-mq-medium',
    'foundation-mq-medium-only',
    'foundation-mq-large',
    'foundation-mq-large-only',
    'foundation-mq-xlarge',
    'foundation-mq-xlarge-only',
    'foundation-mq-xxlarge',
    'foundation-data-attribute-namespace']);

  // Enable FastClick if present

  $(function() {
    if (typeof FastClick !== 'undefined') {
      // Don't attach to body if undefined
      if (typeof document.body !== 'undefined') {
        FastClick.attach(document.body);
      }
    }
  });

  // private Fast Selector wrapper,
  // returns jQuery object. Only use where
  // getElementById is not available.
  var S = function (selector, context) {
    if (typeof selector === 'string') {
      if (context) {
        var cont;
        if (context.jquery) {
          cont = context[0];
          if (!cont) return context;
        } else {
          cont = context;
        }
        return $(cont.querySelectorAll(selector));
      }

      return $(document.querySelectorAll(selector));
    }

    return $(selector, context);
  };

  // Namespace functions.

  var attr_name = function (init) {
    var arr = [];
    if (!init) arr.push('data');
    if (this.namespace.length > 0) arr.push(this.namespace);
    arr.push(this.name);

    return arr.join('-');
  };

  var add_namespace = function (str) {
    var parts = str.split('-'),
        i = parts.length,
        arr = [];

    while (i--) {
      if (i !== 0) {
        arr.push(parts[i]);
      } else {
        if (this.namespace.length > 0) {
          arr.push(this.namespace, parts[i]);
        } else {
          arr.push(parts[i]);
        }
      }
    }

    return arr.reverse().join('-');
  };

  // Event binding and data-options updating.

  var bindings = function (method, options) {
    var self = this,
        should_bind_events = !S(this).data(this.attr_name(true));

    if (S(this.scope).is('[' + this.attr_name() +']')) {
      S(this.scope).data(this.attr_name(true) + '-init', $.extend({}, this.settings, (options || method), this.data_options(S(this.scope))));

      if (should_bind_events) {
        this.events(this.scope);
      }

    } else {
      S('[' + this.attr_name() +']', this.scope).each(function () {
        var should_bind_events = !S(this).data(self.attr_name(true) + '-init');
        S(this).data(self.attr_name(true) + '-init', $.extend({}, self.settings, (options || method), self.data_options(S(this))));

        if (should_bind_events) {
          self.events(this);
        }
      });
    }
    // # Patch to fix #5043 to move this *after* the if/else clause in order for Backbone and similar frameworks to have improved control over event binding and data-options updating.
    if (typeof method === 'string') {
      return this[method].call(this, options);
    }

  };

  var single_image_loaded = function (image, callback) {
    function loaded () {
      callback(image[0]);
    }

    function bindLoad () {
      this.one('load', loaded);

      if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        var src = this.attr( 'src' ),
            param = src.match( /\?/ ) ? '&' : '?';

        param += 'random=' + (new Date()).getTime();
        this.attr('src', src + param);
      }
    }

    if (!image.attr('src')) {
      loaded();
      return;
    }

    if (image[0].complete || image[0].readyState === 4) {
      loaded();
    } else {
      bindLoad.call(image);
    }
  };

  /*
    https://github.com/paulirish/matchMedia.js
  */

  window.matchMedia = window.matchMedia || (function( doc ) {

    'use strict';

    var bool,
        docElem = doc.documentElement,
        refNode = docElem.firstElementChild || docElem.firstChild,
        // fakeBody required for <FF4 when executed in <head>
        fakeBody = doc.createElement( 'body' ),
        div = doc.createElement( 'div' );

    div.id = 'mq-test-1';
    div.style.cssText = 'position:absolute;top:-100em';
    fakeBody.style.background = 'none';
    fakeBody.appendChild(div);

    return function (q) {

      div.innerHTML = '&shy;<style media="' + q + '"> #mq-test-1 { width: 42px; }</style>';

      docElem.insertBefore( fakeBody, refNode );
      bool = div.offsetWidth === 42;
      docElem.removeChild( fakeBody );

      return {
        matches: bool,
        media: q
      };

    };

  }( document ));

  /*
   * jquery.requestAnimationFrame
   * https://github.com/gnarf37/jquery-requestAnimationFrame
   * Requires jQuery 1.8+
   *
   * Copyright (c) 2012 Corey Frang
   * Licensed under the MIT license.
   */

  (function($) {

  // requestAnimationFrame polyfill adapted from Erik Möller
  // fixes from Paul Irish and Tino Zijdel
  // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating

  var animating,
      lastTime = 0,
      vendors = ['webkit', 'moz'],
      requestAnimationFrame = window.requestAnimationFrame,
      cancelAnimationFrame = window.cancelAnimationFrame,
      jqueryFxAvailable = 'undefined' !== typeof jQuery.fx;

  for (; lastTime < vendors.length && !requestAnimationFrame; lastTime++) {
    requestAnimationFrame = window[ vendors[lastTime] + 'RequestAnimationFrame' ];
    cancelAnimationFrame = cancelAnimationFrame ||
      window[ vendors[lastTime] + 'CancelAnimationFrame' ] ||
      window[ vendors[lastTime] + 'CancelRequestAnimationFrame' ];
  }

  function raf() {
    if (animating) {
      requestAnimationFrame(raf);

      if (jqueryFxAvailable) {
        jQuery.fx.tick();
      }
    }
  }

  if (requestAnimationFrame) {
    // use rAF
    window.requestAnimationFrame = requestAnimationFrame;
    window.cancelAnimationFrame = cancelAnimationFrame;

    if (jqueryFxAvailable) {
      jQuery.fx.timer = function (timer) {
        if (timer() && jQuery.timers.push(timer) && !animating) {
          animating = true;
          raf();
        }
      };

      jQuery.fx.stop = function () {
        animating = false;
      };
    }
  } else {
    // polyfill
    window.requestAnimationFrame = function (callback) {
      var currTime = new Date().getTime(),
        timeToCall = Math.max(0, 16 - (currTime - lastTime)),
        id = window.setTimeout(function () {
          callback(currTime + timeToCall);
        }, timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };

    window.cancelAnimationFrame = function (id) {
      clearTimeout(id);
    };

  }

  }( jQuery ));


  function removeQuotes (string) {
    if (typeof string === 'string' || string instanceof String) {
      string = string.replace(/^['\\/"]+|(;\s?})+|['\\/"]+$/g, '');
    }

    return string;
  }

  window.Foundation = {
    name : 'Foundation',

    version : '5.5.0',

    media_queries : {
      'small'       : S('.foundation-mq-small').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
      'small-only'  : S('.foundation-mq-small-only').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
      'medium'      : S('.foundation-mq-medium').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
      'medium-only' : S('.foundation-mq-medium-only').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
      'large'       : S('.foundation-mq-large').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
      'large-only'  : S('.foundation-mq-large-only').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
      'xlarge'      : S('.foundation-mq-xlarge').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
      'xlarge-only' : S('.foundation-mq-xlarge-only').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''),
      'xxlarge'     : S('.foundation-mq-xxlarge').css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, '')
    },

    stylesheet : $('<style></style>').appendTo('head')[0].sheet,

    global: {
      namespace: undefined
    },

    init : function (scope, libraries, method, options, response) {
      var args = [scope, method, options, response],
          responses = [];

      // check RTL
      this.rtl = /rtl/i.test(S('html').attr('dir'));

      // set foundation global scope
      this.scope = scope || this.scope;

      this.set_namespace();

      if (libraries && typeof libraries === 'string' && !/reflow/i.test(libraries)) {
        if (this.libs.hasOwnProperty(libraries)) {
          responses.push(this.init_lib(libraries, args));
        }
      } else {
        for (var lib in this.libs) {
          responses.push(this.init_lib(lib, libraries));
        }
      }

      S(window).load(function(){
        S(window)
          .trigger('resize.fndtn.clearing')
          .trigger('resize.fndtn.dropdown')
          .trigger('resize.fndtn.equalizer')
          .trigger('resize.fndtn.interchange')
          .trigger('resize.fndtn.joyride')
          .trigger('resize.fndtn.magellan')
          .trigger('resize.fndtn.topbar')
          .trigger('resize.fndtn.slider');
      });

      return scope;
    },

    init_lib : function (lib, args) {
      if (this.libs.hasOwnProperty(lib)) {
        this.patch(this.libs[lib]);

        if (args && args.hasOwnProperty(lib)) {
            if (typeof this.libs[lib].settings !== 'undefined') {
              $.extend(true, this.libs[lib].settings, args[lib]);
            }
            else if (typeof this.libs[lib].defaults !== 'undefined') {
              $.extend(true, this.libs[lib].defaults, args[lib]);
            }
          return this.libs[lib].init.apply(this.libs[lib], [this.scope, args[lib]]);
        }

        args = args instanceof Array ? args : new Array(args);
        return this.libs[lib].init.apply(this.libs[lib], args);
      }

      return function () {};
    },

    patch : function (lib) {
      lib.scope = this.scope;
      lib.namespace = this.global.namespace;
      lib.rtl = this.rtl;
      lib['data_options'] = this.utils.data_options;
      lib['attr_name'] = attr_name;
      lib['add_namespace'] = add_namespace;
      lib['bindings'] = bindings;
      lib['S'] = this.utils.S;
    },

    inherit : function (scope, methods) {
      var methods_arr = methods.split(' '),
          i = methods_arr.length;

      while (i--) {
        if (this.utils.hasOwnProperty(methods_arr[i])) {
          scope[methods_arr[i]] = this.utils[methods_arr[i]];
        }
      }
    },

    set_namespace: function () {

      // Description:
      //    Don't bother reading the namespace out of the meta tag
      //    if the namespace has been set globally in javascript
      //
      // Example:
      //    Foundation.global.namespace = 'my-namespace';
      // or make it an empty string:
      //    Foundation.global.namespace = '';
      //
      //

      // If the namespace has not been set (is undefined), try to read it out of the meta element.
      // Otherwise use the globally defined namespace, even if it's empty ('')
      var namespace = ( this.global.namespace === undefined ) ? $('.foundation-data-attribute-namespace').css('font-family') : this.global.namespace;

      // Finally, if the namsepace is either undefined or false, set it to an empty string.
      // Otherwise use the namespace value.
      this.global.namespace = ( namespace === undefined || /false/i.test(namespace) ) ? '' : namespace;
    },

    libs : {},

    // methods that can be inherited in libraries
    utils : {

      // Description:
      //    Fast Selector wrapper returns jQuery object. Only use where getElementById
      //    is not available.
      //
      // Arguments:
      //    Selector (String): CSS selector describing the element(s) to be
      //    returned as a jQuery object.
      //
      //    Scope (String): CSS selector describing the area to be searched. Default
      //    is document.
      //
      // Returns:
      //    Element (jQuery Object): jQuery object containing elements matching the
      //    selector within the scope.
      S : S,

      // Description:
      //    Executes a function a max of once every n milliseconds
      //
      // Arguments:
      //    Func (Function): Function to be throttled.
      //
      //    Delay (Integer): Function execution threshold in milliseconds.
      //
      // Returns:
      //    Lazy_function (Function): Function with throttling applied.
      throttle : function (func, delay) {
        var timer = null;

        return function () {
          var context = this, args = arguments;

          if (timer == null) {
            timer = setTimeout(function () {
              func.apply(context, args);
              timer = null;
            }, delay);
          }
        };
      },

      // Description:
      //    Executes a function when it stops being invoked for n seconds
      //    Modified version of _.debounce() http://underscorejs.org
      //
      // Arguments:
      //    Func (Function): Function to be debounced.
      //
      //    Delay (Integer): Function execution threshold in milliseconds.
      //
      //    Immediate (Bool): Whether the function should be called at the beginning
      //    of the delay instead of the end. Default is false.
      //
      // Returns:
      //    Lazy_function (Function): Function with debouncing applied.
      debounce : function (func, delay, immediate) {
        var timeout, result;
        return function () {
          var context = this, args = arguments;
          var later = function () {
            timeout = null;
            if (!immediate) result = func.apply(context, args);
          };
          var callNow = immediate && !timeout;
          clearTimeout(timeout);
          timeout = setTimeout(later, delay);
          if (callNow) result = func.apply(context, args);
          return result;
        };
      },

      // Description:
      //    Parses data-options attribute
      //
      // Arguments:
      //    El (jQuery Object): Element to be parsed.
      //
      // Returns:
      //    Options (Javascript Object): Contents of the element's data-options
      //    attribute.
      data_options : function (el, data_attr_name) {
        data_attr_name = data_attr_name || 'options';
        var opts = {}, ii, p, opts_arr,
            data_options = function (el) {
              var namespace = Foundation.global.namespace;

              if (namespace.length > 0) {
                return el.data(namespace + '-' + data_attr_name);
              }

              return el.data(data_attr_name);
            };

        var cached_options = data_options(el);

        if (typeof cached_options === 'object') {
          return cached_options;
        }

        opts_arr = (cached_options || ':').split(';');
        ii = opts_arr.length;

        function isNumber (o) {
          return ! isNaN (o-0) && o !== null && o !== '' && o !== false && o !== true;
        }

        function trim (str) {
          if (typeof str === 'string') return $.trim(str);
          return str;
        }

        while (ii--) {
          p = opts_arr[ii].split(':');
          p = [p[0], p.slice(1).join(':')];

          if (/true/i.test(p[1])) p[1] = true;
          if (/false/i.test(p[1])) p[1] = false;
          if (isNumber(p[1])) {
            if (p[1].indexOf('.') === -1) {
              p[1] = parseInt(p[1], 10);
            } else {
              p[1] = parseFloat(p[1]);
            }
          }

          if (p.length === 2 && p[0].length > 0) {
            opts[trim(p[0])] = trim(p[1]);
          }
        }

        return opts;
      },

      // Description:
      //    Adds JS-recognizable media queries
      //
      // Arguments:
      //    Media (String): Key string for the media query to be stored as in
      //    Foundation.media_queries
      //
      //    Class (String): Class name for the generated <meta> tag
      register_media : function (media, media_class) {
        if(Foundation.media_queries[media] === undefined) {
          $('head').append('<meta class="' + media_class + '"/>');
          Foundation.media_queries[media] = removeQuotes($('.' + media_class).css('font-family'));
        }
      },

      // Description:
      //    Add custom CSS within a JS-defined media query
      //
      // Arguments:
      //    Rule (String): CSS rule to be appended to the document.
      //
      //    Media (String): Optional media query string for the CSS rule to be
      //    nested under.
      add_custom_rule : function (rule, media) {
        if (media === undefined && Foundation.stylesheet) {
          Foundation.stylesheet.insertRule(rule, Foundation.stylesheet.cssRules.length);
        } else {
          var query = Foundation.media_queries[media];

          if (query !== undefined) {
            Foundation.stylesheet.insertRule('@media ' +
              Foundation.media_queries[media] + '{ ' + rule + ' }');
          }
        }
      },

      // Description:
      //    Performs a callback function when an image is fully loaded
      //
      // Arguments:
      //    Image (jQuery Object): Image(s) to check if loaded.
      //
      //    Callback (Function): Function to execute when image is fully loaded.
      image_loaded : function (images, callback) {
        var self = this,
            unloaded = images.length;

        if (unloaded === 0) {
          callback(images);
        }

        images.each(function () {
          single_image_loaded(self.S(this), function () {
            unloaded -= 1;
            if (unloaded === 0) {
              callback(images);
            }
          });
        });
      },

      // Description:
      //    Returns a random, alphanumeric string
      //
      // Arguments:
      //    Length (Integer): Length of string to be generated. Defaults to random
      //    integer.
      //
      // Returns:
      //    Rand (String): Pseudo-random, alphanumeric string.
      random_str : function () {
        if (!this.fidx) this.fidx = 0;
        this.prefix = this.prefix || [(this.name || 'F'), (+new Date).toString(36)].join('-');

        return this.prefix + (this.fidx++).toString(36);
      },

      // Description:
      //    Helper for window.matchMedia
      //
      // Arguments:
      //    mq (String): Media query
      //
      // Returns:
      //    (Boolean): Whether the media query passes or not
      match : function (mq) {
        return window.matchMedia(mq).matches;
      },

      // Description:
      //    Helpers for checking Foundation default media queries with JS
      //
      // Returns:
      //    (Boolean): Whether the media query passes or not

      is_small_up : function () {
        return this.match(Foundation.media_queries.small);
      },

      is_medium_up : function () {
        return this.match(Foundation.media_queries.medium);
      },

      is_large_up : function () {
        return this.match(Foundation.media_queries.large);
      },

      is_xlarge_up : function () {
        return this.match(Foundation.media_queries.xlarge);
      },

      is_xxlarge_up : function () {
        return this.match(Foundation.media_queries.xxlarge);
      },

      is_small_only : function () {
        return !this.is_medium_up() && !this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
      },

      is_medium_only : function () {
        return this.is_medium_up() && !this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
      },

      is_large_only : function () {
        return this.is_medium_up() && this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
      },

      is_xlarge_only : function () {
        return this.is_medium_up() && this.is_large_up() && this.is_xlarge_up() && !this.is_xxlarge_up();
      },

      is_xxlarge_only : function () {
        return this.is_medium_up() && this.is_large_up() && this.is_xlarge_up() && this.is_xxlarge_up();
      }
    }
  };

  $.fn.foundation = function () {
    var args = Array.prototype.slice.call(arguments, 0);

    return this.each(function () {
      Foundation.init.apply(Foundation, [this].concat(args));
      return this;
    });
  };

}(jQuery, window, window.document));
;
;(function ($, window, document, undefined) {
  'use strict';

  var noop = function() {};

  var Orbit = function(el, settings) {
    // Don't reinitialize plugin
    if (el.hasClass(settings.slides_container_class)) {
      return this;
    }

    var self = this,
        container,
        slides_container = el,
        number_container,
        bullets_container,
        timer_container,
        idx = 0,
        animate,
        timer,
        locked = false,
        adjust_height_after = false;


    self.slides = function() {
      return slides_container.children(settings.slide_selector);
    };

    self.slides().first().addClass(settings.active_slide_class);

    self.update_slide_number = function(index) {
      if (settings.slide_number) {
        number_container.find('span:first').text(parseInt(index)+1);
        number_container.find('span:last').text(self.slides().length);
      }
      if (settings.bullets) {
        bullets_container.children().removeClass(settings.bullets_active_class);
        $(bullets_container.children().get(index)).addClass(settings.bullets_active_class);
      }
    };

    self.update_active_link = function(index) {
      var link = $('[data-orbit-link="'+self.slides().eq(index).attr('data-orbit-slide')+'"]');
      link.siblings().removeClass(settings.bullets_active_class);
      link.addClass(settings.bullets_active_class);
    };

    self.build_markup = function() {
      slides_container.wrap('<div class="'+settings.container_class+'"></div>');
      container = slides_container.parent();
      slides_container.addClass(settings.slides_container_class);

      if (settings.stack_on_small) {
        container.addClass(settings.stack_on_small_class);
      }

      if (settings.navigation_arrows) {
        container.append($('<a href="#"><span></span></a>').addClass(settings.prev_class));
        container.append($('<a href="#"><span></span></a>').addClass(settings.next_class));
      }

      if (settings.timer) {
        timer_container = $('<div>').addClass(settings.timer_container_class);
        timer_container.append('<span>');
        timer_container.append($('<div>').addClass(settings.timer_progress_class));
        timer_container.addClass(settings.timer_paused_class);
        container.append(timer_container);
      }

      if (settings.slide_number) {
        number_container = $('<div>').addClass(settings.slide_number_class);
        number_container.append('<span></span> ' + settings.slide_number_text + ' <span></span>');
        container.append(number_container);
      }

      if (settings.bullets) {
        bullets_container = $('<ol>').addClass(settings.bullets_container_class);
        container.append(bullets_container);
        bullets_container.wrap('<div class="orbit-bullets-container"></div>');
        self.slides().each(function(idx, el) {
          var bullet = $('<li>').attr('data-orbit-slide', idx).on('click', self.link_bullet);;
          bullets_container.append(bullet);
        });
      }

    };

    self._goto = function(next_idx, start_timer) {
      // if (locked) {return false;}
      if (next_idx === idx) {return false;}
      if (typeof timer === 'object') {timer.restart();}
      var slides = self.slides();

      var dir = 'next';
      locked = true;
      if (next_idx < idx) {dir = 'prev';}
      if (next_idx >= slides.length) {
        if (!settings.circular) return false;
        next_idx = 0;
      } else if (next_idx < 0) {
        if (!settings.circular) return false;
        next_idx = slides.length - 1;
      }

      var current = $(slides.get(idx));
      var next = $(slides.get(next_idx));

      current.css('zIndex', 2);
      current.removeClass(settings.active_slide_class);
      next.css('zIndex', 4).addClass(settings.active_slide_class);

      slides_container.trigger('before-slide-change.fndtn.orbit');
      settings.before_slide_change();
      self.update_active_link(next_idx);

      var callback = function() {
        var unlock = function() {
          idx = next_idx;
          locked = false;
          if (start_timer === true) {timer = self.create_timer(); timer.start();}
          self.update_slide_number(idx);
          slides_container.trigger('after-slide-change.fndtn.orbit',[{slide_number: idx, total_slides: slides.length}]);
          settings.after_slide_change(idx, slides.length);
        };
        if (slides_container.height() != next.height() && settings.variable_height) {
          slides_container.animate({'height': next.height()}, 250, 'linear', unlock);
        } else {
          unlock();
        }
      };

      if (slides.length === 1) {callback(); return false;}

      var start_animation = function() {
        if (dir === 'next') {animate.next(current, next, callback);}
        if (dir === 'prev') {animate.prev(current, next, callback);}
      };

      if (next.height() > slides_container.height() && settings.variable_height) {
        slides_container.animate({'height': next.height()}, 250, 'linear', start_animation);
      } else {
        start_animation();
      }
    };

    self.next = function(e) {
      e.stopImmediatePropagation();
      e.preventDefault();
      self._goto(idx + 1);
    };

    self.prev = function(e) {
      e.stopImmediatePropagation();
      e.preventDefault();
      self._goto(idx - 1);
    };

    self.link_custom = function(e) {
      e.preventDefault();
      var link = $(this).attr('data-orbit-link');
      if ((typeof link === 'string') && (link = $.trim(link)) != '') {
        var slide = container.find('[data-orbit-slide='+link+']');
        if (slide.index() != -1) {self._goto(slide.index());}
      }
    };

    self.link_bullet = function(e) {
      var index = $(this).attr('data-orbit-slide');
      if ((typeof index === 'string') && (index = $.trim(index)) != '') {
        if(isNaN(parseInt(index)))
        {
          var slide = container.find('[data-orbit-slide='+index+']');
          if (slide.index() != -1) {self._goto(slide.index() + 1);}
        }
        else
        {
          self._goto(parseInt(index));
        }
      }

    }

    self.timer_callback = function() {
      self._goto(idx + 1, true);
    }

    self.compute_dimensions = function() {
      var current = $(self.slides().get(idx));
      var h = current.height();
      if (!settings.variable_height) {
        self.slides().each(function(){
          if ($(this).height() > h) { h = $(this).height(); }
        });
      }
      slides_container.height(h);
    };

    self.create_timer = function() {
      var t = new Timer(
        container.find('.'+settings.timer_container_class),
        settings,
        self.timer_callback
      );
      return t;
    };

    self.stop_timer = function() {
      if (typeof timer === 'object') timer.stop();
    };

    self.toggle_timer = function() {
      var t = container.find('.'+settings.timer_container_class);
      if (t.hasClass(settings.timer_paused_class)) {
        if (typeof timer === 'undefined') {timer = self.create_timer();}
        timer.start();
      }
      else {
        if (typeof timer === 'object') {timer.stop();}
      }
    };

    self.init = function() {
      self.build_markup();
      if (settings.timer) {
        timer = self.create_timer();
        Foundation.utils.image_loaded(this.slides().children('img'), timer.start);
      }
      animate = new FadeAnimation(settings, slides_container);
      if (settings.animation === 'slide')
        animate = new SlideAnimation(settings, slides_container);

      container.on('click', '.'+settings.next_class, self.next);
      container.on('click', '.'+settings.prev_class, self.prev);

      if (settings.next_on_click) {
        container.on('click', '.'+settings.slides_container_class+' [data-orbit-slide]', self.link_bullet);
      }

      container.on('click', self.toggle_timer);
      if (settings.swipe) {
        container.on('touchstart.fndtn.orbit', function(e) {
          if (!e.touches) {e = e.originalEvent;}
          var data = {
            start_page_x: e.touches[0].pageX,
            start_page_y: e.touches[0].pageY,
            start_time: (new Date()).getTime(),
            delta_x: 0,
            is_scrolling: undefined
          };
          container.data('swipe-transition', data);
          e.stopPropagation();
        })
        .on('touchmove.fndtn.orbit', function(e) {
          if (!e.touches) { e = e.originalEvent; }
          // Ignore pinch/zoom events
          if(e.touches.length > 1 || e.scale && e.scale !== 1) return;

          var data = container.data('swipe-transition');
          if (typeof data === 'undefined') {data = {};}

          data.delta_x = e.touches[0].pageX - data.start_page_x;

          if ( typeof data.is_scrolling === 'undefined') {
            data.is_scrolling = !!( data.is_scrolling || Math.abs(data.delta_x) < Math.abs(e.touches[0].pageY - data.start_page_y) );
          }

          if (!data.is_scrolling && !data.active) {
            e.preventDefault();
            var direction = (data.delta_x < 0) ? (idx+1) : (idx-1);
            data.active = true;
            self._goto(direction);
          }
        })
        .on('touchend.fndtn.orbit', function(e) {
          container.data('swipe-transition', {});
          e.stopPropagation();
        })
      }
      container.on('mouseenter.fndtn.orbit', function(e) {
        if (settings.timer && settings.pause_on_hover) {
          self.stop_timer();
        }
      })
      .on('mouseleave.fndtn.orbit', function(e) {
        if (settings.timer && settings.resume_on_mouseout) {
          timer.start();
        }
      });

      $(document).on('click', '[data-orbit-link]', self.link_custom);
      $(window).on('load resize', self.compute_dimensions);
      Foundation.utils.image_loaded(this.slides().children('img'), self.compute_dimensions);
      Foundation.utils.image_loaded(this.slides().children('img'), function() {
        container.prev('.'+settings.preloader_class).css('display', 'none');
        self.update_slide_number(0);
        self.update_active_link(0);
        slides_container.trigger('ready.fndtn.orbit');
      });
    };

    self.init();
  };

  var Timer = function(el, settings, callback) {
    var self = this,
        duration = settings.timer_speed,
        progress = el.find('.'+settings.timer_progress_class),
        start,
        timeout,
        left = -1;

    this.update_progress = function(w) {
      var new_progress = progress.clone();
      new_progress.attr('style', '');
      new_progress.css('width', w+'%');
      progress.replaceWith(new_progress);
      progress = new_progress;
    };

    this.restart = function() {
      clearTimeout(timeout);
      el.addClass(settings.timer_paused_class);
      left = -1;
      self.update_progress(0);
    };

    this.start = function() {
      if (!el.hasClass(settings.timer_paused_class)) {return true;}
      left = (left === -1) ? duration : left;
      el.removeClass(settings.timer_paused_class);
      start = new Date().getTime();
      progress.animate({'width': '100%'}, left, 'linear');
      timeout = setTimeout(function() {
        self.restart();
        callback();
      }, left);
      el.trigger('timer-started.fndtn.orbit')
    };

    this.stop = function() {
      if (el.hasClass(settings.timer_paused_class)) {return true;}
      clearTimeout(timeout);
      el.addClass(settings.timer_paused_class);
      var end = new Date().getTime();
      left = left - (end - start);
      var w = 100 - ((left / duration) * 100);
      self.update_progress(w);
      el.trigger('timer-stopped.fndtn.orbit');
    };
  };

  var SlideAnimation = function(settings, container) {
    var duration = settings.animation_speed;
    var is_rtl = ($('html[dir=rtl]').length === 1);
    var margin = is_rtl ? 'marginRight' : 'marginLeft';
    var animMargin = {};
    animMargin[margin] = '0%';

    this.next = function(current, next, callback) {
      current.animate({marginLeft:'-100%'}, duration);
      next.animate(animMargin, duration, function() {
        current.css(margin, '100%');
        callback();
      });
    };

    this.prev = function(current, prev, callback) {
      current.animate({marginLeft:'100%'}, duration);
      prev.css(margin, '-100%');
      prev.animate(animMargin, duration, function() {
        current.css(margin, '100%');
        callback();
      });
    };
  };

  var FadeAnimation = function(settings, container) {
    var duration = settings.animation_speed;
    var is_rtl = ($('html[dir=rtl]').length === 1);
    var margin = is_rtl ? 'marginRight' : 'marginLeft';

    this.next = function(current, next, callback) {
      next.css({'margin':'0%', 'opacity':'0.01'});
      next.animate({'opacity':'1'}, duration, 'linear', function() {
        current.css('margin', '100%');
        callback();
      });
    };

    this.prev = function(current, prev, callback) {
      prev.css({'margin':'0%', 'opacity':'0.01'});
      prev.animate({'opacity':'1'}, duration, 'linear', function() {
        current.css('margin', '100%');
        callback();
      });
    };
  };


  Foundation.libs = Foundation.libs || {};

  Foundation.libs.orbit = {
    name: 'orbit',

    version: '5.5.0',

    settings: {
      animation: 'slide',
      timer_speed: 10000,
      pause_on_hover: true,
      resume_on_mouseout: false,
      next_on_click: true,
      animation_speed: 500,
      stack_on_small: false,
      navigation_arrows: true,
      slide_number: true,
      slide_number_text: 'of',
      container_class: 'orbit-container',
      stack_on_small_class: 'orbit-stack-on-small',
      next_class: 'orbit-next',
      prev_class: 'orbit-prev',
      timer_container_class: 'orbit-timer',
      timer_paused_class: 'paused',
      timer_progress_class: 'orbit-progress',
      slides_container_class: 'orbit-slides-container',
      preloader_class: 'preloader',
      slide_selector: '*',
      bullets_container_class: 'orbit-bullets',
      bullets_active_class: 'active',
      slide_number_class: 'orbit-slide-number',
      caption_class: 'orbit-caption',
      active_slide_class: 'active',
      orbit_transition_class: 'orbit-transitioning',
      bullets: true,
      circular: true,
      timer: true,
      variable_height: false,
      swipe: true,
      before_slide_change: noop,
      after_slide_change: noop
    },

    init : function (scope, method, options) {
      var self = this;
      this.bindings(method, options);
    },

    events : function (instance) {
      var orbit_instance = new Orbit(this.S(instance), this.S(instance).data('orbit-init'));
      this.S(instance).data(this.name + '-instance', orbit_instance);
    },

    reflow : function () {
      var self = this;

      if (self.S(self.scope).is('[data-orbit]')) {
        var $el = self.S(self.scope);
        var instance = $el.data(self.name + '-instance');
        instance.compute_dimensions();
      } else {
        self.S('[data-orbit]', self.scope).each(function(idx, el) {
          var $el = self.S(el);
          var opts = self.data_options($el);
          var instance = $el.data(self.name + '-instance');
          instance.compute_dimensions();
        });
      }
    }
  };


}(jQuery, window, window.document));
;
;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.reveal = {
    name : 'reveal',

    version : '5.5.0',

    locked : false,

    settings : {
      animation: 'fadeAndPop',
      animation_speed: 250,
      close_on_background_click: true,
      close_on_esc: true,
      dismiss_modal_class: 'close-reveal-modal',
      bg_class: 'reveal-modal-bg',
      bg_root_element: 'body',
      root_element: 'body',
      open: function(){},
      opened: function(){},
      close: function(){},
      closed: function(){},
      bg : $('.reveal-modal-bg'),
      css : {
        open : {
          'opacity': 0,
          'visibility': 'visible',
          'display' : 'block'
        },
        close : {
          'opacity': 1,
          'visibility': 'hidden',
          'display': 'none'
        }
      }
    },

    init : function (scope, method, options) {
      $.extend(true, this.settings, method, options);
      this.bindings(method, options);
    },

    events : function (scope) {
      var self = this,
          S = self.S;

      S(this.scope)
        .off('.reveal')
        .on('click.fndtn.reveal', '[' + this.add_namespace('data-reveal-id') + ']:not([disabled])', function (e) {
          e.preventDefault();
        
          if (!self.locked) {
            var element = S(this),
                ajax = element.data(self.data_attr('reveal-ajax'));

            self.locked = true;

            if (typeof ajax === 'undefined') {
              self.open.call(self, element);
            } else {
              var url = ajax === true ? element.attr('href') : ajax;

              self.open.call(self, element, {url: url});
            }
          }
        });

      S(document)
        .on('click.fndtn.reveal', this.close_targets(), function (e) {

          e.preventDefault();

          if (!self.locked) {
            var settings = S('[' + self.attr_name() + '].open').data(self.attr_name(true) + '-init') || self.settings,
                bg_clicked = S(e.target)[0] === S('.' + settings.bg_class)[0];

            if (bg_clicked) {
              if (settings.close_on_background_click) {
                e.stopPropagation();
              } else {
                return;
              }
            }

            self.locked = true;
            self.close.call(self, bg_clicked ? S('[' + self.attr_name() + '].open') : S(this).closest('[' + self.attr_name() + ']'));
          }
        });

      if(S('[' + self.attr_name() + ']', this.scope).length > 0) {
        S(this.scope)
          // .off('.reveal')
          .on('open.fndtn.reveal', this.settings.open)
          .on('opened.fndtn.reveal', this.settings.opened)
          .on('opened.fndtn.reveal', this.open_video)
          .on('close.fndtn.reveal', this.settings.close)
          .on('closed.fndtn.reveal', this.settings.closed)
          .on('closed.fndtn.reveal', this.close_video);
      } else {
        S(this.scope)
          // .off('.reveal')
          .on('open.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.open)
          .on('opened.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.opened)
          .on('opened.fndtn.reveal', '[' + self.attr_name() + ']', this.open_video)
          .on('close.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.close)
          .on('closed.fndtn.reveal', '[' + self.attr_name() + ']', this.settings.closed)
          .on('closed.fndtn.reveal', '[' + self.attr_name() + ']', this.close_video);
      }

      return true;
    },

    // PATCH #3: turning on key up capture only when a reveal window is open
    key_up_on : function (scope) {
      var self = this;

      // PATCH #1: fixing multiple keyup event trigger from single key press
      self.S('body').off('keyup.fndtn.reveal').on('keyup.fndtn.reveal', function ( event ) {
        var open_modal = self.S('[' + self.attr_name() + '].open'),
            settings = open_modal.data(self.attr_name(true) + '-init') || self.settings ;
        // PATCH #2: making sure that the close event can be called only while unlocked,
        //           so that multiple keyup.fndtn.reveal events don't prevent clean closing of the reveal window.
        if ( settings && event.which === 27  && settings.close_on_esc && !self.locked) { // 27 is the keycode for the Escape key
          self.close.call(self, open_modal);
        }
      });

      return true;
    },

    // PATCH #3: turning on key up capture only when a reveal window is open
    key_up_off : function (scope) {
      this.S('body').off('keyup.fndtn.reveal');
      return true;
    },


    open : function (target, ajax_settings) {
      var self = this,
          modal;

      if (target) {
        if (typeof target.selector !== 'undefined') {
          // Find the named node; only use the first one found, since the rest of the code assumes there's only one node
          modal = self.S('#' + target.data(self.data_attr('reveal-id'))).first();
        } else {
          modal = self.S(this.scope);

          ajax_settings = target;
        }
      } else {
        modal = self.S(this.scope);
      }

      var settings = modal.data(self.attr_name(true) + '-init');
      settings = settings || this.settings;


      if (modal.hasClass('open') && target.attr('data-reveal-id') == modal.attr('id')) {
        return self.close(modal);
      }

      if (!modal.hasClass('open')) {
        var open_modal = self.S('[' + self.attr_name() + '].open');

        if (typeof modal.data('css-top') === 'undefined') {
          modal.data('css-top', parseInt(modal.css('top'), 10))
            .data('offset', this.cache_offset(modal));
        }

        this.key_up_on(modal);    // PATCH #3: turning on key up capture only when a reveal window is open
        modal.trigger('open').trigger('open.fndtn.reveal');

        if (open_modal.length < 1) {
          this.toggle_bg(modal, true);
        }

        if (typeof ajax_settings === 'string') {
          ajax_settings = {
            url: ajax_settings
          };
        }

        if (typeof ajax_settings === 'undefined' || !ajax_settings.url) {
          if (open_modal.length > 0) {
            this.hide(open_modal, settings.css.close);
          }

          this.show(modal, settings.css.open);
        } else {
          var old_success = typeof ajax_settings.success !== 'undefined' ? ajax_settings.success : null;

          $.extend(ajax_settings, {
            success: function (data, textStatus, jqXHR) {
              if ( $.isFunction(old_success) ) {
                var result = old_success(data, textStatus, jqXHR);
                if (typeof result == 'string') data = result;
              }

              modal.html(data);
              self.S(modal).foundation('section', 'reflow');
              self.S(modal).children().foundation();

              if (open_modal.length > 0) {
                self.hide(open_modal, settings.css.close);
              }
              self.show(modal, settings.css.open);
            }
          });

          $.ajax(ajax_settings);
        }
      }
      self.S(window).trigger('resize');
    },

    close : function (modal) {
      var modal = modal && modal.length ? modal : this.S(this.scope),
          open_modals = this.S('[' + this.attr_name() + '].open'),
          settings = modal.data(this.attr_name(true) + '-init') || this.settings;

      if (open_modals.length > 0) {
        this.locked = true;
        this.key_up_off(modal);   // PATCH #3: turning on key up capture only when a reveal window is open
        modal.trigger('close').trigger('close.fndtn.reveal');
        this.toggle_bg(modal, false);
        this.hide(open_modals, settings.css.close, settings);
      }
    },

    close_targets : function () {
      var base = '.' + this.settings.dismiss_modal_class;

      if (this.settings.close_on_background_click) {
        return base + ', .' + this.settings.bg_class;
      }

      return base;
    },

    toggle_bg : function (el, modal, state) {
      var settings = el.data(this.attr_name(true) + '-init') || this.settings,
            bg_root_element = settings.bg_root_element; // Adding option to specify the background root element fixes scrolling issue
      
      if (this.S('.' + this.settings.bg_class).length === 0) {
        this.settings.bg = $('<div />', {'class': this.settings.bg_class})
          .appendTo(bg_root_element).hide();
      }

      var visible = this.settings.bg.filter(':visible').length > 0;
      if ( state != visible ) {
        if ( state == undefined ? visible : !state ) {
          this.hide(this.settings.bg);
        } else {
          this.show(this.settings.bg);
        }
      }
    },

    show : function (el, css) {
      // is modal
      if (css) {
        var settings = el.data(this.attr_name(true) + '-init') || this.settings,
            root_element = settings.root_element;

        if (el.parent(root_element).length === 0) {
          var placeholder = el.wrap('<div style="display: none;" />').parent();

          el.on('closed.fndtn.reveal.wrapped', function() {
            el.detach().appendTo(placeholder);
            el.unwrap().unbind('closed.fndtn.reveal.wrapped');
          });

          el.detach().appendTo(root_element);
        }

        var animData = getAnimationData(settings.animation);
        if (!animData.animate) {
          this.locked = false;
        }
        if (animData.pop) {
          css.top = $(root_element).scrollTop() - el.data('offset') + 'px'; //adding root_element instead of window for scrolling offset if modal trigger is below the fold
          var end_css = {
            top: $(root_element).scrollTop() + el.data('css-top') + 'px', //adding root_element instead of window for scrolling offset if modal trigger is below the fold
            opacity: 1
          };

          return setTimeout(function () {
            return el
              .css(css)
              .animate(end_css, settings.animation_speed, 'linear', function () {
                this.locked = false;
                el.trigger('opened').trigger('opened.fndtn.reveal');
              }.bind(this))
              .addClass('open');
          }.bind(this), settings.animation_speed / 2);
        }

        if (animData.fade) {
          css.top = $(root_element).scrollTop() + el.data('css-top') + 'px'; //adding root_element instead of window for scrolling offset if modal trigger is below the fold
          var end_css = {opacity: 1};

          return setTimeout(function () {
            return el
              .css(css)
              .animate(end_css, settings.animation_speed, 'linear', function () {
                this.locked = false;
                el.trigger('opened').trigger('opened.fndtn.reveal');
              }.bind(this))
              .addClass('open');
          }.bind(this), settings.animation_speed / 2);
        }

        return el.css(css).show().css({opacity: 1}).addClass('open').trigger('opened').trigger('opened.fndtn.reveal');
      }

      var settings = this.settings;

      // should we animate the background?
      if (getAnimationData(settings.animation).fade) {
        return el.fadeIn(settings.animation_speed / 2);
      }

      this.locked = false;

      return el.show();
    },

    hide : function (el, css) {
      // is modal
      if (css) {
        var settings = el.data(this.attr_name(true) + '-init') || this.settings,
            root_element = settings.root_element;

        var animData = getAnimationData(settings.animation);
        if (!animData.animate) {
          this.locked = false;
        }
        if (animData.pop) {
          var end_css = {
            top: - $(root_element).scrollTop() - el.data('offset') + 'px', //adding root_element instead of window for scrolling offset if modal trigger is below the fold
            opacity: 0
          };

          return setTimeout(function () {
            return el
              .animate(end_css, settings.animation_speed, 'linear', function () {
                this.locked = false;
                el.css(css).trigger('closed').trigger('closed.fndtn.reveal');
              }.bind(this))
              .removeClass('open');
          }.bind(this), settings.animation_speed / 2);
        }

        if (animData.fade) {
          var end_css = {opacity: 0};

          return setTimeout(function () {
            return el
              .animate(end_css, settings.animation_speed, 'linear', function () {
                this.locked = false;
                el.css(css).trigger('closed').trigger('closed.fndtn.reveal');
              }.bind(this))
              .removeClass('open');
          }.bind(this), settings.animation_speed / 2);
        }

        return el.hide().css(css).removeClass('open').trigger('closed').trigger('closed.fndtn.reveal');
      }

      var settings = this.settings;

      // should we animate the background?
      if (getAnimationData(settings.animation).fade) {
        return el.fadeOut(settings.animation_speed / 2);
      }

      return el.hide();
    },

    close_video : function (e) {
      var video = $('.flex-video', e.target),
          iframe = $('iframe', video);

      if (iframe.length > 0) {
        iframe.attr('data-src', iframe[0].src);
        iframe.attr('src', iframe.attr('src'));
        video.hide();
      }
    },

    open_video : function (e) {
      var video = $('.flex-video', e.target),
          iframe = video.find('iframe');

      if (iframe.length > 0) {
        var data_src = iframe.attr('data-src');
        if (typeof data_src === 'string') {
          iframe[0].src = iframe.attr('data-src');
        } else {
          var src = iframe[0].src;
          iframe[0].src = undefined;
          iframe[0].src = src;
        }
        video.show();
      }
    },

    data_attr: function (str) {
      if (this.namespace.length > 0) {
        return this.namespace + '-' + str;
      }

      return str;
    },

    cache_offset : function (modal) {
      var offset = modal.show().height() + parseInt(modal.css('top'), 10);

      modal.hide();

      return offset;
    },

    off : function () {
      $(this.scope).off('.fndtn.reveal');
    },

    reflow : function () {}
  };

  /*
   * getAnimationData('popAndFade') // {animate: true,  pop: true,  fade: true}
   * getAnimationData('fade')       // {animate: true,  pop: false, fade: true}
   * getAnimationData('pop')        // {animate: true,  pop: true,  fade: false}
   * getAnimationData('foo')        // {animate: false, pop: false, fade: false}
   * getAnimationData(null)         // {animate: false, pop: false, fade: false}
   */
  function getAnimationData(str) {
    var fade = /fade/i.test(str);
    var pop = /pop/i.test(str);
    return {
      animate: fade || pop,
      pop: pop,
      fade: fade
    };
  }
}(jQuery, window, window.document));
;
;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.equalizer = {
    name : 'equalizer',

    version : '5.5.0',

    settings : {
      use_tallest: true,
      before_height_change: $.noop,
      after_height_change: $.noop,
      equalize_on_stack: false
    },

    init : function (scope, method, options) {
      Foundation.inherit(this, 'image_loaded');
      this.bindings(method, options);
      this.reflow();
    },

    events : function () {
      this.S(window).off('.equalizer').on('resize.fndtn.equalizer', function(e){
        this.reflow();
      }.bind(this));
    },

    equalize: function(equalizer) {
      var isStacked = false,
          vals = equalizer.find('[' + this.attr_name() + '-watch]:visible'),
          settings = equalizer.data(this.attr_name(true)+'-init');

      if (vals.length === 0) return;
      var firstTopOffset = vals.first().offset().top;
      settings.before_height_change();
      equalizer.trigger('before-height-change').trigger('before-height-change.fndth.equalizer');
      vals.height('inherit');
      vals.each(function(){
        var el = $(this);
        if (el.offset().top !== firstTopOffset) {
          isStacked = true;
        }
      });

      if (settings.equalize_on_stack === false) {
        if (isStacked) return;
      };

      var heights = vals.map(function(){ return $(this).outerHeight(false) }).get();

      if (settings.use_tallest) {
        var max = Math.max.apply(null, heights);
        vals.css('height', max);
      } else {
        var min = Math.min.apply(null, heights);
        vals.css('height', min);
      }
      settings.after_height_change();
      equalizer.trigger('after-height-change').trigger('after-height-change.fndtn.equalizer');
    },

    reflow : function () {
      var self = this;

      this.S('[' + this.attr_name() + ']', this.scope).each(function(){
        var $eq_target = $(this);
        self.image_loaded(self.S('img', this), function(){
          self.equalize($eq_target)
        });
      });
    }
  };
})(jQuery, window, window.document);
;
;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.accordion = {
    name : 'accordion',

    version : '5.5.0',

    settings : {
      content_class: 'content',
      active_class: 'active',
      multi_expand: false,
      toggleable: true,
      callback : function () {}
    },

    init : function (scope, method, options) {
      this.bindings(method, options);
    },

    events : function () {
      var self = this;
      var S = this.S;
      S(this.scope)
      .off('.fndtn.accordion')
      .on('click.fndtn.accordion', '[' + this.attr_name() + '] > .accordion-navigation > a', function (e) {
        var accordion = S(this).closest('[' + self.attr_name() + ']'),
            groupSelector = self.attr_name() + '=' + accordion.attr(self.attr_name()),
            settings = accordion.data(self.attr_name(true) + '-init') || self.settings,
            target = S('#' + this.href.split('#')[1]),
            aunts = $('> .accordion-navigation', accordion),
            siblings = aunts.children('.'+settings.content_class),
            active_content = siblings.filter('.' + settings.active_class);

        e.preventDefault();

        if (accordion.attr(self.attr_name())) {
          siblings = siblings.add('[' + groupSelector + '] dd > '+'.'+settings.content_class);
          aunts = aunts.add('[' + groupSelector + '] .accordion-navigation');
        }

        if (settings.toggleable && target.is(active_content)) {
          target.parent('.accordion-navigation').toggleClass(settings.active_class, false);
          target.toggleClass(settings.active_class, false);
          settings.callback(target);
          target.triggerHandler('toggled', [accordion]);
          accordion.triggerHandler('toggled', [target]);
          return;
        }

        if (!settings.multi_expand) {
          siblings.removeClass(settings.active_class);
          aunts.removeClass(settings.active_class);
        }

        target.addClass(settings.active_class).parent().addClass(settings.active_class);
        settings.callback(target);
        target.triggerHandler('toggled', [accordion]);
        accordion.triggerHandler('toggled', [target]);
      });
    },

    off : function () {},

    reflow : function () {}
  };
}(jQuery, window, window.document));
;
