(function($) {
	var bool_useSwipe = false,
			bool_whilePageSwitch = false,
			int_startOffset = 0,
			int_scrollOffset = 0,
			int_startWindowSizeWidth = 0,
			obj_callnbackFnt;
  
  
  function placeholder(obj_pElements) {
  	obj_pElements.each(function() {
  		var obj_element = $(this);
  		
  		if (typeof(obj_element.attr('title')) !== 'undefined') {
	      this.value = obj_element.attr('title');
	      obj_element.data('placeholderValue', obj_element.attr('title'));
	      
	      obj_element
	        .bind('focus', function() {
	          if (this.value === obj_element.data('placeholderValue')) {
	            this.value = '';
	          }
	        })
	        .bind('blur', function() {
	          if ($.trim(this.value) === '') {
	            this.value = obj_element.data('placeholderValue');
	          }
	        });
	    }
  	});
  }
  
            
	function swipeGestureAvailable() {
		var bool_available;
		
		$('body').append('<div id="swipeDetector"></div>');
		bool_available = $('#swipeDetector').css('display') === 'none';
		$('#swipeDetector').remove();
		
		return bool_available;
	}
	
	
	function layoutPages(var_pValue) {
    var str_action = typeof(var_pValue) === 'boolean' ? 'init' : 'resize',
    		obj_pagesContainer = $('#pages'),
    		obj_pagesCalculatorContainer = $('#pages-offset-calculator'),
    		obj_pagesCalculatorCurrent = obj_pagesCalculatorContainer.find('div.current'),
    		obj_pagesCalculatorNext = obj_pagesCalculatorContainer.find('div.next'),
        obj_pages = $('> div.page', obj_pagesContainer),
        obj_pageClone, obj_nextPage, 
        int_index = int_offset = 0;

		if (str_action === 'init') {
			obj_pagesCalculatorCurrent.data('oldLeft', obj_pagesCalculatorCurrent.offset().left);
	    
			// Init pages
			obj_currentPage = obj_pages.eq(0);
	    obj_currentPage.addClass('active');
	    
	    if (obj_pages.length > 1) {
	      obj_pageClone = obj_currentPage.clone();
	      obj_pageClone
	        .removeClass('current')
	        .removeClass('active')
	        .data('clone', obj_currentPage);
	        
	      obj_currentPage.data('cloned', obj_pageClone);
			  obj_pagesContainer.append(obj_pageClone);
			  
			  obj_pageClone = obj_currentPage.next('div.page').clone();
			  obj_pageClone.data('clone', obj_currentPage.next('div.page'));
			  obj_pagesContainer.append(obj_pageClone);
			  
	      obj_pages.removeClass('current');
	      obj_nextPage = obj_pages.eq(1);
	      obj_nextPage.addClass('next');
	      
				obj_pageClone = obj_pages.last().clone();
				obj_pageClone
				 .addClass('prev')
				 .data('clone', obj_pages.last());
				 
			  obj_pagesContainer.append(obj_pageClone);
			  obj_pages = $('> div.page', obj_pagesContainer); 
	    }
	    
	    obj_currentPage.addClass('current');
	    
	    if (bool_useSwipe) {
	    	int_startOffset = 45;
		    int_scrollOffset = 1024;
	    }
	    else {
	    	int_startOffset = obj_pagesCalculatorCurrent.offset().left;
		    int_scrollOffset = obj_pagesCalculatorNext.offset().left - obj_pagesCalculatorCurrent.offset().left;
	    }

	    obj_pages.each(function(int_pIndex) {
	      var obj_page = $(this);
	      
	      if (! obj_page.hasClass('current') && ! obj_page.hasClass('prev') && ! obj_page.hasClass('next')) {
	        obj_page.css({
	          display: 'block',
	          left: parseInt(int_startOffset + (int_scrollOffset * (int_pIndex - 0))) + 'px'
	        });
	      }
	      
	      //if (! obj_page.data('clone')) {
	      	obj_page.attr('data-pos', int_index);
		      int_index++;
	      //}
	    });
		}
		else {
			// Resize/relayout elements
			int_startOffset = obj_pagesCalculatorCurrent.offset().left;
			int_scrollOffset = obj_pagesCalculatorNext.offset().left - obj_pagesCalculatorCurrent.offset().left;

			obj_pages.each(function() {
	      var obj_page = $(this);
	      		
	      obj_currentPage = obj_pages.eq(0);
	      obj_nextPage = obj_pages.filter('div.next');
	     	
	     	if (! obj_page.hasClass('prev')) {
	        obj_page.css({
	          left: parseInt(int_startOffset + (int_scrollOffset * (parseInt(obj_page.attr('data-pos') - 0)))) + 'px'
	        });
        }
        
        if (obj_page.hasClass('current')) {
					obj_page
						.removeClass('current')
						.show();
	     	} 
	     	
	     	if (obj_page.hasClass('next')) {
					obj_page
						.removeClass('next')
						.show();
	     	}
	    });
	    
	    if (parseInt(obj_pagesContainer.css('left')) < 0) {
	    	obj_pagesContainer.css({
	    		left: parseInt(parseInt(int_scrollOffset * obj_pages.filter('div.active').attr('data-pos') * -1)) + 'px'
	    	});
	    }
		}
	}
	

	function createPageSwitcher() {
		var obj_pages = $('> div.page[data-pos]', '#pages'),
				obj_footerPager = $('#footer ul.page-indicator'),
				obj_switchButtons = $('#page-switch'),
				str_pages = '',
				int_index = 0;
		
		obj_pages.each(function(int_pIndex) {
			var obj_page = $(this),
					str_class = obj_page.hasClass('current') ? ' class="current"' : '';

			int_index++;
			obj_page.data('pos', int_pIndex);
			if (! obj_page.data('clone')) {
				str_pages += '<li' + str_class + ' data-slide="' + int_index + '">Seite ' + int_index +'</li>';
			}
		});

		obj_footerPager.empty().append(str_pages);
		
		if (obj_pages.length > 1) {
			if (! bool_useSwipe) obj_switchButtons.show();
		}
	}

	
	function slideEnd(obj_pPages, obj_pNewActivePage, obj_pPagesContainer, bool_pJumpBack) {
		var obj_footerPager = $('#footer ul.page-indicator');
      
    obj_pPages.removeClass('active')
		obj_pNewActivePage.addClass('active');

    if (bool_pJumpBack) {	
    	obj_pPagesContainer[0].style.webkitTransition = "none";
    	obj_pPagesContainer.css({
    		left: 0
    	});
    }
    
    obj_footerPager.find('li').removeClass('current');
    obj_footerPager.find('li:eq(' + obj_pNewActivePage.attr('data-pos') + ')').addClass('current');
	}
	
	
	function switchPage(int_pDirection, int_pMultiplicator) {
		var obj_pagesContainer = $('#pages'),
        obj_pages = $('> div.page', obj_pagesContainer),
				obj_activePage = obj_pagesContainer.find('div.active'),
				obj_newActivePage = $(),
				int_left = 0,
				bool_jumpBack = false
				bool_wait = false;
				
		function slideIpad() {
			obj_pagesContainer[0].style.webkitTransition = "left 0.55s ease-out";
			obj_pagesContainer[0].style.left = ((parseInt(obj_pagesContainer.css('left')) || 0) + parseInt(int_left)) + 'px';
			
			if (typeof (obj_callnbackFnt) !== 'undefined') {
				obj_pagesContainer[0].removeEventListener('webkitTransitionEnd',  obj_callnbackFnt, true);	
			}
			
			obj_callnbackFnt = function() {
				slideEnd(obj_pages, obj_newActivePage, obj_pagesContainer, bool_jumpBack);
			};

			obj_pagesContainer[0].addEventListener('webkitTransitionEnd',  obj_callnbackFnt, true);	
			bool_whilePageSwitch = false;
		}
		
		
		if (! bool_whilePageSwitch) {
			bool_whilePageSwitch = true;
			
			if (bool_useSwipe) {
				int_left = 947 * int_pDirection;
			}
			else {
			 int_left = int_scrollOffset * int_pDirection;
			}
		
		  if (int_pDirection === 1) {
		    if (obj_activePage.attr('data-pos') == 0) {
		      obj_activePage = obj_activePage.data('cloned');
          obj_newActivePage = obj_activePage.prev('div.page');
          
          if (bool_useSwipe) {
          	obj_pagesContainer[0].style.webkitTransition = "none";
	          obj_pagesContainer.css({
	            left: ((obj_activePage.index() * 947) * -1) + 'px'
	          });
	          
	          bool_wait = true;
          }
          else {
          	obj_pagesContainer.css({
            	left: ((parseInt(obj_activePage.css('left')) - obj_pages.eq(0).offset().left) * -1) + 'px'
	          });
          }
        }
        else {
        	if (typeof(int_pMultiplicator) === 'number') {
	        	obj_newActivePage = obj_pagesContainer.find('div[data-pos=' + (parseInt(obj_activePage.attr('data-pos')) - int_pMultiplicator) + ']');
	        }
	        else {
	        	obj_newActivePage = obj_activePage.prev('div.page');
	        }
        }
      }
      else {
        if (typeof(int_pMultiplicator) === 'number') {
        	obj_newActivePage = obj_pagesContainer.find('div[data-pos=' + (parseInt(obj_activePage.attr('data-pos')) + int_pMultiplicator) + ']');
        }
        else {
        	obj_newActivePage = obj_activePage.next('div.page');
        }

        if (obj_newActivePage.data('clone')) {
          obj_newActivePage = obj_newActivePage.data('clone');
          bool_jumpBack = true;
        }
      }

			if (bool_useSwipe) {
				if (bool_wait) {
					window.setTimeout(function() {
						slideIpad();
					}, 0);
				}
				else {
					slideIpad();
				}
			}
			else {
				obj_pagesContainer.animate({
					left: '+=' + parseInt(int_left) * (typeof(int_pMultiplicator) === 'number' ? int_pMultiplicator : 1)
				}, {
					duration: 550,
					easing: 'easeInOutQuint',
					complete: function() {
						var obj_footerPager = $('#footer ul.page-indicator');
	          
	          obj_pages.removeClass('active')
						obj_newActivePage.addClass('active');
	          
	          if (bool_jumpBack) {
	          	obj_pagesContainer.css({
	          		left: 0
	          	});
	          }
	          
	          obj_footerPager.find('li').removeClass('current');
	          obj_footerPager.find('li:eq(' + obj_newActivePage.attr('data-pos') + ')').addClass('current');
						bool_whilePageSwitch = false;
						
					}
				});
			}			
		}
	}
	
	
	function openLightbox(obj_pLightbox) {
		var obj_closeButton = obj_pLightbox.find('a.close'),
				int_duration = !bool_useSwipe ? 300 : 0;
		
		obj_pLightbox.fadeIn(int_duration);
		
		obj_closeButton.one('click', function(obj_pEvent) {
			obj_pLightbox.fadeOut(int_duration, function() {
				obj_pLightbox.find('fieldset.thanks, fieldset.error').remove();
				obj_pLightbox.find('fieldset, p.alternate').show();
			});
			$('#header a').removeClass('active');	
			
			obj_pEvent.preventDefault();
		});	
		
		$(window).one('keydown', function(obj_pEvent) {
			if (obj_pEvent.which === 27) {
				obj_closeButton.trigger('click');
			}
		});
		
		obj_pLightbox.on('click', function(obj_pEvent) {
			if ($(obj_pEvent.target).hasClass('lightbox')) {
				obj_pLightbox.off('click');
				obj_closeButton.trigger('click');
			}
		})
	}
	
	
	function contactForm(obj_pForm) {
		obj_pForm.find('fieldset.error').remove();
		obj_pForm.removeClass('validationError');
		
		placeholder(obj_pForm.find('input[type!=radio], textarea'));
		
		obj_pForm.on('submit', function(obj_pEvent) {
			$.ajax({
				type: obj_pForm.attr('method'),
				url: obj_pForm.attr('action'),
				data: obj_pForm.serialize(),
				dataType: 'json',
				success: function(obj_pJSON) {
					var obj_json = typeof(obj_pJSON) === 'string' ? $.parseJSON(obj_pJSON): obj_pJSON,
							str_content = '';
					
					if (obj_json.code === "200") {
						obj_pForm.find('fieldset, p.alternate').hide();
						str_content = '<fieldset class="thanks"><h3>Vielen Dank für Ihre Nachricht.</h3><p>Wir werden uns sobald uns möglich mit Ihnen in Verbindung setzten.</p></fieldset>';
					}
					else {
						str_content = '<fieldset class="error"><h3>Fehler beim Versenden!</h3><p>Leider waren nicht alle Pflichtfelder ausgefüllt.</p></fieldset>';
						obj_pForm.addClass('validationError');
					}
					
					obj_pForm.prepend(str_content);
				}
			});
			
			obj_pEvent.preventDefault();
		});
	}
	
	
	function loadImage(obj_pImage) {
		obj_pImage.attr('src', obj_pImage.attr('data-src'));
	}
	
	
	// Init app and bind event listeners
	$(function() {
		var obj_switchButtons = $('#page-switch a'),
				obj_pageConatiner = $('#pages'),
				obj_startListPoints = $('div.start-page ul.menu li > span');
		
		// Detect swipe gestures
		bool_useSwipe = swipeGestureAvailable();
		if (bool_useSwipe) {
			$('body')[0].addEventListener("touchmove", function(obj_pEvent) {
				obj_pEvent.preventDefault();
			}, false);
		}
		
    // Set pager positions
		layoutPages(true);
		
		// Create pager
		createPageSwitcher();
		if (! bool_useSwipe) {
			$('#footer ul.page-indicator li').bind('click', function() {
				var obj_entry = $(this),
						obj_currentSlide = $('#footer ul.page-indicator li.current'),
						int_direction = 0,
						int_offset = 0;
				
				if (parseInt(obj_currentSlide.attr('data-slide')) - parseInt(obj_entry.attr('data-slide')) !== 0) {			
					if (parseInt(obj_currentSlide.attr('data-slide')) - parseInt(obj_entry.attr('data-slide')) >= 1) {
						int_direction = 1; 
						int_offset = parseInt(obj_currentSlide.attr('data-slide')) - parseInt(obj_entry.attr('data-slide'));
					}
					else if (parseInt(obj_currentSlide.attr('data-slide')) - parseInt(obj_entry.attr('data-slide')) <= -1) {
						int_direction = -1;
						int_offset = (parseInt(obj_currentSlide.attr('data-slide')) - parseInt(obj_entry.attr('data-slide'))) * -1;
					}
					
					switchPage(int_direction, int_offset);
				}
			});
		}
		
		
		if (typeof(bool_ie7) !== 'undefined') {
			$('#footer ul.page-indicator li').text('');
		}
		
		// Load images
		$('img.lazyload').each(function() {
			loadImage($(this));
		});
		
		
		// Bind swipe events on page for mobile touch devices
		if (bool_useSwipe) {
			obj_pageConatiner.multiswipe({
				swipeLeft: function() {
					switchPage(-1);
				},
				
				swipeRight: function() {
					switchPage(1);
				}
			});
		}		
		
		// Bind click events on page buttons for desktop browsers		
		obj_switchButtons.on('click', function(obj_pEvent) {
			var int_direction = $(this).hasClass('prev') ? 1 : -1;
			
			switchPage(int_direction);
			
			obj_pEvent.preventDefault();
		});
		
		
		// Bind »contact« and »impress« menu links. Open lightbox.
		$('#header a').on('click', function(obj_pEvent) {
			var obj_link = $(this),
					obj_lightbox = $(obj_link.attr('href'));
			
			obj_link.addClass('active');
			openLightbox(obj_lightbox);
			
			obj_pEvent.preventDefault();
		});
		
		
		// Handle contact form
		$('#contact form').each(function() {
			contactForm($(this));
		});
		
		
		// rearange page elements after window resize
		int_startWindowSizeWidth = $(window).width();
		$(window).on('resize', function() {
			if (! bool_useSwipe) {
				layoutPages($(window).width() - int_startWindowSizeWidth);
				int_startWindowSizeWidth = $(window).width();
			}
		});
		
		// Handle start list points
		if (bool_useSwipe) {
			obj_startListPoints.on('click', function(obj_pEvent) {
				obj_pEvent.preventDefault();
	
				obj_startListPoints.removeClass('hover');
				$(this).addClass('hover');
			});
		}
		else {
			obj_startListPoints.on('mouseover', function(obj_pEvent) {
				obj_pEvent.preventDefault();
	
				obj_startListPoints.removeClass('hover');
				$(this).addClass('hover');
			});
			obj_startListPoints.on('mouseout', function(obj_pEvent) {
				obj_pEvent.preventDefault();
	
				$(this).removeClass('hover');
			});
		}
	});
})(jQuery);
