_B = document.body
IE = !navigator.appName.search("Mic")

// МЕНЮ
function tmOver(obj,i) {
  obj.parentNode.className='topm1 tm'+i+'1';
}
function tmOut(obj,i) {
  obj.parentNode.className='topm tm'+i+'';
}

function popup_open(path,w,h,label) {
  popupWin = window.open(path, label ,"directories=no,width=" + w + ",height=" + h + ",location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,top=50,left=50");
  popupWin.focus();
  return false;
}

// Список - меню
function MM_jumpMenu(targ,selObj,restore){ //v3.0
 eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
 if (restore) selObj.selectedIndex=0;
}

function get(id) { 
	if(document.getElementById(id)) 
		return document.getElementById(id);
	else
		return false;
}
function get_XY(p) {
  var m = new Array()
  m[0] = m[1] = 0
  while(p) {
    m[0] += p.offsetLeft < 0 ? 0 : p.offsetLeftadd_html
    m[1] += p.offsetTop
    p = p.offsetParent
  }
  return m
}

function getElementsByName(name, tag) {
  var elements = document.getElementsByTagName(tag);
  var ret = new Array();
  for(var i = 0;i < elements.length;i++) {
    if(elements[i].name == name) {
      ret[ret.length] = elements[i];
    }
  }
  if(ret.length > 0) {
  return ret;
  }
  return false;
}


function function_exists (function_name) {
    if (typeof function_name == 'string'){
        return (typeof this.window[function_name] == 'function');
    } else{
        return (function_name instanceof Function);
    }
}

/*№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№*/
//    TOP 10 функций
/*№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№*/

