/* by (v) <v.remix@gmail.com> */

var Shop = {
	searchrepos: function(source, target) {
		var _dim = source.getCoordinates();
		target.setOpacity(0.85).setStyles({
			top: _dim['top'] + _dim['height'],
			left: _dim['left'],
			position: 'absolute',
			visibility: 'visible'
			//width: _dim['width']
		});
	},
	recalculateOption: function(el, pid, price) {
		var ls = $(el).getParent();
		ls.getParent().getChildren().each(function(li){
			if(li.getTag() == 'li') {
				if(li == ls) li.addClass('selected'); else li.removeClass('selected');
			}
			//console.log(li.getTag(), el, li, ls)
		});
		$('pprice'+pid).setText(price);
		//console.log(el, ls.getChildren())
	},
	test: function() {
		// todo
	},
	init: function() {
		new Png();
		// slider options
		if($('anotice')) {
			var slider = $('anotice');
			var sl = slider.effect('margin-left', {'duration': 1500, transition: Fx.Transitions.backOut});
			new Element('a', {
				'href': '#',
				'class': 'a',
				'events': {
					'click': function() {
						slider.setStyle('right','auto');
						sl.start(slider.getCoordinates()['left'], 2);
					}
				}
			}).setHTML('&lsaquo;').injectTop(slider);
			new Element('a', {
				'class': 'a',
				'events': {
					'click': function() {
						sl.start(slider.getCoordinates()['left'], window.getWidth()-2-slider.getSize()['size']['x']);
					}
				}
			}).setHTML('&rsaquo;').inject(slider);
			window.addEvent('scroll', function() {
				slider.setStyle('bottom', window.getScrollTop());
			});
			window.addEvent('resize', function() {
				slider.setStyle('right', 0);
			});
		}
		// search options
		if($('searchmore') && $('searchstring')) {
			//$('searchstring').addEvent('focus', function() {
			$('searchstring').addEvent('click', function() {
				Shop.searchrepos(this, $('searchmore'));
			});
			$('searchstring').addEvent('blur', function() {
				var h = function() {
					$('searchmore').setStyle('visibility', 'hidden')
				}
				h.delay(1000);
			});
		}
		if($('subscription_form')) {
			var m = $('themail');
			var va = m.value;
			m.addEvents({
				"focus": function() {
					if(this.value == va) this.value = '';
			},
				"blur": function() {
					if(this.value == '') this.value = va;
			}});
			$('subscription_form').addEvent('submit', function(e) {
				if(m.value == va || m.getValue() == false || !m.getValue().test('[^_.]([a-zA-Z0-9_]*[.]?[a-zA-Z0-9_]+[^_]){1}@{1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))')) {
					alert('Пожалуйста, заполните корректно поле e-mail!');
					m.addClass('errors');
					m.focus();
					// Prevent the submit
					new Event(e).stop();
				}
			});
		}
		$$(".cut").each(function(o){
			var t = o.innerHTML;
			var max = 200;
			while (max < t.length) {
				c = t.charAt(max);
				if (c.match(/\s/)) {
					d = t.substring(0,max) + "...";
					o.setHTML(d);
					break;
				}
				max--;
			}
		});
		$$(".product-img-list li a").each(function(a){
			var l = a.getProperty('href');
			if(l && (l != '' || l != '#')) {
				a.setProperty('href', l+'?random='+Base64.encode(window.getWidth()+':'+window.getHeight()))
			}
		});
	}
};

window.addEvent('domready', Shop.init);

