/**
 *
 * $Id: dtc.js,v 1.3 2007-09-18 14:21:26 rein Exp $
 * @author Michiel Brandenburg
 * @copyright 2007 Prezent Internet BV
 */
function getxmlHttpObject()
{
    var xmlHttp;
    try{
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }catch (e){
    // Internet Explorer
        try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e){
            try{
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }catch (e){
             //DO NOTHING
            }
        }
    }
    return xmlHttp;
}
var xmlHttp;

function toCurrency(val) {
    if( !val ) {
        return 0;
    }

	var res = 0;
	var USNotation = val.replace( ",", "." );
	var fVal = parseFloat( USNotation );
	if ( !isNaN( fVal ) ) {
		res = fVal;
	}
	return res;
}



/*
 * End Term Loan (Slottermijn financiering)
 */

function ETLSetCosts() {
	var elTotalCosts = document.frm.totale_kosten;
    if ( elTotalCosts ) {
        var fAutoInclOpties        = toCurrency( document.frm.auto_incl_opties.value );
        var fOverTeSluitenLeningen = toCurrency( document.frm.over_te_sluiten_leningen.value );
        var fVerlengdeGarantie     = toCurrency( document.frm.verlengde_garantie.value );

        elTotalCosts.value = (fAutoInclOpties + fOverTeSluitenLeningen + fVerlengdeGarantie).toFixed(2);
    }
}

function ETLSetDiscount() {

    var elTotalDiscount = document.frm.totale_korting;
    if ( elTotalDiscount ) {
        var fInruilWagen         = toCurrency( document.frm.inruilwagen.value );
        var fContanteAanbetaling = toCurrency( document.frm.contante_aanbetaling.value );

        elTotalDiscount.value = (fInruilWagen + fContanteAanbetaling).toFixed(2);
    }
}

function ETLSetSlottermijn() {
	var frm = document.forms['frm'];
	if ( frm ) {
	    var elAutoInclOpties  = frm.auto_incl_opties;
    	var elSlottermijn     = frm.slottermijn;
	    var elSlottermijnPerc = frm.slottermijn_perc;
    	var elTotalCosts		= frm.totale_kosten;
    	var aanbetaling			= frm.aanbetaling;

    	var bedrag			= toCurrency(elAutoInclOpties.value);
    	if (bedrag <= 0) { return; }

	    if ( frm.aanbetaling && toCurrency(aanbetaling.value) > 0) {
	    	bedrag = bedrag-toCurrency(aanbetaling.value);
	    }

	    if ( elTotalCosts && elSlottermijn && elSlottermijnPerc ) {
	        elSlottermijn.value = (Math.round( ( toCurrency( elTotalCosts.value ) / 100 ) * elSlottermijnPerc.value )).toFixed(2);
    	}
    	else {
    		//priceCard, slightly different fields, same functionality
    		if( elAutoInclOpties && elSlottermijn && elSlottermijnPerc ) {
    			elSlottermijn.value = Math.round( ( bedrag / 100 ) * elSlottermijnPerc.value );
    			if ( elSlottermijn.onblur ) {elSlottermijn.onblur(); }
    		}
    	}
    }
}

/**
 * Calculate price cart.
 *
 */
function calculatePriceCart(type) {
	var types = ['standard', 'percentage', 'endterm'];
	if (type == null) {
		type = types[0];
	}
	var frm = document.forms['frm'];
	if ( frm ) {
	    var elAutoInclOpties  = frm.auto_incl_opties;
    	var elSlottermijn     = frm.slottermijn;
	    var elSlottermijnPerc = frm.slottermijn_perc;
    	var elTotalCosts	  = frm.totale_kosten;
    	var aanbetaling		  = frm.aanbetaling;

    	var bedrag			= toCurrency(elAutoInclOpties.value);
    	if (bedrag <= 0) { return; }

	    if ( toCurrency(aanbetaling.value) > 0) {
	    	bedrag = bedrag-toCurrency(aanbetaling.value);
	    }

   		//priceCard, slightly different fields, same functionality
   		if( type == 'standard' || type == 'percentage') {
   			elSlottermijn.value = Math.round( ( bedrag / 100 ) * elSlottermijnPerc.value );
   		} else if ( type == 'endterm') {
   			elSlottermijnPerc.value = (elSlottermijn.value / (Math.round( ( bedrag / 100 )))).toFixed(2);
   		}

    }
}

