
// =======================
// ==== Charts front page
// =======================

var lastTblImg=0;
var lastChartImg=0;

var lastPeriod=12;
var isLastPeriodInDays=false;

function SwitchTopTable(i)
{
	var cnt=0;
	document.getElementById("tblHdr"+lastTblImg).src=ntblHdrs[lastTblImg];
	document.getElementById("tblHdr"+i).src=tblHdrs[i];
	document.getElementById("topstbl"+lastTblImg).style.display="none";
	document.getElementById("topstbl"+i).style.display="block";

	if(i==0) {lastPeriod=12; isLastPeriodInDays=false;}
	else if(i==1) {lastPeriod=6; isLastPeriodInDays=false;}
	else if(i==2) {lastPeriod=1; isLastPeriodInDays=false;}
	else if(i==3) {lastPeriod=7; isLastPeriodInDays=true;}
	lastTblImg=i;
	document.getElementById("clcChart").src=BuildChartSrc(lastChartImg);
}

function SwitchFrontChart(i)
{
	document.getElementById("clcChart").src=BuildChartSrc(i);
	document.getElementById("clcHdr"+lastChartImg).src=nchartHdrs[lastChartImg];
	document.getElementById("clcHdr"+i).src=chartHdrs[i];
	lastChartImg=i;
}

function BuildChartSrc(i)
{
	var valDateFrom=new Date();
	var valDateTo=new Date();
	var monthFrom, yearFrom, dateFrom;
	var monthTo, yearTo, dateTo;

	monthTo=valDateTo.getMonth();
	yearTo=valDateTo.getYear();
	if(uaType==UA_GECKO) yearTo=yearTo+1900;
	dateTo=valDateTo.getDate()-1;

	valDateTo=new Date(yearTo, monthTo, dateTo);

	monthTo=valDateTo.getMonth();
	yearTo=valDateTo.getYear();
	if(uaType==UA_GECKO) yearTo=yearTo+1900;
	dateTo=valDateTo.getDate();

	yearFrom=valDateTo.getYear();
	if(uaType==UA_GECKO) yearFrom=yearFrom+1900;

	if(!isLastPeriodInDays) {monthFrom=monthTo-lastPeriod;} else {monthFrom=monthTo;}	
	if(isLastPeriodInDays) {dateFrom=dateTo-lastPeriod;} else {dateFrom=dateTo;}
	valDateTo=new Date(yearFrom, monthFrom, dateFrom);
	monthFrom=valDateTo.getMonth();
	yearFrom=valDateTo.getYear();
	if(uaType==UA_GECKO) yearFrom=yearFrom+1900;
	dateFrom=valDateTo.getDate();

	var cache
	cache=(i+1)*10+1+lastTblImg

	if(i==0) return "/Chart-front.asp?ch="+cache+"&num=1&df="+dateFrom+"."+(monthFrom+1)+"."+yearFrom+
	"&dt="+dateTo+"."+(monthTo+1)+"."+yearTo+"&c=rur&clc=0&i0=13850&s0=2";
	if(i==1) return "/Chart-front.asp?ch="+cache+"&num=1&df="+dateFrom+"."+(monthFrom+1)+"."+yearFrom+
	"&dt="+dateTo+"."+(monthTo+1)+"."+yearTo+"&c=rur&clc=0&i0=15475&s0=3";
	if(i==2) return "/Chart-front.asp?ch="+cache+"&num=2&df="+dateFrom+"."+(monthFrom+1)+"."+yearFrom+
	"&dt="+dateTo+"."+(monthTo+1)+"."+yearTo+"&c=rur&clc=0&i0=12&s0=0&i1=15&s1=0"
	if(i==3) return "/Chart-front.asp?ch="+cache+"&num=1&df="+dateFrom+"."+(monthFrom+1)+"."+yearFrom+
	"&dt="+dateTo+"."+(monthTo+1)+"."+yearTo+"&c=rur&clc=0&i0=1&s0=4"
}


// =======================
// ==== Charts calc
// =======================

function OpenChartPage(width, height, heightInc)
{
	var i, url, x, y, optStr, winWidth, winHeight;
	var numCh; numCh=new Number(document.getElementById("numCh").value).valueOf();
	winWidth=width+40;
	winHeight=height+150+heightInc*numCh;
	
	url="/ChartPage.asp?w="+width+"&h="+height
	for(i=0;i<=numCh;i++) if(document.getElementById("ch"+i).checked==true) url=url+"&ch"+i+"=on";
	
	OpenNewPage(url, winWidth, winHeight, false);
}

// =======================
// ==== Loan Calculator
// =======================

function SwitchMiniLCalc(tbl)
{
	if(tbl==0)
	{
		document.getElementById("lcalcmain").style.display="block";
		document.getElementById("lcalcloans").style.display="none";
		UpdateControls(0);
	}
	else
	{
		document.getElementById("lcalcmain").style.display="none";
		document.getElementById("lcalcloans").style.display="block";
		UpdateControlsLoans(0);
	}
}

function SubmitLCalcForm(url)
{
	//if(priceId>0) document.getElementById("priceId").value=priceId;
	document.getElementById("lCalcForm").action=url;
	document.getElementById("lCalcForm").submit();
}

function UpdateControlsLoans(curTerm)
{
	SetTermValues(curTerm, "termloans", "loanTypeLoans");
}

function UpdateControls(curTerm)
{
	SetTermValues(curTerm, "termmain", "loanTypeMain");
	SetParamName();	
}

