﻿var BH = BH || {}

BH.mcalc = function () {

    // reference to calculator instances
    var calculators = [];

    // default values for calculation
    var defaults = {
        mortgageMultiplier: 4,
        depositMultiplier: 0.705882352,
        valueMultiplier: 4.705882352,
        minSalary: 1,
        maxSalary: 9999999
    }
	
	// possible values for property ranges	
	var priceRanges = [
		100000,
		200000,
		300000,
		400000,
		500000,
		600000,
		700000,
		800000,
		900000,
		1000000,
		2000000
	];
	
	var priceRangeTypes = { 
		min: 'min',
		max: 'max' 
	};
	
	var priceRangeQuerystring = {
		min: 'price_min',
		max: 'price_max'	
	}
	
	var _this;

    /* constructor for calculator. Requires element (DOM, jQuery or selector) and 
    * optional calculation override 
    */
    function calculator(el, options) {

        this.el = $(el);
        _this = this;

        this.findElements();
        this.bindEvents();

        this.salaryEl.val('').removeAttr("disabled");
        this.generateBtnEl.show();
        this.resultsEl.hide();

        for (var property in defaults) {
            this[property] = defaults[property];
        }

        for (var property in options) {
            this[property] = options[property];
        }

    }

    calculator.prototype.findElements = function () {

        this.salaryEl = this.el.find(".mcalc-salary");
        this.generateBtnEl = this.el.find(".mcalc-generate");
        this.resultsEl = this.el.find(".mcalc-results");
        this.mortgageEl = this.resultsEl.find(".mcalc-mortgage");
        this.depositEl = this.resultsEl.find(".mcalc-deposit");
        this.valueEl = this.resultsEl.find(".mcalc-value");
		this.ctaEl = this.resultsEl.find("a");
    
	}

    calculator.prototype.bindEvents = function () {

        this.salaryEl.keypress(function (e) {
            if (e.which == 13) {
                e.preventDefault(); _this.salaryEl_enter(e);
            }
        });
        this.generateBtnEl.click(function (e) { _this.generateBtnEl_click(e) })

    }

    calculator.prototype.salaryEl_enter = function () {
        this.calculate();
    }

    calculator.prototype.generateBtnEl_click = function () {
        this.calculate();
    }

    // perform calculation
    calculator.prototype.calculate = function () {
        this.salary = parseInt(this.salaryEl.val());

        if (!this.salary || this.salary < this.minSalary) {
            this.salary = this.minSalary;
            this.salaryEl.val(this.minSalary);
        }
        if (this.salary > this.maxSalary) {
            this.salary = this.maxSalary;
            this.salaryEl.val(this.maxSalary);
        }

		var maxValue = parseInt(this.salary * this.valueMultiplier).formatMoney(0, '.', ',');

        this.mortgageEl.html('£' + parseInt(this.salary * this.mortgageMultiplier).formatMoney(0, '.', ','));
        this.depositEl.html('£' + parseInt(this.salary * this.depositMultiplier).formatMoney(0, '.', ','));
        this.valueEl.html('£' + maxValue);

		// update the CTA to reflect properties within price range
		this.ctaEl.attr('href', this.getPriceRangeLink(parseInt(this.salary * this.valueMultiplier)) );	
	
        this.resultsEl.show();
		
    }

	calculator.prototype.getPriceRangeLink = function(value) {
	
		var href = '/find-a-home/';
		
		if (value > 0) {

			// dynamic to find a home
			var querystring = '?' + priceRangeQuerystring.min + '=' + this.getFromPriceRangeArray(value, priceRangeTypes.min) 
								+ '&' + priceRangeQuerystring.max + '=' + this.getFromPriceRangeArray(value, priceRangeTypes.max);
		
		} else {
	
			//default to find a home			 

			var querystring = '?' + priceRangeQuerystring.min + '=' + priceRanges[0] 
								+ '&' + priceRangeQuerystring.max + '=' + priceRanges[priceRanges.length - 1];
			
		}
		
		return href + querystring;

	}
	
	calculator.prototype.getFromPriceRangeArray = function(value, p) {

		var i = 0;
			  
		switch(p)
		{
			case priceRangeTypes.min:
				
				if (value <= priceRanges[0]) return value;
				
				while (priceRanges[i] <= value)
				{
					i++;
					if (i > priceRanges.length - 1) break;
				}
				if(i > 0) i --;
				break;
			case priceRangeTypes.max:
				
				if (value >= priceRanges[priceRanges.length - 1]) return value;
				
				while (value >= priceRanges[i])
				{
					i++;
					if (i > priceRanges.length - 1) break;
				}                    
				break;

		}
		return priceRanges[i];   
					
	}
    
	function init(el, options) {

        calculators.push(new calculator(el, options));

    }

    return {
        init: init,
        calculators: calculators
    }

} ();

Number.prototype.formatMoney = function (c, d, t) {
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

