var urlParams = {};
var mobile = false;
var showHidden = 0;

(function()
{
	var e, a = /\+/g, r = /([^&=]+)=?([^&]*)/g, d = function(s)
	{
		return decodeURIComponent(s.replace(a, " "));
	}, q = window.location.search.substring(1);

	while (e = r.exec(q))
	{
		urlParams[d(e[1])] = d(e[2]);
	}
})();

function initalize()
{
	$.ajaxSetup( {
		url : 'php/interface.php',
		type : 'POST',
		dataType : 'json'
	});

	if (urlParams['lang'] != "en")
	{
		$('#headerButtonCompany').html('Bedrijf');
		$('#headerButtonClients').html('Klanten');
		$('#headerButtonAwards').html('Awards');
		$('#headerButtonContact').html('Contact');
		$('#headerButtonjobs').html('Vacatures');
	}
	else
	{
		$("#header-language").addClass('nl');
	}
	
	
	if(urlParams['showHidden'] == 1)
	{
		showHidden = 1;
	}
		

	if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i)
			|| navigator.userAgent.match(/iPod/i))
	{
		mobile = true;
	}

	VideoJS.setupAllWhenReady();

	fetchSpecials();
	fetchNews();
	fetchProjects();

	$('#header-buttons a').click(function(event)
	{
		toggleSpecial(event);
	});
	

	$('#header-language').click(function(event)
										{
										
											if (urlParams['lang'] == "en")
											{
												urlParams['lang'] = 'nl';
											}
											else
											{
												urlParams['lang'] = 'en';
											}
							
											var qidx = window.location.href.indexOf('?');
											var uri = window.location.href;
											if (qidx != -1)
											{
												uri = uri.substring(0, qidx);
											}
							
											uri += "?lang=" + urlParams['lang'];
											
											var currentElementIndex = $('#carousel-list').data('jcarousel').currentIndex() + 1;
											var currentElement = $('#carousel-list>li[jcarouselindex="' + currentElementIndex + '"]').get(0);
											var openProjectIdx = $(currentElement).attr('projectId');
											if (openProjectIdx>=0)
											{
												uri += "&projectIdx=" + (parseInt(openProjectIdx));
											}
											window.location.href = uri;
							
										});
}

function showSpecialArrow(event)
{
	$('#header-buttons a').parent().each(function(index)
	{
		$(this).removeClass("arrow-up");
	});

	$(event.target).parent().addClass("arrow-up");
}

function hideSpecialArrow(event)
{
	$('#header-buttons a').parent().each(function(index)
	{
		$(this).removeClass("arrow-up");
	});

	if (lastSpecialButtonClicked != null)
	{
		$(lastSpecialButtonClicked).parent().addClass("arrow-up");
	}

}

function toggleProject(element)
{
	var clickIdx = parseInt(element.getAttribute("jcarouselindex")) -1;
	var currentIdx = $('#carousel-list').data('jcarousel').currentIndex();

	if (clickIdx == currentIdx)
	{
		if (element.style.height == "355px" || element.style.height == '') // ingeklapt, dus openen
		{
			openProject(element);
		}
		else
		// open, dus sluiten
		{
			$(element).animate( {
				height : "355px"
			});
			$("#carousel-bg").animate( {
				height : "355px"
			});

			$('.label').show(1);
			$('.sluitButton').fadeOut(600);
			stopAllVideo();
		}
	}
	else if (clickIdx < currentIdx)
	{
		hideAllProjects($('#carousel-list').data('jcarousel').prev, $('#carousel-list').data('jcarousel'));
	}
	else
	{
		hideAllProjects($('#carousel-list').data('jcarousel').next, $('#carousel-list').data('jcarousel'));
	}
}

function openProjectByJCarouselIndex(idx, doAnimation)
{
	if(doAnimation == undefined)
	{
		doAnimation = false;
	}
	var element = $('#carousel-list>li[jcarouselindex="' + idx + '"]').get(0);
	if (element)
	{
		$('#carousel-list').data('jcarousel').scroll(parseInt(idx), doAnimation);
		openProject(element);
	}
}

