/*
* Custom jQuery functions
**/

$(document).ready(function() {	
	// searchField
	var searchFieldText = 'Zoeken...';
	resetValue('searchField', searchFieldText);
	
	$('#searchField').bind('focus', function(event) {
		emptyValue('searchField', searchFieldText);
	});
	$('#searchField').bind('blur', function(event) {
		resetValue('searchField', searchFieldText);
	});
	$('#searchForm').bind('submit', function(event) {
		emptyValue('searchField', searchFieldText);
	});
	
	$('.unfold').click(function() {
		$(this).parent().find('.extraInfo').show();
		$(this).hide();
		return false;
	});
	
	/* product rating*/
	$('#productRating a').bind('mouseover', function(event) {
		if (typeof currentRating === "undefined") {
			// Set current rating first
			currentRating = $(this).parent().attr('class').substring(6,7);
		}
		var nr = $(this).attr('id').substring(4,5);
		// Hover rating on stars
		$('#productRating').removeClass().addClass('rating'+nr);
		if(nr == 1) {
			$('#ratingText').text('geef je mening: '+nr+' ster');
		}else{
			$('#ratingText').text('geef je mening: '+nr+' sterren');
		}
	}).bind('mouseout', function(event) {
		// Set current rating
		$('#productRating').removeClass().addClass('rating'+currentRating);
		$('#ratingText').text('');
	});
	
	$('#productRating a').bind('click', function(event) {	
		var rating = $(this).attr('id').substring(4,5);
		var productId = $(document).find('#productId').attr('value');
		var totalVotes = null;
		var messageId = null;
		var message = null;
		
		// save rating
		$.post(rootPath+"include/ajax.functions.inc.php", { rating: rating, productId: productId },
			function(data) {
				totalVotes = data.totalVotes;
				messageId = data.messageId;
				averageRating = data.averageRating;
				
				// display message
				if (messageId == 1) {
					var message = 'Bedankt voor het stemmen.';
				} else if (messageId == 2) {
					var message = 'Je hebt al gestemd.';
				}
				
				if (totalVotes == 1) {
					$('#productVotes').text('(1 stem)');
				} else {
					$('#productVotes').text('('+totalVotes+' stemmen)');
				}
				$('#ratingMessage').text(message);
				$('#productRating').removeClass().addClass('rating'+averageRating).empty();
	   }, "json");

		return false;	
	});
	
	/* Login overlay */
	
	var emailDefaultText = 'E-mailadres';
	$('input#loginUserName').focus(function() {
		emptyValue('loginUserName', emailDefaultText);
	});
	$('input#loginUserName').blur(function() {
		resetValue('loginUserName', emailDefaultText);
	});
	
	$('input#loginPasswordText').show();
	$('input#loginPassword').hide();
	
	$('input#loginPasswordText').focus(function() {
	    $('input#loginPasswordText').hide();
	    $('input#loginPassword').show();
	    $('input#loginPassword').focus();
	});
	
	$('input#loginPassword').blur(function() {
	    if($('input#loginPassword').val() == '') {
	        $('input#loginPasswordText').show();
	        $('input#loginPassword').hide();
	    }
	});
	
	/* Place experience overlay */
	
	var experienceDefaultText = 'Jouw ervaring (max 300 karakters)';
	$('textarea#experienceContent').live('focus', function(event) {
		if ($('textarea#experienceContent').val() == experienceDefaultText) {
			$('textarea#experienceContent').val('');
		}
	});
	$('textarea#experienceContent').live('blur', function(event) {
		if ($('textarea#experienceContent').val() == '') {
			$('textarea#experienceContent').val(experienceDefaultText);
		}
	});
	
	/* product rating*/
	$('#productRatingOverlay a').bind('mouseover', function(event) {
		if (typeof currentRating === "undefined") {
			// Set current rating first
			currentRating = $(this).parent().attr('class').substring(6,7);
		}
		var nr = $(this).attr('id').substring(4,5);
		// Hover rating on stars
		$('#productRatingOverlay').removeClass().addClass('rating'+nr);
		if(nr == 1) {
			$('#productRatingTextOverlay').text('geef je mening: '+nr+' ster');
		}else{
			$('#productRatingTextOverlay').text('geef je mening: '+nr+' sterren');
		}
	}).bind('mouseout', function(event) {
		var rating = $('#experienceRating').val();
		
		// Set current rating
		$('#productRatingOverlay').removeClass().addClass('rating'+rating);
		$('#productRatingTextOverlay').text('');
	});
	$('#productRatingOverlay a').bind('click', function(event) {
		var rating = $(this).attr('id').substring(4,5);
		
		$('#experienceRating').val(rating);
		$('#productRatingOverlay').removeClass().addClass('rating'+rating);	
	});
	
	externalLinks();
});

