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;
                    var attachment = {'href':d+p.one, name:p.title, description:p.content_text, media:[{type:'flash', swfsrc:d+'/v.swf?photo_id='+p.photo_id, imgsrc:d+p.standard_download, width:p.standard_width, height:p.standard_height, expanded_width:p.standard_width, expanded_height:p.standard_height}]};
                  } catch(e) {
                    try {
                      var s = visual.site;
                      var attachment = {'href':'http://' + s.domain, name:s.site_name};
                    } catch(e) {
                      var attachment = {'href':location.href, name:window.title};
                    }
                  }
                  FB.Connect.streamPublish(this.form.content.value, attachment, null, null, null, function(){this.reload();}.bind(this), true);
                } else {
                  // Just update the page, please
                  this.reload();
                }
              }
              
              // Re-enable submit
              this.setBusy(false);
            }.bind(this)});
      }
    },
    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') {
        this.facebook_uid = FB.Connect.get_loggedInUser();
        if(this.facebook_uid) {
          this.has_facebook = true;
          $$('.comment-input-identity').each(Element.hide);
          FB.Facebook.apiClient.fql_query('select name, pic_square_with_logo, profile_url  from user where uid='+this.facebook_uid, 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));
        }
      }
    },
    reload: function(){
      location.href = location.href.replace(/#.+$/img, '');
    }
  });
