$(document).ready(function() {
	window.dwPortfolioLoader = {
		/* treshold - to load images that are XXX pixels near edges of the viewport. default: 250px (half of width of an image) */
		treshold: 644,
		portfolioVisible: 0,

		__loadProject: function(projectName, project, obj) {
			$template = $('div#projectTemplate').clone().attr('id', 'test');
			$imageTemplateParent = $template.find('.projectImages:first')
			$imageTemplate = $template.find('.projectImage:first').remove()

			$template
				.find('.projectTitle .content').html(project.title)
				.end()
				.find('.projectDescription .content').html(project.description)
				.end()
				.find('.close')
					.click(function(event) {
						event.preventDefault();
						$('.folio_bakcground')
							.html('')
							.animate({
								height: 1,
								top: '50%'
							}, 300)
							.animate({
								backgroundColor: '#f9cc00'
							}, 50)
							.animate({
								width: '1',
								left: '50%'
							}, 500)
							.queue(function() {
								$(this)
									.css({
										display: 'none',
										opacity: 1,
										left: null,
										top: null,
										width: null,
										height: null
									})
									.addClass('initial_style')
									.dequeue()
								dwPortfolioLoader.portfolioVisible = false
							})
					})

			for (var img in project.images) {
				$image = $imageTemplate.clone()
				//$img = $image.find('.image:first')

				//$img
				$image
					.bind('dwLoad', function() {
						$this = $(this)

						$this.addClass('loaded')
						$('<img />')
							.bind('load', {element: $this}, function(event) {
								event.data.element
									/*.css({
										visibility: 'visible',
										display: 'none'
									})*/
									.css('backgroundImage', 'url(' + $(this).attr('src') + ')')
									//.fadeIn('medium')
							})
							.attr('src', $this.data('src'))

						$this.removeData('src')
					})
					.data('src', 'userfiles/images/portfolio/' + projectName + '/' + portfolioType + '/' + project.images[img])

				//$image.find('.description').html(project.images[img].description)

				$imageTemplateParent.append($image)
			}

			$imageTemplateParent
				.append($('<div class="ui-helper-clearfix"></div>'))
				.hover(function() {
					$('.mask', $template).stop().animate({
						opacity: 0
					}, 'slow', '', function(){  $(this).css('display', 'none') })
				}, function() {
					$('.mask', $template).css('display', 'block').stop().animate({
						opacity: 1
					}, 'slow')
				})
				.data('onDrag', function(event, ui) {
					clearTimeout($(this).data('refresh_timer'))
					$(this).data('refresh_timer', setTimeout(function() {
						$imageTemplateParent.find('.projectImage:not(.loaded)').each(function(index, val) {
							$this = $(this)

							if (($this.offset().left + dwPortfolioLoader.treshold) > -$this.outerWidth() && ($this.offset().left - dwPortfolioLoader.treshold) < $(window).width()) {
								$this.trigger('dwLoad');
							}
						})
					}, 30))
				})
				.mousewheel(function(event, delta) {
					$this = $(this)
					containment = $this.data('draggable').options.containment
					$this
						.stop()
						.animate({
							left: Math.max(containment[0], Math.min(containment[2], $this.offset().left + delta  * (644 + 20))) + 'px'
						}, 'fast')
						.data('onDrag')()

					event.stopPropagation()
					event.preventDefault()
				})
				.mousedown(function(event) {
					$(this)
						.data('currentCursor', $(this).css('cursor'))
						.css('cursor', 'url("http://directweb.pl/data/dw/gfx/pointer_scroll_closed.cur"), w-resize')
				})
				.mouseup(function(event) {
					if ($(this).data('currentCursor')) {
						$(this)
							.css('cursor', $(this).data('currentCursor'))
							.removeData('currentCursor')
					}
				})

			$template.css({ visibility: 'hidden' })
			obj.append($template)
			$template
				.css({
					top: ($('.folio_bakcground').height() - $template.height()) / 2
				})
			$template.css({ visibility: 'visible' })

			$imageTemplateParent
				.width($imageTemplateParent.children('.projectImage:first').outerWidth() * project.images.length)
				.draggable({
					axis: 'x',
					delay: 30,
					containment: [
						-($imageTemplateParent.children('.projectImage:first').outerWidth() * project.images.length - $imageTemplateParent.parent().width()), 0,
						0, 0
					],
					drag: function(event, ui){
						$(this).data('onDrag')(event, ui);
					}
				})
				.data('onDrag')()
		},

		loadProject: function(projectName, portfolioType, obj) {
			if (this.portfolioVisible) {
				return
			}
			this.portfolioVisible = true

			$.ajax({
				url: 'ajax/portfolio.php',
				cache: false,
				dataType: 'json',
				data: {
					'project': projectName,
					'type': portfolioType
				},
				error: function(xhr, textStatus, errorThrown) {
					alert(errorThrown)
					dwPortfolioLoader.portfolioVisible = false
				},
				success: function(data, textStatus, xhr) {
					if (data.ret != false) {
						if (data.ret.images.length == 0) {
							dwPortfolioLoader.portfolioVisible = false
							return
						}
						$('div.folio_bakcground').removeClass('initial_style')
						var bodyH = $(document).height() - 90;
						$('div.folio_bakcground')
							.animate({
								width: '100%',
								left: '0%'
							}, 300)
							.animate({
								backgroundColor: '#0a0a0a'
							}, 50)
							.animate({
								height: bodyH,
								top: '90'
							}, 500)
							.queue(function() {
								dwPortfolioLoader.__loadProject(projectName, data.ret, obj)
								$(this).dequeue()
							})
					} else {
						this.error(xhr, 'error', data.errstr)
					}
				}
			});
		}
	}

	var $folio = $('div#portfolio')
	var $scroll = $('div#scroll')
	var $scroller = $('div#scroll').children('div#scroller_bg:first')
	var $prace = $('div#prace')

	var fItemsCount = $prace.find('div.item').length
	var fItemWidth = $folio.find('div.item:first').outerWidth(true)
	var fContainerWidth = fItemWidth * fItemsCount// + $(window).width() - fItemWidth
	$prace.width(fContainerWidth)/*.css({
		paddingLeft: ($(window).width() - fItemWidth) / 2,
		paddingRight: ($(window).width() - fItemWidth) / 2
	})*/

	$scroller.width(fItemWidth / (fItemWidth * fItemsCount) * 100 + '%')

	$scroll
		.click(function(event) {
			half_width = $scroller.width() / 2

			$scroller.stop().animate({
				left: Math.max(half_width, Math.min($scroll.width() - half_width, event.pageX)) - half_width + 'px'
			}, 100, 'easeOutCirc', function() { $scroller.trigger('dw_sync_move') })
		})
		.mousewheel(function(event, delta) {
			$scroller.trigger('dw_scroll', [delta])
			event.stopPropagation()
			event.preventDefault()
		})

	$scroller
		.data('refresh_timer', null)
		.bind('dw_sync_move', function() {
			offset = $scroller.offset().left / ($scroll.width() - $scroller.width())
			//$prace.stop().animate({
			$prace.stop().animate({
				left: -((fContainerWidth - $folio.width()) * offset) + 'px'
			}, 1000, 'easeInOutCirc')
		})
		.click(function(event) {
			/* klikniecie scrollera zatrzymuje przekazanie eventu klikniecia do parenta, zeby nie bylo ze klikamy w tlo scrolla */
			event.stopPropagation()
		})
		.draggable({
			axis: 'x',
			containment: 'parent',
			drag: function(event, ui) {
				clearTimeout($scroller.data('refresh_timer'))
				$scroller.data('refresh_timer', setTimeout(function() {
					$scroller.trigger('dw_sync_move')
				}, 30))
			}
		})
		.bind('dw_scroll', function(event, delta) {
			delta = -delta /*scroll normalnie dziala odwrotnie :P*/

			$scroller.css({
				left: Math.max(0, Math.min($scroll.width() - $scroller.width(), $scroller.offset().left + delta * ($scroll.width() / fItemsCount))) + 'px'
			})
			$scroller.trigger('dw_sync_move')
		})

	$prace
		.mousewheel(function(event, delta) {
			$scroller.trigger('dw_scroll', [delta])
			event.stopPropagation()
			event.preventDefault()
		})
	$prace.find('div.item img').click(function() {
		dwPortfolioLoader.loadProject($(this).siblings('.projectName').text(), portfolioType, $('div.folio_bakcground'))
	})
})
	//klikniecie w prace

/*
$(document).ready(function() {

	var $folio = $("div#portfolio");
	var fItemWidth = $folio.find('div.item').outerWidth(true);
	var fContainerWidth = fItemWidth * $folio.find('div.item').length;
	$folio.find('div#prace').width(fContainerWidth);


	var $scroll = $("div#scroll");
	var $scroller = $("div#scroll").children('div#scroller_bg:first');
	var scrollW =    ($folio.width() / fContainerWidth) *100
	$scroll.find("#scroller_bg").width(scrollW + "%")
	$folio.mousewheel(function(event, delta) {
		//var $scroll = $("div#scroll");
		$(this).stop().animate({scrollLeft: '-=' + (delta * fItemWidth)}, "easein", function(){


			console.debug($folio.scrollLeft());
		});

		$scroller.stop().animate({
			 left: ($scroll.width() - $scroller.width()) / ($folio.scrollLeft() / fContainerWidth) + 'px'
		}, 'fast');

	});


})
*/
