var d = document;
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var isNs = (navigator.appName.indexOf("Netscape") != -1);

function defined(x){return typeof(x) != 'undefined' && x != null;}
function addListener(element,event,func){if(element.attachEvent)element.attachEvent('on'+event,function(){func(window.event)});else if(element.addEventListener)element.addEventListener(event,func,false);}
function sortInc0(i,ii){if(i[0]>ii[0])return 1;else if(i[0]<ii[0])return -1;else return 0;}
function sortDec0(i,ii){if(i[0]>ii[0])return -1;else if(i[0]<ii[0])return 1;else return 0;}
function sortInc1(i,ii){if(i[1]>ii[1])return 1;else if(i[1]<ii[1])return -1;else return 0;}
function sortDec1(i,ii){if(i[1]>ii[1])return -1;else if(i[1]<ii[1])return 1;else return 0;}
function sortInc2(i,ii){if(i[2]>ii[2])return 1;else if(i[2]<ii[2])return -1;else return 0;}
function sortDec2(i,ii){if(i[2]>ii[2])return -1;else if(i[2]<ii[2])return 1;else return 0;}

function trim(str){var newstr=str.replace(/^\s*(.+?)\s*$/, "$1");if(newstr==" "){return "";}return newstr;}
function dropSpaces(str){var newstr=trim(str);return newstr.replace(/(\s)+/g,"");}
function checkEmail(email){var template=/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z])+$/;email = dropSpaces(email);if(template.test(email)){return true;}return false;}
function checkExtImage(value){if(value==""){return true;}var re=new RegExp("^.+\.(jpg|jpeg)$","i");if(!re.test(value)){return false;}return true;}
function parse_str(str,array){var glue1="=";var glue2="&";var array1=str.split("?");str=defined(array1[1])?array1[1]:array1[0];var array2=str.split(glue2);var array3={};for(var x=0;x<array2.length;x++){var tmp=array2[x].split(glue1);if(defined(tmp[0]) && defined(tmp[1])){array3[unescape(tmp[0])]=unescape(tmp[1]).replace(/[+]/g, ' ');}}if(array){array=array3;}else{return array3;}}
function ShowWinMod(options){if(!defined(options.url)){alert('Не указана сылка на страницу!');return false;}if(!defined(options.name)){alert('Не указано название окна!');return false;}if(defined(options.prx) && defined(options.pry)){var x,y;y=screen.availHeight;if(!y)y=screen.height;x=screen.availWidth;if(!x)x=screen.width;x=parseInt(options.prx*x/100);y=parseInt(options.pry*y/100);cx=screen.width/2-(x/2);cy=(screen.height/2-(y/2));}else if(defined(options.x) && defined(options.y)){var x,y;x=options.x;y=options.y;cx=screen.width/2-(x/2);cy=(screen.height/2-(y/2));}else{alert('Не заданы размеры окна!');return false;}options.isscrollbars=(defined(options.isscrollbars))?((options.isscrollbars=="no")?"no":"yes"):"yes";options.toolbar=(defined(options.toolbar))?((options.toolbar=="no")?"no":"yes"):"no";options.status=(defined(options.status))?((options.status=="no")?"no":"yes"):"no";options.directories=(defined(options.directories))?((options.directories=="no")?"no":"yes"):"no";options.menubar=(defined(options.menubar))?((options.menubar=="no")?"no":"yes"):"no";options.resizable=(defined(options.resizable))?((options.resizable=="no")?"no":"yes"):"no";options.wlocation=(defined(options.wlocation))?((options.wlocation=="no")?"no":"yes"):"no";window.open(options.url,options.name,"toolbar="+options.toolbar+",location="+options.wlocation+",status="+options.status+",directories="+options.directories+",menubar="+options.menubar+",resizable="+options.resizable+",width="+x+",height="+y+",scrollbars="+options.isscrollbars+",top="+cy+",left="+cx);}
function createTableTop20(rows){rowsInCol=Math.ceil(rows.length/2);col1=[];col2=[];for(i=0;i<rows.length;i++){if(i<rowsInCol){col1[col1.length]=rows[i];}else{col2[col2.length]=rows[i];}}html='<table width="100%" border="0" cellspacing="6" cellpadding="0" class="c2 f12">';for(i=0;i<col1.length;i++){contestClass=parseInt(col1[i][4])>0?'class="dashed"':'';contestImg=parseInt(col1[i][4])>0?' <a href="/photo/contest/index/'+col1[i][4]+'/" target="_blank" class="notd" title="описание конкурса"><img align="absbottom" height="15" width="15" src="/i/znak.gif" border="0" alt="конкурс"></a>':'';html+='<tr>';html+='<td width="50%"><a '+contestClass+' href="'+countryHref+'?co='+col1[i][3]+'">'+col1[i][2]+'</a>&nbsp;<span class="f10">('+col1[i][0]+'/'+col1[i][1]+')</span>'+contestImg+'</td>';if(defined(col2[i])){contestClass=parseInt(col2[i][4])>0?'class="dashed"':'';contestImg=parseInt(col2[i][4])>0?' <a href="/photo/contest/index/'+col2[i][4]+'/" target="_blank" class="notd" title="описание конкурса"><img align="absbottom" height="15" width="15" src="/i/znak.gif" border="0" alt="конкурс"></a>':'';html+='<td width="50%"><a '+contestClass+' href="'+countryHref+'?co='+col2[i][3]+'">'+col2[i][2]+'</a>&nbsp;<span class="f10">('+col2[i][0]+'/'+col2[i][1]+')</span>'+contestImg+'</td>';}else{html+='<td width="50%">&nbsp;</td>';}html+='</tr>';}html+='</table>';jQuery("#top20").html(html);}
function sNameClick(){jQuery('#sSum').attr('src','/i/ssum_or.gif');if(parseInt(jQuery('#sName').attr('st'))==1){top20.sort(sortInc2);jQuery('#sName').attr({'src':'/i/slang_or_u.gif','st':'0'});}else{top20.sort(sortDec2);jQuery('#sName').attr({'src':'/i/slang_or_d.gif','st':'1'});}createTableTop20(top20);}
function sSumClick(){p=window.location.pathname.split('/');path='photo';if(defined(p)){if(defined(p[1])){if(p[1].length){path=p[1];}}}jQuery('#sName').attr('src','/i/slang_or.gif');if(parseInt(jQuery('#sSum').attr('st'))==1){if(path=='photo'){top20.sort(sortInc0);}else if(path=='album'){top20.sort(sortInc1);}jQuery('#sSum').attr({'src':'/i/ssum_or_u.gif','st':'0'});}else{if(path=='photo'){top20.sort(sortDec0);}else if(path=='album'){top20.sort(sortDec1);}jQuery('#sSum').attr({'src':'/i/ssum_or_d.gif','st':'1'});}createTableTop20(top20);}
// страница списка стран (/country)
function fillCountryTd(rows){html='';for(i=0;i<rows.length;i++){if(rows[i][3].length && parseInt(rows[i][2])>0){img='/i/plus.gif';}else if(parseInt(rows[i][2])>0){img='/i/sminus.gif';}else{img='/i/minus.gif';}contestClass=parseInt(rows[i][5])>0?' dashed':'';contestImg=parseInt(rows[i][5])>0?' <a href="/photo/contest/index/'+rows[i][5]+'/" target="_blank" class="notd" title="описание конкурса"><img align="absbottom" height="15" width="15" src="/i/znak.gif" border="0" alt="конкурс"></a>':'';html+='<div style="padding-bottom: 11px;">';html+='<img '+(rows[i][3].length?'onclick="jQuery(\'#Co'+rows[i][0]+'\').toggle(300);"':'')+' src="'+img+'" id="img_Co'+rows[i][0]+'" border="0" height="9" hspace="5" vspace="2" width="9">';html+='<a href="'+countryHref+'?co='+rows[i][0]+'" class="f12'+contestClass+'" title="фотографии по '+rows[i][3]+'"><strong>'+rows[i][1]+'</strong></a>';if(parseInt(rows[i][2])>0){html+=' <span class="f11 c2">('+rows[i][2]+')</span>';}html+=contestImg;if(rows[i][4].length){html+='<div id="Co'+rows[i][0]+'" class="reBlock" style="display: none;">';for(j=0;j<rows[i][4].length;j++){if(rows[i][4][j][2].length && parseInt(rows[i][4][j][3])>0){html+='<a href="'+countryHref+'?co='+rows[i][0]+'&re='+rows[i][4][j][1]+'" title="фотографии по '+rows[i][3]+', '+rows[i][4][j][2]+'">'+rows[i][4][j][2]+'</a>';html+=' <span class="f11 c2">('+rows[i][4][j][3]+')</span>';html+='<br>';}}html+='</div>';}html+='</div>';}return html;}
function createTableCountrys(rows){html='<table border="0" cellspacing="0" cellpadding="5" width="100%" class="f12"><tr class="row_p1">';if(rows.length){rowsInCol=Math.ceil(rows.length/3);col1=[];col2=[];col3=[];for(i=0;i<rows.length;i++){if(i>=rowsInCol*2){col3[col3.length]=rows[i];}else if(i>=rowsInCol){col2[col2.length]=rows[i];}else{col1[col1.length]=rows[i];}}html+='<td width="33%" valign="top">';html+=fillCountryTd(col1);html+='</td><td width="33%" valign="top">';html+=fillCountryTd(col2);html+='</td><td width="33%" valign="top">';html+=fillCountryTd(col3);html+='</td>';}else{html+='<td align="center" style="padding-top: 15px;"><b class="c2">К сожалению по Вашему запросу ничего не найдено</b></td>';}html += '</td></tr></table>';jQuery("#countrysBlock").html(html);}

