// JavaScript Document   AJAX functions By Michael Hazzard
//                         integrated with scriptaculous -- ported to $ jQuery  2009


//        $('#cc_type').change(function(){
//            $("#signupform").validate().element('#cc_num');
//        });
//
jQuery(document).ready(function() {	
								
//		if ($("#result_fee").val() != '') { // if we are using our back button then populate the proper prices
//		
//			$("#result").html("One-Time Setup: $" + $("#result_fee").val() );
//			$("#result_monthly").html("Monthly Fee: $" + $("#result_monthly_fee").val() );
//		
//		}
//		

	// check if they have selected south carolina as their state
	$("#state").change(function(){
			checkStateNotSC()
        });
	
	function checkStateNotSC() {
			var selected = $("#state option:selected");				

				if(selected.val() == 'SC'){  // if so we inform them that we do not service south carolina
					 $("#special_message_about_state").html("Please Note:<br />At this time we are not offering our services in the state of South Carolina. We apologize for any inconvenience and wish you the best in your efforts.");
					 $("#special_message_about_state").show('slow');
				} else if (selected.val() == 'CO'){  // if so we inform them that we do not service south carolina
					 $("#special_message_about_state").html("Please Note:<br />At this time we are not offering our services in the state of Colorado. We apologize for any inconvenience and wish you the best in your efforts.");
					 $("#special_message_about_state").show('slow');
				} else {
					 $("#special_message_about_state").hide('slow');					 					
				}
	}

	function fadeStateNotSC() {
			var selected = $("#state option:selected");				

				if(selected.val() == 'SC'){  
				/// fade message so they can see it is not functional
					$("#special_message_about_state").fadeOut();
					$("#special_message_about_state").fadeIn();
					$("#special_message_about_state").fadeOut();
					$("#special_message_about_state").fadeIn();	
				 			
				}
	}
	
	$('#signupform').submit(function () {
		var selected = $("#state option:selected");		
		
		if(selected.val() == 'SC'){ 
			$.scrollTo( '#special_message_about_state', 400);
        	return false; 
		};

		if(selected.val() == 'CO'){ 
			$.scrollTo( '#special_message_about_state', 400);
        	return false; 
		};
	}); 

	
// end check if they have selected south carolina as their state
	
	// set the css via javascript
	$("#spouseslider").css("display","none")
	$("#spouseextrafenojs").css("display","none")
	$("#nojavascriptprice").css("display","none")	
	
	// set the css via javascript
	    
		$('#cc_type').change(function(){
			if ($("#cc_num").val() != '') {
            	$("#signupform").validate().element('#cc_num');
			}
        });
	

	jQuery("#signupform").validate({   
	   // manually handle the submit so we can group sections together
			rules: {
                cc_num: {
                    creditcard2: function(){ return $('#cc_type').val(); },
					required: true
                },
				cc_type: {
					required: true
				},
				// south carolina check
				state: { 
						state: function(){ 					
						checkStateNotSC();
						fadeStateNotSC();
						}
							
							
				}
				// end south carolina check
            },	
			messages: {
				cc_num: 'Invalid Number or Card Type'
			},
				
								 
			
			groups: {
   			 workphone: "workphone1 workphone2 workphone3",
			 dob: "dob1 dob2 dob3",
			 dob_spouse: "dob_spouse1 dob_spouse2 dob_spouse3",
			 ss_number: "ss_number1 ss_number2 ss_number3",			 
			 ss_number_spouse: "social_spouse1 social_spouse2 social_spouse3"			 
  			},
  errorPlacement: function(error, element) {
	  
     if (element.attr("name") == "workphone1" 
                 || element.attr("name") == "workphone2" || element.attr("name") == "workphone3" )
       error.insertAfter("#workphone3");
     else if (element.attr("name") == "dob1" 
                 || element.attr("name") == "dob2" || element.attr("name") == "dob3" )
       error.insertAfter("#dob3");
     else if (element.attr("name") == "ss_number1" 
                 || element.attr("name") == "ss_number2" || element.attr("name") == "ss_number3" )
       error.insertAfter("#ss_number3");
     else if (element.attr("name") == "dob_spouse1" 
                 || element.attr("name") == "dob_spouse2" || element.attr("name") == "dob_spouse3" )
       error.insertAfter("#dob_spouse3");
     else if (element.attr("name") == "social_spouse1" 
                 || element.attr("name") == "social_spouse2" || element.attr("name") == "social_spouse3" )
       error.insertAfter("#social_spouse3");
     else
       error.insertAfter(element);
   }
   
   

				
		});
	
});