function SetParamName()
{
	var paramType=document.getElementById("paramType");
	var paramName=document.getElementById("paramName");
	var loanType=document.getElementById("loanTypeMain");
	if(paramType.selectedIndex==0)
	{
		switch(loanType.selectedIndex)
		{
			case 0:
				paramName.innerHTML="Введите стоимость квартиры";
				break;
			case 1:
				paramName.innerHTML="Введите стоимость автомобиля";
				break;
			default:
				paramName.innerHTML="Введите сумму приобретения";
				break;
		}
	}
	else if(paramType.selectedIndex==1) paramName.innerHTML="Введите величину кредита";
	else if(paramType.selectedIndex==2) paramName.innerHTML="Введите желаемую сумму ежемесячных выплат";
	else if(paramType.selectedIndex==3) paramName.innerHTML="Введите сумму Вашего месячного дохода";
	else if(paramType.selectedIndex==4) paramName.innerHTML="Введите желаемую сумму первого взноса";
}

function SetTermValues(curTerm, termname, loanTypeName)
{
	var loanType=document.getElementById(loanTypeName);
	var term=document.getElementById(termname);
	var labels, values
	
	if(loanType.selectedIndex==0)
	{
		values = new Array(3,5,10,15);
		labels = new Array("3 года","5 лет","10 лет","15 лет")		
	}
	else if(loanType.selectedIndex==1)
	{
		values = new Array(1,2,3);
		labels = new Array("1 год","2 года","3 года");
	}
	for(i=0; i<term.options.length; i++)
	{
		term.remove(i);
		i--;
	}
	for(i=0; i<values.length; i++)
	{
		opt=document.createElement("option");
		
		if(uaType==UA_GECKO) term.add(opt, null);
		else term.options.add(opt);
				
		opt.value=values[i];
				
		if(uaType==UA_GECKO) opt.text=labels[i];
		else opt.innerText=labels[i];
		
		if(curTerm>0 && opt.value==curTerm)
		{
			if(uaType==UA_GECKO) opt.defaultSelected=true;
			else opt.selected=true;
		}
	}
}

// =======================
// ==== Calculator itself!
// =======================

var isDateEdited=false;
//==12.02.04 - Lena Kruglova: no auto date change
function OnDateEdit() { /*isDateEdited=true;*/ }
function OnItemChange() { /*UpdateDateControls("From", "To");*/ }
function OnCurrencyChange() { /*UpdateDateControls("From", "To");*/ }

function UpdateDateControls(prefixFrom, prefixTo)
{
	var day, month, year, dateUser, date;
	var dateStock, itemIdStock, sectorIdStock
	var dateCurr, itemIdCurr, sectorIdCurr

	if(GetSelValue("curr")=="rur") {itemIdCurr=1}
	if(GetSelValue("curr")=="usd") {itemIdCurr=12}
	if(GetSelValue("curr")=="eur") {itemIdCurr=15}
	sectorIdCurr=0

	itemIdStock=new Number(GetSelValue("itemSel")).valueOf();
	sectorIdStock=new Number(GetSelValue("sectorSel")).valueOf();

	dateCurr=dates[sectorIdCurr][itemIdCurr];
	dateStock=dates[sectorIdStock][itemIdStock];
	if(isDateEdited)
	{
		dateUser=new Date(document.getElementById("year"+prefixFrom).value,
						  document.getElementById("month"+prefixFrom).value-1,
						  document.getElementById("day"+prefixFrom).value);
		date=new Date(Math.max(dateCurr, dateStock, dateUser));		
		if(date>dateUser) isDateEdited=false;		
	}
	else
	{
		date=new Date(Math.max(dateCurr, dateStock));
	}
	
	if( date.getDate()<10 ) day="0"+date.getDate(); else day=date.getDate();
	if( date.getMonth()+1 < 10 ) month="0"+(date.getMonth()+1); else month=(date.getMonth()+1);
	year=date.getFullYear();
	document.getElementById("day"+prefixFrom).value=day;
	document.getElementById("month"+prefixFrom).value=month;
	document.getElementById("year"+prefixFrom).value=year;
	eval("minDate"+prefixFrom+"=\""+day+"."+month+"."+year+"\";");
	eval("minDate"+prefixTo+"=\""+day+"."+month+"."+year+"\";");	
}

//item id is passed to tune currently selected item by the way
function PreloadSector(itemId, isForm)
{
	var i, itemIds, opt, prevOpt=null, itemSelLen, j, sector;
	for(i=0; i<document.getElementById("itemSel").options.length; i++)
	{
		document.getElementById("itemSel").remove(i);
		i--;
	}
	sector = sectors[new Number(GetSelValue("sectorSel")).valueOf()]	
	
	for(i=0; i<sector.length; i++)
	{
		opt=document.createElement("option");
		
		if(uaType==UA_GECKO) document.getElementById("itemSel").add(opt, null);
		else document.getElementById("itemSel").options.add(opt);
		
		opt.value=sector[i][0];		
		if(uaType==UA_GECKO) opt.text=sector[i][1];
		else opt.innerText=sector[i][1];
		
		if(itemId>0 && opt.value==itemId)
		{
			if(uaType==UA_GECKO) opt.defaultSelected=true;
			else opt.selected=true;
		}
	}
	if(!isForm) OnItemChange();
}

function SubmitCalcForm(formType)
{
	if(formType==1) document.getElementById("calcForm").action=formAction1;
	if(formType==2) document.getElementById("calcForm").action=formAction2;
	document.getElementById("calcForm").submit();
}

function CheckAllHistory(control)
{
	var i;
	var numCh; numCh=new Number(document.getElementById("numCh").value).valueOf();
	for(i=0;i<=numCh;i++)
	{
		if(control.checked==true) document.getElementById("ch"+i).checked=true;
		else document.getElementById("ch"+i).checked=false;
	}
}

