var errors = '';

function getapprovequery(actstep, div, idd, total, providerid, inscompany) {
//    var comment_tag = "comment_" + idd;
//    var comment = document.getElementById(comment_tag).value;
    var forms = $('#form_' + idd).serialize();
    document.getElementById(div).innerHTML = "Processing Please Wait...";
    $.ajax({
        type: "POST",
        url: "getstep.php",
        data: forms + "&act=" + actstep + "&id=" + idd + "&total=" + total + "&provider_id=" + providerid + "&ins_company=" + inscompany,
        success: function () {
            current_opac();
            Materialize.toast('Success! All Information has been saved Successfully', 4000, 'success');
            $('#refresh_items').trigger('click');
        }
    });
}

function errormap(actstep) {
    errors = "";
	
	if (actstep == "part_payment_authorization" ){
		if (!document.getElementById('authorized_amount_requested').value || document.getElementById('authorized_amount_requested').value==0){
            errors = errors + "Part-Payment Amount Requested must be greater than 0\n";
            document.getElementById('authorized_amount_requested').style.border = "solid red 1px";
        } else {
            document.getElementById('authorized_amount_requested').style.border = "";
        }
	}
	
	
	if (actstep == "make_deposit_refund"){
		
	if(!document.getElementById('transaction_type_0').checked && !document.getElementById('transaction_type_1').checked){ 		
		errors = errors + "Please Select Type of Transaction\n";
				document.getElementById('transaction_area').style.border = "solid red 1px";	
		}else{
		     document.getElementById('transaction_area').style.border = "";	
		}
		
		if(document.getElementById('amount_tendered').value<=0){
            errors = errors + "Amount Paid cannot be less than or equal to zero\n";
            document.getElementById('amount_tendered').style.border = "solid red 1px";
        } else {
            document.getElementById('amount_tendered').style.border = "";
        }	
		
	}
	
	
	
    if (actstep == "make_payments") {
        
        if (!document.getElementById('amount_tendered').value) {
            errors = errors + "Amount Tendered must be entered\n";
            document.getElementById('amount_tendered').style.border = "solid red 1px";
            document.getElementById('amount_tendered').focus();

        }

        if (document.getElementById('payment_type_approved').value == 'Part-Payment') {


            if (document.getElementById('part_payment_amount').value > document.getElementById('amount_tendered').value) {

                errors = errors + "Amount Tendered is Less than the Approved Part-Payment Amount to Pay " + document.getElementById('part_payment_amount').value;
                document.getElementById('amount_tendered').style.border = "solid red 1px";
                document.getElementById('amount_tendered').focus();

            }


        } else {

            var amount = parseFloat(document.getElementById('total_price_cash').value).toFixed(2);
            var amount_to_pay = parseFloat(document.getElementById('amount_tendered').value);
            if (amount > amount_to_pay) {
                errors = errors + "Amount Tendered is Less than Total Amount to Pay " + amount;
                document.getElementById('amount_tendered').style.border = "solid red 1px";
                document.getElementById('amount_tendered').focus();

            }

        }
    }
	
	
	if (actstep == "passwordchange" ){
		if (!document.getElementById('oldpassword').value){
            errors = errors + "Old Password is required\n";
            document.getElementById('oldpassword').style.border = "solid red 1px";
        } else {
            document.getElementById('oldpassword').style.border = "";
        }
		
        if (!document.getElementById('newpassword').value){
            errors = errors + "New Password is required\n";
            document.getElementById('newpassword').style.border = "solid red 1px";
        } else {
            document.getElementById('newpassword').style.border = "";
        }
		
		if (!document.getElementById('cpassword').value){
            errors = errors + "Confirm New Password is required\n";
            document.getElementById('cpassword').style.border = "solid red 1px";
        } else {
            document.getElementById('cpassword').style.border = "";
        }
		
		if (document.getElementById('cpassword').value!=document.getElementById('newpassword').value){
            errors = errors + "New Password and Confirmation of New Password do not Match\n";
        }
      
        
    }
	
    if (actstep == "search_patient_policy" ){
        if (!document.getElementById('insurance_company').value){
            errors = errors + "Insurance Company is required\n";
            document.getElementById('insurance_company').style.border = "solid red 1px";
        } else {
            document.getElementById('insurance_company').style.border = "";
        }
		
		if (!document.getElementById('membership_no').value){
            errors = errors + "Membership is required\n";
            document.getElementById('membership_no').style.border = "solid red 1px";
        } else {
            document.getElementById('membership_no').style.border = "";
        }
      
        
    }
	
	
	
	if (actstep == "claimno" ){
		
		
		if(!document.getElementById('patienttype_1').checked && !document.getElementById('patienttype_2').checked){ 		
		errors = errors + "Please Select Type of Patient Visit\n";
				document.getElementById('typeofvisit').style.border = "solid red 1px";	
		}else{
		     document.getElementById('typeofvisit').style.border = "";	
		}
		
        
    }
	
	if(actstep == "submit_claimsoffice_claim_drug_claimsoffice" || actstep == "drug_edit_claim_details_claimsoffice" || actstep == "process_claim_details_claimsoffice"){
		
		
		 if (!document.getElementById('attending_officer').value){
            errors = errors + "Attending Medical Officer is required\n";
            document.getElementById('attending_officer').style.border = "solid red 1px";
        } else {
            document.getElementById('attending_officer').style.border = "";
        }
        
    }
	
	
		
     
    
    return errors;
}

