package Wiki::Score;

use warnings;
use strict;

use File::Find;
use File::Slurp qw/slurp read_file write_file/;
use Data::Dumper;
use Template;
use Wiki::Score::Templates;
use JSON;
use File::Basename;

=head1 NAME

Wiki::Score - The great new Wiki::Score!

=head1 VERSION

Version 0.01

=cut

our $VERSION = '0.01';

my %conf;
my $force;
my $dest;
my @files;
my %ABC;
my %ABC2;
my $TMPDIR = '/tmp/multiabc';
mkdir $TMPDIR unless -e $TMPDIR;
my $abcm2ps = '/usr/bin/abcm2ps';
my $ps2pdf = '/usr/bin/ps2pdf';
my $abc2midi = '/usr/bin/abc2midi';

$ENV{'LANG'} = 'en_US.UTF-8';

=head1 SYNOPSIS

Quick summary of what the module does.

Perhaps a little code snippet.

    use Wiki::Score;

    my $foo = Wiki::Score->new();
    ...

=head1 EXPORT

A list of functions that can be exported.  You can delete this section
if you don't export anything, such as for a purely object-oriented module.

=head1 SUBROUTINES/METHODS

=head2 init_proj

=cut

sub init_proj {
	my ($WIKIROOT, $filename, $spec, $force) = @_;
	return unless ($WIKIROOT and $filename and -e $filename);

	my @created;
	my $DATA = $WIKIROOT.'/data/pages';
	my $MEDIA = $WIKIROOT.'/data/media';

	my $json = read_file($filename, {binmode=>':utf8'});
	my $prj = from_json($json);

	# set project namespace
	my $ns = __prj_attr($prj, 'namespace') || $prj->{prjId};

	# create project dir
	my $dest = "$DATA/$ns";
	mkdir $dest unless -e $dest;
	push @created, $dest;

	# create project attachs dir
	my $media = "$MEDIA/$ns";
	mkdir $media unless -e $media;
	push @created, $media;

	# save project file (json)
	my $target = lc("$MEDIA/$ns/$ns.json");
	write_file($target, {binmode=>':utf8'}, $json);
	push @created, $target;

	# create/update project index file
	my $new_index = __create_index($WIKIROOT,$dest,$prj,$force);
	$target = "$dest/index.txt";

	
=head1 XXX todo update sections that change only
	if (-e $target) {
		my %new_index = __split_sections($new_index);
		my $old_index = slurp("$dest/index.txt");
		my %old_index = __split_sections($old_index);
		my $tmp;
		foreach (@{$new_index{'__order'}}) {
			if ($_ =~ m/(partitura|partes|misc)/i) {
				$tmp .= "$_\n".$new_index{$_};
			}
			else {
				$tmp .= $old_index{$_} ? "$_\n".$old_index{$_} : "$_\n".$new_index{$_};
			}
		}
		$new_index = $tmp;
	}
=cut
	write_file($target, {binmode => ':utf8'}, $new_index);
	push @created, $target;

	push @files, "$dest/t_abc.txt";


	# create/update project state file (after create/update project index file! )
	my $new_state = __create_state($WIKIROOT,$dest,$prj,$force);
	$target = "$media/state.txt";
	write_file($target, {binmode => ':utf8'}, $new_state);
	push @created, $target;


	if ($spec) {
		$target = "$dest/spec.txt";
		my $hs = read_file($spec, {binmode=>':utf8'});
		write_file($target, {binmode=>':utf8'}, __create_spec($prj,$hs));
		push @created, $target;
	}
	__fix_permissions($WIKIROOT, @created);
}

=head2 data2json

=cut

