/**
 * Laat een messagebox zien met alle attributen van het gegeven object
 * 
 * @param object het object waarvan de attributen getoond worden
 * @param functions boolean, laat al dan niet functies zien
 */
function printObject(object,functions){
	var text = '';
	for(val in object){
		if(typeof(object[val]) != 'function' || functions){
			if(object[val] != null){
				text += val + ' = ' + object[val] + '\n';
			}
		}
	}
	
	alert(text);
}

function dumpObject(object,functions){
	var text = '';
	for(val in object){
		if(typeof(object[val]) != 'function' || functions){
			if(object[val] != null){
				text += val + ' = ' + object[val] + '\n';
			}
		}
	}
	
	return text;
}

function errorHandler(message,url,lineNumber){
	return;
	var error = '';
	if(!url){
		error = dumpObject(message);
	}else{
		error = message + ' in ' + url + ' on line ' + lineNumber;
	}
	var ua = dumpObject(navigator);
	var plugins = '';
	if(navigator.plugins){
		for(var x=0;x<navigator.plugins.length;x++){
			if(x == 0 || (x != 0 && navigator.plugins[x-1].name != navigator.plugins[x].name)){
				plugins += navigator.plugins[x].name + '\n';
			}
		}
	}
	$.ajax({
		type: 'POST',
		url: theDomain + 'profiel/javascripterror',
		data: 'location=' + encodeURIComponent(window.location) + '&message=' + encodeURIComponent(message) + '&url=' + encodeURIComponent(url) + '&linenumber=' + encodeURIComponent(lineNumber) + '&ua=' + encodeURIComponent(ua) + '&plugins=' + encodeURIComponent(plugins)
	});
	
	return true;
};
if(theDomain.indexOf('localhost') == -1){
	window.onerror = errorHandler;
	if($.browser.opera){
		$(document).ready(function(){
			document.getElementsByTagName('body')[0].addEventListener('error',errorHandler,true);
		});
	}
}

/**
 * Returnt alle attributen van een object
 * 
 */
function returnObject(object,functions){
	var text = '';
	for(val in object){
		if(typeof(object[val]) != 'function' || functions){
			if(object[val] != null){
				text += val + ' = ' + object[val] + '\n';
			}
		}
	}
	
	return text;
}

function getObjReference(name) {
	element = document.getElementById(name);
	
	if(element == null) {
		if(PZNDEBUG == 1) {
			alert("getObjReference(" + name + "): no such object found!");
		}
	}
	return element; 
}

function conditionalRelocateBlank(condition, where1, where2) {
	if(condition){
		window.open(where1, 'ePGB');
	}else{
		window.open(where2, 'ePGB');
	}
}

function sure(msg, url) {
	if(confirm(msg)) {
		relocate(url);
	}
	return false;
}

function reallysure(msg, msgreally, url) {
	if(confirm(msg)) {
		if(confirm(msgreally)) {
			relocate(url);	
		}
	}
}

function relocate(url){
	window.location = url;
}

function openHelp(theURL) {
	window.open(theDomain + theURL, 'pznhelp', 'toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=yes,toolbar=yes,resizable=1,width=790,height=625');
}

/* 5 minutes before refresh */
var keepAliveTime = 5*60*1000;

$(document).ready(function(){
	setTimeout('keepAlive();', keepAliveTime);
});

function keepAlive() {
	var dummy = new Image();
	var theUrl = theDomain + 'index.php?module=login&action=keepalive&rand=' + Math.round(Math.random() * 1000000, 0);
	dummy.src = theUrl;
	setTimeout('keepAlive();', keepAliveTime);
}

function addPostfix( postfix ) {
	var loc = stripAnchor(window.location);
	
	if(loc.indexOf('?') != -1) {
		//Add using &
		loc += '&' + postfix;
	} else {
		//Add using ?
		loc += '?' + postfix;
	}

	return loc;
}

function stripAnchor( URL ) {
	var pos = URL.indexOf('#');
	
	if(pos != -1) {
		URL = URL.substring(0, pos);
	}
	
	return URL;
	
}

