/*
 * jQuery validation plug-in 1.5.5
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6403 2009-06-17 14:27:16Z joern.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;
		}
		
		validator = new $.validator( options, this[0] );
		$.data(this[0], 'validator', validator); 
		
		if ( validator.settings.onsubmit ) {
		
			// allow suppresing validation by adding a cancel class to the submit button
			this.find("input, button").filter(".cancel").click(function() {
				validator.cancelSubmit = true;
			});
			
			// when a submitHandler is used, capture the submitting button
			if (validator.settings.submitHandler) {
				this.find("input, button").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( {}, $.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: [],
		ignoreTitle: false,
		onfocusin: function(element) {
			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.errorsFor(element).hide();
			}
		},
		onfocusout: function(element) {
			if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
				this.element(element);
			}
		},
		onkeyup: function(element) {
			if ( element.name in this.submitted || element == this.lastElement ) {
				this.element(element);
			}
		},
		onclick: function(element) {
			if ( element.name in this.submitted )
				this.element(element);
		},
		highlight: function( element, errorClass, validClass ) {
			$(element).addClass(errorClass).removeClass(validClass);
		},
		unhighlight: function( element, errorClass, validClass ) {
			$(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).",
		dateDE: "Bitte geben Sie ein gültiges Datum ein.",
		number: "Please enter a valid number.",
		numberDE: "Bitte geben Sie eine Nummer ein.",
		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");
				validator.settings["on" + event.type] && validator.settings["on" + event.type].call(validator, this[0] );
			}
			$(this.currentForm)
				.delegate("focusin focusout keyup", ":text, :password, :file, select, textarea", delegate)
				.delegate("click", ":radio, :checkbox", 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.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.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();
				} 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)
			// workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
			return $([]).add(this.currentForm.elements)
			.filter(":input")
			.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.formSubmitted = false;
			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.clean( element );
			
			// if radio/checkbox, validate first element in group instead
			if (this.checkable(element)) {
				element = this.findByName( element.name )[0];
			}
			
			var rules = $(element).rules();
			var dependencyMismatch = false;
			for( 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");
					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 );
			if ( typeof message == "function" ) 
				message = message.call(this, rule.parameters, element);
			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().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) {
			return this.errors().filter("[for='" + this.idOrName(element) + "']");
		},
		
		idOrName: function(element) {
			return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
		},

		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();
			} else if (!valid && this.pendingRequest == 0 && this.formSubmitted) {
				$(this.currentForm).triggerHandler("invalid-form", [this]);
			}
		},
		
		previousValue: function(element) {
			return $.data(element, "previousValue") || $.data(element, "previousValue", previous = {
				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 (method in $.validator.methods) {
			var value = $element.attr(method);
			if (value) {
				rules[method] = value;
			}
		}
		
		// 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 || $.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':
				var options = $("option:selected", element);
				return options.length > 0 && ( element.type == "select-multiple" || ($.browser.msie && !(options[0].attributes['value'].specified) ? options[0].text : options[0].value).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] = {};
			this.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;
			
			param = typeof param == "string" && {url:param} || param; 
			
			if ( previous.old !== value ) {
				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) {
						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 = {};
							errors[element.name] = previous.message = response || validator.defaultMessage( element, "remote" );
							validator.showErrors(errors);
						}
						previous.valid = valid;
						validator.stopRequest(element, valid);
					}
				}, param));
				return "pending";
			} else if( this.pending[element.name] ) {
				return "pending";
			}
			return previous.valid;
		},

		// 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/dateDE
		dateDE: function(value, element) {
			return this.optional(element) || /^\d\d?\.\d\d?\.\d\d\d?\d?$/.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/numberDE
		numberDE: 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 digits and dashes
			if (/[^0-9-]+/.test(value))
				return false;
			var nCheck = 0,
				nDigit = 0,
				bEven = false;

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

			for (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) {
			return value == $(param).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 ajax = $.ajax;
	var pendingRequests = {};
	$.ajax = function(settings) {
		// create settings for compatibility with ajaxSetup
		settings = $.extend(settings, $.extend({}, $.ajaxSettings, settings));
		var port = settings.port;
		if (settings.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 

// provides triggerEvent(type: String, target: Element) to trigger delegated events
;(function($) {
	$.each({
		focus: 'focusin',
		blur: 'focusout'	
	}, function( original, fix ){
		$.event.special[fix] = {
			setup:function() {
				if ( $.browser.msie ) return false;
				this.addEventListener( original, $.event.special[fix].handler, true );
			},
			teardown:function() {
				if ( $.browser.msie ) return false;
				this.removeEventListener( original,
				$.event.special[fix].handler, true );
			},
			handler: function(e) {
				arguments[0] = $.event.fix(e);
				arguments[0].type = fix;
				return $.event.handle.apply(this, arguments);
			}
		};
	});
	$.extend($.fn, {
		delegate: function(type, delegate, handler) {
			return this.bind(type, function(event) {
				var target = $(event.target);
				if (target.is(delegate)) {
					return handler.apply(target, arguments);
				}
			});
		},
		triggerEvent: function(type, target) {
			return this.triggerHandler(type, [$.event.fix({ type: type, target: target })]);
		}
	})
})(jQuery);


/*
 * Crypto-JS v1.1.0
 * http://code.google.com/p/crypto-js/
 * Copyright (c) 2009, Jeff Mott. All rights reserved.
 * http://code.google.com/p/crypto-js/wiki/License
 */
