$(document).ready(function(){
	$('#container > div.header').gallery({
		duration: 700,
		listOfSlides: 'ul.head-image > li',
		switcher: 'div.list > ul > li',
		effect: true
	});
	$('div.mainContent > div.index-articles').gallery({
		duration: 700,
		listOfSlides: 'ul.big > li',
		switcher: 'ul.small > li',
		autoRotation:5000,
		effect: true
	});
	initHeaderSlide();
	initLogIn();
	initFormValidation();
	$('a.video-popup').simplebox({
		video:true,
		wrapper: '#container'
	});
	$('a.link-popup').simplebox({
		wrapper: '#container'
	});
});

function initFormValidation() {
	var _errorClass = 'error';
	var _regEmail = /^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$/;
	
	$('form.validate-form').each(function(){
		var _form = $(this);
		function checkFields() {
			
			var _flag = false;
			_form.find('.'+_errorClass).removeClass(_errorClass);

			// fields validation
			_form.find('input.required-email').each(function(){
				if(!_regEmail.test($(this).val())) addError($(this));
			});
			_form.find('input.required, textarea.required').each(function(){
				if(!$(this).val().length || $(this).val() == $(this).attr('title')) addError($(this));
			});

			// error class adding
			function addError(_obj) {
				_obj.addClass(_errorClass);
				_flag=true;
			}
			return _flag;
		}

		// catch form submit event
		_form.submit(function(){
			if(checkFields()) {
				return false;
			}
		});
	});
}

function initLogIn(){
	$('div.header > ul.auth').each(function(){
		var hold = $(this);
		var link = hold.find('> li > a.link');
		var box = hold.find('> li > div.form');
		var active;
		
		box.css({top: 36}).each(function(){
			if (!$(this).parent().hasClass('active')) $(this).css({display: 'none'});
		});
		
		link.click(function(){
			active = link.index($(this));
			if(!$(this).parent().hasClass('active')){
				box.slideUp(500, function(){
					_time = setTimeout(function(){
						link.parent().removeClass('active');
					link.eq(active).parent().addClass('active');
					box.eq(active).slideDown(500);
					}, 500);
					
				});
			}
			else{
				$(this).parent().removeClass('active');
				box.slideUp(500);
			}
			return false;
		});
	});
}

function initHeaderSlide(){
	$('div.header > div.bgs').each(function(){
		var hold = $(this);
		var link = hold.find('.link');
		hold.css({display: 'block', overflow: 'hidden'}).wrapInner($('<div style="overflow: hidden; margin-right: -174px" />'));
		
		link.click(function(){
			if(!link.hasClass('open')){
				link.addClass('open');
				hold.find('> div').animate({marginRight:0}, {queue:false, duration: 300});
			}
			else{
				link.removeClass('open');
				hold.find('> div').animate({marginRight: -174}, {queue:false, duration: 300});
			}
			return false;
		});
	});
}

$.fn.simplebox = function(options) { return new Simplebox(this, options); };

function Simplebox(context, options) { this.init(context, options); };

