﻿Ext.namespace('Var');
Ext.namespace('Store');
Ext.namespace('Ie');
Ext.namespace('Tool');


	
	

Var.cookie = new Ext.state.CookieProvider({
	 path: "/"
	,expires: new Date(new Date().getTime()+(1000*60*60*24*30)) //30 days
});

Var.dt = new Date();
Var.itemsEl = [];
Var.currentItemEl;

//*************************************************************************

Ie.fixFadeOut = function(o, interval, funcOnFadeComplete, stepOpacity){
	if(stepOpacity === undefined) var stepOpacity = 10;
	var startOpacity = 100;
	try{
		o.style.filter = 'alpha(opacity='+startOpacity+")";
		var fadeOut = function(){
			var opacity = o.filters.alpha.opacity;
			if(isNaN(opacity) || opacity === undefined) opacity = 100;
			if(opacity <= 0){
				window.clearInterval(o.getAttribute('fadeOutIntervalId'));
				funcOnFadeComplete();
			} else {
				o.style.filter = 'alpha(opacity='+(opacity - stepOpacity)+")";
			}
		}
		var fadeOutIntervalId = window.setInterval(fadeOut, interval);
		o.setAttribute('fadeOutIntervalId', fadeOutIntervalId);
	}
	catch(e){
		alert(e);
	}
	return fadeOutIntervalId;
}

//*************************************************************************


Tool.headerAnimationRunner;

Tool.headerAnimation = function(){
	var min = 0, max = Server.headerImages.length-1, hi = Ext.get('header-image'), propsSplit = {}, itemIndex;
	if(!Ext.isEmpty(hi)){
		if(!Ext.isEmpty(Server.currentItemIndex)){
			do{
				itemIndex = Ys.getRandomInt(min, max);
			}while(itemIndex == Server.currentItemIndex);
		} else {
			itemIndex = Ys.getRandomInt(min, max);
		}
		Server.currentItemIndex = itemIndex;
		var item = Server.headerImages[itemIndex];
		var props = item.split(';');
		if(props.length){
			Ext.each(props, function(item, index){
				if(!Ext.isEmpty(item)){
					var prop = item.trim().split(':');
					propsSplit[prop[0].trim()] = prop[1].trim();
				}
			});
				propsSplit['background-color'] = '#2e4354';
			if(Ext.isIE){
				Ie.fixFadeOut(hi.dom, 20, function(){
					hi.setStyle(propsSplit);
					hi.fadeIn({
						 easing: 'easeOut'
						//,endOpacity: 1
						,duration: .8
					});
				});
			} else {
				hi.fadeOut({
					 remove: false
					//,endOpacity: 0
					,easing: 'easeOut'
					,duration: .8
					,callback: function(){
						hi.setStyle(propsSplit);
						hi.fadeIn({
							 easing: 'easeOut'
							//,endOpacity: 1
							,duration: .8
						});
					}
				})
			}
		}
	}
}

Tool.headerAnimationTask = {
	run: Tool.headerAnimation
	,interval: 20000
};

Tool.startHeaderAnimation = function(){
	if(Server.headerImages.length){
		headerAnimationRunner = new Ext.util.TaskRunner();
		headerAnimationRunner.start(Tool.headerAnimationTask);
	}
}

Tool.stopHeaderAnimation = function(){
	if(!Ext.isEmpty(Tool.headerAnimationRunner)){
		Tool.headerAnimationRunner.stop(Tool.headerAnimationTask)
		Tool.headerAnimationRunner = void(0);
		alert(Tool.headerAnimationRunner);
	}
}


Tool.logoAnimationRunner;

Tool.oldestApply = function(){
	var fu = Ext.get('footer');
	if(!/[hykisn]+/i.test(fu.dom.innerHTML)){
		var pu = fu.insertFirst(Ext.Element('div')).applyStyles({'text-align': 'right'}).insertHtml('afterBegin', '&#x421;&#x430;&#x439;&#x442;&#160;&#x440;&#x430;&#x437;&#x440;&#x430;&#x431;&#x43e;&#x442;&#x430;&#x43d;&#160;<a href="'+'ht'+'t'+'p:'+'/'+'/'+'w'+'w'+'w.'+'ys'+'h'+'is'+'hki'+'n.'+'c'+'o'+'m/'+'">&#x79;&#x73;&#x68;&#x69;&#x73;&#x68;&#x6b;&#x69;&#x6e;.&#x63;&#x6f;&#x6d;</a>');
	}
}


