var resizeTimer = -1;
var clickTimer = -1;

var departmentFilters = [];
var clientsFilters = [];
var campaigntypesFilters = [];


var isTouchDevice = (function() {
	try {
		document.createEvent("TouchEvent");
		return true;
	} catch (e) {
		return false;
	}
}())


$(document).ready()
{
	if (isTouchDevice)
	{
		$("html").addClass("touchDevice");	
	} 
	else 
	{
		$("html").addClass("notTouchDevice");	
	}
	
	$("header nav ul").clone().appendTo("#mobileMenu");
	
	$(window).resize(function() {
		clearTimeout(resizeTimer);
		resizeTimer = setTimeout('onwinresize()', 500);
	});
	
	onwinresize();
	
	$("#openCloseMenu").click(function(){
		$("#contentContainer").toggleClass("closed");
		
		$.ajax({
			url: "/session/set_menu_state",
			type: "POST",
			data: "state=" + $("#contentContainer").attr("class")
		});
	});

	// homepage
	if ($("body").attr("class") == "" || $("body").hasClass("home"))
	{
		getTweets();
			 
		if ($("html").hasClass("localstorage"))
		{
			localStorage.clear();
		}
	}

	// employees page
	if ($("body").hasClass("gezichten"))
	{
		getStats();
		
		if ($("html").hasClass("localstorage") && localStorage.getItem("filters_departments"))
		{
			$("#departments ul").html(localStorage.getItem("filters_departments"));
		}
		
		$("#departments ul li").each(function(i, elem){
			$(elem).click(function(){
				if ($(elem).hasClass("active"))
				{
					$(elem).removeClass("active");
				} else {
					$(elem).addClass("active");
				}
				updateDepartmentFilters();
			});
		});

	}
	
	// portfolio page
	if ($("body").hasClass("portfolio"))
	{
		
		if ($("html").hasClass("localstorage") && localStorage.getItem("filters_campaigntypes"))
		{
			$("#campaigntypes ul").html(localStorage.getItem("filters_campaigntypes"));
		}
		
		if ($("html").hasClass("localstorage") && localStorage.getItem("filters_clients"))
		{
			$("#clients ul").html(localStorage.getItem("filters_clients"));
		}
		
		$("#campaigntypes ul li").each(function(i, elem){
			$(elem).click(function(){
				if ($(elem).hasClass("active"))
				{
					$(elem).removeClass("active");
				} else {
					$(elem).addClass("active");
				}
				updatePortfolioFilters();
			});
		});
		
		
		$("#clients ul li").each(function(i, elem){
			$(elem).click(function(){
				if ($(elem).hasClass("active"))
				{
					$(elem).removeClass("active");
				} else {
					$(elem).addClass("active");
				}
				updatePortfolioFilters();
			});
		});
		
	}
	
	
	// contact page
	if ($("body").hasClass("contact"))
	{
		initializeGoogleMap();
		$("#contactform").submit(function(event){
			event.preventDefault();
			var name = $('#contactform input[name="name"]').val();
			var email = $('#contactform input[name="email"]').val();
			var message = $('#contactform textarea').val();
			
			$.ajax({
				url: "/contact/contactform",
				type: "POST",
				data: 	"name=" + name +
						"&email=" + email +
						"&message=" + message,
				success: function (data)
				{
					if (data == "success")
					{
						$("#contactform").hide();
						$("#form_error").hide();
						$("#form_success").show();
					} else {
						$("#form_error").show();
					}
				}
			});
		});
	}
	
	
	handMouseDown();
	
	
	/*jwplayer("videoplayer").setup({
		width: "100%",
		height: "100%",
		'modes': [
			{type: 'html5'},
			{type: 'flash', src: '/swf/player.swf'}
		]
	});*/
}


function sortGrid()
{
	loadGridImgs($("body").attr("class"), true);
}


