/**
 * A tree plugin for moodgets packer
 * Moodgets library: A widgets library built on mootools.
 *
 * @name PackerTreePlugin
 * @author Maurizio Conventi conventi@inwind.it http://www.moodgets.com
 * @license MIT Style License
 * @use: create a PackerTreePlugin object passing the tree as parameter.
 */
var PackerTreePlugin = new Class({
	Extends: TreePlugin,
	
	id: 'PackerTreePlugin',
	
    /**
     * Returns the tree events used by the plugin
     * @private
     */
	getTreeEvents: function(){
		return {
			beforetreecreation: this.onBeforeTreeCreationHandler.bind(this),
			treecreation: this.onTreeCreationHandler.bind(this)
		}
	},
    /**
     * @private
     */
    onBeforeTreeCreationHandler: function(){    	
    	if ($chk(this.tree)){
    		this.tree.hasTopBar= true;		
    		this.tree.hasBottomBar= true;		
    		this.tree.topBar = new Toolbar(this.tree);
    		var l_group = new Group(this.tree.topBar, {styles:{
				'width': this.tree.topBar.container.getStyle('width'),
				'text-align':'center'
				}});
			new Label(l_group).setText("Select only the widgets you need");
    	}  	     	
    },
    /**
     * @private
     */
    onTreeCreationHandler: function(){    	
    	if ($chk(this.tree)){
    		this.tree.bottomBar = new Toolbar(this.tree);
			
    		var l_group = new Group(this.tree.bottomBar, {styles:{
				'width': this.tree.bottomBar.container.getStyle('width'),
				'text-align':'center'
				}});
			this.downloadBtn = new Button(l_group);
			this.downloadBtn.addClass('customizedDownloadBtn');
			this.downloadBtn.setLabel('Download');
			this.downloadBtn.addEvent('click', this.onDownloadBtnClickHandler.bind(this));	
    	}  	     	
    },
    /**
     * @private
     */
    onDownloadBtnClickHandler: function(p_rootNode, p_nodeId){ 
		var l_checked_nodes_id = '';
		var l_check_nodes = this.tree.getElements('.constraintSelectionCheckbox');
		l_check_nodes.each(function(p_node, i){
			if (p_node.get('checked') == true){
				if (l_checked_nodes_id != '')
					l_checked_nodes_id = l_checked_nodes_id + ',';
				l_checked_nodes_id = l_checked_nodes_id + p_node.retrieve('nodeid');
			}
		});
		if (l_checked_nodes_id != ''){
			var l_params = {widgets: l_checked_nodes_id};
			this.requestOptions.data = l_params;
			this.execRequest();
		}else{
			if(!$chk(this.tree.dialog)){
				this.tree.dialog = new DialogBox(this.tree);
			}
			this.tree.dialog.info("Attention: you have to select at least one widget");			
		}
    },
    /**
     * @private
     */
	execRequest: function(){	
		document.location = this.requestOptions.url + '?widgets=' + this.requestOptions.data.widgets;
	}
});