Simplebox.prototype = {
	options:{},
	init: function (context, options){
		this.options = $.extend({
			duration: 300,
			linkClose: 'span.close, a.btn-close',
			divFader: 'fader',
			faderColor: 'black',
			opacity: 0.7,
			wrapper: '#wrapper',
			linkPopap: '.link-submit',
			video: false
		}, options || {});
		this.btn = $(context);
		this.select = $(this.options.wrapper).find('select');
		this.initFader();
		this.btnEvent(this, this.btn);
	},
	btnEvent: function($this, el){
		el.click(function(){
			if ($(this).attr('href')) $this.toPrepare($(this).attr('href'), {title: $(this).find('img').attr('alt'), text: $(this).attr('title'), link: $(this).attr('rel')});
			else $this.toPrepare($(this).attr('title'));
			return false;
		});
	},
	calcWinWidth: function(){
		this.winWidth = $('body').width();
		if ($(this.options.wrapper).width() > this.winWidth) this.winWidth = $(this.options.wrapper).width();
	},
	toPrepare: function(obj, t){
		if (this.options.video){
			var temp = '<div class="modal" id="modal-video"><div class="video-block"><iframe src="'+obj+
						'" width="588" height="369" frameborder="0"></iframe></div><h2><a href="'+t.link+
						'">'+t.title+'</a></h2> '+t.text+' <span class="close">Закрыть</span> </div>';
			$('body').append(temp);
			obj = '#modal-video';
		}
		this.popup = $(obj);
		this.btnClose = this.popup.find(this.options.linkClose);
		this.submitBtn = this.popup.find(this.options.linkPopap);
		
		if ($.browser.msie) this.select.css({visibility: 'hidden'});
		this.calcWinWidth();
		this.winHeight = $(window).height();
		this.winScroll = $(window).scrollTop();
		
		this.popupTop = this.winScroll + (this.winHeight/2) - this.popup.outerHeight(true)/2;
		if (this.popupTop < 0) this.popupTop = 0;
		this.faderHeight = $(this.options.wrapper).outerHeight();
		if ($(window).height() > this.faderHeight) this.faderHeight = $(window).height();
		
		this.popup.css({
			top: this.popupTop,
			left: this.winWidth/2 - this.popup.outerWidth(true)/2
		}).hide();
		this.fader.css({
			width: this.winWidth,
			height: this.faderHeight
		});
		this.initAnimate(this);
		this.initCloseEvent(this, this.btnClose, true);
		this.initCloseEvent(this, this.submitBtn, false);
		this.initCloseEvent(this, this.fader, true);
	},
	initCloseEvent: function($this, el, flag){
		el.click(function(){
			$this.popup.fadeOut($this.options.duration, function(){
				if ($this.options.video) $this.popup.remove();
				else $this.popup.css({left: '-9999px'}).show();
				if ($.browser.msie) $this.select.css({visibility: 'visible'});
				$this.submitBtn.unbind('click');
				$this.fader.unbind('click');
				$this.btnClose.unbind('click');
				$(window).unbind('resize');
				if (flag) $this.fader.fadeOut($this.options.duration);
				else {
					if ($this.submitBtn.attr('href')) $this.toPrepare($this.submitBtn.attr('href'));
					else $this.toPrepare($this.submitBtn.attr('title'));
				}
			});
			return false;
		});
	},
	initAnimate:function ($this){
		$this.fader.fadeIn($this.options.duration, function(){
			$this.popup.fadeIn($this.options.duration);
		});
		$(window).resize(function(){
			$this.calcWinWidth();
			$this.popup.animate({
				left: $this.winWidth/2 - $this.popup.outerWidth(true)/2
			}, {queue:false, duration: $this.options.duration});
			$this.fader.css({width: $this.winWidth});
		});
	},
	initFader: function(){
		if ($('div.'+this.options.divFader).length > 0) this.fader = $('div.'+this.options.divFader);
		else{
			this.fader = $('<div class="'+this.options.divFader+'"></div>');
			$('body').append(this.fader);
			this.fader.css({
				position: 'absolute',
				zIndex: 999,
				left:0,
				top:0,
				background: this.options.faderColor,
				opacity: this.options.opacity
			}).hide();
		}
	}
}

$.fn.gallery = function(options) { return new Gallery(this.get(0), options); };

function Gallery(context, options) { this.init(context, options); };

