(function($){
	$(function() {
		var $searchbox = $('#find_button').add('#find_form');
		$('#show-searchbox').click(function(){
			$searchbox.show(); 
			return false;
		});
		$('#hide-searchbox').add('#hide-searchbox-img').add('#hide-searchbox-btn').click(function(){
			$searchbox.hide();
			return false;
		});
		$('#show-submit-error').click(function(){ $('#submit-error').toggle(); return false; });
		function chkEmpty() {
			var $this = $(this);
			if($this.val() == '') {
				$this.val($this.data('emptyText')||'').addClass('empty');
			}
		}
		function makeChanged() {
			var $this = $(this);
			if($this.hasClass('empty')) {
				$(this).val('').removeClass('empty');
			}
		}
		$('#tellabouterrorform').add('#knowfirstform').each(function(){
			$('#' + this.id + '_url').val(window.location.href);
		}).submit(function(e){
			$(':input.empty', this).val('');
			$(this).data('readyToSubmit', true);
		});
/*
				var captcha_sid = obj('captcha_sid').value;
				var captcha_word = obj('captcha_word').value;
				var req = new JsHttpRequest();
				req.onreadystatechange = function() {
					if (req.readyState == 4) {
						if (req.responseJS.A == "false") document.getElementById("tellabouterror").innerHTML = "Ошибка! Неправильный код подтверждения";
						else {
							document.getElementById('tellabouterrorform').bSubmit = true;
							document.getElementById('tellabouterrorform').submit();
						}
						
					}
				};
				req.open('get', '/bitrix/ajax.php', true);
				req.send({
					'file': '/bitrix/templates/js/ajax/jshttp/server/captcha_check.php',
					'params': {'CAPTCHA_SID':captcha_sid, 'CAPTCHA_WORD':captcha_word}
				});
*/
		var messages = {
			'knowfirstform': 
				['Спасибо за отправленное сообщение. Как только страница появится, Вы первым узнаете об этом!',
				 'Ошибка! Невозможно зарегистрировать заявку о напоминании появления страницы. Попробуйте позднее.',
				 'Ошибка! Введите корректный e-mail.' ],
			'tellabouterrorform': 
				['Спасибо за отправленное сообщение!',
				 'Ошибка отправки! Попробуйте повторить отправку позднее.',
				 'Ошибка! Введите корректный e-mail.',
				 'Заполнены не все поля.' ]
		};
		var opt = {
			success: function() {
				$(this).remove();
				$('#' + this.id + '_message').text(messages[this.id][0]);
			},
			error:   function(data, status) {
				$('#' + this.id + '_message').text(messages[this.id][status]);
				$(':input', this).each(chkEmpty);
			},
			failure: function(data) {
				$('#' + this.id + '_message').text('Ошибка отправки. Попробуйте позднее.');
				$(':input', this).each(chkEmpty);
			}
		};
		$('#tellabouterrorform').ajaxSubmit(opt);
		$('#knowfirstform').ajaxSubmit(opt);
		$('form input:text').add('form textarea').each(function() {
			$(this).data('emptyText', $(this).val()).focus(makeChanged).blur(chkEmpty);
		});
		$('#want-to-know').click(function(){ var $form = $(this).parents('form').eq(0).submit(); return false; });
		$('#submit-error-btn').click(function(){ $(this).parents('form').eq(0).submit(); return false; });
	});
})(jQuery);


(function($) {
	function loader(forWho){
		var $overlay = $('<div style="background:black; opacity:0.4; filter:alpha(opacity=40); position:absolute;"></div>').appendTo('body').hide();
		var left = 0;
		var top  = 0;
		/// Вынос пересчета координат в отдельный метод
		var geometry = {};
		var from_top = 0;
		var $forWho;
		function getGeometry(){
			$overlay.appendTo('body');
			if(typeof forWho != 'undefined' && forWho != null)
			{
				$forWho = $(forWho);
				geometry = $forWho.offset();
				geometry['width']  = ($forWho.outerWidth() || 10);
				geometry['height'] = ($forWho.outerHeight() || 10);
				$overlay.css({left: geometry.left, top: geometry.top, width: geometry.width, height: geometry.height});
			}
			else
			{
				$overlay.addClass('modal');
			}
			typeof $overlay['bgIframe'] != 'undefined' && $overlay.bgIframe();
			$overlay.remove().show(); // уберем из дома и сделаем видимым
		}
		getGeometry();
		
		this.start = function(delay){
			this.reset();
			if(typeof delay !== 'undefined' && parseInt(delay) > 0)
				this.delayTimeout = setTimeout(function() { $overlay.appendTo('body'); }, delay);
			else
				$overlay.appendTo('body');
		};
	
		this.reset = function(){
			var hidden = false;
			if ($forWho != undefined && $forWho.attr('display') == 'none'){
				hidden = true;
				$forWho.show();
			}
			getGeometry();
			if ($forWho != undefined && hidden){
				$forWho.hide();
			}
		}
		
		this.stop = function(){
			clearTimeout(this.delayTimeout);
			$overlay.remove();
		}
		
		this.get = function(){
			return $overlay;
		}
	}
// -----------------------------
	$.fn.extend({
		ajaxSubmit: function(options) {
			this.each(function() {
				$(this).submit(function(e) {
					var $form = $(this);
					if($form.data('readyToSubmit')) {
						var url = $form.attr('action'); // || window.location.href;
						var method = $form.attr('method') || 'get';
						var data = {};
						var nullFunc = function(){};
						var opt = $.extend({
							url:     url,
							method:  method,
							success: nullFunc,
							error:   nullFunc,
							failure: nullFunc
						}, options);
						$form.find(':input[name]').each(function(){ data[this.name] = $(this).val(); });
						var $loader = new loader(this);
						$loader.start();
						$.ajax({
							data: data,
							url:  opt.url,
							type: opt.method,
							dataType: 'json',
							success: function(data) {
								if(typeof data['returnCode'] != 'undefined' && data['returnCode'] > 0) {
									opt.error.call($form.get(0), data, data['returnCode']);
								}
								else {
									opt.success.call($form.get(0), data);
								}
								$loader.stop();
								delete($loader);
							},
							error: function(request, status, error) {
								opt.failure.call($form.get(0), status);
								$loader.stop();
								delete($loader);
							}
						});
					}
					return false;
				});
			});
		}
	});
})(jQuery);