$(document).ready(function() {
	var onResize = []
	$('.carusel').each(function() {
		var carusel = this, oneWidth, count
		var scroll = $('.scroll-wrap', carusel)
		var node = scroll.get(0)
		var back = $('.back', carusel)
		var next = $('.next', carusel)

		var tmp = $('<div></div>')
		var root = $('.scroll', carusel)
		var items = $('.item-wrap', root)
		oneWidth = items.width()
		items.appendTo(tmp)


		var offset = 0

		var updateSize = function(val) {
			back.css('marginRight', '20px')
			var width = scroll.width()
			count = Math.floor(width / oneWidth)
			back.css('marginRight', (Math.floor((width - (count * oneWidth))/2)+20)+'px')
			show()
		}
		var offsetMinus = function(val) {
			offset -= val
			if (offset < 0) offset = count < offset * -1 ? 0 : Math.floor(items.length / val) * val
		}
		var offsetPlus = function(val) {
			offset += val
			if (items.length < offset) offset = 0
		}

		var scroller = {
			interval: null,
			timeout: null,
			val: 0,
			enable: true,

			_run: function() {
				if (!scroller.enable) return;
				scroller.val = 0
				if (scroller.interval) {
					clearTimeout(scroller.interval)
					scroller.interval = null
				}
				if (scroller.timeout) {
					clearTimeout(scroller.timeout)
					scroller.timeout = null
				}
				scroller.timeout = setTimeout(function() {
					scroller.interval = setInterval(function() {
						if (!scroller.enable) return;
						scroller.val -= 15
						if (oneWidth <= scroller.val*-1) {
							offsetPlus(1)
							show()
							return
						}
						$(':first', root).css('marginLeft', scroller.val+'px')
					}, 5)
				}, 3000)
			},

			_stop: function() {
				if (scroller.timeout) {
					clearTimeout(scroller.timeout)
					scroller.timeout = null
				}
				scroller.enable = false
			},

			_continue: function() {
				scroller.enable = true
				scroller._run()
			}
		}

		var show = function() {
			root.html('')
			var max = count + offset
			items.each(function(i) {
				if (offset <= i && i < max) $(this).clone().appendTo(root)
			})
			max = max - items.length
			if (0 < max) {
				items.each(function(i) {
					if (0 <= i && i < max) $(this).clone().appendTo(root)
				})
			}
			$('a img', root).click(function() {
				location = $(this).parents('a').get(0).href
			})
			scroller._run()
		}
		updateSize()
		$(window).resize(updateSize)
		back.click(function() {
			offsetMinus(count)
			show()
			return false
		})

		next.click(function() {
			offsetPlus(count)
			show()
			return false
		})


		$(carusel).hover(scroller._stop, scroller._continue)

		$(carusel).wheel(function(event,delta) {
			if ($.browser.opera) delta *= -1
			if (0 < delta)  offsetMinus(1) ; else offsetPlus(1)
			show()
			return false
		})
		
		
		onResize.push(function() {
			updateSize()
		})
	})
})
