var unsetClass = false;
var closePopUp = false;
var tinyMCE = false;
var tinyMCEmode = false;
var doLoadForm = false;
var popUpJustify = false;
var ajpath = '/PWE2/etc/loader.php?';
var menuDrop = '';
var doLoadHistory = ajpath;
var reloadPage = false;
var debugAJpath = false;

var etc_path = "/PWE/etc/";

function func(){}

function ping(){
    var req = new JsHttpRequest();
    req.onreadystatechange = function(){
        if (req.readyState == 4){
            if (req.responseJS){
                if (req.responseJS.sysevents.length > 1){
                    if ($('cpmenu1_informer').hasClassName('cpmenu1_informer') == false){
                        $('cpmenu1_informer').addClassName('cpmenu1_informer');
                    }
                    $('cpmenu1_informer').update(req.responseJS.sysevents);
                } else {
                    $('cpmenu1_informer').update('');
                    $('cpmenu1_informer').removeClassName('cpmenu1_informer');
                }
                if (req.responseJS.current_realtor && req.responseJS.current_realtor.length > 1){
                    $('cpmenu2_informer').update(req.responseJS.current_realtor);
                }
                return true;
            }
        }
    }
    req.caching = false;
    req.open('POST', '/PWE2/etc/ping.php', true);
    req.send({
        'ping':1
    });
}

function cpanelOpen(hash){
    // CPanel container
    if (!$('cpanel')){
        new Insertion.Top(document.body, "<div class=cpanel id=cpanel style=display:none></div>");
        new Insertion.Top('expand', "<div id=cpspacer style=line-height:26px align=center>Идет загрузка...</div>");
    }
    new PeriodicalExecuter(ping, 150);
    // Autorization | Call CPanel module
    doLoad(ajpath+'module=cpanel.aj&go=topmenu', (hash ? hash : null), 'cpanel');
}

function cpanelClose(){
    if ($('cpanel'))
        $('cpanel').remove();
    if ($('cpspacer'))
        $('cpspacer').remove();        
}

function cpMenuOver(id){
    if ($(id))
        $(id).className='cpmenu1h';
    if (menuDrop.length > 0 && menuDrop != id){
        if ($('_'+menuDrop))
            $('_'+menuDrop).remove();
        cpMenu(id);
    }
}

function cpMenuOut(id){
    if ($(id))
        $(id).className='cpmenu1';
}

function cpMenu(id){
    if ($('_'+id) && (menuDrop.length == 0 || menuDrop == id)){
        $('_'+id).remove();
        menuDrop = '';
    } else if (id && $(id)) {
        menuDrop = id;
        new Insertion.Bottom(id, "<div class=cpslider id='_"+id+"'></div>");
        new Position.clone(id, '_'+id, {
            'setLeft':true,
            'setTop':true,
            'setWidth':false,
            'setHeight':false,
            'offsetLeft':0,
            'offsetTop':25
        });
        doLoad(ajpath+'module=cpanel.aj&go=submenu&id='+id, null, '_'+id);
    }
}

function cpMenu2(id){
    if ($(id) != null)
        $(id).parentNode.parentNode.className = 'cpmenu1';
    popUp();
    doLoad(ajpath+'module=cpanel.'+id+'.aj', null, 'popUpContent');
}

function wait(){
    if ($('wait')){
        $('wait').remove();
        try{
            WCH.Discard('wait');
        } catch(e){}
    }
    if ($('body100'))
        var bhght = $('body100').getHeight();
    else
        var bhght = document.body.getHeight();
    	
    var hght = document.viewport.getHeight();
    var scroll = document.viewport.getScrollOffsets();
    var diff = bhght - hght - scroll.top;
    new Insertion.Top(document.body, '<table class="iePNG" width="100%" ' +
        (hght > 0 ? ' height="' + bhght + '" ' : '') +
        ' id="wait">' +
        (scroll.top > 0 ? '<tr><td height="' + scroll.top + '"><div style="width:1px;height:1px"><spacer width="1" height="1"></spacer></div></td></tr>' : '') +
        '<tr align="center" valign="center"><td height="' + hght + '"><img src="/PWE2/images/blue-loading.gif" width="32" height="32" border="0" alt="Wait..." onclick="try{WCH.Discard(\'wait\'); $(\'wait\').remove();} catch(e){}"/></td></tr>' +
        (diff > 0 ? '<tr><td height="' + diff + '"><div style="width:1px;height:1px"><spacer width="1" height="1"></spacer></div></td></tr>' : '')+'</table>');
    try{
        WCH.Apply('wait');
    } catch(e){}
    
}

