var curentSM='no';
var c=0;
var timeout_id;
	
function BannerClick(bannerId){
	var url="http://"+document.location.hostname+"/inc/request-handler/banner.php";
	$.ajax({
		url: url,
		data: 	{banner:bannerId,
				method:'ajax'},
		type: "POST",
		dataType: 'json',
		success: function(r) {
			if(r.state=='ok')
			{
				document.location=r.href;	
			}
		}
	});	
		
}

function banner_init() {
	//$("#banner_links").append('<div id="banner_link_0" class="banner_links_link banner_current_link"></div>');
	$("#banner").height(banner_height[0]);
	//for (var i = 1; i < banner_items.length; i++){
	//	$("#banner_links").append('<div id="banner_link_' + 1 + '" class="banner_links_link"></div>');
	//}
	
	$("#banner_content").html(banner_items[0]);
}

$(document).ready(function(){
	$('div.select_brand').toggle(function(){
		$('table.borders').show();
	},
	function(){
		$('table.borders').hide();
	});
	
/*
	$('div.gallery_brand a').each(function(){
		var href=$(this).attr('href');
		href=href.replace('catalo/','catalog///');
		$(this).attr('href',href);
	});
*/	
	
	$("#loginform #pass").bind('keydown', function(e){
		if (e.which === 13){
			jQuery('#login_button').click();
			//$("#error_window li.button a").focus();
		}
	});
	
	
	$('.banner_links_link').click( function(){	
		$(".banner_current_link").removeClass("banner_current_link");
		$(this).addClass("banner_current_link");
		
		var banner_link_id = $(".banner_current_link").attr('id');
		banner_link_id = parseInt(banner_link_id.slice(12, 13));
		
		$("#banner_content").empty().html(banner_items[banner_link_id]);
		$("#banner_content").height(banner_height[banner_link_id]);
	});
	
	$('.menu_item').each(function(i) {
		if ($.cookie('menu_item') == i) {
			$(this).addClass('expanded_menu');
		}
		
		$(this).click(function() {
			$.cookie('menu_item', '');
				
			$.cookie('menu_item', i);
			$('.expanded_menu').removeClass('expanded_menu');
			$(this).addClass('expanded_menu');
		});
	});
});

function init(g_type, g_width, i_width){
	var item_list = $("#"+g_type+"_gallery").find(".gallery_item");
	var gallery_width = item_list.length*i_width;
	$("#"+g_type+"_gallery").width(gallery_width);
	if (gallery_width > g_width) {
		$("#"+g_type+"_right_arrow").css({
			'cursor' : 'pointer'
		});
	} else {
		$("#"+g_type+"_right_arrow").addClass('title_right_arrow_disable');
	}
	
	$("#"+g_type+"_left_arrow").click( function(){
		left(g_type, i_width);
	});	
	$("#"+g_type+"_right_arrow").click( function(){
		right(g_type, g_width, i_width);
	});
	
	if (g_type === "news_list"){
		$("#news_list_gallery").height($(item_list).eq(0).height());
		$("#page_list_li").append('<li id="page_list_0" class="current_page"><a href="" title="">1</a></li>');
		$("#page_list_0").click( function(){
			$(".current_page").removeClass("current_page");
			$(this).addClass("current_page");
			link(g_type, g_width, i_width);
			return false;
		});
		for (var i = 1; i < item_list.length; i++){
			$("#page_list_li").append('<li id="page_list_' + i + '"><a href="" title="">' + (i + 1) + '</a></li>');
			$("#page_list_" + i).click( function(){
				$(".current_page").removeClass("current_page");
				$(this).addClass("current_page");
				link(g_type, g_width, i_width);
				return false;
			});
		}
	}
	
	if (g_type === "banner"){
		timeout_id = setTimeout(function(){
			right(g_type, g_width, i_width);
		}, 7000);
	}
}

