
var KB = (function() {} );

KB.Aliases = {
	'exampleAlias' : function () { alert('test'); }
};

KB.UI = {
	expand : function() {
		var div = $('#' + $(this).attr('expand'));
		var hidden = (div.css('display') == 'none');
		if(hidden) {
			$(this).css('backgroundImage', 'url(../images/icons/collapse.png)');
			div.slideDown('normal');
			Webonyx.cookie.create('xc-' + $(this).attr('expand'), 'expanded', 365);
		} else {
			$(this).css('backgroundImage', 'url(../images/icons/expand.png)');
			div.slideUp('normal');
			Webonyx.cookie.create('xc-' + $(this).attr('expand'), '', -1);
		}
	},
	
	defaultText : function() {
        var msg = $(this).attr('dval');
        $(this).focus(function(e) {
            if($(this).val() == msg) {
                $(this).removeClass('default').val('');
            }
        }).blur(function(e) {
            if($(this).val() == '') {
                $(this).addClass('default').val(msg);
            }
        });
        $(this).blur();
	}
	
};

KB.Dialog = {
	
	INFO : 1,
	WARN : 2,
	ERR  : 4,
	STATIC : 8,
	PROGRESS : 16,
	CONFIRM : 32,

	show : function(msg, type, timeout) {
		if(!timeout) {
			timeout = 1500;
		}
		$.modal.close();
		switch(type) {
			case KB.Dialog.ERR:
				alert(msg);

				break;
			case KB.Dialog.WARN:
				alert(msg);
				
				break;
			case KB.Dialog.CONFIRM:
				return confirm(msg);
				break;
				
			case KB.Dialog.PROGRESS:
				$('#message-dialog').html('<img src="/images/medium-loader.gif" style="width:128px;" />').modal({position:['20%',null]});
				break;
			default:
				$('#message-dialog').html(msg).modal({position:['20%',null], onClose : function(dialog) {
					dialog.container.fadeOut('normal', function () {
						$.modal.close(); // must call this!
					});
				}});
				if(type != KB.Dialog.STATIC) {
					setTimeout(function() {
						$.modal.close();
					}, timeout);
				} else {
					$('#message-dialog form').each(Webonyx.initForm);
					$('#message-dialog :input[dval]').each(KB.UI.defaultText);
				}
				break;
		}
		
	},
	
	close : function() {
		$.modal.close();
	},
	
	setHtml : function(html) {
		$('#message-dialog').html(html);
	},
	
	ajaxHandlers : function() {
		
		$('#loading').ajaxStart(function() {
			$(this).show();
		});
		
		$('#loading').ajaxStop(function() {
			$(this).hide();
		});

	}
};

KB.Buttons = {
	init : function() {
		$('.add-hover').hover(function(e) {
			$(this).addClass('hover');
		}, function(e) {
			$(this).removeClass('hover');
		});
	}
};

KB.Auth = {
	showLogin : function(btn) {
		var frm = $('#login-form');
		frm.modal({position:['20%',null]});
		frm.find('input:first').focus();
		frm.keydown(function(e) {
			if(e.keyCode == 27) {
				$('#login-error').hide();
				frm.find('form').clearForm();
				frm.hide();
			}
		});
	},
	
	forgotPassword : function(r) {
		if (Webonyx.ajax.isError(r)) {
			KB.Dialog.show(r.message, KB.Dialog.ERR);
			return;
		}
		
		KB.Dialog.show(r.message, KB.Dialog.INFO, 3000);
		setTimeout(function() {
			Webonyx.util.redirect('/');
		}, 3000);
		
	},
	
	login : function(r) {
		if (Webonyx.ajax.isError(r)) {
			$('#login-error').show().html(r.message);
			setTimeout(function() {
				$('#login-error').fadeOut('slow');
			}, 2000);
			return;
		}
		Webonyx.util.reload();
	}
};

