var button;

jQuery(function(){
	formValidate();
	jQuery('div.box-image').gallery({
		duration: 700,
		slideElement: 1,
		effect: 'fade',
		autoRotation: 12000,
		listOfSlides: 'ul.gal > li'
	});
});

// ajax preloader js
function selectAjaxSwicther(){
	var switcherName = 'div#content';
	var holderName = 'div.information';
	var selectObj = $(switcherName).find('select.btn-submit');

	var option = button;
	ajaxSwitch();

	function ajaxSwitch(){
		var switcherObj = option.parents(switcherName);
		var holderObj = switcherObj.find(holderName);
		holderObj.css({position: 'relative', height: holderObj.innerHeight()});
		jQuery("<img class='loader'>").appendTo(holderObj);
		holderObj.find('img.loader').attr('src', 'images/ajax-loader.gif').css({
			position: 'absolute',
			top: '50%',
			left: '50%',
			marginTop: -holderObj.find('img.loader').innerHeight() / 2,
			marginLeft: -holderObj.find('img.loader').innerWidth() / 2
		});
		jQuery.ajax({
			url:option.attr('rel'),
			type:"GET",
			success:function(msg){
				holderObj.empty();
				jQuery("<div>").html(msg).appendTo(holderObj);
				holderObj.css({position: 'static', height: 'auto'});
			},
			error:function(){
				alert("AJAX Error!");
			}
		});
	};
}

// form validate js
function formValidate(){
	$("form.form-info").each(function(){
		var _form = $(this);

		var _textFields = _form.find('input.required');
		var _emailFields = _form.find('input#emailtext');
		var _phoneFields = _form.find('input#phone, input#code');
		var _parentsElements = 'div.row';
		var _submit = _form.find('input.btn-submit');
		var _errorClass = 'error';
		
		var _errors = 0;
		_submit.click(function(){
			button = jQuery(this);
			if(_textFields.length){
				_textFields.each(function(){
					var _input = $(this);
					if(_input.val() == ""){
						_errors++;
						_input.parents(_parentsElements).addClass(_errorClass);
					}else{
						_input.parents(_parentsElements).removeClass(_errorClass);
					}
				});
			}
			if(_emailFields.length){
				_emailFields.each(function(){
					var _email = $(this);
					var _result;
					_result = (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(_email.val());
					if(!_result == true){
						if(_email.parents(_parentsElements).filter('[class!='+_errorClass+']')){
							_errors++;
							_email.parents(_parentsElements).addClass(_errorClass);
						}
					}else{
						if(_email.val() != ''){
							_email.parents(_parentsElements).removeClass(_errorClass);
						}
					}
				});
			}
			if(_phoneFields.length){
				_phoneFields.each(function(){
					var _phone = $(this);
					var _result;
					_result = (/^(\+?\d+)?\s*(\(\d+\))?[\s-]*([\d-]*)$/).test(_phone.val());
					if(!_result == true){
						if(_phone.parents(_parentsElements).filter('[class!='+_errorClass+']')){
							_errors++;
							_phone.parents(_parentsElements).addClass(_errorClass);
						}
					}else{
						if(_phone.val() != ''){
							_phone.parents(_parentsElements).removeClass(_errorClass);
						}
					}
				});
			}
		});
		_form.submit(function(){
			//if no errors send email
			if(_errors == 0){
				$.ajax({
					url: _form.attr('action'), //get url of php handler
					data: _form.serialize(), //get all data from fields
					type: 'POST',
					success: function(){
						// if sended you can switch to "thanks" DIV
						selectAjaxSwicther();
					},
					error: function(){
						alert('Ajax Error. Incorect path to file!');
					}
				})
			}
			if(_errors != 0){_errors = 0;}
			return false;
		});
	});
}

// slideshow init
(function($) {
	$.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({
				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
			}, 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');
			}
			
			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.wrapHolderWwrapHolderW--;
		},
		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.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			this.last = this.active;
		},
		scrollElement: function(){
			eval('this.list.animate('+this.anim+', {queue:false, duration: this.options.duration});');
			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(){
				$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();
				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._t) clearTimeout($this._t);
				$this.toPrepare($this, dir);
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		toPrepare: function($this, side){
			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--; }
			};
			if (this.options.disableBtn) this.initDisableBtn();
			if (!$this.options.effect) $this.scrollElement();
			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);
		}
	}
}(jQuery));
