/**
 * Load the following on document ready
 */
$(function() {

	/***************************************************************************
	 * 
	 * Pagination settings
	 * 
	 **************************************************************************/
	if ($('.pagination-texts').length) {
		itemsPerPage = 3;
		paginatorStyle = 1;
		paginatorPosition = 'bottom';
		enableGoToPage = false;
		firstPageSymbol = $('#pagination-text-firstPageSymbol').html();
		previousPageSymbol = $('#pagination-text-previousPageSymbol').html();
		nextPageSymbol = $('#pagination-text-nextPageSymbol').html();
		lastPageSymbol = $('#pagination-text-lastPageSymbol').html();
		$("#project-pagination").pagination();
	}

	/***************************************************************************
	 * 
	 * Project details slideshow + request info button events
	 * 
	 **************************************************************************/
	var projectDetailsContent = $('.project-details-wrapper .project-details-content');
	if (projectDetailsContent.length){
		var requestInfo = $('.request-info',projectDetailsContent);
		$('#slide', projectDetailsContent).cycle({ 
			speedIn: 200, 
			speedOut: 6000,
			delay:100 
	   	});
		
		requestInfo.click(function(){
			$('.project-contact').slideDown('fast');
			$('.extra-info',projectDetailsContent).slideUp('fast');
			return false;
		});
		
		if (!$('.extra-info').length){
			requestInfo.hide();
			requestInfo.trigger('click');
		}
		
	}
	
	
	/***************************************************************************
	 * 
	 * Show and hide overlay
	 * 
	 **************************************************************************/
	$('.overlay-close').click(function() {
		$(".overlay-container").slideUp("fast");
	});
	$('.show-overlay').click(function() {
		$(".overlay-container").slideDown("fast");
		return false;
	});

	/***************************************************************************
	 * 
	 * Project page corner settings
	 * 
	 **************************************************************************/
	  $(".project-details-wrapper").corner("5px");
	  $(".crumbbar.content").corner("5px");
	 $(".footer-inner").corner("5px");
	 $(".crumbbar.home").corner("5px");
	 $(".mainmenu").corner("5px");
	 $(".banner").corner("5px"); 
	$(".banner").corner("br 5px");
	if ($(".project-row").length) {
		$(".project-row").corner();
	}

	/***************************************************************************
	 * 
	 * Project page cookie settings
	 * 
	 **************************************************************************/
	$('.project-details-content .donate, .project-content .donate').click(function() {
		$.cookie("active-project-donate", $(this).attr('projectName'));
	});

	/***************************************************************************
	 * 
	 * Project page form code
	 * 
	 **************************************************************************/
	/*if ($('#project-form').length > 0) {
		$('#project-form .send').click(function() {
						
			/*
			 * var $result = true; var firstname = $("#project-form
			 * #fname").val(); var telephone = $("#project-form #tel").val();
			 * var email = $("#project-form #email2").val(); var message =
			 * $("#project-form #message").val(); var projectname =
			 * '{/literal}{$currentPage.title}{literal}'; var pattern = new
			 * RegExp(
			 * /^(("[\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 (pattern.test($("#project-form #email2").val()) == false) {
			 * $result = false; $("#project-form .email_er").html("<img
			 * src='http://www.bonisa.nl/web/html/images/error.png' />"); } else {
			 * $("#project-form .email_er").html(" "); }
			 * 
			 * if ($("#project-form #fname").val() == '') { $result = false;
			 * $("#project-form .naam_er").html("<img
			 * src='http://www.bonisa.nl/web/html/images/error.png' />"); } else {
			 * $("#project-form .naam_er").html(" "); }
			 * 
			 * if ($("#project-form #message").val() == '') { $result = false;
			 * $("#project-form .msg_er").html("<img
			 * src='http://www.bonisa.nl/web/html/images/error.png' />"); } else {
			 * $("#project-form .msg_er").html(" "); }
			 * 
			 * if ($result == false) return false;
			 * 
			 * var dataString = 'projectname=' + projectname + '&firstname=' +
			 * firstname + '&telephone=' + telephone + '&email=' + email +
			 * '&message=' + message;
			 * 
			 * $.ajax({ type : "POST", dataType : "json", url :
			 * "http://www.bonisa.nl/web/forms/project_info.php", data :
			 * dataString, success : function(data) { if (data.result == true) {
			 * $(".project-message").html(data.message);
			 * $("#project-form")[0].reset(); } }
			 * 
			 * }); return false; });
			 */
		/*});
	}*/

	/***************************************************************************
	 * 
	 * Code to validate and submit the form for subscription to the magazine
	 * 
	 **************************************************************************/
	$('#subscribe-post').click(function() {
		/* check if url is available */
		if ($("#form-1 input[name=config-url]").length > 0 && $("#form-1 input[name=config-url]").val() != '') {

			/* validate form */
			$('#form-1 input.required, #form-1 textarea.required').each(function() {
				$(this).removeClass('invalid');
				if ($(this).val() == $(this).attr('startvalue')) {
					$(this).addClass('invalid');
				}
			});

			/* send from through ajax */
			if ($('#form-1 .required.invalid').length == 0) {
				$.ajax({
					type : "POST",
					url : $("#form-1 input[name=config-url]").val(),
					data : $("#form-1").serialize(),
					success : function(msg) {
						if (msg == 'success') {
							element = $("#form-1-success-message");
							$("#form-1").replaceWith(element);
							element.show();
						} else {
							alert('Sorry, something went wrong.');
						}
					}
				});
			}
			return false;
		}
	});

	/***************************************************************************
	 * 
	 * Code to validate and submit the digital newslettersubscription form
	 * 
	 **************************************************************************/
	$('#digital-newsletter-submit').click(function(event) {
		var url = "/web/forms/news_subscribe.php";

		/* validate form */
		$('#form-digital-newsletter input.required').each(function() {
			$(this).removeClass('invalid');
			if ($(this).val() == $(this).attr('startvalue')) {
				$(this).addClass('invalid');
			}
		});

		if ($('#form-digital-newsletter .required.invalid').length == 0) {
			if (!$("#form-digital-newsletter input[@name='groupId']:checked").val() && !jQuery('.footer-content input#newsletter-list-1:hidden')[0]) {
				alert($('#form-digital-newsletter-no-group-message').html());
			} else {
				$.ajax({
					type : "POST",
					url : url,
					data : $("#form-digital-newsletter").serialize(),
					success : function(msg) {
						if (msg == 'success') {
							element = $("#form-digital-newsletter-success-message");
							$("#form-digital-newsletter").replaceWith(element);
							element.show();
						} else if (msg == 'already-exists') {
							element = $("#form-digital-newsletter-already-exists-message");
							$("#form-digital-newsletter").replaceWith(element);
							element.show();
						} else {
							alert('Sorry, something went wrong.');
						}
					}
				});
			}
		}
		return false;
	});

	/***************************************************************************
	 * 
	 * Code to validate and submit the contact page form
	 * 
	 **************************************************************************/
	$('#submit-contact').click(function() {

		/* check if url is available */
		if ($("#form-contact input[name=config-url]").length > 0 && $("#form-contact input[name=config-url]").val() != '') {

			/* validate form */
			$('#form-contact input.required, #form-contact textarea.required').each(function() {
				$(this).removeClass('invalid');
				if ($(this).val() == '') {
					$(this).addClass('invalid');
				}
			});

			/* send from through ajax */
			if ($('#form-contact .required.invalid').length == 0) {

				/* check if form is for USA and change 'to' e-mail if needed */
				if ($('#form-contact-config-to-usa').length > 0) {
					var country = $('#form-contact-country').val().toLowerCase();
					if (country.toLowerCase().indexOf("us") >= 0 || country.toLowerCase().indexOf("united") >= 0) {
						$('#form-contact-config-to').val($('#form-contact-config-to-usa').val());
					} else {
						$('#form-contact-config-to').val($('#form-contact-config-to-canada').val());
					}
				}

				/* post the form */
				$.ajax({
					type : "POST",
					url : $("#form-contact input[name=config-url]").val(),
					data : $("#form-contact").serialize(),
					success : function(msg) {
						if (msg == 'success') {
							element = $("#form-contact-success-message");
							$("#form-contact").replaceWith(element);
							element.show();
						} else {
							alert('Sorry, something went wrong.');
						}
					}
				});
			}
		}
		return false;
	});

});



