var chatbox = {
    //Total possible boxes
    tBoxes : 3,

    //boxes
    boxes : [],

    //chatboxes container
    container : '',

    //cached emoticons
    emoticons : '',

    checking : false,

    init : function() {
        w = $(document).width();
        if (w > 500 && w < 800) {
            this.tBoxes = 1;
        } else if(w < 500) {
            this.tBoxes = 0;

        }

    },

    keepChecking : function() {
        setInterval(function() {
            if (chatbox.boxes.length > 0 && !chatbox.checking) {
                chatbox.checking = true;
                ids = [];
                for(i=0;i < chatbox.boxes.length; i++){
                    var userid = chatbox.boxes[i];
                    var hisChatbox = $('#chatbox-' + userid);
                    var lastcheck = (hisChatbox.data('lastcheck') == undefined) ? 0 : hisChatbox.data('lastcheck')
                    ids[i] = [userid, lastcheck]
                }

                $.ajax({
                    url : baseUrl + 'chatbox/check',
                    type : 'POST',
                    data : {ids : ids},
                    success : function(data) {
                        chatbox.checking = false;
                        var data = jQuery.parseJSON(data);
                        var needAlert = false;
                        $.each(data, function(i, e) {
                            var userid = e.userid;
                            var lastcheck = e.lastcheck;
                            var messages = e.messages;
                            var typing = e.typing;
                            var status = e.status;
                            var hisChatbox = $("#chatbox-" + userid);
                            var messagesContainer = hisChatbox.find('.chatbox-messages');
                            var boxTitle = hisChatbox.find('.head').find('.name');

                            if (status == 0) {
                                boxTitle.find('i').hide();
                            } else {

                                boxTitle.find('i').show();
                            }

                            if (!boxTitle.find('span').length) {
                                if (typing == 1) {
                                    boxTitle.append('<span> typing...</span>');
                                } else {
                                    boxTitle.find('span').remove();
                                }
                            } else {
                                if (typing == 0) boxTitle.find('span').remove();
                            }

                            hisChatbox.data('lastcheck', lastcheck);
                            messagesContainer.append(messages);
                            if (messages != '') {
                                needAlert = true;
                                chatbox.scrollDown(messagesContainer);
                            }
                        });
                        //on every check we make sure our chat online lists is update
                        if (!document.hasFocus() && needAlert) {

                            document.getElementById('update-sound').play();
                        }
                    }
                })
            }
        }, chatboxspeed);

    },

    //refresh chat list
    refreshChatList : function() {
        var container = $('.chat-list');
        $.ajax({
            url : baseUrl + 'messages/online',
            success : function(data) {
                container.html(data);
            }
        });
    },

    canCreate : function() {
        if (this.tBoxes > 0) return true;

        return false;
    },

    create : function(id, name, link) {

        if (jQuery.inArray(id, this.boxes) != -1) {
            //this.show(id);
            //alert('this is twalo');
        } else {
            if (this.boxes.length < this.tBoxes) {
                this.boxes.push(id);
                this.__create(id, name, link);
            } else {

                var lastIndex = this.boxes[this.boxes.length - 1];

                if (lastIndex != id) {



                    this.destroy($('#chatbox-' + lastIndex),lastIndex);
                    this.boxes.push(id);
                    this.__create(id, name, link);
                }
            }


        }
    },

    scrollDown : function(o) {
        //alert(o.prop('scrollHeight'));
        o.animate({ scrollTop: o.prop('scrollHeight')}, 1000);
    },

    __create : function(id, name, link) {


        var uniqueId = 'chatbox-' + this.boxes.length;

        var c = $("<div class='chatbox "+uniqueId+"' id='chatbox-"+id+"'></div>");
        c.append("<div class='head'><a class='name' data-ajaxify='true' href='"+link+"'><i class='icon ion-record' style='color: #26C281;font-size: 11px'></i> "+name+" </a> <span class='pull-right'><a class='minimize' href=''><i class='icon ion-minus'></i></a> <a class='delete' href=''><i class='icon ion-close'></i></a></span></div> ");

        c.append("<div class='chatbox-messages clearfix'></div>");
        var emoIcon = baseUrl + 'app/Addons/Chatbox/assets/images/emoticon.png';
        c.append('<form action="" enctype="multipart/form-data"><input autocomplete="off" name="text" type="text" placeholder="Send a message"/><div class="emoticons-container"></div> <a href="" class="emoticon-trigger"><img src="'+emoIcon+'"/></a> <span style="position:relative;top: 10px; overflow: hidden;display: inline-block"   class=" fileupload fileupload-exists" data-provides="fileupload"><a   class="btn-file"><span class="fileupload-new"><i class="icon ion-android-camera"></i></span><span class="fileupload-exists"><i class="icon ion-android-camera"></i></span><input   class="" type="file" name="image"></a></span></form></div>');

        $('body').append(c);

        //load there old conversions in
        var chatMessages = c.find('.chatbox-messages');
        $.ajax({
            url : baseUrl + 'chatbox/load/old?userid=' + id,
            success : function(data) {
                chatMessages.html(data);
                //correct time
                $('.post-time span').timeago();
                chatbox.scrollDown(chatMessages);

                reloadPlugins();
            }
        });

        //attach event to this chat messages container when the scroll is about to reach top to load old messages
        chatMessages.scroll(function() {
            var cM = $(this);
            var scrTop = $(this).prop('scrollTop');
            if (scrTop == 0) {
                //load old messages
                if ($(this).attr('old-finish') == undefined && cM.attr('old-working') == undefined){
                    var offset = (cM.attr('offset') == undefined) ? 0 : cM.attr('offset');
                    $.ajax({
                        url : baseUrl + 'chatbox/load/older?userid=' + id + '&offset=' + offset,
                        success : function(data) {
                            var data = jQuery.parseJSON(data);

                            if (data.content != '') {
                                chatMessages.prepend(data.content).attr('offset', data.offset);

                                reloadPlugins();
                            } else {
                                cM.attr('old-finish', 'true');
                            }

                            //cM.removeAttr('old-working').animate({ scrollTop: 160}, 1000);
                        }
                    });
                }

            }
        });
        //attach event to minimize button
        c.find('.minimize').click(function() {
            chatbox.minimize(c);
            return false;
        });

        //attach event to close button
        c.find('.delete').click(function() {
            chatbox.destroy(c, id);
            return false;
        });


        //attach event to emoticon trigger
        c.find('.emoticon-trigger').click(function() {
            var emoContainer = c.find('.emoticons-container');

            if (emoContainer.html() == '') {
                if (chatbox.emoticons == '') {
                    //load the emoticon in
                    $.ajax({
                        url : baseUrl + 'chatbox/load/emoticon',
                        success : function(data) {
                            chatbox.emoticons = data;
                            emoContainer.html(data);
                        }
                    });
                }

                emoContainer.html(chatbox.emoticons);
            }

            if (emoContainer.css('display') == 'none') {
                emoContainer.slideDown('slow');

            } else {
                emoContainer.slideUp('slow');
            }
            return false;
        });

        //if user has started type lets update user that is typing
        c.find('form').find('input[type=text]').keyup(function() {
           if ($(this).data('typing') == undefined || $(this).data('typing') == '0') {
               if ($(this).val() != '') {
                   $(this).data('typing', 1);
                   $.ajax({
                       url : baseUrl + 'chatbox/typing',
                       data : {id : id}
                   });
               }
           }
        }).focusout(function() {
            $(this).data('typing', 0);
            $.ajax({
                url : baseUrl + 'chatbox/offtyping',
                data : {id : id}
            });
        });

        //attach event to sending message
        c.find('form').submit(function(e) {
            e.preventDefault();

            //to prevent multiple send message

            var tf = $(this);
            var input = tf.find('input[type=text]');
            var fI = tf.find('input[type=file]');
            var iV = input.val();
            var hasAttach = false;

            //if both textfield and image field is empty return false
            if (input.val() == '' && fI.val() == '') return false;

            var m = $("<div class='message pull-right'><span class='content'></span><span class='arrow-right'></span></div>");
            m.find('.content').html(iV);
            chatMessages.append(m);
            if (fI.val() != '') {
                //tf.css('opacity', '0.6');
                hasAttach = true;
                var sImage = $("<div style='margin: 5px 2px;color: #808080'>Sending image..</div>");
                m.find('.content').append(sImage);
            }

            chatbox.scrollDown(chatMessages);


            $.ajax({
                url : baseUrl + 'chatbox/send?userid=' + id,
                type : 'POST',
                data : new FormData(this),
                contentType : false,
                cache : false,
                processData : false,
                success : function(data) {
                    //tf.css('opacity', 1);
                    //remove typing event from the input
                    input.data('typing', '0');
                    m.find('.content').html(data);

                    if (hasAttach) {

                        sImage.remove();
                    }
                    reloadPlugins();
                    chatbox.scrollDown(chatMessages);

                }
            });
            input.val('');
            fI.val('');
        })


    },

    ensureContainerCreated : function() {

        if (!$('#chatbox-container').length) {
            $('body').append($('<div id="chatbox-container"></div>'))
            this.container = $('#chatbox-container');
        }
    },

    minimize : function(c) {
        var m = c.find('.chatbox-messages');
        var f = c.find('form');

        if (m.css('display') == 'none') {
            m.slideDown();
            f.slideDown();
        } else {
            m.slideUp();
            f.slideUp();

        }
    },

    destroy : function(c, id) {

        var index = this.boxes.indexOf(id);
        c.remove();
        this.boxes.splice(index, 1);
        this.reposition();

    },

    reposition : function() {
        for(i = 1;i <= this.boxes.length; i++) {
            var index = i - 1;
            var chatbox = $('#chatbox-' + this.boxes[index]);
            chatbox.removeClass('chatbox-1 chatbox-2 chatbox-3').addClass('chatbox-' + i);

        }
    }
};

$(function() {

    //initiate chatbox
    chatbox.init();
    chatbox.refreshChatList();

    chatbox.keepChecking();

    setInterval(function() {
        chatbox.refreshChatList();
    }, 60000)

    //attach event to each emoticon
    $(document).on('click', '.chatbox-emoticon-selector', function() {
        var emoCode = $(this).data('code');
        var p = $(this).parent().parent();
        var input = p.find('input[type=text]');

        input.select().val(input.val() + ' ' + emoCode + ' ').focus();
        $(this).parent().fadeOut();
        return false;
    });

    $(document).on('click', '.chat-list a', function() {
        //ensure initiation of chatbox chat
        chatbox.init();

        if(!chatbox.canCreate()) return true;

        chatbox.create($(this).data('userid'), $(this).data('name'), $(this).data('link'));
        return false;
    });

    $(document).on('click', '.message-dropdown-link', function() {
        //ensure initiation of chatbox chat
        chatbox.init();
        $('.message-dropdown').fadeOut();
        if(!chatbox.canCreate()) return true;

        chatbox.create($(this).data('userid'), $(this).data('name'), $(this).data('link'));

        return false;
    });


});