var styleCheckbox, styleSelect;
var magnificPopupGalleryDefaultSettings = function () {
	this.type = "image";
	this.closeBtnInside = false;
	this.items = [];
	// this.image = {
	// 	markup: '<div class="mfp-figure">'+
	// 				'<div class="mfp-close"></div>'+
	// 				'<figure>'+
	// 					'<div class="mfp-img"></div>'+
	// 					'<figcaption>'+
	// 						'<div class="mfp-bottom-bar">'+
	// 							'<div class="mfp-title"></div>'+
	// 							'<div class="mfp-counter"></div>'+
	// 						'</div>'+
	// 					'</figcaption>'+
	// 				'</figure>'+
	// 				'<span class="slide left mfp-prevent-close"></span>'+
	// 				'<span class="slide right mfp-prevent-close"></span>'+
	// 			'</div>'+
	// 			'<div class="my-thumbnails">'+
	// 				'<img src="uploads/user/_processed_/csm_Reception_Desk_Palmberg_c84167f7f2.jpg" style="max-width:185px;max-height:105px;">'+
	// 			'</div>'
	// };
	this.gallery = {
		enabled: true,
		arrowMarkup: '<span class="slide %dir%"></span>',
		tCounter: '%curr%/%total%'
	};
};

if( document.referrer && ! ( new RegExp('^(https?:\/\/)?[^\/]*pcon-planner\.com\/', 'i') ).test( document.referrer ) ) {
	var date = new Date();
	var expires = new Date();
	expires.setTime(expires.getTime()+(365*24*60*60*1000));
	document.cookie = "referer_url="+document.referrer+"; expires="+expires.toGMTString()+"; path=/";
	document.cookie = "referer_time="+(date.getTime()/1000)+"; expires="+expires.toGMTString()+"; path=/";
}