function OpenCalendarWindow(url, minDate, maxDate, prefix, width, height)
{
	urlStr = url+"?defDate="+
	(document.getElementById("day"+prefix).value+"."+ 
		document.getElementById("month"+prefix).value+"."+ 
	document.getElementById("year"+prefix).value)+
	"&minDate="+minDate+
	"&maxDate="+maxDate+
	"&prefix="+prefix;	
	
	OpenNewPage(urlStr, width, height,false)
}

function ShowHelp(id, isClose)
{
	if(isClose==true)
	{
		document.getElementById(id).style.display="none";
		lastOpenHelp="";
	}
	else
	{
		if(lastOpenHelp!="") document.getElementById(lastOpenHelp).style.display="none";
		document.getElementById(id).style.display="block";
		lastOpenHelp=id;
	}
}

function OpenHelpPageV2(type, itm, curr, instrType, calcType)
{
	helpRef="?type="+type+"&itm="+itm+"&c="+curr+"&it="+instrType+"&ct="+calcType;
	OpenNewPage("/Help.asp"+helpRef,300,300,true);
}

// =======================
// ==== Currency calc
// =======================

function SetCCalcControls()
{
	SetSelValue("currFrom",840);
	SetSelValue("currTo",0);
}

function DoCCalc()
{
	var currFrom=GetSelValue("currFrom");
	var currTo=GetSelValue("currTo");
	var baseamtFrom=cbrates[currFrom][0];
	var baseamtTo=cbrates[currTo][0];
	var rateFrom=cbrates[currFrom][1];
	var rateTo=cbrates[currTo][1];
	var amt=document.getElementById("amt").value;
	var tax=GetSelValue("tax");
	var result="", rate="";
	
	if(!isNaN(amt) && amt>0)
	{
		if(isNaN(tax) || tax==0) tax=0;
		result=(amt*rateFrom/baseamtFrom)*(baseamtTo/rateTo)*(1-(tax/100));
		result=Math.round(result*Math.pow(10,2))/Math.pow(10,2);
		rate=(rateFrom/baseamtFrom)*(baseamtTo/rateTo);
		rate=Math.round(rate*Math.pow(10,2))/Math.pow(10,2);
		document.getElementById("result").innerHTML="<b>Результат: "+result+"<br>Курс: "+rate+"</b>"
		//document.getElementById("rate").innerText=rate;
	}
}


// =======================
// ==== Charts for TA
// =======================

function OpenTAPage(id)
{
	var win;
	win = window.open("/charts/main/default.asp?id="+id, 'win2');
	win.focus();
}

// ===========================
// ==== News Comments & Images
// ===========================

function OpenNewsImage(url, width, height)
{
	OpenNewPage(url, width+20, height+80, false);
}

function ReplyTo(username, id)
{
	
	if(id>0)
	{
		document.getElementById("replyTo").value=id;
		document.getElementById("replyToAll").disabled=false;
		if (navigator.appName == "Opera" || navigator.appName == "Netscape")
			document.getElementById("txtComment").value="Для "+username+": "+document.getElementById("txtComment").value;
		else
			document.getElementById("txtComment").innerHTML="Для "+username+": "+document.getElementById("txtComment").innerHTML;	
	}
	else
	{
		document.getElementById("replyTo").value=0;
		document.getElementById("replyToAll").disabled=true;
	}
}

// ====================
// ==== Discounts-forms
// ====================

function UpdateDiscountAmtControl()
{
	if(GetSelValue("discountType")=="1") document.getElementById("discountVal").disabled=false;
	else document.getElementById("discountVal").disabled=true;
}

// ====================
// ==== Rantier calc
// ====================

function UpdateRiskBar()
{	
	var risk, investTo;
	investTo = new Number(GetSelValue("investTo")).valueOf();
	document.getElementById("rcRiskBar").style.width=investTo * 4;
	document.getElementById("rcRiskBarTd").style.width=investTo * 4 + 2;
	document.getElementById("rcRiskBar").style.height="20";
	if(investTo==5)
		risk="очень низкий";
	else if(investTo==12)
		risk="низкий";
	else if(investTo>12)
		risk="средний";
	document.getElementById("rcRiskBarText").innerHTML="&nbsp;" + risk + "&nbsp;";
}