var Png = new Class({
	initialize: function(){
		var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
		if((rslt != null && Number(rslt[1])>=5.5 && Number(rslt[1])<7) && !window.opera) {
			$$('.png', 'img').each(function(el){
				if(el.getTag() == 'img') {
					if(el.getProperty('src').match(/\.png$/i) != null) {
						$(el).setStyles({
							'width': el.getStyle('width'),
							'height': el.getStyle('height'),
							'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.getProperty('src')+"', sizingMethod='scale')"
						}).setProperty('src', 'http://webfx.eae.net/dhtml/pngbehavior/blank.gif');
					}
				} else {
					// found background-image: *.png
					var pos = $(el).getPosition();
					$(el).clone().setStyles({
						'background': '',
						'width': pos.width+"px",
						'height': pos.height+"px",
						'left': pos.left+"px",
						'top': pos.top+"px",
						'position': 'absolute'
					}).injectInside('body');
					$(el).setStyles({
						'width': pos.width+"px",
						'height': pos.height+"px",
						'background': '',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.currentStyle.backgroundImage.substring(5, el.currentStyle.backgroundImage.length-2)+"', sizingMethod='crop')"
					}).setHTML('');
					el.addEvent("propertychange", function(){
						if(window.event.propertyName=="style.backgroundImage"){
							var el = window.event.srcElement;
							if($(el).hasClass('png'))
								el.filters.item(0).src = el.currentStyle.backgroundImage.substring(5,el.currentStyle.backgroundImage.length-2);
						}
					});					
				}
			});
		}
	}
});
/*
Script: PBBDatePicker.js
	Contains <PBBDatePicker>

Author:
	Pokemon_JOJO, <http://www.mibhouse.org/pokemon_jojo>

License:
	MIT-style license.

*/

