jQuery(function(){
	clearInputs();
	ieHover('#nav li');
	initGallery();
	initSlidebox();
	initPopups();
	jQuery('div.navigation').each(function(){
		if(jQuery(this).find('a').length == 0) jQuery(this).remove();
	});
})

/* ieHover */
function ieHover(_selector, _class){
	if(_class == null) _class = 'hover';
	if (jQuery.browser.msie && jQuery.browser.version < 7) {
		jQuery(_selector).each(function(){
			jQuery(this).mouseenter(function(){
				jQuery(this).addClass(_class)
			}).mouseleave(function(){
				jQuery(this).removeClass(_class)
			})
		})
	}
}

/* clear inputs */
function clearInputs(){
	var _filterClass = 'default';
	jQuery('input:text, input:password, textarea').each(function(){
		var _el = jQuery(this);
		var _val = _el.val();
		_el.bind('focus', function(){
			if(this.value == _val && !jQuery(this).hasClass(_filterClass)) this.value = '';
		}).bind('blur', function(){
			if(this.value == '' && !jQuery(this).hasClass(_filterClass)) this.value = _val;
		});
	});
};

/* initSlidebox */
function initSlidebox(){
	var _el = jQuery('body > .content-facebook, body > .content-twitter');
	_el.each(function(){
		var $this = jQuery(this),
			slideBox = jQuery('.holder-box', this),
			_w = slideBox.width(),
			_duration = 300,
			_delay = 1000,
			_ico = jQuery('.ico', this),
			_t;
		
		$this.css({
			marginLeft: -_w
		})
		
		$this.mouseenter(function(){
			if(_t) clearTimeout(_t);
			_ico.addClass('active');
			$this.animate({marginLeft: 0}, {queue: false, duration: _duration}).css({zIndex: 3});
		}).mouseleave(function(){
			_t = setTimeout(function(){
				$this.animate({marginLeft: -_w}, {queue: false, duration: _duration, complete: function(){
					$this.css({zIndex: 2});
					_ico.removeClass('active');
				}});
			}, _delay)
		})
	})
}

/* initGallery */
function initGallery(){
	/* slideshow init */
	jQuery('div.gallery-home').each(function(){
		var _this = jQuery(this),
			_slideImage = jQuery('.fade-holder > img', _this),
			_visiblePartSwicher = 4,
			_holderSwicher = jQuery('.frame-swicher:eq(0)', this),
			_widthSwicher = _holderSwicher.width(),
			_swicher = jQuery('> ul', _holderSwicher),
			_w;
		
		_slideImage.each(function(){
			var _img = jQuery(this);
			_img.attr('srcimage', _img.attr('src'));
			_img.attr('src', '');
		})
		
		_this.fadeGallery({
			slideElements:'.fade-area > li',
			pagerLinks:'.frame-swicher > ul > li',
			btnNext:'a.btn-next',
			btnPrev:'a.btn-prev',
			pauseOnHover:true,
			autoRotation:true,
			autoHeight: true,
			dynamicImageLoad: '.fade-holder > img',
			dynamicImageLoadAttr:'srcimage',
			switchTime:10000,
			duration:300,
			onBeforeFade: function(_this, _slides, _prevIndex, _currentIndex){
				_w = - (Math.ceil((_currentIndex + 1) / _visiblePartSwicher) - 1) * _widthSwicher;
				_swicher.animate({marginLeft: _w}, {queue: false, duration: 300});
			}
		});
	});
	
	jQuery('.footer-gallery').fadeGallery({
		slideElements:'.footer-gallery-holder > ul > li',
		pagerLinks:'.swicher ul > li',
		pauseOnHover:true,
		autoRotation:true,
		autoHeight: true,
		switchTime:5000,
		duration:800
	})
}