function current_show() {
    $(".fakeloader").css("visibility", "visible");
}

function current_opac() {
    $(".fakeloader").css("visibility", "hidden");
}

function getstep(act, id, id2) {
    if(act == 'records_insert_patient'){
    var type_of_client = $('#type_of_client').val();var surname = $('#surname').val();var othernames = $('#othernames').val();
    var tel = $('#tel').val();var sex = $('#sex').val();
    
    if(type_of_client==''&&surname==''&&othernames==''&&tel==''&&sex==''){
        document.getElementById('type_of_client').style.border = "solid red 2px";
        document.getElementById('surname').style.border = "solid red 2px";
        document.getElementById('othernames').style.border = "solid red 2px";
        document.getElementById('tel').style.border = "solid red 2px";
        document.getElementById('sex').style.border = "solid red 2px";
        return false;
    }

    if(type_of_client==''){
        document.getElementById('type_of_client').style.border = "solid red 2px";
        return false;
    }else{
        document.getElementById('type_of_client').style.border = "1px solid #ccc";
    }
    if(surname==''){
        document.getElementById('surname').style.border = "solid red 2px";
        return false;
    }else{
        document.getElementById('surname').style.border = "1px solid #ccc";
    }
    if(othernames==''){
        document.getElementById('othernames').style.border = "solid red 2px";
        return false;
    }else{
        document.getElementById('othernames').style.border = "1px solid #ccc";
    }
    if(tel==''){
        document.getElementById('tel').style.border = "solid red 2px";
        return false;
    }else{
        document.getElementById('tel').style.border = "1px solid #ccc";
    }
    if(sex==''){
        document.getElementById('sex').style.border = "solid red 2px";
        return false;
    }else{
        document.getElementById('sex').style.border = "1px solid #ccc";
    }
}
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&id=" + id + "&idd2=" + id2,
        success: function (msg) {
            $("#currentarea").html(msg);
            current_opac();
            if (act == 'records_guest_insert_patient' || act == 'records_edit_patient' || act == 'records_insert_patient' || act == 'records_normal_edit_patient') {
                Materialize.toast('Success! Patient Information Saved.', 4000, 'success');
            }
        }
    });
}

function getProcess(act, div, id, id2) {
  if(act == 'patientvisitno'){
    var attending_officer = $('#attending_officer').val();
    var service_category = $('#service_category').val();
    if(attending_officer==''){
        swal("Sorry...", "Please fill in Attending Officer", "error");
        document.getElementById('attending_officer').style.border = "solid red 2px";
        return false;
    }
    if(service_category==''){
        swal("Sorry...", "Please fill in Service Category", "error");
        document.getElementById('service_category').style.border = "solid red 2px";
        return false;
    }
  }
    if(id2 !== 'no_id'){
    $('.patient-sub-menu').removeClass('active');
    $('#'+id2).addClass('active');
    }
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&id=" + id,
        success: function (msg) {
            $(div).html(msg);
            current_opac();
        }
    });

}

function saveInformation(act, div, id) {
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form#edit_patient_info_form').serialize() + "&act=" + act + "&id=" + id,
        success: function (msg) {
            $("html, body").animate({scrollTop: 0}, "fast");
            $(div).html(msg);
            current_opac();
            if (act == 'records_guest_insert_patient' || act == 'records_edit_patient' || act == 'records_insert_patient' || act == 'records_normal_edit_patient') {
                Materialize.toast('Success! Patient Information Saved.', 4000, 'success');
            }
        }
    });
}

function saveInformation2(act, id, form, div) {
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $(form).serialize() + "&act=" + act + "&id=" + id,
        success: function (msg) {
            $('.close_page_refresh').trigger('click');
            if(act == 'edit_supplier_details'){
                 $(div).html(msg);
            } else if(act == 'save_lens_pick_up'){
                $('#patient_follow_up').trigger('click');
            } else{
            var resp = msg.split("@@@");
            $(div).html(resp[2]);
            $("html, body").animate({scrollTop: 0}, "fast");
            Materialize.toast(resp[0], 4000, resp[1]);
        }
        current_opac();
        }
    });
}

function MainsearchItemsName(act, div, id) {
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&item_search=" + id,
        success: function (msg) {
            $(div).html(msg);
            current_opac();
        }
    });
}

function searchItemsName(act, div, id, field, value) {
    if (field == 'no_field') {
        $('#plus_' + id).hide();
        $('#spin_refresh_plus_' + id).show();
    } else {
        $('#trash_' + id).hide();
        $('#spin_refresh_' + id).show();
    }
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&id=" + id + "&field=" + field + "&value=" + value,
        success: function (msg) {
            var resp = msg.split("@@@");
            if(resp[0] == 'top_up'){
              confirmTopUp(act, div, id, "Please Note?", "A Cash Top Up of GHS"+ parseFloat(resp[1]).toFixed(2) +" will be applied since insurance does not cover the whole amount.", field, value);  
            }else{
            Materialize.toast(resp[1], 4000, resp[0]);
            $(div).html(resp[2]);
        }
        $('#close_modal_id').trigger('click');
            if (field == 'no_field') {
                $('#plus_' + id).show();
                $('#spin_refresh_plus_' + id).hide();
            } else {
                $('#trash_' + id).show();
                $('#spin_refresh_' + id).hide();
            }
        }
    });
}

