var
  gcIBSBox = new Array(
    '\x61','\x75','\x2E','\x6D','\x6F','\x63','\x2E','\x73',
    '\x6D','\x65','\x74','\x73','\x79','\x73','\x62','\x69','\x40'
  );

/*function IBSBoxStr(BoxName)
{
  i = gcIBSBox.length - 1;
  while(i >= 0) { BoxName += gcIBSBox[i--]; }
  return BoxName;
}*/

function IBSBoxRun(Login, Subject, Body)
{
  i = gcIBSBox.length - 1;
  while(i >= 0) { Login += gcIBSBox[i--]; }

  Url = 'mailto:' + Login;
  Prefix = '?';
  if (Subject != '') {
    Url += Prefix + 'subject=' + escape(Subject);
    Prefix = '&';
  };
  if (Body != '') {
    Url += Prefix + 'body=' + escape(Body);
    Prefix = '&';
  };
  window.location.href = Url;
}

var
  gcMailRuBox = new Array(
    '\x75','\x72','\x2E','\x6C','\x69','\x61','\x6D','\x40'
  );

function MailRuBoxRun(Login, Subject, Body)
{
  i = gcMailRuBox.length - 1;
  while(i >= 0) { Login += gcMailRuBox[i--]; }

  Url = 'mailto:' + Login;
  Prefix = '?';
  if (Subject != '') {
    Url += Prefix + 'subject=' + escape(Subject);
    Prefix = '&';
  };
  if (Body != '') {
    Url += Prefix + 'body=' + escape(Body);
    Prefix = '&';
  };
  window.location.href = Url;

}

//////////////////////////////////////////////////////////////////
//
//  Cookies
//
//////////////////////////////////////////////////////////////////

/*
 * setCookie

 * Устанавливает значение Cookie

 * name - имя cookie
 * value - значение cookie
 * [expires] - дата окончания действия cookie (по умолчанию - до конца сессии)
 * [path] - путь, для которого cookie действительно (по умолчанию - документ, в котором значение было установлено)
 * [domain] - домен, для которого cookie действительно (по умолчанию - домен, в котором значение было установлено)
 * [secure] - логическое значение, показывающее требуется ли защищенная передача значения cookie
 */
function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/*
 * getCookie
 * Получает значение Cookie с указанным именем
 */
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

//////////////////////////////////////////////////////////////////
//
//  Events
//
//////////////////////////////////////////////////////////////////

function addEventHandler(object, event, handler, useCapture) {
    if (object.addEventListener)
        object.addEventListener(event, handler, useCapture);
    else if (object.attachEvent)
        object.attachEvent('on' + event, handler);
    else object['on' + event] = handler;
}

function removeEventHandler(object, event, handler, useCapture) {
    if (object.removeEventListener)
        object.removeEventListener(event, handler, useCapture);
    else if (object.detachEvent)
        object.detachEvent('on' + event, handler);
   else object['on' + event] = undefined;
}

//////////////////////////////////////////////////////////////////
//
//  Screen gray-out
//
//////////////////////////////////////////////////////////////////

/*
 * grayScreenOut
 
 * Создает эффект затемнения экрана, путем создания полупрозрачного слоя с заданным цветом
 * и zindex'ом 50. Прозрачность слоя, его цвет и zindex можно менять.

 *   vis     - включить или выключить затемнение
 *   options - необязательный параметр, JSON-объект со след. свойствами:
 *             opacity (0-100)   : коэффициент непрозрачности слоя (default: 70%)
 *             zindex            : "высота" слоя (на все, что выше него, эффект затемнения распространяться не будет) (default: 50)
               bgcolor (#xxxxxx) : цвет слоя (RGB Hex color) (default: black)

 *   Пример: grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
 */
function grayScreenOut(vis, options) {
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;   // Прозрачность в диап. 0..100
  var opaque = (opacity / 100);          // прозрачность в диап. 0..1
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars
        tnode.style.display='none';                      // Start out Hidden
        tnode.id = 'darkenScreenObject';                 // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                            // Mozilla 1.7b+, Firefox 0.9+, Safari 1.2+, Opera 9
    dark.style.MozOpacity=opaque;                         // Mozilla 1.6-, Firefox 0.8-
    dark.style.KhtmlOpacity=opaque;                       // Safari 1.1-, Konqueror 3.1-
    dark.style.filter='alpha(opacity='+opacity+')';       // IE 7.0-
    dark.style.zIndex=zindex;
    dark.style.backgroundColor=bgcolor;
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';
  } else {
     dark.style.display='none';
  }
}

