﻿/*
  
  Copyright © 2007 Business Valuation Resources, LLC.

  General purpose client-side helper routines exposed via the BVR.Utils namespace.

*/

Type.registerNamespace("BVR.Utils");

BVR.Utils.setFocus = function(control) {
  if ((control) && (control.focus)) {
    if (!control.disabled) {
      try {
        control.focus();
        if ((control.select) && (control.type.toLowerCase() != "textarea")) {
          control.select();
        }
      }
      catch (e) {}
    }
  }
};

BVR.Utils.numToStr = function(value, decimals) {
  if (this.isUndefined(decimals)) decimals = 2;
  var n = this.toNum(value.toString());
  if (isNaN(n)) return value;
  var neg = (n < 0);
  if (neg) n = 0 - n;
  var s = n.toFixed(decimals);
  var i = s.indexOf(".");
  var c = 0;
  var s2 = (i < 0) ? "" : s.substr(i);
  if (i < 0) i = s.length;
  for (var j = i - 1; j > -1; j--) {
    c++;
    if (c > 3) {
      s2 = "," + s2;
      c = 1;
    }
    s2 = s.substr(j, 1) + s2;
  }
  s = s2;
  if (neg) s = "-" + s;
  return s;
};
  
BVR.Utils.numToPct = function(value, decimals) {
  if (this.isUndefined(decimals)) decimals = 2;
  var hasPct = (value.toString().indexOf("%") != -1);
  var n = this.toNum(value.toString());
  if (isNaN(n)) return value;
  if ((!hasPct) && (n > -1) && (n < 1)) {
    n = (n * 100);
  } 
  return n.toFixed(decimals) + "%";
};
  
BVR.Utils.toNum = function(value) {
  if (value == null) return Number.NaN;
  if (this.isUndefined(value)) return Number.NaN;
  value = value.toString();
  if (value.length == 0) return Number.NaN;
  var neg = ((value.indexOf("(") != -1) && (value.indexOf(")") > value.indexOf("(")));
  value = value.replace(/[\$\s%,\(\)]/g, "");
  var n = new Number(value);
  if (neg) n = 0 - n;
  return n;
};

BVR.Utils.isNum = function(value) {
  return (!isNaN(this.toNum(value)));
};

BVR.Utils.isUndefined = function(target) {
  return (typeof target == "undefined");
};

BVR.Utils.errorOn = function(target) {
  if ((target) && (!this.isUndefined(target)) && (target.style)) {
    target.style.backgroundColor = "#FFFFED";
  }
}

BVR.Utils.errorOff = function(target) {
  if ((target) && (!this.isUndefined(target)) && (target.style)) {
    target.style.backgroundColor = "";
  }
}
  
if(typeof('Sys') !== 'undefined') Sys.Application.notifyScriptLoaded();
