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


//        $('#cc_type').change(function(){
//            $("#signupform").validate().element('#cc_num');
//        });
//


var signupPrice=new Array();
signupPrice[0]=""; // placeholder 
signupPrice[1]='49.00';
signupPrice[2]=round_decimals(signupPrice[1]*2, 2);

var monthlyPrice=new Array();
monthlyPrice[0]=""; // placeholder 
monthlyPrice[1]='49.00';
monthlyPrice[2]=round_decimals(monthlyPrice[1]*1.5, 2);


function gup( name ) {
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
	    return "";
	  else
	    return results[1];
}

function setSignupData(id) {
	$('#signup-fee-price').html('$'+signupPrice[id]+' ');
	$('#signup-monthly-price').html('$'+monthlyPrice[id]+' ');
	$('#result_fee').val(signupPrice[id]);
	$('#result_monthly_fee').val(monthlyPrice[id]);
	$.ajax({
		   type: "POST",
		   dataType: 'json',
		   url: "includes/dateTimeHandler.php",
		   data: 'month='+gup('m')+'&day='+gup('d')+'&year='+gup('y'),
		   success: function(msg){
				$("#sign-up-date-six-days").html(msg.six_days);
				$("#sign-up-date-next-month").html(msg.next_month);
		   }
	}); 
}




jQuery(document).ready(function() {	

	setSignupData(1);	
//		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');					 					
				}
	}
	
	var zip_being_edited = false;
	
	$('#zip').blur(function() {	
		checkZipAndState();		
	});
	$('#zip').keyup(function() {	
		if (zip_being_edited) {
			checkZipAndState();	
		}
	});
	$('#state').change(function() {	
		checkZipAndState();		
	});
	
	

	
	function checkZipAndState() {		
		
		var zip = jQuery('#zip').val();		
		var state_selected = $("#state option:selected");
		
		if (state_selected.val() == '' || zip == '') { // only run if both are populated
			$('#zip_state_error_msg').html(' ');;
			return false;
		}
		zip_being_edited = true;
		
		jQuery.ajax({ 			  
			  cache: false, 
			  url: "/content-management/check_zipcode.php", 
			  data: "action=checkzip&zip="+zip+"&state="+state_selected.val(),
			  success: function(res){ 				 
			    if (res == 1) {
			    	$('#zip_state_error_msg').html(' ');;
			    } else {			    	
			    	$('#zip_state_error_msg').html(' Zip Does Not Match State');;
			    	if (jQuery('#zip').val() == '') {
			    		$('#zip_state_error_msg').html(' ');;
			    	}
			    }
			  } 
			});		
		
	}
	
	$('#zip,#workphone1,#workphone2,#workphone3,#homephone1,#homephone2,#homephone3,#ss_number1,#ss_number2,#ss_number3,#social_spouse1,#social_spouse2,#social_spouse3').keyup(function() {		
		var temp = new String($(this).val());
		temp = temp.replace(/[^0-9]+/g,'');
		temp = temp.replace(/ /g,'');
		$(this).val(temp);
		
	});
	
	function emailsNotMatching() {
		var email_one = $("#email_one");
		var email_confirm = $("#email_confirm");
		if (email_one != email_confirm) {
			return false;
		}
		return true;
	}
	

	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 () {
		
		// check to make sure the zipcode is validated
		var zip_code_avaliable = $('#zip_state_error_msg').html();
		
		if (zip_code_avaliable == ' Zip Does Not Match State') {			
			$('#zip').focus();
			$('#zip_state_error_msg').fadeOut().fadeIn().fadeOut().fadeIn();
			return false;
		}
		
		
		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; 
		};		

		
		if ($("#signupform").valid()) { // page 1
			$('#submitbuttondiv input').css("display", "none");			
			$('#submitbuttondiv').append('<span style="color: #003399; font-weight: bold">Processing... Please Wait</span>');
		}
		
		
		
		
		var new_letter = ucfirst($('#first_name_field').val());
		$('#first_name_field').val(new_letter);
		
		var new_letter = ucfirst($('#last_name_field').val());
		$('#last_name_field').val(new_letter);
		
		var new_letter = ucfirst($('#city_field').val());
		$('#city_field').val(new_letter);	
		
		var new_letter = ucfirst($('#street_field').val());
		$('#street_field').val(new_letter);			

		var new_letter = ucfirst($('#first_name_spouse').val());
		$('#first_name_spouse').val(new_letter);			

		var new_letter = ucfirst($('#last_name_spouse').val());
		$('#last_name_spouse').val(new_letter);			

		
	}); 
	
	function ucfirst(str) { 
		if (str == undefined) {
			return;
		}
		var firstLetter = str.slice(0,1); 
		return firstLetter.toUpperCase() + str.substring(1); 
	} 

	
// 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();
						}
				},
				email: {
					
					
				}, 
				email_confirm: {					
					equalTo: "#email_one"
				}
				
				
				// end south carolina check
            },	
			messages: {
				cc_num: 'Invalid Number or Card Type',
				email_confirm: {
					equalTo: "Email addresses do not match"
				},
				zip: 'Zip Does Not Match State'
			},
				
								 
			
			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;
        	setSignupData(2);

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

            $("#first_name_spouse").attr("class", "required")
            $("#last_name_spouse").attr("class", "required")
        }else{
//            setup_fee_increment = 1; 
//			monthly_fee_increment = 1;
        	setSignupData(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
}