function searchItemsName2(act, div, id, field, value, top_up) {
    if (field == 'no_field') {
        $('#plus_' + id).hide();
        $('#spin_refresh_plus_' + id).show();
    } else {
        $('#trash_' + id).hide();
        $('#spin_refresh_' + id).show();
    }
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&id=" + id + "&field=" + field + "&value=" + value + "&top_up=" + top_up,
        success: function (msg) {
            var resp = msg.split("@@@");
            Materialize.toast(resp[1], 4000, resp[0]);
            $(div).html(resp[2]);
            if (field == 'no_field') {
                $('#plus_' + id).show();
                $('#spin_refresh_plus_' + id).hide();
            } else {
                $('#trash_' + id).show();
                $('#spin_refresh_' + id).hide();
            }
        }
    });
}

function confirmTopUp(act, div, id, title, info, field, value) {
    swal({
        title: title,
        text: info,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#DD6B55',
        confirmButtonText: 'Yes, Apply Top Up!',
        cancelButtonText: "No, Cancel!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                   searchItemsName2(act, div, id, field, value, 'yes');
                }
            });
}

function delInformtion(act, div, id, title, info, display_info) {
    swal({
        title: title,
        text: info,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#DD6B55',
        confirmButtonText: 'Yes, Delete!',
        cancelButtonText: "No, Don't Delete!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                    $('#trash_' + id).hide();
                    $('#spin_refresh_' + id).show();
                    $.ajax({
                        type: "POST",
                        url: "getstep.php",
                        data: $('form').serialize() + "&act=" + act + "&id=" + id,
                        success: function (msg) {
                            Materialize.toast(display_info, 4000, 'success');
                            $(div).html(msg);
                        }
                    });
                }
            });
}

function getpage(actstep, pagenum, totalrows, id, typesearch, searchtxt) {
    current_show();
    $.ajax({
        type: "POST",
        url: "getstep.php",
        data: $('form').serialize() + "&act=" + actstep + "&page_num=" + pagenum + "&totalrows=" + totalrows + "&typesearch=" + typesearch + "&searchtext=" + searchtxt + "&id=" + id,
        success: function (msg) {
            $('#currentarea').html(msg);
            current_opac();
        }
    });
}	

function showtext(str)
{
	if(str == "cash")
	{
	document.getElementById('cashbox').style.display = "block";
	document.getElementById('staff').style.display = "none";
	document.getElementById('insurance').style.display = "none";
	document.getElementById('company').style.display = "none";
	}
	else if(str=="staff")
	{
	document.getElementById('cashbox').style.display = "none";
	document.getElementById('staff').style.display = "block";
	document.getElementById('insurance').style.display = "none";
	document.getElementById('company').style.display = "none";
	}
	else if (str=="insurance")
	{
	document.getElementById('cashbox').style.display = "none";
	document.getElementById('staff').style.display = "none";
	document.getElementById('insurance').style.display = "block";
	document.getElementById('company').style.display = "none";
	}
	else if(str=="company")
	{
	document.getElementById('cashbox').style.display = "none";
	document.getElementById('staff').style.display = "none";
	document.getElementById('insurance').style.display = "none";
	document.getElementById('company').style.display = "block";
	}
}

function showtext2(str)
{
	if(str == "cash")
	{
	// document.getElementById('cashbox').style.display = "block";
	// document.getElementById('staff').style.display = "none";
	document.getElementById('insurance').style.display = "none";
	document.getElementById('company').style.display = "none";
	}
	else if(str=="staff")
	{
	// document.getElementById('cashbox').style.display = "none";
	// document.getElementById('staff').style.display = "block";
	document.getElementById('insurance').style.display = "none";
	document.getElementById('company').style.display = "none";
	}
	else if (str=="insurance")
	{
	// document.getElementById('cashbox').style.display = "none";
	// document.getElementById('staff').style.display = "none";
	document.getElementById('insurance').style.display = "block";
	document.getElementById('company').style.display = "none";
	}
	else if(str=="company")
	{
	// document.getElementById('cashbox').style.display = "none";
	// document.getElementById('staff').style.display = "none";
	document.getElementById('insurance').style.display = "none";
	document.getElementById('company').style.display = "block";
	}
}

function process_information(actstep, id, no, div, idd) {
    current_show();
    $.ajax({
        type: "POST",
        url: "getstep.php",
        data: $('form').serialize() + "&act=" + actstep + "&id=" + id + "&no=" + no + "&medical_note_id=" + idd,
        success: function(msg) {
            $('#'+div).html(msg);
             current_opac();
        }
    });
}

function save_consultation(actstep, id, no, div, idd) {
    current_show();
    $.ajax({
        type: "POST",
        url: "getstep.php",
        data: $('form').serialize() + "&act=" + actstep + "&id=" + id + "&no=" + no + "&medical_note_id=" + idd,
        success: function(msg) {
            if(actstep == 'save_patient_prescription'){
                $('#refresh_tn_lens_presc').trigger('click');
            }
            $('#'+div).html(msg);
             current_opac();
             swal("Successful", "Patient Data Saved Successfully", "success");
        }
    });
}


