$(document).ready(function () {
    var imgFile = {};
    var docFile = {};
    var zipFile = {};
    doAjaxCompany();
    $('#customer_id').keypress(function () {
        $('#customer_id').css('text-transform', 'uppercase');
    });


    //text editor

    $('#modal').html("<form><textarea id=foo name=DSC'></textarea></form>");

    $('#modal').hide();
    $('textarea#foo').ckeditor({
        height: "300px",
        toolbarStartupExpanded: true,
        width: "100%"
    });

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

    window.setTimeout(function () {
        $('#modal').show();
    }, 3000);


    $('.save_text_editor').click(function (e) {
        e.preventDefault();
        $('#loading').modal({show: true, backdrop: 'static', keyboard: false});
        var editorText = CKEDITOR.instances.foo.getData();
        var title = $('#title').val();
        var set_id = $('#set_id').val();

        if (title == '') {
            swal({
                title: "Whoops!",
                text: "Enter Title",
                type: "warning",
                showCancelButton: false,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: 'Ok',
                cancelButtonText: "No, cancel it!",
                closeOnConfirm: false,
                closeOnCancel: false
            })
            $('#loading').modal('hide');
        } else {
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                dataType: 'json',
                url: '/save-text-editor',
                data: {
                    content: editorText, title: title, 'set_id': set_id
                },
                success: function (responce) {
                    $('#loading').modal('hide');
                    var err_message = responce.err_message;
                    var success_message = responce.success;
                    if (err_message) {
                        //$('.error_div').css('display', 'block').fadeOut(4000);
                        //$('.err_msg').text(err_message);
                        swal({
                            title: "Whoops!",
                            text: err_message,
                            type: "error",
                            showCancelButton: false,
                            confirmButtonClass: 'btn-danger',
                            confirmButtonText: 'Ok',
                            cancelButtonText: "No, cancel it!",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        })
                    } else if (success_message) {
                        swal({
                            title: "Success!",
                            text: success_message,
                            type: "success",
                            showCancelButton: false,
                            confirmButtonClass: 'btn-danger',
                            confirmButtonText: 'Ok',
                            cancelButtonText: "No, cancel it!",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        }, function (isConfirm) {
                            if (isConfirm) {
                                var delay = 300;
                                setTimeout(function () {
                                    location.reload();
                                }, delay);
                            }
                        });


                    }
                },

            });
        }
        //alert(" your data is :"+editorText);


        // send your ajax request with value
        // profit!
    });

    $('#title_filter').change(function (e) {
        e.preventDefault();
        $('#loading').modal({show: true, backdrop: 'static', keyboard: false});
        var title_filter = $('#title_filter').val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'GET',
            dataType: 'json',
            url: '/get-filter-title-content/' + title_filter,
            success: function (responce) {
                $('#loading').modal('hide');
                var title = responce.title;
                var id = responce.id;
                var content = responce.content;
                $('#title').val(title);
                $('#set_id').val(id);
                CKEDITOR.instances.foo.setData(content);
            }

        })
    });


    var regular_expression = /^(([^<>()\[\]\\.,;:\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,}))$/;
    $('.customer_create').click(function (e) {
        e.preventDefault();
        $('#loading').modal({show: true, backdrop: 'static', keyboard: false});
        created_fields();
    });

    function created_fields() {
        var name = $('#cus_name').val();
        var cus_company = $('#cus_company').val();
        var customer_id = $('#customer_id').val();
        var cus_address = $('#cus_address').val();
        var cus_mobile = $('#cus_mobile').val();
        var cus_email = $('#cus_email').val();
        var cus_category = $('#cus_category').val();
        var cus_referred_by = $('#cus_referred_by').val();
        var gender = ($("input[type='radio']:checked").val());

        var mob = /^[1-9]{1}[0-9]{9}$/;
        if (name == '') {
            $('#loading').modal('hide');
            $('.err_name').text('Enter Name');
            $('#cus_name').focus();
            return false;
        } else if (customer_id == '') {
            $('#loading').modal('hide');
            $('.err_customer_id').text('Enter Customer id');
            $('#customer_id').focus();
            return false;
        } else if (cus_mobile == '') {
            $('#loading').modal('hide');
            $('.err_mobile').text('Enter Mobile');
            $('#cus_mobile').focus();
            return false
        } else if (mob.test(cus_mobile) == false) {
            $('#loading').modal('hide');
            $('.err_mobile').text('Please enter valid mobile number');
            $('#cus_mobile').focus();
            return false;
        } else if (cus_email == '') {
            $('#loading').modal('hide');
            $('.err_email').text('Enter email');
            $('#cus_email').focus();
            return false
        } else if (!regular_expression.test(cus_email)) {
            $('#loading').modal('hide');
            $('.err_email').text('Invalid Email');
            $('#cus_email').focus();
            return false;
        } else {
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type: 'POST',
                dataType: 'json',
                url: '/add-customer',
                data: {
                    customer_name: name,
                    customer_id: customer_id,
                    company: cus_company,
                    address: cus_address,
                    mobile: cus_mobile,
                    email: cus_email,
                    gender: gender,
                    category: cus_category,
                    referred_by: cus_referred_by,
                },
                success: function (responce) {
                    $('#loading').modal('hide');
                    var err_message = responce.err_message;
                    var success_message = responce.success_message;
                    if (err_message) {
                        //$('.error_div').css('display', 'block').fadeOut(4000);
                        //$('.err_msg').text(err_message);
                        swal({
                            title: "Whoops!",
                            text: err_message,
                            type: "error",
                            showCancelButton: false,
                            confirmButtonClass: 'btn-danger',
                            confirmButtonText: 'Ok',
                            cancelButtonText: "No, cancel it!",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        })
                    } else if (success_message) {
                        swal({
                            title: "Success!",
                            text: success_message,
                            type: "success",
                            showCancelButton: false,
                            confirmButtonClass: 'btn-danger',
                            confirmButtonText: 'Ok',
                            cancelButtonText: "No, cancel it!",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        }, function (isConfirm) {
                            if (isConfirm) {
                                var delay = 300;
                                setTimeout(function () {
                                    location.reload();
                                }, delay);
                            }
                        });


                    }
                },

            });
            return true;
        }

    }


    var cus_category = $('#cus_category').val();
    if (cus_category == 1) {
        var elemant_company = document.getElementById(cus_company);
        document.getElementById("company_lists").hidden = true;

    }

    $('#cus_category').change(function (e) {
        var cus_category = $('#cus_category').val();
        if (cus_category == 1) {
            var elemant_company = document.getElementById(cus_company);
            document.getElementById("company_lists").hidden = true;
        } else if (cus_category == 2) {
            var elemant_company = document.getElementById(cus_company);
            document.getElementById("company_lists").hidden = false;
        } else {
            var elemant_company = document.getElementById(cus_company);
            document.getElementById("company_lists").hidden = true;
        }
    });


    $('.add-company').click(function (e) {
        e.preventDefault();
        $('#add_company').modal('show');

    });


    function doAjaxCompany() {
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: "GET",
            url: "/get-company-lists",
            dataType: 'json',
            success: function (select_value) {
                var company_lists = select_value.companies;
                console.log(company_lists);
                val_length = company_lists.length;
                var cus_company = $('#cus_company');
                cus_company.html('');
                for (j = 0; j < val_length; j++) {
                    var id = company_lists[j].id;
                    var user_id = company_lists[j].user_id;
                    var company = company_lists[j].company;
                    var append_city = '  <option value="' + id + '">' + company + '</option>';
                    cus_company.append(append_city);
                    cus_company.trigger("chosen:updated");
                }
                if (val_length == 0) {
                    cus_company.append('<option value="0">Company Not Available</option>');
                    cus_company.trigger("chosen:updated");
                }
            }

        });
    }

    $('.company_close').click(function (e) {
        $('#add_company').modal('hide');
        $('#add_company_name').val("");
        doAjaxCompany();
    });

    $('.save_add_company').click(function (e) {
        e.preventDefault();
        $('#loading').modal('show');
        var company_val = $('#add_company_name').val();
        //alert(company_val.toUpperCase)
        if (company_val != '') {
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: '/add-company-lists',
                type: 'POST',
                data: {company: company_val},
                dataType: 'json',
                success: function (returndata) {
                    $('#loading').modal('hide');
                    var success = returndata.success_message;
                    var err = returndata.err_message;
                    var set_company = returndata.set_company;
                    var set_company_name = returndata.set_company_name;
                    if (success) {

                        swal({
                            title: "Success",
                            text: returndata.success_message,
                            type: "success",
                            showCancelButton: false,
                            confirmButtonClass: "btn-info",
                            confirmButtonText: "Ok",
                            cancelButtonText: "No, skip it!",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        });
                        $('#add_company').modal('hide');
                        $('#add_company_name').val("");
                        doAjaxCompany();
                        var append_city = '  <option value="' + set_company + '">' + set_company_name + '</option>';
                        $('#cus_company').append(append_city);
                        $('#cus_company').trigger("chosen:updated");
                    }
                    else if (err) {
                        swal({
                            title: "warning",
                            text: err,
                            type: "warning",
                            showCancelButton: false,
                            confirmButtonClass: "btn-info",
                            confirmButtonText: "Ok",
                            cancelButtonText: "No, skip it!",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        });
                    }
                }

            });
        } else {
            swal({
                title: "warning",
                text: "Enter Company Name",
                type: "warning",
                showCancelButton: false,
                confirmButtonClass: "btn-info",
                confirmButtonText: "Ok",
                cancelButtonText: "No, skip it!",
                closeOnConfirm: false,
                closeOnCancel: false
            });
            $('#loading').modal('hide');
        }

    });


    $('.close_btn').click(function (e) {
        e.preventDefault();
        location.reload();
    });


    //update customer logic
    $('.update_customer_btn').click(function (e) {
        e.preventDefault();
        $('.update_customer').modal('show');
        var cus_id = this.id;
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'GET',
            dataType: 'json',
            url: '/get-customer/' + cus_id,
            success: function (responce) {
                var success_message = responce.customer_datas;
                var len = success_message.length;
                for (i = 0; i < len; i++) {
                    var customer_id = success_message[i].customer_id;
                    var customer_name = success_message[i].customer_name;
                    var company = success_message[i].company;
                    var address = success_message[i].address;
                    var mobile = success_message[i].mobile;
                    var email = success_message[i].email;
                    var gender = success_message[i].gender;
                    var category = success_message[i].category;
                    var referred_by = success_message[i].referred_by;
                    var created_by = success_message[i].created_by;
                    var created_at = success_message[i].updated_at;
                    var date = new Date(created_at);

                    if (category == 1 || category == 3) {

                        document.getElementById("cus_company").disabled = true;
                    } else {
                        document.getElementById("cus_company").disabled = false;
                    }

                    $('#customer_table_id').val(cus_id);
                    $('#cus_name').val(customer_name);
                    $('#cus_company').val(company);
                    $('#customer_id').val(customer_id);
                    $('#customer_mobile').val(mobile);
                    $('#customer_email').val(email);
                    $('#customer_gender').val(gender);
                    $('#customer_category').val(category);
                    $('#customer_refer_by').val(referred_by);
                    $('#customer_address').val(address);
                    $('#cus_company').trigger("chosen:updated");
                    if (created_by == 1) {
                        $('.created_by_edit').text('Super Admin');
                    } else if (created_by == 2) {
                        $('.created_by_edit').addClass('badege badge-success').text('Admin');
                    } else {
                        $('.created_by_edit').addClass('badege badge-warning').text('Staff');
                    }


                }
                //if (err_message) {                   //$('.error_div').css('display', 'block').fadeOut(4000);
                //    //$('.err_msg').text(err_message);
                //    swal({
                //        title: "Whoops!",
                //        text: err_message,
                //        type: "error",
                //        showCancelButton: false,
                //        confirmButtonClass: 'btn-danger',
                //        confirmButtonText: 'Ok',
                //        cancelButtonText: "No, cancel it!",
                //        closeOnConfirm: false,
                //        closeOnCancel: false
                //    })
                //} else if (success_message) {
                //    swal({
                //        title: "Success!",
                //        text: success_message,
                //        type: "success",
                //        showCancelButton: false,
                //        confirmButtonClass: 'btn-danger',
                //        confirmButtonText: 'Ok',
                //        cancelButtonText: "No, cancel it!",
                //        closeOnConfirm: false,
                //        closeOnCancel: false
                //    }, function (isConfirm) {
                //        if (isConfirm) {
                //            var delay = 1000;
                //            setTimeout(function () {
                //                location.reload();
                //            }, delay);
                //        }
                //    });
                //
                //
                //}
            }


        });

    });

    $('.update-customer').click(function (e) {
        e.preventDefault();
        var cus_id = $('#customer_table_id').val();
        var customer_name = $('#cus_name').val();
        var company = $('#cus_company').val();
        var customer_id = $('#customer_id').val();
        var mobile = $('#customer_mobile').val();
        var email = $('#customer_email').val();
        var gender = $('#customer_gender').val();
        var category = $('#customer_category').val();
        var referred_by = $('#customer_refer_by').val();
        var address = $('#customer_address').val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            dataType: 'json',
            url: '/update-customer',
            data: {
                cus_id: cus_id,
                customer_name: customer_name,
                company: company,
                customer_id: customer_id,
                mobile: mobile,
                email: email,
                gender: gender,
                category: category,
                referred_by: referred_by,
                address: address
            },
            success: function (responce) {
                var suucees = responce.success;
                var error = responce.error;


                if (error) {               //$('.error_div').css('display', 'block').fadeOut(4000);
                    //$('.err_msg').text(err_message);
                    swal({
                        title: "Whoops!",
                        text: err_message,
                        type: "error",
                        showCancelButton: false,
                        confirmButtonClass: 'btn-danger',
                        confirmButtonText: 'Ok',
                        cancelButtonText: "No, cancel it!",
                        closeOnConfirm: false,
                        closeOnCancel: false
                    })
                } else if (suucees) {
                    swal({
                        title: "Success!",
                        text: suucees,
                        type: "success",
                        showCancelButton: false,
                        confirmButtonClass: 'btn-danger',
                        confirmButtonText: 'Ok',
                        cancelButtonText: "No, cancel it!",
                        closeOnConfirm: false,
                        closeOnCancel: false
                    }, function (isConfirm) {
                        if (isConfirm) {
                            var delay = 300;
                            setTimeout(function () {
                                location.reload();
                            }, delay);
                        }
                    });


                } else {

                }


            }

        })


    });

    $('#select_customer_id').change(function (e) {
        e.preventDefault();
        var customer_id = $('#select_customer_id').val();
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'GET',
            dataType: 'json',
            url: '/get-customer-id/' + customer_id,
            success: function (responce) {
                var customer_id = responce.customer_id;
                $('#customer_name').val(customer_id);
                $('#cus_name').val(customer_id);
            }

        })
    });


    $("#refer_date").datepicker({
        changeMonth: true,
        changeYear: true
    });

    $("#select_from_date").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd-mm-yy'
    });


    $("#select_to_date").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd-mm-yy'
    });


