/* Author: Mattias Bohez (Walking Men)
*/

/* 

	Main navigation 

*/
(function($,window,document,undefined){
$(function(){
	
// set variables	
var container = $('#sw-primaryNav'),
	timeout = null,
	elements = container.children('li'),
	dropdowns = [],
	current = -1;
	

elements.each(
	function(i,li) {
		var dropdown = $(this).find('.dropDown');
		matchHeight(dropdown);
		// store the dropdown element for easy access later on
		dropdowns.push(dropdown);
		
		// add a hover state
		$(this).children('a').bind('mouseenter', function(event){
			//var el = Event.element(event);
			hover(i);
		});
	}
);
container.bind('mouseleave', function(event){
	//var el = Event.element(event);
	unhover();
});

function open(index){
	var oThis = this;
	$(elements[index]).addClass('sfhover');
	$('video').css('visibility','hidden');
	// set classname for drop
	current = index;
}
function close(index){
	$(elements[current]).removeClass('sfhover');
	$('video').css('visibility','visible');
	current = -1;
}
function hover(index){
	// clear a possible running timeout
	try{clearTimeout(timeout)}catch(e){}
	// if the called dropdown is different than the opened one
	if(index != current) {
		
		if(current != -1){
			// hide current dropdown
			close(current);
		}
		
		// show called dropdown
		open(index);
	}
}
function unhover(){
	try{clearTimeout(timeout)}catch(e){}
	
	timeout = setTimeout(function(){
		close(current);
	},350);
}
function matchHeight(parent){
	var boxes = parent.find('ul[class^=grid_]');
	
	var length = boxes.length;
	var i = 0;
	
	while ( i < length) {
		var list = [];
		var mybox = $(boxes[i])
		var top = mybox.offset().top;
		var height = 0;
		
		do{
			list.push(boxes[i]);
			var myHeight = $(boxes[i]).height();
			height = (height > myHeight)? height : myHeight;
			i++;
		}
		while(i < length && top == mybox.offset().top );
		
		if(list.length > 1){
			for(var j=0;j < list.length;j++){
				list[j].style.height = height+'px';
			}
		}
		
	};
}


});
})(window.jQuery,window,document);


/*
	Ads teaser

*/

(function($,window,document,undefined){$(function() {
		$('.sibos-ads').each(function(){
			var ads = [],
				current = 0,
				container = $(this);
			
			function nextAd(){
				current = (current+1)%ads.length;
				container.html(ads[current]);
			}
			$.ajax(container.data('xml'),{
				dataType: 'xml',
				success: function(data){
					$(data).find('ad').each(function(){
						var item = $(this),
							image = item.children('img');
							
						var a = $('<a></a>');
							a.attr('href',item.attr('href'));
							
						var img = $('<img/>');
							img.attr('src',image.attr('src'));
							img.attr('alt',image.attr('alt'));
						a.html(img);
						ads.push(a);
					});
					$.shuffle(ads); // randomize the array
					nextAd();
					setInterval(nextAd,5000);
				}
			});
		});
	});})(jQuery,window,document);



/*
	
	Quotes teaser
	
*/
(function($,window,document,undefined){$(function() {
	$('.sibos-quotes').each(function(){
		var quotes = [],
			current = 0,
			container = $(this)
		
		function nextQuote(){
			current = (current+1)%quotes.length;
			container.html(quotes[current]);
		}
		$.ajax(container.data('xml'),{
			dataType: 'xml',
			success: function(data){
				$(data).find('quota').each(function(){
					quotes.push($(this).text())
				});
				$.shuffle(quotes); // randomize the array
				nextQuote();
				setInterval(nextQuote,7000);
			}
		});
	});
});})(jQuery,window,document);


/*
	
	Tags teaser
	
*/
(function($,window,document,undefined){$(function() {
		$('.sibos-tags').each(function(){
			var container = $(this);
			
			$.ajax(container.data('xml'),{
				dataType: 'xml',
				success: function(data){
					var str = ""					
					$(data).find('tag').each(function(){
						var myData = $(this);
						str += '<a href="'+myData.attr('href')+'" target="'+myData.attr('target')+'" class="size-'+myData.attr('weight')+'">'+myData.text()+'</a> '
					});
					container.html(str)
				}
			});
		});
	});})(jQuery,window,document);


