/**
 * GO 2 Admin Console
 * (c) 2008-2009 www.douglass.com
 * licensing@douglass.com
 *
 * $Author: doug $
 * $Id: gallery.js 106 2009-01-11 01:11:26Z doug $
 * $Date: 2009-01-10 17:11:26 -0800 (Sat, 10 Jan 2009) $
 * $Revision: 106 $
 * $URL: svn+ssh://doug@g2gevents.homeip.net/var/svn/www.g2gevents.com/trunk/js/gallery.js $
 */

Ext.BLANK_IMAGE_URL = '../admin/js/ext-2.2/resources/images/default/s.gif';

//this runs on DOM load - you can access all the good stuff now.

Ext.onReady(function() {
	 
  var xd = Ext.data;
	var chooseAlbum = "";
	var albumArray;
  // ::TODO:: temporary fix because of ldap/.htaccess lockdown of admin/console/... directories
  //var modulePath = "admin/console/modules/gallery/";
  var modulePath = "gallery/";
	
  var store = new Ext.data.JsonStore({
      url: modulePath + 'GalleryProcessor.php',
      root: 'images',
      fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date', dateFormat:'timestamp'},'imgDir','albumname']
  });

  store.load({
    params : {
      action : 'showAlbum'
    }
	});
	
  //this could have been loaded up server side prior to output but for the sake
  //of using javascript not php on the page we'll do it this way
  
  //AJAX request - nice and simple
  Ext.Ajax.request({
    waitMsg: 'Contacting server...',
    url: modulePath + 'GalleryProcessor.php',
    method: 'POST',
    params: {
      action: "getAlbums"
    },
    failure: function(response, options){
      //something went wrong.
      Ext.MessageBox.alert('Warning', 'Failed to contact server...');
    },
    success: function(response, options){
      //success means we can make the menu
      var obj = Ext.util.JSON.decode(response.responseText);
      
      //assign obj to a global array
      albumArray = obj;
      
      //get the element div called 'albums'
      var albumDiv = Ext.get('albums');
      
      //count the albums
      var albumCount = obj.records;
      
      for (var i=0; i<albumCount; i++) {
        Ext.DomHelper.append('albums', '<div id="album-link-wrap-'+i+'"><a href="javascript:;" id="album-link-'+i+'">'+obj.folders[i]+'</a></div>', false);
        
        //set up the event handler
        Ext.get('album-link-'+i).on('click',function(e,t){
          var albumToClick = t.id.split("-");
          if (Ext.query('.selected').length > 0) {
            Ext.query('.selected')[0].className = '';
          }
          Ext.get('album-link-wrap-'+albumToClick[2]).addClass('selected');
          chooseAlbum = obj.folders[albumToClick[2]];
          store.load({
            params: {
              action: 'showAlbum',
              album: chooseAlbum
            },
            callback: function () { Ext.getCmp('thumbnails-wrap').body.scrollTo('top', 0); }
          });
        })
      };
      // Set the 'selected' for default album    
      Ext.get('album-link-wrap-0').addClass('selected');
    }
  }); //end ajax request

  var tpl = new Ext.XTemplate(
  '<tpl for=".">',
    '<div class="thumb-wrap" id="{name}">',
    '<div class="thumb"><img src="{url}" title="{name}"></div>',
    '<span class="x-editable">{shortName}</span></div>',
  '</tpl>',
  '<div class="x-clear"></div>'
  );

  var thumbview = new Ext.DataView({
    store: store,
    tpl: tpl,
    multiSelect: false,
    singleSelect: true,
    overClass: 'x-view-over',
    itemSelector: 'div.thumb-wrap',
    emptyText: 'No images to display right now.',
    prepareData: function(data){
        data.shortName = Ext.util.Format.ellipsis(data.name, 15);
        data.sizeString = Ext.util.Format.fileSize(data.size);
        data.dateString = data.lastmod.format("m/d/Y g:i a");
        return data;
    }
  })

  var thumbnailViewPanel = new Ext.Panel({
    id: 'thumbnails-wrap',
    autoScroll: true,
    height: 104,
    items: thumbview
  });

  var tbarea = Ext.get('thumbnails');
  thumbnailViewPanel.render(tbarea);

  // On thumbnail 'click' method
  thumbview.on('click',function(dview,index,node,event){
    var img_id = Ext.get(node).id;
    
    // Create an image so we can extract the width and height to the FX scaling
    image = new Image();
    image.src = store.getAt(index).data.imgDir+store.getAt(index).data.albumname+"/sized/"+store.getAt(index).data.name;

    // If the 'onload' method is not used, then the references to width and height might
    // be accessed before the image has been loaded.
    image.onload = function() {
      Ext.get('big_image').update(
        "<img src='"+store.getAt(index).data.imgDir+store.getAt(index).data.albumname+"/sized/"+store.getAt(index).data.name+"' id='big_img_"+index+"' width=0 height=0 >",
        false,
        function(e){
          var bigimg = Ext.get('big_img_'+index);
          bigimg.scale(5,image.height,{
            duration: .5,
            easing: 'easeOut'
          });
          bigimg.scale(image.width,undefined,{
            duration: .7,
            easing: 'easeOut'
          });
        } 
      );
    }
    //Ext.get('big_image_name').update("Filename: "+store.getAt(index).data.name);
  });	

});
