var oldThCount=0;
var projects=false;
var tags=false;
var tagsIds=false;
var elements=0;
var page=false;
var curLang=false;
var curTag=-1;
var curProject=-1;
var text={};
var images=false;
var imSizes=false;
var touchObject=false;
var fullscreenHeight=false;
var viewerHistory=false;

function checkLang(){	return (navigator.language) ? navigator.language : navigator.userLanguage;};

function adjustHeight() {
	var html = document.documentElement;
	var size = window.innerHeight;

	html.style.height = (size + size) + "px";
	window.setTimeout(function() {
		if (window.pageYOffset == 0) {
			window.scrollTo(0, 0);
		}
		html.style.height = window.innerHeight + "px";
	}, 0);
}

var getTransformProperty=function(element) {
   var properties = [
       'transform',
       'WebkitTransform',
       'msTransform',
       'MozTransform',
       'OTransform'
   ];
   var p;
   while (p = properties.shift()) {
       if (typeof element.style[p] != 'undefined') {
           return p;
       }
   }
   return false;
}


function getThCols()
{
	var thsWidth=$("#thumbs").width();//-Math.floor($("#thumbs").width()/0.87*0.07);
	cnt=Math.floor(thsWidth/193);

	return cnt;
}

function isiPad(){    return (navigator.platform.indexOf("iPad") != -1 || navigator.platform.indexOf("iPhone") != -1);
}

function isiPhone(){	return (navigator.platform.indexOf("iPhone") != -1);}

function doRebuildTh(newThCount)
{
	needEmpty=$("#thumbs li:not(.empty):visible").size()%newThCount;
	//alert(needEmpty);
	$("#thumbs li.empty").remove();
	if (needEmpty!=0)
	{
		for (i=0; i < newThCount-needEmpty; i++)
		{
			$("#thumbs").append("<li class=\"empty\"><img src=\"/img/spacer.gif\"/></li>");
		}
	}
}

function winListResize(){	//if ($("body").hasClass('index') || $("body").hasClass('contacts')) return false;
	if ($("body").hasClass('contacts')) return false;

	//console.log($(window).height());

	if ($("#viewer:visible").size()==1 && $("#viewer-scroller:animated").size()==0) resizePhoto($(".viewer-img:eq(0)"),curPhoto);

	if ($("body").hasClass('index')){		generateIndexFilter();		return false;
	}

	var subright=$("#subright");

	if (subright.size()>0){/*		if ($.browser.msie){			var right=$("#right");
			var wH=$(window).height();
			right.css({'height':(wH-55 > 740 ? wH-55 : 740 )+'px'});
		}*/
		var cH=$("#rightaddr").offset().top;
		subright.css('height',(cH-subright.offset().top-10)+'px');
	}

	// recalc thumbs count
	var wW=$(window).width();
	var dW=$(document).width();
	if (dW>wW) wW=dW;
	//var wR=(isiPad() ? 260 : $("#subright").width() );
	var wR=300;

	var cL=Math.floor((wW-wR-50)/200);
	var wL=cL*194;

	var mW=Math.floor((wW-wR-wL)/2);
	$("#left").css({'width':wL+'px','margin-left':mW+'px'/*,'margin-top':(mW > 50 ? mW : 50)+'px'*/});
//	$("#right").css({'width':wR+mW+'px'});
//	if (!$("body").hasClass('index'))
//		$("#logo").css({'margin-top':(mW > 50 ? mW : 50)+'px'});

	//console.log(cL+' '+oldThCount);

	if (cL!=oldThCount)
	{
		oldThCount=cL;
		doRebuildTh(cL);
	}
}

function resizePhoto(obj,i)
{	if (!imSizes[images[i]]) return false;
	var wW=$(window).width();
	var dW=$(document).width();
	if (wW<dW) wW=dW;
	var wH=$(window).height();

	if (isiPhone()){		wH+=Math.ceil(wH/(wH>wW ? 360 : 210 )*60);	}

	//$("body").css('height','');
	//if (wH==0) wH=$(document).height();

	//$("body").css('height',wH+'px');

	$("#viewer,.viewer-inner").css({'width':wW+'px','height':wH+'px'});

	/*var wW=$("#viewer").width();
	var wH=$("#viewer").height();*/

	var pW=pNW=imSizes[images[i]][0];
	var pH=pNH=imSizes[images[i]][1];

	var pK=pW/pH;

	if (wW>pNW){ pNW=wW; pNH=Math.floor(wW/pK); }
	if (wH>pNH){ pNH=wH; pNW=Math.floor(wH*pK); }

	//pNW=1000;

	//console.log(obj.attr('src')+': '+pNW+' '+pNH+' original: '+pW+' '+pH);

	obj.css({'width':(pNW+1)+'px','height':(pNH+1)+'px','top':'50%','left':'50%','margin-left':'-'+Math.ceil(pNW/2)+'px','margin-top':'-'+Math.ceil(pNH/2)+'px'});
}

