var poll_tes = new Object();

function PollTE(poll_url, interval){
    this.timer_id = null;
    this.interval = interval;

    this.start = function(url,interval) {
        if(this.timer_id && this.timer_id != null) return false;

        var that = this;
        this.interval = interval;
        this.timer_id = setInterval( function(){ that.req(url) }, interval );
    };
    this.isStarted = function() {return (this.timer_id)?true:false;};
    this.stop = function() {clearInterval(this.timer_id);this.timer_id = null;};
    this.req = function (url) {
        var poll_url = url;
        var that = this;

        var callBack = function(RES){
            if(RES.type === 'error') {
                $(document).trigger("TE_ERROR", [RES.message]);
                that.stop();
                return false; //returned { type : 'error' , message : 'The actual error message'}
            }
            else if(RES.type == 'success') {
                //if(!RES.pending) that.stop(); //If pending is 0 it means no more data to retrieve. STOP!

                for(var i=0; i<RES.output.length; i++){
                    var obj = RES.output[i];
                    $(document).trigger("TE_POLL_EVENT", [obj]);
                }
            }
        };

        $.ajax({
           type: "GET",
           dataType : "json",
           url: poll_url,
           success: callBack,
           timeout: this.interval,
           error : function(evt){that.stop();}
         });
    };
}

function startPollingTE( sid, uid ){
    var obj = poll_tes[sid];
    if(obj && obj.isStarted()) return;

    var tobj = new PollTE()
    tobj.start(ChatConfig.TRANSLATION_ENGINE_URL+"sid:"+sid,ChatConfig.TE_POLL_FREQUENCY);
    poll_tes[sid] = tobj;
}

function stopPollingTE( sid ){
    var obj = poll_tes[sid];
    if(obj && obj.isStarted()){
        obj.stop();
        try{ Logger.log('PollTE stopped for '+sid) }catch(e){}
    }
}