var IE='\v'=='v';

if ($.browser.opera && $.browser.version >= 9.8) {
		$('h2.cufon-index').css('lineHeight', '95px')
	}

if (!($.browser.opera && $.browser.version < 9.5)) {
	Cufon.replace('h1.main-header', {
		color: '-linear-gradient(#363636, #963c28)'
	});
	Cufon.replace('h3.letter', {
		color: '-linear-gradient(#363636, #963c28)'
	});
	Cufon.replace('h2.cufon-index a', {
		color: '-linear-gradient(#363636, #963c28)',

		hover: {
			color: '#363636'
		}
	});
}
/*
 * Мигание фонового изображения
 */

var m = document.uniqueID&& document.compatMode&& !window.XMLHttpRequest&& document.execCommand;

try{if(!!m){m("BackgroundImageCache", false, true)}} catch(oh){};


function invertById(target) {
	if (trgt = $('#'+target)[0])	{
		trgt.className = (trgt.className == 'no'? 'yes' : 'no');
	}
}

function closeId(target) {
	if (trgt = $('#'+target)[0])	{
		trgt.className =  'no';
	}
}

var orderform = {
	onload : function() {
		var $form = this.form = $('#request form');
		var t = this;
		$('.popup-list', $form).each(function() {
			this.onupdate = function(key, val){t.onupdate(key,val)};
		});
		var qq = '';
		for (var i in this.services) {
			qq += i + "=>" + this.services[i] + ", ";
		}
		this.setoptions('salon', this.salons);
		for (var i in this.salon_urls) {
			var href = window.location.href;
			if (href.indexOf(this.salon_urls[i]) != -1) {
				this.val('salon', this.salons[i]);
			}
		}
		this.setoptions('service', this.get_services());
		this.setoptions('masters', this.get_masters());
	},
	onupdate : function(key, val) {
		if (key == 'salon') {
			this.setoptions('service', this.get_services());
		}
		if (key == 'salon' || key == 'service') {
			this.setoptions('masters', this.get_masters());
		}
	},
	val : function(name, val) {
		var $val = $('a[rel=' + name + ']', this.form);
		return $val.text(val);
	},
	setoptions : function (name, options) {
		if (name == 'masters') {
			var wrap = $('.master-wrap', this.form);
			if (options.length) {
				wrap.show();
			} else {
				wrap.hide();
				this.val('masters', '');
			}
		}
		if (!options.length) return;
		$list = $('.small-popup.' + name + ' ul');
		var val = this.val(name);
		var html = '';
		var index = -1;
		for (var i in options)
		{
			html += '<li><a href="#">' + options[i] + '</a></li>';
			if (options[i] == val) index = i;
		}
		$list.html(html);
		if (index == -1)
		{
			this.val(name, options[0]);
		}
	},
	get_salon : function() {
		var salon = this.val('salon');
		for (var i in this.salons) {
			if (this.salons[i] == salon) return i;
		}
		return -1;
	},
	get_services : function() {
		var salon = this.get_salon();
		if (salon == -1) return [];
		var res = [];
		for (var service in this.services) {
			var kind = this.services[service];
			var masters = this.masters[salon][kind];
			if (typeof(masters) == 'undefined' || masters)
			{
				res[res.length++] = service;
			}
		}
		return res;
	},
	get_masters : function() {
		var salon = this.get_salon();
		if (salon == -1) return [];
		var service = this.val('service');
		var kind = this.services[service];
		var masters = this.masters[salon][kind];
		if (!masters) return [];
		return masters.split(", ");
	}
}

