function setupShareThis() {
  Event.observe('fb_share', 'click', function(event) {
    window.open(this.href, 'sharer','toolbar=0,status=0,width=626,height=436');
    try { pageTracker._trackEvent('Sharing', 'Share', 'Facebook'); } catch(err) {}
    $('share-this-sub-menu').hide();
    event.stop();
  });
  Event.observe('twitter_share', 'click', function(event) {
    window.open(this.href, 'twitter','toolbar=0,status=0,width=1024,height=650');
    try { pageTracker._trackEvent('Sharing', 'Share', 'Twitter'); } catch(err) {}
    $('share-this-sub-menu').hide();
    event.stop();
  });

  if ($('add-to-cart')) {
    $('add-to-cart', 'buy_card_link', 'buy_framed_print_link', 'buy_canvas_print_link', 'buy_poster_link').compact().each(function(link) {
      Event.observe(link, 'click', function(event) {
        try { pageTracker._trackEvent('Show Work', 'Configure-New', link.id); } catch(err) {}
      });
    });
  } else {
    $('buy_print_button', 'buy_tshirt_button', 'buy_calendar_button', 'buy_card_link', 'buy_print_link', 'buy_tshirt_link', 'buy_calendar_link').compact().each(function(link) {
      Event.observe(link, 'click', function(event) {
        try { pageTracker._trackEvent('Show Work', 'Configure', link.id); } catch(err) {}
      });
    });
  }

  var popupTimeout;

  function showPopup(event) {
    clearTimeout(popupTimeout);
    popupTimeout = setTimeout(function() { $('share-this-sub-menu').show(); }, 200);
    event.stop();
  }

  if ($('share-this-wrapper')) {
    Event.observe('share-this-wrapper', 'mouseover', showPopup);
    Event.observe('share-this', 'click', showPopup);
    Event.observe('share-this-wrapper', 'mouseout', function(event) {
      clearTimeout(popupTimeout);
      popupTimeout = setTimeout(function() { $('share-this-sub-menu').hide(); }, 10);
    });
  }
}

function setupZoom() {

  // only do this on the '....-show' pages, if 'view-artwork' and 'actions' elements are available:
  if ( ($('artist_art-show') || $('artist_clothing-show')) && $('view-artwork') ) {

    if ($('actions')) {
      // create a new 'zoom in' link
      var zoom_link = document.createElement('a');
      Element.extend(zoom_link);
      zoom_link.setAttribute('id', 'zoom-link');
      zoom_link.setAttribute('href', '#');
      zoom_link.update('View Larger');

      // create a list item. this will make a comfy home for our new link
      var zoom_link_container = document.createElement('li');
      Element.extend(zoom_link_container);
      zoom_link_container.setAttribute('id', 'zoom-link-container');

      // put the list item in the actions menu
      $$('#actions ul')[0].insertBefore(zoom_link_container, $$('#actions ul li')[0]);

      // put the zoom link in the list item
      $('zoom-link-container').appendChild(zoom_link);

      // season to taste
      Element.addClassName('zoom-link', 'zoom-in');

      Event.observe('zoom-link', 'click', zoomIn);
    }

    // attach the link behaviour
    Event.observe('view-artwork', 'click', zoomIn);
    if ($('clear-main')) {
      Event.observe('clear-main', 'click', zoomIn);
    }
    if ($('zoom-icon')) {
      Event.observe('zoom-icon', 'click', zoomIn);
    }
  } // end if

}

function setupZoomOut() {
  // remove the spinner graphic
  Element.removeClassName('zoom-container', 'loading');

  // attach behaviour to 'zoom out' link and main image
  Event.observe('zoom-out-link', 'click', zoomOut);
  Event.observe('artwork-zoom', 'click', zoomOut);
  if( $('clear-zoom') ){
    Event.observe('clear-zoom', 'click', zoomOut);
    }

  // hide the buy button as it's not properly styled yet
  $('buy').style.display = 'none';

  // we won't know the main image's size until it has loaded.
  // once it has loaded, we can use its dimensions in our page layout.
  Event.observe('artwork-zoom', 'load', tweakLayout);

}

