function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}	

function PPMT(intr, Per, NPer, PV, FV , Due )
{
	FV = 0;
	
	float1 = Per - (Due?2:1);
	float2 = - FV*intr/((Math.pow(1+ intr,NPer)- 1)*(Due?1+ intr:1))+ - PV/((Due?1:0)+ 1/intr*(1- 1/Math.pow(1+ intr,NPer- (Due?1:0))));
	return ((- FV*intr/((Math.pow(1+ intr,NPer)- 1)*(Due?1+ intr:1))+ - PV/((Due?1:0)+ 1/intr*(1- 1/Math.pow(1+ intr,NPer- (Due?1:0))))- - (PV*Math.pow(1+ intr,float1)- (- 0*Math.pow(1+ intr,float1)+ - (1/intr)*float2*(Math.pow(1+ intr,float1)- 1)*(Due?1+ intr:1)- (Due?float2:0)))*intr)*-1);
}

function _calculate_pvif( rate, nper )
{
	return ( Math.pow( 1+ rate, nper ));
}


function _calculate_fvifa( rate, nper )
{
	if ( rate == 0 )
		return nper;
	else
		return ( Math.pow( 1 + rate, nper ) - 1 ) / rate;
}

function _calculate_pmt ( rate, nper, pv, fv, type)
{
	pvif = _calculate_pvif ( rate, nper);
	fvifa = _calculate_fvifa (rate, nper);
	
	return ((-pv * pvif - fv ) / ((1.0 + rate * type) * fvifa));
}

function _calculate_interest_part ( pv, pmt, rate, per )
{
	return -( pv * Math.pow(1 + rate, per ) * rate +
		pmt * (Math.pow(1 + rate, per) - 1));
}

function PMT( rate, nper, pv, fv, type )
{
	if ( typeof( fv ) == 'undefined' )
		fv = 0.0;

	if ( typeof( type ) == 'undefined' )
		type = 0;	
		
	return  _calculate_pmt ( rate, nper, pv, fv, type);		
} 
 
function IPMT( rate, per, nper, pv, fv, type )
{
	if ( typeof( fv ) == 'undefined' )
		fv = 0.0;

	if ( typeof( type ) == 'undefined' )
		type = 0;
	
	if ((per < 1) || (per >= (nper + 1)))
		return null;
	else {
		pmt = _calculate_pmt ( rate, nper, pv, fv, type);
		ipmt = _calculate_interest_part ( pv, pmt, rate, per - 1);
		return (isFinite(ipmt) ? ipmt: null);
	}
}


function getCreditId()
{
	var id = $('#hot-links a.selected').attr('id');	
	
	switch ( id )
	{
		case "money-credit":
			return 1;

		case "product-credit":
			return 3;

		case "auto-credit":
			return 2;
	}
}


function countApprox(){
	var krMerkis = getCreditId();
	var Ligums = $('#form #ligums').val();
	
	if ( $('#form #summ').val().length < 1 )
	{
		$('#ball .summ').html( "00.00" ); 
		return;		
	}
	
	var zz =  $('#form #summ').val().replace(',', '.');		
	val = parseInt( zz );	
	
	S = parseFloat(zz);

	if ( S < 50 )
	{
		$('#ball .summ').html('00.00');
		return;
	}
	
	T = parseInt($('#form #term').val());
	AA = 1;
	AK = komis( T, S , Ligums, krMerkis );
	PR = pr( T, S , Ligums, krMerkis );	
	MAI = S * AK / 100;
	KK = MAI + S;

	pmt = -PMT( PR / 100, T, KK );
	var outp = roundNumber( pmt, 2 ) + AA;

	if ( isNaN(outp) )
	{
		$('#ball .summ').html( 'Nav' );
	}
	else
	{
		$('#ball .summ').html( outp.toFixed(2) ); 		
		$('#ball').animate({top:"23px"}, 200).animate({top:"35px"}, 200) // first jump
				.animate({top:"28px"}, 100).animate({top:"35px"}, 100) // second jump
				.animate({top:"35px"}, 100).animate({top:"35px"}, 100); // the last jump
	}
}



function displayGraph(){
	var krMerkis = getCreditId();
	var Ligums = $('#form #ligums').val();
	T = parseInt($('#form #term').val());

	var zz =  $('#form #summ').val().replace(',', '.');		
	val = parseInt( zz );	
	S = parseFloat(zz);
	
	params = {
			'transitionIn'	:	'elastic',
			'transitionOut'	:	'elastic',
			'speedIn'		:	600,
			'speedOut'		:	200,
			'overlayShow'	:	true,
			'autoDimensions'	: false,
			'width'			: 718,
			'scrolling'		: 'auto',
			'hideOnOverlayClick': true
		}
	
	$.ajax({
		type		: "GET",
		cache	: false,
		url		: '/math.php?summa='+S+'&terminsh='+T+'&merkis='+krMerkis+'&ligums='+Ligums+'&lng='+cl_language,
		data		: $(this).serializeArray(),
		success: function(data) {
			$.fancybox( data, params );
		}
	});	
		
	return false;
}



