(function($) {
  var localized = {
  "INVALID_CAPTHCA_ENTERED":"Du har tastet feil sikkerhetskode! Vennligst tast inn ny kode."
  ,"VALID_CAPTHCA_ENTERED":"Sikkerhetskoden var rett."
  ,"UNEXPECTED_ERROR_OCCURRED":"Vi beklager, det oppsto en uventet feil."
  ,"REPLY_PREFIX":"SV: "
  ,"IS_REQUIRED":" m&aring; fylles ut."
  ,"EXPAND_ALL":"Vis alle"
  ,"COLLAPSE_ALL":"Skjul alle"
  };
  
  var settings = {
    "CAPTCHA_WAITING_PATH":"/nrkcommunity/images/loading.gif"
   ,"CAPTCHA_PATH":"/nrkcommunity/JCaptcha"
   ,"CAPTCHA_VALIDATE_PATH":"/nrkcommunity/CaptchaValidator.servlet"
  };


/*
 * Setup
 */
  

$.fn.formToMap = function() {
    var a = {};
    if ($(this).size() == 0) return a;
    
    $(":input", this).each(function() {
      a[$(this).attr("name")] = $(this).val();
      
    });
    return a;
};

$(function() {
  var placeholder = $("#articlecomments");
  if(placeholder.size() < 1) {
    return false;
  }

  placeholder.load("/nrkcommunity/jsp/comment.jsp", placeholder.metadata(), function() {
    /*
  	$("a.expandAllComments").text(localized.EXPAND_ALL).toggle(function() {
      $("#articlecomments dt a.closed").click();
      $(this).text(localized.COLLAPSE_ALL);
      return false;
      }
     ,function() {
      $("#articlecomments dt a.open").click();
      $(this).text(localized.EXPAND_ALL);
      return false;
      }
    );
    */
    
    $("#captcha input").keyup(validateCaptcha);
    $("#captcha img").click(resetCaptcha);
    
    
    $("#commentform").ajaxForm({success:handleCommentResponse, beforeSubmit:validateCommentForm});
    $("#commentform :reset").click(resetCommentForm);
    
    
    $(".toggleCommentForm").toggle(function() {
      return showCommentForm($("#articlecomments a.expandAllComments"));
    }
    ,hideCommentForm
    );
    
    $("#reportform").ajaxForm({success:handleReportResponse, dataType: "xml"});
    $("#reportform :reset").click(resetReportForm);

    
    /* Add event handlers for comment node */
    ehfn(placeholder);
  });
});

/* Add event handlers for comment node */
function ehfn(n) {
	$("dd form", n).each(function() {
    var form = $(this);
    $("input.comment", this).click(function() {
      return showCommentForm(form, form.formToMap());
    });
    $("input.warning", this).click(function() {
      return showReportForm(form, form.formToMap());
    });  
  });
  
	/*
  var openedNodes = 0;
  $("dt a", n).each(function() {
    $(this).toggle(showCommentNode, hideCommentNode);
    if(openedNodes++ < 4) {
      $(this).click();
    }
  });
  */
	
	$("dt a", n).click(function() {
		$(this).blur();
		return false;
  });
}

/*
 * Node handling
 */
/*
function showCommentNode() {
	     
  $(this).attr("class", "open").parent("dt").next("dd").attr("class", "open");
}

function hideCommentNode() {
  $(this).attr("class", "closed").parent("dt").next("dd").attr("class", "closed");
}

*/

/*
 * Comment form handling
 * Inserts the form at the right place and displays it.
 */
function showCommentForm(afterNode, metadata) {
  var commentform = $("#commentform");
  
  resetCommentForm();
  afterNode.after(commentform);
  $(":submit", commentform).attr("disabled", "disabled");
  if(metadata) {
    jQuery.each(metadata, function(key, value) {
      if(key == "title") {
        value = localized.REPLY_PREFIX + value;
      }
      $("input[name=" + key + "]", commentform).val(value);
    });
  }
  
  $("input[name=randomFormId]", commentform).val(Math.round((Math.random()*90000)+1));
  
  commentform.show();
  return false;
}

function hideCommentForm() {
  $("#commentform").hide();
}


function resetCommentForm() {
  resetCaptcha();
  $("#commentform").hide().resetForm();
  resetCommentFormMessage();
}


function validateCommentForm(data, form, options) {
  var errors = new Array();
  $(":input", form).each(function() {
    if($(this).metadata().required) {
      if($(this).val().length < 1) {
        errors.push($(this).metadata().label + localized.IS_REQUIRED);
      }
    }
  });
  
  if(errors.length > 0) {
    displayCommentFormMessage(errors, "error");
    return false;
  }
  return true;
}

function handleCommentResponse(response, status) {
  if(status == "success") {
    var comment = $(response);
    $("#commentform").after(comment).hide();
    ehfn(comment);
    incrementPostCount();
  }
  else {
    // TODO: Better feedback
    displayCommentFormMessage(localized.UNEXPECTED_ERROR_OCCURRED, "error")
  }
}

function lockCommentForm() {
  $("#commentform :submit").attr("disabled","disabled");
}
function unlockCommentForm() {
  $("#commentform :submit").removeAttr("disabled");
}


/*
 * Captcha handling
 */
function validateCaptcha() {
  if($(this).val().length == 3) {
    var data = $(this).serialize();
    jQuery.ajax({
      type: "POST"
     ,url: settings.CAPTCHA_VALIDATE_PATH
     ,data: data
     ,error: function() {displayCommentFormMessage(localized.UNEXPECTED_ERROR_OCCURRED, "error")}
     ,success: function(data) {
       if($("approved", data).text() == "true") {
         //displayCommentFormMessage(localized.VALID_CAPTHCA_ENTERED, "success");
         resetCommentFormMessage();
         lockCaptcha();
         unlockCommentForm();
         
       }
       else {
         displayCommentFormMessage(localized.INVALID_CAPTHCA_ENTERED, "error");
         resetCaptcha();
         lockCommentForm();
       }
      }
    });
  }
  return false;
}

function lockCaptcha() {
  $("#captcha input").attr("disabled", "disabled");
}

function resetCaptcha() {
  $("#captcha input").removeAttr("disabled");
  var captchaImage = $("#captcha img");
  captchaImage.attr("src", settings.CAPTCHA_WAITING_PATH);
  setTimeout(function() {
    captchaImage.attr("src", settings.CAPTCHA_PATH + "?id=" + Math.random());
  },1000);
  return false;
}








function incrementPostCount() {
  var count = $("#articlecomments h2 var");
  count.text((parseInt(count.text(), 10) + 1));
}






















/*
 * Report form handling
 * Inserts the form at the right place and displays it.
 */
function showReportForm(nodeToInsertAfter, metadata) {
  var form = $("#reportform");
  
  resetReportForm();

  if(metadata) {
    jQuery.each(metadata,function(key, value) {
      if(key == "inReplyTo") {
        $("input[name=posting]", form).val(value)
      }
      $("input[name=" + key + "]", form).val(value);
    });
  }
  nodeToInsertAfter.after(form);
  form.show();
  return false;
  
}


function resetReportForm() {
  var form = $("#reportform");
  form.hide().resetForm();
  $(".confirmReport", form).show();
  $(".finishReport", form).hide();
  
}


function handleReportResponse(xml, status) {
  var form = $("#reportform");
  if($("report", xml).text() != "true") {
    $(".confirmReport p", form).text(localized.UNEXPECTED_ERROR_OCCURRED);
  }
  
  $(".confirmReport", form).hide();
  $(".finishReport", form).show();
}




/*
 * User warnings etc.
 */
function resetCommentFormMessage() {
  $("#articlecomments form p.message").empty().removeClass("error").removeClass("success");
}

function displayCommentFormMessage(msg, type) {
  var placeholder = $("#articlecomments form p.message");
  placeholder.empty().removeClass("error").removeClass("success").addClass(type);
  
  if(typeof msg == "object") {
    jQuery.each(msg,function() {
      placeholder.append(this + "<br/>");
    }); 
  }
  else {
    placeholder.text(msg);
  }
}
})(jQuery);