var forum = {
	rating : {
		
		/**
		 * 
		 */
		init : function() {

			// select star rating to update 
			var parent_rating_div = jQuery('#forum-standard-view').css('display') == 'none' ? 'forum-compact-view' : 'forum-standard-view';

			jQuery("#" + parent_rating_div + " div[id^='star-rating']").each(function(i) {
				var value = jQuery(this).attr('curvalue');
				value = typeof value != 'undefined' ? value : 0;
				
				var id_parts = jQuery(this).attr('id').split('-');
				var postid = id_parts[2];
				
				jQuery(this).rating(doc_root + 'includes/ajax/forum.save-user-rating.php', {
					maxvalue: 5, 
					curvalue: value,
					topic_id: postid
				}, forum.rating.update);
			});
		},
		update : function(data, status) {
//			alert(data.postid + ' '+ data.user_rating_count);
			jQuery('#user-rating-count-' + data.postid).html('(' + data.user_rating_count + ')');
			
			jQuery('#star-rating-' + data.postid).empty();
			
//			alert('set curvalue to ' + data.cur_average_rating + ' after delete the previous');
			jQuery('#star-rating-' + data.postid).rating(doc_root + 'includes/ajax/forum.save-user-rating.php', {
				maxvalue: 5, 
				curvalue: Math.round(data.cur_average_rating),
				topic_id: data.postid
			}, forum.rating.update);
			
		},
		toggle_stars : function (postid, rating) {
			if (rating) {
				jQuery('#average-rating-' + postid).hide();
				jQuery('#user-rating-' + postid).show();
			}
			else {
				jQuery('#user-rating-' + postid).hide();
				jQuery('#average-rating-' + postid).show();
				
			}
		},
		highlite : function(obj, rating) {
			// get the common part of the ids of all stars of this obj
			var domid = jQuery(obj).attr('id');
			var domid_parts = domid.split('_');
			var domid_common = domid_parts[0] + '_' + domid_parts[1];
			var rating = domid_parts[2];
			
			//alert(domid_common);
			
			var stars_original = jQuery("img[id^='" + domid_common + "']");
//			alert(stars_original.length);
			// make a working copy
			var stars_cloned = jQuery(stars_original).clone();
			
				
			var stars_parent = jQuery("img[id^='" + domid_common + "']").parent();

			
			jQuery("img[id^='" + domid_common + "']").remove();
			
			jQuery(stars_parent).append(stars_cloned);
			
			
//			alert('stars count: ' + stars_cloned.length);
			
//			jQuery(stars_cloned).each(function(i){
//				jQuery(this).attr('src', 
//							doc_root + 'misc/icons/star_deaktiviert.gif');	
//			}); 
			
			
			for (i = 0; i < 5; i ++) {
				var deactivate = '';
				if (rating <= i) {
					deactivate = '_deaktiviert';
				}
				jQuery('#' + domid_common + '_' + i).attr('src', 
							doc_root + 'misc/icons/star' + deactivate + '.gif');				
			}			
			
		}
	},
	hide_wym_editor : function(reset) {
//		jQuery('#category_id').val("");
//		jQuery('#edit_id').val("");
//		jQuery('#topic_id').val("");
		
		jQuery('#mainNavWrapper').css('z-index', 5);
		jQuery('#idea-container-id').val("");
		
		reset = typeof reset != 'undefined' ? reset : false;
		
		if (reset ) {
			// reset editor input values
			jQuery('#subject').val('');
			
			if (WYMeditor.INSTANCES.length > 0) {
				jQuery.wymeditors(0).html('');
			}
			
			
			jQuery('.remove-link').each(function(){
				jQuery(this).trigger('click');
			});			
		}
		util.close('response-editor');
	},
	
	categories : {
		get: function(project_id) {
			
			// wait for editor to load
			window.setTimeout(function() { // fixing error caused through access to editor when it wasn't loaded
				forum.hide_wym_editor(true);
			}, 2000)

			jQuery('#forum-standard-view').html('<img src="' + doc_root + 'misc/icons/loader.gif" style="padding-left:45%;" />' + gt.gettext("Lade Themenliste"));
			jQuery.post(doc_root + "includes/ajax/forum.get-categories.php", {
				project_id: project_id 
			}, function(data, status) {
				jQuery('#forum-standard-view').html(data);
			}, "json") ;			
		},
		
		get_admin: function(project_id) {
			jQuery('#forum').html('<img src="' + doc_root + 'misc/icons/loader.gif" style="padding-left:45%;" />' + gt.gettext("Lade Themenliste"));
			jQuery.post(doc_root + "includes/ajax/forum.get-categories-admin.php", {
				project_id: project_id 
			}, function(data, status) {
				jQuery('#forum').html(data);
			}, "json") ;			
		}
	},
	topics : {
		get: function(category_id) {
			user.log('forumCategoryView', '[category_id:' + category_id + ']');
			
			
//			$.address.value('js:forum.categories.get(' + project_room_id + ')');
			$.address.value('js:forum.topics.get(' + category_id + ')');
			
			forum.hide_wym_editor(true);
			
			// set category-id in hidden element for later use (in project.php)
			jQuery('#category_id').val(category_id);
			jQuery('#topic_id').val("");
			jQuery('#forum-standard-view').html('<img src="' + doc_root + 'misc/icons/loader.gif" style="padding-left:45%;" />' + gt.gettext("Lade Beitragsliste"));
			jQuery.post(doc_root + "includes/ajax/forum.get-topics.php", {
				project_room_id: jQuery('#project_room_id').val(),
				category_id: category_id 
			}, function(data, status) {
				jQuery('#forum-standard-view').html(data);
				
				// init rating
				forum.rating.init();
				jQuery('div.star').unbind('click');
				jQuery('div.star').bind('click', function() {return false;});
				jQuery('div.star').unbind('mouseover');
				jQuery('div.star').unbind('mouseout');
				jQuery('div.star').unbind('focus');
				jQuery('div.star').unbind('blur');
				
				
				jQuery('div.star').each(function() {
					if (!jQuery(this).hasClass('on')) {
						jQuery('a:hover', this).css('background-position', '0 0');
					}
				});
				
//				jQuery.address.init();
				
			}, 'json') ;			
		}
	},
	responses : {
		get: function(topic_id, scrollto, category_id, jump_id) {
			
			$.address.value('js:forum.responses.get(' + topic_id + ', ' + scrollto + ', ' + category_id + ', ' + jump_id + ')');
			
			
			user.log('forumResponsesView', '[category_id:' + category_id + ', topic_id:' + topic_id + ']');
			jQuery('#category_id').val(category_id);
			jQuery('#topic_id').val(topic_id);
			forum.hide_wym_editor(true);
			
			scrollto = typeof scrollto != 'undefined' ? scrollto : false;
			jump_id = typeof jump_id != 'undefined' ? jump_id : false;
			
			jQuery('#forum-standard-view').html('<img src="' + doc_root + 'misc/icons/loader.gif" style="padding-left:45%;" />' + gt.gettext("Lade Beitrag"));

			jQuery.post(doc_root + "includes/ajax/forum.get-responses.php", {
				topic_id: topic_id, 
				category_id: category_id 
			}, function(data, status) {

				jQuery('#forum-standard-view').html(data.contents);
				
				// init rating
				forum.rating.init();
				
				if (!isNaN(jump_id) && jump_id > 0) {
					jQuery.scrollTo('#post' + jump_id);
				}
				else if (scrollto) {
					jQuery.scrollTo('#bottom');
				}
			}, "json") ;			
		}
	},
	ideacontainer : {
		move : function(post_id) {
			jQuery.post(doc_root + 'includes/ajax/forum.move-to-ideacontainer.php', {
				topic_id : post_id
			}, function(data, status) {
				if (!data.topic_id) {
					forum.topics.get(data.category_id);					
				}
				else {
					forum.responses.get(data.topic_id, false, data.category_id);
				}

				forum.treeview.load();
						
				alert(gt.gettext("Beträge wurden in den Ideenspeicher verschoben"));
					
			}, 'json');
		},
		entry: function(idea_container_id) {
			// append hidden field to form with parent_id of the ideacontainer
			jQuery('#idea-container-id').val(idea_container_id);
			forum.response.show_response_editor();
		}
		
	},
	
	category : {
		
		form_close : function() {
			jQuery('#forum-category-name').val("");
			jQuery('#forum-category-id').val("");
			jQuery('#category-position-id').val("");
			
			util.close('forum-category-edit');
			
			
		},
		
		edit: function(category_id) {
			util.hide_workingspace();
			
			jQuery('#forum-category-edit').css({
				'position' : 'absolute',
				//'background' : '#000000',
//				'margin-top' : '300px;',
//				'margin-left' : '400px',
//				'width' : '600px',
				'z-index' : '99999'
//				'border' : '1px solid #999999'
  			});

  			
			center_div = 'forum-category-edit'; // defined global
			jQuery(window).bind('scroll', util.position);				
			util.position();
	
			jQuery('#forum-category-edit').prependTo('body');
			jQuery('#forum-category-edit').fadeIn('fast');
			

			jQuery.post(doc_root + "includes/ajax/forum.get-category.php", {
				category_id: category_id
			}, function(data, status) {
				if (data) {
					jQuery('#forum-category-name').val(data.strName);
					jQuery('#forum-category-id').val(category_id);
				}
			}, 'json');
		},
		
		
		set_status : function(category_id, category_status) {
//			var answer = confirm("Wollen Sie dieses Thema wirklich löschen?")
//			if (answer){
				//jQuery('#category_container_' + category_id).fadeOut();
				// mark as deleted
				
				jQuery.post(doc_root + "includes/ajax/forum.set-status.php", {
					category_id : category_id,
					category_status : category_status
				}, function() {
					forum.categories.get_admin(projectroom_id);
				}, 'json');
//			}
		},
		add : function(position_id) {
			util.hide_workingspace();		
			
			jQuery('#forum-category-edit').prependTo('body');
			
			jQuery('#forum-category-edit').css({
				'position' : 'absolute',
				//'background' : '#000000',
//				'margin-top' : '300px;',
//				'margin-left' : '400px',
				'width' : '70%',
				'z-index' : '99999'
//				'border' : '1px solid #999999'
  			});
			
			
			// delete fields first
			jQuery('#forum-category-name').val("");
			jQuery('#forum-category-id').val("");
			jQuery('#category-position-id').val(position_id);
			
			

			
			center_div = 'forum-category-edit'; // defined global
			jQuery(window).bind('scroll', util.position);				
			util.position();
	
			jQuery('#forum-category-edit').prependTo('body');
			jQuery('#forum-category-edit').fadeIn('fast');			
			
		
		},
		save : function() {
			var category_id = jQuery('#forum-category-id').val();	
			var position_id = jQuery('#category-position-id').val();	
			var category_name = jQuery('#forum-category-name').val();
			
			if (category_name == '') {
				alert(gt.gettext("Bitte geben Sie ein Thema an"));
				return;
			}
			
			
			if (!isNaN(category_id)) {
				jQuery('#category_' + category_id).html(category_name);
				
				forum.category.form_close();
				
				jQuery.post(doc_root + "includes/ajax/forum.save-category.php", {
						project_id: projectroom_id,
						category_id : category_id,
						position_id : position_id,
						category_status : 'enabled',
						category_name : category_name
				}, function() {
					forum.categories.get_admin(projectroom_id);
				});
			}
		}
	},
	
	response : {
		show_response_editor : function(cite_id, mode, new_topic) {
			new_topic = typeof new_topic != 'undefined' ? new_topic : false;
			util.hide_workingspace();		
					
			jQuery('#forum-response-body').val('');		    
		    WYMeditor.INSTANCES = new Array();
		    jQuery('.wym_box').remove();
		    delete core.wymconfig.html;
		    core.wymconfig.html = '';
		    wym = jQuery('.forum-wymeditor').wymeditor(core.wymconfig);
		    jQuery('.wym_classes').hide();
		    
		    
			mode = typeof mode !== 'undefined' ? mode : '';
			cite_id = typeof cite_id != 'undefined' && !isNaN(cite_id) ? cite_id : false;

			if ('compact' == mode) {
				jQuery('#forum-post-save-button').attr('onclick', '');
				jQuery('#forum-post-save-button').unbind('click'); // remove click event to avoid multiple bindings
				
				jQuery('#forum-post-save-button').click(function() {
					forum.response.save(mode);
				});
			}
			
			jQuery('#mainNavWrapper').css('z-index', -1);
			
			jQuery('#response-editor').css({
				'position' : 'absolute',
				'width' : '900px',
//				'height' : '360px',
//				'overflow' : 'auto',
				'z-index' : '99999'
  			});
			jQuery('#response-editor div.boxContent').css({
//					'position' : 'absolute',
				'height' : '360px',
				'overflow' : 'auto'					
//					'z-index' : '99999'					
			});  			
  			
			
			// change title of the window resp. 
			if (new_topic) {
				jQuery('#response-editor div.boxHeader h3 span').html(gt.gettext("Neuer Beitrag"));	
			}
			else {
				jQuery('#response-editor div.boxHeader h3 span').html(gt.gettext("Antworten"));	
			}
			
  			jQuery('#response-editor').appendTo('body');

			// position of the reponse-editor
			center_div = 'response-editor'; // defined global
			jQuery(window).bind('scroll', util.position);				
			util.position();
			
			
  			
			if (cite_id > 0) { // quote posting of the id
				
				jQuery.post(doc_root + "includes/ajax/forum.get-post.php", {
					topic_id: cite_id

				}, function(data, status) {
					jQuery('#subject').val('Re:' + data.strSubject);

				    
					jQuery.wymeditors(0).html('<p></p><blockquote>' + data.strBody + '</blockquote>');
				    
					jQuery('#response-editor').show('normal');
				}, 'json');
			}
			else {
				user.log('forumShowEditor', '');
				jQuery('#response-editor').show('normal');
			}
			
		},
		close : function() {
			jQuery('#mainNavWrapper').css('z-index', 5);
			var edit_id = jQuery('#edit_id').val();
			if (!isNaN(edit_id)) {
				if (jQuery('#post' + edit_id).length > 0) {
					jQuery.scrollTo('#post' + edit_id);
				}
			}							
			else {
				jQuery.scrollTo('#bottom');
			}
				
			jQuery('#edit_id').val("");
			forum.hide_wym_editor(true);
			
		},
		
		edit : function(post_id, mode) {
			mode = typeof mode !== 'undefined' ? mode : '';
			jQuery('#edit_id').val(post_id);
			user.log('forumEditPost', '{post_id: ' + post_id + '}');
			
			forum.response.show_response_editor(false, mode);
			
			jQuery.post(doc_root + "includes/ajax/forum.get-post.php", {
				topic_id: post_id
			}, function(data, status) {
				jQuery('#category_id').val(data.intCategoryId);
				jQuery('#topic_id').val(data.intTopicId);
				jQuery('#subject').val(data.strSubject);
				
				window.setTimeout(function() {
					jQuery('#subject').focus();
					
					jQuery.wymeditors(0).html(data.strBody);
				}, 1000);
				
			}, 'json');			
		},
		
		_delete : function(post_id, mode) {
			mode = typeof mode !== 'undefined' ? mode : '';
			user.log('forumDeletePost', '{post_id: ' + post_id + '}');
			jQuery.post(doc_root + "includes/ajax/forum.delete-post.php", {
				delete_id: post_id
			}, function(data, status) {
				if (data !== false) {
					if ('compact' == mode) {
						forum.treeview.show(post_id);
					}
					else {
						if (data.load_category) {
	//						alert('load category');
							// load category
							forum.topics.get(data.category_id);
						}
						else {
	//						alert('reloat topic');
							// reload topic
							forum.responses.get(data.topic_id, false, data.category_id, data.jump_id);
						}
					}
				}
				else {
//					alert('post does not exist');
				}
				forum.treeview.load();
			}, 'json');			
			
		},
		
		_activate : function(post_id, mode) {
			mode = typeof mode !== 'undefined' ? mode : '';
			user.log('forumActivatePost', '{post_id: ' + post_id + '}');
			jQuery.post(doc_root + "includes/ajax/forum.activate-post.php", {
				topic_id: post_id
			}, function(data, status) {
				if (data !== false) {
					if ('compact' == mode) {
						forum.treeview.show(post_id);
					}
					else {
						if (data.load_category) {
	//						alert('load category');
							// load category
							forum.topics.get(data.category_id);
						}
						else {
	//						alert('reloat topic');
							// reload topic
							forum.responses.get(data.topic_id, false, data.category_id, data.jump_id);
						}
					}
				}
				else {
//					alert('post does not exist');
				}
				forum.treeview.load();
			}, 'json');			
			
		},
		
		
		/**
		 * Saves a new or editted forum post.
		 * @return {Boolean} FALSE if data is not valid
		 */
		save : function(mode) {
			mode = typeof mode !== 'undefined' ? mode : '';
			//alert(mode);
			var edit_id = jQuery('#edit_id').val();
			jQuery('#edit_id').val("");
			
			var category_id = jQuery('#category_id').val();
			var topic_id = jQuery('#topic_id').val();
			if (category_id > 0) { // have to be known so we can add a topic to this category
				topic_id = typeof topic_id != 'undefined' && !isNaN(topic_id) ? topic_id : false;
				
				var subject = jQuery('#subject').val();
				var bodytext = jQuery.wymeditors(0).xhtml();
				var idea_container_id = typeof jQuery('#idea-container-id').val() != 'undefined' ? jQuery('#idea-container-id').val() : false;

				if (jQuery.trim(subject) == '') {
					jQuery('#subject').addClass('form-error').focus();
					alert(gt.gettext('Bitte geben Sie einen Betreff an'));
					return;
				}
				else {
					jQuery('#subject').removeClass('form-error');
				}
				
				if (jQuery.trim(bodytext) == '') {
					jQuery('.wym_iframe').addClass('form-error').focus();
					alert(gt.gettext('Bitte verfassen Sie einen Beitragstext'));
					return;
				}
				else {
					jQuery('.wym_iframe').removeClass('form-error');
				}
				var url = doc_root + "includes/ajax/forum.save-posting.php";

				// check if edit_id has been set and choose the update-posting url if so
				if (!isNaN(edit_id) && edit_id > 0) {
					url = doc_root + "includes/ajax/forum.update-posting.php"
				}				
				
								
				// saving post data 
				var post_params = {
					category_id: category_id,
					topic_id: topic_id,
					edit_id: edit_id,
					idea_container_id: idea_container_id,
					subject: subject,
					bodytext: bodytext
				};
				
				
				// log
				user.log('forumSavePost', jQuery.toJSON(post_params));
				
				//alert('ideacontainer_id' + idea_container_id);
				jQuery.post(url, post_params, function (data, status) {
					// upload files
					// check if a valid post id has been returned from save-posting.php
					// and if files are queued for uploading
	
					if (!isNaN(data.post_id) && data.post_id > 0 
							&& jQuery("input[id^='uploadfiles']").length > 1) { // 0th one is always empty
						
						// add action attribute to fileupload form (to avoid pathbuilding in the template
						var action_url = doc_root  + 'includes/ajax/fileupload_handler.php?post_id=' + data.post_id;
//						alert(action_url);
						jQuery("#fileupload-form").attr('action', action_url);
						jQuery('#fileupload-form').ajaxSubmit(function() {
							// remove uploaded files from div using remove-function of the plugin
							jQuery('.remove-link').each(function(){
								jQuery(this).trigger('click');
							});
							
							
							if ('compact' == mode) {
								//alert('udpate single post');	
								forum.hide_wym_editor(true);
								forum.treeview.show(data.post_id);
							}
							
							// reload view
							if (typeof topic_id != 'undefined' && !isNaN(topic_id) && topic_id > 0) {
								forum.responses.get(topic_id, true, category_id, data.post_id);
							}
							else {
								forum.topics.get(category_id);
							}

						});
					}
					else {
						if ('compact' == mode) {
							//alert('udpate single post');
							forum.hide_wym_editor(true);
							forum.treeview.show(data.post_id);
						}

							// reload view
							if (typeof topic_id != 'undefined' && !isNaN(topic_id) && topic_id > 0) {
								forum.responses.get(topic_id, true, category_id, data.post_id);
							}
							else {
								forum.topics.get(category_id);
							}

					}
					forum.treeview.load();
				}, "json") ;			
			}
			else {
				alert(gt.gettext("Fehler: Kategorie unbekannt"));
			}
			
			return false;
		}
		
	},
	
	get_category_name: function(category_id, container_id) {
		jQuery.post(doc_root + "includes/ajax/forum.get-category-name.php", {
			category_id: category_id
			
		}, function(data, status) {
			
			jQuery('#'+container_id).html(data.strCategoryName);
			
		}, 'json');
	},
	
	get_project_name: function (category_id, project_room_id, container_id) {
		var project_room_id = typeof project_room_id != 'undefined' && !isNaN(project_room_id) ? project_room_id : false;
		
		jQuery.post(doc_root + "includes/ajax/forum.get-project-name.php", {
			category_id: category_id,
			project_id: project_room_id		
			
		}, function(data, status) {
			
			var html = data.strProjectName;
			
			if( data.strCategory ){
				html += '<p>' + gt.gettext("Kategorie") + ':' + data.strCategory + '</p>';
			}
			
			jQuery('#'+container_id).html(html);
			
		}, 'json');
	},
	
	
	treeview : {
		init : function() {
			//jQuery('#forum-tree-view').parent('.box').hide();
//			alert(jQuery('#forum-tree-view').parent('.box').html());
			forum.treeview.load();
		},
		
		
		
		/**
		 * enables the tree view for the forum. In particular: insert an empty 
		 * uLIst and apply the tree with categories on it (1st level depth).
		 */
		load : function() {

			jQuery('#forum-tree').empty();
			jQuery('#forum-tree').treeview({
				collapsed: true,
				url: doc_root + 'includes/ajax/forum.enable-treeview.php',
				ajax: {
					data: {
//						"additional": function() {
//							return "yeah: " + new Date;
//						},
						'project_id' : project_room_id
					},
					type: "post"
				}				
			});	
		},
		
		
		show : function(post_id) {
  			jQuery.post(doc_root + 'includes/ajax/forum.get-single-post.php', {
  				topic_id : post_id
  			}, function(data, status) {
				// update forum-compact-view
  				jQuery('#forum-compact-view').html(data.contents);
  				
//				// init rating
//				forum.rating.init();
//				
				jQuery('div.star').unbind('click');
				jQuery('div.star').bind('click', function() {return false;});
				jQuery('div.star').unbind('mouseover');
				jQuery('div.star').unbind('mouseout');
				jQuery('div.star').unbind('focus');
				jQuery('div.star').unbind('blur');
				jQuery('div.star').each(function() {
					if (!jQuery(this).hasClass('on')) {
						jQuery('a:hover', this).css('background-position', '0 0');
					}
				});				
				
  			}, 'json');
			
		},
		
		toggle: function() {
			// show compact view (tree)
			if (jQuery('.forum-tree-box').hasClass('hidden')) {
				jQuery('#forum-change-view-btn span').html('<img src="' + doc_root + 'misc/icons/sitemap_color.png" border="0"/>' + gt.gettext("Forumsbaum ausblenden"));
				jQuery('#forum-standard-view').fadeOut('normal', function() {
					jQuery('#forum-compact-view').fadeIn('normal');
				});
				jQuery('.forum-tree-box').slideDown('normal', function() { 
					jQuery(this).removeClass('hidden');
				});
				jQuery('.forum-tree-box').removeClass('hidden');
			}
			// show standard view
			else {
				jQuery('#forum-post-save-button').attr('onclick', '');
				jQuery('#forum-post-save-button').unbind('click'); // remove click event to avoid multiple bindings				
				jQuery('#forum-post-save-button').bind('click', function() {
					forum.response.save();
				});
				
				jQuery('#forum-change-view-btn span').html('<img src="' + doc_root + 'misc/icons/sitemap_color.png" border="0"/>' + gt.gettext("Forumsbaum einblenden"));
				jQuery('.forum-tree-box').slideUp('normal', function() {
					jQuery(this).addClass('hidden');
				});	
				
				jQuery('#forum-compact-view').fadeOut('normal', function() {
					jQuery('#forum-standard-view').fadeIn('normal', function() {
						// init if not already inited
						
						if (jQuery("#forum-standard-view div[id^='star-rating']").size() <= 0) {
							forum.rating.init();
						}
					});				
				});	
			}
		}
	}
	
	
};
