Class("Comments", {
	has: {
		divcom: {is: "rw"},
		divcomform: {is: "rw"},
		formfields: {is: "rw", init: function() { return $("input[id], textarea[id]") } }
	},
	methods:{
		init: function() {
			this.get_comment();
		},
		switch_page: function() {
			$("#comments div").toggle("slow", this.set_comment_link());
		},
		set_comment_link: function () {
			if($("#comment_link").text().match('Einen')) {
				$("#comment_link").html('> Zur Liste <');
			} else {
				$("#comment_link").html('> Einen Kommentar schreiben <');
			}
		},
		save_comment: function() {
			if(!this.check_form()) return;
			var i;
			var params = {};
			
			$.each(this.getFormfields(), function() {
				params[this.id] = this.value;
			});
			
			params = JSON.stringify(params);
	        var url = "/comments/save_comment/params/" + encodeURIComponent(params);

	        $.get(url, function(data){
	            if(data == 'data_saved') {
	                $("#msg").html('<span class="green">Danke, Dein Kommentar wurde gespeichert.</span>');
					var com = new Comments();
	                com.reset_fields();
					com.redirect_to_comments();
					com.get_comment();
	            } else {
	                $("#msg").html('<span class="red">Leider gab es einen Fehler beim Speichern des Kommentars.</span>');
	            }
	        });
		},
		check_form: function() {
			var err = 0, elem = $("input[id], textarea[id]");

	        for(i = 0; i < elem.length; i++) {
	            if(elem[i].value == '') {
	                err = err + 1;
	            }
	        }

	        if(err > 0) {
	            $("#msg").html('<span class="error">Bitte alle Felder ausf&uuml;llen</span>').show("slow");
	            return false;
	        }
	
			return true;
		},
		reset_fields: function() {
			var elem = this.getFormfields();
	        for(i = 0; i < elem.length; i++) {
	            elem[i].value = '';
	        }
		},
		redirect_to_comments: function () {
			window.setTimeout('location.href = "/comments.html"', 5000);
		},
		get_comment: function() {
			$.getJSON("/comments/get_comments/",
				function(data){
					var html;
					var stuff = $.map(data, function(item) { 
						html = "<h3>" + item.name + " <span class=\"date\">" + item.date + "</h3>";
						html += "<p>" + item.comment + "</p>";
						return html; 
					}).join('<br>'); 
					
					$("#entrys").append(stuff);
				}
			);
		}
	} 
});
