function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof window.onload != 'function') {
		window.onload = func;
	} 
	else {
		window.onload = function(){
			oldonload();
			func();
		};
	}
}

function loadCufon(){
	Cufon.replace('h3');  
	Cufon.replace('h2');
	Cufon.replace('.next'); 
	Cufon.replace('ul.accounts li span.title');
	Cufon.replace('#sidebar ul', { hover: true });
	Cufon.replace('#footer');
	Cufon.replace('#budget dl');
	Cufon.replace('#progress .customHeader em');
	Cufon.replace('p.home_h1_sub');
	Cufon.replace('.binnenkort_online');
}

function callback(name) {	
	$("#img_"+name).fadeIn('slow');
}

function showPic(name){
	var std_img = document.getElementById('std');
	std_img.style.display = "none";
	
	var holder = document.getElementById('imageHolder');
	var images = holder.getElementsByTagName('img');
	var visible_images = 0;
	for(var i=0; i < images.length;i++) {
		if(images[i].style.display == 'inline') {
			if(images[i].id != 'img_'+name) {
				$("#"+images[i].id).fadeOut('fast',	callback(name) );
			}
			visible_images += 1;
		}
	}

	if(name && visible_images === 0) {
		$("#img_"+name).fadeIn('slow');
	}
}

function loadCharts(){
	$('table#voorbeeld').visualize({
		type: 'pie', 
		pieMargin: 10, 
		width: 435,
		height: 150,
		colors: ['#888', '#C6AE3E']
	});
}

addLoadEvent(loadCharts);

function toggler(){
	$(".surveyResults").click(function () {
		$(this).next().slideToggle();
		if ( $(this).next().find(".visualize").length === 0 ) {
			var type_post = $(this).next().find("table").attr("id");
			$('table#'+type_post).visualize({ 
				width: 900,
				height: 150,
				colors: ['#880000', '#C6AE3E']
			});
		}
	});
	$("body#statistieken ul li").click(function () {
		$(this).find(".sliderTrigger").slideToggle("300");
		$(this).toggleClass("focus");
	});
}

addLoadEvent(toggler);

$(document).ready(function() {
	$('input[type="text"]').focus(function() { $(this).toggleClass("focusField"); } );
	$('input[type="text"]').blur(function() { $(this).toggleClass("focusField"); } );
	$('textarea').focus(function() { $(this).toggleClass("focusField"); } );
	$('textarea').blur(function() { $(this).toggleClass("focusField"); } );
}); 

function prepareGallery() {
	if (!document.getElementsByTagName) {return false;}
	if (!document.getElementById) {return false;}
	if (!document.getElementById("content")) {return true;}
	var list = document.getElementById("content");
	var item = list.getElementsByTagName("li");
	for ( var i=0; i < item.length; i++ ) {
		if(item[i].id) {
			$("#"+item[i].id).mouseenter( function (){ return showPic(this.id); });
		}
	}
}

addLoadEvent(prepareGallery);
addLoadEvent(loadCufon);

$(document).ready(function() {
	$("div.popup").click(function(event){ event.stopPropagation(); });
	$("ul.accounts span.itembar").createStats();
	$(".popup .close").click(function(){
		// close popups
		closePopups();
		});
	// xhtml valid open link in new target.
	$("a.targetBlank").click(function() {
		window.open(this.href); return false;
	});	
	$(".targetBlank").keypress(function() {
		window.open(this.href); return false;
	});	
});

/**
 * VISUALISATIE BEDRAGEN
 */

$.fn.createStats = function() {
	
	var highest_value = null;
	var values = new Array();
	
	// get all the values and put them in an array.
	$(this).children("span.maxBesparing").each(function(){
		var content = $(this).html();
		//var regex = /[^a-zA-Z 0-9]+/g;
		//var value = content.replace(regex, "")
		var value = content;

		values.push( parseInt( value ) );
	});
	
	// sort the array so we get the highest value
	values.sort(function(a,b){return b - a});
	
	// set the highest value
	highest_value = values[0];
	percentage = parseInt(highest_value)/100;
	
	// set the maxBesparingen bar
	$(this).children("span.maxBesparing").each(function(){
		var content = $(this).html();
		//var regex = /[^a-zA-Z 0-9]+/g;
		//var width = parseInt( content.replace(regex, "") )/percentage;
		var width = parseInt( content )/percentage;
				
		$(this).siblings(".percentage").find(".scalable").animate({ width: width+"%"}, 1000);
	});
	
	// set
	$(this).children("span.huidigeBesparing").each(function(){
		var content = $(this).html();
		//var regex = /[^a-zA-Z 0-9]+/g;
		//var width = parseInt( content.replace(regex, "") )/percentage;
		var width = parseInt( content )/percentage;
				
		$(this).siblings(".percentage").find(".besparing").animate({ width: width+"%"}, 1000);
	});
	
}