/*******************************************************************************
 * 
 * Function setPagination
 * 
 * This custom fuction is called by the paginator jquery plugin each time a
 * pagination function is called or when the paginator is initialized. This
 * function creates a number of wrappers and moved the dom objects to the
 * correct locations so we can style them.
 * 
 ******************************************************************************/
function setPagination() {

	// Add styled classes
	$('.paginator').append('<div class="first"></div>');
	$('.paginator').append('<div class="prev"></div>');
	$('.paginator').append('<div class="pages"><div class="pages-inner"></div></div>');
	$('.paginator').append('<div class="next"></div>');
	$('.paginator').append('<div class="last"></div>');

	// Move to required position
	$('.paginator a').appendTo('.pages-inner');
	$('.pages-inner a:first').appendTo('.first');
	$('.pages-inner a:last').appendTo('.last');
	$('.pages-inner a:first').appendTo('.prev');
	$('.pages-inner a:last').appendTo('.next');

	// Set current page
	$('.pages a').each(function(index) {
		if ($(this).text() == currentPage) {
			$(this).addClass('currentPage');
		}
	});

}

/*******************************************************************************
 * 
 * Function to get cookie contents for 'active-project-donate from iframe
 * 
 ******************************************************************************/
function getProjectCookieValue() {
	return $.cookie("active-project-donate");
}

