
$(function(){
	fadeGallery();
	popups();
})


function hidePopupCommon(id){
	
	// Close the current window and re-init the popups.
	$('a[href=' + id + ']:eq(0)').removeClass('active');
	
	var _d = 150;
	var _f = true;
	var _holderPopup = $('.holder-popup');
	var _pops = $('.popup', _holderPopup);
	var _list = $('.show-popup')
	var _main = $('.main-content');
	_pops.filter(':visible').customFadeOut(_d,function(){
		if(_pops.filter(':visible').length == 0 && _list.filter('.active').length == 0) _main.customFadeIn(_d,function(){_f=true});
	});
	
	// TODO: Verify we're not getting multiple event handlers.
	popups();
};

function popups(){
	var _d = 150;
	var _list = $('.show-popup')
	var _main = $('.main-content');
	var _holderPopup = $('.holder-popup');
	var _ok = $('.btn-confirm', _holderPopup);
	var _f = true;
	_ok.click(function(){
		var _id = $(this).parents('.popup').attr('id');
		$('a[href=#'+_id+']:eq(0)').removeClass('active');
		hidePopup();
		return false;
	});
	_list.click(function(){
		if(_f){
			_f = false;
			var _href = $(this).attr('href');
			if($(this).hasClass('active')){
				hidePopup();
				$(this).removeClass('active');
			}else{
				_list.removeClass('active');
				$(this).addClass('active');
				if(_main.is(':visible')){
					_main.customFadeOut(_d, function(){
						showPopup(_href);
					});
				}else{
					hidePopup();
					setTimeout(function(){
						showPopup(_href);
					},_d)
				}
			}
		}
		return false;
	});
	function showPopup(href){
		var _popup = $(href);
		_popup.customFadeIn(_d,function(){_f=true});
	};
	function hidePopup(func){
		var _pops = $('.popup', _holderPopup);
		_pops.filter(':visible').customFadeOut(_d,function(){
			if(_pops.filter(':visible').length == 0 && _list.filter('.active').length == 0) _main.customFadeIn(_d,function(){_f=true});
		});
	};
}


function fadeGallery(){
	var _swichTime = 2000;
	var _d = 1000;
	$('.fade-gal').each(function(){
		var _this = $(this);
		var _list = $('.g-items > li', _this);
		var _a = _list.index(_list.filter('.active:eq(0)'));
		_swichTime+=_d;
		if(_a == -1) _a = 0;
		_list.removeClass('active').css('opacity', 0).eq(_a).addClass('active').css('opacity', 1);
		var _t;
		if (_swichTime){
			_t = setTimeout(function(){
				if(_a < _list.length - 1) changeEl(_a + 1);
				else changeEl(0);
			},_swichTime);
		}
		function changeEl(_ind){
			if(_t) clearTimeout(_t);
			if(_ind != _a){
				_list.eq(_a).removeClass('active').css({display:'block'}).animate({opacity: 0}, {queue:false, duration:_d});
				_list.eq(_ind).addClass('active').animate({opacity: 1}, {queue:false, duration:_d});
				_a = _ind;
			}
			if (_swichTime){
				_t = setTimeout(function(){
					if(_a < _list.length - 1) changeEl(_a + 1);
					else changeEl(0);
				}, _swichTime);
			}
		}
	});
}