/**
 * Empty the value string of an inputfield, but only if the value equals a certain (standard) text
 */
function emptyValue(elm, text){
	if($('#'+elm).val()==text)
		$('#'+elm).val('');	
}

/**
 * Set the value string of an inputfield to a certain (standard) text, but only if the value is empty
 */
function resetValue(elm, text){
	if($('#'+elm).val()=='')
		$('#'+elm).val(text);
}

/**
 * Adds target="_blank" to links with rel="external" and rel="external nofollow"
 */
function externalLinks() {
	$('a[rel*="external"]').attr('target', '_blank');
}


/* SEO landing template unfold link */
$(document).ready(function() {
	$('#seoUnfold').click(function() {
		$('#seoContent').toggle();
		$('#seoUnfold').toggle();
		return false;
	});
});



/* News */
var olderNewsItemsShown = false;

function toggleOlderNewsItems() {
	if(olderNewsItemsShown) { // Hide
		$('#olderNewsItems').hide();
		olderNewsItemsShown = false;
		$('a#linkOlderNewsItems').text('Meer nieuws >');
	}else{	// Show
		$('#olderNewsItems').show();
		olderNewsItemsShown = true;
		$('a#linkOlderNewsItems').text('Verberg nieuws >');
	}
}

$(function() {
	$(".faqItem").toggle(
		function () {
			$(this).parent().addClass("question_expanded");
	     	$(this).parent().removeClass("question_collapsed");
	  	},
	  	function () {
	  		$(this).parent().removeClass("question_expanded");
	    	$(this).parent().addClass("question_collapsed");
	  	}
	);
	
	$(".faqGroup").toggle(
		function () {
			$(this).parent().addClass("faqGroup_expanded");
	     	$(this).parent().removeClass("faqGroup_collapsed");
	  	},
	  	function () {
	  		$(this).parent().removeClass("faqGroup_expanded");
	    	$(this).parent().addClass("faqGroup_collapsed");
	  	}
	);
	
	
});	


function getCustomerButtonListFiltered() {
	var branche = '';
	var service = '';
	
	// Get values from selectlists
	branche = $('#brancheFilter').val();
	service = $('#serviceFilter').val();
	
	// Send the filter to Ajaxify the overview
	$('#werkContentProjects').html('<div class="ajaxLoading"></div>');
	$.ajax({
		type: "GET",
		url: rootPath+"pages/products.ajax.php",
		data: "action=getCustomerButtonListFiltered&branche="+branche+"&service="+service,
		success: function(msg){
			$('#werkContentProjects').html(msg);
		}
	});
}

/* Sitemap */
function toggleSitemap(id, aId) {
	if($('#'+id).css('display') == 'none') {
		$('#'+id).css('display','block');
		$('a#'+aId+' img.toggleButton').attr('src',imgPath+'sitemap/min.png');
	}else{
		$('#'+id).css('display','none');
		$('a#'+aId+' img.toggleButton').attr('src',imgPath+'sitemap/plus.png');
	}
}

// define function that opens the overlay
function openOverlay() {
	
	// get access to the overlay API
	var api = $("#overlay").overlay();

	// call it's open() method		
	api.load();			
}

//define function that opens the overlay
function openLoginOverlay() {
	Cufon.refresh();
	// get access to the overlay API
	var api = $("#overlayInloggen").overlay();
	// call it's open() method
	api.load();
}

function openRegisterOverlay() {
	Cufon.refresh();
	// get access to the overlay API
	var api = $("#overlayRegister").overlay();
	// call it's open() method
	api.load();
}

function openExperienceOverlay() {
	Cufon.refresh();
	// get access to the overlay API
	var api = $("#overlayPlaceExperience").overlay();
	// call it's open() method
	api.load();
}

function openConfirmOverlay(confirmText) {
	Cufon.refresh();
	$('#confirmText').html(confirmText);
	
	// get access to the overlay API
	var api = $("#overlayConfirm").overlay();
	// call it's open() method
	api.load();
}

function openResetPasswordOverlay() {
	Cufon.refresh();
	// get access to the overlay API
	var api = $("#overlayResetPassword").overlay();
	// call it's open() method
	api.load();
}