sub data2json {
	my ($WIKIROOT, $id, $target) = @_;

	my $txtroot = "$WIKIROOT/data/pages/$id";
	my $jsonfile = "$WIKIROOT/data/media/$id/$id.json";
	$target = $jsonfile unless $target;

	my $json = read_file($jsonfile, {binmode=>':utf8'});
	my $prj = from_json($json);

	# update Abc
	foreach (@{$prj->{cells}}) {
		my $c = read_file("$txtroot/s$_->{Cell}->{xcoord}p$_->{Cell}->{ycoord}.txt", {binmode=>':utf8'});
#		if ($c =~ m/<abc>(.*?)\s*<\/abc>/s) {
		if ($c =~ m/<abc>(.*?)<\/abc>/s) {
			my $abc = $1;
			my ($header, $notes) = split /%%\s*staves.*?\n/s, $abc;
			$notes =~ s/\n*$//;
         $notes =~ s/^V\s*:\s*\d+\w*//;
			$_->{Cell}->{raw} = $abc;
			$_->{Cell}->{ccontents}->{abcmusic}->[0]->[1] = $notes;
			$_->{Cell}->{ycoord} *= 1;
			$_->{Cell}->{xcoord} *= 1;
		}
	}

	write_file($target, {binmode=>':utf8'}, to_json $prj);
}

=head2 hsexec_proj

=cut

sub hsexec_proj {
	my ($WIKIROOT, $hsexec, $id, @extra) = @_;
	my $hshome = '/home/smash/playground/natura.svn.main/musica/Abc/Wiki-Score-Proto'; # XXX
	my $runhaskell = '/usr/bin/runhaskell';

	my $rand = int(rand 10000);
	my $tmpfile = $TMPDIR."/$id.$rand.json";
	my $hsfile = $TMPDIR."/hsexec.$rand.hs";
   my $abcfile = $TMPDIR."/$id.$hsexec.";
   if ($hsexec eq 'all') {
      $abcfile .= "A-$rand.abc";
   }
   else {
      $abcfile .= ($hsexec eq 'row'?'P':'S')."$extra[0]-$rand.abc";
   }
   my $haskell;

	data2json($WIKIROOT, $id, $tmpfile);

	if ($hsexec eq 'column') {
		$haskell = <<"EOF"
import WikiScore

main = do
         prj <- jsonFile2prj "$tmpfile"
         putStr ( show \$ column $extra[1] $extra[0] prj )
EOF
	}
	if ($hsexec eq 'row') {
		$haskell = <<"EOF"
import WikiScore

main = do
         prj <- jsonFile2prj "$tmpfile"
         putStr ( row $extra[1] $extra[0] prj )
EOF
	}
   if ($hsexec eq 'all') {
      $haskell = <<"EOF"
import WikiScore

main = do
         prj <- jsonFile2prj "$tmpfile"
         putStr ( buildAllColumnMajor prj )
EOF
   }

	write_file($hsfile, {binmode => ':utf8'}, $haskell);

	chdir $hshome;
	print STDERR "WSLOG $runhaskell $hsfile > $abcfile\n";
	`$runhaskell $hsfile > $abcfile`;
   my $svgfile = build_svg($abcfile);
   #my $pdffile = build_pdf($abcfile);
   
   my $d_as = 'Download as: <a target="_blank" href="./files/'.basename($abcfile).'">Abc</a> | <a target="_blank" href="./files/'.basename($svgfile).'">SVG</a> | <a target="_blank" href="./mabc_handler.php?id='.$id.'&action=build&target=pdf&source='.basename($abcfile).'">PDF</a> | <a target="_blank" href="./mabc_handler.php?id='.$id.'&action=build&target=midi&source='.basename($abcfile).'">MIDI</a>';
   my $c = read_file($svgfile, {binmode=>':utf8'});
   $c =~ s/^.*<body>//si;
   $c =~ s/<\/body>.*$//si;

   binmode STDOUT, ":encoding(utf8)";
   print $d_as.'/*;;*/'.$c;
}

=head2 build_svg

=cut

sub build_svg {
  my ($abcfile) = @_;
  my $svgfile = $abcfile;

  $svgfile =~ s/abc$/xhtml/;
  print STDERR `$abcm2ps -c -X -O $svgfile $abcfile`;

  return $svgfile;
}

=head2 build_pdf

=cut

