Object.extend(Array.prototype, {
    exists: function(obj){
        return (this.indexOf(obj) > 0)? true : false;
    }
});
Object.extend(Control.Slider.prototype, {
    setNextValue: function(){
        if(this.allowedValues){
            var value = this.getNearestValue(this.value);
            var act = $A(this.allowedValues).indexOf(value);
            if(act < this.allowedValues.length-1){ this.setValue(this.allowedValues[act+1]); }
        }
        return false;
    },
    setPreviousValue: function(){
        if(this.allowedValues){
            var value = this.getNearestValue(this.value);
            var act = $A(this.allowedValues).indexOf(value);
            if(act > 0){ this.setValue(this.allowedValues[act-1]); }
        }
        return false;
    }
});

//magicTable
var magicTable = {};

//sliders
var sliderAmount;
var sliderDuration;
var sliderMonthlyPayment;

//range & values
var sliderMonthlyPaymentRange;
var sliderDurationRange;


var globalComputing = 1;
function disableComputing() {
    if(globalComputing == 1) {
        globalComputing = 0;
        setTimeout("disableComputing()",100);
    } else {
        globalComputing = 1;
    }
}

function getEcheance(elMontant, elDuree) {
    elDuree = $(elDuree);
    elMontant = $(elMontant);
    var mt = elMontant.value;
    var dr = elDuree.value;
    var result = [mt,dr,magicTable[mt][dr]];
    return result;
}
function getDuration(elMontant, elEcheance){
    elMontant = $(elMontant);
    elEcheance = $(elEcheance);
    var Tab = magicTable[elMontant.value];
    var ec = elEcheance.value;
    var dr = ec2 = false;
    $H(Tab).each(
        function(elm){
            if(elm.value < ec && !dr && !ec2){
                dr = elm.key;
                ec2 = elm.value;
            }
        }
    );
    if(!dr){
        dr = $H(Tab).keys().last();
        ec2= $H(Tab).values().last();
    }
    return [0,dr,ec2];
}

function initSliders( elBoxAmount, elBoxDuration, elBoxMonthlyPayment, infoElms ) {
    //appel pour recup?rer objet JSON pour magicTable
	
    new Ajax.Request('index.php?json=getTeg',{
        method: 'get',
        onSuccess: function(ret){
            magicTable = validateJSON(ret.responseText);

		    new Ajax.Request('index.php?json=getAmountRange',{
		        method: 'get',
		        onSuccess: function(ret){
					sliderMonthlyPaymentRange = validateJSON(ret.responseText);

				    new Ajax.Request('index.php?json=getDurations',{
				        method: 'get',
				        onSuccess: function(ret){
							sliderDurationRange = validateJSON(ret.responseText);

				            postInitSliders( elBoxAmount, elBoxDuration, elBoxMonthlyPayment, infoElms );
				            initSlidersValues();
				            initBoxEvents( elBoxAmount, elBoxDuration, elBoxMonthlyPayment );
				        }
				    });
		        }
		    });
        },
        onFailure: function(){
            magicTable = magicTableSecours;
            postInitSliders( elBoxAmount, elBoxDuration, elBoxMonthlyPayment, infoElms );
            initSlidersValues();
        }
    });
}


function postInitSliders( elBoxAmount, elBoxDuration, elBoxMonthlyPayment, infoElms ) {
    // horizontal slider control
    var TabAmountValues = getMagicValues();
    sliderAmount = new Control.Slider('handleAmount', 'trackAmount', {
        range: $R(TabAmountValues.first(),TabAmountValues.last()),
        values: $A(TabAmountValues),
        onSlide: function(v) { $(elBoxAmount).value = (v*1).toFixed(); },
        onChange: function(v){
            $(elBoxAmount).value = (v*1).toFixed();
            var result;
            if(globalComputing == 1) {
                disableComputing();
                result = getEcheance($(elBoxAmount), $(elBoxDuration));
                $(elBoxAmount).value = (result[0]*1).toFixed();
                $(elBoxDuration).value = (result[1]*1).toFixed();
                $(elBoxMonthlyPayment).value = (result[2]*1).toFixed();
                setSliderValue(sliderMonthlyPayment, $(elBoxMonthlyPayment).value);
                setSliderValue(sliderDuration, $(elBoxDuration).value);
                setSliderValue(sliderAmount, $(elBoxAmount).value);
                setInfoValues(infoElms, $(elBoxDuration).value, $(elBoxAmount).value);
            }
        }
    });
    sliderDuration = new Control.Slider('handleDuration', 'trackDuration', {
        range: $R(
        	sliderDurationRange.first(),
        	sliderDurationRange.last()
        ),
        values: $A(sliderDurationRange),
        onSlide: function(v) { $(elBoxDuration).value = (v*1).toFixed(); },
        onChange: function(v){
            $(elBoxDuration).value = (v*1).toFixed();
            var result;
            if(globalComputing == 1) {
                disableComputing();
                result = getEcheance($(elBoxAmount), $(elBoxDuration));
                $(elBoxAmount).value = (result[0]*1).toFixed();
                $(elBoxDuration).value = (result[1]*1).toFixed();
                $(elBoxMonthlyPayment).value = (result[2]*1).toFixed();
                setSliderValue(sliderMonthlyPayment, $(elBoxMonthlyPayment).value);
                setSliderValue(sliderDuration, $(elBoxDuration).value);
                setSliderValue(sliderAmount, $(elBoxAmount).value);
                setInfoValues(infoElms, $(elBoxDuration).value, $(elBoxAmount).value);
            }
        }
    });

    sliderMonthlyPayment = new Control.Slider('handleMonthlyPayment', 'trackMonthlyPayment', {
        range: $R(
        	sliderMonthlyPaymentRange.first(),
        	sliderMonthlyPaymentRange.last()
        ),
        onSlide: function(v) { $(elBoxMonthlyPayment).value = (v*1).toFixed(); },
        onChange: function(v){
            $(elBoxMonthlyPayment).value = (v*1).toFixed();
            var result;
            if(globalComputing == 1) {
                disableComputing();
                var result = getDuration(elBoxAmount, elBoxMonthlyPayment);
                $(elBoxDuration).value = (result[1]*1).toFixed();
                $(elBoxMonthlyPayment).value = (result[2]*1).toFixed();
                setSliderValue(sliderMonthlyPayment, $(elBoxMonthlyPayment).value);
                setSliderValue(sliderDuration, $(elBoxDuration).value);
                setInfoValues(infoElms, $(elBoxDuration).value, $(elBoxAmount).value);
            }
        }
    });
}

