var module = angular.module('calculator', []);

var facilities = {
  marjorie: {
    key: 'marjorie',
    name: 'Marjorie P. Lee',
    cost: 5000,
    contact: {
      name: 'Jenn Schlotbom',
      phone: '513.533.5000'
    },
    colors: {
      primary: {
        r: 159,
        g: 102,
        b: 19,
        hex: '#9f6613'
      },
      secondary: {
        r: 0,
        g: 93,
        b: 110,
        hex: '#005d6e'
      }
    }
  },
  deupree: {
    key: 'deupree',
    name: 'Deupree House',
    cost: 4800,
    contact: {
      name: 'Karen Immell',
      phone: '513.561.6363'
    },
    colors: {
      primary: {
        r: 0,
        g: 80,
        b: 47,
        hex: '#00502f'
      },
      secondary: {
        r: 0,
        g: 93,
        b: 110,
        hex: '#005d6e'
      }
    }
  },
  ech: {
    key: 'ech',
    name: 'Episcopal Church',
    cost: 1500,
    contact: {
      name: 'Elizabeth Pace',
      phone: '502.736.8043'
    },
    colors: {
      primary: {
        r: 105,
        g: 60,
        b: 94,
        hex: '#693C5E'
      },
      secondary: {
        r: 0,
        g: 93,
        b: 110,
        hex: '#005d6e'
      }
    }
  }
};

module.directive('steps', function() {
  return {
    restrict: 'EA',
    transclude: true,
    controller: function($scope, $element) {
      var steps = $scope.steps = [],
        currentStep = 0;

      $scope.select = function(step) {
        _.each(steps, function(stepCompare, idx) {
          if (_.isEqual(stepCompare, step)) {
            stepCompare.select();
            currentStep = idx;
          } else {
            stepCompare.selected = false;
          }
        });
      };

      this.addStep = function(step) {
        steps.push(step);

        if (steps.length - 1 === currentStep) {
          $scope.select(step);
        }
      };

      $scope.advance = function() {
        if (currentStep + 1 > steps.length - 1) {
          currentStep = -1;
        }
        $scope.select(steps[currentStep + 1])
        
        if (currentStep == 6) {
        	submitCalcFormToHS();
        }
      };
    },
    template:
      '<div class="tabbable">' +
        '<ul class="nav nav-pills">' +
          '<li ng-repeat="step in steps" ng-class="{active:step.selected}">' +
            '<button type="button" class="btn" ng-class="{\'btn-primary\':step.selected,\'btn-default\':!step.selected}" ng-click="select(step)">' +
              '{{step.title}}' +
            '</button>' +
          '</li>' +
        '</ul>' +
        '<div class="tab-content" ng-transclude></div>' +
      '</div>',
    replace: true
  }
});

module.directive('step', function() {
  return {
    require: '^steps',
    restrict: 'EA',
    transclude: true,
    scope: { title: '@' },
    link: function($scope, $element, $attrs, stepsCtrl) {
      $scope.$element = $element;
      stepsCtrl.addStep($scope);
    },
    controller: function($scope) {
      $scope.select = function() {
        $scope.selected = true;

        // Select first input
        var inputs = $scope.$element.find('input');
        if (inputs.length) {
          _.defer(function() {
            _.first(inputs).focus();
          });
        }
      }
    },
    template: '<div class="tab-pane" ng-class="{active: selected}" ng-transclude></div>',
    replace: true
  };
});

module.directive('currency', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function($scope, $element, $attrs, ngModelCtrl) {
      ngModelCtrl.$parsers.push(function(data) {
        return parseInt(data.replace(/,/g, ''), 10);
      });
    }
  };
});

