// similar to php number_format
// number_format(number, decimals, comma, formatSeparator)

function number_format(a, b, c, d) {
	
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if(!f[0]) f[0] = '0';
	if(!f[1]) f[1] = '';
	if(f[1].length < b){
		g = f[1];
		for(i = f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j += 3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '': c;
	
	// remove trailing zeros -- d
	for (i=4; i>2 ; i-- )
	{
		if (f[1].substring(i-1, i) == '0')
		{
			f[1] = f[1].substring(0, i-1);
		} else {
			return f[0] + c + f[1] + ' LEI';		
		}
	}
	
	return f[0] + c + f[1] + ' LEI';
}

// calculates the order price in orders_ads

function calcPrice (bidPrice, askPrice)
{
	var theprice = 0;
	var thequantity = 0;
	
	if ( document.getElementById("addPrice") != undefined )
	{
		theprice = document.getElementById("addPrice").value;
		theprice = parseFloat(theprice.replace(",", "."));
	}
	else
		return false;
		
	if ( document.getElementById("addCant") != undefined )
	{
		thequantity = document.getElementById("addCant").value;
		thequantity = parseFloat(thequantity);
	}
	else
		return false;
	
	if ( document.getElementById('addPiata') != undefined )
	{
		if (document.getElementById('addPiata').checked)
		{
			if (document.getElementById('addTip').value == 'sell')
			{
				theprice = parseFloat(bidPrice);
			}
			else if (document.getElementById('addTip').value == 'buy') 	
			{
				theprice = parseFloat(askPrice) + (parseFloat(askPrice) * 15 / 100);
			}
		}
		//thetotal = theprice * thequantity;
		thetotal = MyRound( theprice * thequantity, 4 );

		if (!isNaN(thetotal))
			document.getElementById('totalValue').value	= thetotal;
			//document.forms["orders_add_form"].total.value = thetotal;//number_format(thetotal, 4, ',', '.');
		else 
			document.getElementById('totalValue').value	= 0;
	}
	else 
	{
		thetotal = MyRound( theprice * thequantity, 4 );

		if (!isNaN(thetotal))
			document.getElementById('totalValue').value	= thetotal;
			//document.forms["orders_add_form"].total.value = thetotal;//number_format(thetotal, 4, ',', '.');
		else 
			document.getElementById('totalValue').value	= 0;
	}
}

// calculate the threshold in stoploss orders

function calcStopLossThreshold( pmpPrice, varProc )
{
	if (document.getElementById('slproc'))
	{

	varProc =  parseFloat(document.getElementById('slproc').value);
	quantity = parseInt(document.getElementById('slquant').value);
	
	tipOrdin = ( document.getElementById('take_profit').checked == true ) ?  'take_profit' : 'stop_loss';

	//alert ( pmpPrice + '  ' + varProc +  '  ' + quantity + '  '+ tipOrdin );
	
	
	
	if ( tipOrdin == 'take_profit' )
	{
	//	alert ( pmpPrice  + '  ' + ( 100 + varProc ))
		threshold = pmpPrice * ( 100 + varProc ) / 100;
		tag = 'creste peste ';
	} else {
	//	alert ( pmpPrice  + '  ' + ( 100 - varProc ))
		threshold = pmpPrice * ( 100 - varProc ) / 100;
		tag = 'scade sub ';
	}
	//alert ( threshold );
	document.getElementById( 'sl_details' ).innerHTML = 'Se transforma in ordin la piata in momentul in care pret piata ' +  tag + 	number_format(threshold, 4, ',', '.');
	document.getElementById( 'estimatedValue' ).value = number_format(threshold * quantity, 2, ',', '.'); 
	}

}

//function to proccess the order string in FastOrder

function doFastOrder()
{
	myInput = document.getElementById ('fastOrderInput');
	orderString = myInput.value;
	orderString = orderString.toUpperCase();
	
	
	stringLenght = orderString.length;
	var is_error = false;

	// get order type

	orderType = orderString.substring(0,1);
	switch(orderType)
	{
	case 'B':
	  	document.getElementById	('addTip').options[2].selected=true;
	  break;    
	case 'S':
		document.getElementById	('addTip').options[1].selected=true;
	  break;
	default:
	  is_error = true;
	}
	
	//parse string for quantity, ticker and price
	
	var orderCant = '';
	var orderSimbol = '';
	var orderPrice = '';
	
	for (var i=1; i < stringLenght; i++)
	{
		myChar = orderString.substring(i, i+1);
		//replace comma with dot
		if (myChar == ',') myChar = '.';
		
		//string to number
		charNr = myChar * 1;

		//first numbers for quantity
		if ( !isNaN(charNr)  && orderSimbol == '')
		{
			orderCant = orderCant + myChar;	
		} 
		//first chars for ticker / if SIF get sif number
		else if ( ( isNaN(charNr) || orderSimbol == 'SIF' ) && orderSimbol.length < 4 &&  myChar != '.'  )
		{
			orderSimbol = orderSimbol + myChar;
		} 
		// rest of chars for price
		else {
			orderPrice = orderPrice + myChar;
		}
	}
	
	//validate price and quantity as numbers
	orderPrice = orderPrice * 1;
	orderCant = orderCant * 1;
	if ( isNaN (orderPrice) ||  orderPrice == '' )  is_error = true;
	if ( isNaN (orderCant) || orderCant == '' )  is_error = true;
		
	//return error 
	if (is_error)
	{
		alert ('Eroare format ordin ! Formatul trebuie sa fie : b1234xyz123.45');
		
	} else	{
	document.getElementById('addPrice').value = orderPrice;
	document.getElementById('addObservatii').value = 'Ordin rapid';
	document.getElementById('addCant').value = orderCant;
	document.getElementById('addSimbol').value = orderSimbol;
	
	//update price
	doPrice();
	}
}

//toggle order type
function doChange ()
{
	tip_ordin = document.getElementById('addTip').value;
	document.getElementById('theoperation').value = tip_ordin;
	switch (tip_ordin)
		{
		case 'buy':
			//alert('BUY!');
			document.getElementById('regular_order').style.background = '#9BEAC3';
			break;
		case 'sell':
			//alert('SELL!');		
			document.getElementById('regular_order').style.background = '#F2B4BF';
			break;
		default:
			document.getElementById('regular_order').style.background = '#FFFFFF';
			break;
		}
	doPrice();
}

function RefreshSimbolOrderData()
{

}

//refresh page
function doCheck ()
{
	
	var aSimbol = document.getElementById('addSimbol').value;
	
	document.forms["simbolForm"].action = 	myBaseURL + "ordin_nou/ordin_bvb/"+aSimbol + "/";
		
	document.getElementById('thesimbol').value = aSimbol;
	document.forms["simbolForm"].submit();	
	
	
}


//round number
function MyRound( unNumar, cateZecimale )
{
	var theResult;
	var theMultiplier = 1;

	for ( var i = 0; i < cateZecimale; i++ )
	{
		theMultiplier *= 10;
	}
	theResult  = unNumar * theMultiplier;
	theResult  = parseInt( Math.round ( theResult ) );
	theResult /= theMultiplier;

	return theResult;
}

//toggle order price/martket

function change_status(control, refresh, toggle )
{
	if (toggle == true)
	{
		control.value = '';
		control.disabled = true;
	}
	else
		control.disabled = false;
	if ( refresh )
	{
		doPrice ();
	}


}

// deprecated

function ConfirmOrder(myPassword, myOrderType)
{
	
	var	form_add_hidden = document.forms["orders_add_form_hidden"];

	
	
	var simbol	=  document.getElementById('hiddenSimbol');
	tip =  document.getElementById('hiddenTip');
	tipValabil =  document.getElementById('hiddenTipValabil');
	pret =  document.getElementById('hiddenPrice');
	cantitate =  document.getElementById('hiddenCant');
	total = document.getElementById('hiddenTotal');
	password = document.getElementById('hiddenPass');
	piata = document.getElementById('hiddenPiata');
	confirmare = document.getElementById('hiddenConfirm');	
	observatii = document.getElementById('hiddenObs');
	
	confirmMessage = "Ati introdus un ordin de " + myOrderType +  " pe simbolul: " + document.getElementById('addSimbol').value + ", cantitate: " + document.getElementById('addCant').value + " si pret total: "+ document.getElementById('totalValue').value + "    \nConfirmati introducerea acestui ordin?";

	if (window.confirm(confirmMessage ))
	{

		simbol.value = document.getElementById('addSimbol').value;
		tip.value = document.getElementById('addTip').value;
		
		addTipValabil =	document.getElementsByName('tip_valabil');
		for (i = 0; i < addTipValabil.length; i++) 
		{
		  if (addTipValabil[i].checked == true) 
		  {
			 tipValabil.value = addTipValabil[i].value;
		  }
		}
		
		pret.value = document.getElementById('addPrice').value;
		cantitate.value = document.getElementById('addCant').value;
		total.value = document.getElementById('totalValue').value;
		observatii.value = document.getElementById('addObservatii').value;
		password.value = myPassword;
		
		
		if ( document.getElementById('addPiata').checked == true ) piata.value = 1;

		confirmare.value = 1;

		form_add_hidden.submit();
		


	}



}

function ValidateBvbStocks(password)
{
	
	var simbol	=  document.getElementById('addSimbol');
	var tip =  document.getElementById('addTip');
	var tipSel = tip.selectedIndex;
	var myOrderType = tip.options[tipSel].text

	var tipValabil =  document.getElementById('addTipValabil');
	var pret =  document.getElementById('addPrice');
	var cantitate =  document.getElementById('addCant');
	var total = document.getElementById('totalValue');
	var piata = document.getElementById('addPiata');
	var observatii = document.getElementById('addObservatii');

	
	confirmMessage = "Ati introdus un ordin de " + myOrderType +  " pe simbolul: " + simbol.value + ", cantitate: " + cantitate.value + " si pret total: "+ total.value + "    \nConfirmati introducerea acestui ordin?";

	if (window.confirm(confirmMessage ))
	{
		document.getElementById('if_confirm').value = 1;
		// if test account, then the orderPass control does not exist
		var p, p2, f;
		p = document.getElementById('orderPass');
		p2 = document.getElementById('orderPass2');
		f = document.getElementById('orders_bvb_add_form');

		if ( p ) {
			p.value = password;
			if ( p2 ) {
				p2.value = password;
			}
		}
		f.submit();
	}
	
}

function ConfirmOrderModify( password,simbol,tip,askprice,bidprice )
{
	var pret =  document.getElementById('addPrice');
	var cantitate =  document.getElementById('addCant');

	var theprice = pret.value;
	var theprice = parseFloat(theprice.replace(",", "."));
	var thequantity = cantitate.value;
	var thequantity = parseFloat(thequantity);
	var thetotal = 0;
	
	if ( document.getElementById('addPiata') != undefined )
	{
		if (document.getElementById('addPiata').checked)
		{
			if (document.getElementById('addTip').value == 'sell')
			{
				theprice = parseFloat(bidprice);
			}
			else if (document.getElementById('addTip').value == 'buy') 	
			{
				theprice = parseFloat(askprice);
			}
		}
	}
	
	thetotal = MyRound( theprice * thequantity, 4 );

	confirmMessage = "Ati introdus un ordin de " + tip +  " pe simbolul: " + simbol + ", cantitate: " + thequantity + " si pret total: "+ thetotal + "    \nConfirmati introducerea acestui ordin?";

	if (window.confirm(confirmMessage ))
	{
		document.getElementById('if_confirm').value = 1;
		document.getElementById('password').value = password;
		if( document.getElementById('password2') )
		{
			document.getElementById('password2').value = password;
		}		
		document.orders_modify_form.submit();
	}
	
}

function ValidateBmfmsFutures(password)
{
	var simbol	=  document.getElementById('bmfms_simbol');
	var scadenta =  document.getElementById('scadenta');
	var tip =  document.getElementById('tip_bmfms');
	var tipSel = tip.selectedIndex;

	var pret =  document.getElementById('pret_bmfms');
	var cantitate =  document.getElementById('cantitate_bmfms');
	var confirmMessage =   "Ati introdus un ordin pe contractul " + simbol.value + " " + scadenta.value + ": " + tip.options[tipSel].text + " cantitate: " +cantitate.value+ " si pret " + pret.value +"    \nConfirmati introducerea acestui ordin?";

	if (window.confirm(confirmMessage ))
	{
		document.getElementById('if_confirm').value = 1;
		document.getElementById('password').value = password;
		document.getElementById('orders_bmfms_add_form').submit();
	}
}

function showHidePretActivare()
{
	var tipOrdinSelected = document.getElementById("tip_ordin_bmfms").value;
	var pretActivareID = document.getElementById("pretActivareID");
	
	if ( ( tipOrdinSelected != null ) && ( tipOrdinSelected == "takeprofit" || tipOrdinSelected == "stoploss" ) )
	{
		pretActivareID.style.visibility = "visible";
	}
	else
	{
		pretActivareID.style.visibility = "hidden";
	}
}

function showHideValabilitateTime()
{
	var tipValabilitateSelected = document.getElementById("tip_valabilitate_bmfms").value;
	var valabilitateTimeID = document.getElementById("valabilitateTimeID");
	
	if ( ( tipValabilitateSelected != null ) && ( tipValabilitateSelected == "00:00") )
	{
		valabilitateTimeID.style.visibility = "visible";
	}
	else
	{
		valabilitateTimeID.style.visibility = "hidden";
	}
}

function doPrice ()
{
	var bidPrice = '{bidprice}';
	var askPrice = '{askprice}';
	calcPrice (bidPrice, askPrice );
}

function calcFondOrderValue()
{
	if ( document.getElementById("fond_order_value") )
	{
		var thePrice = document.getElementById("fond_order_price").value;
		var theQuant = document.getElementById("fond_order_quant").value;

		theAmmount = MyRound( thePrice * theQuant, 2 );
		document.getElementById("fond_order_value").value = theAmmount;
	}
}

function calcPriceBond( bondDA, bondVN, bondCM )
{
	var theprice = 0;
	var thequantity = 0;
	
	if ( document.getElementById("addPrice") != undefined )
	{
		theprice = document.getElementById("addPrice").value;
		theprice = parseFloat(theprice.replace(",", "."));
	}
	else
		return false;
		
	if ( document.getElementById("addCant") != undefined )
	{
		thequantity = document.getElementById("addCant").value;
		thequantity = parseFloat(thequantity);
	}
	else
		return false;
	
	if ( document.getElementById('addPiata') != undefined )
	{
		if (document.getElementById('addPiata').checked)
		{
			if (document.getElementById('addTip').value == 'sell')
			{
				theprice = parseFloat(bidPrice);
			}
			else if (document.getElementById('addTip').value == 'buy') 	
			{
				theprice = parseFloat(askPrice) + (parseFloat(askPrice) * 15 / 100);
			}
		}
		
		thetotal = MyRound( ( theprice + bondDA ) / 100 * bondVN * thequantity, 4 );
		//thetotal = MyRound( thetotal + ( thetotal * bondCM / 100 ), 2 );

		if (!isNaN(thetotal))
			document.getElementById('totalValue').value	= thetotal;
			//document.forms["orders_add_form"].total.value = thetotal;//number_format(thetotal, 4, ',', '.');
		else 
			document.getElementById('totalValue').value	= 0;
	}
	else 
	{
		thetotal = MyRound( ( theprice + bondDA ) / 100 * bondVN * thequantity, 4 );
		//thetotal = MyRound( thetotal + ( thetotal * bondCM / 100 ), 2 );

		if (!isNaN(thetotal))
			document.getElementById('totalValue').value	= thetotal;
			//document.forms["orders_add_form"].total.value = thetotal;//number_format(thetotal, 4, ',', '.');
		else 
			document.getElementById('totalValue').value	= 0;
	}
}