var $first = true;

var $direction = '';

function gaTrackEventHome($category, $action, $label, $value){
	if ($first) {				
		//alert('$category : simulateur $action : hpc2c $label : interaction');
		_gaq.push(['_trackEvent','simulateur', 'hpc2c', 'interaction']);
		$first = false;
	}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';
		if(this.allowedValues){
        	var value = this.getNearestValueExt(this.value,1);
            var act = $A(this.allowedValues).indexOf(value);
            if(act <= this.allowedValues.length-1){ this.setValue(this.allowedValues[act]); }
            this.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);

            // Mise à jour du récapitulatif
            updateRecap();
        }
        return false;
    },
    setPreviousValue: function(elBoxAmount, elBoxDuration, elBoxMonthlyPayment){
	    $direction = 'left';
		if(this.allowedValues){
        	var value = this.getNearestValueExt(this.value,0);
            var act = $A(this.allowedValues).indexOf(value);
            if(act >= 0){ this.setValue(this.allowedValues[act]); }
            this.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);

            // Mise à jour du récapitulatif
            updateRecap();

        }
        return false;
    },
    getAllowedValues: function(direction) {
    	var allowedValues;
	var pivot = 5000;
    	switch(this.track.id) {
			case 'trackDuration' :
				if(sliderAmount.value<pivot) {
					allowedValues = magicTableGlobal.classic.duration.r;
				} else if(sliderAmount.value>pivot) {
					allowedValues = magicTableGlobal.classic.duration.p;
				} else {
					if(direction == 1) {
						// up
						allowedValues = magicTableGlobal.classic.duration.p;
					} else {
						// down
						allowedValues = magicTableGlobal.classic.duration.r;
					}
				}
			break;
			case 'trackMonthlyPayment' :
				if(sliderAmount.value <pivot) {
					allowedValues = magicTableGlobal.classic.payment.r;
				} else if(sliderAmount.value >pivot){
					allowedValues = magicTableGlobal.classic.payment.p;
				} else {
					if(direction == 1) {
						allowedValues = magicTableGlobal.classic.payment.p;
					} else {
						allowedValues = magicTableGlobal.classic.payment.r;
					}
				}
			break;
			case 'trackAmount' :
				if(sliderAmount.value<pivot) {
					allowedValues = magicTableGlobal.classic.amount.r;
				} else if(sliderAmount.value >pivot) {
					allowedValues = magicTableGlobal.classic.amount.p;
				} else {
					if(direction == 1) {
						allowedValues = magicTableGlobal.classic.amount.p;
					} else {
						allowedValues = magicTableGlobal.classic.amount.r;
					}
				}
			break;
    	}
    	return allowedValues;
    },
    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;
						resMp = 0;

            // On récupère les valeurs
            var tempArray = Object.clone(magicTableGlobal.revAP[mt]);

            var keyArray = new Array();

            // Boucle sur l'objet pour récupérer les valeurs et les assigner dans un tableau
            $H(tempArray).each(function(val){
              keyArray.push(val.key) 
            });

            // On ne renverse le tableau que pour les cas ou l'on n'a pas webkit
            if (!Prototype.Browser.WebKit)
            {
              // Tri du tableau
              keyArray = keyArray.reverse();
            }

            $A(keyArray).each(function(elm){
							if(!finish) {
								// Quelle est la direction ?
								if ($direction == 'left')
								{
									// On vérifie la direction
									var valMin = $H(magicTableGlobal.revAP[mt]).min();

									// Si la clé est inférieure à la valeur 	
									if (parseInt(elm) <= mp)
									{
										// Stocke la nouvelle valeur
										resMp = elm;
									}
									// Sinon
									else
									{
										if (resMp == 0)
										{
											// On affecte la valeur min au slider
											resMp = valMin[0];
										}
									}
								}
								else
								{
									resMp = elm;
								}
							}
							if(parseInt(elm)>=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;
	}
});
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;
    if(dr == '') {
    	dr = magicTableGlobal.classic.duration.r.first();
    }
