var Notifier;
function NotifierClass() {
    var box = jQuery("#js-message");

    function _show(msg) {
        if (msg.length > 200)
            msg = "Internal Server Error";
        box.empty();
        box.append("<div>" + msg + "</div>");
        box.show();
        setTimeout(function() {
            box.hide()
        }, 5000);
    }

    this.info = function(msg) {
        box.attr('class', 'info');
        _show(msg);
    };

    this.warn = function(msg) {
        box.attr('class', 'warning');
        _show(msg);
    };

    this.error = function(msg) {
        box.attr('class', 'error');
        _show(msg);
    };
}


function msgKey(threadKey) {
    return "message|" + threadKey;
}

function retrieveMessage(key) {
    return localStorage.getItem(msgKey(key));
}

function saveMessage(key, msg) {
    localStorage.setItem(msgKey(key), msg);
}

function toggleName(el, name) {
    if (el.attr('name') == "")
        el.attr('name', name)
    else
        el.attr('name', '');
}

var uploader;
function createEditPane(form, elementName, files) {
    var mtext = $('textarea', form);
    var markedUp = mtext.markItUp(mySettings);
    $('.preview').click(function() {
        $.markItUp({target: "textarea", call: 'preview'});
    });

    if (elementName != null) {
        uploader = new qq.FileUploader({
            template: '<ul class="qq-upload-list"></ul>' +
                    '<div class="qq-upload-button"></div>',
            fileTemplate: '<li><span class="qq-upload-file" name="file" spellcheck="false"></span>' +
                    '<span class="qq-upload-spinner"></span>' +
                    '<span class="qq-upload-size"></span>' +
                    '<a class="qq-upload-cancel" href="#">Cancel</a>' +
                    '<span class="qq-upload-failed-text">Failed</span></li>',
            element: document.getElementById(elementName),
            action: 'upload.view',
            multiple: false,
            sizeLimit: 10 * 1024 * 1024,
            onComplete: function(id, fileName, responseJSON) {
                $('input:submit').removeAttr('disabled');
                if (responseJSON.success)
                    $("li span:contains(" + fileName + "):last").
                            before('<input type="checkbox" name="files" class="file" checked="true" value="' + responseJSON.fileName + '">').
                            val(responseJSON.fileName);
            },
            onSubmit: function(id, fileName) {
                $('input:submit').attr('disabled', 'disabled');
                setTimeout(function() {
                    $('.markItUpHeader').append($("input[type='file']").detach());
                }, 80);
            },
            onCancel: function(id, fileName) {
                $('input:submit').removeAttr('disabled');
            }
        });

        window.setTimeout(function() {
            $('.markItUpHeader').append($("input[type='file']").detach())
            addFiles(files);
        }, 100);
    } else {
        $('#markItUpMtext').after('<br>');
    }
}

function addFiles(files) {
    if (files) {
        var list = $("ul.qq-upload-list");
        $.each(files, function() {
            list.append('<li><input type="checkbox" name="files" class="file" checked="true" value="' + this.name +
                    '"><span class="qq-upload-file" spellcheck="false">' + this.fileName + '</span><span class="fileSize">' + this.size +
                    '</span></li>')
        });
    }
}

var editStack = {edited: false};
function editMessage(msgO) {
    var td = $("#" + msgO + " > td.messageTD");
    $.getJSON("message.view", {msg: msgO}, function(data) {
        var editForm = $("form").detach();
        if (editStack.edited) {
            var oldTD = $("#" + editStack.lastMsg + " > td.messageTD");
            oldTD.html(editStack.html);
        }
        editStack.html = td.html();
        editStack.lastMsg = msgO;
        editStack.edited = true;
        editForm.appendTo(td.empty());

        $('textarea').val(data.text);
        var fileList = $("ul.qq-upload-list").empty();
        addFiles(data.files);

        $("iframe").remove();
    })
}

