/*var preload_imgs = [['buttons/account.gif',
'ico/auth.gif',
'auth_bg.gif',
'buttons/basket.gif',
'chatting.gif',
'text/error.gif',
'buttons/gray_hl.gif',
'buttons/gray_hr.gif',
'buttons/gray_l.gif',
'buttons/gray_r.gif',
'buttons/haccount.gif',
'buttons/hbasket.gif',
'buttons/hlogin.gif',
'intro_bg.gif',
'buttons/join.gif',
'loadingAnimation.gif',
'buttons/login.gif',
'text/login.gif',
'main_menu_bg.gif',
'form/not-ok.gif',
'form/ok.gif',
'buttons/ok.gif',
'buttons/quit.gif',
'text/registration.gif',
'form/required.gif',
'text/restore-pass.gif',
'to_do_bg.gif',
'ill.jpg',
'fake/promo_1.jpg',
'fake/promo_2.jpg',
'bg.png',
'text/chatting_menu.png',
'text/ideas.png',
'ico/intro.png',
'text/intro.png',
'logo.png',
'macFFBgHack.png',
'text/menu.png',
'select.png'], []];

for(i=0;i<preload_imgs[0].length;i++){
	preload_imgs[1][i] = new Image();
	preload_imgs[1][i].src = 'img/'+preload_imgs[0][i];
}
*/

var moodChangerEnabled = true

