(function ($) {
    $.extend({
        plDashboard: function (options)
        {
            var defaults = {
                ws: '',
                rateUcItemURL: '',
                deleteConfirmMsg: '',
                deleteBtnText: '',
                cancelBtnText: '',
                saveBtnText: '',
                setReadURL: '',
                language: '',
                saveNoteURL: '',
                deleteNoteURL: '',
                deleteNoteConfirmMsg: '',
                viewAddressTxt: '',
                newAddressTxt: '',
                ajaxImportNumberURL: '',
                viewAddressURL: ''
            };

            options = $.extend({}, defaults, options);

            var docked = false;

            window.onscroll = function (e) {
                if ((window.pageYOffset > 200) && !docked) {
                    docked = true;
                    $("#ucNavbar").addClass("navbar-fixed-top");
                    $("#content").css("padding-top", "63px");
                } else if ((window.pageYOffset < 200) && docked) {
                    $("#ucNavbar").removeClass("navbar-fixed-top");
                    $("#content").css("padding-top", "20px");
                    docked = false;
                }
            };

            $("#ucDialInput").keypress(function (event) {
                if (event.which == 13) {
                    if (options.ws) {
                        var phoneNumber = $(this).val();
                        var callCommand = {
                            data: {
                                number: phoneNumber
                            },
                            name: "dialNumber",
                            type: "command",
                            uuid: "generate it later"
                        };
                        options.ws.command(callCommand);
                    } else {
                        console.log('ws not found');
                    }
                    event.preventDefault();
                }
            });

            $('.ucItemRating input').click(function () {
                ratingValue = $(this).val();
                icItemId = $(this).attr('name');
                $.post(options.rateUcItemURL,
                        {
                            rating: ratingValue,
                            itemId: icItemId
                        },
                function (data) {
                },
                        'json');
            });

            function toggleCallableBulkActions(element) {
                if (element.hasClass("open")) {
                    element.removeClass("open");
                } else {
                    element.addClass("open");
                }
            }

            $("html").click(function () {
                $(".callableBulk").removeClass("open");
            });

            $(document).on("click", ".callable", function (e) {

                var addressReference = $(this).attr("data-address-reference");
                if (addressReference) {
                    $(".callableBulk").attr("data-address-reference", addressReference);
                    $(".importNumber a").text(options.viewAddressTxt);
                } else {
                    $(".importNumber a").text(options.newAddressTxt);
                    $(".callableBulk").removeAttr("data-address-reference");
                }

                var addressType = $(this).attr("data-number-type");
                if (addressType === "fax") {
                    $(".callableBulk .sendFax").show();
                    $(".callableBulk .callableMakeCall").hide();
                } else {
                    $(".callableBulk .sendFax").hide();
                    $(".callableBulk .callableMakeCall").show();
                }

                var itemId = $(this).attr("data-ucitem-id");
                var number = $(this).attr("data-phone-number");
                $(".callableBulk").attr("data-phone-number", number);
                $(".callableBulk").attr("data-ucitem-id", itemId);
                $(".callableBulk").addClass("open");
                var position = $(this).offset();
                $(".callableBulk").offset({left: position.left, top: (position.top + 16)});
            });
            

            $("html").on("click", ".importNumber", function () {
                url = options.ajaxImportNumberURL;
                var addressReferecne = $(this).parent().parent().attr("data-address-reference");
                if (addressReferecne) {
                    var url = options.viewAddressURL;
                    var data = {addressReferecne: addressReferecne};
                    var success = function (data) {
                        window.location = data.url;
                    };
                    $.get(url, data, success, "json");
                } else {
                    settings = {
                        data: {
                            addressReferecne: addressReferecne,
                            itemId: $(this).parent().parent().attr("data-ucitem-id"),
                            number: $(this).parent().parent().attr("data-phone-number")
                        },
                        type: "POST"
                    };
                    $.ajax(url, settings).success(function (data) {
                        $(".modal-header h4").text(options.newAddressTxt);
                        $(".btn[data-translation-id|=" + options.saveBtnText + "]").text(options.saveBtnText);
                        $(".modal-body").html(data);
                        $(".modal").modal("show");
                    });
                }
            });




            $(document).on('click', '#ucItems a.delete', function () {
                if (!confirm(options.deleteConfirmMsg)) {
                    return false;
                }

                $.ajax({
                    type: 'POST',
                    url: $(this).attr('href'),
                    data: {}
                }).success(function () {
                    window.location.reload(false);
                });
                return false;
            });

            var currentAudio;
            var currentPlayer;
            var currentSlider;
            var draggingSlider = false;

            $('#ucItems').on("click", ".playPause", function () {
                var ucId = $(this).parent().data('uc-id');
                if (currentPlayer != undefined && currentPlayer.data('uc-id') != ucId) {
                    stopAudio(currentAudio, true);
                }

                if (currentAudio != undefined && !currentAudio.paused) {
                    pauseAudio(currentAudio);
                } else {
                    if (currentPlayer != undefined && currentPlayer.data('uc-id') == ucId) {
                        console.log('resume');
                    } else {
                        var audioElement = document.createElement('audio');
                        currentAudio = audioElement;
                        currentPlayer = $(this).parent();
                        addSlider(currentPlayer, currentAudio);

                        currentPlayer.find('a').each(function (id, el) {
                            appendSourceFromLink(el, currentAudio);
                        });
                    }
                    playAudio(currentAudio);
                }
            });

            function playAudio(audioEl) {
                currentAudio.play();

                currentPlayer.find('i').removeClass('icon-play');
                currentPlayer.find('i').addClass('icon-pause');

                $(currentAudio).bind("ended", function () {
                    stopAudio(currentAudio);
                });
                $(currentAudio).bind("timeupdate", function () {
                    updateTime(currentAudio);
                });
            }

            function stopAudio(audioEl, hide) {
                if (audioEl == undefined) {
                    console.log('bad audio element');
                    return false;
                }

                console.log(audioEl);
                audioEl.pause();
                audioEl.currentTime = 0;
                updateTime();

                currentPlayer.find('i').removeClass('icon-pause');
                currentPlayer.find('i').addClass('icon-play');

                if (hide == true) {
                    removeSlider();
                }
            }

            function pauseAudio(audioEl, hide) {
                if (audioEl == undefined) {
                    console.log('bad audio element');
                    return false;
                }

                console.log(audioEl);
                audioEl.pause();
                currentPlayer.find('i').removeClass('icon-pause');
                currentPlayer.find('i').addClass('icon-play');

                if (hide == true) {
                    removeSlider();
                }
            }

            function updateTime() {
                var time = formatTime(Math.floor(currentAudio.currentTime)) + ' / ' + formatTime(Math.floor(currentAudio.duration));
                currentPlayer.find('.duration').html(time);
                currentPlayer.find('input').val(currentAudio.currentTime);

                if (!draggingSlider) {
                    currentSlider.slider('value', currentAudio.currentTime);
                    currentSlider.slider("option", "max", currentAudio.duration);
                }

                var completed = currentAudio.currentTime / currentAudio.duration;
                if (completed == 1) {
                    markAsRead(currentPlayer.data('uc-id'));
                }
            }

            function markAsRead(id) {
                var url = options.setReadURL;
                url += '&id=' + id;

                $.post(url, {});
            }

            function seekAudio(element) {
                var targetTime = element.value;
                if (targetTime < currentAudio.duration) {
                    currentAudio.currentTime = targetTime;
                }
            }

            function formatTime(time) {
                var minutes = pad(Math.floor(time / 60));
                var seconds = pad(time - minutes * 60);

                return minutes + ':' + seconds;
            }

            function pad(n) {
                return (n < 10) ? ("0" + n) : n;
            }

            function appendSourceFromLink(link, audioEl) {
                var source = document.createElement('source');
                source.type = $(link).data('type');
                source.src = link.href;
                audioEl.appendChild(source);
            }

            function addSlider(player, audio) {
                currentSlider = $(player.find('.position .slider')).slider({
                    range: "min",
                    min: 1,
                    step: 0.1,
                    start: function () {
                        draggingSlider = true;
                    },
                    stop: function () {
                        draggingSlider = false;
                    },
                    change: function (event, ui) {
                        if (event.originalEvent) {
                            var targetTime = ui.value;
                            if (targetTime < currentAudio.duration) {
                                currentAudio.currentTime = targetTime;
                            }
                        }
                    }
                });
                currentSlider.parent().css({width: "200px"}).css({opacity: 1});
            }

            function removeSlider() {
                currentPlayer.find('.duration').html(formatTime(Math.floor(currentAudio.duration)));
                currentSlider.parent().css({width: "0px"}).delay(300).css({opacity: 0});
            }

            $(function () {
                $("#ucItems").on("click", ".editNote", function () {
                    var ucContent = $(this).closest('.ucContent').addClass('edit');
                    var noteEl = ucContent.find('.ucNote');

                    noteEl.redactor({
                        lang: options.language,
                        focus: true,
                        linebreaks: true,
                        buttons: [
                            'save',
                            'delete',
                            'cancel',
                            '|',
                            'bold',
                            'italic',
                            'deleted',
                            '|',
                            'unorderedlist',
                            'orderedlist',
                            'outdent',
                            'indent',
                            '|',
                            'link',
                            'alignment',
                            '|',
                            'horizontalrule'
                        ],
                        buttonsCustom: {
                            save: {
                                title: options.saveBtnText,
                                callback: function (buttonName, buttonDOM, buttonObject) {
                                    var html = this.get();
                                    var ucitem = buttonDOM.closest('.ucItem');
                                    var note = ucitem.find('.ucNote');
                                    var itemId = ucitem.data('id');

                                    $.ajax({
                                        type: "POST",
                                        url: options.saveNoteURL + '&id=' + itemId,
                                        data: {
                                            note: html
                                        },
                                        dataType: 'html'
                                    }).success(function (data) {
                                        if (html == '') {
                                            ucitem.find('.icon-trash').hide();
                                            ucitem.find('.removeNote').hide();
                                        } else {
                                            ucitem.find('.icon-trash').show();
                                            ucitem.find('.removeNote').show();
                                        }
                                        note.redactor('destroy');
                                        ucContent.removeClass('edit');
                                    });
                                }
                            },
                            delete: {
                                title: options.deleteBtnText,
                                callback: function (buttonName, buttonDOM, buttonObject) {
                                    var ucitem = buttonDOM.closest('.ucItem');
                                    var note = ucitem.find('.ucNote');
                                    var itemId = ucitem.data('id');
                                    $.ajax({
                                        type: "POST",
                                        url: options.deleteNoteURL + '&id=' + itemId,
                                        data: {},
                                        dataType: 'html'
                                    }).success(function (data) {
                                        note.redactor('destroy');
                                        note.html('');
                                        ucContent.removeClass('edit');
                                        ucitem.find('.removeNote').hide();
                                    });
                                }
                            },
                            cancel: {
                                title: options.cancelBtnText,
                                callback: function (buttonName, buttonDOM, buttonObject) {
                                    var oldHtml = this.content;
                                    this.destroy();
                                    this.$element.parent().find('.ucNote').html(oldHtml);
                                    ucContent.removeClass('edit');
                                }
                            }
                        }
                    });
                });

                $("#ucItems").on("click", ".removeNote", function () {
                    if (confirm(options.deleteNoteConfirmMsg)) {
                        var btn = $(this);
                        var ucitem = btn.closest('.ucItem');
                        var itemId = ucitem.data('id');

                        $.ajax({
                            type: "POST",
                            url: options.deleteNoteURL + '&id=' + itemId,
                            data: {},
                            dataType: 'html'
                        }).success(function (data) {
                            btn.hide();
                            ucitem.find('.ucNote').html('');
                        });
                    }
                });
            });
        }
    });
}(jQuery));