var XMLTickets = XMLDir+'tickets.xml';
var XMLTicket = XMLDir+'ticket.xml';
var XMLTroubleshooting = XMLDir+'troubleshooting.xml';

Tickets = Class.create();
Object.extend(Tickets.prototype, {

	initialize: function(elementList, elementComments, elementForm, elementButtonNew){
		this.elementList = ( elementList || domCE('div') );
		this.elementComments = ( elementComments || domCE('div') );
		this.elementForm = ( elementForm || domCE('div') );
		this.elementButtonNew = ( elementButtonNew || domCE('button') );
		this.tickets = Array();
		this.loaded = false;
		this.focused = false;

		onSessionEvent.subscribe(function(type, args){
			switch(args[0]){
				case 'cookie':
				case 'login':
				case 'reload':
					if(this.loaded){ this.reload(); }else{ this.load(); };
					this.buttonNew.enable();
					break;
				case 'logout':
					if(this.loaded) this.reload();
					this.buttonNew.disable();
					break;
			};
		}, this, true);

		this.eventNew  = this.newTicket.bindAsEventListener(this);
		Event.observe(this.elementButtonNew, "mousedown", this.eventNew);
	},

	registerForm: function(object){
		this.objectForm = object;
	},

	hide: function(){
		this.elementList.hide();
	},

	show: function(){
		this.elementList.show();
	},

	reload: function(){
		this.unload();
		this.load();
	},

	load: function(){
		if(this.loaded) return;
		this.loaded = true;
		this.elementList.domRCN();
		this.ajaxtickets = new Ajax();
		this.ajaxtickets.url = XMLTickets;
		this.ajaxtickets.requestXML(function(response){
			if(typeof response.responseJSON.tickets == 'undefined' || typeof response.responseJSON.tickets.ticket == 'undefined'){
				//no tickets
				this.elementList.domAC(
					domCE('div').setStyle({
						padding: '25px 0px'
					}).domSA({
						align:'center',
						className: 'sep-before'
					}).domCTN(lang('You currently have no support tickets.','Vous n\'avez actuellement aucun billet de support.'))
				);
			}else{
				XMLtickets = response.responseJSON.tickets;
				//is tickets
				XMLtickets.ticket = (typeof XMLtickets.ticket.length == 'undefined')
					? [XMLtickets.ticket]
					: XMLtickets.ticket;
				XMLtickets.ticket.sort(function(a,b){
					return (a['-insert'] < b['-insert']) ? 1 : -1;
				});

				XMLtickets.ticket.each(function(ticket){
					index = this.tickets.length;
					this.tickets[index] = new Ticket(this, ticket);
					this.elementList.domAC(
						domCE('p').setStyle({ clear: 'both' })
					).domAC(
						this.tickets[index].elementList
					);
					this.elementComments.domAC(
						this.tickets[index].elementComments
					);
					this.elementForm.domAC(
						this.tickets[index].elementForm
					);
					if(ticket['-id'] == ( window.location.toString().split('#')[1] || '' )){
						this.tickets[index].focus();
						this.focused = true;
					};
				}.bind(this));

				if(!this.focused){
					this.tickets[0].focus();
					//window.location.href = '#'+this.tickets[0].ticket['-id'];
					window.location.replace('#'+this.tickets[0].ticket['-id']);
				};
			}
		}.bind(this));
	},

	unload: function(){
		this.loaded = false;
		this.focused = false;
		this.tickets.each(function(ticket){
			ticket.destroy();
		}.bind(this));
		this.tickets = Array();
		Event.stopObserving(this.buttonNew, "mousedown", this.eventNew);
	},

	focusTicket: function(ticket){
		for(var t=0; t<this.tickets.length; t++){
			if(this.tickets[t].ticket['-id'] !== ticket.ticket['-id'] && this.tickets[t].focused){
				this.tickets[t].blur();
			};
		};
	},

	blurTicket: function(ticket){},

	newTicket: function(event){
		for(var t=0; t<this.tickets.length; t++){
			this.tickets[t].blur();
		};
		index = this.tickets.length;
		this.tickets[index] = new Ticket(this);

		this.elementComments.domAC(
			this.tickets[index].elementComments
		);
		this.elementForm.domAC(
			this.tickets[index].elementForm
		);
		this.tickets[index].focus();
	}

});

