jQuery(document).ready(function() {
    $('#text-custom-trigger').emojiPicker({
        width: '320px',
        height: '200px',
        button: false
    });
    $('#chat_name').editable();
    $('#toggle').click(function(e) {
        e.preventDefault();
        $('#text-custom-trigger').emojiPicker('toggle');
    });
    $(document).on("click", ".decision-request-create", function() {
		alert();
	});
    $(document).on("click", ".decision-yes", function() {
		var message_id = $('.warehouse-arrangement').data('message_id');
		var decision = "1";
		var dataStringg = 'decision=' + decision + '&message_id=' + message_id;
		$.ajax({
            type: "POST",
            url: "/messenger/order/decision-request-update",
            cache: false,
            data: dataStringg,
            success: function(data) {
                location.reload();
            }
        });
	 
	});
    $(document).on("click", ".decision-no", function() {
		var message_id = $('.warehouse-arrangement').data('message_id');
		var decision = "2";
		var dataStringg = 'decision=' + decision + '&message_id=' + message_id;
		$.ajax({
            type: "POST",
            url: "/messenger/order/decision-request-update",
            cache: false,
            data: dataStringg,
            success: function(data) {
                location.reload();
            }
        });
	 
	});
    $(document).on("click", ".decision-request-details", function() {
		var group_id = $('#chats').data('group_id');
		var decision = $(this).data('decision');
		var id = $(this).data('id');
		var message_id = $(this).data('message_id');
		if(group_id == 1){
			if(decision == 1){
			$('#decision-request-action').html("Your importer have agree to <span class='font-green-meadow bold'>accept</span> this decision request");
			}else if(decision == 2){
				$('#decision-request-action').html("Your importer have agree to <span class='font-red bold'>decline</span> this decision request");
			}
		}else{
			if(decision == 1){
			$('#decision-request-action').html("You have agree to <span class='font-green-meadow bold'>accept</span> this decision request");
			}else if(decision == 2){
				$('#decision-request-action').html("You have agree to <span class='font-red bold'>decline</span> this decision request");
			}
		}
		
		var dataStringg = 'id=' + id + '&message_id=' + message_id;
		$.ajax({
            type: "POST",
            url: "/messenger/order/get-warehouse-arrangement",
            cache: false,
            data: dataStringg,
            success: function(data) {
                $("#getCode4").html(data);
                jQuery("#decision-request-details").modal('show');
            }
        });
    });
    $(document).on("click", ".previewPL", function() {
        var id = $(this).data('order_id');
        var dataStringg = 'id=' + id;
        $.ajax({
            type: "POST",
            url: "/shipping-order/get-packing-list",
            cache: false,
            data: dataStringg,
            success: function(data) {
                $("#getCode").html(data);
                jQuery("#previewPL").modal('show');
            }
        });
    });
    $(document).on("click", ".previewMarking", function() {
        var id = $(this).data('order_id');
        var dataStringg = 'id=' + id;
        $.ajax({
            type: "POST",
            url: "/shipping-order/get-marking",
            cache: false,
            data: dataStringg,
            success: function(data) {
                $("#getCode2").html(data);
                jQuery("#previewMarking").modal('show');
            }
        });
    });

});