function sNameCountryClick(){jQuery('#sSumCountry').attr('src','/i/ssum_or.gif');if(parseInt(jQuery('#sNameCountry').attr('st'))==1){countrysRows.sort(sortInc1);jQuery('#sNameCountry').attr({ 'src':'/i/slang_or_u.gif', 'st':'0' });}else{countrysRows.sort(sortDec1);jQuery('#sNameCountry').attr({ 'src':'/i/slang_or_d.gif', 'st':'1' });}createTableCountrys(countrysRows);}
function sSumCountryClick(){jQuery('#sNameCountry').attr('src','/i/slang_or.gif');if(parseInt(jQuery('#sSumCountry').attr('st'))==1){countrysRows.sort(sortInc2);jQuery('#sSumCountry').attr({ 'src':'/i/ssum_or_u.gif', 'st':'0' });}else{countrysRows.sort(sortDec2);jQuery('#sSumCountry').attr({ 'src':'/i/ssum_or_d.gif', 'st':'1' });}createTableCountrys(countrysRows);}

function showSeries(){if(jQuery('#series_id').attr('checked')){jQuery('td.seriesSel').css('display','');}else{jQuery('td.seriesSel').css('display','none');}}
function selAlbum(){if(parseInt(jQuery('#album').attr('value'))>0){jQuery('#country, #resort, #category, #subcategory').attr('disabled',true);}else{jQuery('#country, #resort, #category, #subcategory').attr('disabled',false);}}
function showEditForm(){jQuery('#editWorkBlock').css('display','');jQuery('#commentWorkBlock').css('display','none');jQuery('#editHref').attr('class','edit_active').find('a').attr('class','');jQuery('#commentHref').attr('class','edit_noactive').find('a').attr('class','dashed_w');}
function showCommentForm(){jQuery('#editWorkBlock').css('display','none');jQuery('#commentWorkBlock').css('display','');jQuery('#commentHref').attr('class','edit_active').find('a').attr('class','');jQuery('#editHref').attr('class','edit_noactive').find('a').attr('class','dashed_w');}

function cacheName(options){name='jsCache_';if(defined(options.url)){name+='u'+options.url;}if(defined(options.params)){name+='p';for(p in options.params){name+=p+':'+options.params[p]+';';}}return escape(name);}
function loadCache(name,onload){if(defined(document.getElementById('cacheJsBlock'))){if(defined(document.getElementById(name))){data=document.getElementById(name).innerHTML;if(data.length>0){if(defined(onload)){var timerOnShow=setInterval(function(){onload(data);clearTimeout(timerOnShow);clearInterval(timerOnShow);},100);}return data;}}}return false;}
function saveCache(name,value){if(defined(document.getElementById('cacheJsBlock'))){if(defined(document.getElementById(name))){document.getElementById(name).innerHTML=value;}else{var divCache=document.createElement('DIV');divCache.id=name;divCache.innerHTML=value;document.getElementById('cacheJsBlock').appendChild(divCache);}}}

function loadContent(href,noCache,afterLoad,leftShift){lShift=defined(leftShift)?leftShift:-20;ch=jQuery('#fileBlock').height();cw=jQuery('#fileBlock').width()+lShift;jQuery('#loadBlock').css({height:((ch>40)?ch:40)+'px',width:cw+'px',filter:"alpha(opacity=50)",opacity:"0.5",display:''});if(defined(noCache)){jQuery.get(href,{},function(data){jQuery('#loadBlock').css('display','none');jQuery('#fileBlock').html(data);saveCache(name,data);if(defined(afterLoad)){afterLoad(data);}},'html');}else{var name=cacheName({url:href});if(!loadCache(name,function(data){jQuery('#loadBlock').css('display','none');jQuery('#fileBlock').html(data);if(defined(afterLoad)){afterLoad(data);}})){jQuery.get(href,{},function(data){jQuery('#loadBlock').css('display','none');jQuery('#fileBlock').html(data);saveCache(name,data);if(defined(afterLoad)){afterLoad(data);}},'html');}}return false;}
function loadCountryFiles(qs){/*return loadContent(countryHref+'/get_data'+qs);*/}
function loadCategoryFiles(qs){/*return loadContent(galleryHref+'/get_data'+qs);*/}
function loadNewFiles(qs){/*return loadContent(newHref+'/get_data'+qs);*/}
function loadTopFiles(qs){/*return loadContent(topHref+'/get_data'+qs);*/}
function loadContestFiles(qs){/*return loadContent(contestHref+'/get_data_works'+qs);*/}
function loadUsers(qs){/*return loadContent(authorHref+'/get_data'+qs);*/}
function loadAuthorFiles(qs){/*return loadContent(authorPhotoHref+'/get_data'+qs);*/}
function loadAuthorAlbum(qs){/*return loadContent(authorAlbumHref+'/get_data'+qs);*/}
function loadAuthorAlbumFile(qs){/*return loadContent(authorAlbumHref+'/get_data_files'+qs);*/}
function loadAuthorComments(qs){/*return loadContent(authorCommentHref+'/get_data'+qs);*/}
function loadNews(qs){/*return loadContent(newsHref+'/get_data'+qs);*/}
function loadClause(qs){/*return loadContent(clauseHref+'/get_data'+qs);*/}
function loadCountryContestFiles(qs){/*return loadContent(countryContestHref+'/get_data'+qs);*/}
function loadOfficeFiles1(qs){return loadContent(userOfficeFile1+'/get_data'+qs,true,
	function(data){
		tb_init('a.thickbox, area.thickbox, input.thickbox');
		jQuery('a.contestInfo').each(function(){
			workId=jQuery(this).attr('work_id');
			jQuery('#contest'+workId).tooltip({
				track:true,
				delay:0,
				showURL:false,
				extraClass:"pretty",
				fixPNG:true,
				opacity:0.95,
				left:-120,
				bodyHandler:function(){return jQuery('#contestBody'+jQuery(this).attr('work_id')).html();}
			});
		});
	},0);
}

