window.onload = enableTooltips;

function showPopover(id) {
	Effect.BlindDown(id, {duration:.25}); }

function hidePopover(id, fade) {
  if (fade == null) {
	  Effect.BlindUp(id, {duration:.25});
	} else {
	  Effect.Fade(id, {duration:.25});
	}
}

function dataSample(id) {
	var sample = encodeURIComponent(sampleRows($(id).value, 10));
	// alert(sample);
	return sample;
}

function sampleRows(text, maxLines) {
	var idx = 0;
	var lastIdx = -1;
	var count = 0;
	while (count < maxLines && idx != -1) {
		lastIdx = idx;
		idx = text.indexOf("\n",lastIdx+1);
		count++;
	}
	if (count == 1 && idx == -1) return text.substring(0,1000);
	s = text.substring(0,lastIdx);
	
	tailIdx = text.lastIndexOf("\n");
	// alert("tail: " + tailIdx + " last: " + lastIdx);
	if (tailIdx > lastIdx) 
		s += text.substring(tailIdx, text.length);
	else
		s += text.substring(lastIdx, text.length);
	return s;
}

/* Help Popovers */

/* This is a tool tip collection */
var tooltips = [
  ['joinTopicHub', 'When you join a topic center, you can add data sets and visualizations. You can also start new discussions on the topic.'],
  ['startNewDiscussion',  'If you log in and join this topic center, you can start new discussions.'],
  ['addVisualization', '<p>If you log in and join this topic center, you can add visualizations to the list.</p> <p>To add a visualization, go to its page, and click on this icon: <img style="vertical-align: middle;" src="images/add_to_topic_hub_disabled.gif"/></p><br/>'],
  ['addDataset', 'If you log in and join this topic center, you can add data sets to the list.<br /><br />  To add a data set, go to its page, and click on this icon: <img src="images/add_to_topic_hub_disabled.gif" style="vertical-align:middle;"/>'],
   ['show_hubs_button', ' Clicking this icon will let you add this to one of your centers. This is a good way to organize a set of visualizations or datasets on a particular topic or theme.'],
  ['addToTopicHubDisabled', "You need to be logged in and should've joined at least one topic center to be able to add visualizations and data sets to topic centers."],
  ['topichubs', 'When you join a topic center, you can add data sets and visualizations. You can also start new discussions on the topic.'],
  ['watchlistLearnMore',  "If you \"watch\" a visualization or dataset, you'll be notified of new comments on your watchlist page.<br/>Clicking on <img style='' src='images/watch_this_disabled.gif'/>will let you be notified of changes to this item on your watchlist page (for example: you'll get notified about new comments, new visualizations, etc "],
  ['dataEditing', 'Clicking on this button will allow you to edit individual data cells, or perform more powerful transformations on the data. After you finish making your changes, you can save them as a new revision.'],
  ['dataEditingDisabled', 'If you were the creator of this data set, you could edit it. Soon, however, we will open up data sets to all Many Eyes users.'],
 
  ['rateButton', 'Give this a thumbs-up or thumbs-down.'],
  ['rateThisPopDisabled', 'Please login to rate this.'],
  ['topicHubs', 'This user does not belong to any topic centers.'],
  
  ['addVisToTopicHubLearnMore', "If you've joined any topic centers, clicking on <img src=\"images/add_to_topic_hub_disabled.gif\" style=\"verticle-align:middle\"/> will let you add the visualization to one of our centers.<br />Topic centers are a good way to organize a set of visualizations on a particular topic or theme."],
  ['addToWatchlistLearnMore', 'Clicking on <img src="images2/watch_this_disabled.gif" style="verticle-align:middle"/> will let you be notified of changes to this item on your watchlist page (for example: youll get notified about new comments, new visualizations, etc).'],
  ['visualizeDisabled', 'In order to visualize this data set, please go to latest revision.'],
  ['addToWatchlist', "If you \"watch\" a visualization or dataset, you'll be notified of new comments on your watchlist page."],
  ['addToWatchlistDisabled', 'Please log in to "watch" this.'],
  ['datasetEditDisabled', 'Only the creator of this data set can edit the data.']
  
];