function doLoad(path, arr, elm){
    if (!path) return;
    var substr_get = '';
    // Создаем новый объект JSHttpRequest.
    var req = new JsHttpRequest();
    if (elm == 'popUpContent' && tinyMCEmode == true && tinyMCE.getInstanceById('text')){
        tinyMCE.execCommand('mceRemoveControl', false, 'text');
    }
    try{
        if ((isArray(arr) || isObject(arr)) && arr.nowait){
            
        } else {
            wait();
        }
    } catch(e){}
    
    // Код, АВТОМАТИЧЕСКИ вызываемый при окончании загрузки.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.responseJS) {
                /*if (!elm || elm=='none' || !$(elm)) elm = 'result';
				$(elm).innerHTML = req.responseJS.wf_main;
				if (req.responseJS.message) alert(req.responseJS.message);
				if (tinyMCEmode == true) tinyMCE.updateContent(elm);*/
                // Result
                if (!elm || elm=='none' || !$(elm))
                    elm = 'result';
                if (doLoadForm) {
                    $(elm).value = req.responseJS.wf_main;
                    doLoadForm = false;
                } else {
                    if ($(elm)){
                        $(elm).update(req.responseJS.wf_main);
                        new Element.show(elm);
                    }
                    if (elm == 'popUpContent' && popUpJustify == true){
                        /*var xx = (document.viewport.getWidth() - $('popUp').getWidth())/2;
                        var yy = (document.viewport.getHeight() - $('popUp').getHeight())/2;
                        if (yy < 30)
                        	yy = 30;
                        new Effect.Move ('popUp', { 'x': xx, 'y': yy, 'mode': 'absolute'});*/
                        document.body.scrollTo();
                        popUpJustify = false;
                    }
                    if (elm == 'popUpContent'){
                        try{
                            if (adjustMapPoints && $('subtable')){
                                var _subt_pos = Position.positionedOffset($('subtable'));
                                var _arr = $$('img.map_point');
                                for (var i=0; i<_arr.length; i++){
                                    Element.setStyle(_arr[i], {
                                        top:(parseInt(Element.getStyle(_arr[i], 'top').sub('px', ''))+_subt_pos[1])+'px',
                                        left:(parseInt(Element.getStyle(_arr[i], 'left').sub('px', ''))+_subt_pos[0])+'px'
                                    });
                                }
                            //var pp = Position.page($('subtable'));
                            //new Insertion.Top(document.body, '<img src=/PWE2/images/crosshair.gif style="position:absolute;top:'+pp[1]+'px;left:'+pp[0]+'px;z-index:1000000"/>');
                            }
                        } catch(e){}
                    }
                }
                if (req.responseJS.iface_title && $('popUpTitle'))
                    $('popUpTitle').update(req.responseJS.iface_title);
                if (unsetClass){
                    $(unsetClass).className = '';
                    unsetClass = false;
                }
                // Отладочная информация
                if (req.responseJS.xmldebug){
                    if (!$('debug_aj'))
                        new Insertion.Top(document.body, '<b>Ajax XML debug</b><pre class="debug" id="debug_aj">'+req.responseJS.xmldebug+'</pre>');
                    else
                        $('debug_aj').innerHTML = req.responseJS.xmldebug;
                    str = false;
                }
                if (elm == 'popUpContent' && req.responseJS.wf_main && req.responseJS.wf_main.length > 1){
                    doLoadHistory = path;
                }
                if (closePopUp == true){
                    popUpClose();
                    closePopUp = false;
                }
            }
            // Отладочная информация
            if (req.responseText.length > 0){
                alert(req.responseText);
            }
            if (debugAJpath == true && elm == 'popUpContent' && $('debug_aj_path')){
                $('debug_aj_path').innerHTML = path;
            }
            if ($('wait')){
                try{
                    WCH.Discard('wait');
                } catch(e){}
                $('wait').remove();
            }
            if (arr && arr.close_dialog && $('dialog')){
                $('dialog').remove();
            }
            if (arr && arr.doLoadFunc){
                eval(arr.doLoadFunc);
            }
        }
    }
    // Разрешаем кэширование (чтобы при одинаковых запросах не обращаться к серверу несколько раз).
    req.caching = false;
    // Подготавливаем объект.
    var xy = '';
    if (elm == 'popUpContent' && $('subtable')){
        try {
            xy = '&subtable_x='+Position.positionedOffset($('subtable')).join("&subtable_y=");
        } catch(e){}
    }
    req.open('POST', path + xy + '&target_elm=' + elm, true);
    // Посылаем данные запроса (задаются в виде хэша): req.send({ q:query, test:303 });
    req.send(arr);
    if (arr && arr.doLoadAfter){
        doLoad(arr.doLoadAfter, null, (arr.doLoadAfterTarget ? arr.doLoadAfterTarget : 'popUpContent'));
        return;
    }
}

