/********************************************************************************* POPUP */
function Popup() {}
Popup.prototype = {
	init: function(opts) {
		opts = opts || {};
		this.popupPlace = opts.container || as.$$("body");
		this.closeType = opts.closeType ? (typeof opts.closeType == "string" ? [opts.closeType] : opts.closeType) : ["ByButton"];
		this.instantShow = opts.instantShow || true;
		this.popupType = opts.popupType || "";
		this.defaultContent = opts.defaultContent || null;
		this.relativeTo = opts.relativeTo || this.popupPlace;
		this.shown = false;
		this.onHide = opts.onHide;
		
		this.createPopup();
		return this;
	},
	createPopup: function() {
		this.popupWrapper = as.append(
			"<div class='as-hidden popup "+this.popupType+"'>" +
				"<b class='t'><i class='png'></i></b>" +
				"<div class='popup-content'></div>" +
				"<b class='b'><i class='png'></i></b>" +
			"</div>",
			this.popupPlace
		);
		this.popupContent = as.$$("div.popup-content",this.popupWrapper);
		this.defaultContent && this.update(this.defaultContent);
		this.initClosing();
		this.instantShow && this.show();
	},
	update: function(content,append) {
		append || (this.popupContent.innerHTML = "");
		if (typeof content == "string") {
			this.popupContent.innerHTML += content;
		}
		else {
			as.append(content,this.popupContent);
		}
		return this;
	},
	show: function() {
		this.popupWrapper.className = this.popupWrapper.className.replace(/\bas-hidden\b/gi,"");
		var relativeToCoords = as.getElementPosition(this.relativeTo);
		as.style(this.popupWrapper,{
			left: relativeToCoords.left + relativeToCoords.width/2 - this.popupWrapper.offsetWidth/2 + "px",
			top: relativeToCoords.top + relativeToCoords.height/2 - this.popupWrapper.offsetHeight/2 + "px"
		});
		setTimeout(as.bind(function() {this.shown = true;},this),0);
	},
	hide: function() {
		this.shown = false;
		this.popupWrapper.className += " as-hidden";
		this.onHide && this.onHide();
	},
	remove: function() {
		as.remove(this.popupWrapper);
	},
	initClosing: function() {
		for (var i=0,l=this.closeType.length;i<l;i++) {
			try {
				this["initClosing"+this.closeType[i]]();
			}
			catch(e) {
				this.initClosingByButton();
				break;
			}
		}
	},
	initClosingByButton: function() {
		var closeLink = as.prepend("<a href='#' class='close'></a>",this.popupWrapper);
		as.w(closeLink).click(as.bind(function(e) {
			e.preventDefault();
			this.hide();
		},this));
		return closeLink;
	},
	initClosingByLink: function() {
		this.initClosingByButton().innerHTML = "Закрыть";
	},
	initClosingByAwayClick: function() {
		var checkClickTarget = as.bind(function(e) {
			if (!this.shown) return;
			if (!as.parent(e.target,this.popupWrapper)) {
				this.hide();
			}
		},this);
		as.e.click(document.body,checkClickTarget);
	}
}

