// pricing_calculator.js
// a little script to calculate prices
var GDI = GDI || {}
GDI.PriceCalculator = $.klass({
  initialize: function(pricing, minimums) {
    this.field_minimums = minimums || {};
    this.reset_prices();
    this.unit_pricing = pricing["unit"] || {};
    this.option_pricing = pricing["options"] || {};
    this.display = this.element.find("#pricing_prices");
    //clear the form
    this.clear_form_elements();
    //now attach event handling to the button, if there is one
    this.initialize_button();
    this.set_minimums();
  },
  initialize_button: function() {
    var _this = this;
    this.recalculate_button = this.element.find("#pricing_recalculate");
    this.enable_button();
    if(this.recalculate_button) {
      // event assignment, with _this indirection. Thanks a ton, jQuery. /sarcasm
      $(this.recalculate_button).click(function(e) {
        if(e) {
          e.preventDefault();
        }
        if( $(this).attr('disabled') ) { return false; }
        _this.redraw.apply(_this, []);
      });
    }
  },
  onsubmit: function(e) {
    e.preventDefault();
  },

  redraw: function() {
    this.set_minimums();
    this.recalculate_prices();
    this.display_estimate();
    this.enable_button();
  },
  set_minimums: function() {
    var _this = this;
    $.each(this.field_minimums, function(i) {
      if($(i) && $(i).val() < _this.field_minimums[i]) {
        $(i).val(_this.field_minimums[i])
      }
    });
  },
  display_estimate: function() {
    $("#monthly_price").html(this.format_price("monthly"));
    $("#yearly_price").html(this.format_price("yearly"));
    this.display_options("mailbox");
    this.display_options("domain");
    this.display_options("enterprise");
		this.display_options("antivirus");
    this.display_options("tls");
    this.display_options("quarantine");
    if( $(this.display).is(":visible") ) {
      $(this.display).hide();
      $(this.display).fadeIn();
    }
    $(this.display).slideDown();
  },
	display_options: function(which) {
		if(this[which + "_price"] != 0) {
			$("#" + which + "_li").show();
		  $("#" + which + "_price_li").show();
			$("#" + which + "_price").html(this.format_price(which));
		} else {
			$("#" + which + "_li").hide();
			$("#" + which + "_price_li").hide();
		}
	},
  hide_estimate: function() { $(this.display).fadeOut(); },
  disable_button: function() { $(this.recalculate_button).attr('disabled', true).addClass('disabled'); },
  enable_button: function() { $(this.recalculate_button).removeAttr('disabled').removeClass('disabled'); },
  clear_form_elements: function() {
    $(this.element.attr("id") + " input[type=text]").val('');
    $(this.element.attr("id") + " input:checkbox").attr('checked', false);
  },
  format_price: function(which) {
    var raw_price = this[which + "_price"];
    return "$" + raw_price.toFixed(2);
  },
  get_options: function() {
    var items = []
    this.element.find("input:checked").each(function(i) {
      items.push(this.id.replace(/pricing_/, ''));
    });
    return items;
  },
  reset_prices: function() {
    this.monthly_price    = 0;
    this.yearly_price     = 0;
    this.mailbox_price    = 0;
    this.domain_price     = 0;
    this.enterprise_price = 0;
    this.antivirus_price  = 0;
    this.tls_price        = 0;
    this.quarantine_price = 0;
  },
  recalculate_prices: function() {
    this.reset_prices();
    var base_price = 0;
    var mailboxes = $("#pricing_mailboxes").val() * 1;
    if(mailboxes == 0) return false;
    var options = this.get_options();
    
    var domain_count = $("#pricing_domains").val() * 1;
    var domain_price = domain_count * this.unit_pricing["domains"];
    
    if(mailboxes > 0 && mailboxes < 10) {
      base_price = this.unit_pricing["family"];
    } else {
      this.mailbox_price = this.get_mailbox_rate(mailboxes) * mailboxes;
      var rate_modifier = this.get_rate_modifier(options, mailboxes);
      rate = this.get_mailbox_rate(mailboxes) + rate_modifier;
    
      base_price = mailboxes * rate;
    }
    
    var sub_total = base_price + domain_price;
    var markups = this.flat_rate_markups(options, (this.get_mailbox_rate(mailboxes) * mailboxes + domain_price), mailboxes);
    var final_price = sub_total;
    $.each(markups, function(i) {
      final_price += this;
    });
    
    this.domain_price = domain_price;
		this.monthly_price = final_price;
    this.yearly_price = final_price * 10;
    
  },
  get_mailbox_rate: function(how_many) {
    var buckets = $.keys(this.unit_pricing["mailboxes"]);
    if(buckets.length == 0) {
      return 0;
    } else {
      var found_bucket = null;
      $.each(buckets, function(index, item) {
        var range = item.split("-");
        var start = range[0], end = range[1];
        if( (start*1) <= how_many && how_many <= (end*1)) {
          found_bucket = item;
          return false;
        }
      });
      if(found_bucket) {
        return this.unit_pricing["mailboxes"][found_bucket];
      } else {
        return 0;
      }
    }
  },
  get_rate_modifier: function(options, quantity) {
    if(options.length == 0) return 0;
    var rate_mod = 0;
    var _this = this;
    $.each(options, function(index) {
      var option_rate_mod = _this.option_pricing["rate"][this];
      if(option_rate_mod) {
        rate_mod += option_rate_mod;
        _this[this + "_price"] = quantity * option_rate_mod;
      }
    });
    return rate_mod;
  },
  flat_rate_markups: function(options, base_price, quantity) {
    if(options.length == 0) return [];
    var markups = [];
    var _this = this;
    $.each(options, function(index) {
      var flat_rate_markup = _this.option_pricing["percent"][this];
      if(flat_rate_markup) {
        markups.push( flat_rate_markup * base_price );
        _this[this + "_price"] = flat_rate_markup * base_price;
      }
    });
    return markups;
  }
});

//$.keys(obj) gets all the keys from the given object.
$.extend({
  keys: function(obj){
    var a = [];
    $.each(obj, function(k){ a.push(k) });
    return a;
  }
});