function popUp(){
    if ($('popUpShell')){
        popUpClose();
    }
    if ($('body100')){
        var bhght = $('body100').getHeight();
    } else {
        var bhght = document.body.getHeight();
    }
    var hght = document.viewport.getHeight();
    var scroll = document.viewport.getScrollOffsets();
    var diff = bhght - hght - scroll.top;    	
    if ($('fullwindow')){
 
    } else {
        new Insertion.Top(document.body, '<table class="iePNG" width="100%" ' +
            (hght > 0 ? ' height="' + bhght + '" ' : '') +
            ' id="popUpShell">' +
            (scroll.top > 0 ? '<tr><td height="' + scroll.top + '"><div style="width:1px;height:1px"><spacer width="1" height="1"></spacer></div></td></tr>' : '') +
            '<tr align="center" valign="top"><td id="popUpShellContent" height="' + hght + '"><center>Идет загрузка...</center></td></tr>' +
            (diff > 0 ? '<tr><td height="' + diff + '"><div style="width:1px;height:1px"><spacer width="1" height="1"></spacer></div></td></tr>' : '')+'</table>');

        $("popUpShellContent").update(
            "<table cellpadding=0 cellspacing=0 class=popUp id=popUp>" +
            "<tr><td class=iface align=right id=popUpIface height=1>" +
            "<h1 id=popUpTitle></h1>" +
            "<input type=image src=/PWE2/images/iface/back.gif width=14 height=14 title=\"История\" onclick=\"popUp(); " +
            "doLoad(ajpath+'&get_history_back=1', null, 'popUpContent')\"/>" +
            "<input type=image src=/PWE2/images/iface/reload.gif width=14 height=14 title=\"Повтор\" onclick=\"popUp(); " +
            "doLoad(doLoadHistory, null, 'popUpContent')\"/>" +
            "<input type=image src=/PWE2/images/iface/sm_close.gif width=14 height=14 onClick=popUpClose('popUp') title=\"Закрыть\"/>" +
            "</td></tr>" +
            "<tr align=left><td id=popUpContent><center>Идет загрузка...</center></td></tr>" +
            "<tr><td id=popUpIface2 class=iface align=right height=1><a href=\"javascript:func()\" onclick=\"popUpClose('popUp')\">закрыть</a></td></tr>" +
            "</table>");
    }
}

function popUpImg(){
    if ($('popUpShell'))
        popUpClose();
    if ($('body100'))
        var bhght = $('body100').getHeight();
    else
        var bhght = document.body.getHeight();
    var hght = document.viewport.getHeight();
    var scroll = document.viewport.getScrollOffsets();
    var diff = bhght - hght - scroll.top;
    /*alert('height='+hght+' scroll='+scroll);	*/
    /*new Insertion.Top(document.body, '<table class="iePNG" width="100%" ' + 
    	(hght > 0 ? ' height="' + bhght + '" ' : '') + 
    	(scroll.top > 0 ? 'style="top:' + scroll.top + 'px"' : '') + 
    	' id="popUpImg"><tr align="center" valign="center"><td id="popUpImgContent" height="' + hght + '">Идет загрузка...</td></tr>' + 
    	(diff > 0 ? '<tr><td height="' + diff + '"><div style="width:1px;height:1px"><spacer width="1" height="1"></spacer></div></td></tr>' : '')+'</table>');*/
    new Insertion.Top(document.body, '<table class="iePNG" width="100%" ' +
        (hght > 0 ? ' height="' + bhght + '" ' : '') +
        ' id="popUpImg">' +
        (scroll.top > 0 ? '<tr><td height="' + scroll.top + '"><div style="width:1px;height:1px"><spacer width="1" height="1"></spacer></div></td></tr>' : '') +
        '<tr align="center" valign="center"><td id="popUpImgContent" height="' + hght + '">Идет загрузка...</td></tr>' +
        (diff > 0 ? '<tr><td height="' + diff + '"><div style="width:1px;height:1px"><spacer width="1" height="1"></spacer></div></td></tr>' : '')+'</table>');
}

