//$Id: header.js,v 1.2 2011/06/22 12:19:11 evg@atom.krasnet.ru Exp $
var pMenu = {};
var countOpenMenu = 0;
document.observe('dom:loaded', function ()
{
 updateContent = new Ajax.ScheduledUpdate('/assets/templ/forms/scheduler_updater.php',{method:'GET',frequency:60});
 $$('div[class=OptionsList] img').each(function(im){
   (new Image()).src = im.src;
 });
 if ($('idInspirationCarouselContent'))
 {
	new UI.Carousel('idInspirationCarouselContent', {direction:'horizontal',rotate:true}).observe('scroll:ended', function(event)
	{
		var divs = $$('div[class=Inspiration-carousel] div[class=article-wrapper]');
		divs.each(function(dv){dv.hide();});
		divs[event.memo.carousel.currentIndex()].show();
	});
 }
 try
 {
 	if (shareAnUpdate) new MessageCarousel($('scheduledUpdatePearleraShareAnUpdate').select('p.v-content').first(),shareAnUpdate);
 } catch(er){};
});

function sendFormData(elem,parentID,contentID,waitID,params)
{
	var block=$(parentID);
	updateContent._form = null;
	updateContent._formParams = params;
	if (elem.tagName.toUpperCase()=='FORM')
	{
		updateContent._form = elem;
	} else if (elem && elem.form)
	{
		updateContent._form = elem.form;
	}
	if (!block)
	{
 	 updateContent.onTimerEvent({id:parentID});
	} else
	{
	 updateContent.onTimerEvent(block);
	}
	try
	{
		if (contentID) Effect.toggle(contentID,'blind',{duration:0.4,query:contentID});
		if (waitID)
		{
			$(waitID).select('p')[0].update(loadingTextString);
			Effect.toggle(waitID,'blind',{duration:0.4,query:waitID});
		}
	} catch(er) {return false;}
	return false;
}

var countOpenMenu=0;
function _toggleMainMenu(elem)
{
	var block = elem.id.replace('li','');
	countOpenMenu += 1;
	Effect.toggle(block,'blind',{duration:0.4,query:elem.id,afterFinish: function()
	{
		if (elem.hasClassName('Cat')) 
		{
			elem.toggleClassName('Collapse').toggleClassName('Expand');
		} else
		{
			elem.toggleClassName('Closed').toggleClassName('Opened');
			if (elem.hasClassName('Opened'))
			{
				$(block).select('div[class^=scroll-]').each(function(el){el.stopObserving('click');el.observe('click', (function(event) {event.stop();carouselNavigation(event);}));});
			}
		}
		var parent = $$('div.MainMenu div.wrapper ul')[0];
		countOpenMenu -= 1;
		$(block).select('div[class=Closer] a[class=Close]').each(function(el) {el.stopObserving('click');el.observe('click', (function(event) {event.stop();closeMainMenu(event);}));});
		if (countOpenMenu==0 && parent.select('li[class*=Expand]').size()+parent.select('li[class*=Opened]').size() == 0)
		{
			$('MainSubMenu').hide();
		}
	}});
}

function toggleMainMenu(elem)
{
	if (elem.tagName.toUpperCase()!='A') return false;	
	var parent=elem.up('li');
	var root = $$('div.MainMenu div.wrapper ul')[0];
	Object.extend(root.select('li[class*=Expand]'),root.select('li[class*=Opened]')).each(function(el){if (el.id!=parent.id) _toggleMainMenu(el);});
	if (countOpenMenu==0) $('MainSubMenu').show();
	_toggleMainMenu(parent);	
	return false;
}

function closeMainMenu(event)
{
	elem = event.element().up('div.Loader');
	_toggleMainMenu($('li'+elem.id));
}

function carouselNavigation(event)
{
	var current = event.element();
	var parent = current.up('div[class=Loader]');
	var params = current.href.parseQuery();
	var loading= parent.select('div[class=ContentLandingLoading]')[0];
	if (loading.visible()) return;
	loading.update('<p>'+loadingTextString+'</p>');
	params['idBlockUpdate'] = parent.identify();	
	new Ajax.ReqUpdater('/assets/templ/include_globals/index_new.html?'+Object.toQueryString(params),{
		method: 'GET',
		onLoading: function()
		{
			var ul = parent.down('div[class=ContentLandingID]');
			ul.morph('opacity:0', {duration:0.3, afterFinish: function(obj){ul.hide();loading.show().morph('opacity:0.8',{duration:0.5});}});
		},
		onComplete: function(response)
		{
			var ul = parent.down('div[class=ContentLandingID]');
			ul.morph('opacity:0.8', {duration:0.5});
			parent.select('div[class^=scroll-]').each(function(el){el.stopObserving('click');el.observe('click', (function(event) {event.stop();carouselNavigation(event);}));});
			parent.select('div[class=Closer] a[class=Close]').each(function(el) {el.stopObserving('click');el.observe('click', (function(event) {event.stop();closeMainMenu(event);}));});
		} 
	});
}