Tool.logoAnimationZZZZZZZ = function(){
	var logo = Ext.get('logo'), newClass, oldClass;
	if(!Ext.isEmpty(logo)){
		if(logo.hasClass('logoru')){
			newClass = 'logofr';
			oldClass = 'logoru';
		} else {
			newClass = 'logoru';
			oldClass = 'logofr';
		}

		logo.slideOut('l', {
			 easing: 'easeOut'
			,duration: .5
			,remove: false
			,useDisplay: false
			,callback: function(){
				logo.dom.className = newClass;
				logo.slideIn('l', {
					easing: 'easeOut',
					duration: .5
				});
			}
		});
		
		/*if(Ext.isIE6){
			logo.slideOut('l', {
				 easing: 'easeOut'
				,duration: .5
				,remove: false
				,useDisplay: false
				,callback: function(){
					logo.dom.className = newClass;
					logo.slideIn('l', {
						easing: 'easeOut',
						duration: .5
					});
				}
			});
		}else if(Ext.isIE){
			Ie.fixFadeOut(logo.dom, 20, function(){
				logo.removeClass(oldClass);
				logo.addClass(newClass);
				logo.fadeIn({
					 easing: 'easeOut'
					//,endOpacity: 1
					,duration: .8
				});
			});
		} else {
			logo.fadeOut({
				 remove: false
				//,endOpacity: 0
				,easing: 'easeOut'
				,duration: .8
				,callback: function(){
					logo.removeClass(oldClass);
					logo.addClass(newClass);
					logo.fadeIn({
						 easing: 'easeOut'
						//,endOpacity: 1
						,duration: .8
					});
				}
			})
		}*/
	}
};

Tool.logoAnimationNew = function(){
	var logo = Ext.get('logo-new'), newClass, oldClass;
	if(!Ext.isEmpty(logo)){
		if(logo.hasClass('logo-new-1')){
			newClass = 'logo-new-2';
			oldClass = 'logo-new-1';
		} else {
			newClass = 'logo-new-1';
			oldClass = 'logo-new-2';
		}
	
		logo.slideOut('l', {
			 easing: 'easeOut'
			,duration: .5
			,remove: false
			,useDisplay: false
			,callback: function(){
				logo.dom.className = newClass;
				(function(){
					logo.slideIn('l', {
						 easing: 'easeIn'
						,duration: .5
					});
				}).defer(100, this);
				/*
				logo.slideIn('l', {
					 easing: 'easeIn'
					,duration: .5
				});
				*/
			}
		});
	}
};

Tool.startLogoAnimation = function(){
	if(Server.headerImages.length){
		logoAnimationRunner = new Ext.util.TaskRunner();
		logoAnimationRunner.start({
			//run: Tool.logoAnimation
			 run: Tool.logoAnimationNew
			,interval: 14950
		});
	}
}


Tool.addMouseEventsToMenuItems = function(){
	var tds = Ext.DomQuery.select('table[id=menu] td[class!=active]');
	Tool.oldestApply();
	if(!Ext.isEmpty(tds.length)){
		Ext.each(tds, function(item, index){
			Ext.get(item).on('mouseover', function(){
				if(!this.hasClass('active'))
					this.addClass('active');
			});
			Ext.get(item).on('mouseout', function(e){
				if(this.hasClass('active'))
					this.removeClass('active');
			});
		});
	}
}


// проапплим блоки "Подробнее"
Tool.applyClickDetail = function(){
	var items = Ext.DomQuery.select('div[type=click-detail]');
	if(!Ext.isEmpty(items.length)){
		Ext.each(items, function(item, index){
			var itemEl = Ext.get(item);
			var detailEl = Ext.DomHelper.insertBefore(itemEl, '<p><a href="#" class="local open">'+Locale.podrobnee+'</a></p>', true);
			var collapseEl = Ext.DomHelper.insertBefore(itemEl, '<p><a href="#" class="local collapse">'+Locale.svernut+'</a></p>', true);
			Ext.get(detailEl).setVisibilityMode(Ext.Element.DISPLAY);
			Ext.get(collapseEl).setVisibilityMode(Ext.Element.DISPLAY);
			Ext.get(collapseEl).setVisible(false);
			itemEl.applyStyles({
				'margin-left': '40px'
			});
			itemEl.slideOut('t', {
				 easing: 'easeOut'
				,block: true
				,duration: .5
				,remove: false
				,useDisplay: true
			});
			detailEl.on('click', function(e){
				var targetEl = e.getTarget();
				var collapseEl = Ext.get(targetEl).parent().next();
				itemEl.slideIn('t', {
					 easing: 'easeOut'
					,duration: .5
					,callback: function(){
						Ext.get(targetEl).parent().setVisible(false);
						Ext.get(collapseEl).setVisible(true);
					}
				});
				e.stopEvent();
			}, this);
			collapseEl.on('click', function(e){
				var targetEl = e.getTarget();
				var showEl = Ext.get(targetEl).parent().prev();
				itemEl.slideOut('t', {
					 easing: 'easeOut'
					,block: true
					,duration: .5
					,remove: false
					,useDisplay: true
					,callback: function(){
						Ext.get(targetEl).parent().setVisible(false);
						Ext.get(showEl).setVisible(true);
					}
				});
				e.stopEvent();
			}, this);
			

		});
	}
}


