var Dial = Class.create(Application.prototype, {

    STATE_INTERVAL : 1000,
    TIMER_INTERVAL : 1000,
    stateHandle : null,
    timerHandle : null,
    stateUrl    : 'state',
    hangupUrl   : 'hangup',
    lastState   : null,

    stateCode   : 'state_code',
    stateDesc   : 'state_desc',
    stateDuration:'state_duration',
    stateBalance: 'state_balance',
    statePromoBalance: 'state_promo_balance',
    
    status      : 'status',
    statusOK    : 0,
    statusFAIL  : 1,
    statusABORT:  2,

    stateEnd    : 101,
    stateActive : 10,
    stateAbort  : 501,
    
    _break       : '<br />',
    
    descContainer : 'desc-container',
    timerContainer : 'info',
    progressContainer : 'pBar',
    endInfoContainer : 'endInfo',
    
    endedPanel   : 'ended-panel',
    abortPanel   : 'cancel-panel',
    
    secContainer : 'info-time-sec',
    minContainer : 'info-time-min',
    
    maxDurationContainer: 'maxDuration',
    
    classState   : 'summary-state',
    classBalance : 'summary-balance',
    classDuration: 'summary-duration',
    classPromo   : 'summary-promo',

    basicInit: function () {
    
        
    },
    
    stateUpdater: function () {
                    
        $.getJSON(this.stateUrl, function(response) {                
                if(response[this.status] !== this.statusOK) {
                    if(response[this.status] == this.statusABORT) {
                        this.uninstallStateUpdater();
                    }
                    $("#" + this.descContainer).html(Dial_lang.ERROR_DIAL);                    
                    return;
                }
                               
                if (this.lastState !== response[this.stateCode]) {
                    this.lastState = response[this.stateCode];
                    this.updateCallState(response);
                }
                
                if(this.lastState == this.stateActive) {
                    this.updateCallSummary(response);                    
                }                         
            }.bind(this)
        );
        return false;        
    },
    
    updateCallSummary : function(response) {
    
        this.timerUpdater(response[this.stateDuration]);
    },
    
    updateCallState : function (response) {

        var state = response[this.stateCode];
        var desc = response[this.stateDesc]; 
        if(state == this.stateEnd || state == this.stateAbort) {
            this.uninstallStateUpdater();
                        
            $("#" + this.progressContainer).hide();
            $("#" + this.timerContainer).hide();
            $("#" + this.maxDurationContainer).hide();
            
            var time = new Time(response[this.stateDuration]);
            desc = '<span class="' + this.classState + '">' + desc + '</span>' + this._break + 
                   '<span class="' + this.classDuration + '">' + Dial_lang.CALL_DURATION + ': <span>' + time.getMin() + ':' + time.getSec() + '</span></span>';
                   
            if (response[this.stateBalance]) {
                desc = desc + this._break + '<span class="' + this.classBalance + '">' + Dial_lang.STATE_BALANCE + ': '+ response[this.stateBalance] + '</span>';
            }
            if (response[this.statePromoBalance]) {            
                desc = desc + this._break + '<span class="' + this.classPromo + '">' + Dial_lang.STATE_PROMO_BALANCE + ': '+ response[this.statePromoBalance] + '</span>';
            }            
            $("#" + this.endInfoContainer).html(desc);
            $("#" + this.abortPanel).hide();
            $("#" + this.endedPanel).show();
            this.unlockSite();
            return;
        }
        if(state == this.stateActive) {
            $("#" + this.timerContainer).show();
            $("#" + this.progressContainer).hide();
        }
        $("#" + this.descContainer).html(desc);
    },
    
    installStateUpdater: function () {
    
        this.stateHandle = setInterval(this.stateUpdater.bind(this), this.STATE_INTERVAL);    
    },
    
    uninstallStateUpdater : function () {
        
        clearInterval(this.stateHandle);
        return false;
    },
    
    hangupRequest: function () {
    
        $.getJSON(this.hangupUrl, function(response) {
                if(response[this.status] !== this.statusOK) {
                    return;
                }        
            }.bind(this)
        );
        return false;
    },
    
    timerUpdater: function (forceTime) {
    
        var iTime;  
        var time;
    
        if ( !forceTime) {    
            var sSec = $("#" + this.secContainer).text();
            var sMin = $("#" + this.minContainer).text();
            iSec = parseInt(sSec, 10);
            iMin = parseInt(sMin, 10);
            iTime = iMin * 60 + iSec;
        } else {
            iTime = forceTime;
        }
        
        var pBar = $("#" + this.progressContainer);
        var info = $("#" + this.timerContainer);       
        
        iTime++;
        time = new Time(iTime);
        $("#" + this.secContainer).text(time.getSec());
        $("#" + this.minContainer).text(time.getMin());
        return false;
    },

    lockSite : function() {
        window.onbeforeunload = function() {
            return Dial_lang.LEAVE_SITE;
        };
        window.onunload = function() {
            dial.unlockSite();
        };
    },
    
    unlockSite : function() {
        window.onbeforeunload = null;
    },

    loginBox: function() {
        login.loginBox({
            phone1: $('#initial-phone1').val(),
            country1: $('#lang1').val(),
            
            phone2: $('#initial-phone2').val(),
            country2: $('#lang2').val()
        })
    }
});

var dial = new Dial();
$(document).ready( function () {
    dial.basicInit();
    var match;
    
    if(match = location.hash.match(/^#(\d*)-(\d*)-(\d*)-(\d*)$/))
    {
        var prefixA = match[1];
        var numberA = match[2];
        var prefixB = match[3];
        var numberB = match[4];
        
        var optionsA = $('#lang1 option');
        var langA = $('#lang1').get(0);
        var optionsB = $('#lang2 option');
        var langB = $('#lang2').get(0);
        
        $('#initial-phone1').val(numberA);
        $('#initial-phone2').val(numberB);
        
        optionsA.each(function(i, option)
        {
			option.selected = option.value == prefixA;
			selected = true;
        });
        
        optionsB.each(function(i, option)
        {
			option.selected = option.value == prefixB;
			selected = true;
        });
        
        if(langA.selectedIndex == -1)
        {
        	langA.selectedIndex = 0;
        }
        
        if(langB.selectedIndex == -1)
        {
        	langB.selectedIndex = 0;
        }
    }
});

function onlyNumbers(event) {
    var e = event || window.event;
    var charCode = e.which || e.keyCode;

    if (e.altKey || e.ctrlKey || e.shiftKey) 
        return false;

    var allowed = [9, 35, 36, 37, 39, 8, 46];

    for(var i = 0; i < allowed.length; i++) {
        var code = allowed[i];
        if (code == charCode)
            return true;
    }  

    if (charCode > 47 && charCode < 58)
        return true;

    return false;
}
