﻿/*
given a dropdown with gallery ids as option values, 

[
  {
      galleryID: 1
    , name: 'Homepage'
    , entries: [  { entryID: 'ccd1ad9b-6c68-4161-a200-f1a9303e9f90', caption: 'yadda yadda' }, ... ]
  }
 , ...
];
*/
var trace = function(str){

    try {
        opera.postError(str);
    } 
    catch (e) {
        try {
            console.log(str);
        } 
        catch (f) {
            //alert(str);
        }
    }

}

var GalleryBrowser = new Class({
  options: {
    ddlGallery: false
  , thumbElement: false
  , thumbPath: false
  , defaultGalleryID: false
  }
, initialize: function(gal, options) {
    if (window.debugging) { trace(options); }
    this.setOptions(options);
    this.gals = gal;
    this.thumbPath = this.options.thumbPath; // has two format args - first is the galleryID, second the entry ID eg /images/gallery/{0}/thumb/{1}.jpg
    this.thumb = this.options.thumbElement ? ($type(this.options.thumbElement) == 'element' ? this.options.thumbElement : $(this.options.thumbElement)) : false;
    if (window.debugging) { trace(this.thumb, this.options.thumbPath); }
    if (window.debugging) { trace(this.thumb, this.options.thumbElement); }
    this.ddl = this.options.ddlGallery ? ($type(this.options.ddlGallery) == 'element' ? this.options.ddlGallery : $(this.options.ddlGallery)) : false;
    if (this.ddl)       // attach an onchange to it to find and render the selected gallery's thumbs if its valid
      this.ddl.addEvent('change',function(){ this.find(this.ddl.options[this.ddl.selectedIndex].value); }.bind(this));
  }
, found: null
, find: function(id) {  // finds the gallery with the passed id and sets found to equal it. if not found, uses default gallery
    this.found = null;  // reset the found gallery
    this.thumb.empty(); // empty it of thumbs
    for (i = 0; i < this.gals.length; i++) { if (this.gals[i].id == id) { this.found = this.gals[i]; continue; } }
    for (i = 0; i < this.gals.length; i++) { if (this.gals[i].id == this.options.defaultGalleryID) { this.found = this.gals[i]; continue; } }
    if (this.found) {    // set the thumb el to have all the gal entry thumbs
      this.thumb.empty();
      this.found.entries.each(function(el) {
        imgHolder = new Element('div', {'class': 'fl'}).injectInside(this.thumb);
        if (this.found.typeid == 3) imgHolder.addClass('dblImg'); // 3 = dblslider gallerytype
        if ($defined(el.image1) && $chk(el.image1))
          new Element('img', { src: this.thumbPath.replace(/\{0\}/, this.found.id).replace(/\{1\}/, el.image1) } ).injectInside(imgHolder);
        if ($defined(el.image2) && $chk(el.image2))
          new Element('img', { src: this.thumbPath.replace(/\{0\}/, this.found.id).replace(/\{1\}/, el.image2) } ).injectInside(imgHolder);
      }.bind(this));
    }
    return this.found;
  }
});
GalleryBrowser.implement(new Options);