function html_entity_decode(str) {
	var ta=document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;
}

YUI().add("addElement",function(Y){
	var addAnime = function(){
		addAnime.superclass.constructor.apply(this,arguments);
	}
	addAnime.NAME = "addElement";
	addAnime.ATTRS = {
		list: {
			value: undefined
		},
		panel: {
			value: undefined
		},
		strings: {
			value: {
				winTitle: "Ajouter un élément",
				searchField: "Rechercher un élément",
				clicktoadd: "Sélectionnez dans cette liste l'élément qui convient",
				notinthelist: "Pas dans la liste ? Ajoutez le !",
				close: "Fermer"
			}
		}
	};

	Y.extend(addAnime,Y.Widget,{
		initializer: function(){
		},
		destructor: function(){
			this.get("boundingBox").remove();
		},
		renderUI: function(){
			this.search = Y.Node.create("<input type='text' name='search' />");
			this.result = Y.Node.create("<ul class='yui-addelement-list'></ul>");
			this.close = Y.Node.create("<a class='close'>"+this.get("strings.close")+"</a>");

			var c = this.get("contentBox"),
				node = Y.Node.create("<fieldset><legend class='"+this.getClassName("searchlabel")+"'>"+this.get("strings.searchField")+"</legend></fieldset>");
			c.append("<h2>"+this.get("strings.winTitle")+"</h2>");
			node.append(this.search);
			c.append(node);
			node = Y.Node.create("<fieldset><legend class="+this.getClassName("resultlabel")+">"+this.get("strings.clicktoadd")+"</legend></fieldset>");
			c.append(node);
			node.append(this.result);
			c.append("<a rel='lightbox' class='lightbox-iframe' href='/addanime/'>"+this.get('strings.notinthelist')+"</a>");
			c.append(this.close);
			this.show();
			this.set("centered",true);
		},
		bindUI: function(){
			this.search.on("keyup",Y.bind(this._search,this));
			this.close.on("click",Y.bind(this._close,this));
		},
		syncUI: function(){

		},
		_close: function(){
			this.hide();
			this.destroy();
		},
		_search: function(){
			this.io = Y.io("/listjson/"+this.get('list').get("user")+"/search/"+encodeURIComponent(this.search.get("value")),{
				on: {
					success: Y.bind(this._searchresult,this)
				}
			});
		},
		_searchresult: function(id,o,args){
			if(this.io.id != id){
				return;
			}
			try{
				var d = Y.JSON.parse(o.responseText),i,node;
				this.result.set("innerHTML","");
				for(i in d){
					node = Y.Node.create("<li>"+d[i].title+" / "+d[i].type+"</li>");
					node.on("click",Y.bind(this._resultclicked,this,i,d[i],node));
					this.result.append(node);
				}
			}
			catch(e){
				Y.log(e);
			}
		},
		_resultclicked: function(i,d,node){
			Y.io("/listaction/addelement/"+this.get("panel")+"/"+i+"/",{
				on:{
					success:Y.bind(this._newLine,this,d,node)
				}
			});
		},
		_newLine: function(d,node,id,o,args){
			node.remove();
			d.done = 0;
			d.score = 0;
			d.start = "0000-00-00";
			d.end = d.start;
			d.sec = "1470";
			this.get("list").newLine(this.get("panel"),o.responseText,d);
			Y.bind(this.get("list").sort,this,'title',this.get("panel"));
			this.get("list")._panelstatRefresh(this.get("panel"));
			this.get("list").refreshTotalStat();
		}
	});

	addAnime = Y.Base.build(addAnime.NAME, addAnime, [Y.WidgetPosition,Y.WidgetPositionExt, Y.WidgetStack], {
		dynamic:false
	});

	Y.addAnime = addAnime;
},1,{
	requires:["widget","io-base","json","widget-position-ext","widget-stack"]
});

