define([
	"dojo/_base/declare",
	"dojo/ready", 
	"dojo/_base/window", 
	"dojo/store/Memory",
	"chy/store/Json",
    "dijit/tree/ObjectStoreModel", 
	"dijit/Tree", 
	"dojo/_base/xhr",
	"chy/_base/Controllor",
	"dojo/cookie",
	"dojo/_base/json"
], function(declare, ready, window, Memory, Json, ObjectStoreModel, Tree, xhr, ctrl, cookie, jsonbase) {
	return declare("chy.widget.Davtree",[Tree], {
		//properties
		openOnClick : false,
		
		//constructor
		constructor: function(args){
			this.inherited(arguments);
			console.log("Load Davtree",args);
			declare.safeMixin(this,args);
			
			var _this = this;
			var myStore = new Memory({
				getChildren: function(object){
					var results = xhr("GET", {
						url: _this.url + object.id,
						handleAs: "json"
					}).then(function(data){
							var res;
							if (data.item){
								res= [].concat(data.item);
							} else {
								res=[];
							}
							return res;
						});
					return results;
				}
			});
			myStore.setData([{ id: this.root, name: this.root, type:'folder', children:'true'}]);
			
			this.model = new ObjectStoreModel({
				store: myStore,
				query: {id: this.root},
				mayHaveChildren : function(object){ 
					return object.children;
				}
			});		
		},
		postCreate:function(){
			this.inherited(arguments);
			ctrl.load(this.detailscall + this.content, 'explorer_right', false, null);			
			var path = new Array();
			var trueval = cookie("davtreePath"+this.root);
			if(typeof trueval == 'undefined' || trueval == ''){
				trueval = this.content.replace(this.root, '');
			} else {
				trueval = trueval.replace(this.root, '');
			}	
			var i = 0;
			while(trueval.indexOf('/') > -1) {
				i++;
				console.log('trueval =', trueval);
				console.log('path =', path);
				if(path.length == 0) {
					path[0] = this.root;
				}
				else {
					path[path.length] = path[path.length-1] + trueval.substring(0,trueval.indexOf('/')+1);
					trueval = trueval.substring(trueval.indexOf('/')+1);
				}
			}
			this.set('path',path);			
		},
		onClick: function(item, t) {
			var path = this.get('path');
			path = path.concat(item.id);
			this.set('path', path);
			t.expand();
			ctrl.load(this.detailscall + item.id, 'explorer_right', false, null);
			cookie("davtreePath"+this.root, item.id, {expires: 1});
		},
		getIconClass: function(/*dojo.store.Item*/ item, /*Boolean*/ opened){
			return (!item || this.model.mayHaveChildren(item)) ? (opened ? "dijitFolderOpened" : "dijitFolderClosed") : "dijitFolderClosed"
		}
	});
});