var flagfirst = true;

/*
	Get Listh of currs, which available to change from chosen one
*/

var ua = navigator.userAgent.toLowerCase();
var isIE = (navigator.appName == "Microsoft Internet Explorer") && (ua.indexOf("opera") == -1);

function SetOldValue (val) {
	document.getElementById("curr_to").value = val;
}

function GetExchangeList(recount) {
	
	var curr_from = document.getElementById("curr_from");
	var curr_to = document.getElementById("curr_to");
	var id = curr_from.value;
	
	var old_val = document.getElementById("curr_to").value;
	
		JsHttpRequest.query(
            './ajax_getlist.php', // backend
            {
                'id': id
            },
            // Function is called when an answer arrives. 
            function(result, errors) {
					var old_index = curr_to.selectedIndex;
					curr_to.options.length = 0;
					len = result.length;
					for (i = 0; i < len; i++) {
						if (old_val == result[i]['id'])
							curr_to.add(new Option(result[i]['name'], result[i]['id'], true, false), isIE ? curr_to.options.length : null);
						else
							curr_to.add(new Option(result[i]['name'], result[i]['id'], false, false), isIE ? curr_to.options.length : null);
					}
					
					if (curr_to.selectedIndex < 0) {
						curr_to.selectedIndex = 0;							
					}							
					
					GetExchangeWay (recount);
					//out_in_change ('curr_form');		
            },	
            false  // do not disable caching
        );
}

//	Add an option to SELECT box
function addOption (oListbox, text, value, isDefaultSelected, isSelected) {
	var oOption = document.createElement("option");
	oOption.appendChild(document.createTextNode(text));
	oOption.setAttribute("value", value);
	
	if (isDefaultSelected) oOption.defaultSelected = true;
	else if (isSelected) oOption.selected = true;
	
	oListbox.appendChild(oOption);
}

//	Get information 'bout choosen change 
function GetExchangeWay (recount) {

	var from = document.getElementById("curr_from").value;
	var to = document.getElementById("curr_to").value;

	JsHttpRequest.query(
            './ajax_backend.php', // backend
            {
                'from': from,  
                'to': to
            },
            // Function is called when an answer arrives. 
            function(result, errors) {
					
					exchange_way['way'] 		= result["way"];
					exchange_way['from'] 		= result["from"];
					exchange_way['to'] 			= result["to"];
					exchange_way['course'] 		= result["course"];
					exchange_way['course_back']	= result["course_back"];
					exchange_way['fromname'] 	= result["fromname"];
					exchange_way['toname'] 		= result["toname"];
					exchange_way['frompic'] 	= result["frompic"];
					exchange_way['topic'] 		= result["topic"];	
					exchange_way['type'] 		= result["type"];		
					exchange_way['komiss'] 		= result["komiss"];	
					
					exchange_way['formula_type'] 		= result["formula_type"];	
					exchange_way['formula_value'] 		= result["formula_value"];	
					exchange_way['formula_perc'] 		= result["formula_perc"];	
					exchange_way['formula_fix'] 		= result["formula_fix"];	
					exchange_way['include_ps_comission'] 	= result["include_ps_comission"];	
					
					exchange_way['sys_comission_perc_to'] 	= result["sys_comission_perc_to"];	
					exchange_way['sys_comission_fix_to'] 	= result["sys_comission_fix_to"];	
					exchange_way['sys_comission_min_to'] 	= result["sys_comission_min_to"];	
					
					exchange_way['sys_comission_perc_from']	= result["sys_comission_perc_from"];	
					//alert( result["sys_comission_perc_from"]);
					exchange_way['sys_comission_fix_from'] 	= result["sys_comission_fix_from"];	
					exchange_way['sys_comission_min_from'] 	= result["sys_comission_min_from"];	
					
					exchange_way['rate'] 	= result["rate"];	
					
					total_amount = parseFloat(result["amount"]);				
					min_amount = parseFloat(result["min_amount"]);
					max_amount = parseFloat(result["max_amount"]);
					komiss = parseFloat(result["komiss"]);
					course = parseFloat(result["course"]);
					course_back = parseFloat(result["course_back"]);
					
					formula_value = parseFloat(result["formula_value"]);
					formula_perc = parseFloat(result["formula_perc"]);
					formula_fix = parseFloat(result["formula_fix"]);
					
					sys_comission_perc_to = parseFloat(result["sys_comission_perc_to"]);
					sys_comission_fix_to = parseFloat(result["sys_comission_fix_to"]);
					sys_comission_min_to = parseFloat(result["sys_comission_min_to"]);
					
					sys_comission_perc_from = parseFloat(result["sys_comission_perc_from"]);
					sys_comission_fix_from = parseFloat(result["sys_comission_fix_from"]);
					sys_comission_min_from = parseFloat(result["sys_comission_min_from"]);
					
					rate = parseFloat(result["rate"]);
					//alert(result["rate"]);
					
					adv_comission_info = result["adv_comission_info"];
					
					var elem = document.getElementById("div_kurs");	
					
					var str = '';
					//if (exchange_way['course'] / exchange_way['course_back'] >= 0.5) {
						cc = 1 + formula_perc;
						fix = formula_fix;
						// системная
						if (exchange_way['include_ps_comission'] == 1) {
							cc = cc - sys_comission_perc_to;
							fix = fix - sys_comission_fix_to;
						}
						cc = cc * rate;
						course2 = (Math.round(cc * 100) / 100);
						if (fix) course2 = course2 + ' (' + (Math.round(fix * 100) / 100) + ' фикс.)';
						str = '<b>1</b> ' + exchange_way['fromname'] + ' = <b>' + course2 + '</b> ' + exchange_way['toname'];

					elem.innerHTML = 'Курс: ' + str;	
					
					var elem2 = document.getElementById("div_amount");
					str = total_amount;
					elem2.innerHTML = 'Остаток средств: <b>' + str + '</b> ' + exchange_way['toname'];
					if (adv_comission_info != '')
						elem2.innerHTML += '<br>' + adv_comission_info;
						
					if (flagfirst) {
						if (exchange_way['course_back'] != null){
							
							if (exchange_way['course'] / exchange_way['course_back'] >= 0.5) {
							    
								document.getElementById('amount_from').value = 1;
								document.getElementById('amount_from_ps').value = with_comiss_ps(1);
								document.getElementById('amount_to').value = exchange_way['course'];
							}
							else {		

								document.getElementById('amount_from').value = exchange_way['course_back'];
								document.getElementById('amount_from_ps').value = with_comiss_ps(exchange_way['course_back']);
								
								document.getElementById('amount_to').value = 1;
							}
						}
						flagfirst = false;
					}
					from_change('curr_form');		
					//in_out_change ('curr_form');
            },	
            false  // do not disable caching
        );

	}