function patient_menu_info(actstep,id,id2) {
    if(actstep == 'add_new_medical_history'){ $('#medical_note_id').val(0);}
        current_show();	
        $.ajax({
            type: "POST",
	    url: "getstep.php",
            data: $('form').serialize()+"&act="+actstep+"&id="+id+"&id2="+id2,
            success: function(msg){
                document.getElementById('patient_sub_page').innerHTML=msg;
                current_opac();
            }
        });
}

function patient_menu_info_2(actstep,id,id2) {
    $('#medical_note_id').val(0);
        current_show();	
        $.ajax({
            type: "POST",
	    url: "getstep.php",
            data: $('form').serialize()+"&act="+actstep+"&id="+id+"&id2="+id2,
            success: function(msg){
                document.getElementById('patient_sub_page').innerHTML=msg;
                current_opac();
            }
        });
}

function process_confirmation_diagnosis(actstep, id) {
    $.ajax({
        type: "POST",
        url: "getstep.php",
        data: $('form').serialize() + "&act=" + actstep + "&id=" + id,
        success: function(msg) {
            if(msg == 'confirmed'){
                $('#status_'+id).show();
            }else{
                 $('#status_'+id).hide(); 
            }
        }
    });
}

 function UploadPatientFiles(i) {
    $("#loading_file_" + i).html('');
    $("#loading_file_" + i).html('<b style="color:green;font-size:12px">Loading File.Please Wait...</b>');
    $("#document_form_"+i).ajaxForm({
        target: '#file_attachment_wrapper_' + i
    }).submit();
}

function AddNewRow(actstep, div, i,data) {
    var total_entry = $("#total_entry").val();
    total_entry = parseFloat(total_entry);
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: "total_entry=" + total_entry+"&act="+actstep+"&data="+data,
        success: function(msg) {
            $('#' + div + i).after(msg);
            current_opac();
            $("#total_entry").val(total_entry + 1);
        }
    });
}

function RemoveNewRow(div,i){
  $("#"+div+i).remove();
}

function DeleteFileAttachment(act, div, i, id) {
    swal({
        title: "Delete File Attachment?",
        text: "You are about to Delete A Patient's File Attachment. Deleted File cannot be Recovered.",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#3cc051',
        confirmButtonText: 'Yes, Delete File!',
        cancelButtonText: "No, cancel!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
    function(isConfirm) {
        if (isConfirm) {
            $.ajax({
                type: "POST",
                url: 'getstep.php',
                data: "id=" + id + "&act=" + act,
                success: function() {
                    current_opac();
                    $("#" + div + i).remove();
                }
            });
        }
    });
}

function movePatientProfile() {
    $("#second_profile_pic").animate({left: '+=250', top: '+=150'}, 100, function () {
        $('#second_profile_pic').hide();
        $('#second_profile_pic').css({left: '40px', top: '0px'});
        $('#patient_profile_sidebar').show();
    });
}

function animationMethod(animationName, div, div2){
    $(div2).hide();
    var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
    $(div).addClass('animated ' + animationName).one(animationEnd, function () {
    $(div).removeClass('animated ' + animationName);
    });
}

function getMedicalHistoryDetails(actstep, id, id2) {	
    current_show();
    $("#success_message").show();
    $.ajax({
        type: "POST",
        url: "getstep.php",
        data: $('form').serialize() + "&act=" + actstep + "&id=" + id + "&id2=" + id2,
        success: function(msg) {
            $("#details_div_wrapper").html(msg);
            current_opac();
            $("#success_message").hide();
        }
    });	
}

function getForwardPatient(act, div, id, title, text) {
    swal({
        title: title,
        text: text,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#3cc051',
        confirmButtonText: 'Yes!',
        cancelButtonText: "No, cancel!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                    current_show();
                    $.ajax({
                        type: "POST",
                        url: 'getstep.php',
                        data: $('form').serialize() +"&id=" + id + "&act=" + act,
                        success: function (msg) {
                            current_opac();
                            var resp = msg.split("@@@");
                            Materialize.toast(resp[1], 4000, resp[0]);
                            $(div).html(resp[2]);
                        }
                    });
                }
            });
}
function issueCashierPayments(act, div, id, title, text, act2, patient_no, patient_id, typeofvisit) {
    swal({
        title: title,
        text: text,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#3cc051',
        confirmButtonText: 'Yes!',
        cancelButtonText: "No, cancel!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                    $.ajax({
                        type: "POST",
                        url: 'getstep.php',
                        data: "id=" + id + "&act=" + act,
                        success: function () {
                            current_opac();
                            getstep(act2, patient_no+'@@@'+patient_id+'@@@'+id+'@@@', typeofvisit);
                        }
                    });
                }
            });
}

function approveGratis(act, id, title, text, head, value, i) {
    var text2 = $('#discount_btn').text();
    if(text2 == 'Apply Discount Now'){
        title = 'Apply Discount Now?';
        text = 'Are you sure you want to Apply Discount for this Client.';
        head = 'Yes, Apply Discount';
        value = 'apply';
    }
    swal({
        title: title,
        text: text,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#3cc051',
        confirmButtonText: head,
        cancelButtonText: "No, cancel!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                    // $('#hide_discount_btn').hide();
                    $.ajax({
                        type: "POST",
                        url: 'getstep.php',
                        data: $('form').serialize() + "&id=" + id + "&act=" + act + "&value=" + value+ "&i=" + i,
                        success: function (msg) {
                            current_opac();
                            var resp = msg.split("@@@");
                            Materialize.toast(resp[1], 4000, resp[0]);
                            $('#status_approve_' + id).show();
                            $('#status_' + id).hide();
                            if(value == 'Remove'){
                            $('#status_tr_' + id).remove();
                           }
                        }
                    });
                }
            });
}

