function FormatNumberBy3(num, decpoint, sep) {
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ",";
  }
  if (arguments.length == 1) {
    sep = ",";
    decpoint = ".";
  }
  // need a string for operations
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x;
}
function calc()
{
	var p;
	var t;
	var total;
	var bwage;
	var protocol;
	var swage;
	var tax;
	var bend;
	var send;
	var penalty;
	
	p=$("#price").val();
	t=$("#tonage").val();
	
	total = p*t*1000;
	if(isNaN(total))
	total = 0;
	
	bwage = total*2.8;
	bwage = bwage/1000;
	bwage = bwage*1.03;
	if(isNaN(bwage))
	bwage = 0;
	
	protocol = total + bwage;
	if(isNaN(protocol))
	protocol = 0;
	
	swage = total*3;
	swage = swage/1000;
	swage = swage*1.03;
	if(isNaN(swage))
	swage = 0;
	
	tax = total*3;
	tax = tax/100;
	if(isNaN(tax))
	tax = 0;
	
	bend = protocol+tax;
	bend = bend/t;
	bend = bend/1000;
	if(isNaN(bend))
	bend = 0;
	
	send = total-bwage;
	send = send/t;
	send = send/1000;
	if(isNaN(send))
	send = 0;
	
	penalty = total*2.5;
	penalty = penalty/1000;
	if(isNaN(penalty))
	penalty = 0;
	
	$("#total").text(farsi(FormatNumberBy3(Math.ceil(total))));
	$("#buywage").text(farsi(FormatNumberBy3(Math.ceil(bwage))));
	$("#protocolprice").text(farsi(FormatNumberBy3(Math.ceil(protocol))));
	$("#sellwage").text(farsi(FormatNumberBy3(Math.ceil(swage))));
	$("#3tax").text(farsi(FormatNumberBy3(Math.ceil(tax))));
	$("#buyerprice").text(farsi(FormatNumberBy3(Math.ceil(bend))));
	$("#sellerprice").text(farsi(FormatNumberBy3(Math.ceil(send))));
	$("#penalty").text(farsi(FormatNumberBy3(Math.ceil(penalty))));	
}
function farsi(s){
	
	var result='';
	
	for (var i=0; i<s.length; i++)
	{
		switch (s.charCodeAt(i)) {
			case 0x30:
			case 0x31:
			case 0x32:
			case 0x33:
			case 0x34:
			case 0x35:
			case 0x36:
			case 0x37:
			case 0x38:
			case 0x39:
				result+=String.fromCharCode(0x6F0+s.charCodeAt(i)-0x30);
				break;
			default:
				result+=s.charAt(i);
				break;
		}
	}
	return result;
}
$(function(){
	$("#price,#tonage").keyup(calc).keyup();
	$("#price").focus();
});

