dojo.hostenv.setModulePrefix('ricebridge', 'ricebridge');
dojo.require("dojo.widget.*");
dojo.widget.manager.registerWidgetPackage('ricebridge.widget');
dojo.require("ricebridge.widget.RicebridgeProgress");


function startProgress() {
  var progress = dojo.widget.manager.getWidgetById("progress");
  if( progress ) {
    progress.startProgress();
  }
}

function stopProgress() {
  var progress = dojo.widget.manager.getWidgetById("progress");
  if( progress ) {
    progress.stopProgress();
  }
}


function Doc( doc ) {
  this.doc = doc;
  this.get = function( elementID ) {
    return this.doc.getElementById( elementID );
  }
  this.make = function( elementName ) {
    return this.doc.createElement( elementName );
  }
  this.text = function( text ) {
    return this.doc.createTextNode( text );
  }
  this.show = function( element ) {
    if( null != element ) { 
      element.style.visibility='visible'; 
    }
  }
  this.hide = function( element ) {
    if( null != element ) { 
      element.style.visibility='hidden'; 
    }
  }
}


function Table( doc ) {
  this.doc   = doc;
  this.table = 0;

  this.build = function( data, fieldnames ) {
    if( 0 == data.length ) {
      return;
    }

    this.table = this.doc.make('table');
    this.table.className = 'data xd_data';

    var tbody = this.doc.make('tbody');

    var tr = this.doc.make('tr');
    var th = this.doc.make( 'th' ); 
    th.innerHTML = 'Record';
    tr.appendChild( th );

    for( var fieldI = 0; fieldI < fieldnames.length; fieldI++ ) {
      var th = this.doc.make( 'th' ); 
      th.innerHTML = fieldnames[fieldI];
      tr.appendChild( th );
    }
    tbody.appendChild( tr );

    for( var rowI = 0; rowI < data.length; rowI++ ) {
      tr = this.doc.make('tr');
      var td = this.doc.make( 'td'); 
      td.innerHTML = ''+(rowI+1);
      tr.appendChild( td );

      var row = data[rowI];
      for( var colI = 0; colI < row.length; colI++ ) {
        td = this.doc.make( 'td' ); 
        td.innerHTML = row[colI];
        tr.appendChild( td );
      }

      tbody.appendChild( tr );
    }

    this.table.appendChild( tbody );
  };

  this.firstChildOf = function( element ) {
    if( 0 != this.table ) {
      if( element.childNodes[0] ) {
        element.replaceChild( this.table, element.childNodes[0] );
      }
      else {
        element.appendChild( this.table );
      }
    }
  };
}

