var stateObj = {AL:"Alabama",AK:"Alaska",AB:"Alberta",AS:"American Samoa",AZ:"Arizona",AR:"Arkansas",BC:"British Columbia",CA:"California",CO:"Colorado",CT:"Connecticut",DE:"Delaware",DC:"District of Columbia",FL:"Florida",GA:"Georgia",HI:"Hawaii",ID:"Idaho",IL:"Illinois",IN:"Indiana",IA:"Iowa",KS:"Kansas",KY:"Kentucky",LA:"Louisiana",ME:"Maine",MB:"Manitoba",MD:"Maryland",MA:"Massachusetts",MI:"Michigan",MN:"Minnesota",MS:"Mississippi",MO:"Missouri",MT:"Montana",NE:"Nebraska",NV:"Nevada",NB:"New Brunswick",NH:"New Hampshire",NJ:"New Jersey",NM:"New Mexico",NY:"New York",NL:"Newfoundland &amp; Labrador",NC:"North Carolina",ND:"North Dakota",MP:"Northern Mariana Islands",NT:"Northwest Territories",NS:"Nova Scotia",NU:"Nunavut",OH:"Ohio",OK:"Oklahoma",ON:"Ontario",OR:"Oregon",PA:"Pennsylvania",PE:"Prince Edward Island",QC:"Quebec",RI:"Rhode Island",SK:"Saskatchewan",SC:"South Carolina",SD:"South Dakota",TN:"Tennessee",TX:"Texas",TT:"Trust Territory",AA:"US Military AA",AE:"US Military AE",AP:"US Military AP",UT:"Utah",VT:"Vermont",VA:"Virginia",WA:"Washington",WV:"West Virginia",WI:"Wisconsin",WY:"Wyoming",YT:"Yukon"};

    var stateSelect = $("<select></select>").attr("id", "state").attr("name", "state").attr("class", "form-control selectBoxFocus brdr-color");
    stateSelect.append($("<option></option>").attr("value", 0).text('State'));

    var monthSelect = $("<select></select>").attr("id", "cMonth").attr("name", "cMonth").attr("class", "form-control selectBoxFocus");
    monthSelect.append($("<option></option>").attr("value", 0).text('MONTH'));

    var yearSelect = $("<select></select>").attr("id", "cYear").attr("name", "cYear").attr("class", "form-control selectBoxFocus");
    yearSelect.append($("<option></option>").attr("value", 0).text('YEAR'));
          
    $.each(stateObj, function(key,valueObj){
       stateSelect.append($("<option></option>").attr("value", key).text(valueObj));
    });

    for(i=1;i<=12;i++){
       monthSelect.append($("<option></option>").attr("value", i).text(i));        
    }
    var currentYear = new Date().getFullYear();

    for(i=currentYear;i<=currentYear+10;i++){
       yearSelect.append($("<option></option>").attr("value", i).text(i));        
    }

// function showPromocode(){
//         $("#promoC").blur(function(){
//     // alert('click me');
//         $("#applyPromo").show();
// });
// }
$('#authorizedFAQForm').on('submit', function() {
    var name = $.trim($('#name').val());
    var email = $.trim($('#email').val());
    var phone = $.trim($('#phone').val());
    var message = $.trim($('#message').val());

    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    var error = false;
    var errorMessage = '';

    if(name == ""){
        error = true;
        errorMessage = "Name is required";
        $('#name').focus();
        if(isMobile){
           alert("Cvv is required");
        }
        else{
            $('.valdMsgName').html(errorMessage);        
            $('.valdMsgName').show();
        }
    }
    else if(email == "" ){
        error = true;
        errorMessage = "Email is required";
        $('#email').focus();
        if(isMobile){
           alert("Cvv is required");
        }
        else{
            $('.valdMsgEmail').html(errorMessage);        
            $('.valdMsgEmail').show();
        }
    }
     else if(!(validateEmail(email))){
        error = true;
        errorMessage = "Please enter valid email";
        $('#email').focus();
        if(isMobile){
           alert("Cvv is required");
        }
        else{
            $('.valdMsgEmail').html(errorMessage);        
            $('.valdMsgEmail').show();
        }
    }
    else if(phone == ""){
        error = true;
        errorMessage = "Phone number is required";
        $('#phone').focus();
        if(isMobile){
           alert("Cvv is required");
        }
        else{
            $('.valdMsgPhone').html(errorMessage);        
            $('.valdMsgPhone').show();
        }
    }
    // else if(isNaN(phone)){
    //     error = true;
    //     errorMessage = "Phone number should be a number";
    //     $('#phone').focus();
    //     if(isMobile){
    //        alert("Cvv is required");
    //     }
    //     else{
    //         $('.valdMsgPhone').html(errorMessage);        
    //         $('.valdMsgPhone').show();
    //     }
    // }
    // else if ((phone.length <= 9) || (phone.length > 15)) {
    //     error = true;
    //     errorMessage = "Phone number should have minimum 10 digits and maximum 15 digits";
    //     $('#phone').focus();
    //     if(isMobile){
    //        alert("Cvv is required");
    //     }
    //     else{
    //         $('.valdMsgPhone').html(errorMessage);        
    //         $('.valdMsgPhone').show();
    //     }
    // }
    else if(message == ""){
        error = true;
        errorMessage = "Message is required";
        $('#message').focus();
        if(isMobile){
           alert("Cvv is required");
        }
        else{
            $('.valdMsgMessage').html(errorMessage);        
            $('.valdMsgMessage').show();
        }
    }
   
    if(error){      
        $('#errorServer').hide();
        $('.errorDiv').html(errorMessage);
        // $('.errorDiv').addClass('alert alert-danger');
        return false;
    }
});

function validateName(){   
  var name = $('#name').val();
  var errorMsg = $('#valdMsgName').text();
  if(name !== "" ){
    $('#valdMsgName').hide();
    // alert('name is there')
  }
}

function validateEmailMsg(){   
  var email = $('#email').val();
  var errorMsg = $('#valdMsgEmail').text();
  if(email !== "" ){
    $('#valdMsgEmail').hide();
  }
}

function validatePhone(){   
  var phone = $('#phone').val();
  var errorMsg = $('#valdMsgPhone').text();
  if(phone !== "" ){
    $('#valdMsgPhone').hide();
  }
}

function validateMessage(){   
  var message = $('#message').val();
  var errorMsg = $('#valdMsgMessage').text();
  if(message !== "" ){
    $('#valdMsgMessage').hide();
  }
}

function submitAuthorizedFAQForm(){
    $('#authorizedFAQForm').submit();
}


var initialName;

function submitSanitationForm(){

    var initialName = $('#initials').val();
    var error = false;
    var errorMessage = '';

    $('#studentInitName').val(initialName);
    
    if(initialName == ""){
        error = true;
        errorMessage = "Please select the initials values";
        $(".logError_san").css("display", "block");
        $('#initialName').focus();
    }
    else{
        $(".logError_san").css("display", "none");
    }

    if(error){      
        $('#errorServer').hide();
        $('.logError_san').html(errorMessage);
        return false;
    }
    
    $('#sanitationModal').modal('hide');
}