Ticket = Class.create();
Object.extend(Ticket.prototype, {

	initialize: function(parent, ticket){
		this.parent = parent;
		this.comments = Array();
		this.focused = false;
		this.loaded = false;
		this.draft = false;

		this.ticket = Object.extend({
			'-id': 0,
			title: lang('Post New Ticket','Envoyer un Nouveau Billet'),
			'is_draft': 0,
			'-num': 0,
			'-insert': '',
			'-read': '0000-00-00 00:00:00',
			'-update': '0000-00-00 00:00:00',
			comments: {
				'-num': 0
			}
		}, (ticket || {}));

		this.elementList = domCE('div').domAC(
			domCE('p').domSA({
				className: 'title sep-before '+(
					(this.ticket['-read'] < this.ticket['-update'])
						? 'unread'
						: 'read'
				)
			}).domAC(
				this.elementLink = domCE('a').domSA({
					href: 'javascript:void(0);',
					className: 'arrow'
				}).domAC(
					this.elementListIcon = domCE('img').domSA({
						src:'/images/icons/32x32_ticket_'+(
							(this.ticket['-read'] < this.ticket['-update'])
								? 'unread'
								: 'read'
						)+'.png',
						height:32,
						width:32,
						align: 'right'
					})
				).domAC(
					this.elementTitle = domCE('span').domCTN(this.ticket.title)
				).domAC(
					domCE('span').domSA({ className: 'op50' }).domCTN('\u00a0('+this.ticket.comments['-num']+')')
				)
			)
		).domAC(
			domCE('p').domSA({
				className: 'content'
			}).domAC(
				this.elementTime = domCE('span').domSA({ className: 'op50' }).domCTN(this.ticket['-insert'])
			).domAC(
				this.elementDraft = domCE('strong').domCTN(lang(' [Draft]',' [Brouillon]')).hide()
			)
		);

		this.elementComments = domCE('div').domAC(
			domCE('div').domSA({
				className: 'plaque'
			}).domAC(
				domCE('img').domSA({
					src:'/images/icons/48x48_ticket_'+(
						(this.ticket['-read'] < this.ticket['-update'])
							? 'unread'
							: 'read'
					)+'_reply.png',
					height:48,
					width:48,
					align: 'left'
				})
			).domAC(
				domCE('h1').domCTN(this.ticket.title)
			).domAC(
				domCE('p').setStyle({ clear: 'both' })
			)
		).hide();
		this.elementForm = domCE('div').hide();

		this.markDraft(((this.ticket.is_draft == 1) ? true : false ));
		this.markTime(this.ticket['-insert']);

		this.eventFocus  = this.focus.bindAsEventListener(this);
		this.eventBlur  = this.blur.bindAsEventListener(this);
		Event.observe(this.elementList, "mousedown", this.eventFocus);
		this.eventClick  = this.click.bindAsEventListener(this);
		Event.observe(this.elementLink, "mousedown", this.eventClick);
	},

	click: function(event){
		window.location.replace('#'+this.ticket['-id']);
	},

	destroy: function(){
		if(typeof this.form != 'undefined' && typeof this.form.destroy == 'function'){ this.form.destroy(); };
		Event.stopObserving(this.elementList, "mousedown", this.eventFocus);
		Event.stopObserving(this.elementList, "mousedown", this.eventBlur);
		this.elementList.remove();
		this.elementComments.remove();
	},

	focus: function(event){
		if(this.focused) return;
		Event.stopObserving(this.elementList, "mousedown", this.eventFocus);
		this.focused = true;
		this.parent.focusTicket(this);
		$(this.elementList).removeClassName('blur');
		$(this.elementList).addClassName('focus');
		if(!this.loaded){ this.load(); };
		this.elementForm.show();
		this.elementComments.show();
		this.elementListIcon.domSA({
			src: '/images/icons/32x32_ticket_'+(
				(this.ticket['-read'] < this.ticket['-update'])
					? 'unread'
					: 'read'
			)+'_reply.png'
		});
	},

	blur: function(event){
		if(!this.focused) return;
		Event.observe(this.elementList, "mousedown", this.eventFocus);
		this.focused = false;
		this.parent.blurTicket(this);
		$(this.elementList).removeClassName('focus');
		$(this.elementList).addClassName('blur');
		this.elementForm.hide();
		this.elementComments.hide();
		this.elementListIcon.domSA({
			src: '/images/icons/32x32_ticket_'+(
				(this.ticket['-read'] < this.ticket['-update'])
					? 'unread'
					: 'read'
			)+'.png'
		});
	},

	reload: function(){
		this.unload();
		this.load();
	},

	load: function(){
		if(this.loaded) return;
		this.loaded = true;
		if(this.ticket['-id'] == 0){
			//new
			this.form = new TicketForm(this, this.elementForm, true);
		}else{
			//existing
			this.ajaxticket = new Ajax();
			this.ajaxticket.url = XMLTicket+'?ticketid='+this.ticket['-id'];
			this.ajaxticket.requestXML(function(response){
				if(typeof response.responseJSON.tickets == 'undefined') return;
				if(typeof response.responseJSON.tickets.ticket == 'undefined') return;
				XMLticket = response.responseJSON.tickets.ticket;
				if(typeof XMLticket.comments.comment == 'undefined'){
					this.form = new TicketForm(this, this.elementForm, true, {
						ticketid: this.ticket['-id'],
						title: this.ticket.title
					});
				}else{
					XMLticket.comments.comment = (typeof XMLticket.comments.comment.length == 'undefined')
						? [XMLticket.comments.comment]
						: XMLticket.comments.comment;
					XMLticket.comments.comment.each(function(comment, index){
						if(comment.is_draft == 1){
							this.draft = true;
							this.form = new TicketForm(this, this.elementForm, ((XMLticket.comments.comment.length==1)?true:false), {
								ticketid: this.ticket['-id'],
								commentid: comment['-id'],
								title: this.ticket.title,
								comment: comment.comment
							});
						}else{
							index = this.comments.length;
							this.comments[index] = new TicketComment(this, this.elementComments, comment, index+1);
						};
					}.bind(this));
					if(!this.draft) this.form = new TicketForm(this, this.elementForm, false, {
						ticketid: this.ticket['-id'],
						commentid: 0
					});
				};
				this.markRead(true);
			}.bind(this));
		};
	},

	unload: function(){
		if(!this.loaded) return;
		this.loaded = false;
	},

	markRead: function(isRead){
		this.elementTitle.domSA({ className: ((isRead) ? 'read' : 'unread' ) });
	},

	markDraft: function(isDraft){
		if(isDraft) this.elementDraft.show();
			else this.elementDraft.hide();
	},

	markTime: function(datetime){
		this.elementTime.domRCN( domCTN(datetime) );
	}
});

