<!DOCTYPE html>
<!--
This is a starter template page. Use this page to start your new project from
scratch. This page gets rid of all links and provides the needed markup only.
-->
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>CREW Administrator</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <meta name="csrf_token" content="{{ csrf_token() }}" />
    <link rel="stylesheet" href="{{ asset('/bower_components/bootstrap/dist/css/bootstrap.min.css') }}">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="{{ asset('/bower_components/font-awesome/css/font-awesome.min.css') }}">
    <!-- Ionicons -->
    <link rel="stylesheet" href="{{ asset('/bower_components/Ionicons/css/ionicons.min.css') }}">
   
    <!-- DataTables -->
    <link rel="stylesheet" href="{{ asset('/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css') }}">
    <!-- AdminLTE Skins. Choose a skin from the css/skins
    folder instead of downloading all of them to reduce the load. -->
    <link rel="stylesheet" href="{{ asset('/bower_components/admin-lte/dist/css/skins/_all-skins.min.css') }}">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- Google Font -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
    <!-- bootstrap-toggle -->
    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
    <!-- ekko-lightbox -->
		<link href="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.css" rel="stylesheet">
    <!-- bootstrap-tagsinput -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css">
    <!-- select2 -->
    <link href="{{ asset('/bower_components/select2/dist/css/select2.min.css') }}" rel="stylesheet" />
    <!-- Theme style -->
    <link rel="stylesheet" href="{{ asset('/bower_components/admin-lte/dist/css/AdminLTE.min.css') }}">
    <!-- jquery-ui -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    {{-- spectrum --}}
	<link rel="stylesheet" href="{{ asset('/assets/spectrum/spectrum.css') }}">
    
    <style>
        /* .store-password-field {
          
        } */
        /* .select2{
            width: 100% !important;
        } */
        .store-logo-holder {
            width: 200px; 
            height:200px; 
            border: 1px solid #e2e2e2; 
            padding:2px; 
            text-align: center;
            position: relative;
        }

        #img_store_logo {
            position: absolute;
            margin: auto;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
        }

        .store-banner-holder {
            width: 100%; 
            height:100px; 
            border: 1px solid #e2e2e2; 
            padding:2px; 
            text-align: center;
            position: relative;
        }

        #img_store_banner {
            position: absolute;
            margin: auto;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
        }
        
        .error{
            color: red;
        }

        .store-logo{
            width: 200px; 
            height:200px; 
            margin: auto;
            padding:2px; 
            text-align: center;
            position: relative;
        }

        .bootstrap-tagsinput {
            width: 100% !important;
            border-radius: 0;
            box-shadow: none;
            border-color: #d2d6de;
        }

        .change_color {
            height: 45px;
            width: 45px;
            margin: 2px;
        }
        #image_preview img {
            height: 65px;
            width: 100%;
        }
        /* div#image_preview {
            column-count: 4;
        }
         */
        .print-file-name{
            padding: 5px;
            text-align: center;
            border-top: 1px solid #e2e2e2;
        }

        .print-file-holder{
            border: 1px solid #e2e2e2;
            margin-bottom: 10px;
            height: 100px;
            padding: 5px;
        }
		</style>
		