// overlay
$(function() {
	$("#overlay").overlay({
		close: 'a.close' ,

		speed: 50,
		// start exposing when overlay starts to load
		onBeforeLoad: function() {
			
			// this line does the magic. it makes the background image sit on top of the mask
			this.getBackgroundImage().expose({opacity: 0.75 ,color: '#000000'});
		}, 
				
		// when overlay is closed take the expose instance and close it as well
		onClose: function() {
			$.expose.close();
		}
	});

	$("#overlay2").overlay({
		close: 'a.close' ,

		speed: 50,
		// start exposing when overlay starts to load
		onBeforeLoad: function() {
			
			// this line does the magic. it makes the background image sit on top of the mask
			this.getBackgroundImage().expose({opacity: 0.75 ,color: '#000000'});
		}, 
				
		// when overlay is closed take the expose instance and close it as well
		onClose: function() {
			$.expose.close();
		}
	});
	
	
	$("#overlayInloggen").overlay({
		close: 'a.btnClose' ,

		speed: 50,
		// start exposing when overlay starts to load
		onBeforeLoad: function() {
			
			// this line does the magic. it makes the background image sit on top of the mask
			this.getBackgroundImage().expose({opacity: 0.75 ,color: '#000000'});
		}, 
				
		// when overlay is closed take the expose instance and close it as well
		onClose: function() {
			$.expose.close();
		}
	});
	
	$("#overlayRegister").overlay({
		close: 'a.btnClose' ,

		speed: 50,
		// start exposing when overlay starts to load
		onBeforeLoad: function() {
			
			// this line does the magic. it makes the background image sit on top of the mask
			this.getBackgroundImage().expose({opacity: 0.75 ,color: '#000000'});
		}, 
				
		// when overlay is closed take the expose instance and close it as well
		onClose: function() {
			$.expose.close();
		}
	});
	
	$("#overlayPlaceExperience").overlay({
		close: 'a.btnClose' ,

		speed: 50,
		// start exposing when overlay starts to load
		onBeforeLoad: function() {
			
			// this line does the magic. it makes the background image sit on top of the mask
			this.getBackgroundImage().expose({opacity: 0.75 ,color: '#000000'});
		}, 
				
		// when overlay is closed take the expose instance and close it as well
		onClose: function() {
			$.expose.close();
		}
	});
	
	$("#overlayConfirm").overlay({
		close: 'a.btnClose' ,

		speed: 50,
		// start exposing when overlay starts to load
		onBeforeLoad: function() {
			
			// this line does the magic. it makes the background image sit on top of the mask
			this.getBackgroundImage().expose({opacity: 0.75 ,color: '#000000'});
		}, 
				
		// when overlay is closed take the expose instance and close it as well
		onClose: function() {
			$.expose.close();
		}
	});
	
	$("#overlayResetPassword").overlay({
		close: 'a.btnClose' ,

		speed: 50,
		// start exposing when overlay starts to load
		onBeforeLoad: function() {
			
			// this line does the magic. it makes the background image sit on top of the mask
			this.getBackgroundImage().expose({opacity: 0.75 ,color: '#000000'});
		}, 
				
		// when overlay is closed take the expose instance and close it as well
		onClose: function() {
			$.expose.close();
		}
	});
});

function mediaVote(type, mediaId, socialMediaType){
	// add to serializedData
	var serializedData ='';
	serializedData = 'action=mediaVote&type='+type+'&mediaId='+mediaId+'&socialMediaType='+socialMediaType;
	
	$.ajax({
		type: 'GET',		
		url: rootPath+'include/photos/ajax_functions.inc.php',
		data: serializedData,
		dataType: 'json',
		success: function(msg) {
			// if total votes isset update number
			if(msg['totalVotes'] != ''){
				if (msg['totalVotes'] == 1) {
					$('.llysVoteDetailVotes').html(msg['totalVotes']+' stem');
				} else {
					$('.llysVoteDetailVotes').html(msg['totalVotes']+' stemmen');
				}
				
			}

			if(socialMediaType == 'facebook'){
				$('#facebookVote').html('');
			}else if(socialMediaType == 'hyves'){
				$('#hyvesVote').html('');
			}else if(socialMediaType == 'twitter'){
				$('#twitterVote').html('');
			}
			
			alert(msg['message']);
		}
	});	
}

/* Home carousel */

/*
function homeCarousel_initCallback(carousel) {
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
	});
	
	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
	});
	
	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});
};
*/

/* Product experiences tab */

function expandExperiences(totalExperiences) {
	if ($('#experiencesItemsExpanded').hasClass('collapsed')) {
		$('#experiencesItemsExpanded').removeClass('collapsed');
		$('#experiencesLink a').html('Meest recente ervaringen');
	} else {
		$('#experiencesItemsExpanded').addClass('collapsed');
		$('#experiencesLink a').html('Alle '+ totalExperiences +' ervaringen');
	}
}

function imposeMaxLength(Object, MaxLen) {
  return (Object.value.length <= MaxLen);
}

/* Experience forms */

/*
function loginUser() {
	var loginData = {action: 'loginUser'}
	loginData.userName = $('form#loginForm input#loginUserName').val();
	loginData.password = $('form#loginForm input#loginPassword').val();
	
	$.ajax({		
		url: rootPath+'include/experience_ajax_functions.inc.php',
		type: 'POST',
		dataType: 'json',
		data: loginData,
		success: function(evt){
			if (evt.msg == 0) {	// OK
				openExperienceOverlay();
				
				$('form#loginForm input#loginUserName').val('E-mail adres');
				$('form#loginForm input#loginPassword').val('');
			} else {
				$('div#loginFeedback').html('De combinatie van dit e-mail adres en wachtwoord is onjuist');
			}
		}
	});
}
*/