function navigate(name){jQuery('#'+name).click();}
function defineHotKey(key,code){
	if(typeof(key)=='string'){
		var plus=key.indexOf('+');
		var key0=plus>0?key.substr(0,plus).toLowerCase():undefined;
		if(!/^(ctrl|alt|shift)$/.test(key0)){return false;}
		var key1=key.substr(plus+1)*1;
	}else{key1=key;}
	function react(e){
		var e=e || window.event;
		var keyCode=e.which || e.keyCode;
		if((eval('e.'+key0+'Key')?key0:!key0) && keyCode==key1){
			if(e.preventDefault){e.preventDefault();}
			e.returnValue=false;
			eval(code);
		}
	}
	if(document.addEventListener){
		// document.removeEventListener('keydown',react);
		document.addEventListener('keydown',react,true);
	}else if(document.attachEvent){
		document.detachEvent('onkeydown',react);
		document.attachEvent('onkeydown',react);
	}
}

function JSFX_FloatTopDiv(){
	this.timer=null;
	this.ftlObj={};
	this.startDiv=null;
	this.DeLayer=function(id){var placeX=(d.body.clientWidth-d.body.clientWidth/2),placeY=(d.body.clientHeight-d.body.clientHeight/2)+100;var GetElements=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];if(d.layers)GetElements.style=GetElements;GetElements.sP=function(x,y){this.style.right=x;this.style.top=y;};GetElements.x=placeX;GetElements.y=isNs?pageYOffset+innerHeight:d.body.scrollTop+d.body.clientHeight;GetElements.y-=placeY;return GetElements;}
	this.add=function(divid){if(!defined(this.ftlObj[divid])){this.ftlObj[divid]=this.DeLayer(divid);}}
	this.stop=function(){clearTimeout(this.timer);clearInterval(this.timer);if(defined(this.startDiv)){this.startDiv.style.display='none';}this.startDiv=null;}
	this.stayTopright=function(){placeY=(d.body.clientHeight-d.body.clientHeight/2)+100;var pY=isNs?pageYOffset+innerHeight:d.body.scrollTop+d.body.clientHeight;this.startDiv.y+=(pY-placeY-this.startDiv.y)/15;this.startDiv.sP(this.startDiv.x,this.startDiv.y);var obj=this;this.timer=setTimeout(function(){obj.stayTopright();},10);}
	this.start=function(divid){this.stop();if(defined(this.ftlObj[divid])){this.startDiv=this.ftlObj[divid];if(defined(this.startDiv)){this.startDiv.style.display='';}this.stayTopright();}}
}
JSFX = new JSFX_FloatTopDiv();


function objVote(){
	this.baseRate=[];
	this.rateContest=[];
	this.view=0;
	this.reload=true;
	this.show=function(options){
		work=parseInt(jQuery('#'+options.blockId).attr('work'));
		album=parseInt(jQuery('#'+options.blockId).attr('album'));
		auth=parseInt(jQuery('#'+options.blockId).attr('auth'));
		vote=parseInt(jQuery('#'+options.blockId).attr('vote'));
		contest=parseInt(jQuery('#'+options.blockId).attr('contest'));
		title=contest>0?'<b class="c6">Голосовать:</b>':'<b>Голосовать:</b>';
		html='<table class="voting" border="0" cellpadding="0" cellspacing="0"><tbody valign="top"><tr><td>'+title+'</td><td><div id="voteSelectBlock'+contest+'_'+work+'">';
		if(vote>0 && auth>0){html+='&nbsp;Спасибо, Ваш голос принят';}
		else{
			name='vote'+contest+'_'+work;
			onclick=(auth>0 || contest>0)?'':'onclick="JSFX.start(\'authVoteBlock\');"';
			html+='<table border="0" cellpadding="0" cellspacing="0"><tbody valign="top"><tr>';
			for(i=0;i<this.baseRate.length;i++){
				html+='<td><input id="'+name+'_'+this.baseRate[i][0]+'" name="'+name+'" value="'+this.baseRate[i][0]+'" type="radio" '+onclick+'></td><td><label for="'+name+'_'+this.baseRate[i][0]+'">'+this.baseRate[i][1];
				if(contest>0){
					html+='<br><span class="c2">'+this.rateContest[i][0]+' '+this.rateContest[i][1]+'</span>';
				}
				html+='</label></td>';
			}

			html+='<td style="padding-left:5px;"><a href="javascript:void(0);" '+(this.reload?'reload="1"':'')+' onclick="clsVote.voted({blockId:\'voteBlock'+album+'_'+contest+'_'+work+'\'},this);"><img src="/i/vote.gif" alt="голосовать" width="107" height="18" hspace="0" vspace="0" border="0"></a></td></tr></tbody></table>';
		}
		html+='</div></td></tr></tbody></table>';
		jQuery('#'+options.blockId).html(html);
	}
	this.voted=function(options,el){
		work=parseInt(jQuery('#'+options.blockId).attr('work'));
		album=parseInt(jQuery('#'+options.blockId).attr('album'));
		auth=parseInt(jQuery('#'+options.blockId).attr('auth'));
		vote=parseInt(jQuery('#'+options.blockId).attr('vote'));
		contest=parseInt(jQuery('#'+options.blockId).attr('contest'));
		if(auth>0 || contest>0){
			if(vote){jAlert('Ваш голос уже принят.', 'Голосование');return false;}
			else{
				name='vote'+contest+'_'+work;
				value=0;
				jQuery("input[@name='"+name+"']").each(function(){if(this.checked){value=this.value;}});
				if(parseInt(value)>0){
					if (parseInt(jQuery(el).attr('action'))==0 || isNaN(parseInt(jQuery(el).attr('action')))) {
						jConfirm('Голосовать?', 'Голосование', function(r) {
							if(r==true){
								html = jQuery(el).html();
								jQuery(el).html('<img src="/i/wait.gif" width="16" height="16" border="0">').attr('action','1');
								var obj=this;
								params={sid:phpSesSid,work:work,album:album,contest:contest,count:value};
								jQuery.post('/vote.php',params,function(data){
									if(defined(data.ok)){
										jAlert(
											'Спасибо, Ваш голос принят.',
											'Голосование',
											function(){
												if(jQuery(el).attr('reload')){window.location.reload();}
												if(!obj.reload){jQuery('#'+options.blockId).empty();}
											}
										);
									}else{
										errorStr='Ошибка при добавлении голоса!';
										if(defined(data.error)){
											error=parseInt(data.error);
											if(error==1){errorStr+='\nГолосование доступно только авторизованным пользователям!'}
											else if(error==2){errorStr+='';}
											else if(error==3){errorStr+='\nВаш голос уже принят!';}
											else if(error==4){errorStr='';}
											else if(error==5){errorStr='';}
										}
										jAlert(errorStr, 'Голосование');
									}
									jQuery(el).attr('action','0').html(html);
								},'json');
							}
						});
					}
				}else{jAlert('Выберите один из вариантов', 'Голосование');return false;}
			}
		}else{JSFX.start('authVoteBlock');return false;}
	}

}
clsVote=new objVote();