sub build_pdf {
	my ($abcfile) = @_;
   my $pdffile = $abcfile;
   my $psfile = $abcfile;
   $psfile =~ s/abc$/ps/;
   $pdffile =~ s/abc$/pdf/;
   
	print STDERR `$abcm2ps -c -O $TMPDIR/$psfile $TMPDIR/$abcfile`;
   print STDERR `$ps2pdf -sPAPERSIZE=a4 $TMPDIR/$psfile $TMPDIR/$pdffile`;

	return $pdffile;
}

=head2 build_midi

=cut

sub build_midi {
   my ($abcfile) = @_;
   my $midifile = $abcfile;
   $midifile =~ s/abc$/midi/;

	`$abc2midi $TMPDIR/$abcfile -o $TMPDIR/$midifile`;

   return $midifile;
}


sub __fix_permissions {
	my ($WIKIROOT, @files) = @_;

	my @stat = stat($WIKIROOT);
	my $uid = $stat[4];
	my $gid = $stat[5];
	chown $uid, $gid, @files;
}

sub __clean_tmpfiles {
	unlink @_;
}

sub __split_sections {
   my $c = shift;
   my %h;
   my $key;
   foreach (split /^/, $c) {
      if ($_ =~ m/^={2,}/) {
         $key = $_;
         chomp $key;
         push @{$h{'__order'}}, $key;
      }
      else {
         $h{$key} .= $_;
      }
   }
   return %h;
}

sub __prj_attr {
	my ($prj, $attr) = @_;

	my $value;
	foreach (@{$prj->{prjattributes}}) {
		$value = $_->{value} if ($_->{aname} =~ m/^$attr$/i);
	}

	return $value;
}

sub __part_attr {
    my ($part, $attr) = @_;

    my $value;
    foreach (@{$part->{prtattributes}}) {
        $value = $_->{value} if ($_->{name} eq $attr);
    }

    return $value;
}

sub __section_attr {
    my ($section, $attr) = @_;

    my $value;
    foreach (@{$section->{sctattributes}}) {
        $value = $_->{value} if ($_->{aname} =~ m/^$attr$/i);
    }
    
    return $value;
} 