var Script = function() {
    $(document).ready(function(e) {
		$(".menu-toggler").trigger('click');
		$(document).on("click", "#close_reply", function() {
			$("#reply_content").empty();
		});
		$(document).on("click", ".recall", function() {
			var reply_id = $(this).data("reply_id");
			var dataStringg = 'reply_id=' + reply_id;
			var first_name = $('#chats').data('first_name')
			$.ajax({
				type: "POST",
				url: "/messenger/recall",
				cache: false,
				data: dataStringg,
				success: function(data) {
					var recall_msg = first_name + " have recalled a message.";
					$('#chats li[data-id="'+reply_id+'"]').find(".mt-comment-text:first").html(recall_msg);						
					$('#chats li[data-id="'+reply_id+'"]').find(".mt-comment-text:last").html("");						
				}
			});
		});
		$(document).on("click", ".reply", function() {
			var reply_id = $(this).data("reply_id");
			var dataStringg = 'reply_id=' + reply_id;
			$.ajax({
				type: "POST",
				url: "/messenger/get-reply-content",
				cache: false,
				data: dataStringg,
				success: function(data) {
					$("#reply_content").html(data);
				}
			});
			
		});

        $('[data-toggle="popover"]').popover({})
        $('.members').click(function(e) {
            $('body').toggleClass('page-quick-sidebar-open');
        });

        var cont = $('#chats');
        var list = $('.chats', cont);
        var form = $('.chat-form', cont);
        var input = $('input', form);
        var btn = $('.btn', form);
        var user_id = $('#chats').data('id');
        input.keypress(function(e) {
            if (e.which == 13) {
                var text = input.val();
                if (text.length == 0) {
                    return;
                }
                sendChat(text, user_id);
            }
        });

    });

    function sendChat(text, user_id) {

        var room_id = $('#general_content').data('room_id');
        if ($('#reply_chat').data('reply_id') != null || $('#reply_chat').data('reply_id') != "") {
			var reply_id = $('#reply_chat').data('reply_id');
			var dataStringg = 'user_id=' + user_id + '&text=' + text + '&room_id=' + room_id + '&reply_id=' + reply_id;
		}else{
			var dataStringg = 'user_id=' + user_id + '&text=' + text + '&room_id=' + room_id;
		}
        $.ajax({
            type: "POST",
            url: "/messenger/send-order",
            data: dataStringg,
            success: function(data) {
                var cont = $('#chats');
                var form = $('.chat-form', cont);
                var input = $('input', form);
                input.val('');
                var trimmed = $.trim(data);
                $("#general_content").append(trimmed);
                var getLastPostPos = function() {
                    var height = 0;
                    cont.find("li.out, li.in").each(function() {
                        height = height + $("#general_content").outerHeight()-100;
                    });

                    return height;
                }
				$("#reply_content").empty();
                cont.find('.scroller').slimScroll({
                    scrollTo: getLastPostPos()
                });
            }
        });
    }

    function startRefresh() {
        var id = 0;
        if ($('#general_content').is(':empty')) {
            var room_id = $('#general_content').data('room_id');
            var dataStringg = 'id=' + id + '&room_id=' + room_id;
        } else {
            id = $('ul#general_content').children('li').last().data('id');
            var room_id = $('#general_content').data('room_id');
            var last_date = $('.date:last').data('id');
            var dataStringg = 'id=' + id + '&last_date=' + last_date + '&room_id=' + room_id;
        }
        $.ajax({
            type: "POST",
            url: "/messenger/get-order",
            data: dataStringg,
            beforeSend: function() {
                $(".unread").remove();
            },
            success: function(data) {
                var trimmed = $.trim(data);
                var cont = $('#chats');
                var removeEmpty = trimmed.replace(/\s/g, '')
                $("#general_content").append(trimmed);
                if (removeEmpty.indexOf('li') > -1) {
                    var getLastPostPos = function() {
                        var height = 0;
                        cont.find("li.out, li.in").each(function() {
                            height = height + $("#general_content").outerHeight()-100;
                        });

                        return height;
                    }

                    cont.find('.scroller').slimScroll({
                        scrollTo: getLastPostPos()
                    });
                }
                setTimeout(startRefresh, 3000);
            }
        });

    };
    $(function() {
        startRefresh();
    });

}();
$().ready(function() {
    $('.modal.printable1').on('shown.bs.modal', function() {
        $('.modal-dialog', this).addClass('focused');
        $('body').addClass('modalprinter');

        if ($(this).hasClass('autoprint')) {
            window.print();
        }
    }).on('hidden.bs.modal', function() {
        $('.modal-dialog', this).removeClass('focused');
        $('body').removeClass('modalprinter');
    });
    $('.modal.printable2').on('shown.bs.modal', function() {
        $('.modal-dialog', this).addClass('focused');
        $('body').addClass('modalprinter');

        if ($(this).hasClass('autoprint')) {
            window.print();
        }
    }).on('hidden.bs.modal', function() {
        $('.modal-dialog', this).removeClass('focused');
        $('body').removeClass('modalprinter');
    });
    $('.add-member-save').click(function() {
		var dataString = $('#form-add-member').serialize();
		var checkedCount = $('input[id="user_ids"]:checked').length;
		if(checkedCount > 0){
			$.ajax({
				type: "POST",
				url: "/messenger/add-member",
				cache: false,
				data: dataString,
				success: function(data) {
					location.reload();
				}
			})
		}
    });	
    $('.add-member').click(function() {
		var room_id = $('#general_content').data('room_id');
        var dataStringg = 'room_id=' + room_id;
        $.ajax({
            type: "POST",
            url: "/messenger/get-staff",
            cache: false,
            data: dataStringg,
            success: function(data) {
                $("#getCode3").html(data);
                jQuery("#add-member").modal('show');
            }
        });
		
	});
    $('#pdf').click(function() {

        var pdf = new jsPDF('l', 'pt', 'a4');
        source = $('#packinglists')[0];

        specialElementHandlers = {
            '#bypassme': function(element, renderer) {
                return true
            }
        };

        margins = {
            top: 20,
            bottom: 60,
            left: 40,
            width: 2000
        };
        pdf.fromHTML(
            source,
            margins.left,
            margins.top, {
                'width': margins.width,
                'elementHandlers': specialElementHandlers
            },
            function(dispose) {
                pdf.save('Packing_List.pdf');
            }, margins);
    });
    $('#pdf2').click(function() {

        var pdf = new jsPDF('l', 'pt', 'a4');
        source = $('#markings')[0];

        specialElementHandlers = {
            '#bypassme': function(element, renderer) {
                return true
            }
        };

        margins = {
            top: 20,
            bottom: 20,
            left: 20,
            width: 2000
        };
        pdf.fromHTML(
            source,
            margins.left,
            margins.top, {
                'width': margins.width,
                'elementHandlers': specialElementHandlers
            },
            function(dispose) {
                pdf.save('Marking.pdf');
            }, margins);
    });

    $('#excel').click(function() {
        var htmls = "";
        var uri = 'data:application/vnd.ms-excel;base64,';
        var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
        var base64 = function(s) {
            return window.btoa(unescape(encodeURIComponent(s)))
        };

        var format = function(s, c) {
            return s.replace(/{(\w+)}/g, function(m, p) {
                return c[p];
            })
        };

        htmls = $('#packinglists').html()

        var ctx = {
            worksheet: 'Worksheet',
            table: htmls
        }


        var link = document.createElement("a");
        link.download = "Packing_List.xls";
        link.href = uri + base64(format(template, ctx));
        link.click();
    });
});

