jQuery(function(){
	initPlugins();
});

function initPlugins(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: true,
		addParentFocus: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
	jQuery('div.gallery-holder').scrollGallery({
		sliderHolder: '>div.holder',
		slider:'>ul',
		slides: '>li',
		autoRotation:true,
		switchTime:5000,
		generatePagination:'div.paging',
		switcherClassTo:'li',
		switcherClassName:'switcher',
		duration:1000
	});
}

function clearFormFields(o){
	if(o.clearInputs == null){o.clearInputs = true;} // true/false
	if(o.clearTextareas == null){o.clearTextareas = true;} // true/false
	if(o.passwordFieldText == null){o.passwordFieldText = false;} // true/false
	if(o.addClassFocus == null){o.addClassFocus = false;} // focus class
	if(o.addParentFocus == null){o.addParentFocus = false;} // true/false or parent selector
	if(!o.filter){o.filter = "default";}
	if(o.clearInputs || o.clearTextareas){
		var inputs = jQuery(eval("o.clearInputs ? 'input' : ''") + eval("o.clearTextareas ? ', textarea' : ''"));
		inputs.each(function () {
		    if (jQuery(this).closest('form').find('div:first').attr('class') != 'standardForm')
            {
			    var _this = jQuery(this);
			    var _type = _this.attr('type') || 'textarea';
			    var _class = _this.attr('class');
			    var _valHtml = _this.val();
//			    if(o.passwordFieldText && _type == 'password'){
//				    var fakeInput = jQuery('<input>');
//				    fakeInput.attr('type', 'text');
//				    fakeInput.attr('value', _valHtml);
//				    fakeInput.attr('class', _class);
//				    fakeInput.fake = true;
//				    fakeInput.focus(function(){
//					    _this.trigger('focus');
//				    });
//				    _this.parent().prepend(fakeInput);
//				    _this.fake = fakeInput;
//				    inputsSwap(_this, null);
//			    }
			    if((_type == 'textarea' || _type == 'text' || _type == 'password') || _class == o.filterClass){
				    _this.focus(function(){
					    if(_valHtml == _this.val()){_this.val('');}
					    if(_this.fake){
						    inputsSwap(_this.fake, _this);
					    }
					    if(o.addClassFocus){
						    _this.addClass(o.addClassFocus);
						    if(_this.fake){_this.fake.addClass(o.addClassFocus);}
						    if(o.addParentFocus == true){
							    _this.parent().addClass('parent-'+o.addClassFocus);
						    }else if(!o.addParentFocus == false){
							    _this.parents(o.addParentFocus).addClass('parent-'+o.addClassFocus);
						    }
					    }
				    });
				    _this.blur(function(){
					    if(_this.val() == ''){
						    _this.val(_valHtml);
						    if(_this.fake){inputsSwap(_this, _this.fake);}
					    }
					    if(o.addClassFocus){
						    _this.removeClass(o.addClassFocus);
						    if(_this.fake){_this.fake.removeClass(o.addClassFocus);}
						    if(o.addParentFocus == true){
							    _this.parent().removeClass('parent-'+o.addClassFocus);
						    }else if(!o.addParentFocus == false){
							    _this.parents(o.addParentFocus).removeClass('parent-'+o.addClassFocus);
						    }
					    }
				    });
                } 
            }
	    });
            
	}
	function inputsSwap(el, el2){
		if(el) el.hide();
		if(el2) el2.show();
	}
}