/*
 * isScreenGrayedOut

 * Возвращает true или false, в зависимости от того, активен ли эффект затемнения экрана
 * (см. функцию grayScreenOut выше) или нет
 */
function isScreenGrayedOut() {
  var dark = document.getElementById('darkenScreenObject');
  return (dark != null && dark.style.display != 'none');
}

/*
 * Кросс-браузерная установка прозрачности
 * Прозрачность задается в процентах от 1 до 100
 */
function SetOpacity(node, opacity) {
  if (typeof node == "string") node = document.getElementById(vHeader);
  if (!node) return;
  node.style.opacity=opacity/100;                       // Mozilla 1.7b+, Firefox 0.9+, Safari 1.2+, Opera 9
  node.style.MozOpacity=opacity/100;                    // Mozilla 1.6-, Firefox 0.8-
  node.style.KhtmlOpacity=opacity/100;                  // Safari 1.1-, Konqueror 3.1-
  node.style.filter='alpha(opacity='+opacity+')';       // IE 7.0-
}

//////////////////////////////////////////////////////////////////
//
//  Toggles
//
//////////////////////////////////////////////////////////////////

/*
 * toggleContent

 * Функция, реализующая функционал "переключателя", т.е., позволяет скрывать/отображать часть HTML-контента

 * vHeader    - указатель на IMG (знак плюс/минус) или строку-заголовок переключателя
 * [vContent] - переключаемый блок, если не указан - будет определён автоматически
 *              (как элемент, следующий за родителем элемента vHeader)
 * [vToggleName] - имя переключателя. Используется для сохранения его состояния между сессиями и
 *                 последующего восстановления с пом. ф-ции toggleInit. Если не указано, используется id элемента vContent

 * vHeader и vContent могут быть как непосредственно объектами, так и их идентификаторами

 * Помимо переключения видимости для vContent, модифицирует vHeader - находит в нем IMG-элемент (предполагается,
 * что он имеет источник "expand.gif", "collapse.gif", "expand-small.gif" или "collapse-small.gif") и соотв.
 * образом меняет его (плюс переключает на минус и обратно).
 *
 */
function toggleContent(vHeader, vContent, vToggleName)
{
  // http://www.javascriptjunkie.com
  if (typeof vHeader == "string") vHeader = document.getElementById(vHeader);
  vParent = vHeader.parentNode;
  // find image within parent (to toggle it's state)
  if (vHeader.nodeName.toUpperCase() != 'IMG') {
    for (vHeader = vParent.firstChild; vHeader && vHeader.nodeName && (vHeader.nodeName.toUpperCase() != 'IMG'); vHeader = vHeader.nextSibling);
  };
  if (!vContent) {
    // find next valid sibling node to parent (this will be element to hide / show)
    vContent = vParent.nextSibling;
    while (vContent.nodeType==3) { // Fix for Mozilla/FireFox Empty Space becomes a TextNode or Something
      vContent = vContent.nextSibling;
    }
  } else if (typeof vContent == "string") vContent = document.getElementById(vContent);

  if (!vToggleName) vToggleName = vContent.id;

  if(vContent.style.display == "none")
  {
    if (vHeader) {
      vHeader.src = vHeader.src.replace(/expand/gi, 'collapse').replace(/plus/gi, 'minus');
      vHeader.alt = "-";
    };
    vContent.style.display = "block";
    if (vToggleName) setCookie('toggle_' + vToggleName + '_expanded', 'true');
  } else {
    vContent.style.display = "none";
    if (vHeader) {
      vHeader.src = vHeader.src.replace(/collapse/gi, 'expand').replace(/minus/gi, 'plus');
      vHeader.alt = "+";
    };
    if (vToggleName) deleteCookie('toggle_' + vToggleName + '_expanded');
  }
  return;
}

