/*
 * Ext JS Library 2.0.1
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

/*
 * Ext JS Library 2.0
 * Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
 
var ImageViewer = function(config){
	this.config = config;
}

ImageViewer.prototype = {
    // cache data by image id for easy lookup
    lookup : {},
    
	show : function(el, callback){
		if(!this.win){
			this.initTemplates();
			
			this.store = new Ext.data.JsonStore({
			    url: this.config.url,
			    root: 'images',
			    fields: [
			        {name:'id',mapping:'photoid'},'name', 'url'
			    ],
			    listeners: {
			    	'load': {fn:function(){ this.view.select(0); }, scope:this, single:true}
			    }
			});
			this.store.load({params:{ID:this.config.params.ID}});
			
			
			var formatData = function(data){
		    	data.shortName = data.name.ellipse(15);
		    	this.lookup[data.id] = data;
		    	return data;
		    };
			
		    this.view = new Ext.DataView({
				tpl: this.thumbTemplate,
				singleSelect: true,
				cls:'filmstrip-container',
				overClass:'x-view-over',
				itemSelector: 'div.thumb-wrap',
				emptyText : '<div style="padding:10px;">No images found</div>',
				store: this.store,
				listeners: {
					'selectionchange': {fn:this.showDetails, scope:this, buffer:100},
					'loadexception'  : {fn:this.onLoadException, scope:this},
					'beforeselect'   : {fn:function(view){
				        return view.store.getRange().length > 0;
				    }}
				},
				prepareData: formatData.createDelegate(this)
			});
		    
			var cfg = {
		    title: 'View Images',
		    id: 'img-chooser-dlg',
		    layout: 'border',
				modal: true,
				closeAction: 'hide',
				border: false,
				items:[{
				id: 'img-chooser-view',
				region: 'center',
				minWidth: 100,
				width: 100,
				autoScroll: true,
				items: this.view,
				//can add a top bar for navigating large sets 
                    tbar:[]
				},{
					id: 'img-detail-panel',
					region: 'east',
				width: 500

				}],
				buttons: [{
					text: 'Close',
					handler: function(){ this.win.hide(); },
					scope: this
				}],
				keys: {
					key: 27, // Esc key
					handler: function(){ this.win.hide(); },
					scope: this
				}
			};
			Ext.apply(cfg, this.config);
		    this.win = new Ext.Window(cfg);
		}
		
		//this.reset();
		this.win.setSize(620,500);
	  this.win.show(el);
		this.callback = callback;
		this.animateTarget = el;
	},
	
	initTemplates : function(){
		this.thumbTemplate = new Ext.XTemplate(
			'<tpl for=".">',
				'<div class="thumb-wrap" id="{id}">',
				'<div class="thumb"><img src="{url}" title="{name}"></div>',
			'</tpl>'
		);
		this.thumbTemplate.compile();
		
		this.detailsTemplate = new Ext.XTemplate(
			'<div class="details">',
				'<tpl for=".">',
					'<img src="{url}"><div class="details-info">',
					'<span>{name}</span></div>',
				'</tpl>',
			'</div>'
		);
		this.detailsTemplate.compile();
	},
	
	load : function(el,photoId,callback) {
		this.show(el,callback);
	  var detailEl = Ext.getCmp('img-detail-panel').body;
		var data = this.lookup[photoId];
		this.view.select(this.store.indexOf(data));
    detailEl.hide();
    this.detailsTemplate.overwrite(detailEl, data);
    detailEl.slideIn('l', {stopFx:true,duration:.2});
    
	},
	
	showDetails : function(){
	  var selNode = this.view.getSelectedNodes();
	  var detailEl = Ext.getCmp('img-detail-panel').body;
		if(selNode && selNode.length > 0){
			selNode = selNode[0];
		  var data = this.lookup[selNode.id];
      detailEl.hide();
      this.detailsTemplate.overwrite(detailEl, data);
      detailEl.slideIn('l', {stopFx:true,duration:.2});
		}else{
		  detailEl.update('');
		}
	},
		
	sortImages : function(){
		var v = Ext.getCmp('sortSelect').getValue();
    this.view.store.sort(v, v == 'name' ? 'asc' : 'desc');
    this.view.select(0);
    },
	
	reset : function(){
		if(this.win.rendered){
			this.view.getEl().dom.scrollTop = 0;
		}
		this.view.select(0);
	},
	
	doCallback : function(){
        var selNode = this.view.getSelectedNodes()[0];
		var callback = this.callback;
		var lookup = this.lookup;
		this.win.hide(this.animateTarget, function(){
            if(selNode && callback){
				var data = lookup[selNode.id];
				callback(data);
			}
		});
    },
	
	onLoadException : function(v,o){
	    this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>'); 
	}
};

String.prototype.ellipse = function(maxLength){
    if(this.length > maxLength){
        return this.substr(0, maxLength-3) + '...';
    }
    return this;
};



//Really want to implement this for a filmstrip style accross bottom
Ext.Slider = function (id, config) { 
     this.init (id, config || {}); 
     } 
      
Ext.Slider.prototype = { 
     width: 300, 
     initialValue: 0, 
     zone: null, 
     slider: null, 
     ddEl: null, 
     startDrag: null, 
     endDrag: null, 
     onDrag: null, 
     bgImage: '/images/icons/slider_bg.gif', 
     sliderImage: '/images/icons/slider_horiz.gif', 
      
     init: function (id, config) { 
        Ext.apply (this, config); 
        this.zone = Ext.DomHelper.append (Ext.get (id),  { tag: 'div', id: Ext.id (), style: 'position:relative;width: '+this.width+'px;height: 20px;background-image:url('+this.bgImage+');z-index:1;' }, true); 
        this.slider = Ext.DomHelper.append (this.zone,  { tag: 'div', id: Ext.id (), style: 'position:absolute;left:'+this.initialValue+'px;width:13px;height:20px;background-image:url('+this.sliderImage+'); overflow: hidden;z-index:2' }, true); 
        var instance = this; 
        this.ddEl = new Ext.dd.DD (this.slider); 
        this.ddEl.setYConstraint (0, 0); 
        this.ddEl.setXConstraint (this.slider.getX ()-this.zone.getX (), this.zone.getRight () -this.slider.getRight ()); 
        this.slider.on ('mouseover', function () {  
           if (!instance.ddEl.isDragged)  
              this.setStyle ('background-position', '0px -20px');  
           this.setStyle ('cursor', 'w-resize'); 
           }); 
        this.slider.on ('mouseout', function () { 
           if (!instance.ddEl.isDragged)  
              this.setStyle ('background-position', '0px 0px');  
           this.setStyle ('cursor', 'default'); 
           }); 
        this.ddEl.onMouseDown = function (x, y) { 
           instance.ddEl.isDragged = true; 
           if (typeof instance.onDragStart == 'function') 
              instance.onDragStart ((instance.slider.getX () - instance.zone.getX ()) /  (instance.width-13) * 100);  
           instance.slider.setStyle ('background-position',  '0px -40px'); 
           }; 
        this.ddEl.onMouseUp = function (x, y) { 
           instance.ddEl.isDragged = false; 
           if (typeof instance.onDragEnd == 'function') 
              instance.onDragEnd ((instance.slider.getX () - instance.zone.getX ()) /  (instance.width-13) * 100);  
           instance.slider.setStyle ('background-position',  '0px 0px'); 
           }; 
        this.ddEl.onDrag = function (e) { 
           if (typeof instance.onDrag == 'function') 
              instance.onDrag ((instance.slider.getX () - instance.zone.getX ()) /  (instance.width-13) * 100);  
           }; 
        } 
     };  
