/* Gutter Plugin */
(function() {
    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;

    YAHOO.gutter = function(richEditor, name, title, id, text_label, doc) {
        return {
            status: false,
            gutter: null,
            createGutter: function() {
                console.log('Creating gutter (#'+id+')', 'info', 'example');
                this.gutter = new YAHOO.widget.Overlay(id, {
                    height: '425px',
                    width: '300px',
                    context: [richEditor.get('element_cont').get('element'), 'tl', 'tr'],
                    position: 'absolute',
                    visible: false
                });
                this.gutter.hideEvent.subscribe(function() {
                    richEditor.toolbar.deselectButton(name);
                    Dom.setStyle(id, 'visibility', 'visible');
                    var anim = new YAHOO.util.Anim(id, {
                        width: {
                            from: 300,
                            to: 0
                        },
                        opacity: {
                            from: 1,
                            to: 0
                        }
                    }, 1);
                    anim.onComplete.subscribe(function() {  
                        Dom.setStyle(id, 'visibility', 'hidden');
                    });
                    anim.animate();
                }, this, true);
                this.gutter.showEvent.subscribe(function() {
                    richEditor.toolbar.selectButton(name);
                    this.gutter.cfg.setProperty('context', [richEditor.get('element_cont').get('element'), 'tl', 'tr']);
                    Dom.setStyle(this.gutter.element, 'width', '0px');
                    var anim = new YAHOO.util.Anim(id, {
                        width: {
                            from: 0,
                            to: 300
                        },
                        opacity: {
                            from: 0,
                            to: 1
                        }
                    }, 1);
                    anim.animate();
                }, this, true);
                var warn = '';
                if (richEditor.browser.webkit || richEditor.browser.opera) {
                    warn = richEditor.STR_IMAGE_COPY;
                }
                this.gutter.setBody('<h2>' + title +'</h2><label for="'+ name +'_search">'+text_label+':</label><input type="text" value="" id="'+name+'_search"><div id="'+name+'_results"><p>'+doc+'</p></div>' + warn);
                this.gutter.render(document.body);
            },
            open: function() {
                Dom.get(name+'_search').value = '';
                console.log('Show Gutter', 'info', 'example');
                this.gutter.show();
                this.status = true;
            },
            close: function() {
                console.log('Close Gutter', 'info', 'example');
                this.gutter.hide();
                this.status = false;
            },
            toggle: function() {
                if (this.status) {
                    this.close();
                } else {
                    this.open();
                }
            }
        }
    }

})();


YAHOO.util.Event.onAvailable('flickr_search', function() {
    console.log('onAvailable: #flickr_search', 'info', 'example');
    YAHOO.util.Event.on('flickr_results', 'mousedown', function(ev) {
        YAHOO.util.Event.stopEvent(ev);
        var tar = YAHOO.util.Event.getTarget(ev);
        if (tar.tagName.toLowerCase() == 'img') {
            if (tar.getAttribute('fullimage', 2)) {
                console.log('Found an image, insert it..', 'info', 'example');
                var img = tar.getAttribute('fullimage', 2),
                    title = tar.getAttribute('fulltitle'),
                    owner = tar.getAttribute('fullowner'),
                    url = tar.getAttribute('fullurl');
                this.toolbar.fireEvent('flickrClick', { type: 'flickrClick', img: img, title: title, owner: owner, url: url });
            }
        }
    }, myEditor, true);
    console.log('Create the Auto Complete Control', 'info', 'example');
    oACDS = new YAHOO.widget.DS_XHR("/api/flickr_proxy",
        ["photo", "title", "id", "owner", "secret", "server"]);
    oACDS.scriptQueryParam = "tags";
    oACDS.responseType = YAHOO.widget.DS_XHR.TYPE_XML;
    oACDS.maxCacheEntries = 0;
    oACDS.scriptQueryAppend = "method=flickr.photos.search";

    // Instantiate AutoComplete
    oAutoComp = new YAHOO.widget.AutoComplete('flickr_search','flickr_results', oACDS);
    oAutoComp.autoHighlight = false;
    oAutoComp.alwaysShowContainer = true; 
    oAutoComp.formatResult = function(oResultItem, sQuery) {
        // This was defined by the schema array of the data source
        var sTitle = oResultItem[0];
        var sId = oResultItem[1];
        var sOwner = oResultItem[2];
        var sSecret = oResultItem[3];
        var sServer = oResultItem[4];
        var urlPart = 'http:/'+'/static.flickr.com/' + sServer + '/' + sId + '_' + sSecret;
        var sUrl = urlPart + '_s.jpg';
        var lUrl = urlPart + '_m.jpg';
        var fUrl = 'http:/'+'/www.flickr.com/photos/' + sOwner + '/' + sId;
        var sMarkup = '<img src="' + sUrl + '" fullimage="' + lUrl + '" fulltitle="' + sTitle + '" fullid="' + sOwner + '" fullurl="' + fUrl + '" class="yui-ac-flickrImg" title="Click to add this image to the editor"><br />';
        return (sMarkup);
    };
});

