// detect browser version
isDOM=document.getElementById //DOM1 browser (MSIE 5+, Netscape 6, Opera 5+)
isOpera=isOpera5=window.opera && isDOM //Opera 5+
isOpera6=isOpera && window.print //Opera 6+
isOpera7=isOpera && document.readyState //Opera 7+
isMSIE=document.all && document.all.item && !isOpera //Microsoft Internet Explorer 4+
isMSIE5=isDOM && isMSIE //MSIE 5+
isNetscape4=document.layers //Netscape 4.*
isMozilla=isDOM && navigator.appName=="Netscape" //Mozilla или Netscape 6.*/** add trim() method to String object **/
String.prototype.trim = function() { return this.replace(/^s+|s+$/, ''); }

/** Current object **/
var currHelpList = null;

/** Класс для работы с всплывающим списком **/
var HelpList = Class.create();
HelpList.prototype = {

	// Constructor
	initialize: function( parent_el, popup_el, uri, el_name ) {
		this.m_parent = parent_el;
		this.m_popup = popup_el;
		this.m_uri = uri;
		this.m_name = el_name;
		this.m_current = parent_el;
		this.m_sleep = 150;
	},

	// Help user typing text.
	help: function( e ) {
		e_popup = $( this.m_popup );
		if ( e_popup ) {
			v = $( this.m_parent ).value;
			v = v.trim();
			if ( v.length > 0 ) {
				currHelpList = this;
				new Ajax.Request(
					this.m_uri + v,
					{
						method: 'get',
						onSuccess: function( transport ) {
							response = transport.responseText.evalJSON();
							info = response.info;
							el = $( currHelpList.m_popup );
							if ( el ) {
								p = $( currHelpList.m_parent );
								el.style.width = ( p.getWidth() + 31 )+ 'px';
								if ( info.length > 1 ) {
									// coordinates
									coord = p.positionedOffset();
									iPosX = coord.left;
									iPosY = coord.top;
									el.style.top = (iPosY + 18) + "px";
									el.style.left = (iPosX - 5) + "px";
									el.show();
									// add new data
									while( el.childNodes.length > 0 ) { el.removeChild( el.lastChild ); }
									for( i = 0; i < info.length; i++ ) {
										if ( info[i].title != '' ) {
											opt = document.createElement( 'option' );
											opt.setAttribute( "value", info[i].id );
											opt.appendChild( document.createTextNode( info[i].title ) );
											el.appendChild( opt );
										}
									}
								} else { currHelpList.hide(); }
							}
						},
						onFailure: function() {
							currHelpList.hide();
						}
					}
				);
			} else {
				this.hide();
			}
			return false;
		}
	},

	// Hide pop-up list.
	hide: function() {
		if ( this.m_current != this.m_parent && this.m_current != this.m_popup ) {
			el = $( this.m_popup );
			if ( el ) { el.hide(); }
		}
	},

	// Put selected element into area.
	select: function( o ) {
		el = $( this.m_parent );
		el.value = o.options[o.selectedIndex].innerHTML;
		this.blur();
	},

	// Blur.
	blur: function( e ) {
		this.m_current = '';
		setTimeout( this.m_name + ".hide()", this.m_sleep );
	},

	// Focus.
	focus: function( e ) {
		this.m_current = e.id;
	},

	// Keyup.
	keyup: function( e ) {
		this.m_current = this.m_parent;
		if ( !e ) e = window.event;
		if ( e.keyCode == 40 ) {
			el = $( this.m_popup );
			if ( el ) {
				el.focus();
				el.selectedIndex = 0;
			}
		} else if ( e.keyCode == 27 ) {
			this.blur();
		} else {
			this.help();
		}
	},

	// Keyup on pop-up list.
	list_keyup: function( o, e ) {
		if ( !e ) e = window.event;
		if ( e.keyCode == 13 ) {
			elem = $( this.m_parent );
			if ( elem ) {
				elem.value = el.options[el.selectedIndex].text;
				this.blur();
			}
		} else if ( e.keyCode == 27 ) {
			this.blur();
		}
	}

};