function getclaimsdetails(actstep, idd) {
    var update = "claims_" + idd;
    var updatedetails = "claimsdetails_" + idd;
    var icondetails = "icon_" + idd;
    var data = $('form').serialize();

    $("#" + update).toggle();
    $("#" + icondetails).toggleClass("fa fa-plus fa fa-minus");
    document.getElementById(updatedetails).innerHTML = "Processing Please Wait...";
    $.ajax({
        type: "POST",
        url: "getstep.php",
        data: data + "&act=" + actstep + "&id=" + idd,
        success: function (msg) {
            str = msg;
            document.getElementById(updatedetails).innerHTML = msg;
            current_opac();
        }
    });

}

function getdisplay(div,no,total){
	for (var i = 1; i <= total; i++) {
		if(i<=no){
		document.getElementById(div+i).style.display="";
		}else{
			document.getElementById(div+i).style.display="none";
			}
	}
}

function receiveSupplyQuantity(act, div, id, head_title, title, info, form) {
    var bill_date = $("#bill_date").val();
    var bill_ref = $("#bill_ref").val();
    var received_date = $("#received_date").val();
    if(bill_date != "" && bill_ref != '' && received_date !=''){
    swal({
        title: title,
        text: info,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#3cc051',
        confirmButtonText: head_title,
        cancelButtonText: "No, Cancel!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                        saveInformation2(act, id, form, div);
                }
            });
        }else{
            Materialize.toast("Red fields cannot be empty.", 4000, 'error');
            document.getElementById('bill_date').style.border = "solid red 2px";
            document.getElementById('bill_ref').style.border = "solid red 2px";
            document.getElementById('received_date').style.border = "solid red 2px";
        }
}

function showpayment(str)
{
    $('.hide_all_payment').hide();
    if (str == "cash")
    {
        $('.creditcardbox').hide();
        $('.chequebox').hide();
        $('#amount_tendered').focus();
    } else if (str == "cheque")
    {
        $('.creditcardbox').hide();
        $('.chequebox').show();
        $('#bank').focus();
    } else if (str == "creditcard")
    {
        $('.creditcardbox').show();
        $('.chequebox').hide();
        $('#cardname').focus();
    } else if (str == "Mobile Money")
    {
        $('.mobilephonebox').show();
        $('#mobile_phone_no').focus();
    }
}


function getitempayment(actstep, viewresponse, idd, itemqtyid) {
    var paymentdetails = $('form').serialize();
    errormap(actstep);
    if ((errors == "<br>") || (!errors)) {
        document.getElementById(viewresponse).innerHTML = "Processing Please Wait";
        $.ajax({
            type: "POST",
            url: "getstep.php",
            data: paymentdetails + "&act=" + actstep + "&id=" + idd + "&itemqty=" + itemqtyid,
            success: function (msg) {
                str = msg;
                document.getElementById(viewresponse).innerHTML = msg;
            }
        });
    } else
    {
        errors = 'Please Correct the following errors\n ------------------------------------------\n' + errors
        alert(errors);
        errors = null;
    }
}


function getbalance(div1, div2, div4, amt, div5) {
    var change = amt - document.getElementById(div2).value;
    if (change >= 0) {
        document.getElementById(div1).innerHTML = parseFloat(change).toFixed(2);
        document.getElementById(div5).value = change;
        document.getElementById(div4).value = 0;
    } else {
        document.getElementById(div1).innerHTML = "";
        document.getElementById(div5).value = 0;
        document.getElementById(div4).value = change;
    }
}

function getcashierprint(num,str,visit) {
    current_show();
    window.open('cashier/print_receipt.php?'+$('form').serialize()+"&receipt="+str+"&num="+num+"&visit="+visit, '_blank', 'toolbar=0,resizable=1,scrollbars=1,menubar=1,width=' + screen.width + ', height=' + screen.height);
    current_opac();
}

function getreceiptpayment(num,visit) {
    current_show();
    window.open('procurements/print_receipt.php?'+$('form').serialize()+"&num="+num+"&visit="+visit, '_blank', 'toolbar=0,resizable=1,scrollbars=1,menubar=1,width=' + screen.width + ', height=' + screen.height);
    current_opac();
}

function getprintPrescription(num,str,visit) {
    current_show();
    window.open('administrative/print_prescription.php?'+$('form').serialize()+"&receipt="+str+"&num="+num+"&visit="+visit, '_blank', 'toolbar=0,resizable=1,scrollbars=1,menubar=1,width=' + screen.width + ', height=' + screen.height);
    current_opac();
}

//function getcashierprint(num,str,visit) {
//    var poststr = "&act=cashier_print";
//    current_show();
//    window.open('cashier/print_receipt.php?'+$('form').serialize()+poststr+"&receipt="+str+"&num="+num+"&visit="+visit, '_blank', 'toolbar=0,resizable=1,scrollbars=1,menubar=1,width=' + screen.width + ', height=' + screen.height);
//    current_opac();
//}