var currentPreviewParams = "";

function setupColorPreviews() {
  if ( $('color-options') ) {
    $$('#color-options li a').each( function(link) {
      var img_url = $('view-artwork').src.toLowerCase();
      var new_img_url;
      if (img_url.indexOf('body_color') != -1) {
        new_img_url = img_url.replace(/body_color:([a-zA-Z]+)/, "body_color:" + link.className);
      } else {
        var elements = img_url.split(',');
        elements[1] = link.className.toLowerCase();
        new_img_url = elements.join(',');
      }
      buy_link = $$('#buy a')[0];
      Event.observe(link, 'click', function(e){
        $('view-artwork').src = new_img_url;
        currentPreviewParams = "body_color=" + link.className.toLowerCase();
        buy_link.href = buy_link.href.split('?')[0] + "?" + currentPreviewParams;
        Event.stop(e);
      });
    });
    tokens = window.location.href.split('?');
    if (tokens.length > 1) {
      currentPreviewParams = tokens[1];
    }
  }
}

function setupCommentForm(){
  if($$('#comment-form form')[0]){ // the normal comment is there, so must be signed in
    // make a toggle link
    comment_toggle = document.createElement('a');
    Element.extend(comment_toggle);
    comment_toggle.setAttribute('id', 'comment-toggle');
    comment_toggle.update('Add a Comment');
    li = $(document.createElement('li'));
    li.insert(comment_toggle);
    Element.insert($$('#actions ul')[0], li);

    // make a place holder for our toggle-able form
    form_container = document.createElement('div');
    Element.extend(form_container);
    form_container.setAttribute('id', 'toggle-form-container');
    Element.insert($('actions'), form_container);

    Event.observe($('comment-toggle'), 'click', function(){
      if($('toggle-form-container').childNodes[0]){
        while ( $('toggle-form-container').childNodes[0] ) {
          Element.remove($('toggle-form-container').childNodes[0]);
        }
      }
      else {
        // copy in the existing comment form
        $('toggle-form-container').update($('comment-form').innerHTML);
        // ..then remove the heading
        $$('#toggle-form-container h3')[0].remove();
      }
    });
  }
}

function tweakLayout() {
  buy_link = $$('#buy a')[0];
  $('buy').style.display = 'block';
  buy_link.href = buy_link.href.split('?')[0] + "?" + currentPreviewParams;
  $$('#zoom-buttons')[0].style.width = Math.max($('artwork-zoom').width, 500) + "px"; // at least 500px wide
}

function zoomIn(event) {
  event.stop();

  // hide just about everything
  if ($('artist-content')) $('artist-content').hide();
  $$('.new-show-work').each(function(el) { el.hide() });
  $('zoom-container').show();

  // get the work id from the url.
  // urls looks like: http://redbubble.com/works/show/8197-my_work or http://redbubble.com/works/show/8197-my_work/
  url = location.href;

  // strip anchor and query params
  url = url.split('#')[0];
  url = url.split('?')[0];

  // Strip trailing slash
  if (url.charAt(url.length - 1) == '/') {
    url = url.substring(0, url.length - 1)
  }

  url += '/zoom?' + currentPreviewParams;

  // add a spinner graphic to show something's happening
  Element.addClassName('zoom-container', 'loading')

  // hey browser please fetch me a lovely picture
  // url_for_work - this comment needs to get caught by mass find because the next line won't pick it up
  new Ajax.Updater('zoom-container', url, { onComplete: setupZoomOut, method: 'get' });

}

function zoomOut() {

  // nuke everything we pulled in from the zoom partial
  while ( $('zoom-container').childNodes[0] ) {
    $('zoom-container').removeChild( $('zoom-container').childNodes[0] );
  }

  // restore the original page layout
  if ($('artist-content')) $('artist-content').show();
  $$('.new-show-work').each(function(el) { el.show() });
}

document.observe('dom:loaded', setupCommentForm);
document.observe('dom:loaded', setupZoom);
document.observe('dom:loaded', setupColorPreviews);
document.observe('dom:loaded', setupShareThis);
