jQuery(function(){
	initPlugins();
	initTabs();
	initNavDelay();
	initSearch();
});

//init delay before close
function initNavDelay(){
	jQuery('#nav a').each(function(){
		var link = jQuery(this),
			parents = link.parents('li'),
			drop = parents.find('>ul'),
			timer,
			activeClass = 'hover';
		link.bind('mouseover', function(){
			parents.addClass('hover');
		});
		link.bind('mouseout', function(){
			if(drop.length){
				clearTimeout(timer);
				timer = setTimeout(function(){
					link.parents('li').removeClass('hover');
				}, 1000);
			}else{
				link.parents('li').removeClass('hover');
			}
		});
	});
}

//init advanced search open block
function initSearch(){
	jQuery('.block-search').each(function(){
		var holder = jQuery(this).addClass('active'),
			link = jQuery('.btn-search', holder),
			block = jQuery('.add-holder', holder),
			height = block.height(),
			speed = 400;
		block.css({height: 0, display: 'block'});
		holder.removeClass('active');
		link.click(function(){
			if(!holder.hasClass('active')){
				holder.addClass('active');
				block.css({height: 0}).stop().animate({height: height}, speed);
			}else{
				holder.removeClass('active');
				block.css({height: height}).stop().animate({height: 0}, speed);
			}
			return false;
		});
	});
}

//init plugins
function initPlugins(){
	//init clear form fields
	clearFormFields({
		clearInputs: false,
		clearTextareas: false,
		passwordFieldText: false,
		addClassFocus: "focus",
		filterClass: "default"
	});
	//init main gallery
	jQuery('div.carousel').galleryCircle({
		btnPrev: 'a.prev',
		btnNext: 'a.next',
		slidesHolder :'.frame',
		slider:'.slide-list',
		autoSlide: true,
		switcher:'.switcher',
		generateSwitcher:true,
		switchTime: 6000,
		easing:'linear',
		duration : 700
	});
}

