
	//-----------------------------------------------------//
	// GLOBAL
	//-----------------------------------------------------//

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};


	$(function() {

		// NAV
		$("div#top ul#nav > li").hover(function() { $(this).find("ul").css("display","block"); $(this).find("a:first").addClass("active"); },function() { $(this).find("ul").css("display","none"); $(this).find("a:first").removeClass("active"); });
		$("div#top ul#nav li ul").each(function() { $(this).find("li:last").addClass("last"); $(this).append($("<li class=\"bottom\"></li>")); });

		// SUB NAV
		$("div#page ul#sub_nav > li:last").css("border-bottom","none");

		// BREADCRUMB
		$("div#page ul.breadcrumb > li:last").css("font-weight","bold");

		// DROPDOWNS
		$("div.dropdown a.arrow").click(function() {
			dropdown_close();
			var width = $(this).parent().width();
			$(this).parent().find("ul li a").css("width",(width+10)+"px");
			$(this).parent().find("ul:hidden").css("width",(width+18)+"px").slideDown(200);
			$("body").bind("click",dropdown_close);
			$(this).addClass("arrow_down");
			$(this).parent().css("z-index","10");
			return false;
		});
		$("div.dropdown ul.inline li a").click(function() {
			var title = $(this).attr("title");
			if(title.length>0) {
				var value = title;
			} else {
				var value = $(this).text();
			}
			$(this).parent().parent().parent().find("div.selected").html($(this).text());
			$(this).parent().parent().parent().find("input").val(value).change();
			dropdown_close();
			return false;
		});
		$("div.dropdown").each(function() { if($(this).find("ul").height() > 150) { $(this).find("ul").addClass("scroll"); } });

		// DISABLED BUTTONS
		$(".disabled").each(function() { $(this).css("opacity","0.3"); });

		// COMMENTS
		$("div#comments a.flag_as_improper").click(function() {
			var flag_id = get_id($(this).attr("id"));
			if(confirm("Are you sure you want to mark this comment as improper?")) {
				$("input#flag_id").val(flag_id);
				$("form#flag_form").submit();
			}
		});
		$("div#comments a.reply").click(function() {
			$("div#leave_a_comment").addClass("reply").find("input#reply_to").val(get_id($(this).attr("id")));
		});
		$("div#leave_a_comment a.cancel").click(function() {
			$("div#leave_a_comment").removeClass("reply").find("input#reply_to").val("0");
			return false;
		});
		$("div#leave_a_comment a.submit").click(function() {
			var comment = $("textarea#comment").val();
			if(comment.length>0) {
				$("form#comment_form").submit();
			} else {
				alert("Please enter a comment and try again.");
			}
			return false;
		});

		// VOTING
		$("div.poll_question a.submit").click(function() {
			$("form#poll_form").submit();
			return false;
		});

		// BOX GRID
		$("ul.box_grid").each(function() {
			var items = $(this).find("li");
			var height = 0;
			for(var i = 0; i < items.length; i++) {
				if(((i+1)%3)==1) {
					height = $(items[i]).height();
					if($(items[i+1]).height()>height&&(i+1)<items.length) { height = $(items[i+1]).height(); }
					if($(items[i+2]).height()>height&&(i+2)<items.legnth) { height = $(items[i+2]).height(); }
				}
				$(items[i]).css("height",height);
				if(((i+1)%3)==0) { $(items[i]).css("margin-right",0); }
			}
		});

		// QUOTE IMAGE
		$("div.quote_image img").load(function() {
			var width = $(this).parent().find("img").width();
			if(width>0) { $(this).parent().css("width",width+"px"); }
			var height = $(this).parent().find("img").height();
			if(height > 0) { $(this).parent().css("height",height+"px"); }
			$(this).parent().find("div.quote").css("width",(width-20)+"px");
		});
		
		$('div.quote_image').each(function() {
			$(this).css({height:$(this).find('img').height()+'px'});								   
		});

		// COUNTY ENTRIES
		$("div.entries div.county_entry:last").css("border-bottom","none");

		// CALENDAR
		$("div#calendar").hover(function() { $(this).css("z-index","100"); },function() { $(this).css("z-index","1"); });
		$("div#calendar ul.days li.event div").each(function() { $(this).append($("<div class=\"marker\"></div>")); });
		$("div#calendar ul.days li.event").hover(function() { $(this).find("div.popup").fadeIn(200); },function() { $(this).find("div.popup").fadeOut(100); });

		// ACCORDION
		$("ul.accordion li div.top a.expand").click(function() {
			var li = $(this).parent().parent();
			if($(li).find("div.body").is(":visible")) {
				$(li).find("div.body").slideUp(200);
				$(li).removeClass("open");
			} else {
				$(li).parent().find("li.open").each(function() {
					$(this).removeClass("open");
					$(this).find("div.body").slideUp(200);
				});
				$(li).find("div.body").slideDown(200);
				$(li).addClass("open");
			}
			return false;
		});
		$("ul.accordion li div.top").each(function() {
			var height = ($(this).height()/2)+6;
			$(this).find("a.expand").css("top",height+"px");
		});

		// CONTACT FORMS
		$("form#contact_form a.submit").click(function() {
			$("form#contact_form").submit();
			return false;
		});

		// SEARCH FORMS
		$("form#search_form a.search").click(function() {
			$("form#search_form").submit();
			return false;
		});
		$("form#inline_search_form a.search").click(function() {
			$("form#inline_search_form").submit();
			return false;
		});

		// MEMBER FORMS
		//if ($('input#registration_existing').length > 0) toggle_member_fields();
		SI.Files.stylizeAll();
	});

	//-----------------------------------------------------//
	// DROPDOWNS
	//-----------------------------------------------------//

	function dropdown_close() {
		$("div.dropdown a.arrow_down").removeClass("arrow_down");
		$("div.dropdown ul").css("display","none");
		$("div.dropdown").removeAttr("style");
		$("body").unbind("click",dropdown_close);
	}

	//-----------------------------------------------------//
	// HOMEPAGE
	//-----------------------------------------------------//

	function fix_homepage_height() {
		var left_height = $("div.top_stories").height()+$("div.featured_news").height()+$("div.upcoming_events").height();
		var right_height = $("div.login").height()+$("div.latest_media").height()+$("div.reader_poll").height();

		if(left_height > right_height) {

			var height = $("div.reader_poll div.module_frame").height();
			height += (left_height-right_height);
			$("div.reader_poll div.module_frame").css("height",height-10);

		} else if(right_height >= left_height) {

			var height = $("div.upcoming_events div.module_frame").height();
			height += (right_height-left_height);
			$("div.upcoming_events div.module_frame").css("height",height+10);
		}
	}

	//-----------------------------------------------------//
	// ALERTS
	//-----------------------------------------------------//

	var alerts=null,alerts_total=0,alerts_current=1,alerts_return=false;

	function alerts_rotate() {
		alerts_current++;
		if(alerts_current > alerts_total) { alerts_return = 1; }
		var position = (alerts_current-1)*-18;
		$("div.alerts ul").animate({top:position+"px"},500,function() {
			if(alerts_return) { $(this).css("top",0); alerts_current = 1; alerts_return = false; }
		});
	}

	function alerts_prepare() {
		alerts_total = $("div.alerts ul li").length;
		alerts = setInterval(alerts_rotate,5000);
		$("div.alerts").hover(function() { clearInterval(alerts); alerts=null; },function() { alerts = setInterval(alerts_rotate,5000); });
		$("div.alerts ul").append($("div.alerts ul li:first").clone());
	}

	//-----------------------------------------------------//
	// TOP STORIES
	//-----------------------------------------------------//

	var top_stories=null,top_stories_total=0,top_stories_current=1,top_stories_return=false;

	function top_stories_update() {
		$("div.top_stories ul.nav li a.active").removeClass("active");
		var items = $("div.top_stories ul.nav li");
		if(top_stories_return) {
			$(items[top_stories_return-1]).find("a").addClass("active");
		} else {
			$(items[top_stories_current-1]).find("a").addClass("active");
		}
	}

	function top_stories_rotate() {
		top_stories_current++;
		if(top_stories_current > top_stories_total) { top_stories_current = 1; }
		top_stories_show(top_stories_current);
	}

	function top_stories_show(story) {
		top_stories_current = story;
		top_stories_update();
		$("div.top_stories div.stories ul li:visible").fadeOut(800);
		var items = $("div.top_stories div.stories ul li");
		$(items[story-1]).fadeIn(1600);
	}

	function top_stories_prepare() {
		top_stories_total = $("div.top_stories div.stories ul li").length;
		top_stories = setInterval(top_stories_rotate,8000);
		$("div.top_stories").hover(function() { clearInterval(top_stories); top_stories=null; },function() { top_stories = setInterval(top_stories_rotate,8000); });
		$("div.top_stories ul.nav li a").click(function() { top_stories_show($(this).text()); return false; });
	}

	//-----------------------------------------------------//
	// LATEST MEDIA
	//-----------------------------------------------------//

	function latest_media_select(tab) {
		$("div.latest_media ul.nav li a.active").removeClass("active");
		$("div.latest_media ul.nav li."+tab+" a").addClass("active");
		$("div.latest_media div.home_slider_frame ul").css("display","none");
		$("div.latest_media div.home_slider_frame ul."+tab).css("display","block");
	}

	function latest_media_prepare() {
		$("div.latest_media ul.nav li").hover(function() { $(this).find("a").addClass("hover"); },function() { $(this).find("a").removeClass("hover"); });
		$("div.latest_media ul.nav li a").click(function() { latest_media_select($(this).text()); return false; });
		$("div.latest_media a.previous").bind("click",latest_media_previous);
		$("div.latest_media a.next").bind("click",latest_media_next);
		$("div.latest_media div.home_slider_frame ul").each(function() {
			var first = $(this).find("li:first");
			var last = $(this).find("li:last");
			$(this).prepend($(last).clone());
			$(this).append($(first).clone());
			var total = $(this).find("li").length;
			var position = 184*total;
			$(this).css({width:position+"px",left:"-184px"});
		});
	}

	function latest_media_off() {
		$("div.latest_media a.previous").unbind("click",latest_media_previous).bind("click",empty);
		$("div.latest_media a.next").unbind("click",latest_media_next).bind("click",empty);
	}

	function latest_media_on() {
		$("div.latest_media a.previous").unbind("click",empty).bind("click",latest_media_previous);
		$("div.latest_media a.next").unbind("click",empty).bind("click",latest_media_next);
	}

	function latest_media_previous() {
		latest_media_off();
		var ul = $(this).parent().find("div.home_slider_frame ul:visible");
		var total = $(ul).find("li").length;
		var position = $(ul).css("left");
		position = Math.floor(position.replace(/px/,""));
		position += 184;
		$(ul).stop().animate({left:position+"px"},500,function() {
			var position = $(this).css("left");
			position = Math.floor(position.replace(/px/,""));
			var total = $(this).find("li").length;
			if(position>=0) {
				total -= 2;
				var new_position = total*-184;
				$(this).css("left",new_position+"px");
			}
			latest_media_on();
		});
		return false;
	}
	function latest_media_next() {
		latest_media_off();
		var ul = $(this).parent().find("div.home_slider_frame ul:visible");
		var total = $(ul).find("li").length;
		var position = $(ul).css("left");
		position = Math.floor(position.replace(/px/,""));
		position -= 184;
		$(ul).stop().animate({left:position+"px"},500,function() {
			var position = $(this).css("left");
			position = Math.floor(position.replace(/px/,""));
			var total = $(this).find("li").length;
			if(position<=((total-1)*-184)) {
				$(this).css("left","-184px");
			}
			latest_media_on();
		});
		return false;
	}

	//-----------------------------------------------------//
	// SLIDER
	//-----------------------------------------------------//

	function slider_prepare() {
		$("div.slider a.previous").bind("click",slider_previous);
		$("div.slider a.next").bind("click",slider_next);
		$("div.slider div.slider_frame ul").each(function() {
			var first = $(this).find("li:first");
			var last = $(this).find("li:last");
			$(this).prepend($(last).clone());
			$(this).append($(first).clone());
			var total = $(this).find("li").length;
			var position = 544*total;
			$(this).css({width:position+"px",left:"-544px"});
		});
	}

	function slider_off() {
		$("div.slider a.previous").unbind("click",slider_previous).bind("click",empty);
		$("div.slider a.next").unbind("click",slider_next).bind("click",empty);
	}

	function slider_on() {
		$("div.slider a.previous").unbind("click",empty).bind("click",slider_previous);
		$("div.slider a.next").unbind("click",empty).bind("click",slider_next);
	}

	function slider_previous() {
		slider_off();
		var ul = $(this).parent().find("div.slider_frame ul");
		var total = $(ul).find("li").length;
		var position = $(ul).css("left");
		position = Math.floor(position.replace(/px/,""));
		position += 544;
		$(ul).stop().animate({left:position+"px"},500,function() {
			var position = $(this).css("left");
			position = Math.floor(position.replace(/px/,""));
			var total = $(this).find("li").length;
			if(position>=0) {
				total -= 2;
				var new_position = total*-544;
				$(this).css("left",new_position+"px");
			}
			slider_on();
		});
		return false;
	}
	function slider_next() {
		slider_off();
		var ul = $(this).parent().find("div.slider_frame ul");
		var total = $(ul).find("li").length;
		var position = $(ul).css("left");
		position = Math.floor(position.replace(/px/,""));
		position -= 544;
		$(ul).stop().animate({left:position+"px"},500,function() {
			var position = $(this).css("left");
			position = Math.floor(position.replace(/px/,""));
			var total = $(this).find("li").length;
			if(position<=((total-1)*-544)) {
				$(this).css("left","-544px");
			}
			slider_on();
		});
		return false;
	}

	//-----------------------------------------------------//
	// PULL QUOTE
	//-----------------------------------------------------//

	function add_pullquote(pull_quote_text) {
		var remaining = 1000;
		var paragraphs = $("#article_content p").length;
		if(paragraphs > 1) {
			for(var i = 1; i < paragraphs; i++) {
				var p_text = $("#article_content").find("p:eq("+i+")").text();
				remaining -= p_text.length;
				if(p_text.length>0) { remaining-= 50; }
				if(remaining <= 0) {
					var pull_quote = "<div class=\"pull_quote\">"+pull_quote_text+"</div>";
					$("#article_content").find("p:eq("+i+")").after(pull_quote);
					return true;
				}
			}
		}
		return false;
	}

	//-----------------------------------------------------//
	// MEMBER REGISTRATION
	//-----------------------------------------------------//

	window.validating_member = false;

	/**
	 * unique id
	 *
	 * generate a unique id
	 *
	 * @param void
	 * @return string unique id
	 */
	function unique_id(){
		var d = new Date();
		return(d.getTime());
	}

	/**
	 * toggle member fields
	 *
	 * toggle all form fields regarding registration/profile updates based on
	 * the type of registration action being performed
	 *
	 * @param void
	 * @return void
	 */
	function toggle_member_fields(){
		// set default states
		var member_all = true;
		var member_existing = false;
		var member_validation = false;
		var member_validated = false;
		var member_new = false;
		var member_non = false;
		var account_expired = false;
		var account_renewal = false;
		var account_paid = false;

		// determine type of registratin
		var registration_type = 'web';
		if($('input#registration_existing').attr('checked')) registration_type = 'existing';
		else if ($('input#registration_new').attr('checked')) registration_type = 'new';
		$('input#registration_type').attr('value', registration_type);

		// re-enable disabled fields
		$('div.inner_form input:not(.file)').removeAttr('disabled').css('opacity', 1);
		$('div.header h3,div.inner_form label,div.inner_form div.dropdown,div.inner_form div.upload_button').css('opacity', 1);

		// set member toggles
		switch(registration_type){
			case 'existing':
				member_existing = true;
				window.validating_member = true;
				break;
			case 'new':
				member_new = true;
				break;
			case 'web':
				member_non = true;
				break;
		}

		// find everything that should be shown
		var keepers = [];
		keepers = $.merge(keepers, $('div.member_all'));
		if (member_existing) keepers = $.merge(keepers, $('div.member_existing'));
		if (member_validation) keepers = $.merge(keepers, $('div.member_validation'));
		if (member_validated) keepers = $.merge(keepers, $('div.member_validated'));
		if (member_new) keepers = $.merge(keepers, $('div.member_new'));
		if (member_non) keepers = $.merge(keepers, $('div.member_non'));
		if (account_expired) keepers = $.merge(keepers, $('div.account_expired'));
		if (account_renewal) keepers = $.merge(keepers, $('div.account_renewal'));
		if (account_paid) keepers = $.merge(keepers, $('div.account_paid'));
		keepers = $.unique(keepers);

		// mark all of the keepers with a unique class
		var uid = 'uid_' + unique_id();
		$.each(keepers, function(){ $(this).addClass(uid); });

		// show everything that should be shown
		$('div.header.' + uid + ',div.inner_form.' + uid).css('display', 'block');

		// hide everything that should be hidden
		$('div.header:not(.' + uid + '),div.inner_form:not(.' + uid + ')').css('display', 'none');

		// if validating an existing membership, lock out the rest of the form fields
		if (member_existing){
			$('div.inner_form.' + uid + ':not(.member_validation) input:not(.file)').attr('disabled', true).css('opacity', 0.6);
			$('div.header.' + uid + ':not(.member_validation) h3,div.inner_form.' + uid + ':not(.member_validation) label,div.inner_form.' + uid + ':not(.member_validation) div.dropdown,div.inner_form.' + uid + ':not(.member_validation) div.upload_button').css('opacity', 0.6);
		}

		// aggpac does not apply to new users
		$('label[for=aggpac_donation],input#aggpac_donation').css('display', member_new ? 'none' : 'block');
		$('div span#ag_greeting').css('display', member_new ? 'none' : 'inline');

		// cleanup
		$.each(keepers, function(){ $(this).removeClass(uid); });
		label_required_fields();

		// scroll down if validating an existing member
		if (window.validating_member){
			$('html').animate({scrollTop:$($('div.header.member_validation')[0]).offset().top}, 'slow');
			if ($('#member_id_validated').val() != '' && $('#member_id').val() != '' && $('#member_zip').val() != ''){
				validate_member($('#member_id').val(), $('#member_zip').val());
			}
		}
	}

	/**
	 * is luhn
	 *
	 * validate if a value passes the luhn mod algorithm
	 *
	 * @param string credit card number
	 * @return boolean
	 */
	function is_luhn(cardnumber){
		var getdigits = /\d/g;
		var digits = [];
		while (match = getdigits.exec(cardnumber)) digits.push(parseInt(match[0], 10));
		var sum = 0;
		var alt = false;
		for (var i = digits.length - 1; i >= 0; i--){
			if (alt){
				digits[i] *= 2;
				if (digits[i] > 9) digits[i] -= 9;
			}
			sum += digits[i];
			alt = !alt;
		}
		return(sum % 10 == 0);
	}

	/**
	 * validate field
	 *
	 * validate a field for valid data
	 *
	 * @param string id
	 * @param string name
	 * @param (optional) boolean required, default = true
	 * @param (optional) string type, default = text (email, date, phone, login, text, cardnumber, /regexp/)
	 * @return mixed, true on success, error message on failure
	 */
	function validate_field(id, name){
		var required = (arguments.length > 2) ? arguments[2] : true;
		var type = (arguments.length > 3) ? arguments[3] : 'text';
		var val = $('#' + id).val();
		if(required){
			if (val == '') return(name + ' is required');
			else {
				switch(type){
					case 'email':
						if (!val.match(/^(.*)@(.*)\.(.*)$/)) return(name + ' is invalid');
						break;
					case 'phone':
						var temp = val.replace(/[^0-9]+/, '');
						if (!temp.match(/^[0-9]+$/)) return(name + ' is invalid');
						break;
					case 'login':
						if (val.length<4||val.length>20||!val.match(/^[a-zA-Z0-9]+$/)) return(name + ' must be 4-20 characters long and contain no special characters');
						break;
					case 'cardnumber':
						if (!is_luhn(val)) return(name + ' must be a valid credit card number');
						break;
					default:
						if (type != 'text' && typeof(type) == 'object' && !val.match(type)) return(name + ' is invalid');
						break;
				}
			}
		}
		return(true);
	}

	/**
	 * validation ruleset
	 *
	 * determine the validatin ruleset
	 *
	 * @param void
	 * @return array validation rules
	 */
	function validation_ruleset(){
		var validation = [];
		switch($('#registration_type').val()){
			case 'existing':
				switch($('#payment_status').val()){
					case 'past':
						validation = [
							['member_id', 'Member Id', true, 'text'],
							['first_name', 'First Name', true, 'text'],
							['middle_name', 'Middle Name/Initial', false, 'text'],
							['last_name', 'Last Name', true, 'text'],
							['address_1', 'Address', true, 'text'],
							['address_2', 'Apt/Ste/Floor', false, 'text'],
							['city', 'City', true, 'text'],
							['state', 'State', true, 'text'],
							['county', 'County', true, 'text'],
							['township', 'Township', false, 'text'],
							['zip', 'Zip', true, /^[0-9]+-*[0-9]*$/],
							['phone_number', 'Phone', false, 'phone'],
							['email', 'Email', true, 'email'],
							['dob_month', 'DOB Month', true, 'text'],
							['dob_day', 'DOB Day', true, 'text'],
							['dob_year', 'DOB Year', true, 'text'],
							['farming_involvement', 'Farming Involvement', true, 'text'],
							['county_fee', 'County Fee', true, 'text'],
							['aggpac_donation', 'AGGPAC Donation', false, 'text'],
							['member_county', 'Member County', true, 'text'],
							['card_type', 'Card Type', true, 'text'],
							['card_number', 'Card Number', true, 'cardnumber'],
							['card_expiration_month', 'Card Expiration Month', true, 'text'],
							['card_expiration_year', 'Card Expiration Year', true, 'text'],
							['promotional_code', 'Promotional Code', false, 'text']
						];
						break;
					case 'due':
						validation = [
							['member_id', 'Member Id', true, 'text'],
							['first_name', 'First Name', true, 'text'],
							['middle_name', 'Middle Name/Initial', false, 'text'],
							['last_name', 'Last Name', true, 'text'],
							['address_1', 'Address', true, 'text'],
							['address_2', 'Apt/Ste/Floor', false, 'text'],
							['city', 'City', true, 'text'],
							['state', 'State', true, 'text'],
							['county', 'County', true, 'text'],
							['township', 'Township', false, 'text'],
							['zip', 'Zip', true, /^[0-9]+-*[0-9]*$/],
							['phone_number', 'Phone', false, 'phone'],
							['email', 'Email', true, 'email'],
							['dob_month', 'DOB Month', true, 'text'],
							['dob_day', 'DOB Day', true, 'text'],
							['dob_year', 'DOB Year', true, 'text'],
							['farming_involvement', 'Farming Involvement', true, 'text'],
							['county_fee', 'County Fee', false, 'text'],
							['aggpac_donation', 'AGGPAC Donation', false, 'text'],
							['member_county', 'Member County', false, 'text'],
							['card_type', 'Card Type', false, 'text'],
							['card_number', 'Card Number', false, 'cardnumber'],
							['card_expiration_month', 'Card Expiration Month', false, 'text'],
							['card_expiration_year', 'Card Expiration Year', false, 'text'],
							['promotional_code', 'Promotional Code', false, 'text']
						];
						break;
					case 'paid':
						validation = [
							['member_id', 'Member Id', true, 'text'],
							['first_name', 'First Name', true, 'text'],
							['middle_name', 'Middle Name/Initial', false, 'text'],
							['last_name', 'Last Name', true, 'text'],
							['address_1', 'Address', true, 'text'],
							['address_2', 'Apt/Ste/Floor', false, 'text'],
							['city', 'City', true, 'text'],
							['state', 'State', true, 'text'],
							['county', 'County', true, 'text'],
							['township', 'Township', false, 'text'],
							['zip', 'Zip', true, /^[0-9]+-*[0-9]*$/],
							['phone_number', 'Phone', false, 'phone'],
							['email', 'Email', true, 'email'],
							['dob_month', 'DOB Month', true, 'text'],
							['dob_day', 'DOB Day', true, 'text'],
							['dob_year', 'DOB Year', true, 'text'],
							['farming_involvement', 'Farming Involvement', true, 'text'],
							['county_fee', 'County Fee', false, 'text'],
							['aggpac_donation', 'AGGPAC Donation', false, 'text'],
							['member_county', 'Member County', false, 'text'],
							['card_type', 'Card Type', false, 'text'],
							['card_number', 'Card Number', false, 'cardnumber'],
							['card_expiration_month', 'Card Expiration Month', false, 'text'],
							['card_expiration_year', 'Card Expiration Year', false, 'text'],
							['promotional_code', 'Promotional Code', false, 'text']
						];
						break;
				}
				break;
			case 'new':
				validation = [
					['member_id', 'Member Id', false, 'text'],
					['first_name', 'First Name', true, 'text'],
					['middle_name', 'Middle Name/Initial', false, 'text'],
					['last_name', 'Last Name', true, 'text'],
					['address_1', 'Address', true, 'text'],
					['address_2', 'Apt/Ste/Floor', false, 'text'],
					['city', 'City', true, 'text'],
					['state', 'State', true, 'text'],
					['county', 'County', true, 'text'],
					['township', 'Township', false, 'text'],
					['zip', 'Zip', true, /^[0-9]+-*[0-9]*$/],
					['phone_number', 'Phone', false, 'phone'],
					['email', 'Email', true, 'email'],
					['dob_month', 'DOB Month', true, 'text'],
					['dob_day', 'DOB Day', true, 'text'],
					['dob_year', 'DOB Year', true, 'text'],
					['farming_involvement', 'Farming Involvement', true, 'text'],
					['county_fee', 'County Fee', true, 'text'],
					['aggpac_donation', 'AGGPAC Donation', false, 'text'],
					['member_county', 'Member County', true, 'text'],
					['card_type', 'Card Type', true, 'text'],
					['card_number', 'Card Number', true, 'cardnumber'],
					['card_expiration_month', 'Card Expiration Month', true, 'text'],
					['card_expiration_year', 'Card Expiration Year', true, 'text'],
					['promotional_code', 'Promotional Code', false, 'text']
				];
				break;
			case 'web':
				validation = [
					['member_id', 'Member Id', false, 'text'],
					['first_name', 'First Name', true, 'text'],
					['middle_name', 'Middle Name/Initial', false, 'text'],
					['last_name', 'Last Name', true, 'text'],
					['address_1', 'Address', false, 'text'],
					['address_2', 'Apt/Ste/Floor', false, 'text'],
					['city', 'City', false, 'text'],
					['state', 'State', true, 'text'],
					['county', 'County', false, 'text'],
					['township', 'Township', false, 'text'],
					['zip', 'Zip', false, /^[0-9]+-*[0-9]*$/],
					['phone_number', 'Phone', false, 'phone'],
					['email', 'Email', true, 'email'],
					['dob_month', 'DOB Month', true, 'text'],
					['dob_day', 'DOB Day', true, 'text'],
					['dob_year', 'DOB Year', true, 'text'],
					['farming_involvement', 'Farming Involvement', false, 'text'],
					['county_fee', 'County Fee', false, 'text'],
					['aggpac_donation', 'AGGPAC Donation', false, 'text'],
					['member_county', 'Member County', false, 'text'],
					['card_type', 'Card Type', false, 'text'],
					['card_number', 'Card Number', false, 'cardnumber'],
					['card_expiration_month', 'Card Expiration Month', false, 'text'],
					['card_expiration_year', 'Card Expiration Year', false, 'text'],
					['promotional_code', 'Promotional Code', false, 'text']
				];
				break;
		}
		if ($('#id').length == 1){
			// profile update
			validation.push(['password', 'Password', false, 'text']);
			validation.push(['confirm_password', 'Password Confirmation', false, new RegExp('^' + $('#password').val() + '$')]);
		} else {
			// new registration
			validation.push(['username', 'Username', true, 'text']);
			validation.push(['password', 'Password', true, 'text']);
			validation.push(['confirm_password', 'Password Confirmation', true, new RegExp('^' + $('#password').val() + '$')]);
		}
		return(validation);
	}

	/**
	 * label required fields
	 *
	 * label the required fields with asterisk characters
	 *
	 * @param void
	 * @return void
	 */
	function label_required_fields(){
		var validation = validation_ruleset();
		var len = validation.length;
		for (var i = 0; i < len; i++) $('label[for=' + validation[i][0] + '] span.required').html(validation[i][2] ? '*' : '');
	}

	/**
	 * validate member fields
	 *
	 * validate all of the member fields
	 *
	 * @param void
	 * @return boolean
	 */
	function validate_member_fields(){
		var errors = [];
		var validation = validation_ruleset();
		var len = validation.length;
		for (var i = 0; i < len; i++) errors.push(validate_field(validation[i][0], validation[i][1], validation[i][2], validation[i][3]));
		var cleanup = new Array();
		for (var i = 0; i < errors.length; i++) if (errors[i] !== true) cleanup.push(errors[i]);
		if (cleanup.length > 0){
			$('#signup_error').html(cleanup.join('<br/>'));
			$('#signup_error').show('fast', function(){
				$('html').animate({scrollTop:0}, 'fast');
			});
			return(false);
		}
		return(true);
	}

	/**
	 * select dropdown
	 *
	 * select one of the available values within one of the artificial dropdowns
	 *
	 * @param string input id
	 * @param string selected value
	 * @return void
	 */
	function select_dropdown(id, value){
		$('#' + id).parent().find('ul.inline li a').each(function(){
			if ((($(this).attr('title') != '') && ($(this).attr('title') == value)) || ($(this).text() == value)){
				$(this).parent().parent().parent().find('div.selected').html($(this).text());
			}
		});
		$('#' + id).change();
	}

	/**
	 * lock dropdown
	 *
	 * lock a dropdown so that a user cannot interact with it
	 *
	 * @param void
	 * @return void
	 */
	function lock_dropdown(id){
		$('#' + id).parent().find('a.arrow').each(function(){
			$(this).css('display', 'none');
		});
	}

	/**
	 * unlock dropdown
	 *
	 * unlock a dropdown so that a user can interact with it
	 *
	 * @param void
	 * @return void
	 */
	function unlock_dropdown(id){
		$('#' + id).parent().find('a.arrow').each(function(){
			$(this).css('display', 'block');
		});
	}

	/**
	 * validate member
	 *
	 * validate that a member is real by testing their ability to know their
	 * member id and their zip code
	 *
	 * @param string member id
	 * @param string zip code
	 * @return boolean
	 */
	function validate_member(member_id, member_zip){
		// set default states
		var member_all = true;
		var member_existing = true;
		var member_validation = false;
		var member_validated = true;
		var member_new = false;
		var member_non = false;
		var account_expired = false;
		var account_renewal = false;
		var account_paid = false;

		// show the loader animation
		$('#retrieve_info_loader').css('display', 'block');

		// make the JSON request for validated member data
		$.getJSON('/account/signup/member_validate.php?member_id=' + member_id + '&zip=' + member_zip, function(data, status){
			if (status == 'success' && data.Result && data.Result[0].Addresses.FullAddressData[0].Address.PostalCode.substring(0,5) == member_zip.substring(0,5)){
				// determine the payment status for this account
				var paid_thru = null;
				var member_county = null;
				var member_types = [
					{'AM': 'Associate Member'},		// Member Degree 5
					{'MI': 'Member Individual'},	// Degree 1-4
					{'MC': 'Member Company'},		// No Longer Used, Degree 1-4
					{'SPS': 'Spouse'},				// Should be attached to a primary member and no more than one primary member
					{'DEP': 'Dependent'},			// Should be attached to a primary member and can be multiple dependents
					{'NMI': 'Non Member'}			// A non member record, a prospective member
				];
				var member_type_code = '';
				var member_type_description = '';
				var len = data.Result[0].Name.Properties.GenericPropertyData.length;
				for (var i = 0; i < len; i++){
					switch(data.Result[0].Name.Properties.GenericPropertyData[i].Name){
						case 'PAID_THRU':
							if (data.Result[0].Name.Properties.GenericPropertyData[i].Value != null){
								paid_thru = data.Result[0].Name.Properties.GenericPropertyData[i].Value.substring(0, 10);
							}
							break;
						case 'CHAPTER':
							if (data.Result[0].Name.Properties.GenericPropertyData[i].Value != null){
								member_county = data.Result[0].Name.Properties.GenericPropertyData[i].Value;
							}
							break;
						case 'MEMBER_TYPE':
							member_type_code = data.Result[0].Name.Properties.GenericPropertyData[i].Value;
							break;
					}
				}
				if (member_type_code == 'AM' || member_type_code == 'MI' || member_type_code == 'MC'){
					var require_payment = false;
					var payment_status = null;
					var payment_greeting = '';
					if (paid_thru != null){
						var split = paid_thru.split('-');
						var yy = split[0];
						var mm = parseInt(split[1]) - 1;
						var dd = parseInt(split[2]);
						var expires = new Date();
						expires.setFullYear(yy, mm, dd);
						var now = new Date();
						var months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
						var expiry_date = (months[expires.getMonth()]) + ' ' + expires.getDate() + ', ' + expires.getFullYear();
						payment_greeting = 'Your membership ';
						if (expires > now){
							// not expired yet
							var days_remaining = (expires.getTime() - now.getTime()) / 86400000;
							var renewal = new Date();
							renewal.setTime(expires.getTime() - (60 * 86400000));
							var renewal_date = (months[renewal.getMonth()]) + ' ' + renewal.getDate() + ', ' + renewal.getFullYear();
							if (days_remaining <= 60){
								account_renewal = true;
								payment_greeting += 'expires ' + expiry_date + ' and is currently eligible for renewal.<br/><span style="font-weight:bold; color:#c00;">Payment is optional at this time, but renew now for uninterrupted membership benefits.</span>';
								require_payment = true;
								payment_status = 'due';
							} else {
								account_paid = true;
								payment_greeting += 'expires ' + expiry_date + ' and will be eligible for renewal starting ' + renewal_date + '.<br/><span style="font-weight:bold; color:#c00;">No payment is due at this time.</span>';
								payment_status = 'paid';
							}
						} else {
							// already expired
							account_expired = true;
							payment_greeting += 'expired ' + expiry_date + ' and is eligible for renewal.<br/><span style="font-weight:bold; color:#c00;">Payment is past due and must be submitted to continue Farm Bureau membership.</span>';
							require_payment = true;
							payment_status = 'past';
						}
					}
					$('#payment_greeting').html(payment_greeting);
					$('#payment_status').attr('value', payment_status);

					// capture all of the relevant ajax data
					var first_name = data.Result[0].PersonName.FirstName;
					var middle_name = data.Result[0].PersonName.MiddleName;
					var last_name = data.Result[0].PersonName.LastName;
					var address_1 = data.Result[0].Addresses.FullAddressData[0].Address.AddressLines.string[0];
					var address_2 = '';
					if (data.Result[0].Addresses.FullAddressData[0].Address.AddressLines.string.length > 1){
						address_2 = data.Result[0].Addresses.FullAddressData[0].Address.AddressLines.string[1];
					}
					var city = data.Result[0].Addresses.FullAddressData[0].Address.CityName;
					var state = data.Result[0].Addresses.FullAddressData[0].Address.CountrySubEntityCode;
					var county = data.Result[0].Addresses.FullAddressData[0].Address.CountyName;
					var township = '';
					var farming_involvement = '';
					var len = data.Result[0].Name_UD_Member_Info.Properties.GenericPropertyData.length;
					for (var i = 0; i < len; i++){
						switch(data.Result[0].Name_UD_Member_Info.Properties.GenericPropertyData[i].Name){
							case 'TOWNSHIP':
								township = data.Result[0].Name_UD_Member_Info.Properties.GenericPropertyData[i].Value;
								break;
							case 'MEMBER_DEGREE':
								farming_involvement = data.Result[0].Name_UD_Member_Info.Properties.GenericPropertyData[i].Value;
								break;
						}
					}
					var zip = data.Result[0].Addresses.FullAddressData[0].Address.PostalCode;
					var phone_number = data.Result[0].Addresses.FullAddressData[0].Phone;
					var email = data.Result[0].Addresses.FullAddressData[0].Email;
					var dob = (data.Result[0].BirthDate) ? data.Result[0].BirthDate.substring(0, 10).split('-') : [];
					var dob_month = dob.length == 3 ? dob[1] : '';
					var dob_day = dob.length == 3 ? dob[2] : '';
					var dob_year = dob.length == 3 ? dob[0] : '';

					// remember this success for the next attempt
					if ($('input#unvalidated_member_id').length > 0) $('input#unvalidated_member_id').attr('value', member_id);
					if ($('input#member_id').length > 0) $('input#member_id').attr('value', member_id);
					$('input#member_confirmed').attr('value', member_id);

					// hide member validation fields
					$('#member_id_validated').attr('value', member_id);
					$('#member_greeting').html('Welcome ' + first_name + '!<br/><br/>');

					// pre-populate every field possible
					$('#first_name').attr('value', first_name);
					$('#middle_name').attr('value', middle_name);
					$('#last_name').attr('value', last_name);
					$('#address_1').attr('value', address_1);
					$('#address_2').attr('value', address_2);
					$('#city').attr('value', city);
					$('#state').attr('value', state);
					select_dropdown('state', $('#state').attr('value'));
					$('#county').attr('value', county);
					select_dropdown('county', $('#county').attr('value'));
					$('#member_county').attr('value', member_county);
					select_dropdown('member_county', (member_county.length == 3) ? member_county.substring(1,3) : member_county);
					if ($('#member_county').attr('value') != '') lock_dropdown('member_county');
					$.each(window.counties, function(key, val){
						if (member_county == key || ((member_county.length == 3) ? member_county.substring(1,3) : member_county) == val['text_id']){
							$('#county_fee').attr('value', val['dues_amount']);
							$('#aggpac_donation').attr('value', val['pac_amount']);
							$('#county_greeting').html('The OFBF membership fee for ' + key + ' County is $' + val['dues_amount'] + ' and is up for renewal every 12 months. ');
						}
					});
					$('#township').attr('value', township);
					select_dropdown('township', township);
					$('#zip').attr('value', zip);
					$('#phone_number').attr('value', phone_number);
					$('#email').attr('value', email);
					$('#dob_month').attr('value', dob_month);
					select_dropdown('dob_month', dob_month);
					$('#dob_day').attr('value', dob_day);
					select_dropdown('dob_day', dob_day);
					$('#dob_year').attr('value', dob_year);
					select_dropdown('dob_year', dob_year);
					$('#farming_involvement').attr('value', farming_involvement);
					select_dropdown('farming_involvement', $('#farming_involvement').attr('value'));
					lock_dropdown('farming_involvement');

					if ($('#member_county').val() != ''){
						$('#member_county_box').css('display', 'block');
						$('#member_county').change();
					}

					// find everything that should be shown
					var keepers = [];
					keepers = $.merge(keepers, $('div.member_all'));
					if (member_existing) keepers = $.merge(keepers, $('div.member_existing'));
					if (member_validation) keepers = $.merge(keepers, $('div.member_validation'));
					if (member_validated) keepers = $.merge(keepers, $('div.member_validated'));
					if (member_new) keepers = $.merge(keepers, $('div.member_new'));
					if (member_non) keepers = $.merge(keepers, $('div.member_non'));
					if (account_expired) keepers = $.merge(keepers, $('div.account_expired'));
					if (account_renewal) keepers = $.merge(keepers, $('div.account_renewal'));
					if (account_paid) keepers = $.merge(keepers, $('div.account_paid'));
					keepers = $.unique(keepers);

					// mark all of the keepers with a unique class
					var uid = 'uid_' + unique_id();
					$.each(keepers, function(){ $(this).addClass(uid); });

					// show everything that should be shown
					$('div.header.' + uid + ',div.inner_form.' + uid).css('display', 'block');

					// hide everything that should be hidden
					$('div.header:not(.' + uid + '),div.inner_form:not(.' + uid + '),div.registration_type,div.member_validation').css('display', 'none');

					// re-enable disabled fields
					$('div.inner_form input:not(.file)').removeAttr('disabled').css('opacity', 1);
					$('div.header h3,div.inner_form label,div.inner_form div.dropdown,div.inner_form div.upload_button').css('opacity', 1);

					// cleanup
					$.each(keepers, function(){ $(this).removeClass(uid); });

					if (!require_payment){
						$('.member_payment input').attr('disabled', true);
						$('.member_payment input,.member_payment label,.member_payment div.dropdown').css('opacity', 0.6);
					}
					label_required_fields();
				} else {
					$('#member_errors').html('We apologize for the inconvenience, but only valid member accounts (degree 1-5) can be reconciled by Member ID. Please contact an OFBF administrator for assistance.').show('fast');
				}
			} else {
				// show the error
				$('#member_errors').html(data['error']).show('fast');
			}
			$('#retrieve_info_loader').hide('fast');
		});
	}

	/**
	 * valiate cancel
	 *
	 * cancel the member validation attempt
	 *
	 * @param void
	 * @return void
	 */
	function validate_cancel(){
		$('input#registration_' + (($('input#registration_type').attr('value') != 'existing') ? $('input#registration_type').attr('value') : 'new')).attr('checked', true);
		toggle_member_fields();
		unlock_dropdown('member_county');
		unlock_dropdown('farming_involvement');
		window.validating_member = false;
		label_required_fields();
		$('html').animate({scrollTop:$($('div.header.registration_type')[0]).offset().top}, 'fast');
	}

	/**
	 * format currency
	 *
	 * format a string that represents a double into currency
	 *
	 * @param string amount
	 * @return string formatted amount
	 */
	function format_currency(num) {
		num = isNaN(num) || num === '' || num === null ? 0.00 : num;
		return parseFloat(num).toFixed(2);
	}
