function openPrintWindow( pageToLoad, width, height) {
  xposition=0; yposition=0;
  if ((parseInt(navigator.appVersion) >= 4 ) ) {
   xposition = (screen.width - width) / 2;
   yposition = (screen.height - height) / 2;
  }
  args = "width=" + width + ","
  + "height=" + height + ","
  + "location=0,"
  + "menubar=1,"
  + "resizable=1,"
  + "scrollbars=1,"
  + "status=0,"
  + "titlebar=0,"
  + "toolbar=1,"
  + "hotkeys=0,"
  + "screenx=" + xposition + "," //NN Only
  + "screeny=" + yposition + "," //NN Only
  + "left=" + xposition + "," //IE Only
  + "top=" + yposition; //IE Only
  window.open( pageToLoad, 'print', args );
}



function atoprint(aId) {
		var atext = document.getElementById(aId).innerHTML;
		var captext = window.document.title;
		var alink = window.document.location;
		var prwin = open('');
		prwin.document.open();
		prwin.document.writeln('<html><head><title>Версия для печати<\/title><link rel="stylesheet" type="text/css" href="/main/print.css" \/><\/head><body text="#000000" bgcolor="#FFFFFF" style="padding: 40px;"><div id="itog" onselectstart="return false;" oncopy="return false;">');
		prwin.document.writeln('<div style="margin-bottom:5px;"><a href="javascript://" onclick="window.print();">Печать<\/a> &bull; <a href="javascript://" onclick="window.close();">Закрыть окно<\/a><\/div><hr>');
		prwin.document.writeln('<h4>'+captext+'<\/h4>');
		prwin.document.writeln(atext);
		prwin.document.writeln('<hr><div style="font-size:8pt;margin-top:20px;">Отложенные книги<\/div>');
		prwin.document.writeln('<div style="font-size:8pt;">Страница: '+alink+'<\/div>');
		prwin.document.writeln('<div style="margin-top:5px;"><a href="javascript://" onclick="window.print();">Печать<\/a> &bull; <a href="javascript://" onclick="window.close();">Закрыть окно<\/a><\/div>');
		prwin.document.writeln('<\/div><\/body><\/html>');
	}

function sendSubscribeForm( form ){
	if( trim( form['Email'].value ) == '' ) 
		{ alert( 'Поле Email должно быть заполнено' ); form['Email'].focus(); return false; }
	form.action = "/index.html?id=103";
   	form.submit();	
}

function searchfClick(f){
	/*var f = document.forms[a];*/ 
	if( ( trim( f['Query'].value ) == '' ) || ( f['Query'].value == 'Поиск по сайту' ) ){
		alert('Укажите ключевые слова для поиска');
		return false;
	}
	ignoreBodyClick = true;
	f.submit();
	return true;
}

function getBodyHeight() {
	if (self.innerWidth) return self.innerHeight;
	else if (document.documentElement && document.documentElement.clientWidth) return document.documentElement.clientHeight;
	else if (document.body) return document.body.clientHeight;
}

function getBodyWidth() {
	if (self.innerWidth) return self.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth) return document.documentElement.clientWidth;
	else if (document.body) return document.body.clientWidth;
}

function setCookie(sName, sValue)
{
  document.cookie = sName + "=" + escape(sValue) + ";expires=Mon, 3 Dec 2040 23:59:59 UTC;path=/;";
}

function getCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}


function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}



function searchClick(){
	var query = trim( document.getElementById('query').value );
	if( query == '' ){
		alert('Введите одно или несколько слов');
		return false;
	}
	var fieldPerson = searchFieldValue('Person');
	var fieldAuthor = searchFieldValue('Author');
	var fieldTitle = searchFieldValue('Title');
	var fieldKeyWords = searchFieldValue('KeyWords');
	var fieldGeo = searchFieldValue('Geo');
	if( !fieldPerson && !fieldAuthor && !fieldTitle && !fieldKeyWords && !fieldGeo ){
		alert("Выберите поля поиска");
		return false;
	}
	document.location.href = "index.php?id=1&Query="+query+"&Author="+fieldAuthor+"&Title="+fieldTitle+"&KeyWords="+fieldKeyWords+"&Person="+fieldPerson+"&Geo="+fieldGeo;
}