function XmlDemo( doc ) {

  this.doc       = doc;
  this.content   = null;
  this.xmlsample = null;
  this.csvsample = null;
  this.type      = 'xml';

  this.handleTab = function( event ) {
    var tab = event.currentTarget;
    for( i=0;i<this.tabs.length;i++) { this.taboff(this.tabs[i]); }
    this.tabon(tab);
  }

  this.taboff = function( tab ) {
    tab.style.backgroundColor = '#bcb';
    tab.style.borderBottom = '0px';
  }

  this.tabon = function( tab ) {
    this.storesample();
    this.coveron();
    tab.style.backgroundColor = '#ded';
    tab.style.borderBottom = '3px solid #787';
    this.doc.hide( this.content );
    this.content = this.tabcontent[tab.id];
    this.type    = this.tabtype[tab.id];
    if( 'xml' == this.type ) {
      this.showsample( null == this.xmlsample ? samples.xml.simple : this.xmlsample, false );
    }
    else if( 'csv' == this.type ) {
      this.showsample( null == this.csvsample ? samples.csv.simple : this.csvsample, false );
    }
    this.doc.show( this.content );
    this.coveroff();
  }


  this.handleSample = function( event ) {
    this.coveron();
    this.showsample( this.samplelinks[event.currentTarget.id], true );    
    this.coveroff();
  }

  function setTableData( data ) {
    var div   = this.doc.get('xd_datatable');
    var table = new Table( this.doc );
    table.build( data, lastfields );
    table.firstChildOf( div );
  };

  function setXmlData( xml ) {
    document.xd_form.xd_genxml.value = xml;
  };

  function setMessage( msg ) {
    if( 'xml' == gType ) {
      document.xd_form.xd_xmlin_msg.value = msg;
    }
    else {
      document.xd_form.xd_xmlout_msg.value = msg;
    }
  };

 
  this.handleProcess = function( event ) {
    this.process( this.type );
  }

  this.process = function( type ) {
    var rs = { record: document.xd_form.xd_record.value };

    var field  = null;
    var fields = [];
    var fI = 0;
    while( null != (field = this.doc.get('xd_field'+fI ) ) ) {
      fields[fI] = field.value;
      fI++;
    }
    rs.fields = fields;
    lastfields = fields;

    var datatext = null;
    if( 'xml' == type ) {
      datatext = document.xd_form.xd_xmlin_text.value;
    }
    else if( 'csv' == type ) {
      datatext = document.xd_form.xd_xmlout_text.value;
    }
    gType = type;

    var jsonquery    = { type: type, rs: rs, data: datatext };
    var jsonquerystr = JSON.stringify(jsonquery);
    startProgress();
    dojo.io.bind({
      url: 'demo-handler.htm',
      method: 'post',
      postContent: jsonquerystr,
      handle: function(type, data, evt){ 
        stopProgress();
        if( type == 'load' ){
           jso = JSON.parse(data);
           if( jso.data ) {
             setTableData( jso.data );
           }
           else if( jso.xml ) {
             setXmlData( jso.xml );
           }
           setMessage( jso.stats+(jso.msg?jso.msg:'') );
        } 
        else {
          setMessage( "Sorry, there's been a server error." );
        }
      },
      mimetype: 'text/plain'
    });
  };


  this.addField = function() {
    this.coveron();

    var fields = this.doc.get('xd_fields');   
    var li     = this.doc.make('li');
    var num    = fields.getElementsByTagName('li').length;

    var label = this.doc.make('label');
    label.appendChild( this.doc.text('Field '+num) );
    li.appendChild( label );
    var input = this.doc.make('input');
    input.id = 'xd_field'+(num-1);
    input.className = 'text';
    input.setAttribute('type','text');
    input.setAttribute('value','');
    li.appendChild(input);

    fields.appendChild( li );
    document.xd_form.xd_removeField.style.visibility='visible';

    this.coveroff();
  }


  this.removeField = function() {
    this.coveron();

    var fields = this.doc.get('xd_fields');   
    var lis    = fields.getElementsByTagName('li');
    if( 2 < lis.length ) {
      fields.removeChild(lis[lis.length-1]);
    }
    if( 2 == lis.length ) {
      document.xd_form.xd_removeField.style.visibility='hidden';
    }

    this.coveroff();
  };


  this.removeAllFieldsAbove = function( above ) {
    this.coveron();

    var fields = this.doc.get('xd_fields');   
    var lis    = fields.getElementsByTagName('li');
    while( 2 < lis.length && above <= lis.length ) {
      fields.removeChild(lis[lis.length-1]);
    }
    if( 2 == lis.length ) {
      document.xd_form.xd_removeField.style.visibility='hidden';
    }

    this.coveroff();
  };


  this.coveron = function() {
    //this.doc.show( this.doc.get('xd_content_cover') );   
  };

  this.coveroff = function() {
    //this.doc.hide( this.doc.get('xd_content_cover') );   
  };


  this.showsample = function( sample, store ) {
    if( store ) {
      this.storesample();
    }

    document.xd_form.xd_record.value = sample.rec;

    this.removeAllFieldsAbove(sample.fields.length);
    for( i=0;i<sample.fields.length;i++ ) {
      if( null == this.doc.get('xd_field'+i) ) {
        this.addField();
      }
      this.doc.get('xd_field'+i).value = sample.fields[i];
    }

    if( sample.xml ) {
      document.xd_form.xd_xmlin_text.value = sample.xml;
      setTableData( [] );
    }
    else if( sample.csv ) {
      document.xd_form.xd_xmlout_text.value = sample.csv;
    }

    if( sample.xml ) {
      this.xmlsample = sample;
    } 
    else {
      this.csvsample = sample;
    }
  }

  this.storesample = function() {
    var cursample = 'xml'==this.type?this.xmlsample:this.csvsample;
    if( null != cursample ) {
      cursample.rec = document.xd_form.xd_record.value;
      var fI = 0;
      while( null != this.doc.get('xd_field'+fI ) ) {
        cursample.fields[fI] = this.doc.get('xd_field'+fI).value;
        fI++;
      }
      if( cursample.xml ) {
        cursample.xml = document.xd_form.xd_xmlin_text.value;
      }
      else if( cursample.csv ) {
        cursample.csv = document.xd_form.xd_xmlout_text.value;
      }
    }

  }

  
  this.initui = function( samples ) {
    dojo.event.connect( doc.get('xd_b_process'), 'onclick', this, 'handleProcess' );

    dojo.event.connect( doc.get('xd_xmlin_tab'), 'onclick', this, 'handleTab' );
    dojo.event.connect( doc.get('xd_xmlout_tab'), 'onclick', this, 'handleTab' );

    dojo.event.connect( doc.get('xd_xis_simple'), 'onclick', this, 'handleSample' );
    dojo.event.connect( doc.get('xd_xis_rss'), 'onclick', this, 'handleSample' );
    dojo.event.connect( doc.get('xd_xis_atom'), 'onclick', this, 'handleSample' );

    dojo.event.connect( doc.get('xd_xos_simple'), 'onclick', this, 'handleSample' );
    dojo.event.connect( doc.get('xd_xos_table'), 'onclick', this, 'handleSample' );

    this.tabs = [ this.doc.get('xd_xmlin_tab'), this.doc.get('xd_xmlout_tab') ];
    this.tabcontent = { xd_xmlin_tab:this.doc.get('xd_xmlin'), xd_xmlout_tab:this.doc.get('xd_xmlout') };
    this.tabtype    = { xd_xmlin_tab:'xml', xd_xmlout_tab:'csv' };

    this.samples = samples;
    this.samplelinks = { xd_xis_simple:this.samples.xml.simple,
                         xd_xis_rss:this.samples.xml.rss, 
                         xd_xis_atom:this.samples.xml.atom,

                         xd_xos_simple:this.samples.csv.simple,
                         xd_xos_table:this.samples.csv.table };
 
    this.showsample( this.samples.xml.simple, false );
  }
}