function DoRantierExt()
{
	var term, termType, curr, startSum, monthlySavings, monthlySavingsType, perIncome, perIncomeType, infl, inflType
	var savings, resultStr, q, q1, t;
	var result, result1, result2, income;
	var iresult, iresult2, iincome;
	term = new Number(document.getElementById("term").value).valueOf();
	termType = new Number(GetSelValue("termType")).valueOf();
	curr = document.getElementById("curr").value;
	startSum = new Number(document.getElementById("startSum").value).valueOf();
	monthlySavings = new Number(document.getElementById("monthlySavings").value).valueOf();
	monthlySavingsType = new Number(GetSelValue("monthlySavingsType")).valueOf();
	perIncome = new Number(document.getElementById("perIncome").value).valueOf();
	perIncomeType = new Number(GetSelValue("perIncomeType")).valueOf();
	infl = new Number(document.getElementById("infl").value).valueOf();
	inflType = new Number(GetSelValue("inflType")).valueOf();
	if(isNaN(term) || term<=0 || isNaN(termType) || (termType!=1 && termType!=12))
		alert("Не указан срок накопления");
	else if(isNaN(startSum) || startSum<=0)
		alert("Не указана начальная сумма");
	else if(isNaN(monthlySavings)  || isNaN(monthlySavingsType) || (monthlySavingsType!=1 && monthlySavingsType!=12))
		alert("Не указан размер месячных накоплений");
	else if(isNaN(perIncome) || perIncome<=0 || isNaN(perIncomeType) || (perIncomeType!=1 && perIncomeType!=12))
		alert("Не указан процент дохода");
	else if(isNaN(infl) || isNaN(inflType) || (inflType!=1 && inflType!=12))
		alert("Не указан размер инфляции");
	else
	{
		if(perIncomeType==12) {q=Math.exp(Math.log(1+0.01*perIncome)/12)-1;} else {q=perIncome*0.01;}
		if(inflType==12) {q1=q-(Math.exp(Math.log(1+0.01*infl)/12)-1);} else {q1=q-infl*0.01;}
			t=term*termType;
			savings=monthlySavings/monthlySavingsType;
			
			result=Math.pow((1+q),t)*startSum + savings*(Math.pow(1+q,t)-1)/q
			iresult=Math.pow((1+q1),t)*startSum + savings*(Math.pow(1+q1,t)-1)/q1
			
			result1=startSum+t*savings;
			if(q1==0) iresult=result1;
			result2=result-result1;
			iresult2=iresult-result1;
			income=result*q;
			iincome=iresult*q1;
			
			resultStr="<b>Срок накопления:</b>&nbsp;"+Math.round(term*Math.pow(10,2))/Math.pow(10,2);
			if(termType==1) {resultStr=resultStr+" месяцев<br>";} else {resultStr=resultStr+" лет<br>";}
			resultStr=resultStr+"<b>Валюта:</b>&nbsp;"+curr+"<br><b>Начальная сумма:</b>&nbsp;"+Math.round(startSum*Math.pow(10,2))/Math.pow(10,2)+"<br><b>Взнос в ";
			if(monthlySavingsType==1) {resultStr=resultStr+" месяц";} else {resultStr=resultStr+" год";}
			resultStr=resultStr+":</b>&nbsp;"+Math.round(monthlySavings*Math.pow(10,2))/Math.pow(10,2)+"<br><b>Доходность в ";
			if(perIncomeType==1) {resultStr=resultStr+" месяц";} else {resultStr=resultStr+" год";}
			resultStr=resultStr+":</b>&nbsp;"+Math.round(perIncome*Math.pow(10,2))/Math.pow(10,2)+"%<br><b>Размер инфляции в ";
			if(inflType==1) {resultStr=resultStr+" месяц";} else {resultStr=resultStr+" год";}
			resultStr=resultStr+":</b>&nbsp;"+Math.round(infl*Math.pow(10,2))/Math.pow(10,2)+"%<br><br>";
			resultStr=resultStr+"<b>Накопленная сумма к отчетному периоду:</b>&nbsp;"+Math.round(result*Math.pow(10,2))/Math.pow(10,2)+
			"<br><b>Из нее накоплено по процентам:</b>&nbsp;"+Math.round(result2*Math.pow(10,2))/Math.pow(10,2)+
			"<br><b>Чистые сбережения:</b>&nbsp;"+Math.round(result1*Math.pow(10,2))/Math.pow(10,2)+
			"<br><b>Месячный доход с накопленной суммы:</b>&nbsp;"+Math.round(income*Math.pow(10,2))/Math.pow(10,2)+"<br><br>"+
			"с поправкой на инфляцию<br>"+
			"<b>Накопленная сумма к отчетному периоду:</b>&nbsp;"+Math.round(iresult*Math.pow(10,2))/Math.pow(10,2)+
			"<br><b>Из нее накоплено по процентам:</b>&nbsp;"+Math.round(iresult2*Math.pow(10,2))/Math.pow(10,2)+
			"<br><b>Чистые сбережения:</b>&nbsp;"+Math.round(result1*Math.pow(10,2))/Math.pow(10,2)+
			"<br><b>Месячный доход с накопленной суммы:</b>&nbsp;"+Math.round(iincome*Math.pow(10,2))/Math.pow(10,2)+"<br><br>";
			document.getElementById("resultStr").innerHTML=resultStr;
	}
}

