$(document).ready(function(){

  //## show anchorComments
  anchorComments = function(bid, cid)
  {	if(bid)
  	{ showComments(bid);

  		var winH = $(window).height();
  	  if(cid)
  	    var ancP = $('#divComment_'+bid+'_'+cid).position();

  	  if(typeof(ancP) == 'undefined')
  	    var ancP = $('#addComm_'+bid).position();

  	  if(typeof(ancP) != 'undefined')
        $(window).scrollTop(Math.max(0, ancP.top-Math.ceil(winH/3)));
    }
  }

  //## showHideComments
  showComments = function(bid) {
    if(bid && typeof($('#showHide_'+bid).attr('id'))!='undefined')
    { $('#showHide_'+bid).text($('#showHide_'+bid).text().replace('Show', 'Hide'));
      $('#showHide_'+bid).attr('title', 'Hide Comments');
      $('#showHide_'+bid).removeClass('showHideCommentsBullet');
      $('#showHide_'+bid).addClass('hideHideCommentsBullet');
      $('#divComments_'+bid).show();
    }
  };
  hideComments = function(bid) {
    if(bid && typeof($('#showHide_'+bid).attr('id'))!='undefined')
    { if(document.frm_comm_add.bid.value == bid)
    	  cancelCommAdd();

    	$('#showHide_'+bid).text($('#showHide_'+bid).text().replace('Hide', 'Show'));
      $('#showHide_'+bid).attr('title', 'Show Comments');
      $('#showHide_'+bid).removeClass('hideHideCommentsBullet');
      $('#showHide_'+bid).addClass('showHideCommentsBullet');
      $('#divComments_'+bid).hide();
    }
  };

  $(".showHideComments").click(function(e){
    e.preventDefault();
    var attr = $(this).attr('id').split('_');
    var bid  = attr[1];

    if(bid)
    { if($(this).attr('title') == 'Show Comments')
    	  showComments(bid);
      else
    	  hideComments(bid);
    }

  });

  //## addComments
  $(".addComments").click(function(e){
    e.preventDefault();
    var attr = $(this).attr('id').split('_');
    var bid  = attr[1];

    if(bid)
    { showComments(bid);
      cancelCommAdd();
    	cancelCommMod();

      $("#divCommAdd_"+bid).html($("#divCommAdd").html());
      $("#divCommAdd").html('');
      $("#divCommAdd_"+bid).show();

      var frm = document.frm_comm_add;
      frm.bid.value = bid;
      setTextareaMaxlength(frm, 'add');
      $(frm).submit(function(e){
        return validateCommAdd(frm);
      });
      $(frm.comment).trigger('keyup');

      if(frm.bypass.value*1)
        frm.comment.focus();
      else
        frm.nickname.focus();
    }
  });
  cancelCommAdd = function() {
    var frm = document.frm_comm_add;
    var bid = frm.bid.value;

    if(bid)
    { frm.reset();
      $("#frm_comm_add_msg").html('');
    	frm.bid.value = '';
    	$("#divCommAdd").html($("#divCommAdd_"+bid).html());
      $("#divCommAdd_"+bid).html('');
      $("#divCommAdd_"+bid).hide();
      hideComments(bid);
      showComments(bid);
    }
  };
  var validateCommAdd = function(frm) {
    if(!frm.bid.value)
    { alert('System error.');
    	return false;
    }
    if(strTrim(frm.nickname.value) == '')
    { alert('Please enter Nickname.');
    	frm.nickname.focus();
    	return false;
    }
    if(!frm.bypass.value*1 && strTrim(frm.nickname.value.toLowerCase()) == 'administrator')
    { alert('The nickname "Administrator" is not allowed.');
    	frm.nickname.focus();
    	return false;
    }
    if(strTrim(frm.comment.value) == '')
    { alert('Please enter Comment.');
    	frm.comment.focus();
    	return false;
    }
    if(!frm.bypass.value*1)
    { if(frm.password.value == '')
      { alert('Please enter Password.');
      	frm.password.focus();
      	return false;
      }
      if(frm.password.value.length < 6)
      { alert('Password must be 6 or more characters.');
      	frm.password.focus();
      	return false;
      }
      if(frm.confirm_password.value == '')
      { alert('Please confirm Password.');
      	frm.confirm_password.focus();
      	return false;
      }
      if(frm.password.value != frm.confirm_password.value)
      { alert("Confirm Password doesn't match.");
      	frm.confirm_password.focus();
      	return false;
      }
    }
    return true;
  };
  var strTrim = function(str) {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  };

  //## pop_pass
  var pop_pass = new eZpopup();
  pop_pass.setContentOverflow('hidden','hidden')
  pop_pass.showHandle = true;
  pop_pass.modal      = true;
  pop_pass.baseZIndex = 200;
  pop_pass.background = '#FFFFFF';
  pop_pass.setContentPadding(0, 0, 0, 0);
  pop_pass.setContentSize(420, 90);
  pop_pass.contentKeep = true;
  pop_pass.title   = 'Comment Password Validation';
  pop_pass.content = $("#divPassword").html();
  $("#divPassword").html('');
  pop_pass.create();

  hidePopPass = function(frm) {
    frm.reset();
    $("#frm_comm_pass_msg").html('');
    pop_pass.hide();
  };

  $(document.frm_comm_pass).submit(function(e){
    e.preventDefault();
    var frm = this;

    if(validatePopPass(frm)) {
      var url="/think-about-it/ajax/comm_pass_validate.php";
      url += "?bid="+frm.bid.value;
      url += "&cid="+frm.cid.value;
      url += "&password="+frm.password.value;
      url += "&sid="+Math.random();
      
	    $.getJSON(url, function(data){
	        if(data['cid'] && data['password'] && data['isvalid']) {
            if(frm.act.value == 'del') {
              var frm_del = document.frm_comm_del;
              frm_del.bid.value = frm.bid.value;
              frm_del.cid.value = frm.cid.value;
              frm_del.password.value = frm.password.value;
              frm_del.submit();
            } else if(frm.act.value == 'mod') {
              hidePopPass(frm);
              showCommModForm(data);
            }
          } else {
            if(!data['cid'] || !data['password'])
              $("#frm_comm_pass_msg").html('<span style="color:#CC0000;">* System error.</span>');
            else
              $("#frm_comm_pass_msg").html('<span style="color:#CC0000;">* Invalid password. Please try again.</span>');
            frm.password.select();
          }
      });
    }
  });
  var validatePopPass = function(frm) {
    if(!frm.bid.value || !frm.cid.value)
    { alert('System error.');
    	return false;
    }
    if(frm.password.value == '')
    { alert('Please enter Password.');
    	frm.password.focus();
    	return false;
    }
    return true;
  };

  //## modComments
  $(".modComments").click(function(e){
    var attr = $(this).attr('id').split('_');
    var bid  = attr[1];
    var cid  = attr[2];

    if(bid && cid)
    { cancelCommAdd();
    	cancelCommMod();

    	if(document.frm_comm_pass.bypass.value)
      { var url="/think-about-it/ajax/comm_get_data.php";
        url += "?bid="+bid;
        url += "&cid="+cid;
        url += "&sid="+Math.random();
        
	      $.getJSON(url, function(data){
	          if(data['cid']) {
                showCommModForm(data);
            } else {
              alert('System error.');
            }
        });
      }
      else
    	{ var thisPos = $(this).position();
    	  var popW    = $(pop_pass.ezpopWindow).width();
    	  pop_pass.show(0, thisPos.left - popW, thisPos.top);
        
        var frm = document.frm_comm_pass;
        frm.bid.value = bid;
        frm.cid.value = cid;
        frm.act.value = 'mod';
        frm.password.focus();
        
        $("#frm_comm_pass_bg").css('background', '#EEEEFF');
        $("#frm_comm_pass_msg").html('<span style="color:#008000;">* Please enter password to modify this comment.</span>');
      }
    }
  });

  showCommModForm = function(data) {
    $("#divCommMod_"+data['bid']+'_'+data['cid']).html($("#divCommMod").html());
    $("#divCommMod").html('');
    $("#divCommMod_"+data['bid']+'_'+data['cid']).show();
    $("#divComment_"+data['bid']+'_'+data['cid']).hide();
    
    var frm = document.frm_comm_mod;
    frm.bid.value = data['bid'];
    frm.cid.value = data['cid'];
    frm.password.value = data['password'];
    if(data['admin']*1)
      frm.locked.disabled = true;
    else
      frm.locked.checked = data['locked']*1 ? true : false;

    frm.display.checked = data['display']*1 ? true : false;

		if(eval(frm.emoticon)){
    for(i=0; i<frm.emoticon.length; i++)
    { if(frm.emoticon[i].value == data['emoticon'])
      { frm.emoticon[i].checked = true;
        break;
      }
    }
    }
    frm.nickname.value = data['nickname'];
    frm.comment.value  = data['comment'];
    setTextareaMaxlength(frm, 'mod');
    $(frm).submit(function(e){
      return validateCommMod(frm);
    });
    $(frm.comment).trigger('keyup');

    setTimeout('document.frm_comm_mod.comment.focus()', 100);
  };
  cancelCommMod = function() {
    var frm = document.frm_comm_mod;
    var bid = frm.bid.value;
    var cid = frm.cid.value;

    if(bid && cid)
    { frm.reset();
      frm.locked.disabled = false;
      $("#frm_comm_mod_msg").html('');
      $("#divCommMod").html($("#divCommMod_"+bid+'_'+cid).html());
      $("#divCommMod_"+bid+'_'+cid).html('');
      $("#divCommMod_"+bid+'_'+cid).hide();
      $("#divComment_"+bid+'_'+cid).show();
    }
  };
  var validateCommMod = function(frm) {
    if(!frm.bid.value || !frm.cid.value)
    { alert('System error.');
    	return false;
    }
    if(strTrim(frm.nickname.value) == '')
    { alert('Please enter Nickname.');
    	frm.nickname.focus();
    	return false;
    }
    if(!frm.bypass.value*1 && strTrim(frm.nickname.value.toLowerCase()) == 'administrator')
    { alert('The nickname "Administrator" is not allowed.');
    	frm.nickname.focus();
    	return false;
    }
    if(strTrim(frm.comment.value) == '')
    { alert('Please enter Comment.');
    	frm.comment.focus();
    	return false;
    }
    return true;
  };

  //## delComments
  $(".delComments").click(function(e){
    var attr = $(this).attr('id').split('_');
    var bid  = attr[1];
    var cid  = attr[2];

    if(bid && cid)
    { cancelCommAdd();
    	cancelCommMod();
    	
    	if(document.frm_comm_pass.bypass.value)
    	{ var resure = confirm('Are you sure you want to delete this comment?      ');
        if(resure)
        { var frm_del = document.frm_comm_del;
          frm_del.bid.value = bid;
          frm_del.cid.value = cid;
          frm_del.submit();
        }
      }
      else
    	{ var thisPos = $(this).position();
    	  var popW    = $(pop_pass.ezpopWindow).width();
    	  pop_pass.show(0, thisPos.left - popW, thisPos.top);
        
        var frm = document.frm_comm_pass;
        frm.bid.value = bid;
        frm.cid.value = cid;
        frm.act.value = 'del';
        frm.password.focus();
        
        $("#frm_comm_pass_bg").css('background', '#FFEEEE');
        $("#frm_comm_pass_msg").html('<span style="color:#008000;">* Please enter password to delete this comment.</span>');
      }
    }
  });

  $(".modCommentsDis, .delCommentsDis").click(function(e){
    alert('This comment has been locked by Administrator.');
  });
  $(".modCommentsAdmin, .delCommentsAdmin").click(function(e){
    alert('Please login as an Administrator for this action.');
  });

  //## setTextareaMaxlength
  setTextareaMaxlength = function(frm, act) {
    $(frm.comment).keyup(function(e){
      if(typeof($(this).attr('maxlength'))=='undefined')
        var maxlength = '';
      else
        var maxlength = parseInt($(this).attr('maxlength'));
      if(!isNaN(maxlength) && maxlength > 0)
      { if($(this).attr('value').length > maxlength)
      	{ $(this).attr('value', $(this).attr('value').substring(0, maxlength));
          $(this).scrollTop($(this).attr('scrollHeight'));
        }
        var chrs = $(this).attr('value').length;
        $("#frm_comm_"+act+"_maxlength").html('<span style="color:'+(chrs<maxlength ? '#0000CC':'#AA0000')+';">'+chrs+' chrs / max.'+maxlength+'</span>');
      }
    });
  };

});

