$(document).ready( function() {
	
	loadYoutubeVideos('latestvideo','GetRealEnergy');
	if(!$('body').hasClass('video')){
		$('.nivoSlider').nivoSlider({
			effect : 'fade', // Specify sets like: 'fold,fade,sliceDown'
			slices : 15, // For slice animations
			boxCols : 8, // For box animations
			boxRows : 4, // For box animations
			animSpeed : 500, // Slide transition speed
			pauseTime : 3000, // How long each slide will show
			directionNav : false, // Next & Prev navigation
			controlNav : false // 1,2,3... navigation
		});
	
		$('.tweetContainer').tweet5('.tweetContainer', {
			username : 'GetRealEnergy',
			numberOfTweets : 3, // 20=max
			showUsername : 'false',
			showUserAvatar : 'false',
			showTweetTime : 'true',
			showReplyButton : 'true',
			showRetweetButton : 'true',
			showLocation : 'true',
			replyButtonText : 'reply',
			retweetButtonText : 'retweet',
			iconColor : 'black', //black or white
			refreshTime : 60, // time in seconds, minimum is 60
			oneMinuteAgoText : '1 minuut geleden',
			xMinutesAgoText : 'minuten geleden',
			oneHourAgoText : '1 uur geleden',
			xHoursAgoText : 'uur geleden',
			yesterdayText : 'gisteren',
			daysAgoText : 'dagen geleden',
			updateAvailable : 'Er zijn nieuwe tweets beschikbaar.',
			altPath : '/'
		});
	}
	
	$('#nssubmit').click(function(){
		var values = $('nsform').serialize();
		$.ajax({
			url: 'http://ymlp.com/subscribe.php?id=gmyebhegmgj',
			type: 'POST',
			data: values,

			success: function(result) {
				$('#nsform').html(result);
			}
		});
	});
	
	$('#nav li').hover(function(){
		$(this).find('.submenu').slideDown(200);
	},function(){
		$(this).find('.submenu').slideUp(200);
	});
	
	$('#contactform .required').blur(function(){
		if($(this).val() !== ''){
			var inputVal = $(this).val();
			var inputId = $(this).attr('id');
			$(this).removeClass('correct').addClass('error');
			if(inputId==='email'){
				var regExMail = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
				if(!regExMail.test(inputVal)){ return false; }
			} else if(inputId==='phone' || inputId==='fax'){
				var regExPhone = /^((((0031)|(\+31))(\-)?6(\-)?[0-9]{8})|(06(\-)?[0-9]{8})|(((0031)|(\+31))(\-)?[1-9]{1}(([0-9](\-)?[0-9]{7})|([0-9]{2}(\-)?[0-9]{6})))|([0]{1}[1-9]{1}(([0-9](\-)?[0-9]{7})|([0-9]{2}(\-)?[0-9]{6}))))$/;
				if(!regExPhone.test(inputVal)){ return false; }
			} else if(inputId==='postcode'){
				var regExPostcode = /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/;
				if(!regExPostcode.test(inputVal)){ return false; }
			} else if(inputId==='huisnummer'){
				var regExHuisnummer = /^([0-9]){1,}([A-Z]){0,3}/;
				if(!regExHuisnummer.test(inputVal)){ return false; }
			} else {}
			$(this).removeClass('error').addClass('correct');
		} else {
			$(this).removeClass('correct').addClass('error');
		}
	});

// Contact submit
	$("#contactsubmit").click( function() {
		var allRequiredFilled = 'check';
		$('#contactform .required').each( function() {
			if($(this).val()==='') {
				$(this).removeClass('correct').addClass('error');
				allRequiredFilled = 'error';
			}
		});
		if($('#contactform .error').length > 0 || allRequiredFilled === 'error' || $('#contactform #checkbox.verplicht').length > 0 && $('#contactform #checkbox.verplicht').attr('checked')!=='checked') {
			if($('#contactform #checkbox.verplicht').length > 0 && $('#contactform #checkbox.verplicht').attr('checked')!=='checked'){
				$('label[for="checkbox"]').addClass('error');
				$('#contactform #checkbox.verplicht').click(function(){
					if ($(this).is(':checked')){
						$('label[for="checkbox"]').removeClass('error');
						$(this).removeClass('error').addClass('correct');
					}
				});
			} else {
				$('label[for="checkbox"]').removeClass('error');
			}
		} else {
			$('#contactform .loading').show();
			var values = $("#contactformulier").serialize();
			$.ajax({
				url: 'formprocess.php?submit=true',
				type: 'POST',
				data: values,

				success: function(result) {
					$('#contactform').append('<p id="response">' + result + '</p>');
					$('#response').hide();
					$('#contactformulier').fadeOut('normal', function() {
						$('#response').fadeIn('normal');
					});
				}
			});
		}
		return false;
	});
});

