;
(function ($) {
    //requests font awesome css
    'use strict';
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
        }
        return "";
    }
    console.log("test");
    $.fn.impChat = function (options) {
        var chat = {},
            elm = this, 
            tagname = '',
            attr='',
            burl='http://app.impulsion.be/calls.php',
            init = function () {
                chat.tag=$();
                chat.settings ={
                    // GENERAL
                    user: "",
                    key: "",
                    lang: "",
                    theme: 'tc',
                    forcedialog: 0,
                    uri: "/"+window.location.pathname.substr(1),
                    uid: getCookie("chatImpUid")/*,
                    // CALLBACKS
                    onloaded: function () {

                    }*/
                };
                $.ajax({
                    type: 'post',
                    url: burl,
                    data: $.extend({}, chat.settings, {type:"impChatInit",user:chat.settings.user,lang:chat.settings.lang}),
                    dataType: "json",
                    crossDomain: true,
                    async:false,
                    success: function (response) {
                        //console.log(response);
                        //console.log(chat.settings.uid );
                        //console.log(response.uid);
                        //if(getCookie("chatImpUid")==""){
                            document.cookie="chatImpUid="+response.uid+"; path=/";
                            chat.settings.uid = getCookie("chatImpUid");
                        //};
                        chat.status=response.status;
                        if($(window).width()<425 && response.mobile==0){
                            chat.status=0;
                        }
                        if(chat.status==1){
                            chat.tag=$(response.html);
                            chat.stylesheet=response.stylesheet;
                            chat.css=$('<link href="'+response.stylesheet+'" rel="stylesheet" />');    
                            chat.settings.forcedialog=response.forcedialog;
                            chat.settings.forcedialogdelay=response.forcedialogdelay;
                            updateSession();
                            if(chat.settings.forcedialog){
                                setTimeout(forceDialog, chat.settings.forcedialogdelay);
                            }
                        }
                    },
                    error: function (c, o, n) {//gros
                        console.log(c);
                    }
                });
                chat.tag.find(".impChatSubmit").on('click', submitMessage);
                chat.tag.find(".impChatInactive").on('click', open);
                chat.tag.find(".impChatHeader").on('click', close);                
                chat.tag.find("textarea").on('keypress', taPress);
                $.get(chat.stylesheet, function(){
                    $("head").append(chat.css);
                    $("body").append(chat.tag);
                    if(getCookie("chatImpStatus")==1){
                        chat.tag.find(".impChatInactive").hide();
                        chat.tag.find(".impChatActive").show();
                    }else{
                        chat.tag.find(".impChatInactive").show();
                        chat.tag.find(".impChatActive").hide();
                    }
                    chat.tag.find(".impChatFeed").animate({scrollTop: 10000}, 1000);
                });
                //chat.tag=
                //elm.on('click', open);
            },
            open = function () {
                chat.tag.find(".impChatInactive").hide();
                chat.tag.find(".impChatActive").show();
                document.cookie="chatImpStatus=1; path=/";
                forceDialog();
            },                 
            close = function () {
                chat.tag.find(".impChatInactive").show();
                chat.tag.find(".impChatActive").hide();
                document.cookie="chatImpStatus=0; path=/";
            },
            submitMessage = function (e) {
                var msg = chat.tag.find("textarea").val();
                $.ajax({
                    type: "POST",
                    url: burl,
                    data: $.extend({}, chat.settings, {type:"impChatSubmitMessage",msg: msg}),
                    dataType:"json",
                    success: function (json) {
                        chat.tag.find(".impChatMessages").append(json.html);
                        chat.tag.find("textarea").val('');
                        chat.tag.find(".impChatFeed").animate({scrollTop: chat.tag.find(".impChatMessages").height()}, 1000);
                    }
                });
            },                      
            taPress = function (e) {
                if (e.keyCode == 13)
                {
                    chat.tag.find(".impChatSubmit").trigger("click");
                }
            }, 
            updateSession = function () {   
                var writing = (chat.tag.find("textarea").val()=="" ? 0 : 1);
                $.ajax({
                    type: "POST",
                    url: burl,
                    data: $.extend({}, chat.settings, {type:"impChatUpdateSession",writing:writing}),
                    dataType: "json",
                    success: function (response) { 
                        console.log(response);
                        var newmsgs=false;
                        if( (typeof response.msgs === "object") && (response.msgs !== null) )
                        {
                            for (var key in response.msgs) {
                            console.log(response);
                                if (!$("#impChat" + key).length) {
                                    newmsgs=true;
                                    chat.tag.find(".impChatMessages").append(response.msgs[key]);
                                }
                            }
                            chat.tag.find(".impChatFeed").animate({scrollTop: 10000}, 1000);
                        }          
                        if(response.writing==1 && !newmsgs){
                            if(chat.tag.find(".impWriting").length==0){
                                chat.tag.find(".impChatMessages").append('<div class="impChatMessage impChatAgent impWriting"><img height="4" src="https://cdn.impulsion.be/chat/img/writing.gif" /></div>');                                
                            }
                        }else{
                            chat.tag.find(".impWriting").remove();
                        }
                        setTimeout(updateSession, 5000);
                    },
                    error: function (a,b,c) {                 
                        console.info(a);                
                        console.info(b);                                        
                        console.info(c);
                    }
                });
            }, 
            forceDialog = function () {
                if(getCookie("chatImpHello")!=1){
                    $.ajax({
                        type: "POST",
                        url: burl,
                        data: $.extend({}, chat.settings, {type:"impChatForceDialog",lang:chat.settings.lang}),
                        dataType: "json",
                        success: function (response) { 
                            document.cookie="chatImpStatus=1; path=/";
                            document.cookie="chatImpHello=1; path=/";
                            if( (typeof response.msgs === "object") && (response.msgs !== null) )
                            {
                                for (var key in response.msgs) {
                                    if (!$("#impChat" + key).length) {
                                        chat.tag.find(".impChatMessages").append(response.msgs[key]);
                                    }
                                }
                                chat.tag.find(".impChatFeed").animate({scrollTop: 10000}, 1000);
                            }                             
                            if($(window).width()>760){
                                chat.tag.find(".impChatInactive").trigger("click");
                            }else{
                                $(".impChatInactive").append("<div class='impChatMessageNotification'>"+$(response.msgs[key]).text()+"</div>");
                                setTimeout(function(){
                                    $(".impChatMessageNotification").fadeOut(300,function(){
                                            $(".impChatMessageNotification").remove();
                                        })
                                    }
                                ,3000);
                            }
                        },
                        error: function (a,b,c) {
                            //alert("error")
                        }
                    });
                }
            }; 
                    
        init();
        return this;
    };

})(jQuery);
$(document).impChat();