var Pages = Class.create({
	
	/**
	 * 
	 */
	initialize: function(inNode, mode) {
	
		this.currentPageTree = null;
		this.currentTemplateList = null;
		this.currentForm = null;
		this.mode = 0;
		this.tree = null;
		this.editor = null;
		this.editorConfig = null;
		this.editorContent = null;
		
		//reset events
		this.onPagesLoaded = null;
		this.onPageOpen = null;
		
		if(mode != null) this.mode = mode;
		else this.mode = 0;
		
		if(this.mode == 0){
			var btadd = Noa.nodes.button('addpage', Noa.getLabel("pagesBtAdd"), { 'click': this.edit.bindAsEventListener(this) });
			
			inNode.appendChild(Builder.node('p', { 'class':'submenu' }, [btadd]));
		}
		
		this.tree = Builder.node('div', {'class':'bloc list PageList'});
		inNode.appendChild(this.tree);
		
		if(this.mode == 0){
			this.editor = Builder.node('div', {'class':'bloc last'});
			inNode.appendChild(this.editor);
		}
		Noa.ajaxCall('Pages', 'getTemplates', null, function(data){
			
			this.currentTemplateList = data.templateList;
			this.list();
			
		}.bind(this));
	},
	
	/**
	 * 
	 */
	list: function(){
		
		this.tree.update();
		if(this.editor) this.editor.update();
		
		Noa.ajaxCall('Pages', 'getPageTree', null, function(data){
			
			function recuPages(pages){
				var ul = Builder.node('ul');
				pages.each(function(page){
					var a = Builder.node('a', { href:'javascript:void(0);'}, [page.mtitle]);
					if(this.mode == 0) a.addClassName('move');
					a.observe('click', this.edit.bindAsEventListener(this, page.id));
					page._link = a;
					
					var bt = new Element('div', {'class': 'move'} );
					
					var li = Builder.node('li');
					if(this.mode == 0) li.appendChild(bt);
					li.appendChild(a);
					li._page = page;
					
					if(page.childs) li.appendChild(recuPages.bind(this)(page.childs));
					
					ul.appendChild(li);
					
				}.bind(this));
				
				if(this.mode == 0){
					ul.identify();
					Sortable.create(ul, {handle: ul.up().down('div'), onChange: this.addSaveTreeButton.bind(this) });
				}
				return ul;
			}
			var list = recuPages.bind(this)(data.pagesTree);
			//Sortable.create(list, {onChange: this.addSaveTreeButton.bind(this), tree:true });
			this.tree.update(list);
			
			this.currentPageTree = data.pagesTree;
			
			if(this.onPagesLoaded) this.onPagesLoaded();
		}.bind(this));
	},
	/**
	 * 
	 */
	edit: function(event, id, fullPath){
		
		var makeForm = function(page){
			
			
			var config = $(Builder.node('div', {'class':'configCol'}));
			this.editorConfig = config;
			config.appendChild(Noa.nodes.input('text', 'title', 'title', null, page ? page.title : null, null, Noa.getLabel("pagesFormTitle")));
			config.appendChild(Noa.nodes.input('text', 'mtitle', 'mtitle', null, page ? page.mtitle : null, null, Noa.getLabel("pagesFormMTitle")));
			config.appendChild(Noa.nodes.input('text', 'path', 'path', null, page ? page.path : null, null, Noa.getLabel("pagesFormPath")));
			//config.appendChild(Noa.nodes.input('checkbox', 'online', 'online', null, page ? page.online : null, null, Noa.getLabel("pagesFormOnline")));

			var elms = this.makePageTree(this.currentPageTree, page, null);
			config.appendChild(Noa.nodes.select('pid', 'pid', null, elms, null, Noa.getLabel("pagesFormParent")));
			
			elms = this.makePageTree(this.currentPageTree, page, page ? page.shortcut : "0");
			config.appendChild(Noa.nodes.select('shortcut', 'shortcut', null, elms, null, Noa.getLabel("pagesFormShortcut")));
			
			elms = [];
			this.currentTemplateList.each(function(template){
				var elm = { label:template.label, value:template.name };
				if(page && page.template == template.name) elm.selected = true;
				elms.push(elm);
			});
			config.appendChild(Noa.nodes.select('template', 'template', null, elms, { change:this.content.bindAsEventListener(this, page) }, Noa.getLabel("pagesFormTemplate")));

			config.appendChild(Noa.nodes.separator());

			var bt = new Element('p');
			bt.appendChild(Noa.nodes.button('save', Noa.getLabel("pagesBtSave"), { click: this.save.bindAsEventListener(this, page) }));
			if(page) bt.appendChild(Noa.nodes.button('delete', Noa.getLabel("pagesBtDel"), { click: this.del.bindAsEventListener(this, page) }));
			config.appendChild(bt);
			
			
			
			
			var content = $(Builder.node('div', {'class':'contentCol'}));
			this.editorContent = content;
			var form = $(Builder.node('form', null, [config, content]));
			this.currentForm = form;
			
			this.editor.update(form);
			
			this.content(null, page);
		};

		if(this.editor) this.editor.update();
		
		var decs = this.tree.descendants();
		decs.each(function(elm){
			if(elm.match('a')) elm.removeClassName('on');
		});
		
		if(id || fullPath){
			var a = null;
			if(event) a = event.element();
			else if(id) a = this.getLinkWithId(id);
			else a = this.getLinkWithId(this.getIdWithFullPath(fullPath));
			if(a){
				a.blur();
				a.addClassName('on');
			}
			Noa.ajaxCall('Pages', 'getPage', {id:id}, function(data){
				if(this.onPageOpen) this.onPageOpen(data.page);
				if(this.mode == 0) makeForm.bind(this)(data.page);
			}.bind(this));
		}
		else{
			makeForm.bind(this)(null);
		}
	},
	/**
	 * 
	 */
	content: function(event, page){
		
		this.editorContent.update();
		var name = this.currentForm['template'].value;
		if(event) name = event.element().value;
		
		this.currentTemplateList.each(function(temp){
			if(temp.name == name) template = temp;
		});
			
		this.editorContent.appendChild(Noa.nodes.collapaseButton(this.editorContent));
		
		
		template.contents.each(function(content){
			Noa.nodes.makeNodesFromContent(content, 'content', page ? page.content : null, this.editorContent);
			
			/*switch(content.type){
				case 'div':
				case 'smalldiv':
				case 'largediv':
				case 'mindiv':
					var ta = Noa.nodes.textarea('content['+content.name+']', 'content['+content.name+']',null, page ? page.content[content.name] : null, null, Noa.getLabel("pagesFormContent")+content.label);
					ta._node.writeAttribute({'allowed': content.allowed});
					ta._node.writeAttribute({'styles': content.styles});
					this.editorContent.appendChild(ta);
					
					if(content.type == 'smalldiv') ta._node.addClassName('small');
					if(content.type == 'largediv') ta._node.addClassName('large');
					if (content.type == 'mindiv') {
						ta._node.writeAttribute({
							'allowed': 'b;i',
							'options': 'min'
						});
						ta._node.addClassName('ssmall');
					}
				break;
				
				case 'h2':
				case 'h3':
				case 'txt':
					this.editorContent.appendChild(Noa.nodes.input('text', 'content['+content.name+']', null, null, page ? page.content[content.name] : null, null, Noa.getLabel("pagesFormContent")+content.label));
				break;
				
				case 'img':
					thumb = (content.thumbs && content.thumbs == "true");
					var img = Noa.nodes.imgselect('content['+content.name+']', null, page ? page.content[content.name] : null, null, Noa.getLabel("pagesFormContent")+content.label, thumb);
					this.editorContent.appendChild(img);
				break;
				
				case 'imglist':
					thumb = (content.thumbs && content.thumbs == "true");
					var img = Noa.nodes.imglist('content['+content.name+']', null, page ? page.content[content.name] : null, null, Noa.getLabel("pagesFormContent")+content.label, thumb);
					this.editorContent.appendChild(img);
				break;
				

				case 'file':
					var file = Noa.nodes.fileselect('content['+content.name+']', null, page ? page.content[content.name] : null, null, Noa.getLabel("pagesFormContent")+content.label);
					this.editorContent.appendChild(file);
				break;

				
				case 'list':
					this.editorContent.appendChild(Noa.nodes.list('content['+content.name+']', null, content.elements, page ? page.content[content.name] : null, null, Noa.getLabel("pagesFormContent")+content.label, content.title));
				break;
			}*/
		}.bind(this));
		
		Noa.mce.init();
	},
	/**
	 * 
	 */
	save: function(event, page){
		
		tinyMCE.triggerSave();
		
		
		
		var params = this.currentForm.serialize(true);
		if(page) params.id = page.id;
		
		Noa.ajaxCall('Pages', 'save', params, function(data){
			if(data.result){
				this.list();
				this.onPagesLoaded = function(){
					this.onPagesLoaded = null;
					this.edit(null, data.result.newPage);
				};
			}
			else{// gestion des erreurs
			}
		}.bind(this) );
	},
	/**
	 * 
	 */
	del: function(event, page){
		
		Noa.message(Noa.getLabel("pagesMessageDel", page.mtitle), function(){
			Noa.ajaxCall('Pages', 'delete', { id:page.id }, function(data){
				if(data.result){
					this.list();
				}
				else{// gestion des erreurs
				}
			}.bind(this) );
		}.bind(this) );
	},
	/**
	 * 
	 */
	savePageTree: function(event){
		
		var params = [];
		
		var ul = this.tree.down('ul');
		
		function recuPages(lis){
			var mi = lis.length;
			for(var i=0; i<mi; i++){
				var li = lis[i];
				
				params.push({id: li._page.id, order: i});
				
				if(li.down('ul')) recuPages(li.down('ul').childElements());
			}
		}
		recuPages(ul.childElements());
		

		Noa.ajaxCall('Pages', 'savePageTree', { tree: params.toJSON() }, function(data){
			if(data.result){
				this.list();
			}
			else{// gestion des erreurs
			}
		}.bind(this) );
	},
	
	/********************************************************************************************************/
	/********************************************************************************************************/
	addSaveTreeButton: function(){
		if(!$('saveTreeBt'))
			this.tree.appendChild(Noa.nodes.input('button', 'saveTreeBt', 'saveTreeBt', 'button', Noa.getLabel("pagesBtSaveTree"), {click: this.savePageTree.bind(this) }, null));
	},
	
	makePageTree: function(pageTree, page, id){
		var elms = [{label:id != null ? "-" : "/", value:"0"}];
		var depth = 0;
		function recuPages(pages, disabled){
			var childDisabled = false;
			if(pages) pages.each(function(p){
				var elm = {label:''};
				for(var i=0; i<depth; i++) elm.label += ' | ';
				elm.label += p.mtitle;
				elm.value = p.id;
				
				if(id != null){
					if(id == p.id) elm.selected = true;
					if(page && page.id == p.id) elm.disabled = true;
				}
				else{
					if(page && page.pid == p.id) elm.selected = true;
					if(page && (page.id == p.id || disabled)){
						elm.disabled = true;
						childDisabled = true;
					}
				}

				elms.push(elm);
				if(p.childs){
					depth ++;
					recuPages(p.childs, childDisabled);
					childDisabled = false;
					depth --;
				}
			});
		}
		recuPages(pageTree);
		
		return elms;
	},
	
	getLinkWithId: function(id){
		var ret = null;
		if(this.currentPageTree){
			function recuPages(pages){
				pages.each(function(page){
					if(page.id == id && page._link) ret = page._link;
					if(page.childs) recuPages(page.childs);
				});
			}
			recuPages(this.currentPageTree);
		}
		return ret;
	},
	
	getIdWithFullPath: function(fullPath){
		var ret = null;
		if(this.currentPageTree){
			function recuPages(pages){
				pages.each(function(page){
					if(page.fullpath == fullPath) ret = page.id;
					if(page.childs) recuPages(page.childs);
				});
			}
			recuPages(this.currentPageTree);
		}
		return ret;
	}
	
});