$(document).keydown(
	function (currentEvent)
	{
		switch (currentEvent.keyCode)
		{
			case 27:
				top.tb_remove()
			break
		}
	}
)
/*
$(document).ready(
	function ()
	{
		$('<span id="modalClose" onclick="top.tb_remove();"></span>').appendTo('#modal')
		setTimeout(
			function()
			{
				$('.autoFocus').focus()
			},
			50
		)
	}
)
*/
$(document).ready(
	function()
	{
		// validator cheat
		$('a.external').attr('target', '_blank');
		
		$('<span id="modalClose" onclick="top.tb_remove();"></span>').appendTo('.modalWindow')


		$('a[href].popup').click(
			function ()
			{
				window.open( $(this).attr('href') )
				return false
			}
		)

		$('#intro ol a').hover(
			function()
			{
				$(this).parent().parent().children('h3').addClass('hover');
			},
			function()
			{
				$(this).parent().parent().children('h3').removeClass('hover');
			}
		)
		
		// Трешовщина
		$('span.gray-button').hover(
			function()
			{
				$(this).addClass('hover-gray-button');
			},
			function()
			{
				$(this).removeClass('hover-gray-button');
			}
		)

		// mood changer
		var mood = $('#mood')
		mood = mood.filter('.enabled')

		if ( mood.length == 1 )
		{
			var moodText = $('span', mood)
			var moodChanger = $('<input type="text" maxlength="60" style="display:none;height:22px;width:100%;/*border:none;*/font-size:13px;/*background:transparent*/;font-family:"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif;"/>')

			moodChanger.blur(
				function ()
				{
					moodChanger.css('display', 'none')
					mood.css('display', 'block')
				}
			)

			moodChanger.keyup(
				function (event)
				{
					switch (event.keyCode)
					{
						case 13:
							if( moodChangerEnabled )
							{
								moodChangerEnabled = false
								
								var newText = $(this).val()

								$.get(
									'/profile/index.html',
									{
										action: 'setMood',
										mood: newText
									}
								)

								if ( newText.length == 0 )
								{
									newText = '[ пусто ]'
								}

								moodText.text( newText )

								moodChanger.css('display', 'none')
								mood.css('display', 'block')
								
								setTimeout(
									function()
									{
										moodChangerEnabled = true
									}, 500
								)
							}
						break
						case 27:
							moodChanger.css('display', 'none')
							mood.css('display', 'block')
						break
					}
				}
			)

			moodChanger.insertAfter(mood)

			mood.click(
				function ()
				{
					mood.css('display', 'none')

					moodChanger.css('display', 'block')
//					moodChanger.css('position', 'relative')
//					moodChanger.css('left', '-' + mood.width() + 'px')
//					moodChanger.css('width', mood.width() + 'px')
//					moodChanger.css('margin-right', '-' + mood.width() + 'px')

					var newVal = moodText.text()
					if ( newVal == '[ пусто ]' )
					{
						newVal = ''
					}

					moodChanger.val( newVal )
					moodChanger.focus()
				}
			)
		}
		
		/* Форма ввода email нового подписчика */
		var contents = $('#modal-subscribeEmailForm div.modalPadding')
		
		if( contents.length > 0 ){
			modalSubscribeEmailFormContent =
				new modalContents(
					contents,
					{
						'mc-subscribeEmailForm-input':
							function()
							{
								setTimeout(
									"$('#mfsei-email').focus()",
									100
								)
							}
					}
				)
			
			var subscribeEmailForm = $('#subscribe-email-form')
			
			/* включаем валидацию для формы ввода емейла */
			/*subscribeEmailForm.validateForm(
				{
					submitSelector: 'input[type=image]',

					markAssociatedLabel: false,
					helpText: null,
					
					valueRegexp:
					{
						'mfsei-email': /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/
					},
					
					passedHandler:
						function ( submit, helpText )
						{
							submit.removeAttr('disabled')
							submit.attr('src', '/img/buttons/ok/normal.gif')
						},
					failedHandler:
						function ( submit, helpText )
						{
							submit.attr('disabled', 'disabled')
							submit.attr('src', '/img/buttons/ok/disabled.gif')
						}
				}
			)*/
			
			subscribeEmailForm.submit(
				function()
				{
					$('#subscribe-email-link').click()
					
					return false
				}
			)
			
			$('#subscribe-email-link').click(
				function()
				{
					$.post(
						'/subscribe/addEmail.html',
						{
							email: $('#subscribe-email-form-input').val()
						},
						function (response)
						{
							response = parseInt(response)
							
							tb_show(null, '/?TB_inline&height=300&width=600&inlineId=modal-subscribeEmailForm&modal=true', null)
							
							switch ( response )
							{
								case 0:
									$('#subscribe-email-form-input').val('').blur()

									modalSubscribeEmailFormContent.select( 'mc-subscribeEmailForm-fail' )
								break;
								case 1:
									modalSubscribeEmailFormContent.select( 'mc-subscribeEmailForm-success' )
								break;
								case 2:
									modalSubscribeEmailFormContent.select( 'mc-subscribeEmailForm-exist' )
								break;
								case 3:
									modalSubscribeEmailFormContent.select( 'mc-subscribeEmailForm-exist-user' )
								break;
							}
						}
					)
					return false
				}
			)
			
			// Лабель идёт в инпут
			var emailLabel = $('label', subscribeEmailForm),
				emailLabelText = emailLabel.text(),
				emailInput = $('input', subscribeEmailForm)
			
			emailLabel.remove()
			
			emailInput.focus(
				function()
				{
					if( emailInput.val() == emailLabelText )
						emailInput.val('')
					
					emailInput.removeClass('empty')
				}
			)
			
			emailInput.keydown(
				function()
				{
					emailInput.removeClass('empty')
				}
			)
			
			emailInput.blur(
				function()
				{
					if( emailInput.val() == '' || emailInput.val() == emailLabelText )
						emailInput.val( emailLabelText ).addClass('empty')
					else
						emailInput.removeClass('empty')
				}
			)
			
			emailInput.blur()
		}
		
		/* Добавление пользователя в подписчики */
		contents = $('#modal-subscribeUserForm div.modalPadding')
		
		if( contents.length > 0 ){
			modalSubscribeUserFormContent = new modalContents( contents, {} )
			
			$('#subscribe-email').click(
				function ()
				{
					$.post(
						'/profile/changeSubscribe.html',
						{
							subscribe: '1'
						},
						function (response)
						{
							response = parseInt(response)

							switch ( response )
							{
								case 0:
									tb_show(null, '/?TB_inline&height=300&width=600&inlineId=modal-subscribeUserForm&modal=true', null)
									modalSubscribeUserFormContent.select( 'mc-subscribeEmailForm-fail' )
								break;
								case 1:
									tb_show(null, '/?TB_inline&height=300&width=600&inlineId=modal-subscribeUserForm&modal=true', null)
									modalSubscribeUserFormContent.select( 'mc-subscribeEmailForm-success' )
								break;
								case 2:
									tb_show(null, '/?TB_inline&height=300&width=600&inlineId=modal-subscribeUserForm&modal=true', null)
									modalSubscribeUserFormContent.select( 'mc-subscribeEmailForm-exist' )
								break;
							}
						}
					)

					return false
				}
			)
		}
		
		// Раскрывающееся меню категорий
		$('#content .store-menu strong').click(
			function()
			{
				var list = $(this).siblings('ul')
				
				if( list.is(':hidden') )
				{
					list.show()
				}
				else{
					list.hide()
				}
			}
		)
	}
)