var flashController = {
	bodies: ['main','collection','fabric','wiki','ideas','contacts'],
	init: function() {
		this.fc = as.$$('div.flash-container');
		this.hc = as.$$('div.html-container');
		this.body = as.$$('body');
		this.htmlHash = {};
		this.checkChapter();
		this.addHTMLCloser();
	},
	checkChapter: function() {
		if (location.search.match(/\bm=\d+\b/)) {
			this.hideFlash();
		}
		else {
			this.hideHTML();
			this.loadFlash();
		}
	},
	loadFlash: function() {
		//var flash = new SWFObject('/swf/shefpovar_home.swf','ShefPovar','100%','100%','9.0.45');
		var flash = new SWFObject('/swf/shef_povar_mai22n_new_2010_113.swf','ShefPovar','100%','100%','8');
		flash.useExpressInstall('/swf/expressinstall.swf');
		flash.addParam('allowScriptAccess','always');
		flash.write(this.fc);
		this.movie = this.getMovie("ShefPovar");	
		this.setFlashMenu();
	},
	addHTMLCloser: function() {		
		this.htmlCloser = as.prepend("<a href='#' class='html-closer'></a>",as.$$('div.layout'));
		as.e.click(this.htmlCloser,this.closeHTML,this);
	},
	closeHTML: function(e) {
		e.preventDefault();
		this.hideHTML();
		if (this.movie) {
			this.toClose();
		}
		else {
			this.loadFlash();
			this.toClose();
		}
	},
	hideHTML: function() {
		this.hc.className += ' as-hidden';
		this.fc.className = this.fc.className.replace(/\bas-flash-hidden\b/gi,"");
	},
	hideFlash: function() {		
		this.fc.className += ' as-flash-hidden';
		this.hc.className = this.hc.className.replace(/\bas-hidden\b/gi,"");
	},
	getMovie: function(movieName) {
		return ((navigator.appName.indexOf("Microsoft")!=-1) ? window : document)[movieName];
	},
	setFlashMenu: function() {
		var cl;
		if (location.search.match(/\bcl=\d+\b/)) {
			cl = location.search.match(/\bcl=\d+\b/)[0].replace("cl=","");
			this.toFlash(Number(cl)-1);
			//this.getContent(cl,1);
		}
	},
	toFlash: function(index) {
		try {
			this.movie.ToFlash(index);
		}
		catch(e) {
			setTimeout(as.bind(function() {
				this.toFlash(index);
			},this),50)
		}
	},
	toClose: function() {
		try {
			this.movie.ToClose();
		}
		catch(e) {
			setTimeout(as.bind(function() {
				this.toClose();
			},this),50)
		}
	},
	getContent: function(tmenu,smenu) {
		//if (arguments.callee.done) return;
		as.ajax("/index.php?cl="+tmenu+"&m="+smenu+"&ajax=1&nocache="+new Date().getTime(),as.bind(this.setContent,this));
		this.body.className = this.bodies[tmenu-1];
		//arguments.callee.done = true;
	},
	setContent: function(content) {
		this.hc.innerHTML = content;
		this.hideFlash();
		this.addHTMLCloser();
		initOnReload();
		//this.initToFlash();
	},
	initToFlash: function() {
		var _self_ = this;
		as.w("ul.menu a").each(function(i) {
			as.e.click(this,function(e) {
				e.preventDefault();
				_self_.hideHTML();
				_self_.toFlash(i);
			})
		});
	}
};

function open_win(tmenu, smenu) {
	this.flashController.getContent.call(flashController,tmenu,smenu);
}

function Gallery() {}
Gallery.prototype = {
	init: function(wrapper) {
		this.wrapper = wrapper;
		this.viewport = as.$$('div.gallery-container',this.wrapper);
		this.gallery = as.$$("ul.gallery",this.wrapper);
		this.left = as.$$('td.back a',this.wrapper);
		this.right = as.$$('td.forward a',this.wrapper);		
		
		this.viewportSize = this.viewport.offsetWidth;
		this.gallerySize = this.gallery.offsetWidth;
		this.sizeRatio = this.viewport.offsetWidth/this.gallery.offsetWidth;
		
		this.startScrollX = this.startGalleryLeft = null;
		this.interval = 2;
		this.step = 6;
		
		this.decorate();
		this.addEvents();
	},
	decorate: function() {
		this.gallery.style.left = 0;
		var _self_ = this, galleryImages = as.w('img',this.wrapper), imgLength = galleryImages.length(), imgCounter = 0;
		galleryImages.each(function() {
			if (!this.complete) {
				setTimeout(as.bind(arguments.callee,this),10);
				return;
			}
			if (++imgCounter == imgLength) {
				_self_.recountWidth();
			}
		});
	},
	recountWidth: function() {
		var width = 0;
		var img = as.w("li img",this.gallery);
		var imgLength = img.length();
		var counter = 0;
		img.each(function () {
			if (!this.complete) {
				setTimeout(as.bind(arguments.callee,this),50);
				return;
			}
			width += (this.offsetWidth + 35);
			as.parent(this,"li").style.width = this.offsetWidth + "px";
			as.parent(this,"li").defaultWidth = this.offsetWidth + "px";
			counter++;
		});
		as.bind(function() {
			if (counter < imgLength) {
				setTimeout(as.bind(arguments.callee,this),50);
				return;
			}
			as.style(this.gallery,{width: width + "px"});
			this.gallerySize = width;
			this.sizeRatio = this.viewport.offsetWidth/this.gallery.offsetWidth;			
		},this)();
	},
	addEvents: function() {
		as.e.mousedown(this.left,this.startScrollLeft,this);
		as.e.mousedown(this.right,this.startScrollRight,this);
		as.e.mouseup(document.body,this.stopScroll,this);		
		
		as.e.click(this.left,function(e) {e.preventDefault()});
		as.e.click(this.right,function(e) {e.preventDefault()});
		
		as.e.mousemove(document.body,this.checkMouseMove,this);
	},
	checkMouseMove: function(e) {
		if (this.gallery.scrollDisabled) return;
		var x = e.clientX + document.documentElement.scrollLeft;
		var y = e.clientY + document.documentElement.scrollTop;
		var cs = as.getElementPosition(this.viewport);
		var diff, left;
		if (x < cs.left + cs.width/6 || x > cs.left + 5*cs.width/6 || y < cs.top || y > cs.top + cs.height) { //away from gallery
			this.startScrollX = this.startGalleryLeft = null;
			return; 
		}		
		if (this.startScrollX == null || this.startGalleryLeft == null) {
			this.startScrollX = x;
			this.startGalleryLeft = parseInt(this.gallery.style.left);
		}
		else {
			diff = x - this.startScrollX;
			left = this.startGalleryLeft - diff/this.sizeRatio*1.5;
			if (left > 0 ) left = 0;
			if (left < this.viewportSize - this.gallerySize) left = this.viewportSize - this.gallerySize;
			this.gallery.style.left = left + "px";
			
			this.startScrollX = x;
			this.startGalleryLeft = parseInt(this.gallery.style.left);
		}
		
	},
	startScrollLeft: function(e) {
		e && e.preventDefault();
		if (this.gallery.scrollDisabled) return;
		this.scrollInterval = setInterval(as.bind(function() {
			var left = parseInt(this.gallery.style.left);
			if (left >= 0) return;
			left += this.step;
			this.gallery.style.left = left + "px";
		},this),this.interval);
	},
	startScrollRight: function(e) {
		e && e.preventDefault();
		if (this.gallery.scrollDisabled) return;
		this.scrollInterval = setInterval(as.bind(function() {
			var left = parseInt(this.gallery.style.left);
			if (left <= (this.viewportSize - this.gallerySize)) return;
			left -= this.step;
			this.gallery.style.left = left + "px";
		},this),this.interval);
	},
	stopScroll: function(e) {
		clearInterval(this.scrollInterval);
	}
}