sub __create_index {
	my ($WIKIROOT,$dest,$prj,$force) = @_;
	my $ns = __prj_attr($prj, 'namespace') || $prj->{prjId};

	my $res = "====== " . __prj_attr($prj,'title') . " ======\n\n";
	my $introduction = __prj_attr($prj,'introduction') || '';
	$res .= "===== Introduction =====\n\n$introduction\n";

	if (__prj_attr($prj,'facsimile')) {
   		$res .= "===== Links =====\n\n";
   		$res .= "    * [[".__prj_attr($prj,'facsimile')."|facsimile]]\n" if __prj_attr($prj,'facsimile');
   		$res .= "    * [[".__prj_attr($prj,'libreto')."|libretto]]\n\n" if __prj_attr($prj,'libreto');
	}

	# XXX
	#$res .= "===== Score =====\n\n";
	#$res .= "  * [[$conf{'slug'}:final]]\n";
	#$res .= "  * {{:$conf{'slug'}:final.pdf?nocache|}}\n";
	#$res .= "  * {{:$conf{'slug'}:final.abc?nocache|}}\n";
	#$res .= "  * {{:$conf{'slug'}:final.mid?nocache|}}\n\n";

	my @sections = sort {$a->{scoord} <=> $b->{scoord}} @{$prj->{sections}};
	my @parts = sort {$a->{pcoord} <=> $b->{pcoord}} @{$prj->{parts}};
	$res .= "===== Matrix =====\n\n";
	$res .= "Empty: <html><img src=\"lib/tpl/default/images/cell.png\"></html>  Ongoing: <html><img src=\"lib/tpl/default/images/cell1.png\"></html> Selected for building: <html><input type='checkbox' checked='yes' disabled='true'><br></html>\n";
	$res .= "|       ";
	for my $s (1 .. @sections) {
		$res .= "^   [S$s] $sections[$s-1]->{sctid}<html><br><span style='font-size: 75%;'><a href=\"javascript: select_col($s);\">Select</a> | <a href=\"javascript: un_select_col($s);\">Unselect</a></span></html>   ";
	}
	$res .= "      |\n|   Fol   | ";
	for my $s (1 .. @sections) {
        $res .= "   " . (__section_attr($sections[$s-1], 'fol.')||'-') . "   |";
	}
	$res .= "      |\n|       | ";
	for my $s (1 .. @sections) {
		$res .= "   <html><input type='submit' onclick=\"javascript: curr_col = $s; build_col(); return false;\" value='  Build S$s  '></html>   |";
	}
	$res .= "\n";
	for my $p (1 .. @parts) {
		$res .= "^   [P$p] $parts[$p-1]->{name}<html><br><span style='font-size: 75%;'><a href=\"javascript: select_line($p);\">Select</a> | <a href=\"javascript: un_select_line($p);\">Unselect</a></span></html>   |";
		for my $s (1 .. @sections) {
			my $cell = __prj_cell($prj, $s, $p);
			if ($cell->{ccontents}) {				
      			$res .= "   <html><a href='doku.php?id=$ns:s${s}p${p}'><img id=\"img_${s}_${p}\"></a><html><input id=\"t_${s}_${p}\" type='checkbox' checked='yes'><br></html>";
      			$res .= " [[$ns:s${s}p$p|S$s P$p]]";
					__create_part($WIKIROOT,$s,$p,$dest,$prj,$force); # XXX
			}
			else {
				$res .= '   <html><span class="empty_cell">&Oslash;</span></html>';	
			}
			$res .= '   |';
   		}
		$res .= "   <html><input type='submit' onclick=\"javascript: curr_line = $p; build_line(); return false;\" value='  Build  P$p  '></html>   |\n";
	}
	$res .=  "|       | ";
	for my $s (1 .. @sections) {
		$res .= "   <html><input type='submit' onclick=\"javascript: curr_col = $s; build_col(); return false;\" value='  Build S$s  '></html>   |";
	}
	$res .= "   <html><input onclick=\"javascript: build(); return false;\" type='submit' value='  Build!  '><br><span style='font-size: 75%'>Select: <a href=\"javascript: select_all();\">All</a> | <a href=\"javascript: unselect_all();\">None</a></span></html>   | \n"; # XXX fix link

	$res .= "\n\n===== Misc =====\n\n";
	$res .= "  * [[$ns:spec|Project Specification]]\n";
	$res .= "  * {{:$ns:".lc($ns).".json?nocache|Project Data (JSON)}}\n";
	#$res .= "  * <html><a href='./mabc_handler.php?action=column&id=$ns'>Concat Sections</a></html>";
	#$res .= "  * [[conf|Ficheiro de configuração]]\n";
	#$res .= "  * [[t_abc|Template ABC]]\n";

	$res .= "\n" . __my_js(scalar(@sections),scalar(@parts),$ns);

	return $res;
}


# create/update project state file (after create/update project index file! ) 
sub __create_state {

	my $res;

	my ($WIKIROOT,$dest,$prj,$force) = @_;
	my $ns = __prj_attr($prj, 'namespace') || $prj->{prjId};

	my @sections = sort {$a->{scoord} <=> $b->{scoord}} @{$prj->{sections}};
	my @parts = sort {$a->{pcoord} <=> $b->{pcoord}} @{$prj->{parts}};
	my $filter = $WIKIROOT.'/lib/filters/TextAbcfilter/text-abcfilter';
	my $target;
	my $cell_state;

	for my $p (1 .. @parts) {
		for my $s (1 .. @sections) {
			my $cell = __prj_cell($prj, $s, $p);
			if ($cell->{ccontents}) {
			 	#correr filtro					
				$target = "$dest/s${s}p${p}.txt";
				$cell_state = `$filter $target`;
				if($p < 10) {$res .= "$cell_state\[${s}0$p\]";}
				else {$res .= "$cell_state\[$s$p\]";}							
			}
			else {
				$res .= '------';	
			}
			$res .= ';';
   		}
		$res .= "\n";
	}

	return $res;
}