TicketComment = Class.create();
Object.extend(TicketComment.prototype, {

	initialize: function(parent, parentelement, comment, index){
		this.parent = parent;
		this.parentelement = parentelement;
		this.comment = comment;
		this.index = index;

		this.parentelement.domAC(
			this.element = domCE('div').domSA({ className: 'plaque sep-before' }).domAC(
				domCE('p').domSA({
					className: 'title'
				}).domAC(
					domCE('img').domSA({
						src: (
							(this.comment.author['-avatar'])
								? 'http://www.doppelme.com/transparent/32/'+this.comment.author['-avatar']+'/crop.png'
								: '/images/icons/32x32_avatar.png'
						),
						height:32,
						width:32,
						alt:'[Avatar]',
						align:'left'
					})
				).domAC(
					domCE('span').domCTN(this.comment.author['#text'])
				)
			).domAC(
				domCE('p').domSA({
					className: 'content op50'
				}).domCTN(this.comment['-insert'])
			).domAC(
				domCE('p').domSA({ className: 'clear' })
			).domAC(
				domCE('p').domSA({
					className: 'content'
				}).domCHTN(comment.comment.nl2br().linkify().unicodeentities())
			)
		);
	},

	hide: function(){
		this.element.hide();
	},

	show: function(){
		this.element.show();
	}
});