$(document).ready( function(){
	var currentItem = 1;
	var totalItems = $('#banners #controls a').length;
	
	rotateSwitch = function(){		
		play = setInterval(function(){ //Set timer									
			currentItem++;
			
			if ( currentItem > totalItems )
				currentItem = 1;
							
			id = currentItem;			
			$('#banners .banners-wrapper .selected').removeClass('selected');		
			$('#banners .banners-wrapper .b'+id).addClass('selected');
			
			$('#banners #controls .selected').removeClass('selected');
			$('#banners #controls a#b'+currentItem).addClass('selected');
		}, 10000);
	};
	
	rotateSwitch();	

	$('#banners #controls a').click( function(){
		id = $(this).attr('id');
		
		$('#banners .banners-wrapper .selected').removeClass('selected');		
		$('#banners .banners-wrapper .'+id).addClass('selected');
		
		$('#banners #controls .selected').removeClass('selected');
		$(this).addClass('selected');
		
		clearTimeout(play);
	});



	$("#form #summ").val('250');

	function strpos (haystack, needle, offset) {
		var i = (haystack+'').indexOf(needle, (offset || 0));
		return i === -1 ? false : i;
	}

	
	$("#form #summ").keypress(function (e)
	{  
		if ( e.which == 46 || e.which == 44 )
		{
			if ( strpos( $(this).val(), "." ) || strpos( $(this).val(), "," ) )
				return false;
		}
		
		if( e.which != 44 && e.which != 46 && e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
			return false;		
	});
	
	$("#form #summ").keyup(function (e){
		var zz =  $(this).val().replace(',', '.');		
		//var ar = $(this).val().split('.', 2);
		
		var decIndex = ( strpos( $(this).val(), ',' ) == false ) ? strpos( $(this).val(), '.' ) : strpos( $(this).val(), ',' );
		
		if ( decIndex != false )
			$(this).val(  $(this).val().substring( 0, decIndex + 3 ) ); //
		
		val = parseInt( zz );
		var krMerkis = getCreditId();
		
		if ( $('#hot-links #auto-credit').hasClass('selected') )
			max_val = 5000;
		else
			max_val = 3000;
		
		if ( val > max_val  )
			$(this).val( max_val );		
		
		var sel = $('#form #term').next('div').find('> ul > li > a.selected');
		var ind = sel.attr('index');
		
		if ( ind > 5 )
		{
			sel.removeClass('selected');						
			new_sel = $('#form #term').next('div').find('> ul > li > a[index=5]').addClass('selected').html();															
			$('#form #term').next('div').find('> div > span.jNiceSelectText').html( new_sel );
		}			
	});


	$("#form #summ").keyup( function(){
		countApprox();		
	});	
	
	
	$('#ball .link').click( function(){ 
		if ( parseFloat( $('#ball .summ').html() ) > 0 )
			displayGraph();
	
		return false;	
	});
	
	
	// Tooltip actions
	$('#tooltip').css('top', ( 160-$('#tooltip').height() ) );

	$('div#show-tooltip').not('.static').mouseenter( function( e ){
		$('#tooltip').removeClass('hidden');
	}).mouseleave( function(e){
		if ( !$(e.relatedTarget).hasClass('bot-b') )			
			$('#tooltip').addClass('hidden');
	});
	
	$('#tooltip').not('.static').mouseleave( function(e){
		$(this).addClass('hidden');
	} );
	
	
	
	$('div.popup').click( function(){
		$(this).addClass('hidden');
	}); 	
	
	$('#hot-links a').click( function(){
		var repl = $('#hot-links a.selected').find('> img').attr('src').replace('active-', '');
		$('#hot-links a.selected').find('> img').attr('src', repl );
		
		$('#form #summ').val('250');
		
		max_val = 3000;
		
		switch ( $(this).attr('id') )
		{
			case 'money-credit':
					$('#calculator #calculator-image').css('background', 'url(../images/calculator/nauda-big.jpg)');

					var sel = $('#form #term').next('div').find('> ul > li > a.selected');
					var ind = sel.attr('index');
					
					if ( ind > 5 )
					{
						sel.removeClass('selected');						
						new_sel = $('#form #term').next('div').find('> ul > li > a[index=5]').addClass('selected').html();												
						
						$('#form #term').next('div').find('> div > span.jNiceSelectText').html( new_sel );
					}
					
					$('#calculator .crtype').val('Nauda');
					
					$(this).find('> img').attr('src', '../images/calculator/active-nauda-'+ cl_language + '.png');
				break;

			case 'auto-credit':
					$('#calculator #calculator-image').css('background', 'url(../images/calculator/auto-big.jpg)');
			
					$('#calculator .crtype').val('Auto');
					
					$(this).find('> img').attr('src', '../images/calculator/active-auto-'+ cl_language + '.png');
					max_val = 5000;
				break;

			case 'product-credit':
					$('#calculator .crtype').val('Prece');
			
					var sel = $('#form #term').next('div').find('> ul > li > a.selected');
					var ind = sel.attr('index');
					
					if ( ind > 5 )
					{
						sel.removeClass('selected');						
						new_sel = $('#form #term').next('div').find('> ul > li > a[index=5]').addClass('selected').html();																		
						$('#form #term').next('div').find('> div > span.jNiceSelectText').html( new_sel );
					}
						
					$('#calculator #calculator-image').css('background', 'url(../images/calculator/preces-big.jpg)');
			
					$(this).find('> img').attr('src', '../images/calculator/active-preces-'+ cl_language + '.png');
				break;
		}		
		
		
		$('#form .note.max').html( from_text + max_val + " Ls" );	
		$('#hot-links a').removeClass('selected');
		$(this).addClass('selected');
				
		countApprox();
	});
});
