function freeNumbers()
{
    window.onload = function()
    {
        setFirstPrefix();

        return;
    }
    return;
}

function setFirstPrefix()
{
    var param = "";
    var http = ajax();
    var select = document.getElementById('first_prefix');
    select.onchange = function()
    {
        var select = document.getElementById('first_prefix');
        clearNumber('PHONE');
        setSecondPrefix(select.options[select.selectedIndex].text);
    }
    var url = '/fun/?cls=Numbers&fun=GetDef&fmt=2';
    http.open('POST', url, false);
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", param.length);
    http.setRequestHeader("Connection", "close");

/*    http.onreadystatechange = function() {//Call a function when the state changes.
    {
        if(http.readyState == 4 && http.status == 200) {

        }
    }*/
    http.send(param);
    eval("var res="+http.responseText+";")
    if(res.length != 0)
    {
        for(var i=0;i<res.length;i++)
        {
            opts = document.createElement('option');
            opts.text=res[i].NAME;
            opts.value = res[i].N;
            try
            {
                select.add(opts,null); // standards compliant
            }
            catch(ex)
            {
                select.add(opts); // IE only
            }
        }
        setSecondPrefix(select.options[0].text);
    }
}
function setSecondPrefix(val)
{
    var param = "DEF="+val;
    var http = ajax();
    var select = document.getElementById('second_prefix');
    select.onchange = function()
    {
       clearNumber('PHONE', 'locateNum');
    }
    removeOptions('second_prefix');
    var url = '/fun/?cls=Numbers&fun=GetPref&fmt=2';
    http.open('POST', url, false);
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", param.length);
    http.setRequestHeader("Connection", "close");

/*    http.onreadystatechange = function() {//Call a function when the state changes.
    {
        if(http.readyState == 4 && http.status == 200) {

        }
    }*/
    http.send(param);
    eval("var res="+http.responseText+";");
    if(res.length != 0)
    {
        for(var i=0;i<res.length;i++)
        {
            opts = document.createElement('option');
            opts.text=res[i].NAME;
            opts.value = res[i].N;
            try
            {
                select.add(opts,null); // standards compliant
            }
            catch(ex)
            {
                select.add(opts); // IE only
            }
        }
    }
    clearNumber('PHONE', 'locateNum');

}

function removeOptions(id)
{
    var select = document.getElementById(id);
    var count = select.options.length;
    for(var i=0;i<count;i++)
        select.remove(select.options[0]);
}

function enterPreparedNum(val) 
{
	el = document.getElementById('PHONE');
    el.value = val;
}
function enterNum(obj){
	el = document.getElementById('PHONE');
    el.value = obj.text;
}
function locateNum(value){
	sel = document.getElementById('NUMBER_LIST');
	selected_num = document.getElementById('SELECTED_NUMBER');
		for (num=sel.options.length-1;num>=0;num--){
			if (sel.options[num].title == undefined){
				continue;
			}
			var str1 = new String(sel.options[num].title);
			var str2 = new String(value);
			if (str1.indexOf(str2) == 0){
				sel.options[num].selected = true;
				selected_num.value = sel.options[num].value;
			}
		}
}

function submitForm(){
	document.SELECT_NUMBER_FORM.submit();
}

function processPhoneKey(val){
     el = document.getElementById('PHONE');
        if (!el){
            return;
        }
        arr = el.value.split('');
        var curPOS = getCurPOS();
        if(typeof(arguments[1])=="undefined"){
            arr[curPOS] = val;
            value = arr.join('');
        }
        el.value = value;        
       setNextPOS(curPOS);
       //allowKey();
}