var cnt = 0;
var isApplyPromoRunning = false;
function applyPromocode(sid,cid){
    if(!isApplyPromoRunning) {
        isApplyPromoRunning = true;
        var code = $('#promoC').val();
        var originalAmount = $('#amount').val();
        var promoEnterMethod = 2;
        if(code == ""){
           $('.validationErrorMessage30').hide();
        }
       
        if(window.promoEnterMethod !== undefined) {
            promoEnterMethod = window.promoEnterMethod;
        }
       
        if(code.length > 0) {
            if(cnt == 0) {
                $.ajax({
                    type:'POST',
                    url:'/site/cfc/course.cfc?method=getPromocode',
                    dataType:"json",
                    data: {
                        code: code,
                        classId: cid,
                        siteId: sid,
                        promoEnterMethod: promoEnterMethod 
                    },
                    success:function(data) {
                        var dataOBj = JSON.parse(data);
                        
                        if(dataOBj.SUCCESS){
                            var discount = dataOBj.DISCOUNT;
                            var newAmount = originalAmount-discount;
                            newAmount = newAmount.toFixed(2);
                            $('#clsNewPrice').html('$'+newAmount);
                            $('#DiscountAmount').html('$'+originalAmount+'');
                            $('#DiscountMessage').html('After savings of $'+discount+' using code '+code+': ');
                            $('#cardNewPrice').html('$'+newAmount);
                            $('#newPrice').html(+newAmount);
                            $('#amount').val(newAmount);
                            $('.validationErrorMessage30').html('');
                            cnt++;
                            $('.validationErrorMessage30').html('Promo code applied'); 
                            $('.validationErrorMessage30').show(); 
                            $('#promoC').prop('readonly', true);
                        }
                        else {
                            $('.validationErrorMessage30').html('Invalid Promocode');           
                            $('.validationErrorMessage30').show();           
                        }
                        isApplyPromoRunning = false;
                    },
                    error:function(obj) {
                        console.log(obj)
                        isApplyPromoRunning = false;
                    }
                });
            }
            else {
                isApplyPromoRunning = false;
            }
        }
        else{
            isApplyPromoRunning = false; 
        }
    }
 
}
//payment modal after login
function initiatePay(){
    $('.errorD').html('');
    $('#response').html('');
    $('#response').removeClass('alert alert-success');
    $('#response').removeClass('alert alert-danger');
    var clientIp = $.trim($('#ipinfo').val());    
    var FirstName = $.trim($('#FirstName').val());
    var LastName = $.trim($('#LastName').val());
    var Address = $.trim($('#Address').val());
    var Address2 = $.trim($('#Address2').val());
    var City = $.trim($('#City').val());
    var PostalCode = $.trim($('#PostalCode').val());
    var state = $.trim($('#state').val());
    var Email = $.trim($('#Email').val());
    var creditcard = $.trim($('#creditcard').val());
    creditcard = creditcard.replace(/\s/g, "");
    var base64Key = "MTIzNDU2NzgxMjM0NTY3OA==";
    var base64IV = "EBESExQVFhcYGRobHB0eHw==";

    var key = CryptoJS.enc.Base64.parse(base64Key);
    var iv  = CryptoJS.enc.Base64.parse(base64IV);

    var encrypted = CryptoJS.AES.encrypt(creditcard, key, {iv: iv});
    var cipher = encrypted.toString();
    // console.log(encrypted.toString());

    var decrypted =  CryptoJS.AES.decrypt(encrypted, key, {iv: iv})
    
    // console.log(decrypted.toString(CryptoJS.enc.Utf8));

    var cMonth = $.trim($('#cMonth').val());
    var cYear = $.trim($('#cYear').val());
    var cvv = $.trim($('#cvv').val());
    var orderId = $.trim($('#orderId').val());
    var classId = $.trim($('#classId').val());
    var studentId = $.trim($('#studentId').val());
    var siteId = $.trim($('#siteId').val());
    var amount = $.trim($('#amount').val());

    var error = false;
    var errorMessage = '';
    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

    if(FirstName == ""){
        error = true;
        errorMessage = "This is required";
        $('#FirstName').focus();
        if(isMobile){
           alert("First Name is required");
        }
        else{
        $('.validationErrorMessage2').html(errorMessage);   
        }     
    }
    else if(LastName == ""){
        error = true;
        errorMessage = "This is required";
        $('#LastName').focus();
        if(isMobile){
           alert("Last Name is required");
        }
        else{
        $('.validationErrorMessage3').html(errorMessage);  
        }        
    }
    else if(Address == ""){
        error = true;
        errorMessage = "This is required";
        $('#Address').focus();
        if(isMobile){
           alert("Address is required");
        }
        else{
        $('.validationErrorMessage4').html(errorMessage);     
        }     
    }
    else if(City == ""){
        error = true;
        errorMessage = "This is required";
        $('#City').focus();
        if(isMobile){
           alert("City is required");
        }
        else{
        $('.validationErrorMessage5').html(errorMessage);  
        }        
    }
    else if(PostalCode == ""){
        error = true;
        errorMessage = "This is required";
        $('#PostalCode').focus();
        if(isMobile){
           alert("PostalCode is required");
        }
        else{
        $('.validationErrorMessage6').html(errorMessage);   
        }       
    }
    else if(isNaN(PostalCode) || PostalCode.length > 7){
        error = true;
        errorMessage = "Invalid zipcode";
        $('#PostalCode').focus();
        if(isMobile){
           alert("Invalid zipcode");
        }
        else{
        $('.validationErrorMessage6').html(errorMessage);  
        }        
    }
    else if(state == 0 || state == ""){
        error = true;
        errorMessage = "This is required";
        $('#state').focus();
        if(isMobile){
           alert("State is required");
        }
        else{
        $('.validationErrorMessage7').html(errorMessage);
        }          
    }
    // else if(Email == ""){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#Email').focus();
    //     $('.validationErrorMessage8').html(errorMessage);          
    // }
    //  else if(!(validateEmail(Email))){
    //     error = true;
    //     errorMessage = "Please enter valid email";
    //     $('#Email').focus();
    //     $('.validationErrorMessage8').html(errorMessage);          
    // }
    else if(creditcard == ""){
        error = true;
        errorMessage = "This is required";
        $('#creditcard').focus();
        if(isMobile){
           alert("Credit card number is required");
        }
        else{
        $('.validationErrorMessage9').html(errorMessage);
        }          
    }
    else if((creditcard.length < 13 || creditcard.length >17) || isNaN(creditcard)){
        error = true;
        errorMessage = "Invalid credit card";
        $('#creditcard').focus();
        if(isMobile){
           alert("Invalid credit card");
        }
        else{
        $('.validationErrorMessage9').html(errorMessage); 
        }         
    }
    else if(cMonth == "" || cMonth == 0 || isNaN(cMonth)){
        error = true;
        errorMessage = "This is required";
        $('#cMonth').focus();
        if(isMobile){
           alert("Month is required");
        }
        else{
        $('.validationErrorMessage10').html(errorMessage); 
        }         
    }
    else if(cYear == "" || cYear == 0 || isNaN(cYear)){
        error = true;
        errorMessage = "This is required";
        $('#cYear').focus();
        if(isMobile){
           alert("Year is required");
        }
        else{
        $('.validationErrorMessage11').html(errorMessage);   
        }       
    }
    else if(cvv == ""){
        error = true;
        errorMessage = "This is required";
        $('#cvv').focus();
        if(isMobile){
           alert("Cvv is required");
        }
        else{
        $('.validationErrorMessage12').html(errorMessage);     
        }     
    }
    else if(cvv.length < 3 || cvv.length > 4 || isNaN(cvv) ){
        error = true;
        errorMessage = "Invalid CVV";
        $('#cvv').focus();
        if(isMobile){
           alert("Invalid CVV");
        }
        else{
        $('.validationErrorMessage12').html(errorMessage);  
        }        
    }
    else if(amount.length == 0 || amount == "" || isNaN(amount) ){
        error = true;
        errorMessage = "Invalid amount";
        $('#cvv').focus();
        if(isMobile){
           alert("Invalid amount");
        }
        else{
        $('.validationErrorMessage12').html(errorMessage);   
        }       
    }
    

    if(error){

    }
    else {
        var lno = studentDetails ? JSON.parse(studentDetails).LICENSENO : '';
        var reqData = {
                    FirstName: FirstName,
                    LastName : LastName,
                    Address : Address,
                    Address2 : Address2,
                    City : City,
                    PostalCode : PostalCode,
                    state : state,
                    Email : Email,
                    creditcard : cipher,
                    cMonth : cMonth,
                    cYear : cYear,
                    cvv : cvv,
                    amount : amount,
                    ip : clientIp,
                    orderId:orderId,
                    classId:classId,
                    lno :lno
                };
        var reqDataOrder = {
                    orderId: orderId,
                    transaction : '',
                    ip : clientIp
                };
        var reqDataJson = JSON.stringify(reqData);

        $.ajax({
            type:'POST',
            url:'/site/cfc/payment.cfc?method=pay',
            data: {reqData : reqDataJson},
            success:function(data) {
                var dataOBj = JSON.parse(data);
                // console.log(dataOBj);
                if(dataOBj.messages.resultCode == 'Ok'){
                   if(dataOBj.transactionResponse){
                        if(dataOBj.transactionResponse.responseCode == 1){                            
                           var transMsg = dataOBj.transactionResponse.messages.messages.message;
                           var transSha = dataOBj.transactionResponse.transHashSha2;
                           var transId = dataOBj.transactionResponse.transId;
                           var avsResultCode = dataOBj.transactionResponse.avsResultCode;
                           switch("1") {
                                case "1":
                               $('#response').html('<div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                               $('#response').addClass('alert alert-success');
                               reqDataOrder.transaction = transId;
                               reqDataOrder.creditcard = creditcard;
                              // updateOrder(reqDataOrder);
                               $('#btnSubmit').remove();
                               setTimeout(function(){
                                window.location.replace("payment.cfm");
                                    // location.reload(true);
                               },1000);
                                break;
                              case "Y":
                               $('#response').html('<div>Street Address and ZIP: Match</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                               $('#response').addClass('alert alert-success');
                               reqDataOrder.transaction = transId;
                               updateOrder(reqDataOrder);
                               $('#btnSubmit').remove();
                               setTimeout(function(){
                                window.location.replace("payment.cfm");
                                    // location.reload(true);
                               },1000);
                                break;
                              case "Z":
                                $('#response').html('<div>Street Address : No Match and ZIP: Match</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-success');
                                // reqDataOrder.transaction = transId;
                               updateOrder(reqDataOrder);
                               $('#btnSubmit').remove();
                               setTimeout(function(){
                                window.location.replace("payment.cfm");
                                    // location.reload(true);
                               },1000);                
                                break;
                                case "S":
                                $('#response').html('<div>AVS Not Supported by Card Issuing Bank</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                                break;
                                case "U":
                                $('#response').html('<div>Address Information For This Cardholder Is Unavailable</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                                break;
                                case "R":
                                $('#response').html('<div>Retry, System Is Unavailable</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                                break;
                                case "P":
                                $('#response').html('<div>AVS not applicable for this transaction</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                                break;
                                 case "G":
                                $('#response').html('<div>Non U.S. Card Issuing Bank</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                                break;
                                 case "N":
                                $('#response').html('<div>Street Address and ZIP: No Match</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                                break;
                                case "E":
                                $('#response').html('<div>AVS Error</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                                break;
                                case "B":
                                $('#response').html('<div>Address not provided for AVS check or street address match, postal code could not be verified</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                                break;
                                case "A":
                                $('#response').html('<div>Street Address: Match and ZIP: No Match</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                                break;
                              default:
                                $('#response').html('<div>Something went wrong. Please try again.</div><div>Transaction ID : '+transId+'</div>');
                                $('#response').addClass('alert alert-danger');
                            }
                        }
                        else{
                           console.log(dataOBj.transactionResponse.errors);
                            var transMsg = dataOBj.transactionResponse.errors.errors.error;
                            var transId = dataOBj.transactionResponse.transId;
                            console.log(transMsg);
                            console.log(transId);
                           if(dataOBj.transactionResponse.responseCode == 2){        
                                $('#response').html('<div>Transaction Declined</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                            }
                            else if(dataOBj.transactionResponse.responseCode == 3){
                                 $('#response').html('<div>Transaction Error</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                            }
                            else if(dataOBj.transactionResponse.responseCode == 4){
                                 $('#response').html('<div>Transaction held for review</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                            }
                            $('#response').addClass('alert alert-danger'); 
                        }
                   }                  
                }
                else {
                   console.log('failed'); 
                   var apiMsg = dataOBj.messages.message.text;
                    $(".modal1").hide();                 
                   var transMsg = dataOBj.transactionResponse.errors.errors.error;
                   console.log(transMsg);
                   console.log(transSha);
                   console.log(transId);
                   $('#response').html('<div>'+apiMsg+'<div><div>Details : '+transMsg+'</div>');
                   $('#response').addClass('alert alert-danger'); 
                    $(window).scrollTop($('#billingInfoDiv').offset().top);     
                }
            },
            error:function(obj) {
                console.log('error');
                console.log(obj)
                $(".modal1").hide();

            },
            beforeSend: function () {
               $(".modal1").show();
            },
            complete: function () {
                $(".modal1").hide();
            }
        });
    }
}

function updateOrder(obj){
    var objJson = JSON.stringify(obj);
    console.log(objJson)
    $.ajax({
        type:'POST',
        url:'/site/service/cfc/classService.cfc?method=updateOrder',
        data: {reqData : objJson},
        success:function(data) {
            var dataOBj = JSON.parse(data);
            console.log(dataOBj);
            
        },
        error:function(obj) {
            console.log('error');
            console.log(obj)
        }
    });
}
$(document).on('click', '#payLater', function() {
    if ($('#payLater').is(':checked')) {
        $('#Ccard').hide();
    } else {
        $('#Ccard').show();
        
    }
});
var old_classId = 0;
var old_amount = 0;

$(document).on('click', '#oneHourCourse', function() {
    var sid = $('#siteId').val();
   
    if ($('#oneHourCourse').is(':checked')) {
        $('#sanitationModal').modal('show');
        $("#SanitationCourse").show();
        $("#SanitationCourse1").show();
        $("#SanitationCourse11").show();
        $("#SkincareCourse").hide();
        $("#SkincareCourse11").hide();
        // if(licenseType == 'Instructor'){
        //     $("#InstructorCourse").hide();
        // }
        $('#classId').val(window.cosmoSanitaionClassId);
       
        $.ajax({
            type:'POST',
            url:'/site/cfc/class.cfc?method=getPriceDetails',
            data: {
                siteId: sid,
                classId : window.cosmoSanitaionClassId
            },
            dataType:"json",
            success:function(data) {
                var dataOBj = JSON.parse(data);   
                var price = dataOBj[0].price;
                $('#amount').val(price);
                $('#newPrice').html(price);
                $('#clsNewPrice').html('$'+price);
                $('#cardNewPrice').html('$'+price);
                $('#applyPromo').attr("onclick",'applyPromocode('+sid+', window.cosmoSanitaionClassId)');
                $('#promoC').attr("onblur",'applyPromocode('+sid+', window.cosmoSanitaionClassId)');
                /*Removing applied promo code*/
                $('#DiscountMessage').html('');
                $('#DiscountAmount').html('');
                $('.validationErrorMessage30').html('');
                $('.validationErrorMessage30').hide(); 
                $('#promoC').prop('readonly', true);
                document.getElementById("applyPromo").disabled = true;
            },
            error:function(obj) {
                console.log('error');
                console.log(obj)
            }
        });       
    } else {
        $('#amount').val(old_amount);
        
        $('#promoC').prop('readonly', false);
        document.getElementById("applyPromo").disabled = false;
        
        if($('#promoC').val().length > 0) {
            cnt = 0;
            applyPromocode(sid,old_classId);
        }
        $('#sanitationModal').modal('hide');
        $('#applyPromo').attr("onclick",'applyPromocode('+sid+', '+old_classId+')');
        $('#promoC').attr("onblur",'applyPromocode('+sid+', '+old_classId+')');
        $("#SanitationCourse").hide();
        $("#SanitationCourse1").hide();
        $("#SanitationCourse11").hide();
        $("#SkincareCourse").show();
        $("#SkincareCourse11").show();
        $('#classId').val(old_classId);
        $('#newPrice').html(old_amount);
        $('#clsNewPrice').html('$'+old_amount);
        $('#cardNewPrice').html('$'+old_amount);
    } 
});

function modalUncheck(sid,cid){
    var sid = $('#siteId').val();

    $('#promoC').prop('readonly', false);
    $('#amount').val(old_amount);
    if($('#promoC').val().length > 0) {
        cnt = 0;
        applyPromocode(sid,old_classId);
    }
    $('#oneHourCourse').prop('checked',false); 

    document.getElementById("applyPromo").disabled = false;
    $('#applyPromo').attr("onclick",'applyPromocode('+sid+', '+old_classId+')');
    $('#promoC').attr("onblur",'applyPromocode('+sid+', '+old_classId+')');
    $("#SanitationCourse").hide();
    $("#SanitationCourse1").hide();
    $("#SanitationCourse11").hide();
    $("#SkincareCourse").show();
    $("#SkincareCourse11").show();
    $('#classId').val(old_classId);
    $('#newPrice').html(old_amount);
    $('#clsNewPrice').html('$'+old_amount);
    $('#cardNewPrice').html('$'+old_amount);
    $(".logError").css("display", "none");
}

$('#getStudentForm').on('submit', function() {
    var lno = $.trim($('#licenseNumber').val());
    lno = lno.replace(/^0+/, '');

    var error = false;
    var errorMessage = '';

    if(lno.length == 0){
        error = true;
        errorMessage = "This is required.";
        $('#licenseNumber').focus();
    }
    else if(isNaN(lno)){
        error = true;
        errorMessage = "License number should be in number";
        $('#licenseNumber').focus();
    }
   
    if(error){      
        $('#errorServer').hide();
        $('.validationErrorMessage1').html(errorMessage);
        $('.validationErrorMessage1').show();
        // $('#errorDiv').addClass('alert alert-danger');
        return false;
    }
});

function validateEmail(email) {
  var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}

$(document).on('submit', '#studentAddForm', function() {
    $('.vald').html('');
    var firstName = $.trim($('#firstName').val());
    var lastName = $.trim($('#lastName').val());
    var address1 = $.trim($('#address1').val());
    var postalCode = $.trim($('#postalCode').val());
    var city = $.trim($('#city').val());
    var State = $.trim($('#state').val());
    var email = $.trim($('#email').val());
    var telephone1 = $.trim($('#Telephone1').val());
    var telephone2 = $.trim($('#Telephone2').val());
    var telephone3 = $.trim($('#Telephone3').val());
    var pass = $.trim($('#pass').val());
    var cnfpass = $.trim($('#cnfpass').val());

    var credit = $.trim($('#credit').val());
    credit = credit.replace(/\s/g, "");
    // var credit1 = $.trim($('#credit1').val());
    // var credit2 = $.trim($('#credit2').val());
    // var credit3 = $.trim($('#credit3').val());
    // var credit4 = $.trim($('#credit4').val());


    var cMonth = $.trim($('#cMonth').val());
    var cYear = $.trim($('#cYear').val());
    var cCvv = $.trim($('#cCvv').val());
    // var licenseState = $.trim($('#licenseState').val());
    // var licenseNumber = $.trim($('#licenseNumber').val());
    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    var error = false;
    var errorMessage = '';

    if(firstName == ""){
        error = true;
        errorMessage = "This is required";
        $('#firstName').focus();
        if(isMobile){
           alert("First Name is required");
        }
        else{
            $('.validationErrorMessage2').html(errorMessage);        
            $('.validationErrorMessage2').show();
        }          
    }
    // else if(lastName == ""){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#lastName').focus();
    //     if(isMobile){
    //        alert("Last Name is required");
    //     }
    //     else{
    //         $('.validationErrorMessage3').html(errorMessage);        
    //         $('.validationErrorMessage3').show();  
    //     }
    // }
    else if(address1 == ""){
        error = true;
        errorMessage = "This is required";
        $('#address1').focus();
        console.log('helo');
        if(isMobile){

           alert("Address is required");
        }
        else{
            $('.validationErrorMessage4').html(errorMessage);        
            $('.validationErrorMessage4').show();
        }  
    }
    else if(postalCode == ""){
        error = true;
        errorMessage = "This is required";
        $('#postalCode').focus();
        if(isMobile){
           alert("PostalCode is required");
        }
        else{
            $('.validationErrorMessage6').html(errorMessage);        
            $('.validationErrorMessage6').show();
        }  
    }
    else if(city == ""){
        error = true;
        errorMessage = "This is required";
        $('#city').focus();
        if(isMobile){
           alert("City is required");
        }
        else{
            $('.validationErrorMessage5').html(errorMessage);        
            $('.validationErrorMessage5').show();
        }  
    }
    else if(State == 0 ){
        error = true;
        errorMessage = "This is required";
        $('#state').focus();
        if(isMobile){
           alert("State is required");
        }
        else{
            $('.validationErrorMessage40').html(errorMessage);        
            $('.validationErrorMessage40').show(); 
        }
    }
    //  else if(email == "" ){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#email').focus();
    //     $('.validationErrorMessage35').html(errorMessage);        
    //     $('.validationErrorMessage35').show();        
    // }
     else if(email.length > 0 && !(validateEmail(email))){
        error = true;
        errorMessage = "Please enter valid email";
        $('#email').focus();
        if(isMobile){
           alert("Please enter valid email");
        }
        else{
            $('.validationErrorMessage35').html(errorMessage);        
            $('.validationErrorMessage35').show();
        }  
    }
     else if(telephone1 == "" ){
        error = true;
        errorMessage = "This is required";
        $('#telephone1').focus();
        if(isMobile){
           alert("Telephone is required");
        }
        else{
            $('.validationErrorMessage8').html(errorMessage);        
            $('.validationErrorMessage8').show();
        } 
    }
    else if(isNaN(telephone1) || telephone1.length !=3 ){
        error = true;
        errorMessage = "Enter valid telephone";
        $('#telephone1').focus();
        if(isMobile){
           alert("Enter valid telephone");
        }
        else{
            $('.validationErrorMessage8').html(errorMessage);        
            $('.validationErrorMessage8').show();
        } 
    }
     else if(telephone2 == "" ){
        error = true;
        errorMessage = "This is required";
        $('#telephone1').focus();
        if(isMobile){
           alert("Telephone is required");
        }
        else{
            $('.validationErrorMessage8').html(errorMessage);        
            $('.validationErrorMessage8').show();
        } 
    }
    else if(isNaN(telephone2) || telephone2.length !=3 ){
        error = true;
        errorMessage = "Enter valid telephone";
        $('#telephone1').focus();
        if(isMobile){
           alert("Enter valid telephone");
        }
        else{
            $('.validationErrorMessage8').html(errorMessage);        
            $('.validationErrorMessage8').show();
        } 
    }
    else if(telephone3 == "" ){
        error = true;
        errorMessage = "This is required";
        $('#telephone1').focus();
        if(isMobile){
           alert("Telephone is required");
        }
        else{
            $('.validationErrorMessage8').html(errorMessage);        
            $('.validationErrorMessage8').show();
        } 
    }
    else if(isNaN(telephone3) || telephone3.length !=4 ){
        error = true;
        errorMessage = "Enter valid telephone";
        $('#telephone1').focus();
        if(isMobile){
           alert("Enter valid telephone");
        }
        else{
            $('.validationErrorMessage8').html(errorMessage);        
            $('.validationErrorMessage8').show();
        } 
    }
    else if(pass == "" ){
        error = true;
        errorMessage = "This is required";
        $('#pass').focus();
        if(isMobile){
           alert("Password is required");
        }
        else{
            $('.validationErrorMessage14').html(errorMessage);        
            $('.validationErrorMessage14').show();
        } 
    }
    else if(cnfpass == "" ){
        error = true;
        errorMessage = "This is required";
        $('#cnfpass').focus();
        if(isMobile){
           alert("Confirm Password is required");
        }
        else{
            $('.validationErrorMessage15').html(errorMessage);        
            $('.validationErrorMessage15').show();
        } 
    }
    else if(pass != cnfpass){
        error = true;
        errorMessage = "Password mismatch!";
        $('#cnfpass').focus();
        if(isMobile){
           alert("Password mismatch!");
        }
        else{
            $('.validationErrorMessage15').html(errorMessage);        
            $('.validationErrorMessage15').show();
        } 
    } 
    // else if(!($('#payLater').is(':checked'))) {
    //     if(credit == "" || isNaN(credit) || (credit.length < 13 || credit.length > 18)){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#credit').focus();
    //     $('.validationErrorMessage17').html(errorMessage);        
    //     $('.validationErrorMessage17').show(); 
    //     }

    else if(!($('#payLater').is(':checked'))) {
   
    if(credit == ""){
        error = true;
        errorMessage = "This is required";
        $('#credit').focus();
        if(isMobile){
           alert("Credit card number is required");
        }
        else{
            $('.validationErrorMessage91').html(errorMessage); 
        }         
    }
    else if((credit.length < 13 || credit.length >16) || isNaN(credit)){
        error = true;
        errorMessage = "Invalid credit card";
        $('#credit').focus();
        if(isMobile){
           alert("Invalid credit card");
        }
        else{
            $('.validationErrorMessage91').html(errorMessage);
        }          
    }

    else if(cMonth == "" || isNaN(cMonth) || cMonth.length > 2 || cMonth == 0){
        error = true;
        errorMessage = "Month is required";
        $('#cMonth').focus();
        if(isMobile){
           alert("Month is required");
        }
        else{
            $('.validationErrorMessage19').html(errorMessage);        
            $('.validationErrorMessage19').show();
        } 

    }
     else if(cYear == "" || isNaN(cYear) || cYear.length != 4){
        error = true;
        errorMessage = "Year is required";
        $('#cYear').focus();
        if(isMobile){
           alert("Year is required");
        }
        else{
            $('.validationErrorMessage20').html(errorMessage);        
            $('.validationErrorMessage20').show();
        }  

    }
    else if( (cCvv == "" || isNaN(cCvv)) && (cCvv.length != 3 || cCvv.length != 4) ){
        error = true;
        errorMessage = "This is required";
        $('#cCvv').focus();
        if(isMobile){
           alert("Cvv is required");
        }
        else{
            $('.validationErrorMessage18').html(errorMessage);        
            $('.validationErrorMessage18').show();
        } 

    }
}
 
if(error){      
    $('#errorServer').hide();
    $('#errorDiv').html(errorMessage);
    $('#errorDiv').addClass('alert alert-danger');
    return false;
}
});

$('#resetForm').on('submit', function() {

    var pass = $.trim($('#pass').val());
    var cnfpass = $.trim($('#cnfpass').val());
    var error = false;
    var errorMessage = '';
    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

     if(pass.length === 0){
        error = true;
        errorMessage = "Please enter the password";
        $('#pass').focus();
    }
    else if(cnfpass.length === 0 ){
        error = true;
        errorMessage = "Please confirm the password";
        $('#cnfpass').focus();

    }
     else if(pass != cnfpass){
        error = true;
        errorMessage = "Password mismatch!";
        $('#cnfpass').focus();

    }
   

    if(error){        
        $('#errorServer').hide();
        $('#pass').val(pass);
        $('#cnfpass').val(cnfpass);
        if(isMobile){
           alert(errorMessage);
        }
        else{
            $('#errorDiv').html(errorMessage);
        }
        $('#errorDiv').addClass('alert alert-danger');
        return false;
    }
});

$('#valQuestForm').on('submit', function() {
    $('.errorD').html('');
    var answer = $('input[name="Answer[]"]');
    var email = $('#Email').val();
    var error = false;
    var errorMessage = '';
    console.log(answer);

    // if(email == "" ){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#Email').focus();
    //     $('#errorEmail').html(errorMessage); 
    // }
    //  else if(!(validateEmail(email))){
    //     error = true;
    //     errorMessage = "Please enter valid email";
    //     $('#email').focus();
    //     $('#errorEmail').html(errorMessage);        
    // }

    answer.each(function(i,obj){
        var valueOfObj = $(obj).val();
        if(valueOfObj == ''){
            error = true;
            $('#error'+(i+1)).html('This is required');
        } 
    });

    if(error){
        return false;
    }
});

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    var intObj = setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        if (display) {
            display.html("Time remaining: "+minutes + ":" + seconds);
        }
        
        // display.textContent = "Time remaining: "+minutes + ":" + seconds;

        if (--timer < 0) {
            clearInterval(intObj);
            $('[name=btnNext]').removeAttr("disabled");
            $('.countdown').html("");
        }
    }, 1000);
}


$(function() {
     
    if (localStorage.checkbox && localStorage.checkbox != '') {
        $('#rememberMe').attr('checked', 'checked');
        $('#username').val(localStorage.usrname);
        $('#password').val(localStorage.pass);
    } else {
        $('#rememberMe').removeAttr('checked');
        $('#username').val('');
        $('#password').val('');
    }

    $('#rememberMeSpan').click(function() {
        if ($('#rememberMe').is(':checked')) {
            localStorage.usrname = '';
            localStorage.pass = '';
            localStorage.checkbox = '';
        } else {
            // save username and password
            localStorage.usrname = $('#username').val();
            localStorage.pass = $('#password').val();
            localStorage.checkbox = $('#rememberMe').val();
        }
    });
});

function loadClassDetail(){
    var classId = $('#classId').val();
    var classNumber = $('#classNumber').val();
    var className = $('#className').val();
    var classDescription = $('#classDescription').val();
    var certificateSrc = '/admin/assets/certificates/'+classId+'/cert.jpg'
    // $('#classNameContainer').html('<b>'+className+'</b>');
    // $('#classDesccontainer').html(classDescription);
    // $('#classNumberContainer').html(' <i>TDLR Provider #1887 | Course # '+classNumber+'</i>');
    // $('#certImage').attr('src',certificateSrc);
    // $('#certImageLarge').attr('src',certificateSrc);
    // $('#frmDataForm > .form-group').remove();
    // $('#classNameContainer').remove();
    // $('#classDesccontainer').remove();
}

$(document).ready(function(){
    loadClassDetail();
    //getPhoneNumber();
    var sections = $('#sections').val();
    console.log($("#sections").length);
    var sectionCount = $('#sectionCount').val();
    var siteId = $('#siteId').val();
    var classId = $('#classId').val();
    var studentId = $('#studentId').val();
    var totalSectionWordCount = $('#totalWordsCount').val();
    var thisSlideWordCount = $('#thisSlideCount').val();
    var slideCount = $('#thisSlideCount').val();
    var sectionTime = $('#sectionTime').val();

    if($("#sections").length){
        var sectionArr = sections.split(',');
        var firstSection = sectionArr[0];
        var minToSec = sectionTime*60;
        var secForOneWord = minToSec/totalSectionWordCount;
        console.log(secForOneWord);
        var secForThisSlide = secForOneWord*thisSlideWordCount;
        console.log(secForThisSlide);
        display = $('.countdown');
        startTimer(secForThisSlide, display);
    }

    $.get("https://ipinfo.io", function(response) { 
           $('#ipinfo').val(response.ip);
        }, "json") 


    

    // getSlide(firstSection,classId,studentId,siteId);
    // getSlide(firstSection);

});

function getSlide(sid){
    var reqData = {
                sectionId: sid
                // classId : cid,
                // studId : studId,
                // siteId : siteId               
            };
      
    var reqDataJson = JSON.stringify(reqData);

    $.ajax({
        type:'POST',
        url:'service/cfc/studentService.cfc?method=getSlide',
        data: {reqData : reqDataJson},
        success:function(data) {
            var dataOBj = JSON.parse(data);
            var arrlen = dataOBj.DATA.length;
            console.log(dataOBj.DATA[0]);
            console.log(arrlen);
            $('#totalSlide').html(arrlen);
            setSlide(dataOBj.DATA[0]);            
        },
        error:function(obj) {
            console.log('error');
            console.log(obj)
        }
    });
}

function setSlide(data){
    $('#slideContent').html(data);

}

function getPhoneNumber(){
    var phonenumber = $('#myphoneNumber').val();
    var sessionid = $('#sessionid').val();
    // var phonenumber1 = $('#myphoneNumber1').val();
    console.log(phonenumber);
    $('.sessioncfid').html(sessionid);
    $('#phonenum').html('<span>'+ '(' + phonenumber.substring(0,3) + ') ' + phonenumber.substring(3,6) + '-' + phonenumber.substring(6,11) +'</span>');
    $('.phonenum').html('(' + phonenumber.substring(0,3) + ') ' + phonenumber.substring(3,6) + '-' + phonenumber.substring(6,11));
    $('.phonenum1').html('(' + phonenumber.substring(0,3) + ') ' + phonenumber.substring(3,6) + '-' + phonenumber.substring(6,11));
}

//payment modal after login and course completion
function initiatePay1(){
    $('.errorD1').html('');
    $('#response1').html('');
    $('#response1').removeClass('alert alert-success');
    $('#response1').removeClass('alert alert-danger');
   var clientIp = $.trim($('#ipinfo').val());
    var FirstName = $.trim($('#FirstName1').val());
    var LastName = $.trim($('#LastName1').val());
    var Address = $.trim($('#Address1').val());
    var Address2 = $.trim($('#Address21').val());
    var City = $.trim($('#City1').val());
    var PostalCode = $.trim($('#PostalCode1').val());
    var state = $.trim($('#state1').val());
    var Email = $.trim($('#Email1').val());
    var creditcard = $.trim($('#creditcard1').val());
    creditcard = creditcard.replace(/\s/g, "");
    var base64Key = "MTIzNDU2NzgxMjM0NTY3OA==";
    var base64IV = "EBESExQVFhcYGRobHB0eHw==";

    var key = CryptoJS.enc.Base64.parse(base64Key);
    var iv  = CryptoJS.enc.Base64.parse(base64IV);

    var encrypted = CryptoJS.AES.encrypt(creditcard, key, {iv: iv});
    var cipher = encrypted.toString();
    // console.log(encrypted.toString());

    var decrypted =  CryptoJS.AES.decrypt(encrypted, key, {iv: iv})
    
    // console.log(decrypted.toString(CryptoJS.enc.Utf8));

    var cMonth = $.trim($('#cMonth1').val());
    var cYear = $.trim($('#cYear1').val());
    var cvv = $.trim($('#cvv1').val());
    var orderId = $.trim($('#orderId1').val());
    var classId = $.trim($('#classId1').val());
    var studentId = $.trim($('#studentId1').val());
    var siteId = $.trim($('#siteId1').val());
    var amount = $.trim($('#amount1').val());

    var error = false;
    var errorMessage = '';
    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

    if(FirstName == ""){
        error = true;
        errorMessage = "This is required";
        $('#FirstName1').focus();
        if(isMobile){
           alert("First Name is required");
        }
        else{
            $('.validationErrorMessage21').html(errorMessage); 
        }       
    }
    else if(LastName == ""){
        error = true;
        errorMessage = "This is required";
        $('#LastName1').focus();
        if(isMobile){
           alert("Last Name is required");
        }
        else{
            $('.validationErrorMessage31').html(errorMessage);
        }          
    }
    else if(Address == ""){
        error = true;
        errorMessage = "This is required";
        $('#Address1').focus();
        if(isMobile){
           alert("Address is required");
        }
        else{
            $('.validationErrorMessage41').html(errorMessage);
        }          
    }
    else if(City == ""){
        error = true;
        errorMessage = "This is required";
        $('#City1').focus();
        if(isMobile){
           alert("City is required");
        }
        else{
            $('.validationErrorMessage51').html(errorMessage);
        }          
    }
    else if(PostalCode == ""){
        error = true;
        errorMessage = "This is required";
        $('#PostalCode1').focus();
        if(isMobile){
           alert("PostalCode is required");
        }
        else{
            $('.validationErrorMessage61').html(errorMessage);
        }          
    }
    else if(isNaN(PostalCode) || PostalCode.length > 7){
        error = true;
        errorMessage = "Invalid zipcode";
        $('#PostalCode1').focus();
        if(isMobile){
           alert("Invalid zipcode");
        }
        else{
            $('.validationErrorMessage61').html(errorMessage);
        }          
    }
    else if(state == 0 || state == ""){
        error = true;
        errorMessage = "This is required";
        $('#state1').focus();
        if(isMobile){
           alert("State is required");
        }
        else{
            $('.validationErrorMessage71').html(errorMessage);
        }          
    }

    else if(creditcard == ""){
        error = true;
        errorMessage = "This is required";
        $('#creditcard1').focus();
        if(isMobile){
           alert("Credit card number is required");
        }
        else{
            $('.validationErrorMessage91').html(errorMessage); 
        }         
    }
    else if((creditcard.length < 13 || creditcard.length >17) || isNaN(creditcard)){
        error = true;
        errorMessage = "Invalid credit card";
        $('#creditcard1').focus();
        if(isMobile){
           alert("Invalid credit card");
        }
        else{
            $('.validationErrorMessage91').html(errorMessage);
        }          
    }
    else if(cMonth == "" || cMonth == 0 || isNaN(cMonth)){
        error = true;
        errorMessage = "This is required";
        $('#cMonth1').focus();
        if(isMobile){
           alert("Month is required");
        }
        else{
            $('.validationErrorMessage101').html(errorMessage);
        }          
    }
    else if(cYear == "" || cYear == 0 || isNaN(cYear)){
        error = true;
        errorMessage = "This is required";
        $('#cYear1').focus();
        if(isMobile){
           alert("Year is required");
        }
        else{
            $('.validationErrorMessage111').html(errorMessage);
        }          
    }
    else if(cvv == ""){
        error = true;
        errorMessage = "This is required";
        $('#cvv1').focus();
        if(isMobile){
           alert("Cvv is required");
        }
        else{
            $('.validationErrorMessage121').html(errorMessage);
        }          
    }
    else if(cvv.length < 3 || cvv.length > 4 || isNaN(cvv) ){
        error = true;
        errorMessage = "Invalid CVV";
        $('#cvv1').focus();
        if(isMobile){
           alert("Invalid CVV");
        }
        else{
            $('.validationErrorMessage121').html(errorMessage);
        }          
    }
    else if(amount.length == 0 || amount == "" || isNaN(amount) ){
        error = true;
        errorMessage = "Invalid amount";
        $('#cvv1').focus();
        if(isMobile){
           alert("Invalid amount");
        }
        else{
            $('.validationErrorMessage121').html(errorMessage);
        }          
    }
    

    if(error){

    }
    else {
        var lno = studentDetails ? JSON.parse(studentDetails).LICENSENO : '';
        var reqData = {
                    FirstName: FirstName,
                    LastName : LastName,
                    Address : Address,
                    Address2 : Address2,
                    City : City,
                    PostalCode : PostalCode,
                    state : state,
                    Email : Email,
                    creditcard : cipher,
                    cMonth : cMonth,
                    cYear : cYear,
                    cvv : cvv,
                    amount : amount,
                    ip : clientIp,
                    orderId:orderId,
                    classId:classId,
                    lno :lno
                };
        var reqDataOrder = {
                    orderId: orderId,
                    transaction : '',
                    ip : clientIp
                };
        var reqDataJson = JSON.stringify(reqData);

        $.ajax({
            type:'POST',
            url:'/site/service/cfc/paymentService.cfc?method=pay',
            data: {reqData : reqDataJson},
            success:function(data) {
                var dataOBj = JSON.parse(data);
                if(dataOBj.messages.resultCode == 'Ok'){
                   if(dataOBj.transactionResponse){
                        if(dataOBj.transactionResponse.responseCode == 1){                            
                           var transMsg = dataOBj.transactionResponse.messages.messages.message;
                           var transSha = dataOBj.transactionResponse.transHashSha2;
                           var transId = dataOBj.transactionResponse.transId;
                           var avsResultCode = dataOBj.transactionResponse.avsResultCode;
                            switch("1") {
                                case "1":
                               $('#response1').html('<div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                               $('#response1').addClass('alert alert-success');
                               reqDataOrder.transaction = transId;
                               reqDataOrder.creditcard = creditcard;
                               $('#btnSubmit').remove();
                               setTimeout(function(){
                                window.location.replace("payment.cfm");
                                    // location.reload(true);
                               },1000);
                                break;
                              case "Y":
                               $('#response1').html('<div>Street Address and ZIP: Match</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                               $('#response1').addClass('alert alert-success');
                               reqDataOrder.transaction = transId;
                               updateOrder(reqDataOrder);
                               $('#btnSubmit').remove();
                               setTimeout(function(){
                                window.location.replace("payment.cfm");
                                    // location.reload(true);
                               },1000);
                                break;
                              case "Z":
                                $('#response1').html('<div>Street Address : No Match and ZIP: Match</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-success');
                                // reqDataOrder.transaction = transId;
                               updateOrder(reqDataOrder);
                               $('#btnSubmit').remove();
                               setTimeout(function(){
                                window.location.replace("payment.cfm");
                                    // location.reload(true);
                               },1000);                
                                break;
                                case "S":
                                $('#response1').html('<div>AVS Not Supported by Card Issuing Bank</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                                break;
                                case "U":
                                $('#response1').html('<div>Address Information For This Cardholder Is Unavailable</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                                break;
                                case "R":
                                $('#response1').html('<div>Retry, System Is Unavailable</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                                break;
                                case "P":
                                $('#response1').html('<div>AVS not applicable for this transaction</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                                break;
                                 case "G":
                                $('#response1').html('<div>Non U.S. Card Issuing Bank</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                                break;
                                 case "N":
                                $('#response1').html('<div>Street Address and ZIP: No Match</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                                break;
                                case "E":
                                $('#response1').html('<div>AVS Error</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                                break;
                                case "B":
                                $('#response1').html('<div>Address not provided for AVS check or street address match, postal code could not be verified</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                                break;
                                case "A":
                                $('#response1').html('<div>Street Address: Match and ZIP: No Match</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                                break;
                              default:
                                $('#response1').html('<div>Something went wrong. Please try again.</div><div>Transaction ID : '+transId+'</div>');
                                $('#response1').addClass('alert alert-danger');
                            }
                        }
                        else{
                           var transMsg = dataOBj.transactionResponse.errors.errors.error;
                            var transId = dataOBj.transactionResponse.transId;
                           if(dataOBj.transactionResponse.responseCode == 2){        
                                $('#response1').html('<div>Transaction Declined</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                            }
                            else if(dataOBj.transactionResponse.responseCode == 3){
                                 $('#response1').html('<div>Transaction Error</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                            }
                            else if(dataOBj.transactionResponse.responseCode == 4){
                                 $('#response1').html('<div>Transaction held for review</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                            }
                            $('#response1').addClass('alert alert-danger'); 
                        }
                   }                  
                }
                else {
                   var apiMsg = dataOBj.messages.message.text;
                    $(".modal1").hide();                 
                   var transMsg = dataOBj.transactionResponse.errors.errors.error;
                    $('#response1').html('<div>'+apiMsg+'<div><div>Details : '+transMsg+'</div>');
                   $('#response1').addClass('alert alert-danger'); 
                    $(window).scrollTop($('#billingInfoDiv').offset().top);     
                }
            },
            error:function(obj) {
                console.log('errorAjax');
                console.log(obj)
                $(".modal1").hide();

            },
            beforeSend: function () {
               $(".modal1").show();
            },
            complete: function () {
                $(".modal1").hide();
            }
        });
    }
}

function printPdfIframe() {
    document.getElementById('printPdf').focus(); 
    document.getElementById('printPdf').contentWindow.print();
}

function login(){
    $('.logError').html('');
    var lno = $('#license_log').val();
    var ps = $('#psw').val();
    var error = false;
    var errorMsg = '';

    if(lno == ''){
        error = true;
        errorMsg = 'Please enter the license number';
    }
    //else if(isNaN(lno)){
    //   error = true;
   //     errorMsg = 'License number should be a number';
   // }
    else if(ps == ''){
        error = true;
        errorMsg = 'Please enter the password';
    }
    if(error){
        $('.logError').html(errorMsg);
    }
    else {
        var parseUrl = parseUrlQueryString(location.search);
        $.ajax({
            type:'POST',
            url:'/site/cfc/login.cfc?method=StudentLogin',
            data: {
                licenseNumber: lno,
                Password : ps,
                siteId : window.siteId,
                siteLicenseType : window.siteLicenseType
            },
            dataType:"json",
            success:function(data) {
                if(data.MESSAGE == 'Success') {
                    if(parseUrl.surveyid !== undefined)
                        location.href = 'survey.cfm?surveyid='+parseUrl.surveyid;
                    else
                        location.href = 'myAccount.cfm';                  
                }
                else{
                    $('.logError').html('Invalid credentials');
                }
            },
            error:function(obj) {
                console.log('error');
                console.log(obj)
            },
            beforeSend: function () {
               $(".modal1").show();
            },
            complete: function () {
                $(".modal1").hide();
            }
        });
    }
}

function modalLogin(){
    $('.logError').html('');
    var lno = $('#license_logModal').val();
    var ps = $('#psw_logModal').val();

    var error = false;
    var errorMsg = '';

    if(lno == ''){
        error = true;
        errorMsg = 'Please enter the license number';
    }
    else if(isNaN(lno)){
        error = true;
        errorMsg = 'License number should be a number';
    }
    else if(ps == ''){
        error = true;
        errorMsg = 'Please enter the password';
    }
    if(error){
        $('.logError_modal').html(errorMsg);
    }
    else {
        var parseUrl = parseUrlQueryString(location.search);
        $.ajax({
            type:'POST',
            url:'/site/cfc/login.cfc?method=StudentLogin',
            data: {
                licenseNumber: lno,
                Password : ps,
                siteId : window.siteId,
                siteLicenseType : window.siteLicenseType
            },
            dataType:"json",
            success:function(data) {
                if(data.MESSAGE == 'Success') {
                    if(parseUrl.surveyid !== undefined)
                        location.href = 'survey.cfm?surveyid='+parseUrl.surveyid;
                    else
                        location.href = 'myAccount.cfm';                  
                }
                else{
                    $('.logError_modal').html('Invalid credentials');
                }
            },
            error:function(obj) {
                console.log('error');
                console.log(obj)
            },
            beforeSend: function () {
               $(".modal1").show();
            },
            complete: function () {
                $(".modal1").hide();
            }
        });
    }
}

function getstudent(params) {
    $('#error3').html('');
    $('#error3').removeClass('alert alert-danger');
    var lno;
    if(params === undefined) {
        var params = {};
    }
    if(params.lno !== undefined) {
        lno = params.lno;
    }else {
        lno = $('#licenseNumber').val();
    }
    var siteId = $('#siteId').val();
    var classId = 0;
    var amount = 0;
    var error = false;
    var errorMsg = '';
    var stateSelect1 = '<div id="stateSel"></div>';
    var monthSelect1 = '<div id="monthSel"></div>';
    var yearSelect1 = '<div id="yearSel"></div>';
    var token = $('meta[name="csrf-token"]').attr('content');
    var url_param = $(location).attr('href').split("?");
    var testparam = false;
    if (url_param.length == 2) {
        console.log(url_param[1]);
        if (url_param[1] == 'test') {
            testparam = true;
        }
    }
    if (lno == '') {
        error = true;
        errorMsg = 'This is required';
    } else if (isNaN(lno)) {
        error = true;
        errorMsg = 'License number should be a number';
    }
    if (error) {
        $('#error3').addClass('alert alert-danger');
        $('#error3').html(errorMsg);
        console.log(errorMsg);
    } 
    else 
    {
        var siteId = window.siteId;
        var siteName = window.siteName;
        
        $.ajax({
            type: 'POST',
            url: '/site/cfc/enrollment.cfc?method=licenseeDataLookup',
            data:{
                licenseNumber: lno,
                siteId:siteId,
                csrftoken: token,
                licenseEnterMethod: window.licenseEnterMethod
            },
            dataType:"json",
            success: function(data) {
                var dataOBj = JSON.parse(data);
                if (dataOBj.SUCCESS) {
                    var customerDataObj = JSON.parse(dataOBj.DATA);
                    var customerData = customerDataObj[0];
                    
                    if(customerData.MiddleName.length){
                        var studentFirstName = customerData.FirstName+' '+customerData.MiddleName;
                    }
                    else{
                        var studentFirstName = customerData.FirstName;
                    }
                    var studentLastName = customerData.LastName  == 'NULL' ? '' : customerData.LastName;
                    var studentAddr1 = customerData.MailingAddress1 == 'NULL' ? '' : customerData.MailingAddress1;
                    var studentAddr2 = customerData.MailingAddress2 == 'NULL' ? '' : customerData.MailingAddress2;
                    var studentCity = customerData.MailingCity == 'NULL' ? '' : customerData.MailingCity;
                    var studentState = customerData.MailingState == 'NULL' ? '' : customerData.MailingState;
                    var studentZip = customerData.MailingZip == 'NULL' ? '' : customerData.MailingZip;
                    var studentMobileNo = customerData.MobilePhone == 'NULL' ? '' : customerData.MobilePhone;
                    
                    var classData = dataOBj.CLASS;
                    var classAmount = classData.PRICE;
                    var classNumber = classData.NUMBER;
                    var classHours = classData.HOURS;
                    var className = classData.NAME;
                    var classId = classData.ID;
                    var classDesc = classData.DESCRIPTION;

                    var hiddenVal = "";

                    old_classId = classId;
                    old_amount = classAmount;
                    
                    var oneHourCourseHtml = '';
                    date = new Date();     
                    fifteenyearsago = date.getFullYear() - 15;
                    sanitationdescription = '<p>This course is for cosmetologists who have held their license IN TEXAS for at least 15 years. (' + fifteenyearsago + ')</p><p>If you do not meet this criteria, this course will <strong>NOT</strong> satisfy your Continuing Education requirement.</p><p>This course covers the rules and laws regarding sanitation for cosmetologists in the state of Texas and also meets the new Human Trafficking requirement which was added in 2018.</p><p><strong>If you are not sure if you meet this requirement, call TDLR at 800-803-9202 (Toll free)</strong></p>';

                    if(siteId == 1) {
                        oneHourCourseHtml = '<div style="color:red; text-decoration: underline;">1 Hour Sanitation Course Available!</div><div class="input-holder checkOtr my-2"> <input type="checkbox" name="oneHourCourse" id="oneHourCourse" data-toggle="modal" data-target="#sanitationModal"><span class="bold">I have held my license IN TEXAS for 15 years or more (' + fifteenyearsago + '). I am only required to take 1 hour of Sanitation Continuing Education. </span><div id="SanitationCourse" style="display: none"> You are Enrolling in the "One Hour Sanitation Course"</div></div>';
                    }
                    var formContent = '<div class="main2 bg-white bg-white text-secondary" id="main2">' +
                        '<form name="studentAddForm" id="studentAddForm" action="" method="post">' +
                        '<div class="col-md-12 form-content">' +
                        '<h1 class="mb-2">' +
                        'Registration Form' +
                        '</h1>' +
                        '</div>' +
                        '<div class="col-md-12 form-content">' +
                        '<div class="input-holder">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input type="text" id="lnum" class="form-control errorBrdr" value="' + dataOBj.LICENSENUMBER + '"  readonly="True">' +
                        '<span class="textField textFieldTop pc">License Number</span>' +
                        '<div class="validationErrorMessage1 vald" style="margin-top:3px;">This is required</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="input-holder row">' +
                        '<div class="col-md-6 pr-0">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input name="firstName" id="firstName" value="' + studentFirstName + '" type="text" class="form-control"  style="border:none;" readonly="True">' +
                        '<span class="textField textFieldTop pc">First Name</span>' +
                        '<div class="validationErrorMessage2 vald" style="margin-top:3px;">This is required</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-6">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input name="lastName" id="lastName" value="' + studentLastName + '" type="text" class="form-control"  style="border:none;" readonly="True">' +
                        '<span class="textField textFieldTop pc">Last Name</span>' +
                        '<div class="validationErrorMessage3 vald" style="margin-top:3px;">This is required</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="input-holder row">' +
                        '<div class="col-md-6 pr-0">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input  name="address1" id="address1" value="' + studentAddr1 + '"  type="text" class="form-control dm-form brdr-color" >' +
                        '<span class="textField  textFieldTop pc">Address</span>' +
                        '<div class="validationErrorMessage4 vald" style="margin-top:3px;">This is required</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-6">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input name="address2" id="address2" type="text" value="' + studentAddr2 + '" class="form-control brdr-color"  >' +
                        '<span class="textField textFieldTop pc">Address2</span>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="input-holder row">' +
                        '<div class="col-md-4 pr-0">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input name="city" id="city" value="' + studentCity + '" type="text" class="form-control brdr-color" >' +
                        '<span class="textField textFieldTop pc">City</span>' +
                        '<div class="validationErrorMessage5 vald" style="margin-top:3px;">This is required</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-4 pr-0">' +
                        '<div class="form-group mb-1 m-0">' + stateSelect1 +
                        '<div class="validationErrorMessage40 vald" style="margin-top:3px;"></div>                                     ' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-4">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input name="postalCode" id="postalCode" value="' + studentZip + '" type="text" class="form-control brdr-color" >' +
                        '<span class="textField textFieldTop pc">ZipCode</span>' +
                        '<div class="validationErrorMessage6 vald" style="margin-top:3px;">This is required</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="input-holder row">' +
                        '<div class="col-md-6 pr-0">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input  name="Telephone1" id="Telephone1" value="' + studentMobileNo.substring(0, 3) + '" type="text" class="form-control brdr-color"   style="width:60px;float:left;margin-right: 5px;">' +
                        '<input  name="Telephone2" id="Telephone2" value="' + studentMobileNo.substring(3, 6) + '" type="text" class="form-control brdr-color"   style="width:60px;float:left;margin-right: 5px;">' +
                        '<input  name="Telephone3" id="Telephone3" value="' + studentMobileNo.substring(6, 11) + '" type="text" class="form-control brdr-color"   style="width:60px;">' +
                        '<span class="textField textFieldTop pc">Phone</span>' +
                        '<div class="validationErrorMessage8 vald" style="margin-top:3px;">Telephone Column 1,2,3 is required</div>                                          ' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-6">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input name="email" id="email" type="text" class="form-control brdr-color" value="" >' +
                        '<span class="textField textFieldTop pc">Email</span>' +
                        '<div class="validationErrorMessage35 vald" style="margin-top:3px;"></div>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '<style>.pc{font-weight: 600 !important;}</style>' +
                        '<div class="input-holder row">' +
                        '<div class="col-md-6 pr-0">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input name="pass" id="pass" type="password" class="form-control brdr-color" value="" >' +
                        '<span class="textField textFieldTop pc">Password *</span>' +
                        '<div class="validationErrorMessage14 vald" style="margin-top:3px;">This is required</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-6">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input type="password" name="cnfpass" id="cnfpass" class="form-control brdr-color" value="" >' +
                        '<span class="textField textFieldTop pc">Confirm Password *</span>' +
                        '<div class="validationErrorMessage15 vald" style="margin-top:3px;">This is required</div>' +
                        '<!--- <div class="validationErrorMessage16 vald" style="margin-top:3px;">Password does not match Confirmation.</div> --->' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="input-holder checkOtr">' +
                        '<input type="checkbox" name="payLater" id="payLater">' +
                        '<span class="bold">Buy Now, Pay Later! Begin your courses today!</span>' + ' ' +
                        'Choosing this option will allow you to pay <b>$</b><span class="bold" id="newPrice">' + classAmount + ' </span> for your courses online at any time after registration.' +
                        '<span class="bold"> I understand that my course(s) will not be considered complete or reported to TDLR until payment has been received.</span>' +
                        '</div>' +
                        '</div>' +
                        '<div id="response1"></div>' +
                        '<div class="toggleOtr cardDtl" id="Ccard">' +
                        '<div class="input-holder row">' +
                        '<div class="col-md-6 pr-0">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input  name="credit" id="credit" value=""  type="text" class="form-control inputs" style="float:left;margin-right: 5px;"  required data-private>' +
                        '<span class="textField textFieldTop" id="licenseNumberLabel" style="">Credit Card Number</span>' +
                        '<div class="validationErrorMessage17 vald" style="margin-top:3px;">This is required</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-3 pr-0">' +
                        '<div class="form-group mb-1 m-0">    ' + monthSelect1 +
                        '<div class="validationErrorMessage19 vald" style="margin-top:3px;">' +
                        'Month,year are required</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-3">' +
                        '<div class="form-group mb-1 m-0">' + yearSelect1 +
                        '<div class="validationErrorMessage20 vald" style="margin-top:3px;">Month is required</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="input-holder row">' +
                        '<div class="col-md-4 pr-0">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input type="password" class="form-control form-group" value="" name="cCvv" id="cCvv" >' +
                        '<span class="textField textFieldTop">CVV</span>' +
                        '<div class="validationErrorMessage18 vald" style="margin-top:3px;">This is required</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-1"><a id="cvvHint" class="fa fa-question-circle" data-toggle="popover-hover" data-img="assets/images/cardimg.png"></a></div>' +
                        '<div class="col-md-7">' +
                        '<div class="form-group mb-1 m-0 txtcard">' +
                        'Your credit card will be charged <span id="cardNewPrice">$' + classAmount + '</span>' +
                        '<br/>' +
                        '' + siteName + ' will appear on your credit card statement.' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-12 form-content">' +
                        '<div class="form-group" style="font-weight: 600; padding-top: 5px;">' + oneHourCourseHtml+
                        
                        '</div>' +
                        '<input type="hidden" name="studentId" value="">' +
                        '<input type="hidden" name="studentInitName" id="studentInitName" value="">' +
                        '<input type="hidden" name="licenseNo" value="' + dataOBj.LICENSENUMBER + '">' +
                        '<input type="hidden" name="classId" id="classId" value="' + classId + '">' +
                        '<input type="hidden" name="siteId" id="siteId" value="' + siteId + '">' +
                        '<input type="hidden" name="amount" id="amount" value="' + classAmount + '">' +
                        hiddenVal +
                        '' +
                        '<div id="SanitationCourse1" style="display: none; font-weight: 700">' +
                        '<p>One Hour Sanitation Course</p>' +
                        '<span class="checkOtr">' + sanitationdescription + '</span>' +
                        '</div>' +
                        '<div id="SkincareCourse" style="font-weight: 700">' +
                        '<p>' + className + '</p>' +
                        '<span class="checkOtr">' + classDesc + '</span>' +
                        
                        '</div>' +
                        '<div class="input-holder row mt-1">' +
                        '<div class="col-md-6 pr-0">' +
                        '<div class="form-group mb-1 floatingLabel">' +
                        '<input type="text" class="form-control brdr-color" name="promoC" id="promoC" class="procode" value="" onblur="applyPromocode(' + siteId + ',' + classId + ');">' +
                        '<span class="textField textFieldTop pc">Promotional Code</span>' +
                        '<div class="validationErrorMessage30 vald" style="margin-top:3px;"></div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="col-md-6">' +
                        '<div class="form-group mb-1">' +
                        '<button type="button" name="applyPromo" id="applyPromo" onclick="applyPromocode(' + siteId + ',' + classId + ');" class="btn btn-primary btn-customcol" '+(params.promocode !== undefined?params.promocode:"")+'>' +
                        'Apply Code' +
                        '</button>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="input-holder"> <br>' +
                        '<div><label style="color:black;">Price:</label>' +
                        '<span id="DiscountAmount" class="crossButton"></span>  <span id="DiscountMessage" style="color:red"></span><span id="clsNewPrice">$' + classAmount + '</span></div>' +
                        '<button type="button" class="btn btn-primary btnVl" onclick="checkPayment()"  name="addStudent" id="addStudent" >Enroll Now</button>' +
                        '</div>' +
                        '</div>' +
                        '</form>' +
                        '</div>';
                    $('#tempVariables').remove();
                    $('#main1').replaceWith(formContent);
                    $('#stateSel').replaceWith(stateSelect);
                    $('#monthSel').replaceWith(monthSelect);
                    $('#yearSel').replaceWith(yearSelect);
                    var option = $('#state').children('option[value="' + studentState + '"]');
                    $(option).attr('selected', 'true');
                    if (params.promocode !== undefined) {
                        $('#promoC').val(params.promocode);
                        applyPromocode(siteId, classId);
                    }
                    $(".modal1").hide();

                } //if(dataOBj.SUCCESS)
                else if(dataOBj.HASACTIVECLASS){
                    if (dataOBj.CLASSSTRUCT.LATEST_COURSE_ENROLLED || dataOBj.CLASSSTRUCT.IS_ACTIVECLASS_ASSIGNED) {
                        var className = dataOBj.CLASSSTRUCT.CLASSNAME;
                        document.getElementById("license_logModal").value = dataOBj.LICENSENUMBER;
                        $('#className_modal').html(className);
                        $(".modal1").hide();
                        $('#enrollModal').modal('show');
                    }
                }
                else {
                    $('.logError').html('Invalid credentials');
                    $(".modal1").hide();
                    $('#error3').addClass('alert alert-danger');
                    $('#error3').html(dataOBj.MESSAGE);
                }
            },
            error: function(obj) {
                console.log('error');
                console.log(obj);
                $(".modal1").hide();
            }
            
        });
    }
}

function gettowstudent() {
    getstudent({licenseType : 'towtruckoperatortest'});
}

function getacrstudent() {
    getstudent({licenseType : 'acrtest'});
}

function getelectricianstudent() {
    getstudent({licenseType : 'electriciantest'});
}

function getauctioneerstudent() {
    getstudent({licenseType : 'auctioneertest'});
}

//before login
function initiatePay3(){
    $('.vald').html('');
    $('#response1').html('');
    $('#response1').removeClass('alert alert-success');
    $('#response1').removeClass('alert alert-danger');
    var clientIp = $.trim($('#ipinfo').val());
    var FirstName = $.trim($('#firstName').val());
    var LastName = $.trim($('#lastName').val());
    var Address = $.trim($('#address1').val());
    var Address2 = $.trim($('#address2').val());
    var City = $.trim($('#city').val());
    var PostalCode = $.trim($('#postalCode').val());
      var pass = $.trim($('#pass').val());
    var cnfpass = $.trim($('#cnfpass').val());
    var state = $.trim($('#state').val());
    var Email = $.trim($('#email').val());
    var promocode = $.trim($('#promoC').val());
    var studentInitName = $.trim($('#studentInitName').val());
    // var credit2 = $.trim($('#credit2').val());
    // var credit3 = $.trim($('#credit3').val());
    // var credit4 = $.trim($('#credit4').val());
     // var credit1 = $.trim($('#credit1').val());
    var creditcard = $.trim($('#credit').val()); 
    creditcard = creditcard.replace(/\s/g, "");
    var base64Key = "MTIzNDU2NzgxMjM0NTY3OA==";
    var base64IV = "EBESExQVFhcYGRobHB0eHw==";

    var key = CryptoJS.enc.Base64.parse(base64Key);
    var iv  = CryptoJS.enc.Base64.parse(base64IV);

    var encrypted = CryptoJS.AES.encrypt(creditcard, key, {iv: iv});
    var cipher = encrypted.toString();
    // console.log(encrypted.toString());

    var decrypted =  CryptoJS.AES.decrypt(encrypted, key, {iv: iv})
    
    // console.log(decrypted.toString(CryptoJS.enc.Utf8));

    var cMonth = $.trim($('#cMonth').val());
    var cYear = $.trim($('#cYear').val());
    var cvv = $.trim($('#cCvv').val());
    var orderId = $.trim($('#orderId').val());
    var classId = $.trim($('#classId').val());
    var studentId = $.trim($('#studentId').val());
    var siteId = $.trim($('#siteId').val());
    var amount = $.trim($('#amount').val());
    var lno = $.trim($('#lnum').val());
    var telephone1 = $.trim($('#Telephone1').val());
    var telephone2 = $.trim($('#Telephone2').val());   
    var telephone3 = $.trim($('#Telephone3').val());
    console.log(amount);

    var error = false;
    var errorMessage = '';
    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

    if(FirstName == ""){
        error = true;
        errorMessage = "This is required";
        $('#firstName').focus();
        if(isMobile){
           alert("First Name is required");
        }
        else
        {
            $('.validationErrorMessage21').html(errorMessage); 
        }       
    }
    // else if(LastName == ""){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#lastName').focus();
    //     if(isMobile){
    //        alert("Last Name is required");
    //     }
    //     else{
    //         $('.validationErrorMessage31').html(errorMessage);
    //     }          
    // }
    else if(Address == ""){
        error = true;
        errorMessage = "This is required";
        $('#address1').focus();
        if(isMobile){
           alert("Address is required");
        }
        else{
            $('.validationErrorMessage4').html(errorMessage); 
            $('.validationErrorMessage4').show();
        }          
    }
    else if(City == ""){
        error = true;
        errorMessage = "This is required";
        $('#city').focus();
        if(isMobile){
           alert("City is required");
        }
        else{
            $('.validationErrorMessage5').html(errorMessage); 
            $('.validationErrorMessage5').show();
        }            
    }
    else if(PostalCode == ""){
        error = true;
        errorMessage = "This is required";
        $('#postalCode').focus();
        if(isMobile){
           alert("PostalCode is required");
        }
        else{
            $('.validationErrorMessage6').html(errorMessage);  
            $('.validationErrorMessage6').show();
        }           
    }
    else if(isNaN(PostalCode) || PostalCode.length > 7){
        error = true;
        errorMessage = "Invalid zipcode";
        $('#PostalCode1').focus();
        if(isMobile){
           alert("Invalid zipcode");
        }
        else{
            $('.validationErrorMessage6').html(errorMessage); 
            $('.validationErrorMessage6').show(); 
        }           
    }
    else if(state == 0 || state == ""){
        error = true;
        errorMessage = "This is required";
        $('#state').focus();
        if(isMobile){
           alert("State is required");
        }
        else{
            $('.validationErrorMessage40').html(errorMessage); 
            $('.validationErrorMessage40').show(); 
        }           
    }


    else if(telephone1 == "" ){
            error = true;
            errorMessage = "This is required";
            $('#telephone1').focus();
            if(isMobile){
                alert("Phone number is required");
            }
            else
            {
                $('.validationErrorMessage8').html(errorMessage);        
                $('.validationErrorMessage8').show();
            }
        }
        else if(isNaN(telephone1) || telephone1.length !=3 ){
            error = true;
            errorMessage = "Enter valid telephone";
            $('#telephone1').focus();
            if(isMobile){
                alert("Enter valid telephone");
            }
            else{
                $('.validationErrorMessage8').html(errorMessage);        
                $('.validationErrorMessage8').show();
            }
        }
         else if(telephone2 == "" ){
            error = true;
            errorMessage = "This is required";
            $('#telephone1').focus();
            if(isMobile){
                alert("Phone number is required");
            }
            else{
                $('.validationErrorMessage8').html(errorMessage);        
                $('.validationErrorMessage8').show();
            }
        }
        else if(isNaN(telephone2) || telephone2.length !=3 ){
            error = true;
            errorMessage = "Enter valid telephone";
            $('#telephone1').focus();
            if(isMobile){
                alert("Enter valid telephone");
            }
            else{
                $('.validationErrorMessage8').html(errorMessage);        
                $('.validationErrorMessage8').show();
            }
        }
        else if(telephone3 == "" ){
            error = true;
            errorMessage = "This is required";
            $('#telephone1').focus();
            if(isMobile){
                alert("Phone number is required");
            }
            else{
                $('.validationErrorMessage8').html(errorMessage);        
                $('.validationErrorMessage8').show();
            }
        }
        else if(isNaN(telephone3) || telephone3.length !=4 ){
            error = true;
            errorMessage = "Enter valid telephone";
            $('#telephone1').focus();
            if(isMobile){
                alert("Enter valid telephone");
            }
            else{
                $('.validationErrorMessage8').html(errorMessage);        
                $('.validationErrorMessage8').show();
            }
        }  
    else if(pass == "" ){
        error = true;
        errorMessage = "This is required";
        $('#pass').focus();
        if(isMobile){
            alert("Password is required");
        } 
        else{
            $('.validationErrorMessage14').html(errorMessage);        
            $('.validationErrorMessage14').show();
        } 
    }
    else if(cnfpass == "" ){
        error = true;
        errorMessage = "This is required";
        $('#cnfpass').focus();
        if(isMobile){
            alert("Confirm Password is required");
        } 
        else{
            $('.validationErrorMessage15').html(errorMessage);        
            $('.validationErrorMessage15').show();
        } 
    }
    else if(pass != cnfpass){
        error = true;
        errorMessage = "Password mismatch!";
        $('#cnfpass').focus();
        if(isMobile){
            alert("Password mismatch!");
        } 
        else{
            $('.validationErrorMessage15').html(errorMessage);        
            $('.validationErrorMessage15').show();
        } 
    } 

    else if(creditcard == ""){
        error = true;
        errorMessage = "This is required";
        $('#credit').focus();
        if(isMobile){
            alert("Credit card number is required");
        }
        else{ 
            $('.validationErrorMessage17').html(errorMessage); 
            $('.validationErrorMessage17').show();
        }            
    }
    else if((creditcard.length < 13 || creditcard.length >16) || isNaN(creditcard)){
        error = true;
        errorMessage = "Invalid credit card";
        $('#credit').focus();
        if(isMobile){
            alert("Invalid credit card");
        }
        else{
            $('.validationErrorMessage17').html(errorMessage); 
            $('.validationErrorMessage17').show(); 
        }           
    }

    // if(credit1 == "" ){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#credit1').focus();
    //     $('.validationErrorMessage17').html(errorMessage);        
    //     $('.validationErrorMessage17').show(); 
    // }
    // else if(isNaN(credit1) || credit1.length !=4 ){
    //     error = true;
    //     errorMessage = "Enter valid credit card number";
    //     $('#credit1').focus();
    //     $('.validationErrorMessage17').html(errorMessage);        
    //     $('.validationErrorMessage17').show(); 
    // }
    //  else if(credit2 == "" ){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#credit2').focus();
    //     $('.validationErrorMessage17').html(errorMessage);        
    //     $('.validationErrorMessage17').show(); 
    // }
    // else if(isNaN(credit2) || credit2.length !=4 ){
    //     error = true;
    //     errorMessage = "Enter valid credit card number";
    //     $('#credit2').focus();
    //     $('.validationErrorMessage17').html(errorMessage);        
    //     $('.validationErrorMessage17').show(); 
    // }
    // else if(credit3 == "" ){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#credit3').focus();
    //     $('.validationErrorMessage17').html(errorMessage);        
    //     $('.validationErrorMessage17').show(); 
    // }
    // else if(isNaN(credit3) || credit3.length !=4 ){
    //     error = true;
    //     errorMessage = "Enter valid credit card number";
    //     $('#credit3').focus();
    //     $('.validationErrorMessage17').html(errorMessage);        
    //     $('.validationErrorMessage17').show(); 
    // }
    // else if(credit4 == "" ){
    //     error = true;
    //     errorMessage = "This is required";
    //     $('#credit4').focus();
    //     $('.validationErrorMessage17').html(errorMessage);        
    //     $('.validationErrorMessage17').show(); 
    // }
    // else if(isNaN(credit4) || credit4.length !=4 ){
    //     error = true;
    //     errorMessage = "Enter valid credit card number";
    //     $('#credit4').focus();
    //     $('.validationErrorMessage17').html(errorMessage);        
    //     $('.validationErrorMessage17').show(); 
    // }

    else if(cMonth == "" || cMonth == 0 || isNaN(cMonth)){
        error = true;
        errorMessage = "This is required";
        $('#cMonth').focus();
        if(isMobile){
            alert("Month is required");
        }
        else{
            $('.validationErrorMessage19').html(errorMessage);   
            $('.validationErrorMessage19').show();
        }          
    }
    else if(cYear == "" || cYear == 0 || isNaN(cYear)){
        error = true;
        errorMessage = "This is required";
        $('#cYear').focus();
        if(isMobile){
            alert("Year is required");
        }
        else{
            $('.validationErrorMessage20').html(errorMessage);
            $('.validationErrorMessage20').show();
        }             
    }
    else if(cvv == ""){
        error = true;
        errorMessage = "This is required";
        $('#cvv').focus();
        if(isMobile){
            alert("Cvv is required");
        }
        else{
            $('.validationErrorMessage18').html(errorMessage); 
            $('.validationErrorMessage18').show();
        }            
    }
    else if(cvv.length < 3 || cvv.length > 4 || isNaN(cvv) ){
        error = true;
        errorMessage = "Invalid CVV";
        $('#cvv1').focus();
        if(isMobile){
            alert("Invalid CVV");
        }
        else{
            $('.validationErrorMessage18').html(errorMessage); 
            $('.validationErrorMessage18').show();
        }            
    }
    else if(amount.length == 0 || amount == "" || isNaN(amount) ){
        error = true;
        errorMessage = "Invalid amount";
        $('#cvv1').focus();
        if(isMobile){
            alert("Invalid amount");
        }
        else{
            $('.validationErrorMessage18').html(errorMessage);  
            $('.validationErrorMessage18').show();  
        }         
    }
    

    if(error){

    }
    else {
        var telephone = telephone1+telephone2+telephone3;

        var reqData = {
                    FirstName: FirstName,
                    LastName : LastName,
                    Address : Address,
                    Address2 : Address2,
                    City : City,
                    PostalCode : PostalCode,
                    state : state,
                    Email : Email,
                    creditcard : cipher,
                    cMonth : cMonth,
                    cYear : cYear,
                    cvv : cvv,
                    amount : amount,
                    ip : clientIp,
                    pass : pass,
                    classId : classId,
                    lno : lno,
                    telephone : telephone,
                    promocode : promocode,
                    studentInitName : studentInitName
                };
        var reqDataOrder = {
                    orderId: orderId,
                    transaction : '',
                    ip : clientIp
                };
        
        var reqDataJson = JSON.stringify(reqData);       
        $.ajax({
            type:'POST',
            url:'/site/cfc/payment.cfc?method=pay',
            data: {reqData : reqDataJson},
            success:function(data) {
                var dataOBj = JSON.parse(data);
                console.log('dataOBj',dataOBj);
                // console.log(dataOBj);
                if('PAID' in dataOBj){
                    console.log('Already paid.');                     
                    $(".modal1").hide();                 
                    var transMsg = 'Student already purchased this class!!. Please login';                      
                    $('#response1').html('<div>Details : '+transMsg+'</div>');
                    $('#response1').addClass('alert alert-success'); 
                }
                if('INACTIVE_ACCOUNT' in dataOBj){
                    console.log('Account is Inactive.');                     
                    $(".modal1").hide();                 
                    var transMsg = 'The Account is Inactive';                      
                    $('#response1').html('<div>Details : '+transMsg+'</div>');
                    $('#response1').addClass('alert alert-danger'); 
                }
                if('PASSWORD_MISSMATCH' in dataOBj){
                    var maskedpass = dataOBj.MASKEDPASSWORD; 
                    $('#maskedpass_modal').html(maskedpass);   
                    console.log('The account already exist.');                     
                    console.log(lno);  
                    var requestData = {
                        lno : lno
                    };
                    var reqDataJson = JSON.stringify(requestData);
                    $.ajax({
                        type:'POST',
                        url:'/site/model/cfc/common.cfc?method=getStudentDistinctEmail',
                        data: {reqData : reqDataJson},
                        success:function(data) {
                            var dataOBj = JSON.parse(data);
                            console.log(dataOBj);
                            console.log(dataOBj.length);
                            if(dataOBj.length){
                              $('#newemailId').html("");
                              $('#newemailId').append(`<option value="0">Choose Email</option>`);
                              for(var i = 0; i < dataOBj.length; i++) {
                                $('#newemailId').append(`
                                  <option value="${dataOBj[i]}">${dataOBj[i].replace(/^(.)(.*)(.@.*)$/,
                                  (_, a, b, c) => a + b.replace(/./g, '*') + c)}</option>
                                  `)
                              }
                            }
                        },
                        error:function(obj) {
                            console.log('error');
                            console.log(obj);
                        }
                    });                       
                    $(".modal1").hide(); 
                    $('#myModal').modal('show');                
                   // var transMsg = 'The account already exist';                      
                   // $('#response1').html('<div>Details : '+transMsg+'</div>');
                   // $('#response1').addClass('alert alert-success'); 
                } else{
                    if(dataOBj.messages.resultCode == 'Ok'){
                        if(dataOBj.transactionResponse){
                           if(dataOBj.transactionResponse.responseCode === "1" || dataOBj.transactionResponse.responseCode === 1 ){                            
                               var transMsg = dataOBj.transactionResponse.messages.messages.message;
                               var transSha = dataOBj.transactionResponse.transHashSha2;
                               var transId = dataOBj.transactionResponse.transId;
                               var orderIdData = dataOBj.orderId;
                               var invoiceId = dataOBj.invoiceId;
                               var avsResultCode = dataOBj.transactionResponse.avsResultCode;
                               switch("1") {
                                    case "1":
                                        $('#response1').html('<div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-success');
                                        //reqDataOrder.transaction = transId;
                                        // reqDataOrder.orderId = dataOBj.orderId;
                                        //updateOrder(reqDataOrder);
                                        $('#btnSubmit').remove();
                                        $('#studentAddForm').append('<input type="hidden" name="transactionId" id="transactionId" value="'+transId+'">')
                                        $('#studentAddForm').append('<input type="hidden" name="orderId" id="orderId" value="'+orderIdData+'">')
                                        $('#studentAddForm').append('<input type="hidden" name="invoiceId" id="invoiceId" value="'+invoiceId+'">')
                                        $('#studentAddForm').append('<input type="hidden" name="addStudent" id="addStudent" >');
                                        $('#studentAddForm').submit();
                                        //setTimeout(function(){$('#studentAddForm').submit();}, 800);
                                    break;
                                    case "Y":
                                        $('#response1').html('<div>Street Address and ZIP: Match</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-success');
                                        reqDataOrder.transaction = transId;
                                        updateOrder(reqDataOrder);
                                        $('#btnSubmit').remove();
                                        $('#studentAddForm').append('<input type="hidden" name="transactionId" id="transactionId" value="'+transId+'">')
                                        $('#studentAddForm').append('<input type="hidden" name="addStudent" id="addStudent" >')
                                        setTimeout(function(){$('#studentAddForm').submit();}, 800);
                                    break;
                                    case "Z":
                                        $('#response1').html('<div>Street Address : No Match and ZIP: Match</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-success');
                                        // reqDataOrder.transaction = transId;
                                        updateOrder(reqDataOrder);
                                        $('#btnSubmit').remove();
                                        $('#studentAddForm').append('<input type="hidden" name="transactionId" id="transactionId" value="'+transId+'">')
                                        $('#studentAddForm').append('<input type="hidden" name="addStudent" id="addStudent" >')
                                        setTimeout(function(){$('#studentAddForm').submit();}, 800);              
                                    break;
                                    case "S":
                                        $('#response1').html('<div>AVS Not Supported by Card Issuing Bank</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "U":
                                        $('#response1').html('<div>Address Information For This Cardholder Is Unavailable</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "R":
                                        $('#response1').html('<div>Retry, System Is Unavailable</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "P":
                                        $('#response1').html('<div>AVS not applicable for this transaction</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "G":
                                        $('#response1').html('<div>Non U.S. Card Issuing Bank</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "N":
                                        $('#response1').html('<div>Street Address and ZIP: No Match</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "E":
                                        $('#response1').html('<div>AVS Error</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "B":
                                        $('#response1').html('<div>Address not provided for AVS check or street address match, postal code could not be verified</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "A":
                                        $('#response1').html('<div>Street Address: Match and ZIP: No Match</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                    default:
                                        $('#response1').html('<div>Something went wrong. Please try again.</div><div>Transaction ID : '+transId+'</div>');
                                        $('#response1').addClass('alert alert-danger');
                                    break;
                                }                         
                              
                            }
                            else{
                               console.log(dataOBj.transactionResponse.errors);
                                var transMsg = dataOBj.transactionResponse.errors.errors.error;
                                var transId = dataOBj.transactionResponse.transId;
                                console.log(transMsg);
                                console.log(transId);
                               if(dataOBj.transactionResponse.responseCode == 2){        
                                    $('#response1').html('<div>Transaction Declined</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                }
                                else if(dataOBj.transactionResponse.responseCode == 3){
                                     $('#response1').html('<div>Transaction Error</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                }
                                else if(dataOBj.transactionResponse.responseCode == 4){
                                     $('#response1').html('<div>Transaction held for review</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                }
                                $('#response1').addClass('alert alert-danger'); 
                            }
                       }                  
                    }
                    else {
                           /* reqDataOrder.orderId = dataOBj.orderId;
                            let reqDataOrderJson = JSON.stringify(reqDataOrder);
                            $.ajax({
                                type:'POST',
                                url:'/site/service/cfc/studentService.cfc?method=deleteInitiatedOrder',
                                data: {reqData : reqDataOrderJson},
                                success:function(data) {
                                },
                                error : function(e){

                                }
                            });
                           console.log('failed'); */
                           var apiMsg = dataOBj.messages.message.text;
                                      
                           var transMsg = dataOBj.transactionResponse.errors.errors.error;
                           $(".modal1").hide();      
                           $('#response1').html('<div>'+apiMsg+'<div><div>Details : '+transMsg+'</div>');
                           $('#response1').addClass('alert alert-danger'); 
                                         
                    }
                }
            },
            error:function(obj) {
                reqDataOrder.orderId = dataOBj.orderId;
                let reqDataOrderJson = JSON.stringify(reqDataOrder);
                $.ajax({
                    type:'POST',
                    url:'/site/service/cfc/studentService.cfc?method=deleteInitiatedOrder',
                    data: {reqData : reqDataOrderJson},
                    success:function(data) {
                    },
                    error : function(e){

                    }
                });
                console.log('error');
                console.log(obj)
                $(".modal1").hide();

            },
            beforeSend: function () {
               $(".modal1").show();
            },
            complete: function () {
                $(".modal1").hide();
            }
        });
    }
}

function initiatePay3Modal(){
    $('.vald').html('');
    $('#response1').html('');
    $('#response1').removeClass('alert alert-success');
    $('#response1').removeClass('alert alert-danger');
    var clientIp = $.trim($('#ipinfo').val());
    var FirstName = $.trim($('#firstName').val());
    var LastName = $.trim($('#lastName').val());
    var pass = $.trim($('#passwrd').val());
    var studentInitName = $.trim($('#studentInitName').val());
    
    var creditcard = $.trim($('#credit').val()); 
    creditcard = creditcard.replace(/\s/g, "");

    var base64Key = "MTIzNDU2NzgxMjM0NTY3OA==";
    var base64IV = "EBESExQVFhcYGRobHB0eHw==";

    var key = CryptoJS.enc.Base64.parse(base64Key);
    var iv  = CryptoJS.enc.Base64.parse(base64IV);

    var encrypted = CryptoJS.AES.encrypt(creditcard, key, {iv: iv});
    var cipher = encrypted.toString();
    console.log(encrypted.toString());

    var decrypted =  CryptoJS.AES.decrypt(encrypted, key, {iv: iv})
    
    console.log(decrypted.toString(CryptoJS.enc.Utf8)); 

    var cMonth = $.trim($('#cMonth').val());
    var cYear = $.trim($('#cYear').val());
    var cvv = $.trim($('#cCvv').val());
    var orderId = $.trim($('#orderId').val());
    var classId = $.trim($('#classId').val());
    var studentId = $.trim($('#studentId').val());
    var siteId = $.trim($('#siteId').val());
    var amount = $.trim($('#amount').val());
    var lno = $.trim($('#lnum').val());
    // var telephone1 = $.trim($('#Telephone1').val());
    // var telephone2 = $.trim($('#Telephone2').val());   
    // var telephone3 = $.trim($('#Telephone3').val());
    console.log(amount);

    var error = false;
    var errorMessage = '';
    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

    if(FirstName == ""){
        error = true;
        errorMessage = "This is required";
        $('#firstName').focus();
        if(isMobile){
           alert("First Name is required");
        }
        else
        {
            $('.validationErrorMessage21').html(errorMessage); 
        }       
    }
    else if(LastName == ""){
        error = true;
        errorMessage = "This is required";
        $('#lastName').focus();
        if(isMobile){
           alert("Last Name is required");
        }
        else{
            $('.validationErrorMessage31').html(errorMessage);
        }          
    }
   

    else if(creditcard == ""){
        error = true;
        errorMessage = "This is required";
        $('#credit').focus();
        if(isMobile){
            alert("Credit card number is required");
        }
        else{ 
            $('.validationErrorMessage17').html(errorMessage); 
            $('.validationErrorMessage17').show();
        }            
    }
    else if((creditcard.length < 13 || creditcard.length >16) || isNaN(creditcard)){
        error = true;
        errorMessage = "Invalid credit card";
        $('#credit').focus();
        if(isMobile){
            alert("Invalid credit card");
        }
        else{
            $('.validationErrorMessage17').html(errorMessage); 
            $('.validationErrorMessage17').show(); 
        }           
    }

    else if(cMonth == "" || cMonth == 0 || isNaN(cMonth)){
        error = true;
        errorMessage = "This is required";
        $('#cMonth').focus();
        if(isMobile){
            alert("Month is required");
        }
        else{
            $('.validationErrorMessage19').html(errorMessage);   
            $('.validationErrorMessage19').show();
        }          
    }
    else if(cYear == "" || cYear == 0 || isNaN(cYear)){
        error = true;
        errorMessage = "This is required";
        $('#cYear').focus();
        if(isMobile){
            alert("Year is required");
        }
        else{
            $('.validationErrorMessage20').html(errorMessage);
            $('.validationErrorMessage20').show();
        }             
    }
    else if(cvv == ""){
        error = true;
        errorMessage = "This is required";
        $('#cvv').focus();
        if(isMobile){
            alert("Cvv is required");
        }
        else{
            $('.validationErrorMessage18').html(errorMessage); 
            $('.validationErrorMessage18').show();
        }            
    }
    else if(cvv.length < 3 || cvv.length > 4 || isNaN(cvv) ){
        error = true;
        errorMessage = "Invalid CVV";
        $('#cvv1').focus();
        if(isMobile){
            alert("Invalid CVV");
        }
        else{
            $('.validationErrorMessage18').html(errorMessage); 
            $('.validationErrorMessage18').show();
        }            
    }
    else if(amount.length == 0 || amount == "" || isNaN(amount) ){
        error = true;
        errorMessage = "Invalid amount";
        $('#cvv1').focus();
        if(isMobile){
            alert("Invalid amount");
        }
        else{
            $('.validationErrorMessage18').html(errorMessage);  
            $('.validationErrorMessage18').show();  
        }         
    }
    

    if(error){

    }
    else {

        var reqData = {
                    FirstName: FirstName,
                    LastName : LastName,
                    creditcard : cipher,
                    cMonth : cMonth,
                    cYear : cYear,
                    cvv : cvv,
                    amount : amount,
                    ip : clientIp,
                    pass : pass,
                    classId : classId,
                    lno : lno,
                    studentInitName : studentInitName
                    
                };
        var reqDataOrder = {
                    orderId: orderId,
                    transaction : '',
                    ip : clientIp
                };
        var reqDataJson = JSON.stringify(reqData);
        console.log(reqDataJson);
        $.ajax({
            type:'POST',
            url:'/site/service/cfc/paymentService.cfc?method=payModal',
            data: {reqData : reqDataJson},
            success:function(data) {
                var dataOBj = JSON.parse(data);

                if('PAID' in dataOBj){
                        console.log('Already paid.');                     
                        $(".modal1").hide();                 
                       var transMsg = 'Student already purchased this class!!. Please login';                      
                       $('#response1').html('<div>Details : '+transMsg+'</div>');
                       $('#response1').addClass('alert alert-success'); 
                    }
                if('INACTIVE_ACCOUNT' in dataOBj){
                    console.log('Account is Inactive.');                     
                    $(".modal1").hide();                 
                   var transMsg = 'The Account is Inactive';                      
                   $('#response1').html('<div>Details : '+transMsg+'</div>');
                   $('#response1').addClass('alert alert-danger'); 
                }
                if('PASSWORD_MISSMATCH' in dataOBj){
                    var maskedpass = dataOBj.MASKEDPASSWORD; 
                    $('#maskedpass_modal').html(maskedpass);   
                    console.log('The account already exist.');                     
                    console.log(lno);  
                    var requestData = {
                        lno : lno
                    };
                    var reqDataJson = JSON.stringify(requestData);
                    $.ajax({
                        type:'POST',
                        url:'/site/model/cfc/common.cfc?method=getStudentDistinctEmail',
                        data: {reqData : reqDataJson},
                        success:function(data) {
                            var dataOBj = JSON.parse(data);
                            console.log(dataOBj);
                            console.log(dataOBj.length);
                            if(dataOBj.length){
                              $('#newemailId').html("");
                              $('#newemailId').append(`<option value="0">Choose Email</option>`);
                              for(var i = 0; i < dataOBj.length; i++) {
                                $('#newemailId').append(`
                                  <option value="${dataOBj[i]}">${dataOBj[i].replace(/^(.)(.*)(.@.*)$/,
                                  (_, a, b, c) => a + b.replace(/./g, '*') + c)}</option>
                                  `)
                              }
                            }
                        },
                        error:function(obj) {
                            console.log('error');
                            console.log(obj);
                        }
                    });                       
                    $(".modal1").hide(); 
                    $('#myModal').modal('show');                
                   // var transMsg = 'The account already exist';                      
                   // $('#response1').html('<div>Details : '+transMsg+'</div>');
                   // $('#response1').addClass('alert alert-success'); 
                }
                else{
                    if(dataOBj.messages.resultCode == 'Ok'){
                       console.log('success');
                       if(dataOBj.transactionResponse){
                        console.log(dataOBj.transactionResponse.messages);
                            if(dataOBj.transactionResponse.responseCode == 1){                            
                               var transMsg = dataOBj.transactionResponse.messages.messages.message;
                               var transSha = dataOBj.transactionResponse.transHashSha2;
                               var transId = dataOBj.transactionResponse.transId;
                               console.log(transMsg);
                               console.log(transSha);
                               console.log(transId);
                               var avsResultCode = dataOBj.transactionResponse.avsResultCode;
                              switch("1") {
                                    case "1":
                                   $('#response1').html('<div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                   $('#response1').addClass('alert alert-success');
                                   reqDataOrder.transaction = transId;
                                   updateOrder(reqDataOrder);
                                   $('#btnSubmit').remove();
                                   $('#studentAddFormModal').append('<input type="hidden" name="transactionId" id="transactionId" value="'+transId+'">')
                                    $('#studentAddFormModal').append('<input type="hidden" name="addStudent" id="addStudent" >')
                                   // setTimeout(function(){
                                   //      location.reload(true);
                                   // },1000);
                                    setTimeout(function(){$('#studentAddFormModal').submit();}, 800);
                                    break;
                                  case "Y":
                                   $('#response1').html('<div>Street Address and ZIP: Match</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                   $('#response1').addClass('alert alert-success');
                                   reqDataOrder.transaction = transId;
                                   updateOrder(reqDataOrder);
                                   $('#btnSubmit').remove();
                                   $('#studentAddFormModal').append('<input type="hidden" name="transactionId" id="transactionId" value="'+transId+'">')
                                    $('#studentAddFormModal').append('<input type="hidden" name="addStudent" id="addStudent" >')
                                    setTimeout(function(){$('#studentAddFormModal').submit();}, 800);
                                    break;
                                  case "Z":
                                    $('#response1').html('<div>Street Address : No Match and ZIP: Match</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-success');
                                    // reqDataOrder.transaction = transId;
                                   updateOrder(reqDataOrder);
                                   $('#btnSubmit').remove();
                                    $('#studentAddFormModal').append('<input type="hidden" name="transactionId" id="transactionId" value="'+transId+'">')
                                    $('#studentAddFormModal').append('<input type="hidden" name="addStudent" id="addStudent" >')
                                    setTimeout(function(){$('#studentAddFormModal').submit();}, 800);              
                                    break;
                                    case "S":
                                    $('#response1').html('<div>AVS Not Supported by Card Issuing Bank</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "U":
                                    $('#response1').html('<div>Address Information For This Cardholder Is Unavailable</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "R":
                                    $('#response1').html('<div>Retry, System Is Unavailable</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "P":
                                    $('#response1').html('<div>AVS not applicable for this transaction</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                    break;
                                     case "G":
                                    $('#response1').html('<div>Non U.S. Card Issuing Bank</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                    break;
                                     case "N":
                                    $('#response1').html('<div>Street Address and ZIP: No Match</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "E":
                                    $('#response1').html('<div>AVS Error</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "B":
                                    $('#response1').html('<div>Address not provided for AVS check or street address match, postal code could not be verified</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                    break;
                                    case "A":
                                    $('#response1').html('<div>Street Address: Match and ZIP: No Match</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                    break;
                                  default:
                                    $('#response1').html('<div>Something went wrong. Please try again.</div><div>Transaction ID : '+transId+'</div>');
                                    $('#response1').addClass('alert alert-danger');
                                }                         
                              
                            }
                            else{
                               console.log(dataOBj.transactionResponse.errors);
                                var transMsg = dataOBj.transactionResponse.errors.errors.error;
                                var transId = dataOBj.transactionResponse.transId;
                                console.log(transMsg);
                                console.log(transId);
                               if(dataOBj.transactionResponse.responseCode == 2){        
                                    $('#response1').html('<div>Transaction Declined</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                }
                                else if(dataOBj.transactionResponse.responseCode == 3){
                                     $('#response1').html('<div>Transaction Error</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                }
                                else if(dataOBj.transactionResponse.responseCode == 4){
                                     $('#response1').html('<div>Transaction held for review</div><div>'+transMsg+'<div><div>Transaction ID : '+transId+'</div>');
                                }
                                $('#response1').addClass('alert alert-danger'); 
                            }
                       }                  
                    }
                    else {
                        
                       
                           console.log('failed'); 
                           var apiMsg = dataOBj.messages.message.text;
                            $(".modal1").hide();                 
                           var transMsg = dataOBj.transactionResponse.errors.errors.error;
                           console.log(transMsg);
                           console.log(transSha);
                           console.log(transId);
                           $('#response1').html('<div>'+apiMsg+'<div><div>Details : '+transMsg+'</div>');
                           $('#response1').addClass('alert alert-danger'); 
                                         
                    }
                }
            },
            error:function(obj) {
                console.log('error');
                console.log(obj)
                $(".modal1").hide();

            },
            beforeSend: function () {
               $(".modal1").show(); 
            },
            complete: function () {
                $(".modal1").hide();
            }
        });
    }
}

function checkPayment(){
    var siteId = $.trim($('#siteId').val());
    var pass = $.trim($('#pass').val());
    var lno = $.trim($('#lnum').val());
    var payLater = $('#payLater').is(':checked');
    var oneHourCourse = $('#oneHourCourse').is(':checked');
    var classId = $.trim($('#classId').val());    
    if(payLater){
      var reqData = {
                siteId: siteId,
                pass: pass,
                lno: lno,
                classId:classId
            };
        var reqDataJson = JSON.stringify(reqData);
        $.ajax({
            type:'POST',
            url:'/site/cfc/enrollment.cfc?method=checkSitePass',
            data: {reqData : reqDataJson},
            success:function(data) {
                var dataOBj = JSON.parse(data);
                console.log(dataOBj);
                if('PASSWORD_MISSMATCH' in dataOBj){
                    var maskedpass = dataOBj.MASKEDPASSWORD; 
                    $('#maskedpass_modal').html(maskedpass);
                    $.ajax({
                        type:'POST',
                        url:'/site/cfc/student.cfc?method=getStudentDistinctEmail',
                        data: {
                            lno : lno
                        },
                        success:function(data) {
                            var dataOBjs = JSON.parse(data);
                            console.log(dataOBjs);
                            console.log(dataOBjs.length);
                            if(dataOBjs.length){
                                $('#newemailId').html("");
                                $('#newemailId').append(`<option value="0">Choose Email</option>`);
                                for(var i = 0; i < dataOBjs.length; i++) {
                                $('#newemailId').append(`
                                    <option value="${dataOBjs[i]}">${dataOBjs[i].replace(/^(.)(.*)(.@.*)$/,
                                    (_, a, b, c) => a + b.replace(/./g, '*') + c)}</option>
                                    `)
                                }
                            }
                        },
                        error:function(obj) {
                            console.log('error');
                            console.log(obj);
                        }
                    });
                    $(".modal1").hide(); 
                    $('#myModal').modal('show');
                }
                if('PASSWORD_MATCH' in dataOBj){
                  // alert('hi')
                  $('#studentAddForm').append('<input type="hidden" name="addStudent" id="addStudent" >')
                  $('#studentAddForm').submit();
                }
                if('INACTIVE' in dataOBj){
                  // alert('hi')
                  $('#studentAddForm').append('<input type="hidden" name="addStudent" id="addStudent" >')
                  $('#studentAddForm').submit();
                }
                if('NEW_USER' in dataOBj){
                  // alert('hi')
                  $('#studentAddForm').append('<input type="hidden" name="addStudent" id="addStudent" >')
                  $('#studentAddForm').submit();
                }
                
            },
            error:function(obj) {
                console.log('error');
                console.log(obj);
            }
        });
        // $('#studentAddForm').append('<input type="hidden" name="addStudent" id="addStudent" >')
        // $('#studentAddForm').submit();
    }
    else{
        initiatePay3();
    }   
}

function checkPaymentModal(){
    var siteId = $.trim($('#siteId').val());
    var pass = $.trim($('#passwrd').val());
    var lno = $.trim($('#lnum').val());
    var payLater = $('#payLater').is(':checked');
    var oneHourCourse = $('#oneHourCourse').is(':checked');
    
    if(payLater){
      var reqData = {
                siteId: siteId,
                pass: pass,
                lno: lno
            };
        var reqDataJson = JSON.stringify(reqData);
        $.ajax({
            type:'POST',
            url:'/site/cfc/enrollment.cfc?method=checkSitePass',
            data: {reqData : reqDataJson},
            success:function(data) {
                var dataOBj = JSON.parse(data);
                console.log(dataOBj);
                if('PASSWORD_MISSMATCH' in dataOBj){
                  var maskedpass = dataOBj.MASKEDPASSWORD; 
                  $('#maskedpass_modal').html(maskedpass);
                  var requestData = {
                          lno : lno
                  };
                  var requestDataJson = JSON.stringify(requestData);
                  $.ajax({
                      type:'POST',
                      url:'/site/cfc/student.cfc?method=getStudentDistinctEmail',
                      data: {reqData : requestDataJson},
                      success:function(data) {
                          var dataOBjs = JSON.parse(data);
                          console.log(dataOBjs);
                          console.log(dataOBjs.length);
                          if(dataOBjs.length){
                            $('#newemailId').html("");
                            $('#newemailId').append(`<option value="0">Choose Email</option>`);
                            for(var i = 0; i < dataOBjs.length; i++) {
                              $('#newemailId').append(`
                                <option value="${dataOBjs[i]}">${dataOBjs[i].replace(/^(.)(.*)(.@.*)$/,
                                (_, a, b, c) => a + b.replace(/./g, '*') + c)}</option>
                                `)
                            }
                          }
                      },
                      error:function(obj) {
                          console.log('error');
                          console.log(obj);
                      }
                  });
                   $(".modal1").hide(); 
                   $('#myModal').modal('show');
                }
                if('PASSWORD_MATCH' in dataOBj){
                  // alert('hi')
                  $('#studentAddFormModal').append('<input type="hidden" name="addStudent" id="addStudent" >')
                  $('#studentAddFormModal').submit();
                }
                if('NEW_USER' in dataOBj){
                  // alert('hi')
                  $('#studentAddFormModal').append('<input type="hidden" name="addStudent" id="addStudent" >')
                  $('#studentAddFormModal').submit();
                }
                
            },
            error:function(obj) {
                console.log('error');
                console.log(obj);
            }
        });
        // $('#studentAddForm').append('<input type="hidden" name="addStudent" id="addStudent" >')
        // $('#studentAddForm').submit();
    }
    else{
        initiatePay3Modal();
    }   
}

function retrivePassword(){
    var emailId = $('#emailId').val();
    $('#validationEmail').html('');       
    var  error = false;
    if(emailId == "" ){
        error = true;
        errorMessage = "This is required";
        $('#emailId').focus();
        $('#validationEmail').html(errorMessage); 
    }
    else if(!(validateEmail(emailId))){
        error = true;
        errorMessage = "Please enter valid email";
        $('#emailId').focus();
        $('#validationEmail').html(errorMessage);        
    }
    if(!error){
        $.ajax({
            type:'POST',
            url:'/site/cfc/login.cfc?method=sendResetLink',
            data: { email : emailId },
            success:function(data) {
                var dataOBj = JSON.parse(data);
                console.log(dataOBj);
                if(dataOBj.SUCCESS){
                    $('#rtrvBtn').remove();
                    $('#frgtCont').html('<p>Link to reset password sent to your registered email. Please check your mail.<p>');
                }
                else{
                    if((dataOBj.SUUID).length == 0){
                        errorMessage = "Email is not registered to any student.";
                        $('#emailId').focus();
                        $('#validationEmail').html(errorMessage);  
                    }
                }
                
            },
            error:function(obj) {
                console.log('error');
                console.log(obj);
            }
        });
    }
    else{
        return false;        
    }
}

function retrivesitePassword(){
    var e = document.getElementById("newemailId");
    var strUser = e.options[e.selectedIndex].text;

    var newemailId = $('#newemailId').val();
    $('#validationEmail011').text('');       
    var  error = false;
    console.log(strUser);

     if(newemailId == 0 ){
        error = true;
        let errorMessage = "This is required";
        $('#newemailId').focus();
        $('#validationEmail011').text(errorMessage); 
    }
    //  else if(!(validateEmail(newemailId))){
    //     error = true;
    //     errorMessage = "Please enter valid email";
    //     $('#newemailId').focus();
    //     $('#validationEmail011').text(errorMessage);        
    // }
    if(error){

    }
    else{
        var reqData = {
                    email : newemailId
                };
       
        var reqDataJson = JSON.stringify(reqData);
        $.ajax({
            type:'POST',
            url:'/site/cfc/login.cfc?method=sendResetLink',
            data: {reqData : reqDataJson},
            success:function(data) {
                var dataOBj = JSON.parse(data);
                console.log(dataOBj);
                if(dataOBj.SUCCESS){
                    $('#rtrvsiteBtn').remove();
                    $('#forgotCont').html('<p>Link to reset password sent to your registered email. Please check your mail.<p>');
                }
                else{
                    if((dataOBj.SUUID).length == 0){
                        errorMessage = "Email is not registered to any student.";
                        $('#newemailId').focus();
                        $('#validationEmail011').html(errorMessage);  
                    }
                }
                
            },
            error:function(obj) {
                console.log('error');
                console.log(obj);
            }
        });        
    }
}

$(".modal").on("hidden.bs.modal", function() { 
    $(this).find('form').trigger("reset"); 
    console.log('test');
$('#logError1').html('');
$('#validationEmail').html('');  
    
});

 $('body').on('mouseover', '#cvvHint', function() {
    console.log('test');
     $(this).popover({
        html: true,
      trigger: 'hover',
      placement: 'bottom',
      content: function () { return '<img src="' + $(this).data('img') + '" />'; }
      }).popover('show');
});

// document.getElementById('credit').addEventListener('input', function (e) {
$('body').on('input', '#credit', function(e) {
  var crediCardValue = e.target.value;
  crediCardValue = crediCardValue.replace(/\s/g, "");
  var ccLength = crediCardValue.length;  
  // console.log(crediCardValue);
  console.log(ccLength);
  if(ccLength <16){
    e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
  }
  else{    
    e.preventDefault();  
  }
});

$('body').on('keypress', '#credit', function(e) {
  var crediCardValue = e.target.value;
  crediCardValue = crediCardValue.replace(/\s/g, "");
  var ccLength = crediCardValue.length;  

  console.log(ccLength);
  if(ccLength >15){   
    e.preventDefault();  
  }
});

$('body').on('input', '#creditcard', function(e) {
  var crediCardValue = e.target.value;
  crediCardValue = crediCardValue.replace(/\s/g, "");
  var ccLength = crediCardValue.length;  
  // console.log(crediCardValue);
  console.log(ccLength);
  if(ccLength <16){
    e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
  }
  else{    
    e.preventDefault();  
  }
});

$('body').on('keypress', '#creditcard', function(e) {
  var crediCardValue = e.target.value;
  crediCardValue = crediCardValue.replace(/\s/g, "");
  var ccLength = crediCardValue.length;  

  console.log(ccLength);
  if(ccLength >15){   
    e.preventDefault();  
  }
});

$('body').on('input', '#creditcard1', function(e) {
  var crediCardValue = e.target.value;
  crediCardValue = crediCardValue.replace(/\s/g, "");
  var ccLength = crediCardValue.length;  
  // console.log(crediCardValue);
  console.log(ccLength);
  if(ccLength <16){
    e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
  }
  else{    
    e.preventDefault();  
  }
});

$('body').on('keypress', '#creditcard1', function(e) {
  var crediCardValue = e.target.value;
  crediCardValue = crediCardValue.replace(/\s/g, "");
  var ccLength = crediCardValue.length;  

  console.log(ccLength);
  if(ccLength >15){   
    e.preventDefault();  
  }
});

$(document).on('change', '#langSelector', function (e) {
    var classId = $(this).attr('data-class');
    var studentId = $(this).attr('data-student');
    var languageId = this.value;

    var reqData = {
                    classId : classId,
                    studentId : studentId,
                    languageId : languageId
                };
       
        var reqDataJson = JSON.stringify(reqData);
        $.ajax({
            type:'POST',
            url:'/site/service/cfc/siteservice.cfc?method=setPreferredLanguage',
            data: {reqData : reqDataJson},
            success:function(data) {
                var dataOBj = JSON.parse(data);
                console.log(dataOBj);
                if(dataOBj.SUCCESS){
                  
                }
                else{
                   
                }
                
            },
            error:function(obj) {
                console.log('error');
                console.log(obj);
            }
        });    
});

function parseUrlQueryString(queryString) {
    var obj = {},
        temp = [];
    if(queryString.length > 0) {
        queryString.replace('?','').trim().split('&').forEach((e) => {
            temp = e.trim().split('=');
            if(temp.length == 2)
                if(temp[0].trim().length > 0)
                    obj[temp[0].trim()] = temp[1].trim();
        });
    }
    return obj;
}
