$(document).ready(function(){
	//InitGalary();
});


function InitGalary(){
	_speed = 500;
	_duration = 5000;
	var _hold = $('.gallery-wrap');
	var _slide = _hold.find('ul.gallery-list');
	var _list = _slide.find('>li');
	var _prev = $('a.prev');
	var _next = $('a.next');
	var _thumb = $('ul.switcher>li');
	var _d = _list.eq(0).outerWidth(true);
	var _x=0;
	
	var _wh = _hold.width();
	var _ws = _list.length*_d;
	var _i = 0;
	_list.eq(_i).addClass('active');
	_thumb.eq(_i).addClass('active');
	
	_thumb.each(function(i){	
		$(this).click(function(){
			_i=i;
			_x = (_i)*_d;
			RunAnimation(_x);
			_thumb.removeClass('active').eq(_i).addClass('active');
			return false;
		});
	});
	
	_next.click(function(){
		_list.eq(_i).removeClass('active');
		_thumb.eq(_i).removeClass('active');
		_i = _i+1;
		if (_x < _ws- _wh){
			if (_i < 1){_x = _x}
			else {_x = _x + _d;}
		}
		else{
			if (_i < _list.length){_x = _x}
			else {_x = 0; _i = 0}
		}
		_list.eq(_i).addClass('active');
		_thumb.eq(_i).addClass('active');
		RunAnimation(_x);
		return false;
	});
	
	
	
	_prev.click(function(){
		_list.eq(_i).removeClass('active');
		_thumb.eq(_i).removeClass('active');
		_i = _i-1;
		if (_x > 0){
			if(_i>(_ws-_wh)/_d){_x = _ws-_wh}
			else{_x = _x - _d;}
		}
		else{
			if(_i>-1){_x = _x}
			else{_x=_ws-_wh;_i=_list.length-1;}
		}
		
		_list.eq(_i).addClass('active');
		_thumb.eq(_i).addClass('active');
		RunAnimation(_x);
		return false;
	});
	
	var _t;
	function runTimer(){
		if(_t) clearInterval(_t);
		_t = setInterval(function(){
			_list.eq(_i).removeClass('active');
			_i = _i+1;
			if (_x < _ws- _wh){
				if (_i < 1){_x = _x}
				else {_x = _x + _d;}			
			}		
			else{
				if (_i < _list.length){_x = _x}
				else {_x = 0; _i = 0}			
			}
		_list.eq(_i).addClass('active');
			RunAnimation(_x);
		}, _duration);
	}
	runTimer();
	
	function RunAnimation(_x){
		_slide.animate({marginLeft: -_x}, {queue:false, duration:_speed, complete:function(){
			runTimer();
		}});
	};
};

$(function(){
    $('a.new-window,a.external').click(function(){
        window.open(this.href);
        return false;
    });
});