/*$(document).ready(function(){
// handle the phone extension boxes
	$(".addworkextlink").click(function() {
		$(".workext").html(' x <input type="text" name="workphone4" size="6" maxlength="5" value="" id="workphone4"  class="number"  />');	
		$(".addworkext").hide();	
	});							 

	$(".addhomeextlink").click(function() {
		$(".homeext").html(' x <input type="text" name="homephone4" size="6" maxlength="5" value=""    class="number" />');	
		$(".addhomeext").hide();	
	});							 

});
*/
$(document).ready(function(){



    //mh pulls prices in from spans in signup
    var result_price = $("#result_price").html();
    var result_monthly_price =  $("#result_monthly_price").html();

/*
    $("#signupform").validate({
        focusInvalid: false,
        errorLabelContainer: "#errors", 
        invalidHandler: function(form, validator) {
            window.location.hash='errors'  //did twice cause safari doesn't like calling same anchor t'
            window.location.hash='errorsAnchor'
            //$("#errors").css("min-height","100") //gave #errors height so form doesnt shift up.  in the middle of filling out
        }
    })

*/

	$(".cvvhelp").click(function() { 
		$("#cvvhelpslider").slideDown("normal");						   
	 });								   

	$(".cvvhelpclose").click(function() { 
		$("#cvvhelpslider").slideUp("normal");						   
	 });								   

    //initial setup of slider  
    if( $("#addspouse").is(":checked") ){
        $("#spouseslider").css("display", "block");
        
        $("#first_name_spouse").attr("class", "required")
        $("#last_name_spouse").attr("class", "required")
    }

    //when addspouse clicked do this
    $("#addspouse").click(function () {
        var number_persons;
        if( $("#addspouse").is(":checked") ){
            setup_fee_increment = 2; 
			monthly_fee_increment = 1.5;

            $("#spouseslider").slideDown("slow");

            $("#first_name_spouse").attr("class", "required")
            $("#last_name_spouse").attr("class", "required")
        }else{
            setup_fee_increment = 1; 
			monthly_fee_increment = 1;

            $("#spouseslider").slideUp("slow");
   
            $("#first_name_spouse").removeAttr("class");
            $("#last_name_spouse").removeAttr("class");
        }

        //calculate replacement
        //get prices from fields so jim! can change the price in the <span> and it auto calc's
        $("#result").html("One-Time Setup: $" + round_decimals(setup_fee_increment * result_price, 2 ) );
        $("#result_monthly").html("Monthly Fee: $" + round_decimals(monthly_fee_increment * result_monthly_price, 2 ) );

        $("#result_fee").val(round_decimals(setup_fee_increment * result_price, 2 ));
        $("#result_monthly_fee").val(round_decimals(monthly_fee_increment * result_monthly_price, 2 ));

    });

    
    $("#submitbutton").attr("disabled", "disabled");

    $(".signature").click(function() {     //doubleagreesubmit! ftw
       
        var sign = $("#electronic_signature").is(":checked");
        var sign_spouse;

        if ( $("#electronic_signature_spouse").length > 0 ) {
            // alert("The ID exists");
            sign_spouse = $("#electronic_signature_spouse").is(":checked");
        }else{
            //set to true if the element doesn't exist so they can submit single'
            sign_spouse = true;
        }
        // alert(sign + sign_spouse);

        if (sign == true && sign_spouse == true) {
            $("#submitbutton").removeAttr("disabled");
        }
        else {
            $("#submitbutton").attr("disabled", "disabled");
        }
    });



    $(".focus_next_field").keyup(function(){
        var field =  $(this).attr("id");
        field = "#" + field;
        
        var size = $(this).attr("size");
        //alert(field + ' ' + size + ' ' + $(field).val().length )
        if(  ($(field).val().length == size) &&  (isNaN($(field).val())==false)  ){
            lastChar = field.length - 1;  //find last character of field name
            oldFieldNo = field.charAt(lastChar);
            fieldNo = field.charAt(lastChar);  //find current fields no.
            fieldNo ++; //add 1 to it
            nextField = field.replace(oldFieldNo,fieldNo);
            $(nextField).focus() //focus next field
            $(nextField).val('');  //empty field if went back
        }

    })




});

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");
    phone_number = phone_number.replace(/./g, "-");
    return this.optional(element) || phone_number.length > 9 &&
    phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");


//deprecating to thickbox hopefully
function Lvl_openWin(u,n,w,h,l,t,c,f,x) { //v2.0 4LevelWebs
    var ww=((screen.width-w)/2);if(c==1){
        l=ww;t=(screen.height-h)/2;
    }if(c==2){
        l=ww
    }
    f+=',top='+t+',left='+l;LvlWin = window.open(u,n,f);LvlWin.focus();
    document.MM_returnValue=false;
}


//pad decimals function
function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}


//i am 1337 --- <-- i thought i was 1337 in 2006 in 2009 i realize how *(&(*& this code is :)
function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++)
            value_string += "0"
    }
    return value_string
}