$(function () {
	/* Галерея */

	var gOpt = {
		init: function() {
			$('.photo-gallery ul').live('click', this.event).parent();
		},
		event: function(e) {
			var et = $(e.target).parent().parent();
			if (!et.hasClass('selected-image')) {
				gOpt.load(et.addClass('selected-image').siblings().removeClass('selected-image').end().end().attr('href'),  $(this).parent());
			}
			return false;
		},
		load:function(src, gallery) {
			timerOff();
			$('div.old', gallery).remove();
			var img = new Image();
			$(img)
				.load(gOpt.completeLoad(src, gallery))
				.error(gOpt.errorLoad)
				.attr('src', src);
		},
		errorLoad:function() {},
		completeLoad:function(src, gallery) {
			var curPhoto = gallery.find('.main-photo');
			var newPhoto = curPhoto.clone(true).css({backgroundImage:'url(' + src + ')', opacity:0}).appendTo($('div.image-container',gallery));

			if (IE && $.browser.version == '6.0') {
				newPhoto.css('opacity', 1)
				curPhoto.remove();
			} else {
				curPhoto.addClass('old')
				newPhoto.animate({opacity:1}, 600, function() {curPhoto.remove()})
			}

			timerOn();
			return false;
		}
	}
	gOpt.init();

	var intervalAutoChange, autoGallery = $('.auto-gallery');
	function timerOn() {
		intervalAutoChange = setTimeout(function () {
			//console.log('set')
			var nextImage = $('li.selected-image+li', autoGallery);
			if (!nextImage.get(0))
				nextImage = $('li:first-child', autoGallery)
			gOpt.load(nextImage.addClass('selected-image').siblings().removeClass('selected-image').end().find('a').attr('href'), autoGallery);
		},
		4000)
	}
	function timerOff() {
		intervalAutoChange = clearTimeout(intervalAutoChange);
	}

	timerOn();



	/* Табы */
	var dlTaber, dtTaber, ddTaber, selectedDt, selectedDD, tabSwitcher = function (el) {
		selectedDt = el;
		selectedDD = el.next('dd.tab');
		if (!$('*', el.next('dd')).get(0)) {
			href = $('a', el).attr('href');
			selectedDD.load(href);
		}
		if (!IE) {
			dlTaber = el.parent();
			dtTaber = $('dt.tab', dlTaber);
			ddTaber = $('dd.tab:visible', dlTaber);
			dtTaber.removeClass('selected');
			el.addClass('selected');
			ddTaber.stop().animate({
				opacity: 0
			},
			500, function () {
				ddTaber.hide()
			});
			selectedDD.stop().show().animate({
				opacity: 1
			},
			500)
		} else {
			el.siblings().removeClass('selected').end().next('dd').andSelf().addClass('selected');
		}
	}
	var cosmeticSwitcher = function (el) {
		el.siblings('dt').removeClass('selected').end().addClass('selected');
		className = $('a', el).attr('class');
		all = $('li img', el.parent());
		if (className) {
			all.stop().animate({
				opacity: .1
			},
			800);
			all.filter('li.' + className + ' img').stop().animate({
				opacity: 1
			},
			800);
		} else {
			all.stop().animate({
				opacity: 1
			},
			800);
		}
	}
	var bindTabs = function () {
		$('dl.taber dt.tab').live('click', function () {
			if (!$(this).hasClass('selected') & !$(this).parent().hasClass('cosmetics')) {
				tabSwitcher($(this));
			} else if ($(this).parent().hasClass('cosmetics')) {
				cosmeticSwitcher($(this));
			}
			return false;
		});
	}
	bindTabs();
	/* Аккордеон */
	var accordSpeedUp = 300,
		accordSpeedDown = 300,
		accordion = function (link, dl) {
		if (!link.parent().hasClass('current')) {
			link.parent().siblings().filter('dd').slideUp(accordSpeedUp).end().removeClass('current').end().next('dd').slideDown(accordSpeedDown).andSelf().addClass('current')
		}
	}
	$('dl.accord-list dd:not(.current)').hide();
	$('dl.accord-list').live('click', function (e) {
		if (e.target.tagName == "A") {
			$(this).unbind('click');
			accordion($(e.target), $(this));
		}
		return false;
	});
	/* Показать попап */
	var mainPopupLinks = $('.popup');
	if (mainPopupLinks.get(0)) {
		var popup = $('#popup-frame'),
			popupShadow = $('.popup-shadow', popup),
			popupBlock = $('.popup-block', popup),
			popupBody = $('.pbody', popup),
			oldPage, newPage, visibleHeight, popupBlockHeight, popupScrollTop, openSpeed, closeSpeed;
		popupShadow.height($(document).height() + 50);
		if (!IE) {
			openSpeed = 150;
			closeSpeed = 150;
		}
		var popupClose = function () {
			if (!IE) {
				popupBlock.animate({
					opacity: 0
				},
				closeSpeed, function () {
					popupShadow.animate({
						opacity: 0
					},
					closeSpeed, function () {
						popup.hide();
						popupBlock.hide();
						popup.removeClass('request');
					});
				});
			} else {
				popupBlock.hide();
				popupShadow.hide();
				popup.hide();
				popup.removeClass('request')
			}
		}
		function newTopPosition(popupBlockHeight) {
			return popupBlockHeight > visibleHeight ? popupScrollTop + 50 : popupScrollTop + (visibleHeight - popupBlockHeight) / 2;
		}
		function popupBlockShow(h) {
			if (!IE) {
				popupBlock.css({
					top: newTopPosition(h),
					display: 'block'
				}).animate({
					opacity: 1
				},
				openSpeed, function () {
					popupShadow.removeClass('progress');
				})
			} else {
				popupBlock.show().css({
					top: newTopPosition(popupBlock.height())
				});
				popupShadow.removeClass('progress');
				if ($.browser.version == 6) {
					$('dd.selected', popupBody).removeClass('selected').addClass('selected')
				}
			};
			popupShadow.height($(document).height() + 50)
		}


		var popupOpen = function (el) {
			//console.log(el)
			if (el) newPage = el.attr('href');
			if (el.hasClass('join')) popup.addClass('request');


			visibleHeight = $('html').height();
			popupScrollTop = $(window).scrollTop();
			popup.show();
			if (!IE) {
				popupShadow.show().css('background-position', '50% ' + (popupScrollTop + visibleHeight / 2).toFixed(0) + 'px').addClass('progress').animate({
					opacity: .9
				},
				openSpeed, function () {
					if (newPage == oldPage) {
						popupBlockShow(popupBlock.height())
					} else {
						$.post(newPage, {'ajax':1}, function(response){
							popupBody.html(response);
							popupBlockShow(popupBlock.height());
							oldPage = newPage;
						})
					}
				});
			} else {
				popupShadow.show().css('background-position', '50% ' + (popupScrollTop + visibleHeight / 2).toFixed(0) + 'px').addClass('progress').css('opacity', '0.9');
				if (newPage == oldPage) {
					popupBlockShow(popupBlock.height());
				} else {
					$.post(newPage, {'ajax':1}, function(response){
						popupBody.html(response);
						popupBlockShow(popupBlock.height());
						oldPage = newPage;
					})
				}
			}
		} // Если в попапе есть контент - инициализируем
		/*
		 * if ($('*', popupBody).get(0)) { popupOpen(); }
		 */
		// Попап по клику на ссылку
		$('.popup').live('click', function (e) {
			var clicked = $(e.target).closest('a');
			if (clicked.get(0)) popupOpen(clicked);
			return false;
		}) // Закрыть попап
		$('.popup-close').add(popupShadow).click(function () {
			popupClose();
			$('.small-popup').hide();
			return false;
		}) // Закрыть попап по Esc
	}
	var list = $('.small-list');
	var multiList = $('.mini-popup');
	var closeMini = function () {
		if (IE) {
			m.hide();
		} else {
			m.animate({
				opacity: 0
			},
			'fast', function () {
				$(this).hide()
			});
		}
		$('body').unbind('click.multi');
	}

	$('.popup-list').live('click', function (e) {
		var t = $(this);

		if (t.hasClass('multi')) {
			cur = t;
			rel = cur.attr('rel');
			startY = e.pageY;
			m = $('.small-popup.' + rel);
			mC = $('.body', m);
			if (!cur.hasClass('puthere')) {
				complete = function ($this) {
					window.location.href = $this.attr('href');
					return false;
				}
			} else {
				complete = function ($this) {
					cur.text($this.text());
					$this.parent().parent().parent().parent().find('li').removeClass('c').end().end().end().end().addClass('c');
					var func = cur.attr('onupdate');
					if (func) func(cur.attr('rel'), cur.text());
					return false;
				}
			}
			if (mC.get(0)) {
				var dl = $('dl', mC);
				x = e.pageX - 90;
				y = e.pageY - 125;
				m.css({
					top: y,
					left: x,
					display: 'block'
				});
				dlH = dl.height();
				//console.log(dlH)
				//console.log(dl)
				dlMT = -dlH / 2 + 16;
				if (IE) {
					dl.css({
						marginTop: dlMT
					})
				} else {
					dl.css({
						marginTop: dlMT,
						top: '100px'
					});
					m.animate({
						opacity: 1
					},
					300)
				}
				if (dlH > 238) {
					$('.body-cont', m).height(215);
					mC.mousemove(function (e) {
						//console.log(1)
						newY = ((dlH / 2 - 107) * (startY - e.pageY)) / 107;
						$('dl', mC).css({
							marginTop: (dlMT + newY)
						})
					})
				} else {
					$('.body-cont', m).css('height','auto');
					mC.unbind('mousemove')
					m.css({
						top: y + m.height() / 2 + 5,
						left: x + m.width() / 2 - 20,
						display: 'block'
					});
					dl.css({
						marginTop: 0,
						top: 0
					});
				}
				$('body').bind('click.multi', function (e) {
					closeMini();
					if ($('a', m).index($(e.target)) != -1) {
						return complete($(e.target));
					}
					$('body').unbind('click.multi');
				})
			}
		} else {
			cur = $(this);
			rel = '.small-popup.' + $(this).attr('rel');
			x = e.pageX;
			y = e.pageY;
			newL = $(rel);
			newL.css({
				top: y - newL.height() + 19,
				left: x - newL.width() / 2
			}).show();
			if (!cur.hasClass('puthere')) {
				complete = function ($this) {
					window.location.href = $this.attr('href');
					return false;
				}
			} else {
				complete = function ($this) {
					if (newL.hasClass('years')) {
						function yearLoad(data) {
							cur.parent().next('dd').html(data.pages).end().parent().prev('div').html(data.page)
						}
						$.getJSON($this.attr('href'), function (data) {
							yearLoad(data)
						})
					}
					cur.text($this.text());
					$this.parent().siblings().removeClass('c').end().addClass('c');
					var func = cur.attr('onupdate');
					if (func) func(cur.attr('rel'), cur.text());
					return false;
				}
			}
			$('body').bind('click.salon', function (e) {
				if (!$(e.target).parent().hasClass('ui-datepicker-header')) {
					newL.hide();
					$('body').unbind('click.salon');
					if ($('a', newL).index($(e.target)) != -1) {
						return complete($(e.target));
					}
				}
			})
		}
		return false;
	});
	$(document).keydown(function (e) {
		if (e.which == 27) {

				closeFaq();
				if (popup) {
					popupClose()
				}
				list.hide();
				closeMini();

		}
	});



	// косметический горизонтальный скролл
	$.fn.slider = function(options) {
		var defaults = {
			enterLeaveSpeed:300,
			imageEvent: false
		}, settings = $.extend(defaults, options);

		return this.each(function(){
			var cosmoblock = $('ul', this)
				,cW = cosmoblock.width()
				,dW = $(document).width()
				,halfdW = .5 * dW
				,halfcW = .5 * cW
				,Q = halfcW - halfdW
				,getLeft = function (x) {
					return -halfcW + ((halfdW - x) * Q / halfdW);
				}
				,slideCosm = function (x, type) {
					cosmoblock.stop().animate({left: x}, settings.enterLeaveSpeed,
						function () {
							if (type != 'mouseleave') moveON();
						})
				}
				,moveON = function () {
					cosmoblock.bind('mousemove', function (e) {
						cosmoblock.stop().css('left', getLeft(e.pageX))
					})
				};

			//if (settings.imageEvent) cosmoblock.bind('mouseover mouseout', settings.imageEvent);

			if (cW > dW) {
				cosmoblock
					.mouseenter(function (e) {
						slideCosm(getLeft(e.pageX))
					})
					.mouseleave(function (e) {
						cosmoblock.unbind('mousemove');
						slideCosm(-halfcW, e.type)
					})
			}
		});

	};



	$('#cosmetics').slider();

/*
	$('#portfolio').slider(
		{
		imageEvent:function(e) {
			var eTarget = e.target, eType = e.type,
				li = $(eTarget).closest('li'),
				hidenBlock = li.find('div.hidden');


			if (IE) {
				if ((eType == 'mouseover' && !li.hasClass('current')) || (eType == 'mouseout' && li.hasClass('current')))
					li.toggleClass('current');
			} else {
				if (eType == 'mouseover' && !li.hasClass('current')) {
					li.addClass('current');
					hidenBlock.stop().animate({opacity:1}, 'fast');
				} else if (eType == 'mouseout' && li.hasClass('current')) {
					li.removeClass('current');
					hidenBlock.stop().animate({opacity:0}, 'fast')
				}
			}


			//console.log(eType)
		}
	});
*/

	var folio = {
		init: function() { var _this = this;
			_this.o = $('#portfolio > ul')
				.bind('mouseenter', _this.mouseenter)
				.bind('mouseleave', _this.mouseleave)
				.find('li').bind('mouseenter mouseleave', _this.imageEvent).end();

			var BC = $(document).width()/2
				AB =  parseInt(_this.o.attr('style').split(IE?'WIDTH:':'width:')[1])/2 - BC;

			_this.bc = BC;
			_this.calc = function(x) {
				return - (x * AB)/BC - BC;
			}
		},
		mouseenter: function(e) { var _this = folio;
			_this.o
				.animate({left:_this.calc(e.pageX)},'fast', function() {
					$(this).bind('mousemove', _this.mousemove);
				})
		},
		mouseleave:function() {	var _this = folio;
			_this.o.unbind('mousemove')
					.animate({left:_this.calc(_this.bc)},'fast')
		},
		mousemove:function(e) {	var _this = folio;
			_this.o.css({left:_this.calc(e.pageX)})
		},
		imageEvent:function(e) {
			var eType = e.type,	li = $(this),
				hidenBlock = li.find('div.hidden');

			if (IE) {
				if ((eType == 'mouseenter' && !li.hasClass('current')) || (eType == 'mouseleave' && li.hasClass('current')))
					li.toggleClass('current');
			} else {
				if (eType == 'mouseenter' && !li.hasClass('current')) {
					li.addClass('current');
					hidenBlock.stop().animate({opacity:1}, 'fast');
				} else if (eType == 'mouseleave' && li.hasClass('current')) {
					li.removeClass('current');
					hidenBlock.stop().animate({opacity:0}, 'fast')
				}
			}
		}
	}

	if ($('#portfolio').get(0)) folio.init();


	// Пагинатор
	if ($('div.page').get(0)) {
		var pager = $('dl.pager dd'),
			page, pageLink;
		pager.live('click', function (e) {
			page = $(this).parent().prev('.page');
			target = $(e.target);
			if (target.hasClass('p') & !target.parent().hasClass('c')) {
				pageLink = target.attr('href');
				target.parent().siblings().removeClass('c').end().addClass('c');
				$('<div>').load(pageLink, '', function (data, status) {
					if (status == 'success') {
						page.html($(this).html())
					}
				})
			}
			return false;
		})
	} // faq
	if ($('.faq-block').get(0)) {
		var fData;

		function bindCloseFaq() {
			$(document).bind('click.faq', function (e) {
				if (e.target.tagName == 'SPAN' && $(e.target).parent().parent().parent().hasClass('faq-block')) {
					x = e.pageX - 15;
					y = e.pageY;
					$('.pbody', Fpopup).html($(e.target).parent().nextAll('div.answer').html());
					fPopupAlign(x, y);
				} else {
					closeFaq();
				}
			})
		}

		function fPopupAlign(x, y) {
			Fpopup.removeClass('right');
			if (($(document).width() - x) < 569) {
				x -= 535;
				Fpopup.addClass('right');
			}
			y -= Fpopup.height();
			if (IE && $.browser.version == 6) {
				y -= 20;
				x += 10
			}
			Fpopup.css({
				left: x,
				top: y
			});
		}

		function showData(data, x, y) {
			bindCloseFaq();
			if (!$('#faq-popup').get(0)) {
				Fpopup = $('<div id="faq-popup"><a href="#close-link" class="popup-close" title="закрыть окно">закрыть окно</a><div class="phead"></div><div class="pbody"></div><div class="ffoot png_bg"></div></div>').appendTo($('body'));
			} else {
				Fpopup = $('#faq-popup');
			}
			$('.pbody', Fpopup).html(data);
			fPopupAlign(x, y);
			Fpopup.show()
		}

		function showFaq(e) {
			clicked = e.target;
			if (clicked.tagName == "SPAN") {
				x = e.pageX - 15;
				y = e.pageY;
				fData = $(clicked).parent().nextAll('div.answer').html();
				showData(fData, x, y);
			}
		}

		function closeFaq() {
			$('#faq-popup').hide();
			$(document).unbind('click.faq')
		}
		var faq = $('.faq-block');
		faq.live('click', function (e) {
			e.preventDefault();
			if (!$('#faq-popup').is(':visible')) {
				showFaq(e);
			}
		}) // $('#faq-popup .popup-close').live('faq.click', function() {
		// closeFaq() } )
	}

	// Формы

	// TODO Тут возникает ошибка в ИЕ
	//$('input#file').live('change', function () {
	//		$(this).next('span#file-name').text($(this).val())
	//	})
	

	// banner
	if ($('#banner').get(0)) {
		var banner = $('#banner');
		$('.close', banner).click(function () {
			banner.animate({
				left: '-5000px'
			},
			{
				duration: 200,
				complete: function () {
					$(this).remove();
					$.get('delete-banner.html')
				}
			})
		})
	}
	// Форма заявки
	var reqFormNewWidth, reqFormLen, reqFormVal;
	var numW = {
		1: 7,
		5: 9,
		7: 6,
		'е': 8,
		'e': 8,
		'-': 5
	}
	$('.req-text').live('keyup', function () {
		reqFormVal = $(this).val();
		reqFormLen = $(this).val().length;
		reqFormCurLetter = reqFormVal[reqFormLen - 1];
		k = numW[reqFormCurLetter];
		if (!k) {
			k = 10
		}
		if (reqFormLen > 6) {
			reqFormNewWidth = 73 + (reqFormLen - 6) * k + 'px'
		} else {
			reqFormNewWidth = '73px'
		}
		$(this).css({
			width: reqFormNewWidth
		})
	})
	/*
	 * Calendar
	 */
	var calendar = $('#calendar');
	if (calendar.get(0)) {
		function onDateSelect(date) {
			if (date.split(' ')[2] == new Date().getFullYear()) {
				date = date.slice(0, date.length - 4)
			} else {
				date += ' года';
			}
			cur.text(date);
			newL.hide();
		}
		$.datepicker.regional['ru'] = {
			closeText: 'Закрыть',
			prevText: '&#x3c;Пред',
			nextText: 'След&#x3e;',
			currentText: 'Сегодня',
			monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
			monthNamesShort: ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октятбря', 'ноября', 'декабря'],
			dayNames: ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'],
			dayNamesShort: ['вск', 'пнд', 'втр', 'срд', 'чтв', 'птн', 'сбт'],
			dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
			dateFormat: 'd M yy',
			firstDay: 1,
			isRTL: false
		};
		$.datepicker.setDefaults($.datepicker.regional['ru']);
		calendar.datepicker({
			inline: true,
			minDate: 0,
			onSelect: onDateSelect
		});
	}
	/* Spoiler */
	spoiler = $('div.spoiler');
	if (spoiler.get(0)) {
		spoiler.each(function () {
			$(this).attr('height', $(this).height());
			if ($(this).hasClass('hidden')) {
				$(this).css('height', '0')
			}
		});

		function spoiling($this, $clicked) {
			if ($this.hasClass('hidden')) { // $clicked.remove();
				spoilerShow($this, $clicked);
				$clicked.text('Свернуть ↑');
			} else {
				spoilerHide($this);
				$clicked.text('Читать далее...');
			}
		}

		function spoilerHide($this) {
			$this.stop().animate({
				height: '0px'
			},
			'fast').addClass('hidden');
		}

		function spoilerShow($this) {
			$this.stop().animate({
				height: $this.attr('height') + 'px'
			},
			'fast').removeClass('hidden');
		}
		$('span.spoiler').click(function (e) {
			spoiling($(e.target).prev('div'), $(e.target))
		})
	}
	/*
	 * Form request
	 */
	rFO = {
		inp: {}
	};
	rFO.sendRequest = function () {
		rFO.form = $(this).parents('form');
		rFO.inp.name = $('input[name="name"]', rFO.form).removeClass('error');
		rFO.inp.phone = $('input[name="phone"]', rFO.form).removeClass('error');
		rFO.inp.cardNumber = $('input[name="cardNumber"]', rFO.form);
		rFO.inp.sbmt = $('input[type="submit"]', rFO.form);
		if (rFO.inp.name.val() != '' && rFO.inp.phone.val() != "") {
			oldPage = '';
			rFO.params = 'subscribe=' + $('input[name="subscribe"]', rFO.form).attr('checked');
			for (var key in rFO.inp) {
				rFO.params += '&' + key + '=' + rFO.inp[key].val();
			}
			$('a[rel*=]', rFO.form).each(function () {
				rFO.params += '&' + $(this).attr('rel') + '=' + $(this).text()
			});
			$.post(rFO.form.attr('action'), rFO.params, function () {
				rFO.form.html('<p>Ваша заявка принята.</p>');
				setTimeout(function () {
					popupClose();
				},
				3000);
			})
		} else {
			if (rFO.inp.name.val() == '') {
				rFO.inp.name.addClass('error')
			}
			if (rFO.inp.phone.val() == '') {
				rFO.inp.phone.addClass('error')
			}
		}
		return false;
	}

	function strip(reg, string) {
		//console.log(string.slice(-1));
		if (reg.test(string.slice(-1))) {
			return string;
		} else {
			if (string.legth > 1) {
				return strip(reg, string.slice(0, -1));
			} else {
				return '';
			}
		}
	}
	$('#req-phone, #phone').live('keyup', function (e) {
		$(this).val(strip(/\d|\-|\+|\s/, $(this).val()));
	});
	$('#cardNumber').live('keyup', function (e) {
		$(this).val(strip(/\d|\-|\s/, $(this).val()))
	});
	$('#age').live('keyup', function (e) {
		$(this).val(strip(/\d/, $(this).val().slice(0, 2)))
	});


	$('#request form input[type=submit]').live('click', rFO.sendRequest);

	var qFO = {
		inp: {},
		postJSON: function () {
			$.post(qFO.form.attr('action'), qFO.post, function (response) {
				if (typeof(response.errors) == 'string') {
					qFO.form.html(response.errors);
					setTimeout(function () {
						popupClose()
					},
					3000);
				} else {
					for (var key in response.errors) {
						qFO.inp[key].addClass('error').after('<span class="error">' + response.errors[key] + '</span>');
					}
				}
			},
			'json');
		}
	}
	qFO.sendQuestion = function () {
		oldPage = '';
		qFO.post = '';
		qFO.form = $(this).parents('form');
		$('span.error', qFO.form).remove();
		$('input[type="text"], textarea, select, input[type="file"]', qFO.form).each(function () {
			qFO.inp[$(this).attr('id')] = $(this).removeClass('error');
		});
		for (var key in qFO.inp) {
			qFO.post += '&' + key + '=' + qFO.inp[key].val();
		}
		qFO.postJSON();
		return false;
	}
	var vFO = {
		filename: '',
		inp: {},
		postJSON: function () {
			$.post(vFO.form.attr('action'), vFO.post, function (response) {
				if (typeof(response.errors) == 'string') {
					vFO.form.html(response.errors);
					setTimeout(function () {
						popupClose();
					},
					3000);
				} else {
					for (var key in response.errors) {
						vFO.inp[key].addClass('error').after('<span class="error">' + response.errors[key] + '</span>');
					}
				}
			},
			'json');
		}
	}
	vFO.sendQuestion = function () {
		oldPage = '';
		vFO.post = '';
		vFO.form = $(this).parents('form');
		$('span.error', vFO.form).remove();
		$('input[type="text"], textarea, select, input[type="file"]', vFO.form).each(function () {
			vFO.inp[$(this).attr('id')] = $(this).removeClass('error');
		});
		for (var key in vFO.inp) {
			vFO.post += '&' + key + '=' + vFO.inp[key].val();
		}
		$('#upload_target').bind('load', function () {
			$('#upload_target').unbind('load');
			vFO.postJSON();
		})
	}

	
	$('#faq-guestion input[type=submit]').live('click', qFO.sendQuestion);
	$('#vacancy input[type=submit]').live('click', vFO.sendQuestion); // $('#vacancy').get(0).target = 'upload_target';


	//Uventa-style

	$('dl.AccList').bind('click', function(e) {
		var dt = $(e.target).closest('dt');
		if(!!dt.get(0))
			$('div.description', dt.next()).slideToggle('slow');
	}).find('dd[class=] div').hide();

	$('div.master').bind('mouseenter mouseleave',
		function(e) {
			IE
			? $('div', $(this)).toggleClass('current-master')
			: $('div', $(this)).stop().animate({opacity:(e.type == 'mouseenter' ? 0.9 : 0)}, 'fast');
		}
	);

	//$('body.black dl.taber > dd[class=tab]').hide();

	var mapInitialize = function(map) {
			//var map = $("#map_canvas").get(0),
				var getLatLng = map.className.split('L-')[1].split(','),
				baloonContent = map.title;
				map.title = '';

			//Карта
			latlng = new google.maps.LatLng(getLatLng[0], getLatLng[1]),
			myOptions = {
				zoom: 16,
				center: latlng,
				//disableDefaultUI:true,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};

			//Маркер
			var map = new google.maps.Map(map, myOptions),
			image = '/i/uventa_icon.png',
			marker = new google.maps.Marker({
				position: latlng,
				map: map,
				icon: image,
				title:''
			});


			// Всплывающий пузырь
			var infowindow = new google.maps.InfoWindow({
	    		content: baloonContent
			});

			google.maps.event.addListener(marker, 'click', function() {
	  			infowindow.open(map,marker);
			});
		};

	if (map = $("#map_canvas")[0]) mapInitialize(map);



})