function flashMovie( url, width, height ) {
	
	theObj = '' +
	'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ' +
	'	codebase="https://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" ' +
	'	width="_WIDTH_" ' +
	'	height="_HEIGHT_" ' +
	'	id="2389802349" ' +
	'	align="middle">' +
	'	' +
	'	<param name="allowScriptAccess" value="sameDomain" />' +
	'	<param name="movie" value="_URL_" />' +
	'	<param name="quality" value="high" />' +
	'	<param name="bgcolor" value="#ffffff" />' +
	'	' +
	'	<embed src="_URL_" ' +
	'		quality="high" ' +
	'		bgcolor="#ffffff" ' +
	'		width="_WIDTH_" ' +
	'		height="_HEIGHT_" ' +
	'		name="PZN Video" ' +
	'		align="middle" ' +
	'		allowScriptAccess="sameDomain" ' +
	'		type="application/x-shockwave-flash" ' +
	'		pluginspage="https://www.macromedia.com/go/getflashplayer" />' +
	'</object>';
	
	
	theObj = theObj.replace( /_URL_/g, 	url );
	theObj = theObj.replace( /_WIDTH_/g, 	width );
	theObj = theObj.replace( /_HEIGHT_/g, 	height );
	
	write( theObj );
}

$(window).unload(function() {
	//Save scroll position of last page.
	var x = 0;
	var y = 0;
	
	if(document.all) {
		//x = document.body.scrollLeft;
		y = document.body.scrollTop;
		var y2 = document.documentElement.scrollTop;
		if(y2>y) y = y2;
	} else {
		//x = window.pageXOffset;
		y = window.pageYOffset;
	}
	
	Set_Cookie( 'scrollY', y, 1 );
});

function resizeImage(tag, max) {
	for(var i=0; i<document.images.length; i++) {
		img = document.images[i];

		if(img.id.indexOf(tag) > -1) {
			
			var factor;
			if(img.height < max && img.width < max) {
				factor = 1;
			} else {
				(img.height > img.width) ? factor = img.height / max : factor = img.width / max;
			}

			img.width = (img.width / factor);
			//img.height = (img.height / factor);
		}
	}
}

function switchBySingleID(id, firstClass, secondClass) {
	element = document.getElementById(id);
	
	if(element.className == firstClass) {
		element.className = secondClass;
	} else  element.className = firstClass;
}

function padTime(time) {
	return time < 10 ? "0" + time : time;
}

function formatTime(minutes){
	return (minutes % 60) ? Math.floor(minutes / 60) + ':' + padTime(minutes % 60) : (minutes / 60);
}

function customRound(value)
{
	return Math.round(parseFloat(value.toFixed(7)));
}

function formatValuta(str){
	str = str.toString();
	str = str.replace('.',',');
	var decimals = str.substring(str.indexOf(',')+1,str.length).length;
	
	if(str.indexOf(',') == -1){
		str += ',-';
	}else{
		for(var x=0;x<2-decimals;x++){
			str += '0';
		}
	}
	return str;
}

function unformatValuta(str){
	return parseFloat(str.substr(1).replace('-','00').replace(',','.'));
}

function formatFloat(value){
	return isNaN(value) ? '' : value.toFixed(2).replace('.', ',');
}

function shortLastName(lastName) {
	var skipNames = new Array('te','ter','ten','van','de','der','den','des','v/d','vd','het','in','\'s','\'','en');
	
	var pieces = lastName.split(' ');
	var goodPieces = new Array();
	
	for(i=0; i<pieces.length; i++) {
		var ok = 1;
		for(var j=0; j<skipNames.length; j++){
			if(pieces[i].toLowerCase() == skipNames[j]){
				ok = 0;
			}
		}
		if(ok){
			goodPieces.push(pieces[i]);
		}
	}
	
	if(!pieces.length){
		return '';
	}else if(!goodPieces.length){
		return pieces[0];
	}else{
		return goodPieces[0];
	}
}

function initials(voornaam, achternaam) {
	
	return '' + voornaam.substring(0,1) + shortLastName(achternaam);
	
}

function write(str) {
	document.write(str);
}


function getItemInURL(theArgName) {
	var sArgs = location.search.slice(1).split('&');
	var r = '';

	for (var i = 0; i < sArgs.length; i++) {
        if (sArgs[i].slice(0,sArgs[i].indexOf('=')) == theArgName) {
        	r = sArgs[i].slice(sArgs[i].indexOf('=')+1);
            break;
        }
    }
    
    
	return (r.length > 0 ? unescape(r).split(',') : '')
}