function PopupController() {}
PopupController.prototype = {
	init: function(wrapper) {
		this.wrapper = wrapper;
		this.gallery = as.$$("ul.gallery",this.wrapper);
		this.popupLinks = as.w("ul.gallery li a",this.wrapper);
		this.currentTarget = null;
		this.viewport = as.parent(this.wrapper,'div.layout');
		
		this.addEvents();
	},
	addEvents: function() {
		this.popupLinks.click(this.tryAnimation,this);
		as.e.click(document.body,this.checkClickLocation,this);
	},
	tryAnimation: function(e) {
		e.preventDefault();
		this.currentTarget && this.clearPrevious();
		var target = as.parent(e.target,"li");
		target.large ? this.showLarge(target) : this.prepareLarge(target);
	},
	prepareLarge: function(target) {
		this.gallery.scrollDisabled = true;
		var largeSRC = as.$$("img",target).onclick().full;
		var _self_ = this;
		target.large = new Image();
		target.large.src = largeSRC;
		target.large.className = "large-image";
		as.bind(function(){
			if (!target.large.complete) {
				setTimeout(as.bind(arguments.callee,this),10);
				return;
			}
			this.showLarge(target);
		},this)();
	},
	showLarge: function(target) {
		this.gallery.scrollDisabled = true;
		as.style(as.$$("a",target),{
			visibility: "hidden",
			width: target.large.width + "px",
			display: 'block'
		});
		target.style.width = target.large.width + "px";
		as.append(target.large,document.body);
		var cs = as.getElementPosition(as.$$('a',target));
		var viewportCS = as.getElementPosition(this.viewport);
		var left = cs.left + cs.width/2 - target.large.width/2;
		if (left + target.large.width > viewportCS.left + viewportCS.width) { left =  viewportCS.left + viewportCS.width - target.large.width}
		if (left < viewportCS.left) { left = viewportCS.left }
		as.style(target.large,{
			left: left + "px",
			top: cs.top + cs.height - target.large.height + "px"
		});
		
		if (target.popup) this.showPopup(target);
		else {
			this.preparePopup(target);
		}
	},
	showPopup: function(target) {
		target.popup.show();
		var top = parseInt(target.large.style.top) - target.popup.popupWrapper.offsetHeight - 20;
		var left = parseInt(target.popup.popupWrapper.style.left) + 90;
		top = top > 16 ? top : 16;
		as.style(target.popup.popupWrapper,{
			top: top + "px",
			left: left + "px"
		});		
		this.currentTarget = target;
	},
	preparePopup: function(target) {
		var content = as.$$('div.popup-content',target).innerHTML;
		target.popup = new Popup().init({
			defaultContent: content,
			relativeTo: target.large,
			closeType: ['ByButton',"ByAwayClick"],
			onHide: as.bind(this.onHide,this),
			instantShow: false
		});
		this.showPopup(target);
	},
	onHide: function() {
		this.gallery.scrollDisabled = false;
		this.clearPrevious();
	},
	clearPrevious: function() {
		as.remove(this.currentTarget.large);
		this.currentTarget.popup.shown && this.currentTarget.popup.hide();
		as.style(as.$$("a",this.currentTarget),{
			visibility: "visible",
			width: "auto",
			display: 'inline',
			position: 'relative',
			zoom: '1'
		});
		this.currentTarget.style.width = this.currentTarget.defaultWidth;
	},
	checkClickLocation: function(e) {
		/*if (!this.currentTarget) return;
		if (!as.parent(e.target,this.currentTarget.popup)) {
			this.clearPrevious();
		}*/
	}
}