//image uploade
    function getObjectLength(o) {
        var length = 0;

        for (var i in o) {
            if (Object.prototype.hasOwnProperty.call(o, i)) {
                length++;
            }
        }
        return length;
    }


//update docs logic
    $('.view_edit_docs').click(function (e) {
        e.preventDefault();
        $('.edit_documents').modal('show');
        var doc_id = this.id;

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'GET',
            dataType: 'json',
            url: 'get-document-list/' + doc_id,
            success: function (responce) {
                var success_message = responce.documents_datas;
                var len = success_message.length;
                for (i = 0; i < len; i++) {
                    var customer_id = success_message[i].customer_id;
                    var customer_name = success_message[i].customer_name;
                    var doc_id = success_message[i].document_id;
                    var subject = success_message[i].subject;
                    var refer_date = success_message[i].refer_date;
                    var message = success_message[i].message;
                    var created_by = success_message[i].created_by;
                    var created_at = success_message[i].updated_at;
                    var user_id = success_message[i].user_id;
                    var date = new Date(created_at);


                    $('#customer_name').val(customer_name);
                    $('#document_id').val(doc_id);
                    $('#select_customer_id').val(customer_id);
                    $('#subject').val(subject);
                    $('#refer_date').val(refer_date);
                    $('#message').val(message);


                    if (user_id == 1) {
                        $('.created_by_edit').text('Super Admin');
                    } else if (user_id == 2) {
                        $('.created_by_edit').addClass('badege badge-success').text('Admin');
                    } else {
                        $('.created_by_edit').addClass('badege badge-warning').text('Staff');
                    }


                }

            }


        });

    });

    $('.update-docs').click(function (e) {
        e.preventDefault();
        $('#loading').modal({show: true, backdrop: 'static', keyboard: false});
        var select_customer_id = $('#select_customer_id').val();
        var customer_name = $('#customer_name').val();
        var document_id = $('#document_id').val();
        var subject = $('#subject').val();
        var refer_date = $('#refer_date').val();
        var message = $('#message').val();

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'POST',
            dataType: 'json',
            url: '/update-docs',
            data: {
                cus_id: select_customer_id,
                customer_name: customer_name,
                document_id: document_id,
                subject: subject,
                refer_date: refer_date,
                message: message

            },
            success: function (responce) {
                $('#loading').modal('hide');
                var suucees = responce.success;
                var error = responce.error;


                if (error) {               //$('.error_div').css('display', 'block').fadeOut(4000);
                    //$('.err_msg').text(err_message);
                    swal({
                        title: "Whoops!",
                        text: err_message,
                        type: "error",
                        showCancelButton: false,
                        confirmButtonClass: 'btn-danger',
                        confirmButtonText: 'Ok',
                        cancelButtonText: "No, cancel it!",
                        closeOnConfirm: false,
                        closeOnCancel: false
                    })
                } else if (suucees) {
                    swal({
                        title: "Success!",
                        text: suucees,
                        type: "success",
                        showCancelButton: false,
                        confirmButtonClass: 'btn-danger',
                        confirmButtonText: 'Ok',
                        cancelButtonText: "No, cancel it!",
                        closeOnConfirm: false,
                        closeOnCancel: false
                    }, function (isConfirm) {
                        if (isConfirm) {
                            var delay = 300;
                            setTimeout(function () {
                                location.reload();
                            }, delay);
                        }
                    });


                } else {

                }


            }

        })


    });


    $("#attachment_photos").on('change', function () {
        //Get count of selected files
        var countFiles = $(this)[0].files.length;
        var imgPath = $(this)[0].value;
        var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
        var image_holder = $("#image-holder").html();
        if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
            if (typeof (FileReader) != "undefined") {
                //loop for each file selected for uploaded.
                for (var i = 0; i < countFiles; i++) {
                    var countFile = getObjectLength(imgFile);
                    imgFile[countFile] = document.getElementById('attachment_photos').files[i];
                    console.log(imgFile);
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var file = e.target;
                        var div2 = '<div class="col-xs-3  select-img"><div class="col-lg-12 image-remove " id="' + countFile + '"">' +
                            '<img src="/images/close.png" class="pull-right"' +
                            ' style="background-color:#ffffff; border-radius: 50%; position: relative;width:15%;top:1em; left:1.4em;z-index: 1001; opacity: 1;">' +
                            '</div>' +
                            '<div class="col-lg-12 prev_img nopad" aria-hidden="true">' +
                            '<img src="' + e.target.result + '" class="thumb-image" style="width:100%">' +
                            '</div></div>';
                        $("#preview_photos").append(div2);
                        $(".image-remove").click(function () {
                            var index = $(this).attr('id');
                            delete imgFile[index];
                            console.log(imgFile);
                            $(this).parent(".select-img").remove();
                        });
                    }
                    reader.readAsDataURL($(this)[0].files[i]);
                }

            } else {
                console.log("This browser does not support FileReader.");
            }
        } else {
            swal({
                title: "Whoops!",
                text: "This is Not an Image",
                type: "warning",
                showCancelButton: false,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: 'Ok',
                cancelButtonText: "No, cancel it!",
                closeOnConfirm: false,
                closeOnCancel: false
            })
        }
    });


    $('#attachment_doc').change(function (e) {
        e.preventDefault();
        var countFiles = $(this)[0].files.length;
        var imgPath = $(this)[0].value;
        var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
        var image_holder = $("#preview_doc").html();
        if (extn == 'pdf' || extn == 'doc' || extn == 'docx' || extn == 'xls' || extn == 'xlsx' ||
            extn == 'txt' || extn == 'csv') {
            if (typeof (FileReader) != "undefined") {
                //loop for each file selected for uploaded.
                for (var i = 0; i < countFiles; i++) {
                    var countFile = getObjectLength(docFile);
                    docFile[countFile] = document.getElementById('attachment_doc').files[i];
                    console.log(docFile);
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var file = e.target;
                        //var div2 = '<div class="col-xs-12 nopad select-img"><div class="row image-remove " id="' + countFile + '"><div class="col-lg-12">' +
                        //
                        //    '<img src="/images/close.png" class="pull-right"' +
                        //    ' style="background-color:#ffffff; border-radius: 50%; position: relative;width:10%;top:0.8em; left:1em;z-index: 1001; opacity: 1;">' +
                        //    '<div class="col-lg-12 prev_doc nopad" aria-hidden="true">' +
                        //    '<p>' + docFile[countFile].name + '</p>' +
                        //    '</div>' +
                        //    '</div></div>' +
                        //    '</div>';
                        var div2 = '  <div class="col-sm-12 prev_doc select-img"> ' +
                            ' <p class="pull-left">' + docFile[countFile].name + '</p>' +
                            ' <i class="fa fa-window-close pull-right image-remove" id="' + countFile + '" aria-hidden="true"></i>' +
                            ' </div>';
                        $("#preview_doc").append(div2);

                        $(".image-remove").click(function () {
                            var index = $(this).attr('id');
                            delete docFile[index];
                            console.log(docFile);
                            $(this).parent(".select-img").remove();
                        });


                    }
                    reader.readAsDataURL($(this)[0].files[i]);
                }


            } else {
                console.log("This browser does not support FileReader.");
            }
        } else {
            swal({
                title: "Whoops!",
                text: "This is Not an File",
                type: "warning",
                showCancelButton: false,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: 'Ok',
                cancelButtonText: "No, cancel it!",
                closeOnConfirm: false,
                closeOnCancel: false
            })
        }

    });


    $('#attachment_files').change(function (e) {
        e.preventDefault();
        var countFiles = $(this)[0].files.length;
        var imgPath = $(this)[0].value;
        var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
        var image_holder = $("#preview_files").html();
        if (extn == 'zip' || extn == 'rar' || extn == 'psd') {
            if (typeof (FileReader) != "undefined") {
                //loop for each file selected for uploaded.
                for (var i = 0; i < countFiles; i++) {
                    var countFile = getObjectLength(docFile);
                    zipFile[countFile] = document.getElementById('attachment_files').files[i];
                    console.log(zipFile);
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var file = e.target;

                        var div2 = '  <div class="col-sm-12 prev_doc select-img"> ' +
                            ' <p class="pull-left">' + zipFile[countFile].name + '</p>' +
                            ' <i class="fa fa-window-close pull-right image-remove" id="' + countFile + '" aria-hidden="true"></i>' +
                            ' </div>';
                        $("#preview_files").append(div2);

                        $(".image-remove").click(function () {
                            var index = $(this).attr('id');
                            delete zipFile[index];
                            console.log(zipFile);
                            $(this).parent(".select-img").remove();
                        });


                    }
                    reader.readAsDataURL($(this)[0].files[i]);
                }


            } else {
                console.log("This browser does not support FileReader.");
            }
        } else {
            swal({
                title: "Whoops!",
                text: "This is Not an Archeive Files",
                type: "warning",
                showCancelButton: false,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: 'Ok',
                cancelButtonText: "No, cancel it!",
                closeOnConfirm: false,
                closeOnCancel: false
            })
        }
    });


    $('.document_create').click(function (e) {
        e.preventDefault();
        $('#loading').modal({show: true, backdrop: 'static', keyboard: false});
        var document_id = $('#doc_id').val();
        var customer_name = $('#cus_name').val();
        var message = $('#message').val();
        var customer_id = $('#select_customer_id').val();
        var subject = $('#subject').val();
        var refer_date = $('#refer_date').val();
        var imgCount = getObjectLength(imgFile);
        var data = new FormData();
        if (imgCount > 0) {
            for (var key in imgFile) {
                data.append("postImgs[]", imgFile[key]);
            }
            for (var key in docFile) {
                data.append("attachment_doc[]", docFile[key]);
            }
            for (var key in zipFile) {
                data.append("attachment_file[]", zipFile[key]);
            }
        } else {
            // console.log(document.getElementById('status_images').files);
            data.append("postImgs[]", '');
            data.append("attachment_doc[]", '');
            data.append("attachment_file[]", '');
        }
        data.append("doc_id", document_id);
        data.append("cus_name", customer_name);
        data.append("message", message);
        data.append("customer_id", customer_id);
        data.append("subject", subject);
        data.append("refer_date", refer_date);

        if (customer_id == '') {
            $('#loading').modal('hide');
            swal({
                title: "Whoops!",
                text: "Choose Customer Id",
                type: "warning",
                showCancelButton: false,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: 'Ok',
                cancelButtonText: "No, cancel it!",
                closeOnConfirm: false,
                closeOnCancel: false
            })

        } else if (subject == "") {
            $('#loading').modal('hide');
            swal({
                title: "Whoops!",
                text: "Subject Field is Empty!",
                type: "warning",
                showCancelButton: false,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: 'Ok',
                cancelButtonText: "No, cancel it!",
                closeOnConfirm: false,
                closeOnCancel: false
            })
        }
        else if (refer_date == "") {
            $('#loading').modal('hide');
            swal({
                title: "Whoops!",
                text: "Reference Date Field is Empty!",
                type: "warning",
                showCancelButton: false,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: 'Ok',
                cancelButtonText: "No, cancel it!",
                closeOnConfirm: false,
                closeOnCancel: false
            })
        } else {

            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: '/add-documents',
                type: 'POST',
                data: data,
                dataType: 'json',
                async: true,
                cache: false,
                contentType: false,
                processData: false,
                success: function (returndata) {
                    $('#loading').modal('hide');
                    swal({
                            title: "Success",
                            text: returndata.success,
                            type: "warning",
                            showCancelButton: false,
                            confirmButtonClass: "btn-info",
                            confirmButtonText: "Ok",
                            cancelButtonText: "No, skip it!",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        },
                        function (isConfirm) {
                            if (isConfirm) {

                                var delay = 10;
                                setTimeout(function () {
                                    location.reload();
                                }, delay);

                            } else {
                                swal("Cancelled", "Your file is safe :)", "error");
                            }
                        });
                }

            });
        }

    });


    //update documents

    $('.update_document').click(function (e) {
        e.preventDefault();
        $('#loading').modal({show: true, backdrop: 'static', keyboard: false});
        var document_id = $('#doc_id').val();
        var data = new FormData();

        for (var key in imgFile) {
            data.append("postImgs[]", imgFile[key]);
        }
        for (var key in docFile) {
            data.append("attachment_doc[]", docFile[key]);
        }
        for (var key in zipFile) {
            data.append("attachment_file[]", zipFile[key]);
        }
        data.append("doc_id", document_id);
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: '/update-document-lists',
            type: 'POST',
            data: data,
            dataType: 'json',
            async: true,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
                $('#loading').modal('hide');
                var success = returndata.success;
                var error = returndata.error;
                if (success) {
                    swal({
                            title: "Success",
                            text: returndata.success,
                            type: "success",
                            showCancelButton: false,
                            confirmButtonClass: "btn-info",
                            confirmButtonText: "Ok",
                            cancelButtonText: "No, skip it!",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        },
                        function (isConfirm) {
                            if (isConfirm) {

                                var delay = 10;
                                setTimeout(function () {
                                    location.reload();
                                }, delay);

                            } else {
                                swal("Cancelled", "Your file is safe :)", "error");
                            }
                        });
                } else if (error) {
                    swal({
                        title: "Whoops!",
                        text: error,
                        type: "warning",
                        showCancelButton: false,
                        confirmButtonClass: 'btn-danger',
                        confirmButtonText: 'Ok',
                        cancelButtonText: "No, cancel it!",
                        closeOnConfirm: false,
                        closeOnCancel: false
                    })
                }

            }

        });
        // console.log(document.getElementById('status_images').files);


    });


    $('.customer_visible').click(function (e) {
        e.preventDefault();
        var id = this.id;
        var data_id = $(this).data('id');
        if (data_id == 0) {

            swal({
                    title: "Are you sure?",
                    text: "This Customer will be hidden to view..?",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonClass: "btn-danger",
                    confirmButtonText: "Yes, Hidden it!",
                    cancelButtonText: "No, skip it!",
                    closeOnConfirm: false,
                    closeOnCancel: false
                },
                function (isConfirm) {
                    if (isConfirm) {

                        var delay = 10;
                        setTimeout(function () {
                            window.location.href = "/customer-hidden/" + id;
                        }, delay);
                        /*$.ajax({
                         type: 'get',
                         url: 'delete-product-image/' + id,
                         dataType: 'json',
                         success: function () {
                         location.reload();
                         }, error: function () {

                         }
                         });*/
                    } else {
                        swal("Cancelled", "Your file is safe :)", "error");
                    }
                });
        } else {
            swal({
                    title: "Are you sure?",
                    text: "This Customer will be Visible to view..?",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonClass: "btn-danger",
                    confirmButtonText: "Yes, visible it!",
                    cancelButtonText: "No, skip it!",
                    closeOnConfirm: false,
                    closeOnCancel: false
                },
                function (isConfirm) {
                    if (isConfirm) {

                        var delay = 10;
                        setTimeout(function () {
                            window.location.href = "/customer-hidden/" + id;
                        }, delay);
                        /*$.ajax({
                         type: 'get',
                         url: 'delete-product-image/' + id,
                         dataType: 'json',
                         success: function () {
                         location.reload();
                         }, error: function () {

                         }
                         });*/
                    } else {
                        swal("Cancelled", "Your file is safe :)", "error");
                    }
                });
        }

    });


});