/* 
	Video player
*/
(function($,window,document,undefined){$(function() {
	$('.sibos-videoTeaser').each(function(){
		var container= $(this),
			next = container.find('.sibos-videoTeaser-next'),
			prev = container.find('.sibos-videoTeaser-prev'),
			navWrap = container.find('.sibos-videoTeaser-nav'),
			nav = navWrap.find('ul'),
			video = container.find('.sibos-videoTeaser-video');
			
			video[0].id = "video"+new Date().getTime();
			
		// setup next and previous buttons
		next.bind('click', function() {
		    navWrap.animate({scrollLeft: navWrap.scrollLeft()+264},'fast');
		    return false;
		});
		prev.bind('click', function() {
		    navWrap.animate({scrollLeft: navWrap.scrollLeft()-264},'fast');
		    return false;
		});
		
		
		$.ajax(container.data('xml'),{
			dataType: 'xml',
			success: function(data){
				// setup data
				
				$(data).find('item').each(function(){
					var myItem = $(this),
						video_url= myItem.children('video_url').text(),
						title= myItem.children('title').text(),
						tagline= myItem.children('tagline').text(),
						image= myItem.children('image').text()
						
					var li = $('<li></li>');
						li.addClass('media');
						li.addClass('sibos-videoTeaser-item');
					
					var img = $('<img/>');
						img.addClass('img');
						img.attr('width','47');
						img.attr('height','35');
						img[0].src = "images/"+image;
					
					var bd = $('<div></div>').html('<strong>'+title+'</strong>'+tagline);
						bd.addClass('bd')
					
					li.click(function(){
						jwplayer(video[0]).load('video/'+video_url);
						jwplayer(video[0]).play();
		    			return false;
					});
					li.append(img);
					li.append(bd);
					nav.prepend(li);
				});
				
				// fix slider width
				var li = nav.find('li:last-child');
				nav.width(li[0].offsetLeft + li.outerWidth()+100); //+100 for ie9 wrapping problem
				
				// setup player and load the first movie
				jwplayer(video[0]).setup({
					flashplayer: "res/jwplayer/player.swf",
					stretching:"uniform",
					file: "video/"+$(data).find('item:last-child').find('video_url').text(),
					image: "images/"+$(data).find('item:last-child').find('image').text(),
					height: 265,
					width: '100%',
					skin: "res/jwplayer/skins/glow/glow.xml"
				});
			}
		});
		
	})
	
	
});})(jQuery,window,document);







/*
	Quotes teaser
*/
(function($,window,document,undefined){$(function() {
	function bubbleSort(array,attr) {
		for (var i = array.length - 1; i >= 0;  i--) {
			for (var j = 0; j < i; j++) {
				if (array[j+1][attr] > array[j][attr]) {
					var temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
	      		}
	   		}
		}
		return array;
	}
/*
	news teaser
*/
	$('.sibos-news').each(function(){
		var container = $(this),
			news = [],
			listWrap = container.find('.sibos-news-list'),
			list = listWrap.find('ul'),
			article = container.find('.sibos-news-item');
			
		function loadArticle(i){
			var ct =  "<img class=\"left\" src=\"images/"+news[i].picture+"\">";
				ct += "<a href=\""+news[i].link+"\" target=\""+news[i].target+"\" class=\"title\">"+news[i].title+"</a>";
				ct += "<div class=\"date\">"+news[i].date+"</div>";
				ct += "<div class=\"slug\">"+news[i].slug+"</div>";
				ct += "<div class=\"html_content\">"+news[i].html_content+"</div>";
				ct += "<a href=\""+news[i].link+"\" target=\""+news[i].target+"\" class=\"more\">Read more</a>";
			article.html(ct);
		}
		
		$.ajax(container.data('xml'),{
			dataType: 'xml',
			success: function(data){
				$(data).find('item').each(function(){
					var item = $(this);
					news.push({
						sort: parseInt(item.children('sort').text(),10),
						feature: item.children('feature').text() === "yes",
						date: item.children('date').text(),
						title: item.children('title').text(),
						slug: item.children('slug').text(),
						picture: item.children('picture').text(),
						html_content: item.children('html_content').text(),
						link: item.children('link').text(),
						target: item.children('target').text()
					});
				});
				news = bubbleSort(news,'sort');
				
				var hasLoaded = false;
				$.each( news, function(i,el){
					if(news[i].feature){
						loadArticle(i);
						hasLoaded = true;
					}else{
						var li = $('<li></li>'),
							a = $('<a></a>');
							a.addClass('media');
							a.attr('href',news[i].link);
							a.attr('target',news[i].target);
						var ct =  "<img class=\"img\" src=\"images/"+news[i].picture+"\" width=\"80\">";
							ct += "<span class=\"bd\">";
							ct += "<span class=\"title\">"+news[i].title+"</span>";
							ct += "<span class=\"html_content\">"+news[i].slug+"</span>";
							ct += "<span class=\"more\">Read more</a>";
							ct += "</div>";
						/*li.click(function(){
							loadArticle(i);
							return false;
						});*/
						a.html(ct);
						li.append(a);
						list.append(li);
					}
				});
				if(!hasLoaded) loadArticle(0);
				
				listWrap.jScrollPane({
					showArrows: true,
					verticalArrowPositions: 'split'
				});
				var jScrollapi = listWrap.data('jsp');
				setInterval(function(){
					jScrollapi.reinitialise();
				},1313)
			}
		});
	});
	
});})(jQuery,window,document);