/*******************************************************************************
 * 
 * Misc legacy code... :(
 * 
 ******************************************************************************/
$(function() {
	var workgroupname = $("#workgroup-select").val();
	$('.werkgroep').html(workgroupname);

	$('.werkgroep-punaises div').each(function() {
		$(this).click(function() {
			// set id
			var id = $(this).attr("pageId");

			// set submenu active links
			$('.submenu-pagelink').removeClass("active");
			$('#submenu-pagelink-pageid-' + id).addClass("active");

			$('.werkgroep-punaises div').removeClass("active");
			var workgroup = $(this).attr("pageId");
			var workgroupname = $(this).attr("title");

			$('.success-message').html('');
			$('.kaart-formulier').show();

			$(this).addClass("active");

			$('.werkgroepen-kaart div').not($('.werkgroep-punaises div')).each(function() {

				var tid = $(this).attr("pageId");

				if (tid == id) {
					$(this).show();
					$(".werkgroep-punaises").show();

					$(".werkgroepen-kaart-formulier").animate({
						opacity : 0
					}, 150, function() {
						$('.werkgroep').html(workgroupname);
					});

					$(".werkgroepen-kaart-formulier").animate({
						opacity : 1
					}, 150);

				} else {
					$(this).hide();
					$('.werkgroep-punaises').show();

				}

			});

		});
	});

	$('.werkgroep-punaises div.active').trigger('click');

	$('#submit-donation').click(function() {
		submitDonationDetails($('#projectId').val(), $('#projectTitle').val(), $('#naam').val(), $('#adres').val(), $('#telefoon').val(), $('#donate-email').val(), $('#bedrag').val(), $('#opmerkingen').val());
		return false;
	});

	$('.close-message').click(function() {
		$(".footer-over").animate({
			opacity : 1
		}, 90);
		$('.news-message').hide();
	});

	$('.close-contact-message').click(function() {
		$(".kaart-omschrijving, .kaart-formulier").animate({
			opacity : 1
		}, 90);

		$('.contact-message').hide();
	});
});