var curPhoto=-1;
var curiPadTop=0;
var curiPadHeight=0;
var iPadTouchStart=[-100,-100];
var iPadTouchCurrent=[-100,-100];
var transformProperty=false;

function closePhoto(){	if ($("body").hasClass('index')) return false;	curPhoto=0;
	if (isiPad() || true){		$("body").unbind('touchstart touchmove touchend');//.css({'overflow':($.browser.msie ? 'auto' : ''),'height':curiPadHeight+'px'});
		if (isiPhone()){			$("html").css({'height':''});
		}
		//$(window).scrollTop(curiPadTop);
	}

	if ($("body").hasClass('about') && curProject==0){		window.location='/#'+(curLang=='ru' ? '' : '/eng')+'/about/';
	}

	$("#viewer").hide();
	if ($(".viewer-hider").hasClass('closed')){		$(".viewer-hider").click();
	}
	//$("body").css({'height':fullscreenHeight+'px','overflow':'none'});
}

function showPhoto(i){	$(".viewer-img").attr("src","");
	$("<img src=\"/img/loader.gif\" class=\"loader\" />").appendTo("#viewer");
	$("#viewer").show();	var im=new Image();	$(im).bind('load',function(){		$(this).unbind('load');
		$("#viewer img.loader").remove();
		imSizes[i]=[this.width,this.height];
		curPhoto=i;
		viewerHistory[curProject]=curPhoto;
		$(".viewer-img").attr("src",this.src);
		if (isiPad() || true){			curiPadHeight=$("body").height();
			$("body").bind('touchstart',onTouchStart).bind('touchmove',onTouchMove).bind('touchend',onTouchEnd);//.css({'overflow':'hidden'});
			if (isiPhone()){
				var bH=$(document).height();
				$("html").css({'height':(bH*2)+'px'});
				$(window).resize();
				//alert(nbH);
			}

			setTimeout(function(){ window.scrollTo(0, 1); $(window).resize(); }, 0);

			//curiPadTop=$(window).scrollTop();
			//$(window).scrollTop(0);
		}
		fullscreenHeight=$("body").height();
		//$("body").css({'height':$(window).height()+'px','overflow':'hidden'});
		resizePhoto($(".viewer-img:eq(0)"),i);
	}).bind('error',function(){		alert('Sorry, file not found.');
		closePhoto();	}).attr('src','/img/photos/'+images[i][0]+'.jpg');
}

function slideLeft(){	var iC=0; for (var i in images) iC++;	if ($(".viewer-inner").size()>1 || iC<2) return false;
	var wW=$(window).width();
	var dW=$(document).width();
	if (wW<dW) wW=dW;
	var orig=$(".viewer-inner");
	var scroller=$("#viewer-scroller");
	var slider=orig.clone()/*.css({'margin-left':'-'+wW+'px'})*/.data('current',true).insertBefore(orig);
	scroller.css({'margin-left':'-'+wW+'px','width':wW*2+20+'px'});
	curPhoto--;
	if (curPhoto<0) curPhoto=(typeof projects[curProject]=='undefined' ? images : projects[curProject]['photos']).length-1;
	viewerHistory[curProject]=curPhoto;
	$(".viewer-img",slider).bind('load',function(){
		$(this).unbind('load');
		resizePhoto($(this),curPhoto);
	}).attr('src','/img/photos/'+images[curPhoto][0]+'.jpg');
	scroller.animate({'margin-left':0},700,'linear',function(){		orig.remove();
		$(this).css({'margin-left':0});
		$(".viewer-inner").each(function(){
			if (!$(this).data('current')) $(this).remove();
		});
		slider.data('current',null);	});
	//orig.stop().animate({'margin-left':Math.floor(wW/2)+'px'},500,'linear');
	/*slider.stop().animate({'margin-left':'0px'},500,'linear',function(){		$(".viewer-inner").each(function(){			if (!$(this).data('current')) $(this).remove();		});		$(this).data('current',null);
		orig.remove();
	});*/}

