/*--- document ready ---*/
$(document).ready(function(){
	fadeBox(700);
	$('div.slide').movingBlock({
		holder:'#sidebar',
		topDif:0,
		toEl:true,
		bottomDif:0,
		cssTop:'top',
		duration:300	
	});
});
/*--- fadeBox ---*/
function fadeBox(_time){
	var _hold = $('.gallery');
	var _tabs = _hold.find('.tabs > li');
	var _items = _hold.find('.items > li');
	var _t;
	var _liCount = _items.index(_items.filter(':last'));
	var _active = _items.index(_items.filter('.active:eq(0)'));
	if (_active == -1) _active = 0;
	var _temp = _active - 1;
	if (_temp == -1) _temp = _liCount;
	_tabs.hide().eq(_active).show();
	function gallFade(){
		_items.removeClass('active').eq(_active).addClass('active');
		_tabs.eq(_temp).fadeOut(_time);
		_tabs.eq(_active).fadeIn(_time);
		_temp = _active;
	};
	function timerGo(){
		_t = setInterval(function(){
			_active++;
			if (_active > (_liCount)) _active = 0;
			gallFade();
		}, 8000);
	};
	gallFade();
	_items.click(function(){
		if(_active != _items.index($(this))){
			_active = _items.index($(this));
			gallFade();
			if(_t) clearTimeout(_t);
			timerGo();
		}
		return false;
	});
	timerGo();
}
// movingBlock

jQuery.fn.movingBlock = function(_options){
	// defaults options
	var _options = jQuery.extend({
		holder:'div.wrapper',
		topDif:0,
		bottomDif:0,
		toEl:false,
		cssTop:'top',
		duration:350
	},_options);
	
	return this.each(function(){
		var _obj = $(this);
		var _holder = $(_options.holder);
		var _offset = _holder.offset();
		var _thisHeight = _obj.outerHeight();
		var _prop = _options.cssTop.toString();
		var _duration = _options.duration;
		var _defTop = parseInt(_obj.css(_prop));
		var _move = true, _height;
		
		_offset.top = _offset.top - _options.topDif + _defTop;
		_offset.bottom = _holder.innerHeight() - _options.bottomDif - _thisHeight - _defTop;
		
		if (_options.toEl) {
			_offset.bottom = $('.wrap').height() - $('.slide').height() - 7;
		}
		var _win = $(window);
		_win.scroll(function(){
			animateBlock()
		});
		_win.resize(function(){
			winResize();
			animateBlock()
		});
		winResize();
		function winResize(){
			if (window.innerHeight) _height = window.innerHeight;
			else _height = document.documentElement.clientHeight;
			if (_thisHeight >= _height) _move = false;
			else _move = true;
		}
		function animateBlock(){
			if (_move) {
				_offset = _holder.offset();
				_offset.top = _offset.top - _options.topDif + _defTop;
				if (_options.toEl) {
					_offset.bottom = $('.wrap').height() - $('.slide').height() - 7;
				}
				var _top = _win.scrollTop();
				var _dif = _top - _offset.top;
				if (_dif > 0) {
					if (_dif >= _offset.bottom - _defTop) _dif = _offset.bottom - _defTop;
					_obj.animate({'top':_dif+_defTop}, {duration:_duration, queue:false});
				} else {
					_obj.animate({'top':_defTop}, {duration:_duration, queue:false});
				}
			}
		}
    });
}