/*
var currHelpList = null;

function hlGlobal( e ) {
	currHelpList = e;
	return false;
}

function HelpList( parent_el, popup_el, uri, el_name ) {
	this.m_parent = parent_el;
	this.m_popup = popup_el;
	this.m_uri = uri;
	this.m_name = el_name;
	this.m_current = parent_el;
	this.m_sleep = 150;
	hlGlobal( this );
	return false;
}

function hlHelp(e) {
	hlGlobal( this );
	var e_popup = document.getElementById( this.m_popup );
	if ( e_popup ) {
		var el = document.getElementById( this.m_parent );
		var v = el.value;
		v = v.trim();
		if ( v.length > 0 ) {
			initRequest();
			if ( my_req ) {
				my_req.onreadystatechange = back_hlHelp;
				my_req.open("GET", this.m_uri + v, true);
				my_req.send(null);
				reqTimeout = setTimeout("my_req.abort();", reqAbortTime);
			}
		} else if ( v.length == 0 ) {
			this.hide();
		}
		return false;
	}
}

function back_hlHelp() {
	if (my_req.readyState == 4) {
		clearTimeout(reqTimeout);
		if (my_req.status == 200) {
			eval('var response = ('+my_req.responseText+')');
			info = response.info;
			el = document.getElementById ( currHelpList.m_popup );
			if ( el ) {
				p = document.getElementById ( currHelpList.m_parent );
				el.style.width = p.clientWidth + 'px';
				if ( info.length > 1 ) {
					// coordinates
					coord = getElementPosition ( currHelpList.m_parent );
					iPosX = coord.left;
					iPosY = coord.top;
					el.style.top = (iPosY + 22) + "px";
					el.style.left = (iPosX + 1) + "px";
					// visibility
					el.style.display = "block";
					// add new data
					while( el.childNodes.length > 0 ) el.removeChild( el.lastChild );
					for( i = 0; i < info.length; i++ ) {
						if ( info[i].title != '' ) {
							opt = document.createElement( 'option' );
							opt.setAttribute("value", info[i].id);
							opt.setAttribute("onclick", currHelpList.m_name + ".select(this);" );
							opt.appendChild( document.createTextNode(info[i].title) );
							el.appendChild( opt );
						}
					}
				} else { currHelpList.hide(); }
			}
		}
	}
	return false;
}

function hlHide() {
	if ( this.m_current != this.m_parent && this.m_current != this.m_popup ) {
		el = document.getElementById( this.m_popup );
		if ( el ) {
			el.style.display = "none";
		}
	}
}

function hlSelect(o) {
	el = document.getElementById( this.m_parent );
	el.value = o.innerHTML;
	this.blur();
}

function hlBlur(e) {
	this.m_current = '';
	setTimeout( currHelpList.m_name + ".hide()", this.m_sleep );
}

function hlFocus(e) {
	this.m_current = e.id;
}

function hlKeyUp( e ) {
	this.m_current = this.m_parent;
	if ( !e ) e = window.event;
	if ( e.keyCode == 40 ) {
		el = document.getElementById( this.m_popup );
		if ( el ) {
			el.focus();
			el.selectedIndex = 0;
		}
	} else if ( e.keyCode == 27 ) {
		this.blur();
	} else {
		this.help();
	}
}

function hlListkeyUp( el, e ) {
	if ( !e ) e = window.event;
	if ( e.keyCode == 13 ) {
		elem = document.getElementById( this.m_parent );
		if ( elem ) {
			elem.value = el.options[el.selectedIndex].text;
			this.blur();
		}
	} else if ( e.keyCode == 27 ) {
		this.blur();
	}
}

HelpList.prototype.help = hlHelp;
HelpList.prototype.hide = hlHide;
HelpList.prototype.select = hlSelect;
HelpList.prototype.blur = hlBlur;
HelpList.prototype.focus = hlFocus;
HelpList.prototype.keyup = hlKeyUp;
HelpList.prototype.list_keyup = hlListkeyUp;
*/

/** Создает popup-подсказки для поля ввода города и названия банка **/
var hlCity = new HelpList( 'id_bs_city', 'id_bs_popup', 'http://www.bankir.ru/bank/backend/load_city_title/?city=', 'hlCity' );
var hlTitle = new HelpList( 'id_bs_title', 'id_bs_popup', 'http://www.bankir.ru/bank/backend/load_bank_title/?city=', 'hlTitle' );
var hlLTitle = new HelpList( 'id_bs_title', 'id_bs_popup', 'http://www.bankir.ru/bank/backend/load_liquidate_bank_title/?city=', 'hlLTitle' );

/** Скрывает/отображает форму изменения параметров поиска (кредиты/вклады/переводы) **/
function changeSearchForm(t) {
	e = $( 'change_search_param' );
	if ( e.visible() ) {
		e.hide();
		t.addClassName( 'search_open' );
		t.update( 'Изменить параметры поиска' );
	} else {
		e.show();
		t.removeClassName( 'search_open' );
		t.update( 'Скрыть' );
	}
}

/** Прячет/показывает меню кредитов/вкладов **/
function cd_menu( el, el2 ) {
	o = $( el );
	div = $( el2 );
	var span = o.parentNode;
	if ( div.visible() ) {
		div.hide();
		span.removeClassName( 'left_subsublist_open' );
		span.addClassName( 'left_subsublist_close' );
	} else {
		div.show();
		span.removeClassName( 'left_subsublist_close' );
		span.addClassName( 'left_subsublist_open' );
	}
}

/** Прячет/показывает слои на странице банка **/
function bank_layer( o, el ) {
	ins = o;
	div = $( el );
	if ( div.visible() ) {
		div.hide();
		ins.removeClassName( 'bank_info_button_open' );
		ins.addClassName( 'bank_info_button' );
		ins.innerHTML = 'Раскрыть';
	} else {
		div.show();
		ins.removeClassName( 'bank_info_button' );
		ins.addClassName( 'bank_info_button_open' );
		ins.innerHTML = 'Свернуть';
	}
}

