	cBkgImageFile		= "/images/bkg.jpg"; 		// Фон загрузки
	cContentPicDefault  = "/userfiles/Image/menu/01.jpg"; // Картинка по умолчанию для контента
	cTimeOutLoading 	= 1; 						// Время для загрузки бєкграунда - таймаут для загрузки флеша
	cFlashLoadingFile 	= "/swf/loading.swf";		// Флеш загрузки
	сFlashMenuSound     = "/swf/menusound.swf";		// Звук меню
	cFlashLoadingWidth 	= "950"; 					// Ширина флеша загрузки
	cFlashLoadingHeight = "440"; 					// Высота -//-
	cMediaWidth			= "545";					// Ширина медиа-контента слева
	cMediaHeight		= "405";					// Высота -//-
	cTagOfIndexPage		= "INDEX";					// Тэг первой страницы
	cTagOfForumPage		= "FORUM";					// Тэг страницы форума
	cTagOfOrderPage		= "ORDER";					// Тэг страницы заказа билетов
	
	cCloseSubmenuTime   = 2.0;						// Время закрытия подменю
	сMenuClassActive	= "active";					// Название класса активного меню
	
	cArrowDownImgP	= "/images/arrowDown_p.jpg"; // Указатель движения контента вниз
	cArrowDownImgA	= "/images/arrowDown_a.jpg"; // Указатель движения контента вниз
	cArrowUpImgP	= "/images/arrowUp_p.jpg";   // Указатель движения контента вверх
	cArrowUpImgA	= "/images/arrowUp_a.jpg";   // Указатель движения контента вверх
	
	cAcclContent		= 50; 					 // Пикселы приращения прокрутки, px
	cAcclTimeout 		= 0.5;					 // Таймаут вызова обработчика прокрутки, сек
	
	hgltMenuDuration 	= 0.8;     				 // Длительность изменения цвета меню
	hgltMenuColorEnd	= "#999966";			 // Цвет меню, до которого разгонять подсветку см CSS
	hgltLinkColorEnd	= "#CCCC66";			 // Цвет ccылок, кроме меню
	orders 				= [];	// Заказ билетов - список выбранных мест
	products 			= [];  	// Заказ билетов - список продуктов их стоимости и доступности
	categories 			= [];	// Заказ билетов - спиоск категорий (совокупность продуктов)
	flagSendData 		= false;  // Флаг, выполняется отправка заказа билетов

	intervalChangePics	= 5; // Интервал смену картинки в галереях
	
	// Включить (выключить) подсветку основного меню
	// hgltMenuColorEnd? hgltMenuDuration
    
//Written by Nathan Faubion: http://n-son.com
//Use this or edit how you want, just give me
//some credit!

function jsScroller (o, w, h) {
  var self = this;
  var list = o.getElementsByTagName("div");
  for (var i = 0; i < list.length; i++) {
    if (list[i].className.indexOf("Scroller-Container") > -1) {
      o = list[i];
    }
  }

  //Private methods
  this._setPos = function (x, y) {
    if (x < this.viewableWidth - this.totalWidth)
      x = this.viewableWidth - this.totalWidth;
    if (x > 0) x = 0;
    if (y < this.viewableHeight - this.totalHeight)
      y = this.viewableHeight - this.totalHeight;
    if (y > 0) y = 0;
    this._x = x;
    this._y = y;
    with (o.style) {
      left = this._x +"px";
      top  = this._y +"px";
    }
  };

  //Public Methods
  this.reset = function () {
    this.content = o;
    this.totalHeight = o.offsetHeight;
    this.totalWidth   = o.offsetWidth;
    this._x = 0;
    this._y = 0;
    with (o.style) {
      left = "0px";
      top  = "0px";
    }
  };
  this.scrollBy = function (x, y) {
    this._setPos(this._x + x, this._y + y);
  };
  this.scrollTo = function (x, y) {
    this._setPos(-x, -y);
  };
  this.stopScroll = function () {
    if (this.scrollTimer) window.clearInterval(this.scrollTimer);
  };
  this.startScroll = function (x, y) {
    this.stopScroll();
    this.scrollTimer = window.setInterval(
      function(){ self.scrollBy(x, y); }, 40
    );
  };
  this.swapContent = function (c, w, h) {
    o = c;
    var list = o.getElementsByTagName("div");
    for (var i = 0; i < list.length; i++) {
      if (list[i].className.indexOf("Scroller-Container") > -1) {
        o = list[i];
      }
    }
    if (w) this.viewableWidth  = w;
    if (h) this.viewableHeight = h;
    this.reset();
  };

  //variables
  this.content = o;
  this.viewableWidth  = w;
  this.viewableHeight = h;
  this.totalWidth   = o.offsetWidth;
  this.totalHeight = o.offsetHeight;
  this.scrollTimer = null;
  this.reset();
};