/* slideshow plugin */
jQuery.fn.fadeGallery = function(_options){
	var _options = jQuery.extend({
		slideElements:'div.slideset > div',
		generatePagination: null,
		pagerLinks:'div.pager a',
		btnNext:'a.next',
		btnPrev:'a.prev',
		btnPlayPause:'a.play-pause',
		btnPlay:'a.play',
		btnPause:'a.pause',
		pausedClass:'paused',
		disabledClass: 'disabled',
		playClass:'playing',
		activeClass:'active',
		loadingClass:'ajax-loading',
		loadedClass:'slide-loaded',
		dynamicImageLoad:false,
		dynamicImageLoadAttr:'alt',
		currentNum:false,
		allNum:false,
		startSlide:null,
		noCircle:false,
		pauseOnHover:true,
		autoRotation:false,
		autoHeight:false,
		onBeforeFade:false,
		onAfterFade:false,
		onChange:false,
		disableWhileAnimating:false,
		switchTime:3000,
		duration:650,
		event:'click'
	},_options);

	return this.each(function(){
		/* gallery options */
		if(this.slideshowInit) return; else this.slideshowInit;
		var _this = jQuery(this);
		var _slides = jQuery(_options.slideElements, _this);
		var _generatePagination = jQuery(_options.generatePagination, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
		var _btnPause = jQuery(_options.btnPause, _this);
		var _btnPlay = jQuery(_options.btnPlay, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _dynamicImageLoad = _options.dynamicImageLoad;
		var _dynamicImageLoadAttr = _options.dynamicImageLoadAttr;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _loadingClass = _options.loadingClass;
		var _loadedClass = _options.loadedClass;
		var _disabledClass = _options.disabledClass;
		var _pausedClass = _options.pausedClass;
		var _playClass = _options.playClass;
		var _autoHeight = _options.autoHeight;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
		var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
		var _startSlide = _options.startSlide;
		var _noCycle = _options.noCircle;
		var _onChange = _options.onChange;
		var _onBeforeFade = _options.onBeforeFade;
		var _onAfterFade = _options.onAfterFade;
		var _disableWhileAnimating = _options.disableWhileAnimating;

		/* gallery init */
		var _anim = false;
		var _hover = false;
		var _prevIndex = 0;
		var _currentIndex = 0;
		var _slideCount = _slides.length;
		var _timer;
		if(_slideCount < 2) return;
		
		if(_generatePagination.length) {
			_generatePagination.empty();
			recalcOffsets();
			var _list = jQuery('<ul />');
			for(var i=0; i<_stepCount; i++) jQuery('<li><a href="#">'+(i+1)+'</a></li>').appendTo(_list);
			_list.appendTo(_generatePagination);
			_pagerLinks = _list.children();
		}
		
		_prevIndex = _slides.index(_slides.filter('.'+_activeClass));
		if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
		else _currentIndex = _prevIndex;
		if(_startSlide != null) {
			if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
			else _prevIndex = _currentIndex = parseInt(_startSlide);
		}
		_slides.hide().eq(_currentIndex).show();
		if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
		else _this.removeClass(_playClass).addClass(_pausedClass);

		/* gallery control */
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				nextSlide();
				return false;
			});
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentIndex != _ind) {
						if(_disableWhileAnimating && _anim) return;
						_prevIndex = _currentIndex;
						_currentIndex = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		/* play pause section */
		if(_btnPlayPause.length) {
			_btnPlayPause.bind(_controlEvent,function(){
				if(_this.hasClass(_pausedClass)) {
					_this.removeClass(_pausedClass).addClass(_playClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_autoRotation = false;
					if(_timer) clearTimeout(_timer);
					_this.removeClass(_playClass).addClass(_pausedClass);
				}
				return false;
			});
		}
		if(_btnPlay.length) {
			_btnPlay.bind(_controlEvent,function(){
				_this.removeClass(_pausedClass).addClass(_playClass);
				_autoRotation = true;
				autoSlide();
				return false;
			});
		}
		if(_btnPause.length) {
			_btnPause.bind(_controlEvent,function(){
				_autoRotation = false;
				if(_timer) clearTimeout(_timer);
				_this.removeClass(_playClass).addClass(_pausedClass);
				return false;
			});
		}

		/* dynamic image loading (swap from ATTRIBUTE) */
		function loadSlide(slide) {
			if(!slide.hasClass(_loadingClass) && !slide.hasClass(_loadedClass)) {
				var images = slide.find(_dynamicImageLoad) // pass selector here
				var imagesCount = images.length;
				if(imagesCount) {
					slide.addClass(_loadingClass);
					images.each(function(){
						var img = this;
						img.onload = function(){
							img.loaded = true;
							img.onload = null;
							setTimeout(reCalc,_duration);
						}
						img.setAttribute('src', img.getAttribute(_dynamicImageLoadAttr));
						img.setAttribute(_dynamicImageLoadAttr,'');
					}).css({opacity:0});

					function reCalc() {
						var cnt = 0;
						images.each(function(){
							if(this.loaded) cnt++;
						});
						if(cnt == imagesCount) {
							slide.removeClass(_loadingClass);
							images.animate({opacity:1},{duration:_duration,complete:function(){
								if(jQuery.browser.msie && jQuery.browser.version < 9) jQuery(this).css({opacity:'auto'})
							}});
							slide.addClass(_loadedClass)
						}
					}
				}
			}
		}

		/* gallery animation */
		function prevSlide() {
			if(_disableWhileAnimating && _anim) return;
			_prevIndex = _currentIndex;
			if(_currentIndex > 0) _currentIndex--;
			else {
				if(_noCycle) return;
				else _currentIndex = _slideCount-1;
			}
			switchSlide();
		}
		function nextSlide() {
			if(_disableWhileAnimating && _anim) return;
			_prevIndex = _currentIndex;
			if(_currentIndex < _slideCount-1) _currentIndex++;
			else {
				if(_noCycle) return;
				else _currentIndex = 0;
			}
			switchSlide();
		}
		function refreshStatus() {
			if(_dynamicImageLoad) loadSlide(_slides.eq(_currentIndex));
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
			if(_currentNum) _currentNum.text(_currentIndex+1);
			if(_allNum) _allNum.text(_slideCount);
			_slides.eq(_prevIndex).removeClass(_activeClass);
			_slides.eq(_currentIndex).addClass(_activeClass);
			if(_noCycle) {
				if(_btnPrev.length) {
					if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
					else _btnPrev.removeClass(_disabledClass);
				}
				if(_btnNext.length) {
					if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
					else _btnNext.removeClass(_disabledClass);
				}
			}
			if(typeof _onChange === 'function') {
				_onChange(_this, _slides, _prevIndex, _currentIndex);
			}
		}
		if(_autoHeight){
			_slides.eq(_currentIndex).parent().css({
				height:_slides.eq(_currentIndex).outerHeight(true),
				width:_slides.eq(_currentIndex).outerWidth(true)
			}).data('dataheight', _slides.eq(_currentIndex).outerHeight(true)).data('datawidth', _slides.eq(_currentIndex).outerWidth(true));
		}
		function switchSlide() {
			_anim = true;
			if(typeof _onBeforeFade === 'function') _onBeforeFade(_this, _slides, _prevIndex, _currentIndex);
			_slides.eq(_prevIndex).fadeOut(_duration,function(){
				_anim = false;
			});
			_slides.eq(_currentIndex).fadeIn(_duration,function(){
				if(typeof _onAfterFade === 'function') _onAfterFade(_this, _slides, _prevIndex, _currentIndex);
				jQuery(this).parent().data('dataheight', _slides.eq(_currentIndex).outerHeight(true)).data('datawidth', _slides.eq(_currentIndex).outerWidth(true));
			});
			if(_autoHeight) _slides.eq(_currentIndex).parent().animate({
				height:_slides.eq(_currentIndex).outerHeight(true),
				width:_slides.eq(_currentIndex).outerWidth(true)
			},{duration:_duration,queue:false});
			refreshStatus();
			autoSlide();
		}
		
		_this.bind('pause', function(){
			_hover = true;
			if(_timer) clearTimeout(_timer);
		})
		_this.bind('play', function(){
			_hover = false;
			autoSlide();
		})
		
		/* autoslide function */
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_this.trigger('pause');
			},function(){
				_this.trigger('play');
			});
		}
		refreshStatus();
		autoSlide();
	});
}

