var portfolio={
	data: {
		articles: [],		//array of articles
		articleId: 0		//current article id
	},


	mouseScroller: {
		a: null,//acceleration
		coords: null,//coordinates (left top corner) of sensitive zones
		interval: 25, //interval for periodical scroll check 
		k: null,//coefficient (between -1 and 1)
		step: 50, //step of scroll animation
		zones: {w: 110,h: 340} //dimensions of sensitive zones
	},

	init: function(){
		portfolio.firstLoading = true;
		portfolio.isAnimating = false;
		if(U.isajax()){
			//inititalize jquery.history
			if(portfolio.historySupport()){
				jQuery.historyInit(portfolio.pageload);
			}
			if (hiddenoOverflow==0)
			{
				//inititalize mouse events
				U.addEvent(document,'mousemove',portfolio.clientXY);
				//set interval for periodical scroll check 
				setInterval('portfolio.contentBlockScroll()',portfolio.mouseScroller.interval);
			}
			else
			{
				$('#arrowLeft').hide();
				$('#arrowRight').hide();		
			}


			var hash;
			
			if(location.hash==''){
			}else{
				hash=location.hash.substr(1);
			}
			if( !portfolio.historySupport() ){
				portfolio.pageload(hash);
			}
			
			//change step parameter for Chrome
			if(BrowserDetect.browser=='Chrome')
			{
				//portfolio.mouseScroller.step = 150;
				portfolio.mouseScroller.interval = 25;
			}
			
			//add event for window resizing
			U.addEvent(window,'resize',portfolio.redrawBlocks);
			portfolio.redrawBlocks();
			portfolio.firstLoading = false;
		}
	
	},

	pageload: function(hash){
		if(hash){
			var id=portfolio.getIdFromAnchor(hash);
			portfolio.articleId = id;
			if(portfolio.articleId>0){
					portfolio.data.articleDisplayed=false;
					U.tryUntil('portfolio.startShowArticleAnimation('+portfolio.articleId+',\''+hash+'\')','U.gbi(\'item'+portfolio.articleId+'\') && portfolio.data.articleDisplayed',25);
			}
			
			portfolio.getData(hash);
		}
	},

	getData: function(hash){
		//get article from the server if data is not cached
		var serverQuery={};
		if( !portfolio.articleIsCached(portfolio.articleId) ){
			serverQuery.id=portfolio.articleId;
		}

		if(serverQuery.id){
			var req=new JsHttpRequest();
			req.onreadystatechange=function(){
				if(req.readyState==4){
					if(req && req.responseText){alert(req.responseText);return;}
					portfolio.setArticleData( req.responseJS.article);
					portfolio.displayData(hash);
				}
			}
			req.open(null,'/page.php?id=1&lang='+currentLang,true);
			req.send(serverQuery);
		}else{
			portfolio.displayData(hash);
		}
	},
	

	displayData: function(hash){
		portfolio.data.articleDisplayed=true;
		if(portfolio.articleId>0){
			if (portfolio.data.articles[portfolio.articleId] !== undefined)
			document.title= pagetitle + ' - '+ portfolio.data.articles[portfolio.articleId].titleTag;
		}
	},

	showArticle: function(id){
		var article=portfolio.data.articles[id];
		for(var i=0; i<article.pages.length; i++){
			
			$('#article'+id+'page'+i).html(article.pages[i].code);
		}
		$('#article'+id+'close').show();		
	},

	hideArticle: function(id){
		//hide article
		$('#artTable'+id).hide();
		
		//restore dashed lines from neighbour blocks
		parentElement = $('#article'+id).parent().parent().parent().parent().parent();
		if(parentElement.next().find("div.article").length > 0)
			{
					parentElement.next().find("div.article").css("border-left",  "1px dashed #8c8c8c");
			}
			if(parentElement.prev().find("div.article").length > 0)
			{
					parentElement.prev().find("div.article").css("border-right",  "1px dashed #8c8c8c");
			}	
		//run animation	
		portfolio.hideArticleAnimation(id);

	},

	startShowArticleAnimation: function(id,hash){
		//prepare article div for animation
		if( !U.gbi('article'+id) ){
			var div=document.createElement('DIV');
			div.setAttribute('id','article'+id);
			div.setAttribute('class','article');
			U.append('item'+id,div);
		}
		
		$('#article'+id).ready(function() {
			$('#article'+id).css({marginTop:'40px',width: '11px',height: '340px'});
			//show article animation
			portfolio.showArticleAnimation(id);
		});
	},
	
	showArticleAnimation: function(id){
		var pagesWidth=portfolio.getPagesWidth(id);
		var articleX=U.layerX(U.gbi('item'+id));
		var contentBlockX=U.gbi('contentBlock').scrollLeft;
		$('#article'+id).animate( {height: "470px", marginTop: "0px"}, 200).animate({width: 11+pagesWidth+"px"}, 200,'easeInQuint',
			function(){
				$('#contentBlock').animate( {scrollLeft: articleX+contentBlockX+"px"}, 400,'easeOutQuint',
					function(){
						portfolio.isAnimating = false;
						U.tryUntil('portfolio.putBlocksInArticle('+id+')','portfolio.data.articles['+id+'].pages',25);
					} );
			} );
	},
	
	hideArticleAnimation: function(id){
			var articleX=U.layerX(U.gbi('article'+id));
			var contentBlockScrollLeft=U.gbi('contentBlock').scrollLeft;
			$('#article'+id).animate({width: 11+"px"}, 800,'easeOutQuint',

			function(){
				$('#article'+id).animate({height: "340px", marginTop: "65px"}, 50,
				function(){
					U.gbi('item'+id).removeChild(U.gbi('article'+id));	
				});

				} );
			$('#contentBlock').animate( {scrollLeft: contentBlockScrollLeft + articleX-50+"px"}, 100,'easeOutQuint');
	},	


	showProject: function(id,typeUrl){
		//break operation if previous operation is not finished
		if(portfolio.isAnimating){return;}
		portfolio.isAnimating = true;
		
		var hash=typeUrl+'article'+id+'.html';
		portfolio.localRedirect(hash);

	},

	closeWork: function(id){
		//break the operation if previous animations is still processing
		if( !portfolio.isAnimating ){
			portfolio.hideArticle(id);
		}
	},

	historySupport: function(){
		//return true;
		if(false
			|| (BrowserDetect.browser=='Explorer' && BrowserDetect.version>=5.5)
			|| BrowserDetect.browser=='Firefox'
			|| BrowserDetect.browser=='Mozilla'
		){
			return true;
		}else{
			return false;
		}
	},

	clientXY: function(evt){
		//define mouse coordinates
		var cx=evt.clientX;
		var cy=evt.clientY;
		var msZonesCoords=portfolio.mouseScroller.coords;
		//check mouse position
		portfolio.mouseScroller.k=portfolio.checkMouseInZone(cx,cy,msZonesCoords);
	},

	contentBlockScroll: function(){
		//break the operation if previous animations is still processing
		if(portfolio.isAnimating){return;}
		var bak_a=portfolio.mouseScroller.a;
		var new_a=portfolio.mouseScroller.k;
		portfolio.mouseScroller.a=(bak_a-new_a)*.7+new_a;
		if(Math.abs(portfolio.mouseScroller.a)<0.01){portfolio.mouseScroller.a=0;}
		if(portfolio.mouseScroller.a){
			//scroll contentBlock
			portfolio.doContentBlockScroll();
		}
		//show or hide scrolling arrows
		if( BrowserDetect.browser!='Explorer'){
			portfolio.showScrollArrow();
		}
	},

	//-----------------------------------------------------------------

	doContentBlockScroll: function(){
		var cb=U.gbi('contentBlock');
		var bak_x=cb.scrollLeft;
		var new_x=bak_x + portfolio.mouseScroller.a*portfolio.mouseScroller.step;
		cb.scrollLeft=new_x;
	},

	showScrollArrow: function(){
		//hide or show arrow
		if(portfolio.mouseScroller.a>0){

			$('#arrowLeft').hide();
			$('#arrowRight').show();
		}else if(portfolio.mouseScroller.a<0){
			$('#arrowLeft').show();
			$('#arrowRight').hide();
		}else{
			$('#arrowLeft').hide();
			$('#arrowRight').hide();
		}
	},


	articleIsCached: function(id){
		return (portfolio.data.articles[id] && portfolio.data.articles[id].pages);
	},


	getIdFromAnchor: function(hash){
		if(hash.indexOf('article')>=0){
			var id=parseInt(hash.substr( (hash.indexOf('article')+7) ));
			return id;
		}else{
			return 0;
		}
	},

	getPagesWidth: function(id){
		var widths=portfolio.data.articles[id].widths;
		var result=32;
		for(var i=0; i<widths.length; i++){
			result+=parseInt(widths[i])+11;
		}
		return result;
	},

	putBlocksInArticle: function(id){
	
		var widths=portfolio.data.articles[id].widths;
		var htmlArticleTable = '<table id="artTable'+id+'"><tbody><tr>';
		for(var i=0; i<widths.length; i++){
			htmlArticleTable = htmlArticleTable + '<td style="width: '+(11+parseInt(widths[i]))+'px;"><div style="width: '+widths[i]+'px;"';
			var image=portfolio.data.articles[id].pages[i]['image'];
			if (image)
				htmlArticleTable = htmlArticleTable + ' class="imagebox"';
			else
				htmlArticleTable = htmlArticleTable + ' class="textbox"';
				
				
			htmlArticleTable = htmlArticleTable + ' id="article'+id+'page'+i+'"></div></td>';
		}
		htmlArticleTable = htmlArticleTable + '<td class="articleClose"><a id="article'+id+'close" href="javascript:portfolio.closeWork('+id+')"></a></td></tr></tbody></table>';
		articleDiv = $('#article'+id);
		if( !U.gbi('artTable'+id) ){
			
			$('#article'+id).append(htmlArticleTable);
	
			U.gbi('article'+id).innerHTML+='';
			parentElement = articleDiv.parent().parent().parent().parent().parent();
			if(parentElement.next().find("div.article").length > 0)
			{
					$('#article'+id).css("border-right", "none");
					parentElement.next().find("div.article").css("border-left", "none");
			}
			if(parentElement.prev().find("div.article").length > 0)
			{
					$('#article'+id).css("border-left", "none");
					parentElement.prev().find("div.article").css("border-right", "none");
			}			
		}
		$('#article'+id).ready(function(){
			portfolio.showArticle(id);
			
		});
	},

	redrawBlocks: function(){
		if (portfolio.firstLoading)
			$('#contentBlock').hide();
		$('#contentBlock').ready(function() {
				portfolio.redraw={
				menuHeight: U.gbi('header').offsetHeight,
				contentHeight: 470,
				lineHeight:390,
				logoHeight:52,
				contentBlockHeight: 490,
				num: 0
			};
			//set body height
			if( !portfolio.tryPlaceCbMiddle() ){
				if( !portfolio.tryPlaceCbDown() ){
					portfolio.placeMinimalCb()
				}
			}
			
			$('#contentBlock').fadeIn("fast",function () {
					//hide or show logo
					if(this.offsetHeight>585){
						$('#pushkarev').fadeIn('slow');
						}else{
							$('#pushkarev').hide();
						}
			});
			
			if (hiddenoOverflow==0)
			{
				portfolio.setMouseScrollZonesCoords();
			}		
			
			portfolio.redraw=null;
		});
	},
	
	tryPlaceCbMiddle: function(){
		var htmlHeight=(U.htmlTag().clientHeight || (U.htmlTag().offsetHeight-4))
		if(
			 htmlHeight > (portfolio.redraw.menuHeight*2 + portfolio.redraw.contentBlockHeight)
		){
			//place content block with proportion 40% from the top
			var top=parseInt((htmlHeight - portfolio.redraw.menuHeight - portfolio.redraw.contentHeight)*0.4+portfolio.redraw.menuHeight);
			var height=(htmlHeight - top)
			if (portfolio.firstLoading == false)
				$('#contentBlock').animate( {height: height+ "px", top: top+"px"}, 1000,function(){ portfolio.setMouseScrollZonesCoords()} );
			else
			{
				$('#contentBlock').css({height: height+'px',top: top+'px'});
			}
			var lineBottom = top + (portfolio.redraw.contentHeight-portfolio.redraw.lineHeight)/2+portfolio.redraw.lineHeight;
			var logoTop = parseInt((htmlHeight - lineBottom-portfolio.redraw.logoHeight)/2)+lineBottom-8;
			$('#pushkarev').css({top:logoTop});
			return true;
		}else{
			return false;
		}
	},

	tryPlaceCbDown: function(){//пытаемся разместить contentBLock под menuBlock, чтобы не было прокрутки
		var htmlHeight=(U.htmlTag().clientHeight || (U.htmlTag().offsetHeight-4))
		if(
			 htmlHeight > portfolio.redraw.menuHeight + portfolio.redraw.contentBlockHeight
			 || portfolio.redraw.num>40
		){
			//place Content Block just right after Menu Block
			var top=portfolio.redraw.menuHeight;
			var bodyHeight=(U.bodyTag().offsetHeight>htmlHeight)
				?U.bodyTag().offsetHeight
				:htmlHeight;
			var height=(bodyHeight - portfolio.redraw.menuHeight);

			$('#contentBlock').css({height: height+'px',top: top+'px'});
			
			var lineBottom = top + (portfolio.redraw.contentHeight-portfolio.redraw.lineHeight)/2+portfolio.redraw.lineHeight;
			var logoTop = parseInt((htmlHeight - lineBottom-portfolio.redraw.logoHeight)/2)+lineBottom-8;
			$('#pushkarev').css({top:logoTop});

			return true;
		}else{
			portfolio.redraw.num++;
			return false;
		}
	},

	placeMinimalCb: function(){
		$('#pushkarev').hide();
		var top=portfolio.redraw.menuHeight;
		var height=portfolio.redraw.contentBlockHeight;
		$('#contentBlock').css({height: height+5+'px',top: top+'px'});
		if(window.opera){U.bodyTag().style.height=top+height+'px';}
	},


	setArticleData: function(article){
		if(article){
			var id=article.id;
			if (portfolio.data.articles[id] !== undefined)
				portfolio.data.articles[id].pages=article.pages;
		}
	},

	localRedirect: function(hash){
			
		if(portfolio.historySupport()){
			jQuery.historyLoad(hash);			
		}else{
			location.replace('#'+hash);
			portfolio.pageload(hash);
		}
	},

	setMouseScrollZonesCoords: function(){
		//define #contentBlock position
		//top position of portfolio bar
		var barTop=U.layerY('portfolioBar');
		//height of bar
		var barHeight=422;
		//width of content block
		var contentBlockWidth=U.gbi('contentBlock').offsetWidth;
		//top MouseScroll зон
		var coordsTop= barTop + (barHeight/2) - (portfolio.mouseScroller.zones.h/2);
		portfolio.mouseScroller.coords={
			left: [0, coordsTop],
			right: [(contentBlockWidth - portfolio.mouseScroller.zones.w), coordsTop]
		}
		$('#arrowLeft').css({left: portfolio.mouseScroller.coords.left[0]+ 'px',top:portfolio.mouseScroller.coords.left[1]+ 'px'});
		$('#arrowRight').css({left: portfolio.mouseScroller.coords.right[0] + 'px',top:portfolio.mouseScroller.coords.right[1]+ 'px'});
	},

	checkMouseInZone: function(cx,cy,msZonesCoords){
		if(true
			&& msZonesCoords
			&& cy <= (msZonesCoords.left[1] + portfolio.mouseScroller.zones.h)
			&& msZonesCoords.left[1] <= cy
			&& cx <= (msZonesCoords.left[0] + portfolio.mouseScroller.zones.w)
			&& msZonesCoords.left[0] <= cx
		){
			var a= (portfolio.mouseScroller.zones.w + msZonesCoords.left[0] - cx) / portfolio.mouseScroller.zones.w;
			a=a*a*-1;
			return a;
		}
		if(true
			&& msZonesCoords
			&& msZonesCoords.right[1] <= cy
			&& cy <= (msZonesCoords.right[1] + portfolio.mouseScroller.zones.h)
			&& msZonesCoords.right[0] <= cx
			&& cx <= (msZonesCoords.right[0] + portfolio.mouseScroller.zones.w)
		){
			var a= (cx - msZonesCoords.right[0]) / portfolio.mouseScroller.zones.w;
			a=a*a;
			return a;
		}
		return 0;
	}
}
