(function () {
    
    function Calculator() {
        this.$inputs = {
            menu: {
                investments: document.getElementById('investments')
            },
            compoundInterest: {
                interestRate: document.getElementById('si-interest-rate'), 
                investment: document.getElementById('si-investment'),
                period: document.getElementById('si-period')
            }

        },
        this.$outputs = {
            wrapper: document.getElementById('output'),
            values:{
                output1: document.getElementById('output1'),
                output2: document.getElementById('output2'),
                output3: document.getElementById('output3'),
                output4: document.getElementById('output4')
            }
        },
        this.sections = {
            current: '',
            investments: document.getElementById('single-investments')
        },
        this.chart = {
            tag: document.getElementById('chart'),
            key: '',
            label: 'year3',
            labels: {
                year1: ["0", "2 months", "4 months", "6 months", "8 months", "10 months", "12 months"],
                year2: ["0", "4 months", "8 months", "12 months", "16 months", "20 months", "24 months"],
                year3: ["0", "6 months", "12 months", "18 months", "24 months", "30 months", "36 months"],
                year4: ["0", "8 months", "16 months", "24 months", "32 months", "40 months", "48 months"],
                year5: ["0", "10 months", "20 months", "30 months", "40 months", "50 months", "60 months"]
            },
            style:{
                type: 'line', 
                data: {
                    labels: ["0", "6 months", "12 months", "18 months", "24 months", "30 months", "36 months"], 
                    datasets: [{
                        label: 'Yearly', 
                        data: [0, 0, 0, 0, 0, 0, 0],
                        backgroundColor: 'rgba(54, 65, 84, 1)', 
                        borderColor: 'rgba(47, 79, 79, 1)'
                    },
                    {
                        label: 'Semesterly',
                        data: [0, 0, 0, 0, 0, 0, 0], 
                        backgroundColor: 'rgba(37, 116, 169, 0.8)',
                        borderColor: 'rgba(119, 136, 153, 1)'
                    },
                    {
                        label: 'Quaterly',
                        data: [0, 0, 0, 0, 0, 0, 0],
                        backgroundColor: 'rgba(92, 151, 191, 0.5)',  
                        borderColor: 'rgba(128, 128, 128, 1)'
                    },
                    {
                        label: 'Monthly',
                        data: [0, 0, 0, 0, 0, 0, 0],
                        backgroundColor: 'rgba(78, 205, 196, 0.2)', 
                        borderColor: 'rgba(192, 192, 192, 1)'
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            },                
            compoundInterest:{
                object: ''
            }
        }, 
        this._model = {
            compoundInterest:{
                interestRate : 0,
                investment : 0,
                peroids: {
                    year1: [1, 2, 4, 12],
                    year2: [2, 4, 8, 24],
                    year3: [3, 6, 12, 36],
                    year4: [4, 8, 16, 48],
                    year5: [5, 10, 20, 60]
                },
                timescale : {
                  year1: ''  
                },
                derived: {
                    interestRate: function(){
                        return (this._model.compoundInterest.interestRate / 100) + 1;
                    }.bind(this),
                    investment: function(){
                        //return Math.round(this._model.investment * this._model.derived.interestRate());
                    }.bind(this)
                }
            }
        };
        //this.init();
    }
    
    /*Calculator.prototype.init = function() {
        console.log("Init");
    }*/
    
    Calculator.prototype.bindUIEvents = function () {
        var that = this;
        Object.keys(this.$inputs).forEach(function (keyMain) {
            
            Object.keys(that.$inputs[keyMain]).forEach(function (keySub) {
                
                if(keyMain == "conversions" || keyMain == "compoundInterest") {
                    // if (that.$inputs[keyMain][keySub].value.trim() !== '') {
                    //     classie.add(that.$inputs[keyMain][keySub].parentNode, 'input--filled');
                    // }
                    
                    if(keySub != "period"){
                        that.$inputs[keyMain][keySub].addEventListener('focus', onInputFocus);
                        that.$inputs[keyMain][keySub].addEventListener('blur', onInputBlur);
                        that.$inputs[keyMain][keySub].addEventListener('input', function(){onInputChange(keyMain, keySub)});
                    }
                    else if(keySub == "period"){
                        that.$inputs[keyMain][keySub].addEventListener('input', function(){onRangesliderChange(keyMain, keySub)});
                    }
                    
                    
                }
            })
        })
    }
    
    Calculator.prototype.updateOutputs = function (keyMain) {
        //var that = this;
        //Object.keys(this._model[keyMain].derived).forEach(function (subKey) {
        var currentPeriod = this.chart.label;
        var length = this._model[keyMain].peroids[currentPeriod].length;
        var periods = this._model[keyMain].peroids[currentPeriod];
        //console.log(currentPeriod+" "+that._model[keyMain].peroids[currentPeriod]+" "+periods);

            for(var i=0; i < length; i++){
                //console.log(that._model[keyMain].periods[i]+" "+that._model[keyMain].derived.interestRate()+" "+that._model[keyMain].investment);
                //console.log(this._model[keyMain].periods[currentPeriod][i]);
                var returnArray = compoundInterest(periods[i], this._model[keyMain].derived.interestRate(), this._model[keyMain].investment);
                var lastValue = returnArray[returnArray.length - 1];
                textOutput(i, lastValue);
                this.chart[keyMain].object.data.datasets[i].data = returnArray;
                this.chart.key = keyMain;
            }
            this.chart[keyMain].style = myCalculator.chart.style;
            //console.log("** whooop");
        
            this.chart[keyMain].object.update();
            
        //})
    }
    
    function textOutput(index, value){
        //console.log(index+" "+value);
        
        switch(index){
            case 0: writeOutput('output1', 'Yearly calculation:', value); break;
            case 1: writeOutput('output2', 'Semesterly calculation:', value); break;
            case 2: writeOutput('output3', 'Quaterly calculation:', value); break;
            case 3: writeOutput('output4', 'Monthly calculation:', value); break;
        }
    }
    
    function writeOutput(id, msg, value){
        myCalculator.$outputs.values[id].innerHTML = msg+" R"+value;
    }

    function compoundInterest(period, interestRate, investment){
        var steps = period / 6;
        var output = new Array(6);
        
        for(var i = 0; i <= 6; i++){
            var temp = steps * i;
            output[i] = Math.round(Math.pow(interestRate, temp) * investment);
        }
        
        //var goal = Math.round((Math.pow(interestRate, period) * investment));
        return output;
    }
    
    function onInputFocus(evt) {
        classie.add(evt.target.parentNode, 'input--filled');
    }

    function onInputBlur(evt) {
        if (evt.target.value.trim() === '') {
            classie.remove(evt.target.parentNode, 'input--filled');
        }
    }

    function onRangesliderChange(main, sub) {
        var element =  myCalculator.$inputs[main][sub];
        var value = parseFloat(element.value);
        var label = '';
        
        switch(value){
            case 1: label = 'year1'; break;
            case 2: label = 'year2'; break;
            case 3: label = 'year3'; break;
            case 4: label = 'year4'; break;
            case 5: label = 'year5'; break;
            default: label = 'year3'; break;
        }
        
        myCalculator.chart.label = label;
        myCalculator.chart[main].object.data.labels = myCalculator.chart.labels[label];
        
        myCalculator.updateOutputs(main);
    }
    
    function onInputChange(main, sub) {
        var element =  myCalculator.$inputs[main][sub];
        var value = parseFloat(element.value);
        var max = element.getAttribute('max');
        var min = element.getAttribute('min');
        
        if(value > max)
            value = max;
        else if(value < min)
            value = min;
        
        myCalculator._model[main][sub] = value;
        
        myCalculator.updateOutputs(main);
    }

    function setupLineChart(element) {
        var canvas = element.chart.tag.getContext("2d");
        var myChart = new Chart(canvas, element.chart.style);
        return myChart;
    }
    
    var myCalculator = new Calculator();
    myCalculator.bindUIEvents();
    myCalculator.chart.compoundInterest.object = setupLineChart(myCalculator);
})();