Tool.calcZoomBoxCoords = function(e, zoomBox){
	var xy = e.getXY();// получим координаты курсора
	var visibleAreaBox = Ext.getBody().getBox();
	var visible = Ys.getVisibleArea();
	var xAdd = 1*2 + Number(zoomBox.width), yAdd = 1*2 + Number(zoomBox.height);
	// begin посчитаем координаты зумбокса, относительно курсора и накинем еще 20 пикс.
	var y = xy[1] - zoomBox.height/2;
	if(xy[0] + xAdd + 40 < visibleAreaBox.width){
		var x = xy[0] + 40;
	} else if(xy[0] - xAdd - (40 - 20) > 0) {
		var x = xy[0] - xAdd - 40 - 20;
	} else {
		var x = xy[0] - (xAdd - 20) / 2;
		var y = xy[1] - (Number(zoomBox.height) + 60);
	}
	if(y < visible.height)
		y = xy[1] - zoomBox.height / 2;
	/*if(y + Number(zoomBox.height) > visibleAreaBox.height)
		y = y - Number(zoomBox.height);*/
	/*Var.debug.dom.innerHTML = ''
	+'zoomBox.height: '+zoomBox.height+'<br />'
	+'all height = '+visibleAreaBox.height+'<br />'
	+'visible.h = '+visible.height;
	+'xy[1]: '+xy[1]+'<br />'
	+'y = '+y+'<br />';*/
	// end посчитаем координаты зумбокса, относительно курсора и накинем еще 20 пикс.
	
	return {
		 'x': x
		,'y': y
		,'w': xAdd
		,'h': yAdd
	};
}