function submitDonationDetails(projectId, projectTitle, naam, adres, telefoon, email, bedrag, opmerkingen) {
	var dataString = 'projectId=' + projectId + '&projectTitle=' + projectTitle + '&naam=' + naam + '&adres=' + adres + '&telefoon=' + telefoon + '&email=' + email + '&bedrag=' + bedrag + '&opmerkingen=' + opmerkingen;
	$.ajax({
		type : "POST",
		dataType : "json",
		url : "http://www.bonisa.nl/web/forms/contactsform.php?action=makedonation",
		data : dataString,
		success : function(data) {
			alert(data.message);
		}

	});
}

function subscribePostNewsletter(salutation, initials, recepient, street, zipcode, city) {
	if (recepient == 'Geadresseerde' || street == 'Straatnaam en nummer' || zipcode == 'Postcode' || city == 'Woonplaats')
		return false;

	var dataString = 'salutation=' + salutation + '&initials=' + initials + '&recepient=' + recepient + '&street=' + street + '&zipcode=' + zipcode + '&city=' + city;

	$.ajax({
		type : "POST",
		dataType : "json",
		url : "http://www.bonisa.nl/web/forms/newsletter.php?action=subscribe_post",
		data : dataString,
		success : function(data) {
			// alert(data.message);

			$(".footer-over").animate({
				opacity : 0.1
			}, 200);
			$('.news-message').show();
			$('.news-message p').html(data.message);

		}

	});

}





	$(document).ready(function(){

	//how much items per page to show
	var show_per_page = 4;
	//getting the amount of elements inside content div
	var number_of_items = $('#parent-blog').children().size();
	//calculate the number of pages we are going to have
	var number_of_pages = Math.ceil(number_of_items/show_per_page);

	//set the value of our hidden input fields
	$('#current_page').val(0);
	$('#show_per_page').val(show_per_page);

	//now when we got all we need for the navigation let's make it '

	/*
	what are we going to have in the navigation?
		- link to previous page
		- links to specific pages
		- link to next page
	*/
	if(number_of_items<=show_per_page){
	$('#page_navigation').css('display', 'none');
	}

	var navigation_html = '<a class="previous_link" href="javascript:previous();"> <<< Vorige blogs</a>';
	var current_link = 0;
	while(number_of_pages > current_link){
		navigation_html += '<a class="page_link" href="javascript:go_to_page(' + current_link +')" longdesc="' + current_link +'">'+ (current_link + 1) +'</a>';
		current_link++;
	}
	navigation_html += '<a class="next_link" href="javascript:next();">Meer blogs >>></a>';

	$('#page_navigation').html(navigation_html);

	//add active_page class to the first page link
	$('#page_navigation .page_link:first').addClass('active_page');

	//hide all the elements inside content div
	$('#parent-blog').children().css('display', 'none');

	//and show the first n (show_per_page) elements
	$('#parent-blog').children().slice(0, show_per_page).css('display', 'block');

});

function previous(){
	$('.next_link').css('display', 'inline');
	new_page = parseInt($('#current_page').val()) - 1;
	//if there is an item before the current active link run the function
	if($('.active_page').prev('.page_link').length==true){
		go_to_page(new_page);
	}
if($('.active_page').prev('.page_link').length==0){
$('.previous_link').css('display', 'none');
}

}

function next(){
	$('.previous_link').css('display', 'inline');
	new_page = parseInt($('#current_page').val()) + 1;
	//if there is an item after the current active link run the function
	if($('.active_page').next('.page_link').length==true){
		go_to_page(new_page);
	}
//alert(new_page);
if($('.active_page').next('.page_link').length==0){
$('.next_link').css('display', 'none');
}
}
function go_to_page(page_num){
	//get the number of items shown per page
	var show_per_page = parseInt($('#show_per_page').val());

	//get the element number where to start the slice from
	start_from = page_num * show_per_page;

	//get the element number where to end the slice
	end_on = start_from + show_per_page;

	//hide all children elements of content div, get specific items and show them
	$('#parent-blog').children().css('display', 'none').slice(start_from, end_on).css('display', 'block');

	/*get the page link that has longdesc attribute of the current page and add active_page class to it
	and remove that class from previously active page link*/
	$('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');

	//update the current page input field
	$('#current_page').val(page_num);
}