function searchFieldValue( field ){
	var cb = document.getElementById('field'+field);
	if( cb.checked )
		return 1;
	else
		return 0;
}

function selectDistrict( district ){
	document.location.href = "index.php?id=9&District=" + district;
}

function updateSearchCaption(){
	var form = document.getElementById('searchForm');
	var caption = "";
	switch ( radioValue( form, 'SearchBy' ) ){
	 	case "Title":
	 		caption = "Название";
	 		break;
	 	case "Author":
	 		caption = "Автор";
	 		break;
	 	case "KeyWords":
	 		caption = "Ключевые слова";
	 		break;
	 }
	document.getElementById('searchCaption').innerHTML = caption + ':';
}

function expandCollapse() {
	for (var i=0; i<expandCollapse.arguments.length; i++) {
		var element = document.getElementById(expandCollapse.arguments[i]);
		element.style.display = (element.style.display == "none") ? "block" : "none";
	}
}

function showSearchExample( sample ){
	var form = document.getElementById('searchForm');
	form['Query'].value = sample;
	submitSearch();
}

function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + url_encode(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

// Инициализируем таблицу перевода
var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
  trans[i] = i - 0x350; // А-Яа-я
trans[0x401] = 0xA8;    // Ё
trans[0x451] = 0xB8;    // ё

// Переопределяем функцию escape()
function url_encode(str)
{
  var ret = [];
  // Составляем массив кодов символов, попутно переводим кириллицу
  for (var i = 0; i < str.length; i++)
  {
    var n = str.charCodeAt(i);
    if (typeof trans[n] != 'undefined')
      n = trans[n];
    if (n <= 0xFF)
      ret.push(n);
  }
  return window.escape(String.fromCharCode.apply(null, ret));
}

function showAdvSearch(){
	document.getElementById('on').style.display = 'none';
	document.getElementById('help').style.display = 'none';
	document.getElementById('expand').style.display = 'block';
	document.getElementById('tabSimple').className = 'advanced';
	document.getElementById('tabHelp').className = 'advanced';
	document.getElementById('tabAdv').className = 'active';
	document.getElementById('SearchMode').value = 'advanced';
	document.getElementById('SearchQuery').style.display = 'none';
	fillSearchFields();
	rememberSearch();
}

function showSimpleSearch(){
	document.getElementById('expand').style.display = 'none';
	document.getElementById('help').style.display = 'none';
	document.getElementById('on').style.display = 'block';
	document.getElementById('tabSimple').className = 'active';
	document.getElementById('tabHelp').className = 'advanced';
	document.getElementById('tabAdv').className = 'advanced';
	document.getElementById('SearchMode').value = 'simple';
	document.getElementById('SearchQuery').style.display = '';
	rememberSearch();
	var form = document.getElementById('searchForm');
	switch( radioValue( form, 'SearchBy' ) ){
		case 'Author':
			form['Query'].value = form['Author'].value;
			break;
		case 'Title':
			form['Query'].value = form['Title'].value;
			break;
		case 'KeyWords':
			form['Query'].value = form['KeyWords'].value;
			break;
	}
}

function showHelpSearch(){
	document.getElementById('expand').style.display = 'none';
	document.getElementById('on').style.display = 'none';
	document.getElementById('help').style.display = 'block';
	document.getElementById('tabSimple').className = 'advanced';
	document.getElementById('tabAdv').className = 'advanced';
	document.getElementById('tabHelp').className = 'active';
}



function showSearch(){
	expandCollapse('expand', 'on');
	document.getElementById('SearchMode').value = 'advanced';
	document.getElementById('SearchQuery').style.display = 'none';
	document.getElementById('searchCaption').style.visibility = 'hidden';
	document.getElementById('SearchBaseTitle').style.display = '';
	document.getElementById('SearchBase').style.width = '200px';
	fillSearchFields();
	rememberSearch();
}

function hideSearch(){
	expandCollapse('expand', 'on');
	document.getElementById('SearchMode').value = 'simple';
	document.getElementById('SearchQuery').style.display = '';
	document.getElementById('searchCaption').style.visibility = 'visible';
	document.getElementById('SearchBaseTitle').style.display = 'none';
	document.getElementById('SearchBase').style.width = '';
	rememberSearch();
	var form = document.getElementById('searchForm');
	switch( radioValue( form, 'SearchBy' ) ){
		case 'Author':
			form['Query'].value = form['Author'].value;
			break;
		case 'Title':
			form['Query'].value = form['Title'].value;
			break;
		case 'KeyWords':
			form['Query'].value = form['KeyWords'].value;
			break;
	}
}

function initSearchForm(){
	var form = document.getElementById('searchForm');
	if(form.Base.value == 'Books'){
		form.action = 'index.php?id=1';
	}
	/*else{
		form.action = '/main/searchArticles.html';
		$('rowNumber').style.display = '';
		$('rowPlace').style.display = '';
		$('rowSource').style.display = '';
	} */
	//updateSearchCaption();
}

function rememberSearch(){
	var expdate = new Date();
	expdate.setTime(expdate.getTime()+(12*30*24*60*60*1000)); // ~1 year
	if( document.getElementById('expand').style.display == 'block' )
		setCookie( "SM", "extended", expdate );
	else
		setCookie( "SM", "simple", expdate );
}

function fillSearchFields(){
	var form = document.getElementById('searchForm');
	switch( radioValue( form, 'SearchBy' ) ){
		case 'Author':
			form['Author'].value = form['Query'].value;
			break;
		case 'Title':
			form['Title'].value = form['Query'].value;
			break;
		case 'KeyWords':
			form['KeyWords'].value = form['Query'].value;
			break;
	}
}

// check that at least one radio is checked
function radioValue( form, radioName )
{
	result = '';
	for( i=0; i < form.length; i++ )
	{
		var element=form.elements[i];
	  	if( element.name == radioName )
	  	{
	  		if( element.type.toLowerCase() == "radio" )
	  		{
	  			if( element.checked )
	    			result = element.value;
	  		}
	  		else
    			result = element.value;
	  	}
	}
	return result;
}

function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}