KB.Group = {
	loadedRows : 10,
	
	more : function(q) {
		var params = {
				'q':q,
				'loadedRows':this.loadedRows
		};
		$.post('/group/more', params, function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			
			var result = $(r.data.template).css('display','none');
			result.appendTo($('#groups')).slideDown(150);
			if (!r.data.more) {
				$('#more-bar').css('display', 'none');
				$('#no-more-bar').css('display', 'block');
			} 
			KB.Search.loadedRows = r.data.loadedRows;
			
		},'json');
	},
	
	saved : function(r) {
		if (Webonyx.ajax.isError(r)) {
			KB.Dialog.show(r.message, KB.Dialog.ERR);
			return;
		}
		Webonyx.util.redirect('/groups/' + r.data.slug);
	},
	
	Suggestion : {
		showing : [],
		hide : function(e) {
			var _self = $(this);
			var params = {
				'group_id' : _self.attr('class'),
				'current'  : KB.Group.Suggestion.showing
			};
			$.post('/group/hide-suggestion', params, function(r) {
				if (Webonyx.ajax.isError(r)) {
					KB.Dialog.show(r.message, KB.Dialog.ERR);
					return;
				}
				if(r.data) {
					KB.Group.Suggestion.showing.push(r.data.id);
					_self.parentsUntil('.suggestion-sm').parent().replaceWith(r.data.suggestion);
					$('.suggestion-sm .' + r.data.id).click(KB.Group.Suggestion.hide);
				} else {
					_self.parentsUntil('.suggestion-sm').parent().remove();
				}
			},'json');
		}
	},
	
	Event : {
		created : function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			
			if($('#e_' + r.data.last_id).length) {
				$('#e-form').trigger('reset');
				return;
			}
			
			KB.Event.last_id = r.data.last_id;
			var event = $(r.data.event);
			event.find('form').each(Webonyx.initForm);
			
			$('#g-eventlist').prepend(event);
			
			$('#e_' + r.data.last_id).hover(function(e) {
				$(this).addClass('hover');
			}, function(e) {
				$(this).removeClass('hover');
			});
			
			$('#e-form').trigger('reset');
			
		}
	},
	
	Feed : {
	
		created : function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			
			$('#f-url').val('').blur();
			$('#feed-list').append(r.data);
	        $('#feed-list li').hover(function(e) {
	            $(this).addClass('hover');
	        }, function(e) {
	            $(this).removeClass('hover');
	        });
			
		},
		
		remove : function(gid, feed) {
			var params = {
				'group_id' : gid,
				'url' : feed
			};
			$.post('/group/remove-feed', params, function(r) {
				if (Webonyx.ajax.isError(r)) {
					KB.Dialog.show(r.message, KB.Dialog.ERR);
					return;
				}
				$('#' + r.data.id).remove();
			},'json');
		}
		
	},
	
	Members : {
		invited : function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			
			$('#invite-addresses').val('').css('height', 50);
			$('#invite-message').show().find('span').html(r.data.invites);
			setTimeout(function() {
				$('#invite-form')[0].reset();
				$('#invite-message').hide();
				$("#g-tabs").tabs('select', 0);
			}, 1500);
			
		}
	},
	
	Moderate : {
		
		userOptions : function(e) {
			var cb = $(this);
			var params = {
				'group_id' : cb.attr('value'),
				'user_id'  : cb.attr('name'),
				'moderator': cb.attr('checked')
			};
			$.post('/group/mod-set-moderator', params, function(r) {
				if (Webonyx.ajax.isError(r)) {
					KB.Dialog.show(r.message, KB.Dialog.ERR);
					return;
				}
			},'json');
			
		},
		
		userRemove : function(e) {
			var conf = confirm("Are you sure you want to remove this member?");
			if(!conf) {
				e.preventDefault();
				return;
			}
			var link = $(this);
			var params = {
				'group_id' : link.attr('gid'),
				'user_id'  : link.attr('uid')
			};
			$.post('/group/mod-remove-user', params, function(r) {
				if (Webonyx.ajax.isError(r)) {
					KB.Dialog.show(r.message, KB.Dialog.ERR);
					return;
				}
				$('#member-' + link.attr('uid')).remove();
			},'json');
		}
		
	},
	
	join : function(gid, btn) {
		var params = {
			'group_id' : gid
		};
		$.post('/group/join', params, function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			if(btn) {
				if($(btn).text() == '+ Join Group') {
					$(btn).text('+ Joined').unbind('click');
				} else {
					$(btn).addClass('joined');
					$(btn).unbind('click');
					$('#group-' + gid + ' .hide').remove();
				}
			} else {
				window.location.href = window.location.href + '?mid=1';
			}
		},'json');
	},
	
	joinViaTile : function(gid, slug) {
		var params = {
			'group_id' : gid
		};
		$.post('/group/join', params, function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			
			$('#group-'+gid).html("<p class=\"joined\">You have successfully joined this group. <a href=\"/groups/"+slug+">Click here</a> to view it</p>");
		},'json');
	},
	
	notInterested : function(gid) {
		var params = {
			'group_id' : gid
		};
		$.post('/group/not-interested', params, function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			
			$('#group-'+gid).html("<p class=\"joined\">You will not longer be suggested this group.</p>");
		},'json');
	},
	
	hide : function(e) {
		var _self = $(this);
		var params = {
			'group_id' : _self.attr('class')
		};
		$.post('/group/hide-suggestion', params, function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			var index = _self.parentsUntil('.jcarousel-item').parent().attr('jcarouselindex');
			$('#suggestedCaro').data('jcarousel').removeAndAnimate(index);
		},'json');
	},
	
	carousel : null,
	
	leave : function(gid) {
		if (KB.Dialog.show("Are you sure you want to leave this group?", KB.Dialog.CONFIRM)) {
			var params = {
				'group_id' : gid
			};
			$.post('/group/leave', params, function(r) {
				if (Webonyx.ajax.isError(r)) {
					KB.Dialog.show(r.message, KB.Dialog.ERR);
					return;
				}
				Webonyx.util.reload();
			},'json');
		}
	},
	
	Preferences : {
	
		saved : function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			$.modal.close()
			
			var emails = $('input[name*="email"]');
			var allEmails = false;
			for (var i = 0; i < emails.length; i++) {
				if ($(emails[i]).attr('checked')) {
					allEmails = true;
				}
			}
			
			if (allEmails) {
				$('#emailSubIconOn').css('display', 'inline');
				$('#emailSubIconOff').css('display', 'none');
		    } else {
		    	$('#emailSubIconOff').css('display', 'inline');
				$('#emailSubIconOn').css('display', 'none');
		    }
			
			var texts = $('input[name*="sms"]');
			var allTexts = false;
			for (var i = 0; i < texts.length; i++) {
				if ($(texts[i]).attr('checked')) {
					allTexts = true;
				}
			}
			
			if (allTexts) {
				$('#smsSubIconOn').css('display', 'inline');
				$('#smsSubIconOff').css('display', 'none');
		    } else {
		    	$('#smsSubIconOff').css('display', 'inline');
				$('#smsSubIconOn').css('display', 'none');
		    }
		},
		
		savePreferences : function(e) {
			$(this).html('Saving...');
			$('#form-save-preferences').submit();
		},
		
		hideFeed : function(e) {
			var link = $(this);
			var params = {
				'feed_url' : $(this).attr('fid'),
				'name'     : $(this).attr('fname')
			};
			$.post('/group/hide-feed', params, function(r) {
				if (Webonyx.ajax.isError(r)) {
					KB.Dialog.show(r.message, KB.Dialog.ERR);
					return;
				}
				
				var msg = $('<span class="message">' + r.message + '</span>');
				link.after(msg);
				link.remove();
				setTimeout(function() {
					$.modal.close();
				}, 2000);
				
			},'json');
			
		},
		
		restoreFeed : function(e) {
			var link = $(this);
			var params = {
				'feed_url' : $(this).attr('fid'),
				'name'     : $(this).attr('fname')
			};
			$.post('/group/restore-feed', params, function(r) {
				if (Webonyx.ajax.isError(r)) {
					KB.Dialog.show(r.message, KB.Dialog.ERR);
					return;
				}
				
				var msg = $('<span class="message">' + r.message + '</span>');
				link.after(msg);
				link.remove();
				setTimeout(function() {
					$.modal.close();
				}, 2000);
				
			},'json');
		},
		
		checkPhoneNumber : function(e) {
			if(!$(this).attr('checked') || $(this).attr('hasMob')) {
				return;
			}
			
            $('#mobile-number').show();
			
		},
		
		toggleTagPrefs : function(obj, type) {
			var match = 'notify_tag_sms';
			if(type == 'email') {
				match = 'notify_tag_email';
			}
			$(obj.form).find('[name*=' + match + ']').attr('disabled', obj.checked);
		},
		
		cancel : function(e) {
			$.modal.close();
		}
	}
};