YAHOO.util.Event.onAvailable('youtube_search', function() {
    console.log('onAvailable: #youtube_search', 'info', 'example');
    YAHOO.util.Event.on('youtube_results', 'mousedown', function(ev) {
        YAHOO.util.Event.stopEvent(ev);
        var tar = YAHOO.util.Event.getTarget(ev);
        if (tar.tagName.toLowerCase() == 'img') {
            if (tar.getAttribute('fulltitle')) {
                console.log('Found an image, insert it..', 'info', 'example');
                var title = tar.getAttribute('fulltitle'),
                    url = tar.getAttribute('fullurl'),
                    id = tar.getAttribute('fullid'),
                    thumb = tar.getAttribute('src');
                this.toolbar.fireEvent('youtubeClick', { type: 'youtubeClick', title: title, url: url, id: id, thumb: thumb});
            }
        }
    }, myEditor, true);
    console.log('Create the Auto Complete Control', 'info', 'example');
    oACDS = new YAHOO.widget.DS_XHR("/api/youtube_proxy",
        ["videos", "title", "url", "thumb", "id"]);
    oACDS.scriptQueryParam = "search";
    oACDS.maxCacheEntries = 0;
    // oACDS.scriptQueryAppend = "method=flickr.photos.search";

    // Instantiate AutoComplete
    oAutoComp = new YAHOO.widget.AutoComplete('youtube_search','youtube_results', oACDS);
    oAutoComp.autoHighlight = false;
    oAutoComp.alwaysShowContainer = true; 
    oAutoComp.formatResult = function(oResultItem, sQuery) {
        var title = oResultItem[0];
        var url = oResultItem[1];
        var thumb = oResultItem[2];
        var id = oResultItem[3];
        var sMarkup = '<img src="' + thumb + '" fulltitle="' + title + '" fullurl="' + url + '" fullid="'+ id + '" class="yui-ac-flickrImg" title="Click to add this movie to the editor"><br />';
        return (sMarkup);
    };
});

YAHOO.util.Event.onAvailable('gallery_search', function() {
    console.log('onAvailable: #gallery_search', 'info', 'example');
    YAHOO.util.Event.on('gallery_results', 'mousedown', function(ev) {
        YAHOO.util.Event.stopEvent(ev);
        var tar = YAHOO.util.Event.getTarget(ev);
        if (tar.tagName.toLowerCase() == 'img') {
            if (tar.getAttribute('fulltitle')) {
                console.log('Found an image, insert it..', 'info', 'example');
                var title = tar.getAttribute('fulltitle'),
                    url = tar.getAttribute('src');
                this.toolbar.fireEvent('galleryClick', { type: 'galleryClick', title: title, url: url});
            }
        }
    }, myEditor, true);
    console.log('Create the Auto Complete Control', 'info', 'example');
    oACDS = new YAHOO.widget.DS_XHR("/api/gallery",
        ["images", "title", "url"]);
    oACDS.scriptQueryParam = "search";
    oACDS.maxCacheEntries = 0;
    // oACDS.scriptQueryAppend = "method=flickr.photos.search";

    // Instantiate AutoComplete
    oAutoComp = new YAHOO.widget.AutoComplete('gallery_search','gallery_results', oACDS);
    oAutoComp.autoHighlight = false;
    oAutoComp.alwaysShowContainer = true; 
    oAutoComp.formatResult = function(oResultItem, sQuery) {
        var title = oResultItem[0];
        var url = oResultItem[1];
        var sMarkup = '<img src="' + url + '" fulltitle="' + title + '" class="yui-ac-flickrImg" title="Click to add this movie to the editor"><br />';
        return (sMarkup);
    };
});