function DoRantierSimple(formType)
{
	var plannedSum, startSum, monthlySavings, investTo, investToLabel, formType;
	var plannedSumPerMonth, result, resultStr, q, t, t0, t1;
	plannedSum = new Number(document.getElementById("plannedSum").value).valueOf();
	startSum = new Number(document.getElementById("startSum").value).valueOf();
	monthlySavings = new Number(document.getElementById("monthlySavings").value).valueOf();
	investTo = new Number(GetSelValue("investTo")).valueOf();
	investToLabel = GetSelLabel("investTo");
	if(isNaN(plannedSum) || plannedSum<=0)
		alert("Не указана требуемая сумма.");
	else if(isNaN(investTo) || investTo<=0)
		alert("Не указан инструмент накопления.");
	else
	{
		if(isNaN(startSum) || new String(document.getElementById("startSum").value).length==0)
		{
			if(formType==0) {startSum=0.1*plannedSum;} else {startSum=6*plannedSum;}
			document.getElementById("startSum").value=Math.round(startSum*Math.pow(10,2))/Math.pow(10,2);
		}
		if(isNaN(monthlySavings) || new String(document.getElementById("monthlySavings").value).length==0)
		{
			if(formType==0) {monthlySavings=0.01*plannedSum;} else {monthlySavings=plannedSum;}
			document.getElementById("monthlySavings").value=Math.round(monthlySavings*Math.pow(10,2))/Math.pow(10,2);
		}
		q=Math.exp(Math.log(1+0.01*investTo)/12)-1;
		if(formType==0)
			plannedSumPerMonth=plannedSum*q;
		else
			plannedSumPerMonth=plannedSum;

		t=Math.log((plannedSumPerMonth+monthlySavings)/(startSum*q+monthlySavings))/Math.log(1+q);

		if(Math.floor(t)!=t) t=Math.floor(t)+1;

		plannedSum = Math.pow(1+q,t)*startSum + monthlySavings*((Math.pow(1+q,t)-1)/q)
		if(formType==1) plannedSum=plannedSum*q
		t1=t % 12;
		t0=(t-t1)/12;

		resultStr="Если у Вас уже есть "+Math.round(startSum*Math.pow(10,2))/Math.pow(10,2)+"$ и Вы можете откладывать "+
		Math.round(monthlySavings*Math.pow(10,2))/Math.pow(10,2)+"$ ежемесячно,";

		if(formType==0)
		{
			resultStr=resultStr+" Вы сможете накопить "+Math.round(plannedSum*Math.pow(10,2))/Math.pow(10,2)+"$ за";
		}
		else
		{
			if(Math.round(t1)<=0 && Math.round(t0)<=0) {resultStr=resultStr+" Вы уже сможете";} else {resultStr=resultStr+" Вы сможете через";}
		}

		if(Math.round(t0)>0) resultStr=resultStr+" "+Math.round(t0)+" лет";
		if(Math.round(t0)>0 && Math.round(t1)>0) resultStr=resultStr+" и";
		if(Math.round(t1)>0) resultStr=resultStr+" "+Math.round(t1)+" месяцев";

		if(formType==0)
		{
			resultStr=resultStr+" при условии что вы используете для накопления "+investToLabel+".";
		}
		else
		{
			resultStr=resultStr+" получать ежемесячный процентный доход в размере "+Math.round(plannedSum*Math.pow(10,2))/Math.pow(10,2)+
			"$, при условии, что Вы используете для накопления "+investToLabel+".";
		}
		document.getElementById("resultStr").innerHTML=resultStr;
	}
}


function add_to_favorites(url, name) {
	if (navigator.userAgent.indexOf('MSIE') != -1) {
		window.external.AddFavorite(url, name);
	} else {
		open_window('/add_to_favorites.html', 400, 250);
	}
}

function set_home_page(url, obj) {
	if (navigator.userAgent.indexOf('MSIE') != -1) {
		obj.style.behavior='url(#default#homepage)';
		obj.setHomePage(url);
	} else {
		open_window('/set_home_page.html', 400, 250);
	}
}

function SetDateInURL (URL) {
	var rqstDate; 
	var filter;
	var day, month, year;
	
	rqstDate = document.getElementById("txtGoToDate").value;
	filter = /^\d{2}-\d{2}-\d{4}$/i;
		
	if (filter.test(rqstDate) == false){
		alert('Неверный формат даты');
		return false;
	}
	else {
		URL = URL.replace ("default.asp","");

		day = rqstDate.substr(0,2)
		day = '00'+parseFloat(day).toString(16)

		month = rqstDate.substr(3,2)
		month = '00'+parseFloat(month).toString(16)

		year = rqstDate.substr(6,4)
		year = '000'+parseFloat(year).toString(16)

		URL = URL+"rqdate"+day.slice(-2)+""+month.slice(-2)+""+year.slice(-3)+"/";
		document.getElementById("frmGoToDate").action = URL
		document.getElementById("frmGoToDate").submit();
		return true;
	}
	return false;
}



function reloadCAPTCHA() {
	document.getElementById('CAPTCHA').src='CAPTCHA/CAPTCHA_image.asp?'+Date();
}



function checkMaxInput(elementId, maxLen) {
	var element = document.getElementById(elementId);
	if (element.value.length > maxLen) 
		element.value = element.value.substring(0, maxLen); 
	else document.getElementById('remLen').value = maxLen - element.value.length; 
}



var prevStockId=new Array();
prevStockId[1]=0;
prevStockId[2]=0;
var prevMarket=new Array();
prevMarket[1]=0;
prevMarket[2]=0;

function SwapChartImage(chartNum, stockId, market)
{
	if (!(stockId==prevStockId[chartNum] && market==prevMarket[chartNum]))
	{
	document.getElementById("chart"+chartNum).src="http://blotter.ru/charts/BlotterChart"+stockId+"("+market+").gif"
	document.getElementById("chartHref"+stockId+"("+market+")").style.color="#fa741c";
	if(prevStockId[chartNum]>0 && prevMarket[chartNum]>0)
		document.getElementById("chartHref"+prevStockId[chartNum]+"("+prevMarket[chartNum]+")").style.color="black";	
	prevStockId[chartNum]=stockId;
	prevMarket[chartNum]=market;
	}
}


function DoVote(url){
	document.location.href=url
}

//	===========================================

function body_load()
{ 	
//	str = '<s'
//	str += 'cript type="text/javascript" src="http://mg.dt00.net/js/a/u/auto.finam.ru.i2.js" encoding="windows-1251">';
//	str += '</s'
//	str += 'cript>';
	
//	document.getElementById("MarketGid3753_JS").innerHTML = str;

//	document.getElementById("MarketGid3753_JS").src = 'src="http://mg.dt00.net/js/a/u/auto.finam.ru.i2.js"';

	if (document.getElementById("Partners"))
		document.getElementById("Partners").innerHTML  = '<center><iframe id="Partners" scrolling="No" src="Partners.html"  frameborder="0" height="280" width="700" hspace="0" vspace="0"></iframe></center>';
	if (document.getElementById("Partners2"))
		document.getElementById("Partners2").innerHTML = '<center><iframe id="Partners" scrolling="No" src="Partners2.html" frameborder="0" height="260" width="700" hspace="0" vspace="0"></iframe></center>';

//	alert (document.getElementById("MarketGid3753_JS").src);
}

