//$j().loadPlugin("idgforum/idgforum.ajax");
(function( $ ){
	var methods = {
			doRequest			: function(options) {
				$.ajax({
			    	url			:	"/forum/ajax/",
			        data		:	({
			        					'request':		options["requestHash"],
			        					'clientInput': 	options["clientInput"]
			        				}),
			        dataType	: 	"json",
			        type		: 	"post",
			        success		: 	function(response){
			        					if(response['success']) {
			        						if(methods[response['data']['handler']]) {
			        							methods[response['data']['handler']](response['data']['args']);
			        						} else {
			        							$.error('Handler ' + response['data']['handler'] + ' does not exist on jQuery.idgforum_ajax');
			        						}
			        					} else {
			        						methods['handleError'](response['data']);			        						
			        					}
									}          
				});
				return this;
			},
			handleError 		: function(myErrors) { 
				$.each(myErrors[400], function(key, value) { alert(value);});
				return this;
			},
			handleCategoryStats : function(args) {
				for(id in args) {
					for(property in args[id]) {
						if(property == 'read') {
							if(!args[id][property])	{
								$('#forum_read_'+id).each(function() {
									$(this).attr('src', '/images/idgforum/unread_48.png');
								});								
							}		
						} 			
					}
				}
				return this;
			},
			handleForumStats 	: function(args) {
				for(property in args) {
					methods['handleTopicStats']({"id":property, "data":args[property]});
				}
				return this;
			},
			handleTopicStats 	: function(args) {
				var id	 = args["id"];
				var data = args['data'];
				
				for(property in data) {
					if(property == 'title') {
						$('#topic_title_'+id).each(function() {
							$(this).html(data[property]);
						});						
					} else if(property == 'posts') {
						$('#topic_replies_'+id).each(function() {
								$(this).html(data[property]);
						});						
					} else if(property == 'views') {
						$('#topic_views_'+id).each(function() {
							$(this).html(data[property]);
						});						
					} else if(property == 'last_poster_uname') {
						$('#topic_last_poster_name_'+id).each(function() {
							$(this).html(data[property]);
						});											
					} else if(property == 'last_post_timestamp') {
						$('#topic_last_post_timestamp_'+id).each(function() {
							$(this).html(data[property]);
						});												
					} else if(property == 'read') {
						if(data[property] == "0") {
							$('#topic_read_'+id).each(function() {
								$(this).attr('src', '/images/idgforum/unread_20.png');
							});							
						}
					} else if(property == 'thumbsup') {
						$('#topic_thumbsup_'+id).each(function() {
							if(data[property]>0) {
								$(this).html("+"+data[property]+'&nbsp;<img src="/images/idgtracker/thumbup.gif" align="middle">');
							}
						});						
					}
				}
			},
			handleWatchTopic 	: function(args) { 
				var newContent = "";
				
				if(args['isWatched']=="1") {
					newContent = '<button id="idgforum_following" style="width:105px" onclick="ajaxRequest(\''+args['newRequest']+'\');return false;">Du følger</button>';					
				} else {
					newContent = '<button id="idgforum_follow" style="width:105px" onclick="ajaxRequest(\''+args['newRequest']+'\');return false;">Følg</button>';																								
				}
					
				$("#topic_watch_"+args['topicid']).html(newContent);
				$().idgforumButton("follow");
				$().idgforumButton("following");
				return this;
			},
			handleReportPost 	: function(args) { 
				if(args["postid"]>0) {
					$("#idgforum_report-"+args["postid"]).replaceWith('<button id="idgforum_reported-'+args['postid']+'" class="ui-state-error">Anmeldt</button>');
					$().idgforumButton("reported");
				}
				return this;
			},
			handleShowThumbsup 	: function(args) { 
				$("#totalThumbsup").html(args["thumbsup"]);
				return this;
			}
	};
	
	$.fn.idgforumAjax = function(method) {
		// Method calling logic
		if(methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if(typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.tooltip');
		}    
	};
}) (jQuery);

//Static function call
function ajaxRequest(requestHash, clientInput)
{
	$j().idgforumAjax("doRequest", {
			"requestHash": requestHash, 
			"clientInput": clientInput
	});
	return false;
}

//$j().loadPlugin("idgforum/idgforum.buttons");
(function( $ ){
	var methods = {
			answer 		: function(options) {
				$(":button[id|=idgforum_answer]").button({
					icons: { primary: "ui-icon-comment"}
				}).click(function(event){ 
						event.preventDefault();
						$.ajax({
							url: '/modules/idgforum/post.php',
							data: { 
								"op"		: "answer",
								"loc"		: $(this).attr("loc"),
								"postid"	: $(this).attr("postid")
							},
							dataType: "html",
							success: function(data) {
								$("#new_post").html(data);
								methods["register"]();
								methods["save"]();
								methods["cancel"]();
								methods["preview"]();
								$("#post_form").validate({
									rules: {
										post_text: "required"												
									},
									errorPlacement: function(error, element) {
										error.appendTo(element.siblings("#error"));
									}
								});
								$("#new_post").show();
								
								if(options["reply"]) {
									$("#idgforum_reply").hide();
								} else if (options["showall"]) {
									$("#foldedposts").show("blind");
									$("#showall").hide();
								}
								
								document.location = "#new_post";
							}
						});
				});
				return this;
			},
			reported 	: function() {
				$(":button[id|=idgforum_reported]").button({
					icons: { primary: "ui-icon-locked"},
					disabled: true			
				});
				return this;
			},
			report 		: function() {
				$(":button[id|=idgforum_report]").button({
					icons: { primary: "ui-icon-alert"}
				}).click(function() { 
					$('#report-requestHash').val($(this).attr("request"));
					$('#report-dialog-form').dialog("open");
				});
				return this;
			},
			register	: function() {
				$(":button[id|=idgforum_register]").button({
					icons: { primary: "ui-icon-plus"}}
				).click(function(e) { 
					e.preventDefault(); 
					document.location = "/forum/profile/login?redirectTo="+$(this).attr('redirect'); 
				});
				return this;
			}, 
			save		: function() {
				$(":button[id|=idgforum_save]").button({
					icons: { primary: "ui-icon-disk"}
				});
				return this;
			},
			cancel		: function() {
				$(":button[id|=idgforum_cancel]").button({
					icons: { primary: "ui-icon-cancel"}
				}).click(function(e) {
					e.preventDefault();
					$("#post_form")[0].reset();
				});
				return this;
			},
			canceltopic		: function() {
				$(":button[id|=idgforum_cancel]").button({
					icons: { primary: "ui-icon-cancel"}
				}).click(function(e) {
					e.preventDefault();
					$("#topic_form")[0].reset();
					document.location = $(this).attr('rel');
				});
				return this;
			},
			preview		: function() {
				$(":button[id|=idgforum_preview]").button({
					icons: { primary: "ui-icon-search"}
				}).click(function(e){ 
					e.preventDefault();
					$.ajax({
						url: '/modules/idgforum/post.php',
						data: {
							"op"		: "preview",
							"returnurl"	: $("#returnurl").val(),
							"topicid"	: $("#topicid").val(),
							"itemtype"	: $("#itemtype").val(),
							"itemid"	: $("#itemid").val(),
							"post_text" : $("#post_text").val()
						},
						dataType: "html",
						success: function(data) {
							$("#preview_post").html(data+ "<br class='clear'/>").show();
							document.location = "#preview_post";
						}
					});
				});
				return this;
			},
			previewtopic	: function() {
				$(":button[id|=idgforum_preview]").button({
					icons: { primary: "ui-icon-search"}
				}).click(function(e){ 
					e.preventDefault();
					$.ajax({
						url: '/modules/idgforum/topic.php',
						data: {
							"op"			: "preview",
							"returnurl"		: $("#returnurl").val(),
							"forumid"		: $("#forumid").val(),
							"itemtype"		: $("#itemtype").val(),
							"itemid"		: $("#itemid").val(),
							"topic_title" 	: $("#topic_title").val(),
							"post_text" 	: $("#post_text").val()
						},
						dataType: "html",
						success: function(data) {
							$("#preview_topic").html(data).show();
							document.location = "#preview_topic";
						}
					});
				});
				return this;
			},
			reply		: function() {
				$(":button[id|=idgforum_reply]").button({
					icons: { primary: "ui-icon-comment"}		
				}).click(function(e) {
					e.preventDefault();
					$.ajax({
						url: '/modules/idgforum/post.php',
						data: { 
							"op": "new",
							"topicid": $(this).attr("topicid")				
						},
						dataType: "html",
						success: function(data) {
							//Load the form into the div
							$("#new_post").html(data);

							//Style the new buttons
							methods["register"]();
							methods["save"]();
							methods["cancel"]();
							methods["preview"]();
							
							$("#post_form").validate({
								rules: {
									post_text: "required"												
								},
								errorPlacement: function(error, element) {
									error.appendTo(element.siblings("#error"));
								}
							});
							
							$("#new_post").show();				
						}		
					});
					$(this).hide();				
				});
			},
			following		: function() {
				$(":button[id|=idgforum_following]").addClass("ui-button-following").button({
					icons: { primary: "ui-icon-check"}
				}).hover(
					function() {
						$(this).toggleClass("ui-button-unfollow")
							.button({
								icons: {primary: "ui-icon-closethick"},
								label: "Følg ikke"
							});
					},
					function(){ 
						$(this).toggleClass("ui-button-unfollow")
							.button({
								icons: {primary: "ui-icon-check"},
								label: "Du følger"
							});
					}
				);						
			},
			follow			: function() {
				$(":button[id|=idgforum_follow]").addClass("ui-button-follow").button({
					icons: { primary: "ui-icon-plusthick"}
				});
			},
			thumbsup		: function() {
				$(":button[id|=idgforum_thumbsup]").addClass("ui-button-thumbsup").button({
					icons: { primary: "ui-icon-thumbsup"}
				}).click(function() {
					idg_tracker.track(TRACKER_TYPE_THUMB_UP, TRACKER_ITEMTYPE_FORUM_TOPIC, $(this).attr("itemid"), '');
					$(":button[id|=idgforum_thumbsup]").replaceWith('<button id="idgforum_hasThumbsup">Du synes om dette emne!</button>');
					$(":button[id|=idgforum_hasThumbsup]").addClass("ui-button-thumbsup").addClass("ui-state-highlight").button({
						icons: { primary: "ui-icon-thumbsup"},
						disabled: true		
					});
				});
			},
			hasThumbsup		: function() {
				$(":button[id|=idgforum_hasThumbsup]").addClass("ui-button-thumbsup").addClass("ui-state-highlight").button({
					icons: { primary: "ui-icon-thumbsup"},
					disabled: true		
				});
			}			
	};
	
	$.fn.idgforumButton = function(method) {
		// Method calling logic
		if(methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if(typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.idgforumButton');
		}    
	};	
	
}) (jQuery)

//$j().loadPlugin("idgforum/idgforum.functions");
function displayLinkWarning(element) {
	$link = $j(element).attr("href");
	
	if (!($link.indexOf("http://"+document.domain) == 0)) { //Link does not start with current domain
		$j('#idgforum-warning-link').html($link);
		$j('#idgforum-warning').dialog("open");
		return false;
	}
	
	return true;
}

function addBBCode(element, startWith, closeWith, option)
{
	var input, begin, end;
	var selection; //array(id, start, length, end, [selected]text) 
	selection = $j(element).getSelection();
	
	begin 	= $j(element).val().substr(0,selection.start); 
	end 	= $j(element).val().substr(selection.end, $j(element).val().length);
	
	if(option == 'img') {
		var prefill = "http://";
		if(selection.text.length > 0) {
			prefill = selection.text;
		}
		
		input = prompt("Angiv billedets webadresse",prefill);		
		if(input == null) {
			return;
		}
	}
	
	if(option == 'url') {
		var prefill = "http://";
		if(selection.text.length > 0) {
			closeWith = closeWith.replace(/link/i, selection.text);
			if(selection.text.indexOf('http://') != -1) {
				prefill = selection.text;
			}
		}
	
		input = prompt("Angiv webadressen",prefill);
		if(input == null) {
			return;
		}
	}
	
  	if(selection.text.length > 0) {
  		if(option == 'img' || option == 'url') {
  			startWith = startWith.replace('%s', input);
  			if(input == selection.text) {
  				startWith = startWith.replace('='+selection.text, '');
  			}
  			closeWith = closeWith.replace('%s', input);
  			$j(element).val(begin + startWith + closeWith + end);
  		} else {
  			$j(element).val(begin + startWith + selection.text + closeWith + end);
  		}
  	} else {
  		if(option == 'img' || option == 'url') {
  			var output = startWith + closeWith;
  			output = output.replace('%s',input);
  			$j(element).val($j(element).val() + output);
  		} else {
  			$j(element).val($j(element).val() + startWith + input + closeWith);
  		}
  	}
}

/*
 * jQuery plugin: fieldSelection - v0.1.0 - last change: 2006-12-16
 * (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd
 */
(function() {
	var fieldSelection = {
		getSelection: function() {
			var e = this.jquery ? this[0] : this;
			return (
				/* mozilla / dom 3.0 */
				('selectionStart' in e && function() {
					var l = e.selectionEnd - e.selectionStart;
					return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) };
				}) ||

				/* exploder */
				(document.selection && function() {
					e.focus();

					var r = document.selection.createRange();
					if (r == null) {
						return { start: 0, end: e.value.length, length: 0 }
					}

					var re = e.createTextRange();
					var rc = re.duplicate();
					re.moveToBookmark(r.getBookmark());
					rc.setEndPoint('EndToStart', re);

					return { start: rc.text.length, end: rc.text.length + r.text.length, length: r.text.length, text: r.text };
				}) ||

				/* browser not supported */
				function() {
					return { start: 0, end: e.value.length, length: 0 };
				}
			)();
		},
		replaceSelection: function() {
			var e = this.jquery ? this[0] : this;
			var text = arguments[0] || '';
			return (
				/* mozilla / dom 3.0 */
				('selectionStart' in e && function() {
					e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
					return this;
				}) ||

				/* exploder */
				(document.selection && function() {
					e.focus();
					document.selection.createRange().text = text;
					return this;
				}) ||

				/* browser not supported */
				function() {
					e.value += text;
					return this;
				}
			)();
		}
	};
	jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });
})();