YUI().add("editElement",function(Y){
	var edit = function(){
		edit.superclass.constructor.apply(this,arguments);
	}
	edit.NAME = "editelement";
	edit.ATTRS = {
		list: {
			value: undefined
		},
		data: {
			value: {}
		},
		strings: {
			value: {
				winTitle: "Modifier l'élément",
				modifelement: "Modifer l'élément",
				modifpersonnal: "Modifer mes infos",
				close: "Fermer",
				modifyitem: "Modifier l'élément",
				modifylink: "Modifier l'élément",
				count: "Nombre de partie dans l'élément",
				duration: "Temps moyen d'une partie de l'élément",
				modifymyinfo: "Modifier vos informations",
				done: "Nombre de parties accomplies",
				score: "Note (entre 1 et 10; 0 correspond à l'absence de note)",
				start: "date de commencement(AAAA-MM-JJ)",
				end: "date de fin(AAAA-MM-JJ)",
				wrongcount: "Merci de mettre un nombre pour le nombre de parties",
				notcount: "Merci de mettre un nombre positif (supérieur ou égal à 0) pour le nombre de parties",
				wrongdate: "Les dates doivent être au format AAAA-MM-JJ",
				scorerange: "La note doit être comprise entre 0 et 10. 0 correspond à l'absence de note.",
				donerange:"Le nombre de parties doit être supérieur à 0 et inférieur au nombre de parties total",
				dateorder: "La date de fin doit être après la date de départ",
				deleteline: "Supprimer l'entrée de votre liste",
				deleteconfirmation: "Êtes-vous sûr de vouloir supprimer cette entrée ? Appuyez sur OK pour confirmer.",
				alias: "Nom sur votre liste"
			}
		}
	};

	Y.extend(edit,Y.Widget,{
		initializer: function(){

		},
		destructor: function(){
			this.get("boundingBox").remove();
		},
		renderUI: function(){
			var c = this.get("contentBox"),fieldset = Y.Node.create("<fieldset></fieldset>"),fieldset2 = Y.Node.create("<fieldset></fieldset>");
			c.append("<h2>"+this.get("strings.winTitle")+"</h2>");
			this.elementform = Y.Node.create("<form></form>");
			this.elementform.append(fieldset);

			fieldset.append("<legend>"+this.get("strings.modifyitem")+"</legend>");
			this.id = Y.Node.create("<input type='hidden' name='id' />");
			fieldset.append(this.id);
			fieldset.append(Y.Node.create("<div><a rel='lightbox' class='lightbox-iframe' href='/editelement/"+this.get("data.id")+"/'>"+this.get("strings.modifylink")+"</a></div>"));
			fieldset.append(Y.Node.create("<div>"+this.get("strings.count")+"</div>"));
			this.count = Y.Node.create("<input type='text' name='count' />");
			fieldset.append(this.count);
			fieldset.append(Y.Node.create("<div>"+this.get("strings.duration")+"</div>"));
			this.duration = Y.Node.create("<input type='text' name='duration' />");
			fieldset.append(this.duration);
			this.submitElement = Y.Node.create("<input type='button' value=\""+this.get("strings.modifelement")+"\" />");
			fieldset.append(this.submitElement);
			c.append(this.elementform);

			this.personnalform = Y.Node.create("<form></form>");
			this.personnalform.append(fieldset2);

			fieldset2.append("<legend>"+this.get("strings.modifymyinfo")+"</legend>");
			this.id2 = Y.Node.create("<input type='hidden' name='id' />");
			fieldset2.append(this.id2);
			fieldset2.append(Y.Node.create("<div>"+this.get("strings.alias")+"</div>"));
			this.alias = Y.Node.create("<select name='alias'></select>");
			fieldset2.append(this.alias);
			fieldset2.append(Y.Node.create("<div>"+this.get("strings.done")+"</div>"));
			this.done = Y.Node.create("<input type='text' name='done' />");
			fieldset2.append(this.done);
			fieldset2.append(Y.Node.create("<div>"+this.get("strings.score")+"</div>"));
			this.score = Y.Node.create("<input type='text' name='score' />");
			fieldset2.append(this.score);
			fieldset2.append(Y.Node.create("<div>"+this.get("strings.start")+"</div>"));
			this.startDate = Y.Node.create("<input type='text' name='start' />");
			fieldset2.append(this.startDate);
			fieldset2.append(Y.Node.create("<div>"+this.get("strings.end")+"</div>"));
			this.endDate = Y.Node.create("<input type='text' name='end' />");
			fieldset2.append(this.endDate);
			this.submitPersonnal = Y.Node.create("<input type='button' value='"+this.get("strings.modifpersonnal")+"' />");
			fieldset2.append(this.submitPersonnal);
			c.append(this.personnalform);

			this.deleteline = Y.Node.create("<input type='button' class='"+this.getClassName("deleteline")+"' value=\""+this.get("strings.deleteline")+"\" />");
			fieldset2.append(this.deleteline);

			this.close = Y.Node.create("<a class='close'>"+this.get("strings.close")+"</a>");
			c.append(this.close);
			this.show();
			this.set("centered",true);
		},
		bindUI: function(){
			this.close.on("click",Y.bind(this._close,this));
			this.submitElement.on("click",Y.bind(this._submitElement,this));
			this.submitPersonnal.on("click",Y.bind(this._submitPersonnal,this));
			this.deleteline.on("click",Y.bind(this._deleteline,this));
		},
		syncUI: function(){
			this.id.set("value",this.get("data.id"));
			this.id2.set("value",this.get("data.id"));
			this.count.set("value",this.get("data.count"));
			var d = parseInt(this.get("data.sec")),
				t = Math.floor(d/3600)+":"+Math.floor((d%3600)/60)+":"+Math.floor(d%60);
			this.duration.set("value",t);
			this.done.set("value",this.get("data.done"));
			this.score.set("value",this.get("data.score"));
			this.startDate.set("value",this.get("data.start"));
			this.endDate.set("value",this.get("data.end"));
			this.getAliasList();
		},
		_close: function(){
			this.hide();
			this.destroy();
		},
		_submitElement: function(){
			if(!Y.Lang.isNumber(parseInt(this.count.get("value")))){
				alert(this.get("strings.notcount"));
				return;
			}
			if(parseInt(this.count.get("value")) < 0){
				alert(this.get("strings.wrongcount"));
				return;
			}
			Y.io("/listaction/modifyelement/",{
				method: "POST",
				form: {
					id: this.elementform
				},
				on: {
					success: Y.bind(this._ElementModified,this)
				}
			});
		},
		_submitPersonnal: function(){
			var regex = /^\d\d\d\d-\d\d-\d\d$/,d;
			if(!regex.test(this.startDate.get("value")) || !regex.test(this.endDate.get("value"))){
				alert(this.get("strings.wrongdate"));
				return;
			}
			d = {
				start: this.startDate.get("value"),
				end: this.endDate.get("value")
			};
			d.startyear = parseInt(d.start.slice(0,4),10);
			d.startmonth = parseInt(d.start.slice(5,7),10);
			d.startday = parseInt(d.start.slice(-2),10);
			d.endyear = parseInt(d.end.slice(0,4),10);
			d.endmonth = parseInt(d.end.slice(5,7),10);
			d.endday = parseInt(d.end.slice(-2),10);
			if(d.endyear != "0000" && d.startyear != "0000"){
				if(new Date(d.endyear,d.endmonth-1,d.endday) < new Date(d.startyear,d.startmonth-1,d.startday)){
					alert(this.get("strings.dateorder"));
					return;
				}
			}

			var score = parseInt(this.score.get("value"),10);
			if(score > 10 || score < 0){
				alert(this.get("strings.scorerange"));
				return;
			}

			var done = parseInt(this.done.get("value"),10);
			var max = this.get("list").line[this.get("data.id")].count;
			if(done < 0 || (max != 0 && done > max)){
				alert(this.get("strings.donerange"));
				return;
			}
			Y.io("/listaction/modifypersonnal/",{
				method: "POST",
				form: {
					id: this.personnalform
				},
				on: {
					success: Y.bind(this._PersonnalModified,this)
				}
			});
		},
		_ElementModified: function(){
			var l = this.get("list"),d = l.line[this.get("data.id")];
			d.title = Y.one("#alias"+this.alias.get("value")).get("innerHTML");
			d.count = this.count.get("value");
			l.modifyLine(d.panel,d.id,d);
			l.sort('title',d.panel);
			l._panelstatRefresh(d.panel);
			l.refreshTotalStat();
		},
		_PersonnalModified: function(){
			var l = this.get("list"), d = l.line[this.get("data.id")];
			d.done = this.done.get("value");
			d.score = this.score.get("value");
			d.start = this.startDate.get("value");
			d.end = this.endDate.get("value");
			d.title = Y.one("#alias"+this.alias.get("value")).get("innerHTML");
			l.modifyLine(d.panel,d.id,d);
			l.sort('title',d.panel);
			l._panelstatRefresh(d.panel);
			l.refreshTotalStat();
		},
		_deleteline: function(){
			if(confirm(this.get("strings.deleteconfirmation"))){
				var l = this.get("list");
				Y.io("/listaction/removeline/"+this.get("data.id")+"/");
				l.removeLine(this.get("data.id"));
				l._panelstatRefresh(this.get("data.panel"));
				l.refreshTotalStat();
				this._close();
			}
		},
		getAliasList: function(){
			var l = this.get("list");
			Y.io("/listjson/"+l.get("user")+"/alias/"+this.get("data.id")+"/",{
				on: {
					success: Y.bind(this._gotAliasList,this)
				}
			});
		},
		_gotAliasList: function(id,o,args){
			try{
				var j = Y.JSON.parse(o.responseText),s = 0,i;
				for(i in j){
					if(j[i] == this.get("list").line[this.get("data.id")].title){
						this.alias.append("<option id='alias"+i+"' selected value='"+i+"'>"+j[i]+"</option>");
						s = this.alias.get("selectedIndex");
					}
					else{
						this.alias.append("<option id='alias"+i+"' value='"+i+"'>"+j[i]+"</option>");
					}
				}
				this.alias.set("selectedIndex",s);
			}
			catch(e){
				Y.log(e);
			}
		}
	});

	edit = Y.Base.build(edit.NAME,edit,[Y.WidgetPosition,Y.WidgetPositionExt, Y.WidgetStack], {
		dynamic:false
	});

	Y.editElement = edit;

},1,{
	requires: ["widget","io-base","io-form","json","widget-position-ext","widget-stack"]
});