function submitSearch(){
	var form = document.getElementById('searchForm');
	if( form['SearchMode'].value == 'simple' ){
		if( trim( form['Query'].value ) == '' ){
			alert('Введите запрос');
			form['Query'].focus();
			return false;
		}
		form['Author'].value = '';
		form['Title'].value = '';
		form['KeyWords'].value = '';
		form['Geo'].value = '';
		form['Person'].value = '';
		form['PublishPlace'].value = '';
		form['PublishDate'].value = '';
		fillSearchFields();
	}else{
		if( ( trim( form['Author'].value ) == '' )
		&& ( trim( form['Title'].value ) == '' )
		&& ( trim( form['KeyWords'].value ) == '' )
		&& ( trim( form['Geo'].value ) == '' )
		&& ( trim( form['PublishPlace'].value ) = '' )
		&& ( trim( form['PublishDate'].value ) == '' )
		&& ( trim( form['Person'].value ) == '' ) ){
			alert('Введите условие поиска');
			return false;
		}
	}
	form.submit();
}

function queryKeyPress(e){
	e = e || window.event;
	var code = e.keyCode || e.which;
    if( code == 13 )
		submitSearch();
}

function toggleBook( checkbox, base ){

         $.ajax({
	  url:	  '/ajax/toggleBook.php?DocID='+checkbox.value+'&Checked='+checkbox.checked+'&Base='+base,
	  type:	  'GET',
	  /*dataType: 'JSON',*/
	  success: function(response, code){ var itog = response.split('|'); document.getElementById('basketText').innerHTML = itog[1];},
	  error:  function(xhr, str){
	    alert('Возникла ошибка: ' + str);
	  }
        });

	/*new Ajax.Request('/ajax/toggleBook.html?DocID='+checkbox.value+"&Checked="+checkbox.checked+'&Base='+base, {
	  onSuccess: toggleBookSuccess
	});*/
}

