$(document).ready(function(){
	
	$(convers8).bind('request_userinfo', function(event) {
		$('.convers8_attached_networks').each(function () {
			id = $(this).attr('id');
			
			if (id != '' && id == parseInt(id)) {
				convers8.users.push(id);
			}
		});
	});
	
	$('.editApiKeys').click(function(){
		$(this).parent().find('.apiKeysBox').slideToggle();
	});
	$('.helpApiKeys').click(function(){
		$(this).parent().find('.aanvraagHelp').slideToggle();
	});
	

	$(convers8).bind('fetched_userinfo', function(event,data) {
		for (user in data.users) {
			user = data.users[user];
			$(".convers8_attached_networks_" + user.id).next('img.convers8_avatar').attr('src',user.picture);
			html = '';
			for (network in user.networks) {
				network = user.networks[network];
				html = html + '<a href="' + network.url + '" class="convers8_icon_small convers8_' + network.network + '" target="_blank" title="' + network.network + '"></a>';
			}	
			
			$(".convers8_attached_networks_" + user.id).html(html);
		}
		
	});
	
     $(convers8).bind("login_credentials", function(event, data) {
		if (data.user == null || typeof(data.user) == "undefined") {
			$('#loggedInUserDiv').hide();
			$('.dropDownMenu').hide();
			$('#notLoggedInUserDiv').show();
			$('.probeerHetZelf').show();
		} else {
			user = data.user;
			var userid = data.user.id;
			var userfirstName = data.user.firstName;
			var userlastName = data.user.lastName;
			if(userfirstName.length + userlastName.length > 23){
				$('#loggedInUserDiv .username').text(user.firstName);
			} else {
				$('#loggedInUserDiv .username').text(user.firstName + ' ' + user.lastName);
			}
			$('#loggedInUserDiv').show();
			$('#loggedInUserDiv .convers8_avatar').attr('src',user.picture);
			$('.probeerHetZelf').hide();
			$('#notLoggedInUserDiv').hide();
			
			
			$('#nameField').val(userfirstName + ' ' + userlastName);
			$('#idField').val(userid);
			
			$('a.dropDown,.dropDownMenu').hover(function(){
				$(this).addClass('hovered');
			},function(){
				$(this).removeClass('hovered');
			});
			
			$('a.dropDown').mouseenter(function(){
				$('.dropDownMenu').show();
				$(this).addClass('up');
			});
			
			$('a.dropDown,.dropDownMenu').mouseleave(function(){
				setTimeout('closeDropDown()',350);
			});
			$('.formHolder .notLoggedIn').hide();
			$('.formHolder #commentForm').show();
		}
	});
	
	$('#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;
	});
	$('#overlay').click(function(){
		popOver('close');
	});
	
	$('.convers8_userpic').hover(function(){
				$(this).find('.convers8_attached_networks').stop(true,true).fadeIn();
			},function(){
				$(this).find('.convers8_attached_networks').stop(true,true).fadeOut();
		});
		
		$('.bartBelMij').click(function(){
			$('.defaultDiv').slideUp('normal',function(){
				$('.enterNrDiv').slideDown();
			});
		});
});

function popUp(url) {
	window.open(url,'popup','location=1,width=500,height=300');
}


function popOver(action,width,height,data){
	if(action == 'close'){
		$('#overlay,#overlayContainer').fadeOut();
	} else {
		$('#overlay').fadeIn();
		$('#overlayContainer').css({'width':width,'height':height,'margin-left':-(width/2) + 'px','margin-top':-(height/2) + 'px'}).fadeIn('normal',function(){
				
		});
	}
}

function sendPhoneNumber(){
	var number = escape($('#phoneNumber').val());
	$.ajax({
		url: '/sendPhoneNumber',
		type: 'POST',
		data: 'phoneNumber=' + number,

		success: function(result) {
			$('.enterNrDiv').slideUp('normal',function(){
				$('.defaultDiv').slideDown();
			});
		}
	});
}