$(function() {

	// Anker Smooth Scrolling
	$(document).on('click.pcon.anker', 'a[href*=#]:not([href=#])', function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var target = $(this.hash);
			target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
			if (target.length) {
				$('html,body').animate({
					scrollTop: target.offset().top
				}, 1000);
				return false;
			}
		}

		// var target = $(this.href);
		// if( target.length ) {
			// event.preventDefault();
			// $('html, body').animate({
				// scrollTop: target.offset().top
			// }, 1000);
		// }
	});

	// Create ToTop Link
	// if( ! $('#totoplink').size() ) {
	// 	$('body').append('<a href="#totop" id="totoplink" class="link-totop"></a>');
	// }

	// ToTop If Event Scroll
	$(document).on('scroll.pcon.totop', function() {

		var minScrollTop = 300,
			totoplink = $('#totoplink');

		if( $(window).scrollTop() >= minScrollTop ) {
			totoplink.fadeIn();
		} else {
			totoplink.fadeOut();
		}
	});
	var toTopPosition = function() {

		var margin, indicator;

		if( $(window).width() < 600 ) {
			margin = 15;
			indicator = '.section-footer';
		} else {
			margin = 23;
			indicator = '.section-contact';
			if( ! $(indicator).size() ) { //FIxMe
				indicator = '.section-footer';
			}
		}

		var pos = $(window).height() - ( $(indicator).offset().top - $(window).scrollTop() );
		if( pos < 0)
			pos = 0;
		$('.link-totop').css('bottom', ( pos + margin ) );
	};
	$(document).ready( function() {
		toTopPosition();
	});
	$(window).scroll( function() {
		toTopPosition();
	});
	$(window).resize( function() {
		toTopPosition();
	});

	// Menu
	$(document).ready( function() {
		$('#header').removeClass('no-js');
		$('#header').addClass('js-active');
		$('.section-header-menu nav .sub').addClass('close');
		$('.section-header-menu2').addClass('close');
	});
	$(document).on('click', '.section-header-menu nav .sub .expand', function() {
		$(this).parent().toggleClass('close');
	});
	$(document).on('click', '.navButton', function() {
		$('.section-header-menu2').toggleClass('close');
	});
	$(document).on('click', '.search .search-icon', function() {
		$('.section-header-menu2').addClass('search-open');
		$(this).parents('.search').find('input[type="text"]').select();
		return false;
		// var elem = this;
		// if( $(elem).parents('.search').is('.close') ) {
		// 	$(elem).parents('.search').addClass('transition');
		// 	$(elem).parents('.search').removeClass('close');
		// 	$(elem).parents('.search').find('input[type="text"]').select();
		// 	$(document).on('click.pcon.search.open', function(event) {
		// 		if( ! ( $(event.target).parents('.search').size() || $(event.target).is('.search') ) ) {
		// 			$(document).off('click.pcon.search.open');
		// 			$(elem).parents('.search').addClass('close');
		// 		}
		// 	});
		// 	return false;
		// }
	});
	$(document).on('click', '.search .close', function() {
		$('.section-header-menu2').removeClass('search-open');
	});

	// Responsive Menu Open/Close
	$(document).on('click.pcon.menu', '.showHideMenu', function() {
		$(this).parent().children('ul').slideToggle({
			complete: function() {
				if( $(this).is(':hidden') ) {
					$(this).attr('style', '');
				}
			}
		});
	});

	// Menu Search Open/Close
	$(document).on('click.pcon.search', '.section-header .search .icon', function() {
		var elem = this;
		$(elem).parents('.search').addClass('open');
		$(elem).parents('.search').find('input[type="text"]').select();
		$(document).on('click.pcon.search.open', function(event) {
			if( ! ( $(event.target).parents('.search').size() || $(event.target).is('.search') ) ) {
				$(document).off('click.pcon.search.open');
				$(elem).parents('.search').removeClass('open');
			}
		});
	});
	$(document).on('click.pcon.search', '.search.desktop svg', function() {
		console.log('click');
		var t = $(this);
		if( ! $(this).parent().is('.open') ) {
			$(this).parent().addClass('open');
			$(this).parent().children('input[type="text"]')
				.show()
				.animate({width: '160px'}, 500, function() {
					$(this).focus();
					$(document).on('click.pcon.search.open', function(e) {
						if( ! ( $(e.target).parents('.search').size() || $(e.target).is('.search') ) ) {
							$(document).off('click.pcon.search.open');

							t.parent().children('input[type="text"]')
								.animate({width: '0px'}, 500, function() {
									$(this).hide();
									$(this).parent().removeClass('open');
								});
						}
					});
				});
		}
	});

	$.fn.checkVisibility = function( fromWindow ) {
		var whichVisibleRegion = 40;

		whichVisibleRegion = whichVisibleRegion / 100;

		$(this).each( function() {
			if( fromWindow ) {
				if (
					(
						// Nach unten scrollen
						$(window).scrollTop() + ( $(window).height() * ( 1 - whichVisibleRegion ) ) > $(this).offset().top
					) && (
						// Nach ober scrollen
						$(window).scrollTop() + ( $(window).height() * ( whichVisibleRegion ) ) < $(this).offset().top + $(this).outerHeight()
					)
				) {
					$(this).addClass('visible');
				}
			} else {
				if(
					(
						$(window).scrollTop() + $(window).height() > $(this).offset().top + ( $(this).outerHeight() * whichVisibleRegion )
					) && (
						$(window).scrollTop() < $(this).offset().top + $(this).outerHeight() - ( $(this).outerHeight() * whichVisibleRegion )
					)
				) {
					$(this).addClass('visible');
				}
			}
		});
	};

	$(document).ready( function() {
		$('.csc-textpic-imagewrap, figure').checkVisibility();
		$('.table.table-listing .table-row').checkVisibility(true);
	});
	$(window).on( 'scroll', function() {
		$('.csc-textpic-imagewrap, figure').checkVisibility();
		$('.table.table-listing .table-row').checkVisibility(true);
	});

	// Slide In by Scroll
	var slideIn = function() {
		var selector = $('.slideIn');
		var visibleArea = 40 / 100;

		selector.each( function() {
			var cssBefore = { position: 'relative', opacity: '0' };
			var cssAfter = { opacity: '1' };

			var distance = $(this).data('slideinDistance') || 100;
			var direction = $(this).data('slideinDirection') || "";
			var width = $(this).data('slideinWidth') || 0;
			if( $(window).width() >= width ) {
				if( direction == 'top' ) {
					cssBefore[direction] = '-'+distance+'px';
					cssAfter[direction] = '0';
				}
				if( direction == 'bottom' ) {
					cssBefore[direction] = '-'+distance+'px';
					cssAfter[direction] = '0';
				}
				if( direction == 'right' ) {
					cssBefore[direction] = '-'+distance+'px';
					cssAfter[direction] = '0';
				}
				if( direction == 'left' ) {
					cssBefore[direction] = '-'+distance+'px';
					cssAfter[direction] = '0';
				}
			}

			if( ! $(this).is('.slideInReady') && ! $(this).is('.slideInFinished') ) {
				$(this).parents('section').css('overflow', 'hidden'); // FixMe
				$(this).addClass('slideInReady').css(cssBefore);
			}
			if( $(this).is('.slideInReady') && ! $(this).is('.slideInFinished') ) {
				if(
					(
						$(window).scrollTop() + $(window).height() > $(this).offset().top + ( $(this).outerHeight() * visibleArea ) + (
							direction == 'top' ? -1 * distance : direction == 'bottom' ? distance : 0
						)
					) && (
						$(window).scrollTop() < $(this).offset().top + $(this).outerHeight() - ( $(this).outerHeight() * visibleArea ) + (
							direction == 'top' ? distance : direction == 'bottom' ? -1 * distance : 0
						)
					)
				) {
					$(this).addClass('slideInFinished').animate(cssAfter);
				}
			}
		});
	};
	$(window).load(function() {
		$(window).on('scroll.pcon.slideIn', function() {
			slideIn();
		});
		slideIn();
	});

	var sliderGetPicture = function( event ) {
		$('.cycle-slideshow .item').each( function() {
			var item = this;
			$(this).find('[data-src]').each(function() {
				var width = $(window).width();
				if( width >= $(this).data('min') && width <= $(this).data('max') ) {
					console.log('src: '+$(this).data('src') );
					$(item).css( 'backgroundImage', 'url("' + $(this).data('src')+ '")' );
				}
			});
		});
	};
	$(document).on('ready', sliderGetPicture);
	$(window).on('resize', sliderGetPicture);

	// Checkbox
	styleCheckbox = function() {
		$('input[type="checkbox"]').each( function() {
			if( ! $(this).next('span.checkbox').size() ) {

				var $checkboxOrg = $(this),
					$checkboxStyled = $('<span class="checkbox"></span>');

				if( $checkboxOrg.is(':checked') ) {
					$checkboxStyled.addClass('checked');
				}

				$checkboxStyled.click( function() {
					if( $(this).hasClass('checked') ) {
						$checkboxOrg.prop( "checked", true ).change();
					} else {
						$checkboxOrg.prop( "checked", false ).change();
					}
				});

				$checkboxOrg.change( function() {
					if( $(this).is(':checked') ) {
						$checkboxStyled.addClass('checked');
					} else {
						$checkboxStyled.removeClass('checked');
					}
				});

				$checkboxOrg.hide();
				$(this).after($checkboxStyled);
			}
		});
	};
	$(document).ready( function() {
		styleCheckbox();
	});

	// Selectbox
	$.widget( "custom.selectmenu", $.ui.selectmenu, {
		_renderItem: function( ul, item ) {
			var li = $( "<li>" );

			$( "<span>", {
				text: item.label,
				style: item.element.attr( "data-style" ),
				"class": item.element.attr( "data-class" )
			}).appendTo( li );

			return li.appendTo( ul );
		}
	});
	styleSelect = function() {
		$(':not(.ui-front) select').each( function() {
			var select = this;
			var position = {
				my: "left top",
				at: "left bottom",
				collision: "flip"
			};
			if( $(this).parents('.language').size() ) {
				position = {
					my: "right top",
					at: "right bottom",
					collision: "flip"
				};
			}
			$(select).wrap( '<div class="ui-front" style="position:relative;"></div>' );
			$(select).selectmenu({
				position: position,
				change: function( event, ui ) {
					$(event.target).change();
				},
				open: function( event, ui ) {
					$(this).next('.ui-selectmenu-button').focus();
				}
			});
		});
	};
	$(document).ready( function() {
		styleSelect();
	});

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

		$('a[href$=".jpg"].lightbox, a[href$=".jpeg"].lightbox, a[href$=".png"].lightbox, a[href$=".gif"].lightbox, a[href$=".svg"].lightbox').magnificPopup({type:'image'});

		$('a.lightbox:not([href$=".jpg"]):not([href$=".jpeg"]):not([href$=".png"]):not([href$=".gif"]):not([href$=".svg"])').magnificPopup({
			type:'iframe',
			closeBtnInside: false,
			fixedContentPos: true,
			// mainClass: 'mfp-no-margins mfp-with-zoom',
			iframe: {
				verticalFit: true
			},
			callbacks: {
				elementParse: function(item) {
					console.log(item);
					console.log('rel',item.el.prop('rel'));
				},
				markupParse: function(template, values, item) {
					var width = parseInt(item.el.prop('rel').replace(/.*;[\s]*width=([0-9]*).*/i,'$1'));
					var height = parseInt(item.el.prop('rel').replace(/.*;[\s]*height=([0-9]*).*/i,'$1'));
					console.log('width: ', item.el.prop('rel').replace(/.*;[\s]*width=([0-9]*).*/i,'$1'), 'height: ', item.el.prop('rel').replace(/.*;[\s]*height=([0-9]*).*/i,'$1'));
					console.log('width: ', width, 'height: ', height);
					if( width > 0 && height > 0 ) {
						template.css({
							width: width,
							maxWidth: '100%',
							height: height,
							maxHeight: '100%',
							position: 'relative',
							paddingTop: 0,
							margin: '0 auto'
						});
					}
					// console.log('mfp-content', template.parents('.mfp-content').size() );
					// template.find('.mfp-iframe').css('border','3px solid red');
					// template.find('.mfp-iframe').css('maxWidth','100px');
					// console.log('Parsing:', template, values, item);



					// template.
				},
			}
		});
	});

	// Clipboard
	$(document).on('click', '.clipboard', function(e) {
		e.preventDefault();
		$(this)[0].select();
	});

	// Box verlinken
	// $(document).on('click', '.csc-box-shadow .csc-textpic-image a', function( event ) {
	// 	console.log("'click', '.csc-box-shadow .csc-textpic-image a'");
	// 	event.stopPropagation();
	// 	return true;
	// });
	// $(document).on('click', '.csc-box-shadow', function() {
	// 	// console.log("'click', '.csc-box-shadow'");
	// 	// event.stopPropagation();
	// 	$(this).find('.csc-textpic-image a').trigger('click');
	// 	// return false;
	// });
	// $(document).on('click', '.csc-box-shadow .csc-textpic-image a', function( event ) {
	// 	event.stopPropagation();
	// 	return true;
	// });

	// Init Skrollr
	// var s = skrollr.init({
	// 	render: function(data) {
	// 		//Debugging - Log the current scroll position.
	// 		//console.log(data.curTop);
	// 	}
	// // });
	// skrollr.init({
	// 	forceHeight: false
	// });

	// $('.video').magnificPopup({
	//   type: 'iframe',


	//   iframe: {
	//     patterns: {
	//       dailymotion: {

	//         index: 'dailymotion.com',

	//         id: function(url) {
	//             var m = url.match(/^.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/);
	//             if (m !== null) {
	//                 if(m[4] !== undefined) {

	//                     return m[4];
	//                 }
	//                 return m[2];
	//             }
	//             return null;
	//         },

	//         src: 'http://www.dailymotion.com/embed/video/%id%'

	//       }
	//     }
	//   }



	//   iframe: {
	//     markup: '<div class="mfp-iframe-scaler">'+
	//               '<div class="mfp-close"></div>'+
	//               '<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>'+
	//             '</div>', // HTML markup of popup, `mfp-close` will be replaced by the close button

	//     patterns: {
	//       youtube: {
	//         index: 'youtube.com/', // String that detects type of video (in this case YouTube). Simply via url.indexOf(index).

	//         id: 'v=', // String that splits URL in a two parts, second part should be %id%
	//         // Or null - full URL will be returned
	//         // Or a function that should return %id%, for example:
	//         // id: function(url) { return 'parsed id'; }

	//         src: '//www.youtube.com/embed/%id%?autoplay=1' // URL that will be set as a source for iframe.
	//       },
	//       vimeo: {
	//         index: 'vimeo.com/',
	//         id: '/',
	//         src: '//player.vimeo.com/video/%id%?autoplay=1'
	//       },
	//       gmaps: {
	//         index: '//maps.google.',
	//         src: '%id%&output=embed'
	//       }

	//       // you may add here more sources

	//     },

	//     srcAction: 'iframe_src', // Templating object key. First part defines CSS selector, second attribute. "iframe_src" means: find "iframe" and set attribute "src".
	//   }

	// });
});