function popUpClose(){
    if ($('popUpShell'))
        $('popUpShell').remove();
    if ($('popUp'))
        $('popUp').remove();        
    if (reloadPage == true){
        reloadPage = false;
        if (confirm('Перезагрузить страницу?')) return document.location.reload(); else return false;
    }
}

function form2hash(form){
    var hash = new Object();
    for (var i=0; i<form.elements.length; i++){
        el = form.elements[i];
        if (!el.name) continue;
        switch (el.type){
            case "text":
            case "textarea":
            case "hidden":
            case "password":
            case "button":
                hash[el.name] = el.value;
                break;
            case "checkbox":
            case "radio":
                if (el.checked)
                    hash[el.name] = el.value;
                break;
            case "select-one":
                hash[el.name] = el.options[el.selectedIndex].value;
                break;
            case "select-multiple":
                hash[el.name] = {};
                for (var j=0; j<el.length; j++){
                    if (el.options[j].selected && !el.options[j].disabled)
                        hash[el.name][j] = el.options[j].value;
                }
                break;
            case "file":
                hash['file'] = el.value;
                break;
        }
    }
    /*alert(Dump(hash));*/
    return hash;
}

function Dump(d,l) {
    if (l == null) l = 1;
    var s = '';
    if (typeof(d) == "object") {
        s += typeof(d) + " {\n";
        for (var k in d) {
            for (var i=0; i<l; i++) s += "  ";
            s += k+": " + Dump(d[k],l+1);
        }
        for (var i=0; i<l-1; i++) s += "  ";
        s += "}\n"
    } else {
        s += "" + d + "\n";
    }
    return s;
}

function submitWarn(id){
    if ($(id))
        $(id).className = 'submitWarn';
}
function submitWarnCB(inst){
    if ($('submit'))
        $('submit').className = 'submitWarn';
}

function isArray(a) {
    return isObject(a) && a.constructor == Array;
}
function isFunction(a) {
    return typeof a == 'function';
}
function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}

function new_win(w, h, n, a){
    if (!n) {
        n = 'new_window';
    }
    if (!a){
        a = '';
    }
    w1=window.open(a, n, 'resizable=yes, menubar=no, status=yes, scrollbars=yes, left='+((screen.availWidth/2)-w/2)+', top='+((screen.availHeight/2)-h/2)+', width='+w+', height='+h);
    w1.focus();
}

function feedback(){
    document.location.href='mail'+'to:'+'dap'+'@'+'parapet'+'.'+'ru';
}

/* дерево */
var cImg = new Image();
cImg.src = '/PWE2/images/plus.gif';
var eImg = new Image();
eImg.src = '/PWE2/images/minus.gif';
var ssel = false;

function toggleState(node) {
    var node;
    if(ssel) resetAll(node);
    doToggle(node);
}

function toggleGroup(str){
    var arr = str.split(',');
    for(var i = 0; i < arr.length; i++){
        toggleState(arr[i]);
    }
}

function doToggle(node, reset) {
    var n;
    var node;
    var n = document.getElementById(node);
    if (n){
        /*m = document.getElementById(ode);*/
        if(!reset) reset = "inline";
        n.style.display = (n.style.display!='none'?'none':reset);
        /*m.style.background = (n.style.display=="inline"?'url(/pic/d2/item1_abg.gif)':'url(/pic/d2/item1_bg.gif)');*/
        document.images[node+'Img'].src = (n.style.display=="inline"?eImg.src:cImg.src);
    }
}