function photodiaryVote(){
	this.baseRate=[];
	this.view=0;
	this.reload=true;
	this.show=function(options){
		photodiary_id=parseInt(jQuery('#'+options.blockId).attr('photodiary_id'));
		auth=parseInt(jQuery('#'+options.blockId).attr('auth'));
		vote=parseInt(jQuery('#'+options.blockId).attr('vote'));
		title='<b>Голосовать:</b>';
		html='<table class="voting" border="0" cellpadding="0" cellspacing="0"><tbody valign="top"><tr><td>'+title+'</td><td><div id="voteSelectBlock'+photodiary_id+'">';
		if(vote>0 && auth>0){html+='&nbsp;Спасибо, Ваш голос принят';}
		else{
			name='vote'+photodiary_id;
			onclick=(auth>0)?'':'onclick="JSFX.start(\'authVoteBlock\');"';
			html+='<table border="0" cellpadding="0" cellspacing="0"><tbody valign="top"><tr>';
			for(i=0;i<this.baseRate.length;i++){
				html+='<td><input id="'+name+'_'+this.baseRate[i][0]+'" name="'+name+'" value="'+this.baseRate[i][0]+'" type="radio" '+onclick+'></td><td><label for="'+name+'_'+this.baseRate[i][0]+'">'+this.baseRate[i][1];

				html+='</label></td>';
			}

			html+='<td style="padding-left:5px;"><a href="javascript:void(0);" '+(this.reload?'reload="1"':'')+' onclick="photodiaryVote.voted({blockId:\'voteBlock'+photodiary_id+'\'},this);"><img src="/i/vote.gif" alt="голосовать" width="107" height="18" hspace="0" vspace="0" border="0"></a></td></tr></tbody></table>';
		}
		html+='</div></td></tr></tbody></table>';
		jQuery('#'+options.blockId).html(html);
	}
	this.voted=function(options,el){
		photodiary_id=parseInt(jQuery('#'+options.blockId).attr('photodiary_id'));
		auth=parseInt(jQuery('#'+options.blockId).attr('auth'));
		vote=parseInt(jQuery('#'+options.blockId).attr('vote'));
		if(auth>0){
			if(vote){jAlert('Ваш голос уже принят.', 'Голосование');return false;}
			else{
				name='vote'+photodiary_id;
				value=0;
				jQuery("input[@name='"+name+"']").each(function(){if(this.checked){value=this.value;}});
				if(parseInt(value)>0){
					if (parseInt(jQuery(el).attr('action'))==0 || isNaN(parseInt(jQuery(el).attr('action')))) {
						jConfirm('Голосовать?', 'Голосование', function(r) {
							if(r==true){
								html = jQuery(el).html();
								jQuery(el).html('<img src="/i/wait.gif" width="16" height="16" border="0">').attr('action','1');
								var obj=this;
								params={sid:phpSesSid,photodiary_id:photodiary_id,count:value};
								jQuery.post('/photodiary/vote',params,function(data){
									if(defined(data.ok)){
										jAlert(
											'Спасибо, Ваш голос принят.',
											'Голосование',
											function(){
												if(jQuery(el).attr('reload')){window.location.reload();}
												if(!obj.reload){jQuery('#'+options.blockId).empty();}
											}
										);
									}else{
										errorStr='Ошибка при добавлении голоса!';
										if(defined(data.error)){
											error=parseInt(data.error);
											if(error==1){errorStr+='\nГолосование доступно только авторизованным пользователям!'}
											else if(error==2){errorStr+='';}
											else if(error==3){errorStr+='\nВаш голос уже принят!';}
											else if(error==4){errorStr='';}
											else if(error==5){errorStr='';}
										}
										jAlert(errorStr, 'Голосование');
									}
									jQuery(el).attr('action','0').html(html);
								},'json');
							}
						});
					}
				}else{jAlert('Выберите один из вариантов', 'Голосование');return false;}
			}
		}else{JSFX.start('authVoteBlock');return false;}
	}

}
photodiaryVote=new photodiaryVote();

function objNotepad(){
	this.notepad=function(options){
		work=parseInt(jQuery('#'+options.blockId).attr('work'));
		album=parseInt(jQuery('#'+options.blockId).attr('album'));
		auth=parseInt(jQuery('#'+options.blockId).attr('auth'));
		notepad = parseInt(jQuery('#'+options.blockId).attr('notepad'));
		if(auth>0){
			params={sid:phpSesSid,work:work,album:album,notepad:notepad>0?0:1};
			jQuery.post('/notepad.php',params,function(data){
				if(defined(data.ok)){
					jQuery('#'+options.blockId).attr('notepad',notepad>0?'0':'1');
					if(album){jQuery('#notepadImg'+album+'_'+work).attr('src',notepad>0?'/i/fav_2.gif':'/i/fav_1.gif');
					}else{jQuery('#notepadImg'+album+'_'+work).attr('src',notepad>0?'/i/fav_2.gif':'/i/fav_1.gif');}
					jAlert(notepad>0?(album?'Альбом удален из избранного!':'Работа удалена из избранного!'):(album?'Альбом добавлен в избранное!':'Работа добавлена в избранное!'), 'Избранные работы');
				}else{
					errorStr='';
					if(defined(data.error)){
						error=parseInt(data.error);
						if(error==1){errorStr='Добавление в избранное доступно только авторизованным пользователям!'}
						else if(error==2){errorStr='Ошибка при добавлении в избранное!\nРабота не найдена.';}
						else if(error==3){errorStr='Ошибка при добавлении в избранное!';}
					}else{errorStr='Ошибка при добавлении в избранное!';}
					jAlert(errorStr, 'Избранные работы');
				}
			},'json');
			return true;
		}else{JSFX.start('auth_ntp_block');return false;}
	}
	this.show=function(options){
		work=parseInt(jQuery('#'+options.blockId).attr('work'));
		album=parseInt(jQuery('#'+options.blockId).attr('album'));
		auth=parseInt(jQuery('#'+options.blockId).attr('auth'));
		notepad=parseInt(jQuery('#'+options.blockId).attr('notepad'));
		onclick=auth>0?'clsNotepad.notepad({blockId:\'notepadBlock'+album+'_'+work+'\'});':'JSFX.start(\'auth_ntp_block\');';
		img=notepad>0?'/i/fav_1.gif':'/i/fav_2.gif';
		title=notepad>0?'удалить из избранного':'добавить в избранное';
		html='<a href="javascript:void(0);" onclick="'+onclick+'"><img id="notepadImg'+album+'_'+work+'" src="'+img+'" alt="'+title+'" title="'+title+'" hspace="0" vspace="0" border="0" height="14" width="14"></a>';
		jQuery('#'+options.blockId).html(html);
	}
}

clsNotepad=new objNotepad();
//класс добавления в избранное альбома при выводе галерей
clsNotepadAlbum=new objNotepad();
clsNotepadAlbum.show=function(options){div=jQuery('div.'+options.blockClass).get(0);work=parseInt(jQuery(div).attr('work'));album=parseInt(jQuery(div).attr('album'));auth=parseInt(jQuery(div).attr('auth'));notepad=parseInt(jQuery(div).attr('notepad'));onclick=auth>0?'clsNotepadAlbum.notepad({blockClass:\'clsNotepadBlock'+album+'_'+work+'\'});':'JSFX.start(\'auth_ntp_block\');';img=notepad>0?'/i/fav_1.gif':'/i/fav_2.gif';title=notepad>0?'удалить из избранного':'добавить в избранное';html='<a href="javascript:void(0);" onclick="'+onclick+'"><img class="clsNotepadImg'+album+'_'+work+'" src="'+img+'" alt="'+title+'" title="'+title+'" hspace="0" vspace="0" border="0" height="14" width="14"></a>';jQuery('div.'+options.blockClass).html(html);}
clsNotepadAlbum.notepad=function(options){div=jQuery('div.'+options.blockClass).get(0);work=parseInt(jQuery(div).attr('work'));album=parseInt(jQuery(div).attr('album'));auth=parseInt(jQuery(div).attr('auth'));notepad=parseInt(jQuery(div).attr('notepad'));if(auth>0){params={sid:phpSesSid,work:work,album:album,notepad:notepad>0?0:1};jQuery.getJSON('/notepad.php',params,function(data){if(defined(data.ok)){jQuery('div.'+options.blockClass).attr('notepad',notepad>0?'0':'1');if(album){jQuery('img.clsNotepadImg'+album+'_'+work).attr('src',notepad>0?'/i/fav_2.gif':'/i/fav_1.gif');}else{jQuery('img.clsNotepadImg'+album+'_'+work).attr('src',notepad>0?'/i/fav_2.gif':'/i/fav_1.gif');}jAlert(notepad>0?'Альбом удален из избранного!':'Альбом добавлен в избранное!','Избранные работы');}else{errorStr='';if(defined(data.error)){error=parseInt(data.error);if(error==1){errorStr='Добавление в избранное доступно только авторизованным пользователям!'}else if(error==2){errorStr='Ошибка при добавлении в избранное!\nРабота не найдена.';}else if(error==3){errorStr='Ошибка при добавлении в избранное!';}}else{errorStr='Ошибка при добавлении в избранное!';}jAlert(errorStr,'Избранные работы');}});return true;}else{JSFX.start('auth_ntp_block');return false;}}