function loadYoutubeVideos(method, username, maxresults){
	var popupWidth = 600; //set to undefined if empty
	var popupHeight = 400; //set to undefined if empty
	if(method!=='videofeed' && method !=='latestvideo' && method!=='videoinfo'){
		$('#videos').text('Error; Method not supported. Use "videofeed", "videoinfo" or "latestvideo"');
		return false;
	}
	if((method==='videofeed' && username === undefined) || (method ==='latestvideo' && username === undefined)){
		$('#videos').text('Error; No username specified');
		return false;
	}
	
	if(method==='videoinfo'){
		$('.videoBlock').each(function(){
			var videoId = $(this).attr('rel');
			var requestUrl = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json-in-script&callback=?';
			$.getJSON(requestUrl, function(data) {
				var videoid = data.entry[ "media$group" ][ "yt$videoid" ].$t;
				var videoImg = '<div class="videoImgContainer"><a href="javascript:void(0);" onclick="videoPopover(\'load\',\'' + videoid + '\',' + popupWidth + ',' + popupHeight + ');"><img src="http://img.youtube.com/vi/' + videoid + '/hqdefault.jpg" /></a></div>';
				var publishedDate = '<span class="videoDate">uploaded: ' + new Date( data.entry[ "published" ].$t.substr( 0, 4 ), data.entry[ "published" ].$t.substr( 5, 2 ) - 1, data.entry[ "published" ].$t.substr( 8, 2 ) ).toLocaleDateString() + '</span>';
				var videoAuthor = '<span class="videoAuthor">by: <a href="http://youtube.com/' + data.entry[ "author" ][ 0 ].name.$t + '" target="_blank">' + data.entry[ "author" ][ 0 ].name.$t + '</a></span>';
				var videoTitle = '<span class="videoTitle">' + data.entry[ "title" ].$t + '</span>';
				var videoDuration = '<span class="videoDuration">' + roundTime(data.entry[ "media$group" ][ "yt$duration" ].seconds) +  '</span>';
				var videoViews = '<span class="videoViews">' + data.entry[ "yt$statistics" ].viewCount + ' views</span>';
				var appendHtml = (videoImg + videoTitle + '<br />' + videoViews + videoAuthor + publishedDate + videoDuration);
				$('.videoBlock[rel=' + videoid + ']').append(appendHtml);
			});
		});
	} else {
		if(maxresults!== undefined) {
			maxresults = '&maxresults=' + maxresults;
		} else{
			maxresults = '';
		}
		var requestUrl = 'getYoutubeVideos.php?username=' + username + '&method=' + method + maxresults;
	
		$.getJSON(requestUrl, function(data) {
			var feed = data.feed;
			var entries = feed.entry || [];
			var html = [''];
			var i='';
			for (i = 0; i < entries.length; i++) {
				var entry = entries[i];
				var videoTitle = entry.title.$t;
				var videoid = entry.id.$t.split("/");
				var videoLink = entry.link[0].href; // Link to youtubepage
				var videoViews = entry.yt$statistics.viewCount;
				var videoDuration = entry.media$group.yt$duration.seconds;
				var videoDescription = entry.content.$t;
				html.push('<a href="javascript:void(0);" onclick="videoPopover(\'load\',\'' + videoid[6] + '\',' + popupWidth + ');" class="videoThumbnail"><span class="videothumbnailtitle">' +  videoTitle + '</span><img src="http://img.youtube.com/vi/' + videoid[6] + '/hqdefault.jpg" class="videothumbnail" /></a>');
			}
			$('#videos').html(html.join(''));
		});
	}
	function roundTime(a){if(a<=0){return"0:00"}else{var b=null;var c=Math.floor(a);var d=Math.floor(c/60);var e=c%60;if(e<"10"){b="0"+e}else if(e>="10"){b=e}return d+":"+b}}
}

