<script type="text/javascript">

var dateObject = {day:'',month:'',year:'',temp_day: ''};

// PURPOSE OF THIS OBJECT IS HOW MANY DAYS IN SPECFIC MONTH

var monthDaysObject = {'1':31,'2':28,'3':31,'4':30,'5':31,'6':30,'7':31,'8':31,'9':30,'10':31,'11':30,'12':31};
  
//Dynamic data generation reference technique
  $(document.body).on('change','.installment_planamount',function(){

      show_remaining_amount();

  });

  function showInstallmentPercentage(event,element,key_element,flag)
  {
     var sum_amount = getAmountSum($('.installment_planamount'));

     var agreed_amount       = isDefaulter("<?php echo e($lagging_amount); ?>");
    
     var remainingamount = (agreed_amount-sum_amount);

     var amount_field        = $('.new_plan_amount_'+key_element);
     
     var percentage_field    = $('.plan_percentage_'+key_element);
     
     var percentage = 0;

     var amount     = 0;

      // if(flag == "true")
      // {
      //     var amount_field        = $(element);

      //     var percentage_field    = $('.plan_percentage_'+key_element);
      // }
      // else if(flag == "false")
      // {
      //     var amount_field        = $('.new_plan_amount_'+key_element);

      //     var percentage_field    = $(element);
      // }

      if(flag == "true" && agreed_amount > 0 && amount_field.val() > 0)
      {
         if(amount_field.val() <= agreed_amount)
         {
            percentage = (amount_field.val() * 100);

            percentage = percentage/agreed_amount;  

            amount     = amount_field.val();
         }
         

      }
      else if(flag == "false" && agreed_amount > 0 && percentage_field.val() > 0 && percentage_field.val() <= 100 )
      {

         percentage = (percentage_field.val()/100);

         amount     = agreed_amount * percentage;

         percentage = percentage_field.val();
      }

      if(remainingamount > 0 && amount <= remainingamount)
      {
          
        amount_field.val(Math.round(amount));

        percentage_field.val(Math.round(percentage));

        calculate_InstallmentDivision(event,this);
      }
      else
      {

        amount_field.val((0));

        percentage_field.val((0));
        messageToaster('warning','Invalid Input Field','Invalid Amount');
      }

          

      




      show_remaining_amount();


  }

  function replaceDayMonthFormat(installment_date)
  {
      // THIS FUNCTION WORKING ON FORMAT 2019-01-02
     
      //SEPRATE INTO 3 PARTS
      installment_date = installment_date.split('-');

      // CHECK MONTH RANGE 1 TO 9 THEN ATTACH 0
      if(installment_date[1] >= 1 && installment_date[1] <= 9)
      {
         installment_date[1] = '0'+installment_date[1];
      }

      // CHECK DAY RANGE 1 TO 9 THEN ATTACH 0
      if(installment_date[2] >= 1 && installment_date[2] <= 9)
      {
         installment_date[2] = '0'+installment_date[2];
      }  

      // AGAIN MERGE INSTALLMENT DATE
      return installment_date[0]+'-'+installment_date[1]+'-'+installment_date[2];
  }
 

  function show_remaining_amount()
  {
    var amountsum = getAmountSum($('.installment_planamount'));
    var agreedamount = "<?php echo e($lagging_amount); ?>";
    var remainingamount = (agreedamount-amountsum);
 
    $('#show_remaining_amount').html(remainingamount);
  }

   //FOR THOSE WHO WANT TO ADD THEIR OWN PAYMENT ENTRY
	function addRow_Installment(event,id)
	{
		event.preventDefault();

	  var amountsum = getAmountSum($('.installment_planamount'));
    var agreedamount = "<?php echo e($lagging_amount); ?>";
    var remainingamount = (agreedamount-amountsum);

		if(remainingamount > 0)
		{

        $('#btn_installment_plan').show();

					var auto_generate = 'amount_'+(countPlanList('#installment_table tr') + 1);

       //INTRODUCED THIS QUOTE VARIABLE BECAUSE WE HAD TO CONCATENATE IT WITH THE CLASS BECAUSE OF CONFLICT OF SINGLE AND DOUBLE QUOTES
		   var special_char = "'";

       var key_element = "<?php echo e(uniqid()); ?>"+"single";

		   var percentage_function = "showInstallmentPercentage(event,this,'"+key_element+"','false');";
       var amount_function     = "showInstallmentPercentage(event,this,'"+key_element+"','true');";



		var description ='<input class = "form-control form-control-sm cls_alpha_numeric" placeholder="Description" type="text" name="description[]"/>';
		

		var amount = '<input onchange="'+amount_function+'" placeholder="Amount" value="'+remainingamount+'" class="installment_planamount new_plan_amount_'+key_element+' form-control form-control-sm cls_decimal_digit" type="text" name="amount[] "/>';

    var percentage = '<input onchange="'+percentage_function+'" placeholder="Percentage" value="'+((remainingamount*100)/agreedamount)+'" class="plan_percentage_'+key_element+' form-control form-control-sm cls_decimal_digit" type="text" name="plan_percentage[] "/>';


        
        var type_of_payment = <?php echo json_encode(EF::getPlanType(), 15, 512) ?>;

		    var dropdown_payment = '<select class = "form-control form-control-sm cls_selection" name="payment_type[]"><option value = "0" selected>Select Type</option>';

		var due_date = '<input class = "form-control form-control-sm cls_date" type="date" name="date[]"/>';

			$.each(type_of_payment, function( index, value ) 
		     {
		    	if(value!= "One Time")
		    	{
		    		dropdown_payment+='<option value="'+value+'">'+value+'</option>';
		    	}
		

		     });

		dropdown_payment+='</select>';


		var buttons = "'#installment_table'";
		

		var action = '<button class="btn-danger btn-sm" onclick="remove_InstallmentRow(event,this)"><i class="fa fa-times"></i></button>';

		var view = '<tr><th scope = "row">'+(countPlanList('#installment_table tr') + 1)+'</th><td><div>'+description+'<small style = "float:none;" class="form-errors  req" value="*"><?php echo e($errors->first("description[]",":message")); ?></small></div></td><td><div>'+dropdown_payment+'<small style = "float:none;" class="form-errors  req" value="*"><?php echo e($errors->first("payment_type[]",":message")); ?></small></div></td><td>'+percentage+'</td><td><div>'+amount+'<small style = "float:none;" class="form-errors  req" value="*"><?php echo e($errors->first("amount[]",":message")); ?></small></div></td><td><div>'+due_date+'<small style = "float:none;" class="form-errors  req" value="*"><?php echo e($errors->first("date[]",":message")); ?></small></div></td><td>'+action+'</td></tr>'; 



		$(id).append(view);
    
    show_remaining_amount();



		}

    
	}


  function rearrangeTableOrder(table_object)
  {
  	 var count = 0;

  	 table_object = $(table_object);

  	 table_object.each(function(){

  	 	$(this).find('th').html(++count);
  	 

  	 });

  	 return count;
  }

    function clickAutomateButton(event)
  {
  	  event.preventDefault();

          var amountsum = getAmountSum($('.installment_planamount'));
          var agreedamount = "<?php echo e($lagging_amount); ?>";
          var remainingamount = (agreedamount-amountsum);

          if (remainingamount > 0)
          {

              $('#automatediv').show();
          }
  	
           
  
  }

	function remove_InstallmentRow(event,obj)
  {
  
  	event.preventDefault();

  	$(obj).closest("tr").remove();
  	rearrangeTableOrder('#installment_table tr');  

    if(countPlanList('#installment_table tr') > 0)
    {
       $('#btn_installment_plan').show();
    }
    else
    {
       $('#btn_installment_plan').hide();

    }

      show_remaining_amount();

  

  }

  function changeInstallmentMode(event,obj,class_name) {
   $value = obj.value;

   if($value == 1){

      $('.'+class_name).val('Monthly');
   }
   else if($value == 3){
      $('.'+class_name).val('Quarterly');
    
   }
   else if($value == 6){
      $('.'+class_name).val('Semi Annually');
    
   }
   else{
      $('.'+class_name).val('Annually');
   }

  }

  function calculate_InstallmentDivision(event,obj)
  {

    var bi_interval        = isDefaulter($('#interval').val());



    var bi_interval_amount = isDefaulter($('#interval_amount').val());

    var number             = isDefaulter($('.number').val());


    var divided_interval = 0;


    var total_installmentamount = 0;

    var calculate_interval_amount  = 0;

    var message = "";

    var agreed_amount              = "<?php echo e($lagging_amount); ?>";

    var updated_divided_interval = 0;

  

    if(bi_interval > 0 && number >= bi_interval)
    {

  
        divided_interval = parseInt(number/bi_interval); 

        total_installments = parseInt(number);


        calculate_interval_amount  = divided_interval * bi_interval_amount;


      
      


        total_installmentamount    = parseInt(getAmountSum($('.installment_planamount')) + parseInt(calculate_interval_amount));

       

    
   



        message = "Total Interval Based Amount :"+divided_interval + "*" +bi_interval_amount + "=" +calculate_interval_amount + "" +'<br>';
    }
    
    else
    {
        total_installments = $('#number').val();

        total_installmentamount    = getAmountSum($('.installment_planamount'));

    }

  	 var divided_amountsum          = (agreed_amount - Math.abs(total_installmentamount));


   

  	 var installment_amount         = Math.floor(divided_amountsum / (parseInt(total_installments)));

    



     var new_nof_installment = (total_installments);


     message += "Total Installment Amount: " +(new_nof_installment) + "*" +installment_amount +"="+(new_nof_installment*installment_amount);

    if(bi_interval == '' && bi_interval_amount == '' && number == '')
    {

    
      $('#installmentamount').val();
      $('#plan_message').html('');


    }
    else
    {
       $('#installmentamount').val(installment_amount);
       $('.amount_into_words').val(numberInWords($('#installmentamount').val()));
       $('#plan_message').html(message);
    }


  	

      

  	

  }

    function create_InstallmentPlan(event,obj)
    {
    	  event.preventDefault();

        var bi_interval            = isDefaulter($('#interval').val());

        var number_of_installments =  $('#number').val();

        var installment_amount     =  $('#installmentamount').val();

        var date                   =  $('#installmentdate').val();

        var gap                    =  $('select[name=gap]').val();

        var bi_amount                 =  isDefaulter($('#interval_amount').val());

        var agreedamount = "<?php echo e($lagging_amount); ?>";

        var bi_interval_amount = isDefaulter($('#interval_amount').val());

        var decided_amount = 0;

        var divided_interval = 0;


        if(bi_interval > number_of_installments)
        {
           field_unsuccess($('#interval'),'Invalid Interval');

            return false;

        }

        if(bi_interval > 0 && number_of_installments >= bi_interval)
        {
           divided_interval = parseInt(number_of_installments/bi_interval); 

           decided_amount = (installment_amount*(number_of_installments-divided_interval));

           number_of_installments = parseInt(number_of_installments);
        }
        else
        {
          decided_amount = (installment_amount*number_of_installments);
        }







    
        if(number_of_installments <= 0)
        {
            field_unsuccess($('#number'),'No. of installments is required');

            return false;
        }


        if(isDefaulter(bi_interval_amount)>isDefaulter(agreedamount))
        {
          field_unsuccess($('#interval_amount'),'Interval amount is invalid');
            
            return false;
        }

        if(installment_amount <= 0)
        {
            field_unsuccess($('#installmentamount'),'Installment amount is required');
            
            return false;
        }

        if(isDefaulter(agreedamount) < isDefaulter(decided_amount) )
        {
        
            field_unsuccess($('#installmentamount'),'Installment amount is invalid');
            
            return false;
        }

        field_refersh($('#installmentamount'));


        if(date == "")
        {
           
            field_unsuccess($('#installmentdate'),'Plan start date is required');
            
            return false;
        }
        field_refersh($('#installmentdate'));


        if(gap <= 0)
        {
           
            field_unsuccess($('input[name=gap]'),'Installment gap is required');
            
            return false;
        }

        field_refersh($('input[name=gap]'));



        date = new Date(date);

        dateObject.day =  date.getDate();

        dateObject.month = (date.getMonth()+1);

        dateObject.year = date.getFullYear(); 

        date = getDateFormat(dateObject.day,dateObject.month,dateObject.year);

        var bi_interval_count = bi_interval;

        for(i = 1 ; i<= number_of_installments; i++)
        {

            
           

            if(number_of_installments >= bi_interval && bi_amount > 0 && (i) == bi_interval_count)
            {
                if(i == (number_of_installments))
                {


                   
                    // FINAL REMAINIGN AMOUNT
                    var amountsum = getAmountSum($('.installment_planamount'));
                    var agreedamount = "<?php echo e($lagging_amount); ?>";
                    var remainingamount = (agreedamount-amountsum);

                    bi_amount = (remainingamount);
                   
                   bi_amount = isDefaulter(bi_amount) - isDefaulter(installment_amount);


                    
                    // END
                }





                i_amount =  isDefaulter(bi_amount) + isDefaulter(installment_amount);
  

                bi_interval_count += bi_interval;
                addInstallment(i,i_amount,date);

               

            }
            else
            {

                if(i == (number_of_installments))
                {
                   
                    // FINAL REMAINIGN AMOUNT
                    var amountsum = getAmountSum($('.installment_planamount'));
                    var agreedamount = "<?php echo e($lagging_amount); ?>";
                    var remainingamount = (agreedamount-amountsum);

                    installment_amount = isDefaulter(remainingamount);
                    
                    // END
                }
                 addInstallment(i,installment_amount,date);


            }
          

           dateObject.month = (parseFloat(dateObject.month)+parseFloat(gap));
           date = getDateFormat(dateObject.day,dateObject.month,dateObject.year);

           

        }

        





        if(countPlanList('#installment_table tr') > 0)
        {
           $('#btn_installment_plan').show();
        }
        else
        {
           $('#btn_installment_plan').hide();

        }


  }
  //i MEANS INSTALLMENT

  function addInstallment(unique_num,i_amount,i_date)
	{
      i_date =  replaceDayMonthFormat(i_date);

		event.preventDefault();

    var agreedamount = "<?php echo e($lagging_amount); ?>";

    var count = $('#installment_table tr').length;

		var description =     '<input placeholder="Description" class="form-control form-control-sm cls_alpha_numeric" value="Installment '+unique_num+'" type="text" name="description[]"/>'


		// var amount = '<input class = "form-control form-control-sm cls_decimal_digit installment_planamount" placeholder="Amount" value="'+i_amount+'"  type="text" name="amount[]"/>';

     var key_element = "<?php echo e(uniqid()); ?>"+unique_num;

     var percentage_function = "showInstallmentPercentage(event,this,'"+key_element+"','false');";
     var amount_function     = "showInstallmentPercentage(event,this,'"+key_element+"','true');";

    var amount = '<input onchange="'+amount_function+'" placeholder="Amount" value="'+i_amount+'" class="installment_planamount new_plan_amount_'+key_element+' form-control form-control-sm cls_decimal_digit" type="text" name="amount[] "/>';

    var percentage = '<input onchange="'+percentage_function+'" placeholder="Percentage" value="'+((i_amount*100)/agreedamount).toFixed(2)+'" class="plan_percentage_'+key_element+' form-control form-control-sm cls_decimal_digit" type="text" name="plan_percentage[] "/>';


        
    var type_of_payment = <?php echo json_encode(EF::getPlanType(), 15, 512) ?>;
        

		var dropdown_payment = '<select class = "form-control form-control-sm cls_selection" name="payment_type[]">';

		var due_date = '<input class = "form-control form-control-sm cls_date" type="date" name="date[]" value="'+i_date+'"/>';

			   $.each(type_of_payment, function( index, value ) 
		     {
  		    	if(value == "Installment")
  		    	{
  		    		  dropdown_payment+='<option value="'+value+'">'+value+'</option>';
  		    	}
		
		     });

		dropdown_payment+='</select>';


		var id = '#installment_table';
		

		var action = '<button class="btn-danger btn-sm" onclick="remove_InstallmentRow(event,this)"><i class="fa fa-times"></i></button>';

		var view = '<tr><th scope = "row">'+(countPlanList('#installment_table tr') + 1)+'</th><td><div>'+description+'<small style = "float:none;" class="form-errors  req" value="*"><?php echo e($errors->first("description[]",":message")); ?></small></div></td><td><div>'+dropdown_payment+'<small style = "float:none;" class="form-errors  req" value="*"><?php echo e($errors->first("payment_type[]",":message")); ?></small></div></td><td>'+percentage+'</td><td><div>'+amount+'<small style = "float:none;" class="form-errors  req" value="*"><?php echo e($errors->first("amount[]",":message")); ?></small></div></td><td><div>'+due_date+'<small style = "float:none;" class="form-errors  req" value="*"><?php echo e($errors->first("date[]",":message")); ?></small></div></td><td>'+action+'</td></tr>'; 

		$(id).append(view);   

     automatePlanReset();

    $('#automatediv').hide();



	}

    function getAmountSum(element)
     {
  	var amount = 0;

  	element.each(function(event){

  		amount+= isDefaulter($(this).val());
  	});

  	return amount;
     }

  function getDateFormat()
  {

    dateObject.temp = dateObject.day;


    if(dateObject.month > 12)
    {
        dateObject.month = Math.abs(dateObject.month - 12);
        dateObject.year++;
    }

    // DAYS VERIFICATION IN SPECFIC MONTH
    if(dateObject.day > monthDaysObject[dateObject.month])
    {
        dateObject.day = Math.abs(monthDaysObject[dateObject.month]);
    }

    new_date = dateObject.year+"-"+dateObject.month+"-"+dateObject.day;

    dateObject.day = dateObject.temp;

    return new_date.trim();
  }

