$(function() {
	//.story-item .announcement a
	var storyPopup;

	function makePopUp(){
		if (storyPopup) storyPopup.remove();

		var w = 580,
			h = 525,
			top = Math.ceil(($(window).height() - h) / 2);

		storyPopup = $('<div id="story-popup"><iframe src="'+this.href+'" frameborder="0" scrolling="no" /><a href="#" id="story-popup-close">закрыть</a></div>')
			.css({
				left: ($(document.body).width() - w) / 2,
				top: (top < 0 ? 10 : top) + $(document).scrollTop()
			})
			.appendTo('body')
			.bb({offset: 10, bg: true});


		$('#story-popup-close').click(function(){
			storyPopup.remove();
			storyPopup = null;
			return false;
		});

		return false;
	}
	$('body.publications-storyList p.announcement a, body.publications-storyList p.text a, body.publications-storyListAll p.announcement a, body.publications-storyListAll p.text a').click(makePopUp);
	$('body.cannes-index .film-big a.more, body.cannes-index .film-big .comment a').live('click', makePopUp);

	// #content img
	//if ($.browser.msie && $.browser.version < 8) {
		$('#content img[align=left]').addClass('align-left');
		$('#content img[align=center]').addClass('align-center');
		$('#content img[align=right]').addClass('align-right');
	//}


	// idias
	$('body.publications-ideas .idia .text').click(function(){
		$(this).parent().parent()
			.toggleClass('idia-open')
			.next().toggle();
	});

	// comments
	function moveCommentForm(elm)
	{
		$('#comment_form').insertAfter(elm);
		$('div.decorate-wrap', '#comment_form').remove();
		decorateText.call($('#comment_form textarea.decorate')[0]);
		$('#comment_form textarea').focus();
	}

	$('div.comments .reply, body.publications-ideas .idia .reply').click(function(){
		moveCommentForm($(this).parent());
		$('#comment_content_id').val(this.onclick());
		$('#comment_parent_id').val('');
		$('#comment_mode').val('add');
		$('#comment_form button.delete').hide();
		return false;
	});

	$('div.comments .reply_comment').click(function(){
		var params = this.onclick();
		moveCommentForm($(this).parent());
		$('#comment_content_id').val(params[0]);
		$('#comment_parent_id').val(params[1]);
		$('#comment_mode').val('add');
		$('#comment_form button.delete').hide();
		return false;
	});

	$('div.comments .edit').click(function(){
		var params = this.onclick();
		moveCommentForm($(this).parent());
		$('#comment_content_id').val(params[0]);
		$('#comment_parent_id').val(params[1]);
		$('#comment_mode').val('edit');
		$('#comment_text').val($.trim($(this).parent().prev().text()));
		$('#comment_form button.delete').show();
		return false;
	});

	$('#comment_form').submit(function(){
		var mode = $('#comment_mode').val();
		if($('#comment_text').val() == '')
		{
			return false;
		}

		if($('#comment_text').val().length > 500)
		{
			alert("Комментарий не может содержать больше 500 символов");
			return false;
		}

		if(mode == "delete")
			return confirm("Вы действительно хотите удалить комментарий?");
		else if(mode == "edit")
			return confirm("Вы действительно хотите отредактировать комментарий?");
		return true;
	});

	$('#comment_form button.delete').click(function(){
		$('#comment_mode').val('delete');
	});

	// form decorate
	$(':checkbox, :radio').addClass('input-checkbox');
	function decorateText()
	{
		var t = $(this);
		var offset = 5;

		if (t.is('select')) {
			var wrap = $('<div class="decorate-wrap"><div class="body"/></div>').insertBefore(this).css({
				width: t.outerWidth(),
				height: t.outerHeight(),
				top: this.offsetTop,
				left: this.offsetLeft
			});
			offset = [3, 5, 3, 5];
		} else {
			p = t.position();
			var wrap = $('<div class="decorate-wrap"><div class="body"/></div>').insertBefore(this).css({
				width: t.outerWidth(),
				height: t.outerHeight(),
				top: p.top + (parseInt(t.css('marginTop')) || 0),
				left: p.left + (parseInt(t.css('marginLeft')) || 0)
			});
		}

		if (t.attr('id') === 'auth_email' || t.attr('id') === 'auth_password') {
			wrap.addClass('decorate2-wrap');
			offset = [4, 5, 4, 5];
		}
		wrap.bb({offset: offset, bg: true});
	};

	var elDecorate = $(':text, textarea, input[type=password], input[type=file], select')
		.not('#medal-forms textarea, #main-festival-cannes form input, body.cannes #comment_form textarea');

	if(($.browser.msie && $.browser.version < 8)){
		elDecorate = elDecorate.not('body.modal :input');
	}
	elDecorate.addClass('decorate').each(decorateText);

	var radio;

	function checkboxCheck()
	{
		if (!this.decr) return;
		if ($(this).attr('checked')) {
			this.decr.addClass('decorate-checkbox-wrap-checked');
			if ($(this).hasClass('small'))
				this.decr.addClass('decorate-checkbox-small-wrap-checked');
		}
		else {
			this.decr.removeClass('decorate-checkbox-wrap-checked');
			this.decr.removeClass('decorate-checkbox-small-wrap-checked');
		}
	}

	$(':checkbox, :radio').each(function(){
		var t = $(this).addClass('decorate-checkbox').css('opacity', 0).change(function(){
			if ($(this).is('input[type=radio]')) {
				$('input[name='+t.attr('name')+']').not(this).each(function(){
					checkboxCheck.apply(this);
				});
			}
			checkboxCheck.apply(this);
		}).click(function(){t.change()});
		var decr = this.decr = $('<div class="decorate-checkbox-wrap"><div/></div>').insertBefore(this).css({
			top: this.offsetTop,
			left: this.offsetLeft
		});

		if (t.hasClass('small')) {
			t.addClass('decorate-checkbox-small');
			decr.addClass('decorate-checkbox-small-wrap');
		}

	}).change();


	///
	$('#razdel-content img[align="center"]').addClass('center');

	// top login
	(function(){

		var email = $('#top-user input.email');
		var password = $('#top-user input.password');

		if(email.val() == ''){
			email.addClass('pholder-email');
		}
		if(password.val() == ''){
			password.addClass('pholder-password');
		}

		email.focus(function(){
			email.removeClass('pholder-email');
		})
		password.focus(function(){
			password.removeClass('pholder-password');
		})

		email.blur(function(){
			if(email.val() == ''){
				email.addClass('pholder-email');
			}
		})
		password.blur(function(){
			if(password.val() == ''){
				password.addClass('pholder-password');
			}
		})

		var tick = setInterval(function(){
			if(password.val() != '') password.removeClass('pholder-password');
		}, 100);
		
	})();

	$('#form3col div.show-options').length && $('#form3col div.show-options').fadeTo(0, 0.85);
//	setTimeout(function(){
//		$('#razdel-content .scrollbox').length && $('#razdel-content .scrollbox').jScrollPane({showArrows:true, scrollbarWidth: 8, scrollbarMargin: 22, arrowSize: 4});
//	}, 10);


	// подсказки ошибок
	$('form .error_list').each(function(){
		var input = $(this).prev().addClass('error');
		var val = input.val();

		var tik = setInterval(function(){
			if (input[0].offsetLeft + 4 != underline[0].offsetLeft) {
				underline.css('left', input[0].offsetLeft + 4);
			}
			if (input.val() === val) return;
			input.removeClass('error');
			clearInterval(tik);
			hint.remove();
			underline.remove();
			underline = hint = tik = val = input = null;
		}, 100);

		var underline = $('<div class="error-underline"/>')
			.css({
				top: input[0].offsetTop + input[0].offsetHeight,
				left: input[0].offsetLeft + 4,
				width: input.outerWidth() - 8
			})
			.click(function(){
				input.click().focus();
			})
			.insertAfter(input);

		var hint = $('<div class="error-hint"/>')
			.html('<ul>'+this.innerHTML+'</ul>')
			.appendTo(document.body);

		var w = hint[0].offsetWidth,
			h = hint[0].offsetHeight;
		hint.hide();

		var ie7 = ($.browser.msie && $.browser.version < 8);
		hint.pos = function(e) {
			var mx = document.body.offsetWidth + (ie7 ? document.body.parentNode.scrollLeft : window.scrollX),
				y = e.pageY + 10, x = e.pageX + 3;
			if (w + x > mx) x = mx - w - 1;
			hint.css({top: y, left: x});
			return this;
		};

		$([input[0], underline[0]]).mouseover(function(e){
			hint && hint.pos(e).show();
		}).mouseout(function(){
			hint && hint.hide();
		}).mousemove(function(e){
			hint && hint.pos(e);
		});
	});

	// сообщение
	$('div.modal-window-message').each(function(){
		if ($.trim(this.innerHTML) == '') return;

		$('body').append(
			'<div id="modal-window" style="display:none">' +
				'<div class="mw-top"></div>' +
				'<a href="" class="simplemodal-close" title="Закрыть">закрыть</a>' +
				'<div class="mw-content">' +
					$(	this).html() +
				'</div>' +
				'<div class="mw-bottom">' +
				'</div>' +
			'</div>'
		);

		$('#modal-window').modal({
			opacity:50,
			overlayCss: {backgroundColor:"#fff"},
			minHeight: 100
		});

		return false;
	});


});

