var $first = 0;
var $direction = '';
var $oldDuration = 0;

function gaTrackEventCredit($category, $action, $label, $value){
	if ($first == 0) {	
		$first++;	//init
	}else if ($first == 1) {				
		//alert('$category : simulateur $action : reserve $label : interaction');
		_gaq.push(['_trackEvent','simulateur', 'reserve', 'interaction']);
		$first++;
	}else{
		//alert('$category : ' + $category + ' $action : ' + $action + ' $label : ' + $label + ' $value : ' + $value);
		_gaq.push(['_trackEvent',$category, $action, $label, parseInt($value)]);
	}
}

Object.extend(Array.prototype, {
    exists: function(obj){
        return (this.indexOf(obj) > 0)? true : false;
    }
});
Object.extend(Control.Slider.prototype, {
    setNextValue: function(elBoxAmount, elBoxDuration, elBoxMonthlyPayment){
	    $direction = 'right';
        //console.log('arguments.length=>'+arguments.length);
		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]); }
			this.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);
			
            // Mise à jour du récapitulatif
            updateRecap();
        }
        return false;
    },
    setPreviousValue: function(elBoxAmount, elBoxDuration, elBoxMonthlyPayment){
	    $direction = 'left';
        //console.log('arguments.length=>'+arguments.length);
        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]); }
			this.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);

            // Mise à jour du récapitulatif
            updateRecap();
        }
        return false;
    },
    computeValues: function(elBoxAmount, elBoxDuration, elBoxMonthlyPayment) {
			var mt = $(elBoxAmount).value;
			var dr = $(elBoxDuration).value;
			var mp = $(elBoxMonthlyPayment).value;
    	switch(this.track.id) {
			case 'trackDuration' :
				// Move amount
				var resDr = 0;
				if(magicTableGlobal.revAD[mt]) {
					if(magicTableGlobal.revAD[mt][dr]) {
						resDr = dr;
					} else {
						var finish = false;
						resDr = 0;
						$H(magicTableGlobal.revAD[mt]).each(function(elm){
							
							if(!finish) {
								// Quelle est la direction ?
								if ($direction == 'left')
								{
									// On vérifie la direction
									var valMin = $H(magicTableGlobal.revAD[mt]).min();

									// Si la clé est inférieure à la valeur 	
									if (elm.key <= dr)
									{
										// Stocke la nouvelle valeur
										resDr = elm.key;
									}
									// Sinon
									else
									{
										if (resDr == 0)
										{
											// On affecte la valeur min au slider
											resDr = valMin[0];
										}
									}
								}
								else
								{
									resDr = elm.key;
								}
							}
							if(elm.key>=dr) {
								finish = true;
							}
						});
					}
	                $(elBoxAmount).value = (mt*1).toFixed();
	                $(elBoxDuration).value = (resDr*1).toFixed();
	                $(elBoxMonthlyPayment).value = (magicTableGlobal.revAD[mt][resDr]*1).toFixed();
	                setSliderValue(sliderAmount, $(elBoxAmount).value);
	                setSliderValue(sliderDuration, $(elBoxDuration).value);
	                setSliderValue(sliderMonthlyPayment, $(elBoxMonthlyPayment).value);
				}
			break;
			case 'trackMonthlyPayment' :
				var resMp = 0;
				if(magicTableGlobal.revAP[mt]) {
					if(magicTableGlobal.revAP[mt][mp]) {
						resMp = mp;
					} else {
						var finish = false;
						$H(magicTableGlobal.revAP[mt]).each(function(elm){
							if(!finish) {
								resMp = elm.key;
							}
							if(elm.key>=mp) {
								finish = true;
							}
						});
					}
	                $(elBoxAmount).value = (mt*1).toFixed();
	                $(elBoxDuration).value = (magicTableGlobal.revAP[mt][resMp]*1).toFixed();
	                $(elBoxMonthlyPayment).value = (resMp*1).toFixed();
	                setSliderValue(sliderAmount, $(elBoxAmount).value);
	                setSliderValue(sliderDuration, $(elBoxDuration).value);
	                setSliderValue(sliderMonthlyPayment, $(elBoxMonthlyPayment).value);
				}
			break;
			case 'trackAmount' :
				// Move amount
				var resDr = 0;
				if(magicTableGlobal.revAD[mt]) {
					if(magicTableGlobal.revAD[mt][dr]) {
						resDr = dr;
					} else {
						var finish = false;
						$H(magicTableGlobal.revAD[mt]).each(function(elm){
							if(!finish) {
								resDr = elm.key;
							}
							if(elm.key>=dr) {
								finish = true;
							}
						});
					}
	                $(elBoxAmount).value = (mt*1).toFixed();
	                $(elBoxDuration).value = (resDr*1).toFixed();
	                $(elBoxMonthlyPayment).value = (magicTableGlobal.revAD[mt][resDr]*1).toFixed();
	                setSliderValue(sliderAmount, $(elBoxAmount).value);
	                setSliderValue(sliderDuration, $(elBoxDuration).value);
	                setSliderValue(sliderMonthlyPayment, $(elBoxMonthlyPayment).value);
				}
			break;
    	}
    },
    getNearestValueExt: function(value, direction) {
    	var newValue = value;
    	var allowedValues = this.getAllowedValues(direction);
	var index = $A(allowedValues).indexOf(value);
    	if(direction == 1) {
    		if(index < (allowedValues.length-1)) {
    			newValue = allowedValues[index+1];
    		}
    	} else {
    		//down
    		if(index > 0){
    			newValue = allowedValues[index-1];
    		}
    	}
 		return newValue;
	}
});

