/* Registered Agent Services Process: jQuery / JS */
(function($){ // Keep jQuery Safe from other libraries
	$(function(){
	
	  var step_counter = 1;
  	var clicked_step = 1;
  	$costPerState = 125;
  	$totalAmount = 0;
  	
  	//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 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;
    }
    
    //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 updateConfirmation() {  
      var post = $('#incorporate-process').serialize();
    
      //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_formation_state').html(post_array['formation_state']);
      
      states_of_service = ''; 
      
      pos = 0; service_states = new Array();
      for(i = 1; i <= 51; i++) {
        if(post_array['states_' + i]) {
          service_states[pos] = post_array['states_' + i];
          pos++;
        }
      }
      $('#conf_service_states').html(service_states.join(', '));
      if(post_array['have_reg_agent']) { $('#existing_registered_agent').html(post_array['have_reg_agent']); }
      else { $('#existing_registered_agent').html('No'); }
        
      
      $('#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_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']);
    }
    
    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');
    }
    
    function validate(step_num) {
      //Adjusted here so we can piggy-back on the nearly identical validation code for the online incorporation form
      adjusted_step_num = step_num + 1;
    
      var post = $('#incorporate-process').serialize();
      post = post + '&step=' + adjusted_step_num + '&ra_form=true';
      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); }
          else if(msg == '2') { step_counter++; showStep(step_counter); }
          else if(msg == '3') { step_counter++; showStep(step_counter); }
          else if(msg == '5') { step_counter++; showStep(step_counter); }
    		  else {
    		    $('#error_output').html(msg);
    		    $('html, body').animate({scrollTop:0}, 'slow');
    		    $('#validation').fadeIn();
    		  }
        }
      });
    }
    
    function showStep(clicked_step, validate_this) {        
      if(validate_this == true) {
        if(clicked_step > step_counter) { validate(clicked_step - 1); return false; }
        else if(clicked_step == 4 && step_counter == 4) { validate(3); 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();
  		}
      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();
  		}
  		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();        
        $('#content div.process').hide();
        $('#submit').removeAttr('disabled');
        
        updateConfirmation();
        
        $('#confirmation').fadeIn();
      }

      $('html, body').animate({scrollTop:0}, 'slow');
    }
    
    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/ra/transaction.php', post, function(data) { 
  		  if(data == 'success') {
  		    /* AJAX Success
  		    /* 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);
  		  }
  		});
    }
    
    // Hide elements
		$('#validation').hide();
		$('#confirmation').hide();
		
		//Hide progress bar on load and display form
		$('p.loading').hide();
		$('div.process').hide();
		$('#stepnav li#one a').addClass('current');
		$('#step-one').fadeIn();
		
		// Next navigation
		$('#next a').live('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); }  		
		});
		
		// Prev navigation
		$('#prev a').live('click',function(){
			var $form = $('#content div.process:visible').attr('id');
			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 == 'confirmation') { clicked_step = 3; showStep(3, false); }
  		return false;
    });
		
		//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'); }
			}
		});
		
		// Autotab: 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' });

		// Autotab: 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' });
		
		// Form Submission
  	$('#incorporate-process').submit(function(){
  	  //Prevent premature submission
  	  if(step_counter >= 4) { processFormValues(); return true; }
  		return false;
  	});
  	
  	//Detect when a new state of service has been checked
  	$('.states_of_service').click(function() {
      if($(this).attr('checked')) {
        //Update cart rows
        $html =  '<tr id="cart_' + $(this).val() + '"><td>' + $(this).val() + '</td>';
        $html += '<td class="amount" summary="' + $costPerState + '">$' + $costPerState + '.00</td></tr>';
        $('#estimate_rows').append($html);
        $totalAmount += 125;
      }
      else {
        //Remove state from cart
        $('#cart_' + $(this).val()).remove();
        $totalAmount -= 125;
      }
      //Update total
      $text_total = '$' + $totalAmount + '.00';
      $('#cart_total').text($text_total);
      $('#conf_total').text($text_total);
      $('#super_total').val($text_total);
  	});
	});
})(jQuery);