(function($) {

$(function() { 
  $(document).ready(function() {
    var typingTimer;                //timer identifier
    var doneTypingInterval = 1500;  //time in ms, 5 second for example
    var $input = $('#edit-email, #edit-fname');
    $input.on('keyup', function () {
      clearTimeout(typingTimer);
      typingTimer = setTimeout(doneTyping, doneTypingInterval);
    });
    var form_submitted = false;
    $( "input.form-submit" ).not('.first_step').on('click', function(e){
      form_submitted = true;
    })
    // Register event to save partial lead only when page closed before submission
    window.addEventListener('beforeunload', function (e) {
      var inputs = $('input.required')
      var name_field = $.trim($( "#edit-fname" ).val());
      var email_field = $.trim($( "#edit-email" ).val());
      if(window.location.href.indexOf("thank-you") < 0 && email_field.length > 0 && isEmail(email_field) && !form_submitted){
        e.preventDefault();
        var last_name = $.trim($( "#edit-lname" ).val());
          var time=$( "#edit-lead_creation_backend" ).val();
          var form_id=$( "#edit-lead_creation_form_id" ).val();
          var ajax_done=$( "#edit-lead_creation_ajax_done" ).val();
          //if(ajax_done==0){
            create_lead_request(email_field,name_field,last_name,time,form_id,ajax_done);
          //}
      }
    });
    var drip_group_container_id_str = $("div.drip-group-container" ).attr( "id" );
    var id_arr = drip_group_container_id_str.split('-');
    var micro_sec_id = id_arr[3];
    var drip_group_option_selected = get_lead_group_option_value(micro_sec_id);
    //on keydown, clear the countdown 
    $input.on('keydown', function () {
      clearTimeout(typingTimer);
    });
    // function doneTyping () {
    //    var last_name = $.trim($( "#edit-lname" ).val());
    //    var email_field = $.trim($( "#edit-email" ).val());
    //    var name_field = $.trim($( "#edit-fname" ).val());
    //    if(email_field) {
    //         var time=$( "#edit-lead_creation_backend" ).val();
    //         var form_id=$( "#edit-lead_creation_form_id" ).val();
    //         var ajax_done=$( "#edit-lead_creation_ajax_done" ).val();
    //        // if(ajax_done==0){
    //           create_lead_request(email_field,name_field,last_name,time,form_id,ajax_done);
    //         //}
    //    }
    // }
    var drip_group_option_checked = get_lead_group_option_value(micro_sec_id); 
   if(drip_group_option_checked=='SELLER'){ //seller
                $('#drip-group-container-'+micro_sec_id).addClass('sell');
                $('#drip-group-container-'+micro_sec_id).removeClass('buy rent other buyer_seller hide-field ');
                process_show_hide_elements(micro_sec_id);
                $( "#drip-seller-subgroup-container-"+micro_sec_id).show();
                
   }else if(drip_group_option_checked=='BUYER'){ //buyer
                $('#drip-group-container-'+micro_sec_id).addClass('buy');
                process_show_hide_elements(micro_sec_id);
                $( "#drip-buyer-subgroup-container-"+micro_sec_id).show();
   }else if(drip_group_option_checked=='RENTER'){ //renter
                $('#drip-group-container-'+micro_sec_id).addClass('rent');
                process_show_hide_elements(micro_sec_id);
                $( "#drip-renter-subgroup-container-"+micro_sec_id).show();
   }else if(drip_group_option_checked=='OTHER'){ //other
                $('#drip-group-container-'+micro_sec_id).addClass('other');
                process_show_hide_elements(micro_sec_id);
                $( "#drip-other-subgroup-container-"+micro_sec_id).show();
   }
   
    $(".step-2 .form-item .form-select").each(function(){
      if( !!$(this).val()){
        $(this).closest('.form-item').addClass('choice');
        $('.step-2 .chosen-container-multi .chosen-choices li.search-field input[type=text]').attr('size',1);
      } 
    });
   function resizeInput() {
    //Check if length needs to be reset for field.
    if($(this).val().length < 1){
        $(this).attr('size', 1); 
    }
    //If user has no input or choices
    if ( $(this).val().length < 1 && $('.chosen-choices .search-choice').length < 1){
      $(this).removeAttr('size');
      $(this).removeAttr('style');
    }
    else if( $(this).val().length<1 ) { 
    //If user has a choice but no new input
      $(this).attr('size', 1); 
    }
    //Resize input to size of input +-
    else
      {
        $(this).attr('size', $(this).val().length);
      }
    };
    // Call resize function above to resize input dynamically based on user input.
    $('.ds .chosen-container .chosen-choices li.search-field input[type=text]').keyup(resizeInput).focusout(resizeInput).each(resizeInput);
    
    $('.form-item .form-select').change(function(){
      console.log('change');
      if($('.chosen-choices .search-choice').length > 0){
        console.log('choice available');
        $(this).closest('.form-item').addClass('choice');
        $('body.ds .chosen-container-multi .chosen-choices li.search-field input[type=text]').attr('size',1);
      }
      else{
        $(this).closest('.form-item').removeClass('choice');
        console.log('no choice');
      }
    });
  }); // ready function ends
    
});

   
function  create_lead_request(email,name_field,last_name,time,form_id,ajax_done){
    var url = window.location.href;
    $.ajax({
      dataType:"html",
      type:"POST",
      url: '/create-lead/backend',
      data: 'lastnamefieldh='+last_name+'&email='+email+'&time='+time+'&form_id='+form_id+'&lead_id='+ajax_done+'&name='+name_field+'&url='+url,
      success: function(msg){
        if(msg){
          $( "#edit-lead_creation_ajax_done" ).val(msg);
          window.close();
        }
      },
      error:function (xhr, ajaxOptions, thrownError){
          alert(xhr.status);
          alert(thrownError);
          window.close();
      } 
    });
}
function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}
})(jQuery);
