﻿<!-- ГЛАВНОЕ МЕНЮ -->
mainmenu = {			   
	menushow	:null, 
	menuhover	:null,
	menuhide	:null,
	showTM	:null,
	hideTM	:null,
	
	init: function(){
		$('div.mnu a').hover(this.mousein, this.mouseout);				
		$('#cat-tree-container').mouseleave(this.mouseleave);		
		//$('a.cat-support').mouseup(function(){ $(this).removeClass('active'); }).mouseleave(function(){ $(this).removeClass('active'); }).mousedown(function(){ $(this).addClass('active'); });		
	},
	
	mousein: function() { 
		with(mainmenu) {
			menuhide = this; 
			hideMenu(); 
			menushow = this;
			if(showTM) clearTimeout(showTM);
		    showTM = setTimeout( showMenu, 450);
		}
	},
	mouseout: function() {
		with(mainmenu) {
			if(menushow == this) { menushow = null; }
		}
	},
	
	mouseleave: function() {
		with(mainmenu) {
		 	menuhide = this;
		 	if(hideTM) clearTimeout(hideTM);
			hideTM = setTimeout( hideMenu, 650);	
		}
	},
		
	hideMenu: function () {
		with(mainmenu) {
			if(menuhide == null) return;
			 $('.subcat-tree').each(function() {
				 	if($(this).css('top') != "-250px")
				 	$(this).animate({ 'top':"-250px" }, 250, "easeOutCirc", function(){ if(menushow==null) $('#cat-tree-container').css({ top:-1000 }); });			
		 	});  
			menuhide = null; menushow = null; $('div.mnu a').removeClass('active');
		}
	},
	
	showMenu: function () { 
		with(mainmenu) { 			
			if(menushow == null) return;  
			$('#cat-tree-container').css('display', 'block');
			var mitempos = $(menushow).offset(); 			
			$('div.mnu a').removeClass('active');	 					
			$('.subcat-tree').css({'z-index':1, 'top':"-250px"});
			$('#'+$(menushow).attr('class')+'-tree').css({'z-index':9000});
			$('#cat-tree-container').css({ left: mitempos.left+6+'px', top:mitempos.top+$(menushow).height() });
			$('#'+$(menushow).attr('class')+'-tree').animate({ 'top':0  }, 200, "easeOutExpo");			
			$(menushow).addClass('active');	
		}
	}		
};