YUI().add("custom",function(Y){
	var custom = function(){
		custom.superclass.constructor.apply(this,arguments);
	}
	custom.NAME = "custom";
	custom.ATTRS = {
		list: {
			value: undefined
		},
		strings: {
			value: {
				winTitle: "Personalisation",
				close: "Fermer",
				modify: "Mettre à jour",
				css: "Contenu du CSS",
				togglecss:"Montrer/Cacher",
				title: "Template de titre",
				toggletitle:"Montrer/Cacher",
				container: "Template de conteneur de liste",
				togglecontainer:"Montrer/Cacher",
				line: "Template de ligne",
				toggleline:"Montrer/Cacher",
				resetcss: "CSS par défaut",
				stat: "Template des statistiques totales",
				togglestat:"Montrer/Cacher",
				panelstat: "Template des statistiques d'un panel"
			}
		}
	};

	Y.extend(custom,Y.Widget,{
		initializer: function(){

		},
		destructor: function(){
			this.get("boundingBox").remove();
		},
		renderUI: function(){
			var c = this.get("contentBox");

			this.form = Y.Node.create("<form></form>");
			this.css = Y.Node.create("<textarea class='hide' name='css'>"+this.get("list").get("style").get("innerHTML")+"</textarea>");
			this.togglecss = Y.Node.create("<a>"+this.get("strings.togglecss")+"</a>");
			this.resetcss = Y.Node.create("<input type='button' class='yui-custom-defaultcss' value='"+this.get("strings.resetcss")+"' />");
			this.title = Y.Node.create("<textarea class='hide' name='title'>"+this.get("list").get("title_template")+"</textarea>");
			this.toggletitle = Y.Node.create("<a>"+this.get("strings.toggletitle")+"</a>");
			this.line = Y.Node.create("<textarea class='hide' name='line'>"+this.get("list").get("line_template")+"</textarea>");
			this.toggleline = Y.Node.create("<a>"+this.get("strings.toggleline")+"</a>");
			this.container = Y.Node.create("<textarea class='hide' name='container'>"+this.get("list").get("container_template")+"</textarea>");
			this.togglecontainer = Y.Node.create("<a>"+this.get("strings.togglecontainer")+"</a>");
			this.stat = Y.Node.create("<textarea class='hide' name='stat'>"+this.get("list").get("stat_template")+"</textarea>");
			this.togglestat = Y.Node.create("<a>"+this.get("strings.togglestat")+"</a>");
			this.panelstat = Y.Node.create("<textarea class='hide' name='panelstat'>"+this.get("list").get("panelstat_template")+"</textarea>");
			this.togglepanelstat = Y.Node.create("<a>"+this.get("strings.togglestat")+"</a>");
			this.submit = Y.Node.create("<input type='button' value=\""+this.get("strings.modify")+"\" />");

			var node = Y.Node.create("<fieldset><legend>"+this.get("strings.css")+"</legend></fieldset>");
			this.form.append(node);
			node.append(this.togglecss);
			node.append(this.css);
			node.append(this.resetcss);

			node = Y.Node.create("<fieldset><legend>"+this.get("strings.title")+"</legend></fieldset>");
			this.form.append(node);
			node.append(this.toggletitle);
			node.append(this.title);
			
			node = Y.Node.create("<fieldset><legend>"+this.get("strings.container")+"</legend></fieldset>");
			this.form.append(node);
			node.append(this.togglecontainer);
			node.append(this.container);
			
			node = Y.Node.create("<fieldset><legend>"+this.get("strings.line")+"</legend></fieldset>");
			this.form.append(node);
			node.append(this.toggleline);
			node.append(this.line);

			node = Y.Node.create("<fieldset><legend>"+this.get("strings.stat")+"</legend></fieldset>");
			this.form.append(node);
			node.append(this.togglestat);
			node.append(this.stat);
			
			node = Y.Node.create("<fieldset><legend>"+this.get("strings.panelstat")+"</legend></fieldset>");
			this.form.append(node);
			node.append(this.togglepanelstat);
			node.append(this.panelstat);
			
			this.form.append(this.submit);
			c.append(Y.Node.create("<h2>"+this.get("strings.winTitle")+"</h2>"));
			c.append(this.form);

			this.close = Y.Node.create("<a class='close'>"+this.get("strings.close")+"</a>");
			c.append(this.close);
			this.set("centered",true);
		},
		bindUI: function(){
			this.close.on("click",Y.bind(this._close,this));
			this.submit.on("click",Y.bind(this._submit,this));
			this.resetcss.on("click",Y.bind(this._resetcss,this));
			this.togglecss.on("click",Y.bind(this._toggle,this,"css"));
			this.toggletitle.on("click",Y.bind(this._toggle,this,"title"));
			this.togglecontainer.on("click",Y.bind(this._toggle,this,"container"));
			this.toggleline.on("click",Y.bind(this._toggle,this,"line"));
			this.togglestat.on("click",Y.bind(this._toggle,this,"stat"));
			this.togglepanelstat.on("click",Y.bind(this._toggle,this,"panelstat"));
		},
		syncUI: function(){

		},
		_close: function(){
			this.hide();
			this.destroy();
		},
		_submit: function(){
			Y.io("/listaction/savetpl/",{
				method: 'POST',
				form:{
					id: this.form
				}
			});
			this.get("list").changeStyle(this.css.get("value"));
			this.get("list").set("container_template",this.container.get("value"));
			this.get("list").set("line_template",this.line.get("value"));
			this.get("list").set("title_template",this.title.get("value"));
			this.get("list").set("stat_template",this.stat.get("value"));
			this.get("list").set("panelstat_template",this.panelstat.get("value"));
			(Y.bind(this.get("list").refreshPanels,this.get("list")))();
		},
		_resetcss: function(){
			Y.io("/css/list.css",{
				on:{
					success:Y.bind(function(id,o,args){
						this.css.set("innerHTML", o.responseText);
					},this)
				}
			})
		},
		_toggle: function(e){
			this[e].toggleClass("hide");
		}
	});

	custom = Y.Base.build(custom.NAME,custom,[Y.WidgetPosition,Y.WidgetPositionExt, Y.WidgetStack], {
		dynamic:false
	});

	Y.custom = custom;

},1,{
	requires: ["widget","io-base","io-form","json","widget-position-ext","widget-stack"]
});

