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();
  });
  
  var popupTimeout;
  
  function showPopup(event) {
    clearTimeout(popupTimeout);
    popupTimeout = setTimeout(function() { $('share-this-sub-menu').show(); }, 200);
    event.stop();
  }
  
  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')) && $('actions') && $('view-artwork') ) {

		// 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');

		// attach the link behaviour
		Event.observe('zoom-link', 'click', zoomIn);
		Event.observe('view-artwork', 'click', zoomIn);
    	if( $('clear-main') ){
		  Event.observe('clear-main', '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('bodycolor') != -1) {
        new_img_url = img_url.replace(/bodycolor:([a-zA-Z]+)/, "bodycolor:" + link.className);
      } else {
        var elements = img_url.split(',');
        elements[2] = 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 = "bodycolor=" + 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() {
	// hide just about everything
	$('artist-content').style.display = 'none';

	// 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] );
	}

	// retore the original page layout
	$('artist-content').style.display = 'block';

}

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