# HG changeset patch
# User J. H. Palmieri <palmieri@math.washington.edu>
# Date 1246318936 25200
# Node ID 644051ea215abd2c7f2a5ffcdbee83e3d18f0966
# Parent  d35be627d29580f364da6bd2703b715f9d077d8a
use javascript for animations

diff -r d35be627d295 -r 644051ea215a sage/plot/animate.py
--- a/sage/plot/animate.py	Sun Jun 28 19:59:15 2009 -0700
+++ b/sage/plot/animate.py	Mon Jun 29 16:42:16 2009 -0700
@@ -350,6 +350,82 @@
             print ""
             print "See www.imagemagick.org, for example."
 
+    def js(self, delay=20, iterations=0):
+        """
+        Produce javascript code for this animation.
+
+        INPUT:
+        
+        -  ``delay`` - (default: 20) delay in hundredths of a
+           second between frames
+        
+        -  ``iterations`` - integer (default: 0); number of
+           iterations of animation. If 0, loop forever.
+        """
+        msec = delay*10  # delay in milliseconds
+        d = self.png()
+        from sage.misc.prandom import randint
+        r = randint(1,1000)
+        file_list = os.listdir(d)
+        file_list.sort()
+        cell_dir = os.path.join(os.path.dirname(os.path.abspath("")), "anim%s"%r)
+        os.makedirs(cell_dir)
+        link_path = os.path.join("/home", cell_dir[cell_dir.find("admin"):])
+        v = []
+        for f in file_list:
+            shutil.copy(os.path.join(d, f), os.path.join(cell_dir, f))
+
+        v = [os.path.join(link_path, f) for f in file_list]
+
+        s = '<BODY onload="animate()">'
+        s += """
+        <SCRIPT language="javascript">
+        <!--
+       Animation = new Array(%s)\n"""%len(v)
+        for i in range(len(v)):
+            s += '       Animation[%s] = new Image();\n'%(i+1)
+            s += '       Animation[%s].src="%s"\n'%(i+1, v[i])
+        s +="""
+        var ii=1;
+        var jj=1;
+        var timerID=null;
+
+        function animate()
+        {
+           if (ii<21)
+                ii++;
+           else
+             {"""
+        if iterations > 0:
+            s += """
+               if (jj<%s)"""%iterations
+            s += """
+                 {
+                    jj++;
+                    ii=1;
+                 }"""
+        else:
+            s += """
+                    ii=1;"""
+        s += """
+             }
+             document.x%s.src=Animation[ii].src;
+             timerID=setTimeout("animate()", %s);
+        }
+        </SCRIPT>"""%(r, msec)
+        s += """        
+                <IMG NAME=x%s SRC="%s" BORDER="0">
+</BODY>"""%(r, v[0])
+        # ideally, delete the following three lines
+        f = open(os.path.join(os.path.abspath(""), "animate.html"), 'w')
+        f.write(s)
+        f.close()
+        # the following should be good enough...
+        print "<html>%s</html>"%s
+        return
+#         return s   # uncomment for debugging the javascript
+
+        
     def show(self, delay=20, iterations=0):
         r"""
         Show this animation.