function simplePopupController() {}
simplePopupController.prototype = {
	init: function(wrapper) {
		this.wrapper = wrapper;
		this.links = as.w("a",this.wrapper);
		
		this.addEvents();
	},
	addEvents: function() {
		this.links.click(this.tryShowPopup,this);
	},
	tryShowPopup: function(e) {
		e.preventDefault();
		var handler = as.parent(e.target,"li");
		if (handler.popup) this.showPopup(handler);
		else {
			this.createPopup(handler);
		}
	},
	showPopup: function(handler) {
		handler.popup.show();
	},
	createPopup: function(handler) {
		var content = as.$$("div.popup-content",handler);
		if (!content) return;
		content = as.create("<div class='catalog-popup-content'><div class='description'>"+content.innerHTML+"</div></div>");
		//var picture = as.before("img",as.$$("div.description",content));
		var picture = as.append("<img style='position: absolute; left: -9999px' />",document.body);
		picture.src = as.$$("a",handler).href;
		setTimeout(function() {
			if (!picture.complete) {
				setTimeout(arguments.callee,10);
				return;
			}
			if (picture.width + 15 + 100 < 364) {
				as.$$('div.description',content).style.paddingTop = picture.height/2 - 20 + "px";
			}
			else {
				as.$$('div.description',content).style.width = "auto";
			}
			as.style(picture,{position: 'static', left: 'auto'});
			as.before(picture,as.$$("div.description",content));
			handler.popup = new Popup().init({
				popupType: "catalog-inside-popup",
				closeType: ['ByButton','ByAwayClick'],
				defaultContent: content
			});
		},10);
	}
}

function cityPopup(e) {
	e.preventDefault();
	var content, ul, data;
	if (this.popup) this.popup.show();
	else {
		data = this.onfocus();
		ul = as.create("<ul class='city-list'></ul>");
		for (var i=0,l=data.length;i<l;i++) {
			as.append("<li><a href='" + data[i].url + "'>" + data[i].name + "</a></li>",ul);
		}
		this.popup = new Popup().init({
			closeType: ['ByButton','ByAwayClick'],
			defaultContent: ul,
			popupType: 'city-list-popup',
			relativeTo: this
		});
	}
}


function initOnReload() {
	//custom scrolls
	as.w('div.classic-quote div.quote-content').each(function() {
		new CustomScroll().init(this);
	});
	as.w('div.faq div.answer-content').each(function() {
		new CustomScroll().init(this);
	});
	as.w('div.awards').each(function() {
		new CustomScroll().init(this);
	});
	as.w('div.ajaxServingSliced').each(function() {
		new CustomScroll().init(this);
	});
	as.w('div.catalog-inside').each(function() {
		new CustomScroll().init(this);
	});
	//galleries
	as.e.demousemove(document.body);
	as.w('table.gallery-container').each(function() {
		new Gallery().init(this);										  
	});
	
	//with popups
	as.w('table.with-popups').each(function() {
		new PopupController().init(this);									
	});
	as.w('ul.catalog-inside-gallery').each(function () {
		new simplePopupController().init(this);											 
	});
	
	as.w('div.where-to-buy a.popup').click(cityPopup);
}


































(function init() {
	flashController.init.apply(flashController);
	initOnReload();
})();