jsHover = function() {
	var hEls = $('#menuUl li');
	for (var i=0, len=hEls.length; i<len; i++) {
		hEls[i].onmouseover=function() { this.className+=" jshover"; }
		hEls[i].onmouseout=function() { this.className=this.className.replace(" jshover", ""); }
	}
	var width1 = $('#menuUl').attr('offsetWidth');
	var width2 = $('#phone').attr('offsetWidth');
	var widthMenu1 = width1 + width2 - 12;
	$('#menu').attr('width', widthMenu1 + 'px');
	var widthMenu2 = $('#headRightBlock').attr('offsetWidth');

	if (widthMenu1 > widthMenu2){
		$('#menu').attr('width', widthMenu1 + 'px');
	} else {
		$('#menu').attr('width', widthMenu2 + 'px');
	}
};
new function() {
    $.fn.validate = {
        init: function(o) {
			if(o.name == 'author') { this.username(o) };
			if(o.name == 'name') { this.username(o) };
			if(o.name == 'pass') { this.password(o) };
			if(o.name == 'passwd') { this.passwd(o) };
			if(o.name == 'email') { this.email(o) };
			if(o.name == 'phone') { this.phone(o) };
			if(o.name == 'subject') { this.subject(o) };
			if(o.name == 'address') { this.address(o, 'адрес') };
			if(o.name == 'captcha') { this.captcha(o) };
			if(o.name == 'comment') { this.address(o, 'комментарий') };
			if(o.name == 'message') { this.message(o) };
			if(o.name == 'producer') { this.producer(o) };
        },
        producer: function(o) {
			if (parseInt(o.value) == 0) doError(o, 'Ошибка: Выберите производителя');
			else doSuccess(o);
        },
        subject: function(o) {
			var str = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
			if (!o.value.match(str)) {
				if (o.value.length == 0) doError(o, 'Ошибка: Введите тему сообщения');
				else if (o.value.length < 5) doError(o, 'Ошибка: Слишком короткая тема сообщений');
				else doSuccess(o);
            } else {
				doError(o, 'Ошибка: недопустимые символы ( ) [ ] + . , / ? : ; \' \" \` \~ # $ % ^ & < >');
			};
        },
        message: function(o) {
			var str = /[(\*\(\)\[\]\+\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
			if (!o.value.match(str)) {
				if (o.value.length == 0) doError(o, 'Ошибка: Введите Ваше сообщение');
				else if (o.value.length < 3) doError(o, 'Ошибка: Слишком короткое сообщение');
				else doSuccess(o);
            } else {
				doError(o, 'Ошибка: недопустимые символы ( ) [ ] + . , / ? : ; \' \" \` \~ # $ % ^ & < >');
			};
        },
        address: function(o, text) {
			var str = /[(\*\(\)\[\]\+\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
			if (!o.value.match(str)) {
				if (o.value.length == 0) doError(o, 'Ошибка: Введите Ваш '+text);
				else doSuccess(o);
            } else {
				doError(o, 'Ошибка: недопустимые символы ( ) [ ] + . , / ? : ; \' \" \` \~ # $ % ^ & < >');
			};
        },
        phone: function(o) {
			var str = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
			if (!o.value.match(str)) {
				if (o.value.length == 0) doError(o, 'Ошибка: Введите номер телефона');
				else doSuccess(o);
            } else {
				doError(o, 'Ошибка: недопустимые символы ( ) [ ] + . , / ? : ; \' \" \` \~ # $ % ^ & < >');
			};
        },
        captcha: function(o) {
			var user = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
			if (o.value == 'Проверочный код*') o.value = '';
			if (!o.value.match(user)) {
				if (o.value.length < 6) doError(o, 'Ошибка: Не верный проверочный код');
				else doSuccess(o);
            } else {
				doError(o, 'Ошибка: недопустимые символы ( ) [ ] + . , / ? : ; \' \" \` \~ # $ % ^ & < >');
			};
        },
        username: function(o) {
			var user = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
			if (!o.value.match(user)) {
				if (o.value.length == 0) doError(o, 'Ошибка: Введите Ваше имя');
				else if (o.value.length < 3) doError(o, 'Ошибка: Слишком короткое имя');
				else doSuccess(o);
            } else {
				doError(o, 'Ошибка: недопустимые символы ( ) [ ] + . , / ? : ; \' \" \` \~ # $ % ^ & < >');
			};
        },
        password: function(o) {
			var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
			if (!o.value.match(pass)) {
				if (o.value.length < 6) doError(o, 'Ошибка: Слишком короткий пароль');
				else if (o.value.length > 12) doError(o, 'Ошибка: Слишком длинный пароль');
				else doSuccess(o);
            } else {
				doError(o, 'Ошибка: недопустимые символы ( ) [ ] + . , / ? : ; \' \" \` \~ # $ % ^ & < >');
            };
        },
		passwd: function(o) {
			var pass = /[(\*\(\)\[\]\+\.\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
			if (!o.value.match(pass)) {
				if (o.value.length > 1 && o.value.length < 6) doError(o, 'Ошибка: Слишком короткий пароль');
				else if (o.value.length > 12) doError(o, 'Ошибка: Слишком длинный пароль');
				else doSuccess(o);
            } else {
				doError(o, 'Ошибка: недопустимые символы ( ) [ ] + . , / ? : ; \' \" \` \~ # $ % ^ & < >');
            };
        },
        email: function(o) {
			var email  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if (o.value.match(email)) {
				if (o.value.length == 0) doError(o, 'Ошибка: Введите email адрес');
				else doSuccess(o);
            } else {
				doError(o, 'Ошибка: Введите корректный email адрес');
            };
        }
     };
     function doSuccess(o) {
		$('#error').attr('class', 'hidden');
		$('#error').html('');
		//o.className = 'text';
     };
     function doError(o,m) {
		$('#error').attr('class', '');
		$('#error').html(m);
		//o.className = 'texterror';
     };
};
$.fn.pass_match = function(m) {
	if ($('#'+this.get(0).id).val() == $(m.match).val()) {
		if ($('#'+this.get(0).id).val().length == 0) {
			$('#error').attr('class', '');
			$('#error').html('Ошибка: Введите подтверждение пароля');
		} else {
			$('#error').attr('class', 'hidden');
			$('#error').html('');
		}
	} else {
		$('#error').attr('class', '');
		$('#error').html('Ошибка: Пароли не совпадают');
	};
};

$(document).ready(function(){
	if (window.attachEvent && navigator.userAgent.indexOf("Opera")==-1) window.attachEvent("onload", jsHover);
	
	$("#query").focus(function() {
		if( this.value == 'Поиск программы' ) this.value = "";
	}).blur(function() {
		if( !this.value.length ) this.value = 'Поиск программы';
	});

	$("#author").focus(function() {
		if( this.value == 'Ваше Имя*' ) this.value = "";
	}).blur(function() {
		if( !this.value.length ) this.value = 'Ваше Имя*';
	});
	
	$("#e_mail").focus(function() {
		if( this.value == 'Ваш email' ) this.value = "";
	}).blur(function() {
		if( !this.value.length ) this.value = 'Ваш email';
	});	
	
	$("#captcha").focus(function() {
		if( this.value == 'Проверочный код*' ) this.value = "";
	}).blur(function() {
		if( !this.value.length ) this.value = 'Проверочный код*';
	});	

	$("#subject").focus(function() {
		if( this.value == 'Тема сообщения*' ) this.value = "";
	}).blur(function() {
		if( !this.value.length ) this.value = 'Тема сообщения*';
	});	
	
	$("#commentform :input").blur(function() {
		$(this).validate.init(this);
  	});
  	
	$('#commentform').submit(function(){
		errors = 0;
		$("#commentform :input").each(function(){
			if (!errors) $(this).blur();
			if ($('#error').html() != '') errors = 1;
		});
		if (errors) return false;
	});
	
	$("#messageform :input").blur(function() {
		$(this).validate.init(this);
  	});
  	
	$('#messageform').submit(function(){
		errors = 0;
		$("#messageform :input").each(function(){
			if (!errors) $(this).blur();
			if ($('#error').html() != '') errors = 1;
		});
		if (errors) return false;
	});
	
	_basket = function(id, _type) {
		if (typeof _type == 'undefined') _type = 0;
		$.ajax({  
			type: 'GET',  
			data: 'module=catalog&mode=set2basket&articleid=' + id + '&type=' + _type,  
			url	: domain + 'index.cgi',
			success: function(response){
				window.location = domain+'catalog/basket/';
			}   
		});
	};	
	closer = function () {
		$.modal.close();
	};
	// Rating
	rate = function(id, v) {
		$.ajax({  
			type: 'GET',  
			data: 'module=catalog&mode=rating&id=' + id + '&v='+v,  
			url	: domain + 'index.cgi',
			success: function(response){
				if (response.length > 0) {
					vals = response.split('_');
					res = parseInt(vals[0])/parseInt(vals[1]);
					$('#r_'+id).html(res.toFixed(1));
					$('#messageText').html('Ваш голос учтен.<br /> Спасибо за голосование');
				} else $('#messageText').html('Вы уже голосовали за данный продукт');
   				$('#message').modal();
   				setTimeout('closer()', 4000); 
			}  
		});	 
	};
	scanSelect = function(){
		link = $('#scan option:selected').val();
		if (link != '#'){
			url = domain + 'catalog/scan/' + link;
			window.location = url;
		}
	};
	clearList = function(){
		$.ajax({  
			type: 'GET',  
			data: 'module=catalog&mode=clearcompare',  
			url	: domain + 'index.cgi',
			success: function(response){
				$('#compare').css("display", "none");
				$('#compare_list').html('');
				
				reg = /^a_(\d+)$/i;
				$('a').each(function(){
					if ($(this).attr('id')){
						if ($(this).attr('id').match(reg)){
							$(this).html('выбрать для сравнения');
							$(this).attr('title','выбрать для сравнения');
						}
					}
				});
				
				
				$('#messageText').html('Список сравнения очищен'); 
	   			$('#message').modal(); 
	   			setTimeout('closer()', 4000);
			}   
		});			
	};
	set2Compare = function(id, st) {
		$.ajax({  
			type: 'GET',  
			data: 'module=catalog&mode=set2compare&articleid=' + id,  
			url	: domain + 'index.cgi',
			success: function(response){
				jsonObj = eval('(' + response + ')');
				if (typeof st == 'undefined') {
					_message = '';
					if (jsonObj.insert == 0){
						_message = 'Антивирус удален из списка сравнения';
						$('#a_'+id).html('выбрать для сравнения');
						$('#a_'+id).attr('title','выбрать для сравнения');
					} else {
						_message = 'Антивирус добавлен в список сравнения';
						$('#a_'+id).html('удалить из сравнения');
						$('#a_'+id).attr('title','удалить из сравнения');
					}
					
					if (jsonObj.cnt == 0){
						$('#compare').css("display", "none");
						$('#compare_list').html('');
					} else {
						$('#compare_list').html(jsonObj.html);
						$('#compare').css("display", "block");
					}
					
					$('#messageText').html(_message); 
	   				$('#message').modal(); 
	   				setTimeout('closer()', 4000);
				} else {
					window.location = window.location; 
				}
			}   
		});	  
	};
	set2Basket = function(id) {
		$.ajax({  
			type: 'GET',  
			data: 'module=catalog&mode=set2basket&articleid=' + id,  
			url	: domain + 'index.cgi',
			success: function(){
				var cnt = parseInt($('#inbasket').html()) +1;
				$('#inbasket').html(''+cnt);
				$('#order').html('Оформить заказ');
				$('#messageText').html('Товар добавлен в корзину'); 
   				$('#message').modal(); 
   				setTimeout('closer()', 4000); 
			}   
		});	  
	};
	$('#rembtn').click(function(){
		var parent = $(this).parents('form:first');
		parent.attr('method','post').attr('action',window.location);
		parent.append('<input name="action" type="hidden" value="send" />').submit();
	});
	// Authorization
	$('#auth').click(function(){
		var parent = $(this).parents('form:first');
		parent.attr('method','post').attr('action',window.location).attr('target', '_self');
		parent.append('<input name="action" type="hidden" value="auth" />');
		parent.submit();
	});
	// Basket
	$('#ch_login').click(function(){
		$.ajax({  
			type: 'GET',  
			data: 'module=catalog&mode=checkLogin&email=' + $('#email').val(),  
			url	: domain + 'index.cgi',
			cache: false,
			success: function(response){
				if (response == 0) {
					$('#error').css("color", "green"); $('#error').css("display", "inline");
					$('#error').removeClass('hidden'); $('#error').addClass('');
					$('#error').html('<b>Email свободен</b>');
				} else if (response == 1) {
					$('#error').css("color", "red"); $('#error').css("display", "inline");
					$('#error').removeClass('hidden'); $('#error').addClass('');
					$('#error').html('<b>Пользователь с таким email уже зарегистрирован</b>');
				} else {
					$('#error').css("color", "red"); $('#error').css("display", "inline");
					$('#error').removeClass('hidden'); $('#error').addClass('');
					$('#error').html('<b>Неверный формат email</b>');
				}
			},
			error: function() {
				$("#ch_st").css("color", "red");
				$('#ch_st').html('<b>Пользователь с таким email уже зарегистрирован</b>');
			}  
		});	
		$("#ch_st").css("margin-left", "10px");
	});
	$('#recalc').click(function(){
		var parent = $(this).parents('form:first');
		parent.attr('method','post').attr('action',window.location);
		parent.append('<input name="action" type="hidden" value="modify" />').submit();
	});
	/*$('input.quantity', '#article_list').each(function() {
		options = {
			mask : '9999',
			type : 'fixed',
			defaultValue : $(this).val()
		};
		$(this).setMask(options); 
	});*/
	// Registration
	$('#submit_reg').click(function(){
		var parent = $(this).parents('form:first');
		parent.attr('method','post').attr('action',window.location).attr('target', '_self');
		parent.append('<input name="action" type="hidden" value="add" />').submit();
	});
	
	// Validation register form
	$("#regform :input").blur(function() {
          $(this).validate.init(this);
  	});
	$("#regform #confirm_pass").blur(function() {
          $(this).pass_match({match: '#pass', error: '#error'});
	});
	$('#regform').submit(function(){
		errors = 0;
		$("#regform :input").each(function(){
			if (!errors) $(this).blur();
			if ($('#error').html() != '') errors = 1;
		});
		if (errors) return false;
	});
	
	// Edit profile
	$('#profile_edit').click(function(){
		var parent = $(this).parents('form:first');
		parent.attr('method','post').attr('action',window.location);
		parent.append('<input name="action" type="hidden" value="edit" />').submit();
	});
	$("#profileform :input").blur(function() {
		$(this).validate.init(this);
  	});
	$("#profileform #confirm_pass").blur(function() {
		if ($('#passwd').attr('value') != '') {
			$(this).pass_match({match: '#passwd', error: '#error'});
		}
	});
	$('#profileform').submit(function(){
		errors = 0;
		$("#profileform :input").each(function(){
			if (!errors) $(this).blur();
			if ($('#error').html() != '') errors = 1;
		});
		if (errors) return false;
	});

	// Register order
	$('#reg_order').click(function(){
		var parent = $(this).parents('form:first');
		parent.attr('method','post').attr('action',domain+'catalog/basket/order/').attr('target', '_self');
		parent.append('<input name="action" type="hidden" value="regist" />').submit();
	});
	
	$("#buyform :input").blur(function() {
		if ($(this).attr('class') != 'hidden') {
			$(this).validate.init(this);
		}
  	});
	$("#buyform #confirm_pass").blur(function() {
		if ($('#pass').attr('class') != 'hidden') {
			$(this).pass_match({match: '#pass', error: '#error'});
		}
	});
	$('#buyform').submit(function(){
		errors = 0;
		$("#buyform :input").each(function(){
			if (!errors) $(this).blur();
			if ($('#error').html() != '') errors = 1;
		});
		if (errors) return false;
	});
	$('#filtr_cat').change(function(){
		filt = $('#filtr_cat option:selected').val();
		if (filt != '#'){
			url = domain + 'catalog/producer/' + $('#producer').val() + '/page' + $('#page').val() + '/filter' + filt + '/';
			window.location = url;
		}
	});	
	$('#filtr_pro').change(function(){
		filt = $('#filtr_pro option:selected').val();
		if (filt != '#'){
			url = domain + 'catalog/category/' + $('#producer').val() + '/page' + $('#page').val() + '/filter' + filt + '/';
			window.location.href = url;
		}
	});
	$('#poll_form').submit(function(){
		$(this).append('<input name="mode" type="hidden" value="poll"/>');
	    $(this).ajaxSubmit({
			type	: 'POST', 
			url		: domain,
			timeout	: 3000,
			success	: function(response){
				$('#messageText').html('Ваш голос учтен.<br /> Спасибо за голосование');
				$('#poll_form').attr('class', 'hidden');
				$('#poll_res').attr('class', '');
				$('#message').modal();
				setTimeout('closer()', 4000); 
			}
		});
	    return false;
	});
});
