var tooltip = null;

var categories = {
  "catHist": "L'histoire",
  "cat2D": "2D",
  "cat3D": "3D",
  "catMOB": "Mobile",
  "catSYN": "Animation 3D"
};

var types = {
  "writing": "Écriture",
  "making": "Fab. / général",
  "shooting": "Fab. / tournage",
  "editing": "Fab. / post-production"
};

var objectTypes = {
	"mediaImageGallery": "Galerie d'images",
	"mediaImage": "Image",
	"mediaPdf": "Document",
	"mediaVideo": "Vidéo",
	"person": "Personne",
	"personGroup": "Groupe de personnes"
}

var Tooltip = function() {
  this.listTemplate = null;
  this.detailsTemplate = null;
  this.dynamicTemplate = null;
  this.headerTemplate = null;
  this.listPanel = null;
  this.dataView = null;
  this.detailsPanel = null;
  this._tooltip = null;
  this.timeout = -1;
  this.init();
};

Tooltip.prototype = {
  init: function() {
    this.listTemplate = new Ext.XTemplate(      
      '<tpl for=".">',
      '<div class="tooltip-item list">',
        '<div class="thumb"><img class="thumb-image" src="{thumbnail}" title="{title}" style="width: 32px; height: 32px;"/></div>',
        '<div class="title">{title}</div>',
        '<div class="clear"></div>',
      '</div>',
      '</tpl>',
      {
        compiled: true,
        disableFormats: true
      }
    );
    
    this.detailsTemplate = new Ext.XTemplate(      
      '<tpl for=".">',
      '<div class="tooltip-item details">',
        '<div class="header"></div>',
        '<div class="thumb">',
        '<a href="{openUrl}">',
        '<tpl if="thumbnail != null || thumbnail_animate != null"/>',        
        '<img class="thumb-image" ',
          '<tpl if="thumbnail_animate != null"/>',        
            'src="{thumbnail_animate}" title="{title}"',
          '</tpl>',
          '<tpl if="thumbnail_animate == null"/>',
            'src="{thumbnail}" title="{title}"',
          '</tpl>',
          '/>',
        '</tpl>',
        '</a>',
        '</div>',
        //'<div class="link"><a href="{openUrl}">Voir la fiche</a></div>',
        '<div class="title"><a href="{openUrl}">{title}</a></div>',        
        '<div class="dynamic-content"></div>',
        '<div class="clear"></div>',
      '</div>',
      '</tpl>',
      {
        compiled: true,
        disableFormats: true
      }
    );

    this.headerTemplate = new Ext.XTemplate(
			'<div class="categories">',
      '<tpl for="category">',
        //'{[xindex == 1 ? "<div class=\'row\'><span class=\'label\'>Catégories : </span>" : ""]}',
        '{[xindex > 1 ? ", " : ""]}',          
        '<span <tpl if="active">class="active"</tpl>><img src="/imgs/icons/{id}<tpl if="!active">_off</tpl>.png" title="{label}"/> ',	
        '{label}</span>',				
        //'{[xindex == xcount ? "</div>" : ""]}',
      '</tpl>',
			'</div>',
      '<tpl for="type">',
        '{[xindex == 1 ? "<div class=\'types\'>" : ""]}',
        '{[xindex > 1 ? ", " : ""]}',          
        '<span class="active">{.}</span>',					
        '{[xindex == xcount ? "</div>" : ""]}',
      '</tpl>',     
      {
        compiled: true,
        disableFormats: true
      }
    );
    
    this.dynamicTemplate = new Ext.XTemplate(  
			'<div class="description">{description:ellipsis(130, true)}</div>',        
      {
        compiled: true,
        disableFormats: false
      }
    );
    
    var store = new Ext.data.JsonStore({
      fields: ["title", "thumbnail", "id", "type", "thumbnail_animate", "openUrl", "hasPrefix"]      
    });

    var formatData = function(data) {
      if (data.hasPrefix != true) {
        if (data.thumbnail != "" && data.thumbnail != null)
          data.thumbnail = globalOptions.urlPrefix + data.thumbnail;
        else
          data.thumbnail = null;
        if (data.thumbnail_animate != "" && data.thumbnail_animate != null)
    	  data.thumbnail_animate = globalOptions.urlPrefix + data.thumbnail_animate;
        else
          data.thumbnail_animate = null;
      }
      return data;
    }; 

    this.dataView = new Ext.DataView({      
      prepareData: formatData.createDelegate(this),
      store: store,
      tpl: this.listTemplate,
      multiSelect: false,
      singleSelect: true,
      simpleSelect: true,
      autoScroll: true,
      overClass: 'x-view-over',
      itemSelector: "div.tooltip-item",
      listeners: {
        scope: this,
        "selectionchange": function(dataView, selections) {
          var selectedRecords = this.dataView.getSelectedRecords();
          if(selectedRecords && selectedRecords.length > 0) {
            var selectedRecord = selectedRecords[0];
            var data = selectedRecord.data;
            this.showDetails(data);
            // load dynamic content
            this.lastObject = {
              type: data.type,
              id: data.id
            };
            Ext.Ajax.request({
              url: globalOptions.urlPrefix + "ajax/details.json?type="+data.type+"&id="+data.id,
              method: "POST",
              scope: this,		
              success: function(response, options) {
                var data = Ext.decode(response.responseText);
                data.objectType = this.lastObject.type;
                data.category = [];
                data.type = [];
                for (var category in categories) {
									data.category.push({
										"id": category,
										"label": categories[category],
										"active": (parseFloat(data[category]) > 0)
									});
                }
                for (var type in types) {
                  if (parseFloat(data[type]) > 0) {
                    data.type.push(types[type]);
                  }
                }
								if (data.visible == "1")
	                this.headerTemplate.overwrite(Ext.query("#tooltip .header")[0], data);
								else 
									Ext.DomHelper.overwrite(Ext.query("#tooltip .header")[0], "");
                this.dynamicTemplate.overwrite(Ext.query("#tooltip .dynamic-content")[0], data);
              }
            });
          }
        }
      }
    });
        
    this.listPanel = new Ext.Panel({
      id: "tooltip-list", 
      layout: "fit", 
      height: 165,
      flex: 1,
      items: this.dataView
    });
    this.detailsPanel = new Ext.Panel({
      id: "tooltip-details",        
      layout: "fit",
      flex: 2
    });
    this._tooltip = new Ext.ToolTip({    
      anchor: "left",
      id: "tooltip",      
      //anchorOffset: 10,
      anchorToTarget: false,
      width: 350,
      //height: 300,
      border: false,
      autoScroll: true,
      //dismissDelay: 2000,
      closable: true,
      autoHide: false,      
      layout: "hbox",
      layoutConfig: {
        align: "stretchmax",
        pack: "start"
      },      
      listeners: {
        "afterrender": function() {
          this.getEl().on({
            "mouseover": tooltip.cancelHide,            
            "mouseout": tooltip.askForHide,
            scope: tooltip
          });
        }
      },
      defaults: {
        border: false
      },
      items: [this.listPanel, this.detailsPanel]
    });
    
    Ext.QuickTips.init();
  },
  
  hide: function() {
    this._tooltip.hide();
  },
  
  show: function(title, items, evt) {
    this.cancelHide();
    this._tooltip.setTitle(title);   
    
    var pageX;
    var pageY;
    if (evt.pageX) pageX = evt.pageX;
    else if (evt.clientX)
      pageX = evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    if (evt.pageY) pageY = evt.pageY;
    else if (evt.clientY)
      pageY = evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
     
    this._tooltip.showAt([pageX + 13, pageY - 10]);
    
    this.dataView.getStore().loadData(items);    
    
    this.detailsPanel.body.update('');
    
    if (items.length == 1) {
      this.listPanel.hide();      
    } else {
      this.listPanel.show();    
    } 
    this._tooltip.doLayout();
    this.dataView.select(0);
       
  },
  
  showDetails: function(data) {
		this._tooltip.setTitle(objectTypes[data.type]);
    this.detailsTemplate.overwrite(this.detailsPanel.body, data);
  },
  
  askForHide: function() {
    this.timeout = setTimeout("tooltip.hide();", 100);
  },
  
  cancelHide: function() {
    clearTimeout(this.timeout);
  }
};

Ext.onReady(function() {
  tooltip = new Tooltip();
});