function resetAll(node) {
    var node;
    var n;
    var nIdx = getIdx(node);
    /*var d = document.getElementsByTagName("img");*/
    var n = document.getElementById(node);
    if (n){
        if(n.style.display=="none") {
            for(var i=0; i<d.length; i++)
                if(d[i].onclick) {
                    node = d[i].onclick.toString();
                    node = node.substr(node.lastIndexOf("(")+2);
                    node = node.substr(0, node.lastIndexOf(")")-1);
                    if(getIdx(node)==nIdx) doToggle(node, "none");
                }
        }
    }
}

function getIdx(node) {
    var i = 0;
    var n = document.getElementById(node);
    if(n)
        while(n.parentNode) {
            n = n.parentNode;
            i++;
        }
    return i;
}

pY = 0;
pX = 0;

function showPosition(e) {
    /*alert("Your mouse is at " + pX + " x " + pY);*/
    pX = Event.pointerX(e);
    pY = Event.pointerY(e);
}

/*function toogleMCE(id) {
	try {
		var inst = tinyMCE.getInstanceById(id);
		if (!inst){
			tinyMCE.execCommand('mceAddControl', false, id);
			tinyMCEmode = true;
		} else {
			tinyMCE.execCommand('mceRemoveControl', false, id);
			tinyMCEmode = false;
		}
	} catch(err){
	
	} 
}*/

function toogleMCE(id) {
    try {
        if (!tinyMCE){
            tinyMCE_GZ.init({
                themes : "advanced",
                plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,preview,media,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
                languages : "en",
                disk_cache : true
            }, function() {
                tinyMCE.init({
                    // General options
                    mode : "textareas",
                    theme : "advanced",
                    language : "en",
                    plugins : "safari,pagebreak,style,table,save,advhr,advimage,advlink,preview,searchreplace,paste,fullscreen,noneditable,visualchars,nonbreaking",
                    //layer,emotions,iespell,inlinepopups,media,contextmenu,directionality,,xhtmlxtras,template
                    // Theme options
                    theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,",
                    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,|,visualchars,nonbreaking,|,undo,redo,|,link,unlink,anchor,image,|,cleanup,removeformat",
                    theme_advanced_buttons3 : "tablecontrols,|,visualaid,|,sub,sup,|,charmap,advhr,|,fullscreen,code,preview",
                    //emotions,iespell,media,hr,blockquote,help,ltr,rtl,|
                    theme_advanced_buttons4 : "",
                    theme_advanced_toolbar_location : "top",
                    theme_advanced_toolbar_align : "left",
                    theme_advanced_statusbar_location : "bottom",
                    theme_advanced_resizing : true,

                    // Example content CSS (should be your site CSS)
                    content_css : "/style.css"
                });
            });
        }
        var inst = tinyMCE.getInstanceById(id);
        if (!inst){
            tinyMCE.execCommand('mceAddControl', false, id);
            tinyMCEmode = true;
        } else {
            tinyMCE.execCommand('mceRemoveControl', false, id);
            tinyMCEmode = false;
        }
    } catch(err){
        tinyMCE = false;
        tinyMCEmode = false;
    }
}

function checkAll(theForm, chboxName) {
    var sw = -1;
    for (i = 0, n = theForm.elements.length; i < n; i ++){
        if (theForm.elements[i].name.indexOf(chboxName) != -1){
            if (sw == -1){
                if (theForm.elements[i].checked == true){
                    sw = false;
                } else {
                    sw = true;
                }
            }
            theForm.elements[i].checked = sw;
        }
    }
}

function CheckAll(Element, Name){
    if(document.getElementById) {
	thisCheckBoxes = Element.parentNode.parentNode.parentNode.getElementsByTagName('input');
	for (i = 1; i < thisCheckBoxes.length; i++){
            if (thisCheckBoxes[i].name == Name){
                thisCheckBoxes[i].checked = Element.checked;
                Colorize(document.getElementById(thisCheckBoxes[i].id.replace('cb','tr')), thisCheckBoxes[i]);
            }
	}
    }
}

function Colorize(Element, CBElement){
    if(document.getElementById) {
	if(Element && CBElement){
            Element.className = ( CBElement.checked ? 'selected' : 'default' );
	}
    }
}

function CheckRadioTR(Element){
    if(document.getElementById) {
	CheckTR(Element);
	thisTRs = Element.parentNode.getElementsByTagName('tr');
	for (i = 0; i < thisTRs.length; i++){
            if (thisTRs[i].id != Element.id && thisTRs[i].className != 'header') thisTRs[i].className = 'default';
	}
    }
}