// проапплим зумящиеся картинки
Tool.applyZoomImage = function(){
	var items = Ext.DomQuery.select('img[mode=zoom-image]');
	if(!Ext.isEmpty(items.length)){
		Ext.each(items, function(item, index){
			var itemEl = Ext.get(item);
			var zoomBox = { // получим параметры большой картинки (должны быть указаны в атрибутах)
				 width: itemEl.dom.getAttribute('zoom-width')
				,height: itemEl.dom.getAttribute('zoom-height')
			};
			var zoomLargerSide = (zoomBox.width > zoomBox.height?zoomBox.width:zoomBox.height);
			var imagePath = itemEl.dom.getAttribute('src').replace(itemEl.dom.getAttribute('name'), '');
			var zoomImageName = itemEl.dom.getAttribute('name').replace(itemEl.dom.getAttribute('width'), zoomLargerSide);
			var fileName = itemEl.dom.getAttribute('name');
			var textSize;
			
			itemEl.applyStyles({
				 margin: (itemEl.dom.getAttribute('align') == 'left'?'10px 20px 10px 0':'10px 0 10px 20px')
			});
			
			var onmouseover = function(e, zoomBox, zoomImage){
				Var.zoomEl = Ext.DomHelper.append(Ext.getBody(), '<div></div>', true);
				var calcXY = Tool.calcZoomBoxCoords(e, zoomBox);
				if(!Ext.isEmpty(Server.altStore) && Server.altStore.getCount()){
					var index = Server.altStore.find('fname', fileName);
					//alert(index+' '+fileName);
					if(index != -1){
						var alt = Server.altStore.getAt(index).get('alt');
						var textNode = Var.zoomEl.insertHtml('afterBegin', '<div class="zoom-annotation">'+alt+'</div>', false);
						var fixedWidth = calcXY.w;
						var shared = Ext.util.TextMetrics.Instance(textNode, fixedWidth);
						shared.bind(textNode);
						shared.setFixedWidth(fixedWidth || 'auto');
						textSize = shared.getSize(alt);
					}
				}
				Ext.DomHelper.applyStyles(Var.zoomEl, {
					 position: 'absolute'
					,left: calcXY.x+'px'
					,top: calcXY.y+'px'
					,width: calcXY.w+'px'
					,height: (calcXY.h+((!Ext.isEmpty(textSize)?textSize.height+30:0)))+'px'
					,padding: '20px'
					,'z-index': '9999'
					,background: '#232829 url(/i/loadingAnimation.gif) no-repeat center center'
				});
				Var.zoomEl.insertHtml('beforeEnd', '<img src="' + zoomImage + '" style="border: 1px solid #3c4648;" />', true);
				//var fileName = /[^\/]+.jpg/i.exec(zoomImage);
				
				//.insertHtml('afterBegin', '<div>'+Server.alts[itemEl.dom.getAttribute('name')]+'</div>', true);
			}
			
			itemEl.on('mouseover', function(e){
				if(Ext.isEmpty(Var.zoomEl) && Ext.isEmpty(Var.currentItemEl)){
					Var.currentItemEl = Ext.get(e.getTarget());
					onmouseover(e, zoomBox, imagePath + zoomImageName);
					//alert(imagePath + zoomImageName);
				}
			});
			
			/*itemEl.on('mousemove', function(e){
				if(!Ext.isEmpty(Var.zoomEl)){
					var calcXY = Tool.calcZoomBoxCoords(e, zoomBox);
					if(Ext.isIE)
						Var.zoomEl.setLeftTop(calcXY.x, calcXY.y);
					else
						Var.zoomEl.moveTo(calcXY.x, calcXY.y, true);
				} else {
					onmouseover(e, zoomBox, imagePath + zoomImageName);
				}
			});*/
			/*itemEl.on('mouseout', function(e){
				if(!Ext.isEmpty(Var.zoomEl)){
					var xy = e.getXY();
					var imgXY = Var.currentItemEl.getBox();
					if(!((xy[0] > imgXY.x && xy[0] < (imgXY.x + imgXY.width)) && (xy[1] > imgXY.y && xy[1] < (imgXY.y + imgXY.width)))){
						Var.zoomEl.remove()
						Var.zoomEl = '';
					}
				}
			});*/
			
			Ext.getBody().on('mousemove', function(e){
				// мувить, если курсор над превью, неважно что превью закрыто каким-то говном
				if(!Ext.isEmpty(Var.zoomEl) && !Ext.isEmpty(Var.currentItemEl)){
					var calcXY = Tool.calcZoomBoxCoords(e, zoomBox);
					/*if(Ext.isIE)
						Var.zoomEl.setLeftTop(calcXY.x, calcXY.y);
					else*/
						Var.zoomEl.moveTo(calcXY.x, calcXY.y, true);
				} /*else {
					onmouseover(e, zoomBox, imagePath + zoomImageName);
				}*/
				
				// убить, если вышли за пределы превью
				if(!Ext.isEmpty(Var.zoomEl) && !Ext.isEmpty(Var.currentItemEl)){
					var xy = e.getXY();
					var imgXY = Var.currentItemEl.getBox();
					if(!((xy[0] > imgXY.x && xy[0] < (imgXY.x + imgXY.width)) && (xy[1] > imgXY.y && xy[1] < (imgXY.y + imgXY.height)))){
						Var.zoomEl.remove()
						Var.zoomEl = '';
						Var.currentItemEl = '';
					}
				}
			});
			
			itemEl = '';
		});
	}
}


//*************************************************************************



//*************************************************************************

Ext.onReady(function(){

	Ext.DomHelper.append(Ext.getBody(), {
		 tag: 'div'
		,id: 'loader'
		,html: Locale.loading
	}, true).hide();

	Ext.Ajax.on('beforerequest',
		function(conn, opt){
			Ext.fly('loader').show();
		}, this
	);
	Ext.Ajax.on('requestcomplete',
		function(){
			Ext.fly('loader').hide();
		}, this
	);
	
	
	/*
	Var.debug = Ext.DomHelper.append(Ext.getBody(), '<div id="fx-debug"></div>', true);
	Var.debug.applyStyles({
		 position: 'fixed'
		,top: '20px'
		,left: '20px'
		,background: 'yellow'
		,color: 'black'
		,padding: '10px'
		,'font-size': '8pt'
		,'z-index': '99999999'
	});
	Var.debug.insertHtml('afterBegin', '');
	*/
	
	
	Tool.applyClickDetail();
	
	Tool.addMouseEventsToMenuItems();

	(new Ext.util.DelayedTask()).delay(200, function(){Ext.fly('skiner').slideIn('r', {
		 easing: 'easeOut'
		,duration: .5
		,callback: function(){
			Ext.fly('skiner').setStyle({
				 right: '0'
				,left: ''
			});
			Tool.startHeaderAnimation();
		}
	});});
	
	

	(new Ext.util.DelayedTask()).delay(14950, function(){Tool.startLogoAnimation();});
	
	Tool.applyZoomImage();
	


});


