/* 
Project: Smultron.pl
Version: 2011-11-20
*/

$(document).ready(function() {
	var $window = $(window),
		previousScrolltop = 0,
		$waves = $('#waves'),
		$tankwater = $('#tankwater'),
		$pipeswater = $('#pipeswater'),
		sectionHeight = 974,
		offsetOffer = $('#offer').offset().top,
		offsetPortfolio = $('#portfolio').offset().top,
		offsetAbout = $('#about').offset().top,
		offsetContact = $('#contact').offset().top;
		pageLang = $('body').attr('id');
		$windowHeight = $window.height();


	/*
	 * NAV
	 */
	
	var $navContainer = $('#pageNav'),
		$nav = $('#pageNav li');
	$nav.eq(0).addClass('current');
	var prevNavInterval,
		navContainerOffset = $navContainer.offset().left,
		navContainerOffsetTop = $navContainer.offset().top,
		curNavOffset = $navContainer.find('li.current').offset().left,
		curNavWidth = $navContainer.find('li.current').width(),
		curNavPos = Math.abs(curNavOffset - navContainerOffset),
		$nund = $('#navUnderline'),
		pagescrolling = false;
	
	$nund.css({
		'left': curNavPos,
		'width': curNavWidth
	});
	
	$('#contact').css({
		'min-height': $windowHeight
	});
	
	function moveNavUnderline(newPos, newWidth, newOpacity) {
		$nund.stop().animate({
			'left': newPos,
			'width': newWidth,
			'opacity': newOpacity
		}, 300);
	}
	
	function setCurrentNav(newCurrentNav) {
		$nav.removeClass('current');
		newCurrentNav.parent().addClass('current');
		curNavOffset = newCurrentNav.parent().offset().left;
		curNavWidth = newCurrentNav.parent().width();
		curNavPos = Math.abs(curNavOffset - navContainerOffset);
		moveNavUnderline(curNavPos, curNavWidth, 1);
	}
	
	$nav.children()
	.bind('click', function(e) {
		e.preventDefault();
		$self = $(this);
		thisLocation = $self.attr('href');
		destinationDistance = Math.abs($nav.offset().top - $(thisLocation).offset().top);
		
		if (destinationDistance > 30) {
			pagescrolling = true;
			if ($.browser.msie) {
				$nund.hide();
			}
			$navContainer.animate({
				'opacity': 0
			}, 100, function() {
				setCurrentNav($self);
			});
			$.scrollTo(thisLocation, destinationDistance*1.25, {
				easing: 'swing',
				onAfter: function() {
					pagescrolling = false;
					$window.trigger('scroll');
					$navContainer.animate({
						'opacity': 1
					}, 400, function() {
						if ($.browser.msie) {
							$nund.fadeIn(200);
						}
						return pagescrolling = false;
					});
				}
			});
		}
	})
	.bind('mouseenter', function() {
		var selfNavOffset = $(this).parent().offset().left;
		var selfNavWidth = $(this).parent().width();
		var selfNavPos = Math.abs(selfNavOffset - navContainerOffset);
		moveNavUnderline(selfNavPos, selfNavWidth, 0.7);
	});
	$navContainer.bind('mouseleave', function() {
		moveNavUnderline(curNavPos, curNavWidth, 1)
	});

	function manageNav(curPos) {
		var navIntervals = function(curPos) {
			if ( (curPos >= 0) && (curPos < 878) ) {
				return 'home'
			} else if ( (curPos >= 878) && (curPos < 1775) ) {
				return 'offer'
			} else if ( (curPos >= 1775) && (curPos < 2825) ) {
				return 'portfolio'
			} else if ( (curPos >= 2825) && (curPos < 3820) ) {
				return 'about'
			} else if (curPos >= 3820) {
				return 'contact'
			}
		}
		curNavInterval = navIntervals(curPos);
		if (curNavInterval !== prevNavInterval) {
			$navContainer.attr('class', curNavInterval);
			$newCurrentNav = $('#pageNav a[href=#' + curNavInterval + ']');
			setCurrentNav($newCurrentNav);
		}
	}
	
	
	/*
	 * BACKGROUNDS ANIM
	 */
	 
	var $pageHeader = $('#pageHeader'),
		navVisible = true,
		animatingNav = false,
		$waves = $('#waves'),
		$tankwater = $('#tankwater'),
		$pipeswater = $('#pipeswater');
		$kranik = $('#kranik');
		$kranik.css({
			'opacity': 0
		});
		kranikVisible = false;
		sc = 0;
		
	function animateBackground() {
		currentScrollTop = $window.scrollTop();
		
		if (currentScrollTop >= navContainerOffsetTop) {
			$pageHeader.attr('class','fxd');
		} else {
			$pageHeader.attr('class','');
		}
		
		if (pagescrolling == false) {
			manageNav(currentScrollTop);
		}
		
		if (currentScrollTop > 1660 && kranikVisible == false) {
			kranikVisible = true;
			$kranik.stop().css({
				'margin-left': 40
			}).animate({
				'margin-left': '-=20',
				'opacity': 1
			}, 300);
		}
		
		if (currentScrollTop < 1660 && kranikVisible == true) {
			kranikVisible = false;
			$kranik.stop().css({
				'margin-left': 20
			}).animate({
				'margin-left': '+=20',
				'opacity': 0
			}, 300);
		}
		
		if (currentScrollTop >= 0 && currentScrollTop < offsetOffer) {
			localScrollTop = currentScrollTop;
			wavePos = 710 - localScrollTop*0.35;
			$waves.css({
				'background-attachment': 'scroll',
				'background-position': 'center ' + wavePos + 'px'
			});
		}
		
		if (currentScrollTop > offsetOffer && currentScrollTop < 1750) {
			localScrollTop = currentScrollTop - sectionHeight;
			wavePos = -300 + localScrollTop*0.35;
			$waves.css({
				'background-attachment': 'fixed',
				'background-position': 'center ' + wavePos + 'px'
			});
		}
		
		if (currentScrollTop > 1680 && currentScrollTop < 2700) {
			localScrollTop = currentScrollTop - 1680;
			tankPos = parseInt(localScrollTop*0.2+100);
			$tankwater.css({
				'background-position': 'center ' + tankPos + 'px'
			});
		}
		
		if (currentScrollTop > 2700 && currentScrollTop < 3540) {
			localScrollTop = currentScrollTop - 2700;
			pipesPos = parseInt(270 + localScrollTop*0.3);
			$pipeswater.css({
				'background-position': 'center ' + pipesPos + 'px'
			});
		}
		
		if ( (currentScrollTop > 150 && currentScrollTop < 900) || (currentScrollTop > 1030 && currentScrollTop < 1776) || (currentScrollTop > 1970 && currentScrollTop < 2840) || (currentScrollTop > 2950 && currentScrollTop < 3840) || (currentScrollTop > 3920) ) {
			if (navVisible == true && pagescrolling == false && animatingNav == false) {
				animatingNav = true;
				$navContainer.stop().animate({
					'opacity': 0
				}, 200, function() {
					navVisible = false;
					animatingNav = false;
					$(this).css({
						'opacity': 0
					});
					$pageHeader.css({
						'z-index': -1
					});
					if ($.browser.msie) {
						$nund.hide();
					}
				});
			}
		}
		else {
			if (navVisible == false && pagescrolling == false && animatingNav == false) {
				animatingNav = true;
				if ($.browser.msie) {
						$nund.show();
					}
				$pageHeader.css({
					'z-index': 5
				});
				$navContainer.stop().animate({
					'opacity': 1
				}, 200, function() {
					navVisible = true;
					animatingNav = false;
					$(this).css({
						'opacity': 1
					}).show();
				});
			}
		}
		previousScrolltop = currentScrollTop;
	}
	$window.scroll(animateBackground);
	$window.trigger('scroll');
	
	
	/*
	 * PORTFOLIO
	 */
	
	var $thumbsCache = $('#thumbsPanel > div').html(),
		$thumbsPanel = $('#thumbsPanel > div'),
		$thumbs = $('#thumbsPanel article'),
		$thumbsNav = $('.thumbsNav'),
		thumbsPanelVisible = true,
		$projectPanel = $('#projectPanel .project'),
		$thumbsSet = $('#thumbsPanel article'),
		$portfolioNav = $('#portfolioNav li'),
		currentThumbIndex = 0,
		currentThumbsSet = [],
		$designsNav = $('.designsNav'),
		designsNavNeeded = true;
		
	$designsNav.hide();
	
	function wrapThumbs($thumbsSet) {
		var thumbIndex = 0;
		currentThumbsSet = [];
		$('#thumbsPanel').show();
		for (i = 0; i <= $thumbs.length; i += 9) {
			$thumbsSet.slice(i, i+9).wrapAll('<div class="thumbsSet" />');
		}
		$('.thumbsSet:first article').css({
			'position': 'abosulte'
		}).animate({
			'top': 0,
			'left': 0
		}, 0);
		$thumbsSet.each(function() {
			thisHref = $(this).find('a').attr('href');
			$(this).attr({
				'data-index': thumbIndex
			});
			currentThumbsSet.push(thisHref);
			thumbIndex = thumbIndex + 1;
		});
		designsNavNeeded = true;
		if (currentThumbsSet.length == 1) {
			designsNavNeeded = false;
		}
		$thumbsPanel.fadeIn(300, function() {
			$('.thumbsSet').masonry();
		});
		$thumbsPanel.carouFredSel({
			auto: {
				play: false
			},
			items: {
				visible: 1,
				height: 606
			},
			prev: '#prevThumbs',
			next: '#nextThumbs',
			scroll: {
				easing: 'easeOutExpo',
				duration: 1000
			}
		});
		return currentThumbsSet;
	}
	wrapThumbs($thumbsSet);
	
	function resetThumbs() {
		$thumbsPanel.attr({
			'class': '',
			'style': ''
		}).html($thumbsCache);
	}
	
	function manageThumbsSets(thumbClass) {
		var i = 0;
		$('.thumbsSet:first').find('article').css({
			'position': 'abosulte'
		}).animate({
			'top': 0,
			'left': 0
		}, 200, function() {
			i+=1;
			if (i == $('.thumbsSet:first').find('article').length) {
				$thumbsPanel.fadeOut(200, function() {
					resetThumbs();
					if (thumbClass == '.all') {
						$thumbsSet = $thumbsPanel.children();
					} else {
						$thumbsPanel.children().not(thumbClass).remove();
						$thumbsSet = $thumbsPanel.children().not('.invis');
					}
					wrapThumbs($thumbsSet);
				});
			}
		});
	}
	
	$portfolioNav.bind('click', function() {
		$portfolioNav.removeClass('current');
		$(this).addClass('current');
		var thumbClass = '.' + $(this).find('span').attr('class').slice(2);
		$thumbsPanel.trigger('destroy', true);
		
		if (thumbsPanelVisible == true) {
			$thumbsNav.fadeOut(200);
			manageThumbsSets(thumbClass);
		} else if (thumbsPanelVisible == false) {
			$('#projectPanel').fadeOut(300, function() {
				$projectPanel.html('');
				$thumbsNav.fadeIn(200);
				manageThumbsSets(thumbClass);
			});
		}
		return false;
	});
	
	$('.imgViewer').live('mouseleave', function() {
		$(this).find('div').slideUp(300);
	}).live('mouseenter', function() {
		$(this).find('div').slideDown(300);
	});
	
	$loader = $('#loader');
	$overlayCurrent = '<div class="overlayCurrent"></div>';
	
	var $projectThumbs = $('.project .thumbs li');
	$projectThumbsCount = $projectThumbs.lenght;
	
	$('.project').delegate('.thumbs a', 'click', function(e) {
	
		e.preventDefault();
		$(this).parent().siblings().removeClass('current').find('.overlayCurrent').remove();
		$(this).parent().addClass('current').append($overlayCurrent);
		
		designUrl = $(this).attr('href');
		$(this).parents('.project').find('.imgViewer img').fadeOut(300, function() {
			$loader.fadeIn(100, function() {
				newDesignImg = new Image();
				newDesignImg.onload = function() {
					$loader.fadeOut(100, function() {
						$('.imgViewer').find('img').attr('src', designUrl).fadeIn(500);
					});
				};
				newDesignImg.src = designUrl;
			});
		});
	});
	
	function loadNextProject() {
		if (currentThumbIndex == (currentThumbsSet.length - 1)) {
			currentThumbIndex = 0;
			projectID = currentThumbsSet[0];
		} else {
			currentThumbIndex = parseInt(currentThumbIndex) + 1;
			projectID = currentThumbsSet[currentThumbIndex];
		}
		loadProject(projectID);
	}
	
	function loadPrevProject() {
		if (currentThumbIndex == 0) {
			currentThumbIndex = (currentThumbsSet.length - 1);
			projectID = currentThumbsSet[currentThumbIndex];
		} else {
			currentThumbIndex = parseInt(currentThumbIndex) - 1;
			projectID = currentThumbsSet[currentThumbIndex];
		}
		loadProject(projectID);
	}
	
	$('#nextDesign').live('click', function() {		
		$designsNav.hide();
		loadNextProject();
	});
	$('#prevDesign').live('click', function() {
		$designsNav.hide();
		loadPrevProject();
	});
	
	var $selfHeader;
	function showDescription(saywhat) {
		saywhat.stop().animate({
			'bottom': 0,
			'opacity': 1
		}, 300, 'easeOutExpo');
	}
	
	function loadProject(projectID) {
		$designsNav.hide();
		$('#thumbsPanel').fadeOut(500, function() {
			$thumbsPanel.trigger('destroy', true);
			$projectPanel.html('<div id="projectLoader">loading...</div>').parent().fadeIn(200);
			$.get(projectID, {clickedThumbHref: projectID}, function(data) {
				$projectPanel.fadeOut(200, function() {
					$(this).html(data).fadeIn(500);
					$('.thumbs li:first').addClass('current').append($overlayCurrent);
					$projectThumbs = $('.project .thumbs li');
					$projectThumbsCount = $projectThumbs.length;
					if (designsNavNeeded == true) {
						$designsNav.fadeIn(200);
					}
				});
			}, 'html').error(function(jqXHR, textStatus, errorThrown) {
				alert('Loading error: ' + textStatus + '\n' + errorThrown);
			});;
		});
	}
	
	$thumbs.find('a')
	.live('click', function(e) {
		e.preventDefault();
		$this = $(this);
		currentThumbIndex = $this.parent().attr('data-index');
		var c = 0;
		projectID = $this.attr('href');
		thumbsPanelVisible = false;
		thumbsSetLength = $('.thumbsSet:first').find('article').length;
		$('.thumbsSet:first').find('article')
		.css({
			'position': 'abosulte'
		})
		.animate({
			'top': 0,
			'left': 0
		}, 200, function() {
			c++;
			if (c == thumbsSetLength) {
				loadProject(projectID);
			}
		});
	})
	.live('mouseenter', function() {
		$selfHeader = $(this).find('header');
		showDesc = setTimeout(function() {
			showDescription($selfHeader);
		}, 400);
	})
	.live('mouseleave', function() {
		clearTimeout(showDesc);
		$selfHeader.stop().animate({
			'bottom': -184,
			'opacity': 0
		}, 300, 'easeOutExpo');
	});
	
	
	/*
	 * SLIDEPANEL
	 */
	 
	$('#slidePanel li').each(function() {
		thisImg = $(this).find('img').attr('src');
		$(this).find('img').remove();
		$(this).css({
			'background-image': 'url(' + thisImg+ ')'
		});
	});
	function initSlidePanel() {
		$('#slidePanel ul').carouFredSel({
			items: {
					visible: 1
				},
			scroll: {
				fx: 'cover',
				easing: 'easeOutExpo',
				duration: 1000,
				pauseOnHover: true
			},
			auto: {
				play: true,
				pauseDuration: 5000
			},
			prev: '#prevSlide',
			next: '#nextSlide',
			pagination: {
				fx: 'crossfade',
				container: '.slidesNav ul',
				anchorBuilder: function(nr) {
					return '<li><a>'+nr+'</a></li>';
				}
			}
		});
	}


	/*
	 * MAP
	 */
	 
	var gmap;
	var markers = []
	var $mapNav = $('#mapNav');
	var dymek;
	
	$window.load(function() {
		$.getJSON($('a#ajaxMapdata').attr('href'), function(data) {
			function setMapNav(pageLang) {
				var mapNav = '<ul>';
				for (k in data.mapData) {
					if (pageLang == 'en') {
						mapNav += '<li id="mapPoint' + k + '">' + data.mapData[k].title.en + '</li>'
					} else if (pageLang == 'pl') {
						mapNav += '<li id="mapPoint' + k + '">' + data.mapData[k].title.pl + '</li>'
					}
				}
				mapNav += '</ul>';
				$mapNav.append(mapNav);
				$mapNav.find('li').live('click', function() {
					$(this).parent().children().removeClass('current');
					$(this).addClass('current');
					thisPoint = $(this).attr('id').slice(8);
					if (dymek) {
						dymek.close();
					}
					google.maps.event.trigger(markers[thisPoint],'click');
				});
				$mapNav.find('li:first').trigger('click');
			}
			
			function gmaps_addMarker(point) {
				var marker = new google.maps.Marker({
					position: new google.maps.LatLng(data.mapData[point].lat, data.mapData[point].lng),
					map: gmap,
					clickable: true,
					icon: data.mapData[point].markerIcon
				});
				markers.push(marker);
				var getContent = function() {
					if ($('body').attr('id') == 'en') {
						return data.mapData[point].descr.en
					} else {
						return data.mapData[point].descr.pl
					}
				}
				google.maps.event.addListener(markers[point], 'click', function() {
					if (dymek) {
						dymek.close();
					}
					dymek = new InfoBox({
						content: '<div>' + getContent() + '<em></em></div>',
						closeBoxURL: $('a#closeboxUrl').attr('href'),
						infoBoxClearance: new google.maps.Size(20, 25),
						pixelOffset: new google.maps.Size(-380, -15),
						maxWidth: 367
					});
					dymek.open(gmap, marker);
				});
			}
			
			function initGmap() {
				var mapOptions = {
					center: new google.maps.LatLng(data.mapData[0].lat, data.mapData[0].lng),
					zoom: 16,
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					disableDefaultUI: true,
					navigationControl: true,
					mapTypeControl: false
				}
				gmap = new google.maps.Map(document.getElementById("map"), mapOptions);
				for (pointsCount = 0; pointsCount < data.mapData.length; pointsCount++) {
					gmaps_addMarker(pointsCount);
				}
			}
			
			initGmap();
			setMapNav(pageLang);
			
		}).error(function(jqXHR, textStatus, errorThrown) {
			alert('$.getJSON error: ' + textStatus);
			alert('Incoming Text: ' + jqXHR.responseText);
		});
	
	});

	
	/*
	 * CONTACT FORM
	 */
	 
	function validEmail(email) {
		var pattern= new RegExp(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$/);
		return pattern.test(email);
	}
	 
	$formLoader = $('#formLoader');
	$formLoader.hide();
	$('#contactForm button').bind('click', function(e) {
		e.preventDefault();
		$('p.errorMsg').fadeOut(200);
		$('input.error, textarea.error').removeClass('error');
		
		$podpis = $('input[name="podpis"]').val();
		$email = $('input[name="email"]').val();
		$message = $('textarea[name="message"]').val();
		
		if ($podpis == '' || $podpis == 'Podpis' || $podpis == 'Signature') {
			$('p.podpis').fadeIn(300);
			$('input[name="podpis"]').addClass('error');
			return false;
		}
		if ($email == '' || $email == 'Email') {
			$('p.email').fadeIn(300);
			$('input[name="email"]').addClass('error');
			return false;
		}
		if (!validEmail($email)) {
			$('p.emailInvalid').fadeIn(300);
			$('input[name="email"]').addClass('error');
			return false;
		}
		if ($message == '') {
			$('p.message').fadeIn(300);
			$('textarea[name="message"]').addClass('error');
			return false;
		}
		var dataString = 'podpis=' + $podpis + '&email=' + $email + '&message=' + $message;
		
		$formLoader.fadeIn(200);
		$.post($('a#ajaxSendMessage').attr('href'), dataString, function() {
			$formLoader.fadeOut(200, function() {
				$('#contactForm button').fadeOut(200, function() {
					$('p.sentMsg').fadeIn(200);
				});
			});
		})
		.error(function(jqXHR, textStatus, errorThrown) {
			alert('Sending error: ' + textStatus + '\n' + errorThrown);
		});
	});


	/*
	 * WINDOW EVENTS
	 */

	var redrawPortfolio;
	
	$window.resize(function() {
		navContainerOffset = $navContainer.offset().left;
		curNavOffset = $navContainer.find('li.current').offset().left;
		
		if ( $thumbsPanel.is(':visible') ) {
			clearTimeout(redrawPortfolio);
			var currentThumbsClass = $('#portfolioNav').find('li.current span').attr('class');

			if (!currentThumbsClass) {
				currentThumbsClass = '.all'
			}
			else {
				currentThumbsClass = '.' + currentThumbsClass.slice(2);
			}
			redrawPortfolio = setTimeout(function() {
				manageThumbsSets(currentThumbsClass);
			}, 500);
		}
	});
	
	$window.load(function() {
		initSlidePanel();
	});

});