function openMenu(id)
{
	if (!pMenu[id]) pMenu[id] = new navgMenu();
	pMenu[id].showMenu(id);
	return false;
}
function closeMenu(id)
{
	if (pMenu[id]) pMenu[id].hideMenu();
	return false;
}

MessageCarousel= Class.create({
 initialize: function(elem, messages, options) {
	this.content = elem;
	this.messages= messages;
	this.current = this.messages.indexOf(this.content.innerHTML);
	if (this.current==-1) this.current = 0;
    this.currentlyExecuting = false;
    this.registerCallback();
 },

 registerCallback: function() {
	this.timer = setInterval(this.onTimerEvent.bind(this), 5*1000);
 },

 stop: function() {
	if (!this.timer) return;
	clearInterval(this.timer);
	this.timer = null;
 },

 onTimerEvent: function() {
	if (!this.currentlyExecuting)
	{
      try
		{
        	this.currentlyExecuting = true;
			this.scroll();
			this.currentlyExecuting = false;
    	} catch(e)
		{
        	this.currentlyExecuting = false;
		}
	}
 },

 scroll: function() {	
	var current = this.current + 1;
	if (current >= this.messages.size()) current -= this.messages.size();
	if (current < 0) current += this.messages.size();	
	this._update(current);
 },

 _update: function(id)
 {
	this.content.morph("opacity:0", {duration: 0.5, afterFinish: function(){
		this.content.update(this.messages[id]);
		this.current = id;
		this.content.morph("opacity:1",{duration: 0.5});
	}.bind(this)});	
 }
});

Ajax.ScheduledUpdate = Class.create(Ajax.ReqPeriodicalUpdater, {
 initialize: function($super, url, options) {
  $super(url, options);
 },

 updateContent: function(response)
 {
 for (id in response)
 {
  try
  {
   var elem = null;
   var fname= id+'Update';
   if (Object.isFunction(this[fname]))
   {
    this[fname](response[id],id);
   } else (response[id] != false)
   {
	this._updateContent(id,response[id]);
   }
  } catch(er){};
 }
 },

 _updateContent: function(id,ret)
 {
	var elem = $(id);
	if (Object.isElement(elem))
	{
	    if (this.options.evalScripts)
    	{
			ret.extractScripts().each(function(script)
			{
				if (window.execScript)
					window.execScript(script,'javascript');
				else
					window.eval(script);
			});
		}
		elem.innerHTML=ret.stripScripts();
	}
 },

 onTimerEvent: function(list,params)
 {
	var suList = [];
	var scheduledUpdate = [];
	this.options.parameters = {};
	if (list)
	{
		scheduledUpdate = [list];
		if (params) this.options.parameters=Object.extend(this.options.parameters,params);
	}else
	{
		scheduledUpdate = $$('*[id^=scheduledUpdate]');
	}	
	
	for (var i=0; i< scheduledUpdate.size(); i++)
	{
		suList.push(scheduledUpdate[i].id);
		var fname = scheduledUpdate[i].id+'Load';
		if (typeof this[fname] == 'function') this[fname](scheduledUpdate[i]);
		if (list)
		{
			var form = null;
			if (this._form) form = this._form; else if (Object.isElement(scheduledUpdate[i])) form = scheduledUpdate[i].down('form');
			if (form)
			{
				this.options.parameters=Object.extend(this.options.parameters,form.serialize().parseQuery());
			}
			this.options.parameters=Object.extend(this.options.parameters,this._formParams);
		}
	}
	if (scheduledUpdate.size())
	{
		this.options.parameters.suList = suList.toString();
		options = Object.clone(this.options);
		var onComplete = options.onComplete;
		options.onComplete = (function(response, json) {
			this.updateContent(response.transport.responseJS);
			if (Object.isFunction(onComplete)) onComplete(response.transport.responseJS,json);
		}).bind(this);
		this.updater = new Ajax.Request(this.url,options);
	 }
 },


 pearleraHandleBasketUpdate: function(ret)
 {
  if (ret['delete'])
  {
   var del = $(ret['delete']);
   if (del)
   {
    del.style.display='none';
   }
  }
  if (ret['emptybasket'])
  {
   document.location.href = '/shop/empty-basket.html';
  }
 },

 NoticeUpdate: function(ret)
 {
	var block = $('Notice');
	block.innerHTML = ret;
	Effect.BlindDown(block,{duration:0.3});
 },

 scheduledUpdateTitleGetNewMessagesUpdate: function(ret)
 {
	document.title = document.title.replace(/^\([0-9]*\)/,ret);
 },

 shortBasketDescriptionLoad: function()
 {
  this.options.parameters = Object.extend(this.options.parameters,this.r2b);
 },

 searchResultAjaxTagsUpdate: function(ret,id)
 {
	this._updateContent(id,ret);
	setTimeout(function()
	{
		var searchTag=$('searchResultAjaxTags');
		if (searchTag)
		{
			var content = searchTag.down('div[class^=vcarousel]');
			if (content) new UI.Carousel(content, {direction:'vertical'});
		}
	},200);
 },

 scheduledUpdatePearleraShareAnUpdateLoad: function()
 {
	this.options.parameters['lastanupdate'] = lastAnUpdate;
 },

 scheduledUpdatePearleraShareAnUpdateUpdate: function(ret, id)
 {
	if (ret.items && ret.items.size())
	{
		lastAnUpdate = ret.lastanupdate;
		shareAnUpdate= Object.extend(shareAnUpdate, ret.items);
	}
 },

 pearleraDetailMainFromUpdate: function(ret,id)
 {
	if (ret!='') 
	{
		this._updateContent(id,ret);
		Effect.BlindDown(id,{duration:0.4,query:id, afterFinish:function()
		{ 
			if ($('idReviewsField')) ratingFieldCreate('idReviewsField');
		}});
	} else
	{
		$('Win').className = 'close';
		$$('ul[id=pageOptions] li[class=active]').each(function(li)	{li.removeClassName('active');});
		lastOpenPage = '';
	}
	Effect.BlindUp(id+'Wait',{duration:0.4,query:id+'Wait'});
 }
});