function getMagicValues(){
    var Tab = $A();
    $H(magicTable).each(
        function(elm){ Tab.push(parseInt(elm.key)); }
    )
    return Tab;
}

function setSliderValue(slider, value) {
    // due to onChange code above we need this or
    // a 0 will be put in the text box when you delete the value
    if (value == '') return;
    if (isNaN(value))
    slider.setValue(0);
    else
    slider.setValue(value);
}

function validateJSON(jsonText) {
    if(jsonText == '' || jsonText == null){ return false; }
    return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
        jsonText.replace(/"(\\.|[^"\\])*"/g, '')))
        && eval('(' + jsonText + ')');
}

function setInfoValues(infoElms, duree, montant) {
    if(!initialized || infoElms==null || duree==null || montant==null) { return false; }

    //recup?re toutes les infos qui vont bien :
    new Ajax.Request('index.php?json=getDetailedInfo&amount='+montant+'&duration='+duree,{
            method:'get',
            onSuccess: function(ret){
                jsonLoan = validateJSON(ret.responseText);
                if(!jsonLoan) { return false; }
                $(infoElms.montant).innerHTML = jsonLoan.amount;
                $(infoElms.duree).innerHTML = jsonLoan.duration;
                $(infoElms.mensualite).innerHTML = jsonLoan.monthlyPayment;
				$(infoElms.couttotal).innerHTML = jsonLoan.totalAmount;
                if(jsonLoan.lastPayment != undefined) {
                $(infoElms.derniere_mensualite).innerHTML = jsonLoan.lastPayment;
                }
                $(infoElms.teg).innerHTML = jsonLoan.teg;
                $(infoElms.interet).innerHTML = jsonLoan.interest;
				if ($(infoElms.teg).innerHTML == '3,90') $(infoElms.tauxDeb).innerHTML = '3,83';
				else if ($(infoElms.teg).innerHTML == '7,40') $(infoElms.tauxDeb).innerHTML = '7,16';
				else if ($(infoElms.teg).innerHTML == '8,15') $(infoElms.tauxDeb).innerHTML = '7,86';
				else if ($(infoElms.teg).innerHTML == '8,60') $(infoElms.tauxDeb).innerHTML = 'ERROR';
				else $(infoElms.tauxDeb).innerHTML = '7,86';
            },
            onFailure: function(){
            	alert('toto');
            	return false;
            }
        }
    );
}

function initBoxEvents( elBoxAmount, elBoxDuration, elBoxMonthlyPayment ) {
    Event.observe(elBoxAmount, 'blur', function(){
        if($A(sliderAmount.range).exists($(elBoxAmount).value)){ setSliderValue(sliderAmount, $(elBoxAmount).value); }
        else if($(elBoxAmount).value < sliderAmount.minimum){ setSliderValue(sliderAmount, sliderAmount.minimum); }
        else if($(elBoxAmount).value > sliderAmount.maximum){ setSliderValue(sliderAmount, sliderAmount.maximum); }
    });

    Event.observe(elBoxDuration, 'blur', function(){
        if($A(sliderDuration.range).exists($(elBoxDuration).value)){ setSliderValue(sliderDuration, $(elBoxDuration).value); }
        else if($(elBoxDuration).value < sliderDuration.minimum){ setSliderValue(sliderDuration, sliderDuration.minimum); }
        else if($(elBoxDuration).value > sliderDuration.maximum){ setSliderValue(sliderDuration, sliderDuration.maximum); }
    });

    Event.observe(elBoxMonthlyPayment, 'blur', function(){
        var v = parseInt($(elBoxMonthlyPayment).value);
        if((v >= sliderMonthlyPaymentRange.first()) && (v <= sliderMonthlyPaymentRange.last())){ setSliderValue(sliderMonthlyPayment, v+1); } //le +1 est pour éviter un bug -> si pas de +1, la valeur prise est celle inférieure ...
        else if(v < sliderMonthlyPaymentRange.first()){ setSliderValue(sliderMonthlyPayment, sliderMonthlyPaymentRange.first()); }
        else if(v > sliderDurationRange.last()){ setSliderValue(sliderMonthlyPayment, sliderMonthlyPaymentRange.last()); }
    });

    Event.observe('trackAmount_minus', 'click', function(){ sliderAmount.setPreviousValue(); });
    Event.observe('trackAmount_plus', 'click', function(){ sliderAmount.setNextValue(); });

    Event.observe('trackMonthlyPayment_minus', 'click', function(){ sliderDuration.setNextValue(); });
    Event.observe('trackMonthlyPayment_plus', 'click', function(){ sliderDuration.setPreviousValue(); });

    Event.observe('trackDuration_minus', 'click', function(){ sliderDuration.setPreviousValue(); });
    Event.observe('trackDuration_plus', 'click', function(){ sliderDuration.setNextValue(); });
}