function loginUser() {
	$('form#loginForm input').removeClass('formerror');
	
	$($('#loginForm')).ajaxSubmit({
		dataType:  'json',
		success: function(e) {
			if (e.succes == 1) {
				// openExperienceOverlay();
				window.location = e.redirectUrl;
			} else {
				$('div#loginFeedback').html(e.errorMessage);
				for(var i in e.errors) {
					$('#'+e.errors[i]).addClass('formerror');
				}
			}
		}
	});
	return false;
}

/*
function registerUser() {
	var registerData = {action: 'registerUser'}
	registerData.registerFirstName = $('form#registerForm input#registerFirstName').val();
	registerData.registerLastName = $('form#registerForm input#registerLastName').val();
	registerData.registerGender = $('form#registerForm input#registerGender').val();
	registerData.registerEmail = $('form#registerForm input#registerEmail').val();
	registerData.registerPassword = $('form#registerForm input#registerPassword').val();
	registerData.registerRepeatPassword = $('form#registerForm input#registerRepeatPassword').val();
	registerData.registerPhoto = $('form#registerForm input#registerPhoto').val();
	
	alert(registerData.registerPhoto);
	
	if ($('#registerConditions').is(':checked')) {
		registerData.registerConditions = $('form#registerForm input#registerConditions').val();
	} else {
		registerData.registerConditions = 'N';
	}
	if ($('#registerNewsletter').is(':checked')) {
		registerData.registerNewsletter = $('form#registerForm input#registerNewsletter').val();
	} else {
		registerData.registerNewsletter = 'N';
	}
	
	$('form#registerForm input').removeClass('formerror');
	
	$.ajax({		
		url: rootPath+'include/experience_ajax_functions.inc.php',
		type: 'POST',
		dataType: 'json',
		data: registerData,
		success: function(evt) {
			if(evt.msg == 0) {	// OK
				// open new screen for download
				// $('div#downloadBrochureFormContent').html('Bedankt voor het invoeren van uw gegevens.<br><a href="'+dlLink+'" target="_blank">Klik hier om uw brochure te downloaden</a>.');
				alert('REGISTER: ' + evt.test);
			} else {
				for(var i in evt.errors) {
					// alert('#'+evt.errors[i]);
				$('#'+evt.errors[i]).addClass('formerror');
				}
			}
		}
	});
}
*/

function registerUser() {
	$('form#registerForm input').removeClass('formerror');
	
	$($('#registerForm')).ajaxSubmit({
		dataType:  'json',
		success: function(e) {
			if (e.succes == 1) {
				window.location = e.redirectUrl;
			} else {
				$('div#registerFeedback').html(e.errorMessage);
				for(var i in e.errors) {
					$('#'+e.errors[i]).addClass('formerror');
				}
			}
		}
	});
	return false;
}

function saveExperience() {
	$('form#experienceForm input').removeClass('formerror');
	
	$($('#experienceForm')).ajaxSubmit({
		dataType:  'json',
		success: function(e) {
			if (e.succes == 1) {
				// GA
				_gaq.push(['_trackEvent', 'Ervaring plaatsen', 'Via ' + e.account, e.product]);
				window.location = e.redirectUrl;
			} else {
				for(var i in e.errors) {
					$('div#placeExperienceFeedback').html(e.errorMessage);
					$('#'+e.errors[i]).addClass('formerror');
				}
			}
		}
	});
	return false;
}

function resetPassword() {
	$('form#resetPasswordForm input').removeClass('formerror');
	
	$($('#resetPasswordForm')).ajaxSubmit({
		dataType:  'json',
		success: function(e) {
			if (e.succes == 1) {
				$('div#overlayContent').html('Er is een e-mail gestuurd met een nieuw wachtwoord.');
			} else {
				$('div#resetPasswordFeedback').html(e.errorMessage);
				for(var i in e.errors) {
					$('#'+e.errors[i]).addClass('formerror');
				}
			}
		}
	});
	return false;
}

function reportBadUserInput(experienceId) {
	var badUserInputData = {action: 'reportBadUserInput'}
	badUserInputData.experienceId = experienceId;
	
	$.ajax({		
		url: rootPath+'include/experience_ajax_functions.inc.php',
		type: 'POST',
		dataType: 'json',
		data: badUserInputData,
		success: function(e) {
			if (e.succes == 1) {
				$('div#badUserInput'+experienceId).html('Bedankt voor je melding.');	
			}
		}
	});
	return false;
}

function foldProductContent(){
	$('#info1 .unfold').show();
	$('#info1 .extraInfo').hide();
}