/*
 * toggleInit

 * Инициализирует начальное состояние переключателя (из cookie). Параметры - аналогично toggleContent.
 * [vExpand] - флаг, позволяющий явно задать состояние переключателя (true - раскрыт, иначе - закрыт)

 * Для корректной инициализации vContent должен иметь начальный атрибут display = "none" или "block",
 * но _обязательно_ заданный в inline-стиле!
 */
function toggleInit(vHeader, vContent, vToggleName, vExpand)
{
  //alert(vHeader);
  if (typeof vHeader == "string") vHeader = document.getElementById(vHeader);
  vParent = vHeader.parentNode;
  // find image within parent (to toggle it's state)
  if (vHeader.nodeName.toUpperCase() != 'IMG') {
    for (vHeader = vParent.firstChild; vHeader && vHeader.nodeName && (vHeader.nodeName.toUpperCase() != 'IMG'); vHeader = vHeader.nextSibling);
  };
  if (!vContent) {
    // find next valid sibling node to parent (this will be element to hide / show)
    vContent = vParent.nextSibling;
    while (vContent.nodeType==3) { // Fix for Mozilla/FireFox Empty Space becomes a TextNode or Something
      vContent = vContent.nextSibling;
    }
  } else if (typeof vContent == "string") vContent = document.getElementById(vContent);

  if (!vToggleName) vToggleName = vContent.id;

  if (!vToggleName) return;

  if (vExpand == undefined) {
    vExpand = getCookie('toggle_' + vToggleName + '_expanded') == 'true';
  };
  if ((vContent.style.display != "none") != vExpand)
    toggleContent(vHeader, vContent, vToggleName);
}

//////////////////////////////////////////////////////////////////
//
//  Node info
//
//////////////////////////////////////////////////////////////////

function _getNodeInfo(vThis)
{
  return ('nodeName: ' + vThis.nodeName + ', nodeType: ' + vThis.nodeType + ', nodeValue: ' + vThis.nodeValue + '.');
}

function getNodeInfo(vThis)
{
  s = _getNodeInfo(vThis);
  if (vThis.parentNode != null) {
    s = s + ' Parent: ' + _getNodeInfo(vThis.parentNode);
  return s;
  };
}

function showNodeInfo(vThis)
{
  self.status = getNodeInfo(vThis);
}

function showNodeInfo2(vThis)
{
  alert(getNodeInfo(vThis));
}

//////////////////////////////////////////////////////////////////
//
//  Misc
//
//////////////////////////////////////////////////////////////////

/*
 * addLoadEvent

 * Добавляет функцию в список обработчиков события window.onload (завершение загрузки / обновления страницы)
 * Использование:
 *   1) addLoadEvent(Имя_функции_для_вызова);
 *   2) addLoadEvent(function() {
 *        // Тело инлайновой функции
 *      });
 */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

/* Workaround для отсутствующей в IE функции getComputedStyle
 * пример вызова:
 * var cs = _getComputedStyle(elem, '');
 * cs.getPropertyValue('color');
 */
function _getComputedStyle (el, pseudo) {
  if (!el) return;
  if (typeof el == "string") el = document.getElementById(el);
  if (window.getComputedStyle) return window.getComputedStyle(el, pseudo);
  else {
    this.el = el;
    this.getPropertyValue = function(prop) {return _getPropertyValue(el, prop)}
    return this;
  };
}

function _getPropertyValue(el, prop) {
  var re = /(\-([a-z]){1})/g;
  if (prop == 'float') prop = 'styleFloat';
  if (re.test(prop)) {
      prop = prop.replace(re, function () {
          return arguments[2].toUpperCase();
      });
  }
  return el.currentStyle[prop] ? el.currentStyle[prop] : null;
}

/* Returns window viewport size (i.e., size of visible window region, not taking into account scrolled area)
   in crossbrowser manner. Result: {width, height} */
window.size = function()
{
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width: w, height: h};
}

/* Returns window scroll offset in crossbrowser manner.
   Result: JSON object {x, y}
 */
