function check(target, condition, message) { /* {{{ */
	var div = target.parent();
	if (eval(condition)) {
		div.removeClass('error');
		$('em', div).remove();
		return true;
	} else {
		if ( ! div.hasClass('error'))
			div.addClass('error').append('<em class="message">'+message+'</em>');
		target.focus();
		return false;
	}
} /* }}} */

function is_valid_email(email) { /* {{{ */
	pattern = /^\w[-\w\.]{0,63}@(\w[-\w]*\.)+[a-z]{2,4}$/i;
	return pattern.test(email);
} /* }}} */

function is_valid_phone(num) { /* {{{ */
	pattern = /^[\(\d][-,\s\d\(\)]{4,}$/;
	return pattern.test(num);
} /* }}} */

function initSearch() { /* {{{ */
	$('#search_text')
	.data('initVal', '... поиск по названию товара ...')
	.focus(function() {
		if($(this).css('color') != '#000000')
			$(this)
			.val('')
			.css('color', '#000000');
	})
	.blur(function() {
		if($(this).val() == '')
			$(this)
			.val($(this).data('initVal'))
			.css('color', '#aaa');
	})
	.triggerHandler('blur');

	$('#search form')
	.submit(function(e) {
		var t = $('#search_text');
		if ((t.val() == '') || (t.val() == t.data('initVal'))) {
			var p = t.position();
			e.preventDefault();
			t.focus();
			$('#search_tip')
			.css({'top' : p.top-8, 'left' : p.left+(t.width()-$('#search_tip').width())/2 })
			.fadeIn(500)
			.fadeOut(1000);
		}
	});
} /* }}} */

function initLogin() { /* {{{ */
	var a = $('#topnav a[href="#"]');
	if (a.length <= 0)
		return;

	$('#login_form')
	.keydown(function(e) { 
			if(e.keyCode == 27) $('#cancel_login').click(); 
	})
	.submit(function(e) {
		var email = $('#login_email').val();
		var pass = $('#pass').val();
		e.preventDefault();
		if (email == '') {
			$('#login_msg').text('E-mail не может быть пустым');
			$('#login_email').focus();
		} else {
			$('#login_msg').addClass('ok').text('подождите, идет проверка ...');
			$.post('check_login.php', {'email':email, 'pass':pass}, function(data) {
				if (data == 1) { // success
					$('#login_form').unbind('submit');
					$('#login').click();
				} else // failure
					$('#login_msg').removeClass('ok').text('Неправильный e-mail и/или пароль');
			});
		}
	});

	$('#disabler')
	.height($(document).height())
	.css('opacity', 0.67);

	$('#cancel_login')
	.click(function(e) {
		e.preventDefault();
		$('#login_form').hide();
		$('#disabler').hide();
	});

	a.click(function(e) {
			var email = $('#login_email');
			e.preventDefault();

			$('#disabler').show();

			$('#login_msg').text('');

			$('#login_form')
			.css({'top' : $('div.hlist').position().top - 14, 
				'left': ($(window).width() - $('#login_form').width())/2})
			.show();

			if (email.val() == '')
				email.focus();
			else
				$('#pass').focus();
	});
} /* }}} */

function initRegistration() { /* {{{ */
	var f = $('#registration form');
	if (f.length <= 0)
		return;

	f.submit(function(e) {

			var res = check($('#fio'), "$.trim(target.val()) != ''", 'Укажите, пожалуйста, Ваши Ф.И.О.')
				&& check($('#reg_email'), "$.trim(target.val()) != ''", 'Укажите, пожалуйста, Ваш e-mail')
				&& check($('#reg_email'), "is_valid_email(target.val())", 'Некорректный e-mail')
				&& check($('#pass1'), "$.trim(target.val()) != ''", 'Пароль не может быть пустым')
				&& check($('#pass2'), "target.val() == $('#pass1').val()", 'Пароли не совпадают')
				&& check($('#contact_info'), "$.trim(target.val()) != ''", 'Укажите, пожалуйста, Ваш контактный телефон')
				&& check($('#contact_info'), "is_valid_phone(target.val())", 'Некорректный номер телефона')
				&& check($('#address'), "$.trim(target.val()) != ''", 'Укажите, пожалуйста, адрес доставки')
			;
			if ( res == false )
				e.preventDefault();
	});
} /* }}} */

function initOrder() { /* {{{ */
	var f = $('#order_form');
	if (f.length <= 0)
		return;

	f.submit(function(e) {

			var res = check($('#contact_info'), "$.trim(target.val()) != ''", 'Укажите, пожалуйста, Ваш контактный телефон')
				&& check($('#contact_info'), "is_valid_phone(target.val())", 'Некорректный номер телефона')
				&& check($('#address'), 
					"($.trim(target.val()) != '') || ($('#address_new').get(0).checked == false)", 
					'Заполните, пожалуйста, новый адрес доставки или выберите существующий')
			;
			if ( res == false )
				e.preventDefault();
	});
} /* }}} */

function onFilter(e) { /* {{{ */
	var f, i;
	if (this.tagName == 'INPUT')
	   f = (this.checked ? '' : 'r') + this.id;
	else {
		e.preventDefault();
		f = this.href.replace(/^.*\//, '');
	}
	// load new filters
	window.location.href = window.location.href.replace(/[^\/]*$/, f+'#content');
} /* }}} */

function initFilters() { /* {{{ */
	$('#filters_src input,#filter a:not(:last)').click(onFilter)
	.filter(':checked').parent().show();
	if ($('#filter').length)
		$('h6.vlist img').css('visibility', 'visible').click(function () {
			window.location = window.location.href.replace(/[^\/]*$/, 'index.php?rf_all');
		});

	$('#filters_src strong').click(function () { $(this).next().toggle(100); return false; });
} /* }}} */

$(function () {
	initFilters();
	initSearch();
	initLogin();
	initRegistration();
	initOrder();
});