var navgMenu = Class.create({ 
 initialize: function(carousel)
 {
	this.current = null;
	this.element = null;
	this.parent = null;
	this.timer = {show:null,hide:null};
	this.content = $(carousel);
	this.carousel = null;
	this.currentlyExecuting = false;
 },
 showMenu: function(id)
 {
	this.current = id;
	if (this.parent==null) {this.parent = $('li'+id);}
//	if (this.content==null) {this.content = $(this.current).down('div[class^=vcarousel]');}
	this.opMenu = 'show';
	if (this.timer.show==null) this.timer.show = setTimeout(this.onTimerEvent.bind(this),200);
	this.onTimerStop('hide');
 },
 onShowMenu: function(element)
 {
	if (!this.element.visible())
	{
		this.currentlyExecuting = true;
		Effect.BlindDown(this.element,{duration:0.2, afterFinish: function()
		{
			this.currentlyExecuting = false;
			if (this.carousel==null)
			{
				this.content = $(this.current).down('div[class^=vcarousel]');
				if (this.content) this.carousel = new UI.Carousel(this.content, {direction:'vertical'});
			}
		}.bind(this)});
	} else if (this.carousel==null)
	{
		this.content = $(this.current).down('div[class^=vcarousel]');
		if (this.content) this.carousel = new UI.Carousel(this.content, {direction:'vertical'});
	}
 },
 hideMenu: function(id)
 {
	if (this.timer.hide==null)
	{
		this.opMenu = 'hide';
		this.timer.hide = setTimeout(this.onTimerEvent.bind(this),200);
	}
	this.onTimerStop('show');
 },
 onHideMenu: function()
 {
	if (this.element.visible())
	{
		this.currentlyExecuting = true;
		Effect.BlindUp(this.element,{duration:0.2,afterFinish: function()
		{
			this.currentlyExecuting = false;
		}.bind(this)});
	}
 },
 onTimerEvent: function()
 {
	if (this.currentlyExecuting)
	{
		this.timer[this.opMenu] = setTimeout(this.onTimerEvent.bind(this),100);
		return;
	}	
	try
	{
		this.element = $(this.current);
		if (this.element == null) return;
		this.currentlyExecuting = true;
		if (this.opMenu=='show') 
		{
			this.onShowMenu();
		} else
		{
			this.onHideMenu();
		}
		this.currentlyExecuting = false;
		this.timer[this.opMenu] = null;
	} catch(er) {this.currentlyExecuting = false;}
 },
 onTimerStop: function(opMenu)
 {
	if (this.timer[opMenu]) {window.clearTimeout(this.timer[opMenu]);}
	this.timer[opMenu] = null;
 }
});

function headerRemoveFromBasket(elem)
{
	updateContent.r2b=elem.href.parseQuery();
	return sendFormData(elem,'shortBasketDescription','headerBasketPreviewContentItems','headerBasketPreviewLoading');
}
