//var slidercontent = new Array();
var sliderlist = new Array();
var lastButton = new Array();
var curLi = 0;
var curOption = new Array();
var curOptionName = new Array();
var curOptionPrice = new Array();
var tmpOptionPrice = new Array();
var begrotingen = new Array();
var werkelijken = new Array();

var newRows = 1;

var options = {activationEvent: 'mouseover', animateHeight: false, buttons: false};

Array.prototype.sum = function() {
	return (! this.length) ? 0 : this.slice(1).sum() + ((typeof this[0] == 'number') ? this[0] : 0);
};

function mousePos(e){
	mouse = new Array();
	boxLeft = boxTop = 0;
	headerHeight = 210;
	addLeft = 90;
	
	if(e.pageX || e.pageY){
		mouse[1] = e.pageX - addLeft;
		mouse[2] = e.pageY - headerHeight;
	} else {
		mouse[1] = e.clientX - addLeft + document.body.scrollLeft;
		mouse[2] = e.clientY - headerHeight + document.body.scrollTop;
	}
	
	return mouse;
}

function toonbudget( catID, id2) {
	
	// vorige sluiten
	if( curLi && curLi != catID ) {
		document.getElementById('wizardOpen'+curLi).style.display = 'none';
		document.getElementById('wizardClosed'+curLi).style.display = 'block';
	}
	
	returnButton( catID );
	toon( 'wizardOpen'+catID, id2 );
	
	// huidige opslaan
	curLi = catID;
}

function toonTrouwzeker(e) {
	id = 'ballon_trouwzeker';
	
	mouse = mousePos(e);
	document.getElementById(id).style.left = mouse[1] + 85;
	document.getElementById(id).style.top = mouse[2] + 10;
	
	document.getElementById(id).style.visibility = 'visible';
	document.getElementById(id).style.display = 'block';
}

function verstopTrouwzeker(e) {
	id = 'ballon_trouwzeker';
	document.getElementById(id).style.visibility = 'hidden';
}

/*
function addSlider( slidername, featuresid, sliderid, id ) {
	// werkt zo niet
	
	slidername = new SlidingTabs(featuresid, sliderid, options );
					
					// this sets up the previous/next buttons, if you want them
					//$('previous').addEvent('click', tabs<?= $category[ 'ID' ] ?>.previous.bind(tabs<?= $category[ 'ID' ] ?>));
					//$('next').addEvent('click', tabs<?= $category[ 'ID' ] ?>.next.bind(tabs<?= $category[ 'ID' ] ?>));
					
					// this sets it up to work even if it's width isn't a set amount of pixels
					window.addEvent('resize', slidername.recalcWidths.bind(slidername));
					
					document.getElementById( sliderid ).style.display = 'none';
				
	sliderlist.push(id);
}
*/

function showSlider( id ) {
	
	curSlider = eval('tabs'+id );
	//document.getElementById( 'slider' ).innerHTML = slidercontent[id];
	
	// close all
	document.getElementById( 'slider_wrap' ).style.display = 'none';
	closeSliders();
	
	// open current
	document.getElementById( 'slider_wrap'+id ).style.display = 'block';
}

function closeSliders() {
		
	for( i=0; i<sliderlist.length; i++ ) {
		document.getElementById( 'slider_wrap'+sliderlist[i] ).style.display = 'none';
	}
}

function updateCosts2( tmp ) {
	
	var total = 0;
	
	if( tmp ) {
		for( i=0; i<tmpOptionPrice.length; i++ ) {
			if( typeof( tmpOptionPrice[i] ) != 'undefined' )
				total += parseInt( tmpOptionPrice[i] );
		}
		
	} else {
	
		for( i=0; i<curOptionPrice.length; i++ ) {
			if( typeof( curOptionPrice[i] ) != 'undefined' )
				total += parseInt( curOptionPrice[i] );
		}
	}
	
	document.getElementById('totalCosts').innerHTML = total;
	
	// voor extern gebruik
	updateLink( total );
}

function updateLink( money ) {
	// verwijder .00
	money = String( money );
	len = money.length;
	end = money.substr( len-3 );
	if( end == '.00' )
		money = money.substr( 0, len-3 );
	
	// trouwzeker offerte
	document.getElementById( 'extlink_trouwzeker' ).href = 'https://www.trouwzeker.nl/10029/1/offerte-aanvragen-tip.html?sReferal=Planmaken.nl&sInsured_money='+money;
}

function changeCosts( catID, name, price, tmp ) {

	tmpOptionPrice[catID] = price;
	
	// kostenlijst updaten
	if( name == '' )
		document.getElementById( 'kostencat'+catID ).innerHTML = '(geen)';
	else
		document.getElementById( 'kostencat'+catID ).innerHTML = name;//'- '+name;
		
	document.getElementById( 'prijs'+catID ).innerHTML = price;
	
	//if( tmp )
		updateCosts2( tmp );
	//else
	//	updateCosts();
}