function CheckTR(Element){
    if(document.getElementById) {
	thisCheckbox = document.getElementById(Element.id.replace('tr','cb'));
	thisCheckbox.checked = !thisCheckbox.checked;
	Colorize(Element, thisCheckbox);
    }
}

function CheckCB(Element){
    if(document.getElementById) {
	if(document.getElementById(Element.id.replace('cb','tr'))){Element.checked = !Element.checked;}
    }
}

function triggerAll(theForm, chboxName, state) {
    for (i = 0,n = theForm.elements.length;i<n;i++){
        if (theForm.elements[i].name.indexOf(chboxName) != -1){
            theForm.elements[i].disabled = state;
        }
    }
}

function GeneratePassword(elm, len) {

    if (parseInt(navigator.appVersion) <= 3) {
        alert("Sorry this only works in 4.0+ browsers");
        return true;
    }

    var length = (len ? len : 8);
    var sPassword = "";
    var num = 33;

    for (i=0; i < length; i++) {
        while (((num >=33) && (num <=47)) || ((num >=58) && (num <=64)) || ((num >=91) && (num <=96)) || ((num >=123) && (num <=126))) {
            num = (parseInt(Math.random() * 1000) % 94) + 33;
        }
        sPassword = sPassword + String.fromCharCode(num);
        num = 33;
    }
    $(elm).value = sPassword;
    sPassword = "";
    
    return true;
}

function generatepw(elm, len){
    var gpwiter = 0;
    new PeriodicalExecuter(function(pe){
        GeneratePassword(elm, len);
        gpwiter++;
        if (gpwiter > 10)
            pe.stop();
    }, 0.1);
}

var _qstimeout = null;
var _qswait = 2000;
var _to = null;

function quick_search(text, path, target) {
    if (!target){
        target = 'qsearch_result';
    }
    $(target).update('Идет загрузка...');
    if (_qstimeout) {
        clearTimeout(_qstimeout); _qstimeout=null;
    }
    _qstimeout = setTimeout(function() {
        _qstimeout=null; quick_search_result(text, path, target)
    }, _qswait);
}