window.scrollOffs = function()
{
	//IE
	if(!window.pageYOffset)
	{
		//strict mode
		if(!(document.documentElement.scrollTop == 0))
		{
			offsetY = document.documentElement.scrollTop;
			offsetX = document.documentElement.scrollLeft;
		}
		//quirks mode
		else
		{
			offsetY = document.body.scrollTop;
			offsetX = document.body.scrollLeft;
		}
	}
	//w3c
	else
	{
		offsetX = window.pageXOffset;
		offsetY = window.pageYOffset;
	}
	return {x: offsetX, y: offsetY};
}

/* Centers element on the screen
   parentSize : JSON-object {width, height}: size of parent object (default: window.size())
 */
function centerElement(elem, parentSize)
{
  //alert(typeof objSize);
  if (typeof elem == "string") elem = document.getElementById(elem);
  if (!parentSize) parentSize = window.size();
  var offset = window.scrollOffs();
  elem.style.left = Math.round((parentSize.width  - elem.clientWidth)  / 2) + offset.x + 'px';
  elem.style.top  = Math.round((parentSize.height - elem.clientHeight) / 2) + offset.y + 'px';
}

/*
   HTMLElement.innerText fix for FireFox & other browsers (except IE)
 */
if ((typeof HTMLElement != 'undefined') && (typeof HTMLElement.innerText == 'undefined')) {
  //alert('123');
  if (typeof HTMLElement.prototype.__defineGetter__ != 'undefined') {
    HTMLElement.prototype.__defineGetter__("innerText", function () {
      if(this.firstChild) return this.firstChild.nodeValue;
      else return '';
    });
  };
  if (HTMLElement.prototype.__defineSetter__ != 'undefined') {
    HTMLElement.prototype.__defineSetter__("innerText", function (str) {
      if (this.firstChild) this.firstChild.nodeValue=str;
      else this.appendChild(document.createTextNode(str));
    });
  };
};

/* Cross-browser XMLHttpRequest object creation */
function createRequestObject()
{
    if (window.XMLHttpRequest) {
        try {
            return new XMLHttpRequest();
        } catch (e){}
    } else if (window.ActiveXObject) {
        try {
            return new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e){
          try {
              return new ActiveXObject('Microsoft.XMLHTTP');
          } catch (e){}
        }
    }
    return null;
};

//////////////////////////////////////////////////////////////////
//
//  Popups
//
//////////////////////////////////////////////////////////////////

var currentPopup;              // Текущий отображаемый Popup-hint
var disabledocOnClick;
var popupOffs = {x: 0, y: 0};  // Смещение popup'ов
var popupMargins = {width: 0, height: 0}; // Макс. границы popup'ов, 0 - границы нет

/*
 * showPopup

 * Отображает Popup-элемент (передается либо объект, либо его id).
 */
function showPopup(Popup, Event) {
  if (!Popup) return;
  if (typeof Popup == 'string') Popup = document.getElementById(Popup);
  if (!Event) Event = window.event;
  if (Popup.style.visibility == 'visible')  {
    hidePopup(Popup);
    return;
  };
  with (window.scrollOffs()) pos = {x: Event.clientX + x + popupOffs.x, y: Event.clientY + y + popupOffs.y};
  maxX = popupMargins.width;
  if (maxX == 0) maxX = window.size().width;
  if (pos.x + Popup.clientWidth > maxX) pos.x = maxX - Popup.clientWidth;
  if (currentPopup && (Popup != currentPopup)) hidePopup(currentPopup);
  with (Popup) {
    style.left = pos.x + 'px';
    style.top  = pos.y + 'px';
    style.visibility = 'visible';
  };
  currentPopup = Popup;
  disabledocOnClick = true;
}

function hidePopup(Popup) {
  if (typeof Popup == 'string') Popup = document.getElementById(Popup);
  Popup.style.visibility = 'hidden';
  if (currentPopup == Popup) currentPopup = undefined;
}

function popupClicked() {
  disabledocOnClick = true;
}

function initPopups() {
  addEventHandler(document, 'click', docOnClick, false);
}

function docOnClick() {
  if (!disabledocOnClick && currentPopup) hidePopup(currentPopup);
  disabledocOnClick = false;
  //Event = window.event;
  //alert('Event.clientX: ' + Event.clientX + ', Event.clientY: ' + Event.clientY);
}