function openProjectByProjectIndex(idx)
{
	var element = $('#carousel-list>li[projectId="' + idx + '"]').get(0);
	if (element)
	{

		openProjectByJCarouselIndex($(element).attr('jcarouselindex'));
	}
}

function openProject(element)
{
	forceCloseSpecial();

	$("#carousel-list li").not(element).each(function(index)
	{
		if (this.style.height != "355px")
		{

			$(this).animate( {
				height : "355px"
			});
		}
	});

	if ($(element).attr('jcarouselindex') != $('#carousel-list').data('jcarousel').currentIndex() + 1)
	{
		$('#carousel-list').data('jcarousel').scroll($(element).attr('jcarouselindex') - 1, false);
	}

	$(element).animate( {
		height : element.scrollHeight
	});

	$("#carousel-bg").animate( {
		height : element.scrollHeight
	});

	createSmallCarousel($(element).attr('projectId'));

	$('.label').fadeOut(600);
	$('.sluitButton').fadeIn(600);
}

function stopAllVideo()
{
	$('video').each(function()
	{
		this.player.pause();
		this.player.showPoster();
	});
}

function hideAllProjects(onComplete, onCompleteThisObj)
{
	$('.label').show(1);
	$('.sluitButton').fadeOut(600);
	stopAllVideo();
	$("#carousel-list li").each(function(index)
	{
		if (getPx(this.style.height) != getPx("355px"))
		{
			$(this).animate( {
				height : "355px"
			});
		}
	});

	if ($("#carousel-bg").height() != getPx("355px"))
	{
		$("#carousel-bg").animate( {
			height : "355px"
		}, {
			complete : function()
			{
				onComplete.call(onCompleteThisObj);
			}
		});
	}
	else
	{
		onComplete.call(onCompleteThisObj);
	}
}

function createSmallCarousel(projectId)
{
	$('#carousel-list-small[projectId="' + projectId + '"]').jcarousel( {
		itemFallbackDimension : 560,
		scroll : 1,
		buttonNextHTML : null,
		buttonPrevHTML : null
	});
	$('#navButton-left-small[projectId="' + projectId + '"]').click(function(event)
	{
		event.stopPropagation();
		$('#carousel-list-small[projectId="' + projectId + '"]').data('jcarousel').prev();
	});
	$('#navButton-right-small[projectId="' + projectId + '"]').click(function(event)
	{
		event.stopPropagation();
		$('#carousel-list-small[projectId="' + projectId + '"]').data('jcarousel').next();
	});

	$('#carousel-small-area[projectId="' + projectId + '"]').click(function(event)
	{
		event.stopPropagation();
	});

	$('.lightbox').lightBox();
}

function hey()
{
	alert('hey');
}

var lastSpecialButtonClicked;

function forceCloseSpecial()
{
	$('#header-buttons a').parent().each(function(index)
	{
		$(this).removeClass("arrow-up");
	});

	$('#special').animate( {
		height : "0px"
	});

	$('#special > div').each(function()
	{
		$(this).height("0px");
	});
	lastSpecialButtonClicked = null;
}

function toggleSpecial(event)
{

	var openHeight = "360px";

	if (lastSpecialButtonClicked == event.target)
	{
		$('#header-buttons a').parent().each(function(index)
		{
			$(this).removeClass("arrow-up");
		});

		$('#special').animate( {
			height : "0px"
		});

		$('#special > div').each(function()
		{
			$(this).height("0px");
		});
		lastSpecialButtonClicked = null;
	}
	else
	{
		$('#header-buttons a').parent().each(function(index)
		{
			$(this).removeClass("arrow-up");
		});

		$('#special > div').each(function()
		{
			$(this).height("0px");
			$(this).hide();
		});

		switch (event.target.id)
		{
			case "headerButtonNews":
				break;
			case "headerButtonCompany":
				$('#company').height(openHeight);
				$('#company').show();
				break;
			case "headerButtonClients":
				$('#clients').height(openHeight);
				$('#clients').show();
				break;
			case "headerButtonAwards":
				$('#awards').height(openHeight);
				$('#awards').show();
			case "headerButtonContact":
				$('#contact').height(openHeight);
				$('#contact').show();
				break;
			case "headerButtonJobs":
				$('#jobs').height(openHeight);
				$('#jobs').show();
				break;
		}

		$(event.target).parent().addClass("arrow-up");
		$('#special').animate( {
			height : openHeight
		});
		lastSpecialButtonClicked = event.target;
	}
}

