var comment_text = "";
var async_request = null;
var duplicate_prevention = generate_duplicate_prevention_string();
var pxuid = retrieve_user_id();

function open_comment() {
  var comment_area = document.getElementById( "comment_area" );
  var comment_link = document.getElementById( "comment_link" );
  if( comment_area && comment_link ) {
    comment_link.innerHTML = (
      '<SPAN class="comment_button">&nbsp;Leave&nbsp;comment&nbsp;</SPAN>' + 
      '<A class="comment_button" href="' + window.location.pathname + 
      '" onclick="close_comment(); return false;">&#215;</A>'
    );
    comment_area.innerHTML = (
      '<TABLE CELLSPACING=0 CELLPADDING=10 BORDER=0 BGCOLOR="#2D2D2D" style="margin-top: 6px;">' +
        '<TR><TD VALIGN=top ROWSPAN=2 WIDTH="100%" BGCOLOR="#FFFFFF">' +
          '&nbsp;' +
        '</TD><TD VALIGN=top>' +
          '<DIV class="comment_fnt">Message:</DIV>' +
        '</TD><TD VALIGN=top>' +
          '<TABLE CELLSPACING=0 CELLPADDING=0 BORDER=0><TR><TD COLSPAN="2">' +
            '<TEXTAREA COLS="35" ROWS="6" WRAP="SOFT" ID="comment_body"></TEXTAREA>' +
          '</TD></TR><TR><TD><DIV class="comment_err" ID="comment_error"></DIV></TD><TD>' +
            '<DIV ALIGN=RIGHT><INPUT TYPE=SUBMIT VALUE="Send" ID="send_button"></DIV>' +
          '</TD></TR>' + 
        '</TABLE>' +
      '</TD></TR></TABLE>'
    );
    var comment_body = document.getElementById( "comment_body" );
    if( comment_body ) {
      if( comment_text != "" ) {
        comment_body.value = comment_text;
      }
      comment_body.focus();
    }
  }
}

function close_comment() {
  var comment_body = document.getElementById( "comment_body" );
  if( comment_body ) {
    comment_text = comment_body.value;
  }
  var comment_area = document.getElementById( "comment_area" );
  var comment_link = document.getElementById( "comment_link" );
  if( comment_area && comment_link ) {
    comment_link.innerHTML = (
      '<A class="comment_button" href="' + window.location.pathname + '#' +
      '" onclick="open_comment(); return false;">&#9660;&nbsp;Leave&nbsp;comment&nbsp;</A>'
    );
    comment_area.innerHTML = '';
  }
}

function send_form() {
  if( async_request )
    return;
  var comment_body = document.getElementById( "comment_body" );
  var email_addr   = document.getElementById( "email_addr" );
  var post_data    = 'dup_prev=' + duplicate_prevention + 
                     '&short_url=' + encodeURIComponent( window.location.pathname );
  if( comment_body ) {
    comment_text = comment_body.value;
    if((! comment_text )||( comment_text == "" ))
      return;
    post_data += '&type=comment&value=' + encodeURIComponent(comment_text);
  } else if( email_addr ) {
    var email = email_addr.value;
    if((! email )||( email == "" ))
      return;
    if( email.indexOf('@') == -1 ) {
      show_comment_error( "Email address should contain @", false );
      return;
    }
    post_data += '&type=email&value=' + encodeURIComponent(email);
  } else {
    return;
  }
  if(( pxuid )&&( pxuid != "" )) {
    post_data += ('&pxuid=' + pxuid);
  }

  var req = null;
  if( window.XMLHttpRequest ) {
    try {
      req = new XMLHttpRequest();
    } catch (e){}
  } else if( window.ActiveXObject ) {
    try {
      req = new ActiveXObject( 'Msxml2.XMLHTTP' );
    } catch (e){
      try {
        req = new ActiveXObject( 'Microsoft.XMLHTTP' );
      } catch (e){}
    }
  }

  if( req ) {
    req.open( 'POST', 'http://' + window.location.hostname + '/shared/post_comment_async.php', true );
    req.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
    req.onreadystatechange = async_request_state_change;
    req.send( post_data );
    async_request = req;
  }
}

function async_request_state_change() {
  try {
    if( async_request ) {
      if( async_request.readyState == 4 ) {
        var req = async_request;
        async_request = null;
        duplicate_prevention = generate_duplicate_prevention_string();
  
        if( req.status != 200 ) {
          show_comment_error( "HTTP " + req.status + ": " + req.statusText, true );
        } else {
          var comment_body = document.getElementById( "comment_body" );
          if( comment_body ) {
            handle_async_success( false, req.responseText );
          } else {
            handle_async_success( true, req.responseText );
          }
        }
      }
    }
  } catch (e) {
    async_request = null;
    show_comment_error( "Internet connection error", true );
  }
}

