/* Copyright (c) 2007 Onlyweb Studio | http://www.onlyweb.ru/ */
/*

Author: Miha Zimin 

Big thanks to http://jquery.org/
Big thanks to http://prototypejs.org/

From Russia with love!

*/

var newClass = function() {
	return function() {
		return this.init.apply(this, arguments);
	}
}

var Onlyweb = {};
var App = {};

/**
Static methods for working with images
*/
Onlyweb.Images = {
	preload: function(a) {
		var cache = [];
		for(var i = 0; i < a.length; i++) {
			cache[i] = new Image();
			cache[i].src = a[i];
		}
	}
};


Onlyweb.Messages = {
	generateHtml: function(content,fwidth) {
		var str = 
		'<table id="message_table" style="width:' + fwidth + 'px"><tbody>' +
		'<tr><td id="message_lt_cell"></td><td id="message_t_cell"></td><td id="message_rt_cell"></td></tr>' +
		'<tr><td id="message_l_cell"></td><td id="message_c_cell">' + content + '</td><td id="message_r_cell"></td></tr>' +
		'<tr><td id="message_lb_cell"></td><td id="message_b_cell"></td><td id="message_rb_cell"></td></tr>' +
		'</tbody></table>';	
		return str;
	}
};

$.extend($.blockUI.defaults, {
	
	pageMessage: Onlyweb.Messages.generateHtml(
		'<div class="BlockMessage">' +
		'<div class="Image"><img src="images/indicator_big.gif" width="32" height="32" /></div><div class="Wait">пожалуйста, подождите</div>' +
		'</div>'
	),
	
	overlayCSS: {
		backgroundColor: '#000',
		opacity: '0.3'
	},
	
	pageMessageCSS: {
		width: '450px',
		margin: '-50px 0 0 -225px',
		top: '50%',
		left: '50%',
		textAlign: 'center',
		color:'#000'/*,
		backgroundColor:'#fff'*/
	},
	
	displayBoxCSS: {
		width: '600px',
		height: '525px',
		top:'50%',
		left:(screen.width/2)/*,
		background: '#ffffff'*/
	},
	
	closeMessage: 'Кликните, чтобы закрыть'
	
});


App.ArticlesMenu = newClass();
App.ArticlesMenu.prototype = {
	
	init: function(p) {
		var t = this;
		t.p = p;
		
		t.articlesMenu = $('#' + t.p.articlesMenu);
		t.articlesMenuContainer = $('#' + t.p.articlesMenuContainer);
		
		/* First item of menu is current by default */
		t.current = 0;
		
		t.articlesMenuItems = {};
		t.articlesMenu.find('.' + t.p.articlesMenuItemC).each(function(i) {
			var index = $(this).attr('id').replace(t.p.articlesMenuItemPrefix, '');
			t.articlesMenuItems[index] = $(this);
			t.articlesMenuItems[index].find('a').click(function(e) {
				return t.menuItemClick(e);
			});
			if(this.className=='AMItem Selected'){t.current = i}
		});
				
		t.articlesSubmenus = {};
		t.articlesMenuContainer.find('.' + t.p.articlesSubmenuC).each(function(i) {
			var index = $(this).attr('id').replace(t.p.articlesSubmenuPrefix, '');
			t.articlesSubmenus[index] = $(this);
		});
		t.articlesMenuItems[t.current].addClass(t.p.selectedC);
		t.articlesSubmenus[t.current].css('display', 'block');
	},
	
	menuItemClick: function(e) {
		var t = this;
		var element = $(e.target);
		var li = element.parents('li.' + t.p.articlesMenuItemC);
		
		if(t.current != undefined) {
			t.articlesMenuItems[t.current].removeClass(t.p.selectedC);
			t.articlesSubmenus[t.current].css('display', 'none');
		};
		
		t.current = li.attr('id').replace(t.p.articlesMenuItemPrefix, '');
		
		li.addClass(t.p.selectedC);
		t.articlesSubmenus[t.current].css('display', 'block');
		
//	return false;
	}
};



