function preload()
{
        if (document.images)
        {
                var imgsrc = preload.arguments;
                arr=new Array(imgsrc.length);
                for (var j=0; j<imgsrc.length; j++)
                {
                    arr[j] = new Image;arr[j].src = imgsrc[j];
                }
        }
}
function SetSearchDmdOrg(PageSearch)
{
    var SetSearchStrVal="";
    if (document.getElementById('docdmdyear'))
    {
        var oListBox=document.getElementById('docdmdyear');
        SetSearchStrVal=PageSearch+"reforginn="+document.getElementById('reforginn').value+"&reforgacs="+document.getElementById('reforgacs').value+"&docdmdyear="+oListBox.options[oListBox.selectedIndex].text;
    }
    else
    {
        SetSearchStrVal=PageSearch+"reforginn="+document.getElementById('reforginn').value+"&reforgacs="+document.getElementById('reforgacs').value;
    }
    return SetSearchStrVal;
}
function StsHandle()
{
    var oListBox=document.getElementById('docdmdsts');
    var strValue=oListBox.options[oListBox.selectedIndex].value;
    if (strValue==2)
    {
        if (confirm('Перевод статуса заявки в "Отправленные на рассмотрение" делает ее дальнейшее изменение невозможным. Вы уверены, что хотите изменить статус?'))
        {
              oListBox.selectedIndex=1;
        }
        else
        {
              oListBox.selectedIndex=0;
        }
    }
    if (strValue>2)
    {
        alert('Выбранный статус недоступен для выбора на форме редактирования!');
        oListBox.selectedIndex=0;
    }
}
function ArtHandle()
{
    var oListBox=document.getElementById('dtbdmdart');
    art=oListBox.options[oListBox.selectedIndex].value;
    ot="";
    document.getElementById('dtbdmdcsi').value=0;
    document.getElementById('REFCSINAM').value="";
    document.getElementById('csilist').style.visibility = 'hidden';
}
/* Вызов формы для изменения заявки */
function GetDocDmdIdn(PageSearch)
{
    var SetSearchStrVal="";
    var oListBox=document.getElementById('VIEWDTBDMD');
    var strString=oListBox.options[oListBox.selectedIndex].text;
    var strMode="&mode=edit";
    if (strString.indexOf("(новая)")==-1)
    {
        strMode="&mode=view";
        alert("Статус заявки предусматривает режим 'только для просмотра'!");
    }
    if(oListBox.options[oListBox.selectedIndex].value!='0')
    {
        SetSearchStrVal=PageSearch+oListBox.options[oListBox.selectedIndex].value+strMode;
    }
    else
    {
        SetSearchStrVal=this.location;
    }
    return SetSearchStrVal;
}
/* Вызов формы для печати заявки */
function PrnDmdIdn(PageSearch)
{
    var SetSearchStrVal="";
    var oListBox=document.getElementById('VIEWDTBDMD');
    var strString=oListBox.options[oListBox.selectedIndex].text;
    if(oListBox.options[oListBox.selectedIndex].value!='0')
    {
        SetSearchStrVal=PageSearch+oListBox.options[oListBox.selectedIndex].value;
    }
    else
    {
        SetSearchStrVal=this.location;
    }
    return SetSearchStrVal;
}
/* Вызов формы для изменения строки по заявке*/
function GetDtbDmdIdn(PageSearch)
{
    var SetSearchStrVal="";
    var oListBox=document.getElementById('VIEWDTBDMD');
    if(oListBox.options[oListBox.selectedIndex].value!='0')
    {
        SetSearchStrVal=PageSearch+oListBox.options[oListBox.selectedIndex].value;
    }
    else
    {
        SetSearchStrVal=this.location;
    }
    return SetSearchStrVal;
}
/* Обработка нажатия кнопки изменения строки по заявке */
function DtbDmdEditHandle()
{
    var oListBox=document.getElementById('VIEWDTBDMD');
    document.getElementById('execute').value='edit';
    document.getElementById('cur_idn').value=oListBox.options[oListBox.selectedIndex].value;
    return '';
}
/* Вызов формы для просмотра заводского номера по заявке */
function GetDtbDmdMnmIdn(PageSearch)
{
    var SetSearchStrVal="";
    var oListBox=document.getElementById('VIEWDTBDMDMNM');
    if(oListBox.options[oListBox.selectedIndex].value!='0')
    {
        SetSearchStrVal=PageSearch+oListBox.options[oListBox.selectedIndex].value;
    }
    else
    {
        SetSearchStrVal=this.location;
    }
    return SetSearchStrVal;
}
/* Обработка нажатия кнопки для удаления заявки */
function DelRecDmd(SecIdn)
{
    var SetSearchStrVal="";
    var oListBox=document.getElementById('docdmdyear');
    var oViewBox=document.getElementById('VIEWDTBDMD');
    var strString=oViewBox.options[oViewBox.selectedIndex].text;
    if (strString.indexOf("(новая)")==-1)
    {
        alert("Удаление возможно только для новых заявок");
    }
    else
    {
        if (confirm("Удалить текущую заявку?"))
        {
            SetSearchStrVal="../pages/detail.php?sec="+SecIdn+"&"+"reforginn="+document.getElementById('reforginn').value+"&reforgacs="+document.getElementById('reforgacs').value+"&docdmdyear="+oListBox.options[oListBox.selectedIndex].text+"&del_idn="+oViewBox.options[oViewBox.selectedIndex].value;
        }
        else
        {
            SetSearchStrVal="../pages/detail.php?sec="+SecIdn+"&"+"reforginn="+document.getElementById('reforginn').value+"&reforgacs="+document.getElementById('reforgacs').value+"&docdmdyear="+oListBox.options[oListBox.selectedIndex].text+"&cur_idn="+oViewBox.options[oViewBox.selectedIndex].value;
        }
    }
    return SetSearchStrVal;
}
/* Обработка нажатия кнопки для удаления строки по заявке */
function DelRecDmdEdt()
{
    var oListBox=document.getElementById('VIEWDTBDMD');
    if (confirm("Удалить текущую строку из заявки?"))
    {
        document.getElementById('execute').value='delete';
        document.getElementById('cur_idn').value=oListBox.options[oListBox.selectedIndex].value;
    }
    else
    {
        document.getElementById('execute').value='review';
        document.getElementById('cur_idn').value=oListBox.options[oListBox.selectedIndex].value;
    }
    return '';
}
/* Обработка нажатия кнопки для удаления заводского номера по заявке */
function DelRecDmdMnmEdt()
{
    var oListBox=document.getElementById('VIEWDTBDMDMNM');
    if (confirm("Удалить текущий заводской номер?"))
    {
        document.getElementById('execute').value='delete';
        document.getElementById('cur_idn').value=oListBox.options[oListBox.selectedIndex].value;
    }
    else
    {
        document.getElementById('execute').value='review';
        document.getElementById('cur_idn').value=oListBox.options[oListBox.selectedIndex].value;
    }
    return '';
}
/* Обработка нажатия кнопки создания нового зав. номера по заявке */
function MnmCreateHandle()
{
    var oListBox=document.getElementById('VIEWDTBDMDMNM');
    if (document.getElementById('num_row').value>=document.getElementById('dtbdmdnmb').value)
    {
        alert('Количество заводских номеров не может быть больше общего количества СИ!');
        document.getElementById('execute').value='review';
        document.getElementById('cur_idn').value=oListBox.options[oListBox.selectedIndex].value;
    }
    else
    {
        document.getElementById('execute').value='create';
    }
    return '';
}
/* Обработка нажатия кнопки изменения зав. номера по заявке */
function MnmEditHandle()
{
    var oListBox=document.getElementById('VIEWDTBDMDMNM');
    document.getElementById('execute').value='edit';
    document.getElementById('cur_idn').value=oListBox.options[oListBox.selectedIndex].value;
    return '';
}
/* Обработка введенного количества СИ, */
/* чтобы  соответствовало количеству зав. номеров */
function CheckNumMnm()
{
    if ((document.getElementById('dtbdmdnmb').value!="") && (document.getElementById('dtbdmdnmb').value!=0))
    {
        if (document.getElementById('dtbdmdnmb').value<document.getElementById('num_row').value)
        {
            alert('Количество заводских номеров не может быть больше общего количества СИ!');
            document.getElementById('dtbdmdnmb').value=document.getElementById('num_row').value;
            document.getElementById('dtbdmdnmb').focus();
        }
    }
    else
    {
        alert('Количество СИ должно быть больше нуля!');
        if (document.getElementById('num_row').value>0)
        {
            document.getElementById('dtbdmdnmb').value=document.getElementById('num_row').value;
        }
        else
        {
            document.getElementById('dtbdmdnmb').value=1;
        }
        document.getElementById('dtbdmdnmb').focus();
    }
    return '';
}
/* Только символы из диапазона validchars - только для события keypress */
function OnlyValid(oTextbox, oEvent)
{
    var sValidChars = oTextbox.getAttribute('validchars');
    /* IE как всегда отдельная песня */
    oEvent=oEvent || window.event;
    var isIE=document.all;
    var code=isIE ? oEvent.keyCode : oEvent.charCode;
    /* Системные кнопки пропускаем */
    if (code<32 || oEvent.ctrlKey || oEvent.altKey) return true;
    var sChar=String.fromCharCode(code);
    /* Проверяем наш символ в заданном диапазоне */
    var bIsValidChar = sValidChars.indexOf(sChar) > -1;
    return bIsValidChar;
}
/* Функции для обращения к справочнику REFCSI */
var ot="", timer=0, art=0, x=-1, y=0;
// Определение координаты элемента
function pageX(elem)
{
return elem.offsetParent ?
    elem.offsetLeft + pageX( elem.offsetParent ) :
    elem.offsetLeft;
}
function pageY(elem)
{
return elem.offsetParent ?
    elem.offsetTop + pageY( elem.offsetParent ) :
    elem.offsetTop;
}
/* Обработка нажатия клавиш на поле REFCSINAM */
function CsiKeyPress(e)
{
    e=e||window.event;
    t=(window.event) ? window.event.srcElement : e.currentTarget;
    g=document.getElementById('csilist');
    if(x==-1&&y==0)
    {
        x=pageX(t); y=pageY(t);
        g.style.top = y + t.clientHeight+1 + "px";
        g.style.left = x + "px";
    }
    if(e.keyCode==40)
    {
        g.focus();
        g.selectedIndex=0;
        return;
    }
    if(ot==t.value)return;
    ot=t.value;
    if(timer) clearTimeout(timer);
    if(ot.length<3)
    {
        timer=0;
        document.getElementById('csilist').style.visibility = 'hidden';
        return;
    }
    timer=window.setTimeout('Load()',1000);
}
/* Загрузка данных */
function Load()
{
   ajaxLoad('csilist', '../pages/refcsi.php?REFCSINAM='+ot+'&REFCSIART='+art, '','','');
   document.getElementById('csilist').style.visibility='visible';
   timer=0;
}
function ajaxLoad(obj,url,defMessage,post,callback)
{
    var ajaxObj;
    if (defMessage) document.getElementById(obj).innerHTML=defMessage;
    if(window.XMLHttpRequest)
    {
        ajaxObj = new XMLHttpRequest();
    }
    else
        if(window.ActiveXObject)
        {
            ajaxObj = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else
        {
            return;
        }
    ajaxObj.open ((post?'POST':'GET'), url);
    if (post&&ajaxObj.setRequestHeader)
        ajaxObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=windows-1251;");
    ajaxObj.setRequestHeader("Referer", location.href);

    ajaxObj.onreadystatechange = ajaxCallBack(obj,ajaxObj,(callback?callback:null));
    ajaxObj.send(post);
    return false;
}
function ajaxCallBack(obj, ajaxObj, callback)
{
    return function()
    {
        if(ajaxObj.readyState == 4)
        {
            if(callback) if(!callback(obj,ajaxObj))return;
            if (ajaxObj.status==200)
            {
                if(ajaxObj.getResponseHeader("Content-Type").indexOf("application/x-javascript")>=0)
                    eval(ajaxObj.responseText);
                else
                {
                    data=ajaxObj.responseText;
                    obj=document.getElementById(obj);
                    obj.options.length = 0;
                    var re=new RegExp ("<option([^<]+)</option>","img");
                    data=data.match(re);
                    if(data)
                    {
                        for(i=0;i<data.length;i++)
                        {
                            var re0 = new RegExp ("value=[\'\"]([^\'\"]+)[\'\"]","i"); value=re0.exec(data[i]); value= value==null? '' : value[1];
                            var re1=new RegExp ("<option [^>]+>([^<]+)</option>","i"); text=re1.exec(data[i]); text= text==null? null : text[1];
                            var re4 = new RegExp ("class=[\'\"]([^\'\"]+)[\'\"]","i"); defclass=re4.exec(data[i]);
                            j=obj.options.length;
                            if (text !=null)
                            {
                                var re2 = /selected/i; defSelected=re2.test(data[i]);
                                obj.options[j] = new Option(text, value, defSelected, defSelected);
                                var re3 = /disabled/i; if(re3.test(data[i]))obj.options[j].disabled=true;
                                if(defclass!=null) obj.options[j].className=defclass[1];
                            }
                        }
                    }
                }
            }
            else alert('Ошибка при обращении к справочнику БД!');
        }
    }
}
/* Обработка нажатия клавиш в списке значений, загруженных с REFCSI */
function CsiListKeyPress(e)
{
    e=e||window.event;
    t=(window.event) ? window.event.srcElement : e.currentTarget;
    var oListBox=document.getElementById('csilist');
    if(e.keyCode==13)
    { // Enter
        document.getElementById('REFCSINAM').value=oListBox.options[oListBox.selectedIndex].text;
        document.getElementById('dtbdmdcsi').value=oListBox.options[oListBox.selectedIndex].value;
        document.getElementById('REFCSINAM').focus();
        document.getElementById('csilist').style.visibility = 'hidden';
    }
    if(e.keyCode==27)
    { // Escape
        document.getElementById('REFCSINAM').focus();
        document.getElementById('csilist').style.visibility = 'hidden';
    }
    if(e.keyCode==38&&t.selectedIndex==0)
    { // Up
        document.getElementById('REFCSINAM').focus();
        document.getElementById('csilist').style.visibility = 'hidden';
    }
}
function CsiListChange()
{
    var oListBox=document.getElementById('csilist');
    ot=oListBox.options[oListBox.selectedIndex].text;
    document.getElementById('dtbdmdcsi').value=oListBox.options[oListBox.selectedIndex].value;
    document.getElementById('REFCSINAM').value=ot;
}
function CsiListDblClick()
{
    var oListBox=document.getElementById('csilist');
    ot=oListBox.options[oListBox.selectedIndex].text;
    document.getElementById('dtbdmdcsi').value=oListBox.options[oListBox.selectedIndex].value;
    document.getElementById('REFCSINAM').value=ot;
    document.getElementById('csilist').style.visibility = 'hidden';
}
function SetSearchDmdYear(PageSearch)
{
    var SetSearchStrVal="";
    var oListBox=document.getElementById('docdmdyear');
    SetSearchStrVal=PageSearch+"reforginn="+document.getElementById('reforginn').value+"&reforgacs="+document.getElementById('reforgacs').value+"&docdmdyear="+oListBox.options[oListBox.selectedIndex].text;
    return SetSearchStrVal;
}
function SetSearchLbl(PageSearch)
{
        var SetSearchStrVal="";
        SetSearchStrVal=PageSearch+document.getElementById('dtbordmetmnmlbl').value;
        return SetSearchStrVal;
}
function SetSearchCsi(PageSearch)
{
        var SetSearchStrVal="";
        SetSearchStrVal=PageSearch+document.getElementById('refcsinam').value;
        return SetSearchStrVal;
}
function SetSearchOrd(PageSearch)
{
        var SetSearchStrVal="";
        SetSearchStrVal=PageSearch+"ordtyp="+document.getElementById('ordtyp').value+"&ordnum="+document.getElementById('ordnum').value+"&ordidn="+document.getElementById('ordidn').value;
        return SetSearchStrVal;
}
function SetCat(set_cat)
{
        var selVals=new Array();
        for (var i=0; i<document.getElementById('RefCat').length; i++)
        {
                if (document.getElementById('RefCat').options[i].selected)
                {
                    selVals[selVals.lenght]=document.getElementById('RefCat').options[i].value;
                    open(set_cat+selVals[selVals.lenght], "_parent");
                }
        }
}
function SetSearchStr(PageSearch)
{
        var SetSearchStrVal="";
        SetSearchStrVal=PageSearch+document.getElementById('SearchField').value;
        return SetSearchStrVal;
}
function SecVot(ToVote)
{
        var SecVotHref="";
        for (var i=1; i<6; i++)
        {
                VoteRadioIdStr="VoteRadioId"+i;
                if (document.getElementById(VoteRadioIdStr).checked)
                {
                        SecVotHref=ToVote+document.getElementById(VoteRadioIdStr).value;
                        return SecVotHref;
                        break;
                }
        }
}
function SetHom(HomPag)
{
        var SetHomVal="";
        for (var i=0; i<document.getElementById('RefCat').length; i++)
        {
                if (document.getElementById('RefCat').options[i].selected)
                {
                        SetHomVal=HomPag+document.getElementById('RefCat').options[i].value;
                        return SetHomVal;
                        break;
                }
        }
}
function InsSubTitle()
{
        var OutStr="";
        if (document.getElementById('subtitle').value!='')
        {
                OutStr="{Подзаголовок-"+document.getElementById('subtitle').value+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsSimTitle()
{
        var OutStr="";
        if (document.getElementById('simtitle').value!='')
        {
                OutStr="{Простой подзаголовок-"+document.getElementById('simtitle').value+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsEmail()
{
        var OutStr="";
        if (document.getElementById('email').value!='')
        {
                OutStr="{Email-"+document.getElementById('email').value+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsRefTitle()
{
        var OutStr="";
        var oListBox=document.getElementById('reftitle');
        if (oListBox.value!='0')
        {
                OutStr="{Загол.ссылка-"+oListBox.value+"&&"+oListBox.options[oListBox.selectedIndex].text+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsPicRight()
{
        var OutStr="";
        if (document.getElementById('pic_right').value!='')
        {
                OutStr="{Рисунок справа-"+document.getElementById('pic_right').value+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsPicLeft()
{
        var OutStr="";
        if (document.getElementById('pic_left').value!='')
        {
                OutStr="{Рисунок слева-"+document.getElementById('pic_left').value+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsPicCenter()
{
        var OutStr="";
        if (document.getElementById('pic_center').value!='')
        {
                OutStr="{Рисунок в центре-"+document.getElementById('pic_center').value+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsTable()
{
        var OutStr="";
        var oListBox=document.getElementById('tbllst');
        if (oListBox.value!='0')
        {
                OutStr="{Таблица-"+oListBox.value+"&&"+oListBox.options[oListBox.selectedIndex].text+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsMap()
{
        var OutStr="";
        if (document.getElementById('map').value!='')
        {
                OutStr="{Схема-"+document.getElementById('map').value+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsExtUrl()
{
        var OutStr="";
        if ((document.getElementById('exturlnam').value!='') && (document.getElementById('exturlurl').value!=''))
        {
                OutStr="{Внеш.ссылка-"+document.getElementById('exturlnam').value+"&&"+document.getElementById('exturlurl').value+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsIntUrl()
{
        var OutStr="";
        var oListBox=document.getElementById('inturl');
        if (oListBox.value!='0')
        {
                OutStr="{Внут.ссылка-"+oListBox.value+"&&"+oListBox.options[oListBox.selectedIndex].text+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsIntObj()
{
        var OutStr="";
        var oListBox=document.getElementById('intobj');
        if (oListBox.value!='0')
        {
                OutStr="{Внут.объект-"+oListBox.value+"&&"+oListBox.options[oListBox.selectedIndex].text+"}";
        }
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsNewPar()
{
        var OutStr="{Абзац}";
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsNewParBrk()
{
        var OutStr="{Абзац с отступом}";
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsDev()
{
        var OutStr="{Разделитель}";
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function InsSerRes()
{
        var OutStr="{Заказ}";
        document.getElementById('paginfart').focus();
        with(document.selection.createRange())
        {
                collapse();
                text=OutStr;
        }
}
function AskDelRec()
{
        if (confirm("Удалить текущую запись?"))
        {
              document.all.del.value='Yes';
        }
        else
        {
              document.all.del.value='No';
        }
}
function ChangeImg()
{
    if(document.images)
    {
        eval("document."+ChangeImg.arguments[0]+".src=('"+ChangeImg.arguments[1]+"')");
    }
}

var left_time=20; // От какой цифры начать обратный отсчет
var speed_time=1000; // Скорость отсчета, 1000 - 1 секунда, 60 000 - 1 минута.
function countdown()
{
    // Уменьшить таймер
    left_time--;
    // Вывести элемент
    document.getElementById('h_txt_time').innerHTML=left_time;
    // Покрасить текст в красный цвет
    document.getElementById('h_txt_time').style.color='red';
    if (left_time <= 0)
    {
        // Если время закончилось - переноправить на другую страницу
        //document.location = document.location;
        this.location.reload();
    }
    else
    {
        setTimeout('countdown()', speed_time);
    }
}