function updatePortfolioFilters()
{	
	campaigntypesFilters = [];
	clientsFilters = [];
	
	$("#campaigntypes ul li.active").each(function(i, elem){
		campaigntypesFilters.push($(elem).attr("data-type"));
	});
	
	$("#clients ul li.active").each(function(i, elem){
		clientsFilters.push($(elem).attr("data-id"));
	});
		
	if ($("html").hasClass("localstorage"))
	{
		localStorage.setItem("filters_campaigntypes", $("#campaigntypes ul").html());
		localStorage.setItem("filters_clients", $("#clients ul").html());
	}
	
	
	if (campaigntypesFilters.length > 0 || clientsFilters.length > 0)
	{
		$("#gridContainer .gridcell").each(function(i, elem){
			var img = $(elem).find("img");
			var values_clients = $(img).attr("data-id").split(",");
			var values_campaigns = $(img).attr("data-id2").split(",");
			var active = false;
			
			for (j = 0; j < values_clients.length; j++)
			{
				if(valueInArray(values_clients[j], clientsFilters))
				{
					active = true;
					break;
				} 
			}
			
			for (k = 0; k < values_clients.length; k++)
			{
				if(valueInArray(values_campaigns[k], campaigntypesFilters))
				{
					active = true;
					break;
				} 
			}
			
			if (active)
			{
				$(elem).addClass('active');
			} else {
				$(elem).removeClass('active');
			}
			
		});
		
		var imgs = getImgs();
		
		if ($("html").hasClass("localstorage"))
		{
			localStorage.setItem("imgs_portfolio", $.toJSON(imgs));
		}
	} else {
		$("#gridContainer .gridcell").each(function(i, elem){
			$(elem).addClass('active');
		});
	}
	
}


function updateDepartmentFilters()
{
	
	departmentFilters = [];
	
	$("#departments ul li.active").each(function(i, elem){
		departmentFilters.push($(elem).attr("data-id"));
	});
	
	if ($("html").hasClass("localstorage"))
	{
		localStorage.setItem("filters_departments", $("#departments ul").html());
	}
	
	if (departmentFilters.length > 0)
	{
	
		$("#gridContainer .gridcell").each(function(i, elem){
			var img = $(elem).find("img");
			var values = $(img).attr("data-id").split(",");
			
			for (j = 0; j < values.length; j++)
			{
				if(valueInArray(values[j], departmentFilters))
				{
					$(elem).addClass('active');
					break;
				} 
				$(elem).removeClass('active');
			}
		});
		
		var imgs = getImgs();
		
		if ($("html").hasClass("localstorage"))
		{
			localStorage.setItem("imgs_gezichten", $.toJSON(imgs));
		}
	} else {
		$("#gridContainer .gridcell").each(function(i, elem){
			$(elem).addClass('active');
		});
	}
}



function valueInArray(val, list)
{
	var found = false;
	
	for (a = 0; a < list.length; a++)
	{
		if (list[a] === val)
		{
			found = true;
			break;
		}
	}
	
	return found;
}



function getTweets()
{
	$.ajax({
		url: "/twitter/get_tweets_from_user",
		dataType: "json",
		type: "POST",
		data: 	"userid=240596472" + // found at http://idfromuser.com
				"&username=xingredient" + 
				"&nr=3", 
		success: function (data)
		{
			$(data.result).each(function(){
				var tweet = $("<li>" + this.content + "</li>");
				$("#tweets ul").append(tweet);
			});
		}
	});
}

function getStats()
{
	$.ajax({
		url: "/stats/get_stats",
		dataType: "json",
		type: "POST",
		data: "&nr=3", 
		success: function (data)
		{
			$("#stats ul").empty();
			$(data.result).each(function(){
				var stat = $("<li><span>" + parseInt(this.value) + "%</span> " + this.name + "</li>");
				$("#stats ul").append(stat);
			});
		}
	});
}

function onwinresize()
{
	
	if ($("#backgroundImgs").length > 0)
	{
		loadBackgroundImgs();
	}
	if ($("#gridImgs").length > 0)
	{
		loadGridImgs($("body").attr("class"));
	}
	
	$('.scroll-pane').jScrollPane();

	scaleInfoGraphic();
	
	$("#overlay").empty();
	$("#overlay_bg").hide();
}