KB.User = {
	
	created : function(r) {
		if (Webonyx.ajax.isError(r)) {
			KB.Dialog.show(r.message, KB.Dialog.ERR);
			return;
		}
		
		Webonyx.util.redirect('/');
		
	},
	
	saved : function(r) {
		if (Webonyx.ajax.isError(r)) {
			KB.Dialog.show(r.message, KB.Dialog.ERR);
			return;
		}
		
		KB.Dialog.show(r.message, KB.Dialog.INFO, 2000);
		
	},
	
	passwordUpdated : function(r) {
		if (Webonyx.ajax.isError(r)) {
			KB.Dialog.show(r.message, KB.Dialog.ERR);
			return;
		}
		KB.Dialog.setHtml(r.message);
		setTimeout(function() {
			$.modal.close();
		}, 1500);
	},
	
	Settings : {
		
		passwordUpdated : function(r) {
			KB.User.saved(r);
			if (!Webonyx.ajax.isError(r)) {
				$('#settings-update-password').clearForm();
			} else {
				$('#settings-update-password input:first').select().focus();
			}
		},
		
		mobileUpdated : function(r) {
			KB.User.saved(r);
		},
		
		mobileActivated : function(r) {
			KB.User.saved(r);
			setTimeout(function() {
				Webonyx.util.reload();
			}, 2500);
		},
		
		mobileDeactivated : function(r) {
			KB.User.saved(r);
			setTimeout(function() {
				Webonyx.util.reload();
			}, 2500);
		},
		
		dndUpdated : function(r) {
			KB.User.saved(r);
		}
	
	}
	
};