var activationExpiresContent = null

function activationExpiresContentReset( byLogin )
{
//	var text
//	if ( typeof byLogin == 'undefined' )
//	{
//		text = 'Прошло больше 72 часов с момента регистрации, и ссылка устарела.'
//	}
//	else
//	{
//		text = 'Перед входом необходимо активировать учётную запись.'
//	}
//	$('#mfae-hint').text(text)

	modalLoginContent.hideAll()
	activationExpiresContent.reset()
}

var activationExpiresFormValidator = false
function createActivationExpiresFormValidator()
{
	if ( !activationExpiresFormValidator )
	{
		var modalExpiresItems = $('div.modal-activationExpires')
		var expiresInputEmailForm = $('form#mcfae', modalExpiresItems)
		expiresInputEmailForm.validateForm(
			{
				submitSelector: 'input[type=image]',

				markAssociatedLabel: false,
				helpText: null,

				valueRegexp:
					{
						'mcfae-email': /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
					},

				passedHandler:
					function ( submit, helpText )
					{
						submit.removeAttr('disabled')
						submit.attr('src', '/img/buttons/restore/normal.gif')
					},
				failedHandler:
					function ( submit, helpText )
					{
						submit.attr('disabled', 'disabled')
						submit.attr('src', '/img/buttons/restore/disabled.gif')
					}
			}
		)


		expiresInputEmailForm.submit(
			function ()
			{
				var self = this

				$.post(
					'/registration/reActivation.html',
					{
						login: $('#mfl-login').val(),
						email: $('#mcfae-email', this).val(),
						password: $('#mcfae-password', this).val(),
						key: $('#mcfae-key', this).val()
					},
					function (response)
					{
						var parsedResponse = parseInt(response)
						switch ( parsedResponse )
						{
							case 0:
								if ( typeof(activationFailedContent) != 'undefined' )
								{
									activationFailedContent.hideAll()
								}
								activationExpiresContent.select('modal-activationExpires-email-invalid')
								$('#mcfae-email', self).val('')
							break;
							case 1:
								if ( typeof(activationFailedContent) != 'undefined' )
								{
									activationFailedContent.hideAll()
								}
								activationExpiresContent.select('modal-activationExpires-sended')
							break;
							case 2:
								if ( typeof(activationFailedContent) != 'undefined' )
								{
									activationFailedContent.hideAll()
								}
								activationExpiresContent.select('modal-activationExpires-email-not-own')
							break;
						}
					}
				)

				return false
			}
		)

		activationExpiresFormValidator = true
	}
}

function createModalActiovationExpiresContent()
{
	if ( activationExpiresContent == null )
	{
		var modalExpiresItems = $('div.modal-activationExpires')

		activationExpiresContent =
			new modalContents(
				modalExpiresItems,
				{
					'modal-activationExpires-sended' : function()
					{
						$('#TB_ajaxContent').height(300);
					},
					'modal-activationExpires-email-invalid' : function()
					{
						$('#TB_ajaxContent').height(300);
					},
					'modal-activationExpires-email-not-own' : function()
					{
						$('#TB_ajaxContent').height(300);
					}
				},
				true
			)
		createActivationExpiresFormValidator()
	}
}