//Written by Nathan Faubion: http://n-son.com
//Use this or edit how you want, just give me
//some credit!
function jsScrollbar (o, s, a, ev) {
  var self = this;

  this.reset = function () {
    //Arguments that were passed
    this._parent = o;
    this._src    = s;
    this.auto    = a ? a : false;
    this.eventHandler = ev ? ev : function () {};
    //Component Objects
    this._up   = this._findComponent("Scrollbar-Up", this._parent);
    this._down = this._findComponent("Scrollbar-Down", this._parent);
    this._yTrack  = this._findComponent("Scrollbar-Track", this._parent);
    this._yHandle = this._findComponent("Scrollbar-Handle", this._yTrack);
    //Height and position properties
    this._trackTop = findOffsetTop(this._yTrack);
    this._trackHeight  = this._yTrack.offsetHeight;
    this._handleHeight = this._yHandle.offsetHeight;
    this._x = 0;
    this._y = 0;
    //Misc. variables
    this._scrollDist  = 5;
    this._scrollTimer = null;
    this._selectFunc  = null;
    this._grabPoint   = null;
    this._tempTarget  = null;
    this._tempDistX   = 0;
    this._tempDistY   = 0;
    this._disabled    = false;
    this._ratio = (this._src.totalHeight - this._src.viewableHeight)/(this._trackHeight - this._handleHeight);

    this._yHandle.ondragstart  = function () {return false;};
    this._yHandle.onmousedown = function () {return false;};
      
    this._addEvent(this._src.content, "mousewheel", this._scrollbarWheel);
    this._removeEvent(this._parent, "mousedown", this._scrollbarClick);
    this._addEvent(this._parent, "mousedown", this._scrollbarClick);

    this._src.reset();
    with (this._yHandle.style) {
      top  = "0px";
      left = "0px";
    }
    this._moveContent();

    if (this._src.totalHeight < this._src.viewableHeight) {
      this._disabled = true;
      this._yHandle.style.visibility = "hidden";
      if (this.auto) this._parent.style.visibility = "hidden";
    } else {
      this._disabled = false;
      this._yHandle.style.visibility = "visible";
      this._parent.style.visibility  = "visible";
    }
  };
  this._addEvent = function (o, t, f) {
    if (o.addEventListener) o.addEventListener(t, f, false);
    else if (o.attachEvent) o.attachEvent('on'+ t, f);
    else o['on'+ t] = f;
  };
  this._removeEvent = function (o, t, f) {
    if (o.removeEventListener) o.removeEventListener(t, f, false);
    else if (o.detachEvent) o.detachEvent('on'+ t, f);
    else o['on'+ t] = null;
  };
  this._findComponent = function (c, o) {
    var kids = o.childNodes;
    for (var i = 0; i < kids.length; i++) {
      if (kids[i].className && kids[i].className == c) {
        return kids[i];
      }
    }
  };
  //Thank you, Quirksmode
  function findOffsetTop (o) {
    var t = 0;
    if (o.offsetParent) {
      while (o.offsetParent) {
        t += o.offsetTop;
        o  = o.offsetParent;
      }
    }
    return t;
  };
  this._scrollbarClick = function (e) {
    if (self._disabled) return false;

    e = e ? e : event;
    if (!e.target) e.target = e.srcElement;

    if (e.target.className.indexOf("Scrollbar-Up") > -1) self._scrollUp(e);
    else if (e.target.className.indexOf("Scrollbar-Down") > -1) self._scrollDown(e);
    else if (e.target.className.indexOf("Scrollbar-Track") > -1) self._scrollTrack(e);
    else if (e.target.className.indexOf("Scrollbar-Handle") > -1) self._scrollHandle(e);

    self._tempTarget = e.target;
    self._selectFunc = document.onselectstart;
    document.onselectstart = function () {return false;};

    self.eventHandler(e.target, "mousedown");
    self._addEvent(document, "mouseup", self._stopScroll, false);

    return false;
  };
  this._scrollbarDrag = function (e) {
    e = e ? e : event;
    var t = parseInt(self._yHandle.style.top);
    var v = e.clientY + document.body.scrollTop - self._trackTop;
    with (self._yHandle.style) {
      if (v >= self._trackHeight - self._handleHeight + self._grabPoint)
        top = self._trackHeight - self._handleHeight +"px";
      else if (v <= self._grabPoint) top = "0px";
      else top = v - self._grabPoint +"px";
      self._y = parseInt(top);
    }

    self._moveContent();
  };
  this._scrollbarWheel = function (e) {
    e = e ? e : event;
    var dir = 0;
    if (e.wheelDelta >= 120) dir = -1;
    if (e.wheelDelta <= -120) dir = 1;

    self.scrollBy(0, dir * 20);
    e.returnValue = false;
  };
  this._startScroll = function (x, y) {
    this._tempDistX = x;
    this._tempDistY = y;
    this._scrollTimer = window.setInterval(function () {
      self.scrollBy(self._tempDistX, self._tempDistY);
    }, 40);
  };
  this._stopScroll = function () {
    self._removeEvent(document, "mousemove", self._scrollbarDrag, false);
    self._removeEvent(document, "mouseup", self._stopScroll, false);

    if (self._selectFunc) document.onselectstart = self._selectFunc;
    else document.onselectstart = function () { return true; };

    if (self._scrollTimer) window.clearInterval(self._scrollTimer);
    self.eventHandler (self._tempTarget, "mouseup");
  };
  this._scrollUp = function (e) {this._startScroll(0, -this._scrollDist);};
  this._scrollDown = function (e) {this._startScroll(0, this._scrollDist);};
  this._scrollTrack = function (e) {
    var curY = e.clientY + document.body.scrollTop;
    this._scroll(0, curY - this._trackTop - this._handleHeight/2);
  };
  this._scrollHandle = function (e) {
    var curY = e.clientY + document.body.scrollTop;
    this._grabPoint = curY - findOffsetTop(this._yHandle);
    this._addEvent(document, "mousemove", this._scrollbarDrag, false);
  };
  this._scroll = function (x, y) {
    if (y > this._trackHeight - this._handleHeight)
      y = this._trackHeight - this._handleHeight;
    if (y < 0) y = 0;

    this._yHandle.style.top = y +"px";
    this._y = y;

    this._moveContent();
  };
  this._moveContent = function () {
    this._src.scrollTo(0, Math.round(this._y * this._ratio));
  };

  this.scrollBy = function (x, y) {
    this._scroll(0, (-this._src._y + y)/this._ratio);
  };
  this.scrollTo = function (x, y) {
    this._scroll(0, y/this._ratio);
  };
  this.swapContent = function (o, w, h) {
    this._removeEvent(this._src.content, "mousewheel", this._scrollbarWheel, false);
    this._src.swapContent(o, w, h);
    this.reset();
  };

  this.reset();
};


//Written by Nathan Faubion: http://n-son.com
//Use this or edit how you want, just give me
//some credit!

function jsScrollerTween (o, t, s) {
  var self = this;

  this._tweenTo = function (y) {
    if (self._idle) {
      var tHeight = self._parent._src ? self._parent._src.totalHeight : self._parent.totalHeight;
      var vHeight = self._parent._src ? self._parent._src.viewableHeight : self._parent.viewableHeight;
      var scrollY = self._parent._src ? self._parent._src._y : self._parent._y;

      if (y < 0) y = 0;
      if (y > tHeight - vHeight) y = tHeight - vHeight;

      var dist = y - (-scrollY);

      self._inc = 0;
      self._timer = null;
      self._values = [];
      self._idle = false;
      for (var i = 0; i < self.steps.length; i++) {
        self._values[i] = Math.round((-scrollY) + dist * (self.steps[i] / 100));
      }
      self._timer = window.setInterval(function () {
        self._parent.scrollTo(0, self._values[self._inc]);
        if (self._inc == self.steps.length-1) {
          window.clearTimeout(self._timer);
          self._idle = true;
        } else self._inc++;
      }, self.stepDelay);
    }
  };
  this._tweenBy = function (y) {
    var scrollY = self._parent._src ? self._parent._src._y : self._parent._y;
    self._tweenTo(-scrollY + y);
  };
  this._trackTween = function (e) {
    e = e ? e : event;
    self._parent.canScroll = false;
    var curY = e.clientY + document.body.scrollTop;
    self._tweenTo((curY - self._parent._trackTop - self._parent._handleHeight/2) * self._parent._ratio);
  };

  this.stepDelay = 40;
  this.steps   = s?s:[0,25,50,70,85,95,97,99,100];
  this._values = [];
  this._parent = o;
  this._timer  = [];
  this._idle   = true;

  o.tweenTo = this._tweenTo;
  o.tweenBy = this._tweenBy;
  o.trackTween = this._trackTween;

  if (t) o._scrollTrack = function (e) {
    this.trackTween(e);
  };
};


var scroller  = null;
var scrollbar = null;
var scrollTween = null;
var set_one = [0,1,3,6,10,15,21,28,36,45,55,64,72,79,85,90,94,97,99,100];
var set_two = [0,25,50,70,85,95,97,99,100];
var set_three = [0,10,20,30,40,50,60,70,80,90,100];
var set_four = [0,25,50,70,85,95,100,105,101,97,100,99,100];
function swapSteps (w) {
  scrollTween.steps = w;
}

