// Чаво надо? :)
function exp(lnk,el)
{
	var row = document.getElementById(el);
	var stat = row.className.indexOf('off')+1;

	var srch = (stat) ? 'off' : 'on';
	var repl = (stat) ? 'on' : 'off';

	row.className = row.className.replace(srch,repl);
	lnk.className = lnk.className.replace(srch,repl);

	return false;
}

var SynList = new Array();
function saveSyn (syn,id) {
	var place = document.getElementById('check'+id);
	var SynSize=SynList.length;
	var id = parseInt(id);
	if (place.checked==true) {
		SynList[id]=syn;
	} else {
		if (SynList[id])
		{
			SynList[id]=false;
		}
	}
}
function show_hide(tid,id){
    dv=document.getElementById(id);
    dt=document.getElementById(tid);
    if(dv.style.display=='none')
     {
      dv.style.display='block';
      dt.innerText='Спрятать';
     }
     else
     {
      dv.style.display='none';
      dt.innerText='Показать';
     }
}
function validate_email(form_name,em_fld){
 if(em_fld=="") em_fld="login";

 var email=eval('document.'+form_name+'.'+em_fld);
 var form=eval('document.'+form_name);
 var reg = new RegExp("[0-9a-z_\\.\\-]+@[0-9\\-a-z_^.]+\\.[a-z]", 'i');
 if (!reg.test(email.value)) {
	 alert('email неверен, укажите в качестве логина свой email'); 
	 return false;
}
 else form.submit();
}


function foo () {
	
}
function disButton () {
	document.getElementById('subButton').value = 'ждите ...';
	document.getElementById('subButton').disabled = true;
	document.getElementById('panelAuto').submit();
}
function clearKey(in_id) {
	document.getElementById(in_id).value='';
}
function upperMe(inputStr,MaxLen,inputNum)
{
  if (inputStr.value.length > MaxLen)
      inputStr.value = inputStr.value.substring(0, MaxLen);
 document.getElementById(inputNum).innerHTML = 'Осталось '+(MaxLen - inputStr.value.length)+' символов';
}
function SubmitSyn (dv,main,id) {
	var SynSize=SynList.length;
	var i = 0;
	var url = '';
	for (i=0;i<=SynSize;i++)
	{
		if (SynList[i])
		{
			url = url + SynList[i] + '|';
		}
	}
	SynList = '';
	SynList = new Array();
	ajax_show(dv,'morph_syn_save',url+main);
	clearSyn('paste_'+id);
}

function clearSyn (id) {
	var arrspan = document.getElementsByTagName('SPAN');
	for(var i=0;i<arrspan.length;i++) {
		if(arrspan[i].className==id) {
			arrspan[i].style.display="none";
		}
	}
}

function pop(url,width,height) {
	if (width==undefined || width=='') {
		width='600';
	}
	if (height==undefined || height=='') {
		height='600';
	}
	window.open(url,'_blank','scrollbars, resizable, width='+width+',height='+height+', left=200, top=200');
}
function click2obid (obid) {
	document.getElementById('clicksimg').src= '/clicks.php?obid='+obid;
}

function help(id,width,height) {
	if (width==undefined || width=='') {
		width='600';
	}
	if (height==undefined || height=='') {
		height='600';
	}
	window.open('/index.php?action=help&id='+id,'_blank','scrollbars, resizable, width='+width+',height='+height+', left=200, top=200');
}

function select_all(type)
{
	linkss=document.getElementsByTagName('input');
	if (!type)
	{
		type = 1;
	}
	for(i=0; i<linkss.length; i++) {
		if(linkss[ i ].type == 'checkbox' && linkss[ i ].value == type) {
			if (linkss[ i ].checked==true)
			{
				linkss[ i ].checked=false;
			} else 
			{
				linkss[ i ].checked=true;
			}
		} else if (linkss[ i ].type == 'checkbox' && linkss[ i ].value != type)
		{
			linkss[ i ].checked=false;
		}
	}
}
// function was made by Dimitry Koterov http://dklab.ru/lib/Subsys_JsHttpRequest/
function ajax_show(in_div,action,id) {
		document.getElementById(in_div).innerHTML = 'подождите ...';
        // Создаем новый объект JSHttpRequest.
        var req = new Subsys_JsHttpRequest_Js();
        // Код, АВТОМАТИЧЕСКИ вызываемый при окончании загрузки.
        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                if (req.responseJS) {
                    // Записываем в <div> результат работы. 
                    document.getElementById(in_div).innerHTML = req.responseJS.action;
					if (req.responseJS.notificate)
					{
						document.getElementById('notice_'+in_div).innerHTML = req.responseJS.notificate;
					}
                }
            }
        }
        // Разрешаем кэширование (чтобы при одинаковых запросах
        // не обращаться к серверу несколько раз).
        req.caching = false;
        // Подготваливаем объект.
        req.open('POST', '/ajax/show.php', true);
        // Посылаем данные запроса (задаются в виде хэша).
		req.send({ action: action, id:id });

    }