function link(g_type, g_width, i_width){
	var page_link_id = $(".current_page").attr('id');
	page_link_id = parseInt(page_link_id.slice(10, 11));
	
	var left = $("#"+g_type+"_gallery").css("left");
	left = parseInt(left.slice(0, left.indexOf("px")));
		
	if (left < "0") {
		$("#"+g_type+"_right_arrow").removeClass('title_right_arrow_disable');
		$("#"+g_type+"_right_arrow").css({
			'cursor' : 'pointer'
		});
	}
	
	var width = $("#"+g_type+"_gallery").width();
	
	if ((width + left) > g_width){
		$("#"+g_type+"_left_arrow").fadeTo('slow', 1);
		$("#"+g_type+"_left_arrow").removeClass('title_left_arrow_disable');
		$("#"+g_type+"_left_arrow").css({
			'cursor' : 'pointer'
		});
	}
	
	var left = -page_link_id*i_width;
	
	if ((width + left) <= g_width) {
		$("#"+g_type+"_right_arrow").addClass('title_right_arrow_disable');
		$("#"+g_type+"_right_arrow").css({
			'cursor' : 'default'
		});
	}
	
	if (left >= 0){
		$("#"+g_type+"_left_arrow").addClass('title_left_arrow_disable');
		$("#"+g_type+"_left_arrow").css({
			'cursor' : 'default'
		});
	}
	item_list = $("#"+g_type+"_gallery").find(".gallery_item")
	
	$("#news_list_gallery").animate({
		'height': $(item_list).eq(page_link_id).height()
	}, 400).clearQueue();
	$("#"+g_type+"_gallery").animate({
		'left': left
	}, 400).clearQueue();
}

function left(g_type, i_width) {
	clearTimeout(timeout_id);
	var left = $("#"+g_type+"_gallery").css("left");
	left = parseInt(left.slice(0, left.indexOf("px")));
		
	if (left < "0") {
		$("#"+g_type+"_right_arrow").removeClass('title_right_arrow_disable');
		$("#"+g_type+"_right_arrow").css({
			'cursor' : 'pointer'
		});

		var k = left%i_width;
		if (k !== 0)
			i_width -= k;

		if (left <= -i_width){
			left = parseInt(left + i_width);
		} else {
			left = 0;
		}

		if (left >= "0"){
			$("#"+g_type+"_left_arrow").addClass('title_left_arrow_disable');
			$("#"+g_type+"_left_arrow").css({
				'cursor' : 'default'
			});
		}
		
		if (g_type === "banner"){
			var qwe = $("#banner_links").find('p').eq(0);
			var asd = parseInt(qwe.text().slice(0, qwe.text().indexOf('/')));
			asd--;
			qwe.text(asd + qwe.text().slice(qwe.text().indexOf('/')));
		}
		$("#"+g_type+"_gallery").animate({
			'left': left
		}, 400).clearQueue();
	} else {
		$("#"+g_type+"_left_arrow").addClass('title_left_arrow_disable');
		$("#"+g_type+"_left_arrow").css({
			'cursor' : 'default'
		});
	}
	if (g_type === "news_list"){
		$(".current_page").removeClass("current_page");
		$("#page_list_" + parseInt(-left/i_width)).addClass("current_page");
		var page_link_id = $(".current_page").attr('id');
		page_link_id = parseInt(page_link_id.slice(10, 11));
		item_list = $("#"+g_type+"_gallery").find(".gallery_item")
		
		$("#news_list_gallery").animate({
			'height': $(item_list).eq(page_link_id).height()
		}, 400).clearQueue();
	}
	
	if (g_type === "banner"){
		timeout_id = setTimeout(function(){
			right(g_type, 550, i_width);
		}, 7000);
	}
};