<!-- ФУНКЦИИ ПОЛЬЗОВАТЕЛЯ -->
customer_handlers = {
	init: function() {
		$('#link_customer_login').click(this.login);
		$('#link_customer_menu').click(this.menu);		
	},
	
	// АВТОРИЗАЦИЯ ПОЛЬЗОВАТЕЛЯ //
	login: function(evnt) {		
		<!-- Если используется обычное соединение, переключаемся в зашифрованное -->
		if( String($(document).attr('location')).indexOf('https') !== 0) {
			document.location = String($(document).attr('location')).replace('http:','https:'); return false;
		}
		
		<!-- Если указан параметр data, отправляем данные на проверку -->
		if(evnt !== undefined && evnt.data) {	
			$.post('/core/session.login', $('#loginFrame form:first').serialize(), function(resp) {
				// Выводим сообщение об ошибке
				
				if(resp.error) alert(resp.error);
				// Если пользователь не активирован, инициализируем активацию
				if(resp.code == 303) customer_handlers.activate();
				if(resp.code == 200) document.location.replace(resp.link);
			}, "json");			
			return false;
		}		

		<!-- Инициализируем диалог авторизации -->
		$('<div>').attr({ id: 'loginFrame' }).css({ 'position':'absolute', 'display':'none', 'width':'350px', 'height':'300px'}).appendTo($("body"));
		$('#loginFrame').load('/core/session/login', {}, function() {
	 		<!-- Инициализируем диалог авторизации -->

			$('#loginFrame').overlay({ expose: { color: '#000', loadSpeed: 100, opacity: 0.30 }, top:'center', 
									 onClose:function(){ document.location = String($(document).attr('location')).replace('https:','http:'); }, closeOnClick: true, api: true}).load();
			
			$('#loginFrame a.submit').bind("click", 'ready', customer_handlers.login);
		});
		return false;
	},
	
	<!-- АКТИВАЦИЯ НОВОГО ПОЛЬЗОВАТЕЛЯ -->
	activate: function(evnt) {
		<!-- Если указан параметр data, отправляем данные на проверку -->
		if(evnt !== undefined && evnt.data !== undefined) {
			$.post('/core/session.activation', $('#loginFrame form:first').serialize(), function(resp) {
				// Выводим сообщение об ошибке
				if(resp.error) alert(resp.error);
				// Если активация прошла успешно, переходим по ссылке
				if(resp.code == 200) document.location.replace( resp.link ); 
			}, "json");						
			return false;
		}
		<!-- Загружаем форму активации -->
		$('#loginFrame').load('/core/session/activation', {}, function() {	
			$('#loginFrame :input[type="submit"]').bind("click", 'ready', customer_handlers.activate);
		});
		return false;
	},
	
	<!-- РЕГИСТРАЦИЯ НОВОГО ПОЛЬЗОВАТЕЛЯ -->
	register: function(stage) {
		switch(stage) { 
			case 1: case 2: case 3: 
				var params = { 'stage':stage };
                
				// Блокируем форму регистрации
				$("#register").block({ message: '<div class="uiblockDataVerify">Проверка данных. Ожидайте...</div>' }); 
                
				// Отправляем данные на проверку
				$.post('/core/session.registration', $("#register").serialize()+'&stage='+stage, function(resp) {
				   // Удаляем текущие сообщения об ошибках
				   $('div.haserror').remove();
				   // Если сервер не вернул данных сообщаем об ошибке
					if(!resp) alert('Сервер не отвечает. Пожалуйста сообщите в поддержку!'); else
				   // Если в данных есть ошибки, выводим сообщения о них
					if(resp.errors != undefined)	{	
						for(var field in resp.errors) { 
							if(!$('#error'+field).size()) {
								var xfield = $('#register :input[name="'+field+'"]:first');
								if( xfield.attr('type') == 'radio' || xfield.attr('type') == 'checkbox' ) {
									xfield.parent().before('<div style="width:'+xfield.parent().width()+ ' auto" id="error'+field+'" class="haserror">'+resp.errors[field]+'</div>');
								} else {
									xfield.addClass('haserror');
									xfield.after('<div id="error'+field+'" class="haserror">'+resp.errors[field]+'</div>');
									xfield.keypress(function() { $('#error'+$(this).attr('name')).remove(); $(this).removeClass('haserror'); $(this).unbind("keypress"); });
									$("#error"+field).width(xfield.width());
								}
							}
						}
					// Если ошибок нет, переходим к следующему шагу
					} else { 
						// Если процесс регистрации завершен успешно, переходим по ссылке
						if(resp.success) { document.location.replace( resp.link ); return false; }
						// Активируем следующий шаг
						$('#register #step'+(stage-1)+'Next').triggerHandler("click", 'verified'); 
					}
					// Разблокируем форму регистрации
					$("#register").unblock();
				}, "json");
				
				return false;
			break;
		
			case undefined: 			
				$.get("/scripts/plugins/jquery.blockui/jquery.blockui.js",{},null, "script");				
				$(function() { $("#register").formToWizard({ 'checker':customer_handlers.register }); $("#stepsForm").show(); });		
		}
	},
	
	
	menu: function() {
		
	}
}

mod_publishers = {
	init: function () {
		//$('input[type=text]').betterTooltip({speed: 150, delay: 300, content:'Введите наименование издания, или город'});
		$('.pager a').click(function() {
			if($(this).hasClass('active')) return false;
			$('#publisher_list').html('<div style="margin:60px auto 60px;"><img src="/images/preloader.gif" /><div>Загрузка...</div></div>');
			$('#publisher_list').load("/press/publishers", { 'page':$(this).html(), 'search':$('#field_search').attr('value') });
			$('.pager a').removeClass('active'); $(this).addClass('active');  return false;			
		});				
	}			
}


$(document).ready(function() {
	 mainmenu.init();
	 customer_handlers.init();
     $('#header_customer_menu li.menu').hover(
	   	function() { $('ul', this).css('display', 'block'); },
		function() { $('ul', this).css('display', 'none'); }
     );	 
});