function objComment() {
	this.workId=0;
	this.isAlbum=0;
	this.isAuth=0;
	this.params={};
	this.url='';
	this._userShow=false;
	this.del=function(id) {
		ch=jQuery('#commentBlock').height();
		cw=jQuery('#commentBlock').width();
		jQuery('#loadComment').css({height:((ch>40)?ch:40)+'px',width:cw+'px',filter:"alpha(opacity=50)",opacity:"0.5",display:''});
		jQuery('#commentForm .commentInput').attr({disabled:true});
		params={};
		params.sid=phpSesSid;
		params.del=id;
		jQuery.post('/comment.php',params,function(data){
			if(!defined(data.ok) || defined(data.error)){jAlert('Ошибка при удалении комментария.','Комментарии');}
			if(clsComment._userShow){clsComment.userShow();}else{clsComment.show(null,true);}
		},'json');
	}
	this.show = function(params,reset){
		jQuery('div.commentError').css('display','none');
		if(this.url.length>0){
			ch=jQuery('#commentBlock').height();
			cw=jQuery('#commentBlock').width();
			jQuery('#loadComment').css({height:((ch>40)?ch:40)+'px',width:cw+'px',filter:"alpha(opacity=50)",opacity:"0.5",display:''});
			jQuery('#commentForm .commentInput').attr({disabled:true});
			params=defined(params)?params:parse_str(window.location.search);
			var name=cacheName({url:this.url,params:params});
			if(defined(reset)){
				jQuery.get(this.url,params,function(data){jQuery('#loadComment').css('display','none');jQuery('#commentBlock').html(data);jQuery('#commentForm .commentInput').attr({disabled:false});saveCache(name,data);},'html');
			}else{
				if(!loadCache(name,function(data){jQuery('#loadComment').css('display','none');jQuery('#commentBlock').html(data);jQuery('#commentForm .commentInput').attr({disabled:false});})){
					jQuery.get(this.url,params,function(data){jQuery('#loadComment').css('display','none');jQuery('#commentBlock').html(data);jQuery('#commentForm .commentInput').attr({disabled:false});saveCache(name,data);},'html');
				}
			}
		}
	}

	this.checkForm=function(){
		jQuery('div.commentError').css('display','none');
		this.params={};
		this.params.commentWorkId=this.workId;
		this.params.commentAlbum=this.isAlbum;
		this.params.commentName=jQuery('#commentName').attr('value');
		this.params.commentEmail=jQuery('#commentEmail').attr('value');
		this.params.commentText=jQuery('#commentText').attr('value');
		this.params.commentEntercode=jQuery('#commentEntercode').attr('value');
		this.params.commentWorkId=defined(this.params.commentWorkId)?this.params.commentWorkId:0;
		this.params.commentAlbum=defined(this.params.commentAlbum)?this.params.commentAlbum:0;
		this.params.commentName=defined(this.params.commentName)?this.params.commentName:'';
		this.params.commentEmail=defined(this.params.commentEmail)?this.params.commentEmail:'';
		this.params.commentText=defined(this.params.commentText)?this.params.commentText:'';
		this.params.commentEntercode=defined(this.params.commentEntercode)?this.params.commentEntercode:'';
		var commentReply=[];
		jQuery("input[@name='comment[]']").each(function(){if(this.checked){commentReply[commentReply.length]=this.value;}});
		this.params.commentReply=commentReply.join(',');
		err=[];
		if(this.params.commentText.length==0){err[err.length]='err_commentText'; jQuery('#commentText').focus();}
		if(this.params.commentText.length>500){err[err.length]='err_commentTextCheckLength'; jQuery('#commentText').focus();}
		if (this.isAuth==0) {
			if(this.params.commentName.length==0){err[err.length]='err_commentName';}
			if(this.params.commentName.length>100){err[err.length]='err_commentNameCheckLength';}
			//проверку на необходимость мыла убираем
			//if(this.params.commentEmail.length==0){err[err.length]='err_commentEmail';}
			if(this.params.commentEmail.length>100){err[err.length]='err_commentEmailCheckLength';}
			if(this.params.commentEmail.length>0){if(!checkEmail(this.params.commentEmail)){err[err.length]='err_commentEmail';}}
			if(this.params.commentEntercode.length==0){err[err.length]='err_commentEntercode';}
		}
		if(err.length==0){
			return true;
		}else{
			for(i=0;i<err.length;i++){jQuery('#'+err[i]).css('display','');}
			return false;
		}
	}

	this.save = function() {
		if(this.checkForm()) {
			jQuery('#commentForm .commentInput').attr({disabled:true});
			ch = jQuery('#commentBlock').height();
			cw = jQuery('#commentBlock').width();
			jQuery('#loadComment').css({ height: ((ch > 40) ? ch : 40) + 'px', width: cw + 'px', filter: "alpha(opacity=50)", opacity: "0.5", display:'' });

			this.params.sid = phpSesSid;
			jQuery.post('/comment.php',this.params,function(data){
				jQuery('#commentEntercodeImg').attr('src','/img.php?rnd='+Math.random());
				if(defined(data.ok)){
					jQuery('#commentReply, #commentName, #commentEmail, #commentText, #commentEntercode').attr('value','');
					jQuery("input[@name='comment[]']").each(function(){this.checked=false;});
					if(clsComment._userShow){clsComment.userShow();}else{clsComment.show(null,true);}
				}else{
					errStr = 'Ошибка при добавлении комментария!';
					err = [];
					if(defined(data.error)){
						if(defined(data.error.err_auth)){}
						if(defined(data.error.err_commentName)){errStr+='\nУкажите Ваше имя!';err[err.length]='err_commentName';}
						if(defined(data.error.err_commentEmail)){errStr+='\nУкажите E-mail в формате somename@domain.ru!';err[err.length]='err_commentEmail';}
						if(defined(data.error.err_commentText)){errStr+='\nУкажите комментарий!';err[err.length]='err_commentText';}
						if(defined(data.error.err_commentEntercode)){errStr+='\nЗащитный код не введен или введен не верно!';err[err.length]='err_commentEntercode';}
						if(defined(data.error.err_commentSave)){err[err.length]='err_commentSave';}
					}
					for(i=0;i<err.length;i++){jQuery('#'+err[i]).css('display','');}
					jAlert(errStr,'Комментарии');
					jQuery('#commentForm .commentInput').attr({disabled:false});
					jQuery('#loadComment').css('display','none');
				}
			},'json');
		}
	}

	this.init = function(options) {
		this.workId = defined(options.workId) ? parseInt(options.workId) : 0;
		this.isAlbum = defined(options.isAlbum) ? parseInt(options.isAlbum) : 0;
		this.isAuth = defined(options.isAuth) ? parseInt(options.isAuth) : 0;
		this.url = defined(options.url) ? parseInt(options.url) : this.url;

		if(this.workId>0){
			jQuery('#commentForm .commentInput').attr({disabled:false,value:''});
			jQuery('#commentWorkId').attr('value',this.workId);
			jQuery('#commentAlbum').attr('value',this.isAlbum);
		}else{
			jQuery('#commentForm .commentInput').attr({disabled:true,value:''});
		}
		jQuery('div.commentError').css('display','none');
	}

	this.userShow = function() { }
}

