var addr,
	triples,
	currentTriple = 0,
	triplePeriod = 9000;


function swapTriple () {
	if (triples.length) {
		var z = 0;
		triples
			.each(function () { z = Math.max (z, $(this).css("z-index")); })
			.eq(currentTriple)
			.hide()
			.css("z-index", ++z)
			.add(".triangle")
			.fadeIn(2000);
		currentTriple = ++currentTriple % $("#image .main").length;
		tripleTimeout = setTimeout (swapTriple, triplePeriod);
	}
}



function getParam (sParamName) {
    var params = location.search.substring(1).split ("&");
    var variable = "";
    for (var i = 0; i < params.length; i++) {
        if (params[i].split("=")[0] == sParamName) {
            if (params[i].split("=").length > 1) variable = params[i].split("=")[1];
            return variable;
        }
    }
    return null;
}


function startSearch () {
	var target = $.trim($("#searchline").val());
	if (target.length > 2) {
		if (addr === "result.php") {
			$.getJSON("search.php",
					{target : target},
					function (json) {
						$("ol").remove();
						if (json.data.length) {
							var div = $("<ol></ol>")
							$.each(json.data, function (index, value) {
								$("<li><a href='" + value.file + "'>" + value.title + " <b>(" + value.file + ")</b></a></li>")
									.appendTo(div);
							});
							$("h2").text("Результаты поиска")
							div.insertAfter("h2");
						} else {
							$("h2").text("Ничего не найдено")
						}
					}
			);
		} else {
			$("#searchline, #searchbutton").unbind().blur();
			location.replace("result.php?target=" + encodeURIComponent(target));
		}
	}
}



function parseXml (xml) {
	
	var addItem = function (it) {
		accord
			.find("ol:last")
			.append("<li><a href='catalog/" + $(it).attr("page") + ".php'>" + $(it).text() + "</a></li>");
	}

	var i = 0,
		accord = $("<ul>");
	$(xml)
		.find("Accordion")
		.each(function() {
			accord.append("<li>" + $(this).children("Title").text() + "</li>");
			if ($(this).find("Categories").length) {
				accord.children("li:last").append("<ul></ul>");
				$(this)
					.find("Category")
					.each(function() {
						accord
							.children("li:last")
							.children("ul")
							.append("<li>" + ($(this).find("Title").text() + "</li>"));
						if ($(this).find("Items").length) {
							accord.find("li:last").append("<ol></ol>");
							$(this)
								.find("Item")
								.each(function() {
									addItem (this);
								}); // each Item
						}
					}); // each Category
			} else if ($(this).find("Items").length) {
				accord.find("li:last").append("<ol></ol>");
				$(this)
					.find("Item")
					.each(function() {
						addItem (this);
					}); // each Item
			}
		}); // each Accordion
	accord
		.find("ul, ol")
		.hide()
		.end()
		.appendTo("#catalogtree");
	$("#catalogtree *")
		.click(function (event) {
					event.stopPropagation();
			})
		.filter("ul > li")
		.click(function () {
					$(this)
						.toggleClass("minus")
						.children()
						.toggle();
			});
}


function briefNews (xml) {
	var items = $(xml).find("Item"),
		listLength = location.pathname.indexOf("news.php") !== -1 ? items.length : 3;
	items.each(function(i) {
					if (i < items.length - listLength) return true; // continue
					$("<li><a href='news/" + $(this).attr("page") + ".php'><span>" + $(this).attr("date") + "</span>" + $(this).text() + "</a></li>")
						.appendTo("#news");
				});
	$("#news li:last").addClass("last");
}

$(function () {
	addr = location.pathname;
	addr = addr.substr (addr.lastIndexOf("/") + 1);
	var current = $("#bigmenu a[href='" + addr + "']").parent(),
		pic = current.find("img").clone();
	current
		.empty()
		.append(pic)
		.addClass("current")
		.prev(".separator")
		.removeClass("real")
		.end()
		.next(".separator")
		.removeClass("real");
	$("#smallmenu a[href='" + addr + "']")
		.addClass("current");

	if (addr === "result.php" && getParam ("target")) {
		$("#searchline").val(decodeURIComponent(getParam ("target")));
		startSearch ();
	}

	var tableWidth = 0;
	$("table").each(function () {
						tableWidth = Math.max (tableWidth, $(this).width());
						$(this)
							.find("tr:first p")
							.css("font-weight", "bold")
							.end()
							.find("tr:odd")
							.css("background-color", "#0391b9");
	});
	$("table").each(function () {
						$(this)
							.width(tableWidth);
	});
	$("table tr").each(function () {
						$(this)
							.find("td:odd p")
							.css("text-align", "right")
							.end()
							.find("td:odd p").each(function () {
								$(this).html($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1&nbsp;'));
							});
	});
	(triples = $("#image img.main"))
		.each(function (index) {
				$(this).offset($("#image").offset());
		})
		.hide();
	$(".triangle")
		.hide();
	$("#mail, #searchbutton")
		.css("opacity", .8)
		.mouseout(function () { $(this).css("opacity", .8) })
		.eq(0)
		.mouseover(function () { $(this).css("opacity", 1) })
		.end()
		.eq(1)
		.mouseover(function () {
						if ($("#searchline").val().length > 2) {
							$(this)
								.css("cursor", "pointer")
								.css("opacity", 1)
								.attr("title", "Искать");
						} else {
							$(this)
								.css("cursor", "default");
						}
		})
		.click(startSearch);
	$("#searchline")
		.keypress(function (e) {
			if (e.which === 13) startSearch ();
	});
	if (location.pathname.indexOf("catalog.php") !== -1) {
		$.ajax({
			type: "GET",
			url: "catalog.xml",
			dataType: "xml",
			success: parseXml
		  });
	} else if ($("#news").length) {
		$.ajax({
			type: "GET",
			url: "news.xml",
			dataType: "xml",
			success: briefNews
		  });
	}
	$(".goback")
		.click(function () { history.back(); })
})


$(window).load(swapTriple);
