var unsetClass = false;
var closePopUp = false;
var tinyMCE = 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 history_back = [];
var history_forward = [];

var etc_path = "/PWE/etc/";

function func(){}

function authform(elm){
    var str =   '<div class="authform" id="authform" style="position:absolute">'+
                '<form name="authForm" id="authForm" method="post" action="" enctype="multipart/form-data">'+
                '<input type="hidden" name="autorize" value="1"/>'+
                '<table><tr><td>Логин</td><td><input type="text" tabindex="1" size="20" name="login"/></td>'+
                '<td><a href="javascript:func()" onclick="$(\'authform\').remove()"><img src="/PWE2/images/iface/sm_close.gif" width="14" height="14" border="0" title="Закрыть"/></a></td></tr>'+
                '<tr><td>Пароль</td><td><input type="password" tabindex="2" size="20" name="password"/></td><td></td></tr>'+
                '<tr><td></td><td><input type="submit" value="Отправить"/></td><td></td></tr></table></form></div>';
    if ($(elm)){
        new Insertion.Top(elm, str);
    }
}

function ping(val){
    try{
        var req = new JsHttpRequest();
        req.onreadystatechange = function(){
            if (req.readyState == 4){
                if (req.responseJS){
                    if (val == 1){
                        if (req.responseJS.reloadPage){
                            if (!parent.document.URL.match(/\?cajnsd\=1/g)){
                                document.location.href = parent.document.URL + '?cajnsd=1';
                            }
                        }
                    }
                    return true;
                }
            }
        }
        req.caching = false;
        req.open('POST', '/PWE2/etc/ping.php', true);
        req.send({
            'ping':1
        });
    } catch(e){}
}

function cpanelOpen(hash){
    // CPanel container
    ping(1);
    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 = '';
    var target_elm = null;

    if (isObject(elm)){
        target_elm = elm;
    } else {
        target_elm = $(elm);
    }

    // Создаем новый объект JSHttpRequest.
    var req = new JsHttpRequest();
    if (tinyMCE && (elm == 'popUpContent' || (elm == 'dialog_content' && path.match(/module=cpanel\.help\.aj/))) && (!arr || arr.tinymce == false)){
        removeMCE2(['text', 'text_ru', 'text_en', 'text_fr']);
    }
    try{
        if ((isArray(arr) || isObject(arr)) && arr.nowait){
            
        } else {
            wait();
        }
    } catch(e){}

    // Код, АВТОМАТИЧЕСКИ вызываемый при окончании загрузки.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.responseJS) {
                // Result
                if (!elm || elm=='none' || !$(elm))
                    elm = 'result';
                if (doLoadForm) {
                    $(elm).value = req.responseJS.wf_main;
                    doLoadForm = false;
                } else {
                    if (isObject(target_elm)){
                        target_elm.update(req.responseJS.wf_main);
                        new Element.show(target_elm);
                    }
                    if ((elm == 'popUpContent' || isObject(elm)) && popUpJustify == true){
                        document.body.scrollTo();
                        popUpJustify = false;
                    }
                    if (elm == 'popUpContent' || isObject(elm)){
                        if ($('history_back') && $('history_forward')){
                            if (history_back.length > 0){
                                $('history_back').src = '/PWE2/images/iface/back.gif';
                                var last = history_back.last();
                                $('history_back').onclick = function(){history_forward.unshift(history_back.slice(history_back.length-1));history_back = history_back.slice(0, history_back.length-2);doLoad(last, null, 'popUpContent');};
                            } else {
                                $('history_back').src = '/PWE2/images/iface/back2.gif';
                                $('history_back').onclick = function(){};
                            }
                            if (history_forward.length > 0){
                                $('history_forward').src = '/PWE2/images/iface/forward.gif';
                                var next = history_forward.first();
                                $('history_forward').onclick = function(){history_forward = history_forward.slice(1);doLoad(next, null, 'popUpContent');};
                            } else {
                                $('history_forward').src = '/PWE2/images/iface/forward2.gif';
                                $('history_forward').onclick = function(){};
                            }
                            if (history_back.last() != path){
                                history_back.push(path);
                            }
                        }
                    }
                }
                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' || isObject(elm)) && 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.change_lang)){
        cpanelOpen();
    }
    if (arr && arr.doLoadAfter){
        _qsto = setTimeout(function() {
            _qsto=null;
            doLoad(arr.doLoadAfter, null, (arr.doLoadAfterTarget ? arr.doLoadAfterTarget : 'popUpContent'));
        }, 2000);
        return;
    }
}