YUI().add("list",function(Y){
	var list = function(){
		list.superclass.constructor.apply(this, arguments);
	}

	list.NAME = "list";

	list.ATTRS = {
		user: {
			value: ""
		},
		style:{
			value: undefined
		},
		title_template: {
			value: ""+
				"<ul class='connected list-panelcontrol'>"+
				"<li><a class='connected yui-list-raisepanel'>monter</a></li>"+
				"<li><a class='connected yui-list-lowerpanel'>descendre</a></li>"+
				"<li><a class='connected yui-list-addelement'>Ajouter un élément</a></li>"+
				"<li><a class='connected yui-list-delpanel'>Supprimer le panel</a></li></ul>"+
				"<h2 class='list-head yui-list-listtoggler'>{title}</h2>\n",
			validator: function(v){
				if(v == ""){
					return false;
				}
				return true;
			}
		},
		container_template: {
			value: "<table>"+
					"<tr class='list-head'>"+
						"<th class='connected drag'></th>"+
						"<th class='yui-list-sorttitle title'>Titre</th>"+
						"<th class='yui-list-sortprogress progress'>Progression</th>"+
						"<th class='yui-list-sortscore score'>Note</th>"+
						"<th class='yui-list-sortstart start'>Début</th>"+
						"<th class='yui-list-sortend end'>Fin</th>"+
						"<th class='yui-list-sortduration duration'>Durée</th>"+
					"</tr>"+
				"</table>",
			validator: function(v){
				if(v == ""){
					return false;
				}
				return true;
			}
		},
		line_template: {
			value: "<tr class='yui-list-dragstate'>"+
					"<td class='connected yui-list-dragline drag' title='Drag and Drop'>: :</td>"+
					"<td class='yui-list-editelement title'>{title}</td>"+
					"<td class='progress'><span class='yui-list-editprogress'>{progress}</span><a class='connected yui-list-plus'>+</a></td>"+
					"<td class='score'><span class='yui-list-editscore'>{score}</span></td>"+
					"<td class='start'>{start}</td>"+
					"<td class='end'>{end}</td>"+
					"<td class='duration'>{duration}</td>"+
				"</tr>",
			validator: function(v){
				if(v == ""){
					return false;
				}
				return true;
			}
		},
		panelstat_template: {
			value: "<div class='listpanelstat'>"+
					"<p>Le panel contient {count} élément(s). Vous avez vu {episodedone} épisodes sur {episodecount}. Cela correspond à {episodeprogress}% de vu soit {donecomp}.</p>"+
				"</div>",
			validator: function(v){
				if(v == ""){
					return false;
				}
				return true;
			}
		},
		stat_template: {
			value: "<div class='liststat'><h2>Grand Total</h2>"+
					"<p>La liste contient {count} élément(s). Vous avez vu {episodedone} épisodes sur {episodecount}. Cela correspond à {episodeprogress}% de vu soit {donecomp}.</p>"+
				"</div>",
			validator: function(v){
				if(v == ""){
					return false;
				}
				return true;
			}
		},
		data_source: {
			value: "/listjson/"
		},
		actionuri: {
			value: "/listaction/"
		},
		connected: {
			value: false
		},
		strings: {
			value: {
				deleteConf: "Êtes-vous sûr de vouloir supprimer ce panel ?",
				newprogress:"Nombre de parties finies",
				wrongprogress:"Le nombre de parties finies doit être compris entre 0 et le nombre de parties.",
				newscore:"Note",
				wrongscore:"La note doit être comprise entre 0 et 10 inclus.",
				togglecheckbox:"Monter/Cacher le panel",
				day: "jour(s)",
				hour: "heure(s)"
			}
		}
	};

	Y.extend(list, Y.Widget, {
		initializer: function(){
			this.publish("panelLoaded",{
				defaultFn: Y.bind(this._panelLoaded,this)
			});
			this.publish("listLoaded",{
				defaultFn: Y.bind(this._listLoaded,this)
			});

			
			Y.later("60000",this,function(){
				if(this.get("connected")){
					Y.io(this.get("actionuri"));
				}
			},null,true);


			//Remove focus
			this.set("tabIndex",null);

			this.panel = {};
			this.line = {};
		},
		destructor: function(){

		},
		renderUI: function(){
			this.toggler = Y.Node.create("<ul class='yui-list-paneltoggler'></ul>");
			this.panelc = Y.Node.create("<div class='"+this.getClassName("panelcontainer")+"'></div>");
			this.stat = Y.Node.create("<div class='"+this.getClassName("statcontainer")+"'></div>");
			this.get("contentBox").append(this.toggler);
			this.get("contentBox").append(this.panelc);
			this.get("contentBox").append(this.stat);
		},
		bindUI: function(){
		},
		syncUI: function(){
			this.fetchPanel();
		},
		/**
			 * Panel Logic
			 */
		fetchPanel: function(){
			Y.io(this.get("data_source")+this.get("user")+"/",{
				on: {
					success: Y.bind(this.panelReceived,this)
				}
			});
		},
		panelReceived: function(id,o,r){
			try{
				var json = Y.JSON.parse(o.responseText);
			}
			catch(e){
				Y.log(e);
			}
			this.fire("panelLoaded",{
				data: json
			});
		},
		renderPanel: function(data){
			var d = new Array(),i=0;
			for(i in data){
				data[i].id = i;
				d.push(data[i]);
			}
			d.sort(function(a,b){
				return a.position - b.position;
			});

			for(i in data){
				this.newPanel(data[i].id,data[i]);
			}
		},
		reorderPanels: function(){
			var d = new Array(),i=0;
			for(i in this.panel){
				this.panel[i].id = i;
				d.push(this.panel[i]);
			}

			d.sort(function(a,b){
				return a.position - b.position;
			});

			for(i in d){
				this.panelc.append(d[i].node.container);
				this.toggler.append(d[i].node.toggler);
			}

		},
		raisePanel: function(p){
			var d = new Array(),i=0;
			for(i in this.panel){
				this.panel[i].id = i;
				d.push(this.panel[i]);
			}

			d.sort(function(a,b){
				return a.position - b.position;
			});

			for(i in d){
				if(d[i].id == p){
					if(i>0){
						var b = d[i-1];
						d[i-1] = d[i];
						d[i-1].position = b.position-1;
						d[i] = b;
						Y.io(this.get("actionuri")+"changeposition/"+p+"/"+d[i-1].position+"/");
					}
				}
			}

			for(i in d){
				this.panelc.append(d[i].node.container);
				this.toggler.append(d[i].node.toggler);
			}
		},
		lowerPanel: function(p){
			var d = new Array(),i=0;
			for(i in this.panel){
				this.panel[i].id = i;
				d.push(this.panel[i]);
			}

			d.sort(function(a,b){
				return a.position - b.position;
			});

			for(i in d){
				if(d[i].id == p){
					if(i<d.length-1){
						var b = d[i-(-1)];
						d[i-(-1)] = d[i];
						d[i-(-1)].position = b.position-(-1);
						d[i] = b;
						Y.io(this.get("actionuri")+"changeposition/"+p+"/"+d[i-(-1)].position+"/");
					}
				}
			}

			for(i in d){
				this.panelc.append(d[i].node.container);
				this.toggler.append(d[i].node.toggler);
			}
		},
		newPanel: function(i,data){
			/**
			 * Create Nodes
			 */
			data.id = i;
			data.node = {
				container: Y.Node.create("<div class='list-container' id='panel"+i+"'></div>"),
				title: Y.Node.create(Y.substitute(this.get("title_template"),data)),
				list: Y.Node.create(this.get("container_template")),
				stat: Y.Node.create("<div></div>"),
				toggler: Y.Node.create("<li class='shown'></li>")
			}
			data.node.container.append(data.node.title);
			data.node.container.append(data.node.list);
			this.panelc.append(data.node.container);

			/**
			 * Toggler
			 */
			var c = Y.Node.create("<input type='checkbox' title=\""+this.get("strings.togglecheckbox")+"\" />"),
				t = Y.Node.create("<a href='#panel"+i+"'>"+data.title+"</a>");
			if(data.hidden == "0"){
				c.set("checked",true);
			}
			c.on("click",Y.bind(this._panelVisibility,this,i));
			data.node.toggler.append(c);
			data.node.toggler.append(t);
			Y.log(data);
			if(data.hidden == "1"){
				data.node.toggler.toggleClass("shown");
				data.node.list.toggleClass(this.getClassName("hide"));
			}
			this.toggler.append(data.node.toggler);

			data.event = {
				toggle: data.node.container.delegate("click",Y.bind(this._togglePanel,this,i),"."+this.getClassName("listtoggler")),
				sortTitle: data.node.container.delegate("click",Y.bind(this.sort,this,'title',i),"."+this.getClassName("sorttitle")),
				sortProgress: data.node.container.delegate("click",Y.bind(this.sort,this,'done',i),"."+this.getClassName("sortprogress")),
				sortDuration: data.node.container.delegate("click",Y.bind(this.sort,this,'duration',i),"."+this.getClassName("sortduration")),
				sortStart: data.node.container.delegate("click",Y.bind(this.sort,this,'start',i),"."+this.getClassName("sortstart")),
				sortEnd: data.node.container.delegate("click",Y.bind(this.sort,this,'end',i),"."+this.getClassName("sortend")),
				sortScore: data.node.container.delegate("click",Y.bind(this.sort,this,'score',i),"."+this.getClassName("sortscore"))
			};

			/**
			 *	Drag and Drop
			 */
			if(this.get("connected")){
				data.drop = new Y.DD.Drop({
					node:data.node.container
				});
				/**
				 * Create Panels Events
				 */

				data.eventc = {
					drop: data.drop.on("drop:hit",Y.bind(this._lineDropped,this,i)),
					deletepanel: data.node.container.delegate("click",Y.bind(this._deletePanel,this,i),"."+this.getClassName("delpanel")),
					addElement: data.node.container.delegate("click",Y.bind(this._addElement,this,i),"."+this.getClassName("addelement")),
					raise: data.node.container.delegate("click",Y.bind(this.raisePanel,this,i),"."+this.getClassName("raisepanel")),
					lower: data.node.container.delegate("click",Y.bind(this.lowerPanel,this,i),"."+this.getClassName("lowerpanel")),
					custom: data.node.container.delegate("click",Y.bind(this._custom,this),"."+this.getClassName("custommenu"))
				};
			}

			this.panel[i] = data;
			this.fetchList(i);
		},
		removePanel: function(i){
			var data = this.panel[i];
			this.panel[i] = undefined;
			if(data !== undefined){
				Y.io(this.get("actionuri")+"deletepanel/"+i+"/");
				data.node.container.remove();
				data.node.toggler.remove();
				Y.Event.purgeElement(data.node.container,true);
				Y.Event.purgeElement(data.node.toggler,true);
				data = undefined;
			}
		},
		hidePanel: function(i){
			this.panel[i].node.list.addClass(this.getClassName("hide"));
		},
		showPanel: function(i){
			this.panel[i].node.list.removeClass(this.getClassName("hide"));
		},
		refreshPanels: function(){
			var i=0,d;
			for(i in this.panel){
				this.refreshPanel(i);
				this._panelstatRefresh(i);
			}
			for(i in this.line){
				d = this.line[i];
				this.removeLine(i);
				this.newLine(d.panel,i,d);
			}
			this.refreshTotalStat();
		},
		refreshPanel: function(i){
			var data = this.panel[i];
			data.node.container.set("innerHTML","");
			data.node.title = Y.Node.create(Y.substitute(this.get("title_template"),data));
			data.node.list = Y.Node.create(this.get("container_template"));
			data.node.container.append(data.node.title);
			data.node.container.append(data.node.list);
			this.panel[i] = data;
		},
		_togglePanel: function(i,e){
			this.panel[i].node.toggler.toggleClass("shown");
			this.panel[i].node.list.toggleClass(this.getClassName("hide"));
		},
		_panelVisibility: function(i,e){
			this._togglePanel(i);
			if(this.get("connected")){
				Y.io(this.get("actionuri")+"togglepanel/"+i);
			}
		},
		_deletePanel: function(i,e){
			if(confirm(this.get("strings.deleteConf"))){
				this.removePanel(i);
			}
		},
		_addElement: function(i,e){
			(new Y.addAnime({
				panel: i,
				list: this
			})).render();
		},
		_panelLoaded: function(e){
			this.renderPanel(e.data);
			this.reorderPanels();
		},
		_lineDropped: function(i,e){
			var drag = e.drag,
				data = drag.get("data"),
				d = this.line[data],
				op = d.panel;
			this.removeLine(data);
			this.newLine(i,data,d);
			this.sort("title",i);
			this._panelstatRefresh(i);
			this._panelstatRefresh(op);
			this.refreshTotalStat();
			Y.io(this.get("actionuri")+"changepanel/"+data+"/"+i+"/");
		},
		_panelstatRefresh: function(i){
			var s = {
				count: 0,
				scored: 0,
				point: 0,
				episodedone: 0,
				episodecount: 0,
				timedone: 0,
				timecount: 0
			}, j=0;
			
			for(j in this.line){
				if(this.line[j].panel == i){
					var da = this.line[j];
					s.count++;
					if(da.score > 0){
						s.scorecount++;
						s.point += da.score;
					}
					s.episodedone+= parseInt(da.done);
					s.timedone += parseInt(da.done)*parseInt(da.sec);
					s.episodecount+= parseInt(da.count);
					s.timecount += parseInt(da.count)*parseInt(da.sec);
					if(da.count == 0){
						s.episodecount += parseInt(da.done);
						s.timecount += parseInt(da.done)*parseInt(da.sec);
					}
				}
			}
			s.averagescore = s.point / s.scorecount;
			s.episodeprogress = Math.round(s.episodedone / s.episodecount * 10000)/100;

			s.timeprogress = Math.round(s.timedone / s.timecount * 10000)/100;
			s.timedonemin = s.timedone/60;
			s.timedonehour = s.timedonemin/60;
			s.timedoneday = Math.round(s.timedonehour/24*100)/100;

			s.doneday = Math.floor(s.timedonehour/24);
			s.donehour = Math.floor(s.timedonehour - s.doneday*24);
			if(s.doneday <= 0){
				s.donecomp = s.donehour+this.get("strings.hour");
			}
			else if(s.donehour <= 0){
				s.donecomp = s.doneday+this.get("strings.day");
			}
			else{
				s.donecomp = s.doneday+this.get("strings.day")+", "+s.donehour+this.get("strings.hour");
			}

			s.timecountmin = s.timecount/60;
			s.timecounthour = s.timecountmin/60;
			s.timecountday = Math.round((s.timecounthour/24)*100)/100;



			for(j in s){
				if(s[j] != s[j]){
					s[j] = 0;
				}
			}

			this.panel[i].stat = s;

			try{
				this.panel[i].node.stat.remove();
			}
			catch(e){
				//Pas Grave
			}
			this.panel[i].node.stat = Y.Node.create(Y.substitute(this.get("panelstat_template"),s));
			this.panel[i].node.container.append(this.panel[i].node.stat);
		},
		refreshTotalStat: function(){
			var p = this.panel;
			var j = 0;
			var s = {
				count: 0,
				scored: 0,
				point: 0,
				episodedone: 0,
				episodecount: 0,
				timedone: 0,
				timecount: 0
			};
			for(j in p){
				if(p[j].stat !== undefined){
					s.count += p[j].stat.count;
					s.scored += p[j].stat.scored;
					s.point += p[j].stat.point;
					s.episodedone += p[j].stat.episodedone;
					s.episodecount += p[j].stat.episodecount;
					s.timedone += p[j].stat.timedone;
					s.timecount += p[j].stat.timecount;
				}
			}

			s.averagescore = s.point / s.scorecount;
			s.episodeprogress = Math.round(s.episodedone / s.episodecount * 10000)/100;
			s.timeprogress = Math.round(s.timedone / s.timecount * 10000)/100;
			s.timedonemin = s.timedone/60;
			s.timedonehour = s.timedonemin/60;
			s.timedoneday = Math.round(s.timedonehour/24*100)/100;
			s.timecountmin = s.timecount/60;
			s.timecounthour = s.timecountmin/60;
			s.timecountday = Math.round((s.timecounthour/24)*100)/100;

			s.doneday = Math.floor(s.timedonehour/24);
			s.donehour = Math.floor(s.timedonehour - s.doneday*24);
			if(s.doneday == 0){
				s.donecomp = s.donehour+this.get("strings.hour");
			}
			else if(s.donehour == 0){
				s.donecomp = s.doneday+this.get("strings.day");
			}
			else{
				s.donecomp = s.doneday+this.get("strings.day")+", "+s.donehour+this.get("strings.hour");
			}

			for(j in s){
				if(s[j] != s[j]){
					s[j] = 0;
				}
			}

			this.stat.setContent(Y.substitute(this.get("stat_template"),s));
		},
		sort: function(param,i){
			var d = new Array();
			var j =0;
			for(j in this.line){
				if(this.line[j].panel == i){
					var da = this.line[j];
					da.id = j;
					d.push(da);
				}
			}
			if(param == 'title'){
				d = d.sort(function(a,b){
					if(a[param].toLowerCase() > b[param].toLowerCase())return 1;
					if(a[param].toLowerCase() < b[param].toLowerCase())return -1;
					return 0;
				});
			}
			else{
				d = d.sort(function(a,b){
					if(a[param] > b[param])return 1;
					if(a[param] < b[param])return -1;
					return 0;
				});
			}
			for(j in d){
				this.panel[i].node.list.append(d[j].node.line);
			}
		},
		/**
		 * List Logic
		 */
		fetchList:function(p){
			Y.io(this.get("data_source")+this.get("user")+"/"+p+"/",{
				on: {
					success: Y.bind(this.listReceived,this,p)
				}
			});
		},
		listReceived: function(p,id,o,args){
			try{
				var json = Y.JSON.parse(o.responseText);
			}
			catch(e){
				Y.log(e);
			}
			this.fire("listLoaded",{
				panel:p,
				data: json
			});
		},
		renderList: function(p,d){
			for(var i in d){
				this.newLine(p,i,d[i]);
			}
			this.sort('title',p);
			this._panelstatRefresh(p);
			this.refreshTotalStat();
		},
		createLine: function(p,i,d){
			d.id = i;
			d.panel = p;
			d.done = parseInt(d.done);
			d.count = parseInt(d.count);
			if(d.done == d.count && d.count != 0){
				d.progress = d.done;
			}
			else if(d.count == 0){
				d.progress = d.done+"/-";
			}
			else{
				d.progress = d.done+"/"+d.count;
			}


			d.startyear = parseInt(d.start.slice(0,4),10);
			d.startmonth = parseInt(d.start.slice(5,7),10);
			d.startday = parseInt(d.start.slice(-2),10);
			d.endyear = parseInt(d.end.slice(0,4),10);
			d.endmonth = parseInt(d.end.slice(5,7),10);
			d.endday = parseInt(d.end.slice(-2),10);
			if(d.endyear != "0000" && d.startyear != "0000"){
				d.duration = Math.floor((new Date(d.endyear,d.endmonth-1,d.endday) - new Date(d.startyear,d.startmonth-1,d.startday))/86400000);
			}
			else if(d.startyear != "0000"){
				d.duration = Math.floor((new Date() - new Date(d.startyear,d.startmonth-1,d.startday))/86400000);
			}
			else{
				d.duration = 0;
			}

			d.node = {
				line: Y.Node.create(Y.substitute(this.get("line_template"), d))
			};

			if(this.get("connected")){
				/**
				 * Drag and Drop
				 */
				d.node.line.plug(Y.Plugin.Drag);
				d.node.line.dd.set("data",i);
				d.node.line.dd.addHandle(".yui-list-dragline");
			}

			if(!this.get("connected") || d.count != 0 && d.done == d.count){
				d.node.line.all(".yui-list-plus").addClass(this.getClassName("hide"));
			}

			if(this.get("connected")){
				d.event = {
					add: d.node.line.delegate("click",Y.bind(this.incLineCount,this,i),".yui-list-plus"),
					drag:d.node.line.dd.on("drag:start",function(e){
						Y.all(".yui-list-dragstate").addClass("yui-list-draginprogress");
					}),
					drop: d.node.line.dd.on("drag:end",function(e){
						Y.all(".yui-list-draginprogress").removeClass("yui-list-draginprogress");
						e.preventDefault();
					}),
					editElement: d.node.line.delegate("click",Y.bind(this._editElement,this,i),"."+this.getClassName("editelement")),
					editProgress: d.node.line.delegate("click",Y.bind(this.editProgress,this,i),"."+this.getClassName("editprogress")),
					editScore: d.node.line.delegate("click",Y.bind(this.editScore,this,i),"."+this.getClassName("editscore"))
				};
			}
			return d;
		},
		newLine: function(p,i,d){
			d = this.createLine(p,i,d);
			this.line[i] = d;
			this.panel[p].node.list.append(d.node.line);
		},
		removeLine: function(i){
			var d = this.line[i];
			this.line[i] = undefined;
			if(d !== undefined){
				d.node.line.remove();
				Y.Event.purgeElement(d.node.line);
				d = undefined;
			}

		},
		modifyLine: function(p,i,d){
			var node = d.node.line;
			d = this.createLine(p,i,d);
			this.panel[p].node.list.insertBefore(d.node.line,node);
			node.remove();
			Y.Event.purgeElement(node);
			delete node;
			this.line[i] = d;
		},
		incLineCount: function(i){
			var d = this.line[i],
				p = this.line[i].panel;
			if(d.count == 0 || d.done < d.count){
				var date = new Date();
				if(d.done == 0){
					var start = date.getFullYear()+"-"+(date.getMonth()-(-1))+"-"+date.getDate();
					this.setStart(i,start);
					d.start = start;
				}
				if(d.done == d.count-1){
					var end = date.getFullYear()+"-"+(date.getMonth()-(-1))+"-"+date.getDate();
					this.setEnd(i,end);
					d.end = end;
				}
				d.done++;
				Y.io(this.get("actionuri")+"inccount/"+i+"/");

				this.modifyLine(p,i,d);
				this._panelstatRefresh(p);
				this.refreshTotalStat();
			}
		},
		editProgress: function(i){
			var p = prompt(this.get("strings.newprogress"),this.line[i].done),l;
			p = parseInt(p);
			if(p!=p || p < 0 || (p > this.line[i].count && this.line[i].count != 0)){
				alert(this.get("strings.wrongprogress"));
			}
			else{
				Y.io(this.get("actionuri")+"changedone/"+i+"/"+p+"/");
				l = this.line[i];
				l.done = p;
				this.modifyLine(l.panel,i,l);
				this._panelstatRefresh(l.panel);
				this.refreshTotalStat();
			}
		},
		editScore: function(i){
			var p = prompt(this.get("strings.newscore"),this.line[i].score),l;
			p = parseInt(p);
			if(p!=p || p < 0 || p > 10){
				alert(this.get("strings.wrongscore"));
			}
			else{
				Y.io(this.get("actionuri")+"changescore/"+i+"/"+p+"/");
				l = this.line[i];
				l.score = p;
				this.modifyLine(l.panel,i,l);
				this._panelstatRefresh(l.panel);
				this.refreshTotalStat();
			}
		},
		setStart: function(i,s){
			Y.io(this.get("actionuri")+"changestart/"+i+"/"+s+"/");
		},
		setEnd: function(i,s){
			Y.io(this.get("actionuri")+"changeend/"+i+"/"+s+"/");
		},
		_listLoaded: function(e){
			this.renderList(e.panel,e.data);
		},
		_editElement: function(i,e){
			var d = this.line[i];
			d.id = i;
			(new Y.editElement({
				data:d,
				list: this
			})).render();
		},
		_custom: function(){
			(new Y.custom({
				list: this
			})).render();
		}
		,
		changeStyle: function(cssstring){
			var node = Y.Node.create("<style type='text/css'>"+cssstring+"</style>");
			this.get("style").remove();
			Y.one("body").append(node);
			this.set("style",node);
		}
	});

	Y.list = list;
},1,{
	requires:["widget","io-base","json","substitute","dd","addElement","editElement","custom"]
});



