jQuery(function($) {
	var showParams = "Полное биб. описание";
	var hideParams = "Скрыть описание";
	var searchRequestFlag = 0;
	var cur_page = 0;
	var step_pagination = 10;
	var left_border = 1;
	var right_border = left_border + step_pagination - 1;
	var prev_params_obj;
	var params_obj;
	var time = new Date().getTime();
	var address = "/search_result.php";
	
	var idxs = [ "IDX100a", "IDX245a", "IDX653a", "IDX020a", "IDX260a",
			"IDX440a", "IDX650b", "IDX773t", "IDX998a", "IDX260c_lower",
			"IDX260c_upper" ]; // задаем массив всех возможных id полей ввода
	$.ajaxSetup( {
		scriptCharset : "utf-8"
	});

	var type_search_var = $("#type-search").attr("value");

	function setNumAdded() {
		var added = $.cookie("list");
		var num = 0;
		if ((added != null) && (added != "")) {
			added = added.split(":");
			num = added.length - 1;
		}
		$("#num-added").html(num);
	}
	setNumAdded();

	function ajaxRequest(params_obj, address) {
		searchRequestFlag = 1;
		if (params_obj['alphabet'] == 'yes') {	
			$.get(address, params_obj, function(data) {
				$("#container").html(printAphs(data));
				showPagination(data);
			}, "xml");
		} else {
			$.get(address, params_obj, function(data) {
				$("#container").html(printLIs(data));
				showPagination(data);
			}, "xml");
		}
	}
	
	function movePageWindow(direction) {
		if (direction == "left") {
			left_border -= step_pagination;
			right_border -= step_pagination;
			left_border++;
			right_border++;
		}
		if (direction == "right") {
			left_border += step_pagination;
			right_border += step_pagination;
			left_border--;
			right_border--;
		}
	}
	$("input[name=IDX020a]").autoComplete( {
		ajax : "ajax_response.php",
		delay : 200,
		minChars : 1,
		postData : {
			type_search : type_search_var,
			table : "IDX020a"
		}
	});
	$("input[name=IDX100a]").autoComplete( {
		ajax : "ajax_response.php",
		delay : 200,
		minChars : 1,
		postData : {
			type_search : type_search_var,
			table : "IDX100a"
		}
	});
	$("input[name=IDX245a]").autoComplete( {
		ajax : "ajax_response.php",
		delay : 200,
		minChars : 1,
		postData : {
			type_search : type_search_var,
			table : "IDX245a"
		}
	});
	$("input[name=IDX260a]").autoComplete( {
		ajax : "ajax_response.php",
		delay : 200,
		minChars : 1,
		postData : {
			type_search : type_search_var,
			table : "IDX260a"
		}
	});
	$("input[name=IDX440a]").autoComplete( {
		ajax : "ajax_response.php",
		delay : 200,
		minChars : 1,
		postData : {
			type_search : type_search_var,
			table : "IDX440a"
		}
	});
	$("input[name=IDX650b]").autoComplete( {
		ajax : "ajax_response.php",
		delay : 200,
		minChars : 1,
		postData : {
			type_search : type_search_var,
			table : "IDX650b"
		}
	});
	$("input[name=IDX653a]").autoComplete( {
		ajax : "ajax_response.php",
		delay : 200,
		minChars : 1,
		postData : {
			type_search : type_search_var,
			table : "IDX653a"
		}
	});
	$("input[name=IDX773t]").autoComplete( {
		ajax : "ajax_response.php",
		delay : 200,
		minChars : 1,
		postData : {
			type_search : type_search_var,
			table : "IDX773t"
		}
	});
	$("input[name=IDX998a]").autoComplete( {
		ajax : "ajax_response.php",
		delay : 200,
		minChars : 1,
		postData : {
			type_search : type_search_var,
			table : "IDX998a"
		}
	});
	$("input[name=clear]").click(function() {
		$("input[name=IDX100a]").val("");
		$("input[name=IDX245a]").val("");
		$("input[name=IDX653a]").val("");
		$("input[name=IDX020a]").val("");
		$("#IDX260c_lower").attr("value", "");
		$("#IDX260c_upper").attr("value", "");
		$("#container").html("");
		$("#search-params").html("");
		$("#go-up").hide();
		$(".pagination").html("");
		left_border = 1;
		right_border = left_border + step_pagination - 1;
	});

	$(".button").live("click", function() {
		$(".extended").animate( {
			opacity : "hide",
			top : "-10"
		}, "fast");
		$(this).prev(".extended").animate( {
			opacity : "show",
			top : "0"
		}, "slow");
	});

	$(".close").live("click", function() {
		$(".extended").animate( {
			opacity : "hide",
			top : "-10"
		}, "fast");
	});

	function min(x, y) {
		if (x < y) {
			return x;
		} else {
			return y;
		}
	}

	function showPagination(data) {
		var inner_text = "";
		var found = $("items_found", data).text();
		var step = $("step", data).text();
		var count = parseInt(found / step);
		if ((found / step) > count) {
			count++;
		}
		var current = ($("begin_item_pos", data).text() / step) + 1;
		cur_page = current;
		if (count > 1) {
			if ((current >= right_border) && (current != count)) {
				movePageWindow("right");
			} else {
				if ((current <= left_border) && (current != 1)) {
					movePageWindow("left");
				}
			}
			if (current != 1) {
				inner_text += "<a href=\"#\" id=\"prev\"> ";
				inner_text += " Предыдущая ";
				inner_text += " </a>";
			}
			for ( var i = left_border; i <= min(count, right_border); i++) {
				if (i != current) {
					inner_text += "<a href=\"#\" class=\"page\">" + i + "</a>";
				} else {
					inner_text += "<b>" + i + "</b>";
				}
			}
			if (current != count) {
				inner_text += "<a href=\"#\" id=\"next\">";
				inner_text += " Следующая ";
				inner_text += " </a>";
			}
		}
		$(".pagination").html(inner_text);
	}

	$("#prev").live("click", function() {
		var ind = cur_page - 1;
		params_obj["num_page"] = ind - 1;
		ajaxRequest(params_obj, address);
	});

	$("#next").live("click", function() {
		var ind = cur_page + 1;
		params_obj["num_page"] = ind - 1;
		ajaxRequest(params_obj, address)
	});

	$(".page").live("click", function() {
		var ind = $(this).text();
		params_obj["num_page"] = ind - 1;
		ajaxRequest(params_obj, address);
		refreshForm(params_obj);
	});

	function refreshForm(params_) {
		var num = 0;
		for ( var i = 0; i < idxs.length; i++) {
			if ($("#" + idxs[i]).length) {
				var re1 = new RegExp(/upper/);
				var re2 = new RegExp(/lower/);
				if ((re1.exec(idxs[i]) == null) && (re2.exec(idxs[i]) == null)) {
					$("#" + idxs[i]).attr(
							"value",
							params_["var" + num].substring(8, params_["var"
									+ num].length));
				}
				num++;
			}
		}
	}

	function printLIs(data) {
		var t_date = new Date();
		time = t_date.getTime() - time;
		time = time / 1000;
		var result = "";
		var num = $("begin_item_pos", data).text();
		num++;
		var y_l = $("year_lower", data).text();
		var y_u = $("year_upper", data).text();
		if (($("#IDX260c_lower").attr("value") != '')
				|| ($("#IDX260c_upper").attr("value") != '')) {
			$("#IDX260c_lower").attr("value", y_l);
			$("#IDX260c_upper").attr("value", y_u);
		}
		$("node", data)
				.each(
						function() {
							result = result + "<li class =\"pane\">";
							result = result + "<div class=\"short\">";
							
							if ($("tag510a", this).text() != "") {
								img = $("tag510a", this).text();
								result = result
										+ '<a href="" class="full-img"><img class="thumb" src="/image.php?size=small&name='
										+ img + '" /></a>';
							} else {
								result = result
								+ '<img class="thumb" src="/image.php?size=small&name=no_image.jpg" />';
							}
							
							
							//result = result + num + ". ";
							if ($("tag100a", this).text() != "") {
								result = result + "<b>"
										+ $("tag100a", this).text() + "</b>, ";
							}
							if ($("tag700a", this).text() != "") {
								result = result + "<b>"
										+ $("tag700a", this).text() + "</b>, ";
							}
							if ($("tag245a", this).text() != "") {
								result = result + $("tag245a", this).text();
							}
							result += ": ";
							if ($("tag245b", this).text() != "") {
								result = result + $("tag245b", this).text();
							}
							if ($("tag260a", this).text() != "") {
								result = result + " - ";
								result = result + $("tag260a", this).text();
							}
							if ($("tag260c", this).text() != "") {
								result = result + " - ";
								result = result + $("tag260c", this).text();
							}
							result = result + "</div>";
							
							
							
							result = result + "<div class=\"extended\">";
							result = result + "<b>" + $("tag090a", this).text()
									+ "</b>";
							result = result + "<br />";
							result = result + "<b>" + $("tag090x", this).text()
									+ "</b>";
							result = result + "<br /><br />";
							if ($("tag100a", this).text() != "") {
								result = result + "<b>"
										+ $("tag100a", this).text() + "</b> ";
							}
							if ($("tag700a", this).text() != "") {
								result = result + "<b>"
										+ $("tag700a", this).text() + "</b> ";
							}
							if ($("tag245a", this).text() != "") {
								result = result + $("tag245a", this).text();
							}
							result = result + " ";
							if ($("tag245b", this).text() != "") {
								result = result + $("tag245b", this).text();
							}
							result = result + " ";
							if ($("tag245c", this).text() != "") {
								result = result + "/ ";
								result = result + $("tag245c", this).text();
								result = result + " ";
							}

							if ($("tag245n", this).text() != "") {
								result = result + " ";
								result = result + $("tag245n", this).text();
								result = result + ", ";
							}
							result = result + " ";
							if ($("tag260a", this).text() != "") {
								result = result + "- ";
								result = result + $("tag260a", this).text();
								result = result + ": ";
							}
							if ($("tag260b", this).text() != "") {
								result = result + $("tag260b", this).text();
								result = result + " ";
							}
							if ($("tag260c", this).text() != "") {
								result = result + $("tag260c", this).text();
								result = result + ". ";
							}
							if ($("tag300a", this).text() != "") {
								result = result + " - ";
								result = result + $("tag300a", this).text();
								result = result + "   ";
							}
							if ($("tag300b", this).text() != "") {
								result = result + " : ";
								result = result + $("tag300b", this).text();
							}
							if ($("tag440a", this).text() != "") {
								result = result + " - (";
								result = result + $("tag440a", this).text();
								if ($("tag440v", this).text() != "") {
									result = result + "; ";
									result = result + $("tag440v", this).text();
								}
								result = result + ").";
							}
							if ($("tag020a", this).text() != "") {
								result = result + "- ISBN ";
								result = result + $("tag020a", this).text();
							}
							if ($("tagT876c:first", this).text() != "") {
								result = result + ": "
										+ $("tagT876c:first", this).text();
							}

							if ($("tag773t", this).text() != "") {
								result = result + ' // ';
								result = result + $("tag773t", this).text();
							}
							if ($("tag773d", this).text() != "") {
								result = result + '. - ';
								result = result + $("tag773d", this).text();
							}
							if ($("tag773g", this).text() != "") {
								result = result + '. - ';
								result = result + $("tag773g", this).text();
							}
							if ($("tag505a", this).text() != "") {
								result = result + "<br /><br />";
								result = result
										+ "<b>Форматированное содержание: </b>";
								result = result + $("tag505a", this).text();
							}
							if ($("tag653a", this).text() != "") {
								result = result + "<br /><br />";
								result = result + "<b>Ключевые слова: </b>";
								result = result + $("tag653a", this).text();
							}
							result = result + "<br /><br />";
							if ($("inv", this).length) {
								result = result
										+ "<table class=\"inv\"><tr><td>Инвентарный №</td><td>сигла хранения</td></tr>";
								$("inv", this)
										.each(
												function() {
													result = result + "<tr>";
													result = result + "<td>";
													if ($("tagT090e", this)
															.text() != ""
															&& $("tagT090e",
																	this)
																	.text() != " ") {
														result = result
																+ $("tagT090e",
																		this)
																		.text();
													} else {
														result += "б.н.";
													}
													result = result + "</td>";
													result = result + "<td>";
													result = result
															+ $("tagT090f",
																	this)
																	.text();
													result = result + "</td>";
													result = result + "</tr>";
												});
								result = result + "</table>";
							}
							if ($("tag084a", this).text() != "") {
								result = result
										+ "<div style=\"text-align: right;\">";
								result = result + "<b>Индекс ББК: </b>";
								result = result + $("tag084a", this).text();
								result = result + "</div>";
							}
							result = result + "<p class=\"close\">" + "Закрыть"
									+ "</p>";
							result = result + "</div>";
							result = result + "<p class=\"button\">"
									+ showParams + "</p>";
							result = result + "<a href='#"
									+ $("doc_id", this).text()
									+ "' class='add-to-list'>Отобрать</a>";
							result = result + "</li>";
							num++;
						});
		num--;
		var search_params = "<hr />";
		var num_founded_items = $("items_found", data).text();
		var step = parseInt($("step", data).text());
		var current = parseInt($("begin_item_pos", data).text()) + 1;
		if (num_founded_items == 0) {
			search_params += "<div id=\"results\">";
			search_params += "Ничего не найдено - попробуйте изменить запрос</div>";
		} else {
			search_params += "<div id=\"results\">Результат ";
			var current_upper = num;
			search_params += current + "-" + current_upper + " из ";
			search_params += num_founded_items;

			search_params += " <div id='time-search'>Поиск выполнен за ";
			search_params += time;
			search_params += " сек.";
			search_params += "</div></div>";
		}
		
		//=!!!=
		if (location.href.indexOf("IDX", 0) != -1){
			search_params += '<a href="" id="alph-back">Вернуться к списку</a>';
		}
		//=!!!=
		
		$("#search-params").html(search_params);
		if (num > 10) {
			var vers = 0;
			if (window.navigator.userAgent.indexOf("MSIE") >= 0) {
				vers = window.navigator.userAgent.substr(
						window.navigator.userAgent.indexOf("MSIE") + 5, 1);
			}
			if (vers != 6) {
				$("#go-up").show();
			}
		} else {
			$("#go-up").hide();
		}
		return result;
	}
	
	function printAphs(data) {
		var t_date = new Date();
		time = t_date.getTime() - time;
		time = time / 1000;
		var result = "";
		var num = $("begin_item_pos", data).text();
		num++;
		$("node", data)
				.each(
						function() {
							result = result + "<li class=\"alph-list-item\">";
							result = result + '&nbsp;<a href="" class="alph-item">' + $('term', this).text() + '</a>';
							result = result + '&nbsp;&nbsp;&nbsp;<b>(' + $('cnt', this).text() + ')</b>';
							result = result + "</li>";
							num++;
						});
		num--;
		var search_params = "<hr />";
		var num_founded_items = $("items_found", data).text();
		var step = parseInt($("step", data).text());
		var current = parseInt($("begin_item_pos", data).text()) + 1;
		if (num_founded_items == 0) {
			search_params += "<div id=\"results\">";
			search_params += "Ничего не найдено - попробуйте изменить запрос</div>";
		} else {
			search_params += "<div id=\"results\">Результат ";
			var current_upper = num;
			search_params += current + "-" + current_upper + " из ";
			search_params += num_founded_items;

			search_params += " <div id='time-search'>Поиск выполнен за ";
			search_params += time;
			search_params += " сек.";
			search_params += "</div></div>";
		}
		$("#search-params").html(search_params);
		return result;
	}

	
	$(".add-to-list").live(
			"click",
			function() {
				var temp = $(this).attr("href");
				temp = temp.replace(/.*#/, "");
				if ($.cookie("list") == null || $.cookie("list") == "") {
					$.cookie("list", $("#type-search").attr("value") + ":"
							+ temp, {
						expires : 1,
						path : '/'
					});
				} else {
					var re = new RegExp($("#type-search").attr("value") + ":"
							+ temp);
					var str = $.cookie("list");
					if (re.exec(str) == null) {
						$.cookie("list", $.cookie("list") + "|"
								+ $("#type-search").attr("value") + ":" + temp,
								{
									expires : 1,
									path : '/'
								});
					}
				}
				setNumAdded();
			});

	$(".del-from-list").live("click", function() {
		var new_cont = $.cookie("list");
		var sub = $(this).attr("href").substr(1, $(this).attr("href").length);
		new_cont = new_cont.replace(sub, "");
		new_cont = new_cont.replace(/^\|/, "");
		new_cont = new_cont.replace(/\|$/, "");
		new_cont = new_cont.replace("||", "|");
		if (new_cont != "") {
			$.cookie("list", new_cont, {
				expires : 1,
				path : '/'
			});
		} else {
			$.cookie("list", null, {
				path : '/'
			});
			$.cookie("list", null, {
				path : '/ls/'
			});
		}
		document.location.href = "/ls/";
	});

	$("#clear-list").live("click", function() {
		$.cookie("list", null, {
			path : '/'
		});
		$.cookie("list", null, {
			path : '/ls/'
		});
		document.location.href = "/ls/";
	});

	$("#go-to-list").click(function() {
		var prev_url = window.location.href.replace(/http:\/\/[\w\.]+/, "");
		$.cookie("prev_url", prev_url, {
			path : "/"
		});
	});

	$(window).scroll(
			function() {
				if (window.navigator.userAgent.indexOf("MSIE") >= 0) {
					var vers = window.navigator.userAgent.substr(
							window.navigator.userAgent.indexOf("MSIE") + 5, 1);
					if (vers == 6) {
						$("#go-up").hide();
						return;
					}
				}
				var pos;
				pos = $(window).scrollTop();
				$("#go-up").css("bottom", 0 - pos);
			});

	$("#search").click(
			function() {
				left_border = 1;
				right_border = left_border + step_pagination - 1;
				address = "/search_result.php";
				params_obj = new Object();
				var num = 0;
				for ( var i = 0; i < idxs.length; i++) {
					if ($("#" + idxs[i]).length) {
						params_obj["var" + num] = idxs[i] + "|"
								+ $("#" + idxs[i]).attr("value");
						num++;
					}
				}
				params_obj["number"] = num;
				params_obj["type_search"] = $("#type-search").attr("value");
				params_obj["num_page"] = 0;
				params_obj["alphabet"] = 'no';
				ajaxRequest(params_obj, address);
			});

	$(".alph-pointer").click(function() {
		$('a').removeClass('active-alph-pointer');
		$(this).addClass('active-alph-pointer');
		left_border = 1;
		right_border = left_border + step_pagination - 1;
		address = "/ajax_response_alph.php";
		params_obj = new Object();
		var loc = location.href;
		var idxTemp = loc.substr(loc.indexOf("IDX", 0), 7);
		params_obj["var0"] = idxTemp + "|" + $(this).text();
		params_obj["number"] = 1;
		params_obj["type_search"] = $("#type-search").attr("value");
		params_obj["num_page"] = 0;
		params_obj["alphabet"] = 'yes';
		ajaxRequest(params_obj, address);
	});
	
	if ($(".alph-pointer").length) {
		temp = $(".alph-pointer:first");
		temp.addClass('active-alph-pointer');
		left_border = 1;
		right_border = left_border + step_pagination - 1;
		address = "/ajax_response_alph.php";
		params_obj = new Object();
		var loc = location.href;
		var idxTemp = loc.substr(loc.indexOf("IDX", 0), 7);
		params_obj["var0"] = idxTemp + "|" + temp.text();
		params_obj["number"] = 1;
		params_obj["type_search"] = $("#type-search").attr("value");
		params_obj["num_page"] = 0;
		params_obj["alphabet"] = 'yes';
		ajaxRequest(params_obj, address);
	}
	
	$(".alph-item").live(
		"click", 
		function() {
			//=!!!=
			prev_params_obj = params_obj;
			//=!!!=
			address = "/search_result.php";
			params_obj = new Object();
			var loc = location.href;
			var idxTemp = loc.substr(loc.indexOf("IDX", 0), 7);
			params_obj["var0"] = idxTemp + "|" + $(this).text();
			params_obj["number"] = 1;
			params_obj["type_search"] = $("#type-search").attr("value");
			params_obj["num_page"] = 0;
			ajaxRequest(params_obj, address);
			return false;
	});
	
	
	$("#alph-back").live(
			"click", 
			function() {
				params_obj = prev_params_obj;
				address = "/ajax_response_alph.php";
				ajaxRequest(params_obj, address);
				return false;
		});
	
	
	$("#loading").ajaxStart(function() {
		if (searchRequestFlag == 1) {
			$("#container").html("");
			$("#search-params").html("");
			$(".pagination").html("");
			$(this).show();
			$("input").attr("disabled", "disabled");
			var t_date = new Date();
			time = t_date.getTime();
		}
	});

	$("#loading").ajaxStop(function() {
		if (searchRequestFlag == 1) {
			$(this).hide();
			$("input").removeAttr("disabled");
			searchRequestFlag = 0;
		}
	});

	$("#IDX260c_lower").keypress(function(e) {
		if (!((e.which >= 48 && e.which <= 57) || (e.which == 8))) {
			var IDX260c_lower_var = String($("#IDX260c_lower").attr("value"));
			IDX260c_lower_var.replace(e, "");
			$("#IDX260c_lower").attr("value", IDX260c_lower_var);
			return false;
		}
	});

	$("#IDX260c_upper").keypress(function(e) {
		if (!((e.which >= 48 && e.which <= 57) || (e.which == 8))) {
			var IDX260c_upper_var = String($("#IDX260c_upper").attr("value"));
			IDX260c_upper_var.replace(e, "");
			$("#IDX260c_upper").attr("value", IDX260c_upper_var);
			return false;
		}
	});

	$("#list-books tr:even > td:even").css( {
		"background-color" : "rgb(240,240,240)"
	});

	$(document).ready(function() {
		$.fn.alignCenter = function() {
			var left = Math.max(100, $(this).width() / 2);
			var top = Math.max(200, $(this).height() / 2);
			top = top - $(window).scrollTop();
			var marginLeft = parseInt($(window).width() / 2 - left) + 'px';
			var marginTop = parseInt($(window).height() / 2 - top) + 'px';
			return $(this).css( {
				'left' : marginLeft,
				'top' : marginTop
			});
		};
	});

	$(".full-img")
			.live(
					"click",
					function() {
						img = $(this).find('img').attr('src');
						img = img.replace('/image.php?size=small&name=', '');
						img = img.replace('image.php?size=small&name=', '');
						img = img.replace(/http:\/\/(.*)\//, '');
						if ($.browser.msie) {
							$('#opaco').height($(document).height())
									.toggleClass('hidden');
						} else {
							$('#opaco').height($(document).height())
									.toggleClass('hidden').fadeTo('slow', 0.7);
						}
						res = '<img src="/image.php?name=' + img + '" /><br />';
						res += '<div id="close-img"><p><a href="">&times;</a><p></div>';
						$('#popup').html(res);
						$('#popup').alignCenter();
						$('#popup').toggleClass('hidden');
						return false;
					});
	
	function closeImg() {
		$('#opaco').toggleClass('hidden');
		$('#popup').toggleClass('hidden');
	}
	
	$("#popup").click(
		function() {
			closeImg();
			return false;
	});
	
});
