var ComponentFinanceLibDef = function() {
    	

    // Defaults mode
    // Service is on
    this.makolabActivated = true;

    // AJAX call are asynchronous
    this.saveUserFiPrefAsync = false;
    this.setLastOfferAsync = false;

    // Servers parameters
    this.parameters = {
        "computePriceRangeUrl" : "",
        "userFiPrefUrl__Save" : "",
        "userFiPrefUrl__readJSON" : "",
        "getMakoLabOffersfUrl__callMakolab" : "",
        "setLastMakolabOfferUrl" : ""
    }

    this.userFiPref = function () {
        this.depositVO = '';
        this.durationVO = '';
        this.kilometersVO = '';
        this.offerTypeVO = '';
        this.monthlyPaymentVO = '';
        this.depositVN = '';
        this.durationVN = '';
        this.kilometersVN = '';
        this.offerTypeVN = '';
        this.monthlyPaymentVN = '';
    }


    this.___inner___ctrUrlParameter = function (paramValue) {
        if (paramValue != null && paramValue != "null") {
            return paramValue;
        }
        return "";
    }

    this.saveUserFiPref = function () {
        var paramStringVO = "deposit=" + this.___inner___ctrUrlParameter(this.userFiPref.depositVO)
                + "&duration=" + this.___inner___ctrUrlParameter(this.userFiPref.durationVO)
                + "&kilometers=" + this.___inner___ctrUrlParameter(this.userFiPref.kilometersVO)
                + "&offerType=" + this.___inner___ctrUrlParameter(this.userFiPref.offerTypeVO)
                + "&monthlyPayment=" + this.___inner___ctrUrlParameter(this.userFiPref.monthlyPaymentVO)
                + "&type=VO";
        var urlVO = this.parameters.userFiPrefUrl__Save + "&" + paramStringVO;
        new Ajax(urlVO, {
            async: this.saveUserFiPrefAsync,
            method: 'get'
        }).request();

        var paramStringVN = "deposit=" + this.___inner___ctrUrlParameter(this.userFiPref.depositVN)
                + "&duration=" + this.___inner___ctrUrlParameter(this.userFiPref.durationVN)
                + "&kilometers=" + this.___inner___ctrUrlParameter(this.userFiPref.kilometersVN)
                + "&offerType=" + this.___inner___ctrUrlParameter(this.userFiPref.offerTypeVN)
                + "&monthlyPayment=" + this.___inner___ctrUrlParameter(this.userFiPref.monthlyPaymentVN)
                + "&type=VN";
        var urlVN = this.parameters.userFiPrefUrl__Save + "&" + paramStringVN;
        new Ajax(urlVN, {
            async: this.saveUserFiPrefAsync,
            method: 'get'
        }).request();
    }


    this.___inner___loadUserFiPref = function () {
        var urlVO = this.parameters.userFiPrefUrl__readJSON + "&type=VO";
        var syncXhrVO = new XHR({async: false, method: 'get'});
        syncXhrVO.send(urlVO, null);
        
       //console.log(syncXhrVO.transport.responseText)
        var resultVO = Json.evaluate(syncXhrVO.transport.responseText)
        
        if (resultVO.deposit != null && resultVO.deposit != "null") {
            this.userFiPref.depositVO = resultVO.deposit;
        }
        if (resultVO.duration != null && resultVO.duration != "null") {
            this.userFiPref.durationVO = resultVO.duration;
        }
        if (resultVO.kilometers != null && resultVO.kilometers != "null") {
            this.userFiPref.kilometersVO = resultVO.kilometers;
        }
        if (resultVO.offerType != null && resultVO.offerType != "null") {
            this.userFiPref.offerTypeVO = resultVO.offerType;
        }
        if (resultVO.monthlyPayment != null && resultVO.monthlyPayment != "null") {
            this.userFiPref.monthlyPaymentVO = resultVO.monthlyPayment;
        }

        var urlVN = this.parameters.userFiPrefUrl__readJSON + "&type=VN";
        var syncXhrVN = new XHR({async: false, method: 'get'});
        syncXhrVN.send(urlVN, null);
        
		var resultVN = Json.evaluate(syncXhrVN.transport.responseText)
        if (resultVN.deposit != null && resultVN.deposit != "null") {
            this.userFiPref.depositVN = resultVN.deposit;
        }
        if (resultVN.duration != null && resultVN.duration != "null") {
            this.userFiPref.durationVN = resultVN.duration;
        }
        if (resultVN.kilometers != null && resultVN.kilometers != "null") {
            this.userFiPref.kilometersVN = resultVN.kilometers;
        }
        if (resultVN.offerType != null && resultVN.offerType != "null") {
            this.userFiPref.offerTypeVN = resultVN.offerType;
        }
        if (resultVN.monthlyPayment != null && resultVN.monthlyPayment != "null") {
            this.userFiPref.monthlyPaymentVN = resultVN.monthlyPayment;
        }

    }

    /**
     * Javascript AJAX routing to perform an addition :)
     * @param monthlyPayment
     * @param duration
     * @param deposit
     * @param type
     */
    this.computePriceRange = function (monthlyPayment, duration, deposit, type) {
        var url = this.parameters.computePriceRangeUrl + "&type=" + type;
        url = url + "&monthlyPayment=" + monthlyPayment;
        url = url + "&duration=" + duration;
        url = url + "&deposit=" + deposit;

        var syncXhrVN = new XHR({async: false, method: 'get'});
        syncXhrVN.send(url, null);
        return Json.evaluate( syncXhrVN.response.text );
    }

    /**
     * @see getMakolabOffers
     * @param financeParameters
     * @param templateName
     * @param cssSelector
     */
    this.getMakolabOffersVN = function (financeParameters, templateName, cssSelector) {
        financeParameters["type"] = "VN";
        this.getMakolabOffers(financeParameters, templateName, cssSelector);
    }

    /**
     * @see getMakolabOffers
     * @param financeParameters
     * @param templateName
     * @param cssSelector
     */
    this.getMakolabOffersVO = function (financeParameters, templateName, cssSelector) {
        financeParameters["type"] = "VO";
        this.getMakolabOffers(financeParameters, templateName, cssSelector);
    }

    /**
     * idem a a default offer call but offers are save in user preference
     * @see getMakolabOffers
     * @param financeParameters
     * @param templateName
     * @param cssSelector
     */
    this.setLastMakolabOfferAndRecall = function (financeParameters) {
        financeParameters["saveMakolabOffers"] = "true"; // Stripes Handler, see com.renault.eplatform.component.finance.makolab.GetMakolabOffersActionBean
        this.getMakolabOffers(financeParameters);
    }

    /**
     * another helper to compute monthly difference between 2 cars
     * @see getMakolabOffers
     * @param financeParameters
     * @param templateName
     * @param cssSelector
     */
    this.getBestCarMakolabOffersVN = function (financeParameters, upperPrice, templateName, cssSelector) {
        financeParameters["upperPrice"] = upperPrice; // Stripes field, see com.renault.eplatform.component.finance.makolab.GetMakolabOffersActionBean
        this.getMakolabOffersVN(financeParameters, templateName, cssSelector);
    }
    
    
    /**
    * Helper to construct query string from hash (simply key value object)
    *
    */
	this.toQueryString = function (hashObject) {
		var hash = $H(hashObject);
		var queryString = [];
		// here the function takes parameters (value, name)
		hash.each(function (value,name) {
			var qs = function(val){
				queryString.push(name + '=' + encodeURIComponent(val));
			};
			if ($type(value) == 'array') value.each(qs);
			else qs(value);
		});
		return queryString.join('&');
	}
	
    /**
     *  Perform a finance default offer request. You can use 'before_makolab_trigger()' and 'after_makolab_trigger(divId, response)' functions
     * to be notified before and after the ajax call. 
     * @param financeParameters hash finance parameters
     * @param templateName
     * @param cssSelector if given, update the HTML elements that matches with the CSS selector (ex : .)
     */
    this.getMakolabOffers = function (financeParameters, templateName, cssSelector) {
        
        // nothing to do if makolab is disabled
        if (! this.makolabActivated) {
            return;
        }
    	
    	if (typeof before_makolab_trigger == "function") before_makolab_trigger();

        financeParameters["templateName"] = templateName;
        
        // Makolab doesn't accept c2g data on engine param :
        if (financeParameters["engine"] != undefined){
        	financeParameters["engine"] = financeParameters["engine"].toUpperCase();
        }
		
        // AJAX call
        var url = this.parameters.getMakoLabOffersfUrl__callMakolab + "&"+ this.toQueryString(financeParameters);

        var resultOffer;
        
		new Ajax(url, {
			method: 'get',
            /*async: this.setLastOfferAsync,*/
			onComplete : function (response) {
				if (cssSelector != undefined){
					cssSelector.each(function(divId) {
						$$(divId).setHTML(response);
					});
                	resultOffer = response;
					new ReloadTipBox;
				}
    			if (typeof after_makolab_trigger == "function") after_makolab_trigger(response);
			}
		}).request();
        
    }
};

var componentFinanceLib = new ComponentFinanceLibDef();