// Поиск значения в массиве
Array.prototype.inArray = function (value) {
  var i;
  for (i=0; i < this.length; i++) {
    if (this[i] === value) {
      return i+1;
    }
  }
  return false;
};
// Показ / скрытие элемента по его ID
function toggle(obj) {
  var el = document.getElementById(obj);
  if(el)
  if ( el.style.display != 'none' ) {
    el.style.display = 'none';
  }
  else {
    el.style.display = '';
  }
}
//getCookie
function getCookie( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ';', len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}
//setCookie
function setCookie( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  document.cookie = name+'='+escape( value ) +
    ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
    ( ( path ) ? ';path=' + path : '' ) +
    ( ( domain ) ? ';domain=' + domain : '' ) +
    ( ( secure ) ? ';secure' : '' );
}
//deleteCookie
function deleteCookie( name, path, domain ) {
  if ( getCookie( name ) ) document.cookie = name + '=' +
      ( ( path ) ? ';path=' + path : '') +
      ( ( domain ) ? ';domain=' + domain : '' ) +
      ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
/*№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№№*/

function get_attr(o, n) {
  return o[n] || (o.attributes && (o = o.attributes.getNamedItem(n)) ? o.value : null)
}
function is_attr(o, n) {
  return get_attr(o, n) != null
}

function add_html(e, s) {
  if(IE) e.innerHTML += s
  else { // mozilla
    var r = document.createRange()
    r.setStartBefore(e)
    var html = r.createContextualFragment(s)
    e.parentNode.appendChild(html)
    //e.parentNode.insertBefore(html, e.nextSibling)
  }
}

function _cross(x1,x2,y1,y2) { return (x1 > y1) && (x1 < y2) || (x2 > y1) && (x2 < y2) || (y1 > x1) && (y1 < x2) || (y2 > x1) && (y2 < x2) }
function show_hide_elm(elm,s,x,y,dx,dy) {
  if(!IE) return
  var e = document.getElementsByTagName(elm),o,t,m
  for(i = 0; i < e.length; i++) {
    o = e[i]; t = o.style
    if(o.id == "_mon" || o.id == "currency") continue
    if(s) t.visibility = ""
    else {
      m = get_XY(o)
      if(_cross(x,x+dx,m[0],m[0]+o.offsetWidth) && _cross(y,y+dy,m[1],m[1]+o.offsetHeight))
        t.visibility = "hidden"
      else t.visibility = ""
    }
  }
}
function show_hide_elm2(elm,s,x,y,dx,dy) {
  if(!IE) return
  var e = document.getElementsByTagName(elm),o,t,m
  for(i = 0; i < e.length; i++) {
    o = e[i]; t = o.style
    if(o.id == "_mon" || o.id == "currency") continue
    if(s) { if(o.hidded != null) { t.visibility = ""; o.hidded = null; } }
    else if(t.visibility != "hidden") {
      m = get_XY(o)
      if(_cross(x,x+dx,m[0],m[0]+o.offsetWidth) && _cross(y,y+dy,m[1],m[1]+o.offsetHeight))
        o.hidded = t.visibility = "hidden"
    }
  }
}
function show_popup(url) {
  window.open(url,"popup","menubar=0,scrollbars=1,titlebar=0,height=500,width=750,resizable=1,left=3000")
}
function move(o, x, y) { o.style.left = x; o.style.top = y }

function set_hp() {
  o = event.srcElement
  o.style.behavior='url(#default#homepage)'
  o.setHomePage(location.href.replace(/[&?]?SE=\w+/, ""))
}

// ####################################################
// Ввод только численных значений и ".,"
function EnsureNumeric(event) {
  if (!window.event) {
    evt=event;
    var k = evt.charCode; 
    if ((k < 48 || k > 57) && k != 0  && k != 44  && k != 46) 
    evt.preventDefault();
  } else {
    evt=window.event;
    var k = evt.keyCode; 
    if ((k < 48 || k > 57) && k != 0  && k != 44  && k != 46) 
    evt.returnValue = false;
  }
}
// ####################################################
// Ввод только численных значений и "., +"
function EnsurePhone(event) {
  if (!window.event) {
    evt=event;
    var k = evt.charCode; 
    if ((k < 48 || k > 57) && k != 0  && k != 44 && k != 32  && k != 43 ) 
    evt.preventDefault();
  } else {
    evt=window.event;
    var k = evt.keyCode; 
    if ((k < 48 || k > 57) && k != 0  && k != 44 && k != 32  && k != 43 && k != 8 ) 
    evt.returnValue = false;
  }
}
// ####################################################
// Ввод буквы + enter + 
function EnsureASCII(event) {
  if (!window.event) {
    evt=event;
    var k = evt.charCode; 
    if (k < 32 && k!=0) 
    evt.preventDefault();
  } else {
    evt=window.event;
    var k = evt.keyCode; 
    if (k < 32 && k!=0 && k!=13 && k!=8) 
    evt.returnValue = false;
  }
}

function showGrid()
{
  get('grid').style.display = 'block';
  return false;
}
function hideGrid()
{
  get('grid').style.display = 'none';
  return false;
}


//
// Переопределяет CSS-класс новым содержимым
//   example: SetClass('\.new','color:#8000FF');
//
function SetClass(pClassName,pClassBody)
{
  var sObj=document.styleSheets[document.styleSheets.length-1],
      sObjRules=sObj.cssRules?sObj.cssRules:sObj.rules,
      e=sObjRules.length-1;

  var editRulesDOM=function()
  { //alert(sObjRules[e]);
    if(sObjRules[e].cssText.match('/^'+pClassName+'[\\s]*\\{/'))
      sObj.deleteRule(e);
    else
      e++;

    sObj.insertRule(pClassName+' {'+pClassBody+'}',e);
  }
  var editRulesIE=function()
  {
    if(sObjRules[e].selectorText.match('/^'+pClassName+'[\\s]*\\{/'))
      sObj.removeRule(e);
    else
      e++;
    sObj.addRule(pClassName,pClassBody,e);
  }
  
  if(sObj.cssRules)
    editRulesDOM();
  else
    editRulesIE();
}
//~


// Определяет существование переменной
function isset(p){ return (typeof(p)=='undefined')?false:true; }




////////////////////////////////////////////////////////////////////////////////



function illusion_getScroll(){
  var xScroll, yScroll;
  if (window.innerHeight && window.scrollMaxY) {
     xScroll = document.body.scrollWidth;
     yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
     xScroll = document.body.scrollWidth;
     yScroll = document.body.scrollHeight;
  } else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
     xScroll = document.documentElement.scrollWidth;
     yScroll = document.documentElement.scrollHeight;
  } else { // Explorer Mac...would also work in Mozilla and Safari
     xScroll = document.body.offsetWidth;
     yScroll = document.body.offsetHeight;
  }
  var windowWidth, windowHeight;
  if (self.innerHeight) { // all except Explorer
     windowWidth = self.innerWidth;
     windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
     windowWidth = document.documentElement.clientWidth;
     windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
     windowWidth = document.body.clientWidth;
     windowHeight = document.body.clientHeight;
  }
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
     pageHeight = windowHeight;
  } else {
     pageHeight = yScroll;
  }
  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){
     pageWidth = windowWidth;
  } else {
     pageWidth = xScroll;
  }
  //return [pageWidth,pageHeight,windowWidth,windowHeight];
  return {'x':pageWidth,'y':pageHeight,'wx':windowWidth,'wy':windowHeight};
}