function suggestOption( catID, ID, name, price ) {
	// rode bolletje
	
	button = document.getElementById( 'button'+catID );
	//buttonDiv = document.getElementById( 'buttonDiv'+catID );
	
	/*
	// methode 1: nieuwe positie bolletje
	newleft = ( nr-1 ) * width + width/2;
	newleftDiv = ( nr-1 ) * width;
	button.style.left = newleft;
	button.style.visibility = 'visible';
	*/
	
	// methode 2: ander plaatje
	document.getElementById( 'li'+ID ).style.background = "url('Pictures/budgetwizard/bar-button.png') no-repeat top center";
	// vorige sluiten
	if( typeof( lastButton[ catID ] ) != 'undefined' && lastButton[ catID ] != ID )
		document.getElementById( 'li'+lastButton[ catID ] ).style.background = "url('Pictures/budgetwizard/bar-line.jpg') no-repeat top center";
	// geselecteerde sluiten
	if( typeof( curOption[ catID ] ) != 'undefined' && curOption[ catID ] != ID )
		document.getElementById( 'li'+curOption[ catID ] ).style.background = "url('Pictures/budgetwizard/bar-line.jpg') no-repeat top center";
	
	lastButton[ catID ] = ID;
	
	changeCosts( catID, name, price, true );
}

function returnButton( catID ) {
	// vorige sluiten
	if( typeof( lastButton[ catID ] ) != 'undefined' )
		document.getElementById( 'li'+lastButton[ catID ] ).style.background = "url('Pictures/budgetwizard/bar-line.jpg') no-repeat top center";
	// geselecteerde openen
	if( typeof( curOption[ catID ] ) != 'undefined' )
		document.getElementById( 'li'+curOption[ catID ] ).style.background = "url('Pictures/budgetwizard/bar-button.png') no-repeat top center";
	
}

function returnOption( catID ) {
	
	if( typeof( curOptionName[catID] ) == 'undefined' )
		name = '';
	else
		name = curOptionName[catID];
		
	if( typeof( curOptionPrice[catID] ) == 'undefined' )
		price = 0;
	else
		price = curOptionPrice[catID];
		
	tmpOptionPrice[catID] = 0;
	//veld = eval( 'document.kostenlijst.prijs'+catID );
	
	changeCosts( catID, name, price, false );
}

function selectOption( catID, ID, name, price, el ) {
	
	suggestOption( catID, ID, name, price );
	
	// oude selectie terugdraaien
	if( typeof( curOption[catID] ) != 'undefined' && curOption[catID] != ID ) {
		
		liID = 'li'+curOption[catID];
		//document.getElementById( liID ).style.backgroundColor = 'white';
		document.getElementById( liID ).className = 'budgetOptionNotActive';
	}
	
	if( typeof( el ) == 'undefined' ) {
		el = document.getElementById( 'li'+ID );
	}
	
	//el.style.backgroundColor = 'yellow';
	el.className = 'budgetOptionActive';
	
	// selectie opslaan
	curOption[catID] = ID;
	curOptionName[catID] = name;
	
	// kostenlijst updaten
	veld = eval( 'document.kostenlijst.prijs'+catID );
	veld.value = ID;
	curOptionPrice[catID] = price;
	changeCosts( catID, name, price, false );
}

function toCurrency( vIn, el ) {
	
	if( vIn == '' ) {
		v = 0.00;
		el.value = '0,00';
	} else {
		v = vIn.replace( /,/g, '.' );
		v = parseFloat( v );
	}
		
	if( typeof( v ) != 'number' || isNaN(v) ) {
		alert( "'"+vIn+"' is geen geldig bedrag!" );
		v = 0.00;
		el.value = '0,00';
	}
	
	return v;
}

function toCurrency2( vIn, el ) {
	// te complex, werkt niet
	
	// kijk of er duizendtal-punten in staan, dan verwijderen
		dotparts = vIn.split('.');
		nrDotparts = dotparts.length;
		
		// niet vervangen als laatste part 2 cijfers groot is
		lastDotpart = dotparts[ nrDotparts-1 ];
		if( lastDotpart.length != 3 ) {
			dotparts[ nrDotparts-2 ] = dotparts[ nrDotparts-2 ] + ',' + lastDotpart;
			dotparts[ nrDotparts-1 ] = '';
		}
		
		vNew = '';
		for(i=0; i<nrDotparts; i++) {
			vNew += dotparts[i];
		}
	
	// weer . van , maken
	v = vNew.replace( /,/g, '.' );
	v = parseFloat( v );
	
	if( typeof( v ) != 'number' || isNaN(v) ) {
		alert( "'"+vIn+"' is geen geldig bedrag!" );
		v = 0.00;
		el.value = '0,00';
	}
	
	return v;
}