// scrolling gallery plugin
jQuery.fn.scrollGallery = function(_options){
	var _options = jQuery.extend({
		sliderHolder: '>div',
		slider:'>ul',
		slides: '>li',
		pagerLinks:'div.pager a',
		btnPrev:'a.link-prev',
		btnNext:'a.link-next',
		activeClass:'active',
		disabledClass:'disabled',
		generatePagination:'div.pg-holder',
		switcherClassName:'switcher',
		switcherClassTo:'a',
		curNum:'em.scur-num',
		allNum:'em.sall-num',
		circleSlide:true,
		pauseClass:'gallery-paused',
		pauseButton:'none',
		pauseOnHover:true,
		autoRotation:false,
		stopAfterClick:false,
		switchTime:5000,
		duration:650,
		easing:'swing',
		event:'click',
		splitCount:false,
		afterInit:false,
		vertical:false,
		step:false
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _sliderHolder = jQuery(_options.sliderHolder, _this);
		var _slider = jQuery(_options.slider, _sliderHolder);
		var _slides = jQuery(_options.slides, _slider);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _switcherClassName = _options.switcherClassName;
		var _switcherClassTo = _options.switcherClassTo;
		var _generatePagination = jQuery(_options.generatePagination, _this);
		var _curNum = jQuery(_options.curNum, _this);
		var _allNum = jQuery(_options.allNum, _this);
		var _pauseButton = jQuery(_options.pauseButton, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _pauseClass = _options.pauseClass;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledClass = _options.disabledClass;
		var _easing = _options.easing;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _step = _options.step;
		var _vertical = _options.vertical;
		var _circleSlide = _options.circleSlide;
		var _stopAfterClick = _options.stopAfterClick;
		var _afterInit = _options.afterInit;
		var _splitCount = _options.splitCount;

		// gallery init
		if(!_slides.length) return;

		if(_splitCount) {
			var curStep = 0;
			var newSlide = $('<slide>').addClass('split-slide');
			_slides.each(function(){
				newSlide.append(this);
				curStep++;
				if(curStep > _splitCount-1) {
					curStep = 0;
					_slider.append(newSlide);
					newSlide = $('<slide>').addClass('split-slide');
				}
			});
			if(curStep) _slider.append(newSlide);
			_slides = _slider.children();
		}

		var _currentStep = 0;
		var _sumWidth = 0;
		var _sumHeight = 0;
		var _hover = false;
		var _stepWidth;
		var _stepHeight;
		var _stepCount;
		var _offset;
		var _timer;

		_slides.each(function(){
			_sumWidth+=$(this).outerWidth(true);
			_sumHeight+=$(this).outerHeight(true);
		});

		// calculate gallery offset
		function recalcOffsets() {
			if(_vertical) {
				if(_step) {
					_stepHeight = _slides.eq(_currentStep).outerHeight(true);
					_stepCount = Math.ceil((_sumHeight-_sliderHolder.height())/_stepHeight)+1;
					_offset = -_stepHeight*_currentStep;
				} else {
					_stepHeight = _sliderHolder.height();
					_stepCount = Math.ceil(_sumHeight/_stepHeight);
					_offset = -_stepHeight*_currentStep;
					if(_offset < _stepHeight-_sumHeight) _offset = _stepHeight-_sumHeight;
				}
			} else {
				if(_step) {
					_stepWidth = _slides.eq(_currentStep).outerWidth(true)*_step;
					_stepCount = Math.ceil((_sumWidth-_sliderHolder.width())/_stepWidth)+1;
					_offset = -_stepWidth*_currentStep;
					if(_offset < _sliderHolder.width()-_sumWidth) _offset = _sliderHolder.width()-_sumWidth;
				} else {
					_stepWidth = _sliderHolder.width();
					_stepCount = Math.ceil(_sumWidth/_stepWidth);
					_offset = -_stepWidth*_currentStep;
					if(_offset < _stepWidth-_sumWidth) _offset = _stepWidth-_sumWidth;
				}
			}
		}

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				nextSlide();
				return false;
			});
		}
		if(_generatePagination.length) {
			_generatePagination.empty();
			recalcOffsets();
			var _list = $('<ul class="'+_switcherClassName+'" />');
			for(var i=0; i<_stepCount; i++) $('<li><a href="#">'+(i+1)+'</a></li>').appendTo(_list);
			_list.appendTo(_generatePagination);
			if(_switcherClassTo.toLowerCase() == 'li'){
				_pagerLinks = _list.children();
			}else{
				_pagerLinks = _list.children().find('a');
			}
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentStep != _ind) {
						if(_stopAfterClick) stopAutoSlide();
						_currentStep = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// gallery animation
		function prevSlide() {
			recalcOffsets();
			if(_currentStep > 0) _currentStep--;
			else if(_circleSlide) _currentStep = _stepCount-1;
			switchSlide();
		}
		function nextSlide() {
			recalcOffsets();
			if(_currentStep < _stepCount-1) _currentStep++;
			else if(_circleSlide) _currentStep = 0;
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
			if(!_circleSlide) {
				_btnPrev.removeClass(_disabledClass);
				_btnNext.removeClass(_disabledClass);
				if(_currentStep == 0) _btnPrev.addClass(_disabledClass);
				if(_currentStep == _stepCount-1) _btnNext.addClass(_disabledClass);
			}
			if(_curNum.length) _curNum.text(_currentStep+1);
			if(_allNum.length) _allNum.text(_stepCount);
		}
		function switchSlide() {
			recalcOffsets();
			if(_vertical) _slider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
			else _slider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function stopAutoSlide() {
			if(_timer) clearTimeout(_timer);
			_autoRotation = false;
		}
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		recalcOffsets();
		refreshStatus();
		autoSlide();

		// pause buttton
		if(_pauseButton.length) {
			_pauseButton.click(function(){
				if(_this.hasClass(_pauseClass)) {
					_this.removeClass(_pauseClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_this.addClass(_pauseClass);
					stopAutoSlide();
				}
				return false;
			});
		}

		if(_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
	});
}

// scroll gallery with HScroll
function initGallery(){
	var _fadeSpeed = 700;
	var _scrollSpeed = 500;
	var _activeClass = 'active';
	$('.gallery-holder').each(function(){
		var _holder = $(this);
		var _imgHolder = $('.zoom-holder', _holder);
		var _images = $('>img', _imgHolder);
		var _zoom = $('.zoom-holder .zoom', _holder);
		var _scrollGall = $('.gallery', _holder);
		var _prev = $('.btn-prev', _scrollGall);
		var _next = $('.btn-next', _scrollGall);
		var _scrollEl = $('.slides-holder', _scrollGall);
		var _scrollTrack = $('.scroll-holder', _scrollGall);
		var _scrollHandle = $('.scroll', _scrollTrack);
		var _thumbs = $('li>a', _scrollEl);
		var _active = _thumbs.filter('.' + _activeClass).length > 0 ? _thumbs.index(_thumbs.filter('.' + _activeClass)) : 0;
		
		_thumbs.removeClass(_activeClass).eq(_active).addClass(_activeClass);
		_images.removeClass(_activeClass).hide().eq(_active).addClass(_activeClass).show();
		_zoom.attr('href', _thumbs.eq(_active).attr('href'));
		
		_zoom.fancybox();
		//clicking thumbs
		_thumbs.each(function(ind){
			var _thumb = $(this);
			var _url = _thumb.attr('href');
			_thumb.click(function(){
				if (ind != _active && _images.filter(':animated').length ==0){
					_images.eq(_active).fadeOut(_fadeSpeed);
					_images.eq(ind).fadeIn(_fadeSpeed, function(){
						_images.eq(_active).removeClass(_activeClass);
						_thumbs.eq(_active).removeClass(_activeClass);
						_active = ind;
						_images.eq(_active).addClass(_activeClass);
						_thumbs.eq(_active).addClass(_activeClass);
					});
					_zoom.attr('href', _url);
				}
				return false;
			})
		});
		
		var _frameW = _scrollGall.find('>div').width();
		var _scrollW = _scrollTrack.width();
		var _slides = _scrollEl.children();
		var _slideW = _slides.eq(0).width();
		var _gallW = _slideW * _slides.length;
		_handleW = _scrollHandle.width();
		_scrollHandle.css({'left':0});
		var _kf = (_scrollW - _handleW)/(_slideW * (_slides.length-3));
		var _steps = _slides.length-3;
		var _curStep = 0;
		var _body = $('body');
		
		_prev.click(function(){
			if (!_scrollEl.is(':animated')){
				_curStep = _curStep < _steps ? _curStep+1 : _steps;
				moveGall();
			}
			return false;
		})
		_next.click(function(){
			if (!_scrollEl.is(':animated')){
				_curStep = _curStep > 0 ? _curStep-1 : 0;
				moveGall();
			}
			return false;
		});
		
		function moveGall(){
			_scrollEl.animate({
				'margin-left': -_curStep * _slideW
			}, _scrollSpeed);
			_scrollHandle.animate({
				'left':_curStep * _slideW * _kf
			}, _scrollSpeed)
		}
		
		_scrollHandle.bind('mousedown',function(e){
			var dragFlag = true;
			var hLeft = _scrollTrack.offset().left;
			var innerOffset = e.layerX || e.offsetX;
			function handleMouseMove(e) {
				var offset  = e.pageX - hLeft - innerOffset;
				var to = 0;
				if(dragFlag) {
					// move slider
					if(offset >= 0 && offset + _handleW < _scrollW) {
						to = offset;
					} else {
						if(offset < 0) to = 0;
						else to = _scrollW - _handleW;
					}
					_scrollHandle.css({'left':to})
					
					// calc index
					var slideStep = Math.round((to/_kf)/_slideW);
					if(slideStep != _curStep) {
						_curStep = slideStep;
						var _pos = _curStep * _slideW;
						_scrollEl.stop().animate({
							'margin-left': -_pos
						}, _scrollSpeed);
					}
				}
				document.onselectstart = function(){return false}
			}
			function handleMouseUp(){
				dragFlag = false;
				document.onselectstart = null;
				_body.unbind('mousemove',handleMouseMove).unbind('mouseup',handleMouseUp);
			}
			_body.bind('mousemove',handleMouseMove).bind('mouseup',handleMouseUp);
			return false;
		}).click(function(){return false});
		
		_scrollTrack.click(function(e){
			var hLeft = _scrollTrack.offset().left;
			var offset = e.pageX - hLeft;
			var to = 0;
			// move slider
			if(offset >= 0 && offset + _handleW < _scrollW) {
				to = offset - _handleW/2 < 0 ? 0: offset - _handleW/2;
			} else {
				if(offset < 0) to = 0;
				else to = _scrollW-_handleW;
			}
			
			_scrollHandle.css({'left':to})
			
			// calc index
			var slideStep = Math.round((to/_kf)/_slideW);
			if (slideStep != _curStep) {
				_curStep = slideStep;
				var _pos = _curStep * _slideW;
				_scrollEl.stop().animate({
					'margin-left': -_pos
				}, _scrollSpeed);
			}
		})
	})
}