YUI().add("addPanel",function(Y){
	var addPanel = function(){
		addPanel.superclass.constructor.apply(this,arguments);
	};

	addPanel.NAME = "addPanel";
	addPanel.ATTRS = {
		list: {
			value: undefined
		},
		strings: {
			value: {
				winTitle: "Ajouter un panel",
				add : "Ajouter le panel",
				name:"Nom du panel",
				hide: "Fermer"
			}
		}
	}

	Y.extend(addPanel, Y.Widget, {
		initializer: function(){
		},
		destructor: function(){

		},
		renderUI: function(){
			this.hidebutton = Y.Node.create("<a class='close'>"+this.get("strings.hide")+"</a>");
			this.name = Y.Node.create("<input type='text' />");
			this.submit = Y.Node.create("<input type='button' value='"+this.get("strings.add")+"' />");
			this.get("contentBox").append("<h2>"+this.get("strings.winTitle")+"</h2>");
			
			var node = Y.Node.create("<fieldset><legend>"+this.get("strings.add")+"</legend></fieldset>");
			this.get("contentBox").append(node);
			
			this.get("contentBox").append(this.hidebutton);
			node.append("<div>"+this.get("strings.name")+"</div>");
			node.append(this.name);
			this.get("contentBox").append(this.submit);
			this.show();
			this.set("centered",true);
		},
		bindUI: function(){
			this.submit.on("click",Y.bind(this._clickSubmit,this));
			this.hidebutton.on("click",Y.bind(this.hide,this));
		},
		syncUI: function(){

		},
		_clickSubmit: function(){
			this.addPanel(this.name.get("value"));
		},
		addPanel: function(name){
			Y.io("/listaction/addpanel/",{
				method: "post",
				data: "name="+name,
				on: {
					success: Y.bind(function(id,o,args){
						this.get("list").newPanel(o.responseText,{
							title: name
						});
					},this)
				}
			});
		}
	});

	addPanel = Y.Base.build(addPanel.NAME, addPanel, [Y.WidgetPosition,Y.WidgetPositionExt, Y.WidgetStack], {
		dynamic:false
	});

	Y.addPanel = addPanel;
},1,{
	requires:["widget","io-base","widget-position-ext","widget-stack"]
});