function auditStatusChange(id, no, type) {
    $('select#branch_id_'+no+' option:selected').attr("selected",null);
    if (type == 'lab') {
        if (id == 'Rejected') {
            $('.audit_location_options_' + no).show();
            $('select#branch_id_'+no+' option[value="Procurement"]').attr("selected","selected");
            $('#lab_' + no).hide();
        } else if (id == 'Job Completed') {
            $('.audit_location_options_' + no).show();
            $('select#branch_id_'+no+' option[value="Procurement"]').attr("selected","selected");
            $('#lab_' + no).hide();
        } else {
            $('.audit_location_options_' + no).hide();
            $('select#branch_id_'+no+' option[value="Lab"]').attr("selected","selected");
             $('#lab_' + no).show();
        }
    } else if (type == 'procurement') {
        if (id == 'Rejected' || id == 'Sent To Lab') {
//            $('.audit_location_options_' + no).show();
            $('select#branch_id_' + no + ' option[value="Lab"]').attr("selected", "selected");
            $('#procurement_' + no).hide();
            $('#lab_' + no).show();
        } else if (id == 'Sent To Branch') {
            $('#procurement_' + no).hide();
            $('#lab_' + no).hide();
            $('.all_branches_' + no).show();
             $('select.all_branches_' + no + ' option[0]').attr("selected", "selected");
        } else {
            $('.audit_location_options_' + no).hide();
            $('select#branch_id_' + no + ' option[value="Procurement"]').attr("selected", "selected");
            $('#procurement_' + no).show();
            $('#lab_' + no).hide();
        }
    }
}

function getData(act, id, div) {
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&id=" + id,
        success: function (msg) {
            $(div).html(msg);
            $('#refresh_btn').trigger('click');
            $('#close_modal_btn').trigger('click');
            current_opac();
        }
    });
}

function getValue(id, div) {
    var text = '';
    var amount = parseFloat(id);
    if (amount > 10) {
        text = 'Forward for Approval';
    } else {
        text = 'Apply Discount Now';
    }
    $(div).text(text);
}

function checkBoxes(){
    if($('#parent_box').prop('checked')===true){
        $('.item_check_box').prop('checked', true);
    }else{
        $('.item_check_box').prop('checked', false);
    }
}

function checkBoxes2(){
    if($('#parent_box').prop('checked')===true){
        $('.item_check_box_2').prop('checked', true);
    }else{
        $('.item_check_box_2').prop('checked', false);
    }
}

function stockReimbursement(act,form,id,title,div, info, btn_title,form) {
    swal({
        title: title,
        text: info,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#3cc051',
        confirmButtonText: btn_title,
        cancelButtonText: "No, Cancel!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                    current_show();
                    $.ajax({
                        type: "POST",
                        url: 'getstep.php',
                        data: $(form).serialize() + "&act=" + act + "&id=" + id,
                        success: function (msg) {
                                var resp = msg.split("@@@");
                                $(div).html(resp[2]);
                                $("html, body").animate({scrollTop: 0}, "fast");
                                Materialize.toast(resp[0], 4000, resp[1]);
                            current_opac();
                        }
                    });
                }
            });
}

function lensPrescriptions(value) {
    $('#lens_description_wrapper').html(value);
}

function displayLensPrescription(){
        var sel = $('input[type=checkbox].addition_lens:checked').map(function(_, el) {
            return $(el).val()+',';
        }).get();
        $('#lens_description_wrapper2').html(sel);
}

function SMSCounter(chars) {
    var $remaining = $('#remaining'),
    $nosms = $('#nosms'),
    $messages = $('#messages');
    var messages = Math.ceil(chars / 160),
            remaining = messages * 160 - (chars % (messages * 160) || messages * 160);
    if (chars == 0) {
        $remaining.text('160 characters remaining');
        $messages.text('1 message(s)');
        $nosms.val(1);
    } else {
        $remaining.text(remaining + ' characters remaining');
        $messages.text(messages + ' message(s)');
        $nosms.val(messages);
    }
}

function Apply_od_os() {
    var od_sphere = $('#od_sphere').val();
    var od_cylinder = $('#od_cylinder').val();
    var od_axis = $('#od_axis').val();
    var od_add = $('#od_add').val();
    var od_pd = $('#od_pd').val();

    if ($('#apply_od_os').prop('checked') === true) {
        $('#os_sphere').val(od_sphere);
        $('#os_cylinder').val(od_cylinder);
        $('#os_axis').val(od_axis);
        $('#os_add').val(od_add);
        $('#os_pd').val(od_pd);
    } else {
        $('#os_sphere').val('');
        $('#os_cylinder').val('');
        $('#os_axis').val('');
        $('#os_add').val('');
        $('#os_pd').val('');
    }
}

function exportReOrderItems(url){
    location.href = url;
    return false;  
}

function PushPullData(act, id) {
    $(id).removeClass('fa fa-arrow-up');
    $(id).addClass('fa fa-refresh fa-spin fa-fw');
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: "act=" + act,
        success: function (msg) {
            var resp = msg.split("@@@");
            Materialize.toast(resp[0], 4000, resp[1]);
            $(id).removeClass('fa fa-refresh fa-spin fa-fw');
            $(id).addClass('fa fa-arrow-up');
        }
    });
}

function printReport(url) {
    window.open(url+'?'+$('form').serialize(), '_blank', 'toolbar=0,resizable=1,scrollbars=1,menubar=1,width=' + screen.width + ', height=' + screen.height);
}