clsComment = new objComment();

function objModerate(){
	this.workId=0;
	this.isAlbum=0;
	this.params={};
	this._userShow=false;
	this.show=function(){
		jQuery('#moderateForm .moderateInput').attr({disabled:false,value:''});
		jQuery('#moderateForm .moderateButton').attr({disabled:false});
		jQuery('div.moderateError').css('display','none');

		jQuery('#moderateForm').css('display','');
		hd=jQuery(window).height();
		wd=jQuery(window).width();
		hb=jQuery('#moderateForm').height();
		wb=jQuery('#moderateForm').width();
		jQuery('#moderateForm').css({top:parseInt((hd-hb)/2)+jQuery(window).scrollTop(),left:parseInt((wd-wb)/2)});
	}
	this.hide=function(){
		jQuery('#moderateForm').css('display','none');
	}
	this.init=function(options){
		this.workId=defined(options.workId)?parseInt(options.workId):0;
		this.isAlbum=defined(options.isAlbum)?parseInt(options.isAlbum):0;
		if(this.workId>0){
			jQuery('#moderateForm .moderateInput').attr({disabled:false,value:''});
			jQuery('#moderateForm .moderateButton').attr({disabled:false});
			jQuery('#moderateWorkId').attr('value',this.workId);
			jQuery('#moderateAlbum').attr('value',this.isAlbum);
		}else{
			jQuery('#moderateForm .moderateInput').attr({disabled:true,value:''});
			jQuery('#moderateForm .moderateButton').attr({disabled:true});
			jQuery('#moderateWorkId').attr('value','');
			jQuery('#moderateAlbum').attr('value','');
		}
		jQuery('div.moderateError').css('display','none');
	}
	this.checkForm=function(){
		jQuery('div.moderateError').css('display','none');
		this.params={};
		this.params.moderateWorkId=this.workId;
		this.params.moderateAlbum=this.isAlbum;
		this.params.moderateName=defined(jQuery('#moderateName').attr('value'))?jQuery('#moderateName').attr('value'):'';
		this.params.moderateEmail=defined(jQuery('#moderateEmail').attr('value'))?jQuery('#moderateEmail').attr('value'):'';
		this.params.moderateText=defined(jQuery('#moderateText').attr('value'))?jQuery('#moderateText').attr('value'):'';
		this.params.moderateEntercode=defined(jQuery('#moderateEntercode').attr('value'))?jQuery('#moderateEntercode').attr('value'):'';
		this.params.moderateWorkId=defined(this.params.moderateWorkId)?this.params.moderateWorkId:0;
		this.params.moderateAlbum=defined(this.params.moderateAlbum)?this.params.moderateAlbum:0;
		err=[];
		if(this.params.moderateText.length==0){err[err.length]='err_moderateText';}
		if(this.params.moderateText.length>500){err[err.length]='err_moderateTextCheckLength';}
		if(this.params.moderateName.length==0){err[err.length]='err_moderateName';}
		if(this.params.moderateName.length>100){err[err.length]='err_moderateNameCheckLength';}
		if(this.params.moderateEmail.length==0){err[err.length]='err_moderateEmail';}
		if(this.params.moderateEmail.length>100){err[err.length]='err_moderateEmailCheckLength';}
		if(this.params.moderateEmail.length>0){if(!checkEmail(this.params.moderateEmail)){err[err.length]='err_moderateEmail';}}
		if(this.params.moderateEntercode.length==0){err[err.length]='err_moderateEntercode';}
		if(err.length==0){
			return true;
		}else{
			for(i=0;i<err.length;i++){jQuery('#'+err[i]).css('display','');}
			return false;
		}
	}
	this.save = function() {
		if(this.checkForm()) {
			jQuery('#moderateForm .moderateInput').attr({disabled:true});
			jQuery('#moderateForm .moderateButton').attr({disabled:true});
			ch = jQuery('#moderateForm').height();
			cw = jQuery('#moderateForm').width();
			jQuery('#moderateLoad').css({height:ch+'px',width:cw+'px',filter:"alpha(opacity=50)",opacity:"0.5",display:''});
			this.params.sid=phpSesSid;
			jQuery.post('/moderate.php',this.params,function(data){
				jQuery('#moderateEntercodeImg').attr('src','/img2.php?rnd='+Math.random());
				if(defined(data.ok)){
					jAlert('Сообщение успешно добавлено.','Пожаловаться модератору');
					jQuery('#moderateForm .moderateInput').attr({disabled:false,value:''});
					jQuery('#moderateForm .moderateButton').attr({disabled:false});
					jQuery('div.moderateError').css('display','none');
					clsModerate.hide();
				}else{
					errStr='Ошибка при добавлении сообщения!';
					err=[];
					if(defined(data.error)){
						if(defined(data.error.err_auth)){}
						if(defined(data.error.err_moderateName)){errStr+='\nУкажите Ваше имя!';err[err.length]='err_moderateName';}
						if(defined(data.error.err_moderateEmail)){errStr+='\nУкажите E-mail в формате somename@domain.ru!';err[err.length]='err_moderateEmail';}
						if(defined(data.error.err_moderateText)){errStr+='\nУкажите текст сообщения!';err[err.length]='err_moderateText';}
						if(defined(data.error.err_moderateEntercode)){errStr+='\nЗащитный код не введен или введен не верно!';err[err.length]='err_moderateEntercode';}
						if(defined(data.error.err_moderateSave)){err[err.length]='err_moderateSave';}
					}
					jAlert(errStr,'Пожаловаться модератору');
					jQuery('#moderateForm .moderateInput').attr({disabled:false});
					jQuery('#moderateForm .moderateButton').attr({disabled:false});
					for(i=0;i<err.length;i++){jQuery('#'+err[i]).css('display','');}
				}
				jQuery('#moderateLoad').css('display','none');
			},'json');
		}
	}
}

clsModerate = new objModerate();