/*
	Events teaser
*/
(function($,window,document,undefined){$(function() {
	$(".sibos-highlight-events").each(function(){
		var container=$(this),
			contentWrap = container.find('.sibos-highlight-content'),
			content = contentWrap.find('ul'),
			next = container.find('.sibos-highlight-next'),
			prev = container.find('.sibos-highlight-prev'),
			nav = container.find('.sibos-highlight-nav').find('ul'),
			contentList = [],
			navlist = [],
			current = 0,
			timeout = null;
		
		function goToItem(index){
			navlist[index].addClass('current').siblings().removeClass('current');
			var speed=(index === 0 && current ===navlist.length-1)? 0 : 500;
			content.animate({left:-contentList[index].position().left},speed);
			//get next element
			current = index;
			try{clearTimeout(timeout)}catch(e){}
			timeout = setTimeout(function(){
				goToItem((index+1)%contentList.length)
			},6000)
		}
		next.click(function(){
			goToItem((current+1)%contentList.length);
		    return false;
		})
		prev.click(function(){
			goToItem((contentList.length+current-1)%contentList.length);
		    return false;
		})
			
		$.ajax(container.data('xml'),{
			dataType: 'xml',
			success: function(data){
				var items = $(data).find('item');
				items.each(function(index){
					// get data from node
					var item = $(this),
						title = item.children('title').text(),
						slug = item.children('slug').text(),
						picture = item.children('picture').text(),
						link = item.children('link').text();
					
					var contentLi = $('<li></li>');
						contentLi.width(99.9/items.length+'%');
					var contentA = $('<a></a>');
						contentA.attr('href',link);
					var contentStr = '<img class="picture" src="images/'+picture+'">';
						contentStr += '<span class="title">'+title+'</span>';
						contentStr += '<span class="slug">'+slug+'</span>';
					contentA.html(contentStr);
					contentLi.html(contentA);
					
					var navLi =  $('<li></li>');
						navLi.width(99.9/items.length+'%');
					navLi.html(index+1);
					
					navLi.click(function(){
						goToItem(index);
		    			return false;
					});
					
					content.width(items.length*100+'%');
					content.append(contentLi);
					nav.append(navLi);
					contentList.push(contentLi);
					navlist.push(navLi);
					
				});
				goToItem(Math.floor(Math.random()*items.length));
			}
		});
		
	})

});})(jQuery,window,document);






/*
	Twitter teaser
*/
(function($,window,document,undefined){$(function() {
	$(".sibos-highlight-twitter").each(function(){
		var container=$(this),
			contentWrap = container.find('.sibos-highlight-content'),
			next = container.find('.sibos-highlight-next'),
			prev = container.find('.sibos-highlight-prev'),
			nav = container.find('.sibos-highlight-nav').find('ul'),
			contentList = [],
			navlist = [],
			current = 0,
			timeout = null;
		
		function goToItem(index){
			navlist[index].addClass('current').siblings().removeClass('current');
			var speed=(index === 0 && current ===navlist.length-1)? 0 : 500;
			contentWrap.find('ul').animate({left:-$(contentList[index]).position().left},speed);
			//get next element
			current = index;
			try{clearTimeout(timeout)}catch(e){}
			timeout = setTimeout(function(){
				contentList = contentWrap.find('.jta-tweet-list-item');
				goToItem((index+1)%contentList.length)
			},10000)
		}
		next.click(function(){
			contentList = contentWrap.find('.jta-tweet-list-item');
			goToItem((current+1)%contentList.length);
		    return false;
		})
		prev.click(function(){
			contentList = contentWrap.find('.jta-tweet-list-item');
			goToItem((contentList.length+current-1)%contentList.length);
		    return false;
		})
		contentWrap.jTweetsAnywhere({
		    searchParams: ['q=%23sibos'],
		    count: 4,
		    showTweetFeed: {
		        expandHovercards: true,
		        showSource: true,
		        paging:{
		        	mode: "none"
		        }
		    }
		});
		var livenodelist=contentWrap[0].getElementsByTagName('li');
		var mytimeout = setInterval(function(){
			if(livenodelist.length > 1){
				clearInterval(mytimeout);
				contentList = contentWrap.find('.jta-tweet-list-item');
				contentList.each(function(index){
					var navLi =  $('<li></li>');
						navLi.width(100/contentList.length+'%');
						navLi.html(index+1);
						navLi.click(function(){
							goToItem(index);
		   					 return false;
						});
					nav.append(navLi);
					navlist.push(navLi);
				})
				goToItem(0);
			}
		},100);
	})

});})(jQuery,window,document);