$(function () {
        $("#biannual_checkbox").click(function () {
            if ($(this).is(":checked")) {
                $(".annual_plan_section").show();
              
            } else {
                $(".annual_plan_section").hide();
                $("#interval").val('');
                $("#interval_amount").val('');
               
            }
        });
    });

  function automatePlanReset()
  {
      $('#number').val('');

      $('#installmentamount').val('');

      $('#installmentdate').val('');

      $('input[name=gap]').val('');

      $('#interval').val('');

      $('#interval_amount').val('');
        $('#plan_message').html('');

       $('#biannual_checkbox').prop('checked',false);

  }
  function clearInstallmentPlan(event,id)
  {
    event.preventDefault();
    $(id).html('');
    $('#btn_installment_plan').hide();
  }

  function intervalReset()
  {
      event.preventDefault();

   

      // $('#installmentamount').val('');

  }

  function showFinalAmount(event,key_element)
  {

    $('.new_plan_amount_'+key_element).val('');

     var sum_amount = getAmountSum($('.installment_planamount'));



      // INSTALLMENT SUM * NOF INSTALLMENTS
      var nof_installment       = isDefaulter($('#number').val());

      var decided_installment   = isDefaulter($('#installmentamount').val());

      var total_plan_amount = 0;

      var message = "";


      // INSTALLMENT BI INTERVAL PORTION
      var bi_interval        = isDefaulter($('#interval').val());
     
      var bi_interval_amount = isDefaulter($('#interval_amount').val());

      var total_interval_amount = 0;

      var divided_interval = 0;

      var message1 = 0;

      var total_interval_amount = 0;

      divided_interval = parseInt(nof_installment/bi_interval); 

      calculate_interval_amount  = divided_interval * bi_interval_amount;

      message1 = "Total Interval Based Amount :"+divided_interval + "*" +bi_interval_amount + "=" +calculate_interval_amount;

      if(bi_interval > 0 && bi_interval_amount > 0)
        {
          total_interval_amount = divided_interval * bi_interval_amount;

          $('#plan_message').html(message1);

        }

      message += "<br>Total Installment Amount: " +(nof_installment) + "*" +decided_installment +"="+(nof_installment*decided_installment);


      if(decided_installment > 0 && nof_installment > 0)
        {
          
          total_plan_amount = decided_installment * nof_installment;

          $('#plan_message').append(message);

        }


      var agreed_amount  = isDefaulter("<?php echo e($lagging_amount); ?>");

      var remaining_amount = (agreed_amount - (sum_amount + total_interval_amount + total_plan_amount));     

      if(remaining_amount > 0)
        {

            remaining_amount += isDefaulter($('.new_plan_amount_'+key_element).val());

            $('.new_plan_amount_'+key_element).val(remaining_amount);


            percentage = (remaining_amount * 100);

            percentage = percentage/agreed_amount;  

            $('.plan_percentage_'+key_element).val(Math.round(percentage));

        }

        else
        {
          $('.new_plan_amount_'+key_element).val('');     

          // percentage = (remaining_amount * 100);

          // percentage = percentage/agreed_amount;  

          $('.plan_percentage_'+key_element).val('');

        }

  }

  function showRemovePlan()
  {
    var counter = 0;

    $('.checked_installment').each(function(event)
     {
          if($(this).prop('checked'))
          {
             $(this).prop('checked',true);
             counter++;

          }
          else
          {
             $(this).prop('checked',false);

          }
         
     });


    if(counter > 0)
    {
      $('.clearremove_installment_button').show();
    }
    else
    {
        $('.clearremove_installment_button').hide();
    }
  }

  $(document.body).on('change','.checked_installment',function(){

     showRemovePlan();

  });

  function selectAllInstallment(event,obj)
  {
    event.preventDefault();
    
    obj = $(obj);

     $('.checked_installment').each(function(event)
     {

          if(obj.prop('checked'))
          {
             $(this).prop('checked',true);

          }
          else
          {
             $(this).prop('checked',false);

          }
         
     });

     showRemovePlan();


  }

  function bulkInstallmentRemove(event,booking)
  {
     event.preventDefault();


    if(confirm("Are you sure you want to remove installment plan?"))
    {
        var route = '/bulkinstallmentremove';

        showLoader();


        var installment_list = {};
        var counter = 0;

        $('.checked_installment').each(function(event){

            if($(this).prop('checked'))
            {
               installment_list[counter] = $(this).prop('value'); 
               counter++;
            }
        });


        var formdata = {'booking_id':booking,'installment_list':installment_list,_token:token};

        $.post(route, formdata, function(result)
        {
          
            removeLoader();
            location.reload();

        },'json')
        .fail(function(data) {
            removeLoader();
            
        
      });
    }
    else
    {

    }
    
  }

  $(document.body).on('change','.installment_planamount',function(event){
    var amount = getAmountSum($('.installment_planamount'));

    var agreedamount = "<?php echo e($lagging_amount); ?>";

    var remainingamount = (agreedamount-amount);

    if(remainingamount < 0)
    {


       messageToaster('warning','Invalid Input Field','Invalid Amount');
        field_unsuccess($(this),'Installment amount is invalid');
        
        return false;

    }
     field_refersh($(this));
  });

  // AJAX REQUEST TO STORE INSTALLMENT PLAN 
  function storeInsallmentPlan(event,obj)
  {
      event.preventDefault();

      var obj = $('#form_add_installment');
      var route = obj.attr('action');     
      var formdata = obj.serialize();
                   
      showLoader();

      $.post(route, formdata, function(result)
      {
          if(result)
          {
              // Reload the current page without the browser cache
              messageToaster('success','Plan has been created.','Success');

              location.reload(true);
                  
          }
      removeLoader();


      },'json')
      .fail(function(data) {

          messageToaster('error','Required form validation.','Failed');
          
          ajax_show_error(data,obj,$('#md_make_installment'));

         
          removeLoader();
    
        });    
  }

  // AJAX REQUEST TO STORE ONE TIME PLAN 
  function storeOneTimePlan(event,obj)
  {
      event.preventDefault();

      var obj = $('#form_add_onetime');
      var route = obj.attr('action');     
      var formdata = obj.serialize();
                   
      showLoader();

      $.post(route, formdata, function(result)
      {
          if(result)
          {
              // Reload the current page without the browser cache
              messageToaster('success','Plan has been created.','Success');
              
              location.reload(true);
                  
          }
      removeLoader();


      },'json')
      .fail(function(data) {

          messageToaster('error','Required form validation.','Failed');
          
          ajax_show_error(data,obj,$('#md_make_installment'));

         
          removeLoader();
    
        });    
  }

</script><?php /**PATH /home/ubuntu/rebmgisplus/skylite/resources/views/scripts/installment.blade.php ENDPATH**/ ?>