<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="Eqy" height="100">
    <Require feature="dynamic-height" />
  </ModulePrefs>
  <Content type="html">
    <![CDATA[
	<!-- link rel="stylesheet" href="http://wave.bryanbibat.com/css/jquery.tooltip.css" / -->

    <script src="https://wave-api.appspot.com/public/wave.js" type="text/javascript"></script>
	<script src="http://wave.bryanbibat.com/js/jquery-1.3.2.min.js" type="text/javascript"></script>
	<!--  script src="http://wave.bryanbibat.com/js/jquery.bgiframe.js" type="text/javascript"></script -->
    <!-- script src="http://wave.bryanbibat.com/js/jquery.dimensions.js" type="text/javascript"></script -->
    <!-- script src="http://wave.bryanbibat.com/js/jquery.tooltip.min.js" type="text/javascript"></script -->
    <div id="content_div" align="center"><img id="eq_img" onClick="eqnClicked();" onload="eqImgLoaded();"></img>
    <textarea rows="5" cols="80" id="edit_box" onchange="editChanged();" 
      onkeypress="editChanged();" onkeydown="editChanged();" onkeyup="editChanged();"> </textarea>
    </div>
    <script type="text/javascript">
	// -*- tab-width: 2 -*-

// Source code for the Mathsys gadget (the xml container is also in this directory).
var div = document.getElementById('content_div');
var eqImg = document.getElementById('eq_img');
var editBox = document.getElementById('edit_box');
var togImg = document.getElementById('toggle_img');

var myconsole;
var myLastEqnUpdate = null;

eqImg.onload = eqImgLoaded;

if(window.loadFirebugConsole) { // Enable console on Firefox
  window.loadFirebugConsole(); 
}

if (window.console)
{
  myconsole = window.console;
}
else {
  // There is no console available so make a dummy console
  myconsole = new DummyConsole();
}

function DummyConsole()
{

}
DummyConsole.prototype.log = function(str)
{
  // Do nothing
}

function stateUpdated()
{
  myconsole.log('stateUpdated()');
  var eq = wave.getState().get('eqn');
  renderEquation(eq);
  // Update the edit box (unless we have a pending state change that hasn't gone through yet - this allows
	// the user to type faster than changes can be synchronized).
  if(myLastEqnUpdate != null) {
		myconsole.log('Pending equation update ' + myLastEqnUpdate + ' received ' + eq);
		if(eq == myLastEqnUpdate) { // The update has come through so any updates now are real.
			myLastEqnUpdate = null;
			myconsole.log('Equation update received.' + myLastEqnUpdate + ' is here');
		}
  }
	else {
		editBox.value = eq;
	}
}

function renderEquation(eq)
// Takes the equation (as a string) and renders it in the gadget.
{
  myconsole.log('Rendering ' + eq);
  // At the moment the only method we have of rendering the equation is using Google's service.
  // In future, we could use MathML on browsers which support it.
  renderWithGoogleChart(eq);
  gadgets.window.adjustHeight();
  myconsole.log('Done');
}


function gChartEscape(eq)
// Escapes the equation string eq for appending to a URL.
{
  // We just need to do standard escaping - BUT we also need to change + characters so they
  // render correctly.
  eq = escape(eq);
  // Modify + characters to %2B
  eq = eq.replace(/\+/g, '%2B');
  return eq;
}

function renderWithGoogleChart(eq)
{
  if (!isEqnEmpty(eq)) {
    eqImg.src = 'http://sciencesoft.at/image/latexurl/?template=no&src=' + 
      gChartEscape('\\documentclass[12pt]{article} \\usepackage{amssymb,amsmath} \\pagestyle{empty} \\begin{document}' + eq + '\\end{document}');
		// Set the alternative text to be something informative
		eqImg.alt = eq;
		eqImg.title = eq;
	/* $("#eq_img").tooltip({ 
		delay: 0, 
		showURL: false, 
		bodyHandler: function() { 
			return wave.getState().get('eqn'); 
		} 
    });	*/
  }
  else {
    myconsole.log('Not rendering equation because it is empty.');
    eqImg.src = 'http://waveyscience.appspot.com/static/1.png';
  }
}

function isWhitespace(str)
// Given   : str is a string
// Returns : true if str is only whitespace
{ 
    if (str == null) {
      return true;  // Return null string as being whitespace
    }

    var white;
    white = " \t\n\r";
    for(var i = 0; i < str.length; i++) {
      if (white.indexOf(str.charAt(i).toLowerCase()) == -1) {
	  return false;
      }
    }
    return true;
} 

function isEqnEmpty(eq)
// Returns true is equation does not contain any meaningful information.
{
  return isWhitespace(eq);
}

function modeChanged()
// Change to display text when in edit mode or otherwise display the picture
{
  myconsole.log('modeChanged()');

  if (wave.getMode() == wave.Mode.EDIT) {
    myconsole.log('Edit mode');
    editBox.style.display = "inline";
		// Make sure that the textbox contains the latest state information.
  }
  else {
    myconsole.log('Display mode');
    editBox.style.display = "none";
  } 

	// Make sure we don't get stuck waiting for a state update that will never come.
	myLastEqnUpdate = null;
	if(wave.getState()) {
		editBox.value = wave.getState().get('eqn');
	}
  gadgets.window.adjustHeight();
}

function eqnClicked()
// The user has clicked on the equation - change to an editable state.
{
  myconsole.log('Equation clicked.');

  // Add a textbox for the user to edit.
  
}

function editChanged()
// User has updated the equation - change state
{
	if(wave && wave.getState()) {
  	var eqn = editBox.value;
	  if (eqn != wave.getState().get('eqn')) {
	    wave.getState().submitDelta({'eqn' : eqn})
		   myLastEqnUpdate = eqn;
      myconsole.log('Edit changed' + eqn);
    }
  }
	else {
		myconsole.log('Edit change but Wave not setup.');
	}
}

function eqImgLoaded()
// Called when the image displaying the equation loads.
{
  // Refresh the height of the gadget.
  gadgets.window.adjustHeight();
}

function init() 
{
  if (wave && wave.isInWaveContainer()) {
    myconsole.log('init()');
    wave.setStateCallback(stateUpdated);
    wave.setModeCallback(modeChanged);
  }
}
gadgets.util.registerOnLoadHandler(init);

	</script>
    ]]>
  </Content>
</Module>