function getPx(cssPxVal)
{
	return parseInt(cssPxVal.replace("px", ""));
}

function fetchSpecials()
{
	$.ajax( {
		data : {
			y : "getSpecials()"
		},
		success : function(data)
		{
			var specials = data['payload'];
			for ( var i in specials)
			{
			
				if (urlParams['lang'] == 'en')
				{
					$("#" + i).append(specials[i]['en']);
				}
				else
				{
					$("#" + i).append(specials[i]['nl']);
				}

			}
		}
	});
}

function fetchNews()
{
	$.ajax( {
		data : {
			y : "getNewsRange(0,3,"+showHidden+")"
		},
		success : function(data)
		{
			var newsItems = data['payload'];
			var cnt = 0;
			while (cnt < 3 && newsItems.length > 0)
			{
				var item = newsItems.pop();
				$("#newsContent").append(createNewsItem(item, cnt));
				cnt++;
			}
			
			if(data['next_btn']==1)
			{
	//			$("#news").append("<div id='#navButton-right-small'></div>");
			}
		}
	});
}

function createNewsItem(item, cnt)
{
	var title = item['title'];
	var body = item['body'];

	if (urlParams['lang'] == 'en')
	{
		title = item['title_en'];
		body = item['body_en'];
	}

	var itemHtml = '<div id = "news-item-' + cnt + '" >';
	itemHtml += '<span class = "title">' + title + '</span><br/>';
	itemHtml += '<hr/>';
	itemHtml += '<span class = "date">' + item['releasedate'] + '</span><br/>';
	itemHtml += body + '</div>';
	return itemHtml;
}

function fetchProjects()
{
	$.ajax( {
		data : {
			y : "getProject(,true,"+showHidden+")"
		},
		success : function(data)
		{
			var projects = data['payload'];
			for ( var i in projects)
			{
				$("#carousel-list").append(createProjectItem(projects[i]));
			}

			createProjectCarousel();

		}
	});
}

function createProjectCarousel()
{
	$('#carousel-list').jcarousel( {
		itemFallbackDimension : 940,
		scroll : 1,
		buttonNextHTML : null,
		buttonPrevHTML : null,
		wrap : "both"
	});

	$("#carousel-list li").each(function(index)
	{
		$(this).addClass("shadow");
	});

	$('.label, .sluitButton').click(function(event)
	{
		var element = event.target;

		while (element.nodeName != "LI")
		{
			element = element.parentNode;
		}

		toggleProject(element);
	});

	$('#navButton-left').click(function(event)
	{
		hideAllProjects($('#carousel-list').data('jcarousel').prev, $('#carousel-list').data('jcarousel'));
		event.stopPropagation()
	});
	$('#navButton-right').click(function(event)
	{
		hideAllProjects($('#carousel-list').data('jcarousel').next, $('#carousel-list').data('jcarousel'));
		event.stopPropagation()
	});

	$('.sluitButton').fadeOut(0);

	$("video").VideoJS();

	$("video").each(function()
	{
		var element = this;
		this.player.onPlay(function(event)
		{
			
			while (element.nodeName != "LI")
			{
				element = element.parentNode;
			}
			
			
			//Stop all other videos
			$('video').each(function()
								{
									var dezeLi = this;
									while (dezeLi.nodeName != "LI")
									{
										dezeLi = dezeLi.parentNode;
									}
									
									if(dezeLi!=element)
									{	
										this.player.pause();
										this.player.showPoster();
									}
								});
			
			
			var clickIdx = parseInt(element.getAttribute("jcarouselindex"));
			var currentIdx = $('#carousel-list').data('jcarousel').currentIndex();
			if(clickIdx!=currentIdx+1)
			{
				//openProjectByJCarouselIndex(clickIdx, true);
				$('#carousel-list').data('jcarousel').scroll(clickIdx);
				this.player.pause();
				this.player.showPoster();
			}
			else
			{
				openProject(element);
			}
		});
	});

	$("#navButtonWrapper").click(function(event)
	{
		var currentIdx = $('#carousel-list').data('jcarousel').currentIndex() +1;
		openProjectByJCarouselIndex(currentIdx);
	});

	if (urlParams['projectIdx'])
	{
		openProjectByProjectIndex(urlParams['projectIdx']);
	}

}