function illusion_onresize()
{
  var roll=illusion_getScroll();
  get('illusion_screen').style.width =get('illusion_screen_img').style.width =roll['x']+"px";
  get('illusion_screen').style.height=get('illusion_screen_img').style.height=roll['y']+"px";
}
function illusion_run()
{
  window.onresize=illusion_onresize;
}

function illusion_show()
{
  get('illusion_ppl').style.display=get('illusion_screen').style.display="";

  var roll=illusion_getScroll();
  get('illusion_screen').style.width =get('illusion_screen_img').style.width =roll['x']+"px";
  get('illusion_screen').style.height=get('illusion_screen_img').style.height=roll['y']+"px";
}
function illusion_show_none()
{
  get('illusion_ppl').style.display=get('illusion_screen').style.display="none";
}


//
// Возвращает HTML Object склонированый с объекта отмеченого индефикатором "id"
//
function getClone(id)
{
  if(id!='' && get(id))
  { // id не пуст и существует соответствующий ему элемент

    if( !arguments.callee.count )
      arguments.callee.count = 0;

    arguments.callee.count++;

    // клонировать DOM-узел и назначить ему новый id
    var a = get(id).cloneNode( true );
    a.id = 'cloned' + arguments.callee.count;

    // назначить метод для получения внутреннего DOM-узла
    // по его уникальному alias
    a.getByAlias = function( alias )
    {
      if( alias != '' )
      {
        var allChilds = this.getElementsByTagName('*');
        for( var i = 0; i < allChilds.length; i++ )
        {
          if( allChilds[i].getAttribute('alias') == alias )
          {
            // вернуть первый же найденный узел
            return allChilds[i];
          }
        }
        return null; // если ничего не нашли
      }
      else return null; // если alias пуст
    };
    return a; // вернуть клонированный объект
  }
  else return null;
}


////////////////////////////////////////////////////////////////////////////////



function illusion_getScroll(){
  var xScroll, yScroll;
  if (window.innerHeight && window.scrollMaxY) {
     xScroll = document.body.scrollWidth;
     yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
     xScroll = document.body.scrollWidth;
     yScroll = document.body.scrollHeight;
  } else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
     xScroll = document.documentElement.scrollWidth;
     yScroll = document.documentElement.scrollHeight;
  } else { // Explorer Mac...would also work in Mozilla and Safari
     xScroll = document.body.offsetWidth;
     yScroll = document.body.offsetHeight;
  }
  var windowWidth, windowHeight;
  if (self.innerHeight) { // all except Explorer
     windowWidth = self.innerWidth;
     windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
     windowWidth = document.documentElement.clientWidth;
     windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
     windowWidth = document.body.clientWidth;
     windowHeight = document.body.clientHeight;
  }
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
     pageHeight = windowHeight;
  } else {
     pageHeight = yScroll;
  }
  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){
     pageWidth = windowWidth;
  } else {
     pageWidth = xScroll;
  }
  //return [pageWidth,pageHeight,windowWidth,windowHeight];
  return {'x':pageWidth,'y':pageHeight,'wx':windowWidth,'wy':windowHeight};
}



function illusion_onresize()
{
  var roll=illusion_getScroll();
  get('illusion_screen').style.width =get('illusion_screen_img').style.width =roll['x']+"px";
  get('illusion_screen').style.height=get('illusion_screen_img').style.height=roll['y']+"px";
}
function illusion_run()
{
  window.onresize=illusion_onresize;
}

function illusion_show()
{
  get('illusion_ppl').style.display=get('illusion_screen').style.display="";

  var roll=illusion_getScroll();
  get('illusion_screen').style.width =get('illusion_screen_img').style.width =roll['x']+"px";
  get('illusion_screen').style.height=get('illusion_screen_img').style.height=roll['y']+"px";
}
function illusion_show_none()
{
  get('illusion_ppl').style.display=get('illusion_screen').style.display="none";
}


//
// Возвращает HTML Object склонированый с объекта отмеченого индефикатором "id"
//
function getClone(id)
{
  if(id!='' && get(id))
  { // id не пуст и существует соответствующий ему элемент

    if( !arguments.callee.count )
      arguments.callee.count = 0;

    arguments.callee.count++;

    // клонировать DOM-узел и назначить ему новый id
    var a = get(id).cloneNode( true );
    a.id = 'cloned' + arguments.callee.count;

    // назначить метод для получения внутреннего DOM-узла
    // по его уникальному alias
    a.getByAlias = function( alias )
    {
      if( alias != '' )
      {
        var allChilds = this.getElementsByTagName('*');
        for( var i = 0; i < allChilds.length; i++ )
        {
          if( allChilds[i].getAttribute('alias') == alias )
          {
            // вернуть первый же найденный узел
            return allChilds[i];
          }
        }
        return null; // если ничего не нашли
      }
      else return null; // если alias пуст
    };
    return a; // вернуть клонированный объект
  }
  else return null;
}