function toggleBookSuccess( transport ){
	var response = transport.responseText.evalJSON();
	document.getElementById('basketText').innerHTML = response.BasketText;
}

function clearBasket(base){
	var form = document.getElementById('booksForm');
	for( var n = 0; n < form.length; n++ ){
		var input = form[n];
		if( input.type == 'checkbox' )
			input.checked = false;
	}

        $.ajax({
	  url:	  '/ajax/clearBasket.html?Base='+base,
	  type:	  'GET',
	  /*dataType: 'JSON',*/ 
	  success: function(response, code){ var itog = response.split('|'); document.getElementById('basketText').innerHTML = itog[1];},
	  error:  function(xhr, str){
	    alert('Возникла ошибка: ' + str);
	  }
        });

	/*new Ajax.Request('/ajax/clearBasket.html?Base='+base, {
	  onSuccess: toggleBookSuccess
	}); */
}

function inputFocused( input ){
	var form = document.getElementById('searchForm');
	var base;
	if(form.Base.value == 'Books')
		base = 'marc';
	else
		base = 'articles';

        $.ajax({
	  url:	  '/ajax/suggest.html?Field='+input.name+'&base='+base+'&',
	  type:	  'GET',
	  /*dataType: 'JSON',*/ 
	  success: function(response, code){ 
	    if (code==200){
	      alert('Сервер вернул: ' + response);
	    } else {
	      alert('Нет подходящих записей');
	    }
	  },
	  error:  function(xhr, str){
	    alert('Возникла ошибка: ' + xhr.responseCode);
	  }
        });


	/*var options = {
		script:'/ajax/suggest.html?Field='+input.name+'&base='+base+'&',
//		script:'/autocomplete/test.php?json=true&',
		varname:'Query',
		json:true,
		shownoresults:true,
		noresults:'Нет подходящих записей',
		maxentries:200,
		timeout:5000,
		maxheight:100,
		valueSep:''
	};
	var json=new AutoComplete(input.id,options);*/
}

function morphBig(){
	setTimeout( "morphBigEvent()", 100 );
};

function morphSmall(){
	setTimeout( "morphSmallEvent()", 100 );
};

function morphSmallEvent(){
	$('morpher').morph( {backgroundColor: '#fff', height: '200px', width: '530px', overflow: 'hidden', border: '1px solid #cbcbcb', margin: '0px', padding: '5px', position: 'absolute', zIndex: '1000' });
};


function morphBigEvent(){
	$('morpher').morph( {padding: '5px', height: '600px', width: '950px', marginTop: '-400px', marginLeft: '-370px', marginRight: '-50px', border: '1px solid #cbcbcb', position: 'absolute' });
//	$('morpher').morph('padding: 5px; height: 600px; width: 950px; margin-top: -400px; margin-left: -370px; margin-right: -50px; border: 1px solid #cbcbcb; position: absolute;');
}

function saveNameNumber(){
	var expdate = new Date();
	expdate.setTime(expdate.getTime()+(12*30*24*60*60*1000)); // ~1 year
	$('email').value = trim($('email').value);
	$('lastName').value = trim($('lastName').value);
	$('number').value = trim($('number').value);
	$('phone').value = trim($('phone').value);
	$('selbibl').value = trim($('selbibl').value);
	setCookie("LastName", $('lastName').value, expdate);
	setCookie("Number", $('number').value, expdate);
	setCookie("Email", $('email').value, expdate);
	setCookie("Phone", $('phone').value, expdate);
	setCookie("Selbibl", $('selbibl').value);
}

function goReserve(){
	saveNameNumber();
	if(($('email').value == '') && ($('phone').value == '')){
		alert('Укажите email или телефон для связи');
		$('email').focus();
		return false;
	}
	if($('lastName').value == ''){
		alert('Укажите фамилию');
		$('lastName').focus();
		return false;
	}
/*	if($('number').value == ''){
		alert('Укажите номер читательского билета');
		$('number').focus();
		return false;
	}*/
	return true;
}

