/* Author: Dion Snoeijen
   Purpose: 
   - Header system
   - Response
   - Device detection
*/
var isiPhone = function() {
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

var isiPad = function() {
	return (
		(navigator.platform.indexOf("iPad") != -1)
	);
}

var isBrowserFromHell = function() {
	if($.browser.msie) {
		if($.browser.version < 9) {return true;}
	}
	return false;
}

// -------------------------
//	Prevent webkit layerX and LayerY problems
// -------------------------
(function(){
    // remove layerX and layerY
    var all = $.event.props,
        len = all.length,
        res = [];
    while (len--) {
      var el = all[len];
      if (el != 'layerX' && el != 'layerY') res.push(el);
    }
    $.event.props = res;
}());

var components = {
	$prevButton: $('<a href="#" class="header_prev"></a>'),
	$nextButton: $('<a href="#" class="header_next"></a>')
}

var ieHeader = {
	init: function(elements) {
		// -------------------------
		//	Select the stuff from the DOM
		// -------------------------
		var $header = $('header');
		var $headerSlideContainer = $('<div id="slide_container"></div>');
		var $textContainer = $('<div id="text_container"></div>').css({'position':'absolute'});
		
		// -------------------------
		//	Insert into the header
		// -------------------------
		$header.append($headerSlideContainer);
		
		// -------------------------
		//	What have we here...
		// -------------------------
		this.totalImages = 0;
		var paths = new Array();
		for(var i in elements) {
			if(elements[i].ieAlternative != "") {
				paths.push(new Array(
					elements[i].ieAlternative, //0
					elements[i].headText, //1
					elements[i].subText, //2
					elements[i].background, //3
					elements[i].textColor, //4
					elements[i].href //5
				));
				ieHeader.totalImages++;
			}
		}
		
		// -------------------------
		//	Variable initialization
		// -------------------------
		var firstRun = true;
		var firstCycle = true;
		var selector = 0;
		var preloadCounter = 0;
		var images = new Array();
		var $header = $('header');
		
		for(var i in paths) {
			var image = new Image();
			images.push(image);
			image.onload = function() {
				preloadCounter++;
				
				// -------------------------
				//	All images loaded...
				// -------------------------
				if(preloadCounter == ieHeader.totalImages) {
					
					// -------------------------
					//	Ad images to container and initialize values
					// -------------------------
					for(var j in images) {
						var $image = $(images[j]);
						var $imageContainer = $('<div></div>').css({
							'width':images[j].width,
							'height':images[j].height
						});
						var $textContainer = $('<div class="ie_header_text_container"></div>').css({
							'z-index':'100',
							'position':'absolute',
							'top':'140px',
							'left':'-440px'
						});
						// -------------------------
						//	Black or White? (text)
						// -------------------------
						var $headTitle = $('<h1 class="header_title">' + paths[j][1] + '</h1>');
						var $subText = $('<p class="header_text">' + paths[j][2] + '</p>').css({'marginTop':'200'});
						if(paths[j][5] != '') {
							var $button = $('<a href="' + paths[j][5] + '"><img src="/images/images_style/btn-ie-header-watch-case.png" alt="watch case" /></a>').css({
								'position':'absolute',
								'top':'270'
							});
						}
						$textContainer.append($headTitle);
						$textContainer.append($subText);
						if(paths[j][5] != '') {$textContainer.append($button);}
						$imageContainer.prepend($textContainer);
						$imageContainer.prepend($image);
						$headerSlideContainer.append($imageContainer);
						$image.attr({
							'width':images[j].width,
							'height':images[j].height
						});
						$image.css({
							'position':'absolute',
							'top':'0',
							'z-index':'1',
							'margin-left':-(images[j].width / 2)
						});
					}
					var customCounter = 0;
					$headerSlideContainer.cycle({
						timeout: 6000,
						before:function(d, i, o, n) {
							
							// -------------------------
							//	Black or White? (text)
							// -------------------------
							$header.removeClass('black');
							if(paths[customCounter][4] == 'black') {$header.addClass('black');}
							// -------------------------
							//	Give the body a correct bg
							// -------------------------
							$('body').css({
								'background' : 'url("' + paths[customCounter][3] + '") repeat-x'
							});
							
							// -------------------------
							//	Text container
							// -------------------------
							customCounter++;
							if(customCounter == o.slideCount) {
								customCounter = 0;
							}
						},
						speed:0
					});
					// -------------------------
					//	Position the container
					// -------------------------
					$headerSlideContainer.css({
						'position':'absolute', 
						'top':'0', 
						'left':'50%', 
						'z-index':'1', 
						'width':'100%', 
						'height':'533px'
					});
				}
			}
			// -------------------------
			//	Get the image to load
			// -------------------------
			image.src = paths[i][0];
		}
	}
}

var header = {
	init: function(elements) {
		this.$header = $('header');
		if(!isiPhone()) {
			this.elements = elements;
			this.loadHeader();
			
			// -------------------------
			//	Keep an eye on the size of the window
			// -------------------------
			$(window).resize(header.responsive);
			header.checkInitialSize();
			
			// -------------------------
			//	If we have more than one header, create next and prev controls.
			//	Also automatically advance to next slide with interval.
			// -------------------------
			this.createNextPrev();
			this.setTheInterval();
		}
	},
	clearTheInterval: function() {clearInterval(header.interval);},
	setTheInterval: function() {
		if(header.elements[1]) {
			header.interval = setInterval(header.nextHeading, 10000);
		}
	},
	checkInitialSize: function() {
		// -------------------------
		//	If the windowsize starts smaller initialize with responsiveness.
		// -------------------------
		if($(window).width() < 960) {
			this.startResponsive = true;
		}
 	},
	loadHeader: function() {
		this.loadedLayers = new Array();
		this.layerSettings = new Object();
		this.headText = this.elements[this.headerSelector].headText;
		this.ieAlternative = this.elements[this.headerSelector].ieAlternative;
		this.subText = this.elements[this.headerSelector].subText;
		this.background = this.elements[this.headerSelector].background;
		this.layerSettings = this.elements[this.headerSelector].layers;
		this.textColor = this.elements[this.headerSelector].textColor;
		
		this.setBackground();
	},
	$headerSiteWidth: $('.header_site_width'),
	$headerMenu: $('#main_menu'),
	$socialMenu: $('#social_menu'),
	$makeItHappen: $('<div id="make_it_happen"></div>'),
	responsive: function() {
		this.windowWidth = $(window).width();
		this.windowHeight = $(window).height();

		// -------------------------
		//	Next Prev Buttons
		// -------------------------
		if(this.windowWidth < 1180) {
			var newPos = ((1180 - this.windowWidth) / 2) - 100;
			if(newPos < 40) {
				header.$prevButton.css({'left':newPos});
				header.$nextButton.css({'right':newPos});
			}
		}
		if(this.windowWidth < 960) {header.$headerSiteWidth.css({'width':this.windowWidth});
		}
		
		// -------------------------
		//	Move text and centralizables to center
		// -------------------------
		if(this.windowWidth < 1080) {
			var difference = 1080 - this.windowWidth;
			var newLeftMargin = header.$headTitleLeftMargin + difference;
			var checkPos = newLeftMargin + (header.$headTitle.width() / 2);

			if(checkPos < 20 || this.startResponsive) {
				header.$headTitle.css({'margin-left':newLeftMargin});
				header.$subText.css({'margin-left':newLeftMargin});
				if(this.readMoreButtonAvailable) {
					header.$readMore.css({'margin-left':newLeftMargin});
				}
			}
			for(var i in header.loadedLayers) {
				if(header.layerSettings[i].centralize) {
					var $cen = $(header.loadedLayers[i]);
					var cen = header.loadedLayers[i];
					var cenLeftMargin = header.layerSettings[i].offsetX - (cen.width / 2);
					var newCenLeftMargin = cenLeftMargin - (difference / 2);
					$cen.css({'margin-left':newCenLeftMargin});
				}
			}
		}
		
		// -------------------------
		//	Remove Sacrificable items
		// -------------------------
		if(this.windowWidth < 800) {
			for(var i in header.loadedLayers) {
				if(header.layerSettings[i].sacrifice) {
					var $sac = $(header.loadedLayers[i]);
					$sac.fadeOut('fast');
				}
			}
		} else {
			for(var i in header.loadedLayers) {
				if(header.layerSettings[i].sacrifice) {
					var $sac = $(header.loadedLayers[i]);
					$sac.fadeIn('fast');
				}
			}
		}
		
		// -------------------------
		//	Move Header Menu
		// -------------------------
		var topVal = header.$headerMenu.css('top');
		var top = parseInt(topVal.substring(0, topVal.length-2));
		if(this.windowWidth < 830) {
			if(top == 0) {
				header.$headerMenu.stop();
				header.$headerMenu.animate({
					'top':60, 
					'right':0
				}, 500);
			}
		} else {
			if(top == 60) {
				header.$headerMenu.stop();
				header.$headerMenu.animate({
					'top':0, 
					'right':200
				}, 500);
			}
		}
		
		this.startResponsive = false;
	},
	sacrificeItems:false,
	headerSelector: 0,
	loadCounter: 0,
	$prevButton: $('<a href="#" class="header_prev"></a>'),
	$nextButton: $('<a href="#" class="header_next"></a>'),
	setBackground: function() {
		$('body').css({
			'background' : 'url("' + this.background + '") repeat-x'
		});
		
		// -------------------------
		//	Retreive the height of the bg image for the preloader graphic
		// -------------------------
		var bg = new Image();
		bg.onload = function() {
			header.bgHeight = this.height;
		}
		bg.src = this.background;
		
		this.loadLayers();
	},
	createNextPrev: function() {
		// -------------------------
		//	There are multiple headers, create next and prev buttons
		// -------------------------
		if(header.elements[1]) {
			this.$header.children(":first").append(this.$prevButton);
			this.$prevButton.delay(1000).animate({'opacity':'1'});
			this.$prevButton.click(function(e) {
				e.preventDefault();
				header.prevHeading();
				header.clearTheInterval();
				header.setTheInterval();
			});
			this.$header.children(":first").append(this.$nextButton);
			this.$nextButton.delay(1000).animate({'opacity':'1'});
			this.$nextButton.click(function(e) {
				e.preventDefault();
				header.nextHeading();
				header.clearTheInterval();
				header.setTheInterval();
			});
		}
	},
	loadLayers: function() {
		// -------------------------
		//	Load images
		// -------------------------
		this.loadCounter = 0;
		for(var i in this.layerSettings) {
			var img = new Image();
			this.loadedLayers.push(img);
			img.onload = function() {
				if(header.loadCounter == header.layerSettings.length - 1) {
					// -------------------------
					//	Done preloading, build them layers
					// -------------------------
					header.buildLayers();
				}
				header.loadCounter++;
			}
			img.src = this.layerSettings[i].src;
			// -------------------------
			//	Disable image dragging in header
			// -------------------------
			$(img).mousedown(function(e) {e.preventDefault();});
		}
	},
	buildLayers: function() {$('.preload_layer').animate({'opacity':'0'}, 500, function() {$(this).remove();});
		
		// -------------------------
		//	Are we starting responsive??
		// -------------------------
		var initialOpacity = 0;
		if(this.startResponsive) {
			initialOpacity = 1;
		} else {
		}
		
		// -------------------------
		//	Black or White? (text)
		// -------------------------
		this.$header.removeClass('black');
		if(this.textColor == 'black') {this.$header.addClass('black');}
		
		// -------------------------
		//	Create make it happen
		// -------------------------
		this.$headerSiteWidth.append(this.$makeItHappen);
		
		// -------------------------
		//	Create a new title
		// -------------------------
		this.$headTitle = $('<h1 class="header_title">' + this.headText + '</h1>');
		this.$header.append(this.$headTitle);
		this.$headTitleLeftMargin = -((this.$headTitle.width() / 2) + 250);
		this.$headTitle.css({
			'top':140, 
			'left':'50%', 
			'margin-left':this.$headTitleLeftMargin, 
			'opacity':initialOpacity
		});

		// -------------------------
		//	Create a subtext
		// -------------------------
		this.$subText = $('<p class="header_text">' + this.subText + '</p>');
		this.$header.append(this.$subText);
		this.$subText.css({
			'top':160 + this.$headTitle.height(), 
			'left':'50%', 
			'margin-left':-((this.$subText.width() / 2) + 250), 
			'opacity':initialOpacity
		});
		
		// -------------------------
		//	Create the "read more" button
		// -------------------------
		this.readMoreButtonAvailable = this.elements[this.headerSelector].href != '' ? true : false;
		if(this.readMoreButtonAvailable) {
			this.$readMore = $('<a href="' + this.elements[this.headerSelector].href + '" class="read_more">Bekijk deze case</a>');
			this.$header.append(this.$readMore);
			this.$readMore.css({
				'top': 190 + this.$headTitle.height() + this.$subText.height(), 
				'left':'50%', 
				'margin-left':-((this.$readMore.width() / 2) + 380), 
				'opacity':initialOpacity
			});
		}
		
		// -------------------------
		//	Show title, subtext and read more
		// -------------------------
		if(!this.startResponsive) {
			this.$headTitle.delay(1000).animate({'opacity':1}, 1000);
			this.$subText.delay(1600).animate({'opacity':1}, 1000);
			if(this.readMoreButtonAvailable) {
				this.$readMore.delay(2200).animate({'opacity':1}, 1000);
			}
		}
		
		for(var i in this.loadedLayers) {
			// -------------------------
			//	One jqo and one "normal" object
			// -------------------------
			var $element = $(this.loadedLayers[i]);
			var element = this.loadedLayers[i];
			
			// -------------------------
			//	Set initail position, scale and alpha
			// -------------------------
			var targetWidth = element.width;
			var targetHeight = element.height;
			var initialWidth = this.layerSettings[i].initialScale * element.width;
			var initialHeight = this.layerSettings[i].initialScale * element.height;
			var initialPosX = -(element.width / 2) + (this.layerSettings[i].offsetX + ((element.width - initialWidth) / 2));
			
			if(this.layerSettings[i].tweenType == 'fromRight') {
				initialPosX = $(window).width();
			}
			
			var initialPosY = this.layerSettings[i].offsetY + (element.height - initialHeight) / 2;
			var opacity = 1;
			if(this.layerSettings[i].tweenType == 'fadeIn' && !this.startResponsive) {
				opacity = 0;
			}
			
			// -------------------------
			//	Execute positioning
			// -------------------------
			$element.css({
				'position':'absolute',
				'left':'50%',
				'z-index':'1',
				'width':initialWidth,
				'height':initialHeight,
				'margin-left':initialPosX, 
				'top':initialPosY,
				'opacity':opacity,
				'display':'block'
			});
			
			// -------------------------
			//	Add element to header
			// -------------------------
			this.$header.append($element);
			
			// -------------------------
			//	Initial transition to target settings
			// -------------------------
			if(!this.startResponsive) {
				$element.delay(this.layerSettings[i].delay).animate({
					'width':targetWidth,
					'height':targetHeight,
					'opacity':1,
					'margin-left':-(targetWidth/ 2) + (this.layerSettings[i].offsetX),
					'top':this.layerSettings[i].offsetY
				}, this.layerSettings[i].transitionTime, this.layerSettings[i].ease);
			}
		}
		
		this.responsive();
	},
	nextHeading: function() {
		// -------------------------
		//	Infinitely loopable headings
		// -------------------------
		if(header.headerSelector < (header.elements.length - 1)) {
			header.headerSelector++;
			header.transition();
		} else {
			header.headerSelector = 0;
			header.transition();
		}
	},
	prevHeading: function() {
		// -------------------------
		//	Infinitely loopable headings
		// -------------------------
		if(header.headerSelector > 0) {
			header.headerSelector--;
			header.transition();
		} else {
			header.headerSelector = header.elements.length - 1;
			header.transition();
		}
	},
	transition: function() {
		// -------------------------
		//	Prelosd layer graphic
		// -------------------------
		var	$preloadLayer = $('<div class="preload_layer"><h1></h1></div>').css({
			'opacity':'0', 
			'background':'url("' + this.background + '")',
			'height':this.bgHeight
		});
		this.$header.append($preloadLayer);
		
		// -------------------------
		//	
		// -------------------------
		$('.header_title').animate({'opacity':0}, 500, function() {$(this).remove();});
		
		$('.header_text').animate({'opacity':0}, 500, function() {$(this).remove();});
		
		$('.read_more').animate({'opacity':0}, 500, function() {$(this).remove()});
		
		$preloadLayer.delay(500).animate({'opacity':'1'}, 500, function() {
		});
		
		for(var i in this.loadedLayers) {
			var $element = $(this.loadedLayers[i]);
			$element.delay(1000).animate({'opacity':0}, 500, function() {
				$(this).remove();
				if(i == (header.loadedLayers.length - 1)) {header.loadHeader();}
			});
		}
	}
}

var menuResponsive = {
	init:function() {
		this.windowWidth = $(window).width();
		$(window).resize(menuResponsive.responsive);
		this.checkInitialSize();
	},
	checkInitialSize:function() {
		if(this.windowWidth < 960) {this.responsive();}
	},
	$contentMenu:$('div#main nav#content_menu ul li'),
	responsive:function() {
		this.windowWidth = $(window).width();
		
		if(this.windowWidth < 960 && menuResponsive.normalMenu) {menuResponsive.adaptMenu();}
		if(this.windowWidth > 960 && !menuResponsive.normalMenu) {menuResponsive.normalizeMenu();}
	},
	normalMenu:true,
	normalizeMenu:function() {
		this.normalMenu = true;
		this.$contentMenu.removeClass('adapt');
	},
	adaptMenu:function() {
		this.normalMenu = false;
		this.$contentMenu.addClass('adapt');
	}
}

var iPhoneExeptions = {
	$headerObject:$('header div.header_site_width'),
	$headerMenu:$('header div.header_site_width nav#main_menu'),
	menuChanged:false,
	init:function() {
		var objectsWidth = $(window).width();
		this.$headerObject.css({
			'height':'100px',
			'background':'#000000',
			'width':objectsWidth
		});
		var mainLogo = $('img.main_logo');
		var socialMenu = $('nav#social_menu');
		
		mainLogo.width(300);
		mainLogo.css({
			'marginTop':'8px', 
			'marginLeft':'8px'
		});
		socialMenu.hide();
		
		this.$headerMenu.hide();
		
		if(!iPhoneExeptions.menuChanged) {
			var headerMenuItems = $('nav#main_menu ul');
			var contentMenuItems = $('nav#content_menu ul');
			var newHtml = '<ul>' + headerMenuItems.html() + contentMenuItems.html() + '</ul>';
			$('div#main nav#content_menu').html(newHtml);
			$('div#main nav#content_menu ul li').addClass('adapt');
			iPhoneExeptions.menuChanged = true;
		}
		
		$('div.footer_component:eq(0)').hide();
		$('div.footer_component:eq(1)').css({'border':'0'});
		$('div.footer_component:eq(2)').hide();
		$('div.footer_component:eq(3)').hide();
		
		$('footer').before('<a href="#" id="back_to_top">Back to top</a>');
		$('a#back_to_top').click(function(e) {
			e.preventDefault();
			$.scrollTo(0);
		});
	}
}

var iPadExeptions = {
	$header:$('header'),
	init:function() {
		var windowWidth = $(window).width();
	}
}

window.onorientationchange = function() {
	var orientation = window.orientation;
	switch(orientation) {
		case 0:
			$(document).trigger("orientationChange");
			$(document).trigger("orientationPortrait");
			break; 
		case 90:
			$(document).trigger("orientationChange");	
			$(document).trigger("orientationLandscapeLeft");
			break;
		case -90:
			$(document).trigger("orientationChange");
			$(document).trigger("orientationLandscapeRight");
			break;
	}
}

var initializeSite = function(width) {
	if(width < 960) {
		$('footer, div#main, div.header_site_width').css({'width':width});
	} else {
		$('footer, div#main, div.header_site_width').css({'width':960});
		$('footer').css({
			'marginTop':'80px', 
			'marginRight':'auto', 
			'marginLeft':'auto', 
			'marginBottom':'30px'
		});
	}
	$('div#main').show();
	$('footer').show();
}

var isResizing = {
	resizing:false,
	time:function() {
		if(!isResizing.resizing) {isResizing.setToTrue();}
		if(this.timer) {clearTimeout(this.timer);}
		this.timer = setTimeout(isResizing.setToFalse, 1000);
	},
	setToTrue:function() {
		isResizing.resizing = true;
		// -------------------------
		//	No header transitions during resize
		// -------------------------
		if(!isBrowserFromHell) {header.clearTheInterval();}
	},
	setToFalse:function() {
		isResizing.resizing = false;
		// -------------------------
		//	Done resizing, get the transitions back in
		// -------------------------
		if(!isBrowserFromHell && !isiPhone()) {header.setTheInterval();}
	}
}

$(document).ready(function() {
	if(isiPhone()) {iPhoneExeptions.init();}
	if(isiPad) {iPadExeptions.init();}
	
	$(window).resize(isResizing.time);
	var windowWidth = $(window).width();
	initializeSite(windowWidth);
	
	$(document).bind("orientationChange", function() {
		initializeSite(windowWidth);
		if(isiPhone()) {iPhoneExeptions.init();}
		if(isiPad) {iPadExeptions.init();}
	});
	menuResponsive.init();
});