/*
Class: PBBDatePicker
	A powerfull DatePicker with many, many options and fonctionnality :D

Arguments:
	options - see Options below

Options:
	showDelay - the delay the onShow method is called. (defaults to 100 ms)
	hideDelay - the delay the onHide method is called. (defaults to 100 ms)
	offsets - the distance of your datepicker from the input. an Object with x/y properties.
	readOnly - is the input have readonly status ? (defaults to true)
	className - name for your DatePicker classNames. defaults to 'PBBDatePicker'.
	weekFirstDay - integer, first day of the week. 0 (for Sunday) through 6 (for Saturday)  
	dateFormat - the return format of selected date like php function date. (defaults to d/m/Y)
		d -> Day of the month, 2 digits with leading zeros
		D -> A textual representation of a day, three letters
		j -> Day of the month without leading zero
		l -> (lowercase 'L') A full textual representation of the day of the week
		N -> ISO-8601 numeric representation of the day of the week. 1 (for Monday) through 7 (for Sunday)
		w -> Numeric representation of the day of the week
		m -> Numeric representation of a month, with leading zeros
		M -> A short textual representation of a month, three letters
		F -> A full textual representation of a month, such as January or March
		n -> Numeric representation of a month, without leading zeros
		Y -> A full numeric representation of a year, 4 digits
		y -> A two digit representation of a year
		
		Example :
			2/15/2007 -> dateFormat : 'd/m/Y', -> 15/02/2007
			2/15/2007 -> dateFormat : 'M j Y', -> Feb 15 2007
		
	defaultYear - Year by default in the Year select list
	defaultMonth - Month by default in the Year select list
	defaultDay - Day by default selected
	selectMinDate - minimum date you can select
	selectMaxDate - maximum date you can select
	rangeYear - how many year to show in the Year select list ? an Object with min/max properties.
	iconImg - Image you can add to the input 
	monthNames - Array for month name
	dayNames - Array for day name
	todayName - Text to show in the TodayPicker ;)

Events:
	onShow - optionally you can alter the default onShow behaviour with this option (like displaying a fade in effect);
	onHide - optionally you can alter the default onHide behaviour with this option (like displaying a fade out effect);
*/
var PBBDatePicker = new Class({

	options: {
		onShow: function(picker){
			picker.setStyle('visibility', 'visible');
		},
		onHide: function(picker){
			picker.setStyle('visibility', 'hidden');
		},
		showDelay: 100,
		hideDelay: 100,
		offsets: {'x': 0, 'y': 20},
		readOnly: true,
		className: 'datepicker',
		weekFirstDay : 0,
		dateFormat : 'd/m/Y',
		defaultYear: new Date().getFullYear(),
		defaultMonth: new Date().getMonth(),
		defaultDay: new Date().getDate(),
		selectMinDate: false,
		selectMaxDate: false,
		rangeYear: {'min': new Date().getFullYear(), 'max': new Date().getFullYear() + 5},
		iconImg : null,
		monthNames : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
		dayNames : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
		todayName : 'Today'
	},

	initialize: function(input, options){
		var table, thead, tbody, th, tr, td;

		this.setOptions(options);
		// Form input  
		this.input = input;
		
		if(this.options.selectMinDate && new Date(this.options.defaultYear, this.options.defaultMonth, this.options.defaultDay).getTime() < this.options.selectMinDate.getTime()) {
			this.options.defaultYear = this.options.selectMinDate.getFullYear();
			this.options.defaultMonth = this.options.selectMinDate.getMonth();
			this.options.defaultDay = this.options.selectMinDate.getDate();			
		}
		
		if(this.options.selectMinDate && this.options.selectMaxDate && this.options.selectMinDate.getTime() > this.options.selectMaxDate.getTime())
			this.options.selectMaxDate = false;
		
		// Cache de la date selectionnee
		this.OnSelected = false;
		this.selectYear = this.options.defaultYear;
		this.selectMonth = this.options.defaultMonth;
		this.selectDay = this.options.defaultDay;
		this.selectedDate = new Date();
		
		// Div principale qui contient le datePicker
		this.datePicker = new Element('div', {
			'class': this.options.className,
			'styles': {
				'position': 'absolute',
				'top': '0',
				'left': '0',
				'visibility': 'hidden'
			}
		}).inject(document.body);
		// Wrapper
		this.wrapper = new Element('div').inject(this.datePicker);

		// Liste deroulante des mois
		this.monthPicker = new Element('select', {
			'events': {
				'focus': (function(){
					this.OnSelected = true;
				}).bindWithEvent(this),
				'blur': (function(){
					this.OnSelected = false;
				}).bindWithEvent(this),
				'change': (function(){
					this.input.focus();
					this.selectMonth = this.monthPicker.value;
					this.build();
				}).bindWithEvent(this)
			}
		});

		for(var m = 0; m < this.options.monthNames.length; m++) {
			if (this.options.defaultMonth == m)
				new Element('option', {'selected': 'selected', 'value': m}).setHTML(this.options.monthNames[m]).injectInside(this.monthPicker);
			else
				new Element('option', {'value': m}).setHTML(this.options.monthNames[m]).injectInside(this.monthPicker);
		}
		
		// Liste deroulante des annees
		this.yearPicker = new Element('select', {
			'events': {
				'focus': (function(){
					this.OnSelected = true;
				}).bindWithEvent(this),
				'blur': (function(){
					this.OnSelected = false;
				}).bindWithEvent(this),
				'change': (function(){
					this.input.focus();
					this.selectYear = this.yearPicker.value;
					this.build();
				}).bindWithEvent(this)
			}
		});

		for(var y = this.options.rangeYear.min; y < (this.options.rangeYear.max); y++) {
			if (this.options.defaultYear == y)
				new Element('option', {'selected': 'selected', 'value': y}).setHTML(y).injectInside(this.yearPicker);
			else
				new Element('option', {'value': y}).setHTML(y).injectInside(this.yearPicker);
		}

		// On ajoute monthPicker et yearPicker
		this.monthPicker.injectInside(this.wrapper);
		this.wrapper.appendText(' ');
		this.yearPicker.injectInside(this.wrapper);

		// Creation du tableau des jours
		table = new Element('table',{'cellspacing': '1px'});
		thead = new Element('thead').injectInside(table);

		// 1ere ligne contenant le nom des jours (1ere lettre)
		tr = new Element('tr').injectInside(thead);
		for (i = 0; i < 7; i++)	{ 
			new Element('th').appendText(this.options.dayNames[(this.options.weekFirstDay + i)%7].substr(0, 1)).injectInside(tr);
		}
		// Tbody contenant les jours
		tbody = new Element('tbody').injectInside(table);
		for(r=0;r<6;r++){
			tr = new Element('tr').injectInside(tbody);
			for(c=0;c<7;c++){
				td = new Element('td').setHTML('&nbsp;').injectInside(tr);
			}
		}		
		table.injectInside(this.wrapper);

		this.todayPicker = new Element('div', {
			'class': 'todayPicker',
			'styles': {
				'cursor':'pointer'
			},
			'events': {
				'click': (function(){
					this.selectYear = new Date().getFullYear();
					this.selectMonth = new Date().getMonth();
					this.selectDay = new Date().getDate();
					this.input.value = this.selectDate(this.options.dateFormat);
					this.build();
					this.end();
					return;
				}).bindWithEvent(this),
				'mouseover': (function(){
					this.todayPicker.addClass('todayPickerOver');
				}).bindWithEvent(this),
				'mouseout': (function(){
					this.todayPicker.removeClass('todayPickerOver');
				}).bindWithEvent(this)
			}
		}).setHTML(this.options.todayName).injectInside(this.wrapper);
		
		// Prepare l'input
		if(this.options.readOnly)
			this.input.setProperty('readOnly', 'true');

		this.input.setStyles({
			'background-image':'url(\'' + this.options.iconImg + '\')', 
			'background-repeat':'no-repeat', 
			'background-position':'center right',
			'cursor':'pointer'
		})		
		
		.addEvent('click', function(){
			if(this.activeDatePicker) {
				this.end(); return;
			}
			else if(this.input.focus)
				this.start();
		}.bindWithEvent(this))

		.addEvent('focus', function(){
			this.start();
		}.bindWithEvent(this))
		
		.addEvent('blur', function(){
			(function(){
				if(!this.OnSelected)
					this.end(); return;
			}.bind(this)).delay(150);
		}.bindWithEvent(this))

		.addEvent(window.ie ? 'keydown' : 'keypress', this.onKeyup.bindWithEvent(this));

		// Remplace les cases vide par le chiffre des jours
		this.build();
	},

	start: function(){
		if(this.activeDatePicker)
			return;

		this.position();
		this.timer = this.show.delay(this.options.showDelay, this);
	},
	
	// Remplacement des jours
	build: function(){
		this.selectFirstDay = new Date(this.selectYear, this.selectMonth, this.selectDay);
		
		this.selectFirstDay.setDate(1);
			
		if(this.selectFirstDay.getDay() == this.options.weekFirstDay)
			this.selectFirstDay.setDate(1 - 7 - (7 + this.selectFirstDay.getDay() - this.options.weekFirstDay)%7);	
		else			
			this.selectFirstDay.setDate(1 - (7 + this.selectFirstDay.getDay() - this.options.weekFirstDay)%7);

		var currentDay = new Date(this.selectFirstDay);
		
		$ES("tbody td", this.datePicker).each(function(el){
			
			el.removeClass('datePickerSelectedDay');
			el.removeClass('datePickerMinDate');
			el.removeClass('datePickerMaxDate');
			el.removeEvents();
			
			if (currentDay.getMonth() == new Date(this.selectYear, this.selectMonth).getMonth()) {
				
				if(this.options.selectMinDate && currentDay.getTime() < this.options.selectMinDate.getTime()) {
					el.addClass('datePickerMinDate');
				}
				else if(this.options.selectMaxDate && currentDay.getTime() > this.options.selectMaxDate.getTime()) {
					el.addClass('datePickerMinDate');
				}
				else {
					// Evenement survole
					el.addEvent('mouseover', function(){
						el.addClass('datePickerOver');
					}.bind(this));
		
					el.addEvent('mouseout', function() {
						el.removeClass('datePickerOver');
					}.bind(this));
					
					el.addEvent('click', function(){
						this.selectDay = el.innerHTML;
						this.input.value = this.selectDate(this.options.dateFormat);
						this.build();
						this.end();
						return;
					}.bind(this));
					
					// Ajoute un style a la case du jour selectionne	
					if(this.selectedDate.getDate() == currentDay.getDate() && this.selectedDate.getMonth() == currentDay.getMonth() && this.selectedDate.getFullYear() == currentDay.getFullYear())
						el.addClass('datePickerSelectedDay');
				}
				el.setHTML(currentDay.getDate());
			}
			else {
				el.setHTML('&nbsp;');
			}
			
			currentDay.setDate(currentDay.getDate() + 1);
		}.bind(this));
	},
	
	onKeyup: function(e){

		if (e.key && !e.shift) switch (e.key) {
			case 'enter':
				e.stop();
				this.input.value = this.selectDate(this.options.dateFormat);
				this.build();
				this.end();
				return;
			case 'right': case 'left': case 'up': case 'down':
				e.stop();
				
				if(e.key == 'right') {
					if(this.options.selectMaxDate && new Date(this.selectYear, this.selectMonth, (this.selectDay + 1)).getTime() > this.options.selectMaxDate.getTime() || this.options.selectMinDate && new Date(this.selectYear, this.selectMonth, (this.selectDay + 1)).getTime() < this.options.selectMinDate.getTime())
						return;
					this.selectDay++;
				}
				else if(e.key == 'left') {
					if(this.options.selectMinDate && new Date(this.selectYear, this.selectMonth, (this.selectDay - 1)).getTime() < this.options.selectMinDate.getTime() || this.options.selectMaxDate && new Date(this.selectYear, this.selectMonth, (this.selectDay - 1)).getTime() > this.options.selectMaxDate.getTime())
						return;
					this.selectDay--;
				}
				else if(e.key == 'up') {
					if(this.options.selectMinDate && new Date(this.selectYear, this.selectMonth, (this.selectDay - 7)).getTime() < this.options.selectMinDate.getTime() || this.options.selectMaxDate && new Date(this.selectYear, this.selectMonth, (this.selectDay - 7)).getTime() > this.options.selectMaxDate.getTime())
						return;
					this.selectDay = this.selectDay - 7;
				}
				else if(e.key == 'down') {
					if(this.options.selectMaxDate && new Date(this.selectYear, this.selectMonth, (this.selectDay + 7)).getTime() > this.options.selectMaxDate.getTime() || this.options.selectMinDate && new Date(this.selectYear, this.selectMonth, (this.selectDay + 7)).getTime() < this.options.selectMinDate.getTime())
						return;
					this.selectDay = this.selectDay + 7;
				}
			
				this.selectedDate = new Date(this.selectYear, this.selectMonth, this.selectDay);
				this.selectYear =  this.selectedDate.getFullYear();
				this.selectMonth =  this.selectedDate.getMonth();
				this.selectDay  = this.selectedDate.getDate();
				
				this.input.value = this.selectDate(this.options.dateFormat);
				this.build();
				return;
			case 'esc':
				this.end(); return;
		}

	},
	
	selectDate: function(returnFormatDate){
		this.selectedDate = new Date(this.selectYear, this.selectMonth, this.selectDay);
		this.monthPicker.value = this.selectMonth;
		this.yearPicker.value = this.selectYear;
		
		if(!returnFormatDate)
			returnDate = this.options.dateFormat;
		else
			returnDate = returnFormatDate;
		
		returnDate = returnDate.replace(/D/g, '[D]').replace(/l/g, '[l]').replace(/F/g, '[F]').replace(/M/g, '[M]');
		
		// [d] Day of the month, 2 digits with leading zeros
		if(this.selectedDate.getDate() < 10)
			returnDate = returnDate.replace(/d/g, '0' + this.selectedDate.getDate());
		else
			returnDate = returnDate.replace(/d/g, this.selectedDate.getDate());
		
		// [j] Day of the month without leading zero
		returnDate = returnDate.replace(/j/g, this.selectedDate.getDate());
		
		// [N] ISO-8601 numeric representation of the day of the week. 1 (for Monday) through 7 (for Sunday)
		if(this.selectedDate.getDay() == 0)
			returnDate = returnDate.replace(/N/g, 7);
		else
			returnDate = returnDate.replace(/N/g, this.selectedDate.getDay());
		
		// [w] Numeric representation of the day of the week
		returnDate = returnDate.replace(/w/g, this.selectedDate.getDay());
			
		// [m] Numeric representation of a month, with leading zeros
		if((this.selectedDate.getMonth() + 1) < 10)
			returnDate = returnDate.replace(/m/g, '0' + (this.selectedDate.getMonth() + 1));
		else
			returnDate = returnDate.replace(/m/g, (this.selectedDate.getMonth() + 1));
			
		// [n] Numeric representation of a month, without leading zeros
		returnDate = returnDate.replace(/n/g, (this.selectedDate.getMonth() + 1));
		
		// [Y] A full numeric representation of a year, 4 digits
		returnDate = returnDate.replace(/Y/g, this.selectedDate.getFullYear());
		
		// [y] A two digit representation of a year
		returnDate = returnDate.replace(/y/g, (this.selectedDate.getFullYear() + '').substr(2, 2) );
		
		// Textual replacement need to be at last ;)
		
		// [D] A textual representation of a day, three letters
		returnDate = returnDate.replace(/\[D\]/g, this.options.dayNames[this.selectedDate.getDay()].substr(0, 3));

		// [l] (lowercase 'L') A full textual representation of the day of the week
		returnDate = returnDate.replace(/\[l\]/g, this.options.dayNames[this.selectedDate.getDay()]);

		// [F] A full textual representation of a month, such as January or March
		returnDate = returnDate.replace(/\[F\]/g, this.options.monthNames[this.selectedDate.getMonth()]);

		// [M] A short textual representation of a month, three letters
		returnDate = returnDate.replace(/\[M\]/g, this.options.monthNames[this.selectedDate.getMonth()].substr(0, 3));
		
		return returnDate;
	},

	end: function(event){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this);
	},

	position: function(){
		var pos = this.input.getPosition();
		this.datePicker.setStyles({
			'left': pos.x + this.options.offsets.x,
			'top': pos.y + this.options.offsets.y			
		});
	},
	
	show: function(){
		this.activeDatePicker = true;
		if (this.options.timeout) this.timer = this.hide.delay(this.options.timeout, this);
		this.fireEvent('onShow', [this.datePicker]);
	},

	hide: function(){
		this.activeDatePicker = false;
		this.fireEvent('onHide', [this.datePicker]);
	}
});