//modules/idgforum/javascript/forum.js
$j(function() {
	$j("#new_topic").button({
		icons: { primary: "ui-icon-comment"}		
	}).click(function () {
		location.href = $j(this).attr("link");
	});
});

//modules/idgforum/javascript/topic.js
$j(document).ready(function() {
	$j("#report_form").validate({
		rules: {
			"report-requestHash": "required",
			"report-reason": "required"									
		},
		errorPlacement: function(error, element) {
			error.insertAfter(element.parent());
		}
	});
	
	$j("#report-dialog-form").dialog({
		autoOpen: false,
		height: 320,
		width: 450,
		modal: true,
		resizable: false,
		buttons: {
			Cancel: function() {
				$j(this).dialog("close");
			},
			"Report": function() {
				ajaxRequest($j("#report-requestHash").val(),
							{
							 	"reason": $j("#report-reason").val(),
							 	"comment": $j("#report-comment").val()
							}); 
				$j(this).dialog("close");
			}			
		}
	});
	
	$j("#idgforum-warning").dialog({
		autoOpen: false,
		height: 320,
		width: 450,
		modal: true,
		resizable: false,
		title: '<span class="ui-icon ui-icon-alert" style="float:left"></span>&nbsp;Attention!',
		buttons: {
			"No": function() {
				$j(this).dialog("close");				
			},
			"Yes": function() {
				document.location = $j("#idgforum-warning-link").html();				
			}			
		}
	})
	
	$j().idgforumButton("report");
	$j().idgforumButton("reported");
	$j().idgforumButton("answer", {"reply" : true});
	$j().idgforumButton("reply");
	$j().idgforumButton("follow");
	$j().idgforumButton("following");
	$j().idgforumButton("thumbsup");
	$j().idgforumButton("hasThumbsup");
	
	//For creating a new topic
	$j().idgforumButton("save");
	$j().idgforumButton("canceltopic");
	$j().idgforumButton("previewtopic");
	
	$j("#topic_form").validate({
		errorPlacement: function(error, element) {
			error.appendTo(element.siblings("#error"));
		}
	});
	
	//Autocomplete on keyword field
	function split( val ) {
		return val.split( /,\s*/ );
	}
	function extractLast( term ) {
		return split( term ).pop();
	}
	
	$j("#topic_keywords")		
		// don't navigate away from the field on tab when selecting an item
		.bind("keydown", function(event) {
		if ( event.keyCode === $j.ui.keyCode.TAB &&
				$( this ).data( "autocomplete" ).menu.active ) {
			event.preventDefault();
		}
	})
	.autocomplete({
		source: function( request, response ) {
			$j.getJSON( "/forum/topic/keywordsearch/", {
				term: extractLast(request.term)
			}, response );
		},
		search: function() {
			// custom minLength
			var term = extractLast(this.value);
			if ( term.length < 2 ) {
				return false;
			}
		},
		focus: function() {
			// prevent value inserted on focus
			return false;
		},
		select: function(event, ui) {
			var terms = split( this.value );
			// remove the current input
			terms.pop();
			// add the selected item
			terms.push( ui.item.label );
			// add placeholder to get the comma-and-space at the end
			terms.push( "" );
			this.value = terms.join( ", " );
			return false;
		}
	});	
});