/*
    if (mt < 5000){
    	var res = magicTableGlobal.classic.duration.r.first();
    	magicTableGlobal.classic.duration.r.each(function(elm){
			if(elm >= dr){ res = elm; }
    	});
    	dr = res;
    }
    else{
    	var res = magicTableGlobal.classic.duration.p.first();
    	magicTableGlobal.classic.duration.p.each(function(elm){
			if(elm >= dr){ res = elm; }
    	});
    	dr = res;
    }

    var result = [mt,dr,magicTable[mt][dr]];
*/
	var result = [mt,dr,magicTableGlobal.revAD[mt][dr]];
    return result;
}

function getDuration(elMontant, elEcheance)
{
    elMontant = $(elMontant);
    elEcheance = $(elEcheance);
    // var Tab = magicTable[elMontant.value];
    var mt = 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();
    }
	var result = [mt,dr,magicTableGlobal.revAP[mt][ec]];
    return result; // [0,dr,ec2];
*/
    return [0,dr,ec2];
}

function initSliders( elBoxAmount, elBoxDuration, elBoxMonthlyPayment )
{
    //appel pour recup?rer objet JSON pour magicTable
    new Ajax.Request('/layout/set/vide/simulateurs/indexvalue?json=getTeg',{
        method: 'get',
        onSuccess: function(ret){
            magicTable = validateJSON(ret.responseText);

		    new Ajax.Request('/layout/set/vide/simulateurs/indexvalue?json=getAmountRange',{
		        method: 'get',
		        onSuccess: function(ret){
					sliderMonthlyPaymentRange = validateJSON(ret.responseText);

				    new Ajax.Request('/layout/set/vide/simulateurs/indexvalue?json=getDurations',{
				        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 );
						        }
						    });
				        }
				    });
		        }
		    });

        },
        onFailure: function(){
            magicTable = magicTableSecours;
            postInitSliders( elBoxAmount, elBoxDuration, elBoxMonthlyPayment );
            initSlidersValues();
        }
    });
}

function getMagicValues()
{
    var Tab = $A();
    $H(magicTable).each(
        function(elm){ Tab.push(parseInt(elm.key)); }
    )
    return Tab;
}

function postInitSliders( elBoxAmount, elBoxDuration, elBoxMonthlyPayment )
{
    // 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();
                sliderAmount.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);
                updateRecap();
				
				// Mantis 162 GA
				gaTrackEventHome('simulateur', 'hpc2c', '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();
                sliderDuration.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);
                updateRecap();
				
				// Mantis 162 GA
				gaTrackEventHome('simulateur', 'hpc2c', 'duree',$(elBoxDuration).value);
            }
        }
    });

    sliderMonthlyPayment = new Control.Slider('handleMonthlyPayment', 'trackMonthlyPayment', {
		range: $R(
        	sliderMonthlyPaymentRange.first(),
        	sliderMonthlyPaymentRange.last()
        ),
        values:$A(magicTableGlobal.classic.payment.g),
        onSlide: function(v) { $(elBoxMonthlyPayment).value = (v*1).toFixed(); },
        onChange: function(v){
            $(elBoxMonthlyPayment).value = (v*1).toFixed();
            var result;
            if(globalComputing == 1) {
                disableComputing();
                sliderMonthlyPayment.computeValues(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);
                updateRecap();
				
				// Mantis 162 GA
				gaTrackEventHome('simulateur', 'hpc2c', 'mensualite',$(elBoxMonthlyPayment).value);
            }
        }
    });

}

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 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(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);
    });
    Event.observe('trackAmount_plus', 'click', function(){
    	sliderAmount.setNextValue(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);
    });
    Event.observe('trackMonthlyPayment_minus', 'click', function(){
    	sliderMonthlyPayment.setPreviousValue(elBoxAmount, elBoxDuration, elBoxMonthlyPayment);
    });
    Event.observe('trackMonthlyPayment_plus', 'click', function(){
    	sliderMonthlyPayment.setNextValue(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);
    });
}

function validateJSON(jsonText)
{
    if(jsonText == '' || jsonText == null){ return false; }
    return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
        jsonText.replace(/"(\\.|[^"\\])*"/g, '')))
        && eval('(' + jsonText + ')');
}