function submit_file() {
    var file_name = document.getElementById("file").files[0].name;
    var r = confirm("Are you sure you want to upload " + file_name);
    if (r == true) {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("file").files[0]);
        oFReader.onload = function(oFREvent) {

            $("#filesbase64").val(oFREvent.target.result);
            var file = encodeURIComponent($('#filesbase64').val());
            var mime = document.getElementById("file").files[0].type;
            var file_name = document.getElementById("file").files[0].name;
            var user_id = $('#chats').data('id');
            var room_id = $('#general_content').data('room_id');
            var dataStringg = 'user_id=' + user_id + '&room_id=' + room_id + '&mime=' + mime + '&file_name=' + file_name + '&file=' + file;

            $.ajax({
                type: "POST",
                url: "/messenger/send-file",
                data: dataStringg,
                success: function(data) {
                    var cont = $('#chats');
                    var form = $('.chat-form', cont);
                    var input = $('input', form);
                    input.val('');
                    var trimmed = $.trim(data);
                    $("#general_content").append(trimmed);
                    var getLastPostPos = function() {
                        var height = 0;
                        cont.find("li.out, li.in").each(function() {
                            height = height + $("#general_content").outerHeight()-100;
                        });

                        return height;
                    }

                    cont.find('.scroller').slimScroll({
                        scrollTo: getLastPostPos()
                    });
                }
            });

        }
    }
};

function submit_file2() {
    var file_name = document.getElementById("file2").files[0].name;
    var r = confirm("Are you sure you want to upload " + file_name);
    if (r == true) {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("file2").files[0]);
        oFReader.onload = function(oFREvent) {

            $("#filesbase64").val(oFREvent.target.result);
            var file = encodeURIComponent($('#filesbase64').val());
            var mime = document.getElementById("file2").files[0].type;
            var file_name = document.getElementById("file2").files[0].name;
            var user_id = $('#chats').data('id');
            var room_id = $('#general_content').data('room_id');
            var dataStringg = 'user_id=' + user_id + '&room_id=' + room_id + '&mime=' + mime + '&file_name=' + file_name + '&file=' + file;

            $.ajax({
                type: "POST",
                url: "/messenger/send-file",
                data: dataStringg,
                success: function(data) {
                    var cont = $('#chats');
                    var form = $('.chat-form', cont);
                    var input = $('input', form);
                    input.val('');
                    var trimmed = $.trim(data);
                    $("#general_content").append(trimmed);
                    var getLastPostPos = function() {
                        var height = 0;
                        cont.find("li.out, li.in").each(function() {
                            height = height + $("#general_content").outerHeight()-100;
                        });

                        return height;
                    }

                    cont.find('.scroller').slimScroll({
                        scrollTo: getLastPostPos()
                    });
                }
            });

        }
    }
};

function submit_file3() {
    var file_name = document.getElementById("file3").files[0].name;
    var r = confirm("Are you sure you want to upload " + file_name);
    if (r == true) {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("file3").files[0]);
        oFReader.onload = function(oFREvent) {

            $("#filesbase64").val(oFREvent.target.result);
            var file = encodeURIComponent($('#filesbase64').val());
            var mime = document.getElementById("file3").files[0].type;
            var file_name = document.getElementById("file3").files[0].name;
            var user_id = $('#chats').data('id');
            var room_id = $('#general_content').data('room_id');
            var dataStringg = 'user_id=' + user_id + '&room_id=' + room_id + '&mime=' + mime + '&file_name=' + file_name + '&file=' + file;

            $.ajax({
                type: "POST",
                url: "/messenger/send-file",
                data: dataStringg,
                success: function(data) {
                    var cont = $('#chats');
                    var form = $('.chat-form', cont);
                    var input = $('input', form);
                    input.val('');
                    var trimmed = $.trim(data);
                    $("#general_content").append(trimmed);
                    var getLastPostPos = function() {
                        var height = 0;
                        cont.find("li.out, li.in").each(function() {
                            height = height + $("#general_content").outerHeight()-100;
                        });

                        return height;
                    }

                    cont.find('.scroller').slimScroll({
                        scrollTo: getLastPostPos()
                    });
                }
            });

        }
    }
};

function downloadDataUrlFromJavascript(filename, dataUrl) {

    // Construct the a element
    var link = document.createElement("a");
    link.download = filename;
    link.target = "_blank";

    // Construct the uri
    link.href = dataUrl;
    document.body.appendChild(link);
    link.click();

    // Cleanup the DOM
    document.body.removeChild(link);
    delete link;
}