function LTLSetAanbetaling() {
	if ( document.getElementById("frm") ) {

		var targetForm		= document.getElementById("frm");
	    var autoInclOpties	= targetForm.auto_incl_opties;
    	var aanbetaling     = targetForm.aanbetaling;
	    var aanbetalingPerc	= targetForm.aanbetaling_perc;

	    if( autoInclOpties && aanbetaling && aanbetalingPerc ) {
	    	// aanbetaling.value = (Math.round( ( toCurrency( autoInclOpties.value ) / 100 ) * aanbetalingPerc.value )).toFixed(2);
    		aanbetaling.value = Math.round( ( autoInclOpties.value / 100 ) * aanbetalingPerc.value );
    	}
    }
}

function LTLUpdateAanbetalingPercentage() {
	var targetForm		= document.getElementById("frm");
    var autoInclOpties	= targetForm.auto_incl_opties;
   	var aanbetaling     = targetForm.aanbetaling;
    var aanbetalingPerc	= targetForm.aanbetaling_perc;

    if( autoInclOpties && aanbetaling && aanbetalingPerc ) {
   		aanbetalingPerc.value = Math.round( (aanbetaling.value/autoInclOpties.value)*100);
   	}
}
function LTLUpdateAanbetaling() {
	var targetForm		= document.getElementById("frm");
    var autoInclOpties	= targetForm.auto_incl_opties;
   	var aanbetaling     = targetForm.aanbetaling;
    var aanbetalingPerc	= targetForm.aanbetaling_perc;

    if( autoInclOpties && aanbetaling && aanbetalingPerc ) {
   		aanbetaling.value = Math.round( ( autoInclOpties.value / 100 ) * aanbetalingPerc.value );
   	}
}

function ETLSpinUp(e) {
    if (!e) var e = window.event

    ETLSetSlottermijn();
    ETLSetDiscount();
    ETLSetPrincipal();
}

function ETLSpinDown(e) {
    if (!e) var e = window.event

    ETLSetSlottermijn();
    ETLSetDiscount();
    ETLSetPrincipal();
}

function ETLSetPrincipal() {
	var frm = document.forms['frm'];
	var elPrincipal = frm.financieringsbedrag;
	if ( elPrincipal ) {
		var elTotalCosts    = frm.totale_kosten;
		var elTotalDiscount = frm.totale_korting;

		if ( elTotalCosts.value != '' && elTotalDiscount.value != '' ) {
			fTotalCosts    = toCurrency( elTotalCosts.value );
			fTotalDiscount = toCurrency( elTotalDiscount.value );

			elPrincipal.value = (fTotalCosts - fTotalDiscount).toFixed(2);
		}
	}
}

