var Espresso = Class.create({
  tmpl_mesg: '',
  tmpl_cover_text: '',
  tmpl_cover_img: '',
  tmpl: '',
  form_id: 'search_form',
  search_progress: 'search_progress',
  results_id: 'results',
  maillist_id: 'maillist_form',
  maillist_email: 'email_addr',
  maillist_mesg: 'maillist_mesg',
  order_email: 'oscarsbooks@shaw.ca',
  intervals: [],

  initialize: function(){
    this.tmpl_mesg = new Template('<div id="result_count" class="result_row message">#{status_message}</div>');
    this.tmpl_cover_text = new Template('<div class="book_cover">#{title_trunc}</div>');
    this.tmpl_cover_img = new Template('<img src="#{thumbnail}" alt="#{title}" title="#{title}" width="170"/>');
    this.tmpl_order_link = new Template('<a href="mailto:#{order_email}?subject=Book%20Request:%20#{isbn13}&body=Customer%20' +
      'Name:%20%0A%0AISBN:%20#{isbn13}%0ATitle:%20#{title}%0APrice:%20$#{srp}">' + '<div class="order_book order_link">Order this book</div></a>'
      );
    this.tmpl = new Template(
      '<div class="result_row"><div class="cover"><div class="divmid"><div class="divtop"><div class="divbot">#{cover}</div></div>' +
      '</div></div><div class="info"><h1>#{title}</h1><h2>By #{author}</h2><p class="price">Price: $#{srp} #{currency}</p><p>' +
      '(price to be confirmed)</p>#{order_link}<div class="preview"></div><div><table border="0" cellpadding="0" ' +
      'cellspacing="0" class="bookdetails"><tbody><tr><td><strong>Publisher</strong> #{publisher}</td><td><strong>Pages</strong> ' +
      '#{pages}</td></tr><tr><td><strong>Imprint</strong> #{imprint}</td><td><strong>ISBN</strong> #{isbn13}</td></tr><tr><td>' +
      '<strong>Supplier</strong> #{supplier}</td></tr></tbody></table></div></div><div class="clear"></div></div>'
      );
    if ($(this.form_id).tagName && $(this.form_id).tagName.toLowerCase()=='form'){
      $(this.form_id).observe('submit',this.doSearch.bindAsEventListener(this));
    }
    if ($(this.maillist_id).tagName && $(this.maillist_id).tagName.toLowerCase()=='form'){
      $(this.maillist_id).observe('submit',this.doSignUp.bindAsEventListener(this));
    }
  },
  doSignUp: function(e) {
    e.stop();
    var prg = $(this.maillist_mesg);
    prg.update('Contacting list');
    this.intervals.push(window.setInterval(function(){
      var text = prg.innerHTML;
      if (text.length < 19) {
        prg.update(text + '.');
      } else {
        prg.update('Contacting list')
      }
    }, 300));

    new Ajax.Request('/espresso.php',{method:'post',
      parameters: $(this.maillist_id).serialize(true),
      onSuccess: function(transport) {
    	var json = transport.responseText.evalJSON();
        prg.update('[ '+json.status_message+' ]');
        if (!json.success) {
          $(this.maillist_email).activate();
        }
      }.bind(this),
      onComplete: function(){
        this.intervals.each(function(s){
          window.clearInterval(s);
        });
      }.bind(this)
    });
  },
  doSearch: function(e){
    e.stop();
    $(document.getElementsByTagName('body')[0]).setStyle({cursor:'progress'});
    var prg = $(this.search_progress);
    this.intervals.push(window.setInterval(function(){
      var text = prg.innerHTML;
      if (text.length > 0 && text.length < 13){
        prg.update(text + '.');
      } else {
    	prg.update('Searching');
      }
    }, 300));

    new Ajax.Request('/espresso.php',{method:'post',
      parameters: $(this.form_id).serialize(true),
      onSuccess: this.displayResults.bind(this),
      onComplete: function(){
        $(document.getElementsByTagName('body')[0]).setStyle({cursor:''});
        this.intervals.each(function(s){
          window.clearInterval(s);
        });
        $(this.search_progress).update();
      }.bind(this)
    });
  },
  displayResults: function(transport) {
    var json=transport.responseText.evalJSON();
    $(this.results_id).descendants().invoke('remove');
    $(this.results_id).insert(this.tmpl_mesg.evaluate(json));
    json.results.each(function(s){
      s.title_trunc = s.title.truncate(100, '...');
      s.cover = (s.thumbnail.blank()) ? this.tmpl_cover_text.evaluate(s) : this.tmpl_cover_img.evaluate(s);
      s.order_email = this.order_email;
      s.order_link = this.tmpl_order_link.evaluate(s);
      $(this.results_id).insert(this.tmpl.evaluate(s));
    }.bind(this));
    /*
    var pagination = new Element('div',{'class':'pagination'});
    if (json.prev_page) {
      var prev_link = new Element('div',{'class':'left'}).insert(
        new Element('a',{style:'cursor:pointer'}).update('Previous').observe('click',function(e){
          $($(this.form_id).getInputs('hidden','p')[0]).setValue(json.prev_page);
          this.doSearch(e);
        }.bind(this)));
      pagination.insert(prev_link);
    }
    if (json.next_page) {
        var next_link = new Element('div',{'class':'right'}).insert(
          new Element('a',{style:'cursor:pointer'}).update('Next').observe('click',function(e){
            $($(this.form_id).getInputs('hidden','p')[0]).setValue(json.next_page);
            this.doSearch(e);
          }.bind(this)));
        pagination.insert(next_link);
    }
    $(this.results_id).insert(pagination);
    */
  }
});