(function(){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";window.Crypto={};var a=Crypto.util={rotl:function(d,c){return(d<<c)|(d>>>(32-c))},rotr:function(d,c){return(d<<(32-c))|(d>>>c)},endian:function(d){if(d.constructor==Number){return a.rotl(d,8)&16711935|a.rotl(d,24)&4278255360}for(var c=0;c<d.length;c++){d[c]=a.endian(d[c])}return d},randomBytes:function(d){for(var c=[];d>0;d--){c.push(Math.floor(Math.random()*256))}return c},stringToBytes:function(e){var c=[];for(var d=0;d<e.length;d++){c.push(e.charCodeAt(d))}return c},bytesToString:function(c){var e=[];for(var d=0;d<c.length;d++){e.push(String.fromCharCode(c[d]))}return e.join("")},stringToWords:function(f){var e=[];for(var g=0,d=0;g<f.length;g++,d+=8){e[d>>>5]|=f.charCodeAt(g)<<(24-d%32)}return e},bytesToWords:function(d){var f=[];for(var e=0,c=0;e<d.length;e++,c+=8){f[c>>>5]|=d[e]<<(24-c%32)}return f},wordsToBytes:function(e){var d=[];for(var c=0;c<e.length*32;c+=8){d.push((e[c>>>5]>>>(24-c%32))&255)}return d},bytesToHex:function(c){var e=[];for(var d=0;d<c.length;d++){e.push((c[d]>>>4).toString(16));e.push((c[d]&15).toString(16))}return e.join("")},hexToBytes:function(e){var d=[];for(var f=0;f<e.length;f+=2){d.push(parseInt(e.substr(f,2),16))}return d},bytesToBase64:function(d){if(typeof btoa=="function"){return btoa(a.bytesToString(d))}var c=[],f;for(var e=0;e<d.length;e++){switch(e%3){case 0:c.push(b.charAt(d[e]>>>2));f=(d[e]&3)<<4;break;case 1:c.push(b.charAt(f|(d[e]>>>4)));f=(d[e]&15)<<2;break;case 2:c.push(b.charAt(f|(d[e]>>>6)));c.push(b.charAt(d[e]&63));f=-1}}if(f!=undefined&&f!=-1){c.push(b.charAt(f))}while(c.length%4!=0){c.push("=")}return c.join("")},base64ToBytes:function(d){if(typeof atob=="function"){return a.stringToBytes(atob(d))}d=d.replace(/[^A-Z0-9+\/]/ig,"");var c=[];for(var e=0;e<d.length;e++){switch(e%4){case 1:c.push((b.indexOf(d.charAt(e-1))<<2)|(b.indexOf(d.charAt(e))>>>4));break;case 2:c.push(((b.indexOf(d.charAt(e-1))&15)<<4)|(b.indexOf(d.charAt(e))>>>2));break;case 3:c.push(((b.indexOf(d.charAt(e-1))&3)<<6)|(b.indexOf(d.charAt(e))));break}}return c}};Crypto.mode={}})();(function(){var a=Crypto.util;var b=Crypto.MD5=function(e,c){var d=a.wordsToBytes(b._md5(e));return c&&c.asBytes?d:c&&c.asString?a.bytesToString(d):a.bytesToHex(d)};b._md5=function(s){var g=a.stringToWords(s),h=s.length*8,q=1732584193,p=-271733879,o=-1732584194,n=271733878;for(var j=0;j<g.length;j++){g[j]=((g[j]<<8)|(g[j]>>>24))&16711935|((g[j]<<24)|(g[j]>>>8))&4278255360}g[h>>>5]|=128<<(h%32);g[(((h+64)>>>9)<<4)+14]=h;for(var j=0;j<g.length;j+=16){var e=q,k=p,f=o,r=n;q=b._ff(q,p,o,n,g[j+0],7,-680876936);n=b._ff(n,q,p,o,g[j+1],12,-389564586);o=b._ff(o,n,q,p,g[j+2],17,606105819);p=b._ff(p,o,n,q,g[j+3],22,-1044525330);q=b._ff(q,p,o,n,g[j+4],7,-176418897);n=b._ff(n,q,p,o,g[j+5],12,1200080426);o=b._ff(o,n,q,p,g[j+6],17,-1473231341);p=b._ff(p,o,n,q,g[j+7],22,-45705983);q=b._ff(q,p,o,n,g[j+8],7,1770035416);n=b._ff(n,q,p,o,g[j+9],12,-1958414417);o=b._ff(o,n,q,p,g[j+10],17,-42063);p=b._ff(p,o,n,q,g[j+11],22,-1990404162);q=b._ff(q,p,o,n,g[j+12],7,1804603682);n=b._ff(n,q,p,o,g[j+13],12,-40341101);o=b._ff(o,n,q,p,g[j+14],17,-1502002290);p=b._ff(p,o,n,q,g[j+15],22,1236535329);q=b._gg(q,p,o,n,g[j+1],5,-165796510);n=b._gg(n,q,p,o,g[j+6],9,-1069501632);o=b._gg(o,n,q,p,g[j+11],14,643717713);p=b._gg(p,o,n,q,g[j+0],20,-373897302);q=b._gg(q,p,o,n,g[j+5],5,-701558691);n=b._gg(n,q,p,o,g[j+10],9,38016083);o=b._gg(o,n,q,p,g[j+15],14,-660478335);p=b._gg(p,o,n,q,g[j+4],20,-405537848);q=b._gg(q,p,o,n,g[j+9],5,568446438);n=b._gg(n,q,p,o,g[j+14],9,-1019803690);o=b._gg(o,n,q,p,g[j+3],14,-187363961);p=b._gg(p,o,n,q,g[j+8],20,1163531501);q=b._gg(q,p,o,n,g[j+13],5,-1444681467);n=b._gg(n,q,p,o,g[j+2],9,-51403784);o=b._gg(o,n,q,p,g[j+7],14,1735328473);p=b._gg(p,o,n,q,g[j+12],20,-1926607734);q=b._hh(q,p,o,n,g[j+5],4,-378558);n=b._hh(n,q,p,o,g[j+8],11,-2022574463);o=b._hh(o,n,q,p,g[j+11],16,1839030562);p=b._hh(p,o,n,q,g[j+14],23,-35309556);q=b._hh(q,p,o,n,g[j+1],4,-1530992060);n=b._hh(n,q,p,o,g[j+4],11,1272893353);o=b._hh(o,n,q,p,g[j+7],16,-155497632);p=b._hh(p,o,n,q,g[j+10],23,-1094730640);q=b._hh(q,p,o,n,g[j+13],4,681279174);n=b._hh(n,q,p,o,g[j+0],11,-358537222);o=b._hh(o,n,q,p,g[j+3],16,-722521979);p=b._hh(p,o,n,q,g[j+6],23,76029189);q=b._hh(q,p,o,n,g[j+9],4,-640364487);n=b._hh(n,q,p,o,g[j+12],11,-421815835);o=b._hh(o,n,q,p,g[j+15],16,530742520);p=b._hh(p,o,n,q,g[j+2],23,-995338651);q=b._ii(q,p,o,n,g[j+0],6,-198630844);n=b._ii(n,q,p,o,g[j+7],10,1126891415);o=b._ii(o,n,q,p,g[j+14],15,-1416354905);p=b._ii(p,o,n,q,g[j+5],21,-57434055);q=b._ii(q,p,o,n,g[j+12],6,1700485571);n=b._ii(n,q,p,o,g[j+3],10,-1894986606);o=b._ii(o,n,q,p,g[j+10],15,-1051523);p=b._ii(p,o,n,q,g[j+1],21,-2054922799);q=b._ii(q,p,o,n,g[j+8],6,1873313359);n=b._ii(n,q,p,o,g[j+15],10,-30611744);o=b._ii(o,n,q,p,g[j+6],15,-1560198380);p=b._ii(p,o,n,q,g[j+13],21,1309151649);q=b._ii(q,p,o,n,g[j+4],6,-145523070);n=b._ii(n,q,p,o,g[j+11],10,-1120210379);o=b._ii(o,n,q,p,g[j+2],15,718787259);p=b._ii(p,o,n,q,g[j+9],21,-343485551);q+=e;p+=k;o+=f;n+=r}return a.endian([q,p,o,n])};b._ff=function(g,f,l,j,e,i,h){var k=g+(f&l|~f&j)+(e>>>0)+h;return((k<<i)|(k>>>(32-i)))+f};b._gg=function(g,f,l,j,e,i,h){var k=g+(f&j|l&~j)+(e>>>0)+h;return((k<<i)|(k>>>(32-i)))+f};b._hh=function(g,f,l,j,e,i,h){var k=g+(f^l^j)+(e>>>0)+h;return((k<<i)|(k>>>(32-i)))+f};b._ii=function(g,f,l,j,e,i,h){var k=g+(l^(f|~j))+(e>>>0)+h;return((k<<i)|(k>>>(32-i)))+f};b._blocksize=16})();

/*
 * HTTP-Digest (RFC2617) implementation
 * Copyright (c) 2009, Robin H. Johnson @ IsoHunt. All rights reserved.
 * Freely licensed under the 3-clause BSD license.
 *
 * Uses the Crypto-JS project: http://code.google.com/p/crypto-js/
 * Specifically, their MD5 implementation.
 *
 * TODO: Test with the new 2.0.0 version.
 *
 * vim: ts=4 et sts=4 sw=4 ft=javascript:
 */

RFC2617 = (function(){

/**
 * Generate a random binary stream of desired length 
 *
 * @param   len Length desired
 * @return      binary string of length 
 */
function random_string(len) {
    var arr = []; 
    for (var i = 0; arr.length < len; i++) {
        /* Get 3 bytes out of each random call,
         * the last byte is not safe */
        var n = Math.random() * (1 << 24);
        while (n > 0) {
            /* Suck off one byte */
            var rem = n % 256;
            /* Discard it from the store */
            n = n >> 8;
            /* Convert it to raw ASCII, and add to array.
             * String.concat is slow in JS. */
            arr.push(String.fromCharCode(rem))
            /* Stop if we have enough chars */
            if (arr.length == len) break;
        }   
    }   
    return arr.join('');
}   

/**
 * Handshake between two arrays, picking the first common element.
 * If no matching elements are found, failure_value is returned.
 *
 * @param server_support array of strings
 * @param client_support array of strings
 * @param failure_value  value to return on no matching element.
 * @return               The first matching array element or the
 *                       contents of failure_value.
 */
function best_available(server_support, client_support, failure_value) {
    var chosen = failure_value;
    for(var i = 0; i < server_support.length && chosen == failure_value; i++) {
        for(var j = 0; j < client_support.length && chosen == failure_value; j++) {
            if(server_support[i] == client_support[j]) {
                chosen = server_support[i];
            }
        }
    }
    return chosen;
}

/**
 * TODO: write JavaDoc for this.
 *
 * Perform RFC2617 authorization calculations.
 *
 * @usage
 * ------
 * auth(username, password, realm, nonce, opaque, method, digestUri 
 *              [, serverQop [, serverAlgorithm [, nonceCount [, clientNonce 
 *              [, entityBody]]]]])
 *
 * @input
 * ------
 * username, password - inputs from user
 * realm, nonce, opaque - input direct from server
 * method, digestUri - implicit arguments from the HTML form
 * serverQop, serverAlgorithm - server's methods and algorithms
 * nonceCount, clientNonce - client-side hashing values, created if needed.
 * entityBody - copy of entire unmodified page as sent by server
 *
 * @output
 * -------
 * structure with the following fields:
 * username, password, realm, nonce, opaque, method, digestUri, qop, 
 * algorithm, nonceCount, clientNonce, response
 *
 * @note
 * -----
 * - Only MD5-class algorithms are supported.
 * - This function only supports the client-side calculation. It does NOT offer
 *   the server-side pre-calculated H(A1) mode.
 *
 */
function auth(username, password, realm, nonce, opaque, method, digestUri, serverQop, serverAlgorithm, nonceCount, clientNonce, entityBody) {
    function h(s) {
        return Crypto.MD5(s);
    }
    function ha(arr) {
        return h(arr.join(':'));
    }
    function str2hex(str) {
        return Crypto.util.bytesToHex(Crypto.util.stringToBytes(str));
    }
    function str2b64(str) {
        return Crypto.util.bytesToBase64(Crypto.util.stringToBytes(str));
    }
    
    // Valid input first!
    if (username == '' || password == '' || realm == '' || 
        nonce == '' ||  opaque == '' || method == '' || 
        digestUri == '') {
        throw new Error("rfc2617-input", "HTTP-Digest: Invalid input to function");
    }

    // Make sure their MD5 works
    if(h("abc").toLowerCase() != "900150983cd24fb0d6963f7d28e17f72") {
        throw new Error("rfc2617-md5broken", "HTTP-Digest: MD5 function is broken");
    }

    // Must always be uppercase, to match HTTP verbs.
    method = method.toUpperCase();

    // QOP and algorithm may be provided by the server, but we need to modify them.
    var serverQop = serverQop.split(',');
    var serverAlgorithm = serverAlgorithm.split(',');
    var clientQop = ['auth-int', 'auth', '']; // empty item is the old RFC2069 mode
    var clientAlgorithm = ['MD5-sess', 'MD5']; // SHA1 NOT supported, no empty item

    // If we do not have the body of the page, we cannot use auth-int.
    if(entityBody == '') { clientQop.shift(); }
    
    // Handshake qop and algorithm
    var failure_value = 'NONE_MATCHED';
    var qop = best_available(serverQop, clientQop, failure_value);
    var algorithm = best_available(serverAlgorithm, clientAlgorithm, failure_value);

    // error checking
    if(qop == failure_value || algorithm == failure_value) {
        throw new Error("rfc2617-handshake", "HTTP-Digest: failed to handshake on QOP or hash algorithm");
    }
    if(algorithm.slice(0,3) != 'MD5') {
        throw new Error("rfc2617-md5", "HTTP-Digest: This implementation only supports MD5 and variants");
    }
    
    // If these are not set, we provide defaults for them.
    //
    if (algorithm == 'MD5-sess' || qop == 'auth' || qop == 'auth-int') {
        if(nonceCount == '') { nonceCount = new Date().getTime(); }
        if(clientNonce == '') { clientNonce = str2b64(random_string(24)); }
    }

    var a1='', a2='', response='';
    var ha1='', ha2='';
    // RFC2617, "3.2.2.2 A1"
    a1 = [username, realm, password];
    if (algorithm == 'MD5-sess') {
        // HA1 already exists here if we are validating.
        if (ha1 == '') ha1 = ha(a1);
        // Mix in the nonce values
        a1 = [ha1, nonce, clientNonce];
        // Reset HA1 to empty so we know it's been included.
        ha1 = ''; 
    }

    // RFC2617, "3.2.2.3 A2"
    a2 = [method, digestUri];
    if(qop == 'auth-int') {
        a2.push(h(entityBody));
    }

    // RFC2617, "3.2.2.1 Request-Digest"
    // HA1 already exists here if we are validating.
    if(ha1 == '') ha1 = ha(a1);
    // But not HA2
    ha2 = ha(a2);
    if(qop == 'auth' || qop == 'auth-int') {
        response = ha([ha1, nonce, nonceCount, clientNonce, qop, ha2]);
    } else if (qop == '') {
        response = ha([ha1, nonce, ha2]);
    }

    // Now set the outputs for the server
    if(response == '' || ha1 == '' || ha2 == '') {
        throw new Error("rfc2617-hash", "HTTP-Digest: hashing failure");
    }
    
    var d = { 
        nonce: nonce,
        opaque: opaque,
        method: method,
        digestUri: digestUri,
        algorithm:algorithm,
        response: response 
    };
    // These 3 do not exist on the server validation
    if(username != '') d.username = username;
    if(password != '') d.password = password;
    if(realm != '') d.realm = realm;

    // These do not exist when using the old RFC2069 compatible mode.
    if(clientNonce != '') d.clientNonce = clientNonce;
    if(nonceCount != '') d.nonceCount = nonceCount;
    if(qop != '') d.qop = qop;

    return d;
}

return {
    best_available: best_available,
    auth: auth
};

})();

/*
 * HTTP-Digest (RFC2617) wiring for jQuery
 * Copyright (c) 2009, Robin H. Johnson @ IsoHunt. All rights reserved.
 * This file is NOT freely licensed. You may use it as an example only.
 *
 * Requires lib/rfc2617.js
 *
 * vim: ts=4 et sts=4 sw=4 ft=javascript:
 */
(function($){

$.extend({digest_login: digest_login});

/**
 * jQuery interface for RFC2617 code.
 *
 * @param   $password   jQuery object of the form.
 * @param   form        form DOM element
 */
function digest_login($password, form, entityBody) {
    // User input:       
    var username = $('#username').val().toLowerCase();
    var password = $password.val();
    // Server input:
    var realm = $('#realm').val();
    var nonce = $('#nonce').val();
    var opaque = $('#opaque').val();
    var method = ruby_http_method($(form));
    var digestUri = ruby_relative_uri($(form).attr('action'));
    // Server input AND client-side changed:
    var qop = $('#qop').val();
    var algorithm = $('#algorithm').val();
    // Output variables.
    var nonceCount = '';
    var clientNonce = '';
    
    // Possible alternative choices you could make for inputs.
    /* This one is in the arguments: */
    // var entityBody = ...;
    /* You might want this one instead. */
    //var digestUri = ruby_absolute_path($(form).attr('action'));

    try {
        //alert('inputs:'
        //        +', :username=>"'+username+'"'
        //        +', :password=>"'+password+'"'
        //        +', :realm=>"'+realm+'"'
        //        +', :nonce=>"'+nonce+'"'
        //        +', :opaque=>"'+opaque+'"'
        //        +', :method=>"'+method+'"'
        //        +', :digestUri=>"'+digestUri+'"'
        //        +', :qop=>"'+qop+'"'
        //        +', :algorithm=>"'+algorithm+'"'
        //        +', :nonceCount=>"'+nonceCount+'"'
        //        +', :clientNonce=>"'+clientNonce+'"'
        //         );
        var rfc2617 = RFC2617.auth(username, password, realm, nonce, opaque, method, digestUri, qop, algorithm, nonceCount, clientNonce, entityBody);
        //alert('outputs:'
        //+', :qop=>"'+rfc2617.qop+'"'
        //+', :algorithm=>"'+rfc2617.algorithm+'"'
        //+', :nonceCount=>"'+rfc2617.nonceCount+'"'
        //+', :cnonce=>"'+rfc2617.clientNonce+'"'
        //+', :response=>"'+rfc2617.response+'"'
        //         );

        $('#qop').val(rfc2617.qop);
        $('#algorithm').val(rfc2617.algorithm);
        $('#nc').val(rfc2617.nonceCount);
        $('#cnonce').val(rfc2617.clientNonce);
        $('#response').val(rfc2617.response);
        $password.val(null);
    } catch(err) {
        // TODO: Throw up a message that we failed to auth AND alert FogBugz
        alert("rfc2617 failure:"+err);
    }
}

/**
 * This is to help us find the actual HTTP method, because Ruby overloads
 * methods in the _method parameter of forms, and makes it nearly impossible to
 * find what was actually used.
 *
 * @param   f   jQuery object of the form.
 */
function ruby_http_method(f) {
    var method = null;
    // Ruby's special case.
    try {
        method =  $("input[name='_method']", f).val();
    } catch (e) {
        // Do nothing, throw array any errors.
    }
    // Normal form.
    if(method == null) {
        try {
            method = f.attr('method');
        } catch (e) {
            // Do nothing, throw array any errors.
        }
    }
    // Default per HTML spec.
    if(method == null) {
        method = 'GET';
    }
    return method.toUpperCase();
}

/**
 * Convert any URI to an absolute URI.
 *
 * @param   p   URI path
 * @param   loc Base URI to append to if needed.
 * @return      Absolute URI
 */
function ruby_absolute_path(p, base_loc) {
    if(/^http/.test(p)) { return p; }
    if(loc == null || loc == '') { loc = location.href; }
    return loc.replace(/\/$/, '') + '/' + p.replace(/^\//, '');
}

/**
 * Convert any URI to a relative URI.
 *
 * @param   p   URI
 * @return      Relative URI
 */
function ruby_relative_uri(p) {
    return(p.replace(/^https?:\/\/[^\/]+\/+/,'/'))
}


})(jQuery);


// Sign up form (pop-up)

// include lib/jquery.validate.js
// include lib/1.1.0-crypto-md5.js
// include lib/rfc2617.js
// include support/digest_login.js

// View:
// layouts/_header.haml


jQuery(function($) {
    $('#login_form').submit(function(){
        $.digest_login($('#password'), this, RFC2617_PAGE_CAPTURE);
        // Detect working javascript :-)
        $('#working_javascript').val(1);
        
        $('#quick_login').addClass('loading_left');
        
        $(this).ajaxSubmit({
            success: function(){
                window.location.reload(true);
            },
            error: function(xhr, textStatus, errorThrown){
                $('#login_error_container')
                    .find('.message')
                    .empty()
                    .append(xhr.responseText)
                    .end()
                    .slideDown('slow');
                $('#username, #password').one('focus', function(){
                    $('#login_error_container').slideUp('slow');
                });
                $('#quick_login').removeClass('loading_left');
            }
        });
        
        return false;
    });
});