function right(g_type, g_width, i_width) {
	clearTimeout(timeout_id);
	var left = $("#"+g_type+"_gallery").css("left");
	left = parseInt(left.slice(0, left.indexOf("px")));
	
	var width = $("#"+g_type+"_gallery").width();
	
	if ((width + left) > g_width){
		$("#"+g_type+"_left_arrow").fadeTo('slow', 1);
		$("#"+g_type+"_left_arrow").removeClass('title_left_arrow_disable');
		$("#"+g_type+"_left_arrow").css({
			'cursor' : 'pointer'
		});
		var right_part = width + left - g_width;
		var k = right_part%i_width;
		if (k !== 0)
			i_width += k;
		
		if (right_part >= i_width) {
			left = parseInt(left - i_width);
		} else{
			left = parseInt(left - right_part);
		}

		if ((width + left) <= g_width) {
			$("#"+g_type+"_right_arrow").addClass('title_right_arrow_disable');
			$("#"+g_type+"_right_arrow").css({
				'cursor' : 'default'
			});
		}
		
		if (g_type === "banner"){
			var qwe = $("#banner_links").find('p').eq(0);
			var asd = parseInt(qwe.text().slice(0, qwe.text().indexOf('/')));
			asd++;
			qwe.text(asd + qwe.text().slice(qwe.text().indexOf('/')));
		}
		$("#"+g_type+"_gallery").animate({
			'left': left
		}, 400).clearQueue();
		
		if (g_type === "banner"){
			timeout_id = setTimeout(function(){
				right(g_type, g_width, i_width);
			}, 7000);
		}
	} else {
		if (g_type === "banner"){
			$("#banner_right_arrow").removeClass('title_right_arrow_disable');
			$("#banner_left_arrow").addClass('title_left_arrow_disable');
			var qwe = $("#banner_links").find('p').eq(0);
			qwe.text(1 + qwe.text().slice(qwe.text().indexOf('/')));
			$("#banner_gallery").animate({
				'left': 0
			}, 400).clearQueue();
			timeout_id = setTimeout(function(){
				right(g_type, g_width, i_width);
			}, 7000);
		} else {
			$("#"+g_type+"_right_arrow").addClass('title_right_arrow_disable');
			$("#"+g_type+"_right_arrow").css({
				'cursor' : 'default'
			});
		}
	}
	if (g_type === "news_list"){
		$(".current_page").removeClass("current_page");
		$("#page_list_" + parseInt(-left/i_width)).addClass("current_page");
		var page_link_id = $(".current_page").attr('id');
		page_link_id = parseInt(page_link_id.slice(10, 11));
		item_list = $("#"+g_type+"_gallery").find(".gallery_item")
		
		$("#news_list_gallery").animate({
			'height': $(item_list).eq(page_link_id).height()
		}, 400).clearQueue();
	}
};


