/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/
jQuery.noConflict();

var Utf8 = {

    // public method for url encoding
    encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    },

    // public method for url decoding
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }
        return string;
    }
}

var ajax_comments = {
  locked: [],

  onsubmit: function() {
    var form = this;
    if (ajax_comments.locked[form]) { return false; } // one at a time
    else { ajax_comments.locked[form] = true; } // lock this form

    jQuery.ajax({
      type: 'POST',
      //url: 'http://se.pianetascuolatest.it/wp-content/plugins/ajax-comments/ajax-comments-post.php',
      //url: 'http://192.168.151.86/pscuola/nose/servizi/feedback/feedback_scrivi_xmlrpc.jsp',
      url: '/pscuola/nose/servizi/feedback/feedback_scrivi_xmlrpc.jsp',
      data: jQuery(this).formSerialize(),
      dataType: 'json',
      cache: false,
      timeout: 60000,

      beforeSend: function(XMLHttpRequest) {
        jQuery('.ajax_comments_error', form).remove(); // remove any previous errors
        jQuery('input[@type=submit]', form) // select form submit button
          .attr('disabled', 'disabled') // disable it
          .hide() // hide it
          //.after('<div class="ajax_comments_spinner" title="Submitting your comment..." style="background:url(http://se.pianetascuolatest.it/wp-content/plugins/ajax-comments/ajax-comments-spinner.gif);width:220px;height:19px;text-indent:-9999px;font-size:0;line-height:0;">Submitting...</div>'); // show AJAX spinner
          .before('<div class="ajax_comments_spinner" title="Submitting your comment..." style="background:url(http://se.pianetascuolatest.it/wp-content/plugins/ajax-comments/ajax-comments-spinner.gif);width:220px;height:19px;text-indent:-9999px;font-size:0;line-height:0;">Submitting...</div>'); // show AJAX spinner
      },

      success: function(data, textStatus) {
        if ( // validate server response
          typeof(data.comment_type) == 'undefined' ||
          typeof(data.comment_ID) == 'undefined' ||
          typeof(data.comments_template) == 'undefined' ||
          !data.comments_template ||
          data.comment_error
        ) { // if response is not as expected...
          //this.error({responseText:''}, '', ''); // display unknown error
          this.error({responseText:data.comment_error}, 'errore', ''); // display unknown error
          return; // abort
        }

        var wrapper = jQuery(form).parents('div#ajax_comments_wrapper');
        var commentlist = jQuery('#commentlist', wrapper);
        var new_wrapper = jQuery(Utf8.decode(data.comments_template));
        //var new_comment = jQuery('#comment-'+ data.comment_ID +', #commentlist *:last', new_wrapper).eq(0).hide();
        var new_comment = jQuery('#comment-'+ data.comment_ID , new_wrapper).hide();
        if (data.comment_type == 'conventional' && commentlist.length > 0) {  
          //commentlist.append(new_comment); // append new comment to existing wrapper          
          //jQuery('#comments', wrapper).after(jQuery('#comments', new_wrapper)).remove(); // replace comment count element
          //FS20081027
   
          var title = jQuery('h3', commentlist); // Tutti i commenti.  
          jQuery('.commenthead', commentlist).remove(); //tolgo commento di testa
          commentlist.prepend(new_comment);		// metto il nuovo commento in testa
          jQuery('h3', commentlist).remove(); 
          new_comment.before(jQuery(new_wrapper));
          //title.after(jQuery(new_wrapper));
          //jQuery('#comments', wrapper).after(jQuery('#comments', new_wrapper)).remove();
          
        } else { // flexible
          var new_comment_form = jQuery('//textarea[@name=comment]', new_wrapper).parents('form');
          if (new_comment_form.length) {
            new_comment_form.after(form).remove(); // replace comment form in new wrapper
          } else {
            new_wrapper.append(form); // append comment form to new wrapper
          }
          wrapper.after(new_wrapper).remove(); // replace old wrapper with new
        }
        jQuery('#tab1Link0').click();
        new_comment.fadeIn('slow'); // show new comment using nice effect

        // WP Ajax Edit Comments compatibility
        if (typeof(AjaxEditComments) != 'undefined') {
          AjaxEditComments.init();
        }
        
        jQuery('textarea#comment', form).val(''); // clear comment

        this.cleanup();
      },

      error: function(XMLHttpRequest, textStatus, errorThrown) {
        var error = '';
        if (typeof(XMLHttpRequest.responseText) == 'string' && XMLHttpRequest.responseText != '') {
          error = textStatus + ': ' + XMLHttpRequest.responseText;
        } else if (textStatus == 'timeout') {
          error = 'The server is taking too long to respond. Please try again later.';
        } else {
          error = 'Unknown error while submitting your comment. Try again?';
        }
        jQuery(form).prepend('<div class="ajax_comments_error" style="background:#d00d00;margin:1em 0;padding:.8em;color:#fff;line-height:1.3em;">'+ error +'</div>'); // display error above comment form
        this.cleanup();
      },

      cleanup: function() {
        jQuery('.ajax_comments_spinner', form).remove(); // remove the AJAX spinner
        jQuery('input[@type=submit]', form) // select form submit button
          .removeAttr('disabled') // enable it
          .show(); // show it
        ajax_comments.locked[form] = false; // unlock this form
      }
    });
    return false; // abort non-AJAX form submission
  }
}

// execute on document load
jQuery(function() {
  // bind to the comment form
  jQuery('#commentform').bind('submit', ajax_comments.onsubmit);
});