function slideRight(){	var mI=-999,iC=0; for (var i in images){		k=parseInt(i,10);		if (k>mI) mI=k;
		iC++
	}
	//console.log(curPhoto+' '+mI+' '+images.length);
	if ($(".viewer-inner").size()>1 || iC<2) return false;
	var wW=$(window).width();
	var dW=$(document).width();
	if (wW<dW) wW=dW;
	var orig=$(".viewer-inner");
	var slider=orig.clone()/*.css({'margin-left':wW+'px'})*/.data('current',true).insertAfter(orig);
	var scroller=$("#viewer-scroller");
	scroller.css({'margin-left':0,'width':wW*2+20+'px'});
	curPhoto++;
	if (curPhoto>mI) curPhoto=0;
	viewerHistory[curProject]=curPhoto;
	$(".viewer-img",slider).bind('load',function(){		$(this).unbind('load');		resizePhoto($(this),curPhoto);	}).attr('src','/img/photos/'+images[curPhoto][0]+'.jpg');
	scroller.animate({'margin-left':'-'+wW+'px'},700,'linear',function(){		orig.remove();
		$(this).css({'margin-left':0});
		$(".viewer-inner").each(function(){
			if (!$(this).data('current')) $(this).remove();
		});
		slider.data('current',null);	});
/*	orig.stop().animate({'margin-left':'-'+Math.floor(wW/2)+'px'},500,'linear');
	slider.stop().animate({'margin-left':'0px'},500,'linear',function(){		$(".viewer-inner").each(function(){
			if (!$(this).data('current')) $(this).remove();
		});
		$(this).data('current',null);		orig.remove();	});
	*/};

function onTouchStart(event){
	var e=event.originalEvent;
	//alert(e.touches.length);	if (e.touches.length!=1 || !e.target){		iPadTouchStart[0]=-100;		return false;
	}
	touchObject=e.target;
	event.preventDefault();
	event.stopPropagation();
	iPadTouchStart[0]=iPadTouchCurrent[0]=e.touches[0].pageX;
	iPadTouchStart[1]=iPadTouchCurrent[1]=e.touches[0].pageY;

	return false;}

function onTouchMove(event){	if (iPadTouchStart[0]<0) return true;
	var e=event.originalEvent;	iPadTouchCurrent[0]=e.touches[0].pageX;
	iPadTouchCurrent[1]=e.touches[0].pageY;
}

function onTouchEnd(e){	if (iPadTouchStart[0]<0) return true;
	if (Math.sqrt(Math.pow(iPadTouchStart[0]-iPadTouchCurrent[0],2)+Math.pow(iPadTouchStart[1]-iPadTouchCurrent[1],2)) < 25){		//e.stopPropagation();
		//alert(touchObject.nodeName);
		$(touchObject).click();
		//closePhoto();
		return false;
	}

	touchObject=false;

	var deltaX=iPadTouchStart[0]-iPadTouchCurrent[0];
	var deltaY=iPadTouchStart[1]-iPadTouchCurrent[1];

	if (Math.abs(deltaX)>Math.abs(deltaY)){
		if (Math.abs(deltaX)<50) return false;
		if (deltaX>0){			slideRight();
		}else{			slideLeft();		};
	}else{		if (Math.abs(deltaY)<50) return false;
		if (deltaY>0){
			slideDown();
		}else{
			slideUp();
		};	}
}

function slideUp(){	//if (!prevNextGal[0]) return false;
	if ($(".viewer-inner").size()>1) return false;
	if (images[-2]){
		var wW=$(window).width();
		var dW=$(document).width();
		if (wW<dW) wW=dW;
		var wH=$(window).height();
		var orig=$(".viewer-inner");
		var slider=orig.clone()/*.css({'margin-top':'-'+wH+'px'})*/.data('current',true).insertBefore(orig);
		var scroller=$("#viewer-scroller").css({'width':wW+'px','height':wH*2+20+'px','margin-top':'-'+wH+'px'});
		$(".viewer-img",slider).bind('load',function(){			$(this).unbind('load');
			resizePhoto($(this),-2);
			curPhoto=0;
			window.location="/#/"+($("body").hasClass('detail') ? page[1] : "")+"/"+(projects[curProject-1] ? projects[curProject-1]['url'] : projects[projects.length-1]['url'])+"/";
		}).attr('src','/img/photos/'+images[-2][0]+'.jpg');
		//return;
		scroller.animate({'margin-top':0},700,'linear',function(){
			orig.remove();
			$(this).css({'margin-top':0});
			$(".viewer-inner").each(function(){
				if (!$(this).data('current')) $(this).remove();
			});
			slider.data('current',null);
			winListResize();
		});
	}}

function slideDown(){	if ($(".viewer-inner").size()>1) return false;
	if (images[-1]){
		var wW=$(window).width();
		var dW=$(document).width();
		if (wW<dW) wW=dW;
		var wH=$(window).height();
		var orig=$(".viewer-inner");
		var slider=orig.clone()/*.css({'margin-top':wH+'px'})*/.data('current',true).insertAfter(orig);
		var scroller=$("#viewer-scroller").css({'width':wW+'px','height':wH*2+20+'px','margin-top':0});
		$(".viewer-img",slider).unbind('load').bind('load',function(){
			$(this).unbind('load');
			resizePhoto($(this),-1);
			curPhoto=0;
			window.location="/#/"+($("body").hasClass('detail') ? page[1] : "")+"/"+(projects[curProject+1] ? projects[curProject+1]['url'] : projects[0]['url'])+"/";
		}).attr('src','/img/photos/'+images[-1][0]+'.jpg');
		scroller.animate({'margin-top':'-'+wH+'px'},700,'linear',function(){
			orig.remove();
			$(this).css({'margin-top':0});
			$(".viewer-inner").each(function(){
				if (!$(this).data('current')) $(this).remove();
			});
			slider.data('current',null);
			winListResize();
		});
	}
}