PBBDatePicker.implement(new Events, new Options);

/*
	Slimbox v1.41 - The ultimate lightweight Lightbox clone
	by Christophe Beyls (http://www.digitalia.be) - MIT-style license.
	Inspired by the original Lightbox v2 by Lokesh Dhakar.
*/

var Lightbox = {

	init: function(options){
		this.options = $extend({
			resizeDuration: 400,
			resizeTransition: false,	// default transition
			initialWidth: 250,
			initialHeight: 250,
			animateCaption: true,
			showCounter: true
		}, options || {});

		this.anchors = [];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^lightbox/i)){
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);
		this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

		this.overlay = new Element('div', {'id': 'lbOverlay'}).injectInside(document.body);

		this.center = new Element('div', {'id': 'lbCenter', 'styles': {'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth/2), 'display': 'none'}}).injectInside(document.body);
		this.image = new Element('div', {'id': 'lbImage'}).injectInside(this.center);
		this.prevLink = new Element('a', {'id': 'lbPrevLink', 'href': '#', 'title': 'Щелкните, чтобы открыть предыдущее изображение', 'styles': {'display': 'none'}}).injectInside(this.image);
		this.nextLink = this.prevLink.clone().setProperties({'id': 'lbNextLink', 'title': 'Щелкните, чтобы открыть следующее изображение'}).injectInside(this.image);
		this.prevLink.onclick = this.previous.bind(this);
		this.nextLink.onclick = this.next.bind(this);

		this.bottomContainer = new Element('div', {'id': 'lbBottomContainer', 'styles': {'display': 'none'}}).injectInside(document.body);
		this.bottom = new Element('div', {'id': 'lbBottom'}).injectInside(this.bottomContainer);
		new Element('a', {'id': 'lbCloseLink', 'href': '#'}).injectInside(this.bottom).onclick = this.overlay.onclick = this.close.bind(this);
		this.caption = new Element('div', {'id': 'lbCaption'}).injectInside(this.bottom);
		this.number = new Element('div', {'id': 'lbNumber'}).injectInside(this.bottom);
		new Element('div', {'styles': {'clear': 'both'}}).injectInside(this.bottom);

		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			resize: this.center.effects($extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
			image: this.image.effect('opacity', {duration: 500, onComplete: nextEffect}),
			bottom: this.bottom.effect('margin-top', {duration: 400, onComplete: nextEffect})
		};

		this.preloadPrev = new Image();
		this.preloadNext = new Image();
	},

	click: function(link){
		if (link.rel.length == 8) return this.show(link.href, link.title);

		var j, imageNum, images = [];
		this.anchors.each(function(el){
			if (el.rel == link.rel){
				for (j = 0; j < images.length; j++) if(images[j][0] == el.href) break;
				if (j == images.length){
					images.push([el.href, el.title]);
					if (el.href == link.href) imageNum = j;
				}
			}
		}, this);
		return this.open(images, imageNum);
	},

	show: function(url, title){
		return this.open([[url, title]], 0);
	},

	open: function(images, imageNum){
		this.images = images;
		this.position();
		this.setup(true);
		this.top = window.getScrollTop() + (window.getHeight() / 15);
		this.center.setStyles({top: this.top, display: ''});
		this.fx.overlay.start(0.8);
		return this.changeImage(imageNum);
	},

	position: function(){
		this.overlay.setStyles({'top': window.getScrollTop(), 'height': window.getHeight()});
	},

	setup: function(open){
		var elements = $A(document.getElementsByTagName('object'));
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.style.visibility;
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});
		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		this.step = 0;
	},

	keyboardListener: function(event){
		switch (event.keyCode){
			case 27: case 88: case 67: this.close(); break;
			case 37: case 80: this.previous(); break;
			case 39: case 78: this.next();
		}
	},

	previous: function(){
		return this.changeImage(this.activeImage-1);
	},

	next: function(){
		return this.changeImage(this.activeImage+1);
	},

	changeImage: function(imageNum){
		if (this.step || (imageNum < 0) || (imageNum >= this.images.length)) return false;
		this.step = 1;
		this.activeImage = imageNum;

		this.bottomContainer.style.display = this.prevLink.style.display = this.nextLink.style.display = 'none';
		this.fx.image.hide();
		this.center.className = 'lbLoading';

		this.preload = new Image();
		this.preload.onload = this.nextEffect.bind(this);
		this.preload.src = this.images[imageNum][0];
		return false;
	},

	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.center.className = '';
			this.image.style.backgroundImage = 'url('+this.images[this.activeImage][0]+')';
			this.image.style.width = this.bottom.style.width = this.preload.width+'px';
			this.image.style.height = this.prevLink.style.height = this.nextLink.style.height = this.preload.height+'px';

			this.caption.setHTML(this.images[this.activeImage][1] || '');
			this.number.setHTML((!this.options.showCounter || (this.images.length == 1)) ? '' : 'Изображение '+(this.activeImage+1)+' из '+this.images.length);

			if (this.activeImage) this.preloadPrev.src = this.images[this.activeImage-1][0];
			if (this.activeImage != (this.images.length - 1)) this.preloadNext.src = this.images[this.activeImage+1][0];
			if (this.center.clientHeight != this.image.offsetHeight){
				this.fx.resize.start({height: this.image.offsetHeight});
				break;
			}
			this.step++;
		case 2:
			if (this.center.clientWidth != this.image.offsetWidth){
				this.fx.resize.start({width: this.image.offsetWidth, marginLeft: -this.image.offsetWidth/2});
				break;
			}
			this.step++;
		case 3:
			this.bottomContainer.setStyles({top: this.top + this.center.clientHeight, height: 0, marginLeft: this.center.style.marginLeft, display: ''});
			this.fx.image.start(1);
			break;
		case 4:
			if (this.options.animateCaption){
				this.fx.bottom.set(-this.bottom.offsetHeight);
				this.bottomContainer.style.height = '';
				this.fx.bottom.start(0);
				break;
			}
			this.bottomContainer.style.height = '';
		case 5:
			if (this.activeImage) this.prevLink.style.display = '';
			if (this.activeImage != (this.images.length - 1)) this.nextLink.style.display = '';
			this.step = 0;
		}
	},

	close: function(){
		if (this.step < 0) return;
		this.step = -1;
		if (this.preload){
			this.preload.onload = Class.empty;
			this.preload = null;
		}
		for (var f in this.fx) this.fx[f].stop();
		this.center.style.display = this.bottomContainer.style.display = 'none';
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		return false;
	}
};