var globalAllow;
var globalDontAsk = false;
function allowKey()
{
    if (isFocus) return;
    var restrictedKeys = new Array(0,1,2,3,4,5,6,7,8,9);
    globalAllow =[];
    var first_select = document.getElementById('first_prefix');
    var second_select = document.getElementById('second_prefix');
    var prefix;
    try{
    prefix = first_select.options[first_select.selectedIndex].text+second_select.options[second_select.selectedIndex].text;
    }
    catch(e){}
    //"7800100";

    var input = document.getElementById('PHONE');
    var value = input.value.replace(/(\*)/g, "_");
    var naturValue = new String(input.value.replace(/(\*)/g, ""));
    var param = "IN_STR=" + prefix + value;
    param += "&POS=" + getCurPOS();
    var http = ajax();    
    var url = '/fun/?cls=Numbers&fun=GetFreeNumbersXXX';
    var bt;
    http.open('POST', url, true);
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", param.length);
    http.setRequestHeader("Connection", "close");

    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            if(http.responseText=="e")
            {
                for(var i=0;i<10;i++){
                    bt = document.getElementById('button-'+i);
                    bt.src = "/i/zebra/img/btn_"+i+"_s.gif";
                    bt.onclick = function(){
                        return false;
                    }
                }
                document.getElementById('btn-connect').src = "/i/zebra/img/btn_connect.gif";
            }
            else
            {
                try{
                    var res = http.responseText.split(",");
                    for(var i=0;i<res.length;i++)
                        restrictedKeys[res[i]] = -1;
                    for(i=0;i<10;i++)
                    {
                        bt = document.getElementById('button-'+i);
                        if(restrictedKeys[i]==-1)
                        {
                            bt.src = "/i/zebra/img/btn_"+i+".gif";
                            bt.onclick = function(){
                                processPhoneKey(this.value);
                                return false;
                            }
                            globalAllow.push(i);
                        }
                        else
                        {
                            bt.src = "/i/zebra/img/btn_"+i+"_s.gif";
                            bt.onclick = function(){
                                return false;
                            }
                        }
                    }
                    document.getElementById('btn-connect').src = "/i/zebra/img/btn_connect_s.gif";
                }
                catch(e)
                {
                    for(vari=0;i<10;i++){
                        bt.src = "/i/zebra/img/btn_"+i+"_s.gif";
                        bt.onclick = function(){
                            return false;
                        }
                    }
                }
            }
            if(naturValue.length ==4)
                document.getElementById('btn-connect').src = "/i/zebra/img/btn_connect.gif";
            else
                document.getElementById('btn-connect').src = "/i/zebra/img/btn_connect_s.gif";
        }
        }
        http.send(param);
}


function clearNumber(item){
	var el = document.getElementById(item);
    if (!el) {
        return;
    }
    el.value = '****';
        //processPhoneKey('*');
    setPOS(0);    
    return;
}

function ajax(){
    var xmlHttp = false;
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
        xmlHttp = false;
      }
    }
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
      xmlHttp = new XMLHttpRequest();
    }
    return xmlHttp;
}

function reservNreg()
{
    var first_select = document.getElementById('first_prefix');
    var second_select = document.getElementById('second_prefix');
    var prefix = first_select.options[first_select.selectedIndex].text+second_select.options[second_select.selectedIndex].text
    var phone = document.getElementById('PHONE').value;
    //alert(phone+":"+typeof(phone));
    if(!/^\d+$/.test(phone))
    {
        alert('Выберите номер для резервирования');
        return false;
    }


    var http = ajax();
    var param = "PHONE="+prefix+phone;
    var url = '/fun/?cls=Numbers&fun=GetNumberId';
    http.open('POST', url, false);
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", param.length);
    http.setRequestHeader("Connection", "close");

//    http.onreadystatechange = function() {//Call a function when the state changes.
//        if(http.readyState == 4 && http.status == 200) {
//        }
//      }
    http.send(param);
    var selectedNum = http.responseText;    
    if(typeof(GearJsAuth) == "undefined" || !GearJsAuth)
    {
        setCookie('number_id',selectedNum+":"+prefix+phone,null,"/");
        document.location.href = '/registration';
    }
    else
    {
        alert('Резервирование номера доступно в Личном кабинете');
        document.location.href = '/office';
        return;
        var http = ajax();
       //s doRegRequest('');
        var url = '/cls/call?cls=Numbers&fun=Reserve';
        http.open('POST', url, true);
        var _param = "N="+selectedNum;
        //Send the proper header information along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader("Content-length", _param.length);
        http.setRequestHeader("Connection", "close");

        http.onreadystatechange = function() {//Call a function when the state changes.
	        if(http.readyState == 4 && http.status == 200) {
                document.location.href = '/office';
	        }
	        if(http.readyState == 4 && http.status == 500) {}
        }
        http.send(_param);
    }

}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function backspace(id)
{
    var phone = document.getElementById(id);
    if (!phone.value.length == 0)
    {
        //phone.value = phone.value.substr(0,phone.value.length-1);
        //processPhoneKey(phone.value,1);
        var s = getCurPOS();
        globalDontAsk = true;
        setPrevPOS(s);
        isFocus = true;
        processPhoneKey('*');
        isFocus = true;
        globalDontAsk = false;
        setPrevPOS(s);
        isFocus = false;
    }
    return;
}
(function () {
    var dom = typeof window.addEventListener == "function";
    var ie = typeof window.attachEvent == "object";

    function handle(evt) {
        //if (evt.keyCode == 8) {
        if (dom) {
            evt.preventDefault();
        } else if (ie) {
            evt.returnValue = false;
        }
        return inputUpdate(evt);
		//}
    }

    if (dom) {
        window.addEventListener("keypress", handle, false);
    } else if (ie) {
        document.attachEvent("onkeydown", handle);
    }
})();