function setDiff( ID, pre ) {
	
	richtprijsEl = eval( 'document.kostenlijst.'+pre+'budget'+ID );
	richtprijs = richtprijsEl.value;
	werkelijkEl = eval( 'document.kostenlijst.'+pre+'prijs'+ID );
	werkelijk = werkelijkEl.value;
		
	richtprijs = toCurrency( richtprijs, richtprijsEl );
	werkelijk = toCurrency( werkelijk, werkelijkEl );
	
	// nieuwe waarden opslaan
	begrotingen[ ID ] = richtprijs;
	werkelijken[ ID ] = werkelijk;
	
	verschil = richtprijs - werkelijk;
	verschil = parseFloat( verschil );
	
	verschilStr = verschil.toFixed(2);
	document.getElementById( pre+'diff'+ID ).innerHTML = verschilStr.replace( '.', ',' );
	
	if( verschil < 0 )
		document.getElementById( pre+'diff'+ID+'div' ).style.color = 'red';
	else if( verschil >= 0 )
		document.getElementById( pre+'diff'+ID+'div' ).style.color = 'green';
		
	updateCosts();
	disableToSave();
}

function disableToSave() {
	txtExcel = ''//"Voordat uw budgetplanner kan worden geopend in Excel moeten de wijzigingen worden opgeslagen!";
	txtPdf = ''//"Voordat u uw budgetplanner kunt printen moeten de wijzigingen worden opgeslagen!";
	newHtml = "<img src='Pictures/budgetwizard/csv_gr.png' onMouseover='showDisabledDiv(\"disabledCSV\", event)' onMouseout='hideDisabledDiv(\"disabledCSV\")' alt='"+txtExcel+"' /> <img src='Pictures/budgetwizard/pdf_gr.png' onMouseover='showDisabledDiv(\"disabledPDF\", event)' onMouseout='hideDisabledDiv(\"disabledPDF\")' alt='"+txtPdf+"' /></a>";
	document.getElementById( 'exportButtons' ).innerHTML = newHtml;
}

function showDisabledDiv( id, e ) {
	mouse = mousePos(e);
	document.getElementById(id).style.left = mouse[1]+0;
	document.getElementById(id).style.top = mouse[2] + 130;
	document.getElementById(id).style.display = 'block';
}
function hideDisabledDiv( id ) {
	document.getElementById(id).style.display = 'none';
}

function addOption() {
	tabel = document.getElementById( 'kostentabel' );
	
	lastRow = tabel.rows.length;
    row = tabel.insertRow(lastRow-2);
	row.id = 'tr'+newRows;
	
	// cellen toevoegen, in omgekeerde volgorde
	budgetDelete = row.insertCell(0);
	budgetDiff = row.insertCell(0);
	budgetWerkelijk = row.insertCell(0);
	budgetBudget = row.insertCell(0);
	budgetPrijs = row.insertCell(0);
	budgetName = row.insertCell(0);
	
	budgetName.innerHTML = "<input type='hidden' name='ID"+newRows+"' value='new' /><input type='text' name='option"+newRows+"' />";
	budgetBudget.innerHTML = " &euro; <input type='text' name='newbudget"+newRows+"' value='0,00' onChange='setDiff("+newRows+", \"new\");' onFocus='this.select();' />";
	budgetWerkelijk.innerHTML = " &euro; <input type='text' name='newprijs"+newRows+"' value='0,00' onChange='setDiff("+newRows+", \"new\");' onFocus='this.select();' />";
	budgetDiff.innerHTML = "<div id='newdiff"+newRows+"div'> &euro; <span id='newdiff"+newRows+"'>0,00</span></div>";
	budgetDelete.innerHTML = "<a class='verwijderknop' href='#' onClick='deleteOption("+newRows+", false)'><img src='Pictures/delete.png' alt='Verwijder budgetpost'></a>";
	
	/*
	totalTR = tabel.lastChild;
	
	while( totalTR.nodeName != 'TR' ) {
		totalTR = totalTR.previousSibling;
		alert(totalTR.nodeName);
	}
	
	newTR = document.createElement('tr');
	newTR.innerHTML = "<td><input type='text' name='option"+newRows+"'></td><td></td><td> &euro; <input type='text' name='prijs"+newRows+"' onFocus='this.select();' onChange='' /></td><td></td>";
	
	tabel.insertBefore( newTR, totalTR );
	*/
	newRows++;
}

function deleteOption( ID, inDB ) {
	rowNr = document.getElementById( 'tr'+ID ).rowIndex;
	document.getElementById( 'kostentabel' ).deleteRow(rowNr);
	
	begrotingen[ ID ] = 0;
	werkelijken[ ID ] = 0;
	updateCosts();
	disableToSave();
	
	// uit database verwijderen
	if( inDB ) {
		// te verwijderen IDs opslaan als string met IDs gescheiden door $
		document.kostenlijst.toDelete.value += '$'+ID;
	}
}

function array_sum( array ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nate
    // +   bugfixed by: Gilbert
    
    var key, sum = 0;
    
    // input sanitation
    if (typeof array !== 'object') {
        return null;
    }
    
    for (key in array) {
        //tester_print_r(typeof sum);
        sum += (array[key] * 1);
    }
 
    return sum;
}