Pages.NORMAL_MODE = 0;
Pages.POPIN_MODE = 1;








Pages.lang = {uk_en:{
	pagesTitle:			"Pages",
	
	pagesBtAdd:			"Add page",
	pagesFormTitle:		"Title",
	pagesFormMTitle:	"Menu title",
	pagesFormPath:		"Path",
	pagesFormOnline:	"Online ?",
	pagesFormParent:	"Parent page",
	pagesFormShortcut:	"Shortcut to",
	pagesFormTemplate:	"Template",
	pagesBtSave:		"Save",
	pagesBtDel:			"Delete",
	pagesMessageDel:	"Delete the page \"{$}\" ?",
	pagesBtSaveTree:	"Save tree"
}};
Object.extend(Noa.langData.uk_en, Pages.lang.uk_en);


Pages.lang = {fr_fr:{
	pagesTitle:			"Pages",
	
	pagesBtAdd:			"Ajouter une page",
	pagesFormTitle:		"Titre",
	pagesFormMTitle:	"Titre de menu",
	pagesFormPath:		"Chemin",
	pagesFormShortcut:	"Raccourcis",
	pagesFormOnline:	"En ligne ?",
	pagesFormParent:	"Page parent",
	pagesFormTemplate:	"Gabarit",
	pagesBtSave:		"Enregistrer",
	pagesBtDel:			"Supprimer",
	pagesMessageDel:	"Vraiment supprimer la page \"{$}\" ?",
	pagesBtSaveTree:	"Enregistrer"
}};
Object.extend(Noa.langData.fr_fr, Pages.lang.fr_fr);