function clear_text_win()
{ 	
	str = window.location.href;

//	#forum
	str = str.replace('#forum','');
	
	num = str.indexOf('?');
	if (num > 0)
		str += '&is_print=1';
	else
		str += '?is_print=1';

	window.location = str;
	
//	myWinOpt="top=5,left=300,width=450,height=600,status=yes,toolbar=yes,menubar=yes,titlebar=yes,directories=yse,location=yes,resizable=yes,scrollbars=yes";
//	print_file_name = str;
//	printFile = open(print_file_name,"fr_1",myWinOpt);
}

function mailAlert()
{
//	created	by burmm@mail.ru

	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		if (event.ctrlKey == true && event.keyCode == 13)
		{
			range = document.selection.createRange();
			str1 = "Ошибка на странице : " + document.title + encodeURI("\r\n\r\n");
			str = str1 + "URL страницы : " + window.location.href + encodeURI("\r\n\r\n");
			str += "Проблемный текст: " + range.text;
	
			reg = /<([^>]*)>/gi;
	//		reg = /<.*?>/gi;
			str = str.replace(reg," ");
			
			reg = /\r/gi;
			str = str.replace(reg," ");
			reg = /\n/gi;
			str = str.replace(reg," ");
	
			reg = /"/gi;
			str = str.replace(reg,encodeURI('"'));
			str1 = str1.replace(reg,encodeURI('"'));
			reg = /'/gi;
			str = str.replace(reg,encodeURI("'"));
			str1 = str1.replace(reg,encodeURI("'"));
	
			reg = /&nbsp;/gi;
			str = str.replace(reg," ");
			reg = /&amp;/gi;
			str = str.replace(reg," ");
			reg = /&quot;/gi;
			str = str.replace(reg,encodeURI('"'));
			str1 = str1.replace(reg,encodeURI('"'));
			reg = /&lt;/gi;
			str = str.replace(reg,encodeURI("<"));
			str1 = str1.replace(reg,encodeURI("<"));
			reg = /&gt;/gi;
			str = str.replace(reg,encodeURI(">"));
			str1 = str1.replace(reg,encodeURI(">"));
			reg = /&copy;/gi;
			str = str.replace(reg," ");
			reg = /&laquo;/gi;
			str = str.replace(reg," ");		
			reg = /&raquo;/gi;
			str = str.replace(reg," ");		
			reg = /&/gi;
			str = str.replace(reg," ");
			str1 = str1.replace(reg," ");
	
	//		document.all("txtTest").value = str;

			parent.location="mailto:news@finam.ru?subject=" + str1 + "&body=" + str;
		}
	}
//	if (navigator.appName == "Netscape")
//	{
//		alert (navigator.appName);
//	}
}

function changeTestDrive(Pg, ID)
{
	str = window.location.href;

	num = str.indexOf('?');
	if (num > 0)	
	{
		str1 = str.substring(num, str.length)
		str = str.replace(str1,'');
	}
	str += '?Pg=' + Pg + '&divID='+ID;

	window.location = str;
}

// =======================================

function delItem(fid,str_out)
{	
	if (confirm(str_out)) 
	{	
//		document.forms('CommentsForm2').submit();	// не работает в FireFox
		str = window.location.href;
		str = str.replace('show','');
		str = str.replace('comment','');
		num = str.indexOf('?');
		if (num > 0)
			str += '&act=del';
		else
			str += '?act=del';
		str += '&delId=' + fid
		window.location = str;
	}
}
function delItemReFuelling(str,str_out)
{	
	if (confirm(str_out)) 
	{	
		window.location = str;
	}
}

function OpenCalendarControl(control)
{
	if ( document.getElementById(control).disabled ) return;

	document.getElementById(control+"CalendarIf").src="/admin/calendar_adm.asp?setControl=" + control + "&RequestDate=" + document.getElementById(control).value;
	
	if(document.getElementById(control+"Calendar").style.display=="none")
	{
		document.getElementById(control+"Calendar").style.display="block";
		document.getElementById(control+"Icon").src="../i/arrow_down_close.gif";
		document.getElementById(control+"Icon").alt="Закрыть";
	}
	else
	{
		document.getElementById(control+"Calendar").style.display="none";
		document.getElementById(control+"Icon").src="../i/arrow_down.gif";
		document.getElementById(control+"Icon").alt="Открыть";
	}
//	alert (document.getElementById(control+"Calendar").src);
}

function switch_value_Travel(obj)
{
	for (i=0; i<block_control_name.length; i++)
	{
		if (document.getElementById(block_control_name[i]))
		{	document.getElementById(block_control_name[i]).disabled = true; // false;
			document.getElementById(block_control_name[i]).style.backgroundColor= '#eeeeee'; // 'white';
		}
	}
	if (document.getElementById(obj))
	{	document.getElementById(obj).disabled = false; // true;
		document.getElementById(obj).style.backgroundColor='white'; // '#eeeeee';
	}
}

function initData(brandId, modelId)
{
//	alert(brandId);
//	alert(modelId);

    var request = '/export/load_carModels.asp?brandId=' + brandId + '&modelId=' + modelId;

    oS = document.createElement("script");
    oS.setAttribute("src",request);
    oS.setAttribute("name",'loadScript');
    oS.setAttribute("id",'loadScript');

    document.body.appendChild(oS);
}