</head>
<!--
BODY TAG OPTIONS:
=================
Apply one or more of the following classes to get the
desired effect
|---------------------------------------------------------|
| SKINS         | skin-blue                               |
|               | skin-black                              |
|               | skin-purple                             |
|               | skin-yellow                             |
|               | skin-red                                |
|               | skin-green                              |
|---------------------------------------------------------|
|LAYOUT OPTIONS | fixed                                   |
|               | layout-boxed                            |
|               | layout-top-nav                          |
|               | sidebar-collapse                        |
|               | sidebar-mini                            |
|---------------------------------------------------------|
-->
<body class="hold-transition skin-black sidebar-mini">
    <div class="wrapper">

    <!-- Main Header -->
    @include('admin.header')
    <!-- Left side column. contains the logo and sidebar -->
    @include('admin.sidebar')

    <!-- Content Wrapper. Contains page content -->
        @yield('content')
    <!-- /.content-wrapper -->

    <!-- Main Footer -->
    @include('admin.footer')

    <!-- Add the sidebar's background. This div must be placed               
    immediately after the control sidebar -->
    <div class="control-sidebar-bg"></div>
    </div>

    <div class="modal fade" id="modal_add_category" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <form id="frm_add_category">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Adding Category</h4>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div id="modal_add_category_msg"></div>
                                <div class="form-group">
                                    Category Name *
                                    <div class="row">
                                        <div class="col-sm-12">
                                            <input type="text" name="category" class="form-control" placeholder="Enter category name">
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    Category Status *
                                    <div class="row">
                                        <div class="col-sm-12">
                                            <select name="is_active" class="form-control">
                                                <option value="1">Active</option>
                                                <option value="0">Inactive</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary btn-custom-save">Save</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<!-- ./wrapper -->

    <!-- REQUIRED JS SCRIPTS -->

    <!-- jQuery 3 -->
    <script src="{{ asset('/bower_components/jquery/dist/jquery.min.js') }}"></script>
    <!-- Bootstrap 3.3.7 -->
    <script src="{{ asset('/bower_components/bootstrap/dist/js/bootstrap.min.js') }}"></script>
    {{-- spectrum --}}
    <script src="{{ asset('/assets/spectrum/spectrum.js') }}"></script>
    <!-- DataTables -->
    <script src="{{ asset('/bower_components/datatables.net/js/jquery.dataTables.min.js') }}"></script>
    <script src="{{ asset('/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js') }}"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.flash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
    <!-- moment -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
    <!-- datetime-moment -->
    <script src="http://cdn.datatables.net/plug-ins/1.10.19/sorting/datetime-moment.js"></script>
    <!-- bootstrap-toggle -->
    <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
    <!-- AdminLTE App -->
    <script src="{{ asset('/bower_components/admin-lte/dist/js/adminlte.min.js') }}"></script>
    <!-- ekko-lightbox -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.js"></script>
    <!-- validate -->
	<script src="{{ asset('/bower_components/jquery-validation/dist/jquery.validate.min.js') }}"></script>
    <!-- Optionally, you can add Slimscroll and FastClick plugins.
        Both of these plugins are recommended to enhance the
     user experience. -->
    <!-- bootstrap-tagsinput.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.js"></script>
    <!-- fabric js -->
    <script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.15/fabric.min.js"></script>
    <!-- select2 -->
    <script src="{{ asset('/bower_components/select2/dist/js/select2.min.js') }}"></script>
    <!-- jquery-ui -->
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
   

    <script>
        $(document).ready(function() {

            // var hash = window.location.hash;
            // hash && $('ul.nav a[href="' + hash + '"]').tab('show');

            // $.fn.dataTable.moment( 'DD/M/YYYY' );
            callSpectrumApi();
            $('#orders_table').DataTable({
                columnDefs: [{
                    target: 6,
                    type: 'datetime-moment'
                }]
            });

            $('#store_owners_table').DataTable();
            
            $('#tbl_commission').DataTable({
                initComplete: function () {
                    this.api().columns(0).every( function () {
                        var column = this;
                        var select = $('<select class="form-control"><option value=""></option></select>')
                            .appendTo( $('#store_filter').empty() )
                            .on( 'change', function () {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    $(this).val()
                                );

                                column
                                    .search( val ? '^'+val+'$' : '', true, false )
                                    .draw();
                            } );

                        column.data().unique().sort().each( function ( d, j ) {
                            select.append( '<option value="'+d+'">'+d+'</option>' )
                        } );
                    } );
                },
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'csv',
                        className : "btn btn-default",
                        text: "<i class=\"fa fa-table\"></i> CSV",
                        title : function() {
                            return "Commission Reports";
                        }
                    },
                    {
                        extend: 'excel',
                        className : "btn btn-default",
                        text: "<i class=\"fa fa-file-excel-o\"></i> Excel",
                        title : function() {
                            return "Commission Reports";
                        }
                    }
                ],
            });
            
            $.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {

                   if (settings.nTable.id !=='tbl_store_orders') {
                        return true;
                   }
                    var min = $('#min').datepicker("getDate");
                    var max = $('#max').datepicker("getDate");
                    var startDate = new Date(data[10]);
                    if (min == null && max == null) { return true; }
                    if (min == null && startDate <= max) { return true;}
                    if(max == null && startDate >= min) {return true;}
                    if (startDate <= max && startDate >= min) { return true; }
                    return false;
                    
                },
            );

          
            
            var table = $('#tbl_store_orders').DataTable({
                initComplete: function () {
                    this.api().columns(0).every( function () {
                        var column = this;
                        var select = $('<select class="form-control"><option value=""></option></select>')
                            .appendTo( $('#store_filter').empty() )
                            .on( 'change', function () {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    $(this).val()
                                );

                                column
                                    .search( val ? '^'+val+'$' : '', true, false )
                                    .draw();
                            } );

                        column.data().unique().sort().each( function ( d, j ) {
                            select.append( '<option value="'+d+'">'+d+'</option>' )
                        } );
                    } );
                },
                scrollX: true,
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'csv',
                        exportOptions: {
                            columns: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
                        },
                        className : "btn btn-default",
                        text: "<i class=\"fa fa-table\"></i> CSV",
                        title : function() {
                            return "ORDER REPORTS";
                        }
                    },
                    {
                        extend: 'excel',
                        exportOptions: {
                            columns: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
                        },
                        className : "btn btn-default",
                        text: "<i class=\"fa fa-file-excel-o\"></i> Excel",
                        title : function() {
                            return "ORDER REPORTS";
                        }
                    }
                ],
                columnDefs: [
                    { targets: 10, type: 'date', visible: false },
                    { targets: 10, type: 'date' }
                ],
            });

           
            $("#min").datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
            $("#max").datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });

            $(document).on('a click', '.btn-order-item-details', function(e){
					
                e.preventDefault();
                var getCK = $(this).data('ck');
                var getPid = $(this).data('pid');
                var getId = $(this).data('id');
                $.ajax({
                    data: {
                        ck: getCK,
                        pid: getPid,
                        id: getId
                    },
                    type: 'POST',
                    url  : "{{ url('admin/post/show-store-order-details') }}",
                    dataType: 'json',
                    beforeSend:function(xhr){
                        
                        var token = $('meta[name="csrf_token"]').attr('content');

                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                        xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success:function(result) {
                        if(result.success){
                            $('#modal_store_order_details_body_content').html(result.payment_details_response);
                        }
                    }
                });
                $('#modal_store_order_details').modal('show');
            });

            try{
                var canvas = new fabric.Canvas('canvas');
                canvas.setWidth($('.canvas-container').width());
            }catch(e){

            }
            
            var tblbody_clipart_cat = $('#tblbody_clipart_cat');
 
            tblbody_clipart_cat.sortable({
                revert: 100,
                placeholder: 'placeholder'
            });

            tblbody_clipart_cat.disableSelection();

            $('#svg_clipart').on('change', function(event) {
                var tmppath = URL.createObjectURL(event.target.files[0]);
                // $("img").fadeIn("fast").attr('src', URL.createObjectURL(event.target.files[0]));
                fabric.loadSVGFromURL(URL.createObjectURL(event.target.files[0]), function(objects, options) {
                    var clipart = fabric.util.groupSVGElements(objects, options, );
                    clipart.set({
                       
                        borderColor: '#71b7f3',
                        cornerColor: '#71b7f3',
                        opacity: 10,
                        cornerSize: 10,
                        transparentCorners: false,
                        hasControls: true,
                        lockScalingFlip: true,
                        centeredScaling: true,
                        lockUniScaling: true,
                        cache: false,
                    }).scale('0.1');
                    canvas.clear();
                    canvas.add(clipart);
                    canvas.setActiveObject(clipart);
                    clipart.bringToFront();
                    clipart.center();
                    clipart.setCoords();
                    canvas.renderAll();
                    var obj = canvas.getActiveObject();

                    $('.available-colors').html('');
                    $('.available-colors').append('Colors:<div class="row"><div class="col-md-12">')
                    
                    for (var j in obj.paths) {

                        var i = j;
                        var idName = "color";
                        var count = ++j;
                        var fill = obj.paths[i].get('fill');
                        obj.paths[i].id = idName + count;
                        var id = obj.paths[i].get('id');

                        $('.available-colors').append('<button type="button" data-id="' + id + '" data-orig-color="'+fill+'" id="btn_' + id + '" data-toggle="popover" title="HEX Color" data-content="' + fill + '" class="btn btn-default change_color" style="background-color:' + fill + '"></button>');

                    }
                    console.log(obj);
                    $('.available-colors').append('</div></div>');

                    $('.additional-info').css("display", "block");

                    $('[data-toggle="popover"]').popover({
                        trigger: "hover",
                        placement: "bottom"
                    });

                });
            });

            $(document).on('button click', '.change_color', function() {

                var getPathId = $(this).data('id');
                var hexc = hexcolor();
                // var colour = hex2rgb(hexc);

                $(this).attr('data-content', hexc);
                $($(this).next().children()[2]).text(hexc);

                changeColor(getPathId, hexc);
                /* alert(getPathId); */

            });

            

          

            $('#list').click(function(event){
                event.preventDefault();
                $('#products .item').addClass('list-group-item');
            });

            $('#grid').click(function(event){
                event.preventDefault();
                $('#products .item').removeClass('list-group-item');
                $('#products .item').addClass('grid-group-item');
            });

            $("#store_name").on('keyup',function(){
                var getsportName = $(this).val();
                getsportName = getsportName.replace(/\s+/g, '-').toLowerCase(); //new object assigned to var str
                $("#store_url").val(getsportName);
            });

            $(document).on('click', '[data-toggle="lightbox"]', function(event) {
                event.preventDefault();
                $(this).ekkoLightbox({
                    alwaysShowClose: true,
                });
            });

            $(document).on('click', '[data-toggle="lightbox_visualizer"]', function(event) {
                event.preventDefault();
                var v = $(this).closest("div.input-group").find("input[type='file']").val();
                if(v == ""){
                    return false;
                }

                $(this).ekkoLightbox({
                    alwaysShowClose: true,
                });
            });

            $(document).on('change', '#select_sort_stores', function(event) {
                event.preventDefault();
                $('#frm_search_store').submit();
            });

            $(document).on('click', '#btn_delete_store', function(event) {
                event.preventDefault();

                var r = confirm("Do you really want to delete this Store? This process cannot be undone.");
                var id = $(this).data('store-id');
                var store_url = $(this).data('store-url');

                if (r == true) {

                    $.ajax({
                        type : 'POST',
                        url  : "{{ url('admin/store/delete') }}/"+id+'/'+store_url,
                        data : {
                            id : id,
                            store_url : store_url
                        },
                        beforeSend: function(xhr){

                            var token = $('meta[name="csrf_token"]').attr('content');
                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }

                        },
                        success :  function(response){ 
                            if(response.success){
                                alert(response.message);
                                window.location = "{{ url('admin/stores-list') }}";
                            }else{
                                alert(response.message);
                            }
                        }
                    });
                } 

                return false;
            });
            
            $("#frm_create_store").validate({
                rules: {
                    store_name: {
                        required: true
                    },
                    store_url: {
                        required: true
                    },
                    store_password: {
                        required: '#with_password_opt:checked'
                    },
                    store_logo: {
                        required: true
                    },
                    store_banner: {
                        required: true
                    },
                    store_status: {
                        required: true
                    },
                    store_currency: {
                        required: true
                    }
                },
                messages: {},
                errorPlacement: function(error, element) {
                    var placement = $(element).data('error');
                    if (placement) {
                        $(placement).append(error);
                    }else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: submitFormCreateStore
            });

            $("#frm_edit_store").validate({
                rules: {
                    store_name: {
                        required: true
                    },
                    store_url: {
                        required: true
                    },
                    store_password: {
                        required: '#with_password_opt:checked'
                    },
                    // store_logo: {
                    //     required: true
                    // },
                    // store_banner: {
                    //     required: true
                    // },
                    store_status: {
                        required: true
                    },
                },
                messages: {},
                errorPlacement: function(error, element) {
                    var placement = $(element).data('error');
                    if (placement) {
                        $(placement).append(error);
                    }else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: submitFormEditStore
            });

            $("#frm_tag_user_as_store_owner").validate({
                rules: {
                    user_name: {
                        required: true
                    },
                    user_id: {
                        required: true
                    },
                    
                },
                messages: {},
                errorPlacement: function(error, element) {
                    var placement = $(element).data('error');
                    if (placement) {
                        $(placement).append(error);
                    }else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: submitForm_frm_tag_user_as_store_owner
            });

            $("#frm_create_user_as_store_owner").validate({
                rules: {
                    name: {
						required : true
					},
					username: {
						required : true
					},
					email: {
						required: true,
						email: true
					},
					password: {
						required: true
						//minlength: 6  // <-- remove
					}
                    
                },
                messages: {},
                errorPlacement: function(error, element) {
                    var placement = $(element).data('error');
                    if (placement) {
                        $(placement).append(error);
                    }else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: submitForm_frm_create_user_as_store_owner
            });
            
            $('#with_password_opt').change(function() {
                if($(this).prop('checked')){
                    $('.store-password-field').css({
                        'display': 'block'
                    });
                }else{
                    $('.store-password-field').css({
                        'display': 'none'
                    });
                }
            });

            $(".upload_img").change(function() {
                var $id = $(this).data('use-id');
                readURL(this, $id);
            });

            $(".upload-visualizer").change(function() {
                var $id = $(this).data('use-id');
                readURLVisualizer(this, $id);
            });

            function changeColor(pathid, hexc) {
                var obj = canvas.getActiveObject();
                for (var j in obj.paths) {

                    var id = obj.paths[j].get('id');

                    if (id == pathid) {
                        obj.paths[j].setFill(hexc);
                        canvas.renderAll();
                        break;
                    }
                }
                $('#btn_' + pathid).css({
                    'background-color': hexc
                })
            }

            $("#frm_add_category").validate({
				rules: {
                    category: {
						required: true
					},
					is_active: {
						required: true
					}
                },
				messages: {},
				errorPlacement: function(error, element) {
					var placement = $(element).data('error');
					if (placement) {
						$(placement).append(error);
					}else {
						error.insertAfter(element);
					}
				},
				submitHandler: submitAddCategoryForm
			});
     
            $(document).on('hidden.bs.modal', '.modal-close-reload', function(){
                location.reload();
            });


            $(document).on('button click', '.remove-store-access', function(e){

                var get_user_id = $(this).data('id');
                $.ajax({
                    type : 'POST',
                    url  : "{{ url('admin/post/remove-store-access') }}",
                    data : {
                        id : get_user_id
                    },
                    beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                            xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success :  function(response){ 
                        // console.log(response);
                        if(response.result){
                            alert("User is successfully remove as Store Owner.");
                            location.reload();
                        }else{
                            alert("Something went wrong. Please try again!");
                            location.reload();
                        }
                    }
                });
                return false;
            });

           
            $("#frm_clipart").validate({
				rules: {
                    upload_clipart: {
						required: true
					},
					category: {
						required: true
					},
                    clipart_tags: {
						required: true
					}
                },
				messages: {},
				errorPlacement: function(error, element) {
					var placement = $(element).data('error');
					if (placement) {
						$(placement).append(error);
					}else {
						error.insertAfter(element);
					}
				},
				submitHandler: submitClipartForm
			});

            ///

            function formatUserList(data) {
                if (data.loading) return data.text;
                var user = "<div class='select2-result-listsitory clearfix'>" +
                "<div class='select2-result-listsitory__meta'>" +
                "<div class='select2-result-listsitory__title'>" + data.name + " &mdash; " + data.email + "</div>";
                "</div>";
                return user;
            }

            function formatUserListSelection(list) {
                return list.name;
            }
            
            $('.select2-select-user').on('select2:select', function(e) {
                $('#user_id').val(e.params.data.id);
            });

            
            $("#sel_clipart_category").select2();

            $(".select2-select-user").select2({
                placeholder: "Select a state",
                allowClear: true,
                dropdownParent: $('#modal_add_existing_user'),
                ajax: {
                    url: "{{ url('/') . '/admin/user-list' }}",
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            q: params.term // search term
                        };
                    },

                    processResults: function(data, params) {
                        // parse the results into the format expected by Select2
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data, except to indicate that infinite
                        // scrolling can be used
                        var resData = [];
                        data.results.forEach(function(value) {
                            if (value.name.indexOf(params.term) != -1 || value.email.indexOf(params.term) != -1 )
                                resData.push(value)
                        })
                        return {
                            results: $.map(resData, function(item) {
                                return {
                                    id: item.id,
                                    name: item.name,
                                    email: item.email
                                }
                            })
                        };
                    },
                    cache: true
                },
                escapeMarkup: function(user) {
                    return user;
                },
                minimumInputLength: 1,
                templateResult: formatUserList,
                templateSelection: formatUserListSelection,
                
            });

            function submitClipartForm(){
                var obj = canvas.getActiveObject(canvas.setActiveObject(canvas.item(0)));
                obj.set({
                    left: 0,
                    top: 0
                }).scale(1);
                
                $('.change_color').each(function(i, elem) {
        
                    var def_color = $(elem).data('orig-color');
                    var def_id    = $(elem).data('id');
                    var id = obj.paths[i].get('id');
                    
                    if (id == def_id) {
                        obj.paths[i].setFill(def_color);
                    }
                });
                

                var normal_obj = canvas.getActiveObject(obj);
                var svg = canvas.toSVG({
                    width:  normal_obj.getWidth(),
                    height: normal_obj.getHeight(),
                    viewBox: {
                        x: '0',
                        y: '0',
                        width: normal_obj.getWidth(),
                        height: normal_obj.getHeight()
                    }
                });
                console.log(new FormData($('#frm_clipart')[0]))
                $.ajax({
                    type: "POST",
                    url  : "{{ url('admin/clipart/save-svg-clipart') }}",
                    data: new FormData($('#frm_clipart')[0]),
                    processData: false,
                    contentType: false,
                    beforeSend: function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');
                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                    },
                    success: function(response){
                        if(response.success){
                            alert(response.message);
                            location.reload();
                        }
                    }
                    
                });
            }

            $(document).on('button click', '.btn-delete-clipart-cat', function() {      
                var getId = $(this).data('id');
                $.ajax({
                    type : 'POST',
                    url  : "{{ url('admin/clipart/delete-clipart-category') }}",
                    data : {
                        id : getId
                    },
                    beforeSend: function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');
                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                    },
                    success :  function(response){
                        if(response.success){                          
                            alert(response.message)
                            location.reload();
                        }          
                    }
                });
            });

            $(document).on('button click', '.btn-edit-clipart-cat', function() {
                var getId = $(this).data('id');
                var getCategory = $(this).data('category');
                var getStatus = $(this).data('status');

                $('#modal_edit_category').modal('show');
                $('#edit_category').val(getCategory);
                $('#edit_is_active').val(getStatus);
                $('#cat_id').val(getId);
                
            });

            $("#frm_edit_category").validate({
				rules: {
                    category: {
						required: true
					},
					is_active: {
						required: true
					}
                },
				messages: {},
				errorPlacement: function(error, element) {
					var placement = $(element).data('error');
					if (placement) {
						$(placement).append(error);
					}else {
						error.insertAfter(element);
					}
				},
				submitHandler: submitEditCategoryForm
			});

            $('#btn_save_clipart_cat_sorting').on('click', function(e) {
                e.preventDefault();
                var sorted_data = tblbody_clipart_cat.sortable('serialize');
                // console.log(sorted_data);
                
                $.ajax({
                    data: sorted_data,
                    type: 'POST',
                    url  : "{{ url('admin/clipart/save-clipart-cat-ordering') }}",
                    beforeSend:function(xhr){
                        
                        var token = $('meta[name="csrf_token"]').attr('content');

                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                        xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success:function(result) {
                        if(result.success){
                            alert(result.message);
                        }
                    }
                });
            });

             //saving new template
            $('#stepOneNextBtn').click(function() {
                if($("#frm_addnew_visualizer").valid()){
                    var $active = $('.wizard .nav-tabs li.active');
                    $active.next().removeClass('disabled');
                    nextTab($active);
                }
                // $('#getSkins').val($('#_addPatterns').val());
            });

            $('#stepTwoNextBtn').click(function() {
                if($("#frm_addnew_visualizer").valid()){
                    var $active = $('.wizard .nav-tabs li.active');
                    $active.next().removeClass('disabled');
                    nextTab($active);
                }
            });

            $('#stepOneNextBtn_edit').click(function() {
                if($("#frm_edit_visualizer").valid()){
                    var $active = $('.wizard .nav-tabs li.active');
                    $active.next().removeClass('disabled');
                    nextTab($active);
                }
                // $('#getSkins').val($('#_addPatterns').val());
            });

            $('#stepTwoNextBtn_edit').click(function() {
                if($("#frm_edit_visualizer").valid()){
                    var $active = $('.wizard .nav-tabs li.active');
                    $active.next().removeClass('disabled');
                    nextTab($active);
                }
            });

            //Initialize tooltips
            // $('.nav-tabs > li a[title]').tooltip();
            
            //Wizard
            $('a[data-toggle="tab"]').on('show.bs.tab', function (e) {

                var $target = $(e.target);
            
                if ($target.parent().hasClass('disabled')) {
                    return false;
                }
                
            });

            $(".prev-step").click(function (e) {
                var $active = $('.wizard .nav-tabs li.active');
                prevTab($active);
            });

            
            $(document).on('change', '#numberOfTrims', function(event) {
                // alert()
                var numberOfTrims = $(this).val();
                if(numberOfTrims > 0){
                    $('#list_of_trims').html('');
                    for (i = 1; i <= numberOfTrims; i++) {
                        if(i == 1){
                            $('#list_of_trims').append('<div class="form-group"> ' +  
                                                            '<label  class="col-sm-4 control-label">Set Default Trim Color</label> ' + 
                                                            '<div class="col-sm-6"> ' + 
                                                                ' <input type="text" name="trim_label[]" class="form-control" value="Trim '+i+'"> ' + 
                                                            '</div> ' + 
                                                            '<div class="col-sm-2"> ' + 
                                                                    ' <input type="hidden" name="trim_def_color[]" class="colorPicker-trim" value="#FFFFFF"> ' + 
                                                                '</div> ' + 
                                                        '</div>');
                        }else{
                            $('#list_of_trims').append('<div class="form-group"> ' +  
                                                            '<label  class="col-sm-4 control-label">&nbsp;</label> ' + 
                                                            '<div class="col-sm-6"> ' + 
                                                                ' <input type="text" name="trim_label[]" class="form-control" value="Trim '+i+'"> ' + 
                                                            '</div> ' + 
                                                            '<div class="col-sm-2"> ' + 
                                                                    ' <input type="hidden" name="trim_def_color[]" class="colorPicker-trim" value="#FFFFFF"> ' + 
                                                                '</div> ' + 
                                                        '</div>');
                        }
                    }
                    callSpectrumApi();
                }else{
                    $('#list_of_trims').html('');
                }
            });

            $(".colorPicker").spectrum({
                preferredFormat: "rgb",
                showInput: true,
                localStorageKey: "spectrum.demo",
            });

           
            $(document).on('button change', '#sportName', function() {
                var sportsId = $(this).val();
                $.ajax({
                    type : 'POST',
                    url  : "{{ url('admin/visualizer/request/get-sports-category') }}",
                    data : {
                        id: sportsId
                    },
                    beforeSend: function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');
                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                    },
                    success :  function(response){
                        console.log(response)
                        if(response.success){
                            $('#sport_category').html('');
                            var cat_item = response.data;

                            cat_item.forEach(function(cat){
                                $('#sport_category').append('<option value="'+cat['Id']+'">'+cat['Category']+'</option>');
                            });
                        }
                    }
                });
            });

            // $('#modal_edit_category').modal('show', function(){

            // });

            $(document).on('button click', '.btn-preview-visualizer', function(event) {
                event.preventDefault();

                if($(this).data("for") != "edit"){
                    var v = $(this).closest("div.input-group").find("input[type='file']").val();
                    if(v == ""){
                        return false;
                    }
                }
                
                $('#modal_preview_visualizer_body').html('');
                $('#modal_preview_visualizer_body').html('<object id="obj_visualizer_preview"  type="image/svg+xml" height="502px" width="100%"> ' +
                            'Your browser is not supported svg file ' +
                        '</object>')
                    
                document.getElementById('obj_visualizer_preview').setAttribute('data', $(this).attr('data-visualizer'));
                $(this).attr('disabled', true);
                $(this).html('<i class="fa fa-spinner fa-spin"></i> opening');
                
                var self = $(this);
                setTimeout(function(){
                    $('#modal_preview_visualizer').modal('show');
                    $(self).attr('disabled', false);
                    $(self).html('<i class="fa fa-eye"></i> Preview');
                }, 1000);
              
            });

            $("#select2_select_pattern").select2({
                placeholder: "Select Overlay Pattern",
                templateResult: formatStatePattern
            });

            $("#frm_addnew_visualizer").validate({
                rules: {
                    sportName: {
                        required: true
                    }
                },
                messages: {},
                errorPlacement: function(error, element) {
                    var placement = $(element).data('error');
                    if (placement) {
                        $(placement).append(error);
                    }else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: submitFormAddNewVisualizer
            });

            $("#frm_edit_visualizer").validate({
                rules: {
                    sportName: {
                        required: true
                    }
                },
                messages: {},
                errorPlacement: function(error, element) {
                    var placement = $(element).data('error');
                    if (placement) {
                        $(placement).append(error);
                    }else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: submitFormEditVisualizer
            });

            $("#frm_upload_print_files").validate({
                rules: {},
                messages: {},
                errorPlacement: function(error, element) {
                    var placement = $(element).data('error');
                    if (placement) {
                        $(placement).append(error);
                    }else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: submitFormUploadPrintFiles
            });

            

            $(document).on('button click', '#btn_delete_visualizer', function() {

                if (!confirm("Are you sure you want to delete this Visualizer?")) {
                    return false;
                }

                var vis_id = $(this).data('id');
                $.ajax({
                    type : 'POST',
                    url  : "{{ url('admin/visualizer/delete') }}",
                    data : {
                        id: vis_id
                    },
                    beforeSend: function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');
                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                    },
                    success :  function(response){
                        console.log(response)
                        if(response.success){
                            alert(response.message);
                            window.location = "../visualizer"
                        }
                    }
                });
            });

            $(document).on('button click', '.delete-clipart', function() {

                if (!confirm("Are you sure you want to delete this Clipart?")) {
                    return false;
                }

                var clipart_id = $(this).data('id');
                $.ajax({
                    type : 'POST',
                    url  : "{{ url('admin/clipart/delete') }}",
                    data : {
                        id: clipart_id
                    },
                    beforeSend: function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');
                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                    },
                    success :  function(response){
                        console.log(response)
                        if(response.success){
                            alert(response.message);
                            location.reload();
                        }
                    }
                });


            });

            $("#uploadPrintFiles").change(function(){
                $('#image_preview').html("");
                var total_file=document.getElementById("uploadPrintFiles").files.length;


                for(var i=0;i<total_file;i++)
                {
                    $('#image_preview').append("<div class='col-sm-3'> " +
                            "<div class='print-file-holder'> " +
                                "<img class='svg-print-file-preview' src='"+URL.createObjectURL(event.target.files[i])+"'>  " +
                                "<div class='print-file-name'>"+event.target.files[i]['name']+ 
                                "</div>  " +
                            "</div> " +
                        "</div>");
                }


            });

            $(".btn-delete-print-file").click(function(e){
                e.preventDefault();
                var r = confirm("Do you really want to delete this Print File? This process cannot be undone.");
                if (r == true) {
                    var id = $(this).data('id');
                    $.ajax({
                        type : 'POST',
                        url  : "{{ url('admin/print-files/delete') }}",
                        data : {
                            id: id
                        },
                        beforeSend: function(xhr){
                            var token = $('meta[name="csrf_token"]').attr('content');
                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                        },
                        success :  function(response){
                        
                            if(response.success){
                                alert(response.message);
                                location.reload();
                            }
                        }
                    });

				}
				return false;
			});


            $('#store_hibernate').change(function() {
                var data = $("#frm_edit_store").serializeArray();
                $.ajax({
                    type : 'POST',
                    url  : "{{ url('admin/post/update-hibernate') }}",
                    data : {
                        data: data,
                        IsActive: $(this).prop('checked')
                    },
                    beforeSend:function(xhr){
                        var token = $('meta[name="csrf_token"]').attr('content');

                            if (token) {
                                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                            }
                            xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                    },
                    success :  function(response){
                        // console.log(response);
                        if(response.success){
                            alert(response.message);
                        }else{
                            // $('#isActiveAnnouncement').attr('checked', false);

                            $('#isActiveAnnouncement').removeClass('btn-primary');
                            // $(this).addClass('btn-default');
                        }
                    }
                });
                    return false;
            });
					
        }); // end document ready

        function formatStatePattern (state) {
            if (!state.id) { 
                return state.text; 
            }

            // index 0 is pattern id index 1 is thumbnail
            var split_id = state.id.split("##");
            
            var thumb = "{{ minio_url('uploads/images/') }}" + split_id[1];
            var $state = $('<div><img sytle="display: inline-block;" height="45px" src="'+thumb+'" /><span>' + state.text + '</span></div>'
            );
            return $state;
        }

        function callSpectrumApi(){
            $(".colorPicker-trim").spectrum({
                preferredFormat: "rgb",
                showInput: true,
                localStorageKey: "spectrum.demo",
            });
            
        
        }
       
        
        function nextTab(elem) {
            $(elem).next().find('a[data-toggle="tab"]').click();
        }
        
        function prevTab(elem) {
            $(elem).prev().find('a[data-toggle="tab"]').click();
        }
        
        function submitEditCategoryForm(){

            var data = $("#frm_edit_category").serializeArray();

            $.ajax({
                type : 'POST',
                url  : "{{ url('admin/clipart/update-clipart-category') }}",
                data : data,
                beforeSend: function(xhr){
                    var token = $('meta[name="csrf_token"]').attr('content');
                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }
                },
                success :  function(response){
                    if(response.success){
                        $('#modal_edit_category_msg').html('<div class="alert alert-success alert-dismissible"> ' +
                                                    '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' +
                                                    '<h4><i class="icon fa fa-check"></i> Success!</h4> ' +
                                                    '<p>'+response.message+'</p> ' +
                                                    '</div>').fadeIn().delay(2000).fadeOut(function (){
                                                        $('#modal_edit_category').modal('hide');
                                                        location.reload();
                                                    });
                        
                        var form = $('#frm_edit_category')
                        form.validate().resetForm();
                        form[0].reset();
                    }else{
                        $('#modal_edit_category_msg').html('<div class="alert alert-danger alert-dismissible"> ' +
                                                    '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' +
                                                    '<h4><i class="icon fa fa-ban"></i> Error!</h4> ' +
                                                    '<p>'+response.message+'</p> ' +
                                                    '</div>').fadeIn().delay(2000).fadeOut();
                    }          
                }
            });
        }

        function submitAddCategoryForm(){

            var data = $("#frm_add_category").serializeArray();

            $.ajax({
                type : 'POST',
                url  : "{{ url('admin/clipart/save-category') }}",
                data : data,
                beforeSend: function(xhr){
                    var token = $('meta[name="csrf_token"]').attr('content');
                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }
                },
                success :  function(response){
                    if(response.success){
                        var getURL = "{{ Request::is('admin/clipart-categories') }}";
                        $('#modal_add_category_msg').html('<div class="alert alert-success alert-dismissible"> ' +
                                                    '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' +
                                                    '<h4><i class="icon fa fa-check"></i> Success!</h4> ' +
                                                    '<p>'+response.message+'</p> ' +
                                                    '</div>').fadeIn().delay(2000).fadeOut(function (){
                                                        $('#modal_add_category').modal('hide');
                                                        if(getURL){
                                                            location.reload();
                                                        }else{
                                                            $("#sel_clipart_category").append('<option value="'+response.last_inserted_id+'">'+data[0]['value']+'</option>');
                                                        }
                                                    });
                        
                        var form = $('#frm_add_category')
                        form.validate().resetForm();
                        form[0].reset();
                    }else{
                        $('#modal_add_category_msg').html('<div class="alert alert-danger alert-dismissible"> ' +
                                                    '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' +
                                                    '<h4><i class="icon fa fa-ban"></i> Error!</h4> ' +
                                                    '<p>'+response.message+'</p> ' +
                                                    '</div>').fadeIn().delay(5000).fadeOut();
                    }          
                }
            });
        }

        function hexcolor() {
            var colorSet = '#' + Math.random().toString(16).slice(2, 8).toUpperCase();
            /* console.log(colorSet); */
            return colorSet;
        }

        

        function submitFormAddNewVisualizer(){
            $.ajax({
                type: "POST",
                url: "{{ url('admin/add-new-visualizer/save') }}",
                data: new FormData($('#frm_addnew_visualizer')[0]),
                processData: false,
                contentType: false,
                dataType: 'json',
                beforeSend: function(xhr){
                    $("#submitTemplateBtn").attr('disabled', true);
                    $("#submitTemplateBtn").html('<i class="fa fa-spinner fa-spin"></i> Saving...');

                    var token = $('meta[name="csrf_token"]').attr('content');
                    
                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }

                },

                success: function (response) {
                    console.log(response)
                    if(response.success){
                        alert(response.message);
                        location.reload();
                    }
                }
            });
            return false;
        }

        function submitFormEditVisualizer(){
            $.ajax({
                type: "POST",
                url: "{{ url('admin/visualizer/update') }}",
                data: new FormData($('#frm_edit_visualizer')[0]),
                processData: false,
                contentType: false,
                dataType: 'json',
                beforeSend: function(xhr){
                    $("#submitTemplateBtn").attr('disabled', true);
                    $("#submitTemplateBtn").html('<i class="fa fa-spinner fa-spin"></i> Saving...');

                    var token = $('meta[name="csrf_token"]').attr('content');
                    
                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }

                },

                success: function (response) {
                    console.log(response)
                    if(response.success){
                        alert(response.message);
                        location.reload();
                    }
                }
            });
            return false;
        }

        function submitFormUploadPrintFiles(){
            $.ajax({
                type: "POST",
                url: "{{ url('admin/upload-print-file/save') }}",
                data: new FormData($('#frm_upload_print_files')[0]),
                processData: false,
                contentType: false,
                dataType: 'json',
                beforeSend: function(xhr){
                    $("#submitSaveBtn").attr('disabled', true);
                    $("#submitSaveBtn").html('<i class="fa fa-spinner fa-spin"></i> Saving...');

                    var token = $('meta[name="csrf_token"]').attr('content');
                    
                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }

                },

                success: function (response) {
                    console.log(response)
                    if(response.success){
                        alert(response.message);
                        location.reload();
                    }
                }
            });
            return false;
        }

        function submitFormCreateStore(){
            $.ajax({
                type: "POST",
                url: "{{ url('admin/create-store/save') }}", // admin/sports/save
                data: new FormData($('#frm_create_store')[0]),
                processData: false,
                contentType: false,
                dataType: 'json',
                beforeSend: function(xhr){
                    $("#btn_save_new_store").attr('disabled', true);
                    $("#btn_save_new_store").html('<i class="fa fa-spinner fa-spin"></i> Saving...');

                    var token = $('meta[name="csrf_token"]').attr('content');
                    
                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }

                },

                success: function (response) {
                    if(response.success){
                        $('#create_store_msg').html('<div class="alert alert-success alert-dismissible"> ' +
                                                    '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' +
                                                    '<h4><i class="icon fa fa-check"></i> Success!</h4> ' +
                                                    '<p>'+response.message+'</p> ' +
                                                    '</div>').fadeIn().delay(5000).fadeOut();

                    }else{
                        $('#create_store_msg').html('<div class="alert alert-danger alert-dismissible"> ' +
                                                    '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' +
                                                    '<h4><i class="icon fa fa-ban"></i> Error!</h4> ' +
                                                    '<p>'+response.message+'</p> ' +
                                                    '</div>').fadeIn().delay(5000).fadeOut();
                    }

                    $("html, body").animate({ scrollTop: 0 }, "slow");
                    $("#btn_save_new_store").attr('disabled', false);
                    $("#btn_save_new_store").html('Save');

                    if(response.clearform){
                        var form = $('#frm_create_store')
                        form.validate().resetForm();
                        form[0].reset();

                        // $("#with_password_opt").prop("checked", false);

                        $('.img_store_logo_href').attr('href', "{{ minio_url('uploads/images/teamstore/')  . 'store-logo-placeholder.jpg' }}");
                        $('.img_store_logo_img').attr('src', "{{ minio_url('uploads/images/teamstore/')  . 'store-logo-placeholder.jpg' }}");

                        $('.img_store_banner_href').attr('href', "{{ minio_url('uploads/images/teamstore/')  . 'store-banner-placeholder.jpg' }}");
                        $('.img_store_banner_img').attr('src', "{{ minio_url('uploads/images/teamstore/')  . 'store-banner-placeholder.jpg' }}");
                    }
                }
            });
            return false;
        }

        function submitFormEditStore(){
            $.ajax({
                type: "POST",
                url: "{{ url('admin/store/update') }}", // admin/sports/save
                data: new FormData($('#frm_edit_store')[0]),
                processData: false,
                contentType: false,
                dataType: 'json',
                beforeSend: function(xhr){
                    $("#btn_update_store").attr('disabled', true);
                    $("#btn_update_store").html('<i class="fa fa-spinner fa-spin"></i> Saving...');

                    var token = $('meta[name="csrf_token"]').attr('content');
                    if (token) {
                        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                    }

                },
                success: function (response) {
                    // console.log(response);
                    if(response.success){
                        $('#edit_store_msg').html('<div class="alert alert-success alert-dismissible"> ' +
                                                    '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' +
                                                    '<h4><i class="icon fa fa-check"></i> Success!</h4> ' +
                                                    '<p>'+response.message+'</p> ' +
                                                    '</div>').fadeIn().delay(5000).fadeOut();

                    }else{
                        $('#edit_store_msg').html('<div class="alert alert-danger alert-dismissible"> ' +
                                                    '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ' +
                                                    '<h4><i class="icon fa fa-ban"></i> Error!</h4> ' +
                                                    '<p>'+response.message+'</p> ' +
                                                    '</div>').fadeIn().delay(5000).fadeOut();
                    }

                    $("html, body").animate({ scrollTop: 0 }, "slow");
                    $("#btn_update_store").attr('disabled', false);
                    $("#btn_update_store").html('Save Changes');

                    if(response.clearform){
                        var form = $('#frm_edit_store')
                        form.validate().resetForm();
                        form[0].reset();

                        // $("#with_password_opt").prop("checked", false);

                        $('.img_store_logo_href').attr('href', "{{ minio_url('uploads/images/teamstore/')  . 'store-logo-placeholder.jpg' }}");
                        $('.img_store_logo_img').attr('src', "{{ minio_url('uploads/images/teamstore/')  . 'store-logo-placeholder.jpg' }}");

                        $('.img_store_banner_href').attr('href', "{{ minio_url('uploads/images/teamstore/')  . 'store-banner-placeholder.jpg' }}");
                        $('.img_store_banner_img').attr('src', "{{ minio_url('uploads/images/teamstore/')  . 'store-banner-placeholder.jpg' }}");
                    }
                }
            });
            return false;
        }

        function readURL(input, id) {
            console.log(input, id)
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    $('#'+id).attr('src', e.target.result);
                    $('.'+id+'_href').attr('href', e.target.result);
                    $('.'+id+'_img').attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        function readURLVisualizer(input, id) {
            console.log(input, id)
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    // $('.'+id+'_href').removeData('data-visualizer');
                    $('.'+id+'_href').attr('data-visualizer', e.target.result);
                    // console.log(e.target.result);
                    // document.getElementById('.'+id+'_href').setAttribute('data', $(this).data('visualizer'))
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        function submitForm_frm_tag_user_as_store_owner (){
            var data = $("#frm_tag_user_as_store_owner").serialize();
            $.ajax({
                type : 'POST',
                url  : "{{ url('admin/post/update-user-as-store-owner') }}",
                data : data,
                beforeSend:function(xhr){
                    var token = $('meta[name="csrf_token"]').attr('content');

                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                        xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                },
                success :  function(response){ 
                    if(response.result){
                        alert("User is successfully add as Store Owner.");
                        location.reload();
                    }else{
                        alert("Something went wrong. Please try again!");
                        location.reload();
                    }
                }
            });
            return false;
        }

        function submitForm_frm_create_user_as_store_owner(){
            var data = $("#frm_create_user_as_store_owner").serialize();

            $.ajax({
                type : 'POST',
                url  : "{{ url('admin/post/save-new-store-owner') }}",
                data : data,
                beforeSend:function(xhr){
                    var token = $('meta[name="csrf_token"]').attr('content');

                        if (token) {
                            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
                        }
                        xhr.setRequestHeader( 'X-Requested-With',  'XMLHttpRequest');
                },
                success :  function(response){ 
                    // console.log(response)
                    if(response.success){
                        alert("User is successfully add as Store Owner.");
                        location.reload();
                    }else{
                        $('#add_user_msg').html(response.message);
                        // location.reload();
                    }
                }
            });
            return false;
        }
    </script>
</body>
</html>