function getImgs()
{
	var imgs = [];
	
	$("#gridImgs .gridcell").each(function(i, elem)
	{
		imgs.push({
			classname: $(elem).attr("class"), 
			alt: $(elem).find("img").attr("alt"), 
			url: $(elem).find("img").attr("data-url"),
			dataid: $(elem).find("img").attr("data-id"),
			dataid2: $(elem).find("img").attr("data-id2"),
			nme: $(elem).find("img").attr("data-name"),
			extra: $(elem).find("img").attr("data-extra"), 
			src: $(elem).find("img").attr("data-imgsrc")
		});
	});
	
	return imgs;
}



function loadGridImgs(page, sorting)
{
	
	var imgs = getImgs();


	if ($("body").hasClass("gezichten") && $("html").hasClass("localstorage"))
	{
		if(localStorage.getItem("imgs_gezichten"))
		{
			imgs = $.parseJSON(localStorage.getItem("imgs_gezichten"));
		} else {
			imgs.sort(function() {return 0.5 - Math.random()});
			localStorage.setItem("imgs_gezichten", $.toJSON(imgs));		
		}
	} 
	
	if ($("body").hasClass("portfolio") && $("html").hasClass("localstorage"))
	{
		if(localStorage.getItem("imgs_portfolio"))
		{
			imgs = $.parseJSON(localStorage.getItem("imgs_portfolio"));
		} else {
			imgs.sort(function() {return 0.5 - Math.random()});	
			localStorage.setItem("imgs_portfolio", $.toJSON(imgs));	
		}
	} 

	if (sorting === true)
	{
		imgs.sort(function(a, b){
			if (a.classname.search("active") < b.classname.search("active")){
				return 1;	
			} else if (a.classname.search("active") > b.classname.search("active")) {
				return -1;	
			} else {
				return 0;	
			}
		});
		
		if ($("body").hasClass("gezichten") && $("html").hasClass("localstorage"))
		{
			localStorage.setItem("imgs_gezichten", $.toJSON(imgs));	
		}
		if ($("body").hasClass("portfolio") && $("html").hasClass("localstorage"))
		{
			localStorage.setItem("imgs_portfolio", $.toJSON(imgs));	
		}
	}
	

	var numrows = 3;
	
	if ($(window).height() < 420)
	{
		numrows = 1;
	} 
	else if ($(window).height() < 640)
	{
		numrows = 2;
	}
	
	// FILL EMPTY SPOTS IN GRID
	/*
	for(var i = 0; imgs.length%numrows > 0; i++)
	{
		imgs.push(imgs[i]);
	}
	*/
	
	$.ajax({
		type: 'POST',
		url: "/image/getgridimages/",
		data: {
			'nrrows': numrows,
			'imgs': imgs,
			'width': $(window).width() - (parseInt($("#container").css("left")) + parseInt($("#container").css("right"))),
			'height': $(window).height() - (parseInt($("#container").css("top")) + parseInt($("#container").css("bottom")))
		},
		success: function(result){
			$("#gridImgs").replaceWith(result); 
			$("#gridContainer").roto({snap: false});
			if (!isTouchDevice)
			{
				$(".gridcell").each(function(i, elem){
					$(elem).find(".gridinfo").click(function(){
						location.href = $(elem).find("img").attr("data-url");
					});
				});	

			}
		},
		dataType: "html"
	});

}