/*
	From In to Out OnChange handler
*/
function in_out_change(fid, id, code, bForce) {
   
	if (document.forms[fid].amount_from == null) return;
  
	if (document.forms[fid].curr_from.value == document.forms[fid].curr_to.value)
		return;
  
	in_val = document.forms[fid].amount_from.value.replace(",", ".");
	if (isNaN(in_val)) { in_val = "0"; }
	
	amount = Math.round(in_val * 100) / 100;
	
	// added 23.05.07 - change amount_from according to precision
	if ((in_val != '') && (parseFloat(in_val) != amount))
		document.forms[fid].amount_from.value = amount;

	if (isNaN(document.forms[fid].amount_from.value)) {
		amount = min_amount[fid];
		document.forms[fid].amount_from.value = amount;
		out_in_change(fid, id, code, bForce);
		return;
	}	
	
	if (amount < min_amount) {
		amount = min_amount;
		document.forms[fid].amount_from.value = min_amount;
		document.forms[fid].amount_from_ps.value = with_comiss_ps( min_amount );
		
		in_out_change(fid, id, code, bForce);
		//alert('Минимальная сумма обмена ' + min_amount);
		return;
	}
	if (amount > max_amount) {
		
		amount = max_amount;
		document.forms[fid].amount_from.value = amount;
		document.forms[fid].amount_from_ps.value = with_comiss_ps(amount);
		
		in_out_change(fid, id, code, bForce);
		//alert('Максимальная сумма обмена ' + max_amount);
		return;
	}
	
	if (document.forms[fid].amount_from.value < 0) {
		amount = -amount;
		document.forms[fid].amount_from.value = amount;
		document.forms[fid].amount_from.value = with_comiss_ps(amount);
		out_in_change(fid, id, code, bForce);
		return;
	}
	
	//alert(document.forms[fid].amount_from.value);
	//alert(with_comiss_ps(document.forms[fid].amount_from.value));
	//amount_to = Math.round((amount * cc + fix) * 100) / 100;
	//alert(cc);
	//document.forms[fid].amount_in_ps.value = with_comiss_ps(document.forms[fid].amount_from.value); //amount_to;
	document.forms[fid].amount_to.value = Math.round( (amount * cc + fix) * 100) / 100;//amount_to;
	
	
	
	if (bForce) { out_in_change(fid, code); }
}