//modules/idgforum/javascript/profile.js
$j(document).ready(function() {
	$j("#profile_form").validate({
		rules: {
			agree: "required",
			username: {
				required: true,
				minlength: 2
				
			},
			pass1: {
				required: true,
				minlength: 6
			},
			pass2: {
				required: true,
				minlength: 6,
				equalTo: "#pass1"
			},
			name: "required",
			address: "required",
			postal: "required",
			city: "required",
			email: {
				required: true,
				email: true
			}							
		},
		errorPlacement: function(error, element) {
			error.insertAfter(element.parent());
		}
	});
	
	$j("#edit_profile").click(function() { 
		document.location = "/forum/profile/edit/"; 
	});
	
	$j(":button[id|=goto_edit]").button({ 
		icons: { primary: "ui-icon-pencil" } 
	}).click(function () {
		document.location = "/forum/profile/edit/";
	});
	
	$j(":button[id|=new_profile]").button({
		icons: { primary: "ui-icon-plus" }
	});
	
	$j(":button[id|=upgrade_profile]").button({
		icons: { primary: "ui-icon-plusthick" }
	});
	
	$j(":button[id|=edit_profile]").button({
		icons: { primary: "ui-icon-pencil" }
	});
	
	$j().idgforumButton("follow");
	$j().idgforumButton("following");

});