function clearState() {
    if (editStack.edited) {
        var editForm = $("form").detach();
        editForm.appendTo($('#newMessage > td.messageTD'));
        $("#" + editStack.lastMsg + " > td.messageTD").html(editStack.html);
        editStack.edited = false;
        $('textarea').text('');
        $("ul.qq-upload-list").empty();
    }
}

var title;
//var entered = false;
var unreadMessages;
var showedNotification;
function getNotifications(daemon) {
    if (daemon) setTimeout(getNotifications, 15000, true);

    return $.getJSON("countNotifications", {},
                    function(data) {
                        $("#menu-unread:hidden").remove(); //delete old menu;
                        $('#notifications > ul:hidden').remove();

                        var all = data.length;
                        var keyToMsg = new Object();
                        var newUnread = new Array();
                        $.each(data, function() {
                            keyToMsg[this.forum] = keyToMsg[this.forum] === undefined ? 1 : keyToMsg[this.forum] + 1;
                            keyToMsg[this.thread] = keyToMsg[this.thread] === undefined ? 1 : keyToMsg[this.thread] + 1;
                            newUnread.push(this.msg);
                        });

                        $.each(keyToMsg, function(key, value) {
                            var tr = $("#" + key + ", ." + key);
                            if (value > 0)
                                $('.NEW', tr).show().text(value);
                        });

                        if (all > 0) {
                            if (daemon && unreadMessages !== undefined && window.webkitNotifications.checkPermission() == 0) {
                                var notification;
                                var msg;
                                for (var i = 0; i < newUnread.length; i++) {
                                    if (unreadMessages.indexOf(newUnread[i]) == -1) {
                                        msg = newUnread[i];
                                        var url = "desktop-notification.jsp?msg=" + msg + "&window=" + window.name;
                                        var msgUrl = "show-message.jsp?msg=" + msg + "&window=" + window.name;
                                        ;
                                        notification = webkitNotifications.createHTMLNotification(url);
                                        notification.onclick = function(event) {
                                            console.log(event);
                                            window.open(msgUrl, '_self', '');
                                            notification.cancel();
                                        }
                                    }
                                }

                                if (notification) {
                                    if (showedNotification) showedNotification.cancel();
                                    showedNotification = notification;
                                    if (! localStorage.getItem(msg)) {
                                        localStorage.setItem(msg, 'showed');
                                        showedNotification.show();
                                    }
                                }
                            }
                            $('.unreadCount').text(all).show();
                            document.title = "(" + all + ") " + title;
                        } else {
                            $('.unreadCount, .NEW').hide();
                            document.title = title;
                        }
                        unreadMessages = newUnread;
                    }).error(function(x, event, settings) {
//        event.stopPropagation();
    })
}