TicketForm = Class.create();
Object.extend(TicketForm.prototype, {

	initialize: function(parent, parentElement, origin, preload){

		this.parent = parent;
		this.parentElement = parentElement;
		this.origin = origin;

		this.parentElement.domAC(
			this.element = domCE('div').domSA({
				className: 'noprint plaque sep-before'
			}).domAC(
				this.elementForm = domCE('form').domAC(
					this.inputAction = domCE('input', 'text').domSA({
						name: 'action'
					}).hide()
				).domAC(
					this.inputTicketid = domCE('input', 'text').domSA({
						name: 'ticketid'
					}).hide()
				).domAC(
					this.inputCommentid = domCE('input', 'text').domSA({
						name: 'commentid'
					}).hide()
				).domAC(
					domCE('h2').domCTN((
						(this.origin)
							? lang('Post New Ticket','Envoyer un Nouveau Billet')
							: lang('Post Reply','Envoyer une Réponse')
					))
				).domAC(
					domCE('p').domAC(
						domCE('span').domCTN(lang('Want a speedy resolution?','Veulent une solution rapide?')+String.nbsp)
					).domAC(
						domCE('a').domSA({
							className: 'popup',
							href:'javascript:void(0);',
							onclick: function(){
								$('ticket-tips').show();
								setTimeout(function(){
									$('ticket-tip').center();
								}, 250);
							}
						}).domCTN(lang('Writing tips for product related problems', 'Conseils de rédaction pour des problèmes de produits connexes'))
					)
				).domAC(
					this.elementTitle = domCE('p').domSA({
						className: 'sep-before'
					}).domCTN(lang('Subject:','Sujet:')).domAC(
						this.inputTitle = domCE('input', 'text').domSA({
							name: 'title'
						}).setStyle({
							width: '98%'
						})
					)
				).domAC(
					this.elementComment = domCE('p').domSA({
						className: 'sep-before'
					}).domAC(
						domCE('span').domCTN(lang('Question / Comment:','Question / Commentaire:')+String.nbsp)
					)
				).domAC(
					this.inputComment = domCE('textarea').domSA({
						name: 'comment',
						rows: 5
					}).setStyle({
						width: '98%'
					}).autoRows(5, true)
				).domAC(
					this.elementButtons = domCE('div').domSA({
						className: 'buttons'
					}).domAC(
						this.elementMessage = domCE('span').setStyle({
							padding: '5px',
							float: 'left'
						}).domSA({
							className: 'content'
						})
					).domAC(
						this.buttonSend = domCE('button').domSA({
							onclick: function(){ return false; }
						}).domCTN(lang('Send','Envoyer')).disable()
					).domAC(
						this.buttonSave = domCE('button').domSA({
							onclick: function(){ return false; }
						}).domCTN(lang('Save','Sauvegarder')).disable()
					).domAC(
						this.buttonDiscard = domCE('button').domSA({
							onclick: function(){ return false; }
						}).domCTN(lang('Discard','Effacer'))
					)
				)
			)
		);

		if(this.origin){
			this.elementTitle.show();
		}else{
			this.elementTitle.hide();
		};


		if(typeof preload != 'undefined'){
			this.inputTicketid.value = (typeof preload.ticketid == 'undefined') ? 0 : preload.ticketid;
			this.inputCommentid.value = (typeof preload.commentid == 'undefined') ? 0 : preload.commentid;
			if(typeof preload.title != 'undefined' && this.origin){
				this.inputTitle.value = preload.title;
			};
			if(typeof preload.comment == 'undefined'){
				this.inputComment.value = '';
				this.buttonSend.disable();
			}else{
				this.inputComment.value = preload.comment;
				this.buttonSend.enable();
			};
		}

		if(this.inputComment.value == ''){
			this.buttonDiscard.disable();
		};

		this.eventKeyPress  = this.keypress.bindAsEventListener(this);
		Event.observe(this.inputTitle, "keydown", this.eventKeyPress);
		this.eventKeyPressCT  = this.keypress.bindAsEventListener(this, true);
		Event.observe(this.inputComment, "keydown", this.eventKeyPressCT);

		this.eventSend  = this.send.bindAsEventListener(this);
		Event.observe(this.buttonSend, "mousedown", this.eventSend);

		this.eventSave  = this.save.bindAsEventListener(this);
		Event.observe(this.buttonSave, "mousedown", this.eventSave);

		this.eventDiscard  = this.discard.bindAsEventListener(this);
		Event.observe(this.buttonDiscard, "mousedown", this.eventDiscard);

		if(origin){
			this.eventTips = this.tips.bindAsEventListener(this);
			Event.observe(this.inputComment, "focus", this.eventTips);
		};
		this.toSave = false;
		this.timeoutSave = 30000; //30 seconds
	},

	tips: function(event){
		Event.stopObserving(this.inputComment, "focus", this.eventTips);
		$('ticket-tips').show();
		setTimeout(function(){
			$('ticket-tip').center();
		}, 250);
	},

	hide: function(){
		this.parentElement.hide();
	},

	show: function(){
		this.parentElement.show();
	},

	keypress: function(event, capturetab){
		if(
			(typeof event.keyCode != 'undefined')
			&& (
				event.keyCode == 8 /* backspace */
				|| event.keyCode == 9 /* tab */
				|| event.keyCode == 13 /* carriage return */
				|| event.keyCode == 32 /* space */
				|| (event.keyCode >= 46 && event.keyCode <= 111) /* alpha-numeric */
				|| event.keyCode >= 124 /* skip F1(112)-F12(123) */
			)
		){
			//capture tab
			capturetab = (typeof capturetab == 'undefined') ? false : capturetab;
			if(event.keyCode == 9 && capturetab){
				try{ if(event && typeof(Event.stop) == 'function') Event.stop(event); }catch(e){};
				this.inputComment.insertAtCursor('\t');
			};

			this.buttonSend.enable();
			this.buttonSave.enable();
			this.buttonDiscard.enable();
			if(!this.toSave){
				this.toSave = true;
				this.timerSave = setTimeout(function(){ this.save(); }.bind(this), this.timeoutSave);
			};
		};
	},

	send: function(event){
		if(this.toSave){
			this.toSave = false;
			clearTimeout(this.timerSave);
		};
		this.buttonSend.domRCN(domCTN(lang('Please wait...','Patientez...')));
		this.buttonSend.disable();
		this.buttonSave.disable();
		this.buttonDiscard.disable();
		this.inputAction.value = 'ticket_comment_send';

		this.ajaxsend = new HttpPost();
		this.ajaxsend.requestXML(function(response){
			XML = response.responseJSON.httppost;
			if(XML['-errors'] == 0){
				//success
				this.parent.parent.reload();
			}else{
				//failed
			};
			this.buttonSend.domRCN(domCTN(lang('Send','Envoyer')));
			this.buttonSend.enable();
			this.buttonDiscard.enable();
		}.bind(this), [], this.elementForm);
	},

	save: function(event){
		if(this.toSave){
			this.toSave = false;
			clearTimeout(this.timerSave);
		};
		this.buttonSave.disable();
		this.inputAction.value = 'ticket_comment_save';

		this.ajaxsave = new HttpPost();
		this.ajaxsave.requestXML(function(response){
			XML = response.responseJSON.httppost;

			if(typeof XML.ticketid.value != 'undefined') this.inputTicketid.value = XML.ticketid.value;
			if(typeof XML.commentid.value != 'undefined') this.inputCommentid.value = XML.commentid.value;

			if(XML['-errors'] == 0){
				//success
				this.parent.markDraft(true);
				var Now = new Date();
				this.elementMessage.domRCN(
					domCTN(lang('Draft saved at ','	Brouillon sauvegardé à ')+Now.toLocaleTimeString()+String.nbsp)
				);
			}else{
				//failed
			};
		}.bind(this), [], this.elementForm);
	},

	discard: function(event){
		this.buttonSave.disable();
		if(this.toSave){
			this.toSave = false;
			clearTimeout(this.timerSave);
		};
		this.inputAction.value = 'ticket_comment_discard';
		this.ajaxdiscard = new HttpPost();
		this.ajaxdiscard.requestXML(function(response){
			XML = response.responseJSON.httppost;
			if(XML['-errors'] == 0){
				//success
				this.inputTicketid.value = XML.ticketid.value;
				this.inputCommentid.value = XML.commentid.value;

				this.parent.markDraft(false);
				this.inputTitle.value = '';
				this.inputComment.value = '';
				this.parent.parent.reload();
			}else{
				//failed
				this.inputTitle.value = '';
				this.inputComment.value = '';
				this.parent.parent.reload();
			};
		}.bind(this), [], this.elementForm);
	},

	destroy: function(){
		Event.stopObserving(this.inputTitle, "keydown", this.eventKeyPress);
		Event.stopObserving(this.inputComment, "keydown", this.eventKeyPressCT);
		Event.stopObserving(this.buttonSend, "mousedown", this.eventSend);
		Event.stopObserving(this.buttonSave, "mousedown", this.eventSave);
		Event.stopObserving(this.buttonDiscard, "mousedown", this.eventDiscard);
		this.element.remove();
	}

});