function createProjectItem(projectData)
{
	var title = projectData['title'];
	var intro = projectData['intro'];
	var body = projectData['body'];

	if (urlParams['lang'] == 'en')
	{
		title = projectData['title_en'];
		intro = projectData['intro_en'];
		body = projectData['body_en'];

	}

	var screenshotsUl;
	if (projectData['screenshot_ids'].length > 0)
	{
		screenshotsUl = '<div class = "carousel-small-wrapper"><div id = "carousel-small-area" class = "small" projectId = "' + projectData['id']
				+ '"><ul id = "carousel-list-small" class="jcarousel-skin-tango small" projectId = "' + projectData['id'] + '">';
		for ( var i in projectData['screenshot_ids'])
		{
			screenshotsUl += ('<li><a href="' + projectData['screenshot_ids'][i]['url'] + '" class = "lightbox">');
			screenshotsUl += ('<img src = "' + projectData['screenshot_ids'][i]['url'] + '"/></a></li>');
		}
		screenshotsUl += ('</div>'); // carousel-small-area
		screenshotsUl += ('<div id = "navButtons-small"><span id = "navButton-left-small" projectId = "' + projectData['id']
				+ '"></span><span id = "navButton-right-small" projectId = "' + projectData['id'] + '"></span></div></div>');
	}
	else
	{
		screenshotsUl = "";
	}
	var li = '<li projectId = "' + projectData['id'] + '">';
	li += ('<div class = "project-container">');

	li += ('<div class = "main_screenshot-container">');
	switch (projectData['main_screenshot']['type'])
	{
		case 'image':
			li += ('<img class = "main_screenshot" src = "' + projectData['main_screenshot']['url'] + '"/>');
			break;
		case 'video':
			if (!mobile)
			{
				li += createVideoTag(projectData['main_screenshot']);
			}
			else
			{
				li += ('<img class = "main_screenshot" src = "' + projectData['main_screenshot']['url'] + '"/>');
			}
			break;
	}

	li += ("</div>"); // main_screenshot-container
	li += ('<div class = "label">' + title + '<br/><div class="bekijk');
	if (urlParams['lang'] == 'en')
	{
		li += ('_en');
	}
	li += ('"></div></div>');
	li += ('<div class = "sluitButton"></div>');
	li += ('<div class = "project">');
	li += ('<span class = "title">' + title + '</span><br/>');
	li += ('<hr>');
	li += ('<p class = "intro">');

	if (mobile && projectData['main_screenshot']['type'] == 'video')
	{
		// li+="<a href='showVideo.php?vid="+
		// projectData['main_screenshot']['id'] + "' target='_blank'>";
		li += "<a href='" + projectData['main_screenshot']['url_mp4'] + "' target='_blank'>";
		if (urlParams['lang'] == 'en')
		{
			li += "Click here to show the video trailer";
		}
		else
		{
			li += "Klik hier om de videotrailer te bekijken";
		}
		li += "</a><br/>";
	}
	li += (intro + "</p>");
	li += screenshotsUl;
	li += ('<p class = "body">');
	li += (body);
	li += ('</p>');
	li += '</div>'; // project
	li += '<div class = "infoblock">';

	if (projectData['url_href'] && projectData['url_href'] != '' && projectData['url_href'] != 'null')
	{
		li += '<a href="' + projectData['url_href'] + '" target = "_blank" class = "playthegame">';
		li += '</a>';
		li += '<br/><span class = "title">URL</span><br/><a href="' + projectData['url_href'] + '" target = "_blank">' + projectData['url_text']
				+ '</a><br/></br>';
	}
	else
	{
	//	li += '<br/><span class = "title">URL</span><br/>' + projectData['url_text'] + '<br/></br>';
	}
	li += '<span class = "title">Release</span><br/>';
	if(projectData['releasedate']=='null' || projectData['releasedate']==null)
	{
		if (urlParams['lang'] == 'en')
		{
			li += 't.b.a.';
		}
		else
		{
			li += 'n.n.b.';
		}
	}
	else
	{
		li += projectData['releasedate'];
	}
	li += '<br/><br/>';

	if (projectData['client_ids'].length > 0)
	{
		if (urlParams['lang'] == 'en')
		{
			li += '<span class = "title">Client</span><br/>';
		}
		else
		{
			li += '<span class = "title">Klant</span><br/>';
		}
		var clientNameList = [];
		for ( var i in projectData['client_ids'])
		{
			clientNameList.push(projectData['client_ids'][i]['title']);
		}

		li += clientNameList.join(',') + '<br/></div>'; // infoblock
	}

	li += '</div>'; // project-container
	li += '</li>';

	return li;
}