function popUp(disable_controls){
    if ($('popUpShell')){
        popUpClose();
    }
    if ($('body100')){
        var bhght = $('body100').getHeight();
    } else {
        var bhght = document.body.getHeight();
    }
    var hght = document.viewport.getHeight();
    var wdth = document.viewport.getWidth();
    var scroll = document.viewport.getScrollOffsets();
    var diff = bhght - hght - scroll.top;

    if (wdth > 1200){
        var width = '1200';
    } else {
        var width = '100%';
    }

    if ($('fullwindow')){
        width = '100%';
        $("fullwindow").setStyle({
            height: '300px',
            width: (width != '100%' ? width+"px" : width),
            margin: '0 auto'
        });
    } 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 width="+width+">" +
        "<tr><td class=iface align=right id=popUpIface height=1>" +
        "<h1 id=popUpTitle></h1>" +
        (disable_controls == true ? "" : "<input type=image src=/PWE2/images/iface/house.gif width=14 height=14 title=\"Главстраница\" onclick=\"doLoad(ajpath+'&module=cpanel.welcome.aj', null, 'popUpContent')\">" +
        "<input id=history_back type=image src=/PWE2/images/iface/back2.gif width=14 height=14 title=\"История\"/>" +
        "<input id=history_forward type=image src=/PWE2/images/iface/forward2.gif width=14 height=14 title=\"История\"/>" +
        "<input id=re_load 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/tray.gif width=14 height=14 title=\"\" onclick=\"popUpTray($('popUpTitle').innerHTML)\">" +
        "<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>" +
        ($('fullwindow') ? "" : "<tr><td id=popUpIface2 class=iface align=right height=1><a href=\"javascript:func()\" onclick=\"popUpClose('popUp')\">закрыть</a></td></tr>") +
        "</table>");
}

function popUpImg(dncpup, id){
    if ($('popUpShell') && !dncpup)
        popUpClose();
    if ($('popUpImg') &&  !dncpup){
        $('popUpImg').remove();
    }
    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 ($('cpanel')){
        scroll.top = scroll.top + 30;
    }
    new Insertion.Top(document.body, '<table class="iePNG" width="100%" ' +
        (hght > 0 ? ' height="' + bhght + '" ' : '') +
        ' id="'+(id ? 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 popUpTray(popUpTitle){
    $('popUpShell').hide();
    doLoad(ajpath+'&module=cpanel.tray.aj', {'current':doLoadHistory, 'back':history_back, 'forward':history_forward, 'title':popUpTitle}, 'cpanelTray');
}

function popUpUnTray(hash){
    $('cpanelTray').update();
    history_back = hash.back;
    history_forward = hash.forward;
    popUp();
    doLoad(hash.current, {'cpanelTrayClear':1}, 'popUpContent');
}

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).hasClassName('submitWarn')){
        $(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 = '';
    }
    if (!w){
        w = document.viewport.getWidth();
    }
    if (!h){
        h = document.viewport.getHeight();
    }
    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) {
    pX = Event.pointerX(e);
    pY = Event.pointerY(e);
}

function toogleMCE2(id) {
    try {
        if (tinyMCE){
            if (isArray(id)){
                var _arr = id;
            }else {
                var _arr = [id];
            }
            for (var k in _arr){
                var inst = tinyMCE.get(_arr[k]);
                if (!inst){
                    tinyMCE.execCommand('mceAddControl', false, _arr[k]);
                } else {
                    tinyMCE.execCommand('mceRemoveControl', false, _arr[k]);
                }
            }
        } else {
            alert('No tinyMCE');
        }
    } catch (e){}
}

function removeMCE2(id){
    try {
        if (isArray(id)){
            var arr = id;
        } else {
            var arr = [id];
        }
        for (var k in arr){
            tinyMCE.execCommand('mceRemoveControl', false, arr[k]);
        }
    } catch (e){}
}

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,
                convert_urls : false,
		relative_urls : false,
                extended_valid_elements : "script[language|type],div[class|title|style]"
            }, function() {
                tinyMCE.init({
                    // General options
                    mode : "none",
                    theme : "advanced",
                    language : "en",
                    plugins : "safari,pagebreak,style,table,save,advhr,advimage,advlink,preview,searchreplace,paste,fullscreen,noneditable,visualchars,nonbreaking,media",
                    //layer,emotions,iespell,inlinepopups,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,media,|,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,
                    convert_urls : false,
                    relative_urls : false,
                    // Example content CSS (should be your site CSS)
                    content_css : "/style.css",
                    extended_valid_elements : "script[language|type],div[class|title|style]"
                });
                if (tinyMCE){
                    var inst = tinyMCE.get(id);
                    if (!inst){
                        tinyMCE.execCommand('mceAddControl', false, id);
                    } else {
                        tinyMCE.execCommand('mceRemoveControl', false, id);
                    }
                }
            });
        }
    if (tinyMCE){
        var inst = tinyMCE.get(id);
        if (!inst){
            tinyMCE.execCommand('mceAddControl', false, id);
        } else {
            tinyMCE.execCommand('mceRemoveControl', false, id);
        }
    }
    /* } catch(err){
        tinyMCE = 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);
}

function dialog(ID, offsetLeft, offsetTop){
    var targ;
    if ($('popUpContent')){
        targ = $('popUpContent');
    } else {
        targ = document.body;
    }
    new Insertion.Top(targ, "<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)
    });
    Event.observe(window, 'keypress', function(event){if (event.keyCode==27 || event.which==27) $('dialog').remove();});
}


