var Connect = {
	/* api: "5e32df598516ca96003be6f0c0c5390d",*/
	api: "ad5bde842084000d8f7a0807a8b39d70",
	xd: "/xd_receiver.htm",
	fanPageId: "124028419460",
	init: function(){
		FB_RequireFeatures(["XFBML"], function(){
			FB.init(Connect.api, Connect.xd, { ifUserConnected: Connect.login });
			FB.XFBML.Host.autoParseDomTree = false;
			$(".fb-login").attr("onlogin", "Connect.login()").fbml("LoginButton");
			$(".fb-picture").each(function(){
				var pic = $(this);
				pic.attr("uid", pic.attr("title")).fbml("ProfilePic");
			});
			$(".fb-fanbox").append("<fb:fan profile_id=\"" + Connect.fanPageId + "\" stream=\"0\" connections=\"12\" width=\"374\"></fb:fan>").each(function(){
				FB.XFBML.Host.parseDomElement(this);
			});
			//Connect.login(699525550); // Remove
		});
	},
	login: function(uid){
		if(!uid){ uid = FB.Facebook.apiClient.get_session().uid; }
		if(!Connect.list){
			$(".friends").each(function(){
				var url = $("input[name=page_url]", this).val();
				Connect.list = new FriendList(this, { "limit": 7 });
				Connect.inviteForm = new InvitationForm({ "url": url });
				
				$(".fb-login-wrap", this).hide();
				
				$(this).after( $("<p />").append( $("<a href=\"#invite\">Tipsa in dina Facebook-vänner</a>").click(Connect.invite) ) );
			});
		}
		if(!Connect.form){
			$("div.discussion-login div.login-form").each(function(){
				Connect.form = new ReplyForm(this, { "uid": uid, "api": Connect.api });
			});
		}
		if(!Connect.controlPanel){
			$("#login").hide();
			$("#facebook-side div.login-form").hide();
			$("#facebook-side").append(
				$("<div class=\"picture-wrap />").append($("<div uid=\"" + uid + "\" size=\"square\" linked=\"false\" />").fbml("ProfilePic")),
				$("<p class=\"fb-text\">Inloggad som </p>").append($("<span uid=\"" + uid + "\" useyou=\"false\" linked=\"false\" />").fbml("Name")),
				$("<a class=\"button-blue\" href=\"#logout\">Logga ut</a>").click(Connect.logout)
			);
			Connect.controlPanel = true;
		}
	},
	invite: function(e){
		e.preventDefault();
		Connect.inviteForm.show();
	},
	logout: function(e){
		if(e){ e.preventDefault(); }
		FB.Connect.logoutAndRedirect(document.location.href);
	}
};
var ReplyForm = function(el, options){
	$.extend(this.options, options);
	this.login = $(el);
	this.login.hide();
	this.thread = $("div.discussion-replies");
	this.threadid = $("input[name=threadid]").val();
	this.render();
};
ReplyForm.prototype = {
	options: {
		url: "/templates/ua/pages/ajax/comment.aspx",
		image: "img/no-pic.gif",
		cssClass: "discussion-replies-item",
		altCssClass: "discussion-replies-item-alt",
		prepend: false
	},
	render: function(){
		this.form = $("<div class=\"reply-form clearfix\" />");
		this.field = $("<textarea class=\"field-blue\" cols=\"40\" rows=\"4\" />");
		this.submit = $("<input class=\"button-gray\" value=\"Skicka\" type=\"submit\" disabled=\"disabled\" />").click($.fnbind(this.submit, this));
		this.form.append(
			$("<div class=\"field-wrap\" />").append(
				"<label>Kommentar<br /></label>",
				this.field,
				this.submit
			),
			$("<div class=\"picture-wrap />").append("&nbsp;<br />", $("<div uid=\"" + this.options.uid + "\" />").fbml("ProfilePic"))
		);
		this.login.after(this.form);
		FB.Facebook.apiClient.users_getInfo([this.options.uid], ["name"], $.fnbind(this.hasInfo, this));
		
	},
	hasInfo: function(data){
		this.name = data[0].name;
		this.submit.attr("disabled", false);
	},
	submit: function(e){
		e.preventDefault();
		this.field.attr("disabled", true);
		this.submit.attr("disabled", true);
		this.form.addClass("loading");
		
		$.post(this.options.url, {
			"comment": this.field.val(),
			"uid": this.options.uid,
			"api": this.options.api,
			"name": this.name,
			"threadid" : this.threadid
		}, $.fnbind(this.complete, this), "html");
	},
	complete: function(obj){
		var s = obj.split('~~~~~~~~~~');
		var text = s[0];
		var data = s[1];
		if(data && data.length>0){
			this.form.removeClass("loading");
		
			var c = this.thread.children();
			var cssClass = $(c[c.length - 1]).hasClass(this.options.altClass) ? this.options.cssClass : this.options.altCssClass;
			
			var post = $("<div class=\"" + cssClass + " clearfix\">" + data + "</div>").hide();
			if(this.options.prepend)
				this.thread.prepend(post);
			else
				this.thread.append(post);
				
			$(".fb-picture", post).each(function(){
				var pic = $(this);
				pic.attr("uid", pic.attr("title")).fbml("ProfilePic");
			});
			post.slideDown();
			
			var success = $("<div class=\"success\">" + text + "</div>").hide();
			this.form.before(success);
			success.slideDown();
			
		}else{
			var error = $("<div class=\"error\">" + text + "</div>").hide();
			this.form.before(error);
			error.slideDown();
		}
	}
};
var FriendList = function(wrapper, options){
	$.extend(this.options, options);
	this.wrapper = $(wrapper);
	FB.Facebook.apiClient.friends_get(null, $.fnbind(this.render, this));
};
FriendList.prototype = {
	options: {
		element: "ul",
		cssClass: "fb-friends clearfix",
		limit: 5
	},
	render: function(arr){
		if(arr){
			var friends = [];
			var max = arr.length > this.options.limit ? this.options.limit : arr.length;
			for(var i=0;i<max;i++){
				var index = $.rand(0, (arr.length - 1));
				friends.push(arr[index]);
				arr.splice(index,1);
			}
			var el = $("<" + this.options.element + " class=\"" + this.options.cssClass + "\" />");
			$(friends).loop(function(id){
				el.append(
					$("<li />").append(
						$("<div uid=\"" + id + "\" size=\"square\" linked=\"false\" />").fbml("ProfilePic")
					)
				);
			}, this);
			this.wrapper.html(el);
		}
	}
};
$(document).ready(Connect.init);

