$(document).ready(function () {

  if( $('[name="tax_amount"]').val() != '' ){
     $('span.fee').html($('[name="tax_amount"]').val());
  }

  if( $('[name="amount"]').val() != '' ){
     $('span#totalAmount').html($('[name="amount"]').val());
  }

  $('#terms_conditions').on('change', function() {
    var is_checked = $(this).is(":checked");
    if(is_checked == true ) {
      $('.payButton').removeClass('disabled');
    } else {
      $('#payButton').addClass('disabled');
    }
  })


  $('#renew_form').on('submit', function() {
    $('.payButton').attr('disabled', true);
  })


  $('#step1next').on('click', function() {
    $('.ballance_error').hide();
    if( !$(this).hasClass('disabled') ) {
      var renew_data = $('#domains_renew_list').serializeArray();
      var data = {};
      $(renew_data).each(function(index, obj){
          data[obj.name] = obj.value;
      });
      var domain_data =JSON.stringify(data);

      $.ajax({
        type:'POST',
        url:'/intranet/calculate-price',
        dataType: "json",
        headers: {
          'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        },
        data:data,
        beforeSend: function(){
            $('.account_wait').css({'display': 'block'});
        },

        success:function(data){

          if( data.error ) {
            $('.ballance_error').show();
            $('.account_wait').css({'display': 'none'});
          } else {
            $('.account_wait').css({'display': 'none'});
            //console.log(data);
            var content = '';
            for (var domain in data.domains) {
              if( data.domains[domain].period != 'do_not_renew' ) {
                price = data.domains[domain].price.toFixed(2);
                content = content + '<tr><td>'+domain+'</td><td>'+data.domains[domain].period+' year(s)</td><td style="text-align:right;padding-right:0px;">£'+price+'</td></tr>';
              }

            }
            $('#step2 .domain-table').html(content);
            $('#sub-total span').html('£' + data.subtotal.toFixed(2) );
            $('#total span').html('£' + data.total );
            $('span#totalAmount').html(data.total);
            $('#amount_field').val(data.total);

            if( data.tax != 0 ) {
              $('#tax-info span').html('£' + data.tax.toFixed(2) );
            }

            if( data.total > data.subtotal ) {

              $('#tax_amount').val( (data.total - data.subtotal).toFixed(2) )
            } else {
              $('.small-info-payment').hide();
            }
            $('#step1').hide();
            $('#step2').show();
            $('[name="renew_data"]').val(JSON.stringify(data));
          }

        }

      });
    }

    return false;
  });

    $('a.info').click( function(event){

    event.preventDefault();

    $('#overlay').fadeIn(400,

      function(){

        $('#modal_form')

          .css('display', 'block')

          .animate({opacity: 1, top: '50%'}, 200);

    });

  });

  $('a.terms_link').click( function(event){

    event.preventDefault();

    $('#overlay').fadeIn(400,

      function(){

        $('#modal_form2')

          .css('display', 'block')

          .animate({opacity: 1, top: '10%'}, 200);

    });

  });

  $('#modal_close2, #overlay').click( function(){

    $('#modal_form2')

      .animate({opacity: 0, top: '0%'}, 200,

        function(){

          $(this).css('display', 'none');

          $('#overlay').fadeOut(400);

        }

      );

  });


  $('#modal_close, #overlay').click( function(){

    $('#modal_form')

      .animate({opacity: 0, top: '45%'}, 200,

        function(){

          $(this).css('display', 'none');

          $('#overlay').fadeOut(400);

        }

      );

  });

  $('#termsBack').on('click', function() {

    $('#step2').show();
    $('#terms_conditions').hide();

    return false;
   });

  $('#agree').on('change', function() {
    var is_checked = $('#agree').is(":checked");
    if(is_checked == false ) {
      $('#termsNext').addClass('disabled');
    } else {
      $('#termsNext').removeClass('disabled');
    }
  });


$('#cardNumber').on('keyup', function() {
    $('#cardNumber').validateCreditCard(function(result) {
      if( result.length_valid == true ) {
         if( result.luhn_valid != true ) {
          $('.payButton').attr('disabled', true);
          $('.payButton').addClass('disabled');
          $('.card-error').show();
         }else {
           $('.payButton').attr('disabled', false);
            $('.payButton').removeClass('disabled');
            $('.card-error').hide();
         }
      }

  });
})




  $('#termsNext').on('click', function() {
    var is_checked = $('#agree').is(":checked");
    if(is_checked == false ) {
      alert( 'Please indicate that you have read and agree to the Terms and Conditions' );
    } else {

       var is_checked = $('#pay_by_invoice').is(":checked");
      if(is_checked == false ) {
         $('#terms_conditions').hide();
        $('#step3').show();
      } else {
        var domain_data = $('[name="renew_data"]').val();
        //console.log(domain_data);
        $.ajax({
          type:'POST',
          url:'/intranet/renew-direct-debit',
          dataType: "json",
          headers: {
            'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
          },
          data:{data:domain_data},
          beforeSend: function(){
              $('.account_wait3').css({'display': 'block'});
          },

          success:function(data){
            $('.account_wait3').css({'display': 'none'});
            console.log(data.status);

            if( data.status == true ){
              window.location.replace("https://thinking.fish/intranet/thank-you");
            } else {
              $('.errors_dd').html(data.error + '. Please contact administrator')
            }

          }

        });
      }

    }
    return false;
  });

  $('.terms_wrapper').scroll(function () {

    if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
        $('#agree').removeAttr('disabled');
    } else {

    }
});

   $('#step2Next').on('click', function() {
        $('#step2').hide();
        $('#terms_conditions').show();

    return false;
   });

  $('#step3Back').on('click', function() {
    $('#step2 .domain-table').html('');
    $('#sub-total span').html('');

    $('.alert.alert-danger').html('');
    $('#step1').show();
    $('#step3').hide();

    return false;
   });

  $('.select-period').on('change', function() {
    var disabled = true;
    $('.select-period').each( function() {
      if($(this).val() !=0) {
        disabled = false;
      }
    });
    if( disabled == false ) {
      $('#step1next').removeClass('disabled');
    } else {
      $('#step1next').addClass('disabled');
    }
  })

  $('#step2Back').on('click', function() {
    $('#step2 .domain-table').html('');
    $('#sub-total span').html('');
    $('#step1').show();
    $('#step2').hide();
    return false;
  });

  $('input#cardNumber').bind('keyup change', function(){
    var cardType = getCardType($(this).val().replace(/\s*/g,''));
    console.log(cardType);
    $('ul.creditcards img').removeClass('highlight');
    $('img.creditcard_' + cardType).addClass('highlight');
    $('[name="card_type"]').val(cardType);
  });


});