$(document).bind('ready',function(){
	$(window).bind('resize',winListResize);
	if ($("body").hasClass('detail')){		var cPhoto=0;		$("#subleft,#thumbs li:not(.empty)").each(function(){			$(this).bind('click',function(){				var z=($(this).attr('id')=="subleft" ? idCover : parseInt( $(this).attr("id").substring(1),10) );
				showPhoto(z);
			});		});
/*
		$(".viewer-inner").bind('click',function(e){			e.stopPropagation();			closePhoto();
			return false;		});
*/
		transformProperty=getTransformProperty(document.body);
	}

	$("#viewer-controls area").live('click',function(e){		e.stopPropagation();
		switch($(this).attr('id')){
			case 'slide-left': slideLeft(); break;
			case 'slide-right': slideRight(); break;
			case 'slide-up': slideUp(); break;
			case 'slide-down': slideDown(); break;
		}
		return false;
	});

	$(".viewer-inner").live('click',function(e){
		e.stopPropagation();
		closePhoto();
		return false;
	});

	$(document).bind('keydown',function(e){		if ($("body").hasClass('detail') && $("#viewer:visible").size()==1)
		switch (e.keyCode) {
			case 37: if ($("#viewer:visible").size()==1) { e.preventDefault(); slideLeft(); return false;} break;
			case 39: if ($("#viewer:visible").size()==1) { e.preventDefault(); slideRight(); return false;} break;
			case 38: if ($("#viewer:visible").size()==1) { e.preventDefault(); slideUp(); return false;} break;
			case 40: if ($("#viewer:visible").size()==1) { e.preventDefault(); slideDown(); return false;} break;
			default:
		};
	});

	$(".viewer-right .logo").live('click',function(e){		e.preventDefault();
		e.stopPropagation();
		$("body").animate({'opacity':0},500,'linear',function(){
			window.location=(curLang=="en" ? "/eng" : "")+"/";
		});
		return false;	});

	$(".viewer-hider").live('click',function(e){		e.preventDefault();
		var panel=$(".viewer-right");
		if ($(this).hasClass('closed')){			var wH=$(window).height()-55;
			if (wH<740) wH=740;
			$(".controls",panel).css({'display':'block'});			panel.css({'height':wH+'px'}).animate({'top':0},500,function(){				$(this).css({'height':null,'bottom':55+'px'})
				$(".viewer-hider").removeClass('closed');			});		}else{			var pH=panel.height();			$(".controls",panel).css({'display':'none'});			panel.css({'bottom':null,'height':pH+'px'}).animate({'top':'-'+(pH-50)+'px'},function(){				$(".viewer-hider").addClass('closed');			});
			//panel.addClass('hidden').animate({'height':30+'px'});
		}
		return false;	});

	var toPreload=['/img/loader.gif','/img/a_up.png','/img/a_down.png']

    for (var l in toPreload){
		var im=new Image();
		im.src=toPreload[l];
	}

	if (isiPad() && false)
	$(window).scroll(function(){		//alert('scrolled');		$("#viewer").css({'margin-top':$(window).scrollTop()+'px'});	});

	$(window).hashchange(function(){		var url=window.location.hash.substring(1);
		if (url==""){			window.location="/#"+window.location.pathname;			return false;		}

		$(".pdflike").remove();
		var u=window.location.hash.split('/');
		var lang=u[1];
		if (lang=="eng"){u.shift();lang="en";}else{lang="ru"};

		var jlang=checkLang();

		if (ua!=false && lang=="ru" && u.length==2 & (ua.indexOf('ru')==-1 && jlang.indexOf('ru')==-1)){			ua=false;
			window.location='/#/eng/';
			return;
		}

		ua=false;

		//console.log(u+' '+curLang+' '+lang);
		if (u[1]=="projects" || u[1]=="events" || u[1]=="about"){			if (($("body").hasClass('projects') || $("body").hasClass('events') || $("body").hasClass('about')) && curLang==lang){				if (u[2]=="tag"){					tagClick(u[3]);
				}else
				if (u[2]!=""){					showProject(u[2]);
				}else{					tagClick("");				}				return false;
			}else{				url=(lang=="en" ? "/eng" : "")+"/"+u[1]+"/";			}
		}
		//if (url=="/" && $('body').hasClass('index')) return false;
		$("body").stop().animate({'opacity':0},400);
		$.post(url,{'mode':'ajax'},function(res){			page=u;
			curLang=res['lang'];			document.title='MEL Space'+(res['title'] ? ' - '+res['title'] : '');			$("body").stop().animate({'opacity':0},400,function(){				$("body").removeClass();				//console.log(res);
				switch(res['class']){					case 'index': indexLoaded(res); break;
					case 'about':
					case 'events':
					case 'projects': projectsLoaded(res); break;
					case 'space': spaceLoaded(res); break;
					case 'contacts': contactsLoaded(res); break;
				}

				$("body").addClass(res['class']+' '+res['lang']);//.css('overflow',(res['class']=='index' ? 'hidden' : ($.browser.msie ? 'auto' : '') ));
/*				if (!$.browser.msie){
					$("#right").css('bottom','55px');
				}else{					$("#right").css('position','absolute');
					$("body").css('overflow',(res['class']=='index' ? 'hidden' : 'auto'))				}*/
				oldThCount=-1; $(window).resize();

				buildAjaxLinks();

				$("body").animate({'opacity':1},400);
			});
		},'json');	});

	$(window).hashchange();
});

function tagClick(tag){	curTag=tagsIds[tag] || -1;

	$("#tags li").removeClass('current');
	$("li:eq(0),#t"+curTag,"#tags").addClass('current');

	if ($("body").hasClass('detail')){		showProjects();
		//console.log('projects from detail');
	}else{
		var pList=[];
		for (var i=0;i<projects.length;i++){			if (curTag==-1 || $.inArray(curTag,projects[i]['tags'])!=-1) pList.push(projects[i]['id']);
		}
		$("#thumbs").stop().animate({'opacity':0},400,function(){			$("li",this).each(function(){				$(this).css('display',(typeof $(this).attr('id')!="undefined" && $.inArray(parseInt($(this).attr('id').substring(1),10),pList)!=-1 ? 'inline-block' : 'none' ));			});
			oldThCount=-1;
			$(window).resize();
			$(this).animate({'opacity':1},400);		});
	}}

function buildAjaxLinks(){	$("a").each(function(){
		if ($(this).data('ajax') || $(this).hasClass('out')) return true;
		var h=$(this).attr('href');
		if (h && h.indexOf(window.location.protocol)!=-1){			var u=h.split('/'); var t=[];
			if (u[2]!=window.location.hostname) return true;
			for (var i=3;i<u.length;i++) t.push(u[i]);
			h='/'+t.join('/');// console.log(h);
		}
		$(this).attr('href','#'+h).data('ajax',true);
	});
}

function showProject(url){
	function buildProject(){		$("#rightaddr .inner").hide();		$("<div class=\"pdflike\">"+(projects[i]['pdf'] ? "<a href=\""+projects[i]['pdf']+"\" class=\"out\" target=\"_blank\"><img src=\"/img/pdf-icon.png\" alt=\"\" /></a>" : "")+"<iframe scrolling=\"no\" frameborder=\"0\" allowtransparency=\"true\" style=\"border:none; overflow:hidden; width:140px; height:24px;\" src=\"http://www.facebook.com/plugins/like.php?href="+encodeURIComponent(window.location.protocol+"//"+window.location.hostname+(curLang=='ru' ? '' : '/eng')+"/"+page[1]+"/"+projects[i]['url']+"/")+"&amp;layout=button_count&amp;show_faces=false&amp;width=140&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=24&amp;locale=en_US\"></iframe></div>").prependTo("#rightaddr").clone().appendTo(".viewer-right");		$("#subright").html("<span id=\"title\">"+projects[i]['title']+"</span> "+projects[i]['descr']);
		$(".viewer-right .viewer-content").html("<span id=\"title\">"+projects[i]['title']+"</span><br/><br/>"+projects[i]['descr']);
		$("#thumbs li").remove();
		$("body").addClass('detail');
		var photosString="";
		var idCover=-99;
		for (var k=0;k<projects[i]['photos'].length;k++){			//console.log(projects[i]['photos'][k][0]);			if (page[1]=="events" && projects[i]['photos'][k][0]==projects[i]['cover']){				idCover=k;				//continue;
			}
			photosString+="<li id=\""+page[1].substring(0,1)+k+"\"><img src=\"/img/thumbs/photos/"+projects[i]['photos'][k][0]+(projects[i]['photos'][k][1] ? "u" : "")+".jpg\" alt=\""+projects[i]['photos'][k][0]+"\" /></li>";
		}
		$("#tags li").removeClass('current');
		$("li:eq(0),#t-1","#tags").addClass('current');
		for (var k=0;k<projects[i]['tags'].length;k++){
			$("#tags #t"+projects[i]['tags'][k]).addClass("in_project");
		}
		$("#thumbs").html(photosString);
		if (page[1]=="projects"){
			document.title='MEL Space'+(curLang=='en' ? ' - Project - '+projects[i]['title'] : ' - Проект - '+projects[i]['title']);
		}else
		if (page[1]=="events"){			//$("#subleft").remove();			//$("<div id=\"subleft\"><img class=\"event-cover\" src=\"/img/photos/"+projects[i]['cover']+".jpg\" id=\"cover\" /></div>").insertBefore("#thumbs");			document.title='MEL Space'+(curLang=='en' ? ' - Event - '+projects[i]['title'] : ' - Событие - '+projects[i]['title']);
			$(".event-cover").bind('click',function(){ showPhoto (idCover);})		}else
		if (page[1]=="about"){			document.title='MEL Space'+(curLang=='en' ? ' - Публикация - '+projects[i]['title'] : ' - Публикация - '+projects[i]['title']);		}
		oldThCount=-1;
		$(window).resize();

		$("#subleft,#thumbs li:not(.empty)").each(function(){
			$(this).bind('click',function(){				var z=($(this).attr('id')=="subleft" ? idCover : parseInt( $(this).attr("id").substring(1),10) );				showPhoto(z);
			});
		});

		var tmp=images[curPhoto] || 0;

		images={};
		var l=0;
		if (projects[i-1]) {l++;images[-2]=projects[i-1]['photos'][viewerHistory[i-1]];}else			if (projects.length>1){ l++; images[-2]=projects[projects.length-1]['photos'][viewerHistory[projects.length-1]]; }
		if (projects[i+1]) {l++; images[-1]=projects[i+1]['photos'][viewerHistory[i+1]];}else
			if (projects.length>1) {l++; images[-1]=projects[0]['photos'][viewerHistory[0]];}
		for (var k in projects[i]['photos']) {l++; images[k]=projects[i]['photos'][k];}
		imSizes={};
		var im=[];
		//console.log(images);
		for (var k in images){			im[k]=new Image();
			(function(){				var j=images[k];
				if (k==0 && page[1]=="about" && i==0) showPhoto(0);
				im[k].onload=function(){
					imSizes[j]=[this.width,this.height];
				};
				im[k].src='/img/photos/'+images[k][0]+'.jpg';
			})();
		}

		//$(window).scrollTop(0).scroll();
	}
	var i=0;
	for (; i<projects.length && projects[i]['url']!=url; i++);

	if (!projects[i]) return false;

	curProject=i;

	if ($("body").css('opacity')!=0 && !($("body").hasClass('detail') && $("#viewer:visible").size()==1)){
		$("body").stop().animate({'opacity':0},400,function(){			buildProject();			$("body").animate({'opacity':1},400);		});
	}else{		buildProject();	}
}

function showProjects(){	var projectsString="";
	for (var i=0; i<projects.length;i++)
		projectsString+="<li id=\"p"+projects[i]['id']+"\""+(curTag==-1 || $.inArray(curTag,projects[i]['tags']) !=-1 ? "" : " style=\"display:none\"")+"><a href=\""+(curLang=='ru' ? '' : '/eng')+"/"+page[1]+"/"+projects[i]['url']+"/\"><img src=\"/img/thumbs/photos/"+projects[i]['cover']+".jpg\" alt=\""+projects[i]['title']+"\"><span class=\"name\">"+(projects[i]['title'] || '')+(page[1]=='events' ? '&nbsp;' : '')+"</span><span class=\"date\">"+projects[i]['date']+"&nbsp;</span></a></li>";
	$("body").removeClass('detail');
	if ($("body").css('opacity')!=0){		$("body").animate({'opacity':0},400,function(){			$("#subleft").remove();			$("#tags li").removeClass('in_project');
			$("#subright").html(text['projects']);
			$("#thumbs").html(projectsString); oldThCount=-1; $(window).resize();
			$("#rightaddr .inner").show();
			$("body").animate({'opacity':1},400);
			buildAjaxLinks();
		});
	}else{		$("#subleft").remove();		$("#tags li").removeClass('in_project');		$("#subright").html(text['projects']);
		$("#thumbs").html(projectsString); oldThCount=-1; $(window).resize();	}
}

function contactsLoaded(data){	$("body").html("<div id=\"main\"><div id=\"left\" class=\"clearfix\"><div id=\"subleft\">"+data['content']['content']+"</div></div><div id=\"right\" class=\"clearfix\"><a href=\""+(data['lang']=="en" ? "/eng" : "")+"/\"><img src=\"/img/viewer_logo.png\" id=\"logo\" alt=\"melspace.ru\" /></a><div id=\"rightaddr\"><div class=\"inner\">"+data['content']['contacts']+"</div></div></div></div>");
}

function spaceLoaded(data){	//console.log(data);
	images=data['content']['photos'];
	$("body").html("<div id=\"main\"><div id=\"left\"><ul id=\"thumbs\" class=\"clearfix\"></ul></div><div id=\"right\" style=\"overflow:hidden;\"><a href=\""+(data['lang']=='ru' ? '' : '/eng')+"/\"><img src=\"/img/viewer_logo.png\" id=\"logo\" /></a><div id=\"subright\" class=\"clearfix\">"+data['content']['right']+"</div><div id=\"rightaddr\"><div class=\"inner\">"+data['content']['contacts']+"</div></div></div></div><div id=\"viewer\" style=\"display:block;display:none;overflow:hidden;\"><a class=\"viewer-hider\" href=\"#\">Hide</a><div id=\"viewer-scroller\"><div class=\"viewer-inner\"><img src=\"\" class=\"viewer-img\" alt=\"\" /></div></div><div class=\"viewer-right\"><div class=\"viewer-back\"></div><a href=\"/\" class=\"logo\"></a><div class=\"viewer-content\">"+data['content']['right']+"</div><img src=\"/img/viewer_buttons_space.png\" alt=\"viewer controls\" usemap=\"#viewer-controls\" class=\"controls\" /></div><map name=\"viewer-controls\" id=\"viewer-controls\"><area href=\"#\" shape=\"rect\" id=\"slide-left\" coords=\"0,31,57,65\" /><area href=\"#\" shape=\"rect\" id=\"slide-right\" coords=\"128,31,185,65\" /></map></div>").addClass('detail');
	var spaceString="";
	for (var i in data['content']['photos']){
		spaceString+="<li id=\"s"+data['content']['photos'][i][0]+"\"><img src=\"/img/thumbs/photos/"+data['content']['photos'][i][0]+".jpg\" alt=\""+data['content']['photos'][i][0]+"\"></li>";
	}
	$("#thumbs").html(spaceString);
	oldThCount=-1; $(window).resize();

	imSizes={};
	var im=[];
	for (var k in images){
		im[k]=new Image();
		(function(){
			var j=images[k];
			im[k].onload=function(){
				imSizes[j]=[this.width,this.height];
			};
			im[k].src='/img/photos/'+images[k][0]+'.jpg';
		})();
	}

	var cPhoto=0;
	$("#thumbs li:not(.empty)").each(function(){
		var z=cPhoto++;
		$(this).bind('click',function(){ showPhoto(z); });
	});
}

function projectsLoaded(data){	projects=data['content']['projects'];
	elements=data['content']['projects'].length;
	tags=data['content']['tags'];
	text['projects']=data['content']['right'];
	tagsIds={};
	viewerHistory=[];
	for (var i=0;i<elements;i++) viewerHistory[i]=0;
	for (var i=0;i<data['content']['tags'].length;i++){		tagsIds[data['content']['tags'][i]['url']]=data['content']['tags'][i]['id'];
	}
	if (data['class']=="events"){
		tagsIds['over']=-3;
		tagsIds['future']=-2;
	};
	curTag=(page.length>2 && page[2]=="tag" ? tagsIds[page[3]] : -1);
	var html="<div id=\"main\"><div id=\"left\"><ul id=\"thumbs\" class=\"clearfix\"></ul></div><div id=\"right\" style=\"overflow:hidden;\"><a href=\""+(data['lang']=='ru' ? '' : '/eng')+"/\"><img src=\"/img/viewer_logo.png\" id=\"logo\" /></a><ul id=\"tags\" class=\"clearfix\">";
	if (data['class']=="projects"){
		html+="<li class=\"current\"><a href=\""+(data['lang']=='ru' ? '' : '/eng')+"/projects/\">"+(data['lang']=='ru' ? 'проекты' : 'projects')+"</a></li><li"+(curTag==-1 ? " class=\"current\"" : "")+" id=\"t-1\"><a href=\""+(data['lang']=='ru' ? '' : '/eng')+"/projects/\">"+(data['lang']=='ru' ? 'все' : 'all')+"</a></li>";
	}
	else
	if (data['class']=="events"){		html+="<li class=\"current\"><a href=\""+(data['lang']=='ru' ? '' : '/eng')+"/events/\">"+(data['lang']=='ru' ? 'события' : 'events')+"</a></li><li"+(curTag==-3 ? " class=\"current\"" : "")+" id=\"t-3\"><a href=\"/events/tag/over/\">"+(data['lang']=='ru' ? 'прошедшие' : 'past')+"</a></li><li"+(curTag==-2 ? " class=\"current\"" : "")+" id=\"t-2\"><a href=\"/events/tag/future/\">"+(data['lang']=='ru' ? 'будущие' : 'future')+"</a></li><li"+(curTag==-1 ? " class=\"current\"" : "")+" id=\"t-1\"><a href=\""+(data['lang']=='ru' ? '' : '/eng')+"/events/\">"+(data['lang']=='ru' ? 'все' : 'all')+"</a></li>";
	}else
	if (data['class']=="about"){
		html+="<li class=\"current\"><a href=\""+(data['lang']=='ru' ? '' : '/eng')+"/about/\">"+(data['lang']=='ru' ? 'о нас' : 'about us')+"</a></li><li"+(curTag==-1 ? " class=\"current\"" : "")+" id=\"t-1\"><a href=\""+(data['lang']=='ru' ? '' : '/eng')+"/about/\">"+(data['lang']=='ru' ? 'все' : 'all')+"</a></li>";
	}
	html+="</ul><div id=\"subright\" class=\"clearfix\">"+data['content']['right']+"</div><div id=\"rightaddr\"><div class=\"inner\">"+data['content']['contacts']+"</div></div></div></div><div id=\"viewer\" style=\"display:block;display:none;overflow:hidden;\"><a class=\"viewer-hider\" href=\"#\">Hide</a><div id=\"viewer-scroller\"><div class=\"viewer-inner\"><img src=\"\" class=\"viewer-img\" alt=\"\" /></div></div><div class=\"viewer-right\"><div class=\"viewer-back\"></div><a href=\"/\" class=\"logo\"></a><div class=\"viewer-content\"></div><img src=\"/img/viewer_buttons.png\" alt=\"viewer controls\" usemap=\"#viewer-controls\" class=\"controls\" /></div><map name=\"viewer-controls\" id=\"viewer-controls\"><area href=\"#\" shape=\"rect\" id=\"slide-left\" coords=\"0,31,57,65\" /><area href=\"#\" shape=\"rect\" id=\"slide-right\" coords=\"128,31,185,65\" /><area href=\"#\" shape=\"rect\" id=\"slide-up\" coords=\"63,0,122,32\" /><area href=\"#\" shape=\"rect\" id=\"slide-down\" coords=\"63,33,122,65\" /></map></div>";
	$("body").html(html);
	var tagsString="";
	for (var i=0; i<data['content']['tags'].length;i++)		tagsString+="<li id=\"t"+data['content']['tags'][i]['id']+"\""+(curTag==data['content']['tags'][i]['id'] ? " class=\"current\"" : "")+"><a href=\""+(data['lang']=='ru' ? '' : '/eng')+"/projects/tag/"+data['content']['tags'][i]['url']+"/\">"+data['content']['tags'][i]['title']+"</a></li>";
	$(tagsString).insertAfter("#tags li:eq(0)");

	if (curTag==-1 && page.length>2 && page[2]!=""){		showProject(page[2]);
	}else{
		showProjects();
	}
}

function generateIndexFilter(){	var wH=$(window).height(); wH2=Math.floor(wH/2);

	var c=$("<canvas width=\"4\" height=\""+wH+"\"></canvas>");
	if (typeof c[0].getContext=="undefined"){
		$("#viewer").css('opacity','0.5');
		return false;
	}
	var ctx = c[0].getContext("2d");
	var cnt=Math.ceil(wH2/4);
	var maxR=2.8;
	var minR=0.5;
	var step=maxR/(cnt+Math.floor(cnt*0.1));

	ctx.fillStyle='#fff';
	ctx.beginPath();

	var r=0;

	for (var i=0; i<cnt;i++){
		r=maxR-(i*step);
		if (r<minR) r=minR;
		ctx.arc(2, i*4+2, r, 0, Math.PI*2, true);
	}

	//console.log(wH2%4);

	for (var i=0; i<cnt+(wH2%4<2);i++){
		r=maxR-(i*step);
		if (r<minR) r=minR;
		ctx.arc(2, wH-i*4, r, 0, Math.PI*2, true);
	}

	ctx.closePath();
	ctx.fill();

	var data=c[0].toDataURL("image/png");
	//console.log(data);

	$("#index-mask").css({'background':'transparent url('+data+') 0 0 repeat-x'});}

function indexLoaded(data){	$("body").html(data['content']);

	if (data['img']!=''){
		var im=new Image();
		$(im).bind('load',function(){
			$("<div id=\"viewer\"><div class=\"viewer-inner\"><img src=\""+$(this).attr('src')+"\" class=\"viewer-img\" alt=\"\" /></div></div><div id=\"index-mask\"></div>").css('z-index',10).appendTo("body");
			imSizes={};
			var x=$(this).attr('src');
			imSizes[x]=[this.width,this.height];
			images=[$(this).attr('src')];
			curPhoto=0;
			$(window).resize();
		}).attr('src','/img/index/'+data['img']);
	}

	if (data['flash']){
		var player = '<div id=\"stream\"><div id="inner_stream" ></div></div>';
		var obj = $(player).insertBefore("#logo");
		swfobject.embedSWF("/include/mel-live.swf", 'inner_stream', "100%", "100%", "10.1.0", false, {}, {wmode:"transparent", allowScriptAccess:"always"}, {},  function(e) {
			if (e.success) return;
		});
	}}