/**
 * POPUP
 */
$( function () {
	
	$(".accounts span.itembar").click( function(event) {

		var subpost = false;
		// stop propagation
		event.stopPropagation();

		//check if the item has subposts	
		if( $(this).siblings("div.popup").length == 0 && ( $(this).parent().parent().hasClass("accounts") ) &&  ( $(this).children(".subpost").length > 0 ) ) { 
			
			var isFolded = $(this).parent().hasClass("folded");
			
			// loop trough all folded posts and unfold
			$(".accounts li.folded").each(function(){
				$(this).removeClass("folded");
				$(this).find(".subpost").hide();
			});
			
			if( isFolded ) {
				$(this).parent().addClass("folded");
				$(this).find(".subpost").show();
			}
			
			//unfold the item
			$(this).parent().toggleClass("folded");
			$(this).find(".subpost").toggle("slide",{ direction: "up" }, 600);

			closePopups();		
			
			return false;
		} else if( $(this).parent().parent().hasClass("subpost") ) {
			subpost = true;
		}
		if( !$(this).parent().hasClass("active") ) {
			if( !$(this).parent().parent().parent().parent().hasClass("folded") ) {
				closePopups();
				// unfold if item is folded
				var thisJQ = $(this);
				var slideJQ = $(".accounts li.folded").find(".subpost");
				if (slideJQ.length != 0) {
					slideJQ.toggle("slide",{ direction: "up" }, 600, function(){
						$(".accounts li.folded").removeClass("folded");
						openPopup(thisJQ);
					});
				}
				else {
					openPopup(thisJQ);
				}
			}
			else {
				closePopups();
				openPopup($(this));
			}
		}
		else {
			$(this).parent().toggleClass("active");
			$(this).parent().children(".popup").animate({left: "0px", opacity: 0}, 750, function(){ 
				$(this).css("display", "none");
				resetPopup($(this) );
			});				
		}
	});
});

function openPopup(jqe){

	jqe.parent().toggleClass("active");

	// Place slide below: #rightColumn h2 or #budget, whichever is lower.
	// slide is now always in the visible window, but also always below the budget and the rightcol heading.
	// get #rightColumn h2 bottom
	var rightColH2Object = $('#rightColumn').find('h2');
	var offsetColH2 = rightColH2Object.offset();
	var budgetObject = $('#budget');
	var offsetBudget = budgetObject.offset();
	var topDistanceColH2 =  offsetColH2.top + rightColH2Object.outerHeight();
	var topDistanceBudget =  offsetBudget.top + budgetObject.outerHeight();
	var offsetParent = jqe.parent().offset();
	var topDistance = topDistanceColH2 - offsetParent.top;
	if (topDistanceColH2 < topDistanceBudget) {
		topDistance = topDistanceBudget - offsetParent.top;
	}
	
	jqe.parent().children(".popup").css('top', topDistance + 'px' );
	jqe.parent().children(".popup").toggle().animate({opacity: 1, left: "478", top: topDistance}, 750, "swing", function(){
	
		if ( jqe.parent().find(".visualize").length === 0 ) {
			
			var type_post = jqe.parent().find("table").attr("id");
			
			//make some charts
			$('table#'+type_post).visualize({
				type: 'pie', 
				pieMargin: 10, 
				width: 465,
				height: 180,
				colors: ['#888', '#C6AE3E']
			});
		}
	});
}

function insertAfter(newElement, targetElement){
	var parent = targetElement.parentNode;
	if(parent.lastChild == targetElement) {
		parent.appenChild(newElement);
	} else {
		parent.insertBefore(newElement, targetElement.nextSibling);
	}
}

/**
 * MENU
 */

