/// <reference name="MicrosoftAjax.js"/>

// Init expand/collapse panels
Sys.Application.add_load(processCollapsePanel);

var __collapsePanels = null;

function processCollapsePanel() {
	__collapsePanels = new Array();

	this.itemClick = function(source, isCollapsed) {
		if(!isCollapsed) {
			// If expand collapse all nodes
			Array.forEach(__collapsePanels, Function.createDelegate(this, function(item, index) {
				if(!item.isCollapsed && item != source) {
					item.setCollapse(true);
				}
			}));
		}
	}

	var divs = document.getElementsByTagName('table');
	Array.forEach(divs, Function.createDelegate(this, function(item, index) {
		if(Sys.UI.DomElement.containsCssClass(item, 'faqBox')) {
			var faqObj = new faqObject(item);
			Array.add(__collapsePanels, faqObj);
			
			// Toogle state handler
			faqObj.add_toogleExpand(this.itemClick);
		}
	}), this);
}

function faqObject(element) {
	this.element = element;
	this.title = null;
	this.body = null;
	this.isCollapsed = null;
	this._handlersClick = new Array();
	
	this.setCollapse = function(value) {
		this.setVisible(this.body, !value);
		this.isCollapsed = value;
		
		if(this.isCollapsed) {
			Sys.UI.DomElement.removeCssClass(this.element, 'expand')
		} else {
			Sys.UI.DomElement.addCssClass(this.element, 'expand')			
		}
	}

	this.toogleCollapse = function() {
		this.setCollapse(!this.isCollapsed);
	}
	
	this.setVisible = function(items, value) {
		Array.forEach(items, function(item, index) {
			Sys.UI.DomElement.setVisible(item, value);
		}, this);
	}
	
	this.init = function() {
		this.body = new Array();
		Array.forEach(this.element.getElementsByTagName('tr'), Function.createDelegate(this, function(item, index) {
			if(item.nodeType === 1) {
				if(Sys.UI.DomElement.containsCssClass(item, 'faqTitle')) {
					this.title = item;
				} else {
					Array.add(this.body, item);
				}
			}
		}), this);
		
		if(this.title == null) {
			this.title = this.body[0];
			Array.remove(this.body, this.title);
		}
		
		// Display
		Sys.UI.DomElement.setVisible(this.title, true);
		Sys.UI.DomElement.setVisible(this.element, true);
		
		this.setCollapse(true);
		
		// Handlers
		$addHandler(this.title, 'click', Function.createDelegate(this, function(e) {
			this.toogleCollapse();
			
			Array.forEach(this._handlersClick, Function.createDelegate(this, function(item, index) {
				item(this, this.isCollapsed);
			}));
		}));
	}
	
	this.init();
	
	// Events
	this.add_toogleExpand = function(func) {
		Array.add(this._handlersClick, Function.createDelegate(this, func));
	}
}
