/*  
	File: imageSelector.js
*/

/*  
	Class: MEMOZ.galleryAlbum
*/
MEMOZ.galleryAlbum = function(initObj) {
	this.childs = [];
	if (initObj) {
		this.id = initObj.id;	
		this.allowUpload = initObj.allowUpload;	
		this.allowCreateDir = initObj.allowCreateDir;	
		this.id = initObj.id;			
		this.name = initObj.name;
		this.owner = initObj.owner;
		if (initObj.resources) {
			for (var i = 0; i < initObj.resources.length; i++) {
				if (initObj.resources[i]) {
					this.resources[i] = new MEMOZ.galleryResource(initObj.resources[i]);
				}
			}
		}
	}
}
MEMOZ.galleryAlbum.prototype = {
	type: 'album',
	id: 0,
	owner: 0,
	allowUpload: false,
	allowCreateDir: false,
	childs: [],
	resources: [],
	index: -1,
	node: null,
	name: '',
	
	/*
		int: focusedImage
		The image currently focused (used by the context-menus)
	*/
	focusedImage: 0,
	
	focusedAlbum: null,
	
	/*
		Method: setNode
		
		Parameters:
			node - TreeNode
	*/
	setNode: function(node) {
		this.node = node;
	},
	
	/*
		Method: setName
		
		Paramters:
			name - String
	*/
	setName: function(name) {
		this.name = name;
		if (this.node) {
			if (this.node.getLabelEl()) {
				this.node.getLabelEl().innerHTML = name;
			}
		}
	},
	
	deleteChildAlbum: function(id) {
		for (var i = 0; i < this.childs.length; i++) {
			if (this.childs[i]) {
				if (this.childs[i].id == id) {
					delete this.childs[i];
					return true;
				}
			}
		}
		return false;
	},
				
	/*
		Method: removeImage
		
		Paramters:
			id - image id
	*/
	removeImage: function(id) {
		var jump = false;
		for (var i = 0; i < this.resources.length; i++) {
			if (this.resources[i]) {
				if (jump) {
					this.resources[i-1] = this.resources[i];
				}
				if (this.resources[i].id == id) {
					jump = true;
				}
			}
		}
		this.resources.pop();
	}
};

/*  
	Class: MEMOZ.galleryResource
*/
MEMOZ.galleryResource = function(initObj) {
	if (initObj) {
		this.id = initObj.id;
		this.type = initObj.type;
		this.name = initObj.name;
		this.link = initObj.link;
		this.preview = initObj.preview;
	}
}
MEMOZ.galleryResource.prototype = {
	type: 'resource',
	id: 0,
	name: '',
	link: '',
	preview: ''
};


/*  
	Class: MEMOZ.imageDropTarget
*/
MEMOZ.imageDropTarget = function(el, albumObj) {
	this.albumObj = albumObj;
	this.init(el,'images');
}
YAHOO.extend(MEMOZ.imageDropTarget, YAHOO.util.DDTarget, { 
    _className: "MEMOZ.imageDropTarget"
});

/*  
	Class: MEMOZ.imageDragDrop    
    Draggable image, extending YAHOO.util
*/
MEMOZ.imageDragDrop = function(ref, imageObj) {
	YAHOO.util.DDM.mode = 0;
    this.ref = ref;
    this.imageObj = imageObj;
    this.dragDiv = imageObj.a;
    this.init(this.dragDiv, 'images');   
    this.initFrame();
};
YAHOO.extend(MEMOZ.imageDragDrop, YAHOO.util.DDProxy, {	
    _className: "MEMOZ.imageDragDrop",
    
	/*
		Method: onDrag
		Abstract method called during the onMouseMove event while dragging an object.
		
		Parameters:
    		e - <Event> the mousemove event 
	*/
	onDrag: function(e) { 
    	this.dragging = true;
		//var el = this.getEl();
        /*
        var newPos = [YAHOO.util.Event.getPageX(e), YAHOO.util.Event.getPageY(e)];
        newPos[0] = Math.max(this.minX, newPos[0] - this.startOffset[0]);
        newPos[1] = Math.max(this.minY, newPos[1] - this.startOffset[1]);
		YAHOO.util.Dom.setXY(this.getEl(),newPos);
		*/
	}, 
    
    /*
    	Method: onDragDrop
    	Abstract method called when this item is dropped on another DragDrop obj.
    	
    	Parameters:
    		e  - <Event> the mouseup event 
    		id - <String> In POINT mode, the element id this was dropped on.     		
    */
    onDragDrop: function(e, id) {
		if (!this.dragging) return;
		this.dragging = false;
		var oDD = YAHOO.util.DDM.getDDById(id);
		if (oDD._className == 'MEMOZ.imageDropTarget') {

			YAHOO.util.Dom.setStyle(id,'background','');		
			var oDD = YAHOO.util.DDM.getDDById(id);		
			var el = this.getEl(); 
			
			this.ref.moveResource(this.imageObj, oDD.albumObj);
		
		}
	},
	
	/*
		Method: onDragEnter
		Abstract method called when this element fist begins hovering over another DragDrop obj
		
		Parameters:
    		e - <Event> the mousemove event 
    		id - <String> In POINT mode, the element id this is hovering over
    */
	onDragEnter: function(e, id) {
		var oDD = YAHOO.util.DDM.getDDById(id);
		if (oDD._className == 'MEMOZ.imageDropTarget') {
			console.info('drag enter' + id);
			YAHOO.util.Dom.setStyle(id,'background','#ffffaa');
		}
		//self.rollOver(id);    	        
	},
	
	/*
		Method: onDragOut
		Abstract method called when we are no longer hovering over an element
		
		Parameters:
    		e  - <Event> the mousemove event 
    		id - <String> In POINT mode, the element id this was hovering over.
    */
	onDragOut: function(e, id) {
		var oDD = YAHOO.util.DDM.getDDById(id);
		if (oDD._className == 'MEMOZ.imageDropTarget') {
			console.info('drag out'+id);
			YAHOO.util.Dom.setStyle(id,'background','');
		}
		//self.rollOut(id);    	        
	},
	
	
	/*
		Method: endDrag
		Fired when we are done dragging the object
		
		Parameters:
	    	e - <Event> the mouseup event 
	*/
	endDrag: function(e) {
		/*
		if (self.currentlyHighlightedFolder != null) {
			YAHOO.util.Dom.removeClass(self.currentlyHighlightedFolder,'schoolclassSelected');
			self.currentlyHighlightedFolder = null;
		}*/
	},
    
    /*
    	Method: onInvalidDrop
    	Abstract method called when this item is dropped on an area with no drop target
    	
    	Parameters:
    		e - <Event> the mouseup event     	
    */
    onInvalidDrop: function(e) {
    	var self = this;
    	console.warn('Invalid drop target');
    	/*
		// return to the start position 
		// Dom.setXY(this.getEl(), startPos); 
		
		// Animating the move is more intesting 
		new YAHOO.util.Motion(  
			this.dragDiv, 
			{ points: { to: this.startPanelPos } },  
			0.3,  
			YAHOO.util.Easing.easeOut  
		).animate();  
		*/
   	}
   	
});