function ETLSetMonthlyPayment(SID) {

	var frm = document.frm;
	if ( frm ) {
		var elMonthlyPayment = document.frm.maandtermijn;
		var elPrincipal      = document.frm.financieringsbedrag;
		var elLooptijd       = document.frm.looptijd;
		var elSlottermijn    = document.frm.slottermijn;
		var elCosts 		 = document.frm.kosten;

		var i = elLooptijd.selectedIndex;
		var looptijd = elLooptijd.options[i].text;

		if ( elMonthlyPayment && elPrincipal && elLooptijd && elSlottermijn ) {
			principal      = toCurrency( elPrincipal.value );
			creditFactorID = parseInt( elLooptijd.value );
			endTermAmount  = toCurrency( elSlottermijn.value );
			if ( !isNaN( creditFactorID )
					&& principal > 0
					&& creditFactorID > 0 ) {
			    xmlHttp = getxmlHttpObject();
			    if ( xmlHttp ) {
			        xmlHttp.onreadystatechange = function() {
						if ( xmlHttp.readyState==4 || xmlHttp.readyState=="complete" ) {

				            elMonthlyPayment.value = xmlHttp.responseText.replace(/,/g,"");
            	            new Effect.Highlight(elMonthlyPayment);

            	            /*update credit costs*/
							//TODO: not sure if result of this calculation is correct
							var slottermijn = parseFloat(elSlottermijn.value);

							if (isNaN(slottermijn))	{
								slottermijn = 0;
							}
							elCosts_value = ( ( (parseFloat(elMonthlyPayment.value)*parseFloat(looptijd)) - parseFloat( looptijd ) ) + slottermijn );
							// Round to nearest integer value
							elCosts.value = elCosts_value.toFixed(0);
						}
					};
					// principal, creditFactorID, endTermAmount
				    xmlHttp.open( 'GET'
				    				, '/ajax/dtc.xhr.php?req='
										+'&productType=EndTermLoan'
										+'&principal='+principal
										+'&creditFactorID='+creditFactorID
										+'&endTermAmount='+endTermAmount
										+'&'+SID
									, true );
			    	xmlHttp.send( null );
				}
			}
		} else if( elMonthlyPayment && elSlottermijn ) { // prijskaart
			principal      = toCurrency( document.frm.auto_incl_opties.value );
			creditFactorID = parseInt( elLooptijd.value );
			endTermAmount  = toCurrency( elSlottermijn.value );
			downPayment    = toCurrency( document.frm.aanbetaling.value );

			if( downPayment > 0 )
				principal -= downPayment;

			if ( !isNaN( creditFactorID )
					&& principal > 0
					&& creditFactorID > 0 ) {
			    xmlHttp = getxmlHttpObject();
			    if ( xmlHttp ) {
			        xmlHttp.onreadystatechange = function() {
						if ( xmlHttp.readyState==4 || xmlHttp.readyState=="complete" ) {

				            elMonthlyPayment.value = xmlHttp.responseText.replace(",","");
            	            new Effect.Highlight(elMonthlyPayment);
						}
					};
					// principal, creditFactorID, endTermAmount
				    xmlHttp.open( 'GET'
				    				, '/ajax/dtc.xhr.php?req='
										+'&productType=EndTermLoan'
										+'&principal='+principal
										+'&creditFactorID='+creditFactorID
										+'&endTermAmount='+endTermAmount
										+'&'+SID
									, true );
			    	xmlHttp.send( null );
				}
			}

		}
	}
}

//add extra functionality to onclick method for spinbuttons
function ETLEvents() {
    // attach extra function to the onclick event of the btnUp spinbutton
    var btn = document.getElementById('btnUp');
    if( btn ) {
        var _onClick_btnUp = (btn.onclick) ? btn.onclick : function () {};
        btn.onclick = function () {_onClick_btnUp(); ETLSpinUp()};
    }

    // attach extra function to the onclick event of the btnDown spinbutton
    var btn = document.getElementById('btnDown');
    if( btn ) {

        var _onClick_btnDown = (btn.onclick) ? btn.onclick : function () {};
        btn.onclick = function () {_onClick_btnDown(); ETLSpinDown()};
    }
}

function ETLPopupPricecard(SID) {
	pMonthlyPayment = toCurrency( document.frm.maandtermijn.value );
	// finance
	pPrincipal          = toCurrency( document.frm.auto_incl_opties.value );
	pEndTermAmount  = toCurrency( document.frm.slottermijn.value );
	pCreditFactorID = parseInt( document.frm.looptijd.value );
	pInsurance		= toCurrency( document.frm.verzekering.value );
	pLicense		= document.frm.kenteken.value;
	pDownpayment    = toCurrency( document.frm.aanbetaling.value );


	if ( isNaN( pCreditFactorID ) ) { pCreditFactorID = 0; }

    sURL = '/popups/dtc.prijskaart.php?productType=EndTermLoan'
    		+'&monthlyPayment='+pMonthlyPayment
			+'&principal='+pPrincipal
			+'&endTermAmount='+pEndTermAmount
			+'&creditFactorID='+pCreditFactorID
			+'&insurance='+pInsurance
			+'&license='+pLicense
			+'&downpayment='+pDownpayment
			+'&'+SID;



    popup = window.open( sURL, 'SlottermijnFinanciering', '' );
    popup.focus();
}

function ETLValidatePrincipal(val) {

	principal = toCurrency( val );
	return (principal > 0 && principal < 100000);
}

/*
 * Financial Lease (Financial lease)
 */