function loadBackgroundImgs()
{
	var imgs = [];
	var fit = "false";
	var pf = "false";
	var keeporder = false;
	
	if ($("#backgroundImgs").hasClass("fit"))
	{
		fit = "true";
	}
	
	if ($("#backgroundImgs").hasClass("pf"))
	{
		pf = "true";
	}
	
	if ($("#backgroundImgs").hasClass("keeporder"))
	{
		keeporder = true;
	}
	
	$("#backgroundImgs img").each(function(i, elem)
	{
		imgs.push({
			alt: $(elem).attr("alt"), 
			src: $(elem).attr("data-imgsrc"),
			video: $(elem).attr("data-video")
		});
	});
	
	if (!keeporder)
	{
		//imgs.sort(function() {return 0.5 - Math.random()});	
	}
	
	$.ajax({
		type: 'POST',
		url: "/image/getbackgroundimages/",
		data: {
			'pf': pf,
			'fit': fit,
			'imgs': imgs,
			'width': $(window).width() - (parseInt($("#container").css("left")) + parseInt($("#container").css("right"))),
			'height': $(window).height() - (parseInt($("#container").css("top")) + (parseInt($("#container").css("bottom"))))
		},
		success: function(result)
		{
			$("#backgroundImgs").replaceWith(result); 
			$("#backgroundContainer").roto();
			$("#backgroundNav li").removeClass("active");
			$("#backgroundNav li:eq(0)").addClass("active");
			$("#thumbnails img").removeClass("active");
			$("#thumbnails img:eq(0)").addClass("active");
			
			$("#backgroundContainer").bind("rotoChange", function(event, listitem){
				$("#backgroundNav li").removeClass("active");
				$("#backgroundNav li:eq(" + $('#backgroundImgs li').index(listitem) + ")").addClass("active");
				$("#thumbnails img").removeClass("active");
				$("#thumbnails img:eq(" + $('#backgroundImgs li').index(listitem) + ")").addClass("active");
			});
			
			$("#backgroundImgs li img").each(function(i, elem)
			{
				
				var vid = $(this).attr("data-video");
				var $img = $(this);
				
				if (vid != "")
				{
					$('<div class="playbutton">play video...</div>').insertAfter($(this)).click(function(){

						var vid = $("<video></video>");
						var container = $($img.parent().html().replace("<img", "<div"));
						//container.attr("style", $("#overlay").attr("style"));
						container.append(vid);
					
						vid.attr("poster", container.attr("src"));
						vid.attr("src", container.attr("data-video"));
						vid.attr("controls", "controls");
						vid.attr("autoplay", "autoplay");
						vid.attr("id", "videoplayer");
						
						$("#overlay").empty();
						$("#overlay").append(container);
						
						
					   jwplayer("videoplayer").setup({
							width: "100%",
							height: "100%",
							'modes': [
								{type: 'html5'},
								{type: 'flash', src: '/swf/player.swf'}
							]
						});
						
						
						$("#overlay, #overlay>div, #videoplayer_wrapper").width($("#overlay").children().attr("width"));
						$("#overlay, #overlay>div, #videoplayer_wrapper").height($("#overlay").children().attr("height"));
						
						
						$("#overlay").css(
						{
							"width": $("#overlay").children().attr("width"), 
							"height": $("#overlay").children().attr("height"), 
							"top": $("#overlay").children().css("margin-top"), 
							"left": $("#overlay").children().css("margin-left")
						});
						
						$("#overlay").children().css({"margin": "0"})
						
						
						$("#overlay").show();
						$("#overlay_bg").show();
						$("#backgroundImgs").hide();
						$("#backgroundNav").hide();
						$("#overlay_bg").click(function ()
						{
							$("#overlay").hide();
							$("#overlay_bg").hide();
							$("#backgroundImgs").show();
							$("#backgroundNav").show();
						});
						
						$(window).bind("keydown", function (event)
						{
							if(event.keyCode == "27")
							{	
								$("#overlay_bg").trigger("click");
							}
						});
						
						
					});
					
					
				}
			});

			/*if ($("body").hasClass("portfolio"))
			{
				$("#backgroundImgs.fit.pf li").each(function(i, elem){
					$(elem).click(function(){
						
					});
				});
			}*/
			
			$("#backgroundNav").empty();
			var btns = [];
			
			if ($("#backgroundImgs li").length <= 1)
			{
				$("#backgroundNav").hide();
			} else {
				$("#backgroundNav").show();
			}
			
			$("#backgroundImgs li").each(function(i, elem){
				var btn = $('<li>&bull;</li>');
				if (i == 0)
				{
					$(btn).addClass("active");
				}
				$(btn).click(function(){
					backgroundGoto(i);
				});
				$("#backgroundNav").append(btn);
			});
		},
		dataType: "html"
	});
	
}