//magicTable
var magicTable = {};
var magicTableGlobal = {};

//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('/layout/set/vide/simulateurs/indexvalue?json=getTegCredit',{
        method: 'get',
        onSuccess: function(ret){
            magicTable = validateJSON(ret.responseText);

		    new Ajax.Request('/layout/set/vide/simulateurs/indexvalue?json=getAmountRangeCredit',{
		        method: 'get',
		        onSuccess: function(ret){
					sliderMonthlyPaymentRange = validateJSON(ret.responseText);

				    new Ajax.Request('/layout/set/vide/simulateurs/indexvalue?json=getDurationsCredit',{
				        method: 'get',
				        onSuccess: function(ret){
							sliderDurationRange = validateJSON(ret.responseText);
							
						    new Ajax.Request('/layout/set/vide/simulateurs/indexvalue?json=getMultiData&fixed=1',{
						        method: 'get',
						        onSuccess: function(ret){
									magicTableGlobal = validateJSON(ret.responseText);
						            postInitSliders( elBoxAmount, elBoxDuration, elBoxMonthlyPayment );
						            initSlidersValues();
						            initBoxEvents( elBoxAmount, elBoxDuration, elBoxMonthlyPayment );
						        }
						    });
							
							
				            /*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);
				
				sliderAmount.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);

                // Mise à jour du récapitulatif
                updateRecap();
				
				// Mantis 162 GA
				gaTrackEventCredit('simulateur', 'reserve', 'montant', $(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);
				
				sliderDuration.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);
				
                // Mise à jour du récapitulatif
                updateRecap();
				
				// Mantis 162 GA
				gaTrackEventCredit('simulateur', 'reserve', 'duree', $(elBoxDuration).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);
				
				sliderMonthlyPayment.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);
				
                // Mise à jour du récapitulatif
                updateRecap();
				
				// Mantis 162 GA
				gaTrackEventCredit('simulateur', 'reserve', 'mensualite', $(elBoxMonthlyPayment).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('layout/set/vide/simulateurs/indexvalue?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;
                if(jsonLoan.lastPayment != undefined) {
                $(infoElms.derniere_mensualite).innerHTML = jsonLoan.lastPayment;
                }
                $(infoElms.teg).innerHTML = jsonLoan.teg;
                $(infoElms.couttotal).innerHTML = jsonLoan.totalAmount;
                $(infoElms.interet).innerHTML = jsonLoan.interest;
            },
            onFailure: function(){
            	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(elBoxAmount, 'change', 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 ($(elBoxDuration).value > $oldDuration)
		{
			$direction = 'right';
		}
		else
		{
			$direction = 'left';
		}
		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(elBoxDuration, 'change', function(){
        if ($(elBoxDuration).value > $oldDuration)
		{
			$direction = 'right';
		}
		else
		{
			$direction = 'left';
		}
        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(elBoxDuration, 'focus', function(){
		oldDuration = $(elBoxDuration).value;
    });

    Event.observe(elBoxMonthlyPayment, 'blur', function(){
		var v = parseInt($(elBoxMonthlyPayment).value);
        if((v >= sliderMonthlyPaymentRange.first()) && (v <= sliderMonthlyPaymentRange.last())){ setSliderValue(sliderMonthlyPayment, v); }
        else if(v < sliderMonthlyPaymentRange.first()){ setSliderValue(sliderMonthlyPayment, sliderMonthlyPaymentRange.first()); }
        else if(v > sliderDurationRange.last()){ setSliderValue(sliderMonthlyPayment, sliderMonthlyPaymentRange.last()); }
    });

    Event.observe(elBoxMonthlyPayment, 'change', function(){
		var v = parseInt($(elBoxMonthlyPayment).value);
        if((v >= sliderMonthlyPaymentRange.first()) && (v <= sliderMonthlyPaymentRange.last())){ setSliderValue(sliderMonthlyPayment, v); }
        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(elBoxAmount, elBoxDuration, elBoxMonthlyPayment); });
    Event.observe('trackAmount_plus', 'click', function(){ sliderAmount.setNextValue(elBoxAmount, elBoxDuration, elBoxMonthlyPayment); });

    Event.observe('trackMonthlyPayment_minus', 'click', function(){ sliderDuration.setNextValue(elBoxAmount, elBoxDuration, elBoxMonthlyPayment); });
    Event.observe('trackMonthlyPayment_plus', 'click', function(){ sliderDuration.setPreviousValue(elBoxAmount, elBoxDuration, elBoxMonthlyPayment); });

    Event.observe('trackDuration_minus', 'click', function(){ sliderDuration.setPreviousValue(elBoxAmount, elBoxDuration, elBoxMonthlyPayment); });
    Event.observe('trackDuration_plus', 'click', function(){ sliderDuration.setNextValue(elBoxAmount, elBoxDuration, elBoxMonthlyPayment); });
}