jQuery(document).ready(function($) {
    Notifier = new NotifierClass();


    title = document.title;
    $.ajaxSetup({
        type: "POST",
        global: true,
        cache: false,
        error: function(jqXHR, status, error) {
            var msg = $($(jqXHR.responseText).find('u')[0]).text();
            Notifier.error(msg);
        }
    });


    /*$(document).ajaxError(function(x, event, settings) {
     var msg = $('#msg').empty();
     msg.append("Sorry, there was an error");
     msg.show(220);
     setTimeout("jQuery('#msg').hide(220)", 3000);
     });*/


    var listUrneadFocused = false;
    $(".listUnread").hover(function(e) {
        var el = $(e.target).closest('.listUnread');
        var key = el.data('forum') + el.data('thread');
        var ul = $("#menu-unread");
        if (ul.length == 0 || ul.data('key') != key) {
            ul.remove();
            ul = $("<ul id='menu-unread' class='menu'><li>Loading...</li></ul>");
            ul.hover(
                    function(e) {
                        listUrneadFocused = true;
                        e.stopPropagation()
                    },
                    function(e) {
                        listUrneadFocused = false
                    }
                    );

            el.append(ul);
            ul.data('key', key);
            $.getJSON("listUnread", {forum: el.data('forum'), thread: el.data('thread')}, function(data) {
                ul.empty();
                var textLength = 40;
                if (data.length > 0) {
                    $.each(data, function(key, o) {
                        var text = o.text;
                        if (!text)
                            text = '(пустое сообщение)'
                        else if (text.length > textLength)
                            text = text.substr(0, textLength) + "...";
                        ul.append('<li><a href="show-message.jsp?msg=' + encodeURIComponent(o.name) + '">'
                                + text + '</a></li>')
                    })
                } else
                    ul.append('<li>Нет новых сообщений</li>');
            });
        }

        var elPos = el.position();
        elPos.left -= 12;
        elPos.top += 2;
        ul.css(elPos);
        ul.show();

    }, function(e) {
        setTimeout(function() {
            if (!listUrneadFocused) $("#menu-unread").hide()
        }, 200);
    });


    $('#notifications').hover(function() {
        var ul = $('#notifications > ul');
        if (ul.length == 0) {
            var markAll = $('<li><a style="width:100px; margin-left:auto; margin-right:auto" href="#">mark all as read</a></li>');
            markAll.click(function() {
                if (window.confirm("Отметить все новые сообщения как прочитанные?")) {
                    $.get("notifications.jsp?all=true", {}, function() {
                        document.title = title;
                        $(".NEW").hide();
                        $('#notifications').trigger('mouseleave');
                    })
                }
            });

            ul = $("<ul><li>Loading...</li></ul>").appendTo('#notifications');
            $.getJSON("listUnread", {}, function(data) {
                ul.empty();
                if (data.length > 0) {
                    $.each(data, function(key, o) {
                        var text = $("<div>" + o.text + "</div>").text()
                        if (text.length > 21)
                            text = text.substr(0, 21) + "...";
                        ul.append('<li><a class="text" title="перейти" href="show-message.jsp?msg=' + encodeURIComponent(o.name) + '">'
                                + text + '</a></li>')
                    })
                    ul.append(markAll);
                } else
                    ul.append('<li><a class="normal">Нет новых сообщений</span></a></li>');
            });
        }
        ul.show();
    }, function() {
        $('#notifications > ul').hide();
    });


    //------ for adding/removing tags---------//

    function addTag(el, tag) {
        var tr = el.closest('tr').attr('id');
        var liInput = el.closest('li');
        return $.getJSON('tagTree.view', {action: "addObjectTag", object: tr, oName: tag},
                        function(data) {
                            var li = el.closest("ul").find('li.template').clone().removeClass('template');
                            var tag = data[0].tag;
                            li.find('.span-tag-text').text(tag.name);
                            li.data('id', tag.oName)
                            liInput.before(li);
                            el.val('');
                        });
    }

    $(".input-tag").keypress(function(event) {
        if (event.which == 13) {
            var el = $(this);
            addTag(el, el.val());
        }

    });

    $(".input-tag").each(function() {
        var _this = $(this);
        _this.autocomplete({
            source: "autocomplete.view",
            source: function(request, response) {
                request.object = _this.closest('tr').attr('id');
                $.getJSON("autocomplete.view", request, function(data, status, xhr) {
                    response(data);
                })
            },
            minLength:2,
            select: function(event, ui) {
                addTag($(this), ui.item.tagName);
            }
        }).data( "autocomplete" )._renderItem = function( ul, item ) {
            var parentsToStr = function (arr){
                var str = '';
                for (var i = arr.length - 1; i > 0; i--){
                    if (str.length > 0)
                        str += " &rarr; ";
                    str += JSON.parse(arr[i]).value;
                }
                return str;
            };

			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a><div class='tag-label'>" + item.label + "</div><div class='tag-path'>" + parentsToStr(item.parents) + "</div></a>" )
				.appendTo( ul );
		};
    });

    $(document).delegate('.span-right', 'click', function(event) {
        var li = $(event.target).closest('li');
        var tr = li.closest('tr');
        $.getJSON('tagTree.view', {action: "deleteObjectTag", object: tr.attr('id'), oName: li.data('id')},
                 function(data) {
                     li.remove();
                 });
    });

});