YUI().add("comments",function(Y){
	var comments = function(){
		comments.superclass.constructor.apply(this,arguments);
	}
	comments.NAME = "comments";
	comments.ATTRS = {
		user: {
			value: undefined
		},
		listid: {
			value: undefined
		},
		strings: {
			value: {
				winTitle: "Commentaires",
				addcomment: "Ajouter un Commentaire",
				addauthor: "Votre Nom",
				addtext: "Texte de votre commentaire",
				addbutton: "Poster"
			}
		}
	};

	Y.extend(comments,Y.Widget,{
		initializer: function(){
		},
		destructor: function(){
			this.get("boundingBox").remove();
		},
		renderUI: function(){
			this.close = Y.Node.create("<a class='close'>"+this.get("strings.close")+"</a>");
			var c = this.get("contentBox");
			c.append("<h2>"+this.get("strings.winTitle")+"</h2>");
			c.append(this.close);
			c = Y.Node.create("<div></div>");

			this.comments = Y.Node.create("<ul></ul>");
			c.append(this.comments);

			this.form = Y.Node.create("<form></form>");
			c.append(this.form);
			var fs = Y.Node.create("<fieldset><legend>"+this.get("strings.addcomment")+"</legend></fieldset>");
			this.form.append(fs);

			if(this.get("user")==""){
				this.author = Y.Node.create("<input type='text' name='author' />");
				fs.append("<div>"+this.get("strings.addauthor")+"</div>");
				fs.append(this.author);
			}

			this.text = Y.Node.create("<textarea name='comment'></textarea>");
			fs.append("<div>"+this.get("strings.addtext")+"</div>");
			fs.append(this.text);

			this.post = Y.Node.create("<input type='button' value=\""+this.get("strings.addbutton")+"\" />");
			fs.append(this.post);

			this.get("contentBox").append(c);
			this.show();
			this.set("centered",true);
		},
		bindUI: function(){
			this.post.on("click",Y.bind(this._submit,this));
			this.close.on("click",Y.bind(this._close,this));
		},
		syncUI: function(){
			this._queryComments();
		},
		_close: function(){
			this.hide();
			this.destroy();
		},
		_submit: function(){
			Y.io("/listaction/addcomment/"+this.get("listid")+"/",{
				method: "post",
				form:{
					id: this.form
				}
			});
			this.text.set("value","");
		},
		_queryComments: function(){
			Y.io("/listaction/commentlist/"+this.get("listid")+"/",{
				on:{
					success: Y.bind(this._refreshComments,this)
				}
			});
		},
		_refreshComments: function(id,o,args){
			this.comments.set("innerHTML","");
			var j = {};
			try{
				j = Y.JSON.parse(o.responseText);
			}
			catch(e){

			}
			var com = undefined;
			for(var i in j){
				com = Y.Node.create("<li></li>");
				if(j[i].registered == 1){
					com.append("<div class='username'><a href='/list/"+encodeURIComponent(j[i].author)+"/'>"+j[i].author+"</a></div>");
				}
				else{
					com.append("<div class='username'>"+j[i].author+"</div>");
				}
				com.append("<div class='date'>"+j[i].date+"</div>");
				com.append("<div class='text'>"+j[i].text+"</div>");
				this.comments.append(com);
			}
		}
	});

	comments = Y.Base.build(comments.NAME, comments, [Y.WidgetPosition,Y.WidgetPositionExt, Y.WidgetStack], {
		dynamic:false
	});

	Y.comments = comments;
},1,{
	requires:["widget","io-base","io-form","json","widget-position-ext","widget-stack"]
});