function printReport2(url,id) {
    window.open(url+'?'+"id=" + id, '_blank', 'toolbar=0,resizable=1,scrollbars=1,menubar=1,width=' + screen.width + ', height=' + screen.height);
}

function BoxesforSwapCancel() {
    var i = $(".swap_cancel_items input[name='item_ids_[]']:checked").length;
    if (i > 0) {
        $('#swap_cancel_item_wrapper').show();
    } else {
        $('#swap_cancel_item_wrapper').hide();
    }
}

function SwapCancelItem(act,form,id,title, info, btn_title) {
    swal({
        title: title,
        text: info,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#3cc051',
        confirmButtonText: btn_title,
        cancelButtonText: "No, Cancel!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                    current_show();
                    $.ajax({
                        type: "POST",
                        url: 'getstep.php',
                        data: $(form).serialize() + "&act=" + act + "&id=" + id,
                        success: function (msg) {
                                var resp = msg.split("@@@");
                                $("html, body").animate({scrollTop: 0}, "fast");
                                Materialize.toast(resp[0], 4000, resp[1]);
                            current_opac();
                        }
                    });
                }
            });
}

function generateLensPO(act,id,title, info, btn_title) {
    var sel = $('input[type=checkbox].item_check_box:checked').length;
    if(sel == 0){
        swal("Sorry...", "Please check a Lens before generating Purchase Order", "error");
    }else{
    swal({
        title: title,
        text: info,
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#3cc051',
        confirmButtonText: btn_title,
        cancelButtonText: "No, Cancel!",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                    getData(act, '0', '');
                }
            });
        }
}

function processInfo(act, id, form, div) {
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&id=" + id,
        success: function (msg) {
            $('#close_modal_id').trigger('click');
            var resp = msg.split("@@@");
            $(div).html(resp[2]);
            Materialize.toast(resp[0], 4000, resp[1]);
        current_opac();
        }
    });
}

function getProcessInfo(actstep, form, id, div) {
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $(form).serialize() + "&act=" + actstep + "&id=" + id,
        success: function (msg) {
            current_opac();
            var resp = msg.split("@@@");
            Materialize.toast(resp[1], 4000, resp[0]);
            $(div).html(resp[2]);
            $('close_modal_now').trigger('click');
        }
    });
}

function rxVersionControl(actstep, div) {
    if (actstep == 'rxVersionUpdate') {
        $('#install_btn').html('Installing Update...Please Wait');
    }
    $.ajax({
        type: "POST",
        url: "getstep.php",
        data: "act=" + actstep,
        success: function (msg) {
            if (msg !== '') {
                $('#' + div).html(msg);
                $('#version_update').modal('show');
                if (actstep == 'rxVersionUpdate') {
                    $('#install_btn').html('Installation Completed');
                }
            }
        }
    });
}

function Patient_Status(value){
    $('.hide_all_status').hide();
    if(value === 'discharged_review'){
        $('#date_of_review_div').show();
//         $('#date_of_review_death').val('').attr('placeholder','Enter Date for Review').show();
//         $('#date_of_review_death_div').removeClass('col-md-6').addClass('col-md-12');
//         $('#time_of_review_death').hide();
    }else if(value === 'pending_observation'){
        $('#reason_for_detention_div').show();
    }
}

