var from_number, to_number;

function strip(a){
    return a.replace(/\D/g,'');
}

function update_active(v){
    if(active=='#id_from_number') return update_rate_from(v);
    if(active=='#id_to_number') return update_rate_to(v);
    input = $(active);
    input.val(v);
    if(input.hasClass('to_numbers')){
	next_li = input.parent().next();
	if(next_li.length){
	    if(next_li.is(':hidden')) next_li.show();
	    next_li.find('input').focus();
	    set_focus(next_li.find('input')[0].id);
	    return false;
	}
    }
    input.focus();
    return false;
}

function add_num(num) {
    switch(num){
    case 'C': v=''; break;
    case '+': v='+'; break;
    case '<': 
        v=$(active).val();
        v=v.substr(0,v.length-1);
        break;
    default:
        v=$(active).val()+num;
    }
    return update_active(v);
}

function set_focus(tag) {
	active='#'+tag;
}

function save_number(){
    $('#id_message').text('Saved').fadeOut(2000);
    $('.phoneSort img').css('border','none');
    $('.phoneSort img').unbind('click');
    return $('#id_from_number').val();
}

function save_mobile_number(){
    mobile_number = save_number();
    return false;
}

function save_home_number(){
    home_number = save_number();
    return false;
}

function save_office_number(){
    office_number = save_number();
    return false;
}

function update_to_number(v){
    $('#id_to_number').val(v);
}


function speed_dial_button(num){
    $(active).val(eval('speed_dial_'+num));
    $('#callbackForm').submit();
    return false;
}

function update_speed_dial(){
    if(speed_dial_1){
        $('.speedBullets a').eq(0).addClass('active');
    }else{
        $('.speedBullets a').eq(0).removeClass('active');
    }
    if(speed_dial_2){
        $('.speedBullets a').eq(1).addClass('active');
    }else{
        $('.speedBullets a').eq(1).removeClass('active');
    }
}

function conf_plus(el){
    $('#conference li:hidden:first input').val('');
    $('#conference li:hidden:first').show();
    return false;
}

function conf_minus(el){
    $.each($(el).parent().nextAll().filter(':visible'),function(){
        $(this).prev().find('input').val($(this).find('input').val());
    });
    $('#conference li:visible:last').hide();
}

var conf_options = {
        matchContains: true,
        formatItem: function(row){
            return row[0] + " (<strong>"+row[1]+"</strong>)";
        },
        formatResult: function(row){
            return row[0];
        }
    };

function toggle_conference(copy){
    $('#conference').toggle();
    $('#id_is_conference').click();
    $('#id_to_number').attr('disabled',$('#conference:visible').length)
    if($('#conference:visible').length){
        if(typeof(copy)=='undefined') $('#conference input')[0].value=$('#id_to_number').val();
        active = '#conference input';
        $.cookie('show_conference','1');
    }else{
        if(typeof(copy)=='undefined') $('#id_to_number').val($('#conference input')[0].value);
        active = '#id_to_number';
        $.cookie('show_conference',null);
    }
    $(active).focus();
}

function toggle_dialpad(){
    $('#numbers').toggle();
    $('#steps').toggle();
    $('#mainTable').toggleClass('dialpadHidden');
    if($('#numbers:visible').length){
	$('.hideDialpad').text('hide dialpad');
        $.cookie('hide_dialpad',null);
    }else{
	$('.hideDialpad').text('show dialpad');
        $.cookie('hide_dialpad','1');
    }
    return false;
}

function update_rate_from(e){
    if(typeof(e)=='undefined')
        v=$('#id_from_number').val();
    else if(typeof(e)=='string'){
        $('#id_from_number').val(v=e).focus();
    }else if(strip(this.value)==from_number)
        return;
    else
        v=from_number=strip(this.value);
    /*$.post('http://voip.phones.com/cust/A2BCustomer_UI/get_rate.php',{num:'12345'},*/
    if(String(v).length>=8)
	$.post('/callback/get_rate/', {num:v}, function(data){
	    rate_from=parseFloat(data);
	    if(isNaN(rate_from))
		$('#callRate').hide();
	    else
		$('#callRate span').text((rate_from+rate_to).toFixed(2));
	});
    return typeof(e)=='object';
}

function update_rate_to(e){
    if(typeof(e)=='undefined')
        v=$('#id_to_number').val();
    else if(typeof(e)=='string'){
        $('#id_to_number').val(v=e).focus();
    }else if(strip(this.value)==to_number)
        return;
    else
        v=to_number=strip(this.value);
    /*$.post('http://voip.phones.com/cust/A2BCustomer_UI/get_rate.php',{num:'12345'},*/
    if(String(v).length>=8)
	$.post('/callback/get_rate/', {num:v}, function(data){
	    rate_to=parseFloat(data);
	    if(isNaN(rate_to))
		$('#callRate').html('');
	    else
		$('#callRate span').text((rate_from+rate_to).toFixed(2));
	});
    return typeof(e)=='object';
}

var call_started, duration=0, timer_handle;

function update_timer(){
    timer_handle=setTimeout(update_timer,1000);
    $('#duration').html('<div><label>Call Duration:</label><span>'+Math.floor(duration/60)+':'+(duration%60<10?"0":"")+duration%60+'</span></div>').show();
    duration+=1;
}

function check_call_started(call_id){
    $.get('/callback/check_call_status/'+call_id+'/',{},function(data){
	if(data=='Q')
	    setTimeout(check_call_started,2000,call_id);
	else{
	    show_end_call();
	    call_started=new Date();
            duration=0;
            update_timer()
	    check_call_finished(call_id);
        }
    });
}

function check_call_finished(call_id){
    $.get('/callback/check_call_status/'+call_id+'/',{},function(data){
        var now = new Date();
	msg = '<div><label>Call Duration:</label><span>'+Math.floor(duration/60)+':'+(duration%60<10?"0":"")+duration%60+'</span></div>';
	if(data[0]=='F'){
            clearTimeout(timer_handle);
	    show_start_call();
	    $('#duration').html(msg + '<div><label>Call cost:</label><span>$'+data.substr(1)+'</span></div>').fadeOut(7000);
	}else{
            setTimeout(check_call_finished,10000,call_id);
        }
    });
}

function process_result(data){
    var is_valid=true,
        errors=data['errors'];
    for(field in errors){
        $('#'+field+'_err').html(errors[field]);
        if(errors[field]) is_valid=false;
    }
    if(is_valid)
        if(data['res'].length==13){
            $('#id_message').html('Your call is being connected ...').show().fadeOut(10000);
            setTimeout(check_call_started,2000,data['res']);
	}else
            $('#id_message').html('Request failed: '+data['res']+'.').show().fadeOut(10000);
    return false;
};

function show_message(data){
    $('#id_message').text(data).show().fadeOut(10000);
}

function show_start_call(){
    $('.endCall').hide();
    $('.makeCall').show();
}

function show_end_call(){
    $('.makeCall').hide();
    $('.endCall').show();
}