function switch_value_ReFuelling(obj)
{
	for (i=0; i<block_control_name.length; i++)
	{
		if (document.getElementById(block_control_name[i]))
		{	document.getElementById(block_control_name[i]).disabled = true; // false;
			document.getElementById(block_control_name[i]).style.backgroundColor= '#eeeeee'; // 'white';
		}
	}
	if (document.getElementById(obj))
	{	document.getElementById(obj).disabled = false; // true;
		document.getElementById(obj).style.backgroundColor='white'; // '#eeeeee';
	}
}

function Clear_username()
{	if (document.getElementById('F_username').value == "e-mail")
		document.getElementById('F_username').value = "";
}

// ===================================================


block_control_name = new Array ("full_sum", "start_sum", "payment");
noblock_control_name = new Array ("rate", "term", "commission");
curr_default_A = new Array (24, 20, 20);
curr_default_I = new Array (20, 15, 15);
curr_default_P = new Array (30, 23, 23);

function round2(original)
{	return Math.round(original*100)/100;
}

function switch_value(obj)
{
	for (i=0; i<block_control_name.length; i++)
	{
		if (document.getElementById(block_control_name[i]))
		{	document.getElementById(block_control_name[i]).disabled = false;
			document.getElementById(block_control_name[i]).style.backgroundColor='white';
		}
	}
	if (document.getElementById(obj))
	{	document.getElementById(obj).disabled = true;
		document.getElementById(obj).style.backgroundColor='#eeeeee';
	}
}

function curr_default()
{	i = document.getElementById("curr").value;
	if (loanType == "A") document.getElementById("rate").value = curr_default_A[i];
	if (loanType == "I") document.getElementById("rate").value = curr_default_I[i];
	if (loanType == "P") document.getElementById("rate").value = curr_default_P[i];
}

function parse_Float(obj,check)
{
	obj.value = obj.value.replace(',','.');
	val=obj.value;
	
	flag = false;

	if ( val != "" )
	{
		if (check == "float")
		{
			flag = isNaN(parseFloat(val));
			obj.value = parseFloat(val);
		}
		if (check == "int")
		{
			flag = isNaN(parseInt(val));
			obj.value = parseInt(val);
		}
	}
	else
	{	if (obj.name == "rate" || obj.name == "term")
		flag = true;
	}

	if ( flag )
	{
		alert("Не корректное значение");
		document.getElementById(obj.id).select();
		document.getElementById(obj.id).focus();	

	}
}

