
(function(){

    function HandAjax(method, url, async, onload, params){

        var text = params;
        method = method ? method : 'GET';

        if(params && method == 'GET'){
            url += "?";
            for(var i in params){
                url += i + "=" + params[i] + "&";
            }
            url=url.substr(0, url.length-1);
        }

        var xhr = this.xhr = new XMLHttpRequest();
        xhr.open(method, url, async);

        /*if(params){

            text = JSON.stringify(params);
            //xhr.setRequestHeader("Content-length", text.length);
        }*/

        xhr.onreadystatechange = onload;
        xhr.send(text);
    }

    var positionLibrary = function(){

        var coords = [];
        var last = null;

        return {
            getTime : function(){
                var d = new Date();
                return d.getTime();
            },
            add : function(x,y, event){
                var time = this.getTime();

                coords.push({
                    "x" : x,
                    "y" : y,
                    "coordinates" : x + ',' + y,
                    "timeStamp" : time,
                    "pageUrl" : location.href,
                    "userEvent" : event,
                    "userToken" : UH.userId,
                    "caseToken" : UH.questionToken
                });
                

                /*if(last){
                    coords.push({
                        "x" : last.x,
                        "y" : last.y,
                        "coordinates" : last.x + ',' + last.y,
                        "time" : time - last.time,
                        "timeStamp" : time,
                        "pageUrl" : location.href,
                        "userEvent" : last.userEvent
                    });
                }

                last = {
                    "x" : x,
                    "y" : y,
                    "time" : time,
                    "userEvent" : event
                };*/
            },
            getData : function(len){
                if(len){
                    var temp = [];
                    for(var i = 0; i < len && i < coords.length ; i++){
                        temp.push(coords[i]);
                    }
                    coords = coords.slice(len);
                    return temp;
                } else {
                    var temp = coords;
                    coords = [];
                    return temp;
                }
            }
        };
    };

    var pLib = new positionLibrary();

    function UserHand(){

        var self = this;
        this.content = {
            init : "init content <a href='#' class='start'>start</a>",
            process : "content during test <a href='#' class='cancel'>cancel</a> <a href='#' class='finish'>finish</a>",
            finish : "finish text <a href='#' class='close'>close</a>"
        };

        this.callbacks = {
            init : function(){
                document.querySelector("#userHand .start").onclick = function(){
                    pLib.add(0,0,"starttest");
                    self.start();
                    return false;
                }
            },
            process : function(){
                document.querySelector("#userHand .cancel").onclick = function(){
                    pLib.add(0,0,"canceltest");
                    self.clear();
                    return false;
                }
                document.querySelector("#userHand .finish").onclick = function(){
                    pLib.add(0,0,"finishtest");
                    self.finish();
                    return false;
                }
            },
            finish : function(){
                document.querySelector("#userHand .close").onclick = function(){
                    pLib.add(0,0,"closetest");
                    self.clear();
                    return false;
                }
            }
        };

        this.endLink = null;

        //this.siteToken = window.UH_TOKEN;

        this.questionToken = this.getQuestionToken();

        if(!this.questionToken){
            return;
        }

        this.userId = this.getUserId(); //read from cookie

        this.userStatus = this.getUserStatus();

    }

    UserHand.prototype.getQuestionToken = function(){
        var index = null;
        var token = null;
        if( ( index = location.href.indexOf("#question=") ) > -1 ) {
            token = location.href.substr(index + "#question=".length);
        } else if( ( index = location.href.indexOf("?question=") ) > -1){
            token = location.href.substr(index + "?question=".length);
        } else if( ( index = location.href.indexOf("&question=") ) > -1){
            token = location.href.substr(index + "&question=".length);
        } else {
            token = this.getCookie("UHquestionToken");
        }

        if(token){
            this.setCookie("UHquestionToken", token);
        }
        return token;
    };

    UserHand.prototype.getContent = function(){
        var self = this;

        if(!this.userId){
            new HandAjax(
                "GET",
                "http://usershand.wi-net.com.ua/api/GetNewUserToken",
                true,
                function(e){
                    if (this.readyState==4 && this.status==200){

                        var obj = JSON.parse(this.responseText);
                        if(obj && obj.token){
                            self.setUserId(obj.token);
                        }
                    }
                },
                null
            );
        }


        new HandAjax(
            "GET",
            "http://usershand.wi-net.com.ua/api/TestCaseTextValues?caseToken=" + this.questionToken,
            true,
            function(e){
                if (this.readyState==4 && this.status==200){

                    var obj = JSON.parse(this.responseText);
                    if(obj && obj.endPage){
                        self.content = {
                            init : obj.titleText,
                            process : obj.taskText,
                            finish : obj.doneText
                        };
                        self.endLink = obj.endPage;

                        self.render();

                        pLib.add(0,0,"pageload");

                    }
                }
            },
            null
        );
    }

    UserHand.prototype.getCookie = function(name){
        var i,
            x,
            y,
            cookies = document.cookie.split(";");
        for (i=0;i<cookies.length;i++)
        {
            x=cookies[i].substr(0,cookies[i].indexOf("="));
            y=cookies[i].substr(cookies[i].indexOf("=")+1);
            x=x.replace(/^\s+|\s+$/g,"");
            if (x==name)
            {
                return unescape(y);
            }
        }
        return null;
    }

    UserHand.prototype.setCookie = function(name, value){
        var exdate=new Date();
        exdate.setTime(exdate.getTime() + 2 * 86400000);
        var c_value=escape(value) + "; path=/; expires=" + exdate.toUTCString();
        document.cookie=name + "=" + c_value;
    }

    UserHand.prototype.getUserStatus = function(){
        var status = this.getCookie("UHStatus");
        if(!status) {
            status = "init";
            this.setCookie("UHStatus", status);
        }
        return status;
    }

    UserHand.prototype.getUserId = function(){
        return this.getCookie("UHid");
    }

    UserHand.prototype.setUserId = function(userId){
        this.userId = userId;
        this.setCookie("UHid", userId);
    }

    UserHand.prototype.render = function(){

        if(!this.node){
            this.node = document.createElement("div");
            this.node.id = "userHand";
            this.node.setAttribute('style',"position : fixed; top : 0; left : 0; width : 100%; padding : 15px 0; background : #000; border : 1px solid #eee; color : #fff; font-size : 16px;");
            document.body.appendChild(this.node);
        }

        this.node.innerHTML = this.content[this.userStatus];
        document.body.style.paddingTop = this.node.offsetHeight + 'px';
        this.callbacks[this.userStatus]();

        this.sendEvents();
    }

    UserHand.prototype.setUserStatus = function(userStatus){
        this.userStatus = userStatus;
        this.setCookie("UHStatus", userStatus);
    }

    UserHand.prototype.start = function(){
        this.setUserStatus('process');
        this.render();
    }

    UserHand.prototype.clear = function(){
        this.setUserStatus('');
        this.userId = '';
        this.setCookie("UHid", '')
        this.questionToken = '';
        this.setCookie("UHquestionToken", '');
        this.node.parentNode.removeChild(this.node);
        document.body.style.paddingTop = '0px';
        clearInterval(this.timeout);
    }

    UserHand.prototype.finish = function(){
        this.setUserStatus('finish');
        this.render();
    }

    UserHand.prototype.initEvents = function(){
        /*var self = this;
        this.counter = this.counter ? this.counter : 0;
        document.body.addEventListener("mousemove", function(e){
            if( self.counter ++ == 150) {
                self.counter = 0;
                pLib.add(e.pageX, e.pageY, "mousemove");
            }
        });*/
    }

    UserHand.prototype.sendEvents = function(){
        /*if(this.userStatus != 'process' || this.timeout){
            return;
        }*/

        var self = this;

        var sendQuery = function(){

            /*if(self.userStatus == 'finish' || self.userStatus == null){
                return;
            }*/

            var d = pLib.getData(1);
            if(d.length > 0){
                d = d[0];
                
                if(!d.userToken){
                    d.userToken = self.userId;
                }

                if(!d.caseToken){
                    d.caseToken = self.questionToken;
                }

                new HandAjax("GET", "http://usershand.wi-net.com.ua/api/SaveUserActions", true, function(e){
                    self.timeout = setTimeout(function(){
                        sendQuery();
                    }, 300);
                }, d);
            } else {
                self.timeout = setTimeout(function(){
                    sendQuery();
                }, 300);
            }
        };

        sendQuery();

    }

    var UH = new UserHand();

    window.addEventListener("DOMContentLoaded", function(){
        UH.getContent();
        UH.initEvents();
    }, false);

}());