function inputUpdate(e) {
    //return true;
    var keynum;
    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    else if (e) {
        keynum = e.keyCode;
    }

    if(keynum==32){
        setNextPOS();
        return false;
    }
    if (keynum == 8) {
        backspace('PHONE');
            //return true;
        return false;
    }
    if (keynum == 39) {
        setNextPOS();
    }
    if (keynum == 37) {
        setPrevPOS();
    }
    var key = keynum - 48;
    var ieKey = keynum - 96;
    if (key > 9 || key < 0) {
        if (ieKey > 9 || ieKey < 0)
            return false;
        else
            key = ieKey;
    }
    if (globalAllow)
        for (var i = 0; i < globalAllow.length; i++) {
            if (globalAllow[i] == key) {
                processPhoneKey(key);
            }
        }
    return false;
}

function ieSetSelectionRange(element, startPos, endPos)
{
    if (startPos > endPos)
        startPos = endPos;

      // Вводим поправку на то, что знак \r не учитывается
    var startCorrection = element.value.substr(0, startPos).match(/\r/g);
    startCorrection = startCorrection ? startCorrection.length : 0;
    var endCorrection = element.value.substr(0, endPos).match(/\r/g);
    endCorrection = endCorrection ? endCorrection.length : 0;

    selection = element.createTextRange();
    selection.collapse(true);
    selection.moveEnd("character", endPos - endCorrection);
    selection.moveStart("character", startPos - startCorrection);

    selection.select();

      // Это нужно для случая, когда startPos == endPos
    //storeSelection();
}

function getSelectionStart(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveEnd('character', o.value.length)
        if (r.text == '') return o.value.length
        return o.value.lastIndexOf(r.text)
    } else return o.selectionStart
}

function getSelectionEnd(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveStart('character', -o.value.length)
        return r.text.length
    } else return o.selectionEnd
}

var isFocus = false;

function setSelection(obj) {
    if (!obj) return false;
    var s = getCurPOS();
    setPOS(s);
    return false;
}

function getCurPOS()
{
    var obj = document.getElementById('PHONE');
    return getSelectionStart(obj);
}

function setPOS(POS) {
    var obj = document.getElementById('PHONE');
    if (!obj) return;
    var start,end;
    if (POS > 0 && POS < 4) {
        //obj.setSelectionRange(POS,POS+1);
        start = POS;
        end = POS + 1;
    }
    if (POS == 0) {
        /*obj.selectionStart = 0;
        obj.selectionEnd = 1;*/
        start = 0;
        end = 1;
    }

    if (POS == 4) {
        /*obj.selectionStart = 3;
        obj.selectionEnd = 4;*/
        start = 3;
        end = 4;
    }
    if (!obj.setSelectionRange)
        ieSetSelectionRange(obj, start, end);
    else
        obj.setSelectionRange(start, end);
    allowKey();
    isFocus = true;
    document.getElementById('PHONE').focus();
    isFocus = false;
}

function setNextPOS(s) {
    if (typeof(s) == "undefined") {
        var obj = document.getElementById('PHONE');
        s = getCurPOS();
    }
    if (s < 3)
        setPOS(s + 1);
    else
        setPOS(0);
}

function setPrevPOS(s) {
    if (typeof(s) == "undefined") {
        var obj = document.getElementById('PHONE');
        s = getCurPOS();
    }
    if (s > 0) {
        setPOS(s - 1);
    }
    else
        setPOS(3);
}

function selectInput() {
    document.getElementById('PHONE').focus();
    return false;
}

function showSelectedNumber()
{
    var number_id = getCookie('number_id');
     if(typeof(number_id)!="undefined" && number_id)
    {
        document.getElementById('selectedNum').innerHTML = "Выбранный номер: "+number_id.split(":")[1]+"&nbsp;<a href='/'>Выбрать другой</a>";
    }
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

freeNumbers();