/** Очищает поля ввода от предустановленных значений. **/
function clearField( el, deftxt ) {
	if ( el.value == deftxt )
		el.value = '';
	else if ( el.value == '' )
		el.value = deftxt;
}

/** Скрывает/отображает информацию доп. офисе или опер. кассе **/
function showBO( id ) {
	b = $( 'm_'+id );
	i = $( 'img_'+id );
	if ( b.visible() ) {
		b.hide();
		i.removeClassName( 'open' );
		i.addClassName( 'close' );
	} else {
		b.show();
		i.removeClassName( 'close' );
		i.addClassName( 'open' );
	}
}

/** Загружает и показывает/скрывает список филиалов банка для TOP-50 **/
var banks_loaded = new Hash();
var curr_bank = 0;

function load_branches( id ) {
	curr_bank = id;
	len_subs = banks_loaded.get( id );
	if ( len_subs > 0 ) {
		/** Данные уже были загружены - скрываем или отображаем банки **/
		if ( len_subs - 1 == 0 ) { return false; }
		el = $( 'tr_' + curr_bank );
		img = $( 'img_' + curr_bank );
		tbl = $( 'id_banks_list' );
		if ( el && tbl && img ) {
			if ( el.name == 'open' ) {
				// Скрываем
				el.name = 'close';
				img.removeClassName( 'filial_open' );
				img.addClassName( 'filial_close' );
				for ( i = 0; i < len_subs-1; i++ ) { tbl.rows[el.rowIndex + i + 1].style.display = 'none'; }
			} else {
				// Отображаем
				el.name = 'open';
				img.removeClassName( 'filial_close' );
				img.addClassName( 'filial_open' );
				tr_show = ( isMSIE ) ? 'block' : 'table-row';
				for ( i = 0; i < len_subs-1; i++ ) { tbl.rows[el.rowIndex + i + 1].style.display = tr_show; }
			}
		}
	} else {
		/** Загружаем данные с сервера **/
		new Ajax.Request(
			'http://www.bankir.ru/bank/backend/load_branches/?bank='+id,
			{
				method: 'get',
				onSuccess: function( transport ) {
					response = transport.responseText.evalJSON();
					info = response.info;
					info_len = info.length;
					banks_loaded.set( curr_bank, info_len );
					info_len--;
					if ( info_len > 0 ) {
						el = $( 'tr_' + curr_bank );
						parent_site = el.childElements()[2].childElements()[0].readAttribute( 'href' );
						img = $( 'img_' + curr_bank );
						tbl = $( 'id_banks_list' );
						if ( el && tbl && img ) {
							img.removeClassName( 'filial_close' );
							img.addClassName( 'filial_open' );
							el.name = 'open';
							for ( var i = 0; i < info_len; i++ ) {
								if ( info[i].id != 0 ) {
								
									var tr = tbl.insertRow( el.rowIndex + i + 1 );
									if ( i % 2 ) { tr.className = 'odd' }
									
									td1 = tr.insertCell( 0 );
									ins = new Element( 'ins' );
									a = new Element( 'a', { href: 'http://www.bankir.ru/bank/' + info[i].id } ).update( info[i].title );
									a.innerHTML = info[i].title;
									ins.appendChild( document.createTextNode( (i + 1) + '. ' ) );
									ins.appendChild( a );
									td1.appendChild( ins );
									
									td2 = tr.insertCell( 1 );
									td2.appendChild( document.createTextNode( info[i].regn ) );
									
									td3 = tr.insertCell( 2 );
									url = ( info[i].url == '' ) ? parent_site : info[i].url;
									a = new Element( 'a', {href: url, target: '_blank', title: 'Перейти на сайт банка'} ).update( parent_site );
									a.innerHTML = parent_site;
									td3.appendChild( a );
									
									td4 = tr.insertCell( 3 );
									td4.appendChild( document.createTextNode( info[i].city ) );
									
								}
							}
						}
					}
				},
				onFailure: function() {
					alert( 'Fail!' );
				}
			}
		);
	}
}

/** Показывает форму для выбора периода на странице финансовых показателей **/
function showPeriodForm() {
	e = $( 'period_form' );
	if ( !e.visible() ) {
		e.show();
		$('period_btn').hide();
	}
}

/** Добавляет строку в таблицу заполнения валют банков **/
function add_kurs_row() {
	var last_tr = $('id_last_row');
	if ( last_tr ) {
		var row = $( 'id_row' ).cloneNode( true );
		row.id = '';
		last_tr.insert( { before: row } );
	}
}

/** Удаляет строку в таблице **/
function del_kurs_row(e) {
	row = e.parentNode.parentNode;
	if ( row.id != 'id_row' ) row.remove();
}

/** Проверяет корректны ли введенные значения **/
function check_float( e ) {
	var val = parseFloat( e.value );
	if ( isNaN(val) ) val = 0.0;
	e.value = val;
}