KB.Event = {
	
	Comment : {
		remove : function (eId, cId, obj) {
			if (KB.Dialog.show("Are you sure you want to delete this comment?", KB.Dialog.CONFIRM)) {
				var params = {
					'event_id' : eId,
					'comment_id' : cId
				};
				$.post('/message/remove-comment', params, function(r) {
					if (Webonyx.ajax.isError(r)) {
						KB.Dialog.show(r.message, KB.Dialog.ERR);
						return;
					}
					$(obj).parents('div.cbody').html('<div class="pad"><em>'+r.data.html+'</em></div>');
				},'json');
			}
		}, 
		
		created : function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			
			$('#comment-list').append(r.data.html);
			$('#comment-input textarea').val('');
			
		},

		icreated : function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			
			$('#' + r.data.id).before(r.data.html);
			$('#' + r.data.id + ' textarea').val('').blur();
			KB.Event.Comment.showAll(r.data.id.replace('c-', ''));
			
		},
		
		showInput : function(id) {
			var c = $('#' + id);
			c.show();
			c.find('input[type=text]').hide();
			c.find('.expanded-input').show().find('textarea').focus().blur(function(e) {
				if($(this).val() == '') {
					var input = c.find('input[type=text]');
					if(input.val()) {
						c.find('input[type=text]').show();
						c.find('.expanded-input').hide();
					}
				}
			});
		},
		
		showAll : function(id) {
			$('#' + id).find('.comment').show();
			$('#' + id).find('.showall').hide();
		}
	
	},
	
	showOptions : function(id) {
		var params = {'id' : id};
		$.get('/message/get-options', params, function(r) {
			$('#message-options').html(r).modal({position:['15%',null], onClose : function(dialog) {
				dialog.container.fadeOut('normal', function () {
					$.modal.close(); // must call this!
				});}
			});
			
			// Other Bindings
			$('#message-options form.story').each(Webonyx.initForm);
			$('#message-options [class*=KB_]').each(function() { 
				$(this).click(eval('KB.Group.Preferences.' + $(this).attr('class').replace('KB_', '')));
			});
				
		});
		
	},
	
	updateProfileEvents : function(message) {
		KB.Event.checkForNew('/index/get-new', $('#home-events'));
	},
	
	updateGroupEvents : function(message) {
		KB.Event.checkForNew('/group/check-new-messages', $('#g-eventlist'), message.data.group_id);
	},

	updateEventComments : function(message) {
		KB.Event.updateComments(message.data);
	},
	
	updateComments : function(data) {
		var container = $('#c-' + data.hash);
		var params = {
			comment_id : data.comment_id,
			event_id   : data.event_id
		};
		
		if($('#' + data.comment_id).length) {
			return;
		}
		
		$.get('/message/get-comment-updates', params, function(r) {
			if (Webonyx.ajax.isError(r)) {
				return;
			}
			
			if(r.data.comment) {
				var comment = $(r.data.comment);
				container.before(comment);
			}
			
		},'json');
		
	},
	
	last_id : null,
	
	checkForNew : function(service, list, gid) {
		if(gid == undefined) {
			gid = '';
		}
		var params = {
			'last_id'  : KB.Event.last_id,
			'group_id' : gid
		};
		
		$.get(service, params, function(r) {
			if (Webonyx.ajax.isError(r)) {
				return;
			}

			if($('#e_' + r.data.last_id).length) {
				return;
			}
			
			KB.Event.last_id = r.data.last_id;
			if(r.data.events) {
				var events = $(r.data.events);
				list.prepend(events);
				
				for(var i in r.data.ids) {
					$('#e_' + r.data.ids[i] + ' form').each(Webonyx.initForm);
					$('#e_' + r.data.ids[i]).hover(function(e) {
						$(this).addClass('hover');
					}, function(e) {
						$(this).removeClass('hover');
					});
                    $('#e_' + r.data.ids[i] + ' textarea').height(51).elastic();
				}
			}
			
		},'json');
	},
	
	remove : function (eId) {
		if (KB.Dialog.show("Are you sure you want to delete this message?", KB.Dialog.CONFIRM)) {
			var params = {
				'event_id' : eId
			};
			$.post('/message/remove-message', params, function(r) {
				if (Webonyx.ajax.isError(r)) {
					KB.Dialog.show(r.message, KB.Dialog.ERR);
					return;
				}
				$('#e_' + eId).removeClass('add-hover').html('<div class="pad"><em>'+r.data.html+'</em></div>');
				setTimeout(function() {
					$('#e_' + eId).fadeOut();
				}, 1500);
			},'json');
		}
	}
};