console.log('Editor loaded..', 'info', 'example');

var gutter = null;
var youtube_gutter = null;
var gallery_gutter = null;

var myEditor = new YAHOO.widget.Editor('body', { 
  height: '300px', 
  width: '522px', 
  dompath: true, //Turns on the bar at the bottom 
  animate: true, //Animates the opening, closing and moving of Editor windows 
  handleSubmit: false,
  focusAtStart: true,
  markup: 'css'
}); 

myEditor.on('toolbarLoaded', function() { 
  console.log('Toolbar loaded, add button and create gutter', 'info', 'example');
  var flickr_doc = 'Enter flickr tags into the box above, separated by commas. Be patient, this may take a few seconds to get the images..';
  gutter = new YAHOO.gutter(myEditor, "flickr", "Flickr Image Search", 'gutter1', 'Tags', flickr_doc);

  var youtube_doc = 'Enter youtube search strings into the box above, separated by commas and limit the search to a particular user using "user:USERNAME" where USERNAME is the user\'s username. Be patient, this may take a few seconds to get the previews..';
  youtube_gutter = new YAHOO.gutter(myEditor, "youtube", "YouTube Movie Search", 'gutter2', 'Search', youtube_doc);

  var gallery_doc = 'Enter image ids into the box above separated by commas or "page:XX" where XX is a number starting from 1. Be patient, this may take a few seconds to get the images..';
  gallery_gutter = new YAHOO.gutter(myEditor, "gallery", "Internal Image Search", 'gutter3', 'Ids', gallery_doc);

  var flickrConfig = {
          type: 'push',
          label: 'Insert Flickr Image',
          value: 'flickr'
  }
  
  var youtubeConfig = {
      type: 'push',
      label: 'Insert YouTube Movie',
      value: 'youtube'
  }

  var galleryConfig = {
      type: 'push',
      label: 'Insert internal image',
      value: 'gallery'
  }

  myEditor.toolbar.addButtonToGroup(flickrConfig, 'insertitem');
  myEditor.toolbar.addButtonToGroup(youtubeConfig, 'insertitem');
  myEditor.toolbar.addButtonToGroup(galleryConfig, 'insertitem');
  
  myEditor.toolbar.on('flickrClick', function(ev) {
      console.log('flickrClick: ' + YAHOO.lang.dump(ev), 'info', 'example');
      this._focusWindow();
      if (ev && ev.img) {
          console.log('We have an image, insert it', 'info', 'example');
          //To abide by the Flickr TOS, we need to link back to the image that we just inserted
          var html = '<div class="flickr-image"><a href="' + ev.url + '"><img src="' + ev.img + '" title="' + ev.title + '" /></a></div>';
          this.execCommand('inserthtml', html);
      }
      gutter.toggle();
  }, myEditor, true);
  myEditor.toolbar.on('youtubeClick', function(ev) {
      console.log('youtubeClick: ' + YAHOO.lang.dump(ev), 'info', 'example');
      this._focusWindow();
      if (ev && ev.id) {
          console.log('We have a movie, insert it', 'info', 'example');
          var html = '<div class="ytembed" id="'+ ev.id +'"><a href="'+ev.url+'"><img src="'+ev.thumb+'" alt="thumbnail" /></a><br />This video requires Javascript to be enabled, and requires the <a href="http://www.adobe.com/go/getflashplayer">Adobe Flash Player.</a></div>';
          this.execCommand('inserthtml', html);
      }
      youtube_gutter.toggle();
  }, myEditor, true);
  myEditor.toolbar.on('galleryClick', function(ev) {
      console.log('galleryClick: ' + YAHOO.lang.dump(ev), 'info', 'example');
      this._focusWindow();
      if (ev && ev.url) {
          console.log('We have an image, insert it', 'info', 'example');
          var html = '<div class="gallery-image"><img src="' + ev.url + '" title="' + escape(ev.title) + '" /></div>';
          this.execCommand('inserthtml', html);
      }
      gallery_gutter.toggle();
  }, myEditor, true);

  gutter.createGutter();
  youtube_gutter.createGutter();
  gallery_gutter.createGutter();

});