(function() {
	var galleryIndex = 0;
	var slider = $('#galleryBox div.slide div.display div.slider');
	var mode = 'next';
	var loaded = [];
	var loading = false;

	var widthBase = 620;

	var moveSlide = function(obj) {
		
		var interval = setInterval(function() {
			var nowLeft = obj.style.marginLeft.num();
			var absolute = 0;
			if (mode == 'next') absolute = nowLeft % widthBase + widthBase;
			else absolute = (nowLeft % widthBase == 0) ? 0 : -1 * nowLeft % widthBase;

			var add = parseInt(absolute / 10) + 1;
			var addNum = (mode == 'next') ? -1 * add : 1 * add;

			var left = nowLeft + addNum;

			obj.style.marginLeft = left.str('px');
			if (left % widthBase == 0) {
				clearInterval(interval);
				loading = false;
			}
		}, 1);
	};
	slider.execute(function() {
		var rect = this.getParent().getRect();
		if (widthBase != rect.width) {
			widthBase = rect.width;
		}

		if (!loaded[galleryIndex]) {
			var self = this;
			var ax = new ajax();
			ax.param('page', galleryIndex);
			ax.param('board', '갤러리');
			ax.success = function() {
				var node = document.createElement('div');
				if (node.innerHTML = this.html()) {
					var width = self.style.width.num() + widthBase;
					self.style.width = width.str('px');
					self.appendChild(node);
					if (galleryIndex > 0) moveSlide(self);
					else loading = false;
					loaded[galleryIndex] = true;
				}
				else {
					galleryIndex--;
					loading = false;
				}
			};
			ax.send('/proxy/async-html/latestGallery.ffm', true);
		}
		else moveSlide(this);
	});

	$('#galleryBox div.slide button').click(function() {
		if (loading == false) {
			loading = true;
			mode = this.className;
			if (mode == 'prev') {
				galleryIndex--;
				if (galleryIndex < 0) {
					galleryIndex = 0;
					loading = false;
					return;
				}
			}
			else galleryIndex++;
			slider.execute();
		}
	});
})();

