/**
 * CMA.JS
 *
 * @description		Custom javascript operations and methods for CMA.
 * @author 			Brad Condo
 * @revision 		0.4
 * @date			2011-02-10
 */
	
var animate={speed:400,easing:'easeOutExpo'};
		
$(function() { // START JQUERY READY

/* ===============================================================================================
	FORM ELEMENT OPERATIONS
   ----------------------------------------------------------------------------------------------- */
		
		/**
		 * PASSWORD TEXT
		 *
		 * Hide text version of password and replace with password version on focus.
		 */
		$("input.password[type='text']").focus(function() {
			$(this).hide().next('input.password').show().focus();
		});
		
		/**
		 * PASSWORD REPLACE
		 *
		 * Show text version of password on blur.
		 */
		$("input.password[type='password']").blur(function() {
			if($(this).val()=='') {
				$(this).hide().prev('input.password').show();
			}
		});
	
		/**
		 * INPUT FOCUS
		 *
		 * Clear input fields on focus (checking title attribute)
		 */
		$('input,textarea').live('focus',function() {
			if( $(this).attr('title').length>0 && $(this).val()==$(this).attr('title') ) {
				$(this).addClass('pending');
			}
		});
		
		/**
		 * INPUT BLUR
		 *
		 * Populate input fields on blur (checking title attribute)
		 */
		$('input,textarea').live('blur',function() {
			if( $(this).val().length==0 && $(this).attr('title').length>0 ) {
				$(this).val($(this).attr('title'));
			}
			$(this).removeClass('pending');
		}).blur();
	
		/**
		 * INPUT KEYDOWN
		 *
		 * Remove title text on keydown if value matches title text.
		 */
		$('input,textarea').live('keydown',function(e) {
			if( $(this).attr('title').length>0 && $(this).val()==$(this).attr('title') ) {
				$(this).removeClass('pending');
				$(this).val('');
			}
		});
		
		/**
		 * INPUT KEYUP
		 *
		 * Return title text to input field if keyed to empty.
		 */
		$('input,textarea').live('keyup',function(e) {
			if( $(this).val().length==0 && e.keyCode!=8 /* not backspace */ && $(this).attr('title').length>0 ) {
				$(this).addClass('pending');
				$(this).val($(this).attr('title'));
			}
		});
		
		/**
		 * FORM SUBMIT
		 *
		 * Clear all replacement text from fields on form submit.
		 */
		$('form').submit(function() {
			$(this).find('input').each(function() {
				if($(this).attr('title').length>0&&$(this).val()==$(this).attr('title')) $(this).val('');
			});
			$(this).find('textarea').each(function() {
				if($(this).attr('title').length>0&&$(this).val()==$(this).attr('title')) $(this).val('');
			});
			return true;
		});
		
		/**
		 * DATE PICKER
		 *
		 * Set up datepicker inputs.
		 */
		$('input.dtpicker').datepicker();
		$('a.sprite.datepicker').click(function() { 
			$(this).siblings('input.text.dtpicker:first').focus();
			return false;
		});
			
			
/* ===============================================================================================
	GENERAL CONTENT OPERATIONS
   ----------------------------------------------------------------------------------------------- */
	   			
		/**
		 * DROPDOWN CONTROL
		 *
		 * Show / hide top dropdown element.
		 */
		$('#dropdown .control').click(function() {
			if($('#dropdown form').is(":hidden")) {
				$('#dropdown form').show();
				$('#dropdown').stop().animate({marginTop:0},animate.speed,animate.easing);
			} else {
				$('#dropdown form').hide();
				$('#dropdown').stop().animate({marginTop:'-77px'},animate.speed,animate.easing);
			}
			return false;
		});
		
		/**
		 * PRIMARY NAV
		 *
		 * Show / hide primary navigation dropdowns.
		 */
		$('.primary_nav > li').hover(function() {
			$(this).find('a:first').addClass('hover');
			$(this).find('.dropdown').fadeIn(animate.speed/4);
		},function() {
			$(this).find('a:first').removeClass('hover');
			$(this).find('.dropdown').fadeOut(animate.speed/4);
		});
		
		/**
		 * SUB NAV
		 *
		 * Setup sub navigation.
		 */
		$('#sub_nav > li:first').css({borderTop:'none'});
	
		/**
		 * INLINE TABS
		 *
		 * Show tab content on tab click.
		 */
		$('.tabs .inline a').not('[rel="external"]').click(function() {
			$(this).parents('.tabs').find('li').removeClass('active');
			$(this).parent().addClass('active');
			$(this).parents('.tabs').parent().find('div.inline-content').hide().end().find('div.'+$(this).attr('href')).show();
			location.hash = $(this).attr('href');
			return false;
		});
		
		if($('ul.tabs').length && location.hash.length) {
			var hash = location.hash;
			if(hash.indexOf('#') != -1) hash = hash.substring(hash.indexOf('#')+1);
			$("ul.tabs").find("a[href='"+hash+"']").click();
		}

		/**
		 * TABLES
		 *
		 * Setup table elements.
		 */
		$('table').each(function() {
		
			$(this).find('tr').each(function() {
				$(this).find('td:last').css({borderRight:'none'});
			});
			
			// bwhitman: ignore this rule for purchase detail tables.
			$(this).not('.purchase_detail table').find('tr:last').each(function() {
				$(this).find('td').css({borderBottom:'none'});
			});
		
		});

		/**
		 * TERMS POPUP
		 *
		 * Handle terms click and find terms content.
		 */
		$('a.terms_popup').click(function() {
			display_message({
				title: 'Terms &amp; Conditions',
				message: $('div.terms_popup').html()
			});
			return false;
		});

		/**
		 * EVENT "sections"
		 *
		 * Setup div with the "section" class to avoid footer conflicts
		 */
		$('div.section:last-child').css({borderBottom:'none'});
	
		/**
		 * AREAS OF INTEREST
		 *
		 * Setup areas of interest actions.
		 */
		$('div.areas_of_interest ul.alerts li .area').hover(function() {
			$(this).parent().css({zIndex:100}).end().append('<a href="#add" class="sprite trigger-alerts" data-uid="'+$(this).parents('li').data('uid')+'" data-table="cma_areas" data-id="'+$(this).data('id')+'">Add to Alerts<div class="tooltip">Add to Alerts<span class="sprite quote"></span><div class="mask"></div></div></a>');
		},function() {
			clearTimeout(tooltiptimeout);
			tooltiptimeout = null;
			$(this).parent().css({zIndex:1}).end().find('a.trigger-alerts').remove();
		});
	
		/**
		 * ADD AREA TO ALERTS
		 *
		 * Add area to alerts actions.
		 */
		$('div.areas_of_interest ul.alerts li .area a.trigger-alerts').live('hover',function(event) {
			if (event.type == 'mouseenter') {
				if(tooltiptimeout!=null) {
					clearTimeout(tooltiptimeout);
					tooltiptimeout = null;
				} else {
					$(event.target).find('.tooltip').show();
				}
			} else {
				tooltiptimeout = setTimeout(hide_alert_tooltip,animate.speed);
			}
		});
		
		/**
		 * CMS INLINE IMAGES
		 *
		 * Convert images aligned right to inline image format.
		 */
		$(".cmscontent img[align='right']").each(function() {
		    position_inline_image(this);
		});


		/**
		 * CMS ANCHOR FIX
		 *
		 * Fix anchor problem due to <base>
		 */
		$('a[href^="#"]').each(function() {
			var anchor = $(this).attr('href');
			$(this).attr('href', location.href + anchor);
		});
		
		
		/**
		 * STORE ITEM ALIGNMENT
		 *
		 * Align adjacent store items.
		 */
		$('.resource_library .feed').each(function() {
			align_store_feed();
		});
		
		
		/**
		 * STORE BUTTON PLACEMENT
		 *
		 * If no non-member price, move button up.
		 */
		$('.resource_library div.info div.right').each(function() {
			if($(this).height()<25) {
				$(this).parent().find('a.add_to_cart').css({top:'12px'});
				$(this).parent().find('a.download_file').css({top:'12px'});
			}
		});

/* ===============================================================================================
	GRID OPERATIONS
   ----------------------------------------------------------------------------------------------- */
	
		/**
		 * GRID MORE LINK
		 *
		 * Setup a.more links within grid elements.
		 */
		$('.grid a.more').click(function() {
		
			var feed_info = get_feed_info();
			if(grid_animating) return false;
			
			if($(feed_info).data('disabled')!='disabled') {
				
				grid_animating = true;
				
				//
				// Set Page
				var page = $(feed_info).data('page')+1;
		   		$(feed_info).data('page',page);
		   		var feed = $(feed_info).prev('.feed');
		   		
		   		//
		   		// Get Filters
		   		var filters = '';
		   		if($(feed_info).data('filters')!=undefined&&$(feed_info).data('filters')!=null)
		   			filters = $(feed_info).data('filters');
		   		
		   		//
		   		// Get Search
		   		var search = '';
		   		if($(feed_info).data('search')!=undefined&&$(feed_info).data('search')!=null)
		   			search = $(feed_info).data('search');
		   		
		   		//
		   		// Track
		   		ga_track_event(location.href,'Grid Next',page);
		   		
		   		//
		   		// Elements Exist
		   		$(feed).find('.page-'+page).remove();

		   		//
		   		// Retrieve Elements
				$.ajax({
					type: "POST",
					url: $(feed_info).data('url'),
					data: "page="+page+"&filters="+filters+"&search="+search,
					dataType: "json",
					success: function(data) {

						//
						// Disable feed if last page
						if(data.results.length<$(feed_info).data('perpage')) {
							$(feed_info).data('disabled','disabled');
						}
						
						if(data.results.length>0) {
						
							//
							// Set height for animation
							var height = $(feed).height()+16;
							
							//
							// Add new items
							for(var i=0; i<data.results.length; i++)
								$(feed).append(data.results[i]);
							
							//
							// Wrap feed
							$(feed).wrap('<div class="items_wrapper" style="height: '+height+'px;" />');
							
							//
							// Animate Feed
							$(feed).css({top:'8x'}).animate({top: -(height-16)+'px'},animate.speed,function() {
								$(this).css({top:'8px'}).find('.page-'+(page-1)).hide().end().unwrap();
								grid_animating=false;
							});
						
						} else {
							$(feed_info).data('page',page-1);
							grid_animating=false;
						}
						
					},
					error: function (msg1,msg2,msg3) {
						$(feed_info).data('page',page-1);
						grid_animating=false;
					}
		   		});
			   	
	   		} else {
	   			grid_animating=false;
	   		}
	   		
			return false;
			
		});
		
		/**
		 * GRID LESS LINK
		 *
		 * Setup a.less links within grid elements.
		 */
		$('.grid a.less').click(function() {
		
			if(!grid_animating) {
			
				var feed_info = get_feed_info();
	   			var feed = $(feed_info).prev('.feed');
				var page = $(feed_info).data('page')-1;
				if(page<=0) return false;
				$(feed_info).data('page',page).removeData('disabled');
				grid_animating=true;
		   		
		   		//
		   		// Track
		   		ga_track_event(location.href,'Grid Less',page);
				
				//
				// Set height for animation
				var height = $(feed).height()+16;
				
				//
				// Elements Exist
				$(feed).find('.page-'+page).remove();
	   		
		   		//
		   		// Get Filters
		   		var filters = '';
		   		if($(feed_info).data('filters')!=undefined&&$(feed_info).data('filters')!=null)
		   			filters = $(feed_info).data('filters');
		   		
		   		//
		   		// Get Search
		   		var search = '';
		   		if($(feed_info).data('search')!=undefined&&$(feed_info).data('search')!=null)
	   				search = $(feed_info).data('search');
			
				$.ajax({
					type: "POST",
					url: $(feed_info).data('url'),
					data: "page="+page+"&filters="+filters+"&search="+search,
					dataType: "json",
					success: function(data) {
					
						//
						// Add Items
						for(var i=data.results.length; i>=0; i--)
							$(feed).prepend(data.results[i]);
			
						//
						// Show items on previous page
						$(feed_info).prev('.feed').find('.page-'+page).show();
						
						//
						// Wrap feed
						$(feed_info).prev('.feed').wrap('<div class="items_wrapper" style="height: '+height+'px;" />');
						
						//
						// Animate Feed
						$('.items_wrapper .feed').css({top: -(height-16)+'px'}).animate({top: 0},animate.speed,function() {
							$(this).find('.page-'+(page+1)).hide().end().unwrap();
							grid_animating=false;
						});
							
						
					},
					error: function (msg1,msg2,msg3) {
						$(feed_info).data('page',page+1);
						grid_animating=false;
					}
		   		});
			
			}
			return false;
		});
			

/* ===============================================================================================
	LOGIN OPERATIONS
   ----------------------------------------------------------------------------------------------- */


		function inline_signup_2012() {
			
			var html = '<iframe src="/web-account" style="height: 350px; width: 690px; overflow: hidden;" scrolling="no" frameBorder="0"></iframe>';
			
			// Display Overlay/Message
			display_message({ title: 'Create Your Online Account', message: html });
			var side = ( parseInt($(document).width()) - 750) / 2;
			$('div#message').css('width','750px').css('left',side+'px');
			$('div#message ul li:last').addClass('last');

			// Remove Close Button
			$('#message .message').css('margin','0').css('padding','0');
			$('#message a.close').remove();	
		
		}

		
		/**
		 * INLINE SIGNUP AUTOCOMPLETE
		 *
		 * Inline signup autocomplete handler.
		 */
		function inline_signup() {
			
			//
			// Get Variables
			var firstname = $('input#firstname').val().replace('First Name','');
			var lastname = $('input#lastname').val().replace('Last Name','');

			var section=$('input#firstname').parents('.section');
			var list=$(section).find('ul.located_accounts');
				
			//
			// Clear Form
			clearerrors(section);
				
			//
			// Setup Autocomplete List
			$(section).find('div.autocomplete').show();
   			$(list).css({height:'auto'}).find('li.result').remove().end().find('li.loading').remove();
   			$(list).find('li.not_found').before('<li class="loading">&nbsp;</li>');
   			
   			//
   			// Stop Previous Ajax Requests
   			if($(section).data('ajax')!=undefined) $(section).data('ajax').abort();
   			
   			$(section).find('div.loginstep2').show();

			
			//
   			// Retrieve List
	   		$(section).data('ajax',$.ajax({
				type: "POST",
				url: "/lookups/member-new/",
				data: 'term='+firstname+' '+lastname,
				dataType: "json",
				success: function(data) {
					if(data.result=='error') {
						displayerrors(section,data.errors);
						close_autocomplete();
					} else if(data.result=='success') {
					
						//
						// Build HTML
						var html = '<div id="account_results">';
						html += '<div class="hd_message">In pretium arcu non ipsum lobortis vitae bibendum lacus ullamcorper. Maecenas porta condimentum dui id fermentum. In dignissim aliquam sem, non iaculis lectus tristique et. Etiam pretium est vel odio.</div>';
						html += '<div class="results" style="height: 200px; overflow-x:hidden;overflow-y:auto;"><ul>';
						for(var i=0; i<data.accounts.length; i++) {
							if(data.accounts[i].Fulladdress==null) {
								data.accounts[i].Fulladdress = '&nbsp;';
							}
							html += '<li>';
							html += '  <div class="name">';
							html +=      data.accounts[i].Fullname+'<span>'+data.accounts[i].Customertype+'</span>';
							html += '  </div>';
							html += '  <div class="address">';
							html +=      data.accounts[i].Fulladdress+'&nbsp;';
							html += '  </div>'
							html += '  <div class="select_acct">';
							html +=      '<a href="#'+data.accounts[i].Customercd+'" class="select_account" alt="'+data.accounts[i].Customercd+'">select</a>';
							html += '  </div>';
							html += '  <div class="clear"></div>';
							html += '  <div class="Firstname" style="display: none;">'+data.accounts[i].Firstname+'</div>';
							html += '  <div class="Lastname" style="display: none;">'+data.accounts[i].Lastname+'</div>';
							html += '</li>';
						}
						html += '</ul></div>';
						html += '<div class="not_found">Can\'t find yourself in the list above? <a href="#">Continue without linking account</a>.</div>';
						html += '</div>';

						// Display Overlay/Message
						display_message({ title: 'Locate Account', message: html });
						$('div#message').css('width','680px');
						$('div#message ul li:last').addClass('last');
					
						// Remove Close Button
						$('#message .message').css('margin','0');
						$('#message a.close').remove();						
						
						//
						$('#account_results ul li .select_acct a').click(function() {
							
							// copy in first name
							var firstname = $(this).parent().parent().find('.Firstname').html();
							$('#firstname').val(firstname);
							// copy in last name
							var lastname = $(this).parent().parent().find('.Lastname').html();
							$('#lastname').val(lastname);						 	
						 	// copy member id
						 	$('#memberid').val($(this).attr('alt'));
						 	
							$('div.birthdate').show();
							$('input#loginsearch').hide();
					 		$('div.loginstep2').hide();
					 		$('div.loginstep3').show();
					 		close_messages();
					 		return false;
						});

						//
						$('#account_results .not_found a').click(function() { 
							$('div.birthdate').show();
							$('input#loginsearch').hide();
					 		$('div.loginstep2').hide();
					 		$('div.loginstep3').show();
					 		close_messages();
							return false;
						});
						
						
					}
					$(section).removeData('ajax');
				},
				error: function(msg1,msg2,msg3) {
					$(section).removeData('ajax');
				}
	   		}));



			
			return false;
			
		}
		
		$('.inline-signup #loginsearch').click(function() {
			//inline_signup();
			inline_signup_2012();
			return false;
		});
	 	
	 	$('.inline-signup ul.located_accounts li.result a').live('click',function() {
	 		$('div.birthdate').show();
			$('input#loginsearch').hide();
	 		$('div.loginstep2').hide();
	 		$('div.loginstep3').show();
	 	});
	 	
	 	/**
	 	 * NEW ACCOUNT TRIGGER
	 	 *
	 	 * Clear autocomplete triggers and data on click.
	 	 */
		$('.inline-signup ul.located_accounts li.not_found a').click(function() {
			$(this).parents('.autocomplete').remove();
			$('input#loginsearch').hide();
			$('div.birthdate').hide();
			$('div.loginstep2').hide();
			$('div.loginstep3').show();
			return false;
		});
	 	
	 	/**
	 	 * REGISTRANT VALIDATION
	 	 *
	 	 * Capture form#registrant submission and validate data. If valid, allow form submission.
	 	 * Otherwise display errors and stay on page.
	 	 */
		$('form#registrant').bind('submit',validate_user);
		function validate_user() {
		
			//
			// Get Form
			var form=$('form#registrant');
			
			//
			// Allow Capture of Disabled Fields
			$(form).find('.disabled').removeAttr('disabled');
			
			//
			// Send Data
			$.ajax({
				type: "POST",
				url: "/lookups/validate-user/",
				data: $(form).serialize(),
				dataType: "json",
				success: function(data){
					if(data.result=='error') {
						clearerrors(form);
						displayerrors(form,data.errors);
						highlighterrors(data.fields);
						$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
					} else if(data.result=='success') {
						present_captcha();
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(form,'There was an error connecting to the server. Try again later.');
					$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
				}
	   		});
			
			return false;

		}
		
		function present_captcha() {
			
			var opening_text 	= '<p>Please type the words that you see below to confirm your new web account.</p>';
			var form_open 		= '<form id="captcha_form" name="captcha_form" method="POST" action="?" style="padding: 0; margin: 0;">';
			var captcha 		= '<div id="captcha_container"></div>';
			var submit 			= '<div style="text-align: right; padding: 15px 0 0;"><input type="image" src="/img/btn-complete.png"></div>';
			var form_close 		= '</form>';
			
			// Display Box/Overlay
			display_message({
				title: 'Complete Signup Process',
				message: opening_text + form_open + captcha + submit + form_close
			});
			
			// Place captcha
			place_captcha();
			
			// Bind Submit
			$('form#captcha_form').bind('submit',validate_captcha);
			
			// Remove Close Button
			$('#message .message').css('margin','0');
			$('#message a.close').remove();	
						
		}
		
		function place_captcha() {
		
			Recaptcha.create("6LdrV8gSAAAAAOnIdKoOqhmK7WoFNOAvQFLVfoMr", 'captcha_container', {
             	theme: "clean",
             	callback: Recaptcha.focus_response_field});
             	
		}
		
		function validate_captcha() {
			
			
			$.ajax({
				type: "POST",
				url: "/lookups/validate-captcha/",
				data: $('form#captcha_form').serialize(),
				dataType: "json",
				success: function(data){

					if(data.result == 'success') {
						submit_user();
					} else {
						var message = '<div id="captcha_error" style="color: red; font-weight: bold; padding: 10px 10px 0;">Captcha value is not valid. Please try again.</div>';
						$('#captcha_error').remove();
						$('#message .title').after(message);
					}
					
				},
				error: function(msg1,msg2,msg3) {
					$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
				}
	   		});
	   		
	   		
	   		return false;
			
		}
	
		function submit_user() {
			$('form#registrant').unbind('submit',validate_user).submit();
		}
		
		
		
		
/* ===============================================================================================
	SEARCH OPERATIONS
   ----------------------------------------------------------------------------------------------- */
		
		/**
		 * SEARCH FILTER
		 *
		 * Show / hide main search filter.
		 */
		$('#header .search .filter .selected').click(function() {
			close_search_autocomplete();
			if($(this).parents('.filter').find('.dropdown').is(':hidden')) {
				$(this).removeClass('selected').addClass('open');
				$(this).parents('.filter').find('.dropdown').fadeIn(animate.speed/4);
				$('body').bind('click',close_filter);
			}
			return false;
		});
		
		/**
		 * FILTER SELECTION
		 *
		 * Select filter option.
		 */
		$('#header .search .filter li a').click(function() {
			$(this).parents('ul').find('a.on').removeClass('on');
			$(this).addClass('on');
			$(this).parents('.filter').find('.open span:first').text($(this).text());
			$(this).parents('.filter').find('input').val($(this).text());
			close_filter();
			return false;
		});		
		
		/**
		 * SEARCH AUTOCOMPLETE
		 *
		 * Autocomplete search results.
		 */
		$('#header .search input#string').autocomplete({
			minLength: 2,
			delay: 400,
			search: function(event,ui) {
				
				//
				// Set Variables
				var search=$(this).parents('.search');
   				var autocomplete=$(search).find('div.autocomplete');
   				var keywords = $(this).val();
   				
   				//
   				// Setup Autocomplete List
   				$(autocomplete).show();
   				$('body').bind('click',close_search_autocomplete);
	   			$(autocomplete).find('tr.result').remove().end().find('tr.loading').remove();
	   			$(autocomplete).find('table').prepend('<tr class="loading"><td colspan="2">&nbsp;</td></tr>');
	   			
	   			//
	   			// Stop Previous Ajax Requests
	   			if($(search).data('ajax')!=undefined) $(search).data('ajax').abort();
	   			
	   			//
	   			// Track Search
				ga_track_event('Search','Live',keywords);
				
	   			//
	   			// Retrieve List
		   		$(search).data('ajax',$.ajax({
					type: "POST",
					url: "/search/ajax/",
					data: 'keywords='+keywords+'&type='+$('#header .search .filter .selected').text(),
					dataType: "json",
					success: function(data){
						if(data.result=='success') {
							for(var i=0; i<data.results.length; i++) {
								$(autocomplete).find('.loading').before('<tr class="result"><td class="type">'+data.results[i].type+'</td><td>'+data.results[i].html+'</td></tr>');
							}
							$(autocomplete).find('tr.history').removeClass('hidden').find('td:last').html(data.history);
						}
						$(autocomplete).find('tr.loading').remove();
						$(search).removeData('ajax');
					},
					error: function(msg1,msg2,msg3) {
						$(search).removeData('ajax');
					}
		   		}));
			
				return false;
				
			}
		}).keyup(function() {
			var search = $(this).parents('.search');
			if($(this).val().length<3&&$(search).data('ajax')!=undefined) {
				$(search).data('ajax').abort();
			}
		});
		
		/**
		 * CLOSE SEARCH AUTOCOMPLETE
		 *
		 * Close search autocomplete dropdown.
		 */
		function close_search_autocomplete() {
			$('#header .search .autocomplete').hide();
		}
		
		/**
		 * CLOSE FILTER
		 *
		 * Close search filter.
		 */
		function close_filter() {
			$('#header .search .filter a:first').removeClass('open').addClass('selected');
			$('#header .search .filter .dropdown:visible').fadeOut(animate.speed/4);
			$('body').unbind('click',close_filter);
		}
			

/* ===============================================================================================
	HOMEPAGE OPERATIONS
   ----------------------------------------------------------------------------------------------- */
		
		/**
		 * HOMEPAGE FEATURES ELEMENT
		 *
		 * Setup special actions for homepage features zone.
		 */
		$('.homepage #features').each(function() {
		
			//
			// Initial Setup
			$(this).data('current',1);
			$(this).data('to',1);
			$(this).data('total',$(this).find('.slides li').length);
		
			//
			// Thumbnail Item Hover
			$(this).find('.thumbs li').hover(function() {
				$(this).addClass('hover');
			},function() {
				$(this).removeClass('hover');
			});
			
			//
			// Thumbnails Show
			$(this).find('.thumbs a.control').hover(function() {
				if(!$(this).parents('.thumbs').hasClass('open')) {
					$(this).parents('.thumbs').addClass('open').stop().animate({left:0},animate.speed,animate.easing);
				}
				return false;
			},function() {});
			
			//
			// Thumbnails Hide
			$(this).find('.thumbs').hover(function() {},function() {
				$(this).removeClass('open').stop().animate({left:'-214px'},animate.speed,animate.easing);
			});
			
			//
			// Thumbnail Item Selection
			$(this).find('.thumbs li a').click(function() {
				var obj=$(this).parents('#features');
				$(obj).data('to',$(this).attr('href'));
				go_to_slide(obj,'direct');
				return false;
			});
			
			//
			// Slider Controls
			$(this).find('a.previous').click(previous_slide);
			$(this).find('a.next').click(next_slide);
			
			//
			// Next Action
			function next_slide(e) {
				var parent=$(e.target).parents('#features');
				var current=$(parent).data('current');
				var total=$(parent).data('total');
				current++;
				if(current>total) current=1;
				$(parent).data('to',current);
				go_to_slide(parent,'next');
				ga_track_event('Homepage','Slide Next',current);
				return false;
			}
			
			//
			// Previous Action
			function previous_slide(e) {
				var parent=$(e.target).parents('#features');
				var current=$(parent).data('current');
				var total=$(parent).data('total');
				current--;
				if(current<1) current=total;
				$(parent).data('to',current);
				go_to_slide(parent,'previous');
				ga_track_event('Homepage','Slide Previous',current);
				return false;
			}
			
			//
			// Slide Change Method
			function go_to_slide(obj,direction) {
				var from=$(obj).data('current');
				var to=$(obj).data('to');
				var slides=$(obj).find('.slides li');
				var width=$(slides[0]).width();
				$(slides).stop().show().css({left:'-2000px'});
				$(slides[from-1]).css({left:0});
				if(direction=='previous') {
					$(slides[to-1]).css({left:-width+'px'}).stop().animate({left:0},animate.speed*2,animate.easing);
					$(slides[from-1]).stop().animate({left:width+'px'},animate.speed*2,animate.easing);
				} else if(direction=='next') {
					$(slides[to-1]).css({left:width+'px'}).stop().animate({left:0},animate.speed*2,animate.easing);
					$(slides[from-1]).stop().animate({left:-width+'px'},animate.speed*2,animate.easing);
				} else {
					$(slides[from-1]).css({left:'-2000px'});
					$(slides[to-1]).css({left:0});
				}
				$(obj).find('.thumbs .selected').removeClass('selected').find('img').css({opacity:1});
				$(obj).find('.thumbs li:eq('+(to-1)+')').addClass('selected').find('img').css({opacity:0.5});
				$(obj).data('to',0);
				$(obj).data('current',to);
			}
			
			go_to_slide(this,'direct');
			homepage_banner_timeout = setTimeout(rotate_homepage_banner,7000);
		
		}).hover(function() {
			clearTimeout(homepage_banner_timeout);
			homepage_banner_timeout = null;
		},function() {
			homepage_banner_timeout = setTimeout(rotate_homepage_banner,7000);
		});


/* ===============================================================================================
	FILTERS OPERATIONS
   ----------------------------------------------------------------------------------------------- */
		
		/**
		 * FILTER BY LINK
		 *
		 * Open filters element.
		 */
		$('a.filter_by').click(function() {
			$(this).hide();
			$(this).prev('.filters').fadeIn(animate.speed,animate.easing);
			return false;
		});
		
		/**
		 * APPLY FILTERS
		 *
		 * Apply filters to feed elements.
		 */
		$('.filters a.apply_filters').click(apply_filters);
		$('.filters .btn.app').click(apply_filters);
		$('.filters .apply .close').click(apply_filters);
		function apply_filters() {
		
			//
			// Apply Filters
			$("input[name='cma_feed_info']").data('page',1);
			update_feeds();
			
			//
			// Update Filter By Button
			update_filter_count();
				
			return false;
			
		}
					
		/**
		 * RESET POLICY FILTERS
		 *
		 */
		$('.filters .btn.reset').click(reset_policy_filters); 
		function reset_policy_filters() {
			//
			$('#year, #area_of_interest, #refined_area, #keyword').val('');
			//
			$('div.applied ul').html('');
			//
			update_filter_count();
			return false;				
		}
		
		/**
		 * UPDATE FEEDS
		 *
		 * Find all feeds on page and update them.
		 */
		function update_feeds() {
			
			update_filter_count();

			var filters = '';
			
			//
			// Area Filters
			var areas = $("input[name='areas_applied']");
			filters += 'areas[';
			for(var i=0; i<areas.length; i++) {
				if(i!=0) filters += ',';
				filters += $(areas[i]).val();
			}
			filters += ']';
			
			//
			// Keyword Filters
			var keywords = $("input[name='keywords_applied']");
			filters += '|keywords[';
			for(var i=0; i<keywords.length; i++) {
				if(i!=0) filters += ',';
				filters += $(keywords[i]).val();
			}
			filters += ']';

			//
			// Society Filters - bwhitman - 2011-04-06 - add society to filter set
			var society = '';
			if($("input[name='society']").length)
				society = $("input[name='society']").val();

			//
			// Date Filters
			var date = '';
			if($("input[name='start_date']").length)
				date = $("input[name='start_date']").val()+"||"+$("input[name='end_date']").val();

			//
			// Year Filters
			var year = '';
			if($("select[name='year']").length)
				year = $("select[name='year']").val();
			
			//
			// Event Type Filter
			var event_type = '';
			if($("select[name='event_type']").length)
				event_type = $("select[name='event_type']").val();
			
			//
			// Location Filters
			var filter_location = '';
			if($("input[name='filter_location']").length&&$("input[name='filter_location']").val()!=$("input[name='filter_location']").attr('title'))
				filter_location = $("input[name='filter_location']").val();
			
			//
			// Sub Search
			var search='';
			if($("input.feed_search_string").length&&$("input.feed_search_string").val()!=$("input.feed_search_string").attr('title'))
				search = $("input.feed_search_string").val();
			
			//
			// Category
			var category='';
			if($("select.feed_category").length&&$("select.feed_category").val().length)
				category = $("select.feed_category").val();

			//
			// Criteria
			var criteria=$("input[name='criteria']:checked").val();
			if($("select.feed_category").length&&$("select.feed_category").val().length)
				criteria = $("input[name='criteria']:checked").val();
			
			//
			// Update Feeds
			var feed_info = $("input[name='cma_feed_info']");
			for(var i=0; i<feed_info.length; i++) {
			
				//
				// Show Loading
				$(feed_info[i]).prev('.feed').append('<div class="feed_loading"></div>').find('.feed_loading').css({opacity: 0.5});
			
				//
				// Re-enable Feed
				$(feed_info[i]).removeData('disabled');
				
				//
				// Sort Order
				var sortby = $(feed_info[i]).data('sortby');
				if(sortby==undefined||sortby==null) sortby='';
				var sortorder = $(feed_info[i]).data('sortorder');
				if(sortorder==undefined||sortorder==null) sortorder='';
				
				//
				// Save Paramters
				$(feed_info[i]).data('filters',filters).data('date',date).data('event_type',event_type).data('location',location).data('search',search);

				//
				// Build Tracking Event
				var ga_label = 'page='+$(feed_info[i]).data('page');
				if(sortby.length>0) ga_label+='&sortby='+sortby;
				if(sortorder.length>0) ga_label+='&sortorder='+sortorder;
				if(filters.length>0) ga_label+='&filters='+filters;
				if(date.length>0) ga_label+='&date='+date;
				if(year.length>0) ga_label+='&year='+year;
				if(event_type.length>0) ga_label+='&event_type='+event_type;
				if(filter_location.length>0) ga_label+='&location='+filter_location;
				if(search.length>0) ga_label+='&search='+search;
				if(category.length>0) ga_label+='&category='+category;
				ga_track_event($(feed_info[i]).data('url'),'Filter',ga_label);
				
				//trace("page="+$(feed_info[i]).data('page')+"&sortby="+sortby+"&sortorder="+sortorder+"&filters="+filters+"&date="+date+"&year="+year+"&event_type="+event_type+"&location="+filter_location+"&search="+search+"&category="+category+"&society="+society+"&criteria="+criteria);
				
				$.ajax({
					type: "POST",
					url: $(feed_info[i]).data('url'),
					data: "page="+$(feed_info[i]).data('page')+"&sortby="+sortby+"&sortorder="+sortorder+"&filters="+filters+"&date="+date+"&year="+year+"&event_type="+event_type+"&location="+filter_location+"&search="+search+"&category="+category+"&society="+society+"&criteria="+criteria,
					dataType: "json",
					success: function(data) {
					
						//
						// Update Feed
						$(this).prev('.feed').html('');
						for(var j=0; j<data.results.length; j++)
							$(this).prev('.feed').append(data.results[j]);
						
						align_store_feed();
						
						//
						// Set Message
						if(data.results.length==0)
							$(this).prev('.feed').html('<p class="empty">No results match your selected filters, please try broadening your search.</p>');
						
						//
						// Takeover Pagination Elements
						if(data.pagination!=undefined&&data.pagination!=null) {
							if(data.pagination.length>0) {
								$('div.paginate').replaceWith(data.pagination);
							} else {
								$('div.paginate').html('');
							}
							$('div.paginate a').click(paginate_feed);
						}
						
						//
						// Takeover Order Elements
						if(data.order!=undefined&&data.order!=null) {
							$('div.order').replaceWith(data.order);
							$('div.order a').click(order_feed);
						}
						
					},
					context: feed_info[i]
		   		});
		   	}
		   	
			$('div.filters').hide().next('a.filter_by').show();
			return false;
			
		}
		
		/**
		 * PAGINATE FEED
		 *
		 * Paginate current feed on click.
		 */
		function paginate_feed() {
			var href = $(this).attr('href');
			var page = href.match(/page=([0-9]+)/i)[1];
			$(this).parents('.feed_container').find("input[name='cma_feed_info']").data('page',page);
			update_feeds();
			return false;
		}
		
		/**
		 * ORDER FEED
		 *
		 * Order current feed on click. (go to page 1)
		 */
		function order_feed() {
			var href = $(this).attr('href');
			var sortby = href.match(/sortby=([a-zA-Z0-9-_]+)/i)[1];
			var sortorder = href.match(/sortorder=([a-zA-Z0-9-_]+)/i)[1];
			$(this).parents('.feed_container').find("input[name='cma_feed_info']").data('page',1).data('sortby',sortby).data('sortorder',sortorder);
			update_feeds();
			return false;
		}
		
		/**
		 * FEED SEARCH
		 *
		 * Handle feed search submit click.
		 */
		$('input.feed_search_button').click(function() {
			$("input[name='cma_feed_info']").data('page',1);
			update_feeds();
			return false;
		});
		
		/**
		 * FEED SEARCH INPUT
		 *
		 * Handle feed search enter key press.
		 */
		$('input.feed_search_string').keypress(function(event) {
			if (event.which=='13') {
    			$("input[name='cma_feed_info']").data('page',1);
    			update_feeds();
    			return false;
    		}
		});
		
		/**
		 * FEED RESET
		 *
		 * 
		 */
		$('a#sub_reset').click(function() { 
			reset_policy_feed();
			return false;
		});
		function reset_policy_feed() {
			$('#sub_search_string').val('');
			reset_policy_filters();
			update_feeds();
		}
			
		/**
		 * AREA OF INTEREST SELECT
		 *
		 * Populate select#refined_area on selection of an area of interest.
		 */
		$('div.filters select#area_of_interest').change(function() {
		
			var children = $(this).find('option:selected').data('children');
			var refined_area = $('div.filters select#refined_area');
			$(refined_area).html('<option value=""></option>');
			
			if(children!=null)
				for(var i=0; i<children.length; i++)
					$(refined_area).append('<option value="'+children[i].id+'">'+children[i].area+'</option>');
		
		});
			
		/**
		 * AREA OF INTEREST ADD
		 *
		 * Add selected area of interest / refined area to applied filters.
		 */
		$('div.filters a.add_area').click(function() {
			
			var refined_area_id = $('select#refined_area').val();
			var area_id = $('select#area_of_interest').val();
			var applied = $(this).next('.applied');
			
			if(refined_area_id!=undefined&&refined_area_id!=null&&refined_area_id.length>0) {
				var refined_area = $('select#refined_area').find('option:selected').text();
				$(applied).find('ul').append('<li>'+refined_area+'<input type="hidden" name="areas_applied" value="'+refined_area_id+'" /><a href="#" class="remove"><span><span class="sprite x">x</span></span></a></li>');
			} else if(area_id!=undefined&&area_id!=null&&area_id>0) {
				var area = $('select#area_of_interest').find('option:selected').text();
				$(applied).find('ul').append('<li>'+area+'<input type="hidden" name="areas_applied" value="'+area_id+'" /><a href="#" class="remove"><span><span class="sprite x">x</span></span></a></li>');
			}
			
			$('select#area_of_interest').find('option:selected').removeAttr('selected').end().find('option:first').attr('selected','selected').change();
		
			return false;
		
		});
		
		/**
		 * APPLIED ITEM SETUP
		 *
		 * Setup applied filter items.
		 */
		$('div.filters div.applied li').each(function() {
			$(this).append('<a href="#" class="remove"><span><span class="sprite x">x</span></span></a>');
		});
		
		/**
		 * APPLIED ITEM HOVER
		 *
		 * Setup hover for applied filter items.
		 */
		$('div.filters div.applied li').live('hover',function(event) {
		    if(event.type == 'mouseenter') {
			    $(this).addClass('hover');
			} else {
			    $(this).removeClass('hover');
			}
		});
		
		/**
		 * APPLIED ITEM REMOVE
		 *
		 * Remove clicked applied filter.
		 */
		$('div.filters div.applied a.remove').live('click', function(event) {
			$(this).parents('li').remove();
			return false;
		});
		
		/**
		 * KEYWORD AUTOCOMPLETE
		 *
		 * Setup autocomplete for keyword filter input.
		 */		   	
		$('div.filters input#keyword').autocomplete({
			delay: 300,
			search: function(event,ui) {
				
				//
				// Set Variables
				var filters=$(event.target).parents('.filters');
   				var list=$(filters).find('div.autocomplete ul');
   				
   				//
   				// Setup Autocomplete List
   				$(filters).find('div.autocomplete').show();
	   			$(list).css({height:'auto'}).find('li.result').remove().end().find('li.loading').remove();
	   			$(list).append('<li class="loading">&nbsp;</li>');
	   			
	   			//
	   			// Stop Previous Ajax Requests
	   			if($(filters).data('ajax')!=undefined) $(filters).data('ajax').abort();
	   			
	   			//
	   			// Track Event
				ga_track_event('Keyword','Lookup',$(this).val());
				
	   			//
	   			// Retrieve List
		   		$(filters).data('ajax',$.ajax({
					type: "POST",
					url: "/lookups/keyword/",
					data: 'term='+$(this).val(),
					dataType: "json",
					success: function(data){
						$(list).find('.loading').remove();
						for(var i=0; i<data.length; i++)
							$(list).append('<li class="result"><a href="#" onclick="return select_keyword(\''+data[i].keyword+'\','+data[i].id+');">'+data[i].keyword+'</a></li>');
						$(filters).removeData('ajax');
					},
					error: function(msg1,msg2,msg3) {
						$(filters).removeData('ajax');
					}
		   		}));
			
				return false;
				
			}
		}).keyup(function() {
			var filters=$(this).parents('.filters');
			if($(this).val().length<3&&$(filters).data('ajax')!=undefined) {
				$(filters).data('ajax').abort();
			}
		}).click(function() {
			var autocomplete = $(this).parents('.filters').find('div.autocomplete');
			if($(autocomplete).is(':hidden')) {
				$(autocomplete).show();
				$('body').bind('click',close_autocomplete);
			}
			return false;
		});
			
			
/* ===============================================================================================
	POST CLASSIFIED
   ----------------------------------------------------------------------------------------------- */

		/**
		 * UPDATE TOTALS
		 *
		 * Update totals with user selections on Post Job Step 1: Details
		 */
		function update_job_totals(e) {
			
			//
			// Get Price
			var listingtype = $("input[name='listingtype']:checked");
			var price = $(listingtype).parent().next('.price').find('strong:first').data('price');
			
			//
			// Featured
			var featured = $("input[name='featured']:checked").data('price');
			if(featured==undefined||featured==null) featured=0;
			
			//
			// Update Subtotal
			var subtotal = parseFloat(price) + parseFloat(featured);
			
			if(subtotal>0)
				$('strong.subtotal').html('$'+subtotal+' <span>per month</span>');
			else
				$('strong.subtotal').html('FREE');
			
			//
			// Months
			var months = $("select[name='months']").val();
			if(months==undefined||months==null) months = 1;
			
			//
			// Update Total
			var total = parseInt(months) * parseFloat(subtotal);
			if(total>0)
				$('strong.total').html('$'+total);
			else
				$('strong.total').html('FREE');
			
		}
		
		/**
		 * TYPE CHANGE
		 *
		 * Show / Hide Specialty based on Type selection
		 */
		$('.jobs select#type').change(function() {
			if($(this).val()=='classified') {
				$('.jobs div.specialty').hide();
			} else {
				$('.jobs div.specialty').show();
			}
		});
		
		/**
		 * UPDATE TRIGGERS
		 *
		 * Trigger job update_job_totals for various elements.
		 */
		$(".jobs .step_1 form input[name='listingtype']").click(update_job_totals);
		$(".jobs .step_1 form input[name='featured']").click(update_job_totals);
		$(".jobs .step_1 form select[name='months']").change(update_job_totals);
		
		/**
		 * VALIDATE INFORMATION
		 *
		 * Validate Step 2: Information on submit.
		 */
		$('.jobs .step_2 form#information').bind('submit',submit_post_information);
		function submit_post_information() {
		
			//
			// Get Form
			var form=$('form#information');
		
			//
			// Allow Serialization of Disabled Fields
			$(form).find('.disabled').removeAttr('disabled');
			
			//
			// Validate Data
			$.ajax({
				type: "POST",
				url: "/classifieds/post/validate-information/",
				data: $(form).serialize(),
				dataType: "json",
				success: function(data){
					if(data.result=='error') {
						clearerrors(form);
						displayerrors(form,data.errors);
						highlighterrors(data.fields);
						$(form).find('input.text').blur().end().find('textarea').blur().end().find('.disabled').attr('disabled','disabled');
					} else if(data.result=='success') {
						$(form).unbind('submit',submit_post_information).submit();
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(form,'There was an error connecting to the server. Try again later.');
					$(form).find('input.text').blur().end().find('textarea').blur().end().find('.disabled').attr('disabled','disabled');
				}
	   		});
	   		
			return false;

		}
		
		/**
		 * PUBLISH DATE
		 *
		 * Manual publish date actions.
		 */
		$('.jobs .step_2 select#publish').change(function() {
			if($(this).val()=='date')
				$(this).next('div.pub_date').removeClass('hidden');
			else
				$(this).next('div.pub_date').addClass('hidden');
		}).change();
		
		/**
		 * CATEGORIES POPUP
		 *
		 * Display popup message box listing categories.
		 */
		$('.popup-categories').click(function() {
			$.ajax({
				type: "POST",
				url: "/lookups/classifieds-categories/",
				dataType: "json",
				success: function(data){
					var categories = '';
					for(var i=0; i<data.length; i++)
						categories += '<li>'+data[i].title+'</li>';
					display_message({
						title: 'Classifieds Categories',
						message: '<ul class="singlespace">'+categories+'</ul>'
					});
				}
	   		});
			return false;
		});


/* ===============================================================================================
	CHECKOUT OPERATIONS
   ----------------------------------------------------------------------------------------------- */
	
		/**
		 * BILLING AS SHIPPING
		 *
		 * Show / hide shipping elements.
		 */
		$('input#copybilling').change(function() {
			if($(this).attr('checked')) {
				$(this).parent().find('div.shipping').hide();
			} else {
				$(this).parent().find('div.shipping').show();
			}
		}).change();
		
		/**
		 * CALIFORNIA CITY SELECT
		 *
		 */
		$('.checkout select#billingstate, .checkout select#shippingstate').change(function() {
			
			var $this = $(this);
			var state = $(this).val().toUpperCase();
			
			//
			// Replace city element for CA selections
			if( state == 'CA' || state == 'CALIFORNIA' ) {
			
				//
				// Get cities
				$.ajax({
					type: "GET",
					url: "/lookups/cities",
					dataType: 'json',
					success: function(data) {
						
						var city = $this.prev('input').val();
						if( city == 'City' ) city = '';
						
						var select = $('<select name="' + $this.prev('input').attr('name') + '" id="' + $this.prev('input').attr('id') + '" />');
						select.append('<option value="">City</option><option disabled="disabled">-----------------</option><option value="other">My city is not listed</option><option disabled="disabled">-----------------</option>');
						for( var i=0; i<data.length; i++) {
							if(data[i].toLowerCase()==city.toLowerCase()) {
								select.append('<option selected="selected">' + data[i] + '</option>');
							} else {
								select.append('<option>' + data[i] + '</option>');
							}
						}
						
						select.change(function() {
							if( $(this).val()=='other' ) {
								$(this).replaceWith('<input type="text" name="' + $(this).attr('name') + '" id="' + $(this).attr('id') + '" value="City" class="text" />');
							}
						});
						
						$this.prev('input').replaceWith(select);
						
					}
				});
			
			} else {
			
				
			
			}
			
		});
		$('.checkout select#billingstate, .checkout select#shippingstate').change();
	   
	  	/**
	  	 * UPDATE SUBTOTAL
	  	 *
	  	 * Update quantities and retrieve subtotal from current cart object.
	  	 */
	   	$('.checkout table a.update_subtotal').click(function() {
	   
	   		//
	   		// Set Variables
	   		var items = $('table tr.item');
	   		var quantities = '';
	   		var table = $(this).parents('table');
	   		
	   		//
	   		// Build Quantities List
	   		for(var i=0; i<items.length; i++)
	   			quantities += '['+$(items[i]).attr('itemid')+':'+$(items[i]).find('input.qty').val()+']';
			
			//
			// Retrieve Subtotal
			$.ajax({
				type: "POST",
				url: checkout_url+"/qty/",
				data: "quantities="+quantities,
				dataType: "json",
				success: function(data){
					if(data.result=='error') {
						displayerrors(table,'There was an error updating the cart. Please try again.');
					} else {
						clearerrors(table);
						$(items).addClass('pending');
						for(var i=0; i<data.items.length; i++)
							$('.checkout table tr[itemid='+data.items[i].id+']').removeClass('pending').find('input.qty').val(data.items[i].qty).end().find('td:last').text('$'+data.items[i].total);
						$('.checkout table tr.pending').remove();
						$('.checkout table .subtotal').text(data.subtotal);
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(table,'There was an error connecting to the server. Try again later.');
				}
	   		});
	   		
	   		return false;
	   	
	   	});
	   
	   	/**
	   	 * REMOVE CART ITEM
	   	 *
	   	 * Remove item from cart, and get new subtotal.
	   	 */
	   	$('.checkout table a.remove').click(function() {
			
			//
			// Set Variables
			var table = $(this).parents('table');
			var tr = $(this).parents('tr');
			
			//
			// Remove and Retrieve Subtotal
			$.ajax({
				type: "POST",
				url: checkout_url+"/qty/",
				data: "quantities=["+$(tr).attr('itemid')+":0]",
				dataType: "json",
				success: function(data){
					if(data.result=='error') {
						displayerrors(table,'There was an error updating the cart. Please try again.');
					} else {
						clearerrors(table);
						$(tr).remove();
						$('.checkout table .subtotal').text(data.subtotal);
						if($(table).find('tr.item').length==0)
							location.reload();
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(table,'There was an error connecting to the server. Try again later.');
				}
	   		});
	   			   		
	   		return false;
	   	
	   	});
	   
	   	/**
	   	 * VALIDATE CUSTOMER
	   	 *
	 	 * Capture form#customer submission and validate data. If valid, allow form submission.
	 	 * Otherwise display errors and stay on page.
	 	 */
		$('.checkout form#customer').bind('submit',submit_customer);
		function submit_customer() {
		
			//
			// Get Form
			var form=$('form#customer');
		
			//
			// Allow Serialization of Disabled Fields
			$(form).find('.disabled').removeAttr('disabled');
			
			//
			// Validate Data
			$.ajax({
				type: "POST",
				url: checkout_url+"/validate-customer/",
				data: $(form).serialize(),
				dataType: "json",
				success: function(data){
					if(data.result=='error') {
						clearerrors(form);
						displayerrors(form,data.errors);
						highlighterrors(data.fields);
						$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
					} else if(data.result=='success') {
						$(form).unbind('submit',submit_customer).submit();
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(form,'There was an error connecting to the server. Try again later.');
					$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
				}
	   		});
	   		
			return false;

		}
	   
	   	/**
	   	 * VALIDATE PAYMENT
	   	 *
	 	 * Capture form#payment submission and validate data. If valid, allow form submission.
	 	 * Otherwise display errors and stay on page.
	 	 */
		$('.checkout form#payment').bind('submit',submit_payment);
		function submit_payment() {
		
			//
			// Get Form
			var form=$('form#payment');
			
			//
			// Allow Serialization of Disabled Fields
			$(form).find('.disabled').removeAttr('disabled');
			
			//
			// Validate Data
			$.ajax({
				type: "POST",
				url: checkout_url+"/validate-payment/",
				data: $(form).serialize(),
				dataType: "json",
				success: function(data){
					if(data.result=='error') {
						clearerrors(form);
						displayerrors(form,data.errors);
						highlighterrors(data.fields);
						$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
					} else if(data.result=='success') {
						$(form).find('#place_your_order').attr('disabled','disabled').css({opacity:'0.5'});
						$(form).find('#submit').attr('disabled','disabled').css({opacity:'0.5'});
						$(form).unbind('submit',submit_payment).submit();
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(form,'There was an error connecting to the server. Try again later.');
					$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
				}
	   		});
	   		
			return false;

		}


/* ===============================================================================================
	ADVERTISING
   ----------------------------------------------------------------------------------------------- */

		/**
		 * ADVERTISING FORM
		 *
		 * Capture advertising form submission and validate data.
		 */
		$('form#advertisingform').bind('submit',advertising_form);
		function advertising_form() {
		
			//
			// Get Form
			var form=this;
			
			//
			// Allow Serialization of Disabled Fields
			$(form).find('.disabled').removeAttr('disabled');
			
			//
			// Validate Data
			$.ajax({
				type: "POST",
				url: "/advertising/process/",
				data: $(form).serialize(),
				dataType: "json",
				success: function(data){
					if(data.result=='error') {
						clearerrors(form);
						displayerrors(form,data.errors);
						highlighterrors(data.fields);
						$(form).find('input.text').blur().end().find('textarea').blur().end().find('.disabled').attr('disabled','disabled');
					} else if(data.result=='success') {
						clearform(form);
						display_message({
							title: 'Thank You',
							message: data.message
						});
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(form,'There was an error connecting to the server. Try again later.');
					$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
				}
	   		});
	   		
			return false;
		
		}
		
		/**
		 * CLICK TRACKING
		 *
		 * Track advertising clicks in google analytics.
		 */
		$('div#sidebar div.ad a').click(function() {
			ga_track_event('ads','clicks',$(this).data('eventname'));
		});


/* ===============================================================================================
	SHARE
   ----------------------------------------------------------------------------------------------- */

		/**
		 * SHARE FORM
		 *
		 * Capture advertising form submission and validate data.
		 */
		$('form#shareform').bind('submit',share_form);
		function share_form() {
		
			//
			// Get Form
			var form=this;
			
			//
			// Allow Serialization of Disabled Fields
			$(form).find('.disabled').removeAttr('disabled');
			
			//
			// Validate Data
			$.ajax({
				type: "POST",
				url: "/share/process",
				data: $(form).serialize(),
				dataType: "json",
				success: function(data){
					if(data.result=='error') {
						clearerrors(form);
						displayerrors(form,data.errors);
						highlighterrors(data.fields);
						$(form).find('input.text').blur().end().find('textarea').blur().end().find('.disabled').attr('disabled','disabled');
					} else if(data.result=='success') {
						ga_track_event('Share','Success');
						clearform(form);
						display_message({
							title: 'Thank You',
							message: data.message
						});
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(form,'There was an error connecting to the server. Try again later.');
					$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
				}
	   		});
	   		
			return false;
		
		}
		
		/**
		 * BOTTOM SHARE HOVER
		 *
		 * Show / hide bottom share popup.
		 */
		$('.content_footer .share').hover(function() {
		    if(bottomsharetimeout != null) { clearTimeout(bottomsharetimeout); bottomsharetimeout = null; return; }
			$(this).find('.share_popup').fadeIn(animate.speed/4);
		},function() {
		    if(bottomsharetimeout == null)
			    bottomsharetimeout = setTimeout(fadeout_bottom_share,animate.speed);
		});
		$('.content_footer .share .share_popup').hover(function() {
		    if(bottomsharetimeout != null) { clearTimeout(bottomsharetimeout); bottomsharetimeout = null; return; }
		},function() {});
		
		/**
		 * TOP SHARE HOVER
		 *
		 * Show / hide popup taken from bottom share element.
		 */
		$('.top_share').hover(function() {
		    if(topsharetimeout != null) { clearTimeout(topsharetimeout); topsharetimeout = null; return; }
			$(this).append($('.share_popup').clone(true));
			$(this).find('.share_popup').fadeIn(animate.speed/4);
		},function() {
		    if(topsharetimeout == null)
			    topsharetimeout = setTimeout(fadeout_top_share,animate.speed);
		});


/* ===============================================================================================
	CONTACT
   ----------------------------------------------------------------------------------------------- */

		/**
		 * DEPARTMENTS CHANGE
		 *
		 * Load contacts for department on change event.
		 
		$('.contact select#department').change(function() {
			$.ajax({
				type: "POST",
				url: "/contact/contacts",
				data: "department="+$(this).val(),
				dataType: "json",
				success: function(data){
					$('.contact .departments .contacts').html(data.contacts);
					update_contact_map();
				}
	   		});
		
		});*/

		/**
		 * CONTACT FORM
		 *
		 * Capture contact form submission and validate data.
		 */
		$('form#contactform').bind('submit',contact_form);
		function contact_form() {
		
			//
			// Get Form
			var form=this;
			
			//
			// Allow Serialization of Disabled Fields
			$(form).find('.disabled').removeAttr('disabled');
			
			//
			// Validate Data
			$.ajax({
				type: "POST",
				url: "/contact/process/",
				data: $(form).serialize(),
				dataType: "json",
				success: function(data){
					if(data.result=='error') {
						clearerrors(form);
						displayerrors(form,data.errors);
						highlighterrors(data.fields);
						$(form).find('input.text').blur().end().find('textarea').blur().end().find('.disabled').attr('disabled','disabled');
					} else if(data.result=='success') {
						ga_track_event('Contact','Success');
						clearform(form);
						display_message({
							title: 'Thank You',
							message: data.message
						});
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(form,'There was an error connecting to the server. Try again later.');
					$(form).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
				}
	   		});
	   		
			return false;
		
		}
		

/* ===============================================================================================
	ALERTS
   ----------------------------------------------------------------------------------------------- */
		
		/**
		 * TRIGGER ALERTS
		 *
		 * Global add to alerts handler.
		 */
		$('.trigger-alerts').live('click',function() {
			
			var table = $(this).data('table');
			var id = $(this).data('id');
			var uid = $(this).data('uid');
			
			if(uid==undefined||uid==null||uid==0) {
				display_message({
					title: 'Login Required',
					message: 'You must be logged in to add an alert. You may log in at any time using the login option at the top of the page. If you are a new user, you will first need to <a href="/users/register/">register</a>.'
				});
			} else if(table!=undefined&&table!=null&&id!=undefined&&id!=null) {
			
				$.ajax({
					type: "POST",
					url: "/alerts/add/",
					data: "uid="+uid+"&table="+table+"&id="+id,
					dataType: "json",
					success: function(data){
						ga_track_event('Alerts','Subscribed',"uid="+uid+"&table="+table+"&id="+id);
						display_message({
							title: data.title,
							message: data.message
						});
					},
					error: function(msg1,msg2,msg3) {
						display_message({
							title: 'Error',
							message: 'The alert could not be added. Please try again later.'
						});
					}
		   		});
			
			}
			
			return false;
			
		});


/* ===============================================================================================
	SOCIETIES
   ----------------------------------------------------------------------------------------------- */
	
		/**
		 * MAP LIST SELECT
		 *
		 * Go to detail page upon selection of item from list on map page.
		 */
		$('.societies select#select_society').change(function() {
			if($(this).val().length) {
				location.href = $(this).val();
			}
		});
		

/* ===============================================================================================
	EVENT REGISTRATION OPERATIONS
   ----------------------------------------------------------------------------------------------- */
	   	
	   	/**
	   	 * ADD ATTENDEE
	   	 *
	   	 * Attempt to add attendee to current registration. If valid, add to registrant list and update
	   	 * registration totals. Otherwise, display errors.
	   	 */
	   	$('.events form#attendee').submit(function() {
	   	
	   		//
	   		// Get Form
			var form=this;
	   	
	   		//
	   		// Allow Serialization of Disabled Fields
	   		$(this).find('.disabled').removeAttr('disabled');
			
			//
			// Validate Data
	   		$.ajax({
				type: "POST",
				url: "/events/register/add-attendee/",
				data: $(this).serialize(),
				dataType: "json",
				success: function(data){
					clearerrors(form);
					if(data.result=='error') {
						displayerrors(form,data.errors);
						highlighterrors(data.fields);
					} else if(data.result=='success') {
						$('div#attendees').show().find('table tr.total').before(data.tr);
						clearform(form);
						update_registration_totals(data);
						update_registration_status();
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(form,'There was an error connecting to the server. Try again later.');
				}
	   		});
	   		
	   		//
	   		// Restore Disabled Fields and Trigger Input Blurs
	   		$(this).find('input.text').blur().end().find('.disabled').attr('disabled','disabled');
	   		
	   		//
	   		// Check capacity
	   		$.getJSON('/events/register/capacity', function(data) {
				var cut_off = false;
				if (data.capacity>0 && data.available<1) {
					// Turn off	
					cut_off = true;					
				} 
				
				if (cut_off) {
					$('#cap_error').show();
					$('form#attendee .section.add_attendee').hide();
					$('form#attendee .section.primary_attendee').hide();
				}
	
			});
	   		
	   		return false;
	   		
	   	});
	   	
	   	/**
	   	 * REMOVE ATTENDEE
	   	 *
	   	 * Remove attendee from current registration, update registrant list and update totals.
	   	 */
	   	$('.events div#attendees a.remove').live('click',function() {
	   		var link=this; var table=$(link).parents('table');
	   		$.ajax({
				type: "POST",
				url: "/events/register/remove-attendee/",
				data: 'href='+$(this).attr('href'),
				dataType: "json",
				success: function(data){
					clearerrors(table);
					if(data.result=='error') {
						displayerrors(table,data.errors);
					} else if(data.result=='success') {
						$(link).parents('tr').remove();
						update_registration_totals(data);
						update_registration_status();
					}
				},
				error: function(msg1,msg2,msg3) {
					displayerrors(table,'There was an error connecting to the server. Try again later.');
				}
	   		});
	   		return false;
	   	});
	   	
	   	/**
	   	 * ATTENDEE SEARCH AUTOCOMPLETE
	   	 *
	   	 * Setup autocomplete for input#attendee_search element.
	   	 */
	   	$('.attendee_search input#attendee_search').autocomplete({
			minLength: 5,
			delay: 750,
			search: function(event,ui) {
			
				//
				// Check First and Last Name
				var split = $(this).val().split(' ');
				if(split[0]!=undefined&&split[0].length>=2&&split[1]!=undefined&&split[1].length>=2) {
			
					//
					// Set Variables
					var section=$(event.target).parents('.section');
	   				var list=$(section).find('ul.located_accounts');
					
					//
					// Clear Previous Errors
					clearerrors(section);
	   				
	   				//
	   				// Setup Autocomplete List
	   				$(section).find('div.autocomplete').show();
		   			$(list).css({height:'auto'}).find('li.result').remove().end().find('li.loading').remove();
		   			$(list).find('li.not_found').before('<li class="loading">&nbsp;</li>');
		   			
		   			//
		   			// Stop Previous AJAX Requests
		   			if($(section).data('ajax')!=undefined) $(section).data('ajax').abort();
		   			
		   			//
		   			// Track Event
		   			ga_track_event('Event Registration','Attendee Search',$(this).val());
		   			
		   			//
		   			// Retrieve List
			   		$(section).data('ajax',$.ajax({
						type: "POST",
						url: "/lookups/member/",
						data: 'term='+$(this).val(),
						dataType: "json",
						success: function(data) {
							if(data.result=='error') {
								displayerrors(section,data.errors);
								close_autocomplete();
							} else if(data.result=='success') {
								$(list).find('li.not_found').prev('.loading').remove().end().find('li.result').remove();
								if(data.accounts.length>3)
									$(list).css({height:'300px'});
								for(var i=0; i<data.accounts.length; i++) {
									var item=data.accounts[i].html;
									$(list).find('li.not_found').before(item).prev('li').data('account',data.accounts[i]);
								}
							}
							$(section).removeData('ajax');
						},
						error: function(msg1,msg2,msg3) {
							$(section).removeData('ajax');
						}
			   		}));
		   		
		   		}
		   		
				return false;
				
			}
		}).keyup(function() {
			var section=$(this).parents('.section');
			if($(this).val().length<5&&$(section).data('ajax')!=undefined) {
				$(section).data('ajax').abort();
			}
		}).keypress(function(event) {
            if (event.which=='13') event.preventDefault();
		}).click(function() {
			var autocomplete = $(this).parents('.section').find('div.autocomplete');
			if($(autocomplete).is(':hidden')) {
				$(autocomplete).show();
				$('body').bind('click',close_autocomplete);
			}
			return false;
		});
	   	
	   	/**
	   	 * UPDATE REGISTRATION TOTALS
	   	 *
	   	 * Update registration totals with input data.
	   	 */
	   	function update_registration_totals(data) {
	   		var cell=$('.events div#attendees tr.total td');
	   		$(cell).html('<br />');
	   		if(data.discount>0) $(cell).html($(cell).html()+'Group Discounts: &nbsp; <strong>($'+data.discount+')</strong><br /><br />');
	   		$(cell).html($(cell).html()+'Subtotal: &nbsp; <strong>$'+data.total+'</strong>');
	   	}
	   	
	   	/**
	   	 * UPDATE REGISTRATION STATUS
	   	 *
	   	 * Remove primary items if primary attendee is specified. Show / Hide List
	   	 * based on # of attendees.
	   	 */
	  	function update_registration_status() {
	  		if($('#attendees tr.primary').length>0) {
	  			$('#attendee h4').each(function() {
	  				$(this).text($(this).text().replace("Primary ",""));
	  			});
	  			$('#attendee .primary').remove();
	  		}
	  		if($('#attendees tr').length<=3) $('#attendees').hide();
	  	}
		update_registration_status();


/* ===============================================================================================
	MY ACCOUNT OPERATIONS
   ----------------------------------------------------------------------------------------------- */
	   	

		/**
		 * CMA Publications form validation - bwhitman - 2011-03-30
		 */
		$('#publications_form').submit( function() {
			// remove old errors
			$(this).find('input').removeClass('error');
			$(this).children('div.error').remove();
		
			
			var errors = 0;			
			// foreach of the checked publications
			$(this).find('input[name^="subscribe"]').each( function() {
				if(this.checked) {
		
					// find the sub-form and loop through checking the reuireds.
					var pubid = $(this).attr('id').split('_')[1];
					$('fieldset#pub_' + pubid).find('input[alt]').each(function() {
						if( this.value == '' ) {
							errors++;
							$(this).addClass('error');
						}
					});
				}
			});

			// handle any errors.
			if( errors > 0 ) {
				msg = '<div class="error">We found <span class="cnt">' + errors + '</span> error(s) with your submissions. Please check your entry and try again.</div>';
				$(this).prepend(msg);
				$('html, body').scrollTop(0);
				return false;
			}

			return true;
		});

		$("input.pubcheckbox").click(function() {
			$('#pub_' + this.value).toggle(this.checked);
		});


		/**
		 * My account : profile visibility - bwhitman - 2011-03-30
		 */
		$('.my_account').find('div.public').children('input[type="checkbox"]').click(function() {
			if(this.checked) $(this).parent().next('.members').find('input').get(0).checked = true;
		});
		$('.my_account').find('div.members').children('input[type="checkbox"]').click(function() {
			if(!this.checked) $(this).parent().prev('.public').find('input').get(0).checked = false;
		});


		/**
		 * My account : profile multi-select replacement - bwhitman - 2011-03-30
		 */
		$('select.Secondaryspeciality').change( function() {
			if(this.value != '') {
				$(this).parent().after( $(this).parent().clone(true) );
				var html = '<input type="hidden" name="Secondaryspeciality[]" value="' + this.value + '" /><strong>' + this.options[this.selectedIndex].text +'</strong>';
				$(this).replaceWith( html );
			}
		});
		$('select.Designationlst').change( function() {
			if(this.value != '') {
				$(this).parent().after( $(this).parent().clone(true) );
				var html = '<input type="hidden" name="Designationlst[]" value="' + this.value + '" /><strong>' + this.options[this.selectedIndex].text +'</strong>';
				$(this).replaceWith( html );
			}
		});

		/**
		 * Print Button
		 *
		 */
		$('.print.button').click(function() { 
			window.print();
			return false;
		});
		
	   	/**
	   	 * Pagination Select Action
	   	 *
	   	 */   	
	   	$('select.page_select').change(function() { 
	   		window.location = $(this).val();
	   	});
	
	   	
}); // END JQUERY READY


var grid_animating=false, homepage_banner_timeout=null;

/* ===============================================================================================
	GLOBAL OPERATIONS
   ----------------------------------------------------------------------------------------------- */	
	

	/**
	 * UPDATE VISUAL FILTER COUNT
	 *
	 */
	function update_filter_count() {
	
		//
		// Update Filter By Button
		var count = $('div.filters div.applied li').length;
		if($('#year').length>0 && $('#year').val()!='') {
			count = count + 1;
		}
		
		if(count>0)
			$('a.filter_by').addClass('filter_wide').find('.circle').text(count).removeClass('hidden');
		else
			$('a.filter_by').removeClass('filter_wide').find('.circle').text('0').addClass('hidden');
					
	}

	
	/**
	 * Get Current Year
	 *
	 */
	function year() {
		var currentTime = new Date();
		var year = currentTime.getFullYear();
		return year;
	}
	
	
	/**
	 * cmaViewMap
	 *
	 * popup a google map to the specified address
	 */
	function cmaViewMap(addr) {
		var q = encodeURIComponent( addr );
		var googleurl = 'http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=' + q
		window.open(googleurl);
	}


	/**
	 * ADD NEW ATTENDEE
	 *
	 * Clear form to allow new attendee for registration.
	 */
	function add_new_attendee() {
		clearform($('#attendee'));
		return false;
	}
	
	/**
	 * SELECT MEMBER
	 *
	 * Select member from retrieved lookup list and update form with member information.
	 */
	function select_member(e) {
	
		//
		// Set Variables
		var data = $(e).parent().data('account');
		var form = $(e).parents('form');
		
		//
		// Name Data
		$('input#firstname').val(data.Firstname).attr('disabled','disabled').addClass('disabled');
		if(data.Middlename!=null&&data.Middlename!='.')
			$('input#middlename').val(data.Middlename).attr('disabled','disabled').addClass('disabled');
		else
			$('input#middlename').val('').blur();
		$('input#lastname').val(data.Lastname).attr('disabled','disabled').addClass('disabled');
		
		//
		// Email Data
		//$('input#email').val(data.Email).blur();
		//if(data.Email!=null) $('input#email').attr('disabled','disabled').addClass('disabled');
		
		//
		// Address Data
		$('input#address').val(data.Address1).blur();
		$('input#city').val(data.City).blur();
		$('select#state').val(data.Statecd).blur();
		$('input#zip').val(data.Zip).blur();
		
		//
		// Phone Data
		if(data.Homephone!=null&&data.Homephone.length>0)
			$('input#phone').val(data.Homephone);
		else if(data.Mobilephone!=null&&data.Mobilephone.length>0)
			$('input#phone').val(data.Mobilephone);
		else
			$('input#phone').val(data.Workphone).blur();
			
		//
		// Member ID
		$('input#memberid').val(data.Customercd);
		
		//
		// Set Birthdate Hash
		$('input#memberhash').val($(e).data('hash'));
		
		close_autocomplete();
		
		return false;
		
	}
			
	/**
	 * SELECT FILTER KEYWORD
	 *
	 * Add selected keyword filter to applied keyword list.
	 */
	function select_keyword(keyword,id) {
		$('.filters input#keyword').val('');
		$('div.keywords .applied ul').append('<li>'+keyword+'<input type="hidden" name="keywords_applied" value="'+id+'" /><a href="#" class="remove"><span><span class="sprite x">x</span></span></a></li>');
		close_autocomplete();
		return false;
	}
			
	/**
	 * GET FEED INFO
	 *
	 * Get first visible feed info element.
	 */   
	function get_feed_info() {
		var feed_info = $("input[name='cma_feed_info']");
		if(feed_info.length>1)
			feed_info = $(".inline-content:visible input[name='cma_feed_info']");
		return feed_info;
	}
	
	/**
	 * CLOSE AUTOCOMPLETE
	 *
	 * Close all open autocompletes and clear lists.
	 */
	function close_autocomplete() {
		$('div.autocomplete').each(function() {
			$(this).hide();
		});
		$('body').unbind('click',close_autocomplete);
	}
	
	/**
	 * HIGHLIGHT ERROR FIELDS
	 *
	 * Add error class (highlight) all specified fields.
	 */
	function highlighterrors(fields) {
		for(var i=0; i<fields.length; i++) {
			$('#'+fields[i]).addClass('error');
		}
	}
	
	/**
	 * CLEAR ERRORS
	 *
	 * Clear errors from children of e.
	 */
	function clearerrors(e) {
		$(e).prev('div.error').remove();
		$(e).find('div.error').remove().end().find('.error').removeClass('error');
	}
	
	/**
	 * DISPLAY ERRORS
	 *
	 * Add specified error element before e.
	 */
	function displayerrors(e,errors) {
		clearerrors(e);
		$(e).before('<div class="error">'+errors+'</div>');
		/*display_message({
			title: 'Error Processing Form',
			message: 'The following errors were encountered while attempting to process your form information.<br /><br />'+errors
		});*/
	}
	
	/**
	 * CLEAR FORM
	 *
	 * Clear data and errors from form element.
	 */
	function clearform(form) {
		clearerrors(form);
		$(form).find('.disabled').removeAttr('disabled').removeClass('disabled');
		$(form).find('input.text').val('').blur();
		$(form).find('textarea').val('').blur();
		$(form).find('input:checked').removeAttr('checked');
		$(form).find('select').each(function() { $(this).find('option:selected').removeAttr('selected').end().find('option:first').attr('selected','selected'); });
	}
	
	/**
	 * TRACE
	 *
	 * Display input in console.
	 */
	function trace(msg) {
		try {window.console.log(msg)} catch (err) {}
	}
	
	/**
	 * ISSET
	 *
	 * JS implementation of php isset function.
	 */
	function isset(variable_name) {
		try {
			if(typeof(eval(variable_name))!='undefined' && eval(variable_name)!=null) return true;
		} catch(e) { }
		return false;
	}
	
	/**
	 * DISPLAY MESSAGE
	 *
	 * Display message overlay.
	 */
	function display_message(data) {
		show_overlay();
		$('body').append('<div id="message"><div class="frame"><div class="box"><div class="title">'+data.title+'</div><div class="message">'+data.message+'</div><a href="#close" onclick="return false;" class="button close">close</a>&nbsp;</div></div></div>');
		$('div#message').hide().fadeIn(200);
		var width = ($(window).width() - parseFloat($('div#message').css("width")))/2 + $(window).scrollLeft();
		var height = ($(window).height() - parseFloat($('div#message').css("height")))/2;
		if(width < 0) { width = 0; } if(height < 0) { height = 0; }
		$('div#message').css("top",height+"px").css("left",width+"px").show();
		$("div#message").find('.close').bind('click',close_messages);
	}
	
	/**
	 * CLOSE MESSAGES
	 *
	 * Close message overlays.
	 */
	function close_messages() {
		$('div#message').fadeOut(100,function() { $(this).remove(); });
		hide_overlay();
		$("div#message").find('.close').unbind('click',close_messages);
	}


	/**
	 * DISPLAY CONFIRM MESSAGE
	 *
	 * Display message overlay.
	 */
	function display_confirmmessage(data) {
		show_overlay();
		$('body').append('<div id="message"><div class="frame"><div class="box"><div class="title">'+data.title+'</div><div class="message">'+data.message+'</div><div class="buttons">'+data.buttons+'</div></div></div></div>');
		$('div#message').hide().fadeIn(200);
		var width = ($(window).width() - parseFloat($('div#message').css("width")))/2 + $(window).scrollLeft();
		var height = ($(window).height() - parseFloat($('div#message').css("height")))/2;
		if(width < 0) { width = 0; } if(height < 0) { height = 0; }
		$('div#message').css("top",height+"px").css("left",width+"px").show();
	}
	
	
	/**
	 * SHOW OVERLAY
	 *
	 * Show screen overlay.
	 */
	function show_overlay() {
		var hide_select = $('<iframe id="hide_select" class="hide_select"></iframe>');
		var overlay = $('<div id="message_overlay" class="message_overlay"></div>');
		$("body").append(hide_select).append(overlay);
		$('iframe#hide_select').hide().fadeIn(200,function () { $(this).css({opacity: 0}); });
		$('div#message_overlay').hide().fadeIn(200,function () { $(this).css({opacity: 0.5}); });
	}
	
	/**
	 * HIDE OVERLAY
	 *
	 * Hide screen overlay.
	 */
	function hide_overlay() {
		$("iframe.hide_select").fadeOut(100,function() { $(this).remove(); });
		$("div.message_overlay").fadeOut(100,function() { $(this).remove(); });
	}
	
	/**
	 * POSITION INLINE IMAGE
	 *
	 * Position an align="right" image with inline image style box.
	 */
	function position_inline_image(obj) {
	   
	    //
	    // Wrap with Div
	    $(obj).wrap('<div class="inline_image" />');
		
		//
		// Apply Caption
		if($(obj).attr('alt').length>0)
			$(obj).after('<div class="caption">'+$(obj).attr('alt')+'</div>');
		
		//
		// Remove Align Tag
		$(obj).removeAttr('align').css({width:'auto'});

	}
	
	/**
	 * SHARE FADEOUT FUNCTIONS
	 */
	var topsharetimeout = null, bottomsharetimeout = null;
	function fadeout_bottom_share() { clearTimeout(bottomsharetimeout); bottomsharetimeout = null; $('.content_footer .share .share_popup').fadeOut(animate.speed/4); }
	function fadeout_top_share() { clearTimeout(topsharetimeout); topsharetimeout = null; $('.top_share .share_popup').fadeOut(animate.speed/4, function() { $(this).remove(); }); }

	
	/**
	 * ALERT TOOLTOP FADEOUT FUNCTIONS
	 */
	var tooltiptimeout = null;
	function hide_alert_tooltip() { clearTimeout(tooltiptimeout); tooltiptimeout = null; $('a.trigger-alerts .tooltip').hide(); }


	/**
	 * ALIGN STORE FEED
	 */
	function align_store_feed() {
		$('.resource_library .feed .product:even').each(function() {
			var item1 = this;
			var item2 = $(item1).next('.product');
			if($(item2).height()<=0) return;
			if($(item1).height()>$(item2).height()) {
				$(item2).css({height: $(item1).height()+'px'});
			} else {
				$(item1).css({height: $(item2).height()+'px'});
			}
		});
	}
	
	
	/**
	 * ANALYTICS TRACK PAGE VIEW
	 *
	 * Tracks a page view within google analytics.
	 *
	 * @param string url
	 */
	function ga_track_page(url) {
		if(url.substr(0,1)!='/') url='/'+url;
		_gaq.push(['_trackPageview', url]);
	}
	
	
	/**
	 * ANALYTICS TRACK EVENT
	 *
	 * Tracks an event within google analytics.
	 *
	 * @param string category
	 * @param string action
	 * @param string label [o]
	 * @param string value [o]
	 */
	function ga_track_event(category,action,label,value) {
		
		//
		// Category + Action + Label + Value
		if(value!=null&&value!=undefined) {
			_gaq.push(['_trackEvent', category, action, label, value]);
		
		//
		// Category + Action + Label
		} else if(label!=null&&label!=undefined) {
			_gaq.push(['_trackEvent', category, action, label]);
			
		//
		// Category + Action
		} else if(action!=null&&action!=undefined&&category!=null&&category!=undefined) {
			_gaq.push(['_trackEvent', category, action]);
		}
		
	}
	
	
	/**
	 * ROTATE HOMEPAGE BANNER
	 *
	 * Rotate homepage banner using interval.
	 */
	function rotate_homepage_banner() {
		$('.homepage #features a.next').click();
		homepage_banner_timeout = setTimeout(rotate_homepage_banner,7000);
	}



	/**
	* HOUSE OF DELEGATES
	**/
	$(document).ready( function() {
		$("select#refcommittee").change(function() {
			$("tbody#resolutionlist").children('tr').show();
			if( this.value.length )  $("tbody#resolutionlist").children('tr').not('.refcomm_'+this.value).hide();
		});

		$("#discussion_title").blur( function() {
			var title = $.trim(this.value);
			if(!cmaWordLimit(title, 6)) {
				this.value = $.trim(title.substring(0, sp));
				alert('Title can have a maximum of 6 words.');
			}

		});

		$("a#attachanother").click(function() {
			var i = parseInt($("#attachfiles").children('.filebox').length) + 1;
			var html = '<div class="filebox"><input type="text" class="text" name="attachtitle_' + i + '" id="attachtitle_' + i + '" title="File Title" value="File Title" /><br /><input type="text" class="text file" name="attachname_' + i + '" id="attachname_' + i + '" title="filename.pdf" value="filename.pdf" /> <span class="button browse_button">Browse</span><br /><input type="file" class="fileinput" name="attachfile_' + i + '" id="attachfile_' + i + '" onchange="$(this).siblings(\'.file\').val(this.value);" /></div>';
			$("#attachfiles").append(html);
			if(i == 10) $(this).remove();
		});

		$("span.browse_button").live('click', function() {
			$(this).siblings('input.fileinput').focus();
		});
	});

	function filterResolutions(grp) {
		var index = 0;
		var sel = $("select#refcommittee").get(0);
		for( var i = 0; i < sel.options.length; i++ )
			if( $(sel.options[i]).val() == grp )
				index = i;

		sel.selectedIndex = index;
		$(sel).change();

		$(".tabs").find("a[href='groupresolutions']").click();
	}



	/**
	* COMMENTS
	**/
	$(document).ready( function() {
		// post comments via ajax
		$("#commentform").submit(function() {
			$.post('/comments/post/', $(this).serialize(), function(data) {
				eval(data);
			});
			return false;
		});
		// comment actions
		$(".actcomment").live('click', function() {
			$.get($(this).attr('href'), function(data) {
				eval(data);
			});
			return false;
		});

		// word limit 
		$("textarea.wordlimit").keydown( function(e) {
			if( e.keyCode == 8 ) return true;
			return commentCheckLimit(this);
		}).blur( function(e) {
			if(!commentCheckLimit(this)) 
				this.value = this.value.substring(0, cmaLastWord(this.value, 500));
			commentCheckLimit(this);
		});
	});

	function postComment(html) {
		var append = $(".order").find('a.active').hasClass('DESC');
		if(append)	$("ul#comments").append(html);
		else 		$("ul#comments").prepend(html);
	}

	function sortComments(type, rel, order) {
		var url = '/comments/load/?type=' + type + '&rel=' + rel + '&order=' + order;
		$("ul#comments").fadeTo(0, 0.3).load(url, function() {
			$(this).fadeTo(0, 1);
		});
		var opp = (order == 'ASC') ? 'DESC' : 'ASC';
		$(".order").find('a').removeClass('active').filter('.'+opp).addClass('active');
		
	}

	function commentCheckLimit(ta) {
		var words = cmaWordCount(ta.value);
		if(words > 500) return false;

		$("#charlimit").children('strong').text( (500-words) );
		return true;
	}

	function cmaWordLimit(str, lim) { 
		return (cmaWordCount(str) <= lim);
	}
	function cmaWordCount(str) { 
		spaces = 0;
		sp = str.indexOf(' ');

		while( sp != -1 ) { 
			spaces++;
			sp = str.indexOf(' ', sp+1);
		}

		return (spaces+1);
	}
	function cmaLastWord(str, lim) { 
		spaces = 0;
		sp = str.indexOf(' ');

		while( sp != -1 ) { 
			spaces++;
			if( spaces == lim ) return sp;
			sp = str.indexOf(' ', sp+1);
		}

		return -1;
	}