sub __create_part {
	my ($WIKIROOT,$s,$p,$dest,$prj,$force) = @_;
	$conf{'barpp'} ||=5;

	my $target = "$dest/s${s}p${p}.txt";
	return if -e $target && !$force;
	my @created;

	my $cell = __prj_cell($prj, $s, $p);
	my $ns = __prj_attr($prj, 'namespace') || $prj->{prjId};

	my $c = "===== " . __prj_attr($prj,'title') . " =====\n\n";

	my @sections = sort {$a->{scoord} <=> $b->{scoord}} @{$prj->{sections}};
    	if (__section_attr($sections[$s-1], 'fol.')) {
        $c .= "   * ".__section_attr($sections[$s-1], 'fol.')."\n";
	}
	
	if (__prj_attr($prj,'facsimile')) {
       		$c .= "   * [[".__prj_attr($prj,'facsimile')."|Facsimile]]\n\n";
	}
	else {$c .= "   * __\n";}
	

	$c .= "==== Section $s: $cell->{secid} ====\n\n";
	$c .= "=== Part $p: $cell->{parid} ===\n\n";

   my $default_abc = $cell->{raw};

   if (-e $target) {
		my $txt = read_file($target, {binmode=>':utf8'});
      if ($txt =~ m/%%staves.*?\n(.*)\s*<\/abc>/s) {
          my $old = $1;
          $default_abc =~ s/(%%staves.*?\n)/$1$old/s;
		}
   }

   $default_abc =~ s/\[.*?\]\s*$//;
	$c .= "<abc>$default_abc\n</abc>\n"; # XXX

	# add abc links
	$c .= "\nUseful links: [[http://abcnotation.com/blog/2009/12/23/how-to-get-started-with-abc-notation/|Get Started With Abc]] [[http://abcnotation.com/examples|Abc Examples]] [[http://abcnotation.com/wiki/abc:standard:v2.1|Abc Standard]]\n";

	# handle remarks
   my $remarks = $cell->{remarks} || '';
   #$c .= "\n=== Remarks ===\n\n$remarks";

   $c .= "\nJump to: [[$ns:index|Project Index]] | \n";
   $c .= "<html> <select name='cell' onchange=\"javascript: window.location = '/wiki-score/doku.php?id=$ns:'+this.options[this.selectedIndex].value;\"> <option selected='selected' value='s${s}p${p}'>Project cell</option>";
   #foreach (@{$prj->{cells}}) {
   foreach (sort {$a->{Cell}->{ycoord} <=> $b->{Cell}->{ycoord} && $a->{Cell}->{xcoord} <=> $b->{Cell}->{xcoord}} @{$prj->{cells}}) {
      my $str = "s$_->{Cell}->{xcoord}p$_->{Cell}->{ycoord}";
      $c .= "<option value='$str'>$str</option>";
   }
   $c .= '</select></html> | [[:start|Wiki Index]]';

	write_file($target, {binmode => ':utf8'}, $c);
	push @created, $target;

	__fix_permissions($WIKIROOT, @created);
}

sub __create_spec {
	my ($prj, $hs) = @_;
	my $ns = __prj_attr($prj, 'namespace') || $prj->{prjId};

   my $res = "====== " . __prj_attr($prj,'title') . " ======\n\n";
   $res .= "===== Specification =====\n\n";
	$res .= "<code>\n$hs\n</code>\n";
	$res .= " <html><input type='submit' disabled='yes' onclick=\"parent.location='./mabc_handler.php?action=$prj->{prjId}'\" value='  Update Project  '></html> |\n";
	$res .= "[[$ns:index|Back to project index]]\n";

	return $res;
}

sub __prj_cell {
	my ($prj, $s, $p) = @_;

	my $cell;
	foreach (@{$prj->{cells}}) {
		$cell = $_->{Cell} if ($_->{Cell}->{xcoord} == $s) and ($_->{Cell}->{ycoord} == $p);
	}

	return $cell;
}