//просто и сердито (заплатка)
function from_change(fid){

  amount = document.forms[fid].amount_from.value;
  document.forms[fid].amount_from_ps.value = with_comiss_ps(document.forms[fid].amount_from.value);
  document.forms[fid].amount_to.value = Math.round( (amount * cc + fix) * 100) / 100;
  //alert(amount+"---"+with_comiss_ps(document.forms[fid].amount_from.value)+"---"+Math.round( (amount * cc + fix) * 100) / 100);

}

/*
	From Out to In OnChange handler
*/
function out_in_change(fid, id, code, bForce) {

	//alert ('out_in_change');
	if (document.forms[fid].curr_from.value == document.forms[fid].curr_to.value) {
		//alert('return 1');
		return;
	}
	if (document.forms[fid].amount_to == null) {
		//alert('return 2');
		return;
	}
	if (id == null) {
		//alert('return 3');
		return;
	}
	
	out_val = document.forms[fid].amount_to.value.replace(",", ".");
	if (isNaN(out_val)) { out_val = "0"; }

	amount = Math.round(out_val * 100) / 100;
	
	// added 23.05.07 - change amount_out according to precision
	if ((out_val != '') && (parseFloat(out_val) != amount))
		document.forms[fid].amount_to.value = amount;
  
	if (isNaN(document.forms[fid].amount_to.value)) {
		amount = 0;
		document.forms[fid].amount_to.value = amount;
		in_out_change(fid, id, code, bForce);
		//alert('return 4');
		return;
	}
	
	if (document.forms[fid].amount_to.value < 0) {
		amount = -amount;
		document.forms[fid].amount_to.value = amount;
		in_out_change(fid, id, code, bForce);
		//alert('return 5');
		return;
	}
	
	if (course == 0) {
		//alert('return 6');
		return;
	}
    
	amount_from = Math.round((out_val / course) * 100) / 100;
	
	if (amount_from > max_amount) {
		//in_out(fid, id, code, bForce);
		
		amount_from = max_amount;
		amount_to = Math.round( (max_amount * cc  + fix) * 100) / 100;
		alert('Максимальная сумма обмена ' + max_amount);
		return;
	}

	if (amount_from < min_amount) {
		//in_out(fid, id, code, bForce);
		
		amount_from = min_amount;
		amount_to = Math.round( (min_amount * cc + fix) * 100) / 100;
		alert('Миимальная сумма обмена ' + min_amount);
		return;
	}
	
	document.forms[fid].amount_from.value = amount_from;
	document.forms[fid].amount_to.value = amount_to;
	

	
	
	amount = parseFloat(amount_from);
	comiss = (sys_comission_perc_from * amount) + sys_comission_fix_from;
	
	if ( comiss < sys_comission_min_from )
		comiss = sys_comission_min_from;
	comiss = Math.round(comiss * 100) / 100;
	
	document.forms[fid].amount_from_ps.value = Math.round((amount + comiss) * 100) / 100;
	
	
	
	
	
	
	
	//document.forms[fid].amount_from_ps.value = with_comiss_ps(amount_from);
	
	if (bForce) { in_out_change(fid, code); }

}



/*
	From In to Out OnKeyUp handler
*/
function in_out_keyup(fid, id, code, bForce) {

	if (document.forms[fid].amount_from == null) return;
  
	in_val = document.forms[fid].amount_from.value.replace(",", ".");
	if (isNaN(in_val)) { in_val = "0"; }
	
	amount = Math.round(in_val * 100) / 100;
	
	// added 23.05.07 - change amount_from according to precision
	if ((in_val != '') && (parseFloat(in_val) != amount))
		document.forms[fid].amount_from.value = amount;

	if (isNaN(document.forms[fid].amount_from.value)) {
		amount = min_amount;
		document.forms[fid].amount_from.value = amount;
		out_in_keyup(fid, id, code, bForce);
		return;
	}	

	
	if (document.forms[fid].amount_from.value < 0) {
		amount = -amount;
		document.forms[fid].amount_from.value = amount;
		out_in_keyup(fid, id, code, bForce);
		return;
	}
	
	document.forms[fid].amount_to.value = Math.round( (amount * cc + fix) * 100) / 100;
	document.forms[fid].amount_from_ps.value = with_comiss_ps(amount);
	
	
	if (bForce) { out_in_keyup(fid, code); }
}



