		
	// создать XMLHttp запрос
	function createRequest() {
		var request = false;
		try {
			// нормальные браузеры
			request = new XMLHttpRequest(); 
		} catch (e) {
			try {
				// некоторые версии IE
				request = new ActiveXObject("MsXML2.XMLHTTP");
			} catch (e) {
				try {
					// другие версии IE
					request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					request = false;
				}
			}
		}	
		return request;
	}
	
	// обновить капчу
	function updateCaptcha() {
		$('#captcha').attr('src', '/ajax.php?page=captcha&rnd=' + Math.random() );
	}
	
	// установить обработчики для текстовых элементов формы (дефолтовое значение)
	function setTextfieldsHandlers($selectors) {
		$($selectors).each(function() {
			var default_value = this.value;						
			$(this).focus(function() {
				if(this.value == default_value) {
					this.value = '';
				}
			});
			$(this).blur(function() {
				if(this.value == '') {
					this.value = default_value;
				}
			});
		});
	}
	
	// установить отчет об обработке
	function setProcessingReport(report, status) {
		$('#report_box').remove();
		$("<div id='report_box' class='rounded_2'>" + report + "</div>").insertBefore($('#header'));
		if ( status == 'bad' ) { $('#report_box').addClass('bad'); }
		setTimeout(function() {
			$('#report_box').animate({opacity: 0}, 1000, function() {
				$('#report_box').remove();
			});
		}, 2000);
	}
	
	// вовзращает случайное целое число из заданного промежутка
	function getRandomInt(min, max) {
	  return Math.floor(Math.random() * (max - min + 1)) + min;
	}
	
	// создает preloader иконку до переданного объекта
	// возвращает ссылку на созданный объект
	function insertPreloaderBefore(object) {
		var preloader_id = getRandomInt(0, 999999);
		$(object).parent().css('position', 'relative');
		$("<img id='preloader_" + preloader_id + "' src='/_images/preloader.gif' class='preloader' />").insertBefore($(object));
		return document.getElementById("preloader_" + preloader_id);
	}
	
	// отправить данные формы
	function submitForm(button) {
		var preloader = insertPreloaderBefore(button);
		var form = $(button).parents('form')[0];
		var request = createRequest(); 
		request.open('POST', $(form).attr('action'), true);
		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		var string = '';
		$(form).find('textarea, input, select').each(function() {
			if ( $(this).attr('type') == 'checkbox' ) {
				if ( $(this).attr('checked') == 'checked' ) { string += "&" + $(this).attr('name') + "=" + $(this).val(); }
			} else {
				string += "&" + $(this).attr('name') + "=" + $(this).val();
			}												  
		});
		request.send(string.substr(1));
		request.onreadystatechange = function(){
			if (request.readyState == 4) {
				$(preloader).remove();
				if (request.status == 200) {
					var response = request.responseText.split('|');
					if ( response[1] == 'update' ) { document.location.reload(); }
					else if ( response[1] == 'follow' ) { document.location.href = response[2]; }
					else { setProcessingReport(response[1], response[0]); }
				}
			}
		};
	}
	
	/* Array.shuffle( deep ) - перемешать элементы массива случайным образом
	deep - необязательный аргумент логического типа, указывающий на то, 
		   нужно ли рекурсивно обрабатывать вложенные массивы;
		   по умолчанию false (не обрабатывать) */
	Array.prototype.shuffle = function( b ) {
		var i = this.length, j, t;
		while( i ) {
			j = Math.floor( ( i-- ) * Math.random() );
			t = b && typeof this[i].shuffle !== 'undefined' ? this[i].shuffle() : this[i];
			this[i] = this[j];
			this[j] = t;
		 }
		return this;
	};
	
	// крутилка partner goods
	var pg_interval = null;
	function rotatePartnerGoods( settings ) {
		var goods = [
					 ['Тюбетейка вязаная зеленая', 'http://www.tatville.ru/shop/product_24', '65', 'http://www.tatville.ru/files/site/product_type/24_27_1.jpg'],
					 ['Открытка "Эниемэ"', 'http://www.tatville.ru/shop/product_228', '20', 'http://www.tatville.ru/files/site/product_type/228_273_1.jpg'],
					 ['Кольцо с узорами', 'http://www.tatville.ru/shop/product_205', '485', 'http://www.tatville.ru/files/site/product_type/205_247_1.jpg'],
					 ['Подвеска с кулоном', 'http://www.tatville.ru/shop/product_58', '65', 'http://www.tatville.ru/files/site/product_type/58_65_1.jpg'],
					 ['Ключница', 'http://www.tatville.ru/shop/product_141', '75', 'http://www.tatville.ru/files/site/product_type/141_149_1.jpg'],
					 ['Кружка "Панорама Казанского Кремля"', 'http://www.tatville.ru/shop/product_210', '175', 'http://www.tatville.ru/files/site/product_type/210_253_1.jpg'],
					 ['Татарча дискотека', 'http://www.tatville.ru/shop/product_43', '145', 'http://www.tatville.ru/files/site/product_type/43_46_1.jpg']
					 ];
		goods.shuffle();
		$('#mnpg_rotator').animate({opacity: 0}, 200, function() {
			$('#mnpg_rotator .name').text(goods[0][0]);
			$('#mnpg_rotator .name').attr('href', goods[0][1]);
			$('#mnpg_rotator .price').text(goods[0][2] + ' рублей');
			$('#mnpg_rotator img').attr('src', goods[0][3]);
			$('#mnpg_rotator').animate({opacity: 1}, 200);
		});
		
		if ( settings == 'stop' ) { clearInterval(pg_interval); }
		else if ( settings == 'first_run' ) { $('#mnpg_rotator').css('visibility', 'visible'); }
	}
	
	
	
	$(document).ready(function(){
   		
		//
		setTextfieldsHandlers("textarea, input[type='text']:not([handler='off']), input[type='password']");
		
		//
		rotatePartnerGoods('first_run');
		pg_interval = setInterval(function() { rotatePartnerGoods(); }, 20000);
		
		// обработчик tooltip
		$(".tooltip").tooltip({
			track: true,
			delay: 100,
			showURL: false,
			opacity: 0.85,
			fixPNG: true,
			top: -40,
			left: -30
		});
		
		// удаляем report_box, если он создан при загрузке страницы
		setTimeout(function() {
			$('#report_box').animate({opacity: 0}, 1000, function() {
				$('#report_box').remove();
			});
		}, 2000);
		
		// устанавливаем обработчик поискового бокса 
		$("#search_box.hidden .show_button").click(function() {
			var $show_button = $(this);									 
			var $show_content = $('#search_box .show_content');
			
			$show_button.hide();
			$show_content.show();
		 
			var first_click = true;
			$(document).bind('click.search_box', function(e) {
				if (!first_click && $(e.target).closest('#search_box .show_content').length == 0) {
					$show_button.show();
					$show_content.hide();
					$(document).unbind('click.search_box');
				}
				first_click = false;
			});
			
		});
		
		// установить обработчики формы входа
		$("#auth_menu .enter_button").click(function() {
			var $enter_button = $(this);									 
			var $form = $('#auth_menu form');
			
			if ($form.css('display') != 'block') {
				$form.show();
				$enter_button.addClass('pressed');
		 
				var first_click = true;
				$(document).bind('click.auth_menu', function(e) {
					if (!first_click && $(e.target).closest('#auth_menu form').length == 0) {
						$form.hide();
						$enter_button.removeClass('pressed');
						$(document).unbind('click.auth_menu');
					}
					first_click = false;
				});
			}
			
		});
		
		// установить обработчик главного меню
		$('#main_menu .submenu').each(function() {
			$(this).mouseover(function() {
				$(this).children('ul').css('display', 'block');
				$(this).children('a').addClass('hover');
			});
			$(this).mouseout(function() {
				$(this).children('ul').css('display', 'none');
				$(this).children('a').removeClass('hover');
			});
		});
		
	});
	
	
	
	
	
	
	// сгенерировать форму комментирования для форума
	function commentTheme(button, comment_id) {
		var preloader = insertPreloaderBefore(button);
		$('#frmpg_form').remove();
		var request = createRequest();
		var url = 'ajax.php?page=comment_form';
		request.open('GET', url, true);
		request.send(null);
		request.onreadystatechange = function(){
			if (request.readyState == 4) {
				$(preloader).remove();
				if (request.status == 200) {
					var previous = document.getElementById('comment_' + comment_id) || document.getElementById('frmpg_theme_review');
					$("<form id='frmpg_form' method='post' action='/ajax.php?page=new_comment&theme=" + $('#theme_id').val() + "&comment=" + comment_id + "'>" + request.responseText + "</form>").insertAfter( previous );
					setTextfieldsHandlers("#frmpg_form textarea, #frmpg_form input[type='text']");
				}
			}
		};
	}
	
	
	
	
	
	
	
	
	
	