sub __my_js {
   my ($c, $l, $ns) = @_;
	my $js=<<"EOF";
<html>
  <style type="text/css">
  #overlay {
     visibility: hidden;
     position: absolute;
     left: 0px;
     top: 0px;
     width:100%;
     height:100%;
     z-index: 1000;
  }
  #overlay div {
     width: 70%;
     margin: 80px auto;
     background-color: #fff;
     border:1px solid #000;
     padding:15px;
     -moz-box-shadow: 5px 5px 5px #555;
     -webkit-box-shadow: 5px 5px 5px #555;
     box-shadow: 5px 5px 5px #555;
  }
  </style>
  <div id="overlay">
     <div>
       <span style="font-weight: bold; font-size: 16px;">Build Result</span><span style="float: right;"><a href="javascript: show_overlay();">Close</a></span>
       <hr>
       <span style="font-size: 11px; padding-left: 10px;" id="overlay_download"></span><br>
       <span style="text-align:center;" id="overlay_content"><br>Please wait for build to finish...</span>
     </div>
  </div>
  <script type="text/javascript">
    var curr_col;
    var curr_line;

    function select_col(c) {
      var c_max = $c;
      var l_max = $l;
      for (l=1 ; l <= l_max ; l++) {
        var el = document.getElementById("t_"+c+"_"+l);
        if (!el) continue;
        el.checked = true;
      }
    }
    function un_select_col(c) {
      var c_max = $c;
      var l_max = $l;
      for (l=1 ; l <= l_max ; l++) {
        var el = document.getElementById("t_"+c+"_"+l);
        if (!el) continue;
        el.checked = false;
      }
    }

    function select_line(l) {
      var c_max = $c;
      var l_max = $l;
      for (c=1 ; c <= c_max ; c++) {
        var el = document.getElementById("t_"+c+"_"+l);
        if (!el) continue;
        el.checked = true;
      }
    }
    function un_select_line(l) {
      var c_max = $c;
      var l_max = $l;
      for (c=1 ; c <= c_max ; c++) {
        var el = document.getElementById("t_"+c+"_"+l);
        if (!el) continue;
        el.checked = false;
      }
    }

    function select_all() {
       var c_max = $c;
       var l_max = $l;
       for (c=1 ; c <= c_max ; c++)
         for (l=1 ; l <= l_max ; l++) {
           var el = document.getElementById("t_"+c+"_"+l);
           if (!el) continue;
           el.checked = true;
         }
    }
    function unselect_all() {
       var c_max = $c;
       var l_max = $l;
       for (c=1 ; c <= c_max ; c++)
         for (l=1 ; l <= l_max ; l++) {
           var el = document.getElementById("t_"+c+"_"+l);
           if (!el) continue;
           el.checked = false;
         }
    }

    function build_col() {
       var c_max = $c;
       var l_max = $l;
       document.getElementById("overlay_download").innerHTML = '';
       document.getElementById("overlay_content").innerHTML = '<br>Please wait for build to finish...';

       if (!curr_col) {
         alert("Please select a column before building.");
         return false;
       }

       var selected = new Array();
       for (l=1 ; l <= l_max ; l++) {
        var el = document.getElementById("t_"+curr_col+"_"+l);
        if (!el)
          continue;
        if (el.checked)
          selected.push(l);
        }
        var s = '['+selected.join()+']';

        var req = new XMLHttpRequest();
        req.onreadystatechange=function() {
          if (req.readyState==4 && req.status==200) {
            var c = req.responseText;
            var l = c.split('/*;;*/');
            document.getElementById("overlay_download").innerHTML = l[0];
            document.getElementById("overlay_content").innerHTML = l[1];
          }
        };
        var myurl = './mabc_handler.php?action=column&id=$ns&c='+curr_col+'&extra='+s;
        req.open("GET",myurl,true);
        req.send();
        show_overlay();
        scrollTo(0,0);
    }
    function build_line() {
       var c_max = $c;
       var l_max = $l;
       document.getElementById("overlay_download").innerHTML = '';
       document.getElementById("overlay_content").innerHTML = '<br>Please wait for build to finish...';

       if (!curr_line) {
         alert("Please select a part before building.");
         return false;
       }

       var selected = new Array();
       for (c=1 ; c <= c_max ; c++) {
        var el = document.getElementById("t_"+c+"_"+curr_line);
        if (!el)
          continue;
        if (el.checked)
          selected.push(c);
        }
        var s = '['+selected.join()+']';

        var req = new XMLHttpRequest();
        req.onreadystatechange=function() {
          if (req.readyState==4 && req.status==200) {
            var c = req.responseText;
            var l = c.split('/*;;*/');
            document.getElementById("overlay_download").innerHTML = l[0];
            document.getElementById("overlay_content").innerHTML = l[1];
          }
        };
        var myurl = './mabc_handler.php?action=row&id=$ns&r='+curr_line+'&extra='+s;
        req.open("GET",myurl,true);
        req.send();
        show_overlay();
        scrollTo(0,0);
    }
    function build() {
       document.getElementById("overlay_download").innerHTML = '';
       document.getElementById("overlay_content").innerHTML = '<br>Please wait for build to finish...';

       var req = new XMLHttpRequest();
       req.onreadystatechange=function() {
          if (req.readyState==4 && req.status==200) {
            var c = req.responseText;
            var l = c.split('/*;;*/');
            document.getElementById("overlay_download").innerHTML = l[0];
            document.getElementById("overlay_content").innerHTML = l[1];
          }
       };
       var myurl = './mabc_handler.php?action=all&id=$ns';
       req.open("GET",myurl,true);
       req.send();
       show_overlay();
       scrollTo(0,0);
    }
    function show_overlay() {
        el = document.getElementById("overlay");
        el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
    }

    function loadMatrixState() {

	var ajax = new XMLHttpRequest();

        ajax.onreadystatechange = function(){
                    if(ajax.readyState==4){                     
			 var state = ajax.responseText;

                         var matrix_state = state.split('\\n');
			 var line_state;
                         var cell_state;
 			 var i = 0;
                         var j = 0;
			 var path_to_images = "lib/tpl/default/images/[selected_text]";           
       			 var selected_text;
			 var c_max = $c;
       	  		 var l_max = $l;

        		
			 for (l=1 ; l <= l_max ; l++) {
                                line_state = matrix_state[i++].split(';');
				j = 0;	
                         	for(c=1 ; c <= c_max; c++){ 					
                			var img = document.getElementById("img_"+c+"_"+l);          
        				if(!img) {j++; continue;}

        				cell_state = line_state[j++][0];    
					switch(cell_state)
					{
					case '1':
				        	selected_text = 'cell1.png';
 						break;
                                        default : selected_text = 'cell.png';
					}
       
                                        img.src = path_to_images.replace("[selected_text]",selected_text);                       		      	 
           			}
        		}        
                    }
        }       
       
        var myurl = 'state_handler.php?id=$ns';
        ajax.open("POST",myurl,false);
        ajax.send();  
    }	



  </script>
  <style type="text/css">
    .empty_cell {
      background-color: white;
    }
  </style>
<body onload="loadMatrixState()">
</body>
</html>
EOF
	return $js;
}

=head1 AUTHOR

Nuno Carvalho, C<< <smash at cpan.org> >>

José João Almeida, C<< <jj@di.uminho.pt> >>

=head1 BUGS

Please report any bugs or feature requests to C<bug-music-coopera at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Wiki-Score>.  I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.




=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Wiki::Score


You can also look for information at:

=over 4

=item * RT: CPAN's request tracker

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Wiki-Score>

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/Wiki-Score>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/Wiki-Score>

=item * Search CPAN

L<http://search.cpan.org/dist/Wiki-Score/>

=back


=head1 ACKNOWLEDGEMENTS


=head1 LICENSE AND COPYRIGHT

Copyright 2011 Nuno Carvalho.

This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.


=cut

1; # End of Wiki::Score
