// 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("addPret") != undefined )
	{
		theprice = document.getElementById("addPret").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);
			}
		}
		//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 
		return false;

}

// calculate the threshold in stoploss orders

function calcStopLossThreshold( pmpPrice, tipVar )
{
	if (document.getElementById('slproc'))
	{

		varProc =  parseFloat(document.getElementById('slproc').value);
		quantity = parseInt(document.getElementById('slquant').value);
		pretActivare = parseFloat(document.getElementById('slactiv').value);
		pretExercitare = parseFloat(document.getElementById('slexerc').value);

		tipOrdin = ( document.getElementById('take_profit').checked == true ) ?  'take_profit' : 'stop_loss';

		//alert ( pmpPrice + '  ' + varProc +  '  ' + quantity + '  '+ tipOrdin );
		if ( pretActivare > 0 )
		{
			if ( tipOrdin == 'take_profit' )
			{
			//	alert ( pmpPrice  + '  ' + ( 100 + varProc ))
				threshold = pretActivare;
				tag = 'creste peste ';
			} else {
			//	alert ( pmpPrice  + '  ' + ( 100 - varProc ))
				threshold =  pretActivare;
				tag = 'scade sub ';
			}

		} else {			
			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 );
	    saleprice = ( pretExercitare > 0 ) ? number_format(pretExercitare, 4, ',', '.') :'piata';
		document.getElementById( 'sl_details' ).innerHTML = 'Devine ordin de vanzare la '+ saleprice +' cand pret piata ' +  tag + 	number_format(threshold, 4, ',', '.');
		exercitare = (pretExercitare > 0) ? pretExercitare :  threshold;
		document.getElementById( 'estimatedValue' ).value = number_format(exercitare * quantity, 4, ',', '.'); 
	}

}

//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 ()
{
	document.getElementById('theoperation').value = document.getElementById('addTip').value;
	doPrice();
}

function RefreshSimbolOrderData()
{

}

//refresh page
function doCheck ()
{
	if ( XmlHttp == false)
	{
		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();
	} else {
			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)
{
	alert("something");
	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;
		document.getElementById('orderPass').value = password;
		document.getElementById('orders_bvb_add_form').submit();
	}
}