function createVideoTag(videoResourceObj, width, height)
{
	if (!width) width = 940;
	if (!height) height = 550;

	var videotag = '<div class="video-js-box">';
	videotag += '<!-- Using the Video for Everybody Embed Code http://camendesign.com/code/video_for_everybody -->';
	videotag += '<video id="' + videoResourceObj['title'] + '" class="video-js"';
	videotag += 'width="' + width + '" height="' + height + '" ';
	videotag += 'controls="controls" preload="none" ';
	videotag += 'poster="' + videoResourceObj['url'] + '">';

	if (videoResourceObj['url_mp4'] != '' && videoResourceObj['url_mp4'] != null)
	{
		videotag += '<source src="' + videoResourceObj['url_mp4'] + '" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />';
	}

	if (videoResourceObj['url_webm'] != '' && videoResourceObj['url_webm'] != null)
	{
		videotag += '<source src="' + videoResourceObj['url_webm'] + '" type=\'video/webm; codecs="vp8, vorbis"\' />';
	}

	if (videoResourceObj['url_ogg'] != '' && videoResourceObj['url_ogg'] != null)
	{
		videotag += '<source src="' + videoResourceObj['url_ogg'] + '" type=\'video/ogg; codecs="theora, vorbis"\' />';
	}

	if (videoResourceObj['url_mp4'])
	{
		videotag += '<!-- Flash Fallback. Use any flash video player here. Make sure to keep the vjs-flash-fallback class. -->';
		videotag += '<object id="flash_fallback_' + videoResourceObj['title'] + '" class="vjs-flash-fallback" ';
		videotag += 'width="' + width + '" height="' + height + '" ';
		videotag += 'type="application/x-shockwave-flash"';
		videotag += 'data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf">';
		videotag += '<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />';
		videotag += '<param name="allowfullscreen" value="true" />';
		videotag += '<param name="flashvars" value=\'config={';
		videotag += '"playlist":["' + videoResourceObj['url'] + '",';
		videotag += '{"url": "' + videoResourceObj['url_mp4'] + '"';
		videotag += ',"autoPlay":false,"autoBuffering":true}]}\' />';
		videotag += '<!-- Image Fallback. Typically the same as the poster image. -->';
		videotag += '<img src="http://video-js.zencoder.com/oceans-clip.png" width="' + width + '" height="' + height + '" alt="Poster Image"';
		videotag += 'title="No video playback capabilities." />';
		videotag += '</object>';
	}

	videotag += '</video>';
	videotag += '<!-- Support VideoJS by keeping this link. <a href="http://videojs.com">HTML5 Video Player</a> by VideoJS -->';
	videotag += '</div>';

	return videotag;
}
/*
 * function onCarouselNext(instance, element, flag) { hideAllProjects(null); }
 * 
 * function onCarouselPrev(instance, element, flag) { hideAllProjects(null); }
 */