function navigateSendForm()
{
	$("li#p1").click(function (){
	$("form").append("<input type='hidden' name='pg' value='1' />");
	$("form").submit();		
	} );
	
	$("li#p2").click(function (){
	$("form").append("<input type='hidden' name='pg' value='2' />");
	$("form").submit();		
	} );
	
	$("li#p3").click(function (){
	$("form").append("<input type='hidden' name='pg' value='3' />");
	$("form").submit();		
	} );

	$("li#p4").click(function (){
	$("form").append("<input type='hidden' name='pg' value='4' />");
	$("form").submit();		
	} );	
	
	$("li#last").click(function (){
	$("form").append("<input type='hidden' name='pg' value='5' />");
	$("form").submit();		
	} );	

	$("span.toPage1").click(function (){
	$("form").append("<input type='hidden' name='pg' value='1' />");
	$("form").submit();		
	} );
	
	$("span.toPage2").click(function (){
	$("form").append("<input type='hidden' name='pg' value='2' />");
	$("form").submit();		
	} );
	
	$("span.toPage3").click(function (){
	$("form").append("<input type='hidden' name='pg' value='3' />");
	$("form").submit();		
	} );
	
	$("span.toPage4").click(function (){
	$("form").append("<input type='hidden' name='pg' value='4' />");
	$("form").submit();		
	} );	
	$("span.toPage5").click(function (){
	$("form").append("<input type='hidden' name='pg' value='5' />");
	$("form").submit();		
	} );	
}

addLoadEvent(navigateSendForm);

function addCommas(nStr)
{
	nStr += '';
	var x = nStr.split(',');
	var x1 = x[0];
	var x2 = x.length > 1 ? ',' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}

function rmFormat(nStr)
{
	var noFormat = nStr.replace(/\./g, "");
	noFormat = noFormat.replace("€ ", "");
	noFormat = noFormat.replace(",-", "");
	return noFormat;
}

function scrolToWarning()
{
	var isWarning = $("#error");
	if(typeof(isWarning) !== 'undefined') 
	{
		var offset = isWarning.offset();
		scroll(0, offset.top);
	}
}

function scrolToWarning()
{
	var isWarning = $("#error");
	if(typeof(isWarning) !== 'undefined') 
	{
		var offset = isWarning.offset();
		window.scroll(0, offset.top);
	}
}

addLoadEvent(scrolToWarning);

function closePopups() {
	//check if other items are active
	$(".accounts li").each( function(i) {
		$(this).children(".popup").each( function(i){
			if( $(this).parent().hasClass("active") ){
				$(this).parent().toggleClass("active");
				$(this).animate({left: "0px", opacity: 0}, 750, function(){ 
					$(this).css("display", "none");
					// reset values
					resetPopup($(this) );
				});
			}
		});
	});
}

function postcodeValidation() {
	var postcodeInputElement = $("#useritem_postcode");
	if (postcodeInputElement != null) {
		$(postcodeInputElement).change(function () {
			var postcodeInputvalue = $("#useritem_postcode").attr('value');
			postcodeInputvalue = postcodeInputvalue.toUpperCase();
			postcodeInputvalue = jQuery.trim(postcodeInputvalue);
			if (postcodeInputvalue != '' && !VerifyPostcode_check(postcodeInputvalue)) {
				if ( $('#useritem_postcode').next().hasClass("inputError") ) {
					$('#useritem_postcode').next().html(postcodeInputvalue + ' is geen correcte postcode.');
				}
				else {
				$('<p class="inputError">' + postcodeInputvalue + ' is geen correcte postcode.</p>').insertAfter('#useritem_postcode');
				}
				setTimeout(function() { $("#useritem_postcode").focus();$("#useritem_postcode").select(); }, 0);
			}
			else {
				if (postcodeInputvalue.length == 6) { 
					var pc = postcodeInputvalue.substr(0,4) + ' ' + postcodeInputvalue.substr(4,2); 
					postcodeInputvalue = pc;
					}
				if ( $('#useritem_postcode').next().hasClass("inputError") ) {
					$('#useritem_postcode').next().remove();
				}
				$('#useritem_postcode').val(postcodeInputvalue);
			}
		});
	}
}
addLoadEvent(postcodeValidation);

function VerifyPostcode_check(str) {
	  if (str.length == 6) {var pc = str.substr(0,4) + ' ' + str.substr(4,2); str = pc}
	  str=str.replace(/(^\s*)|(\s*$)/g, "");
	  if(!str.match(/^[1-9][0-9]{3}[\s][A-Z]{2}$/i)) {
	    return false;
	  } else {
	    return true;
	  }
	}