function FLSetTerms(SID) {
	var elMonthlyPayment = document.frm.maandtermijn;
	objectID  = parseInt( document.frm.soort_object.value );
	principal = toCurrency( document.frm.kredietbedrag.value );

	var selectID = document.frm.looptijd.id;

	if ( principal > 0 ) {
	    xmlHttp = getxmlHttpObject();
	    if ( xmlHttp ) {
	        xmlHttp.onreadystatechange = function() {
				if ( xmlHttp.readyState==4 || xmlHttp.readyState=="complete" ) {

					var ieBug = $('iebug');

			        if ( ieBug ) {
			            ieBug.innerHTML = xmlHttp.responseText;
           	            new Effect.Highlight(elMonthlyPayment);
					}
				}
			};

			//we pass along the id on the select elements as well
			//or quickform will get confused.
		    xmlHttp.open( 'GET'
		    				, '/ajax/dtc.xhr.php?req=FLGetTerms'
		    					+'&objectID='+objectID
		    					+'&selectID='+selectID
		    					+'&principal='+principal
		    					+'&'+SID
		    				, true );
		   	xmlHttp.send( null );
		}
	}
	else {
		var elLooptijd = document.frm.looptijd;
		elLooptijd.innerHTML = '';
	}
}

function FLSetMonthlyPayment(SID) {

	var frm = document.frm;
	if ( frm ) {
		var elMonthlyPayment = document.frm.maandtermijn;
		var elKredietbedrag  = document.frm.kredietbedrag;
		var elLooptijd       = document.frm.looptijd;
		var elSlottermijn    = document.frm.slottermijn;
		var elSoortObject    = document.frm.soort_object;
		var elCosts			 = document.frm.kosten;


		if ( elMonthlyPayment && elKredietbedrag && elLooptijd && elSlottermijn && elSoortObject ) {
			principal      = toCurrency( elKredietbedrag.value );
			creditFactorID = parseInt( elLooptijd.value );
			endTermAmount  = toCurrency( elSlottermijn.value );
			objectID       = elSoortObject.value;

			if ( !isNaN( creditFactorID )
					&& !isNaN( objectID )
					&& principal > 0
					&& creditFactorID > 0
					&& objectID > 0 ) {
			    xmlHttp = getxmlHttpObject();
			    if ( xmlHttp ) {
			        xmlHttp.onreadystatechange = function() {
						if ( xmlHttp.readyState==4 || xmlHttp.readyState=="complete" ) {
				            elMonthlyPayment.value = xmlHttp.responseText.replace(",","");
            	            new Effect.Highlight(elMonthlyPayment);
            	            if (elCosts)
            	            {
   								elCosts.value = ""+ toCurrency((parseFloat(elMonthlyPayment.value)*parseFloat(looptijd) - parseFloat(elPrincipal.value))).toFixed(2);
   							}
						}
					};

					// principal, creditFactorID, endTermAmount, objectID
				    xmlHttp.open( 'GET'
				    				, '/ajax/dtc.xhr.php?req='
										+'&productType=FinancialLease'
										+'&principal='+principal
										+'&creditFactorID='+creditFactorID
										+'&endTermAmount='+endTermAmount
										+'&objectID='+objectID
									, true );
                    //"/ajax/dtc.xhr.php?reg=&productType=FinancialLease&principal=5000&creditFactorID=30&endTermAmount=1200&objectID=50,01&SID="
                    //principal: 5000, productType: FinancialLease, creditFactorID: 30, endTermAmount: 1200, objectID: 50,01
                    xmlHttp.send( null );
				}
			}
		}
	}
}

function FLValidatePrincipal(val) {

	principal = toCurrency( val );
	return (principal > 0 && principal < 70000);
}

/*
 * Long Term Loan (Doorlopend krediet)
 */

function LTLSetCosts() {
	var elTotalCosts = document.frm.totale_kosten;
    if ( elTotalCosts ) {
        var fAutoInclOpties        = toCurrency( document.frm.auto_incl_opties.value );
        var fOverTeSluitenLeningen = toCurrency( document.frm.over_te_sluiten_leningen.value );
        var fVerlengdeGarantie     = toCurrency( document.frm.verlengde_garantie.value );

        elTotalCosts.value = (fAutoInclOpties + fOverTeSluitenLeningen + fVerlengdeGarantie).toFixed(2);

    }
}

function LTLSetDiscount() {

    var elTotalDiscount = document.frm.totale_korting;
    if ( elTotalDiscount ) {
        var fInruilWagen         = toCurrency( document.frm.inruilwagen.value );
        var fContanteAanbetaling = toCurrency( document.frm.contante_aanbetaling.value );

        elTotalDiscount.value = (fInruilWagen + fContanteAanbetaling).toFixed(2);
    }
}