/*
 * выводит модальное окно с сообщением
 * cl - string - класс dom элемента из которого будет взят html
 * msgHtml - string - html
*/
function showModalWindow(cl, msgHtml){

	var msg;
	
	if(msgHtml){
		msg = msgHtml;
	} else {
		msg = $('.' + cl).html();
	}

	$("#modal-window").remove();

	$('body').append(
		'<div id="modal-window" style="display:none">' +
			'<div class="mw-top"></div>' +
			'<a href="" class="simplemodal-close" title="Закрыть">закрыть</a>' +
			'<div class="mw-content">' +
				msg +
			'</div>' +
			'<div class="mw-bottom">' +
			'</div>' +
		'</div>'
	);

	$('#modal-window').modal({
		opacity:50,
		overlayCss: {backgroundColor:"#fff"},
		minHeight: 100
	});
}



function showAuthWindow(fn)
{
	window.AUTH_CALLBACK = fn;
	
	var win = $([
		'<div id="modal-iframe-win" style="width: 400px; background: #000; padding: 20px 40px; border: solid 2px #b49675; -moz-border-radius: 5px; -webkit-border-radius: 5px; ">',
			'<div style="padding: 0 0 10px; text-align: center;">',
				'<input id="link-action-register" type="radio" name="link-action" checked="checked"> <label for="link-action-register">Зарегистрироваться</label>',
				'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
				'<input id="link-action-login" type="radio" name="link-action"> <label for="link-action-login">Уже зарегистрирован</label>',
			'</div>',
			'<iframe id="modal-iframe" src="',BASE_PATH,'modal/register" frameborder="0" scrolling="no" style="background: transparent; width: 100%; height: 290px;"/>',
		'</div>'
	].join('')).appendTo('body');
	$('#link-action-register').click(function(){
		$('#modal-iframe').attr('src', BASE_PATH+'modal/register').height(290);
	});
	$('#link-action-login').click(function(){
		$('#modal-iframe').attr('src', BASE_PATH+'modal/login').height(120);
	});
	
	win.modal({
		opacity:50,
		overlayCss: {backgroundColor:"#fff"},
		minHeight: 100,
		onClose: function() {
			$.modal.close();
			$('#modal-iframe-win').remove();
		}
	});
}

function authorizeUser(user)
{
	$.modal.close();
	window.USER_AUTH = 1;
	window.USER = user;
	
	$('#top-user').empty().append([
		'<dl>',
				'<dt>',
					user.avatar ? '<img src="'+user.avatar+'" width="50" alt="'+user.name+'" />' : '',
			'</dt>',
			'<dd>',
				'<p class="hello">',
					'Здравствуйте,<br />',
					'<em>', user.name, '</em>',
				'</p>',
				'<p>',
					'<a href="', BASE_PATH, 'user/edit/">Личный кабинет</a><br/>',
					'<a href="', BASE_PATH, 'logout/">Выход</a>',
				'</p>',
			'</dd>',
		'</dl>'
		].join(''));
	
	if (window.AUTH_CALLBACK) window.AUTH_CALLBACK(user);
}