function photodiaryComment() {
	this.photodiaryId=0;
	this.isAuth=0;
	this.params={};
	this.url='';
	this._userShow=false;
	this.del=function(id) {
		ch=jQuery('#commentBlock').height();
		cw=jQuery('#commentBlock').width();
		jQuery('#loadComment').css({height:((ch>40)?ch:40)+'px',width:cw+'px',filter:"alpha(opacity=50)",opacity:"0.5",display:''});
		jQuery('#commentForm .commentInput').attr({disabled:true});
		params={};
		params.sid=phpSesSid;
		params.del=id;
		jQuery.post('/photodiary/comment',params,function(data){
			if(!defined(data.ok) || defined(data.error)){jAlert('Ошибка при удалении комментария.','Комментарии');}
			if(photodiaryComment._userShow){photodiaryComment.userShow();}else{photodiaryComment.show(null,true);}
		},'json');
	}
	this.show = function(params,reset){
		jQuery('div.commentError').css('display','none');
		if(this.url.length>0){
			ch=jQuery('#commentBlock').height();
			cw=jQuery('#commentBlock').width();
			jQuery('#loadComment').css({height:((ch>40)?ch:40)+'px',width:cw+'px',filter:"alpha(opacity=50)",opacity:"0.5",display:''});
			jQuery('#commentForm .commentInput').attr({disabled:true});
			params=defined(params)?params:parse_str(window.location.search);
			var name=cacheName({url:this.url,params:params});
			if(defined(reset)){
				jQuery.get(this.url,params,function(data){jQuery('#loadComment').css('display','none');jQuery('#commentBlock').html(data);jQuery('#commentForm .commentInput').attr({disabled:false});saveCache(name,data);},'html');
			}else{
				if(!loadCache(name,function(data){jQuery('#loadComment').css('display','none');jQuery('#commentBlock').html(data);jQuery('#commentForm .commentInput').attr({disabled:false});})){
					jQuery.get(this.url,params,function(data){jQuery('#loadComment').css('display','none');jQuery('#commentBlock').html(data);jQuery('#commentForm .commentInput').attr({disabled:false});saveCache(name,data);},'html');
				}
			}
		}
	}

	this.checkForm=function(){
		jQuery('div.commentError').css('display','none');
		this.params={};
		this.params.commentPhotodiaryId=this.photodiaryId;
		this.params.commentName=jQuery('#commentName').attr('value');
		this.params.commentEmail=jQuery('#commentEmail').attr('value');
		this.params.commentText=jQuery('#commentText').attr('value');
		this.params.commentEntercode=jQuery('#commentEntercode').attr('value');
		this.params.commentPhotodiaryId=defined(this.params.commentPhotodiaryId)?this.params.commentPhotodiaryId:0;
		this.params.commentName=defined(this.params.commentName)?this.params.commentName:'';
		this.params.commentEmail=defined(this.params.commentEmail)?this.params.commentEmail:'';
		this.params.commentText=defined(this.params.commentText)?this.params.commentText:'';
		this.params.commentEntercode=defined(this.params.commentEntercode)?this.params.commentEntercode:'';
		var commentReply=[];
		jQuery("input[@name='comment[]']").each(function(){if(this.checked){commentReply[commentReply.length]=this.value;}});
		this.params.commentReply=commentReply.join(',');
		err=[];
		if(this.params.commentText.length==0){err[err.length]='err_commentText'; jQuery('#commentText').focus();}
		if(this.params.commentText.length>500){err[err.length]='err_commentTextCheckLength'; jQuery('#commentText').focus();}
		if (this.isAuth==0) {
			if(this.params.commentName.length==0){err[err.length]='err_commentName';}
			if(this.params.commentName.length>100){err[err.length]='err_commentNameCheckLength';}
			//проверку на необходимость мыла убираем
			//if(this.params.commentEmail.length==0){err[err.length]='err_commentEmail';}
			if(this.params.commentEmail.length>100){err[err.length]='err_commentEmailCheckLength';}
			if(this.params.commentEmail.length>0){if(!checkEmail(this.params.commentEmail)){err[err.length]='err_commentEmail';}}
			if(this.params.commentEntercode.length==0){err[err.length]='err_commentEntercode';}
		}
		if(err.length==0){
			return true;
		}else{
			for(i=0;i<err.length;i++){jQuery('#'+err[i]).css('display','');}
			return false;
		}
	}

	this.save = function() {
		if(this.checkForm()) {
			jQuery('#commentForm .commentInput').attr({disabled:true});
			ch = jQuery('#commentBlock').height();
			cw = jQuery('#commentBlock').width();
			jQuery('#loadComment').css({ height: ((ch > 40) ? ch : 40) + 'px', width: cw + 'px', filter: "alpha(opacity=50)", opacity: "0.5", display:'' });

			this.params.sid = phpSesSid;
			jQuery.post('/photodiary/comment',this.params,function(data){
				jQuery('#commentEntercodeImg').attr('src','/img.php?rnd='+Math.random());
				if(defined(data.ok)){
					jQuery('#commentReply, #commentName, #commentEmail, #commentText, #commentEntercode').attr('value','');
					jQuery("input[@name='comment[]']").each(function(){this.checked=false;});
					if(photodiaryComment._userShow){photodiaryComment.userShow();}else{photodiaryComment.show(null,true);}
				}else{
					errStr = 'Ошибка при добавлении комментария!';
					err = [];
					if(defined(data.error)){
						if(defined(data.error.err_auth)){}
						if(defined(data.error.err_commentName)){errStr+='\nУкажите Ваше имя!';err[err.length]='err_commentName';}
						if(defined(data.error.err_commentEmail)){errStr+='\nУкажите E-mail в формате somename@domain.ru!';err[err.length]='err_commentEmail';}
						if(defined(data.error.err_commentText)){errStr+='\nУкажите комментарий!';err[err.length]='err_commentText';}
						if(defined(data.error.err_commentEntercode)){errStr+='\nЗащитный код не введен или введен не верно!';err[err.length]='err_commentEntercode';}
						if(defined(data.error.err_commentSave)){err[err.length]='err_commentSave';}
					}
					for(i=0;i<err.length;i++){jQuery('#'+err[i]).css('display','');}
					jAlert(errStr,'Комментарии');
					jQuery('#commentForm .commentInput').attr({disabled:false});
					jQuery('#loadComment').css('display','none');
				}
			},'json');
		}
	}

	this.init = function(options) {
		this.photodiaryId = defined(options.photodiaryId) ? parseInt(options.photodiaryId) : 0;
		this.isAuth = defined(options.isAuth) ? parseInt(options.isAuth) : 0;
		this.url = defined(options.url) ? parseInt(options.url) : this.url;

		if(this.photodiaryId>0){
			jQuery('#commentForm .commentInput').attr({disabled:false,value:''});
			jQuery('#commentPhotodiaryId').attr('value',this.photodiaryId);
		}else{
			jQuery('#commentForm .commentInput').attr({disabled:true,value:''});
		}
		jQuery('div.commentError').css('display','none');
	}

	this.userShow = function() { }
}

var photodiaryComment = new photodiaryComment();

function photodiaryRateStarsRender(rate) {
	var full_stars, empty_stars, result = '';
	var sizeStars = 5;
	full_stars = Math.floor(rate);
	full_stars = 0;
	if (rate >= 20) {
		full_stars = 1;
	} else if (rate >= 40) {
		full_stars = 2;
	} else if (rate >= 60) {
		full_stars = 3;
	} else if (rate >= 80) {
		full_stars = 4;
	} else if (rate >= 100) {
		full_stars = 5;
	}
	result += '<img src="/i/star_' + full_stars + '.gif" alt="" border="0">';
	document.write(result);
}