function LTLSetPrincipal() {

	var elPrincipal = document.frm.financieringsbedrag;
	if ( elPrincipal ) {
		var elTotalCosts    = document.frm.totale_kosten;
		var elTotalDiscount = document.frm.totale_korting;
		if ( elTotalCosts && elTotalDiscount ) {
			fTotalCosts    = toCurrency( elTotalCosts.value );
			fTotalDiscount = toCurrency( elTotalDiscount.value );

			elPrincipal.value = (fTotalCosts - fTotalDiscount).toFixed(2);
		}
	}
}

function LTLSetMonthlyPayment(SID) {
	var frm = document.frm;
	if ( frm ) {
		var elMonthlyPayment       = document.frm.maandtermijn;
		var elPrincipal            = document.frm.financieringsbedrag;
		var elAflossingsPercentage = document.frm.aflossingspercentage;
		var elTheoretischeLooptijd = document.frm.theoretische_looptijd;
		var elCosts				   = document.frm.kosten;

		if ( elMonthlyPayment && elPrincipal && elAflossingsPercentage && elTheoretischeLooptijd ) {
			principal  = toCurrency( elPrincipal.value );
			percentage = toCurrency( elAflossingsPercentage.value );
			if ( !isNaN( principal )
					&& !isNaN( percentage )
					&& principal > 0 ) {

				    xmlHttp = getxmlHttpObject();
				    if ( xmlHttp ) {
				        xmlHttp.onreadystatechange = function() {
							if ( xmlHttp.readyState==4 || xmlHttp.readyState=="complete" ) {
					            elMonthlyPayment.value       = xmlHttp.responseText.replace(",","");

                                if( percentage == 2.0 )
                                {
                                   elTheoretischeLooptijd.value = '63';
    					        } else if( percentage == 1.5 )
    					        {
    					           elTheoretischeLooptijd.value = '91';
    					        } else if( percentage == 1.0 )
    					        {
                                    elTheoretischeLooptijd.value = '177';
    					        }

								//update the cost for this credit
  								elCosts.value = ( parseFloat( elMonthlyPayment.value )*parseFloat( elTheoretischeLooptijd.value ) ) - parseFloat(elPrincipal.value);


                	            new Effect.Highlight(elMonthlyPayment);
							}
						};
						//HACK: to avoid adding another parameter to this mess we abuse the creditFactorID
						//parameter because it is not used with the long term loan, this value will contain
						//the preferred payment percentage
					    xmlHttp.open( 'GET'
					    				, '/ajax/dtc.xhr.php?req='
					    				    +'&objectID='
											+'&productType=LongTermLoan'
											+'&principal='+principal
											+'&creditFactorID='+percentage
											+'&'+SID
										, true );
					   	xmlHttp.send( null );
					}
			}
		} else if( elMonthlyPayment && document.frm.aanbetaling ) {
			//pricecard
			var principal = document.frm.auto_incl_opties.value;
			var percentage = 2.0;
			var elMonthlyPayment       = document.frm.maandtermijn;
			var downPayment = document.frm.aanbetaling.value;

			if( downPayment > 0 )
				principal -= downPayment;

			if ( !isNaN( principal )
					&& !isNaN( percentage )
					&& principal > 0 ) {

				    xmlHttp = getxmlHttpObject();
				    if ( xmlHttp ) {
				        xmlHttp.onreadystatechange = function() {
							if ( xmlHttp.readyState==4 || xmlHttp.readyState=="complete" ) {
					            elMonthlyPayment.value       = xmlHttp.responseText.replace(",","");

								elTheoretischeLooptijd.value = '63';

                	            new Effect.Highlight(elMonthlyPayment);
							}
						};
						//HACK: to avoid adding another parameter to this mess we abuse the creditFactorID
						//parameter because it is not used with the long term loan, this value will contain
						//the preferred payment percentage
					    xmlHttp.open( 'GET'
					    				, '/ajax/dtc.xhr.php?req='
					    				    +'&objectID='
											+'&productType=LongTermLoan'
											+'&principal='+principal
											+'&creditFactorID='+percentage
											+'&'+SID
										, true );
					   	xmlHttp.send( null );
					}


			}




		} else if( elMonthlyPayment && document.frm.inruilwagen ) {
			//mini calculation
			var principal = document.frm.auto_incl_opties.value;
			var percentage = 2.0;
			var elMonthlyPayment       = document.frm.maandtermijn;
			var downPayment = document.frm.inruilwagen.value;

			if( downPayment > 0 )
				principal -= downPayment;

			if ( !isNaN( principal )
					&& !isNaN( percentage )
					&& principal > 0 ) {

				    xmlHttp = getxmlHttpObject();
				    if ( xmlHttp ) {
				        xmlHttp.onreadystatechange = function() {
							if ( xmlHttp.readyState==4 || xmlHttp.readyState=="complete" ) {
					            elMonthlyPayment.value       = xmlHttp.responseText.replace(",","");

								elTheoretischeLooptijd.value = '63';

                	            new Effect.Highlight(elMonthlyPayment);
							}
						};
						//HACK: to avoid adding another parameter to this mess we abuse the creditFactorID
						//parameter because it is not used with the long term loan, this value will contain
						//the preferred payment percentage
					    xmlHttp.open( 'GET'
					    				, '/ajax/dtc.xhr.php?req='
					    				    +'&objectID='
											+'&productType=LongTermLoan'
											+'&principal='+principal
											+'&creditFactorID='+percentage
											+'&'+SID
										, true );
					   	xmlHttp.send( null );
					}


			}

		}
	}
}