window.addEvent('domready', Lightbox.init.bind(Lightbox));

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

function open_window(link,w,h) { //opens new window
	var win = "width="+w+",height="+h+",menubar=no,location=no,resizable=yes,scrollbars=yes";
	newWin = window.open(link,'newWin',win);
	newWin.focus();
}

function confirmDelete(id, ask, url) { //confirm order delete
	temp = window.confirm(ask);
	if (temp) //delete
	{
		window.location=url+id;
	}
}

function buyProduct(id) {
	document.forms['HiddenFieldsForm_'+id].submit();
}

function confirmUnsubscribe() //unsubscription confirmation
{
	temp = window.confirm('{/literal}{$smarty.const.QUESTION_UNSUBSCRIBE}{literal}');
	if (temp) //delete
	{
		window.location="index.php?killuser=yes";
	}
}

function validate() // newsletter subscription form validation
{
	if (document.subscription_form.email.value.length<1)
	{
		alert("{/literal}{$smarty.const.ERROR_INPUT_EMAIL}{literal}");
		return false;
	}
	if (document.subscription_form.email.value == 'Email')
	{
		alert("{/literal}{$smarty.const.ERROR_INPUT_EMAIL}{literal}");
		return false;
	}
	return true;
}
function validate_disc() // review form verification
{
	if (document.formD.nick.value.length<1)
	{
		alert("{/literal}{$smarty.const.ERROR_INPUT_NICKNAME}{literal}");
		return false;
	}

	if (document.formD.topic.value.length<1)
	{
		alert("{/literal}{$smarty.const.ERROR_INPUT_MESSAGE_SUBJECT}{literal}");
		return false;
	}

	return true;
}
function validate_search()
{

	if (document.Sform.price1.value!="" && ((document.Sform.price1.value < 0) || isNaN(document.Sform.price1.value)))
	{
		alert("{/literal}{$smarty.const.ERROR_INPUT_PRICE}{literal}");
		return false;
	}
	if (document.Sform.price2.value!="" && ((document.Sform.price2.value < 0) || isNaN(document.Sform.price2.value)))
	{
		alert("{/literal}{$smarty.const.ERROR_INPUT_PRICE}{literal}");
		return false;
	}

	return true;
}
function _formatPrice( _price )
{	
			
	_pointIndex = -1;	
	for( i=0; i< _price.length; i++ )
		if ( _price.charAt(i) == '.' )
		{
			_pointIndex = i;
			break;
		}

	if (  _pointIndex == -1 )
		_price = _price + ".00";
	else if (  _price.length-1 - _pointIndex == 1  )
		_price = _price + "0";

	_res = "";

	i=0;
	for( i=_price.length-1; i >= 0; i-- )
	{
		if ( _price.charAt(i) == '.' )
			break;
		else
			_res = _price.charAt(i) + _res;
	}

	_res = "." + _res;

	i--;
	_digitCounter = 0;
	for( ; i>=0; i-- )
	{
		_digitCounter ++;
		_res = _price.charAt(i) + _res;
		if ( _digitCounter == 3 && i != 0 )
		{
			_res = "," + _res;
			_digitCounter = 0;
		}
				
	}

	return _res;						
			
}