//Note: There are lots of hard coded costs in here that we should consider storing in a global array.
(function($){ // Keep jQuery Safe from other libraries
$(function(){
	
	// Global Vars
	var $regAgentRemoved;
	var step_counter = 1;
	var clicked_step = 1;
	var $selected_package = 'special';
	var $optional_services = new Array();
	
	$regAgentRemoved = false;
	
	$('#validation').hide();
	$('#confirmation').hide();
	
	$('#submit').one('click',function() {
		return true;
	});
	
	//Reset checkboxes on load to ensure the running total stays accurate
	$('table.pricing input[name="registered_agent"]').attr('checked', false);
	
	//Default to special package
	//$('#radio_special').attr('checked', true);
	
	$('table.pricing input[type="checkbox"][value]').removeAttr('checked');
	$('table.pricing input[type="checkbox"][value]').removeAttr('disabled');
	
	//Credit: http://snipplr.com/view/11583/retrieve-url-params-with-jquery/
	$.urlParam = function(name){
	 var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
	 if(results) { return results[1]; }
	 else { return false; }
	}
	
	function preventSkipAhead(clicked_step_num) {
	 $('#validation').hide();
	 $('#confirmation').hide(); //A convenient place to hide the confirmation tab if it's been reached
	 if((clicked_step_num <= step_counter)) { showStep(clicked_step_num); }
	}
	
	// Step Nav
	$('p.loading').hide();
	
	$('#stepnav li#one a').click(function() { clicked_step = 1; preventSkipAhead(1); return false; });
	
	$('#stepnav li#two a').click(function() { clicked_step = 2; preventSkipAhead(2); return false; });
	
	$('#stepnav li#three a').click(function() { clicked_step = 3; preventSkipAhead(3); return false; });
	
	$('#stepnav li#four a').click(function() { clicked_step = 4; preventSkipAhead(4); return false; });
	
	$('#stepnav li#five a').click(function() { clicked_step = 5; preventSkipAhead(5); return false; });
  
	$('#stepnav li a').each(function(index){
		var $index = index;
		$href = $(this).attr('href');
		$title = $(this).attr('title');
		$($href).hide();
		if(index == 0){
			$($href).show();
			$(this).addClass('current');
		}
	});
	
	//Next Navigation
	$('#next a').click(function(){
    var $form = $('#content div.process:visible').attr('id');
		if($form == 'step-one') { clicked_step = 2; showStep(2, true); }
		if($form == 'step-two') { clicked_step = 3; showStep(3, true); }
		if($form == 'step-three') { clicked_step = 4; showStep(4, true); }
		if($form == 'step-four') { clicked_step = 5; showStep(5, true); }
		if($form == 'step-five') { clicked_step = 6; showStep(6, true); }
		return false;
	});
	
	//Prev Navigation
	$('#prev a').click(function(){
	  var $form = $('#content div.process:visible').attr('id');
	  
	  $('#validation').hide();

		if($form == 'step-one') { clicked_step = 1; showStep(1, false); }
		if($form == 'step-two') { clicked_step = 1; showStep(1, false); }
		if($form == 'step-three') { clicked_step = 2; showStep(2, false); }
		if($form == 'step-four') { clicked_step = 3; showStep(3, false); }
		if($form == 'step-five') { clicked_step = 4; showStep(4, false); }
		return false;
	});
  
  function resetStepHighlight() {
    $('#stepnav li#one a').removeClass('current').removeClass('complete');
    $('#stepnav li#two a').removeClass('current').removeClass('complete');
    $('#stepnav li#three a').removeClass('current').removeClass('complete');
    $('#stepnav li#four a').removeClass('current').removeClass('complete');
    $('#stepnav li#five a').removeClass('current').removeClass('complete');
  }
  
  //Lifted from http://www.webtoolkit.info/javascript-string-replace.html
  function str_replace(haystack, needle, replacement) {
	  var temp = haystack.split(needle);
    return temp.join(replacement);
  }
  
  function serializeToArray(serialized_array) {
    serialized_array = str_replace(serialized_array, '+', ' ');
  
    first_pass = serialized_array.split('&');
    
    second_pass = new Array();
    for(i in first_pass) {
      temp = first_pass[i].split('=');
      
      temp[1] = temp[1].replace('%40', '@');
      temp[1] = temp[1].replace('%2C', ',');
      
      second_pass[temp[0]] = temp[1];
    }

    return second_pass;
  }
  
  function updateConfirmation() {  
    var post = $('#incorporate-process').serialize();
  
    //Update confirmation tab
		if($selected_package == 'silver') { $('#conf_package').text('Silver Package including:'); }
		else if($selected_package == 'special') { $('#conf_package').text('Special Package including:'); }
		else if($selected_package == 'gold') { $('#conf_package').text('Gold Package including:'); }
		else if($selected_package == 'platinum') { $('#conf_package').text('Platinum Package including:'); }
		
		$('#package').val($selected_package);
		
		//Iterate through the optional services array, if the cost is greater than zero, add to confirmation
		var service_output = '';
		for (i in $optional_services) { 
		  if($optional_services[i] > 0) {
        service_output += '<li>' + i + '</li>';
      }
    };
    $('#conf_package_detail').html(service_output);
    
    //Convert the form fields into something easier to parse through
    post_array = serializeToArray(post);
    
    //Build out confirmation info
    $('#conf_company_name').html(post_array['company_name_1']);
    $('#conf_company_desc').html(post_array['business_activity']);
    
    $('#conf_contact_address_name').html(post_array['full_name']);
    $('#conf_contact_address_address1').html(post_array['address_1']);
    $('#conf_contact_address_address2').html(post_array['address_2']);
    $('#conf_contact_address_city').html(post_array['city']);
    $('#conf_contact_address_state').html(post_array['state']);
    $('#conf_contact_address_zip').html(post_array['zipcode']);
    $('#conf_contact_address_county').html(post_array['county']);
    $('#conf_contact_address_phone').html(post_array['phone_a'] + post_array['phone_b'] + post_array['phone_c']);
    $('#conf_contact_address_fax').html(post_array['fax_a'] + post_array['fax_b'] + post_array['fax_c']);
    $('#conf_contact_address_email1').html(post_array['email_1'].replace('%40', '@'));
    $('#conf_contact_address_email2').html(post_array['email_2'].replace('%40', '@'));
    
    $('#conf_company_address_name').html(post_array['lc_name']);
    $('#conf_company_address_address1').html(post_array['lc_address_1']);
    $('#conf_company_address_address2').html(post_array['lc_address_2']);
    $('#conf_company_address_city').html(post_array['lc_city']);
    $('#conf_company_address_state').html(post_array['lc_state']);

    $('#conf_company_address_zip').html(post_array['lc_zipcode']);
    $('#conf_company_address_county').html(post_array['lc_county']);
    $('#conf_company_address_phone').html(post_array['lc_phone_a'] + post_array['lc_phone_b'] + post_array['lc_phone_c']);
    
    $('#conf_reg_agent_name').html(post_array['ra_name']);
    $('#conf_reg_agent_address1').html(post_array['ra_address_1']);
    $('#conf_reg_agent_address2').html(post_array['ra_address_2']);
    $('#conf_reg_agent_city').html(post_array['ra_city']);
    $('#conf_reg_agent_state').html(post_array['ra_state']);
    
    $('#conf_reg_agent_zip').html(post_array['ra_zipcode']);
    $('#conf_reg_agent_county').html(post_array['ra_county']);
    $('#conf_reg_agent_phone').html(post_array['ra_phone_a'] + post_array['ra_phone_b'] + post_array['ra_phone_c']);
    
    $('#conf_people_president').html(post_array['o_president']);
    $('#conf_people_treasurer').html(post_array['o_treasurer']);
    $('#conf_people_secretary').html(post_array['o_secretary']);
    
    $('#conf_billing_address_name').html(post_array['ba_name']);
    $('#conf_billing_address_address1').html(post_array['ba_address_1']);
    $('#conf_billing_address_address2').html(post_array['ba_address_2']);
    $('#conf_billing_address_city').html(post_array['ba_city']);
    $('#conf_billing_address_state').html(post_array['ba_state']);
    
    $('#conf_billing_address_zip').html(post_array['ba_zipcode']);
    $('#conf_billing_address_county').html(post_array['ba_county']);
    $('#conf_billing_address_phone').html(post_array['ba_phone_a'] + post_array['ba_phone_b'] + post_array['ba_phone_c']);
    
    //Add directors
    if(post_array['do_directors'] > 0) {
      for(i = 1; i <= post_array['do_directors']; i++) {
        $('#conf_people_officers').append("<dt>Name</dt><dd>" + post_array['do_name_' + i] + "</dd>");
      }
    }
    
    //Add managers
    if(post_array['do_num_mm'] > 0) {
      for(i = 1; i <= post_array['do_num_mm']; i++) {
        $('#conf_people_officers').append("<dt>Name</dt><dd>" + post_array['do_mm_name_' + i] + "</dd>");
      }
    }
  }
  
  function showStep(clicked_step, validate_this) {  
    //Make sure a package has been selected
    if(!$.urlParam('type')) {
		$('#error_output').html("<li>Please click 'Get Started' to continue.</li>\n");
		$('#validation').fadeIn();
		return false;
    }
  
    if(validate_this == true) {
      if(clicked_step > step_counter) { validate(clicked_step - 1); return false; }
      else if(clicked_step == 6 && step_counter == 6) { validate(5); return false; }
    }
  
    resetStepHighlight();
    
    step_counter = clicked_step;
  
    if(clicked_step == 1) {
      $('#stepnav li#one a').addClass('current');
      $('#content div.process').hide();
			$('#step-one').show();
		}
    else if(clicked_step == 2) {
      $('#stepnav li#one a').removeClass('current').addClass('complete');
      $('#stepnav li#two a').addClass('current');
      $('#content div.process').hide();
			$('#step-two').show();
			addRegAgent();
		}
    else if(clicked_step == 3) {
      $('#stepnav li#one a').removeClass('current').addClass('complete');
      $('#stepnav li#two a').removeClass('current').addClass('complete');
      $('#stepnav li#three a').addClass('current');
      $('#content div.process').hide();
			$('#step-three').show();
			addRegAgent();
		}
		else if(clicked_step == 4) {
		  $('#stepnav li#one a').removeClass('current').addClass('complete');
		  $('#stepnav li#two a').removeClass('current').addClass('complete');
		  $('#stepnav li#three a').removeClass('current').addClass('complete');
		  $('#stepnav li#four a').addClass('current');
      $('#content div.process').hide();
      $('#step-four').show();
      addRegAgent();
    }
    else if(clicked_step == 5) {
      $('#stepnav li#one a').removeClass('current').addClass('complete');
		  $('#stepnav li#two a').removeClass('current').addClass('complete');
		  $('#stepnav li#three a').removeClass('current').addClass('complete');
      $('#stepnav li#four a').removeClass('current').addClass('complete');
      $('#stepnav li#five a').addClass('current');
      $('#content div.process').hide();
  		$('#step-five').show();
  		addRegAgent();
    }
    else if(clicked_step == 6) {
      $('#stepnav li#one a').removeClass('current').addClass('complete');
		  $('#stepnav li#two a').removeClass('current').addClass('complete');
		  $('#stepnav li#three a').removeClass('current').addClass('complete');
      $('#stepnav li#four a').removeClass('current').addClass('complete');
      $('#stepnav li#five a').removeClass('current').addClass('complete');
      $('#content div.process').hide();
      $('#submit').removeAttr('disabled');
      
      updateConfirmation();
      
      $('#confirmation').fadeIn();
  		addRegAgent();
    }
    $('html, body').animate({scrollTop:0}, 'slow');
    
    
  }
  
  //Update Progress Bar
  $progress = 1;
  function advance_progress(msg) {
  	if(msg == $progress) {
    	$('#progress-bar li.active + li').addClass('active');
    	$progress++;
  	}
  }
  
  function validate(step_num) {
    var post = $('#incorporate-process').serialize();
    post = post + '&step=' + step_num;
    in_process = true;
    
    $.ajax({
      type: "POST",
      url: "/wp-content/themes/cfs/inc/validate.php",
      data: post,
      success: function(msg){
        $('#validation').hide();
        if(msg == '1') { step_counter++; showStep(step_counter); advance_progress(msg); }
        else if(msg == '2') { step_counter++; showStep(step_counter); advance_progress(msg);}
        else if(msg == '3') { step_counter++; showStep(step_counter); advance_progress(msg);}
  		  else if(msg == '4') { step_counter++; showStep(step_counter); advance_progress(msg);}
  		  else if(msg == '5') { step_counter++; showStep(step_counter); advance_progress(msg);}
  		  else {
  		    $('#error_output').html(msg);
  		    $('html, body').animate({scrollTop:0}, 'slow');
  		    $('#validation').fadeIn();
  		  }
      }
    });
  }
	
	// Advanced CSS
	$('#content *.cBox').each(function(){
		$(this).find('h4:first').addClass('first');
	});
	
	// Pricing Table
	$('table.pricing').each(function(){
		$(this).find('tbody tr:even').addClass('odd');
	});
	
	/* Step #1 State & Type Selects
	var $setQueriesType;
	var $setQueriesState;
	$('select.setQueries').each(function(){
		$(this).change(function(){
			if($(this).attr('id') == 'type'){
				$setQueriesType = $(this).val();
			} else {
				$setQueriesState = $(this).val();
				$(this).parent().empty().css({'text-align':'center'}).text('Loading...').animate({ color: '#36ac4d' }, 1500);
				window.location = '?type='+ $setQueriesType +'&state='+ $setQueriesState +'';
			}
		});
	});
	*/
	
	// Step #1 Get Started Click Event
	$('#step-1-get-started').click(function(){
    	var state = $(this).parent().find('#states').val();
		var type = $(this).parent().find('#type').val();
		$(this).parent().empty().css({'text-align':'center'}).text('Loading...').animate({ color: '#36ac4d' }, 1500);
		window.location = '?type=' + type + '&state=' + state;
		$('#progress').fadeIn(600);
	});
	
	// Functions
	function addRegAgent() {
	  if(step_counter >= 3 && $selected_package !== 'special') {
  		if( ($('#cart tr#registered_agent').length < 1) && ($regAgentRemoved == false) ) {
  		  if($selected_package == 'special') { $totalAmount = $totalAmount + 125; }
  		  else { $totalAmount = $totalAmount + 62; }
  			$('#conf_reg_agent').hide();
  			
  			// Create XHTML
  			var $registeredHtml = '<tr id="registered_agent">';
  			$registeredHtml += '<td>FilingsMadeEasy as my Registered Agent</td>';
  			
  			if($selected_package == 'special') { $registeredHtml += '<td class="amount" summary="125">$125.00</td>'; }
  			else { $registeredHtml += '<td class="amount" summary="62">$62.00</td>'; }
  			
  			$registeredHtml += '</tr>';
  			$('table#estimate tbody').append($registeredHtml)
  			$('table#estimate tbody #registered_agent').hide().css({ color: '#36ac4d' }).fadeIn().animate({ color: '#5a5a5a' }, 1500);

  			// Add Value to Cart
  			$('#total').empty().text('$'+$totalAmount+'.00');
  			$('#bottom-total').empty().text('$'+$totalAmount+'.00');
  			
  			//Update addon array
  			if($selected_package == 'special') { $optional_services['FilingsMadeEasy as my Registered Agent'] = 125; }
  			else { $optional_services['FilingsMadeEasy as my Registered Agent'] = 62; }
  			
  		}
    }     
	}
	
	function removeRegAgent() {
		$totalAmount -= 62;
		
		// Create XHTML
		$('#registered_agent').animate({ color: '#c32e2a', opacity: 0 }, 1000, function(){
			$(this).remove();
		});

  	//Update addon array
  	$optional_services['FilingsMadeEasy as my Registered Agent'] = 0;
	}

	function processFormValues(){
	  //Store total
    $('#total_amount').attr('value', $totalAmount);
	 
		var post = $('#incorporate-process').serialize();
		
		$('#confirmation input:submit').attr('disabled','disabled');   
		$.post('/wp-content/themes/cfs/inc/process.php', post, function(data) { 
		  if(data == 'success') {
		    /* AJAX Success
		    $('#confirmation').hide();
		    $('#stepnav').hide();
		    $('ul.nextprevnav').hide();
		    $('html, body').animate({scrollTop:0}, 'slow');
		    $('#output').hide().html('<h3>Thank you for your order!</h3><p>If you have have any questions please call us at <strong>888.237.3410</strong> or email us at <a href="mailto:customerservice@filingsmadeeasy.com">CustomerService@FilingsMadeEasy.com</a>. We\'ll be in touch with you shortly regarding the status of your order.</p>').fadeIn();
		    */
		    /* Redirect Success for Adwords Conversion Tracking */
		    if(!$.urlParam('test')) {
		    	window.location = "http://www.filingsmadeeasy.com/thank-you/?process=complete";
		    } else {
		    	window.location = "http://www.filingsmadeeasy.com/thank-you/";
		    }
		  }
		  else {
		    //$('#output').text('An error occurred. Please ensure your credit card information is accurate.');
		    $('#confirmation input:submit').removeAttr('disabled');
		    $('#confirmation').hide();
		    step_counter = 4;
		    showStep(5);
		    $('#output').html(data);
		  }
		});
	}
	
	// Form Submission
	$('#incorporate-process').submit(function(){
	  //Prevent premature submission
	  if(step_counter >= 6) { processFormValues(); return true; }
		return false;
	});
	
	$('td.special input, td.silver input, td.platinum input').attr('disabled','disabled');
	
	// Event Handlers
	$('table.pricing input[type="radio"][value], table.pricing input[type="checkbox"][value], input[name="registered_agent"]').live('click',function(){
		
		// Add to Cart
		if($(this).is(':checkbox')) {
		
			// Radio Events
			var $others = $(this).parent().siblings().find('input')
			$others.each(function(){
				var $val = $(this).val();
				var $desc = $(this).attr('summary');
				var $name = $(this).attr('name');
				
				$val = parseInt($val);
				
				if($others.is(':checked')){
					$others.removeAttr('checked');
					$('#'+$name).animate({ color: '#c32e2a', opacity: 0 }, 1000, function(){
						$(this).remove();
					});
					$totalAmount = $totalAmount - $val;
				}
			});
			var $val = $(this).val();
			$val = parseInt($val);
			if($(this).attr('name') == 'registered_agent') {
				var $desc = $(this).attr('summary');
				$regAgentRemoved = true;
			} else {
				var $desc = $(this).parent().parent().find('td:first').text();
			}
			
			var $name = $(this).attr('name');
			var $html = '<tr id="'+$name+'">';
			$html += '<td>'+$desc+'</td>';
			$html += '<td class="amount" summary="'+$val+'">$'+$val+'.00</td>';
			$html += '</tr>';
			if($(this).is(':checked')) {
				if( ($(this).attr('name') == 'registered_agent') && ($('#registered_agent').length > 0) ) {
					$totalAmount = $totalAmount - $val;
				}
				else {
					$('table#estimate tbody').append($html)
					$('table#estimate tbody #'+$name).hide().css({ color: '#36ac4d' }).fadeIn().animate({ color: '#5a5a5a' }, 1500);
					$totalAmount = $totalAmount + $val;
				}
				
				//Store enabled options
        $optional_services[$desc] = $val;
			}
			else {
			  //Remove this addon
			  $optional_services[$desc] = 0;
			  
				$totalAmount = $totalAmount - $val;
				$('#'+$name).animate({ color: '#c32e2a', opacity: 0 }, 1000, function(){
					$(this).remove();
					/* Default Message (when nothing is in the cart)
					if($('table#estimate tbody tr').size() < 2) {
						$('#default').show();
						$totalAmount = 0;
					}
					*/
				});
			}
		}
		else {
			$('#service_package').hide();
			
			// Remove package addons when switching to another package
			var $package = '.'+$(this).parent().parent().attr('class');
			$('td:not('+$package+') input:checked').each(function(){
				$(this).removeAttr('checked');
				//var $prevVal = $(this).val();
				var $prevName = $(this).attr('name');
				$('#'+$prevName).animate({ color: '#c32e2a', opacity: 0 }, 1000, function(){
					$(this).remove();
				});
				//$totalAmount = $totalAmount - $prevVal;
			  $optional_services = new Array();
			});
			
			// Radio Events
			var $radioVal = $(this).val();
			$radioVal = parseInt($radioVal);
			var $radioDesc = $(this).attr('summary');
			var $radioName = $(this).attr('name');
			
			$('table#estimate tbody').html('');
		  $totalAmount = 0;
			
			// Add Row to Estimate
			var $radioHtml = '<tr id="'+$radioName+'">';
			$radioHtml += '<td>'+$radioDesc+'</td>';
			$radioHtml += '<td class="amount" summary="'+$radioVal+'">$'+$radioVal+'.00</td>';
			$radioHtml += '</tr>';
			
			// Package Conditionals
			if($(this).parent().parent().hasClass('special')) {
			  $selected_package = 'special';
				$(this).parent().parent().parent().parent().next().find('td.special input').removeAttr('disabled');
				$(this).parent().parent().parent().parent().next().find('td:not(.special) input').attr('disabled','disabled');
				
				//Disable registered agent for this package
				$('#reg_agent_chk').attr('checked', true);
				$('#reg_agent_chk').attr('disabled', 'disabled');
				
				//Hide non-special registered agent content and show the other
				$('#non_special_reg_agent').hide();
				$('#special_reg_agent').show();
				
				//Disable non-special registered agent checkbox so it doesn't show in post
				$('#reg_agent_chk').attr('disabled', 'disabled');
				$('#hid_registered_agent').removeAttr('disabled');
			}
			else {
			  $('#non_special_reg_agent').show();
				$('#special_reg_agent').hide(); 
			
			  $('#reg_agent_chk').removeAttr('disabled');
        $('#hid_registered_agent').attr('disabled', 'disabled');
		  }
			
			if($(this).parent().parent().hasClass('silver')) {
			  $selected_package = 'silver';
				$(this).parent().parent().parent().parent().next().find('td.silver input').removeAttr('disabled');
				$(this).parent().parent().parent().parent().next().find('td:not(.silver) input').attr('disabled','disabled');
			}
			if($(this).parent().parent().hasClass('gold')) {
			  $selected_package = 'gold';
			  $(this).parent().parent().parent().parent().next().find('td.gold input').removeAttr('disabled');
				$(this).parent().parent().parent().parent().next().find('td:not(.gold) input').attr('disabled','disabled');
			}
			if($(this).parent().parent().hasClass('platinum')) {
			  $selected_package = 'platinum';
				$(this).parent().parent().parent().parent().next().find('td.platinum input').removeAttr('disabled');
				$(this).parent().parent().parent().parent().next().find('td:not(.platinum) input').attr('disabled','disabled');
			}
			if( ($radioName == 'service_package') && ($('table#estimate tbody tr#service_package').length > 0) ) {
				var $oldVal = $('table#estimate tbody tr#service_package').find('td.amount').attr('summary');
				$oldVal = parseInt($oldVal);
				$totalAmount = $totalAmount - $oldVal;
				$('table#estimate tbody tr#service_package').remove();
			}
			if($(this).is(':checked')) {
				$('table#estimate tbody').append($radioHtml);
				$('table#estimate tbody #'+$radioName).hide().css({ color: '#36ac4d' }).fadeIn().animate({ color: '#5a5a5a' }, 1500);
				$totalAmount = $totalAmount + $radioVal;
			} else {
				$totalAmount = $totalAmount - $radioVal;
				$('#'+$radioName).animate({ color: '#c32e2a', opacity: 0 }, 1000, function(){
					$(this).remove();
				});
			}
		}
		
		$('#total').empty().text('$'+$totalAmount+'.00');
		$('#bottom-total').empty().text('$'+$totalAmount+'.00');
	});
	
	// Autotab for phone fields
	// Phone
	$('input[name=phone_a]').autotab({ target: 'phone_b', maxlength: 3, format: 'numeric' });
	$('input[name=phone_b]').autotab({ target: 'phone_c', previous: 'phone_a', maxlength: 3, format: 'numeric' });
	$('input[name=phone_c]').autotab({ previous: 'phone_b', maxlength: 4, format: 'numeric' });
	// Fax
	$('input[name=fax_a]').autotab({ target: 'fax_b', maxlength: 3, format: 'numeric' });
	$('input[name=fax_b]').autotab({ target: 'fax_c', previous: 'fax_a', maxlength: 3, format: 'numeric' });
	$('input[name=fax_c]').autotab({ previous: 'fax_b', maxlength: 4, format: 'numeric' });
	
	// Checkbox Toggler
	$('div.hidden').hide();
	$('input[type="checkbox"].toggler').live('click',function(){
		var $div;
		if($(this).attr('name') == 'irs_form_ss_4') {
			$div = $(this).parent().next();
		} else {
			$div = $(this).parent().parent().next();
		}
		//$div.toggle();
	});
	
	// Select Togglers
	$('#directors p:not(:first)').hide();
	$('#members-managers p:not(:first)').hide();
	$('select.toggler').change(function(){
		var $num = $(':selected', this).text()
		if($(this).attr('id') == 'num_directors') {
			var $container = $('#directors');
			var $field = 'input[name^=do_name]';
		
		} else if($(this).attr('id') == 'do_num_mm') {
			var $container = $('#members-managers');
			var $field = 'input[name^=do_mm_name]';
		}
		$container.find($field).parent().parent().children().hide();
		$container.find($field).each(function(index){
			if((index) < $num) {
				$(this).parent().show();
			}
		});
	});
	
	// Members & Managers Toggler
	//$('#mm-question').next('p').hide();
	//$('#members-managers').parent().hide();
	$('#mm-question input[type=radio]').click(function(){
		if($(this).val() == 'Yes') {
			$(this).parent().next().show();
			$('#members-managers').show();
		} else {
			$(this).parent().next().hide();
		}
	});
	
	// Same as above for contact fields
	$('input[name$="same_as_above"]').live('click',function(){
		$contactField = $(this).parent().parent();
		if(!$(this).attr('checked')) {
			function defaultVal(field) {
				if(window.console&&window.console.log) { console.log(field); }
				$contactField.find(field).attr('value', $(field).attr('default')).addClass('placeholder');
			}
			defaultVal('input[name$="name"]');
			defaultVal('input[name$="address_1"]');
			defaultVal('input[name$="address_2"]');
			defaultVal('input[name$="city"]');
			$contactField.find('select[name*="state"]').removeAttr('value');
			defaultVal('input[name$="zipcode"]');
			defaultVal('input[name$="county"]');
			defaultVal('input[name$="phone_a"]');
			defaultVal('input[name$="phone_b"]');
			defaultVal('input[name$="phone_c"]');
		} else {
			$name = $('fieldset#contact').find('input[name="full_name"]').val();
			$address_1 = $('fieldset#contact').find('input[name="address_1"]').val();
			$address_2 = $('fieldset#contact').find('input[name="address_2"]').val();
			$city = $('fieldset#contact').find('input[name="city"]').val();
			$state = $('fieldset#contact').find('select[name="state"]').val();
			$county = $('fieldset#contact').find('input[name="county"]').val();
			$zip = $('fieldset#contact').find('input[name="zipcode"]').val();
			$phone_a = $('fieldset#contact').find('input[name="phone_a"]').val();
			$phone_b = $('fieldset#contact').find('input[name="phone_b"]').val();
			$phone_c = $('fieldset#contact').find('input[name="phone_c"]').val();
			$fax_a = $('fieldset#contact').find('input[name="fax_a"]').val();
			$fax_b = $('fieldset#contact').find('input[name="fax_b"]').val();
			$fax_c = $('fieldset#contact').find('input[name="fax_c"]').val();
			// Copy to this contact fieldset
			$contactField.find('input[name$="name"]').attr('value',$name).removeClass('placeholder');
			$contactField.find('input[name$="address_1"]').attr('value',$address_1).removeClass('placeholder');
			$contactField.find('input[name$="address_2"]').attr('value',$address_2).removeClass('placeholder');
			$contactField.find('input[name$="city"]').attr('value',$city).removeClass('placeholder');
			$contactField.find('select[name*="state"]').attr('value',$state);
			$contactField.find('input[name$="county"]').attr('value',$county).removeClass('placeholder');
			$contactField.find('input[name$="zipcode"]').attr('value',$zip).removeClass('placeholder');
			$contactField.find('input[name$="phone_a"]').attr('value',$phone_a).removeClass('placeholder');
			$contactField.find('input[name$="phone_b"]').attr('value',$phone_b).removeClass('placeholder');
			$contactField.find('input[name$="phone_c"]').attr('value',$phone_c).removeClass('placeholder');
			if(window.console&&window.console.log) { console.log('Clicked'); }
		}
	});

  //$('#radio_special').trigger('click');

});
})(jQuery);