jQuery(document).ready(function() {
	jQuery('ul.Nav li ul :last-child a,ul.Nav li ul :last-child span').addClass('Last');
	
	$(".menu_item").hover( function() {
		var j = $(this).find(".sub_menu_item");
		var q = 44;
		for (var i = 0; i < j.length; i++)
		{
			q += j.eq(i).height();
		}
		
		$(this).animate({
			height : q + 'px'
		}, 600);
		
		$(this).clearQueue();
	});
	$('#menu').mouseleave( function() {
		$(".menu_item").animate({
			height : '44px'
		}, 600);
		
		$(this).clearQueue();
	});
	
	
	
	
	
	
$("#spb_link").click( function(){
	$(this).addClass("current_city");
	$("#spb_header_contacts").addClass("current_contacts")
	
	$("#msk_link").removeClass("current_city");
	$("#msk_header_contacts").removeClass("current_contacts")
	
	return false;
})

$("#msk_link").click( function(){
	$(this).addClass("current_city");
	$("#msk_header_contacts").addClass("current_contacts")
	
	$("#spb_link").removeClass("current_city");
	$("#spb_header_contacts").removeClass("current_contacts")
	
	return false;
})

$('#login').focusin( function() {
	if (this.value == 'Логин') this.value = '';
});
$('#login').focusout( function() {
	if (this.value == '') {
		this.value = 'Логин';
	}
});

$('#fakepass').focusin( function() {
	$('#pass').show();
	//$('<input type="password" class="login_input" id="pass">').insertAfter(this);
	$(this).remove();
	$('#pass').focus();
});
	//Обновление дизигна
	
	
	if(window.self != window.top)
        window.top.location = window.self.location;
    var d = document;
    for(var i=0; i < d.links.length; i++) {
		var link = d.links[i];
	    if(link.href.substr(0,8) == 'http://$') {
	    	var arr = link.href.split('$');
	    	if(arr.length >= 4)
	    	    d.links[i].href = 'mailto:'+arr[2]+'@'+arr[1]+arr[3];
	    	if(arr.length > 4)
	    	    for(var j=4; j < arr.length; j++)
	    	        d.links[i].href += '$'+arr[j];
	    	if(link.href.charAt(link.href.length-1) == '/')
	    	    d.links[i].href = d.links[i].href.substr(0,link.href.length-1);
	    }
	}
	jQuery('#search_form input#SearchText').focus(function() {
		if(this.value == 'Поиск...')
		    this.value = '';
	    else
		    jQuery(this).select();
	});
	jQuery('#search_form :submit').click(function() {
		if(jQuery(this).prev().val() == 'Поиск...')
		    return false;
	});
	/*
	jQuery('#message_window a, #error_window a').click(function() {
		jQuery(this).parent().parent().hide(); return false;
	});*/
	jQuery('#city').change(function() {
		var metro = jQuery('#metro');
		if(jQuery(this).val() == '0')
		    jQuery(metro).html('<option>Выберите станцию метро</option>');
		else
		    jQuery(metro).load('/inc/request-handler/metro.php',{"city":jQuery(this).val()});
	});
	var login_form = jQuery('#login_form');
	jQuery(login_form).find('a.Enter').click(function() {
		jQuery(login_form).find('input').removeClass('EI'); jQuery(login_form).submit();
	});
	jQuery(login_form).find('p a').click(function() {
		var li = jQuery(this).parent().parent();
		jQuery(li).hide().prev().hide().prevAll().show();
		jQuery(li).next().hide().nextAll().show();
	});
	var dont_send = jQuery('#user_form ul.LPBlock :last-child input');
	jQuery(dont_send).click(function() {
		var checked = jQuery(this).attr('checked');
		if (checked)
			jQuery(this).parent().prevAll().find('input').removeAttr('checked')
	});
	var ch=jQuery('#user_form ul.LPBlock input');
	jQuery(ch).click(function(){
		var id=jQuery(this).attr('id');
		if (id)
		{
			if (id.substr(0,8)=='Delivery')
				btnchkDoNot('Delivery',id.substring(8));
			else if(id.substr(0,5)=='Goods')
				btnchkDoNot('Goods',id.substring(5));
			else if(id.substr(0,7)=='Channel')
				btnchkDoNot('Channel',id.substring(7));
		}
	});
	
	var city = document.getElementById('UsCity');
	if(city) {
		var metro1 = jQuery(city).nextAll('select');
		var active_station = (metro1 ? String(jQuery(metro1).attr('id')) : 0);
		if(active_station)
		    active_station  = active_station.substr(7);
		jQuery(metro1).load('/inc/request-handler/metro.php',{"city":jQuery(city).val(), "metro":active_station});
	}
	jQuery(city).change(function() {
		jQuery(metro1).load('/inc/request-handler/metro.php',{"city":jQuery(city).val(), "metro":active_station});
	});
	jQuery("#UsBirth").mask("99/99/9999");
	jQuery("#user_form input.ChildBirth").mask("99/99/9999");
	jQuery('#user_form p.AddChild a').click(function() {
		var child_data = jQuery('#children').next(); var count = jQuery(child_data).nextUntil('p').size()+1;
		if(count > 11)
		    return false;
		var clone = jQuery(child_data).clone().removeAttr('id');
		jQuery(clone).find('label, input').each(function() {
     	        jQuery(this).val('');
				if(jQuery(this).hasClass('ChildBirth'))
				    jQuery(this).mask("99/99/9999");
				var name = jQuery(this).attr('name');
			    if(name)
				    jQuery(this).attr('name',name.substr(0,name.length-1)+count);
			    var id = jQuery(this).attr('id');
				if(id)
   				    jQuery(this).attr('id',id.substr(0,id.length-1)+count);
			    var attr_for = jQuery(this).attr('for');
			    if(attr_for)
   				    jQuery(this).attr('for',attr_for.substr(0,attr_for.length-1)+count);
			});
		jQuery(clone).insertBefore(jQuery(this).parent()); return false;
	});
	
	$('#LeftMenu ul').each(function(i) { // Для всех подменюшек
		if ($.cookie('submenuMark-' + i)) {  // Если индекс подменюшки записан в куках сразу ее открываем:
			$(this).show().prev().removeClass('collapsed').addClass('expanded'); // Показываем
		}else {
			$(this).hide().prev().removeClass('expanded').addClass('collapsed'); // Скрываем
		}
		$(this).prev().addClass('collapsible').click(function() { //Добавляем обработчик события
			var this_i = $('#LeftMenu ul').index($(this).next()); // Получаем индекс выбранного подменю
			if (curentSM==this_i) return;
			curentSM=this_i;
			if ($(this).next().css('display') == 'none') {
				//Открывая новое меню мы скрываем все остальные
				$('#LeftMenu ul').each(function(j) {//Перебираем все подменюшки
					if (j != curentSM) { //Кроме новооткрытой
						cookieDel($('#LeftMenu ul').index($(this))); //Чистим куки срзу
					}
				});
				
				setTimeout(function(){
					$('#LeftMenu ul').each(function(j) {//Перебираем все подменюшки
						if (j != curentSM) { //Кроме новооткрытой
							$(this).slideUp(200,function() {
								$(this).prev().removeClass('expanded').addClass('collapsed'); //Скрываем их через 2 секунды
							});
						}
					});
				},2000);
				// :end
				
				$(this).next().slideDown(200,function() { // Show submenu:
					$(this).prev().removeClass('collapsed').addClass('expanded');
					cookieSet(this_i);
				});
			} else {
				
				$(this).next().slideUp(200,function() { // Hide submenu:
					$(this).prev().removeClass('expanded').addClass('collapsed');
					cookieDel(this_i);
					$(this).find('ul').each(function() {
						$(this).hide(0,cookieDel($('#LeftMenu ul').index($(this)))).prev().removeClass('expanded').addClass('collapsed');
					});
				});
			}
		return false;
		}).click(function() {
			 if($(this).next().css('display') == 'none')
				 cookieSet($('#LeftMenu ul').index($(this).next()));
		 });
	});
    $("ul.Nav li").hover(function() {				
				$(this).find("ul").show(250);
			} , function() {
				$(this).find("ul").hide(100);
			});
			
	user_form({ window_id: 'orderregister',
	            button_id: 'orderreg',
                handler: 'reg.php',
				clean: true,
				condition:function(){
					if (!$('#chk_rules').length)
						return true;
					var val=$('#chk_rules').is(':checked');
					if (val)
						return true;
					message('Вы должны согласиться с правилами интернет-магазина');
					return false;	
				},
				dontsubmit: true,
				success: function(){ConfirmOrder();}
						 ,
		        regExp: { name: /^[а-яА-Яa-z][a-zа-яА-Я \-']*[a-zа-яА-Я]$/i,
						  phone: /^[\d\-+() ]{7,40}$/,
						  city: /^[1-9]\d{0,10}$/,
						  login: emailRegEx,
						  UserComment : /^[^\>\<\&]*$/i,
						  address: /^[^\>\<\&]{1,}$/i},
				clean: true
	});
	user_form({ window_id: 'register',
	            button_id: 'send',
                handler: 'registration.php',
				clean: true,
				condition:function(){
					var val=$('#chk_rules').is(':checked');
					if (val)
						return true;
					message('Вы должны согласиться с правилами интернет-магазина');
					return false;	
				},
				success: function() { 
				             message('Вы зарегистрированы.<br /> Для окончания регистрации перейдите по ссылке в письме<br /> отправленном на e-mail адрес, указанный вами при регистрации');
							 $('ul#message_window a').click(function(){
								 document.location='/';
								 });
						 },
		        regExp: { name: /^[а-яА-Яa-z][a-zа-яА-Я \-']*[a-zа-яА-Я]$/i,
						  phone: /^[\d\-+() ]{7,40}$/,
						  city: /^[1-9]\d{0,10}$/,
						  login: emailRegEx },
				          clean: true
	});
	user_form({ window_id: 'user_form',
	            button_id: 'send',
                handler: 'user_settings.php',
				success: function() { 
				                     message('Изменения сохранены');
								 },
		        regExp: { name: /^[a-zа-яА-Я][a-zа-яА-Я \-']*[a-zа-яА-Я]$/i,
						  child_name0: /^([a-zа-яА-Я][a-zа-яА-Я \-']*[a-zа-яА-Я]|)$/i,
						  phone: /^[\d\-+() ]{7,40}$/,
						  pass: /^([a-z0-9]{6,20}|)$/i },
						  authorization: true
	});
	user_form({
		window_id: 'login_form',
		button_id: 'send',
		handler: 'password_recovery.php',
		regExp: {
			login: emailRegEx
		}
	});
	
	user_form({
		window_id: 'remind_form',
		button_id: 'btn_remind',
		handler: 'password_recovery.php',
		regExp: {
			login: emailRegEx
		},
		success: function() { 
			ClosePopup();
			message('На вашу почту придет письмо <br />с новым паролем для авторизации');
		}
	});
	
	user_form({ 
		window_id: 'loginform',
		button_id: 'login_button',
		handler: 'login.php',
		success: function() { 
					//ClosePopup();
					//$('#login_submit').focus().click();
					
					$('#loginform').submit();
					message('Вы успешно авторизованы',false,function(){
						//function(){return false}
						var pageAdress = location.href
						window.location=pageAdress;
						//location.reload();
					
						});
				 },
		regExp: { 
				  pass: /^([a-z0-9]{6,20}|)$/i,
				  login: emailRegEx },
		error: function(msg){
			message("Неверный логин или пароль",1);
			//$('#AuthPopup p.Info').show();
			//$('#AuthPopup p.Info').html(msg);
			//alert(msg);
		}
	});
	
	
	$('a.Login').click(function(){
		$('#AuthPopup p.Info').hide();
		ShowPopup('AuthPopup');
		return false;
	});
	$('a.CloseAuth').click(function(){
		ClosePopup();
		return false;
	});
	$('a.PassRemind').click(function(){
		ShowPopup('PassRemind');
		return false;
	});
	$('a.CloseRem').click(function(){
		ClosePopup();
		return false;
	});
	$('a.CloseMessage').click(function(){
		ClosePopup();
		return false;
	});
	
	$("#loginform").keypress(function (event) {
		if (event.keyCode == 13)
			$('#btn_login').click();
	})
});

function submitForm(){
	
	return false;	
}


function cookieSet(index) {
	$.cookie('submenuMark-' + index, 'opened', {expires: null, path: '/'}); // Set mark to cookie (submenu is shown):
}
function cookieDel(index) {
	$.cookie('submenuMark-' + index, null, {expires: null, path: '/'}); // Delete mark from cookie (submenu is hidden):
}
function user_form(opt) {
	var user_win = document.getElementById(opt.window_id);
    if(user_win) {
		var button = (opt.button_id ? jQuery(user_win).find('#'+opt.button_id) : jQuery(user_win).find(':button'));
		var button='#'+opt.button_id;
		jQuery(button).click(function() {
			if (typeof(opt.condition)=='function')
				if(!opt.condition())
					return false;
		    var data = {};
			if(opt.authorization) {
				data.uid = jQuery.cookie('user_id'); data.sign = jQuery.cookie('user_sign');
			}
			if (opt.session)
				data.sid = jQuery.cookie(opt.session);
			
			var no_error = empty = true;
			jQuery(user_win).find(':text:enabled, :password:enabled, :file:enabled, input:enabled[type=hidden], textarea:enabled, select:enabled').removeClass('EI').each(function() {
					var key = jQuery(this).attr('name'), val = jQuery(this).val();
					if(val)
						empty = false;
					if(jQuery(this).attr('type') != 'file')
						jQuery(this).val(jQuery.trim(val));
					if(opt.regExp[key])
						if(!opt.regExp[key].test(jQuery(this).val())) {
							no_error = false; error(this); return false;
						}
				});
	
			
            var options = {
                type: 'POST',
                url: '/inc/request-handler/'+opt.handler,
                dataType: 'json',
				data: data,
                success: function(result) {
                    if(result.error)
					    if(typeof(opt.error) == 'function')
						    opt.error(result.error);
						else
						    message(decodeURIComponent(result.error),1);
					else if(result.ok) {
						 if(typeof(opt.success) == 'function')
							 opt.success(result.ok);
						 else   
							 message(decodeURIComponent(result.ok));
						 if(opt.clean)
							 jQuery(user_win).find(':not(:radio)').clearFields();
						 jQuery(user_win).find(':password:enabled, :file:enabled').val('');
					 }
                }
            };
			if(no_error && !empty){
				if(!opt.dontsubmit){
					jQuery(user_win).ajaxSubmit(options);
				}
				else{
					if(typeof(opt.success) == 'function')
						opt.success();
				}
			}
			return false;
		});
	}
}

function btnchkDoNot(preId,id)
{
	if(id){
		var i=1;var ch=0;
		while(jQuery('#'+preId+i).length && jQuery('#'+preId+(i+1)).length){
			if (jQuery('#'+preId+i).attr('checked'))
				ch=1;
			i++;
		}		
		if(id==i) ch=0;	
		if (ch)	jQuery('#'+preId+i).removeAttr('checked');
		else jQuery('#'+preId+i).attr('checked','checked');
	}
}
function invalid(field, r, msg) {
    if(!field.disabled  &&  !r.test(field.value))  {
        msg = msg || 'Поле заполнено неверно';
        jQuery(field).addClass('EI'); message(msg,1); field.focus(); field.select(); return true;
    }
    return false;
}
function error(field) {
	jQuery(field).addClass('EI'); field.focus(); message('Поле заполнено неверно',1);  field.select();
}
var emailRegEx = /^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9]([a-z0-9_\-]{0,253}[a-z0-9])?\.){1,3}[a-z]{2,6}$/i;
function emailCloak(domain, userName) { 
	document.write(userName+'@'+domain);
}
function message2(msg, err_msg) {
	var id = (err_msg ? 'error_window' : 'message_window');
	var win = jQuery('#'+id); jQuery(win).find('.Mess p').text(msg);
	jQuery(win).css('left',(jQuery(window).width()-jQuery(win).width())/2).css('top',
	    (jQuery(window).height()-jQuery(win).height())/2+jQuery(window).scrollTop()).
	     stop(true,false).show().delay(5000).fadeOut('slow').css('z-index',5000);
}

function message(msg, err_msg,CB) {
	var id = (err_msg ? 'error_window' : 'message_window');
	var win = jQuery('#'+id); 
	jQuery(win).find('.Mess p').html(msg);
	//ClosePopup();
	//ShowPopup(id,5000);
	ShowPopup(id,0,CB);
}


var popupnow=0;
var popupid_now='';
var popupcallback=null;
var popupCount=0;
var popups=new Array();
var popupCB=new Array();
function ClosePopup(popup){
	if (typeof(popup) == "undefined") popup = popupCount;
	$('#'+popups[popup]).hide();//Скрываем попап
	if (typeof(popupCB[popup]) == "function") popupCB[popup]();//Выполняем колбэк
	delPopup(popup);//Удаляем его из массива
	setIndexes();//Пересчитываем z-index'ы
	if (popupCount==0)//Если нет попапов-скрываем подложку
		$('#modaldiv').hide();
	$('#'+popups[popupCount]).show();//Показываем последний Попап
	//return false;
}

function ShowPopup(popup_id,fadeout,callbackf){
	if (typeof(fadeout) == "undefined") fadeout = 0;
	if (typeof(callbackf) == "undefined") callbackf = 0;
	//ClosePopup();
	popupCount++;
	var popupnow=popupCount; //Номер текущего попапа
	popups[popupnow]=popup_id;//Добавляем попап
	popupCB[popupnow]=callbackf;//Добавляем коллбак
	
	jQuery(window).bind('resize', function(){ //Добавляем перерисовку для попапа
		popupRedraw(popupnow);
	}).trigger('resize');
	//Скрываем все остальные попапы
	for(var i=1;i<popupCount;i++)
		$('#'+popups[i]).hide();//Скрываем все попапы
	setIndexes();//Пересчитываем z-index'ы
	$('#'+popup_id).show();//показываем текущий попап
	$('#modaldiv').show();//Показываем подложку
	popupRedraw(popupnow);//Перерисовываем попап
	if (fadeout){
		if (fadeout<1000)
			fadeout=1000;
		$('#modaldiv').delay(fadeout-1000).fadeOut(1000);
		$('#'+popup_id).delay(fadeout-1000).fadeOut(1000);
		setTimeout(function(){
			if(popups[popupnow]==popup_id && (popupnow<=popupCount))
				ClosePopup(popupnow);
			},fadeout);		
	}
}
function delPopup(p){
	
	for(var i=p;i<popupCount;i++){
		popups[i]=popups[i+1];
		popupCB[i]=popupCB[i+1];
	}
	popupCount--;
}
function setIndexes(){
	for(var i=1;i<=popupCount;i++)
		$('#'+popups[i]).css('z-index',5000+i*100);	
}
function popupRedraw(pp){
	var p=popups[pp];
	$('#modaldiv').css('position', 'fixed').css('left', 0).css('top', 0).css('z-index', 5000)
		.css('height', $(window).height()+'px').css('width', $(window).width()+'px').css('opacity', 0.5);
	$('#'+p).css('position', 'fixed').css('left', ($(window).width() - $('#'+p).width()) / 2)
		.css('top', ($(window).height() - $('#'+p).height()) / 2).css('opacity', 1);
}

