/*******************************************************************************
 * Copyright (c) 2007 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
dojo.provide("cosmos.widget.Navigator");
dojo.require("dojo.widget.*");
dojo.require("dojo.event.*");
dojo.require("dojo.widget.TreeV3");
dojo.require("dojo.widget.TreeNodeV3");
dojo.require("dojo.widget.TreeBasicControllerV3");

dojo.widget.defineWidget(
	// class
	"cosmos.widget.Navigator",

	// superclass	
	dojo.widget.TreeV3,
	
	// member variables/functions
	{
		widgetClass:'cosmos:Navigator',
	    onNavSelect: function(message){
			var params= new Array();
			params['RESOURCE_CONTEXT']=message.node.object;
			params['RESOURCE_CLASS']=message.node.nodeClass;
			if (typeof(this.targetTopics) != 'undefined'){
					for (i=0;i < this.targetTopics.length;i++){
						dojo.event.topic.publish(this.targetTopics[i], params);
		 			}
 			}	    
	    },
		initWidget: function(styles){
			this.styles = styles;
			initParam = styles.getStyles()[this.widgetClass];
		    this.targetTopics = initParam.targetTopics;
		    this.handler = initParam.handler;
			//populate node
  			dojo.io.bind({    
  			    treeWidget: this,
				url: this.handler,    
				load: function(type, data, evt){
					this.treeWidget.setChildren(data);
				 },    
				 error: function(type, error){
				 	dojo.debug(error.message);
				 },				 
				mimetype: "text/json"
			});	
			dojo.debug("initalizing Navigator"  + this.id);	
		},
		postCreate: function(){
			//call superclass
			cosmos.widget.Navigator.superclass.postCreate.apply(this, arguments);
		  	dojo.event.topic.subscribe("initializeWidget", this, "initWidget");	
			
		},
		createNode:function (data) {
		    if (data.nodeClass){
				initParam = this.styles.getStyles()[data.nodeClass];
				if (initParam)
					data.title="<img src=\""+initParam.icon+"\"/>"+data.title;
		    }
			return cosmos.widget.Navigator.superclass.createNode.apply(this, [data]);			
		},		
		mixInProperties: function(args, fragment, parent){
			var controller = dojo.widget.createWidget("TreeBasicControllerV3");
			var treeSelector = dojo.widget.createWidget("TreeSelectorV3");
			this.selector = treeSelector.widgetId;
		  	dojo.event.topic.subscribe(treeSelector.eventNames.select, this, this.onNavSelect);			
			this.listeners = [controller.widgetId,treeSelector.widgetId];
			//call superclass						
			cosmos.widget.Navigator.superclass.mixInProperties.apply(this, arguments);
		}		
	}
);
