var login = (function() {
	
	var main,
		offset,
		z,
		elems = {},
		words = [
			['Яндекс', 24, 0.2, 250, 320],
			['SearchEngines', 22, 0.15, 785, 220],
			['Google', 22, 0.15, 440, 160],
			['Seo', 24, 0.1, 220, 210],
			['Yahoo', 16, 0.2, 280, 180],
			['Linux', 20, 0.15, 290, 275],
			['Web', 26, 0.2, 710, 300],
			['Оптимизация', 22, 0.2, 200, 240],
			['Apple', 16, 0.2, 150, 120],
			['Windows', 18, 0.15, 865, 120],
			['Ссылка', 22, 0.15, 540, 50],
			['Биржа', 20, 0.1, 220, 36],
			['ТиЦ', 16, 0.2, 280, 80],
			['Rambler', 20, 0.15, 140, 165],
			['Дизайн', 22, 0.2, 710, 200],
			['Freelance', 20, 0.2, 770, 350],
			
		];
	
	var style = {
		input: {fill: '90-#a6a1ca-#7770af', stroke: '#293357', 'stroke-opacity': 0.5},
		descr: {'text-anchor': 'start', fill: '#aaa'},
		regver: {'text-anchor': 'start', fill: '#aaa', 'font-size': 14},
	};
	
	function header() {
		elems.logo = z.image('/img/login/logo.png', 215, 50, 570, 105);
		elems.words = [];
		for (var i = 0, l = words.length; i < l; i++) {
			elems.words[i] = z.text(words[i][3], words[i][4], words[i][0]).attr({opacity: words[i][2], 'font-size': words[i][1]});
		}
		//setTimeout(wordsAnimate, 2500);
	}
	
	
	var login = (function() {
		
		var l_input,
			p_input;
		
		function enterToChat() {
			$.ajax({
				type: 'POST',
				url: '/login.php',
				data: { auth: true, login: l_input.val(), pass: p_input.val() },
				success: function(data) {
					if (data.error) alert('error');
					else window.location = "/chat.php";
				},
				dataType: 'json'
			});
			console.log('enter');
		}
		
		function loginfocus() {
			if (l_input.val() == '') elems.loginPanel.text.login.animate({opacity: 0}, 300);
		}
		
		function loginblur() {
			if (l_input.val() == '') elems.loginPanel.text.login.animate({opacity: 0.6}, 300);
		}	
		
		function passfocus() {
			if (p_input.val() == '') elems.loginPanel.text.pass.animate({opacity: 0}, 300);
		}
		
		function passblur() {
			if (p_input.val() == '') elems.loginPanel.text.pass.animate({opacity: 0.6}, 300);
		}
		
		return {
			createPanel: function() {
				l_input = $('#login'),
				p_input = $('#pass');
				elems.loginPanel = {
					panel: z.path('m 359,209 284,0 c 5.54,0 10,4.46 10,10 l 0,130 c 0,5.54 -4.46,10 -10,10 l -81.625,0 c -64.5,-23.125 -56,24.5 -119.125,0 L 359,359 c -5.54,0 -10,-4.46 -10,-10 l 0,-130 c 0,-5.54 4.46,-10 10,-10 z')
							.attr({fill: '90-#1b2147-#4e5186', stroke: 'none', opacity: 0.6}),
					button_rect: z.rect(440, 332, 120, 50, 10).attr({fill: '90-#5660a1-#262071', stroke: 'none', opacity: 0.3}),
					l_input: z.rect(364, 230, 271, 42, 10).attr({fill: '90-#3b4167-#4b5177:40-#2f355b', stroke: 'none'}),
					p_input: z.rect(364, 280, 271, 42, 10).attr({fill: '90-#2b3157-#3b4167:40-#2f355b', stroke: 'none'}),
					text: {
						login: z.image('/img/login/login.png', 374, 240, 94, 25).attr('opacity', 0.6),
						pass: z.image('/img/login/pass.png', 374, 288, 112, 32).attr('opacity', 0.6),
						enter: z.image('/img/login/enter.png', 445, 343, 112, 32),
						reg: z.image('/img/login/reg.png', 220, 380, 180, 20),
						fpass: z.image('/img/login/fpass.png', 600, 380, 190, 20),
					},
					button: z.rect(440, 332, 120, 50, 10).attr({stroke: 'none', fill: '#fff', opacity: 0.1})	
				};
				if (l_input.val() != '') elems.loginPanel.text.login.attr('opacity', 0);
				l_input.css({top: 230, left: offset.left+374});
				p_input.css({top: 280, left: offset.left+374});
				linkCursor([
					elems.loginPanel.text.reg,
					elems.loginPanel.text.fpass,
					elems.loginPanel.text.enter,
					elems.loginPanel.button
				]);
				$(elems.loginPanel.text.reg.node).click(function() {
					alert("Извините, на данный момент проводятся тех. работы - доступ в чат ограничен.\n По всем вопросам - icq: 391299629");
					//register.show();
				});
				observer.attach('window_resize', function() {
					offset = main.offset();
					l_input.css({top: 230, left: offset.left+374});
					p_input.css({top: 280, left: offset.left+374});
				});
				$(elems.loginPanel.button.node).bind({
					click: enterToChat,
					mouseover: function() {
						elems.loginPanel.button.animate({opacity: 0.2}, 500);
					},
					mouseout: function() {
						elems.loginPanel.button.animate({opacity: 0.1}, 300);
					}
				});
				l_input.keypress(function(e) { if (e.keyCode == 13) p_input.trigger('focus') })
				p_input.keypress(function(e) { if (e.keyCode == 13) enterToChat(); });
				l_input.bind({
					focus: loginfocus,
					blur: loginblur
				});
				p_input.bind({
					focus: passfocus,
					blur: passblur
				});
			}
		}
	})();
	
	
	var stat = (function() {
		
		var data = {
			hit_max: 345,
			post_max: 210,
			user_max: 51,
			days: [
				{
					num: 4,
					hit: 221,
					post: 116,
					user: 31
				},
				{
					num: 5,
					hit: 240,
					post: 140,
					user: 23
				},
				{
					num: 6,
					hit: 290,
					post: 126,
					user: 15
				},
				{
					num: 7,
					hit: 318,
					post: 210,
					user: 19
				},
				{
					num: 8,
					hit: 275,
					post: 167,
					user: 44
				},
				{
					num: 9,
					hit: 285,
					post: 190,
					user: 36
				},
				{
					num: 10,
					hit: 345,
					post: 197,
					user: 22
				},
				{
					num: 11,
					hit: 278,
					post: 176,
					user: 19
				},
				{
					num: 12,
					hit: 310,
					post: 196,
					user: 51
				},
				{
					num: 13,
					hit: 340,
					post: 156,
					user: 39
				},
			]
		};
		
		function createValues() {
			var onepr = data.hit_max / 100,
				onepx = 1.7,
				topline = 490,
				xval = 590;
			for (var i = 0, l = data.days.length; i < l; i++) {
				var hit = data.days[i].hit,
					post = data.days[i].post,
					user = data.days[i].user,
					hit_height = Math.floor(Math.floor(hit /onepr) * onepx),
					post_height = Math.floor(Math.floor(post /onepr) * onepx),
					user_height = Math.floor(Math.floor(user /onepr) * onepx),
					hit_y = topline + (170 - hit_height),
					post_y = topline + (170 - post_height),
					user_y = topline + (170 - user_height);
				z.rect(xval, hit_y, 30, hit_height).attr({stroke: 'none', fill: '#162061', opacity: 0.2});
				z.rect(xval, post_y, 30, post_height).attr({stroke: 'none', fill: '#162061', opacity: 0.2});
				z.rect(xval, user_y, 30, user_height).attr({stroke: 'none', fill: '#162061', opacity: 0.4});
				z.text(xval+15, 670, data.days[i].num);
				xval += 34;
			}
			var ply = topline + (170 - Math.floor(Math.floor(data.post_max /onepr) * onepx)),
				uly = topline + (170 - Math.floor(Math.floor(data.user_max /onepr) * onepx)),
				hit_line = z.path('M 535,'+topline+' L 950,'+topline).attr('opacity', 0.4),
				post_line = z.path('M 535,'+ply+' L 950,'+ply).attr('opacity', 0.4),
				user_line = z.path('M 535,'+uly+' L 950,'+uly).attr('opacity', 0.4),
				hit_num = z.text(535, topline + 6, data.hit_max).attr({'text-anchor': 'start', opacity: 0.4}),
				post_num = z.text(535, ply + 6, data.post_max).attr({'text-anchor': 'start', opacity: 0.4}),
				user_num = z.text(535, uly + 6, data.user_max).attr({'text-anchor': 'start', opacity: 0.4});
		}
		
		return {
			createPanel: function() {
				elems.statPanel = {
					panel: z.rect(520, 450, 442, 252, 10).attr({fill: '#5b6189', opacity: 0.7, stroke: 'none'}),
					title: z.image('/img/login/stat.png', 535, 460, 153, 22),
					line: z.path('M 535,660 L 950,660'),
					legenda: {
						user_icon: z.rect(535, 680, 10, 10).attr({stroke: 'none', fill: '#162061', opacity: 0.8}),
						user: z.text(585, 686, 'пользователи'),
						post_icon: z.rect(640, 680, 10, 10).attr({stroke: 'none', fill: '#162061', opacity: 0.4}),
						post: z.text(685, 686, 'сообщения'),
						hit_icon: z.rect(735, 680, 10, 10).attr({stroke: 'none', fill: '#162061', opacity: 0.2}),
						hit: z.text(780, 686, 'просмотры')
					}					
				};
				createValues();
			}
		}
	})();
	
	function news() {
		elems.newsPanel = {
			panel: z.rect(30, 450, 442, 252, 10).attr({fill: '#5b6189', opacity: 0.7, stroke: 'none'}),
			title: z.image('/img/login/news.png', 45, 460, 270, 28)
		};
		$('#news').css({
			top: offset.top + 500,
			left: offset.left + 45
		});
		observer.attach('window_resize', function() {
			offset = main.offset();
			$('#news').css({
				top: offset.top + 500,
				left: offset.left + 45
			});
		});
	}
	
	var register = (function() {
		
		var splash,
			div, z, open = false,
			title, toreg, close,
			rlogin, rnick, remail, rpass;
		
		function focus(el) {
			if (el.elem.val() == '') el.text.animate({opacity: 0}, 300);
		}
		
		function blur(el) {
			if (el.elem.val() == '') {
				el.text.animate({opacity: 1}, 300);
				el.ver.hide();
				el.error.attr('opacity', 0);
			}
			else {
				if (el.elem.attr('id') == 'rlogin') verify(el, 'login');
				if (el.elem.attr('id') == 'rnick') verify(el, 'nick');
				if (el.elem.attr('id') == 'remail') verify(el, 'email');
				if (el.elem.attr('id') == 'rpass') verify(el, 'pass');
			}
		}
		
		function verify(el, vid) {
			$.ajax({
				type: 'POST',
				url: '/register.php',
				data: { mod: 'verify_'+vid, str: el.elem.val() },
				success: function(data) {
					if (data.error) {
						el.ver.hide();
						el.error.attr({'text': data.error, opacity: 1});
						el.iserror = true;
					}
					else {
						el.error.attr('opacity', 0);
						el.iserror = false;
						el.ver.show();
					}
				}, dataType: 'json'
			});
		}
		
		function mg(el) {
			el.rect.animate({stroke: '#b22', 'stroke-width': 4}, 300, function() { 
				el.rect.animate({stroke: '#000', 'stroke-width': 1}, 300, function() { 
					el.rect.animate({stroke: '#b22', 'stroke-width': 4}, 300, function() {
						el.rect.animate({stroke: '#293357', 'stroke-width': 1}, 100);
			}); }); });
		}
		
		function reg() {
			var exit = false;
			if (rlogin.elem.val() == '' || rlogin.iserror) { mg(rlogin);	exit = true; }
			if (rnick.elem.val() == '' || rnick.iserror) { mg(rnick);	exit = true;  }
			if (remail.elem.val() == '' || remail.iserror) { mg(remail);	exit = true;  }
			if (rpass.elem.val() == '' || rpass.iserror) { mg(rpass);	exit = true;  }
			if (exit) return false;
			$.ajax({
				type: 'POST',
				url: '/register.php',
				data: { mod: 'reg', login: rlogin.elem.val(), nick: rnick.elem.val(), email: remail.elem.val(), pass: rpass.elem.val() },
				success: function(data) {
					if (data.error) {
						if (data.error == 'login') mg(rlogin);
						if (data.error == 'nick') mg(rnick);
						if (data.error == 'email') mg(remail);
						if (data.error == 'pass') mg(rpass);
					}
					else {
						toreg.hide();
						window.location = "/chat.php";
					}
				}, dataType: 'json'
			});
			return false;
		}
		
		function closereg() {
			splash.hide();
			div.hide();
			open = false;
		}
		
		return {
			init: function() {
				splash = $('#splashfon');
				$('#splashbox').width(537);				
				div = $('#register');
				splash.show(); div.show();
				z = Raphael('register', 537, 314);
				title = z.image('/register.php?mod=rlogo', 10, 10, 450, 40);
				close = z.image('/img/close.png', 514, 10, 13, 12);
				toreg = z.image('/img/register/toreg.png', 195, 285, 326, 22);
				rlogin = {
					rect: z.rect(13, 60, 330, 30, 10).attr(style.input),
					elem: $('#rlogin'),
					text: z.image('/img/register/rlogin_text.png', 23, 70, 193, 16),
					descr: z.text(23, 100, 'Разрешены латинские буквы, цифры и нижнее подчеркивание').attr(style.descr),
					error: z.text(360, 76, '').attr(style.regver),
					iserror: false,
					ver: z.image('/img/register/check.png', 360, 56, 34, 34).hide()
				};
				rnick = {
					rect: z.rect(13, 115, 330, 30, 10).attr(style.input),
					elem: $('#rnick'),
					text: z.image('/img/register/rnick_text.png', 23, 125, 71, 11),
					descr: z.text(23, 155, 'Разрешены латинские буквы, кирилица, цифры, пробел').attr(style.descr),
					error: z.text(360, 131, '').attr(style.regver),
					iserror: false,
					ver: z.image('/img/register/check.png', 360, 111, 34, 34).hide()
				};
				remail = {
					rect: z.rect(13, 170, 330, 30, 10).attr(style.input),
					elem: $('#remail'),
					text: z.image('/img/register/remail_text.png', 23, 180, 133, 15),
					descr: z.text(23, 210, 'Для подтверждения на почту будет отправлено письмо').attr(style.descr),
					error: z.text(360, 186, '').attr(style.regver),
					iserror: false,
					ver: z.image('/img/register/check.png', 360, 166, 34, 34).hide()
				};
				rpass = {
					rect: z.rect(13, 225, 330, 30, 10).attr(style.input),
					elem: $('#rpass'),
					text: z.image('/img/register/rpass_text.png', 23, 235, 52, 15),
					descr: z.text(23, 265, 'Комбинация букв, цифр, знаков; строка от шести символов').attr(style.descr),
					error: z.text(360, 241, '').attr(style.regver),
					iserror: false,
					ver: z.image('/img/register/check.png', 360, 221, 34, 34).hide()
				};
				splash.hide(); div.hide();
				linkCursor([
					close, toreg
				]);
				$(close.node).click(closereg);
				$(toreg.node).click(reg);
				$(rlogin.elem).bind({ focus: function() { focus(rlogin); }, blur: function() { blur(rlogin); } });
				$(rnick.elem).bind({ focus: function() { focus(rnick); }, blur: function() { blur(rnick); } });
				$(remail.elem).bind({ focus: function() { focus(remail); }, blur: function() { blur(remail); } });
				$(rpass.elem).bind({ focus: function() { focus(rpass); }, blur: function() { blur(rpass); } });
				observer.attach('window_resize', function() {
					if (open) {
						splash.css({width: $(window).width(), height: $(window).height()});
						var offset = div.offset();
						rlogin.elem.css({top: offset.top+62, left: offset.left+14});
						rnick.elem.css({top: offset.top+117, left: offset.left+14});
						remail.elem.css({top: offset.top+172, left: offset.left+14});
						rpass.elem.css({top: offset.top+227, left: offset.left+14});
					}
				});
				
			},
			show: function() {
				open = true;
				splash.css({width: $('#docbody').innerWidth(), height: $('#docbody').innerHeight()});
				splash.show();
				div.show();
				var offset = div.offset();
				rlogin.elem.css({top: offset.top+62, left: offset.left+14});
				rnick.elem.css({top: offset.top+117, left: offset.left+14});
				remail.elem.css({top: offset.top+172, left: offset.left+14});
				rpass.elem.css({top: offset.top+227, left: offset.left+14});
			}
		}
	})();
	
	function linkCursor(els) {
		for (var i = 0, l = els.length; i < l; i++) {
			$(els[i].node).bind({
				mouseover: function() {
					$('#docbody').css('cursor', 'pointer');
				},
				mouseout: function() {
					$('#docbody').css('cursor', 'default');
				}
			});
		}
	}
	
	function wordsAnimate() {
		var l = elems.words.length-1,
			w = [];
		for (var i = 0; i < 10; i++) {
			w[i] = elems.words[rand(0, l, w)];
			var delay = rand(300, 1000);
			w[i].animate({opacity: 0}, delay);
			setTimeout((function(el) {
				return function() { 
					//el.attr('translation', rand(-40, 40)+' '+rand(-40, 40)); 
					el.animate({opacity: rand(5, 20)/100}, 3000+rand(-2000, 3000)); };
			})(w[i]), delay+50);
		}
		setTimeout(wordsAnimate, 7200);		
	}
	
	function rand(min, max, ns) { 
		ns = ns || [];
	    if(max) {
	        var r = Math.floor(Math.random() * (max - min + 1)) + min;
	        if (array_search(r, ns)) return rand(min, max, ns);
	        else return r;
	    } 
	    else {
	        var r = Math.floor(Math.random() * (min + 1));
	        if (array_search(r, ns)) return rand(min, max, ns);
	        else return r;
	    }
	}

	function array_search( needle, haystack, strict ) { 
		
	    strict = !!strict;
	 
	    for(var key in haystack){
	        if( (strict && haystack[key] === needle) || (!strict && haystack[key] == needle) ){
	            return key;
	        }
	    }
	 
	    return false;
	}

	
	return {
		init: function() {
			main = $('#main');
			z = Raphael('main', 1000, 800);
			offset = main.offset();
			header();
			login.createPanel();
			news();
			stat.createPanel();
			register.init();
			var copyright = z.image('/img/login/(c).png', 400, 750, 200, 20);
			$(window).resize(function() {
				observer.notify('window_resize');
			});
			observer.notify('window_resize');
		}
	}
})();

$(document).ready(login.init);

