var 
	COOKIE_VALUES_SEPARATOR=',',
	COOKIE_PARTS_SEPARATOR='|',
	COOKIE_PARTS_NAME_SEPARATOR=':',
	APPLY_SAVING_DEFAULT=false;

var _viewer=null; //Common PicViewer
$(document).ready(
	function(){
		
		/* Projects tag groups */
		window['projectsGroups']=[];
		$('div.prtag').each(
			function(){
				var pg=new ProjectsGroup(this);
				window['projectsGroups'].push(pg);
				}
			);
	
		
		}
	);

function ProjectsGroup(container){
	this.container=$(container);
	if (!this.container.length){
		return false;
		}
	this.containerListWrap=$('.prtag-list',this.container);
	this.containerList=$('ul',this.container);
	this.removed=[];
	this.initialize();
	}
ProjectsGroup.prototype={
	initialize:function(){
		var $this=this;		
		this.tagId=this.container[0].id.split('_').pop();
		this.isSelectedTag=this.container.hasClass('prtag-selected');
		this.tag=PROJECTS[this.tagId]['tag'];
		this.projects=setArray(PROJECTS[this.tagId]['projects']);
		//alert(this.tag.caption+' => '+is_array(this.projects));

		this.viewSwitcher=$('.foot a.view',this.container);
		this.resetSwitcher=$('.foot a.reset',this.container);
		this.APPLY_SAVING=APPLY_SAVING_DEFAULT;
		this.saved=getParsedCookie('tag_'+$.md5(this.tag.caption));
		this._modifiedByUser=(this.saved && (is_array(this.saved.r) || this.saved.o));
		if (this._modifiedByUser){
			this.resetSwitcher.show();
			}
		else{
			this.resetSwitcher.hide();
			}
		this.applySaved();
		
		this.VIEWCLASS_FULL='prtag-full';
		this.pix=[];
		this.fictives=[];
		
		
		
		this.foreachProjectsContainers(
			function(){
				if ($(this).hasClass('tag-caption')){
					return;
					}
				
				var currOrder=$this.pix.length;
				var projectContainer=this;
				
				if ($(this).hasClass('fictive')){
					var fictive={
						wrap:this,
						_order:currOrder+$this.fictives.length,
						_fictive:true
						};
					$this.fictives.push(fictive);
					projectContainer.pic=fictive
					return;
					}
				
				
				var projectId=searchInClass(this,'project_');				
				var project=$this.getProject(projectId);
				var pic=$this.prepareProjectTitlePic(project,projectContainer,currOrder);
				pic.handleRendered($(projectContainer));
				
				}
			);
		
		this.refreshProjectsVisibility();
		this.refreshProjectsOrder();
		this.putEvents();
		},
		
	prepareProjectTitlePic:function(project,container,currOrder){
		var $this=this;		
		$.extend(
			project,
			{
				_order:currOrder,
				_container:container
				}
			);
		var picSize=2;
		var picData=project.pic;
		var pic=new ProjectPic(
			$.extend(
				{
					project:project,
					size:picSize,
					onselect:function(){
						$this.displayPic(pic);
						},
					onchangeorder:function(newOrder){								
						$this.changeProjectOrder(pic,newOrder)								
						},
					onhandlerclick:function(){
						$this.removeProject(pic);
						}
					},
				picData
				)
			);
		project.titlePic=pic;
		pic.getPixPreviewsGeometry=function(heap){
			if (!heap){
				heap=$this.pix;
				}
			var geometry={};
			$this.foreachProjectsContainers(
				function(){
					var p=this.pic;
					if (p._fictive){
						geometry['fictive_'+p._order]=$where(p.wrap);
						geometry['fictive_'+p._order].pic={
							wrap:$(p.wrap)
							};
						}
					else{
						geometry[p.getData('id')]=$where(p.wrap);
						geometry[p.getData('id')].pic=p;
						}
					}
				);
			return geometry;
			}		
		container.pic=pic;
		$this.pix.push(pic);
		return pic;
		},
	applySaved:function(){
		var $this=this;
		var saved=this.saved;
		if (!saved || saved==null || !is_array(saved.o)){
			return false;
			}
		if (is_array(saved.r)){
			this.removed=saved.r.concat();
			if (this.APPLY_SAVING){
				$.each(
					saved.r,
					function(){
						var removedId=String(this);
						$('li.project_'+removedId,$this.container).remove();
						}
					);
				}
			}
		if (this.APPLY_SAVING){
			$.each(
				saved.o,
				function(order){
					var pid=String(this);
					var target=$('li',$this.container)[order];
					if (target){
						$('li.project_'+pid,$this.container).insertAfter(target);
						}
					}
				);
			this.refreshProjectsVisibility();
			}
		return true;
		},
	getProject:function(id){
		if (is_array(this.projects)){
			for(var i=0;i<this.projects.length;i++){
				if (id==this.projects[i]['id']){
					return this.projects[i];
					}
				}
			}
		},
	removeProject:function(pic){
		if (!pic){
			return false;
			}
		var project=pic.getData('project');
		$(project._container).remove();
		for (var i=0;i<this.pix.length;i++){
			if (this.pix[i].getData && this.pix[i].getData('id')==pic.getData('id')){				
				this.pix.splice(i,1);			
				break;
				}
			}
		this.refreshProjectsVisibility();
		this.refreshProjectsOrder();
		this.removed.push(project.id);		
		this.save();
		this.resetSwitcher.show();
		},
	changeProjectOrder:function(pic,newOrder){
		var $this=this;
		//var pic=this.pix[currOrder];
		var project=pic.getData('project');
		var cnt=$(project._container);
		var cntPrev=cnt.prev()[0];
		var cntNext=cnt.next()[0];		
		var currOrder=project._order;
		var insOrder=newOrder-1;
		var target=$('li',$this.container)[newOrder];
		var toFictive=$(target).hasClass('fictive');
		//alert(newOrder+' to ' +currOrder);
		if (target){			
			if (newOrder>currOrder){
				cnt.insertAfter(target);
				if(toFictive && cntPrev){					
					$(target).insertAfter(cntPrev);
					}
				}
			else{	
				cnt.insertBefore(target);
				if(toFictive && cntNext){
					//alert(cntNext);
					$(target).insertBefore(cntNext);
					}
				}
			}
		this.pix.splice(currOrder,1)
		this.pix.splice(insOrder,null,pic);
		this.refreshProjectsOrder();
		this.refreshProjectsVisibility();
		this.save();
		this.resetSwitcher.show();
		},
	refreshProjectsVisibility:function(){
		var items=$('li',this.containerList);
		if (items.length%6){
			var diff=6-items.length%6;
			for (var i=0;i<diff;i++){
				var li=$('<li class="fictive"><span></span></li>').appendTo(this.containerList);	
				li[0].pic={
					_fictive:true,
					wrap:li
					}
				}
			}
		var tailFictives=$('li.real:last',this.containerList).nextAll();
		if (tailFictives.length==6){
			tailFictives.remove();
			}
		items=$('li',this.containerList);
		items.slice(1,PROJECTS_INGROUP_VISIBLE_DEFAULT+1).removeClass('hidden');
		if (!this.isSelectedTag && (items.length-1)>PROJECTS_INGROUP_VISIBLE_DEFAULT){
			items.slice(PROJECTS_INGROUP_VISIBLE_DEFAULT+1).addClass('hidden');
			this.viewSwitcher.show();
			}
		else{
			this.viewSwitcher.hide();
			}
		this.actualizeView();
		},
	refreshProjectsOrder:function(){
		this.foreachProjectsContainers(
			function(ord){
				var pic=this.pic;
				if (this.pic){
					if (!this.pic._fictive){
						var project=pic.getData('project');
						project._order=ord;
						pic.setData('project',project);
						}
					else{
						this.pic._order=ord;
						}
					}
				}
			);
		/* $.each(
			this.pix,
			function(ord){
				var pic=this;
				var project=pic.getData('project');
				project._order=ord;
				pic.setData('project',project);
				}
			); */
		},
	save:function(){
		var res={};
		var projects=[];
		/* this.foreachPix(
			function(pic,order){
				projects.push(pic.getData('project').id);
				}
			); */
		this.foreachProjectsContainers(
			function(){
				var p=this.pic;
				if (p._fictive){
					projects.push(0);
					}
				else{
					projects.push(p.getData('project').id);
					}
				}
			);
		for (var i=projects.length-1;i>=0;i--){
			if (projects[i]==0){
				projects.splice(i,1);
				}
			else{
				break;
				}
			}
		res={
			o:projects,
			r:this.removed
			};
		setCookie('tag_'+$.md5(this.tag.caption),res);
		},		
	testPix:function(){
		var o='';
		for (var i=0;i<this.pix.length;i++){
			var pic=this.pix[i];
			o+=pic.getData('project').id+"\n";
			}
		alert(o);
		},
	foreachPix:function(action){
		if (is_array(this.pix) && is_function(action)){
			for (var i=0;i<this.pix.length;i++){
				var pic=this.pix[i];
				action(pic,i+1);
				}		
			}
		},
	foreachProjectsContainers:function(action){
		$('li:not(.tag-caption)',this.container).each(action);
		},
	putEvents:function(){
		var $this=this;
		this.viewSwitcher
			.click(
				function(){
					$this.toggleView();
					}
				);
		this.resetSwitcher
			.click(
				function(){
					$this.reset();
					}
				);
		},
	displayPic:function(pic){
		var $this=this;
		this.refreshViewer();
		this._currentPic=pic;		
		var currentPicId=pic.getData('id');
		var project=this._currentProject=pic.getData('project');
		_viewer.setData(
			{
				type:'fullview',
				title:this.tag.caption,
				onBuild:function(im){
					im.msgContainer.html(
						fetchTemplate(
							'iMsg_fullPicView',
							{
								header:project.caption,
								subheader:pic.getData('dsc'),
								url:(project.url||''),
								dsc:project.dsc||'',
								projectViewUrl:PATH_PROJECT_SINGLEVIEW+project.id+'/',
								picViewUrl:PATH_PIC_SINGLEVIEW+pic.getData('id')+'/'
								}
							)
						);
					/* Pix feed */
					var renderPixFeed=function(pix){
						var cnt=$('#pix-feed-list');
						if (!cnt.length){
							cnt=$('<ul id="pix-feed-list"></ul>').appendTo("#pix-feed-core");					
							}							
						var feedPix=[];
						var 
							itemNum=0,
							activeItemNum=0;
						$.each(
							pix,
							function(){
								var p=this;
								var id=Number(p.getData('id'));
								var feedPic=new ProjectPic(
									concatObjects(
										{
											onselect:function(){
												$this.displayPic(p);
												}
											},
										p.getData()
										)
									);
								feedPic.container=$('<li'+(id==currentPicId?' class="active"':'')+'></li>').appendTo(cnt);
								if (id==currentPicId){
									activeItemNum=itemNum;
									}
								feedPix.push(feedPic);
								feedPic.render(1);
								itemNum++;
								}
							);
						cnt[0].rolling=new iRollingVertical(
							$('#pix-feed')[0],
							{
								oncancel:function(irv){
									if (BROWSER.isIE6){
										$(irv.coreWrapper).height($(irv.core).height()).css('marginTop',-40).css('marginBottom',-40);
										im.actualize();
										}
									}
								}
							);
						cnt[0].rolling.setPositionToItem(activeItemNum);
						}
					if (project.pix){
						renderPixFeed(project.pix)
						}
					else{
						$this.getProjectPix(
							project.id,
							function(pix){
								var pp=[];
								$.each(
									pix,
									function(){
										var p=this;
										p.project=project;
										var pic=new ProjectPic(p);
										pp.push(pic);
										}
									);
								project.pix=pp;
								renderPixFeed(project.pix);
								}
							);
						}
						
					/* Pic view */
					var picView=im.msgContainer.picView=new ProjectPic(
						concatObjects(							
							{
								onselect:function(){
									if ($this.getNeighbourProjectPic($this._currentPic.getData('id'))){
										$this.displayNextProjectPic()
										}
									else{
										$this.displayNextProject();
										}
									}								
								
								},
							pic.getData()
							)
						);
					picView.container=$('#picview',im.msgContainer);	
					picView.render(3);
					var actualPicWidth=pic.getData('size_3_width')||ProjectPic.PIX_SIZES[3].width;
					im.container.width(Number(actualPicWidth)+180);

					if ($this.getNeighbourProjectPic($this._currentPic.getData('id')) || !$this._currentProject.pix){
						picView.container.css('cursor','pointer');
						picView.container.attr('title','Перейти к следующему изображению проекта');
						}
					else if ($this.getNeighbourProject(1)){
						picView.container.css('cursor','pointer');
						picView.container.attr('title','Перейти к следующему проекту');
						}
					else{
						picView.container.css('cursor','default');
						picView.container.attr('title','');
						}
					
					/* Neighbour arrows */
					if (!$this.getNeighbourProject(1)){
						_viewer.nextArrow.hide();
						}
					else{
						_viewer.nextArrow.show();
						}
					if (!$this.getNeighbourProject(-1)){
						_viewer.prevArrow.hide();
						}
					else{
						_viewer.prevArrow.show();
						}
					
					/* Cloud */
					var cloudCnt=$('#project-cloud').empty();
					var cloudList=$('<ul class="cloud"></ul>').appendTo(cloudCnt);
					if (is_array(project.tags)){
						$.each(
							project.tags,
							function(num){
								var tagData=getTag(this.id);
								var li=$('<li class="w'+(tagData.category||1)+'"><a href="/tag/'+encodeURI(this.caption)+'/">'+this.caption+'</a></li>').appendTo(cloudList);
								}
							);
						}					
					}
				}
			);
		
		_viewer.render();
		_viewer.show();
		},
	displayPrevProjectPic:function(){
		var pic=this.getNeighbourProjectPic(this._currentPic.getData('id'),-1);		
		if (pic){
			this.displayPic(pic);
			}
		},
	displayNextProjectPic:function(){
		var pic=this.getNeighbourProjectPic(this._currentPic.getData('id'),1);
		if (pic){
			this.displayPic(pic);
			}
		},
	getNeighbourProjectPic:function(id,offset){
		if (isNaN(offset)){
			offset=1;
			}
		if (!is_array(this._currentProject.pix)){
			return false;
			}
		for (var i=0;i<this._currentProject.pix.length;i++){
			var p=this._currentProject.pix[i];			
			if (p.getData('id')==id){				
				if (this._currentProject.pix[i+offset]){
					return this._currentProject.pix[i+offset];
					}
				else{
					return null;
					}
				}
			}
		},
		
	displayNextProject:function(){
		var pr=this.getNeighbourProject(1);
		if (pr){
			this.displayPic(pr);
			}
		},
	displayPrevProject:function(){
		var pr=this.getNeighbourProject(-1);
		if (pr){
			this.displayPic(pr);
			}
		},
	getNeighbourProject:function(offset){
		if (isNaN(offset)){
			offset=1;
			}
		//var num=Number(this._currentProject._order);
		var currLi=this._currentProject.titlePic.container;
		for (var i=0;i<Math.abs(offset);i++){
			if (offset>0){
				currLi=currLi.nextAll('.real:first');
				}
			else{
				currLi=currLi.prevAll('.real:first');
				}
			if (!currLi[0]){
				return null;
				}
			//alert(i+' ('+offset+') => '+currLi[0].className);
			}
		return currLi[0].pic||null;

		/* if (!is_array(this.pix) || isNaN(num)){			
			return false;
			}
		if (this.pix[num+offset]){
			return this.pix[num+offset];
			}
		else{
			return null;
			} */
		},
	getProjectPix:function(id,onload){
		$A(
			'getProjectPix',
			{
				project_id:id		   	
				},
			function(res){
				if (is_function(onload)){
					onload(res);
					}
				}
			);
		},
	refreshViewer:function(){
		var $this=this;
		var vData={
			buttons:[],
			onNextClick:function(){
				$this.displayNextProject();
				},
			onPrevClick:function(){
				$this.displayPrevProject();
				}

			};
		if (!_viewer){
			_viewer=new picViewer(vData);
			}
		else{
			$.extend(
				_viewer.data,
				vData
				);
			}
		return _viewer;
		},
	actualizeView:function(){
		if (!this.isSelectedTag){
			this.containerListWrap.css('overflow','hidden');
			}
		this.containerListWrap.animate(
			{
				height:this.containerList.height()
				}
			);
		},
	toggleView:function(){
		if (this.container.hasClass(this.VIEWCLASS_FULL)){
			this.view_default();
			}
		else{
			this.view_all();			
			}
		this.actualizeView();
		},
	view_all:function(){
		this.container.addClass(this.VIEWCLASS_FULL);		
		/* this.foreachPix(
			function(pic){							
				if (!pic.isDisplaying()){
					//pic.container.fadeIn('fast');
					pic.container.show();
					}
				}
			); */
		},
		
	view_default:function(){
		this.container.removeClass(this.VIEWCLASS_FULL);
		/* this.foreachPix(
			function(pic,num){
				if (num>PROJECTS_INGROUP_VISIBLE_DEFAULT){
					//pic.container.fadeOut('fast');
					pic.container.hide();
					}
				}
			); */
		},
		
	reset:function(){
		var $this=this;
		$('li:not(.tag-caption)',this.containerList).remove();
		this.pix=[];

		$.each(
			this.projects,
			function(ord){
				var project=this;
				var li=$('<li class="real project_'+project.id+'"></li>').appendTo($this.containerList);
				if (ord>PROJECTS_INGROUP_VISIBLE_DEFAULT){
					li.addClass('hidden');
					}
				var pic=$this.prepareProjectTitlePic(project,li[0],ord);
				pic.container=li;
				pic.render(2);
				}
			);
		this.refreshProjectsVisibility();
		this.refreshProjectsOrder();
		this.resetSwitcher.hide();
		//this.putEvents();
		clearCookie('tag_'+$.md5(this.tag.caption));
		//SitePage.refresh();
		}	
	}