function show_comment_error( error_message, is_connection_error ) {
  var comment_error = document.getElementById( "comment_error" );
  if( comment_error ) {
    comment_error.innerHTML = error_message;
  } else {
    alert( error_message );
  }
  if( is_connection_error ) {
    var send_button = document.getElementById( "send_button" );
    if( send_button ) {
      send_button.value = "Resend";
    }
  }
}

function handle_async_success( is_second_request, response_text ) {
  if(! is_second_request ) {
    comment_text = "";
    var comment_area = document.getElementById( "comment_area" );
    if( comment_area ) {
      if(( pxuid )&&( pxuid != "" )) {
        comment_area.innerHTML = (
          '<TABLE CELLSPACING=0 CELLPADDING=10 BORDER=0 ' + 
            'BGCOLOR="#2D2D2D" style="margin-top: 6px;">' + 
            '<TR><TD VALIGN=top WIDTH="100%" BGCOLOR="#FFFFFF">' +
              '&nbsp;' +
            '</TD><TD VALIGN=top>' +
              '<DIV class="comment_fnt" style="width:400px;">Sent successfully. Thank you.</DIV>' +
            '</TD></TR>' +
          '</TABLE>'
        );
      } else {
        comment_area.innerHTML = (
          '<TABLE CELLSPACING=0 CELLPADDING=10 BORDER=0 ' + 
            'BGCOLOR="#2D2D2D" style="margin-top: 6px;">' +
            '<TR><TD VALIGN=top ROWSPAN=3 WIDTH="100%" BGCOLOR="#FFFFFF">' +
              '&nbsp;' +
            '</TD><TD VALIGN=top COLSPAN=2>' +
              '<DIV class="comment_fnt">Sent successfully. Thank you.<BR><BR>' +
              'If you intend to get reply, you may enter your email address:</DIV>' +
            '</TD></TR><TR><TD COLSPAN=2>' +
              '<INPUT TYPE=TEXT ID="email_addr" NAME="email" SIZE=50>' +
            '</TD></TR><TR><TD><DIV class="comment_err" ID="comment_error"></DIV></TD><TD>' +
              '<DIV ALIGN=RIGHT><INPUT TYPE=SUBMIT VALUE="Send" ID="send_button"></DIV>' +
            '</TD></TR>' +
          '</TABLE>'
        );
        var email_addr = document.getElementById( "email_addr" );
        if( email_addr ) {
          email_addr.focus();
        }
      }
    }
  } else {
    var r = new RegExp( "^[a-f0-9]+$", "i" );
    if( response_text.match( r ) ) {
      save_user_id( response_text );
      pxuid = response_text;
    }

    var comment_area = document.getElementById( "comment_area" );
    if( comment_area ) {
      comment_area.innerHTML = (
        '<TABLE CELLSPACING=0 CELLPADDING=10 BORDER=0 ' + 
          'BGCOLOR="#2D2D2D" style="margin-top: 6px;">' + 
          '<TR><TD VALIGN=top WIDTH="100%" BGCOLOR="#FFFFFF">' +
            '&nbsp;' +
          '</TD><TD VALIGN=top>' +
            '<DIV class="comment_fnt" style="width:400px;">Email address was sent successfully. Thank you.</DIV>' +
          '</TD></TR>' +
        '</TABLE>'
      );
    }
  }
}

function save_user_id( pxuid ) {
  expires = new Date();
  expires.setTime( expires.getTime() + (365 * 24 * 3600) );
  document.cookie = (
    "pxuid=" + encodeURIComponent(pxuid) +
    "; expires=" + expires.toGMTString()
  );
}

function retrieve_user_id() {
  var arr_cookies = document.cookie.split( ";" );
  for( var i = 0; i < arr_cookies.length; i++ ) {
    var pair = arr_cookies[i];
    var eq   = pair.indexOf( "=" );
    if( eq != -1 ) {
      var first  = pair.substr( 0, eq );
      var second = pair.substr( eq + 1 );
      first = first.replace( /^\s+|\s+$/g,"" );
      if( first == "pxuid" ) {
        return decodeURIComponent( second );
      }
    }
  }
  return "";
}

function generate_duplicate_prevention_string() {
   var chars = "0123456789";
   var randomstring = '';
   for( var i = 0; i < 10; i++ ) {
     var rnum = Math.floor( Math.random() * 10 );
     randomstring += chars.substring( rnum, rnum + 1 );
   }
   return randomstring;
}