function LTLPopupPricecard(SID) {

	var frm = document.frm;
	if ( frm ) {
		pMonthlyPayment = toCurrency( frm.maandtermijn.value );
		pPrincipal      = toCurrency( frm.auto_incl_opties.value );
		pInsurance		= toCurrency( frm.verzekering.value );
		pLicense		= frm.kenteken.value;
		pDownpayment	= toCurrency( frm.aanbetaling.value );
//		pCreditFactorID = parseInt( document.frm.looptijd.value );

	    sURL = '/popups/dtc.prijskaart.php?productType=LongTermLoan'
	    		+'&monthlyPayment='+pMonthlyPayment
				+'&principal='+pPrincipal
				+'&insurance='+pInsurance
				+'&license='+pLicense
				+'&downpayment='+pDownpayment
				+'&'+SID;

	    popup = window.open( sURL, 'DoorlopendKrediet', '' );
	    popup.focus();
	}
}

function LTLValidatePrincipal(val) {

	principal = toCurrency( val );
	return (principal > 0 && principal < 100000);
}

/*
 * Personal Loan (Persoonlijke lening)
 */

function PLSetCosts() {

	var elTotalCosts = document.frm.totale_kosten;
    if ( elTotalCosts ) {
        var fAutoInclOpties        = toCurrency( document.frm.auto_incl_opties.value );
        var fOverTeSluitenLeningen = toCurrency( document.frm.over_te_sluiten_leningen.value );
        var fVerlengdeGarantie     = toCurrency( document.frm.verlengde_garantie.value );

        elTotalCosts.value = (fAutoInclOpties + fOverTeSluitenLeningen + fVerlengdeGarantie).toFixed(2);
    }
}

function PLSetDiscount() {

    var elTotalDiscount = document.frm.totale_korting;
    if ( elTotalDiscount ) {
        var fInruilWagen         = toCurrency( document.frm.inruilwagen.value );
        var fContanteAanbetaling = toCurrency( document.frm.contante_aanbetaling.value );

        elTotalDiscount.value = (fInruilWagen + fContanteAanbetaling).toFixed(2);
    }
}

function PLSetPrincipal() {

	var elPrincipal = document.frm.financieringsbedrag;
	if ( elPrincipal ) {
		var elTotalCosts    = document.frm.totale_kosten;
		var elTotalDiscount = document.frm.totale_korting;
		if ( elTotalCosts && elTotalDiscount ) {
			fTotalCosts    = toCurrency( elTotalCosts.value );
			fTotalDiscount = toCurrency( elTotalDiscount.value );

			elPrincipal.value = (fTotalCosts - fTotalDiscount).toFixed(2);
		}
	}
}