var samples = {
  xml: {
    simple: { rec:"/root/record", fields:["@name","foo","bar"], xml:'<root>\n  <record name="r1">\n    <foo>f1</foo>\n    <bar>b1</bar>\n  </record>\n  <record name="r2">\n    <foo>f2</foo>\n    <bar>b2</bar>\n  </record>\n  <record name="r3">\n    <foo>f3</foo>\n    <bar>b3</bar>\n  </record>\n</root>\n' },
    rss: { rec:"//item", fields:["/rss/channel/title","title","description","pubDate"], xml:'<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0">\n  <channel xml:base="http://www.ricebridge.com/admin/feeds/">\n  <title>Ricebridge News</title>\n  <link>http://www.ricebridge.com/admin/feeds/news.rss</link>\n  <copyright>Copyright (c) 2005 Ricebridge</copyright>\n  <description>Ricebridge News</description>\n  <lastBuildDate>Tue Dec 07 11:30:00 GMT 2005</lastBuildDate>\n\n  <item>\n    <title>Red News</title>\n    <link>http://www.ricebridge.com/news/red.htm</link>\n    <description>\n      &lt;p&gt;red stuff&lt;/p&gt;\n    </description>\n    <pubDate>Tue, 07 Dec 2005 09:30:00 GMT</pubDate>\n  </item>\n\n  <item>\n    <title>Blue News</title>\n    <link>http://www.ricebridge.com/news/blue.htm</link>\n    <description>\n      &lt;p&gt;blue stuff&lt;/p&gt;\n    </description>\n    <pubDate>Tue, 07 Dec 2005 10:30:00 GMT</pubDate>\n  </item>\n\n  <item>\n    <title>Green News</title>\n    <link>http://www.ricebridge.com/news/green.htm</link>\n    <description>\n      &lt;p&gt;green stuff&lt;/p&gt;\n    </description>\n    <pubDate>Tue, 07 Dec 2005 11:30:00 GMT</pubDate>\n  </item>\n\n  </channel>\n</rss>' },
    atom: { rec:"/feed/entry", fields:["/feed/title", "title","link[not(@rel) or @rel='alternate']/@href","content/@type","rb:xml(content)"], xml:'<?xml version="1.0" encoding="UTF-8"?>\n<feed xmlns="http://www.w3.org/2005/Atom"\n      xml:base="http://www.example.com/"\n      xml:lang="en-us">\n <title>Atom</title>\n <link href="http://www.example.com/atom" />\n <link rel="self" href="atom/atom.xml" />\n <logo>atom.gif</logo>\n <icon>atom.ico</icon>\n <updated>2005-07-12T15:21:01-00:00</updated>\n <author><name>Richard Rodger</name></author>\n <subtitle>An Atom test case for XmlManager</subtitle>\n <id>http://www.example.com/atom</id>\n <rights>Public Domain</rights>\n <generator>By Hand</generator>\n\n <entry>\n  <title>Red</title>\n  <link href="http://www.example.com/red" />\n  <id>http://www.example.com/red</id>\n  <published>2005-07-01T01:00:00-00:00</published>\n  <updated>2005-07-01T01:01:00-00:00</updated>\n  <category scheme="http://www.example.com/category" term="color/red" label="Colors/Red" />\n  <category scheme="http://www.example.com/category" term="word/red" label="Words/Red" />\n  <content type="xhtml">\n<div xmlns="http://www.w3.org/1999/xhtml">red <b>red</b> reds</div>\n  </content>\n </entry>\n\n <entry><title>Green</title>\n  <link href="http://www.example.com/green" />\n  <id>http://www.example.com/green</id>\n  <published>2005-07-02T01:00:00-00:00</published>\n  <updated>2005-07-02T01:01:00-00:00</updated>\n  <category scheme="http://www.example.com/category" term="color/green" label="Colors/Green" />\n  <category scheme="http://www.example.com/category" term="word/green" label="Words/Green" />\n  <content type="xhtml">\n<div xmlns="http://www.w3.org/1999/xhtml">green <b>green</b> greens</div>\n  </content>\n </entry>\n\n <entry><title>Blue</title>\n  <link href="http://www.example.com/blue" />\n  <id>http://www.example.com/blue</id>\n  <published>2005-07-03T01:00:00-00:00</published>\n  <updated>2005-07-03T01:01:00-00:00</updated>\n  <category scheme="http://www.example.com/category" term="color/blue" label="Colors/Blue" />\n  <category scheme="http://www.example.com/category" term="word/blue" label="Words/Blue" />\n  <content type="xhtml">\n<div xmlns="http://www.w3.org/1999/xhtml">blue <b>blue</b> blues</div>\n  </content>\n </entry>\n</feed>\n'}
  },
  csv: {
    simple: { rec:"/root/record", fields:["@name","foo","bar"], csv:'r1,f1,b1\nr2,f2,b2\nr3,f3,b3'},
    table: { rec:"/table/tr", fields:["td[1]","td[2]","td[3]"], csv:'One,Red,10\nTwo,Green,20\nThree,Blue,30' }
  }
};


var gType = 'xml';
var doc = new Doc(document);
var xmldemo = new XmlDemo(doc);
var lastfields = [];

function xmlDemoOnLoad() {
  xmldemo.initui( samples );
}

dojo.event.connect(window, "onload", xmlDemoOnLoad);