var visibleDiv = '';

function showComment(elem,eid) {

	// check if entry id is numeric
	if (eid != parseInt(eid)) {
		return false;
	}
	
	// hide the layer first (if it is visible)
	if ($("#commentFormContainer").is(':visible')) {
		$("#commentFormContainer").slideUp("slow",function callback() {
			$("#commentFormContainer").remove();
			
			// we hided the layer, so show the one the user wants to see
			if (visibleDiv == 'add') {
				showComment(elem, eid);
			}
		});
		return;
	};				
	
	$("#loadingDiv_"+eid).show();					
	
	// we build a container and load the comments in it
    $("#commentFormContainer").remove();
    $(elem).parent().after("<div id=\"commentFormContainer\" style=\"display:none;\">&nbsp;</div>");
    $("#commentFormContainer").load("/ajax_get_comments.php?eid=" + eid, null, function(responseText, textStatus, XMLHttpRequest){
        // if form is successfully loaded, we display it
        $("#commentFormContainer").slideDown("slow");
		visibleDiv = 'show'; // need in order to know which to hide
		
		$("#loadingDiv_"+eid).hide();
		
	});				
}

function addComment(elem, eid){
        
	// check if entry id is numeric
	if (eid != parseInt(eid)) {
		return false;
	}
    
	// hide the layer first (if it is visible)
	if ($("#commentFormContainer").is(':visible')) {
		$("#commentFormContainer").slideUp("slow",function callback() {
			$("#commentFormContainer").remove();
			
			// we hided the layer, so show the one the user wants to see
			if (visibleDiv == 'show') {
				addComment(elem, eid);
			}
		});
		return;
	};

	$("#loadingDiv_"+eid).show();
	
    // @todo replace the link so it cant be clicked anymore (or use toggle)
    
	// we build a container and load the comment form in it
    $("#commentFormContainer").remove();
    $(elem).parent().after("<div id=\"commentFormContainer\" style=\"display:none;\">&nbsp;</div>");
    $("#commentFormContainer").load("/ajax_get_comment_form.php?eid=" + eid, null, function(responseText, textStatus, XMLHttpRequest){

        // if form is successfully loaded, we display it
        $("#commentFormContainer").slideDown("slow");
		visibleDiv = 'add'; // need in order to know which to hide
		$("#loadingDiv_"+eid).hide();
		
		// since the form is displayed now, we can register our submit event
		$("#submit").click(function(){

	           $(".error").remove(); // @todo needed?
		
		
	           var hasError = false;
	           var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        
			// do some validations
            var emailVal = $("#email").val();
            if (emailVal == "") {
				$("#email").after("<span class=\"error\">Bitte trage Deine E-Mail Adresse ein.</span>");
				hasError = true;
			}
			else if (emailVal.length > 50){
                $("#email").after("<span class=\"error\">Deine E-Mail Adresse ist zu lang.</span>");
                hasError = true;
			}						
			else if (!emailReg.test(emailVal)) {
				$("#email").after("<span class=\"error\">Bitte gib eine gültige E-Mail Adresse ein.</span>");
				hasError = true;
			}
            
            var commentVal = $("#comment").val();
            if (commentVal == "") {
                $("#comment").after("<span class=\"error\">Bitte trage einen Kommentar ein.</span>");
                hasError = true;
            }
			else if (commentVal.length > 2000){
                $("#comment").after("<span class=\"error\">Dein Kommentar ist zu lang, es dürfen maximal 2000 Zeichen abgesendet werden.</span>");
                hasError = true;
			}

            
            var nameVal = $("#name").val();
            if (nameVal == "") {
                $("#name").after("<span class=\"error\">Bitte trage Deinen Namen ein.</span>");
                hasError = true;
            }
			else if (nameVal.length > 50){
                $("#name").after("<span class=\"error\">Der Name darf maximal 50 Zeichen lang sein.</span>");
                hasError = true;
			}						
            
            var eidVal = $("#eid").val();
            var tokenVal = $("#token").val();
            
            if (hasError == false) {
            
                $("#loading").show();
                $("#submit").hide();
                
                var inputs = [];
                inputs.push("name=" + nameVal);
                inputs.push("email=" + emailVal);
                inputs.push("comment=" + commentVal);
                inputs.push("eid=" + eidVal);
                inputs.push("token=" + tokenVal);
                
                var form = $("#commentForm");
				var action = form.attr("action");

                $.ajax({
                    type: "POST",
                    data: inputs.join("&"), 
                    url: action,
                    cache: false,
                    timeout: 10000,
                    error: function(){
						$("#commentForm").slideUp("normal", function(){
							$("#commentForm").before("<p class=\"failed\">Dein Kommentar konnte nicht gespeichert werden.</p>");
						});
                    },
                    success: function(ret){
                        $("#loading").hide();

                        
                        if (ret == '0') {
                        	$("#commentForm").slideUp("normal", function() {		
                             	$("#counter_" + eidVal).html(parseInt($("#counter_" + eidVal).html()) + 1);
                            	$("#commentForm").before("<p class=\"success\">Dein Kommentar wurde erfolgreich abgeschickt und ist nun im Blog sichtbar.</p>");
                             });                                
                        }
                        else if (ret == '10') {
							$("#commentForm").slideUp("normal", function(){
								$("#commentForm").before("<p class=\"failed\">Dein Kommentar konnte nicht gespeichert werden, denn es wurden nicht alle benötigten korrekt Eingabefelder ausgefüllt.</p>");
							});
						}
						else if (ret == '20') {
							$("#commentForm").slideUp("normal", function(){
								$("#commentForm").before("<p class=\"failed\">Dein Kommentar konnte nicht gespeichert werden, denn die Sicherheitsüberprüfung ist fehlgeschlagen.</p>");
							});
						}
						else if (ret == '30') {
							$("#commentForm").slideUp("normal", function(){
								$("#commentForm").before("<p class=\"failed\">Dein Kommentar konnte nicht gespeichert werden, denn es wurden ungültige Formularfelder übertragen.</p>");
							});
						}
						else if (ret == '50') {
							$("#commentForm").slideUp("normal", function(){
								$("#commentForm").before("<p class=\"failed\">Dein Kommentar wurde nicht gespeichert, denn du oder jemand aus deinem Umfeld hat innerhalb der letzten 60 Minuten bereits mehrere Kommentare geschrieben. Bitte warte eine Stunde, bis du weitere Kommentare schreiben kannst.</p>");
							});
						}															
						else {
							$("#commentForm").slideUp("normal", function(){
								$("#commentForm").before("<p class=\"failed\">Dein Kommentar konnte nicht gespeichert werden.</p>");
							});
							
						}
                    }
                });
                
            }
            
        	return false;
 	   });
    
    
    });
    
    
    return false;
}