var MathLib = function(){
	
	this.countValuePercentage = function(total, value, result) {
		var total_value = jQuery(total).val();
		var total_percent = 100;
		var find_value = jQuery(value).val();
		var find_percent = total_percent - ( (find_value * total_percent) / total_value );
		jQuery(result).val( this.roundNumber(find_percent, 2) );
	}
	
	this.countPercentageValue = function(total, percent, result) {
		var total_value = jQuery(total).val();
		var total_percent = 100;
		var find_percent = jQuery(percent).val();
		var find_value = total_value - ( (total_value * find_percent) / total_percent );		
		jQuery(result).val( this.roundNumber(find_value, 2) );
	}
	
	this.roundNumber = function(num, dec) {
		if(typeof(dec) == 'undefined' || dec < 0) dec = 2;
		var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
		return result;
	}
	
	this.formatAmount = function(s) {
		// convert to string
		if(typeof(s) != 'string') s = new String(s).valueOf();
		// add .00 if needed
		if (String(s).indexOf(".") < 0) {
			  return this.commaFormatted(s + ".00");
		}
		return this.commaFormatted(s);
	}
	
	this.parseCommaFormatted = function(amount) {
		if(amount == null) return 0;
		var a = amount.split(',');
		return new Number( a.join('') ).valueOf();
	}
	
	this.intval = function(mixed_var, base) {
	    var tmp;
	    var type = typeof( mixed_var );

	    if (type === 'boolean') {
	        return (mixed_var) ? 1 : 0;
	    } else if (type === 'string') {
	        tmp = parseInt(mixed_var, base || 10);
	        return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
	    } else if (type === 'number' && isFinite(mixed_var) ) {
	        return Math.floor(mixed_var);
	    } else {
	        return 0;
	    }
	}
	
	this.commaFormatted = function(amount)
	{
		var delimiter = ","; // replace comma if desired
		var a = amount.split('.',2);
		var d = a[1];
		var i = parseInt(a[0]);
		
		if(isNaN(i)) { 
			return ''; 
		}
		
		var minus = '';
		if(i < 0) { 
			minus = '-'; 
		}
		i = Math.abs(i);
		var n = new String(i);
		var a = [];
		
		while(n.length > 3)
		{
			var nn = n.substr(n.length-3);
			a.unshift(nn);
			n = n.substr(0,n.length-3);
		}
		
		if(n.length > 0) { 
			a.unshift(n); 
		}
		
		n = a.join(delimiter);
		
		if(d.length < 1) { 
			amount = n; 
		} else { 
			amount = n + '.' + d; 
		}
		amount = minus + amount;
		return amount;
	}
	
	this.sum = function(a, b) {
		return new Number( a ).valueOf() + new Number( b ).valueOf();
	}
	
	this.minus = function(a, b) {
		return new Number( a ).valueOf() - new Number( b ).valueOf();
	}

}

var cmsMath = new MathLib();

