
var ths;

function Sign (options) {

    var _this = this;
    ths = this;

    this.settings = {
        "delay"    : 10,
        "interval" : 2,
        "timeout"  : 30
    };

    if (options) {
        $jq.extend( this.settings, options);
    }
   
    this.timeout   = new Date().getTime() + this.settings.timeout * 1000;
    this.tmCheck   = setTimeout(function () { _this.check();}, this.settings.delay * 1000);
    this.tmTimer   = setInterval( function () { _this.timer();}, 1000);
}

Sign.prototype.check = function () {

    var _this = this;

    $jq.post(
    		this.settings.url, 
    		{ 
    			"act" 		: this.settings.act,
    			"task" 		: this.settings.task,
    			"sesskey"   : this.settings.sesskey,
    			"req" 		: this.settings.req,
    		}, 
    		function(data) { _this.checkCb(data);});

};

Sign.prototype.timer = function () {

    var now = new Date().getTime();
    var timeLeft = Math.round((this.timeout - now) / 1000);

    if (timeLeft <= 0 || timeLeft > this.settings.timeout) {
        this.finTm();
        return;
    }
    
    this.settings.timer.html(timeLeft);

};

Sign.prototype.checkCb = function (data) {

    var _this = this;

    switch(data.status) {
        case "wait":
            this.tmCheck = setTimeout(function () { _this.check();}, this.settings.interval * 1000);
            break;
        case "done":
            this.finOk();
            break;
        case "timeout":
            this.finTm();
            break;
        default:
            this.finErr("", data.error_message);
    }
}

Sign.prototype.finOk = function () {
    this.finish();
    if (this.settings.par)
        this.settings.par.cbOk();    
    else
        this.settings.cbOk();    
};

Sign.prototype.finErr = function (msg, msgtxt) {
    this.finish();
    if (this.settings.par)
        this.settings.par.cbErr(msg, msgtxt);
    else
        this.settings.cbErr(msg, msgtxt);
};

Sign.prototype.finTm = function () {
    this.finish();
    if (this.settings.par)
        this.settings.par.cbTm();
    else
        this.settings.cbTm("2366");
        
};

Sign.prototype.finish = function () {
    clearInterval(this.tmTimer);
    clearTimeout(this.tmCheck);
};