function videoPopover(val,videoid,width,height){
	if(val==='close'){
		$('#overlay').fadeOut().remove();
		$('.overlayContainer').fadeOut('normal',function(){
			$(this).remove();
		});
	} else {
		if(height===undefined && width !== undefined){
			height = width/1.6;
		} else if ( width===undefined && height!== undefined){
			width = height*1.6;
		}	
		$('body').append('<div id="overlay"/><div class="overlayContainer" style="width:' + width + 'px;height:' + height + 'px;margin:-' + (height/2) + 'px 0 0 -' + (width/2) + 'px;"><div class="overlayContent"><iframe src="popupplayer.php?videoid=' + videoid + '&width=' + width + '&height=' + height + '" width="' + width + '" height="' + height + '" frameborder="0" hspace="0" scrolling="no"></iframe></div><span class="overlayClose" onclick="videoPopover(\'close\');">&times;</span><span class="overlayLoading">loading...</span></div>');
		$('#overlay').click(function(){ videoPopover('close'); });
		$(document).keydown(function(e){if (e.keyCode == 27) {videoPopover('close');}});
		$('#overlay').fadeIn();
		$('.overlayContainer').fadeIn();
	}
}

function imgPopover(val,src,width,height){
	if(val==='close'){
		$('#overlay').fadeOut().remove();
		$('.overlayContainer').fadeOut('normal',function(){
			$(this).remove();
		});
	} else {
		if(height===undefined && width !== undefined){
			height = width;
		} else if ( width===undefined && height!== undefined){
			width = height*1.6;
		}	
		$('body').append('<div id="overlay"/><div class="overlayContainer" style="width:' + width + 'px;height:80%;margin:-' + (height/2) + 'px 0 0 -' + (width/2) + 'px;"><div class="overlayContent"><img src="' + src + '" /><span class="overlayClose" onclick="videoPopover(\'close\');">&times;</span><span class="overlayLoading">loading...</span></div>');
		$('#overlay').click(function(){ videoPopover('close'); });
		$(document).keydown(function(e){if (e.keyCode == 27) {videoPopover('close');}});
		$('#overlay').fadeIn();
		$('.overlayContainer').fadeIn();
	}
}

function goBackContact(){
	$("#response").remove();
	$("#contactformulier").show();
}

// Placeholder-support
(function($) {
	// Return if native support is available.
	if ("placeholder" in document.createElement("input")) return;

	$(document).ready(function(){
		$(':input[placeholder]').not(':password').each(function() {
			setupPlaceholder($(this));
		});

		$(':password[placeholder]').each(function() {
			setupPasswords($(this));
		});

		$('form').submit(function(e) {
			clearPlaceholdersBeforeSubmit($(this));
		});
	});

	function setupPlaceholder(input) {

		var placeholderText = input.attr('placeholder');

		setPlaceholderOrFlagChanged(input, placeholderText);
		input.focus(function(e) {
			if (input.data('changed') === true) return;
			if (input.val() === placeholderText) input.val('');
		}).blur(function(e) {
			if (input.val() === '') input.val(placeholderText); 
		}).change(function(e) {
			input.data('changed', input.val() !== '');
		});
	}

	function setPlaceholderOrFlagChanged(input, text) {
		(input.val() === '') ? input.val(text) : input.data('changed', true);
	}

	function setupPasswords(input) {
		var passwordPlaceholder = createPasswordPlaceholder(input);
		input.after(passwordPlaceholder);

		(input.val() === '') ? input.hide() : passwordPlaceholder.hide();

		$(input).blur(function(e) {
			if (input.val() !== '') return;
			input.hide();
			passwordPlaceholder.show();
		});

		$(passwordPlaceholder).focus(function(e) {
			input.show().focus();
			passwordPlaceholder.hide();
		});
	}

	function createPasswordPlaceholder(input) {
		return $('<input>').attr({
			placeholder: input.attr('placeholder'),
			value: input.attr('placeholder'),
			id: input.attr('id'),
			readonly: true
		}).addClass(input.attr('class'));
	}

	function clearPlaceholdersBeforeSubmit(form) {
		form.find(':input[placeholder]').each(function() {
			if ($(this).data('changed') === true) return;
			if ($(this).val() === $(this).attr('placeholder')) $(this).val('');
		});
	}
})(jQuery);