function with_comiss_ps(amount) {
	//alert(sys_comission_perc_from);
	//alert(amount);
	amount = parseFloat(amount);
	comiss = (sys_comission_perc_from * amount) + sys_comission_fix_from;
	
	if ( comiss < sys_comission_min_from )
		comiss = sys_comission_min_from;
	comiss = Math.round(comiss * 100) / 100;
	//alert(Math.round((amount + comiss) * 100) / 100);
	return Math.round((amount + comiss) * 100) / 100;
}

function without_comiss_ps(amount) {
	comiss = (sys_comission_perc_from * amount) + sys_comission_fix_from;
	if ( comiss < sys_comission_min_from )
		comiss = sys_comission_min_from;
	comiss = Math.round(comiss * 100) / 100;
	return Math.round((amount - comiss) * 100) / 100;
}

function in_out_keyup_ps(fid, id, code, bForce) {

	if (document.forms[fid].amount_from_ps == null) return;
  
	in_val = document.forms[fid].amount_from_ps.value.replace(",", ".");
	if (isNaN(in_val)) { in_val = "0"; }
	
	amount = Math.round(in_val * 100) / 100;
	
	// added 23.05.07 - change amount_from according to precision
	if ((in_val != '') && (parseFloat(in_val) != amount))
		document.forms[fid].amount_from_ps.value = amount;
	
	
	
	if (isNaN(document.forms[fid].amount_from_ps.value)) {
		amount = min_amount;
		document.forms[fid].amount_from_ps.value = with_comiss_ps(amount);
		in_out_keyup(fid, id, code, bForce);
		out_in_keyup(fid, id, code, bForce);
		return;
	}	


	
	if (document.forms[fid].amount_from_ps.value < 0) {
		amount = -amount;
		document.forms[fid].amount_from_ps.value = with_comiss_ps(amount);
		in_out_keyup(fid, id, code, bForce);
		out_in_keyup(fid, id, code, bForce);
		return;
	}
	
	document.forms[fid].amount_from.value = without_comiss_ps(amount);
	
	document.forms[fid].amount_to.value = Math.round( (without_comiss_ps(amount) * cc + fix) * 100) / 100;
	if (bForce) { out_in_keyup(fid, code); }
	
}

/*
	From Out to In OnKeyUp handler
*/
function out_in_keyup(fid, id, code, bForce) {
	//alert ('out_in_keyup');
	if (document.forms[fid].amount_to == null) return;
	// if (id == null) return;
	
	out_val = document.forms[fid].amount_to.value.replace(",", ".");
	if (isNaN(out_val)) { out_val = "0"; }
	
	amount = Math.round(out_val * 100) / 100;
		
	// added 23.05.07 - change amount_out according to precision
	if ((out_val != '') && (parseFloat(out_val) != amount))
		document.forms[fid].amount_to.value = amount;
	
	if (isNaN(document.forms[fid].amount_to.value)) {
		amount = 0;
		document.forms[fid].amount_to.value = amount;
		in_out_keyup(fid, id, code, bForce);
		return;
	}
  
	if (course == 0) return;
	
	amount_from = Math.round(((out_val - fix) / cc ) * 100) / 100;
  	document.forms[fid].amount_from.value = amount_from;
	
	document.forms[fid].amount_from_ps.value = with_comiss_ps(amount_from);
  
  
	if (document.forms[fid].amount_from.value > max_amount) {
		//in_out(fid, id, code, bForce);
		document.forms[fid].amount_from.value = max_amount;
		document.forms[fid].amount_from_ps.value = with_comiss_ps(max_amount);
		document.forms[fid].amount_to.value = Math.round( ((max_amount - fix) / cc) * 100) / 100;
		alert('Максимальная сумма обмена ' + max_amount);
		return;
	}
	
  if (bForce) { in_out_keyup(fid, code); }

}


function SetCourses () {

	if (course / course_back >= 0.5) {
		document.getElementById('curr_from').value = 1;
		document.getElementById('curr_from').value = course;
	}
	else {
		document.getElementById('curr_from').value = course_back;
		document.getElementById('curr_from').value = 1;
	}	

}