ArticleRating = Class.create();
Object.extend(ArticleRating.prototype, {
	initialize: function(element, options, faqid, currentrating){
		this.element = element;
		this.options = options;
		this.faqid = faqid;
		this.currentrating = currentrating;
		this.seed = Math.floor(Math.random()*1000001);
		this.areas = new Array();

		this.element.domSA({
			isMap: 'ismap',
			useMap: '#rating'+this.seed
		});

		this.element.parentNode.appendChild(
			this.map = domCE('map').domSA({
				id: 'rating'+this.seed,
				name: 'rating'+this.seed
			})
		);

		this.options.each(function(option){
			pointer = this.areas.length;
			this.areas[pointer] = new ArticleRatingArea(this, option);
			this.map.domAC(
				this.areas[pointer].element
			);
			if(Math.ceil(this.currentrating/2) == option.value){
				this.element.domSA({
					src: option.image
				});
			};
		}.bind(this));
	},

	mouseover: function(area){
		this.element.domSA({
			src: area.options.image
		});
	},

	mousedown: function(area){
		this.form = domCE('form').domAC(
			domCE('input', 'hidden').domSA({
				name: 'action',
				value: 'faq_rate'
			})
		).domAC(
			domCE('input', 'hidden').domSA({
				name: 'faqid',
				value: this.faqid
			})
		).domAC(
			domCE('input', 'hidden').domSA({
				name: 'rating',
				value: area.options.value
			})
		);

		this.ajax = new HttpPost();
		this.ajax.requestXML(function(response){
			alert('You have rated this support article with '+response.responseJSON.httppost.rating.value+' star(s).\n\nThank you,\n\nThis feedback will help us improve our services.');
		}, [], this.form);
	}
});