YUI().add("history",function(Y){
	var history = function(){
		history.superclass.constructor.apply(this,arguments);
	}
	history.NAME = "history";
	history.ATTRS = {
		user: {
			value: undefined
		},
		list: {
			value: undefined
		},
		listid: {
			value: undefined
		},
		strings: {
			value: {
				winTitle: "Historique",
				loadinghistory: "Chargement de l'historique en cours",
				deletehistory: "Êtes vous sûr de vouloir supprimer cette ligne de votre historique ?",
				close: "Fermer"
			}
		}
	};

	Y.extend(history,Y.Widget,{
		initializer: function(){
		},
		destructor: function(){
			this.get("boundingBox").remove();
		},
		renderUI: function(){
			this.close = Y.Node.create("<a class='close'>"+this.get("strings.close")+"</a>");
			var c = this.get("contentBox");
			c.append("<h2>"+this.get("strings.winTitle")+"</h2>");
			c.append(this.close);
			c = Y.Node.create("<div></div>");

			this.history = Y.Node.create("<ul></ul>");
			this.history.append("<li>"+this.get("strings.loadinghistory")+"</li>");
			c.append(this.history);

			this.get("contentBox").append(c);
			this.show();
			this.set("centered",true);
		},
		bindUI: function(){
			this.close.on("click",Y.bind(this._close,this));
		},
		syncUI: function(){
			this._queryhistory();
		},
		_close: function(){
			this.hide();
			this.destroy();
		},
		_queryhistory: function(){
			Y.io("/listaction/gethistory/"+this.get("listid"),{
				on:{
					success: Y.bind(this._refreshhistory,this)
				}
			});
		},
		_refreshhistory: function(id,o,args){
			this.history.set("innerHTML","");
			var j = {},
				h = undefined,
				c = undefined,
				count = 0,
				d = undefined,
				node = undefined;
			try{
				j = Y.JSON.parse(o.responseText);
			}
			catch(e){

			}
			
			for(var i in j){
				if(d != j[i].date.slice(0,10)){
					d = j[i].date.slice(0,10);
					if(node!= undefined){
						node.append("<div class='historytotal'>"+count+"</div>");
					}
					node = Y.Node.create("<li></li>");
					node.append("<h4>"+d+"</h4>");
					c = Y.Node.create("<ul></ul>");
					node.append(c);
					this.history.append(node);
					count = 0;
				}
				count++;
				h = Y.Node.create("<li></li>");
				h.append("<div class='title'>"+j[i].name+"</div>");
				h.append("<div class='number'>"+j[i].number+"</div>");
				if(this.get("list").get("connected")){
					var n = Y.Node.create("<div class='delete'>X</div>");
					n.on("click",Y.bind(this._deleteHistory,this,j[i].id));
					h.append(n);
				}
				h.append("<div class='date'>"+j[i].date+"</div>");
				c.append(h);
			}
			if(node!= undefined){
				node.append("<div class='historytotal'>"+count+"</div>");
			}
			this.set("centered",true);
		},
		_deleteHistory: function(i){
			if(confirm(this.get("strings.deletehistory"))){
				Y.io("/listaction/removehistory/"+i,{
					on:{
						success: Y.bind(this._queryhistory,this)
					}
				});
			}
		}
	});

	history = Y.Base.build(history.NAME, history, [Y.WidgetPosition,Y.WidgetPositionExt, Y.WidgetStack], {
		dynamic:false
	});

	Y.history = history;
},1,{
	requires:["widget","io-base","io-form","json","widget-position-ext","widget-stack"]
});