function scrollbarEvent (o, type) {
  if (type == "mousedown") {
    if (o.className == "Scrollbar-Track") o.style.backgroundColor = "black";
    else o.style.backgroundColor = "black";
  } else {
    if (o.className == "Scrollbar-Track") o.style.backgroundColor = "black";
    else o.style.backgroundColor = "black";
  }
}



    function onloadscrollbar()
    {
        scroller  = new jsScroller(document.getElementById("News"), 400, 180);
        scrollbar = new jsScrollbar (document.getElementById("Scrollbar-Container"), scroller, true, scrollbarEvent);
        scrollTween = new jsScrollerTween (scrollbar, true);
        scrollbar._scrollDist = 10;
    }
	function highlightLink(id, state, endColor, duration) {
		var link = $(id);
		if (link) {
		if (state) {
			if (link.textHighlight)	link.textHighlight.cancel();
				link.textHighlight = new Effect.ChangeHighlight(link, 'color', {duration:duration , 
																				endcolor:endColor});
			} 
			else {
				if(link.textHighlight) link.textHighlight.cancel();
				link.textHighlight = new Effect.ChangeHighlight(link, 'color', {duration:duration , 
																				endcolor:endColor});
			}
		}
	}
	
	// Обработчики меню
	var objHandlersMenu = Class.create();
	objHandlersMenu.prototype = {
		initialize: function() {
			this.hSubmenu = new Hash(); // Пакет обработчиков подменю
			this.timerOpen = null;
			this.timerClose = null;
			this.menuIdOpenDefault = null;
			this.pointerState = false; // Указатель над меню или нет
		},
		// Добавить обработчик подменю
		addHandler: function(menuId) {
			this.hSubmenu[menuId] = new objHandlerSubmenu(menuId, {parent:this});
		},
		// Получить обработчик для заданного подменю
		getHandler: function(menuId) {
			return (this.hSubmenu[menuId] != "undefined") ? this.hSubmenu[menuId] : null;
		},
		// получить обработчик открытого меню
		getOpenned: function() {
			var hOpenned = null;
			this.hSubmenu.values().each(function(handler){ 
					if (handler.state == 'openned') {
						hOpenned = handler;
						throw $break;
					}
				});
			return hOpenned;
		},
		// Обновить состояние указателя мыши: над блоком меню(подменю)
		updatePointerState: function(pointerState) {
			if (this.pointerState != pointerState && !pointerState) {
				// Указатель покинул область меню - открыть подменю
				if(this.menuIdOpenDefault) {
				  this.queryOpen(this.menuIdOpenDefault)
				} else {
				if (this.getOpenned())
				  this.queryClose(this.getOpenned().menuId);
				}
			}
			this.pointerState = pointerState;
		},
		// Нужно открывать или пункт меню открытый, открывается
		needOpen: function(menuId) {
			var h = this.getHandler(menuId);
			return !(!h || h.state == "openned" || h.state == "idleopen");			
		},
		// Нужно закрывать меню или нет: меню закрыто, закрывает - не трогаем */ 
		needClose: function(menuId) {
			var h = this.getHandler(menuId);
			return !(!h || h.state == "closed" || h.state == "idleclose");
		},
		// Существует открытый пункт меню или нет  
		existOpenned: function() {
			return (this.getOpenned()) ? this.getOpenned().menuId : null  ;
		},
		// Запрос - открыть подменю
		queryOpen: function(menuId) {
			this.handlerEvent("queryOpen -> created", menuId);
	
			// Вызов внешней функции -- возможо убрать
			highlightLink(menuId, true, hgltMenuColorEnd, hgltMenuDuration);
	
			// Если хендлер в состояние "открыт" или "открывается", то ничего не делаем
			if (!this.needOpen(menuId)) {
				this.handlerEvent("queryOpen -> accepted", menuId);
				return;
			}
			// Чистим интервал - если пришел новый запрос открытия меню, старый можно удалить
			
			if (this.timerOpen) {
				clearInterval(this.timerOpen);
				var self = this;
				this.hSubmenu.values().each(function(handler){ 
					if(handler.menuId != menuId && handler.menuId != self.getOpenned()) {	
						highlightLink(handler.menuId, false, $(handler.menuId).restoreColor, hgltMenuDuration);
					}
				});	
			}	
			// Существует открытый 
			if (this.existOpenned()) {
				// Закроем активный 
				this.queryClose(this.getOpenned().menuId);	
				// ждем пока закроется пред. пункт меню
				var self = this;
				this.timerOpen = setTimeout(function(){self.queryOpen(menuId)}, 200);
				this.handlerEvent("queryOpen -> postpone", menuId);
				return;
			}
			// получить обработчик 
			var handler = this.getHandler(menuId);
			if(handler)	{
				// откроем подменю
				handler.open();
				// сообщение
				this.handlerEvent("queryOpen -> accepted", menuId);
			}
		},
		// Запрос - закрыть подменю
		queryClose: function(menuId) {	
			this.handlerEvent("queryClose -> created", menuId);
			// Если хендлер в состояние "закрыт" или "закрывается", то ничего не делаем
			if (!this.needClose(menuId)) {
				this.handlerEvent("queryClose -> accepted", menuId);
				return;
			}
			// получить обработчик 
			var handler = this.getHandler(menuId);
			if(handler) {
				handler.close();
		
				// Вызов внешней функции -- возможо убрать
				highlightLink(menuId, false, $(menuId).restoreColor, hgltMenuDuration);
		
				this.handlerEvent("queryClose -> accepted", menuId);
			}
		},
		// Установить дефолтный пункт меню
		setOpenDefault: function(menuId) {
			this.menuIdOpenDefault = menuId;
		},
		// Обработчик событий
		handlerEvent : function (type, menuId) {
	//		__debug(menuId, type);
			return true;
		}
	};
	
	// Обработчик подменю
	var objHandlerSubmenu = Class.create();
	objHandlerSubmenu.prototype = {
	
		// Инициализация
		initialize: function(menuId) {
			// меню
			this.menuId = menuId;
			// подменю (область div)
			this.submenuId = menuId + "_sub";
			// Cостояние хендлера: closed openned idleclose idleopen
			this.state = 'closed';
			// Таймер закрытия
			this.timerClose = null;
			// Опции: createEvent, звуки и т.д.
			this.options = arguments[1] || {};
		},
		// Создать событие type - тип, elem - елемент, message - сообщение
		createEvent: function(type, elemId) {
			if (this.options.parent && this.options.parent.handlerEvent) {
			this.options.parent.handlerEvent(type, elemId);
			}
		},
		
		// Может закрываться форма или нет
		setCanClose: function(value) {
			this.canClose = value;
		},
		
		// открыть подменю
		open: function() {
			this.state = "idleopen";
			if ($(this.submenuId)) $(this.submenuId).show();
			this.state = "openned";
			// Сохраним текущий класс меню
			this.oldClassName = $(this.menuId).className;
			// Установим класс парента активным
			$(this.menuId).className = сMenuClassActive;
			// Событие
			this.createEvent("openned", this.menuId);
		},
		
		// закрыть подменю
		close: function() {
			this.state = "idleclose";
			if ($(this.submenuId)) $(this.submenuId).hide();
			this.state = "closed";
			// Вернем класс парента обратно
			$(this.menuId).className = this.oldClassName;
			// Событие
			this.createEvent("closed", this.menuId);
		},
		// прекратить 
		cancel: function() {
				true;		
		},
		// восстановить параметры
		refresh: function() {
			true;
		}
	};

	// Скроллинг контента
	var objContentScroll = Class.create();
	objContentScroll.prototype = {
		initialize: function(outerId, 	  // Внешн. область - просмотр
							 innerId,	  // Внутр. область - контент
							 scrollId,    // Указатель скрол-бара
							 arrowUpImg,  // Объект   {id:"Стрелка вверх(вниз) - img", a:"Активное состояние" ,
							 arrowDownImg// d:"Не активное состояние" [idBkg]:"Стрелка вверх(вниз) - подложка "}
							 )
		{
			/* Исходные переменные */
			this.outerId = outerId;
			this.innerId =  innerId;
			this.scrollId = scrollId;
			this.arrowUpImg = arrowUpImg;
			this.arrowDownImg = arrowDownImg;
			/* Высота областей - расчитывается в show */
			this.outerHeight = 0;
			this.innerHeight = 0;
			/* Неактивные стрелки */
			$(this.arrowUpImg.id).src = this.arrowUpImg.p;
			$(this.arrowDownImg.id).src = this.arrowDownImg.p;
			/* Назначить обработчики */
			this.setHandlers();
			/* Показывать (не показывать скроллинг) */
			this.show();
			/* Таймер повторения */
			this.scrollRepeatTimer = null;
			/* Ускорение пикселов - можно задать внешней константой */
			this.acclContent = (typeof cAcclContent != "undefined") ? cAcclContent : 5;
			/* Интерал между повторением, если удерживается нажатой клавиша - сек
			 * можно задать внешней константой
			 * */
			this.acclTimeout = (typeof cRepeatTimeOut != "undefined") ? cAcclTimeout : 0.1;
		},
		/* Показывать (не показывать скроллинг) */
		show : function() {
			/* Необходимость в стрелках и скролл-баре */
			/* Расчет высоты, параметров */
			this.outerHeight = $(this.outerId).getHeight();
			this.innerHeight = $(this.innerId).getHeight();

			if (this.innerHeight > this.outerHeight) {
				$(this.arrowUpImg.id).show();
				$(this.arrowDownImg.id).show();
				$(this.scrollId).show();
				/* Если заданы картинки - подложки (фона), активируем */
				if (typeof this.arrowUpImg.idBkg != "undefined") {
					$(this.arrowUpImg.idBkg).show();
					$(this.arrowUpImg.idBkg).src = this.arrowUpImg.p;
				}
				if (typeof this.arrowDownImg.idBkg != "undefined") {
					$(this.arrowDownImg.idBkg).show();
					$(this.arrowDownImg.idBkg).src = this.arrowDownImg.p;
				}
			}
			else /* прячем */
			{
				$(this.arrowUpImg.id).hide();
				$(this.arrowDownImg.id).hide();
				if (typeof this.arrowUpImg.idBkg != "undefined") {
					$(this.arrowUpImg.idBkg).hide();
				}
				if (typeof this.arrowDownImg.idBkg != "undefined") {
					$(this.arrowDownImg.idBkg).hide();
				}
				$(this.scrollId).hide();
				this.scrollBarPos(0);
				this.contentOffset(0);
			}
		},
		/* Обработчики */
		setHandlers: function() {
			var self = this;
			/* Подсветка */
			Event.observe(this.arrowUpImg.id, 'mouseover', function() {self.arrowActive(self.arrowUpImg)});
			Event.observe(this.arrowUpImg.id, 'mouseout', function() {self.arrowPassive(self.arrowUpImg)});
			Event.observe(this.arrowDownImg.id, 'mouseover', function() {self.arrowActive(self.arrowDownImg)});
			Event.observe(this.arrowDownImg.id, 'mouseout', function() {self.arrowPassive(self.arrowDownImg)});
			/* Нажатие клавиш */
			Event.observe(this.arrowUpImg.id, 'mousedown', function() {self.scrollUp()});
			Event.observe(this.arrowUpImg.id, 'mouseup', function() {clearInterval(self.scrollRepeatTimer)});
			Event.observe(this.arrowDownImg.id, 'mousedown', function() {self.scrollDown()});
			Event.observe(this.arrowDownImg.id, 'mouseup', function() {clearInterval(self.scrollRepeatTimer)});


			/* Обработчик указателя скролл-бара */
			xEnableDrag(this.scrollId, null, function(ele, dx, dy) {self.scrollBarChange(dy)}, null);
		},
		/* Изменение положение указателя скролл-бара */
		scrollBarChange: function(dy) {
			var newTop = xTop(this.scrollId)+dy;
			var maxPos = xHeight(xParent(this.scrollId)) - xHeight(this.scrollId);

			newTop = (newTop < 0) ? 0 : newTop;
			newTop = (newTop > maxPos) ? newTop = maxPos : newTop ;
			xMoveTo(this.scrollId,xLeft(this.scrollId),newTop);

			this.contentOffset(newTop / maxPos);
		},
		/* Сдвинуть, установить указатель скролл-бара */
		scrollBarPos: function(pos) {
			var maxPos = xHeight(xParent(this.scrollId)) - xHeight(this.scrollId);
			xMoveTo(this.scrollId,xLeft(this.scrollId),Math.round(pos*maxPos));
		},
		/* Сдвинуть, установить просмотр контента */
		contentOffset: function(offset) {
			var maxOffset = Math.abs(this.innerHeight - this.outerHeight);
			xTop(this.innerId, -Math.round(offset*maxOffset));
		},
		/* Значение верхн. координаты внутр. элемента для расчета сдвига  */
		getInnerTop: function() {
			return xTop(this.innerId);
		},
		/* Подсветка стрелок - активный элемент или нет */
		arrowActive: function(arrow) {
			if (!this.canScrolling(arrow))
				return;
			$(arrow.id).src = arrow.a;
			$(arrow.id).setStyle({cursor:"pointer"});
		},
		/* Можем выполнять скроллинг или нет */
		canScrolling : function(arrow) {
			if (this.isBottom() && arrow == this.arrowDownImg ) {
				return false;
			}
			if (this.isTop() && arrow == this.arrowUpImg ) {
				return false;
			}
			return true;
		},
		/* Подсветка стрелок - пассивный элемент или нет */
		arrowPassive: function(arrow) {
			$(arrow.id).src = arrow.p;
			$(arrow.id).setStyle({cursor:"default"});
		},
		/* Прокрутка вниз */
		scrollDown: function() {
			clearInterval(this.scrollRepeatTimer);
			if (this.isBottom())
				return;
			var innerTop = this.getInnerTop() - this.acclContent;
			(Math.abs(innerTop) + this.outerHeight > this.innerHeight) ? innerTop = -(this.innerHeight - this.outerHeight) : false;
			xTop(this.innerId, innerTop);
			this.scrollBarPos(Math.abs(innerTop/ (this.innerHeight - this.outerHeight)));

			if (this.isBottom()) {
				this.arrowPassive(this.arrowDownImg);
			}
			else {
				var self = this;
				this.scrollRepeatTimer = setTimeout(function() {self.scrollDown();} , this.acclTimeout*1000);
			}
		},
		/* Прокрутка вверх */
		scrollUp: function() {
			clearInterval(this.scrollRepeatTimer);
			if (this.isTop())
				return;
			var innerTop = this.getInnerTop() + this.acclContent ;
			(innerTop > 0) ? innerTop = 0 : false;
			xTop(this.innerId, innerTop);
			this.scrollBarPos(Math.abs(innerTop/ (this.innerHeight - this.outerHeight)));
			if (this.isTop()) {
				this.arrowPassive(this.arrowUpImg);
			}
			else {
				var self = this;
				this.scrollRepeatTimer = setTimeout(function() {self.scrollUp();} , this.acclTimeout*1000);
			}
		},
		/* Нижняя граница достигнута */
		isBottom : function() {
			return (Math.abs(this.getInnerTop()) == (this.innerHeight - this.outerHeight));
		},
		/* Верхняя граница достигнута */
		isTop: function() {
			return (this.getInnerTop() == 0);
		}
	};

	var objContentScrollAdv = Class.create();
	Object.extend(Object.extend(objContentScrollAdv.prototype, objContentScroll.prototype), {
		/* Подсветка стрелок - активный элемент или нет */
		arrowActive: function(arrow) {
			if (!this.canScrolling(arrow))
				return;
			$(arrow.id).setStyle({cursor:"pointer"});
			$(arrow.id).setStyle({opacity:0});
			$(arrow.id).src = arrow.a;
			if(typeof $(arrow.id).effect != "undefined" && $(arrow.id).effect.cancel)
				$(arrow.id).effect.cancel();
			$(arrow.id).effect = new Effect.Appear($(arrow.id), {to:1.0});
		},
		/* Подсветка стрелок - пассивный элемент или нет */
		arrowPassive: function(arrow) {
			$(arrow.id).setStyle({cursor:"default"});
			if(typeof $(arrow.id).effect != "undefined" && $(arrow.id).effect.cancel)
				$(arrow.id).effect.cancel();
			$(arrow.id).effect = new Effect.Fade($(arrow.id), {to:0.01});
		}
	});

	
	// Функция синхронизация потоков
	function waitEvent(checkfunc, dofunc, errorfunc, maxcount, curcount) {
		// Проверяем наступление события 
		if (!checkfunc()) {
			// Событие не наступило - проверим количество попыток
			if (maxcount <= curcount + 1) {
				// Вызов обработчика ошибок - не дождались события
				if(errorfunc) {
				 errorfunc();
				}
				 return false;
			}
			// Событие не наступило, но попытки не исчерпаны - таймаут
			setTimeout("waitEvent(" + checkfunc + "," + 
						dofunc + "," + errorfunc + "," + maxcount + "," + (curcount + 1) +")", 1000);
		}
		else
		{
			// Событие наступило - выполняем функцию
			if(dofunc) {
				dofunc();	
			}	
			return true;
		}
	}
	
	// Управление галлерей
	var objGalleryData = Class.create();
	objGalleryData.prototype = {
		initialize: function(container,    // Id - контейнер
							 data,         // Галерея данных [{type:"Тип - SWF, PIC",img:"Путь к элементу", about:"Подпись"},{},...{}]
							 backId,       // Управление - стрелка назад
							 nextId) {     // Управление - стрелка вперед
			/* Исходные переменные */
			this.container = container;
			this.data = data;
			this.backId = backId;
			this.nextId = nextId;
			/* Настроим обработчики */ 
			this.setHandlers();
			/* Покажем стрелки */	
			if(this.backId) $(this.backId).show();
			if(this.nextId) $(this.nextId).show();
			/* Стартовый индекс */ 
			this.index = 0;	
			/* Кэш */
			this.cache = new Array();
			this.timerLoaded = null; // Таймер загрузки
			this.cTimeCheckLoaded = (typeof cTimeCheckLoaded == "undefined") ? 0.5 : cTimeCheckLoaded;  // Интервал проверки загрузки, сек
		},
		/* Обработчики */
		setHandlers: function() {
			var self = this;
			if(this.nextId) Event.observe(this.nextId, 'click', function() {self.next()});
			if(this.backId)	Event.observe(this.backId, 'click', function() {self.back()});
			Event.observe(this.container, 'click', function() {self.next()});
		},
		/* Прокрутка вперед */
		next: function() {
			this.index = (this.index + 1 >= this.data.length) ? 0 : this.index + 1; 
			this.show();
		},
		/* Прокрутка назад */
		back: function() {
			this.index = (this.index - 1 < 0) ? this.data.length-1 : this.index - 1; 
			this.show();
		},
		/* Показать медиа-контент в зависимости от Типа */
		show: function() {
			switch (this.data[this.index].type) {
				case 'PIC' : this.showPIC();
					break;
			}
		},
		/* Показать картинку типа JPEG, PNG, BMP */
		showPIC: function() {
			this.loadcachePIC(this.index, this.data[this.index].img);
			this.renderingPIC();
		},
		/* Кеширование */
		loadcachePIC: function(index, filename) {
			this.cache[index] = new Image();
			this.cache[index].loaded = false;
			this.cache[index].onload = function () { this.loaded = true; };
			this.cache[index].src = filename;
		},
		/* Отображение картинки */
		renderingPIC: function() {
			this.fadePIC(); /* Выключение картинки, вызов спец. эффектов */ 
		},
		/* Выключение картинки  */
		fadePIC: function() {
			this.waitloadPIC();	 /* Ждем загрузки картинок */
		},
		/* Ожидание загрузки картинки */
		waitloadPIC: function() {
	
			var self  = this;
			if (this.timerLoaded) clearInterval(this.timerLoaded);
			if (!this.cache[this.index].loaded) {
				this.timerLoaded = setTimeout(function(){self.renderingPIC()}, this.cTimeoutLoaded*1000);
				return;
			}
			this.insertPIC(); /* Создаем картинку в родительском контейнере */
		},
		/* Создание картинки в родительском контейнере */
		insertPIC: function() {
			$(this.container).innerHTML = '<img id="galleryImg" src="' + 
											this.cache[this.index].src + '" alt="галерея, фото, картинки" />';	
			this.appearPIC(); /* Включаем картинку */								
		},	
		appearPIC: function() {
			true;
		}
	};
	
	/* Галлерея со спец.эффектами: погасить, зажечь при изменении картинок */
	var objGalleryFadeAp = Class.create();
	Object.extend(Object.extend(objGalleryFadeAp.prototype, objGalleryData.prototype), {
		fadePIC: function() {
			var self = this;
			$(this.container).effect = new Effect.Fade(this.container, {
															afterFinish: function(){ 
																self.waitloadPIC(); }
														});
		},
		appearPIC: function() {
			$(this.container).effect = new Effect.Appear(this.container);
		},
		/* Обработчики */
		setHandlers: function() {
			var self = this;
/*			Event.observe(this.nextId, 'click', function() {self.next()});
			Event.observe(this.nextId, 'mouseover', function() {self.arrowState(self.nextId, true)});
			Event.observe(this.nextId, 'mouseout', function() {self.arrowState(self.nextId, false)});
			Event.observe(this.backId, 'click', function() {self.back()});
			Event.observe(this.backId, 'mouseover', function() {self.arrowState(self.backId, true)});
			Event.observe(this.backId, 'mouseout', function() {self.arrowState(self.backId, false)});
			*/ 
			Event.observe(this.container, 'click', function() {self.next()});
			new PeriodicalExecuter(function(pe) {self.next()}, intervalChangePics);	
		},
		arrowState: function(id, state) {
			if(typeof $(id).effect != "undefined" && $(id).effect.cancel) 
				$(id).effect.cancel();
			$(id).effect = (state) ?  new Effect.Appear($(id), {to:1.0}) : new Effect.Fade($(id), {to:0.01}) ;
		}
	});
	
	// проиграть звук
	function soundPlay(soundFile, soundDiv) {
			if (soundFile && soundDiv && $(soundDiv)) {
				var so = new SWFObject(soundFile, '', 1, 1, '6', '#000000');
		    	so.write(soundDiv);		
			}	
		}
	// остановить проигрывание звука
	function soundStop(soundDiv) {
			if(soundDiv && $(soundDiv)) {
				$(soundDiv).innerHTML = "";
			}
		}
	// Загрузка изображения в кэш
	function loadImgToCache(filename, cache) {
		// Повторные загрузки уберем ... !?
		cache[filename] = new Image();
		cache[filename].loaded = false;
		cache[filename].onload = function () { this.loaded = true; };
		cache[filename].src = filename;
		}
	
	// Показать картинку
	function runImg(filename, img, cache) {
		if (cache)	 {
			if(typeof cache[filename] == "undefined") {
				loadImgToCache(filename, cache);
			}
		}
		$(img).show();
		$(img).src = (cache && typeof cache[filename] != "undefined") ? cache[filename].src   : filename;
	}
	
	// Показать флеш
	function runFlash(filename, width, height, container) {
		var so = new SWFObject(filename, '', width, height, '6', '#FFFFFF');
			if (so.installedVer.major >= 6) {
				$(container).show();			
			    so.addParam('quality', 'high');
				so.addParam('wmode', 'transparent');
			    so.addParam('salign', 't');
			    so.write(container);		
			}
			else
			{
			/* Статическая картинка */	
			}		
	}
	
	// Страница по умолчанию(первая) загружена или нет
	function isIndexPage() {
		return ($params.tag == cTagOfIndexPage);
	}
	
	// Страница - форум
	function isForumPage() {
		return ($params.tag == cTagOfForumPage);
	}
	
	// Контентная страница
	function isContentPage() {
		return (!isForumPage() && !isOrderPage());		
	}
	
	// Галерейная страница
	function isGalleryPage() {
		return ($params.galleryData.data.length > 0);
	}
	
	// Заказы билетов - страница
	function isOrderPage() {
		return ($params.tag == cTagOfOrderPage);
	}
	
	// Таймаут показа флеша загрузки - подгрузки бэкграунда.
	function timeoutShowPage(timeOutLoading, bkgId) {
		setTimeout(function() {showPage()}, timeOutLoading*1000 )
	}
	
	// Спрятать флеш
	function hideFlash(container) {
		$(container).hide();
		$(container).innerHTML = "";
	}
	
	// Покажем бєкграунд
	function showBkg() {
		$("inner").setStyle({'backgroundImage':'url('+ cBkgImageFile  + ')'});
	}
	
	// Покажем слой медиа-контента слева
	function showMedia() {
		$("media").show();
		switch($params.mediaType) {
			case 'SWF' 	:
					if($params.mediaFile) {
						runFlash($params.mediaFile, cMediaWidth, cMediaHeight, "mediaFlash");
					}
					break;
			case 'PIC'	:
					if($params.mediaFile) {
						runImg($params.mediaFile, "mediaImg", cacheImages);
					}
					break;
			case 'GALLERY' : 
					break;		
		}
	}
	
	// Откроем блок новостей, blockNom - 0-верхний блок, 1- нижний блок
	function openNews(blockNom) {
		// Спрячем все 
		$("news0").oldHeight = 	$("news0").getHeight();
		$("news1").oldHeight = 	$("news1").getHeight();
		$("news0").hide();
		$("news1").hide();
		$("news" + blockNom).show();
		$("news" + blockNom + "text").hide();
		$("news" + blockNom + "textF").show();
		$("news" + blockNom).setStyle({height:"auto"});
		/* Обновим поле скроллинга */
		if(contentScroll)  {
			contentScroll.show();
		}
		
	}
	
	// Закрыть блок новостей, blockNom - 0-верхний блок, 1- нижний блок
	function closeNews(blockNom) {
		$("news0").hide();
		$("news1").hide();
		$("news" + blockNom).setStyle({height:$("news" + blockNom).oldHeight + "px"});
		$("news0textF").hide();
		$("news1textF").hide();
		$("news0text").show();
		$("news1text").show();
		if ($params.news0) $("news0").show();
		if ($params.news1) $("news1").show();
		/* Обновим поле скроллинга */
		if(contentScroll)  {
			contentScroll.show();
		}
		
	}
	
	// Сдвиг подменю
	function offsetSubmenu() {
		// Обработчики основного меню - елементы меню
		$A(document.getElementsByTagName('a')).findAll(
					function(s) {return s.id.match(/^m_(\d*)$/)}).each(function (link) {
						var menuId = $(link).id;
						var submenuId = menuId+"_sub";
						if($(submenuId)) {
							var menuLeft = 	xPageX(menuId) - xPageX("inner"); // Сдвиг Х относительно слоя иннер
							var menuLayerLeft = xPageX("menuItems") - xPageX("inner");
							var innerWidth = $("inner").getWidth();
							var menuItemMiddle = menuLeft + Math.round(xWidth(menuId)/2);
							var subMenuWidth =  $(submenuId).getWidth(); // ширина подменю
							var subMenuLeft = menuItemMiddle - Math.round(subMenuWidth/2);
							// коррекция
							(subMenuLeft < menuLayerLeft) ? subMenuLeft = menuLayerLeft : false;
							(subMenuLeft + subMenuWidth >= innerWidth) ? subMenuLeft = innerWidth - subMenuWidth - 5 : false;
							$(submenuId).setStyle({left:subMenuLeft + "px"})	;
							(innerWidth < subMenuWidth) ? $(submenuId).setStyle({width:innerWidth  + "px"}) : false;
						}
					});
	}
	
	/* Проверка полей формы форума - Email */ 
	function CheckEmailField(field)
	{
		if ( field.search(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i) == -1)
		{ return false; }
		return true;
	}
	
	/* Проверка текстового поля */
	function CheckFIOFieald(field) {
	}
	
	/* Проверка поля телефон */
	function CheckTelField(field) {
	}
	/* Блокируем єлементы формы заказа */
	function enableIfaceOrder(state) {
		$("commentsend").setStyle({opacity:(state) ? 1 : 0.5});
   	    $("commentsend").disabled = !state;		
	}
		
	/* Проверка полей формы для Заказа билетов  */
	function checkFormOrder() {
		if (!orders || orders.length == 0)	{
			alert($msgErrorEmptyOrder);	return false;	}						
		if ($('telinput').value.length <= 4)  {
		// $msgErrorTel	
			alert($msgErrorTel);	return false;	}
		
		return checkForm();
	}
	
	
	function checkForm()						
	{
		if ($('fioinput').value.length < 4 || $('fioinput').value.length > 255) 
		{	alert($msgErrorFIO);	return false;	}
		if (!CheckEmailField($('emailinput').value))
		{	alert($msgErrorEmail);	return false;	}
		if ($('commentinput').value.length > 500) 
		{	alert($msgErrorComment);	return false;	}
		// $msgCode	
		if ($('kodinput').value.length < 4) 
		{	alert($msgCode);	return false;	}
	
		return true;
	}
	/* Отправка сообщения */
