// 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] ;		
		}
	}
	
	return f[0] + c + f[1] ;
}



function disableAuto()
{ 
	var formCollection = document.getElementsByTagName( 'form' ); 
	
	for ( var i = 0; i < formCollection.length; i++ ) 
		{ 
			//formCollection[i].autocomplete = 'off';
			formCollection[i].setAttribute("autocomplete","off"); 
		} 
}

function openWindowScroll(dest,name,width,height,fullscreen)
{
		var x,y;
		if(fullscreen==1) {
				width=screen.availWidth; height=screen.availHeight;
				x = 0;y = 0;}
		else {   
				x = (screen.availWidth-width)/2; y = (screen.availHeight-height)/2;}
		wnd = window.open (dest,name,"resizable=1,left="+x+",top="+y+",width="+width+", height="+height+", scrollbars=1");
		wnd.focus();
}


function emptySearchIfNeeded( searchObj, defaultText ) {
	if ( searchObj && searchObj.value && searchObj.value == defaultText ) {
		searchObj.value = "";
	}
}

function switchQFunds ( display )
{
	switch(display)
	{
		case "values":
			document.getElementById("qfond_vars").style.display = 'none';
			document.getElementById("qfond_values").style.display = 'block';
			break;
		case "vars":
			document.getElementById("qfond_vars").style.display = 'block';
			document.getElementById("qfond_values").style.display = 'none';
			break;


	}

}


function SelectBuyFond( fondid )
{
    if ( document.getElementById("buy_fond_"+fondid) )
    {
        for( i=1; i<10; i++ )
        {
            var elID = "#selectbuy_"+i;
            
            if (fondid == i)
            {
                document.getElementById("buy_fond_"+i).style.display = 'block';
				document.getElementById("master").style.display = 'block';
                //document.getElementById("selectbuy_"+i).className ="read-more-y fselected";
                $(elID).addClass("active").css({'color':'#FFF','border-bottom':'1px solid #ff7c00'});
                
            } else {
                if (document.getElementById("buy_fond_"+i))
                {
                    document.getElementById("buy_fond_"+i).style.display = 'none';	

                }
                if (document.getElementById("selectbuy_"+i))
                {
                    //document.getElementById("selectbuy_"+i).className ="read-more-y";
                    $(elID).removeClass("active").css({'color':'#003D76','border-bottom':'none'});
                    
                }
            }
        }
    }else
    {
        var newLocation = jsBase + ( (ifInvest) ? 'investitie/' : 'rascumpara/' ) + fondid + '/';
        document.location = newLocation;
    }
}

/*
function calcFondUnits(myform)
{
	var fond_value = myform.quote_value.value;
	var invest_ammount = myform.fond_order_value.value;

	nr_units = invest_ammount/fond_value;
   //alert ( fond_value + ' ' + myform.quote_value.value);
	nr_units = isNaN( nr_units ) ?  0 : nr_units ;  
	myform.fond_order_quant.value = number_format(nr_units,6,",",".");
}


function calcFondValues( myform )
{
	var fond_value = myform.quote_value.value;
	var nr_units = myform.fond_order_units.value;

	ammount = fond_value * nr_units;
	
	myform.fond_order_quant.value = number_format(ammount,2,",",".");
}
*/

function switchRedeem ( fondid, valueType )
{
	
    unitsobject = "redeem_units"+fondid;
	units = document.getElementById(unitsobject);
	ammountobject = "redeem_ammount"+fondid;
	ammount = document.getElementById(ammountobject);
    
    var theValueTipe = valueType;
	
    switch (valueType)
	{
		case 0:
			units.style.display= ( BrowserDetect.browser == 'Explorer' ) ? 'inline' : 'table-row';
			ammount.style.display='none';
		break;
		default:
			units.style.display= 'none';
            ammount.style.display= ( BrowserDetect.browser == 'Explorer' ) ? 'inline' : 'table-row';;
	}
    displayBankAccounts( fondid );
}

function displayBankAccounts( fundID )
{
    // get selected currency
    var currencySelectEl = document.getElementById( 'fond_ammount_type_' + fundID );
    var selectedCurrency = currencySelectEl.options[currencySelectEl.selectedIndex].title;
    
    /*
    
    // repopulate bank accounts select element
    
    var bankSelectEl = document.getElementById( 'bank_account_' + fundID );
    bankSelectEl.options.length = 0;
    
    bankSelectEl.options[0]=new Option( 'Alege un cont', '', true, true );
    bankSelectEl.options[0].title = '-|-';
    
    eval( 'var arr = bankAccountsArray' + fundID );
    var index = 1;
    for ( var i = 0; i < arr.length; i++ ) {
        if( (selectedCurrency=='units') || (arr[i]["valuta"] == selectedCurrency) )
        {
            bankSelectEl.options[index]=new Option( arr[i]["option_text"], arr[i]["iban"], false, false );
            bankSelectEl.options[index].title = arr[i]["banca"] + '|' + arr[i]["beneficiar"];
            index ++;
        }
    }
    
    */
    
    updateBankAccountInfo( fundID );
    updateTextInfo( fundID, selectedCurrency );
    clearErrorMessage( 'error' );
}