jQuery(document).ready(function(){
	if(!defined(document.getElementById('cacheJsBlock'))){
		var divCache=document.createElement('DIV');
		divCache.id='cacheJsBlock';
		divCache.style.display='none';
		document.body.appendChild(divCache);
	}
	/*
	jQuery("div.blls_1").tooltip({
		track: true,
		delay: 0,
		showURL: false,
		fixPNG: true,
		showBody: " - ",
		extraClass: "pretty fancy",
		top: -15,
		left: 5
	});
	*/
	/* Фотодневники */
	var imgId, insId = 0;

	jQuery("img.img1").click(function(){
		/*opener.thumbID - глобальная переменная, которая передается при вызове PopUp-окна*/
		var thumbID = opener.thumbID;
		var photodata = jQuery("input",jQuery(this).parent().parent()).val().split(",");
		var globalImgCount = 0;
		if (!isNaN(jQuery.cookie('imgCount')) && jQuery.cookie('imgCount') != null)
			globalImgCount = parseInt(jQuery.cookie('imgCount'));
		jQuery.cookie('imgCount', ++globalImgCount, {path: '/'});
		var newImg = jQuery("<img />", opener.document).attr("src", jQuery(this).attr("src").replace(/150x150r/,'100x100c')).attr("id", "img" + globalImgCount).css("margin", "5px");
		jQuery(opener.document).find("div#thumbnails" + thumbID).append(jQuery("<ins class='diary_thumbnail'></ins>", opener.document).append(jQuery("<div class='diary_r'></div>").append(newImg).append("<div class='ico_edit'><a href='javascript: void(0)' title='Изменить описание'></a></div>")));

		var hiddenFieldImageData = jQuery("<input type='hidden' />", opener.document).attr("name", "imagedata[" + thumbID + "][" + globalImgCount + "]").attr("value", photodata[5]);
		jQuery(opener.document).find("div#thumbnails" + thumbID).parent().find("#photoDesc").append(hiddenFieldImageData);

		if (jQuery(opener.document).find("div#thumbnails" + thumbID + " > ins").length >= 5) {
			jQuery(opener.document).find("div#uploadButtons"  + thumbID).hide();
			jQuery(opener.document).find("table#photoDiaryPart" + thumbID ).find("div#photoLimitMessage").show();
		}
		self.close();
	});


	jQuery("a[id^='addPart']").click(function(){
		var partsCount = jQuery("table[id^='photoDiaryPart']:visible").length;
		if (partsCount < 5) {
			var partId = jQuery("input[name='partId']", jQuery("table[id^='photoDiaryPart']:hidden:first")).val();
			jQuery("table[id^='photoDiaryPart']:hidden:first").insertAfter(jQuery(this).parents().eq(3));
			jQuery("table[id^='photoDiaryPart']:hidden:first").show().find("#photoDesc").hide();
			jQuery("#addPartDown").hide();
		}
		else alert("Ограничение в 5 разделов");
	});

	jQuery("a[id^='delPart']").click(function() {
		if(confirm('Вы уверены, что хотите удалить этот раздел?')){
			var partId = jQuery("div[id^='thumbnails']", "table[id^='photoDiaryPart']:has(#" + jQuery(this).attr("id") + ")").attr("partId");
			//удаляю фото и описания
			jQuery("#photoDesc > input", "table[id^='photoDiaryPart']:has(#" + jQuery(this).attr("id") + ")").remove();
			jQuery("div[id^='thumbnails'] > ins", "table[id^='photoDiaryPart']:has(#" + jQuery(this).attr("id") + ")").remove();
			jQuery("input[name^='name']", "table[id^='photoDiaryPart']:has(#" + jQuery(this).attr("id") + ")").val("");
			jQuery("textarea[id^='description']", "table[id^='photoDiaryPart']:has(#" + jQuery(this).attr("id") + ")").text("");
			jQuery("table#photoDiaryPart" + thumbID).find("div#photoLimitMessage").hide();
			nicEditors.findEditor('description[' + partId + ']').setContent('');
			nicEditors.findEditor('photodescription[' + partId + ']').setContent('');
			jQuery("table[id^='photoDiaryPart']:has(#" + jQuery(this).attr("id") + ")").hide();
			//
			if(jQuery("table[id^='photoDiaryPart']:visible").length == 0) {
				jQuery("#addPartDown").show();
			}
		 }
	});

	jQuery("div[id^='thumbnails']").click(function(event){
		if (jQuery(event.target).is("a") === false)
			return false;
		var partId = jQuery(this).attr("partId");
		insId = jQuery(event.target).parents().eq(3).find("ins").index(jQuery(event.target).parents().eq(2));
		imgId =  jQuery(event.target).parents().eq(1).find("img").attr('id').replace(/img/,"");
		if (jQuery("#photoDesc > input[name=\"photodesc[" + partId + "][" + imgId + "]\"]", jQuery(event.target).parents().eq(4)).length > 0) {
			nicEditors.findEditor('photodescription[' + partId + ']').setContent(jQuery("#photoDesc > input[name=\"photodesc[" + partId + "][" + imgId + "]\"]", jQuery(event.target).parents().eq(4)).val());
		} else {
			nicEditors.findEditor('photodescription[' + partId + ']').setContent('<div></div>');
		}
		jQuery("#photoDesc", jQuery(event.target).parents().eq(4)).css("padding-left", jQuery(event.target).parents().eq(2)[0].offsetLeft).show("slow");
	});

	jQuery("a[id^='delPhoto']").click(function(){
		if (confirm('Вы уверены, что хотите удалить это изображение?')) {
			var partId = jQuery(this).parents().eq(0).attr("partId");
			jQuery(this).parents().eq(1).find("ins:eq(" + insId + ")").remove();
			jQuery(this).parents().eq(0).find("input[name=\"photodesc[" + partId + "][" + imgId + "]\"], input[name=\"imagedata[" + partId + "][" + imgId + "]\"]").remove();
			jQuery(this).parents().eq(0).hide();
			//
			if (jQuery("div#thumbnails" + partId + " > img").length < 5) {
				jQuery("div#uploadButtons"  + partId).show();
				jQuery("table#photoDiaryPart" + thumbID ).find("div#photoLimitMessage").hide();
			}
		}
	});

	jQuery("button[id^='savePhotoDesc']").click(function(){
		var partId = jQuery(this).parents().eq(0).attr("partId");
		if (jQuery(this).parents().eq(0).find("input[name=\"photodesc[" + partId + "][" + imgId + "]\"]").length == 0) {
			var hiddenField = document.createElement("input");
			hiddenField.type = "hidden";
			hiddenField.name = "photodesc[" + partId + "][" + imgId + "]";
			hiddenField.value = nicEditors.findEditor('photodescription[' + partId + ']').getContent();
			jQuery(this).parents().eq(0).append(hiddenField);
		} else {
			jQuery(this).parents().eq(0).find("input[name=\"photodesc[" + partId + "][" + imgId + "]\"]").val(nicEditors.findEditor('photodescription[' + partId + ']').getContent());
		}
		jQuery(this).parents().eq(0).hide("slow",function(){nicEditors.findEditor('photodescription[' + partId + ']').setContent("<div></div>");});
	});

	jQuery("#cancelDiary").click(function(){
		if (confirm("Вы уверены, что хотите удалить этот дневник?")) {
			window.location = "/photodiary/cancel" + location.search;
		}
	});

	jQuery("a[id^='setMainPhoto']").click(function(){
		var partId = jQuery(this).parents().eq(0).attr("partId");
		jQuery("ins > div.diary_r > img").attr("class", "");
		jQuery(this).parents().eq(1).find("ins > div.diary_r > img#img" + imgId).attr("class", "mainPhoto");
		var photoID = jQuery(this).parent().find("input[name='imagedata[" + partId + "][" + imgId + "]']").val();
		jQuery("input[name='photo_preview']").val(photoID);
	});

	jQuery("form#photodiary_step2, form#photodiary_edit").submit(function(){
		var error = 0;
		jQuery.each(jQuery("textarea[name^=description]", "table[id^='photoDiaryPart']:visible"), function() {
			if (nicEditors.findEditor(jQuery(this).attr("id")).getContent().toLowerCase() == '<br>' || nicEditors.findEditor(jQuery(this).attr("id")).getContent().toLowerCase() == '') {
		      alert('Поле "Текст раздела" не заполнено');
		      ++error;
		    }
		});
		if (jQuery("input[name='photo_preview']").val() <= 0 || jQuery("img.mainPhoto").size() < 1) {
			 alert('Необходимо установить одну из фотографий "главной"');
		     ++error;
		}
		if (error == 0) {
			if (jQuery.getUrlVar('active') == 0) {
				window.open("/photodiary/preview?id=" + jQuery.getUrlVar('id'), '_blank').focus();
			}
			return true;
		}
		return false;
	});
	/* --- */
	jQuery("a#popupAuth").click(function(){
		 jQuery.blockUI({
	            message: jQuery('#login_block'),
	            css: { top: '40%',  left:'40%', border: '', cursor: 'default'},
	            overlayCSS: {cursor: 'default'}
	        });
		return false;
	});

	jQuery("form#ajaxAuth").submit(function(){
		jQuery.post(
				"/photo/auth/ajaxlogin",
				{
					login: this.login.value,
					pass: this.pass.value,
					back: jQuery.getUrlVar("back")
				},
				function(data){
				    switch (data.error) {
					case "0":
						location.href = data.backUrl;
						break;
					case "1":
						alert(data.errorText);
						break;
					default:
						alert("Internal error");
						break;
					}
				  },
				  "json"
		);
		return false;
	});

});

jQuery.extend({
	  getUrlVars: function(){
	    var vars = [], hash;
	    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++)
	    {
	      hash = hashes[i].split('=');
	      vars.push(hash[0]);
	      vars[hash[0]] = hash[1];
	    }
	    return vars;
	  },
	  getUrlVar: function(name){
	    return jQuery.getUrlVars()[name];
	  }
});