//вырезает пустое пространство в начале и в конце строки
String.prototype.trim = function()
{
  return this.replace(/(^\s+|\s+$)/g, "");
}



//
// escape(), совместимый с русскими буквами
//

// Инициализируем таблицу перевода
var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
  trans[i] = i - 0x350; // А-Яа-я
trans[0x401] = 0xA8;    // Ё
trans[0x451] = 0xB8;    // ё
//trans[0x224] = 0x2B;    // +

// Сохраняем стандартную функцию escape()
var escapeOrig = window.escape;

// Переопределяем функцию escape()
window.escape = function(str)
{
  var ret = [];

  // Составляем массив кодов символов, попутно переводим кириллицу
  for (var i = 0; i < str.length; i++)
  {
    var n = str.charCodeAt(i);
    if (typeof trans[n] != 'undefined')
      n = trans[n];
    if (n <= 0xFF)
      ret.push(n);
  }
  return escapeOrig(String.fromCharCode.apply(null, ret)).replace(new RegExp( "\\+", "g" ),"%2B");
}
//~




function modalbox(pContent)
{
  get('illusion_content').innerHTML='\
<div style="width:410px;margin-top:70px;background-color:#E8E8E8;">\
<div style="border:1px solid #555555;">\
<div style="padding:14px 14px 12px 14px;">\
'+pContent+'\
</div>\
</div>\
</div>\
';
  illusion_show();
}

function non_digits_slasher2(e,obj,w_plus) {
	w_plus = typeof w_plus == "undefined" ? true : w_plus; 
	var key = window.event ? e.keyCode : e.which;
	//alert(key);
	var keychar = String.fromCharCode(key);
	var result = false;
	reg = w_plus ? /[^\d,\+]+/ : /[^\d]+/;
	if( !reg.test(keychar) ||  key == 8 ||  key == 9 || key == 17 || key == 46 || key == 37 || key == 39 || key == 0 || e.ctrlKey ) {
		result = true;
	}
	return result;
}


//Берет элементы по имени класса, возвращает массив. Второй параметр ограничивает область заданием родительской ноды (тега), третий параметр дает возможность исключать из выходного массива элементы, у которых в имени класса пристуствует его название
function getByClass(classname, node, classexclude)  {
	node = typeof node == "undefined" ? document.getElementsByTagName("body")[0] : document.getElementsByTagName(node)[0];
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var exc_re = typeof classexclude == "undefined" ? false : new RegExp('\\b' + classexclude + '\\b');
	var els = node.getElementsByTagName("*");
	var eval_var = exc_re ? "if(re.test(els[i].className) && !exc_re.test(els[i].className))a.push(els[i]);" : "if(re.test(els[i].className))a.push(els[i]);";
	for(var i=0,j=els.length; i<j; i++) {
		eval(eval_var);
	}
	return a;
}

if (!Array.prototype.some) {
  Array.prototype.some = function(fun /*, thisp*/)  {
	var len = this.length;
	if (typeof fun != "function")
	  throw new TypeError();

	var thisp = arguments[1];
	for (var i = 0; i < len; i++) {
	  if (i in this &&
		  fun.call(thisp, this[i], i, this))
		return true;
	}
	return false;
  };
}

//ходит-бродит по всем элементам формы f_name. Если видит, что аттрибут элемента формы с названием n_txt_field не пуст, а значение самого элемента пустое, выводит алертом содержание аттрибута n_txt_field
function is_empty_needle_fileds( f_name, n_txt_field ) {
	n_txt_field = typeof n_txt_field == "undefined" ? "needle_txt" : n_txt_field;
	var res = false;
	for( var i=0; i<document.forms[f_name].length; i++ ) {
		if( typeof document.forms[f_name][i].getAttribute(n_txt_field) != "undefined" && document.forms[f_name][i].getAttribute(n_txt_field) != null && document.forms[f_name][i].value == "" ) {
			document.forms[f_name][i].focus();
			alert( document.forms[f_name][i].getAttribute(n_txt_field) );
			res = true;
			break;
		}
	}
	return res;
}