$('.customer_delete').on('click', function (e) {
    e.preventDefault();

    var id = (this.id);
    /*console.log(id);*/
    swal({
            title: "Are you sure?",
            text: "You will not be able to recover this file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel plx!",
            closeOnConfirm: false,
            closeOnCancel: false
        },
        function (isConfirm) {
            if (isConfirm) {
                swal("Deleted!", "Your file has been deleted.", "success");
                var delay = 1000;
                setTimeout(function () {
                    window.location.href = "customer-delete/" + id;
                }, delay);
            } else {
                swal("Cancelled", "Your file is safe :)", "error");
            }
        });
});


$('.document_delete').on('click', function (e) {
    e.preventDefault();

    var id = (this.id);
    console.log(id);
    swal({
            title: "Are you sure?",
            text: "You will not be able to recover this file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel plx!",
            closeOnConfirm: false,
            closeOnCancel: false
        },
        function (isConfirm) {
            if (isConfirm) {
                swal("Deleted!", "Your file has been deleted.", "success");
                var delay = 1000;
                setTimeout(function () {
                    window.location.href = "/document-delete/" + id;
                }, delay);
            } else {
                swal("Cancelled", "Your file is safe :)", "error");
            }
        });
});


$('.delete-docs').on('click', function (e) {
    e.preventDefault();
    var id = (this.id);
    console.log(id);
    swal({
            title: "Are you sure?",
            text: "You will not be able to recover this file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel plx!",
            closeOnConfirm: false,
            closeOnCancel: false
        },
        function (isConfirm) {
            if (isConfirm) {
                swal("Deleted!", "Your file has been deleted.", "success");
                var delay = 1000;
                setTimeout(function () {
                    window.location.href = "/document-view-delete/" + id;
                }, delay);
            } else {
                swal("Cancelled", "Your file is safe :)", "error");
            }
        });
});


// number fileds validation
$(document).ready(function () {
    //called when key is pressed in textbox
    $(".number_fileds").keypress(function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            //display error message
            $("#errmsg").html("Digits Only").show().fadeOut("slow");
            return false;
        }
    });
});

