var Gallery = {
    animating: false,

	init: function(class_name, pager){
		var wrapper = $('.' + class_name + 'Wrapper');
		var obj = $('.' + class_name);
		obj.steps = obj.find('img').length - 1;
		if (obj.steps > 1){
			obj.step = 0;
			Gallery.activateArrows(wrapper, obj);
			if (pager) Gallery.activatePager(wrapper, obj);
		}

        $('.leftBtn, .rightBtn', wrapper).removeClass('inactive');
	},
	activateArrows: function(wrapper, obj){
		wrapper.prepend('<div class="leftBtn inactive"></div><div class="rightBtn"></div>')
		wrapper.find('.leftBtn').bind('click', function()
        {
            if (Gallery.animating) return;
			if (!$(this).hasClass('inactive'))
            {
				obj.step--;
                obj.step = (obj.step + obj.steps) % obj.steps;
				Gallery.go(wrapper, obj, -1);
			}
		});
		wrapper.find('.rightBtn').bind('click', function(){
            if (Gallery.animating) return;
			if (!$(this).hasClass('inactive')){
				obj.step++;
                obj.step = obj.step % obj.steps;
				Gallery.go(wrapper, obj, +1);
			}
		});
	},
	activatePager: function(wrapper, obj){
		for (i = 0; i < obj.steps; i++){
			wrapper.find('.galleryPager').append('<a '+((i == 0)? 'class="active"' : '')+'></a>');
		}
		wrapper.find('.galleryPager a').bind('click', function(){
			if (!$(this).hasClass('active')){
				obj.step = wrapper.find('.galleryPager a').index(this);
				Gallery.go(wrapper, obj);
			}
		});
	},
	go: function(wrapper, obj, dir){

        $('.leftBtn, .rightBtn', wrapper).removeClass('inactive');

        //if (obj.step == 0) {
		//	wrapper.find('.leftBtn').addClass('inactive');
		//} else {
		//	wrapper.find('.leftBtn').removeClass('inactive');
		//}
		//if (obj.step == (obj.steps-1)) {
		//	wrapper.find('.rightBtn').addClass('inactive');
		//} else {
		//	wrapper.find('.rightBtn').removeClass('inactive');
		//}

        wrapper.find('.galleryPager a.active').removeClass('active');
		$(wrapper.find('.galleryPager a')[obj.step]).addClass('active');

        if (dir === -1 && obj.step == obj.steps - 1) // <-
            obj.css('marginLeft', -obj.steps * wrapper.width());

        Gallery.animating = true;

		obj.animate(
            { 'margin-left': -((obj.step == 0 && dir === 1) ? obj.steps : obj.step) * wrapper.width() },
            500,
            function()
            {
                if (dir === 1 && obj.step == 0) // ->
                    obj.css('marginLeft', 0);

                Gallery.animating = false;
            }
        );
	}
};