function Get_Cookie( name ) {
	
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
	{
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function Set_Cookie( name, value, expires, path, domain, secure ) {
	var today = new Date();

	today.setTime( today.getTime() );
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

// Working with factuur indicaties
function onClickIndicatieCheckboxFactuur(name) {
	onClickIndicatieCheckbox(name, [1,15]);
}

// Working with zorgtaak indicaties
function onClickIndicatieCheckboxZorgtaak(name) {
	onClickIndicatieCheckbox(name, [1,10]);
}

function onClickIndicatieCheckbox(name, wmoKeys){
	var checkboxes = document.getElementsByName(name);
	var a_wmo_checked = a_awbz_checked = false
	for(var x=0;x<checkboxes.length;x++){
		checkboxes[x].disabled = false;
		if(checkboxes[x].checked){
			if($.inArray(parseInt(checkboxes[x].value), wmoKeys) >  -1) a_wmo_checked = true;
			if($.inArray(parseInt(checkboxes[x].value), wmoKeys) == -1) a_awbz_checked = true;
		}
		
	}
	if(a_wmo_checked){
		for(var x=0;x<checkboxes.length;x++){
			if($.inArray(parseInt(checkboxes[x].value), wmoKeys) == -1)
				checkboxes[x].disabled = true;
		}
	}

	if(a_awbz_checked){
		for(var x=0;x<checkboxes.length;x++){
			if($.inArray(parseInt(checkboxes[x].value), wmoKeys) >  -1){
				checkboxes[x].disabled = true;
			}
		}	
	}
}

// 2011 indicatie JS for Huishoudelijk, Bemiddeling 
function onClickIndicatieCheckbox2011(name) {
	// 1 = Huishoudelijk, 11 = Bemiddeling
	processIndicatie(name, [1, 10, 11], [1,10]);
}

// Process indicaties for 2011
function processIndicatie(name, loneIds, groupIds) {
				
	$('input[@name="'+name+'"]').each(function(i) {
		$(this).attr("disabled", false);
	});
			
	for(i in loneIds) {
		if($('input[@name="'+name+'"][@value='+loneIds[i]+']').attr("checked") &&
				$('input[@name="'+name+'"]:checked').length > 1) {
			
			if($.inArray(loneIds[i], groupIds) > -1 && $('input[@name="'+name+'"]:checked').length <= groupIds.length)
				continue;
			else
				return;
		}
	}
	
	var disableLone = false;
	var disableOther = false;
	
	$('input[@name="'+name+'"]').each(function(i) {
		// If indicatie was checked
		if($(this).attr("checked")) {
			// If normal indicatie was checked, then disable all lone indicaties
			if($.inArray(parseInt($(this).val()), loneIds) == -1 && disableOther == false){
				disableLone = true;
			// If lone indicatie was checked, then disable all normal indicaties and other lone
			} else if (disableLone == false)  {
				disableOther = true;
				loneValue = $(this).val();
			}
		}
	});
					
	// Disabling of indicaties
	$('input[@name="'+name+'"]').each(function(i) {
		if(disableLone == true) {
			// If indicatie is lone - disable
			if($.inArray(parseInt($(this).val()), loneIds) > -1) {
				$(this).attr("disabled", true);
			}
		}
		
		if(disableOther == true) {
			// if indicatie is normal - disable, and disable other lones
			if($.inArray(parseInt($(this).val()), loneIds) == -1 || 
					($(this).val() != loneValue && 
							($.inArray(parseInt($(this).val()), groupIds) == -1 ||  
							 $.inArray(parseInt(loneValue), groupIds) == -1))) {
				
				$(this).attr("disabled", true);
			}
		}
	});
}
function getBrowserWidth(){
	if (self.innerHeight){ //all except Explorer
		return self.innerWidth;
	}
	else if (document.documentElement && document.documentElement.clientHeight){ //IE6 strict
		return document.documentElement.clientWidth;
	}
	else if (document.body){ // other Explorers
		return document.body.clientWidth;
	}
	return 0;
}

function getBrowserHeight(){
	if (self.innerHeight){ //all except Explorer
		return self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight){ //IE6 strict
		return document.documentElement.clientHeight;
	}
	else if (document.body){ //other Explorers
		return document.body.clientHeight;
	}
	return 0;
}

/**
 * Functie die een form submit via AJAX.
 * 
 * @param id id van de form
 */
function submitForm(id){
	var postData = '';
	$('#' + id + ' input,#' + id + ' select').each(function(){
		var type = $(this).attr('type');
		if(type == 'checkbox'){
			postData += '&' + $(this).attr('name') + '=';
			postData += $(this).attr('checked') ? encodeURIComponent($(this).attr('value')) : '0';
		}else if(type != 'submit' && type != 'button'){
			postData += '&' + $(this).attr('name') + '=' + encodeURIComponent($(this).val());
		}
	});
	postData = postData.substr(1);
	var action = $('#' + id).attr('action');
	$.ajax({
		type: 'POST',
		url: action,
		data: postData,
		dataType: 'xml',
		success: onAjaxSuccess
	})
}

/**
 * Kloont een javascript object, subobjecten exclusief
*/
function cloneObject(obj){
	var clone = new Object();
    for(i in obj){
        clone[i] = obj[i];
    }
    return clone;
}

function isValidHour(str){
	var hour = parseInt(str,10);
	return hour >= 0 && hour <=24;
}

function isValidMinutes(str){
	var minutes = parseInt(str,10);
	return minutes >= 0 && minutes <=59;
}

function isValidTime(str){
	var time = /^([0-9]{2}):([0-9]{2})$/.exec(str);
	var hour = parseInt(time[1],10);
	var minutes = parseInt(time[2],10);
	return (minutes >=0 && minutes <= 59 && hour >=0 && hour <=23) || (hour == 24 && minutes == 0);
}

function sureRelocateBlank(where){
	if(confirm("Weet je het zeker?")) {
		relocateBlank(where);
	}
}

function sureRelocate(where){
	if(confirm("Weet je het zeker?")){
		relocate(where);
	}
}

function relocateBlank(where) {
	window.open(where, 'ePGB');
}


/* For IndefiniteDateFormfield */
function toggleDateDisabled(key) {
	if($('#' + key + '_indefinite').attr('checked')) {
		$('#' + key + '_day').attr("disabled", "disabled");
		$('#' + key + '_month').attr("disabled", "disabled");
		$('#' + key + '_year').attr("disabled", "disabled");
		($('#' + key + '_day').val(0));
		($('#' + key + '_month').val(0));
		($('#' + key + '_year').val('0000'));
		$('#' + key + '_checkbox_selected').val(1);
	} else {
		$('#' + key + '_day').removeAttr("disabled");
		$('#' + key + '_month').removeAttr("disabled");
		$('#' + key + '_year').removeAttr("disabled");
		$('#' + key + '_indefinite').removeAttr('checked');
		$('#' + key + '_checkbox_selected').val(0);
	}
}

/* For CheckboxDateFormfield */
function toggleDateDisabled_inverse(key) {
	if(!$('#' + key + '_indefinite').attr('checked')) {
		$('#' + key + '_day').attr("disabled", "disabled");
		$('#' + key + '_month').attr("disabled", "disabled");
		$('#' + key + '_year').attr("disabled", "disabled");
		$('#' + key + '_day').val(0);
		$('#' + key + '_month').val(0);
		$('#' + key + '_year').val('0000');
		$('#' + key + '_checkbox_selected').val(0);
		$('#' + key + '_indefinite').removeAttr('checked');
	} else {
		$('#' + key + '_day').removeAttr("disabled");
		$('#' + key + '_month').removeAttr("disabled");
		$('#' + key + '_year').removeAttr("disabled");
		$('#' + key + '_checkbox_selected').val(1);
	}
}

/* For CheckboxTextFormfield */
function toggleTextboxDisabled(key) {
	if($('#' + key + '_checkbox').attr('checked')) {
		$('#' + key).attr("disabled", "disabled");
		$('#' + key).val('');
	} else {
		$('#' + key).removeAttr("disabled");
		$('#' + key + '_checkbox').removeAttr('checked');
	}
}

/* Voor als een inverted IndefiniteFormField switched (en er een eventhandler al op zit) handig */
function herinnering_changed(target) {
		
	if($('#' + target + '_indefinite').attr("checked")) {
		$('#' + target + '_day').show();
		$('#' + target + '_month').show();
		$('#' + target + '_year').show();
		$('#' + target + '_checkboxtext').show();
				
	} else {
		$('#' + target + '_day').hide();
		$('#' + target + '_month').hide();
		$('#' + target + '_year').hide();
		$('#' + target + '_checkboxtext').hide();
	}
}

function showNavigation(){
	if($('#navigationdropdown').is(':visible')){
	//	$('#navigationdropdown').hide();
	}else{
		$('#navigationdropdown').show();
		var pos = $('#periode').offset();
		$('#navigationdropdown').css({left: pos.left-5, top: pos.top + 25, width: $('#periode').width() + 14}).show();
	}
}

function toFloat(value)
{
	if (value == '' || value == undefined)
		return parseFloat('0.0');
	
	if (value.indexOf(',') != -1)
		value = value.replace('.', '');	
	
	return parseFloat(value.replace(',', '.'));
}

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                return true;
            }
        }
    }
     return false;
}