function local_calc()
{
	var xx;
	if (loanType == "A") xx=0.3;
	if (loanType == "I") xx=0.3;
	if (loanType == "P") xx=0.1;
	flag = true;
	
	rate = document.getElementById("rate").value.replace(',','.');
	rate = rate/(12.*100.);
	if (loanType == "P")
	{	if (document.getElementById("rate_add").value == '') document.getElementById("rate_add").value = 0.;
		rate_add = document.getElementById("rate_add").value.replace(',','.')/100.;
	}
	else
	{	rate_add = 0.
	}
	rate_sum = rate*1. ; // + rate_add*1.;

	term = document.getElementById("term").value.replace(',','.');
	if (loanType == "I") term=term*12.;

	Q 			= 1.0 + rate_sum*1.;
	Qn			= Math.pow(Q, term);
	
	if (document.getElementById("commission").value	== '') document.getElementById("commission").value = 0.;
	
	if (document.forms["lCalcForm"].elements["block_control"][0].checked)
	{
		if (document.getElementById("start_sum").value == '' && document.getElementById("payment").value == '')
		{
			flag = false;
			if (loanType == "A") str1 = "Первоначальный взнос";
			if (loanType == "I") str1 = "Первоначальный взнос";
			if (loanType == "P") str1 = "Первоначальный взнос";
			if (loanType == "A") str2 = "Размер ежемесячного платежа";
			if (loanType == "I") str2 = "Размер ежемесячного платежа";
			if (loanType == "P") str2 = "Размер ежемесячного платежа";
			alert('Хотя бы одно из полей "' + str1 + '" или "' + str2 + '" должно быть заполнено');
			return false;
		} 
		if (document.getElementById("start_sum").value == '' && document.getElementById("payment").value != '')	
		{	credit_tmp = document.getElementById("payment").value.replace(',','.')*(Qn-1)/(rate_sum*Qn);
			document.getElementById("start_sum").value = round2(credit_tmp*xx/(1.-xx));
		}
		if (document.getElementById("start_sum").value != '' && document.getElementById("payment").value == '')	
		{	credit_tmp = document.getElementById("start_sum").value.replace(',','.')*(1.-xx)/xx;
			document.getElementById("payment").value = round2(credit_tmp*rate_sum*Qn/(Qn-1));
		}
	}

	if (document.forms["lCalcForm"].elements["block_control"][1].checked)
	{
		if (document.getElementById("full_sum").value == '' && document.getElementById("payment").value == '')
		{
			flag = false;
			if (loanType == "A") str1 = "Стоимость автомобиля";
			if (loanType == "I") str1 = "Стоимость квартиры";
			if (loanType == "P") str1 = "Требуемая сумма";
			if (loanType == "A") str2 = "Размер ежемесячного платежа";
			if (loanType == "I") str2 = "Размер ежемесячного платежа";
			if (loanType == "P") str2 = "Размер ежемесячного платежа";
			alert('Хотя бы одно из полей "' + str1 + '" или "' + str2 + '" должно быть заполнено');
			return false;
		} 
		if (document.getElementById("full_sum").value == '' && document.getElementById("payment").value != '')	
		{	credit_tmp = document.getElementById("payment").value.replace(',','.')*(Qn-1)/(rate_sum*Qn);
			document.getElementById("full_sum").value = round2(credit_tmp/(1.-xx));
		}
		if (document.getElementById("full_sum").value != '' && document.getElementById("payment").value == '')	
		{	document.getElementById("start_sum").value = round2(document.getElementById("full_sum").value*xx);
			credit_tmp = document.getElementById("full_sum").value.replace(',','.')*(1.-xx);
			document.getElementById("payment").value = round2(credit_tmp*rate_sum*Qn/(Qn-1));
		}
	}
	
	if (document.forms["lCalcForm"].elements["block_control"][2].checked)
	{
		if (document.getElementById("full_sum").value == '' && document.getElementById("start_sum").value == '')
		{
			flag = false;
			if (loanType == "A") str1 = "Стоимость автомобиля";
			if (loanType == "I") str1 = "Стоимость квартиры";
			if (loanType == "P") str1 = "Требуемая сумма";
			if (loanType == "A") str2 = "Первоначальный взнос";
			if (loanType == "I") str2 = "Первоначальный взнос";
			if (loanType == "P") str2 = "Первоначальный взнос";
			alert('Хотя бы одно из полей "' + str1 + '" или "' + str2 + '" должно быть заполнено');
			return false;
		} 
		if (document.getElementById("full_sum").value == '' && document.getElementById("start_sum").value != '')	
			document.getElementById("full_sum").value = round2(document.getElementById("start_sum").value/xx);
		if (document.getElementById("full_sum").value != '' && document.getElementById("start_sum").value == '')	
			document.getElementById("start_sum").value = round2(document.getElementById("full_sum").value*xx);
	}

	for (i=0; i<noblock_control_name.length; i++)
	{	document.getElementById(noblock_control_name[i]).value = document.getElementById(noblock_control_name[i]).value.replace(',','.');
		if (document.getElementById(noblock_control_name[i]).value == "")
		{
			flag = false;
			alert("Не корректное значение");
			document.getElementById(noblock_control_name[i]).select();
			document.getElementById(noblock_control_name[i]).focus();	
			return false;
		}
	}
	for (i=0; i<block_control_name.length; i++)
	{	document.getElementById(block_control_name[i]).value = document.getElementById(block_control_name[i]).value.replace(',','.');
		if (document.getElementById(block_control_name[i]).value == "" && !document.forms["lCalcForm"].elements["block_control"][i].checked)
		{
			flag = false;
			alert("Не корректное значение");
			document.getElementById(block_control_name[i]).select();
			document.getElementById(block_control_name[i]).focus();	
			return false;
		}
	}

full_sum 	= document.getElementById("full_sum").value;
start_sum	= document.getElementById("start_sum").value;
payment 	= document.getElementById("payment").value;
commission	= document.getElementById("commission").value;

//		pout = loanVol*monthRate*(Q^termm) / ((Q^termm)-1)
	
	if (document.forms["lCalcForm"].elements["block_control"][0].checked)
	{	credit 		= payment*(Qn-1)/(rate_sum*Qn);
		full_sum	= credit*1. + start_sum*1.;

		document.getElementById("full_sum").value = round2(full_sum);
	}
	document.getElementById("full_sum_H").value = full_sum;
		
	if (document.forms["lCalcForm"].elements["block_control"][1].checked)
	{	credit 		= payment*(Qn-1)/(rate_sum*Qn);
		start_sum	= full_sum - credit;

		document.getElementById("start_sum").value = round2(start_sum);
	}
	document.getElementById("start_sum_H").value = start_sum;

	if (document.forms["lCalcForm"].elements["block_control"][2].checked)
	{	credit 		= full_sum - start_sum;
		payment		= credit*rate_sum*Qn/(Qn-1);
	
		document.getElementById("payment").value = round2(payment);
	}
	document.getElementById("payment_H").value = payment;

	S_total = payment * term;
	S_per	= S_total - credit;
	var payment_add;
	payment_add = credit*rate_add*1.;

	document.getElementById("credit_sum").innerText = round2(credit);
	document.getElementById("payment_sum").innerText = round2(S_total + commission*1. + payment_add*term);
	document.getElementById("percent_sum").innerText = round2(S_per);
if (loanType == "P") document.getElementById("payment_add").innerText = round2(payment_add);
	document.getElementById("incom").innerText = round2(payment*2.5);
	document.getElementById("credit_sum_H").value = credit;
	document.getElementById("payment_sum_H").value = S_total;
	document.getElementById("percent_sum_H").value = S_per;
if (loanType == "P") document.getElementById("payment_add_H").value = payment_add;
	document.getElementById("incom_H").value = round2(payment*2.5);

	return true;
}

function submit_form()
{	flag = local_calc();
	if ( flag )
	{
		for (i=0; i<block_control_name.length; i++)
		{
			document.getElementById(block_control_name[i]).disabled = false;
			document.getElementById(block_control_name[i]).style.backgroundColor='white';
		}
	}
	return flag;
}

function submit_form_print(lCalcForm)
{	str = document.forms[lCalcForm].action;
	num = str.indexOf('?is_print');
	if ( ! (num > 0) )
		document.forms[lCalcForm].action = str + "?is_print=1";
	document.forms[lCalcForm].target = "_blank";
	document.forms[lCalcForm].submit();
	document.forms[lCalcForm].action = str;
	document.forms[lCalcForm].target = "";
}