ArticleRatingArea = Class.create();
Object.extend(ArticleRatingArea.prototype, {
	initialize: function(parent, options){

		this.parent = parent;
		this.options = options;
		this.element = domCE('area').domSA({
			shape: 'rect',
			coords: this.options.coords,
			href: 'javascript:void(0);'
		});

		this.eventMouseOver  = this.mouseover.bindAsEventListener(this);
		Event.observe(this.element, "mouseover", this.eventMouseOver);

		this.eventMouseDown  = this.mousedown.bindAsEventListener(this);
		Event.observe(this.element, "mousedown", this.eventMouseDown);

		this.tooltip = new Tooltip();
		this.tooltip.initTooltip();
		this.tooltip.registerTooltipElement(this.element);
		this.element.setStyle('cursor:pointer;');
		this.tooltip.registerTooltipTitle(
			domCE('div').domAC(
				domCE('h4').setStyle({width: '235px' }).domSA({
					className: 'tooltiptitle'
				}).domCTN(lang('Rate Article', 'Rate Article')+' - '+this.options.value)
			)
		);
		this.tooltip.registerTooltipBody(
			domCE('div').domAC(
				domCE('p').setStyle({width: '235px'}).domSA({
					className: 'tooltipbody'
				}).domAC(
					domCE('p').domCHTN(lang('Click to rate this article at '+this.options.value+' star(s). 1-star (not useful) to 5-stars (very useful).', 'Click a star to rate this article. 1-star (not useful) to 5-stars (very useful).'))
				)
			)
		);
	},

	mouseover: function(event){
		this.parent.mouseover(this);
	},

	mousedown: function(event){
		this.tooltip.hideTooltip();
		this.parent.mousedown(this);
	}
});