// init circle carousel plugin
jQuery.fn.galleryCircle = function(_options){
	// defaults options
	var _options = jQuery.extend({
		btnPrev: 'a.link-prev',
		btnNext: 'a.link-next',
		slidesHolder :'.frame',
		slider:'ul',
		fadeSlides:'ul.fade > li',
		autoSlide: false,
		switcher:'div.swicher .holder .pg-holder',
		generateSwitcher:false,
		vertical:false,
		autoHeight:false,
		switchTime: 6000,
		easing:'linear',
		duration : 700,
		pauseOnHover:false,
		asynchronous:false
	},_options);

	return this.each(function(_galIndex){
		var _holder = $(this);
		var _btnPrev = jQuery(_options.btnPrev, _holder);
		var _btnNext = jQuery(_options.btnNext, _holder);
		var _slidesHolder = jQuery(_options.slidesHolder, _holder);
		var _slider = jQuery(_options.slider, _slidesHolder);
		var _slides = _slider.children();
		var _slidesCount = _slides.length;
		var _slideWidth = _slides.eq(0).outerWidth(true);
		var _slideHeight = _slides.eq(0).outerHeight(true);
		var _currentIndex = 0;
		var _oldIndex = _currentIndex;
		var _animating = false;
		var _timer;
		var _sumWidth = _slidesCount*_slideWidth;
		var _sumHeight = _slidesCount*_slideHeight;
		var switcher = jQuery(_options.switcher, _holder);
		var _vertical = _options.vertical;
		var _waitAnimation = true;
		var _autoSlide = _options.autoSlide;
		var _easing = _options.easing;
		var _switchTime = _options.switchTime;
		var _speed = _options.duration;
		var _autoStopByThumbs = false;
		var _swGenerate = _options.generateSwitcher;
		var _autoHeight = _options.autoHeight;
		var _asynchronous = _options.asynchronous;
		var _fadeSlides = jQuery(_options.fadeSlides);
		var _pauseOnHover = _options.pauseOnHover;

		_fadeSlides.hide().eq(_currentIndex).show();
		switcher.each(function(_ind){
			jQuery(this).attr('rel', _ind);
		});
		elNum();
		_slider.append(_slides.clone()).append(_slides.clone());
		_slides = _slider.children();
		if(_fadeSlides.length && !_swGenerate){
			switcher.each(function(){
				jQuery(this).click(function(){
					var _ind = jQuery(this).attr('rel');
					if(_ind != _currentIndex){
						_fadeSlides.fadeOut(_speed).eq(_ind).fadeIn(_speed);
					}
				});
			});
		}
		_holder.css({position:'relative'});
		if(!_vertical){
			_slider.css({
				position: 'relative',
				left:-_sumWidth,
				height:_sumWidth*3
			});
		}else{
			_slider.css({
				position: 'relative',
				top:-_sumHeight,
				height:_sumHeight*3
			});
		}
		_slides.each(function(i, el){
			if(!_vertical){
				_slides.eq(i).css({
					position:'absolute',
					top:0,
					left:_slideWidth*i
				});
			}else{
				_slides.eq(i).css({
					position:'absolute',
					top:_slideHeight*i,
					left:0
				});
			}
			if(_slides.eq(i).find('img').attr('src') && _slides.eq(i).find('img').attr('src').indexOf('.png') != -1){
				_slides.eq(i).find('img').addClass('png');
			}
		})

		// Switcher
		function elNum(){
			if (switcher && !_fadeSlides.length || switcher && _swGenerate) {
				var switcherEl='';
				var num=1;
				var difference=1;
				if(_swGenerate){
					while (difference <= _slides.length){
						switcherEl+='<li><a href="">'+ num + '</a></li>';
						num++;
						difference++;
					}
					switcher.html('<ul class="switcher">'+ switcherEl+'</ul>');
					if(_currentIndex!=-1){
						switcher.find('li').eq(_currentIndex).addClass('active');
					}
				}
				var link = switcher.find('a');
				link.click(function(_ind){
					if(_currentIndex != link.index(jQuery(this))) {
						_currentIndex=link.index(jQuery(this));
						switchSlide();
					}
					if(_autoStopByThumbs && _timer!=-1) clearTimeout(_timer)
					switcher.removeClass('active');
					jQuery(this).parent().addClass('active');
					return false;
				});
				switcher.hover(
					function(){
						if(_autoStopByThumbs && _timer!=-1 ) clearTimeout(_timer)
					},
					function(){
						if(_autoStopByThumbs){
							clearTimeout(_timer);
							autoslide();
						}
					}
				)
			}
		}
		//gallery control
		_btnPrev.click(function(){
			prevSlide();
			return false;
		});
		_btnNext.click(function(){
			nextSlide();
			return false;
		});
		// gallery animation
		function prevSlide() {
			if(_animating) return;
			_currentIndex--;
			switchSlide();
		}
		function nextSlide() {
			if(_animating) return;
			_currentIndex++;
			switchSlide();
		}

		// gallery animation
		function switchSlide(){
			_animating = true;
			if(_autoHeight){_holder.animate({height: _slides.eq(_currentIndex).outerHeight(true)}, {duration:_speed, queue:false});}
			if(!_vertical){
				_slider.animate({left:-_sumWidth-_currentIndex*_slideWidth},{duration:_speed, queue:false,complete:function(){
					if(_currentIndex == _slidesCount || _currentIndex == -_slidesCount ) {
						_currentIndex = 0;
						_slider.css({left:-_sumWidth});
					}
					if(_currentIndex == -1  ) {
						_currentIndex=_slidesCount+_currentIndex;
						_slider.css({left:-_sumWidth-_currentIndex*_slideWidth});
					}
					_animating = false;
				}});
			}else{
				_slider.animate({top:-_sumHeight-_currentIndex*_slideHeight},{duration:_speed, queue:false,complete:function(){
					if(_currentIndex == _slidesCount || _currentIndex == -_slidesCount ) {
						_currentIndex = 0;
						_slider.css({top:-_sumHeight});
					}
					if(_currentIndex == -1  ) {
						_currentIndex=_slidesCount+_currentIndex;
						_slider.css({top:-_sumHeight-_currentIndex*_slideHeight});
					}
					_animating = false;
				}});
			}
			switcher.find('li').removeClass('active').eq(Math.abs(_currentIndex) == _slidesCount ? 0 : _currentIndex).addClass('active');
			autoSlide();
			if(jQuery.browser.msie && parseInt(jQuery.browser.version) < 9){
				_fadeSlides.hide().eq(Math.abs(_currentIndex) == _slidesCount ? 0 : _currentIndex).show();
			}else{
				_fadeSlides.fadeOut(_speed).eq(Math.abs(_currentIndex) == _slidesCount ? 0 : _currentIndex).fadeIn(_speed);
			}
		}
		function autoSlide() {
			if(!_autoSlide) return;
			if(_timer) clearInterval(_timer);
			_timer = setInterval(nextSlide,_switchTime);
		}
		if(_pauseOnHover){
			_holder.hover(function(){
				if(_timer) clearInterval(_timer);
			}, function(){
				_timer = setInterval(nextSlide,_switchTime);
			})
		}
		if(!_asynchronous || (_asynchronous && _galIndex == 0)){
			autoSlide();
		}else{
			if(_galIndex > 0){
				setTimeout(function(){
					autoSlide();
				}, _asynchronous * _galIndex);
			}
		}
	});
}

function initTabs() {
    if (jQuery('link#current-tab').length > 0) {
        jQuery('a.tab').parent().removeClass('active');
        currentRel  = jQuery('link#current-tab').attr('rel');
        currentLink = jQuery('a[href="'+ currentRel + '"]');
        currentLink.parent().addClass('active');
    }

	jQuery('ul.tabset').each(function(){
		if(!jQuery(this).hasClass('custom')){
			var _list = jQuery(this);
			var _links = _list.find('a.tab');

			_links.each(function() {
				var _link = jQuery(this);
				var _href = _link.attr('href');
				var _tab = jQuery(_href);

				if(_link.parent().hasClass('active')) _tab.show();
				else _tab.hide();

				_link.click(function(){
					_links.parent().filter('.active').each(function(){
						jQuery(jQuery(this).removeClass('active').find('> a.tab').attr('href')).hide();
					});
                    var url = '/index/store-tab/tab-name/' + (_link.attr('href').substring(1, 100));
                    jQuery.ajax({
                        type    : 'GET',
                        url     : url
                    });


					_link.parent().addClass('active');
					_tab.show();
					return false;
				});
			});
		}
	});
}

// clearFormFields
function clearFormFields(o){
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filter) o.filter = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass)) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass)) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}