function validate(elem){
	var chain = "";
	$(elem).parent().find(".verplicht").each(function(){
		if(this.type == "text" || this.type == "password" || this.type == "select-multiple" || this.type == "select" || this.type == "file"){
			if ((this.value.length==0) || (this.value==null) || (this.value=="http://")) {
				$(this).css("border","2px dashed #f33").css("background-color","#FF8585");
				chain += this.name;
			} else {
				$(this).css("border","1px solid #ABADB3").css("background-color","#fff");
			}
		} else if (this.type == "checkbox"){
			if ((this.checked == false)) {
				$(this).css("outline","2px dashed #f33");
				chain += this.name;
			} else {
				$(this).css("outline","0");
			}
		}
		else if (this.type == "radio"){
			var name = this.name;
			var path = eval('document.getElementById("inschrijfform").' + name);
			checked = false;
			for(i=0; i<path.length; i++){
			    if(path[i].checked){
			        checked=true;
			    }
			}
			if ((checked != true)) {
				$(this).css("outline","2px dashed #f33");
			} else {
				$(this).css("outline","0");
			}
		} else {
			if ((this.value.length==0) || (this.value==null) || (this.value=="http://")) {
				$(this).css("border","2px dashed #f33").css("background-color","#FF8585");
				chain += this.name;
			} else {
				$(this).css("border","1px solid #ABADB3").css("background-color","#fff");
			}
		}
	});	
	if(chain == ""){
		postComment(elem);
	}
	if(chain != ""){
	}
}

function loadCommentForm(tabel,item,level,linkedto,elem){
	$.ajax({
		url: '/comments.php',
		type: 'GET',
		data: 'tabel=' + tabel + '&item=' + item + '&level=' + level + '&linkedto=' + linkedto + '&request=form',

		success: function(result) {
			$(elem).parent().parent().after(result);
		}
	});
}

function postComment(elem){
	var values = $("#commentForm").serialize();
	$.ajax({
		url: '/comments.php?submit=true',
		type: 'POST',
		data: values,

		success: function(result) {
			$(elem).parent().empty().before(result);
		}
	});
}

function home(){
	slider('load');
	getTweets();
}

function getTweets(){
	$('.tweetContainer').tweet5('.tweetContainer', {
		username: 'convers8social',
		searchTerm: '',
		searchLanguage: 'nl', // language in  ISO 639-1 code. Search everything when empty or not available
		numberOfTweets: 3, // 20=max
		showUsername: 'false',
		showUserAvatar: 'false',
		showTweetTime: 'true',
		showRetweets: 'true',
		showReplyButton: 'true',
		showRetweetButton: 'true',
		showLocation: 'true',
		replyButtonText: 'reply',
		retweetButtonText: 'retweet',
		iconColor: 'black', //black or white
		refreshTime: 60, // time in seconds, minimum is 60
		altPath: '/'
	});
}

function closeDropDown(){
	if($('a.dropDown').hasClass('hovered') || $('.dropDownMenu').hasClass('hovered')){}
	else {
		$('.dropDownMenu').hide();
		$('a.dropDown').removeClass('up');
	}
}

function slider(val){
	var animationTime = 300;
	var slideDelay = 2600;
	var nrOfSlides = 5;
	if(val=='load'){
		$('.slideContainer img:nth-child(1)').fadeIn();
		$('.slideSteps div:nth-child(1)').addClass('active');
		currentSlide = 1;
		setTimeout('slider()',slideDelay);
		$('.slideSteps div').hover(function(){
			var nrHovered = $(this).attr('rel');
			var imgSrc = $('.slideContainer img.' + nrHovered).attr('src');
			$('.slideContainerOverlay').attr('src',imgSrc).show();
		},function(){
			$('.slideContainerOverlay').hide();
		});
	} else {
		if(currentSlide == nrOfSlides){
			$('.slideContainer img:visible').fadeOut(animationTime,function(){
				currentSlide = 1;
				$('.slideSteps div.active').removeClass('active');
				$('.slideContainer img:nth-child(' + currentSlide + ')').fadeIn(animationTime,function(){
					$('.slideSteps div:nth-child(' + currentSlide + ')').addClass('active');
					setTimeout('slider()',slideDelay);
				});
			});
		} else {
			$('.slideContainer img:visible').fadeOut(animationTime,function(){
				currentSlide++;
				$('.slideSteps div.active').removeClass('active');
				$('.slideContainer img:nth-child(' + currentSlide + ')').fadeIn(animationTime,function(){
					$('.slideSteps div:nth-child(' + currentSlide + ')').addClass('active');
					setTimeout('slider()',slideDelay);
				});
			});
		}
	}
}

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);


