var CommentHandler = Class.create({
    initialize: function(form, recaptcha_key) {
      // Prepare for action
      this.form = $(form);
      this.form.return_url.value = '';
      this.busy = false;
      // Handle submit flow
      this.form.observe('submit', this.submit.bind(this));
      this.addIndicator();
      // Handle signing and captchas
      this.has_recaptcha = false;
      this.recaptcha_key = recaptcha_key;
      this.form.signature.value=hex_md5(this.form.signature_key.value);
      // Handle Facebook Connect
      this.facebook_uid = null;
      this.has_facebook = false;
      this.updateFacebookConnect();
      // Error messages
      this.error_container = this.form.select('.comment-error-message')[0];
      this.error_container.hide();
    },
    setBusy:function(busy){
      this.busy = busy;
      this.form.select('.indicator').each(function(el){el.setStyle({display:(busy?'block':'none')})});
    },
    addIndicator:function(){
      this.form.appendChild(new Element('div').addClassName('indicator').update('Posting your comment...'));
    },
    submit:function(e){
      // Over-write default submit action
      Event.stop(e);

      if (!this.busy) {
        // Dsiable button for now
        this.setBusy(true);
        // Hide error message
        this.error_container.hide();
        // Submit the comment,
        new Ajax.Request('/actions', {postBody:this.form.serialize(), method:'POST', onComplete:function(r){
              // Parse return status
              var status = /^([a-z]+): (.+)$/.exec(r.responseText);
              
              switch(status[1]) {
              case 'input':
                // Not all fields are filled in
                this.error_container.update(status[2]);
                this.error_container.show();
                break;
                
              case 'badsignature':
              case 'spam':
              case 'recaptchafailed':
                // Not all fields are filled in
                this.addReCaptcha(status[2]);
                break;
                
              case 'ok':
              default:
                // All is good, ...
                if(this.has_facebook && this.facebook_uid) {
                  // If we're using Facebook, prompt the user to post message there as well...
                  try {
                    var d = 'http://' + visual.site.domain;
                    var p = visual.photo;
                    FB.ui({method:'feed', message:this.form.content.value, link:d+p.one, name:p.title, description:p.content_text, source:d+'/v.swf?photo_id='+p.photo_id, swfsrc:d+'/v.swf?photo_id='+p.photo_id, picture:d+p.standard_download, imgsrc:d+p.standard_download}, function(response){
                        this.reload();
                      }.bind(this));
                  }catch(e){console.debug(e);}
                } else {
                  // Just update the page, please
                  this.reload();
                }
              }
              
              // Re-enable submit
              this.setBusy(false);
            }.bind(this)});
      }
      return(false);
    },
    addReCaptcha: function(message){
      // Add the reCaptcha thingy to the form
      if (!this.has_recaptcha) {
        var wrapper = this.form.select('.comment-recaptcha')[0];
        var text = new Element('div').addClassName('comment-error');
        wrapper.appendChild(text);
        this.recaptcha_message = text;
        var container = new Element('div', {id:'recaptchaContainer'}).addClassName('comment-error comment-recaptcha');
        wrapper.appendChild(container);
        this.has_recaptcha = true;
        Recaptcha.create(this.recaptcha_key, "recaptchaContainer", {theme:'clean'});
      }
      this.recaptcha_message.update(message + ' To post the comment, write the two words you see on the image below and click the Post button again.');
    },
    updateFacebookConnect: function(){
      if (typeof(FB)!=='undefined') {
        FB.getLoginStatus(function(o){
            this.facebook_uid = o.session.uid;
            this.has_facebook = true;
            $$('.comment-input-identity').each(Element.hide);
            var q = FB.Data.query('select name, pic_square_with_logo, profile_url from user where uid={0}', this.facebook_uid);
            q.wait(function(rows){
                if (rows.length>0) {
                  var data = rows[0];
                  var image_node = this.form.select('.comment-facebook-image')[0];
                  image_node.appendChild(new Element('img', {src:data.pic_square_with_logo.replace(/amp;/img, '')}));
                  var name_node = this.form.select('.comment-facebook-name')[0];
                  name_node.setAttribute('href', data.profile_url);
                  name_node.update(data.name);
                  $$('.comment-facebook')[0].setStyle({display:'block'});
                }
              }.bind(this));
          }.bind(this));
      }
    },
    reload: function(){
      location.href = location.href.replace(/#.+$/img, '');
    }
  });