TroubleShootingGuide = Class.create();
Object.extend(TroubleShootingGuide.prototype,  {
	initialize: function(element, data) {
		this.element = element;
		this.data = Object.extend({
			troubleshootingid: 0,
			parenttroubleshootingid: 0,
			sort: 0,
			title_en: null,
			title_fr: null,
			body_en: null,
			body_fr: null,
			language: 'en',
			expand: true
		}, (data || {}));

		this.stack = new Array();
		this.child = new Array();
		this.first = 0;

		this.element.domRCN();
		this.element.domSA({
			className: 'control'
		}).domAC(
			this.elementScroller = domCE('div').domSA({
				className: 'scroll'
			})
		).domAC(
			this.elementButton = domCE('div').domSA({
				className: 'button'
			}).domAC(
				domCE('img').domSA({
					src: '/images/icons/16x16_reset.png',
					align: 'left'
				})
			).domCTN(String.nbsp+'Restart').hide()
		);
		this.load(0, this.data.troubleshootingid);

		this.eventReset  = this.reset.bindAsEventListener(this);
		Event.observe(this.elementButton, "click", this.eventReset);
	},

	load: function(index, troubleshootingid, onload){
		onload = onload || function(){};
		this.ajax = new Ajax();
		this.ajax.url = XMLTroubleshooting+'?troubleshootingid='+troubleshootingid;
		this.ajax.caching = true;
		this.ajax.requestXML(function(response){
			if(
				response.responseJSON == undefined
				|| response.responseJSON.troubleshooting == undefined
			) return;
			this.stack[index] = response.responseJSON.troubleshooting;
			this.render();
			onload();
		}.bind(this));
	},

	reset: function(event){
		this.stack.length = 0;
		this.child.length = 0;
		this.first = 0;
		this.load(0, this.data.troubleshootingid);
		this.elementButton.hide();
	},

	render: function(){

		this.elementScroller.domRCN();

		this.stack.each(function(troubleshooting, index){
			this.elementScroller.domAC(
				this.stack[index].elementWrapper = domCE('div').domSA({
					className: 'item-wrapper'
				}).domAC(
					this.stack[index].element = domCE('div').domSA({
						className: 'item shadow'+((this.stack[index].children == undefined)?' stop':'')
					}).domAC(
						domCE('p').domSA({
							className: 'title'
						}).domCTN(lang('Step #', 'Étape #')+(index+1))
					).domAC(
						domCE('p').domSA({
							className: 'body'
						}).domCHTN(lang(this.stack[index].body_en.nl2br(), this.stack[index].body_fr.nl2br()))
					)
				)
			);

			if(this.stack[index].children != undefined){
				this.stack[index].children.child = (this.stack[index].children.child.length == undefined)
					? [this.stack[index].children.child]
					: this.stack[index].children.child ;

				this.stack[index].children.child.each(function(child, c){
					this.stack[index].element.domAC(
						element = domCE('p').domSA({
							className: 'child'+((this.child[index] == child['-id'])?' focus':'')
						}).domCHTN(lang(child.title_en, child.title_fr))

					);
					if(this.child[index] != child['-id']){
						Event.observe(element, "click", this.click.bindAsEventListener(this, index, child['-id']));
					};
				}.bind(this));
			};

			if(index == this.stack.length - 1){
				this.AnimPout = new YAHOO.util.ColorAnim(this.stack[index].element, {
					borderColor: { from: '#00cc00', to: '#aaaaaa' }
				}, 2.00, YAHOO.util.Easing.easeNone);
				this.AnimPout.onComplete.subscribe(function(){
					this.stack[index].element.style.removeProperty("border-color");
				}.bind(this));
				this.AnimPout.animate();
			};
		}.bind(this));

	},

	click: function(event, index, troubleshootingid){

		if(index < 2){
			this.elementButton.hide();
		}else{
			this.elementButton.show();
		};

		switch(index - this.first){
			case 0:
				if(this.first == 0){
					this.stack.length = 1;
					this.child.length = 1;
					this.child[index] = troubleshootingid;
					this.load((index + 1), troubleshootingid);
				}else{
					this.child[index] = troubleshootingid;
					this.elementScroller.setStyle({ marginLeft: -320 });
					this.stack[(index - 1)].elementWrapper.show();
					this.slideRight(1, function(){
						this.elementScroller.setStyle({ marginLeft: 0 });
						this.first--;
						this.stack.length--;
						this.child.length--;
						this.load((index + 1), troubleshootingid, function(){
							for(i=0;i<index-1;i++){
								this.stack[i].elementWrapper.hide();
							};
						}.bind(this));
					}.bind(this));
				};
				break;
			case 1:
				this.child[index] = troubleshootingid;
				this.load((index + 1), troubleshootingid, function(){
					for(i=0;i<index-1;i++){
						this.stack[i].elementWrapper.hide();
					};
				}.bind(this));
				break;
			case 2:
				this.stack.length = index + 1;
				this.child.length = index + 1;
				this.child[index] = troubleshootingid;
				this.load((index + 1), troubleshootingid, function(){
					for(i=0;i<index-2;i++){
						this.stack[i].elementWrapper.hide();
					};
					this.slideLeft(1, function(){
						this.stack[index - 2].elementWrapper.hide();
						this.elementScroller.setStyle({ marginLeft: 0 });
						this.first++;
					}.bind(this));
				}.bind(this));
				break;
		};
	},

	slideLeft: function(num, oncomplete){
		var num = num || 1;
		var oncomplete = oncomplete || function(){};
		this.AnimSlide = new YAHOO.util.Anim(this.elementScroller, {
			marginLeft: {
				from: 0,
				to: -(322 * num)
			}
		}, 0.5, YAHOO.util.Easing.easeOut);
		this.AnimSlide.onComplete.subscribe(oncomplete);
		this.AnimSlide.animate();
	},

	slideRight: function(num, oncomplete){
		var num = num || 1;
		var oncomplete = oncomplete || function(){};
		this.AnimSlide = new YAHOO.util.Anim(this.elementScroller, {
			marginLeft: {
				from: -(322 * num),
				to: 0
			}
		}, 0.5, YAHOO.util.Easing.easeOut);
		this.AnimSlide.onComplete.subscribe(oncomplete);
		this.AnimSlide.animate();
	}
});
