/*
 * yui-ext
 * Copyright(c) 2006, Jack Slocum.
 */

var ImageChooser = function(config){
    // create the dialog from scratch
    var dlg = new YAHOO.ext.LayoutDialog(config.id || YAHOO.util.Dom.generateId(), {
		autoCreate : true,
		width:700,
		height:500,
		syncHeightBeforeShow: true,
		shadow:true,
		fixedcenter: true,
		constraintoviewport: false,
		center:{autoScroll:false},
		proxyDrag: true,
		resizable: false,
		movable: false,
		shim: true,
		east:{split:true,initialSize:400,minSize:400,maxSize:400, resizable: false}
	});
	dlg.setTitle('<center>Please select a swatch on the left.</center>');
	dlg.getEl().addClass('ychooser-dlg');
	dlg.addKeyListener(27, dlg.hide, dlg);
    
    // add some buttons
    dlg.setDefaultButton(dlg.addButton('Dismiss', dlg.hide, dlg));
    //this.ok = dlg.addButton('OK', this.doCallback, this);
    //this.ok.disable();
    dlg.on('show', this.load, this, true);
	this.dlg = dlg;
	var layout = dlg.getLayout();
	
	layout.beginUpdate();
	var vp = layout.add('center', new YAHOO.ext.ContentPanel(YAHOO.util.Dom.generateId(), {
		autoCreate : true,
		fitToFrame:true
	}));
	var dp = layout.add('east', new YAHOO.ext.ContentPanel(YAHOO.util.Dom.generateId(), {
		autoCreate : true,
		fitToFrame:true
	}));
	layout.endUpdate();
	
	var bodyEl = vp.getEl();
	var viewBody = bodyEl.createChild({tag:'div', cls:'ychooser-view'});
	vp.resizeEl = viewBody;
	
	this.detailEl = dp.getEl();
	
	// create the required templates
	this.thumbTemplate = new YAHOO.ext.Template(
		'<div class="thumb-wrap" id="{name}" style="float: left;">' +
		'<div class="test"><img src="{url_thumb}" title="{name}"></div>' +
		'<span>{shortName}</span></div>'
	);
	this.thumbTemplate.compile();	
	
	this.detailsTemplate = new YAHOO.ext.Template(
		'<div class="details"><img src="{url_details}"><div class="details-info">' +
		'<b>{name}</b>' +
		'</div></div>'
	);
	this.detailsTemplate.compile();	
    
    // initialize the View		
	this.view = new YAHOO.ext.JsonView(viewBody, this.thumbTemplate, {
		singleSelect: true,
		jsonRoot: 'images',
		emptyText : '<div style="padding:10px;">No images match the specified filter</div>'
	});
	this.view.bufferedListener('selectionchange', this.showDetails, this);
    //this.view.on('dblclick', this.doCallback, this, true);
    this.view.on('loadexception', this.onLoadException, this, true);
    this.view.on('beforeselect', function(view){
        return view.getCount() > 0;
    });
    YAHOO.ext.util.Config.apply(this, config, {
        width: 600, height: 700
    });
    
    var formatSize = function(size){
        if(size < 1024) {
            return size + " bytes";
        } else {
            return (Math.round(((size*10) / 1024))/10) + " KB";
        }
    };
    
    // cache data by image name for easy lookup
    var lookup = {};
    // make some values pretty for display
    this.view.prepareData = function(data){
    	data.shortName = data.name.ellipse(8);
    	data.sizeString = formatSize(data.size);
    	data.dateString = new Date(data.lastmod).format("m/d/Y g:i a");
    	lookup[data.name] = data;
    	return data;
    };
    this.lookup = lookup;
    
	dlg.resizeTo(this.width, this.height);
	this.loaded = false;
};
ImageChooser.prototype = {
	show : function(el, callback){
	    this.reset();
	    this.dlg.show(el);
		this.callback = callback;
	},
	
	reset : function(){
	    this.view.getEl().dom.scrollTop = 0;
	    //this.view.clearFilter();
		//this.txtFilter.dom.value = '';
		this.view.select(0);
	},
	
	load : function(){
		if(!this.loaded){
			this.view.load({url: this.url, params:this.params, callback:this.onLoad.createDelegate(this)});
		}
	},
	
	onLoadException : function(v,o){
	    this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>'); 
	},
	
	/*filter : function(){
		var filter = this.txtFilter.dom.value;
		this.view.filter('name', filter);
		this.view.select(0);
	},
	*/
	onLoad : function(){
		this.loaded = true;
		this.view.select(0);
	},
	
	sortImages : function(){
		var p = this.sortSelect.dom.value;
    	var dsc = p != 'name';
    	this.view.sort(p, p != 'name' ? 'desc' : 'asc');
    	this.view.select(0);
    },
	
	showDetails : function(view, nodes){
	    var selNode = nodes[0];
		if(selNode && this.view.getCount() > 0){
			//this.ok.enable();
		    var data = this.lookup[selNode.id];
			this.detailEl.move('right', 450, true, .15, function(){
					this.detailsTemplate.overwrite(this.detailEl.dom, data);
					this.detailEl.move('left', 450, true, .15, null, YAHOO.util.Easing.easeOutStrong);
				}.createDelegate(this));
			
		}else{
		    //this.ok.disable();
		    this.detailEl.update('');
		}
	},
	
	doCallback : function(){
		var selNode = this.view.getSelectedNodes()[0];
		var callback = this.callback;
		var lookup = this.lookup;
		this.dlg.hide(function(){
			if(selNode && callback){
				var data = lookup[selNode.id];
				callback(data);
			}
		});
	}
};

String.prototype.ellipse = function(maxLength){
    if(this.length > maxLength){
        return this.substr(0, maxLength-3) + '...';
    }
    return this;
};

