// requires: jquery, jquery.easing

jQuery(document).ready(function(){	
	newsLetterInit();
});

function newsLetterInit()
{
	jQuery('.newsletter_signup, .account_preferences').each(function(elm){
    	Newsletter.initialize(elm);
    });
}


//-------------------------------------------------------------------------------

var Newsletter = function(){
  var self = {
	/**
         * Initialize an element for expanding behaviour
         * @param DOM element
         */
	initialize: function(elm) {
	  
	  elm = jQuery(elm);

	  // add click behaviour for checkbox
	  var optInCheckbox = elm.find('input[name="newsletter_signup"]');

	  // if we have an areasofinterest then set initialise 
	  var areasOfInterest = elm.find('.areasofinterest');
	  Expanding.create(areasOfInterest);
	  var panels = areasOfInterest.find('.panel');
	  //Expanding.togglePanel(panels);
	  jQuery(".editPrefs").livequery('click',function() {
		  Expanding.openPanel(panels);
		  jQuery('#editPanel .editPrefs').hide();
	  });
	  
	  // set optIn checkbox if catagory checkbox is selected
	  jQuery(".selectCategory").livequery('click',function() {
		 	if (this.checked) {
				jQuery('#newsletter_signup').get(0).checked = true;
			}
		 	
		 	if (jQuery(".selectCategory:checked").length < 1) {
		 		jQuery('#newsletter_signup').get(0).checked = false;
		 	}
	  });
	  
	  // when opt in is unchecked, unset all the category check boxes
	  jQuery('#newsletter_signup').livequery('click', function(){

		  if (!jQuery('#newsletter_signup').get(0).checked) {
			  jQuery(".selectCategory").each(function() {
				  this.checked = false;
			  });
		  }
		  else {
			  jQuery(".selectCategory.checked:first").each(function() {
				  this.checked = true;
			  });
		  }
		  
		  if (!panels.is('.open') && optInCheckbox.get(0).checked) {
			  Expanding.togglePanel(panels);
		  }   
	  });
	  
	  //pre select boxes that should be checked
	  if (jQuery(".loggedout").length > 0) {
		  jQuery(".selectCategory.checked:first").attr('checked', true);
		  jQuery(".single_newsletter input").attr('checked', true);
	  }
	  
  	}
  };
  return self;
}();