function PLSetMonthlyPayment(SID) {

	var frm = document.frm;
	if ( frm ) {
		var elMonthlyPayment = document.frm.maandtermijn;
		var elPrincipal      = document.frm.financieringsbedrag;
		var elLooptijd       = document.frm.looptijd;
		var elCosts			 = document.frm.kosten;

		var i = elLooptijd.selectedIndex;
		var looptijd = elLooptijd.options[i].text;

		if ( elMonthlyPayment && elPrincipal && elLooptijd ) {
			principal      = toCurrency( elPrincipal.value );
			creditFactorID = parseInt( elLooptijd.value );
			if ( !isNaN( creditFactorID )
					&& principal > 0
					&& creditFactorID > 0 ) {
			    xmlHttp = getxmlHttpObject();
			    if ( xmlHttp ) {
			        xmlHttp.onreadystatechange = function() {
						if ( xmlHttp.readyState==4 || xmlHttp.readyState=="complete" ) {
				            elMonthlyPayment.value = xmlHttp.responseText.replace(",","");

	           	            //update credit cost
            	            new Effect.Highlight(elMonthlyPayment);

							//update the cost for this credit
							elCosts.value = (parseFloat(elMonthlyPayment.value)*parseFloat(looptijd) - parseFloat(elPrincipal.value)).toFixed(2);

						}
					};
					// principal, creditFactorID
				    xmlHttp.open( 'GET'
				    				, '/ajax/dtc.xhr.php?req='
										+'&productType=PersonalLoan'
										+'&principal='+principal
										+'&creditFactorID='+creditFactorID
										+'&'+SID
									, true );
				   	xmlHttp.send( null );
				}
			}
		}
	}
}

function PLValidatePrincipal(val) {

	principal = toCurrency( val );
	return (principal > 0 && principal < 100000);
}

/*
    Methods for extended warranty
*/

function EWUpdate()
{
    if( document.frm.garantie_periode )
    {
        ewPeriod = document.frm.garantie_periode.value;
    }

    if( document.frm.garantie_periode )
    {
        ewClass = document.frm.garantie_klasse.value;
    }

    elGarantie = document.frm.verlengde_garantie;

    xmlHttp = getxmlHttpObject();
    if ( xmlHttp ) {
        xmlHttp.onreadystatechange = function() {
			if ( xmlHttp.readyState==4 || xmlHttp.readyState=="complete" ) {

	            elGarantie.value = xmlHttp.responseText;

	            UpdateCosts();
	            if( elGarantie.value != "" ) {
    	            new Effect.Highlight(elGarantie);
	            }
			}
		};
		// principal, creditFactorID
	    xmlHttp.open( 'GET'
	    				, '/ajax/dtc.xhr.php?req=warranty'
							+'&period='+ewPeriod
							+'&class='+ewClass

						, true );
		   	xmlHttp.send( null );
	}

}

function EWPopupPrepare()
{
    new Effect.Fade($('help'));
}
function EWPopupInfo(e)
{
        var helpdiv = $('help');

        if(helpdiv.style.display == 'none')
        {
            new Effect.BlindDown(helpdiv);
        }
        else
        {
            new Effect.BlindUp(helpdiv);
        }
}

function UpdateCosts()
{
    var product = parseInt(document.frm.productid.value);

    if( product == 1 )
    {
        LTLSetCosts();
        LTLSetDiscount();
        LTLSetPrincipal();
    }
    else if( product == 2 )
    {
        PLSetCosts();
        PLSetDiscount();
        PLSetPrincipal();
    }
    else if( product == 3 )
    {
        ETLSetCosts();
        ETLSetDiscount();
        ETLSetPrincipal();
        ETLSetSlottermijn();
    }
    else if( product == 5 )
    {
        FLSetCosts();
    }

}

function UpdatePercentage() {

	var frm = document.forms['frm'];
    //when a endterm value has been entered, determine the percentage
    var endterm = parseInt(frm.slottermijn.value);
    var principal = 0;
    if( frm.totale_kosten ) { //produkt scherm
    	principal = parseInt(frm.totale_kosten.value);
    } else { //prijskaart
    	principal = frm.auto_incl_opties.value;
    	principal
    }

    var percentage = endterm  / (principal / 100);
    if ( frm.slottermijn_perc ) {
    	frm.slottermijn_perc.value = percentage;
    }
}