KB.Search = {		
	loadedRows : 1,
	
	more : function(q) {
		var params = {
				'q':q,
				'loadedRows':this.loadedRows
		};
		$.post('/search/more', params, function(r) {
			if (Webonyx.ajax.isError(r)) {
				KB.Dialog.show(r.message, KB.Dialog.ERR);
				return;
			}
			
			var result = $(r.data.template).css('display','none');
			result.appendTo($('#results')).slideDown(150);
			if (!r.data.more) {
				$('#more-bar').css('display', 'none');
				$('#no-more-bar').css('display', 'block');
			} 
			KB.Search.loadedRows = r.data.loadedRows;
			
		},'json');
	}
};

$(document).ready(function() {
	KB.Buttons.init();

	$('textarea.tinymce').tinymce({
		theme : "simple",
		content_css : "/css/base.css,/css/kb.css"
	});
	$('form').bind('form-pre-serialize', function(e) {
		tinyMCE.triggerSave();
	});
	
	$('form').submit(function() {
		var btn = $(this).find('input[type=submit]');
		var w = btn.width() + 18;
		btn.attr('tmpvalue', btn.val());
		btn.css('width', w + 'px').val('Please wait...').addClass('loading').attr('disabled', 'disabled');
	});
	
	$('form.auto-submit input').click(function() {
		$(this.form).trigger('submit');
	});
	
	$('textarea[autoexpand]').height(51).elastic();
	
	$('[expand]').click(KB.UI.expand);
	
	$(':input[dval]').each(KB.UI.defaultText);
	
	// Setup default ajax handlers
	KB.Dialog.ajaxHandlers();
	
});