// Делает заказ билетов. Возврат в формате JSON
// На вход передается массив из таких элементов:
// $params[0] - идентификаторы билетов (товаров) через ";" Например, "1;12;23"
// $params[1] - числовой код (защита от роботов)
// $params[2] - ФИО
// $params[3] - e-mail
// $params[4] - контактный телефон
// $params[5] - комментарий
// $params[6] -
// $params[7] -
// $params[8] -
// Возврат: объект JavaScript следующего вида:
// {
//   code - код выполнения: 0 - все ок; 1 - ошибка
//	 message - сообщение которое надо показать пользователю
// }	
	function sendData(elem) {
		flagSendData = true;
		// $msgSendOrder
		$("messages").update($msgSendOrder); 	        
		enableIfaceOrder(false);
		
		var $fio = $('fioinput').value,
			$tel = $('telinput').value,
	       	$email = $('emailinput').value,
    	    $comment = $('commentinput').value,
	   		$kod = $('kodinput').value;
		
		var $varOrder = "";
	 	for(i=0; i < orders.length; i++) {
	 			if (i != 0) $varOrder += ";";
		 		$varOrder += getProductForCeil(orders[i]).id;
		 	}
		var url = "getData.php?query=createOrder";
		// orders
		url += "&v1=" +  $varOrder +
			   "&v2=" +  encodeURIComponent($kod)      +	 
   			   "&v3=" +  encodeURIComponent($fio)      +	 
   			   "&v4=" +  encodeURIComponent($email)    +	 
   			   "&v5=" +  encodeURIComponent($tel)      +	 
   			   "&v6=" +  encodeURIComponent($comment);
   	
   		sendDataAJ = new Ajax.Request(url, {
				   		 contentType: 'text/html',
   						 encoding: 'UTF-8',
						 method: 'post',
						 onSuccess: function(transport) {
						 	enableIfaceOrder(true);
							$("messages").update("");
							var result = eval("(" + transport.responseText + ")");					 	
						 	if (!result.code) {
							 	cleanOrder();						 	
							 	$('kodinput').value = "";
						 	}
						 	alert(result.message);
						 	flagSendData = false;
						},
						onFailure : function() {
						 	enableIfaceOrder(true);
						 	// $msgErrDataHandle
							$("messages").update($msgErrDataHandle);
						 	flagSendData = false;
						},
						onException: function() {
							enableIfaceOrder(true);
							// $msgErrDataHandle
							$("messages").update($msgErrDataHandle);
						 	flagSendData = false;
						}
			});
   	   
   	    
		return true;
	}
	
	// Сделан заказ или нет
	function inOrders(order) {
		for(var i=0; i < orders.length; i++) {
			if(orders[i].row == order.row && orders[i].col == order.col) {
				return i;			
			}
		}
		return -1;
	}
	
	// Добавить заказ
	function addOrder(order) {
		if(inOrders(order) == -1) {
			orders[orders.length] = order;
		}
	}	
	
	// Удалить заказ
	function delOrder(order) {
		var i = inOrders(order);
		if (i != -1) {
			orders[i] = null;
			orders = orders.compact();
		}
	}
	
	// Получить список директорий	
	function getCategories() {
		var url = '/getData.php?query=getCategories';
		var getData = new Ajax.Request(url, {
						 method: 'get',
						 onSuccess: function(transport) {
						 	categories = eval("(" + transport.responseText + ")");
						 	if (categories.code	) {
						 		alert("Error AX: getCategories	");
						 		return -1;
						 	}
				 			selectCategories(0);
						}
			});
	}
	
	function getProducts(categoryId) {
		var url = '/getData.php?query=getProducts&v1=' + categoryId;
		var getData = new Ajax.Request(url, {
						 method: 'get',
						 onSuccess: function(transport) {
						 	products = eval("(" + transport.responseText + ")");
						 	if (products.code) {
						 		alert("Error AX: getProducts");
						 		return -1;
						 	}
						 	updateIfaceHall();
						}
			});
	}
	
	// Вернуть информацию о продукте
	function getProductForCeil(ceil) {
		if (typeof products['products'] == "undefined")
			return null;
		for(var i=0; i < products['products'].length; i++) {
			if (products['products'][i].row == ceil.row && 
					products['products'][i].col == ceil.col) {
				return products['products'][i];
			}
		}
		
		return null;
	}
	
	// Обновить интерфейс: enableToOrder disabledToOrder
	function updateIfaceHall() {
		// Обработчики зала
		$A(document.getElementsByTagName('td')).findAll(
					function(s) {return s.id.match(/^col_(\d{1,})_(\d{1,})/)}).each(function (link) {
							$(link).className = "";
					});			
		for(var i=0; i < products['products'].length; i++) {
			var product = products['products'][i];
			var ceil = "col_" + product.row + "_" + product.col;
			if ($(ceil)) {
				$(ceil).className = (product.state) ? 'passive' : 'reserved'
			}
		}
	}
	
	// Выбрать категорию
	function selectCategories(nom) {
		cleanOrder();
		categoryActive = nom;
		updateIfaceCategories();
		getProducts(categories['categories'][nom]['id']);
	}
		
	// Очистить заказ 
	function cleanOrder() {
		for(var i=0; i < orders.length; i++) {
			var ceil = "col_" + orders[i].row + "_" + orders[i].col;
			if ($(ceil)) {
				$(ceil).className = 'passive';
			}
		}
		orders = [];
		updateIfaceOrder();
	}	
		
	// Обновить интерфейс 
	function updateIfaceCategories() {
		var $html = "", $hallHeader = "";
		for(var i=0; i < categories['categories'].length; i++ ) {
		//	var category = categories['categories'][i]['name'].replace(/;|\s{1,}/g, "&nbsp;&nbsp;&nbsp;");
		//	if(i== categoryActive) $hallHeader = category;
			$class = (i == categoryActive) ? 'active' : 'passive';
			$html += ("<a id=" + "m_" + i + "_order" + 
					  ' href="#" class="' + 
					   $class + '" onmouseover="hgltCategories(' + i 
					   + ',true);" onmouseout="hgltCategories(' + i + ',false)" onclick="selectCategories(' 
					   + i +  ')"  >' + categories['categories'][i]['name']  + '</a><br>');
		}
		$("categories").innerHTML = $html;
		$("hallHeader").setStyle({color:"#000000"});
		$("hallHeader").hgltHandler = new Effect.ChangeHighlight("hallHeader", 'color', {endcolor:"#FFFFFF", duration:1.0}); 
		$("hallHeader").update(categories['categories'][categoryActive]['name'] );
	}
	
	function hgltCategories(elem, state) {
		var elemId = "m_" + elem + "_order";
		if (elem == categoryActive)
			return;
		if ($(elemId)) {
			$(elemId).restoreColor = "#999999";
			highlightLink(elemId, state, (state) ? hgltMenuColorEnd : $(elemId).restoreColor, hgltMenuDuration);			
		}
	}
	
	// Обновить интерфейс - поля заказа
	function updateIfaceOrder() {
		/* Расчет стоимости заказа */
		$("orderCalculated").update(calculatedOrders().toFixed(2) );
		$("orderCount").update(orders.length);
	}	
	
	// Подсчет стоимости заказа
	function calculatedOrders() {
		var $sum = 0;
		for(var i=0; i < orders.length; i++) {
			$sum += getProductForCeil(orders[i]).price;
		}
		return $sum;
	}
	
	// Назначаем обработчики
	function setHandlers() {
			// Обработчки для ссылок, кроме меню и подменю
			$A(document.getElementsByTagName('a')).findAll(
				function(link) {
					// Меню, подменю не рассматриваем
					if ($(link).id.indexOf("m_", 0) == -1) {
						$(link).restoreColor = $(link).getStyle("color").parseColor();
						Event.observe(link, "mouseover", function(){if(typeof(highlightLink) === 'function') highlightLink(link, true, hgltLinkColorEnd, hgltMenuDuration);});
						Event.observe(link, "mouseout", function(){if(typeof(highlightLink) === 'function') highlightLink(link, false,$(link).restoreColor, hgltMenuDuration );});								
					}
				});
						
			// Обработчики основного меню - елементы меню
			$A(document.getElementsByTagName('a')).findAll(
					function(s) {return s.id.match(/^m_(\d*)$/)}).each(function (link) {
						// установим обработчик для меню
						handlersMenu.addHandler($(link).id);
						$(link).restoreColor = $(link).getStyle('color').parseColor();
						Event.observe(link, 'mouseover', function() {
														//	if(highlightLink) highlightLink(link, true);
															handlersMenu.queryOpen($(link).id);
															if(typeof(soundPlay) === 'function') soundPlay(сFlashMenuSound, "sound");
															} );
						Event.observe(link, 'mouseout', function() {
														 //   if(highlightLink) highlightLink(link, false);
															if(typeof(soundPlay) === 'function') soundStop("sound");										
															} );
						} );
			// Пункт меню дефолтный
			if ($params.pid) {
				handlersMenu.setOpenDefault("m_" + $params.pid);	
			}
			// Обработчики подменю
			$A(document.getElementsByTagName('a')).findAll(
					function(s) {return s.id.match(/^m_(\d)*_sub/)}).each(function (link) {
							var menuId = $(link).id.match(/^m_(\d{1,})/)[0];
							$(link).restoreColor = $(link).getStyle('color').parseColor();
	
							Event.observe(link, 'mouseover', function() { 
										if(typeof(highlightLink) === 'function') highlightLink(link, true, hgltMenuColorEnd,  hgltMenuDuration);
										if(typeof(soundPlay) === 'function') soundPlay(сFlashMenuSound, "sound");
															} );
							Event.observe(link, 'mouseout', function() { 
										if(typeof(highlightLink) === 'function') highlightLink(link, false, $(link).restoreColor, hgltMenuDuration);
										if(typeof(soundPlay) === 'function') soundStop("sound");									
															} );
				} );
			// Указатель над областью подменю или нет
			Event.observe("outer", 'mousemove', function(e) { 
															if (!e) var e = window.event;
															var tg = (window.event) ? e.srcElement : e.target;
															if (tg.nodeName != 'DIV' && tg.nodeName != 'A') return;
															handlersMenu.updatePointerState(
																	(tg.id.search(/^m_|^menuItems/) != -1));
															return false;		
														} );
			// Обработчики зала
			$A(document.getElementsByTagName('td')).findAll(
					function(s) {return s.id.match(/^col_(\d{1,})_(\d{1,})/)}).each(function (link) {
							var hallid = $(link).id.match(/^col_(\d{1,})_(\d{1,})/);
							var row = hallid[1];
							var col = hallid[2];
							var ceil = {row:row, col:col};
							
							$(link).highlightHandler = null; 
							
							if(row > 0 && col > 0) {
							Event.observe(link, 'click', function() { 
																		if(!inOrders || !getProductForCeil || flagSendData)
																			return;
																		var product = getProductForCeil(ceil);											
																		if(!product || !product.state)
																			return;
																		
																		// Изменение подсветки
																		if(inOrders(ceil) != -1) {
																			delOrder(ceil);	
																			$(link).className ='passive'
																		} else {
																			addOrder(ceil);
																			$(link).className ='active';																			
																		}
																	
																		if ($(link).highlightHandler)	
																		$(link).highlightHandler.cancel();			
																		$(link).setStyle({color:'#666666'});
																		$(link).update(col);
																			
																		updateIfaceOrder();
															} );
							
							Event.observe(link, 'mouseover', function() { 
															if(typeof inOrders == "undefined")
																return;
								
															if(inOrders(ceil) != -1)
																return;
															var product = getProductForCeil(ceil);
															if(!product || !product.state) 
																return;
															$(link).setStyle({color:'#000000'});
															$(link).update(product.price.toFixed(2).replace(".00","") + "<br>"+ cCurrencyShort);
															if ($(link).highlightHandler)	
																$(link).highlightHandler.cancel();
															$(link).highlightHandler = 
																new Effect.ChangeHighlight(link, 'color', {
																						duration: 1.0,
																						endcolor: '#FFFFFF',
																						afterFinish: function(){
																								$(link).highlightHandler = 
																									new Effect.ChangeHighlight(link, 
																										'color', {duration: 1.0,
																												  delay: 1.0,
																												  endcolor: '#000000',
																												  afterFinish: function(){
																													$(link).setStyle({color:'#666666'});
																													$(link).update(col);
																												 } 	
																									});
																							} 	 									
																						});
															} );
							Event.observe(link, 'mouseout', function() {
															if(typeof inOrders == "undefined")
																return;
								
															var product = getProductForCeil(ceil);
															if(!product || !product.state) 
																return;
															if ($(link).highlightHandler)	
																$(link).highlightHandler.cancel();
															$(link).setStyle({color:'#666666'});
															$(link).update(col);																
															} );							
							}
				} );													
	}
	
	// Показать страницу - основные элементы
	function showPage() {
		// Спрячем флеш
		hideFlash("flash");
		// Покажем бєкграунд
		//showBkg();
		// Показываем остальные элементы
		$("langBar").show();
		// Показать меню
		$("menuItems").show();
		// Активируем область подменю
		$("submenuArea").show();
		// Сдвиг подменю
		offsetSubmenu();
		// Активируем рабочую область 
		$("workArea").show();
		// Показать медиа-контент справа: если фото или флеш, или галерея
		if (!isForumPage() && !isOrderPage() ) showMedia();
		// Контент или нет 
		if(isContentPage()) $("contentOuter").show();
		// Если новости 
		if (isIndexPage()) {
			if ($params.news0) $("news0").show();
			if ($params.news1) $("news1").show();
		  	$("newspages").show();
		}	 
		// Показываем подменю, если есть
		if($params.pid) {
			handlersMenu.queryOpen("m_"+ $params.pid);
		}	 
		// Подпись
		$("sign").show();
		// Контент
		if (!isForumPage() && !isOrderPage()) {
			$("scrollContent").show();
			contentScroll = new objContentScrollAdv("contentOuter", "contentDB", "scrollBarImg",
											 {id:"arrowUpImg", idBkg:"arrowUpImgBkg", a:cArrowUpImgA,p:cArrowUpImgP},
											 {id:"arrowDownImg", idBkg:"arrowDownImgBkg" ,a:cArrowDownImgA,p:cArrowDownImgP});
		}
		// Галерея
		if(isGalleryPage()){
			$("mediaGallery").show();
			galleryData  = new objGalleryFadeAp("mediaGallery", 
											  $params.galleryData.data, 
											  null /*"galleryArrowBack_a"*/, 
											  null /*"galleryArrowNext_a"*/);		
			/*$("galleryArrowBack_p").show();	
			$("galleryArrowNext_p").show();
			$("galleryArrowBack_a").setStyle({opacity:0.01});
			$("galleryArrowNext_a").setStyle({opacity:0.01});*/
			galleryData.show();										  								 
		}
		// Форум 
		if(isForumPage()){
			$("extOuter").show();
			var fmessagesScroll = new  objContentScrollAdv("fmessagesOuter", "fmessagesInner", "scrollBarImgF",
									 {id:"arrowUpImgF", idBkg:"arrowUpImgBkgF", a:cArrowUpImgA,p:cArrowUpImgP},
									 {id:"arrowDownImgF", idBkg:"arrowDownImgBkgF" ,a:cArrowDownImgA,p:cArrowDownImgP});
		}									 
		// Заказ билетов
		if(isOrderPage()) {
			$("extOuter").show();
			
			getCategories();
			
				contentScroll1 = new objContentScrollAdv("contentOuter1", "contentDB1", "scrollBarImg1",
											 {id:"arrowUpImg1", idBkg:"arrowUpImgBkg1", a:cArrowUpImgA,p:cArrowUpImgP},
											 {id:"arrowDownImg1", idBkg:"arrowDownImgBkg1" ,a:cArrowDownImgA,p:cArrowDownImgP});
		
		}
	}
	
	// Страница загружена
	function loadFinished() {
        onloadscrollbar();
		handlersMenu = new objHandlersMenu();
		// назначаем обработчики
		setHandlers();

		// Определяем что и как показывать
		if (isIndexPage() && $params.playflash) {
			// Если первая страница - проиграем флешик. 
			runFlash(cFlashLoadingFile, cFlashLoadingWidth, cFlashLoadingHeight, "flash");
			// Покажем єлемены с задержкой
			timeoutShowPage(cTimeOutLoading);
		}
		// Если нет - сразу покажем єлементы
		else {

			showPage();
		}
	//	waitEvent(function() {return false;}, function() {alert("ok");}, function() {alert("notok");},  20, 0);
	}