var EmailForm = function(wrapper, options){
	$.extend(this.options, options);
	this.wrapper = $(wrapper);
	this.field = $("textarea", this.wrapper);
	this.button = $("input[type=submit]", this.wrapper);
	this.button.click($.fnbind(this.submit, this));
};
EmailForm.prototype = {
	options: {
		url: "dummies/sendEmail.aspx"
	},
	submit: function(e){
		e.preventDefault();
		this.button.attr("disabled", true);
		this.field.attr("disabled", true);
		this.wrapper.addClass("loading");
		$.post(this.options.url, { "email": this.field.val() }, $.fnbind(this.complete, this), "json");
	},
	complete: function(obj){
		this.wrapper.removeClass("loading");
		var response = $("<div class=\"" + (obj.response ? "success" : "error") + ">" + obj.text + "</div>").hide();
		this.wrapper.before(response);
		response.slideDown();
	}
};
var InvitationForm = function(options){
	$.extend(this.options, options);
	this.render();
	this.w = $(window);
};
InvitationForm.prototype = {
	options: {
		cssClass: "invitation-form",
		header: "Tipsa dina vänner",
		invitation: "Unga Aktiespararna ordnar en aktivitet som jag tror du skulle vara intresserad av",
		button: "Läs mer"
	},
	render: function(){
		this.wrapper = $("<div class=\"" + this.options.cssClass + "\" />");
		this.wrapper.appendTo($(document.body));
		
		var fbml = '<fb:serverfbml style="width: 750px"><script type="text/fbml"><fb:fbml><fb:request-form action="' + this.options.url + '" method="POST" type="invite" content="' + this.options.invitation +
		" <fb:req-choice url='" + this.options.url + "' label='" + this.options.button + "' />" + 
		'"><fb:multi-friend-selector showborder="false" actiontext="' + this.options.header + '" max="20" /></fb:request-form></fb:fbml></script></fb:serverfbml>';
		
		FB_RequireFeatures(["XFBML"], $.fnbind(function(){
			this.wrapper.each(function(){
				this.innerHTML = fbml;
				FB.XFBML.Host.parseDomElement(this);
			}).hide().append( $("<a href=\"#close\">Stäng</a>").click($.fnbind(this.hide, this)) );
		}, this));
	},
	show: function(){
		this.wrapper.show();
		var top = this.w.scrollTop() + (this.w.height() / 2) - (this.wrapper.height() / 2);
		var left = this.w.scrollLeft() + (this.w.width() / 2)  - (this.wrapper.width() / 2);
		this.wrapper.css({
			"top": top,
			"left": left
		});
		if(!$.support.boxModel){
			if(!this.iframe){ this.iframe = $("iframe", this.wrapper); }
			if(this.iframe.height() < 100){
				this.iframe.height(652);
			}
		}
	},
	hide: function(e){
		e.preventDefault();
		this.wrapper.hide();
	}
};
$(document).ready(function(){
	$(".email-form").each(function(){
		new EmailForm(this);
	});
});