// Very simple IE8 and older IndexOf implementation - it doesn't cover all functionality.
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(obj, start) {
		for (var i = (start || 0), j = this.length; i < j; i++) {
			if (this[i] === obj) { return i; }
		}
		return -1;
	}
}

function openWindowCenter(url, width, height, scroll, status, resizable) {
	if(!status)
		status = 'no';

	if(!resizable)
		resizable = 'no';
		
	if(!scroll)
		scroll = 'no';

	var intTop = ((screen.Height / 2) - (height / 2));
	var intLeft = ((screen.Width / 2) - (width / 2));

	window.open(url, '', 'width='+ width +', height='+ height +', resizable='+ resizable +', location=no, titlebar=no, toolbar=no, menubar=no, directories=no, channelmode=no,  scrollbars='+ scroll +', status='+ status +', top='+ intTop +', left='+ intLeft +'');
}

$(function(){
	// Go to cases top link
	$('h2.intro').mouseenter(function() {
		$(this).find("em").stop(true, true).slideUp();
		$(this).find("a").stop(true, true).slideDown();
	}).mouseleave(function() {
		$(this).find("em").stop(true, true).slideDown();
		$(this).find("a").stop(true, true).slideUp();
	}).mouseup(function() {
		$('html, body').animate({ scrollTop: $("#cases-container").offset().top }, 'slow');
	});
	

	// Place background
	var feature_margin_to_content = 20;
	var feature_max_height = 610;
	var feature_size_factor = 1.2;
	var feature_parallax_factor = 3.5;

	var feature_height = 0;
	var feature_image_offset = 0;
	var feature_init_content_offset = ( $('#feature').length != 0 ) ? $('.first').offset().top : 0;
	function setFeature(fheight, scrollTop, foffset) {
		// Calculate and set feature heights
		if ( $('#feature').length != 0 ) {
			var new_height = fheight - scrollTop;
			if (new_height < 0) $('#feature-images').hide();
			else {
				$('#feature-images').show().height(new_height);
				// Do a bit of parallax thingy
				$('#feature-images .images.selected').height(new_height).css('background-position-y', -scrollTop/feature_parallax_factor - foffset);
				
				$('#feature-images .images.selected div').each(function(index) {
					var left = Number($(this).attr("data-pos-left"));
					$(this).css('left', Math.round(($(window).width() - 950) / 2 + left));
					$(this).height(Math.max(0, new_height-Number($(this).attr('data-pos-top'))));
					
					var factor = Number($(this).attr("data-parallaxfactor"));
					var postop = -scrollTop/factor + Number($(this).attr("data-pos-top"));
					$(this).css('top', Math.ceil(postop));
					$(this).height(new_height - postop);
				});
			}
		}
	}
	function initFeature() {
		if ( $('#feature').length != 0 ) {
			feature_height = Math.floor(Math.max( Math.min( feature_max_height, $(window).height()/feature_size_factor ), 3 + $('#feature').offset().top + parseInt($('#feature .hideoverflow').css('padding-top'), 10) + $('#feature .hideoverflow').height()));
			feature_image_offset = Math.floor((feature_max_height - feature_height) / 2);
			
			// Position overlays
			$('#feature-images .images.selected div').each(function(index) {
				// Set data-pos attributes to the css specified
				var pos = $(this).position();
				if ($(this).attr("data-height") == undefined) $(this).attr("data-height", $(this).height());
				if ($(this).attr("data-pos-left") == undefined) $(this).attr("data-pos-left", pos.left);
				
				// Set top position
				switch ($(this).attr("data-positionfrom")) {
					case "bottom":
						$(this).attr("data-pos-top", feature_height - $(this).attr("data-height"));
						break;
						
					default:
						if ($(this).attr("data-pos-top") == undefined) $(this).attr("data-pos-top", pos.top);				
				}
				
				// Set background to full feature height and reposition image, so we can use background pos to animate element instead of div pos
				//var h = $(this).height();
				//var top = Number($(this).attr("data-pos-top"));
				//$(this).height(feature_height).css('top', 0).css('background-position-y', top);
				
				// Place overlay
				$(this).css('left', ($(window).width() - 950) / 2 + Number($(this).attr("data-pos-left")));
				//$(this).css('top', feature_height - Number($(this).attr("data-height")));
				
				//$(this).css('left', ($(window).width() - 950) / 2 + left);
			});


			var scrollTop = $(window).scrollTop();
			setFeature(feature_height, scrollTop, feature_image_offset);
			

			// Move content below feature
			$('.first').css('margin-top', feature_height - feature_init_content_offset + feature_margin_to_content + 40);
		}
	}
	initFeature();
	$(window).resize(function() {
		initFeature();
	});
	// ===== FEATURE SLIDESHOW =====
	// Finds all .slideshow and creates a slideshow of their images
	// If the attribute autoplay="2000ms", it starts as a slideshow with 2000ms between slides
	var feature_timer = 0;
	var feature_slideshowDefaultTimer = 4000;
	var feature_headline_height = $('#feature .headlines div').height();
	function featureAnimateBetween(curr,next) {
		// check if current needs to animate anything away
		$($('#feature .images')[curr]).find('div').fadeOut('fast');
		$($('#feature .images')[next]).find('div').fadeIn('slow');
		//$($('#feature .images')[next]).find('div').show();
		
		// check if next needs to animate anything in - if so, hide it so we can animate it in when the slide is showing
		/*var $overlays = $($('#feature .images')[next]).find('div');
		if( $overlays.length > 0 ) {
			$($overlays).each( function( index ) {
				$(this).css('top', Number($(this).attr("data-pos-top"))+100 ).show().height( Number($(this).attr("data-height"))-100 ).animate({
					top: $(this).attr("data-pos-top"),
					height: $(this).attr("data-height")
				  }, 600, function() {
				    // Animation complete.
				  });
			});
		}
		*/
		$($('#feature .images')[next]).addClass("selected");
		
		initFeature(); // make sure elements are correctly placed since last showing

		if (next > curr) {
			$($('#feature .images')[next]).stop(true, true).hide().fadeIn('slow', function() {
				$($('#feature .images')[curr]).hide();
				$($('#feature .images')[curr]).removeClass("selected");
				
				// check if new current needs to animate anything in
			});
		
		} else if (next < curr) {
			$($('#feature .images')[next]).show();
			$($('#feature .images')[curr]).stop(true, true).fadeOut('slow', function() {
				$($('#feature .images')[curr]).hide();
				$($('#feature .images')[curr]).removeClass("selected");
				
				// check if new current needs to animate anything in
			});
		}
		setFeature(feature_height, $(window).scrollTop(), feature_image_offset);
		
		$('#feature .headlines').stop(true, true).animate( { top: -next*feature_headline_height }, 300);
		
		// Show marker for new image
		$('#feature ul').find('.selected').removeClass('selected');
		$($('#feature li').get(next)).addClass('selected');
	}
	function featurePlayNext() {
		// Find image showing
		var $this = $('#feature li');
		var curr = $($this).index( $(".selected") );
		var next = (curr+1 > $($this).length-1) ? 0 : curr+1;	
		
		featureAnimateBetween(curr,next); // Animate slides
		featureStartAutoplayIfEnabled(); // Set timer
	}
	function featureStartAutoplayIfEnabled(delayfactor) {
		if (delayfactor == undefined) {		
			delayfactor = 1;
		}
		var autoplay = slideshowGetAutoplay(0, "#feature");
		if ( autoplay != false ) {
			feature_timer = window.setTimeout(function() { featurePlayNext(); }, autoplay * delayfactor);
		}
	}
	// Make buttons clickable
	$('#feature li').mouseup( function() {
		// Clear autoplay
		window.clearTimeout( feature_timer );
		featureStartAutoplayIfEnabled(2); // Set loooong wait for autoplay
		
		// Animate slides
		var curr = $('#feature li').index( $(".selected") );
		var next = $(this).index();
		
		featureAnimateBetween(curr,next);
	});
	// Setup slideshows
	$('#feature').each( function(index) {
		featureStartAutoplayIfEnabled();
	});
	// ====== END FEATURE SLIDESHOW ======

	
	// Background effect
	var agent = navigator.userAgent.toLowerCase();
	//agent = "iphone";
	if ((agent.indexOf("iphone") == -1) &&
     	(agent.indexOf("ipod") == -1) &&
     	(agent.indexOf("ipad") == -1) &&
     	(agent.indexOf("android") == -1)) {

		// Make background parallax
		if ( $('#feature').length != 0 ) {
			$('#feature-images').css('position', 'fixed');
		}

		// Insert parallax background
		if ( $('#parallax').length != 0) {
			var bgimages = "";
			for (var i=1; i<=8; i++) bgimages += '<img src="../images/bg-roger-black-'+i+'.png" style="top: ' + 0 + 'px;' + (($('#feature').length == 0) ? '' : ' z-index: 2;') + '" />';
			$('#parallax').append( bgimages );
		}
		
		// Remove background image
		$('body').css('background-image', 'none');
	
		$(window).scroll(function() {
			var scrollTop = $(window).scrollTop();
			setFeature(feature_height, scrollTop, feature_image_offset);
			
			$("#parallax img").css('top', function(index) {
				var h = 237; // Height of parallax elements
				var y = Math.round( -scrollTop / (index + 3)*1.7 );
				var ny = $(window).height() + (y % ($(window).height() + h + h));
				// do some stuff to get it to start at the top and only let half of them to appear at the bottom
				ny = (y > -h)  ? ny - $(window).height() : (index % 2 == 1) ? -h : ny + h;
							
				return ny;
			});
		});
	}



	// hide bottom logo if top logo is visible
	function showOrHideBottomLogo() {
		if ($('.intro.logo').length != 0) {
			var y1 = $('h1').offset().top + $('h1').height(); // Bottom of top logo
			var y2 = $('.intro.logo').offset().top; // Top of bottom logo
			if (y2-y1 < $(window).height()) $('.intro.logo').css('background-image', 'none');
		}
	}
	showOrHideBottomLogo();
	

	// ===== INLINE SLIDESHOW =====
	// Finds all .slideshow and creates a slideshow of their images
	// If the attribute autoplay="2000ms", it starts as a slideshow with 2000ms between slides
	var slideshowTimers = [];
	var slideshowDefaultTimer = 4000;
	function slideshowPlayNext(index) {
		// Find image showing
		var $this = $('.slideshow').get(index);
		var curr = $($this).find('.selected').index();
		var next = (curr+1 > $($this).find('li').length-1) ? 0 : curr+1;
		
		// Show marker for new iamge
		$($this).find('.selected').removeClass('selected');
		var $nli = $($this).find('li').get(next);
		$($nli).addClass('selected');
		
		// Animate slides
		$($this).find('.images').stop(true, true).animate( { top: -next*487 }, 300);
		
		// Set timer
		slideshowAutoplay(index)
	}
	function slideshowGetAutoplay(index, selector) {
		var $this = $(selector).get(index);
		var autoplay = $($this).attr("data-autoplay");
		if ( autoplay != undefined && autoplay != "false" && autoplay != "no") {
			if (autoplay.indexOf("ms") == autoplay.length-2) autoplay = autoplay.substr(0, autoplay.length-2)
			else if (isNaN(autoplay)) autoplay = slideshowDefaultTimer;
			autoplay = parseInt(autoplay, 10);
		} else autoplay = false;
		return autoplay;
	}
	function slideshowAutoplay(index) {
		var autoplay = slideshowGetAutoplay(index, '.slideshow');
		if ( autoplay != false ) {
			slideshowTimers[index] = window.setTimeout(function() { slideshowPlayNext(index); }, autoplay);
		}
	}
	// Setup slideshows
	$('.slideshow').each( function(index) {
		// Add hide overflow as IE6/7 fix
		$(this).append('<div class="hideoverflow" />');

		// Create navigation
		var imglength = $(this).find('img').length;
		var html = "<ul>";
		for (var i=0; i<imglength;i++) {
			html += '<li' + ((i==0) ? ' class="selected"' : '') + '>&nbsp;</li>';
		}
		html += "</ul>";
		$(this).prepend( html );

		// Move images into container div
		$(this).find(".hideoverflow").append('<div class="images" />');
		$(this).find('img').appendTo( $(this).find('.images') );

		// Start playing those that should be played
		slideshowAutoplay(index);
	});
	// Make buttons clickable
	$('.slideshow li').mouseup( function() {
		// Clear autoplay
		var index = $('.slideshow').index( $(this).parent().parent() );
		window.clearTimeout( slideshowTimers[index] );
		// Set loooong wait for autoplay
		var autoplay = slideshowGetAutoplay(index, '.slideshow');
		if ( autoplay != false ) {
			slideshowTimers[index] = window.setTimeout(function() { slideshowPlayNext(index); }, autoplay*6);
		}
		
		
		// Show marker for new image
		$(this).parent().find('.selected').removeClass('selected');
		$(this).addClass('selected');
		
		// Animate slides
		var next = $(this).index();
		$(this).parent().parent().find('.images').stop(true, true).animate( { top: -next*487 }, 300);
	});
	// ====== END SLIDESHOW ======


	var $container = $('#cases-container');

	$container.isotope({
		masonry: {
			columnWidth: 158
		},
		sortBy: 'date',
		getSortData: {
			date: function( $elem ) {
				var date = $elem.attr('data-date');
				return new Date(Date.parse(date));
			},
			alphabetical: function( $elem ) {
				var name = $elem.find('.name'),
					itemText = name.length ? name : $elem;
				return itemText.text();
			},
			ordered: function( $elem ) {
				return $elem.attr('data-id');
			},
			random: function( $elem ) {
				return $elem.attr('data-number');
			}
		}
	});


	var ajaxError = function(){
		//alert('Could not load cases...');
	};

	// dynamically load cases
	$.getJSON("../cases.json",
		{
			mode: "JSON"
		})
		.fail( ajaxError )
 		.done(function( data ){
 		
			// proceed only if we have data
			if ( !data || !data.length ) {
				ajaxError();
				return;
			}
		
			//noOfPages = data.xml.paging["@totalpages"];
			var items = [], categories = [], teasers = [];
			var noOfItems = 0;

			function parseObject(obj) {
				var id = (obj["@id"] != null) ? obj["@id"] : 0;
				//var navn = (obj.displayname["#cdata-section"] != null) ? obj.displayname["#cdata-section"] : "";
				//var blognavn = obj.subject["#cdata-section"];
				var caseurl = (obj.extrainfo != null) ? obj.extrainfo : "";
				var casedate = (obj.date != null) ? obj.date : "";
				var casename = (obj.displayname["#cdata-section"] != null) ? obj.displayname["#cdata-section"] : "";
				var casedescription = (obj.text["#cdata-section"] != null) ? obj.text["#cdata-section"] : "";
				var casecategories = (obj.subject["#cdata-section"] != null) ? obj.subject["#cdata-section"] : "";
				var thumbimage = (obj.mediaitems.media.thumb["#text"] != null) ? obj.mediaitems.media.thumb["#text"] : "";
				var largeimage = (obj.mediaitems.media.regular["#text"] != null) ? obj.mediaitems.media.regular["#text"] : "";

				// If no special thumb URL is defined, use the thumb image in the caseurl folder
				if (thumbimage == "") thumbimage = caseurl + "/thumb.jpg";

				// Return list item, which is appended to the HTML in another place // <img src="../images/transp.gif" /> // <img class="overlay" src="../images/thumb-overlay.png" />
				var thumbhtml = '<div class="' + casecategories + '" data-date="' + casedate + '" data-id="'+id+'"><img src="' + thumbimage + '" /><a href="' + caseurl + '"><img src="../images/transp.gif" /></a><p>' + ((casename == "") ?  '' : '<span>' + casename + '</span>') + '<img class="overlay" src="../images/thumb-overlay.png" /></p></div>';
				
				// Only create teaser for frontpage, if there is a large image defined
				if (largeimage != "") {
					// Return list item, which is appended to the HTML in another place
					var teaserhtml = '<div class="paragraph"><p>' + casedescription + '<br /><a href="' + caseurl + '">Læs mere</a></p><img src="' + largeimage + '" alt="' + casename + '" /></div>';
				} else {
					var teaserhtml = "";
				}
				
				return {thumb: thumbhtml, teaser: teaserhtml, categories: casecategories.split(" ")};
			}
			

			// Parse JSON
			if ($.isArray(data[0].xml.entries.entry)) {
				$.each(data[0].xml.entries.entry, function(key, val) {
					var obj = parseObject(val);
					items.push( obj.thumb );
					teasers.push( obj.teaser );
					
					// Add categories to list, if they don't exist 
					for (var j=0; j<obj.categories.length; j++) {
						if (categories.indexOf(obj.categories[j]) == -1) {
							categories.push(obj.categories[j]);
						}
					}
					noOfItems++;
				});
			} else {
				items.push( parseObject(data[0].xml.entries.entry) );
				noOfItems++;
			}

			var $items = $( items.join('') );
			if ($('#teasers').length != 0) $('#teasers').append( teasers.join('') );
			
			
			// Add categories to list
			var cathtml = "";
			for (var i=0; i<categories.length; i++) {
				cathtml += '<li><a href="#'+categories[i]+'" data-option-value=".'+categories[i]+'">'+categories[i].toLowerCase()+'</a></li>';
			}
			$('#filter').append( cathtml );

			var $optionSets = $('#options .option-set'),
					$optionLinks = $optionSets.find('a');

			$optionLinks.click(function(){
				var $this = $(this);
				// don't proceed if already selected
				if ( $this.hasClass('selected') ) {
					return false;
				}
				var $optionSet = $this.parents('.option-set');
				$optionSet.find('.selected').removeClass('selected');
				$this.addClass('selected');
	
				// make option object dynamically, i.e. { filter: '.my-filter-class' }
				var options = {},
					key = $optionSet.attr('data-option-key'),
					value = $this.attr('data-option-value');
				// parse 'false' as false boolean
				value = value === 'false' ? false : value;
				options[ key ] = value;
				if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
					// changes in layout modes need extra logic
					changeLayoutMode( $this, options )
				} else {
					// otherwise, apply new options
					$container.isotope( options );
				}
				
				return false;
			});
		

			// set random number for each item
			$items.each(function(){
				$(this).attr('data-number', ~~( Math.random() * 100 + 15 ));
			});
			
			$items.imagesLoaded(function(){
				//$sitesTitle.removeClass('loading').text('Sites using Isotope');
				$container.append( $items );
				$items.each(function(){
					var $this = $(this);
					var w = $this.find('img').width();
					var h = $this.find('img').height();
					
					// Width and height hack for IE7
					$this.width( w );
					$this.height( h );
					$this.find('a img').width( w );
					$this.find('a img').height( h );
					$this.find('img.overlay').width( w );
					$this.find('img.overlay').height( h );
				});
				
				// Add rollover to photos
				$("#cases-container a").mouseenter(function() {
					$(this).parent().find("p").stop(true, true).fadeIn("fast");
				}).mouseleave(function() {
					$(this).parent().find("p").stop(true, true).fadeOut();
				});
				
				$container.isotope( 'insert', $items );
			});
		}
	);
});