module.controller('CalculatorCtrl', ['$scope', 'facility',
  function($scope, facility) {
    var totals = $scope.totals = {
        housing: {},
        utilities: {},
        expenses: {},
        recreation: {}
      },
      grandTotal = 0,
      chartCtx = document.getElementById('cvsResults').getContext('2d');

    $scope.facility = facility;

    var misc = $scope.misc = {};
    $scope.chargesPerYearOptions = [
      { value: 12, text: 'per month' },
      { value: 4, text: 'per quarter' },
      { value: 1, text: 'per year' }
    ];

    $scope.getOpportunityCost = function() {
      return (((misc.homeEquity || 0) - (misc.homeEquity || 0) * 0.1) * 0.075) / 12;
    };

    $scope.getFacility = function() {
      return facility;
    };

    $scope.getSavings = function() {
      return this.getGrandTotal() - facility.cost;
    };

    $scope.getGrandTotal = function() {
      return _.reduce(totals, function(memo, value, section) {
        return memo + $scope.getTotal(section);
      }, 0);
    };

    $scope.getTotal = function(section) {
      if (!(section in totals)) return 0;

      return _.reduce(totals[section], function(memo, field) {
        var value = parseFloat(field.cost);
        if (!isNaN(value)) {
          if ('chargesPerYear' in field) {
            return memo += (value * field.chargesPerYear) / 12;
          }
          return memo += value;
        }
        return memo;
      }, 0);
    };

    $scope.updateChart = function(facilityCost, currentExpenses) {
      var max = Math.max(facilityCost, currentExpenses),
        roundedMax = Math.round(max / 500) * 500,
        stepWidth = (roundedMax + 500) / 10,
        colors = facility.colors;

      if (typeof G_vmlCanvasManager === 'object') {
        G_vmlCanvasManager.initElement(document.getElementById('cvsResults'));
      }

      new Chart(chartCtx).Bar({
        labels: [ facility.name, "Current Expenses" ],
        datasets: [{
          fillColor : ['rgba(' + colors.primary.r + ',' + colors.primary.g + ',' + colors.primary.b + ',0.7)', 'rgba(' + colors.secondary.r + ',' + colors.secondary.g + ',' + colors.secondary.b + ',0.7)'],
          strokecolors : ['rgba(' + colors.primary.r + ',' + colors.primary.g + ',' + colors.primary.b + ',1)', 'rgba(' + colors.secondary.r + ',' + colors.secondary.g + ',' + colors.secondary.b + ',1)'],
          data : [ facilityCost, currentExpenses ]
        }]
      }, {
        animation: false,
        scaleOverride: true,
        scaleSteps: 10,
        scaleStepWidth: stepWidth,
        scaleStartValue: 0,
        scaleLabel: '$<%= value %>',
        scaleFontSize: 11
      });
    };

    $scope.$watch(function() {
      var newGrandTotal = $scope.getGrandTotal();
      if (grandTotal !== newGrandTotal) {
        grandTotal = newGrandTotal;
        $scope.updateChart(facility.cost, newGrandTotal);
      }
    });

    $scope.updateChart(facility.cost, 0);
  }]
);


function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

$(document).ready(function() {
	$('.email-results').click(function(){
		window.location.href = "http://www.episcopalretirement.com/get-your-cost-of-living-results-marjorie";
	});
});

function submitCalcFormToHS(){
	var args = $('form[name=calculatorForm]').serialize();
	args = args + '&grand-total=' + encodeURIComponent($('.grand-total').html());
	args = args + '&savings1=' + encodeURIComponent($('.savings1').html());
	args = args + '&savings2=' + encodeURIComponent($('.savings2').html());
	args = args + '&hutk=' + encodeURIComponent(readCookie('hubspotutk'));
	args = args + '&housing-expenses-total=' + encodeURIComponent($('.housing-expenses-total').html());
	args = args + '&utilities-total=' + encodeURIComponent($('.utilities-total').html());
	args = args + '&expenses-total=' + encodeURIComponent($('.expenses-total').html());
	args = args + '&recreation-total=' + encodeURIComponent($('.recreation-total').html());
	args = args + '&opportunity-cost=' + encodeURIComponent($('.opportunity-cost').html());
	args = args + '&rent=' + encodeURIComponent($('#txtRent').val());
	args = args + '&rent-period=' + encodeURIComponent($('select[name=txtRentPeriod]').val());
	args = args + '&homeowners-insurance=' + encodeURIComponent($('#txtHomeInsurance').val());
	args = args + '&homeowners-insurance-period=' + encodeURIComponent($('select[name=txtHomeInsurancePeriod]').val());
	args = args + '&property-tax=' + encodeURIComponent($('#txtPropertyTax').val());
	args = args + '&property-tax-period=' + encodeURIComponent($('select[name=txtPropertyTaxPeriod]').val());
	args = args + '&gas=' + encodeURIComponent($('#txtGas').val());
	args = args + '&gas-period=' + encodeURIComponent($('select[name=txtGasPeriod]').val());
	
	$.ajax({
		type: "POST",
		url: 'http://app.marjorieplee.com/submitCalcFormToHS.php',
		data: args,
		success: function( response ) {
			console.log( response );
		}
	});
}