function Subsys_JsHttpRequest_Js() { this._construct() }
(function() { // to create local-scope variables
    var COUNT       = 0;
    var PENDING     = {};
    var CACHE       = {};

    // Called by server script on data load.
    Subsys_JsHttpRequest_Js.dataReady = function(id, text, js) {
        var undef;
        var th = PENDING[id];
        delete PENDING[id];
        if (th) {
            delete th._xmlReq;
            if (th.caching) CACHE[th.hash] = [text, js];
            th._dataReady(text, js);
        } else if (typeof(th) != typeof(undef)) {
            alert("ScriptLoader: unknown pending id: "+id);
        }
    }
    
    Subsys_JsHttpRequest_Js.prototype = {
        // Standard properties.
        onreadystatechange: null,
        readyState:         0,
        responseText:       null,
        responseXML:        null,
        status:             200,
        statusText:         "OK",
        
        // Additional properties.
        session_name:       "PHPSESSID",  // set to SID cookie or GET parameter name
        responseJS:         null,         // JavaScript response array/hash
        caching:            false,        // need to use caching?

        // Internals.
        _span:              null,
        _id:                null,
        _xmlReq:            null,
        _openArg:           null,
        _reqHeaders:        null,

        dummy: function() {}, // empty function

        abort: function() {
            if (this._xmlReq) return this._xmlReq.abort();
            if (this._span) {
                this.readyState = 0;
                if (this.onreadystatechange) this.onreadystatechange();
                this._cleanupScript();
            }
        },
            
        open: function(method, url, asyncFlag, username, password) {
            this._openArg = {
                'method':    method,
                'url':       url,
                'asyncFlag': asyncFlag,
                'username':  username,
                'password':  password
            };
            this._id = null;
            this._xmlReq = null;
            this._reqHeaders = [];
            return true;
        },
        
        send: function(content) {
            var id = (new Date().getTime()) + "" + COUNT++;
            
            // Build QUERY_STRING from query hash.
            var query = this._hash2query(content);

            // Append SID to original URL now.
            var url = this._openArg.url;
            var sid = this._getSid();
            if (sid) url += (url.indexOf('?')>=0? '&' : '?') + this.session_name + "=" + this.escape(sid);

            // Solve hash BEFORE appending ID.
            var hash = this.hash = url + '?' + query;
            if (this.caching && CACHE[hash]) {
                var c = CACHE[hash];
                this._dataReady(c[0], c[1]);
                return false;
            }

            // Try to use XMLHttpRequest.
            this._xmlReq = this._obtainXmlReq(id, url);

            // Pass data in URL (GET, HEAD etc.) or in request body (POST)?
            var hasSetHeader = this._xmlReq && (window.ActiveXObject || this._xmlReq.setRequestHeader); 
            var href, body;
            if (this._xmlReq && hasSetHeader && (""+this._openArg.method).toUpperCase() == "POST") {
                // Use POST method. Pass query in request body.
                // Opera 8.01 does not support setRequestHeader, so no POST method.
                this._openArg.method = "POST";
                href = url;
                body = query;
            } else {
                this._openArg.method = "GET";
                href = url + (url.indexOf('?')>=0? '&' : '?') + query;
                body = null;
            }

            // Append ID: a=aaa&b=bbb&<id>
            href = href + (href.indexOf('?')>=0? '&' : '?') + id;

            // Save loading script.
            PENDING[id] = this;

            if (this._xmlReq) {
                // Open request now & send it.
                // In XMLHttpRequest mode request URL MUST be ended with "<id>-xml".
                var a = this._openArg;
                this._xmlReq.open(a.method, href+"-xml", a.asyncFlag, a.username, a.password);
                if (hasSetHeader) {
                    // Pass pending headers.
                    for (var i=0; i<this._reqHeaders.length; i++)
                        this._xmlReq.setRequestHeader(this._reqHeaders[i][0], this._reqHeaders[i][1]);
                    // Set non-default Content-type. We cannot use 
                    // "application/x-www-form-urlencoded" here, because 
                    // in PHP variable HTTP_RAW_POST_DATA is accessible only when 
                    // enctype is not default (e.g., "application/octet-stream" 
                    // is a good start). We parse POST data manually in backend 
                    // library code.
                    this._xmlReq.setRequestHeader('Content-Type', 'application/octet-stream');
                }
                // Send the request.
                return this._xmlReq.send(body);
            } else {
                // Create <script> element and run it.
                this._obtainScript(id, href);
                return true;
            }
        },

        getAllResponseHeaders: function() {
            if (this._xmlReq) return this._xmlReq.getAllResponseHeaders();
            return '';
        },
            
        getResponseHeader: function(label) {
            if (this._xmlReq) return this._xmlReq.getResponseHeader(label);
            return '';
        },

        setRequestHeader: function(label, value) {
            // Collect headers.
            this._reqHeaders[this._reqHeaders.length] = [label, value];
        },


        //
        // Internal functions.
        //

        // Constructor.
        _construct: function() {},

        // Do all work when data is ready.
        _dataReady: function(text, js) { with (this) {
            if (text !== null || js !== null) {
                readyState = 4;
                responseText = responseXML = text;
                responseJS = js;
            } else {
                readyState = 0;
                responseText = responseXML = responseJS = null;
            }
            if (onreadystatechange) onreadystatechange();
            _cleanupScript();
        }},

        // Create new XMLHttpRequest object.
        _obtainXmlReq: function(id, url) {
            // If url.domain specified, cannot use XMLHttpRequest!
            if (url.match(new RegExp('^[a-z]+://', 'i'))) return null;
            
            // Try to use built-in loaders.
            var req = null;
            if (window.XMLHttpRequest) {
                try { req = new XMLHttpRequest() } catch(e) {}
            } else if (window.ActiveXObject) {
                try { req = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
                if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
            }
            if (req) {
                var th = this;
                req.onreadystatechange = function() { 
                    var s = req.readyState;
                    if (s == 4) {
                        // Avoid memory leak by removing closure.
                        req.onreadystatechange = th.dummy;
                        // Remove possible junk from response.
                        var responseText = req.responseText;
                        try {
                            // Call associated dataReady().
                            eval(responseText);
                        } catch (e) {
                            Subsys_JsHttpRequest_Js.dataReady(id, "JavaScript code generated by backend is invalid!\n"+responseText, null);
                        }
                    } else {
                        th.readyState = s;
                        if (th.onreadystatechange) th.onreadystatechange() 
                    }
                };
                this._id = id;
            }
            return req;
        },

        // Create new script element and start loading.
        _obtainScript: function(id, href) { with (document) {
            var span = null;
            // Oh shit! Damned stupid fucked Opera 7.23 does not allow to create SCRIPT 
            // element over createElement (in HEAD or BODY section or in nested SPAN - 
            // no matter): it is created deadly, and does not respons on href assignment.
            // So - always create SPAN.
            span = body.appendChild(createElement("SPAN"));
            span.style.display = 'none';
            span.innerHTML = 'Text for stupid IE.<s'+'cript></' + 'script>';
            setTimeout(function() {
                var s = span.getElementsByTagName("script")[0];
                s.language = "JavaScript";
                if (s.setAttribute) s.setAttribute('src', href); else s.src = href;
            }, 10);
            this._id = id;
            this._span = span;
        }},

        // Remove last used script element (clean memory).
        _cleanupScript: function() {
            var span = this._span;
            if (span) {
                this._span = null;
                setTimeout(function() {
                    // without setTimeout - crash in IE 5.0!
                    span.parentNode.removeChild(span);
                }, 50);
            }
            return false;
        },

        // Convert hash to QUERY_STRING.
        _hash2query: function(content, prefix) {
            if (prefix == null) prefix = "";
            var query = [];
            if (content instanceof Object) {
                for (var k in content) {
                    var v = content[k];
                    if (v.constructor.prototype[k]) continue;
                    var curPrefix = prefix? prefix+'['+this.escape(k)+']' : this.escape(k);
                    if (v instanceof Object)
                        query[query.length] = this._hash2query(v, curPrefix);
                    else
                        query[query.length] = curPrefix + "=" + this.escape(v);
                }
            } else {
                query = [content];
            }
            return query.join('&');
        },

        // Return value of SID based on QUERY_STRING or cookie
        // (PHP compatible sessions).
        _getSid: function() {
            var m = document.location.search.match(new RegExp('[&?]'+this.session_name+'=([^&?]*)'));
            var sid = null;
            if (m) {
                sid = m[1];
            } else {
                var m = document.cookie.match(new RegExp(s='(;|^)\\s*'+this.session_name+'=([^;]*)'));
                if (m) sid = m[2];
            }
            return sid;
        },
        
        // Stupid JS escape() does not quote '+'.
        escape: function(s) {
            return escape(s).replace(new RegExp('\\+','g'), '%2B');
        }
    }
})();

var azWin = '     Ё               ё       АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя'
var azKoi = 'ё                Ё           юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ'
var AZ=azWin
var azURL = '0123456789ABCDEF'
var b64s  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
var b64a  = b64s.split('')
function enB(str) {
  var a=Array(), i
  for( i=0; i<str.length; i++ ){
    var cch=str.charCodeAt(i)
    if( cch>127 ){  cch=AZ.indexOf(str.charAt(i))+163; if(cch<163) continue; }
    a.push(cch)
  };
  var s=Array(), lPos = a.length - a.length % 3
  for(i=0;i<lPos;i+=3){
    var t=(a[i]<<16)+(a[i+1]<<8)+a[i+2]
    s.push( b64a[(t>>18)&0x3f]+b64a[(t>>12)&0x3f]+b64a[(t>>6)&0x3f]+b64a[t&0x3f] )
  }
  switch ( a.length-lPos ) {
    case 1 : var t=a[lPos]<<4; s.push(b64a[(t>>6)&0x3f]+b64a[t&0x3f]+'=='); break
    case 2 : var t=(a[lPos]<<10)+(a[lPos+1]<<2); s.push(b64a[(t>>12)&0x3f]+b64a[(t>>6)&0x3f]+b64a[t&0x3f]+'='); break
  }
  return s.join('')
}
function deB(str) {
  while(str.substr(-1,1)=='=')str=str.substr(0,str.length-1);
  var b=str.split(''), i
  var s=Array(), t
  var lPos = b.length - b.length % 4
  for(i=0;i<lPos;i+=4){
    t=(b64s.indexOf(b[i])<<18)+(b64s.indexOf(b[i+1])<<12)+(b64s.indexOf(b[i+2])<<6)+b64s.indexOf(b[i+3])
    s.push( ((t>>16)&0xff), ((t>>8)&0xff), (t&0xff) )
  }
  if( (b.length-lPos) == 2 ){ t=(b64s.indexOf(b[lPos])<<18)+(b64s.indexOf(b[lPos+1])<<12); s.push( ((t>>16)&0xff)); }
  if( (b.length-lPos) == 3 ){ t=(b64s.indexOf(b[lPos])<<18)+(b64s.indexOf(b[lPos+1])<<12)+(b64s.indexOf(b[lPos+2])<<6); s.push( ((t>>16)&0xff), ((t>>8)&0xff) ); }
  for( i=s.length-1; i>=0; i-- ){
    if( s[i]>=168 ) s[i]=AZ.charAt(s[i]-163)
    else s[i]=String.fromCharCode(s[i])
  };
  return s.join('')
}
 
 function effective (in_div,id,url) {
	var words = document.getElementById('key_'+id).value;
	var setWords = enB(words + '||' + url + '||' +id);
	ajax_show(in_div,'check_word',setWords);
 }
 function ajaxshow (in_div,text) {
	 document.getElementById(in_div).innerHTML=text;
 }
  function linked (in_div,url) {
	 ajax_show(in_div,'linked',url);
 }