function getTag(id){
	if (ALL_TAGS){
		for(var i=0;i<ALL_TAGS.length;i++){
			if (ALL_TAGS[i]['id']==id){
				return ALL_TAGS[i];
				}
			}
		}
	return null;
	}
	
function getTagCategory(){
	
	}
	
function setCookie(field,value,data){
	var str='';
	if (is_object(value)){
		var res=[];
		$.each(
			value,
			function(name){
				if (is_array(this)){
					res.push(name+COOKIE_PARTS_NAME_SEPARATOR+this.join(COOKIE_VALUES_SEPARATOR));
					}
				}
			)
		str=res.join(COOKIE_PARTS_SEPARATOR)
		}
	else{
		str=value;
		}
	data=$.extend(
		data,
		{
			expires:365				
			}
		);
	$.cookie(field,str,data);
	}
	
function getParsedCookie(field){
	var val=$.cookie(field);	
	var res={};
	if (!val){
		return null;
		}
	var parts=val.split(COOKIE_PARTS_SEPARATOR);
	if (is_array(parts)){
		$.each(
			parts,
			function(){
				var pp=String(this).split(COOKIE_PARTS_NAME_SEPARATOR);
				if (pp[1]){
					res[pp[0]]=pp[1].split(COOKIE_VALUES_SEPARATOR);
					}
				}
			);
		}
	return res;
	}

function clearCookie(field){
	$.cookie(field,null);	
	}
	