function updateBankAccountInfo( fundID )
{
    var bankSelectEl = document.getElementById( 'bank_account_' + fundID );
    var stringData = bankSelectEl.options[bankSelectEl.selectedIndex].title;
    var dataArray = stringData.split( '|' );
    var htmlData = 'Banca: ' + ( ( dataArray[0] != '' ) ? dataArray[0] : '-' ) + '<br />' + 'Titular: ' + ( ( dataArray[1] != '' ) ? dataArray[1] : '-' );
    
    var bankAccountInfoEl = document.getElementById( 'bankAccountInfo' + fundID );
    bankAccountInfoEl.innerHTML = htmlData;
    
    if( noticeEnabled == 1 )
    {
        var textNoticeEl = document.getElementById( 'textNotice' + fundID );
        if( ( fundID == 1 ) && ( dataArray[1] == ' SSIF Intercapital Invest' ) )
        {
            textNoticeEl.style.display = 'block';
        }else{
            textNoticeEl.style.display = 'none';
        }
    }        
    
    clearErrorMessage( 'error' );
}

function updateTextInfo( fundID, someCurrency )
{
    // update amount label
    document.getElementById('fond_order_value_label_' + fundID).innerHTML = 'Suma in ' + someCurrency;
    
    //update texts
    var currenciesArr = new Array('RON', 'EUR', 'USD');
    for ( var i = 0; i < currenciesArr.length; i++ ) {
        
        var textInfoEl = 'textInfo'+currenciesArr[i]+fundID;
        
        if( document.getElementById( textInfoEl ) )
        {
            document.getElementById( textInfoEl ).style.display = ( someCurrency == currenciesArr[i] ) ? 'block' : 'none';
        }
    }
}

function fillFullRedeem( fondID )
{
    var ammountTypeEl = document.getElementById( 'fond_ammount_type_' + fondID );
    ammountTypeEl.selectedIndex = 0;
    ammountTypeEl.disabled = true;
    switchRedeem( fondID, 0);
    var redeemUnitsEl = document.getElementById( 'fond_order_units_' + fondID );
    redeemUnitsEl.disabled = true;
    var unitsEl = document.getElementById( 'units' + fondID );
    redeemUnitsEl.value = unitsEl.value;
}

function clearFullRedeem( fondID )
{
    // uncheck full redeem option by checking the alternate option
    document.getElementById( 'fullRedeemNo' + fondID ).checked = true;
    var ammountTypeEl = document.getElementById( 'fond_ammount_type_' + fondID );
    ammountTypeEl.disabled = false;
    var redeemUnitsEl = document.getElementById( 'fond_order_units_' + fondID );
    redeemUnitsEl.disabled = false;
}

function clearErrorMessage( errorHolderID )
{
    // clears previous error message (if any) when switching funds
    if( document.getElementById( errorHolderID ) )
    {
        document.getElementById( errorHolderID ).innerHTML = '';
    }
}

function fondRedeemSubmit( fondID, fondName )
{
    
    //see if units or ammount
    var ammountTypeEl = document.getElementById( 'fond_ammount_type_' + fondID );
    var ifUnits = ( ammountTypeEl.options[ammountTypeEl.selectedIndex].value == 'units' ) ? true : false;

    // confirm operation   
    if( ifUnits )
    {
        var redeemUnitsEl = document.getElementById( 'fond_order_units_' + fondID );
        var howmuch = redeemUnitsEl.value;
        
        var confirmMessage = 'Prin aceasta comanda intentionezi sa rascumperi un numar de '+ howmuch + ' unitati din fondul ' + fondName + ' administrat de Intercapital Investment Management.\n\nDoresti sa confirmi aceasta operatiune?'
    }else{
        var redeemQuantEl = document.getElementById( 'fond_order_quant_' + fondID );
        var howmuch = redeemQuantEl.value;
        var confirmMessage = 'Prin aceasta comanda intentionezi sa rascumperi suma de '+ howmuch + ' RON din fondul ' + fondName + ' administrat de Intercapital Investment Management.\n\nDoresti sa confirmi aceasta operatiune?'
    }
    
    if( howmuch != '' )
    {
        if ( confirm( confirmMessage ) ) 
        {
            // enable disabled controls (if any) to make sure all data goes to POST
            var ammountTypeEl = document.getElementById( 'fond_ammount_type_' + fondID );
            ammountTypeEl.disabled = false;
            var redeemUnitsEl = document.getElementById( 'fond_order_units_' + fondID );
            redeemUnitsEl.disabled = false;
            
            // submit our form
            var formEl = document.getElementById( 'addFondSell' + fondID );
            formEl.submit();
        }
    }else
    {
        if( ifUnits )
        {
            alert( 'Nu ati introdus numarul de unitati pe care doriti sa le rascumparati!' )
            redeemUnitsEl.focus();
        }else
        {
            alert( 'Nu ati introdus suma pe care doriti sa o rascumparati!' )
            redeemQuantEl.focus();
        }
    }

    return false;
}

function fondInvestSubmit( fondID, fondName )
{
    
    var investQuantEl = document.getElementById( 'fond_order_value_' + fondID );
    var howmuch = investQuantEl.value;
    if( howmuch != '' )
    {    
        var confirmMessage = 'Prin aceasta comanda intentionezi sa investesti suma de '+ howmuch + ' RON in fondul ' + fondName + ' administrat de Intercapital Investment Management.\nComisionul de adeziune pentru ' + fondName + ' este zero.\n\nDoresti sa confirmi aceasta operatiune?';
            
        if ( confirm( confirmMessage ) ) 
        {
            // submit our form
            var formEl = document.getElementById( 'addFondOrder' + fondID );
            formEl.submit();
        }
    }else
    {
        alert( 'Nu ati introdus suma pe care doriti sa o investiti!' )
        investQuantEl.focus();
    }

    return false;
}