function ValidateBvbSLStocks( password, myOrderType )
{
	var simbol	=  document.getElementById('addSimbol');

	var pret_activare =  document.getElementById('slactiv');
	var activareValue = pret_activare.value;
	var variatie = document.getElementById('slproc');
	var variatieValue = variatie.value;
	
	var pret_exercitare =  document.getElementById('slexerc');
	var exercitareValue = pret_exercitare.value;
	var piata = document.getElementById('slmarket');
	
	var cantitate =  document.getElementById('slquant');
	var estimated = document.getElementById('estimatedValue');
	var observatii = document.getElementById('addObservatii');

	var pretText = ( variatie.value == 0 )	? ", pret de activare: " + activareValue : ", variatie: " + variatieValue + "%";
	
	if ( piata.checked ) {	exercitareValue = 'piata';	}

	confirmMessage = "Ati introdus un ordin " + myOrderType +  " pe simbolul: " + simbol.value + ", cantitate: " + cantitate.value + ", pret exercitare: " + exercitareValue + pretText + ", cu valoare estimata de: "+ estimated.value + "    \nConfirmati introducerea acestui ordin?";

	if (window.confirm(confirmMessage ))
	{
		document.getElementById('if_confirm').value = 1;
		document.getElementById('orderPass').value = password;
		document.getElementById('orders_bvb_stoploss_add_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 ValidateBvbStocksCancel(password,language)
{
	var orderID = document.getElementById('cancelorderID');
	
	if(language == "ro")
	{
		confirmMessage = "Ati introdus un ordin de anulare. \nConfirmati introducerea acestui ordin?";
	}
	else
	{
		if(language == "en")
		{
			confirmMessage = "You introduced a \" Cancel \" order. \nDo you confirm this order?";
		}
	}

	if (window.confirm(confirmMessage ))
	{
		document.getElementById('if_confirm').value = 1;
		document.getElementById('orderPass').value = password;
		document.getElementById('orders_bvb_cancel_form').submit();
	}
}

function ValidateBvbStocksCancelP2(password, password2, language)
{
	var orderID = document.getElementById('cancelorderID');
	
	if(language == "ro")
	{
		confirmMessage = "Ati introdus un ordin de anulare. \nConfirmati introducerea acestui ordin?";
	}
	else
	{
		if(language == "en")
		{
			confirmMessage = "You introduced a \" Cancel \" order. \nDo you confirm this order?";
		}
	}

	if (window.confirm(confirmMessage ))
	{
		document.getElementById('if_confirm').value = 1;
		document.getElementById('orderPass').value = password;
		document.getElementById('orderPass2').value = password2;
		document.getElementById('orders_bvb_cancel_form').submit();
	}
}

function ValidateBvbStocksModify(password,language)
{
	var pret =  document.getElementById('modifyPrice');
	var cantitate =  document.getElementById('modifyCant');
	var piata = document.getElementById('modifyPiata');
	var orderID = document.getElementById('modifyorderID');
	var confirmMessage = "aaa";
	
	if(language == "ro")
	{
		if (pret.value == 0)
		{
			confirmMessage = "Ati introdus un ordin de modificare: la piata, cantitate: " + cantitate.value + "    \nConfirmati introducerea acestui ordin?";
		} else {
			confirmMessage = "Ati introdus un ordin de modificare in pretul de " + pret.value + ", cantitate: " + cantitate.value + "    \nConfirmati introducerea acestui ordin?";
		}
	}
	else
	{
		if(language == "en")
		{
			if (pret.value == 0)
			{
				confirmMessage = "You introduced a \" Modify \" order, market, quantity: " + cantitate.value + "    \nDo you confirm this order?";
			} else {
				confirmMessage = "You introduced a \" Modify \" order, price: " + pret.value + ", quantity: " + cantitate.value + "    \nDo you confirm this order?";
			}
		}
	}

	if (window.confirm(confirmMessage ))
	{
		document.getElementById('if_confirm').value = 1;
		document.getElementById('orderPass').value = password;
		document.getElementById('orders_bvb_modify_form').submit();
	}
}

function ValidateBvbStocksModifyP2(password, password2, language)
{
	var pret =  document.getElementById('modifyPrice');
	var cantitate =  document.getElementById('modifyCant');
	var piata = document.getElementById('modifyPiata');
	var orderID = document.getElementById('modifyorderID');
	var confirmMessage = "aaa";
	
	if(language == "ro")
	{
		if (pret.value == 0)
		{
			confirmMessage = "Ati introdus un ordin de modificare: la piata, cantitate: " + cantitate.value + "    \nConfirmati introducerea acestui ordin?";
		} else {
			confirmMessage = "Ati introdus un ordin de modificare in pretul de " + pret.value + ", cantitate: " + cantitate.value + "    \nConfirmati introducerea acestui ordin?";
		}
	}
	else
	{
		if(language == "en")
		{
			if (pret.value == 0)
			{
				confirmMessage = "You introduced a \" Modify \" order, market, quantity: " + cantitate.value + "    \nDo you confirm this order?";
			} else {
				confirmMessage = "You introduced a \" Modify \" order, price: " + pret.value + ", quantity: " + cantitate.value + "    \nDo you confirm this order?";
			}
		}
	}

	if (window.confirm(confirmMessage ))
	{
		document.getElementById('if_confirm').value = 1;
		document.getElementById('orderPass').value = password;
		document.getElementById('orderPass2').value = password2;
		document.getElementById('orders_bvb_modify_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 cancelSLOrder ( id, tip, pret_activare, simbol )
{

	if (window.confirm( 'Doriti sa anulati ordinul ' + tip + ' la ' + pret_activare + ' pe ' + simbol + ' ?' ))
	{
		document.getElementById("sl_co_id").value = id;
	//	alert (document.getElementById("sl_co_id").value );
		document.getElementById("f_c_sl").submit();

	}
	
}