App.Gallery = newClass();
App.Gallery.prototype = {
	
	init: function(p) {
		var t = this;
		t.p = p;
		
		t.indexPhotoGallery = $('#' + this.p.indexPhotoGallery);
		t.indexPhotoGallery.css('display', 'block');
		
		t.gallery = $('#' + this.p.gallery);
		
		t.shuffle();
		
		var f = Math.round(this.photos.length / 2 - 3);
		t.firstCurrentIndex = f < 0 ? 0 : f;
		
		t.createFirstPhotoGalleryImages();
		
		t.initButtons();
		
	},
	
	shuffle: function() {
		var t = this;
		
		t.photos = [];
		t.len = t.p.photos.length;
		
		for(var i = 0; i < t.len; i++) {
			t.photos[i] = t.p.photos[i];
		}
		
		/* We'll shuffle the array */
		
		for(var i = 0; i < t.len; i++) {
			var a = Math.round(Math.random()*100000) % t.len;
			var b = Math.round(Math.random()*100000) % t.len;
			var x = t.photos[a];
			t.photos[a] = t.photos[b];
			t.photos[b] = x;
		};
		
		
		/* Add 3 photos from the beginning to the end */
		for(var i = 0; i < 3; i++) {
			t.photos[t.len + i] = t.photos[i];
		}
	},
	
	initButtons: function() {
		var t = this;
		
		t.downButton = t.indexPhotoGallery.find('.' + t.p.downButtonClassName);
		t.upButton = t.indexPhotoGallery.find('.' + t.p.upButtonClassName);
		
		t.downButton
		.click(function(event) {
			return t.downButtonClick(event);
		})
		.mouseover(function(event) {
			return t.downButtonMouseover(event);
		})
		.mouseout(function(event) {
			return t.downButtonMouseout(event);
		});
		
		t.downButton.fadeTo("fast", 0.50);
		
		t.upButton
		.click(function(event) {
			return t.upButtonClick(event);
		})
		.mouseover(function(event) {
			return t.upButtonMouseover(event);
		})
		.mouseout(function(event) {
			return t.upButtonMouseout(event);
		});
		
		t.upButton.fadeTo("fast", 0.50);
		
	},
	
	increaseIndex: function() {
		var t = this;
		
		if(t.currentFirstPhotoIndex + 1 < t.len) {
			t.currentFirstPhotoIndex++;
		} else {
			t.currentFirstPhotoIndex = 0;
		}
	},
	
	decreaseIndex: function() {
		var t = this;
		
		if(t.currentFirstPhotoIndex > 0) {
			t.currentFirstPhotoIndex--;
		} else {
			t.currentFirstPhotoIndex = t.len - 1;
		}
	},
	
	downButtonClick: function(event) {
		var t = this;
		
		t.increaseIndex();
			
		// add new element
		t.gallery.append(t.createNewPhotoGalleryImage(t.currentFirstPhotoIndex + 3, (4 * t.p.photoGalleryImageHeight.replace(/px$/, '')) + 'px'));
		
		var deleted = false;
		
		t.gallery.find('.' + t.p.photoGalleryImageClassName).animate({
			top: ('-' + t.p.photoGalleryImageHeight)
		},
		"slow",
		"linear",
		function() {
			if(!deleted) {
				// delete first element, when animation end off (if we didn't do it in past time)
				t.gallery.find('.' + t.p.photoGalleryImageClassName + ':first').remove();
				deleted = true;
			}
		});
	},
	
	downButtonMouseover: function(event) {
		this.downButton.fadeTo("normal", 0.70);
	},
	
	downButtonMouseout: function(event) {
		this.downButton.fadeTo("normal", 0.50);
	},
	
	
	upButtonClick: function(event) {
		var t = this;
		
		t.decreaseIndex();
		
		// add new element
		this.gallery.prepend(this.createNewPhotoGalleryImage(this.currentFirstPhotoIndex, '-' + this.p.photoGalleryImageHeight));
		
		var deleted = false;
		
		this.gallery.find('.' + this.p.photoGalleryImageClassName).animate({
			top: ('+' + t.p.photoGalleryImageHeight)
		},
		"slow",
		"linear",
		function() {
			if(!deleted) {
				// delete last element, when animation end off (if we didn't do it in past time)
				t.gallery.find('.' + t.p.photoGalleryImageClassName + ':last').remove();
				deleted = true;
			}
		});
		
	},
	

	upButtonMouseover: function(event) {
		this.upButton.fadeTo("normal", 0.70);
	},
	
	upButtonMouseout: function(event) {
		
		this.upButton.fadeTo("normal", 0.50);
	},
	
	createNewPhotoGalleryImage: function(index, topOffset) {
		var t = this;
		
		/* TODO: security */
		var elementHtml = t.p.photoGalleryImageTemplate
		.replace(/\{0\}/img, t.photos[index][0].replace(/\"/img, '&quot;'))
		.replace(/\{1\}/img, t.photos[index][1].replace(/\"/img, '&quot;'))
		.replace(/\{2\}/img, t.photos[index][2].replace(/\"/img, '&quot;'));
		
		var element = $(elementHtml);
		
		/* i didn't use css() method, becouse it work only with elements, which are already in DOM */
		// element.attr('style', 'top: ' + topOffset);
		
		element.attr('style', 'cursor:pointer;top: ' + topOffset + ';');		
		element.click(function(){
			window.location = '/gallery/#all';
		});
		
		return element;
	},
	
	createFirstPhotoGalleryImages: function() {
		var t = this;
		
		for(var i = 0; i < 4; i++) {
			t.gallery.append(t.createNewPhotoGalleryImage(t.firstCurrentIndex + i, (i * t.p.photoGalleryImageHeight.replace(/px$/, '')).toString() + 'px'));
		}
		
		t.currentFirstPhotoIndex = t.firstCurrentIndex;
	}
};


App.LoginAndJoin = newClass();
App.LoginAndJoin.prototype = {
	
	init: function(p) {
		var t = this;
		t.p = p;
		
		t.login = $('#' + t.p.login);
		t.join = $('#' + t.p.join);
		
		var loginContent = '<div class="RegMessage"><div class="RegMessageHeader"><span>закрыть</span></div>' + 
		'<h1>Войти</h1>' + 
		'<form method="post" action="" onsubmit="formSubmit();return false">' + 
		'<table><input id="cmd" name="cmd" type="hidden" value="logon" />' + 
		'<tr><td class="Label"><label for="fl_login">Логин</label></td><td><input id="fl_login" name="fl_login" type="text" /></td></tr>' + 
		'<tr><td class="Label"><label for="fl_pas">Пароль</label></td><td><input id="fl_pas" name="fl_pas" type="password" /></td></tr>' + 
		'<tr><td class="Label" colspan="2"><span name="loginerror" id="loginerror"style="color:red;font-size:80%"></span></td></tr>' + 
		'</table>' + 
		'<div class="Button" name="submitBlock" id="submitBlock"><input type="submit" value="Войти"/><input class="Cancel" type="button" value="Отмена" /></div>' +
		'</form>' + 
		'<div class="Ref" style="padding-bottom:0px"><a href="#" class="JS SwitchToJoin">Регистрация на сайте</a></div>' + 
		'<div class="Ref"><a href="/forgot/" class="JS">Забыли пароль?</a></div>' + 
		'</div>';
		
		var joinContent = '<div class="RegMessage"><div class="RegMessageHeader"><span>закрыть</span></div>' + 
		'<h1>Регистрация на сайте</h1>' + 
		'<form action="" method="post" onsubmit="regFormSubmit();return false">' + 
		'<table><input id="cmd" name="cmd" type="hidden" value="register" />' + 
		'<tr><td class="Label"><label for="f_login">Логин</label></td><td><input id="f_login" name="f_login" type="text" req="1" validate="latin" /></td></tr>' + 
		'<tr><td class="Label"><label for="f_name">Фамилия, имя</label></td><td><input id="f_name" name="f_name" type="text" req="1" /></td></tr>' + 
		'<tr><td class="Label"><label for="f_pas">Пароль</label></td><td><input id="f_pas" name="f_pas" type="password" req="1" /></td></tr>' + 
		'<tr><td class="Label"><label for="f_pas_1">Ещё раз</label></td><td><input id="f_pas_1" name="f_pas_1" type="password" req="1" /></td></tr>' + 
		'<tr><td class="Label"><label for="f_email">Эл. почта</label></td><td><input id="f_email" name="f_email" type="text" req="1" validate="email" /></td></tr>' + 
		'<tr><td colspan="2"><div style="width:270px;color:gray;font-size:80%"><input type="checkbox" checked="checked" disabled="true"/>Я&nbsp;даю согласие ЗАО &laquo;Издательский дом &laquo;Бурда&raquo; (ОГРН 1027739494584) на&nbsp;обработку моих персональных данных любым способом, в&nbsp;том числе на&nbsp;сбор, хранение, а&nbsp;также передачу третьим лицам для рассылки рекламных материалов.<br/><input type="checkbox" checked="checked" disabled="true"/>С <a href="/rules/" target="_blank">Условиями использования интерактивных сервисов</a> на сайте ознакомлен.</div></td></tr>' + 
		'<tr><td class="Label" colspan="2"><span name="formerror" id="formerror" style="color:red;font-size:80%"></span></td></tr>' + 
		'</table>' + 
		'<div class="Button" name="rSubmitBlock" id="rSubmitBlock"><input type="submit" class="JoinButton" value="Зарегистрироваться"/><input class="Cancel" type="button" value="Отмена" /></div>' +
		'</form>' + 
		'<div class="Ref"><a href="#" class="JS SwitchToLogin">Вход на сайт</a></div>' + 
		'</div>';
		
		t.loginHtml = Onlyweb.Messages.generateHtml(loginContent);
		t.joinHtml = Onlyweb.Messages.generateHtml(joinContent);
		
		t.login.append(t.loginHtml);
		t.join.append(t.joinHtml);
		
		$('#' + t.p.loginRef)
		.click(function(e) {
			return t.loginRefClick(e);
		});
		
		$('#' + t.p.joinRef)
		.click(function(e) {
			return t.joinRefClick(e);
		});
		oValidator.validateAll()
		setTimeout(function() {
			t.login.find('.RegMessage .RegMessageHeader span')
			.click(function(e) {
				return t.closeMessegeClick(e);
			});
			t.login.find('.RegMessage .Cancel')
			.click(function(e) {
				return t.closeMessegeClick(e);
			});
			t.join.find('.RegMessage .RegMessageHeader span')
			.click(function(e) {
				return t.closeMessegeClick(e);
			});
			t.join.find('.RegMessage .Cancel')
			.click(function(e) {
				return t.closeMessegeClick(e);
			});
			t.login.find('.RegMessage .SwitchToJoin')
			.click(function(e) {
				return t.switchToJoinClick(e);
			});
			t.join.find('.RegMessage .SwitchToLogin')
			.click(function(e) {
				return t.switchToLoginClick(e);
			});
		}, 10);
	},
	
	loginRefClick: function(e) {
		var t = this;
		var evt = window.scrollY;
		if (document.attachEvent != null) { // Internet Explorer & Opera
			evt = document.documentElement.scrollTop + document.body.scrollTop;
		}
		if($.browser.opera){
			evt = evt/2;
		}
		t.join.css('display', 'none');
		t.login.css('display', 'block');
		t.login.css('top', evt);
		$('#fl_login')[0].focus()
		return false;
	},
	
	joinRefClick: function(e) {
		var t = this;
		var evt = window.scrollY;
		if (document.attachEvent != null) { // Internet Explorer
			evt = document.documentElement.scrollTop + document.body.scrollTop;
		}
		if($.browser.opera){
			evt = evt/2;
		}
		t.login.css('display', 'none');
		t.join.css('display', 'block');
		t.join.css('top', evt);
		$('#f_login')[0].focus()
		return false;
	},
	
	closeMessegeClick: function(e) {
		var t = this;
		
		t.login.css('display', 'none');
		t.join.css('display', 'none');
	},
	
	switchToJoinClick: function(e) {
		var t = this;
		var evt = window.scrollY;
		if (document.attachEvent != null) { // Internet Explorer
			evt = document.documentElement.scrollTop + document.body.scrollTop;
		}
		if($.browser.opera){
			evt = evt/2;
		}
		t.login.css('display', 'none');
		t.join.css('display', 'block');
		t.join.css('top', evt);
		return false;
	},
	
	switchToLoginClick: function(e) {
		var t = this;
		var evt = window.scrollY;
		if (document.attachEvent != null) { // Internet Explorer
			evt = document.documentElement.scrollTop + document.body.scrollTop;
		}
		if($.browser.opera){
			evt = evt/2;
		}
		t.join.css('display', 'none');
		t.login.css('display', 'block');
		t.join.css('top', evt);
		return false;
	}
}



App.Quiz = newClass();
App.Quiz.prototype = {
	
	init: function(p){
		var t = this;
		t.p = p;
		
		var content = '<div class="RegMessage"><div class="RegMessageHeader"><span>закрыть</span></div><div class="quiz_text">'+
									this.buildHtml()+
									'</div></div>';
		
		t.str = Onlyweb.Messages.generateHtml(content,600);
		
		$('#' + t.p.quizRef).click(function(e) {return t.quizRefClick();}).html(t.p.data.question);
		
	},
	
	buildHtml: function(){
		var t = this;
		var choicesHtml = '';
		var bVoted = t.p.data.voted>0;
		
		if(bVoted){
			for(var i = 0, hi = t.p.data.choices.length; i < hi; i++) {
//				choicesHtml += '<tr><td class="RadioLabel"><label for="f_choice_' + i + '">' + t.p.data.choices[i] + '</label></td><td><div class="poll_progress" style="width:'+t.p.data.poll_percent[i]+'px"></div><span class="poll_count">'+t.p.data.poll_count[i]+'</span></td></tr>';
				choicesHtml += '<tr><td class="RadioLabel"><label for="f_choice_' + i + '">' + t.p.data.choices[i] + '</label></td><td><div class="poll_progress" style="width:'+t.p.data.poll_percent[i]+'px"></div><span 	class="poll_count">'+t.p.data.poll_count[i]+'</span></td></tr>';
			}
		} else {
			for(var i = 0, hi = t.p.data.choices.length; i < hi; i++) {
				if(t.p.data.type == '1'){input_type = 'checkbox'} else {input_type = 'radio'};
				choicesHtml += '<tr><td><input id="f_choice_' + i + '" name="f_choice" type="'+input_type+'" value="'+t.p.data.ids[i]+'" /></td><td class="RadioLabel"><label for="f_choice_' + i + '">' + t.p.data.choices[i] + '</label></td></tr>';
			}
		}
		
		var content = '' + 
		'<h1 style="text-align:center">' + t.p.data.question + '</h1>' + 
		'<form action="#" method="post">' + 
		'<table>' + 
		choicesHtml +
		'</table>';
		if(!bVoted){
			content += '<div class="Button"><input type="button" value="Проголосовать" onclick="voteTop()"/></div>';
		}
		content += '</form>';
		return content;
	},
	
	quizRefClick: function() {
		
		$(this.str).displayBox();
		
		// hack
		$('.RegMessage .RegMessageHeader span')
		.click(function(event) {
			$.blockUI.impl.boxRemove();
		});
		
		return false;
	}
}

App.Avatar = newClass();
App.Avatar.prototype = {
	
	init: function(p) {
		var t = this;
		t.p = p;
		
		var choicesHtml = '';
		
		var content = '<div class="RegMessage"><div class="RegMessageHeader"><span>закрыть</span></div>' + 
		'<form action="/profile/update.html" method="post" enctype="multipart/form-data">' + 
		'<input name="avatarinfo" type="hidden" value="avatar" />' +
		'<p>Аватар:</p>' +
		'<div class="File"><input type="file" name="avatar_file" /></div>' +
		'<div class="Button"><input type="submit" value="Загрузить" /></div>' +
		'</form>' + 
		'</div>';
		
		t.str = Onlyweb.Messages.generateHtml(content);
		
		$('#' + t.p.loadAvatarRef)
		.click(function(e) {
			return t.loadAvatarRefClick();
		});
		
	},
	
	loadAvatarRefClick: function() {
		
		$(this.str).displayBox();
		
		// hack
		$('.RegMessage .RegMessageHeader span')
		.click(function(event) {
			$.blockUI.impl.boxRemove();
		});
		
		return false;
	}
}


App.SetupJournal = newClass();
App.SetupJournal.prototype = {
	
	init: function(p) {
		var t = this;
		t.p = p;
		
		var choicesHtml = '';
		
		var content = '<div class="RegMessage"><div class="RegMessageHeader"><span>закрыть</span></div>' + 
		'<form action="#" method="post">' + 
    '<h1>Настройки дневника</h1>' +
    '<table>' +
    
    '<tr><td class="Label"><label for="f_journal_name">Название</label></td>' +
    '<td><input class="Text" id="f_journal_name" name="f_journal_name" type="text" /></td></tr>' +
		
    '<tr><td class="LabelTop"><label for="f_description">Описание</label></td>' +
    '<td><textarea class="Text" id="f_description" name="f_description" /></textarea></td></tr>' +
		
    '<tr><td></td><td>' +
		
    '<div class="CheckBoxCont"><input type="checkbox" id="f_cb_for_all" name="f_cb_for_all" /><label for="f_cb_for_all">Мой блог видят все</label></div>' +
		
    '<div class="CheckBoxCont"><input type="checkbox" id="f_cb_comment" name="f_cb_comment" /><label for="f_cb_comment">По умолчанию разрешено комментировать всё</label></div>' +
		
    '<div class="CheckBoxCont"><input type="checkbox" id="f_cb_email" name="f_cb_email" /><label for="f_cb_email">Высылать комментарии мне на почту</label></div>' +
		
    '<div class="EMailForComments">' +
    '<label for="f_email_for_comments">Эл. почта для комментариев</label><br />' +
    '<input class="Text" type="text" name="f_email_for_comments" id="f_email_for_comments" />' +
    '</div>' +
		
		'<div class="Button"><input type="button" value="Сохранить" /></div>' +
		
    '<input type="hidden" name="f_delete_journal" value="0" id="delete_journal_inp" />' +
    '<div class="DelButton"><input type="button" value="Удалить" id="delete_journal_btn" /></div>' +
		
    '</td></tr></table>' +
    '</form>' + 
		'</div>';
		
		t.str = Onlyweb.Messages.generateHtml(content);
		
		$('#' + t.p.setupJournalRef)
		.click(function(e) {
			return t.setupJournalRefClick();
		});

    $('#delete_journal_btn')
    .click(function(e) {
      return t.deleteJournalButtonClick(e);
    });		
	},

  deleteJournalButtonClick: function() {
	
	},
	
	setupJournalRefClick: function() {
		
		$(this.str).displayBox();
		
		// hack
		$('.RegMessage .RegMessageHeader span')
		.click(function(event) {
			$.blockUI.impl.boxRemove();
		});
		
		return false;
	}
}

App.Resizer = newClass();
App.Resizer.prototype = {
	
	init: function(p) {
		var t = this;
		t.p = p;
		
		t.extraArticle = $('#' + t.p.extraArticle);
		t.topExtraArticle = $('#' + t.p.topExtraArticle);

		window.onresize = function(){
			t.resizeWindow();
		}
		
		// First time:
		t.resizeWindow();
	},
	
	resizeWindow: function() {
		var t = this;
		
		var width = document.documentElement.clientWidth || document.body.clientWidth;
		if(width < '1210') {
			t.extraArticle.css('display', 'none');
			t.topExtraArticle.css('display', 'none');
		} else {
			t.extraArticle.css('display', 'block');
			t.topExtraArticle.css('display', 'block');
		}
	}
};


/* TODO */
App.ChooseCover = newClass();
App.ChooseCover.prototype = {
	
	init: function(p) {
		var t = this;
		t.p = p;
		
		t.chooseCover = $('#' + t.p.chooseCover);
		
		t.coverSubmit = $('#' + t.p.coverSubmitElement);
		
		/*
		t.coverInputs = {};
		t.chooseCover.find('.' + t.p.coverInputC).each(function(i) {
			var index = $(this).attr('id').replace(t.p.coverInputPrefix, '');
			t.coverInputs[index] = $(this);
			t.coverInputs[index].change(function(e) {
				return t.coverInputChange(e);
			});
			t.coverInputs[index].click(function(e) {
				return t.coverInputChange(e);
			});
		});
		*/
		
		//var r = Math.round(Math.random()*100000) % 100000;
		
		t.coverImages = {};
		t.chooseCover.find('.' + t.p.coverImageC).each(function(i) {
			var index = $(this).attr('id').replace(t.p.coverImagePrefix, '');
			t.coverImages[index] = $(this);
			
			var html = t.p.inputTemplate
			.replace(/\{val\}/gi, index);
			
			t.chooseCover.find('#' + t.p.coverChoicePrefix + index)
			.prepend(html);
		});
		
		t.coverInputs = {};
		setTimeout(function() {
			for(index in t.coverImages) {
				t.coverImages[index].click(function(e) {
					return t.coverImageClick(e);
				});
				t.coverInputs[index] = t.chooseCover.find('#' + t.p.coverInputPrefix + index);
				t.coverInputs[index].change(function(e) {
					return t.coverInputChange(e);
				});
				t.coverInputs[index].click(function(e) {
					return t.coverInputChange(e);
				});
				if(t.coverInputs[index].get(0).checked) {
					t.coverSubmit.removeAttr('disabled');
				}
			}
		}, 10);
	},
	
	coverInputChange: function(e) {
		var element = $(e.target);
		// var index = element.attr('id').replace(this.p.coverInputPrefix, '');
		// this.coverInputs[index].attr('checked', 'checked');
		this.coverSubmit.removeAttr('disabled');
	},
	
	coverImageClick: function(e) {
		var element = $(e.target);
		var index = element.attr('id').replace(this.p.coverImagePrefix, '');
		this.coverInputs[index].attr('checked', 'checked');
		this.coverSubmit.removeAttr('disabled');
	}
	
};


App.AnswersFromExperts = newClass();
App.AnswersFromExperts.prototype = {
	
	init: function(p) {
		var t = this;
		var a = Common.Cookie.get('postEx');
		t.p = p;
		
		t.expertsQAA = $('#' + t.p.expertsQAA);
		t.allAnswersRef = $('#' + t.p.allAnswersRef);
		t.allAnswersOpen = $('#' + t.p.allAnswersOpen);
		
		t.experts = {};
		
		t.expertsQAA.find('.' + t.p.answerFromExpertC).each(function() {
			var el = $(this);
			var id = el.attr('id').replace(t.p.answerFromExpertP, '');
			t.experts[id] = {};
			t.experts[id].answer = el;
			t.experts[id].ref = t.expertsQAA.find('#' + t.p.answerRefP + id);
			t.experts[id].ref.click(function(e) {
				return t.answerRefClick(e);
			});
			t.experts[id].show = t.experts[id].answer.css('display') == 'none' ? false : true;
		});
		
		t.checkAllAnswer();
		
		t.allAnswersRef
		.click(function(e) {
			return t.allAnswersRefClick(e);
		});
		
		t.allAnswersOpen
		.click(function(e) {
			return t.allAnswersOpenClick(e);
		});
		
		if(a=='openEx'){
			return t.allAnswersOpenClick(1);
		};
	},
	
	answerRefClick: function(e) {
		var t = this;
		var el = $(e.target);
		
		var id = el.attr('id').replace(t.p.answerRefP, '');
		
		var showedAnswersRemained = false;
		
		if(t.experts[id] != undefined) {
			if (t.experts[id].answer.css('display') != 'none') {
				t.experts[id].answer.css('display', 'none');
				el.html(t.p.showAnswer);
				t.experts[id].show = false;
			} else {
				t.experts[id].answer.css('display', 'block');
				el.html(t.p.hideAnswer);
				t.experts[id].show = true;
			}
		};
		
		t.checkAllAnswer();
		
		return false;
	},
	
	checkAllAnswer: function() {
		var t = this;
		
		for(id in t.experts) {
			if(t.experts[id].show) {
				t.allAnswersRef.removeClass('Disabled');
				t.allAnswersOpen.removeClass('Disabled');
				return;
			}
		}
		
		
		t.allAnswersOpen.removeClass('Disabled');
	},
	
	allAnswersRefClick: function(e) {
		var t = this;
		
		t.allAnswersRef.html(t.p.showAllAnswer);
			
		for(id in t.experts) {
			t.experts[id].answer.css('display', 'none');
			t.experts[id].ref.html(t.p.showAnswer);
			t.experts[id].show = false;
		};
		
		t.showAnswerCounter = 0;
		t.allAnswersRef.addClass('Disabled');
		t.allAnswersOpen.removeClass('Disabled');
		Common.Cookie.set('postEx','closeEx','/');
		return false;
	},
	
	allAnswersOpenClick: function(e) {
		var t = this;
		
		t.allAnswersOpen.html(t.p.showAllAnswer);
			
		for(id in t.experts) {
			t.experts[id].answer.css('display', 'block');
			t.experts[id].ref.html(t.p.hideAnswer);
			t.experts[id].show = false;
		};
		
		t.allAnswersOpen.addClass('Disabled');
		t.allAnswersRef.removeClass('Disabled');
		Common.Cookie.set('postEx','openEx','/');
		return false;
	}
	
};


App.ListOfExperts = newClass();
App.ListOfExperts.prototype = {
	
	init: function(p) {
		var t = this;
		t.p = p;
		
		t.expertCellTemplate =
		'<td>' +
		'<div class="Person">' +
		'<div class="Photo"><a href="{url}"><img src="{photo}" width="75" height="100" /></a></div>' +
		'<div class="Text"><h2><a href="{url}">{name}</a></h2><p>{description}</p></div>' +
		'</div>' +
		'</td>';
		
		t.generateTableContent();
		
		// alert(t.p.listOfExpertsRef);
		
		$('#' + t.p.listOfExpertsRef)
		.click(function(e) {
			return t.listOfExpertsClick(e);
		});
	},
	
	generateTableContent: function() {
		var t = this;
		
		var people = t.p.data.people;
		
		var html = '';
		
		for(var i = 0, hi = people.length; i < hi; i++) {
			html += '<tr>';
			for(var j = 0; j < 2; j++) {
				if(people[i] != undefined) {
					html += t.expertCellTemplate
					.replace(/\{name\}/gi, people[i].name)
					.replace(/\{photo\}/gi, people[i].photo)
					.replace(/\{description\}/gi, people[i].description)
					.replace(/\{url\}/gi, people[i].url);
				};
				if(j == 0) {
					i++;
				}
			}
			html += '</tr>';
		};
		
		var content = '<div class="PopupMessage"><div class="PopupMessageHeader"><span>Закрыть</span></div>' + 
		'<table class="ExpertsTable"><tbody>' +
		html +
		'</tbody></table>' +
		'</div>';
		
		t.str = Onlyweb.Messages.generateHtml(content);
	},
	
	listOfExpertsClick: function(e) {
		
		
		$(this.str).displayBox();
		
		// hack
		$('.PopupMessage .PopupMessageHeader span')
		.click(function(event) {
			$.blockUI.impl.boxRemove();
		});
		
		return false;
	}
};

App.ExpertFormButton = newClass();
App.ExpertFormButton.prototype = {
	
	init: function(p) {
		var t = this;
		t.p = p;
		t.expertFormButton = $('#' + t.p.expertFormButton);
		t.expertFormButtonSecond = $('#' + t.p.expertFormButtonSecond);
		t.qte = $('#' + t.p.qte);
		
		t.expertFormButton
		.click(function(e) {
			return t.expertFormButtonClick(e);
		});
		t.expertFormButtonSecond
		.click(function(e) {
			return t.expertFormButtonClick(e);
		});
	},
	
	expertFormButtonClick: function() {
		var t = this;
		if(t.qte.css('display')=='none'){
			t.qte.css('display', 'block');
			t.expertFormButton.attr('src', t.p.expertFormButtonUrl)
		}else{
			t.qte.css('display', 'none');
			t.expertFormButton.attr('src', t.p.expertFormDbButtonUrl)
		};
		t.expertFormButton.removeClass(t.p.activeC);
		return false;
	}
	
}


App.preloadImages = function() {
	Onlyweb.Images.preload([		
		'/_img/message_lt.png',
		'/_img/message_t.png',
		'/_img/message_rt.png',
		'/_img/message_r.png',
		'/_img/message_rb.png',
		'/_img/message_b.png',
		'/_img/message_lb.png',
		'/_img/message_l.png',
		'/_img/red_bstar.gif',
		'/_img/red_h_bstar.gif'
	]);
};