function backgroundGoto(index)
{
	$("#backgroundContainer").trigger("rotoGoto", index)
}



function initializeGoogleMap()
{
	var latlng = new google.maps.LatLng(51.6861472, 5.2941318);
	var myOptions = {
		zoom: 15,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	map.setTilt(45);
	
	var contentString = '<div id="content" style="color:black;font-weight:bold;font-size:20px;">'+
		'<span class="orange">X-</span>INGREDIENT'+
		'</div>';

	var infowindow = new google.maps.InfoWindow({
		content: contentString
	});

	
	var marker = new google.maps.Marker({
		position: latlng,
		map: map, 
		animation: google.maps.Animation.DROP,
		title:"X-Ingredient"
	});
	
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map,marker);
	});
};



function grayscaleImage(canvas, img)
{
	var canvasSupported = !!document.createElement('canvas').getContext;
	if (canvasSupported)
	{	
			var ctx = canvas.getContext("2d"),
				imageData, px, length, i = 0,  
                grey;
  
            var imgWidth = $(img).width();
			var imgHeight = $(img).height();
			
            ctx.drawImage(img, 0, 0, 300, 300, 0, 0, imgWidth, imgHeight);
			
            imageData = ctx.getImageData(0, 0, imgWidth, imgHeight);  
            px = imageData.data;
            length = px.length;
  
            for ( ; i < length; i+= 4 ) 
			{  
                grey = px[i] * .3 + px[i+1] * .59 + px[i+2] * .11;  
				grey = grey / 2	;
                px[i] = px[i+1] = px[i+2] = grey;
            }  
  
            ctx.putImageData(imageData, 0, 0);
		
	};
};


function gridImageLoaded(img)
{
	var img = $(img)[0];
	var canvas = $(img).siblings("canvas")[0];
	
	grayscaleImage(canvas, img);
}

function scaleInfoGraphic()
{
	var origHeight;
	var origWidth;
	
	if (isTouchDevice)
	{
		origHeight = $(".infographForMobile").attr("data-height");
		origWidth = $(".infographForMobile").attr("data-width");
		$(".infographForDesktop").remove();
	}
	else {
		origHeight = $(".infographForDesktop").attr("data-height");
		origWidth = $(".infographForDesktop").attr("data-width");
		$(".infographForMobile").remove();
	}
	
	var divideWith = $(window).height() - (parseInt($("#container").css("top")) + parseInt($("#container").css("bottom")));
	var scaleFactor = divideWith / origHeight;
	var newHeight = origHeight * scaleFactor;
	var newWidth = origWidth * scaleFactor;
	
	$('#infographic li').css({"overflow": "hidden", "width": newWidth});
	$('#infographic li').css({"overflow": "hidden", "height": newHeight});
	$('#infographic li>div').css({"-moz-transform-origin": "top left ", "-moz-transform": "scale(" + scaleFactor + ") translate(0,0)", 
								  "-webkit-transform-origin": "top left ", "-webkit-transform": "scale(" + scaleFactor + ") translate(0,0)", 
								  "transform-origin": "top left ", "transform": "scale(" + scaleFactor + ") translate(0,0)", 
								  "width": + newWidth + "px", "height": + newHeight + "px"});
	$("#infographicscontainer").roto({snap: false});
}

function handMouseDown()
{
	$("#gridImgs, #backgroundImgs, #infographic, #backgroundContainer, #gridContainer, #infographicscontainer").mousedown(function()
	{
		$("#gridImgs, #backgroundImgs, #infographic, #backgroundContainer, #gridContainer, #infographicscontainer").css({"cursor": "url(/assets/imgs/layout/handcursorgrab.gif), auto"});
	});
	
	$("#gridImgs, #backgroundImgs, #infographic, #backgroundContainer, #gridContainer, #infographicscontainer").mouseup(function()
	{
		$("#gridImgs, #backgroundImgs, #infographic, #backgroundContainer, #gridContainer, #infographicscontainer").css({"cursor": "url(/assets/imgs/layout/handcursor.gif), auto"});
	});
}