/* popups function */
function initPopups() {
	var _zIndex = 1000;
	var _fadeSpeed = 350;
	var _faderOpacity = 0.75;
	var _faderBackground = '#000';
	var _faderId = 'lightbox-overlay';
	var _closeLink = 'a.btn-close, a.close, a.cancel';
	var _fader;
	var _lightbox = null;
	var _ajaxClass = 'ajax-load';
	var _openers = jQuery('a.open-popup');
	var _page = jQuery(document);
	var _minWidth = 1000;
	var _scroll = false;

	/* init popup fader */
	_fader = jQuery('#'+_faderId);
	if(!_fader.length) {
		_fader = jQuery('<div />');
		_fader.attr('id',_faderId);
		jQuery('body').append(_fader);
	}
	_fader.css({
		opacity:_faderOpacity,
		backgroundColor:_faderBackground,
		position:'absolute',
		overflow:'hidden',
		display:'none',
		top:0,
		left:0,
		zIndex:_zIndex
	});

	/* IE6 iframe fix */
	if(jQuery.browser.msie && jQuery.browser.version < 7) {
		if(!_fader.children().length) {
			var _frame = jQuery('<iframe src="javascript:false" frameborder="0" scrolling="no" />');
			_frame.css({
				opacity:0,
				width:'100%',
				height:'100%'
			});
			var _frameOverlay = jQuery('<div>');
			_frameOverlay.css({
				top:0,
				left:0,
				zIndex:1,
				opacity:0,
				background:'#000',
				position:'absolute',
				width:'100%',
				height:'100%'
			});
			_fader.empty().append(_frame).append(_frameOverlay);
		}
	}

	/* lightbox positioning function */
	function positionLightbox() {
		if(_lightbox) {
			var _windowHeight = jQuery(window).height();
			var _windowWidth = jQuery(window).width();
			var _lightboxWidth = _lightbox.outerWidth();
			var _lightboxHeight = _lightbox.outerHeight();
			var _pageHeight = _page.height();

			if (_windowWidth < _minWidth) _fader.css('width',_minWidth);
				else _fader.css('width','100%');
			if (_windowHeight < _pageHeight) _fader.css('height',_pageHeight);
				else _fader.css('height',_windowHeight);

			_lightbox.css({
				position:'absolute',
				zIndex:(_zIndex+1)
			});

			/* vertical position */
			if (_windowHeight > _lightboxHeight) {
				if (jQuery.browser.msie && jQuery.browser.version < 7) {
					_lightbox.css({
						position:'absolute',
						top: parseInt(jQuery(window).scrollTop()) + (_windowHeight - _lightboxHeight) / 2
					});
				} else {
					_lightbox.css({
						position:'fixed',
						top: (_windowHeight - _lightboxHeight) / 2
					});
				}
			} else {
				var _faderHeight = _fader.height();
				if(_faderHeight < _lightboxHeight) _fader.css('height',_lightboxHeight);
				if (!_scroll) {
					if (_faderHeight - _lightboxHeight > parseInt(jQuery(window).scrollTop())) {
						_faderHeight = parseInt(jQuery(window).scrollTop())
						_scroll = _faderHeight;
					} else {
						_scroll = _faderHeight - _lightboxHeight;
					}
				}
				_lightbox.css({
					position:'absolute',
					top: _scroll
				});
			}

			/* horizontal position */
			if (_fader.width() > _minWidth) _lightbox.css({left:(_fader.width() - _lightbox.outerWidth()) / 2});
			else _lightbox.css({left: - jQuery(window).scrollLeft()});
		}
	}

	/* show/hide lightbox */
	function toggleState(_state) {
		if(!_lightbox) return;
		if(_state) {
			_fader.fadeIn(_fadeSpeed,function(){
				_lightbox.fadeIn(_fadeSpeed);
			});
			_scroll = false;
			positionLightbox();
			setTimeout(function(){
				jQuery(_lightbox).each(function(){
					var _this = jQuery(this);
					_this.trigger('play');
					if(jQuery('.popup-fade', _this).data('dataheight')){
						jQuery('.popup-fade', _this).css({
							height: jQuery('.popup-fade', _this).data('dataheight'),
							width: jQuery('.popup-fade', _this).data('datawidth')
						})
					}
				});
			}, (_fadeSpeed + 100))
		} else {
			_lightbox.fadeOut(_fadeSpeed,function(){
				_fader.fadeOut(_fadeSpeed);
				_scroll = false;
			});
			setTimeout(function(){
				jQuery(_lightbox).each(function(){
					var _this = jQuery(this);
					_this.trigger('pause');
					if(jQuery('.popup-fade', _this).data('dataheight')){
						jQuery('.popup-fade', _this).css({
							height: jQuery('.popup-fade', _this).data('dataheight'),
							width: jQuery('.popup-fade', _this).data('datawidth')
						})
					}
				});
			}, (_fadeSpeed + 100))
		}
	}

	/* popup actions */
	function initPopupActions(_obj) {
		if(!_obj.get(0).jsInit) {
			_obj.get(0).jsInit = true;
			/* close link */
			_obj.find(_closeLink).click(function(){
				_lightbox = _obj;
				toggleState(false);
				return false;
			});
			setTimeout(function(){
				jQuery(_obj).find('.popup-fade img').each(function(){
					var _img = jQuery(this);
					
					if(_img.width() > 988){
						_img.css({
							width: 988,
							height: 'auto'
						})
					}
				})
				jQuery(_obj).each(function(){
					var _this = jQuery(this),
						_visiblePartSwicher = 4,
						_holderSwicher = jQuery('.frame-swicher:eq(0)', this),
						_widthSwicher = _holderSwicher.width(),
						_swicher = jQuery('> ul', _holderSwicher),
						_w;
					
					_this.fadeGallery({
						slideElements:'.popup-fade > li',
						pagerLinks:'.frame-swicher > ul > li',
						btnNext:'a.btn-next',
						btnPrev:'a.btn-prev',
						pauseOnHover:true,
						autoRotation:true,
						autoHeight: true,
						switchTime:10000,
						duration:300,
						onBeforeFade: function(_this, _slides, _prevIndex, _currentIndex){
							_w = - (Math.ceil((_currentIndex + 1) / _visiblePartSwicher) - 1) * _widthSwicher;
							_swicher.animate({marginLeft: _w}, {queue: false, duration: 300});
						}
					});
				});
				positionLightbox();
			}, (_fadeSpeed + 100))
		}
	}

	/* lightbox openers */
	_openers.each(function(){
		var _opener = jQuery(this);
		var _target = _opener.attr('href');

		/* popup load type - ajax or static */
		if(_opener.hasClass(_ajaxClass)) {
			_opener.click(function(){
				/* ajax load */
				if(jQuery('div[rel*="'+_target+'"]').length == 0) {
					jQuery.ajax({
						url: _target,
						type: "POST",
						dataType: "html",
						data: 'ajax=1',
						success: function(msg){
							/* append loaded popup */
							_lightbox = jQuery(msg);
							_lightbox.find('img').load(positionLightbox)
							_lightbox.attr('rel',_target).hide().css({
								position:'absolute',
								zIndex:(_zIndex+1),
								top: -9999,
								left: -9999
							});
							jQuery('body').append(_lightbox);

							/* init js for lightbox */
							initPopupActions(_lightbox);

							/* show lightbox */
							toggleState(true);
						},
						error: function(msg){
							alert('AJAX error!');
							return false;
						}
					});
				} else {
					_lightbox = jQuery('div[rel*="'+_target+'"]');
					toggleState(true);
				}
				return false;
			});
		} else {
			if(jQuery(_target).length) {
				/* init actions for popup */
				var _popup = jQuery(_target);
				initPopupActions(_popup);
					/* open popup */
					_opener.click(function(){
					if(_lightbox) {
						_lightbox.fadeOut(_fadeSpeed,function(){
							_lightbox = _popup.hide();
							toggleState(true);
						})
					} else {
						_lightbox = _popup.hide();
						toggleState(true);
					}
					return false;
				});
			}
		}
	});

	/* event handlers */
	jQuery(window).resize(positionLightbox);
	jQuery(window).scroll(positionLightbox);
	jQuery(document).keydown(function (e) {
		if (!e) evt = window.event;
		if (e.keyCode == 27) {
			toggleState(false);
		}
	})
	_fader.click(function(){
		if(!_fader.is(':animated')) toggleState(false);
		return false;
	})
}