function view_calendar(id){
    var url = "index.php?" + "calendar="+id;
    location.href = url;    
    }

    function ShowEventDiv(id,div,type) {
        $.ajax({
            type: "POST",
            url: "scheduler/process_calendar.php",
            data: "id=" + id + "&type=" + type,
            success: function(msg) {
                $("#" + div).html(msg);
                $('#pop_up_modal').modal('show');
                // $("#pop_up_modal").show();
                // $("#pop_up_modal").animate({"right": "0px"});
            }
        });
    }
    
    function HideEventDiv() {
        $("#pop_up_modal").animate({"right": "-400px"}, function() {
        $("#pop_up_modal").hide();
        });
    }

    function event_headings(value){
        $('.hide_all').hide();
        var title = value.split("@@@");
        $('#event_headings').html(title[0]);
        if(title[1] == 'normal'){
            $('#event_title_wrapper').show();
            $('.repeat_event_wrapper').show();
            if($("#repeat_event").prop("checked") == true){
            $('.repeat_event_wrapper_2').show();
            }
        }else{
           $('.patient_wrapper').show(); 
           $('.repeat_event_wrapper').hide(); 
           $('.repeat_event_wrapper_2').hide(); 
        }
    }

    function process_information_2(url, actstep, div, id) {
        $.ajax({
            type: "POST",
            url: url,
            data: $('form').serialize() + "&act=" + actstep + "&id=" + id,
            success: function(msg) {
                $('#search_result_wrapper').show();
                $('#' + div).html(msg);
                var delayme = 50;
                for (var i = 1; i <= 100; i++) {
                    $('#patient_details_' + i).delay(delayme).animate({'top': '0px'});
                    delayme += 50;
                }
            }
        });
    }

    function selectPatientAppointment(id){
        // $('.todo-tasklist-item').live('click', function() {
        $('.todo-tasklist-item').css({"background-color": "#edf7f9", "color": "#000000"});
        $('.icon-ok').hide();
        $('#tasklist_'+id).css({"background-color": "#8ce196", "color": "#FFFFFF"});
        $('#tasklist_'+id).find('.icon-ok').show();
        var patient_id = $('#tasklist_'+id).find('.todo-tasklist-item-title').attr('id');
        $('#patient_id_receiver').val(patient_id);
        var info = patient_id.split('@@@');
        $('#description').val('Appointment with '+ info[2]+ ' with Patient No:'+ info[1] +'');
    // });
    }

    function Repeat_Interval(value) {
        var text = '';
        if (value != '1') {
            if(value == '0'){ text = 'Days';$('#repeat_frequency_text').val('Days');}
            if(value == '2'){
                $('#repeat_on_weekly').show();
                text = 'Weeks';$('#repeat_frequency_text').val('Weeks');
            }else{$('#repeat_on_weekly').hide();}
            if(value == '3'){ text = 'Months';$('#repeat_frequency_text').val('Months');}
            if(value == '4'){ text = 'Years';$('#repeat_frequency_text').val('Years');}
            $('#label_every_repeat').html(text);
        } else {
            $('#repeat_frequency_text').val('Every Weekday');
        } 
    }
    
    function Summary() {
        var number = $('#repeat_frequency').val();
        var repeat_interval = $('#repeat_interval').val();
        var text = $('#repeat_frequency_text').val();
        var summary = '';
        var summary2 = '';
        var date = $('#schedule_start_date').val().split("-");
        var monDate = $.datepicker.formatDate("DD, MM d, yy", new Date($('#schedule_start_date').val())).split(",");
    
        if (repeat_interval == '2') {
            var sel = $('input[type=checkbox].repeat_on:checked').map(function(_, el) {
                return $(el).val();
            }).get();
            summary2 = 'On ' + sel;
        } else if (repeat_interval == '3' && number != '1' && $('#schedule_start_date').val() != '') {
            summary2 = 'On Day ' + date[2];
        } else if(repeat_interval == '4' && number != '1' && $('#schedule_start_date').val() != ''){
            summary2 = 'On ' + monDate[1]; 
        } else {
            summary2 = '';
        }
    
        if (number == '1' && repeat_interval == '0') {
            summary = 'Daily';
        } else if (number == '1' && repeat_interval == '2') {
            summary = 'Weekly';
        } else if (number == '1' && repeat_interval == '3') {
            summary = 'Monthly';
        } else if (number == '1' && repeat_interval == '4') {
            summary = 'Yearly';
        } else if (number != '1') {
            summary = 'Every ' + number + ' ' + text;
        }
    
        $('#summary_wrapper').html(summary + ' ' + summary2);
    }
    
    function CheckCurrentDay() {
        var formattedDate = $.datepicker.formatDate("DD, d MM, yy", new Date($('#schedule_start_date').val()));
        var day = formattedDate.split(',');
        $('.repeat_on').prop('checked', false);
        $('.repeat_on').each(function() {
            if ($(this).val() == day[0]) {
                $(this).prop('checked', true);
                Summary();
            }
        });  
    }

    function getItemDetails(id,item,price,service_type){
            $('#top_up_amount').val('');
            $('#cash_top_up_title').html(item+ ' - Cash Top Up');
            if(service_type == 'Optical Lens'){
                $('#item_original_price').prop("readonly", false).val(price);
            }else{
                $('#item_original_price').prop("readonly", true).val(price);
            }
            $('#item_id_cash_top_up').val(id);
    }

    function processAPImemberStatus(actstep,id){
        current_show();
        $.ajax({
            type: "POST",
            url: 'api_integration.php',
            data: $('form').serialize() + "&act=" + actstep,
            success: function(response) {
                current_opac();
                $('#'+id).hide();
                if(response == '1'){
                    $('#'+id).show();
                    $('#success_via_api').show().html("Member Active for Service");
                    $('#error_via_api').hide();
                }else{
                    $('#error_via_api').show().html(response);
                    $('#success_via_api').hide();
                }
            }
        });
    }

    function BoxesforJobNumber() {
        var i = $(".item_check_box_job_no input[name='item_trans_amount[]']:checked").length;
        if (i > 0) {
            $('#generate_job_no_item_wrapper').show();
        } else {
            $('#generate_job_no_item_wrapper').hide();
        }
    }

    function valueChanged(idd,id)
{
    if($(idd).is(":checked")){   
        $(".main_job_number_"+id).animate({"background-color":"#8ce196"});
    }else{
       $(".main_job_number_"+id).animate({"background-color":"#FFF"});
   }
}

function getSimpleData(act, id, div) {
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&id=" + id,
        success: function (msg) {
            $(div).html(msg);
            current_opac();
        }
    });
}

function calculateLensPrice(act, id, id2, div){
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&id=" + id + "&id2=" + id2,
        success: function (msg) {
            $(div).html(msg);
            current_opac();
        }
    });
}

function calculateCashTop(value2, value){
    var amount = parseFloat(value2).toFixed(2);
    var amount2 = parseFloat(value).toFixed(2);
    var remainder = amount - amount2;
    $('#main_lens_price').val(remainder);
}

function changePassword(act,id,div){
    current_show();
    $.ajax({
        type: "POST",
        url: 'getstep.php',
        data: $('form').serialize() + "&act=" + act + "&id=" + id,
        success: function (msg) {
            $(div).html(msg);
            current_opac();
        }
    });
}