YUI().add("connectbox",function(Y){
	var connectbox = function(){
		connectbox.superclass.constructor.apply(this,arguments);
	};

	connectbox.NAME = "connectbox";
	connectbox.ATTRS = {
		connected: {
			value: false
		},
		strings: {
			value: {
				winTitle: "Connexion",
				login : "Connexion",
				name: "Nom d'utilisateur",
				password: "Mot de passe",
				connect: "Connexion",
				logoutconf: "Êtes vous sûr de vouloir vous déconnecter ?",
				notregistered: "Pas encore inscrit ?",
				hide: "Fermer"
			}
		}
	}

	Y.extend(connectbox, Y.Widget, {
		initializer: function(){
		},
		destructor: function(){

		},
		renderUI: function(){
			this.hidebutton = Y.Node.create("<a class='close'>"+this.get("strings.hide")+"</a>");
			this.get("contentBox").append("<h2>"+this.get("strings.winTitle")+"</h2>");
			this.get("contentBox").append(this.hidebutton);

			if(!this.get("connected")){
				var node = Y.Node.create(
					"<form action='/log/in' method='POST'>"+
						"<fieldset>"+
							"<legend>"+this.get("strings.login")+"</legend>"+
							"<div class='loginusername'>"+this.get("strings.name")+"</div><input type='text' name='user' />"+
							"<div class='loginpassword'>"+this.get("strings.password")+"</div><input type='password' name='password' />"+
						"</fieldset>"+
						"<input type='submit' value='"+this.get("strings.connect")+"' />"+
					"</form>"+
					"<div class='notregistered'><a href='/register'>"+this.get("strings.notregistered")+"</a></div>"
				);
				this.get("contentBox").append(node);
			}
			else{
				if(confirm(this.get("strings.logoutconf"))){
					window.location = "/log/out";
					return;
				}
			}

			this.show();
			this.set("centered",true);
		},
		bindUI: function(){
			this.hidebutton.on("click",Y.bind(this._close,this));
		},
		syncUI: function(){

		},
		_clickSubmit: function(){
			this.connectbox(this.name.get("value"));
		},
		_close: function(){
			this.hide();
			this.get("contentBox").remove();
			this.destroy();
		}
	});

	connectbox = Y.Base.build(connectbox.NAME, connectbox, [Y.WidgetPosition,Y.WidgetPositionExt, Y.WidgetStack], {
		dynamic:false
	});

	Y.connectbox = connectbox;
},1,{
	requires:["widget","io-base","widget-position-ext","widget-stack"]
});

YUI({
	modules:{
		"gallery-lightbox":{
			name: "lightbox-js",
			type:"js",
			fullpath: "/js/gallery-lightbox-min.js",
			requires: ["widget", "widget-position-ext", "widget-stack","node","event"]
		}
	}
}).use("anim","gallery-lightbox","event",function(Y){
	Y.on("domready",function(){
		var LB = new Y.Lightbox({
			zIndex:255
		});
		LB.render();
	});
});