Gallery.prototype = {
	options:{},
	init: function (context, options){
		this.options = $.extend({
			infinite: false,								
			duration: 700,									
			slideElement: 1,								
			autoRotation: false,							
			effect: false,									
			listOfSlides: 'ul > li',						
			switcher: false,								
			disableBtn: false,								
			nextBtn: 'a.link-next, a.btn-next, a.next',		
			prevBtn: 'a.link-prev, a.btn-prev, a.prev',		
			circle: true,									
			direction: false,								
			event: 'click',									
			IE: false,										
			autoHeight: false								
		}, options || {});
		var _el = $(context).find(this.options.listOfSlides);
		if (this.options.effect) this.list = _el;
		else this.list = _el.parent();
		this.switcher = $(context).find(this.options.switcher);
		this.nextBtn = $(context).find(this.options.nextBtn);
		this.prevBtn = $(context).find(this.options.prevBtn);
		this.count = _el.index(_el.filter(':last'));
		
		if (this.options.switcher) this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
		else this.active = _el.index(_el.filter('.active:eq(0)'));
		if (this.active < 0) this.active = 0;
		this.last = this.active;
		
		this.woh = _el.outerWidth(true);
		if (!this.options.direction) this.installDirections(this.list.parent().width());
		else {
			this.woh = _el.outerHeight(true);
			this.installDirections(this.list.parent().height());
		}
		
		if (!this.options.effect) {
			this.rew = this.count - this.wrapHolderW + 1;
			if (!this.options.direction) this.anim = '{marginLeft: -(this.woh * this.active)}';
			else this.anim = '{marginTop: -(this.woh * this.active)}';
			eval('this.list.css('+this.anim+')');
		}
		else {
			this.rew = this.count;
			this.list.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
			this.switcher.removeClass('active').eq(this.active).addClass('active');
			if(this.options.autoHeight) this.list.parent().css({height: this.list.eq(this.active).outerHeight()});
		}
		this.flag = true;
		if (this.options.infinite){
			this.count++;
			this.active += this.count;
			this.list.append(_el.clone());
			this.list.append(_el.clone());
			eval('this.list.css('+this.anim+')');
		}
		
		this.initEvent(this, this.nextBtn, true);
		this.initEvent(this, this.prevBtn, false);
		if (this.options.disableBtn) this.initDisableBtn();
		if (this.options.autoRotation) this.runTimer(this);
		if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
	},
	initDisableBtn: function(){
		this.prevBtn.removeClass('prev-'+this.options.disableBtn);
		this.nextBtn.removeClass('next-'+this.options.disableBtn);
		if (this.active == 0 || this.count+1 == this.wrapHolderW) this.prevBtn.addClass('prev-'+this.options.disableBtn);
		if (this.active == 0 && this.count == 1 || this.count+1 <= this.wrapHolderW) this.nextBtn.addClass('next-'+this.options.disableBtn);
		if (this.active == this.rew) this.nextBtn.addClass('next-'+this.options.disableBtn);
	},
	installDirections: function(temp){
		this.wrapHolderW = Math.ceil(temp / this.woh);
		if (((this.wrapHolderW - 1) * this.woh + this.woh / 2) > temp) this.wrapHolderW--;
	},
	fadeElement: function(){
		if ($.browser.msie && this.options.IE){
			this.list.eq(this.last).css({opacity:0});
			this.list.removeClass('active').eq(this.active).addClass('active').css({opacity:'auto'});
		}
		else{
			this.list.eq(this.last).animate({opacity:0}, {queue:false, duration: this.options.duration});
			this.list.removeClass('active').eq(this.active).addClass('active').animate({
				opacity:1
			}, {queue:false, duration: this.options.duration, complete: function(){
				$(this).css('opacity','auto');
			}});
		}
		if(this.options.autoHeight) this.list.parent().animate({height: this.list.eq(this.active).outerHeight()}, {queue:false, duration: this.options.duration});
		if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
		this.last = this.active;
	},
	scrollElement: function($this){
		if (!$this.options.infinite) eval('$this.list.animate('+$this.anim+', {queue:false, duration: $this.options.duration});');
		else eval('$this.list.animate('+$this.anim+', $this.options.duration, function(){ $this.flag = true });');
		if ($this.options.switcher) $this.switcher.removeClass('active').eq($this.active / $this.options.slideElement).addClass('active');
	},
	runTimer: function($this){
		if($this._t) clearTimeout($this._t);
		$this._t = setInterval(function(){
			if ($this.options.infinite) $this.flag = false;
			$this.toPrepare($this, true);
		}, this.options.autoRotation);
	},
	initEventSwitcher: function($this, el){
		el.bind($this.options.event, function(){
			$this.active = $this.switcher.index($(this)) * $this.options.slideElement;
			if($this._t) clearTimeout($this._t);
			if ($this.options.disableBtn) $this.initDisableBtn();
			if (!$this.options.effect) $this.scrollElement($this);
			else $this.fadeElement();
			if ($this.options.autoRotation) $this.runTimer($this);
			return false;
		});
	},
	initEvent: function($this, addEventEl, dir){
		addEventEl.bind($this.options.event, function(){
			if ($this.flag){
				if ($this.options.infinite) $this.flag = false;
				if($this._t) clearTimeout($this._t);
				$this.toPrepare($this, dir);
				if ($this.options.autoRotation) $this.runTimer($this);
			}
			return false;
		});
	},
	toPrepare: function($this, side){
		if (!$this.options.infinite){
			if (($this.active == $this.rew) && $this.options.circle && side) $this.active = -$this.options.slideElement;
			if (($this.active == 0) && $this.options.circle && !side) $this.active = $this.rew + $this.options.slideElement;
			for (var i = 0; i < $this.options.slideElement; i++){
				if (side) { if ($this.active + 1 <= $this.rew) $this.active++; }
				else { if ($this.active - 1 >= 0) $this.active--; }
			};
		}
		else{
			if ($this.active >= $this.count + $this.count && side) $this.active -= $this.count;
			if ($this.active <= $this.count-1 && !side) $this.active += $this.count;
			eval('$this.list.css('+$this.anim+')');
			if (side) $this.active += $this.options.slideElement;
			else $this.active -= $this.options.slideElement;
		}
		if (this.options.disableBtn) this.initDisableBtn();
		if (!$this.options.effect) $this.scrollElement($this);
		else $this.fadeElement();
	},
	stop: function(){
		if (this._t) clearTimeout(this._t);
	},
	play: function(){
		if (this._t) clearTimeout(this._t);
		if (this.options.autoRotation) this.runTimer(this);
	}
}