function PopupOfferte()
{
	costs = document.frm.costs.value;
	principal = document.frm.principal.value;
	terms = document.frm.terms.value;
	monthly_term = document.frm.monthly_term.value;
	rate = '';
	if (document.frm.rate)
	{
		rate = '&rate='+document.frm.rate.value;
	}
	productid = document.frm.productid.value;
	object = document.frm.object.value;

	dealername = document.frm.dealername.value;
	dealercontact = document.frm.dealercontact.value;
	dealeraddress = document.frm.dealeraddress.value;
	dealerzipcode = document.frm.dealerzipcode.value;
	dealercity = document.frm.dealercity.value;
	dealerphone = document.frm.dealerphone.value;
	dealerfax = document.frm.dealerfax.value;

	customername = document.frm.customername.value;
	customerlastname = document.frm.customerlastname.value;
	customeraddress = document.frm.customeraddress.value;
	customerzipcode = document.frm.customerzipcode.value;
	customercity = document.frm.customercity.value;
	customergender = document.frm.customergender.value;
	customercompany = document.frm.customercompany.value;

	onsetcity = document.frm.onsetcity.value;
	onsetdate = document.frm.onsetdate.value;

	endTerm = 0;
	if( document.frm.endterm ) {
		endTerm  = toCurrency( document.frm.endterm.value );
	}

	/*
		We construct the offerte GET request so we the variable names
		in the request are conforming to the offerte template, so
		we can just set the GET request array as variables for the
		sigma template, and not have to change them around again.

		We first need some missing information though (such as the product name)
		For implementation ease we hardcode the product names here
		(this isn't really elegant, but it's not likely to change anytime soon anyway)
	*/

	productname = "";
	switch(productid) {
		case '1':
			productname = "Doorlopend Krediet";
		break;
		case '2':
			productname = "Persoonlijke Lening";
		break;
		case '3':
			productname = "Slottermijn Financiering";
		break;
		case '5':
			productname = "Financial Lease";
		break;
	}
	gender = "";
	gendershort = "";
	switch(customergender) {
		case "M":
			gender="heer";
			gendershort="dhr.";
		break;
		case "V":
			gender="mevrouw";
			gendershort="mevr.";
		break;
		case "O":
			gender="heer/ mevrouw";
			gendershort="dhr./ mevr.";
		break;

	}

    sURL = '/popups/dtc.offerte.php?'+
    		'dealername='+dealername+
    		'&dealercontact='+dealercontact+
    		'&dealeraddress='+dealeraddress+
    		'&dealerzipcode='+dealerzipcode+
    		'&dealercity='+dealercity+
    		'&dealerphone='+dealerphone+
    		'&dealerfax='+dealerfax+
    		'&customer_name='+customername+'%20'+customerlastname+
    		'&customer_company='+customercompany+
    		'&customer_address='+customeraddress+
    		'&customer_zipcode='+customerzipcode+
    		'&customer_city='+customercity+
    		'&gender_short='+gendershort+
    		'&gender_descriptive='+gender+
    		'&customer_last_name='+customerlastname+
    		'&onsetcity='+onsetcity+
    		'&onset_date='+onsetdate+
    		'&product_name='+productname+
    		'&object='+object+
    		'&costs='+costs+
    		'&principal='+principal+
    		'&terms='+terms+
    		'&monthly_term='+monthly_term+
    		rate+
    		'&end_term='+endTerm;


    popup = window.open( sURL, 'Offerte', '' );
    popup.focus();

}

/** Redirect bezoeker vanaf krediet pagina naar het Offerte aanvraag formulier
 * @param string redirectUrl Url 2 target page
 * @param float financieringsbedrag Gewenst leenbedrag
 */
function naarOfferteAanvraagForm(redirectUrl, financieringsbedrag) {
	var num		= parseFloat(financieringsbedrag);
	var bedrag	= num.toFixed(0);

	if ( isNaN( bedrag ) ) {
		alert("Vul eerst het veld 'Auto incl. opties' in.");
		return false;
	}
	window.location.href=redirectUrl+'?kredietbedrag='+bedrag;
	return false;
}

/* Temporary code to fill the offerte form during testing
function DebugOfferte() {
	document.frm.dealername.value = "Dealer Totaal Concept";
	document.frm.dealercontact.value = "Raymond Alflen";
	document.frm.dealeraddress.value = "Floridalaan 2";
	document.frm.dealerzipcode.value = "3404 WV";
	document.frm.dealercity.value = "IJsselstein";
	document.frm.dealerphone.value = "030-6868750";
	document.frm.dealerfax.value = "030-6868755";

	document.frm.customername.value = "K.";
	document.frm.customerlastname.value = "Koper";
	document.frm.customeraddress.value = "Spoorlaan 310";
	document.frm.customerzipcode.value = "5000 AC";
	document.frm.customercity.value = "Tilburg";
	document.frm.customergender.value = "Man";

	document.frm.onsetcity.value = "IJsselstein";
	document.frm.onsetdate.value = "10 januari 2007";
	document.frm.object.value = "Toyota Starlet 1.3i";
}
*/