function quick_search_result(text, path, target){
    clearTimeout(_qstimeout);
    _qstimeout=null;
    var spl = text.split(/[\s~!@#&$%^*()\[\]{}:\"<>?`=;\',\.\/\\|\-]+/i);
    var words = [];
    for (var i=0; i<spl.length; i++)
        if (!spl[i].match(/^[a-zа-я_0-9]{0,2}$/))
            words[words.length] = spl[i].toLowerCase();
    text = words.join(" ");
    $(target).show();
    //$('qsearch_result').update(text);
    Event.observe(document, 'click', function(event) {
        $(target).hide();
    });
    _qswait = 2000;
    doLoad(path, {
        'text':text
    }, target);
}

function quick_view_comp_obj(comp, query){
    _to=setTimeout("tooltype('qv"+comp+"', '"+query+"')", 500);
}

function tooltype(ID, query){
    new Insertion.Top('popUpContent', "<div id=tooltype class=tooltype onmouseover='clearTimeout(_to)' onmouseout='_to = setTimeout(function() { _to=null;  if ($(\"tooltype\")) $(\"tooltype\").remove(); }, 500);'><div id=tooltype_content>Идет загрузка...</div></div>");
    Position.clone(ID, 'tooltype', {
        'setWidth':false,
        'setHeight':false,
        'offsetLeft':1,
        'offsetTop':10
    });
    clearTimeout(_to);
    _to=null;
    doLoad(query, {
        'nowait':1
    }, 'tooltype_content');
}

function onfly(text, path, elm) {
    $(elm).update('Идет проверка...');
    if (_qstimeout) {
        clearTimeout(_qstimeout); _qstimeout=null;
    }
    _qstimeout = setTimeout(function() {
        _qstimeout=null; onfly_result(text, path, elm)
    }, _qswait);
}

function onfly_result(text, path, elm){
    clearTimeout(_qstimeout);
    _qstimeout=null;
    var spl = text.split(/[\s~!@#&$%^*()\[\]{}:\"<>?`=;\',\.\/\\|\-]+/i);
    var words = [];
    for (var i=0; i<spl.length; i++)
        if (!spl[i].match(/^[a-zа-я_0-9]{0,2}$/))
            words[words.length] = spl[i].toLowerCase();
    text = words.join(" ");
    /*Event.observe(document, 'click', function(event) { $(elm).hide(); });*/
    _qswait = 2000;
    doLoad(path, {
        'text':text
    }, elm);
}

function chkpasswd(pass1, pass2, elm) {
    $(elm).update('');
    if (_qstimeout) {
        clearTimeout(_qstimeout); _qstimeout=null;
    }
    _qstimeout = setTimeout(function() {
        _qstimeout=null;
        if (pass1 != pass2)
            $(elm).update('<span class="warn">Пароль и его повтор не совпадают</span>');
        else
            $(elm).update('<span style="color:green">Пароль и его повтор совпадают</span>');
    }, 2000);
}

function dialog(ID, offsetLeft, offsetTop){
    new Insertion.Top('popUpContent', "<div id=dialog class=dialog><div align=right style=\"margin-bottom:5px\"><input type=image src=/PWE2/images/iface/sm_close.gif width=14 height=14 onClick=\"$('dialog').remove()\" title=\"Закрыть\"/></div><div id=dialog_content>Идет загрузка...</div></div>");
    Position.clone(ID, 'dialog', {
        'setWidth':false,
        'setHeight':false,
        'offsetLeft':(offsetLeft ? offsetLeft : 1),
        'offsetTop':(offsetTop ? offsetTop : 1)
    });
}

/*function addJS(src){
	var script = document.createElement('script');
	script.setAttribute('type', 'text/javascript');
	//script.setAttribute('charset', charset);
	script.setAttribute('src', src);
	// InsertBefore for IE.
	// IE crashes on using appendChild before the head tag has been closed.
	var head = document.getElementsByTagName('head').item(0);
	head.insertBefore(script, head.firstChild);
}*/

function addMapPoint(eventX, eventY, offsetX, offsetY){
    var _subt_pos = Position.positionedOffset($('subtable'));

    var X = eventX - offsetX - 5;
    var Y = eventY - offsetY - 5;
    if (X < 1) X = 1;
    if (Y < 1) Y = 1;

    var XX = X - _subt_pos[0] + 3;
    var YY = Y - _subt_pos[1] + 3;
    if (XX < 1) XX = 1;
    if (YY < 1) YY = 1;
    
    var IE='\v'=='v';
    if (IE){
        X = X - _subt_pos[0] - 3;
        Y = Y - _subt_pos[1] - 3;
        XX = XX - 3;
        YY = YY - 3;
    }

    if ($('curpoint'))
        $('curpoint').remove();
    new Insertion.Top('container', '<img src="/files/map/dom.gif" id="curpoint" border="0" style="position:absolute; top:'+Y+'px; left:'+X+'px">');

    document.dataForm.X.value = XX;
    document.dataForm.Y.value = YY;
}

function rsz_bn(name){
    if ($('_'+name).visible()){
        $('_'+name).hide();
        $(name).setStyle({
            height:'290px'
        });
    } else {
        $('_'+name).show();
        $(name).setStyle({
            height:'40px'
        });
    }
}

function substring(str, obj){
    if (obj && str.length > 0){
        var out = '';
        out = obj.sub(str, '');
        out = obj.strip();
        /*alert(str+' | '+obj+' | '+out);*/
        return out;
    }
}

function sales_urls(form){
    var chb = form.getInputs('checkbox', 'sl[]');
    for (var i=0; i<chb.length; i++){
        if (i == 20){
            break;
        }
        var val = chb[i].getValue();
        if ($('url'+val)){
            var url = $('url'+val).getValue();
            if (url.length > 0){
                window.open(url, url, '');
            }
        }
    }
}

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}
/* USE:
 * var value = $RF('radio_btn_id');
 * var value = $RF('form_id', 'radio_grp_name');
 * */

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {input id} input
* OR
* @param {input id} input
* @param {set state, boolean} state
*/
function readonly_input(input, state){
    $(input).readOnly = state;
    if (state == false){
        $(input).style.backgroundColor = '#ffffff';
    } else {
        $(input).style.backgroundColor = '#eeeeee';
    }
}