function enableTooltips() {
  /* Create all hidden divs */
  
  for (i = 0; i < tooltips.size(); i++) {
    var id = tooltips[i][0];
    var text = tooltips[i][1];
    
    if ($(id)) {
      var parent = $(id).ancestors()[0];
      
      var attrs = {
        style: 'display:none',
        id: id + 'Popover'
      };
      
      var newHelpDiv = new Element('div', attrs);
      newHelpDiv.addClassName('viewPopover helpPopover');
      newHelpDiv.innerHTML = text;
      
      if (parent) {
        parent.insert(newHelpDiv);
        
        /* Also append onmouseover to original item */
        /*$(id).writeAttribute('onmouseover', "showInContextHelp('" + id +"', 0);")
        #$(id).writeAttribute('onmouseover', "alert('boo');")
        $(id).onmouseover = function () {showInContextHelp(id);}
        alert('id ' + id)
        $(id).addEventListener('mouseover',function () {showInContextHelp(id);},false)
        $(id).onmouseover = function() {return showInContextHelp(id, 0);}*/
        Event.observe($(id), 'mouseover', showInContextHelp.bindAsEventListener($(id),id, 0));
      }
    }
  }
}
/**
 * Help Popover: Position a popover div relative to its trigger and lower
 */
function repositionBelow(triggerId, id)
{
    var left = 0, top= 0;
    var offsets = Position.cumulativeOffset($(triggerId));
    if (offsets[0]>document.body.clientWidth/2) {
      left = -200;
      top = 30;
  } else {
      left = 30;
      top = 30;
  }
    if (navigator.userAgent.match(/Firefox/))
    {
        top -= 10;
        left -= 10;
    }
    Position.clone(triggerId, id,
                   {setWidth:false, setHeight:false,
                    offsetLeft:left, offsetTop:top});
}
/*
Help Popover: Data structure and helper function to ensure triggered events are properly
terminated before triggering a new event.
*/
var effectsQueue = [];

function clearEffectsQueue()
{
 for (var i=0; i<effectsQueue.length; i++)
   {
      effectsQueue[i].cancel();
   }
   effectsQueue = [];
}

/**
Help Popover: Reposition a popover and make it visible
*/
function showInContextHelp(event, triggerId, delayTime, close)
{
    var triggerId = Event.element(event).id
    delayTime = $A(arguments)[2];
    var delayTime = (delayTime==null)? 1:delayTime;
    id=triggerId+"Popover";
    var layerText=$(id).innerHTML;
    if(close!=null) {
      if(!(layerText.match("<!--close link added-->"))) {
        $(id).innerHTML = layerText+"<br/><a href=\"javascript:hidePopover('"+id+"',1)\">close</a><!--close link added-->";
      }
    }
	  // Hide the alt attribute when mouse over
    $(triggerId).setAttribute('old_alt', $(triggerId).getAttribute('alt'));
    $(triggerId).setAttribute('alt', '');
	
    //$(triggerId).onmouseout=hideInContextHelp;
    if (close == null) {
      Event.observe(triggerId, 'mouseout', hideInContextHelp);
    }
    repositionBelow(triggerId, id);
    effectsQueue.push(new Effect.Appear(id, {duration:0.25, delay:delayTime}));
}
/**
Help Popover: Hide a popover after calculating the trigger
*/
function hideInContextHelp()
{
  triggerId = this.id;
  
  id=triggerId+"Popover";
  new Effect.Fade(id, {duration:.25, delay:0});
  
  // Reset alt attribute
  $(triggerId).setAttribute('alt', $(triggerId).getAttribute('old_alt'));
  $(triggerId).removeAttribute('old_alt');
  
  clearEffectsQueue();
}

function checkDisplayErrors(id) {
  if (Element.getStyle($(id), 'display') != 'none') {
    $('createbutton').hide();
  } else {
    $('createbutton').show();
  }
}