// window.onload = function() {
	// $('figure.monitor').each( function() {
		// console.log( $(window).scrollTop() + $(window).height()+' >>> '+$(this).offset().top );
		// console.log( $(window).scrollTop() + $(window).height()+' >>> '+$(this).position().top );
		// console.log( $(window).scrollTop() + $(window).height()+' >>> '+$('figure.monitor').offset().top );
		// console.log( $(window).scrollTop() + $(window).height()+' >>> '+$('figure.monitor').position().top );
	// });
// };

// $(window).load(function() {
	// // Scroll Window Nav
	// var pconScrollTop = $(window).scrollTop();
	// var pconScrollTimeout = undefined;
	// $(document).on('mousewheel DOMMouseScroll', function() {

		// console.log( 'scroll.pcon.window ' + pconScrollTop + '|'+$(window).scrollTop() );

		// if( pconScrollTop != $(window).scrollTop() ) {

			// if( pconScrollTop < $(window).scrollTop() ) {

				// clearTimeout(pconScrollTimeout);

				// $('header').animate({
					// marginTop: '-' + $('header').outerHeight()
				// },750, function() {
					// pconScrollTop = $(window).scrollTop();
				// });

				// pconScrollTimeout = setTimeout(function() {
					// $('header').stop(true,true).animate({
						// marginTop: '0'
					// },750, function() {
						// pconScrollTop = $(window).scrollTop();
					// });
				// },500);

			// }
			// pconScrollTop = $(window).scrollTop();
		// }
	// });
// });

// var start = ( new Date() ).getTime();
// $(function() {
	// console.log( ( start - ( new Date() ).getTime() ) + ' ms $(function()' );
// });
// window.onload = function() {
	// console.log( ( start - ( new Date() ).getTime() ) + ' ms window.onload' );
// };
// $(document).ready(function() {
	// console.log( ( start - ( new Date() ).getTime() ) + ' ms $(document).ready' );
// });
// $(window).ready(function() {
	// console.log( ( start - ( new Date() ).getTime() ) + ' ms $(window).ready' );
// });
// $(window).load(function() {
	// console.log( ( start - ( new Date() ).getTime() ) + ' ms $(window).load' );
// });

// setTimeout( function() {
// 	skrollr.init({
// 		forceHeight: false
// 	});
// }, 4000);