/*  
	Class: MEMOZ.imageSelector    
    The imageSelector-class is an interface to let users select images from the LifeType-gallery. 
    It can display a treeview of the albums available and thumbnails for the images in each album. 
*/

/* 
    Constructor: MEMOZ.imageSelector 
    Initializes the object.
*/
MEMOZ.imageSelector = function() { 
	MEMOZ.log('creating customEvent: onAlbumSelected');
	this.onAlbumSelected = new YAHOO.util.CustomEvent("onAlbumSelected", this); 
}

YAHOO.extend(MEMOZ.imageSelector, MEMOZ.base, {

    _className: "MEMOZ.imageSelector",

    /* 
    	strings: Lokalisering
    	labelAddGalleryAlbumPromt 	- Navn på det nye albumet:
    	labelSelectAlbum 			- Velg album:
    	labelMyImages 				- Denne memozen
    	labelClassImages		 	- Klassens bilder
    	labelImageArchive	 		- Bildearkiv
    */
    labelSelectAlbum: 'Velg album:',
	labelMyImages: 'Denne memozen',
	labelClassImages: 'Klassens bilder',
	labelImageArchive: 'Bildearkiv',
	
	/*
		Event: onAlbumSelected
		Fired when a new album is selected in the treeview or by other means.
	*/
	onAlbumSelected: null,
	
	/*
		Var: imageContextMenu
		Context-menu for thumbnails. Instance of YAHOO.widget.ContextMenu 
	*/
	imageContextMenu: null,

	/*
		Var: albumContextMenu
		Context-menu for albums. Instance of YAHOO.widget.ContextMenu 
	*/
	albumContextMenu: null,
    
    /* 
    	var: treeData
    	Cache containing the currently fetched gallery albums and resources.
    */
    treeData: null,

    dropDownDiv: null,
    dropDownSelectId: '',
    fileSubmitId: '',
    inputDirId: '',
    imagePaneDiv: null,
    uploadDiv: null,
    activityDiv: null,
    errorDiv: null,
    selectedDir: null,
    selectedImage: null,
    memozId: -1,
    uniqueId: -1,
    btnUpload: null,
    btnNewAlbum: null,
    
    /* 
    	string: rootDir 
    	If set, the treeview will show the subdirs of this dir only.
    */
    rootDir: '',
    selectIndexCache: [],

    onSelect: null,

    /* ______________________ PRIVATE FUNCTIONS ____________________________ */

    dummyElemFilter: function(e) {
        return true;
    },
	
	/* 
		Method: getImageByUrl
		Incrementive function that lookus up an returns an image object from an image url.
		
		Parameters:
			url - <string> The full image url
			dir - <object> (optional) The current dir to search through
		Returns:
			object or false if not found
	*/
    getImageByUrl: function(url, dir) {
    	if (!dir) dir = this.treeData;
        for (var i = 0; i < dir.childs.length; i++) {
       		if (dir.childs[i]) {
				var img = this.getImageByUrl(url, dir.childs[i]);
				if (img != false) return img;
    	    }
   		}
   		for (var i = 0; i < dir.resources.length; i++) {
    		if (dir.resources[i]) {
    	   		if (dir.childs[i].link == url) {
        	    	dir.childs[i].dir = dir;
            	    return dir.childs[i];                	
                }
            }
        }
        return false;
    },

	/* 
		Method: getImageById
		Incrementive function that lookus up an returns an image object from an image id.
		
		Parameters:
			id - <int> The image id
			dir - <object> (optional) The current dir to search through
		
		Returns:
			object or false if not found
	*/
    getImageById: function(id, dir) {
    	if (!dir) dir = this.treeData;
        for (var i = 0; i < dir.childs.length; i++) {
            if (dir.childs[i]) {
				var img = this.getImageById(id, dir.childs[i]);
				if (img !== false) return img;				
			}
        }
        for (var i = 0; i < dir.resources.length; i++) {
            if (dir.resources[i]) {
            	if (dir.resources[i].id == id) {
					dir.resources[i].dir = dir;
					return dir.resources[i];
				}
			}        
        }
        return false;
    },
    
    /* 
		Method: getAlbumById
		Incrementive function that lookus up an returns an album object from an album id.
		Example:
			this.getAlbumById(albumId)   
		
		Parameters:
			id - <int> The album id
			dir - <object> (optional) The current dir to search through
		
		Returns:
			object or false if not found
	*/
    getAlbumById: function(id, dir) {
    	if (!dir) dir = this.treeData;
        for (var i = 0; i < dir.childs.length; i++) {
            if (dir.childs[i]) {
				var r = this.getAlbumById(id, dir.childs[i]);
				if (r !== false) return r;
				if (dir.childs[i].id == id) {
					return dir.childs[i];
				}
			}
        }
        return false;
    },
    
    /* 
		Method: getParentAlbum
		Incrementive function that lookus up an returns an album object from an album id.
		
		Example:
			this.getParentAlbum(albumId)   
		
		Parameters:
			id - <int> The album id
			dir - <object> (optional) The current dir to search through
		
		Returns:
			object or false if not found
	*/
    getParentAlbum: function(id, dir) {
    	if (!dir) dir = this.treeData;
        for (var i = 0; i < dir.childs.length; i++) {
            if (dir.childs[i]) {
				var r = this.getParentAlbum(id, dir.childs[i]);
				if (r !== false) return r;
				if (dir.childs[i].id == id) {
					return dir;
				}
			}
        }
        return false;
    },
    
    /* 
		Method: getAlbumFromLabelAnchor
		Incrementive function that lookus up an returns an album object from an label anchor id.
		Example:
			this.getAlbumFromLabelAnchorId('ygtvlabelel1')   
		
		Parameters:
			id - <int> The album id
			dir - <object> (optional) The current dir to search through
		
		Returns:
			object or false if not found
	*/
    getAlbumFromLabelAnchorId: function(id, dir) {
    	if (!dir) dir = this.treeData;
        for (var i = 0; i < dir.childs.length; i++) {
            if (dir.childs[i]) {
				var r = this.getAlbumFromLabelAnchorId(id, dir.childs[i]);
				if (r !== false) return r;
				if (dir.childs[i].node.getLabelEl().id == id) {
					return dir.childs[i];
				}
			}
        }
        return false;
    },
    
    /* 
		Method: getImagePath
		Incrementive function that lookus up an returns an image object from an image id.
		
		Parameters:
			id - <int> The image id
			dir - <object> (optional) The current dir to search through
		
		Returns:
			object or false if not found
	*/
    getAlbumPath: function(id) {
		var scanDir = function(id, dir, path) {
			path.push(dir);
			for (var i = 0; i < dir.childs.length; i++) {
				if (dir.childs[i]) {
					if (dir.childs[i].id == id) {
						path.push(dir.childs[i]);
						return path;
					}
					var img = scanDir(id,dir.childs[i],path);
					if (img !== false) return img;				
				}
			}
			path.pop();
			return false;
		};
		var res = scanDir(id, this.treeData, []);
		var str = '';
		for (var i = 1; i < res.length; i++) {
			str += '<strong style="color:#888;">'+res[i].name+'</strong>: ';
		}
        return str;
    },

    /*
    	Method: getAlbumByNode
    	
    	Parameters:
    		node: Tree node
    	
    	Returns:
    		Album data object
    */
	getAlbumByNode: function(node) {
		var path = [];
		var tmp = node;
		while (tmp.depth >= 0) {
			path.push(tmp.index);
			tmp = tmp.parent;
		}
		tmp = this.treeData;
		for (var i = path.length-1; i >= 0; i--) tmp = tmp.childs[path[i]];
		return tmp;
	},

    /* _____________________ GETTERS AND SETTERS ___________________________ */

    getSelectedImage: function() {
        return this.selectedImage;
    },

    setUniqueId: function(uniqueId) {
        this.uniqueId = uniqueId;
        this.dropDownDiv = $('imgSel'+this.uniqueId+'DropDown');
        if (!this.dropDownDiv) { console.error('[imageSelector.setUniqueId] "imgSel'+this.uniqueId+'DropDown" not found!'); }
        this.imagePaneDiv = $('imgSel'+this.uniqueId+'ImgPane');
        if (!this.imagePaneDiv) { console.error('[imageSelector.setUniqueId] "imgSel'+this.uniqueId+'ImgPane" not found!'); }
        this.uploadDiv = $('imgSel'+this.uniqueId+'Upload');
        if (!this.uploadDiv) { console.error('[imageSelector.setUniqueId] "imgSel'+this.uniqueId+'Upload" not found!'); }
        this.activityDiv = $('imgSel'+this.uniqueId+'Activity');
        if (!this.activityDiv) { console.error('[imageSelector.setUniqueId] "imgSel'+this.uniqueId+'Activity" not found!'); }
    },

    setMemoz: function(memozId) {
        this.memozId = memozId;
    },
    
    setRoot: function(root) {
    	this.rootDir = root;
    },

    setSelectedImage: function(selectedImage) {
        this.selectedImage = selectedImage;
    },

    setErrorDiv: function(errorDiv) {
        this.errorDiv = errorDiv;
    },

    /* _________________________ Draw selector _____________________________ */

	/*
		Method: draw
		Called on init. Will call <buildTree> and then <fetchSelectedImagePath> if an selected
		image has been set. Draws the upload form and context-menus.
	*/
    draw: function() {
        
        var me = this;
        
        /* Make file upload elems */
        this.fileSubmitId =  'imgSelUploadBtn'+this.uniqueId;
        this.inputDirId =  'imgSel'+this.uniqueId+'DirId';  
        this.inputOwnerId =  'imgSel'+this.uniqueId+'OwnerId';  
        var selectedDirId = (this.selectedDir != null) ? this.selectedDir.id : -1;  
        this.uploadDiv.innerHTML = '<form id="imgSel'+this.uniqueId+'Form" onsubmit="return false;" enctype="multipart/form-data">'+
        	'<strong style="display:block;padding-top:10px;color:#666">Last opp nytt bilde:</strong> ' +
            '<input type="hidden" name="ownerId" id="'+this.inputOwnerId+'" value="'+this.memozId+'">' +
            '<input type="hidden" name="albumId" id="'+this.inputDirId+'" value="'+selectedDirId+'">' +
            '<input type="file" name="uploadedFile" id="imgSel'+this.uniqueId+'uploadinp" size="10"> ' +
            '<input name="uploadBtn" id="'+this.fileSubmitId+'" type="button" value="Last opp" class="button">'+
            '</form>';
        
        // Upload button:
        YAHOO.util.Event.onAvailable(this.fileSubmitId, function() {
        	me.btnUpload = new YAHOO.widget.Button(me.fileSubmitId, {
                onclick: { fn: me.upload, scope: me }
            })
        });
        
        // New album button:
        YAHOO.util.Event.onAvailable('btnAddAlbum', function() {
        	me.btnNewAlbum = new YAHOO.widget.Button('btnAddAlbum', {
                onclick: { fn: me.addGalleryAlbum, scope: me }
            })
        });

       	YAHOO.util.Dom.setStyle('btnNewSubAlbum'+this.uniqueId, 'visibility','hidden');       		
       	YAHOO.util.Dom.setStyle(this.uploadDiv, 'visibility','hidden');
        
        this.buildTree();
        
        if (this.selectedImage) {
        	this.fetchSelectedImagePath();
        }
        
		// Create the image context menu			
		this.imageContextMenu = new YAHOO.widget.ContextMenu('imgSel'+this.uniqueId+'ImageMenu', { 
			trigger: this.imagePaneDiv, 
			zIndex: 954,
			lazyload: true 
		});                     
		this.imageContextMenu.triggerContextMenuEvent.subscribe(function(p_oEvent, p_oMenu) { 
			me.onTriggerImageContextMenu(p_oEvent, p_oMenu, this); 
		});
		this.imageContextMenu.hideEvent.subscribe(function(p_sType, p_aArgs) { 
			me.onImageContextMenuHide(p_sType, p_aArgs, this); 
		}); 
		this.imageContextMenu.addItems([
			{ text: "Info", onclick: { fn: me.viewImageInfo, scope: me } },
			{ text: "Slett", onclick: { fn: me.confirmDeleteImage, scope: me } }
		]);
		this.imageContextMenu.render(document.body);
		
		var dlgDiv = document.createElement('div');
        dlgDiv.id = 'dlgImageInfo'+this.uniqueId;
        dlgDiv.innerHTML = ' '+
			'<div class="hd">Bildeinfo</div> '+
			'<div class="bd"> '+
			'	<div id="dlgImageInfoBox'+this.uniqueId+'"></div>' +
			'</div>';
		document.body.appendChild(dlgDiv);
		YAHOO.util.Dom.setStyle(dlgDiv,'visibility','hidden');
        YAHOO.util.Event.onContentReady(dlgDiv.id, function() {
			me.dlgImageInfo = new MEMOZ.dialog(dlgDiv.id);
		});
			
    },
    
    viewImageInfo: function() {
    	this.dlgImageInfo.show();
    	$('dlgImageInfoBox'+this.uniqueId).innerHTML = "<p align='center'><img src='"+this.imageDir+"/indicator8.gif'></p>";
    	this.ajaxReq('getResourceInfo','gotImageInfo', { resId: this.focusedImage });
    },
    
    gotImageInfo: function(json) {
    	if (json.error == 0) {
    		$('dlgImageInfoBox'+this.uniqueId).innerHTML = json.code;
    	} else {
	    	$('dlgImageInfoBox'+this.uniqueId).innerHTML = json.error;
    	}    	
    },
    
    /*
    	Method: fetchSelectedImagePath
    	Fetches the path to the selected image. We call this on init to be able to expand the 
    	necessary tree nodes so we can show the path to the selected image.
    	Example:
    		We send imageId=99 to the server. The image with id 99 is contained in a folder named 
    		"Diverse" in "Klassens bilder". The return from server might then look like this:
    	{"action":"fetchImagePath", "error":0, "rootFolder": "c", "path":[
    		{"error":0,"id":"c","nodes":[
    			{"id":36,"name":"Diverse","owner":31,"index":-1,"allowUpload":true,"childs":[]}
    		],"resources":[]},
			{"error":0,"id":36,"nodes":[],"resources":[
				{"type":"image","id":97,"name":"jupiter1280.jpg","link":"http:\/\/test.ndla.no\/piczo\/gallery\/31\/jupiter1280.jpg","preview":"http:\/\/test.ndla.no\/piczo\/gallery\/31\/previews\/jupiter1280.jpg"},
				{"type":"image","id":99,"name":"Instrumental_Temperature_Record.png","link":"http:\/\/test.ndla.no\/piczo\/gallery\/31\/Instrumental_Temperature_Record.png","preview":"http:\/\/test.ndla.no\/piczo\/gallery\/31\/previews\/Instrumental_Temperature_Record.png"}
			]}
		],}
    */
    fetchSelectedImagePath: function() {
		this.setWorking(true);
    	this.ajaxReq('getImagePath','fetchedSelectedImagePath', { 
    		memozId: this.memozId,
    		imageId: this.selectedImage.id 
    	});
    },
    
    /*
    	Method: fetchedSelectedImagePath
    	Callback for the request made from <fetchSelectedImagePath>. Will call <onSelectAlbum>.	    	
    */
    fetchedSelectedImagePath: function(json) {
		this.setWorking(false);
    	if (json.error) {
    		MEMOZ.log(json.error,'error');
    	} else {
    		// parse result
    		var root = this.tree.getRoot();
    		var node = this.getTreeChild(this.treeData, json.rootFolder);
    		if (!node) {
    			MEMOZ.log('The specified rootFolder '+json.rootFolder+' does not exist anymore, or you don\'t have permissions to it.','error');
    			return false;
    		}
    		var dat = this.treeData.childs[node.index];
    		for (var i = 0; i < json.path.length; i++) {
				dat.childs = [];
				for (var j = 0; j < json.path[i].nodes.length; j++) {
					var tempNode = new YAHOO.widget.TextNode(json.path[i].nodes[j].name, node, false); 					
					dat.childs[tempNode.index] = new MEMOZ.galleryAlbum(json.path[i].nodes[j]);
					dat.childs[tempNode.index].setNode(tempNode);
					
					if (json.path[i].nodes[j].allowUpload) {			
						YAHOO.util.Event.onAvailable(tempNode.labelElId, this.makeLabelDropTarget, {
							node: tempNode,
							album: dat.childs[tempNode.index]
						});
					}
					
				}
				dat.resources = json.path[i].resources;
				node.loadComplete();
				node.expand();
    		 	if (i < json.path.length-1) {
    		 		node = this.getTreeChild(dat, json.path[i+1].id);
					if (!node) {
						MEMOZ.log('The folder with id '+json.path[i+1].id+' at pos '+(i+1)+' (total path length: '+ json.path.length+') does not exist anymore, or you don\'t have permissions to it.','error');
						return false;
					}
    		 		dat = dat.childs[node.index];
    		 	}
	    	}
			this.onSelectAlbum(dat);
		}
	},
	
	/* 
		Method: getTreeChild
		Finds a child with the given album id
		
		Parameters:
			parentNode	- The treeData object (NOT treeNode object) to search within. Search is NOT recursive
			id			- The node's album id (NOT index). :)
		
		Returns:
			The album's TreeNode or false if not found
	*/
	getTreeChild: function(parentNode, id) {
		for (var i = 0; i < parentNode.childs.length; i++) {
			if (parentNode.childs[i]) {
				if (parentNode.childs[i].id == id) return parentNode.childs[i].node;
			}
		}
		return false;
	},
    
    /*
    	Method: onShow
    	Called when the dialog is shown.
    */
    onShow: function() {
        YAHOO.util.Dom.setStyle(this.imagePaneDiv, 'display','block'); // Fix for Firefox-bug       		
		if (this.selectedDir != null) {
			if (this.selectedDir.allowCreateDir) {
				YAHOO.util.Dom.setStyle('btnNewSubAlbum'+this.uniqueId, 'visibility','visible');       		
				YAHOO.util.Dom.setStyle(this.uploadDiv, 'visibility','visible');
			} else {
				YAHOO.util.Dom.setStyle('btnNewSubAlbum'+this.uniqueId, 'visibility','hidden');       		
				YAHOO.util.Dom.setStyle(this.uploadDiv, 'visibility','hidden');
			}
		}
	},
    
    /*
    	Method: onHide
    	Called when the dialog is hidden.
    */
    onHide: function() {
    	YAHOO.util.Dom.setStyle('btnNewSubAlbum'+this.uniqueId, 'visibility','');       		
	    YAHOO.util.Dom.setStyle(this.uploadDiv, 'visibility','');
    	YAHOO.util.Dom.setStyle(this.imagePaneDiv, 'display','none'); // Fix for Firefox-bug       		
	},
	    
    /*
    	Method: buildTree
    	Creates an YAHOO.widget.TreeView-instance and draws it. If <rootDir> != '', it will
    	call <loadRootNode>.
    */
    buildTree: function() { 
		var me = this;
    	this.tree = new YAHOO.widget.TreeView('imgSel'+this.uniqueId+'Tree');
		this.tree.setDynamicLoad(function(node, fnLoadComplete) { me.loadNodeData(node); }, 1); 
		var root = this.tree.getRoot(); 
		this.treeData = new MEMOZ.galleryAlbum();		
		if (this.rootDir == '') {
			
			var initData = [
				{ id: 'm', allowUpload: false, allowCreateDir: true, index: -1, childs: [], resources: [], node: null, name: this.labelMyImages }
			];
			var groups = this.getCtrlPanel().memozGroups;
			console.log(groups);
			for (var i = 0; i < groups.length; i++) {
				initData.push(
					{ id: 'group:'+groups[i].id, allowUpload: false, allowCreateDir: true, index: -1, childs: [], resources: [], node: null, name: groups[i].name }
				);
			}
			initData.push(				
				{ id: 'a', allowUpload: false, allowCreateDir: true, index: -1, childs: [], resources: [], node: null, name: this.labelImageArchive }
			);
			console.log(initData);
			for (var i=0, j=initData.length; i<j; i++) { 
				var tempNode = new YAHOO.widget.TextNode(initData[i].name, root, false); 
				var newAlbum = this.treeData.childs[tempNode.index] = new MEMOZ.galleryAlbum(initData[i]);
				newAlbum.setNode(tempNode);
			} 
		}
		this.tree.draw();
		this.tree.subscribe('labelClick',function(node) { me.treeLabelClick(node); });

		// Create the album context menu			
		YAHOO.util.Event.onAvailable('imgSel'+this.uniqueId+'Tree', function() {
			me.albumContextMenu = new YAHOO.widget.ContextMenu('imgSel'+me.uniqueId+'AlbumMenu', { 
				trigger: this, 
				zIndex: 956,
				lazyload: true 
			});
			me.albumContextMenu.triggerContextMenuEvent.subscribe(function(p_oEvent, p_oMenu) { 
				me.onTriggerAlbumContextMenu(p_oEvent, p_oMenu, this); 
			});
			me.albumContextMenu.hideEvent.subscribe(function(p_sType, p_aArgs) { 
				me.onAlbumContextMenuHide(p_sType, p_aArgs, this); 
			}); 
			me.albumContextMenu.addItems([
				{ text: "Gi nytt navn", onclick: { fn: me.renameAlbumPrompt, scope: me } },
				{ text: "Slett", onclick: { fn: me.confirmDeleteAlbum, scope: me } }
			]);
			me.albumContextMenu.render(document.body);	
		});
		
		if (this.rootDir != '') {
			this.loadRootNode();
		}
	},
	
    /*
    	Method: destroyTree
    	Destroys the tree
    */
	destroyTree: function() {
		this.tree.unsubscribe('labelClick');
		delete this.tree;
	},
		
	/*
    	Method: loadNodeData
    	Called from the Treeview on album-click if the album sub-albums haven't been cached already.
    	We'll create child nodes based on what we get back when we send the album id to our 
    	Lifetype-connector.
    	
    	Paramters:
    		node - TreeNode
    		fnLoadComplete - Load complete function
    */
	loadNodeData: function(node, fnLoadComplete) {
		this.tree.removeChildren(node);
		var dataObj = this.getAlbumByNode(node);
		var uniqueId = dataObj.id;
		this.setWorking(true);
		this.ajaxReq('getGalleryNodeData', 'gotNodeData', {
			memozId: this.memozId,
			albumId: uniqueId
		}, {node: node, path: dataObj});
	},
	
   /*
    	Method: gotNodeData
    	Callback for the request made from <loadNodeData>. Will call <onSelectAlbum>.
    	
    	Paramters:
    		json - <object> Server response
    		obj - object containing info about current node and pos
    */
	gotNodeData: function(json, obj) {		
		this.setWorking(false);
		obj.path.childs = [];
		for (var i = 0; i < json.nodes.length; i++) {
			var tempNode = new YAHOO.widget.TextNode(json.nodes[i].name, obj.node, false);		
			var el = tempNode.getElId();
			obj.path.childs[tempNode.index] = new MEMOZ.galleryAlbum(json.nodes[i]);
			obj.path.childs[tempNode.index].setNode(tempNode);
			var albumObj = obj.path.childs[tempNode.index];
			if (json.nodes[i].allowUpload) {
				YAHOO.util.Event.onAvailable(tempNode.labelElId, this.makeLabelDropTarget, {
					node: tempNode,
					album: albumObj
				});
			}
		}
		obj.path.resources = json.resources;
		obj.node.loadComplete();
		this.onSelectAlbum(obj.path);
	},
	
	/*
    	Method: loadRootNode
    	If a root dir is specified, we must load the contents of it.
    */
	loadRootNode: function() {
		this.setWorking(true);
		this.ajaxReq('getGalleryNodeData', 'gotRootNode', {
			memozId: this.memozId,
			albumId: this.rootDir
		});
	},
	
	/*
    	Method: gotRootNode
    	Callback for the request made from <loadRootNode>.
    	
    	Paramters:
    		json - <object> Server response
    */
	gotRootNode: function(json) {
		this.setWorking(false);
		var root = this.tree.getRoot(); 
		for (var i = 0; i < json.nodes.length; i++) {
			var tempNode = new YAHOO.widget.TextNode(json.nodes[i].name, root, false); 
			this.treeData.childs[tempNode.index] = new MEMOZ.galleryAlbum(json.nodes[i]);
			this.treeData.childs[tempNode.index].setNode(tempNode);
			var albumObj = this.treeData.childs[tempNode.index];
			if (json.nodes[i].allowUpload) {
				YAHOO.util.Event.onAvailable(tempNode.labelElId, this.makeLabelDropTarget, {
					node: tempNode,
					album: albumObj
				});
			}
		}
		root.loadComplete();
		//this.onSelectAlbum(this.treeData);
	},
	
	/*
		Method: makeLabelDropTarget
		Makes a TreeView-label a DropTarget (called when the label is available in the DOM)
	*/
	makeLabelDropTarget: function(obj) {
		var el = obj.node.getLabelEl();
		obj.album.dropTarget = new MEMOZ.imageDropTarget(el, obj.album);					
	},
	
	/*
    	Method: treeLabelClick
    	Called on TreeView-click. Will call <onSelectAlbum> if the album-contents already
    	have been cached.
    	
    	Paramters:
    		node - TreeView Node.
    */
	treeLabelClick: function(node) {		
		if (node.dynamicLoadComplete) {
			var albumObj = this.getAlbumByNode(node);
			this.onSelectAlbum(albumObj);
		}		
	},
	
	/* 
		Method: onSelectAlbum
		Called when an album is clicked.
		
		Parameters:
			dataObj - <object> (optional) The selected album as a <MEMOZ.galleryAlbum>-object.
								If no value given, the current selected album will be unselected.
	*/
	onSelectAlbum: function(dataObj) {
		var self = this;
		var curObj;  

        /**** Remove old elements ****/
        if (this.selectedDir) {
        	if (this.selectedDir.resources.length < 1) {
        		var children = YAHOO.util.Dom.getChildren(this.imagePaneDiv);
				for (var i = 0; i < children.length; i++) {
					this.imagePaneDiv.removeChild(children[i]);
				}        		
        	}
			for (var i = 0; i < this.selectedDir.resources.length; i++) {
				curObj = this.selectedDir.resources[i];
	            if (curObj.type == 'image') {
					if ($(curObj.a)) {
						this.imagePaneDiv.removeChild(curObj.a);
						YAHOO.util.Event.purgeElement(curObj.a);
					}
				}
			}
	       	YAHOO.util.Dom.removeClass(this.selectedDir.node.getLabelEl(), 'albumSelected');       		
		}
		
		if (!dataObj) {
			this.selectedDir = null;
	        this.dropDownDiv.innerHTML = '&nbsp;';
       		YAHOO.util.Dom.setStyle('btnNewSubAlbum'+this.uniqueId, 'visibility','hidden');       		
       		YAHOO.util.Dom.setStyle(this.uploadDiv, 'visibility','hidden');
			return;
		}
		
		/**** Change properties ****/
        this.selectedDir = dataObj;  
        if (this.selectedDir.node.parent) {
        	if (!this.selectedDir.node.parent.expanded) {
        		this.selectedDir.node.parent.expand();
        	}
        }
        this.dropDownDiv.innerHTML = this.getAlbumPath(dataObj.id);
        MEMOZ.log('owner: '+ this.selectedDir.owner);
        $(this.inputOwnerId).value = this.selectedDir.owner;
        $(this.inputDirId).value = this.selectedDir.id;
       	if (this.selectedDir.allowUpload) {
       		YAHOO.util.Dom.setStyle(this.uploadDiv, 'visibility','visible');       	
       	} else {
       		YAHOO.util.Dom.setStyle(this.uploadDiv, 'visibility','hidden');       	
       	}
       	if (this.selectedDir.allowCreateDir) {
       		YAHOO.util.Dom.setStyle('btnNewSubAlbum'+this.uniqueId, 'visibility','visible');       		
       	} else {
       		YAHOO.util.Dom.setStyle('btnNewSubAlbum'+this.uniqueId, 'visibility','hidden');       		
		}
	    YAHOO.util.Dom.addClass(this.selectedDir.node.getLabelEl(), 'albumSelected');       		
		
		
        /**** Add new elements ****/
        if (dataObj.resources.length < 1) {
			var tmpMsg = document.createElement('div');
			tmpMsg.innerHTML = '<em style="display:block;padding:20px;color:#aaa;">Denne mappen inneholder ingen bilder</em>';
			this.imagePaneDiv.appendChild(tmpMsg);
        }
		for (var i = 0; i < dataObj.resources.length; i++) {		
            curObj = dataObj.resources[i];
            if (curObj.type == 'image') {
                curObj.a = document.createElement('a');
                curObj.a.id = 'previewImgLink'+this.uniqueId+'-'+curObj.id;
                curObj.a.innerHTML = '<img src="'+curObj.preview+'" alt="'+curObj.name+'" style="width:120px; height:120px;background:#eee;" />';
                this.imagePaneDiv.appendChild(curObj.a);

				YAHOO.util.Event.addListener(curObj.a, "click", function(e) { 
					self.onSelectImage(this.id);
				} );				
				if (this.selectedImage != null) {
					if (this.selectedImage.id == curObj.id) {
						this.onSelectImage('previewImgLink'+this.uniqueId+'-'+this.selectedImage.id);
					}
				}
				curObj.dd = new MEMOZ.imageDragDrop(this, curObj);
            }
        }
        this.onAlbumSelected.fire(this.selectedDir);
    },
      
	/* 
		Method: onSelectImage
		Called when an image-thumbnail is clicked.
		
		Parameters:
			imageId - <int> The id of the clicked image.
	*/
    onSelectImage: function(imageId) {
        //console.log('selectImage: '+imageId);
        var imgA = imageId.split('-');
        var imgId = imgA[1];
        //console.log('imgId: '+imgId);
        var dir = this.selectedDir;
        for (var i = 0; i < dir.resources.length; i++) {
            if (dir.resources[i].id == imgId) {
                var imgObj = dir.resources[i];
                break;
            }
        }
       
        this.selectedImage = imgObj;
        
        var imgLinks = YAHOO.util.Dom.getElementsBy(this.dummyElemFilter, 'a', this.imagePaneDiv);
        for (var i = 0; i < imgLinks.length; i++) {
            YAHOO.util.Dom.removeClass(imgLinks[i], 'bgImgSelected');
        }
        YAHOO.util.Dom.addClass('previewImgLink'+this.uniqueId+'-'+imgObj.id, 'bgImgSelected');
        if (this.onSelect) {
            this.onSelect();
        }
    },

	/*
	   +------------------------------------------------------------------------------------------+
	   | Section: Context menu events		     											 	  |
	   +------------------------------------------------------------------------------------------+
	*/    
	
	/*
		 Method: getTextNodeFromEventTarget
		 Utility method used to return the parent A element of the actual node that fired 
		 the "contextmenu" event
	*/
	getTextNodeFromEventTarget: function(p_oTarget) {
		if (p_oTarget.tagName.toUpperCase() == "A" && YAHOO.util.Dom.hasClass(p_oTarget, "ygtvlabel")) {
			return p_oTarget;
		}
		return false;
	},

	/*
		 Method: getAnchorElemFromEventTarget
		 Returns a TextNode instance that corresponds to the DOM element whose "contextmenu" event
		 triggered the display of the context menu.
	*/
	getAnchorElemFromEventTarget: function(p_oNode) {
		if (p_oNode.tagName.toLowerCase() == "div") {		
			return false;
		} else if (p_oNode.tagName.toLowerCase() == "a") {		
			return p_oNode;
		} else {
			/*
				 If the target of the event was a child of a A, 
				 get the parent A element
			*/
			do {
				if (p_oNode.tagName.toLowerCase() == "a") {
					return p_oNode;
					break;				
				}
			} while ((p_oNode = p_oNode.parentNode));
		}
	},	
	
	/*
		Method: onTriggerAlbumContextMenu
		"contextmenu" event handler for the element(s) that triggered the display of the context menu	
	*/
	onTriggerAlbumContextMenu: function(p_oEvent, p_oMenu, ref) {
		var oTextNode = this.getTextNodeFromEventTarget(ref.contextEventTarget);
		if (oTextNode) {
			this.focusedAlbum = this.getAlbumFromLabelAnchorId(oTextNode.id);
			oTextNode.focus();
		} else {
        	ref.cancel();
        }
	},

	/*
		Method: onAlbumContextMenuHide
		CustomEvent fired after the menu is hidden. We blur the EventTarget if an image.
	*/
	onAlbumContextMenuHide: function(p_sType, p_aArgs, ref) {
		var oA = this.getAnchorElemFromEventTarget(ref.contextEventTarget);		
		if (oA) oA.blur();
		this.focusedAlbum = null;
	},
	

	/*
		Method: onTriggerImageContextMenu
		"contextmenu" event handler for the element(s) that triggered the display of the context menu.
		If the EventTarget isn't an image, we cancel the menu.
	*/
	onTriggerImageContextMenu: function(p_oEvent, p_oMenu, ref) {
		var oA = this.getAnchorElemFromEventTarget(ref.contextEventTarget);
		if (!oA) {
			MEMOZ.log('No image clicked. We should not show the context menu!');
			ref.cancel();
		} else {
			this.focusedImage = parseInt(oA.id.substr(oA.id.indexOf('-')+1));
			oA.focus();
		}
	},

	/*
		Method: onImageContextMenuHide
		CustomEvent fired after the menu is hidden. We blur the EventTarget if an image.
	*/
	onImageContextMenuHide: function(p_sType, p_aArgs, ref) {
		var oA = this.getAnchorElemFromEventTarget(ref.contextEventTarget);		
		if (oA) oA.blur();
		this.focusedImage = 0;
	},


	/*
	   +------------------------------------------------------------------------------------------+
	   | Section: Utility functions for server communication								      |
	   +------------------------------------------------------------------------------------------+
	*/

	/*
		Method: setWorking
		Will toggle the activity indicator and lock/unlock the controls. Used by <upload>,
		<addGalleryAlbum> and <deleteImage>.
		
		Parameters:
			isWorking - <bool> True to show activity indicator, false to hide it.
	*/
	setWorking: function(isWorking) {
		this.isWorking = isWorking;
		if (isWorking) {
			this.tree.locked = true;
			this.errorMessage('');
	        YAHOO.util.Dom.setStyle(this.uploadDiv,'visibility','hidden');
    	    YAHOO.util.Dom.setStyle(this.activityDiv,'visibility','visible');
    	} else {
			this.tree.locked = false;
	        YAHOO.util.Dom.setStyle(this.uploadDiv,'visibility','visible');
    	    YAHOO.util.Dom.setStyle(this.activityDiv,'visibility','hidden');    	
    	}
	},
	
	/*
		Method: errorMessage
		Will output the error message if an errorDiv has been assigned to the imageSelector.
		
		Parameters:
			str - <string> The message
	*/
	errorMessage: function(str) {
		if (this.errorDiv) {
			this.errorDiv.innerHTML = str;
		}	
	},

	/*
	   +------------------------------------------------------------------------------------------+
	   | Section: Moving gallery resource     												      |
	   +------------------------------------------------------------------------------------------+
	*/
        
    /*
    	Method: moveResource 
    	
    	Parameters:
			imageObj - <object> The image to move.
			albumObj - <object> The album to move to.
	*/
    moveResource: function(imageObj, albumObj) {
		this.setWorking(true);
    	this.ajaxReq('moveResource','resourceMoved', { 
    		memozId: this.memozId, 
    		resourceId: imageObj.id,
    		albumId: albumObj.id,
    		albumOwner: albumObj.owner    		
    	});    	
    },
    
	/* 
		Method: resourceMoved
		Callback function for the request made from <moveResource>
		
		Parameters:
			json - <object> Return from server
	*/
    resourceMoved: function(json) {
    	var me = this;
		this.setWorking(false);
    	if (json.error == 0) {
    		var oldAlbum = this.getImageById(json.resId).dir;
    		var newAlbum = this.getAlbumById(json.albumId);		    		
    		//this.onSelectAlbum(newAlbum);
    		me.onAlbumSelected.subscribe(function(type,selectedAlbum,obj) {    			
    			obj.album.removeImage(obj.res);
    			me.onAlbumSelected.unsubscribeAll();
    		},{album: oldAlbum, res: json.resId});
    		this.loadNodeData(newAlbum.node);
    	} else {
    		MEMOZ.log('Kunne ikke flytte ressurs','error');
    		this.errorMessage('Kunne ikke flytte ressurs');
    	}
    },
        
	/*
	   +------------------------------------------------------------------------------------------+
	   | Section: Creating gallery album     												      |
	   +------------------------------------------------------------------------------------------+
	*/
    
	/* 
		Method: addGalleryAlbum
		Will prompt the user for an album name and then make an AJAX request to create the album.
	*/
	addGalleryAlbum: function() {
		if (this.isWorking) return;
		var self = this;
		var newName = prompt(this.getLabel('addGalleryAlbumPromt'), '');
		if (newName == null || newName == '') return false;
    	this.setWorking(true);
    	this.ajaxReq('addGalleryAlbum','galleryAlbumAdded', { 
    		memozId: this.memozId, 
    		parentAlbum: this.selectedDir.id,
    		name: newName
    	});
	},
	
	/* 
		Method: galleryAlbumAdded
		Callback function for the request made from <addGalleryAlbum>.
		If successful, we will receive an object from the server containing id and name of 
		the new album. If not, error != 0.
		
		Parameters:
			json - <object> Return from server
	*/
	galleryAlbumAdded: function(json) {
		var me = this;
		// this.setWorking(false); // Skip, since we will call loadNodeData
		if (json.error == 0) {
			var tempNode = new YAHOO.widget.TextNode(json.name, this.selectedDir.node, false);
			this.selectedDir.childs[tempNode.index] = {
				id: json.id,
				owner: json.owner,
				name: json.name,
				index: tempNode.index,
				childs: [],
				resources: [],
				allowUpload: json.allowUpload,
				allowCreateDir: json.allowCreateDir,
				node: tempNode
			};
			this.selectedDir.node.refresh();
			YAHOO.util.Event.onAvailable(tempNode.labelElId, function() {
				me.loadNodeData(tempNode);
			});
		} else {
			this.setWorking(false);
    		this.errorMessage(json.error);
		}
	},

	/*
	   +------------------------------------------------------------------------------------------+
	   | Section: Uploading gallery resource     												  |
	   +------------------------------------------------------------------------------------------+
	*/
	
    /* 
		Method: upload
		Uploads a new image to the LifeType gallery usying YAHOO.util.Connect.asyncRequest.
	*/
    upload: function() {
    	if (this.isWorking) return;
        var self = this;
        var formObject = $('imgSel'+this.uniqueId+'Form');
        if (!formObject) { MEMOZ.log('Upload form not found!','error'); return; }
        
        // the second argument is true to indicate file upload. 
        YAHOO.util.Connect.setForm(formObject, true); 
        MEMOZ.log("Uploading file to dir "+$(this.inputDirId).value+" (owner: "+$(this.inputOwnerId).value+")...");
        MEMOZ.ajaxTransactionId++; // We must manually update this!
        var cObj = YAHOO.util.Connect.asyncRequest('POST', './?upload', {
       	 	upload: function(o){ self.uploadComplete(o); }, 
        	failure: function(o){ self.uploadFailed(o); }
    	}); 
        this.setWorking(true);
    },

    /* 
		Method: uploadComplete
		Callback function for the request made from <upload>.
		If successful, this function will evaluate the server-response and pass it on to <addResource>.
		
		Parameters:
			o - <object> Return from server
	*/
	uploadComplete: function(o) {
        this.setWorking(false);
        try {
            var json = eval('(' + o.responseText + ')');
        } catch(err) {
        	MEMOZ.log(o.responseText,"error");
            var json = { error: 'serverError'};
        }
        switch (json.error) {
            case 0:
                this.onResourceAdded(json.resource);
                break;
            default:
            	var err;
            	if ((err = this.getLabel(json.error)) != 'label_not_defined') 
	                this.errorMessage(err);
                else
                	this.errorMessage(json.error);
                // MEMOZ.log(json.error,'error');
                break;            
        }        
    },

    /* 
		Method: uploadFailed
		Callback function. Called when we've got an server response about the image upload if
		something went seriously wrong.
		
		Parameters:
			o - <object> Return from server
	*/
	uploadFailed: function(o) {
        this.setWorking(false);
    	this.errorMessage('Opplastingen mislyktes pga. en meget ukjent feil!');
        MEMOZ.log("Upload failed",'error');
    },

    /* 
		Method: onResourceAdded
		Draws a newly added resource to the userinterface. This is called from <uploadComplete>. This
		should not be called directly, as the process of adding a resource starts with <upload>.
		
		Parameters:
			res - <object> New resource
	*/
    onResourceAdded: function(res) {
        MEMOZ.log("New resource uploaded");
        var self = this;
        
        if (this.selectedDir.resources.length < 1) {
			var children = YAHOO.util.Dom.getChildren(this.imagePaneDiv);
			for (var i = 0; i < children.length; i++) {
				this.imagePaneDiv.removeChild(children[i]);
			}        		
		}
        
		res.a = document.createElement('a');
		res.a.id = 'previewImgLink'+this.uniqueId+'-'+res.id;
		res.a.innerHTML = '<img src="'+res.preview+'" alt="'+res.name+'" />';
		this.imagePaneDiv.appendChild(res.a);
		
		res.dd = new MEMOZ.imageDragDrop(this, res);

		this.selectedDir.resources.push(res);

		YAHOO.util.Event.addListener(res.a.id, "click", function(e) { 
			self.onSelectImage(this.id);
		} );        
		
		this.onSelectImage(res.a.id);
        
 	}, 	

	/*
	   +------------------------------------------------------------------------------------------+
	   | Section: Renaming albums			     											 	  |
	   +------------------------------------------------------------------------------------------+
	*/ 	
 	
 	/* 
		Method: renameAlbumPrompt
		Will prompt the user for a new album name and then make an AJAX request to rename it.
	*/
	renameAlbumPrompt: function() {
		if (this.isWorking) return;
		var me = this;		
		var album = this.focusedAlbum;
		var newName = prompt(this.getLabel('renameAlbumPrompt'), album.name);
		if (newName == null || newName == '') return false;
    	this.setWorking(true);
    	this.ajaxReq('renameGalleryAlbum','albumRenamed', { 
    		memozId: this.memozId, 
    		albumId: album.id,
    		name: newName
    	});
	},
	
	/* 
		Method: albumRenamed
		Callback function for the request made from <renameAlbumPrompt>.
		
		Parameters:
			json - <object> Result from server
	*/
	albumRenamed: function(json) {
		this.setWorking(false);
		if (json.error == 0) {
			var albumObj = this.getAlbumById(json.albumId);
			albumObj.setName(json.name);
		} else {
    		this.errorMessage(json.error);
		}
	},

	/*
	   +------------------------------------------------------------------------------------------+
	   | Section: Deleting gallery resources     											 	  |
	   +------------------------------------------------------------------------------------------+
	*/ 	
 	
	/*
		Method: confirmDeleteAlbum
    	Uses <MEMOZ.dialog.confirmDlg> to ask the user for confirmation. If positive, we'll call <deleteImage>
	*/
 	confirmDeleteAlbum: function() {
		if (this.isWorking) return;
 		var me = this;
 		var albumId = this.focusedAlbum.id;
 		// MEMOZ.showModalBg();
		MEMOZ.dialog.confirmDlg(this.getLabel('confirmDeleteAlbum'), function(doit) { 
			// MEMOZ.hideModalBg();
			if (doit) me.deleteAlbum(albumId); 
		});
	},

	/* 
    	Method: deleteAlbum
    	Makes an AJAX-request to delete an album.
    	
    	Parameters:
    		albumId - The unique album id
    */
	deleteAlbum: function(albumId) {
        
		this.setWorking(true);

		if (this.selectedDir) { // ) && (this.selectedDir.id == albumId)
			this.onSelectAlbum();
        }
        this.ajaxReq('deleteGalleryAlbum', 'albumDeleted', { 
    		memozId: this.memozId, 
    		albumId: albumId
		});  
        
    },

	/* 
    	Method: albumDeleted
    	Callback for the request made from <deleteAlbum>.
    	
    	Parameters:
    		json - Server response
    */
    albumDeleted: function(json){ 
    
		this.setWorking(false);
		
		if (json.error != 0) {
	    	this.errorMessage(json.error);
		} else {
			var albumObj = this.getAlbumById(json.albumId);
			
			this.tree.removeNode(albumObj.node);

			var parentAlbum = this.getParentAlbum(json.albumId);
			parentAlbum.deleteChildAlbum(json.albumId);

			this.tree.draw();
		}
		
    },		
	
	/*
		Method: confirmDeleteImage
		Uses <MEMOZ.dialog.confirmDlg> to ask the user for confirmation of deletion of <focusedImage>.
    	If positive, we'll call <deleteImage>
		
		Parameters:
			e - click event
	*/
	confirmDeleteImage: function(e) {
		if (this.isWorking) return;
    	var me = this;
		MEMOZ.showModalBg();
		MEMOZ.dialog.confirmDlg(this.getLabel('confirmDeleteImage'), function(doit) { 
			MEMOZ.hideModalBg();
			if (doit) me.deleteImage(me.focusedImage); 
		});    
	},
	
	/* 
    	Method: deleteImage
    	Makes an AJAX-request to delete an image.
    	
    	Parameters:
    		imageId - The unique image id
    */
	deleteImage: function(imageId) {
        
		this.setWorking(true);

		var oldSelect = this.selectedDir;
		this.onSelectAlbum();		
        
        this.ajaxReq('deleteImage', 'imageDeleted', { 
    		memozId: this.memozId, 
    		resourceId: imageId
		}, oldSelect);  
        
    },

	/* 
    	Method: imageDeleted
    	Callback for the request made from <deleteImage>.
    	
    	Parameters:
    		json - Server response
    		oldSelect - Selected album
    */
    imageDeleted: function(json, oldSelect){ 
    
		this.setWorking(false);
		
		this.loadNodeData(oldSelect.node);

		if (json.error != 0) {
	    	this.errorMessage(json.error);
		}
		
    } 	

});
