BBX.namespace('folks');
BBX.folks = function() {

	
	
	
	
	
	
	// this o is returned to become BBX.folks
	var o = {
	
		'drawer':function() {

			var openarrow = '▼', closearrow = '▲';
		
			function slammer(e) {

				BBX.log('slam');
				BBX.log(this);
				BBX.log(e.relatedTarget);
				
				var t = $(this);
				
				if(!t.hasChild(e.relatedTarget) && t != e.relatedTarget) {
					drawer.apply(this,[false,true]);
					t.cssSelect('.metaslider').first().setStyle('top','0px');
					t.removeEvent('mouseout',slammer);
				}	
				t.blur();
			}
			
			/*
			This function is specifically for IE.  It removes the focus from a grid item.
			*/
			function ieSlammer(e) {
				var t = $(this);
				if(!t.hasChild(e.relatedTarget) && t != e.relatedTarget) {
					t.blur();
					t.removeEvent('mouseout',ieSlammer);
				}
				
			}
		
		
		
			function drawer(e,fast) {
	
				BBX.log('in drawer');
	
				var t,p, d, dur, h;
			
				if(e === false ) {
					p = $(this);
				} else {
				
					t = $(this);
					p = $(BBX.traverse.getAncestorByClass(t,'item'));
				
				}
				
				
				d = p.cssSelect('.metacabinet').first();
				BBX.log(d);
				
				if(fast) {
					dur = 1;
				} else {
					dur = BBX.configdata.getVal('animation_duration');
				}
				
				if(d) {
					
					d.stop(); // stop any existing animations
					if(d.retrieve('drawerstatus') === 'open') {
						p.cssSelect('.actionsymbol').replaceContent(openarrow);
						d.store('drawerstatus','closed');
						d.animate({'height':'0'},{duration:dur,easing:BBX.easing.easeOutExpo});
						p.removeEvent('mouseout',slammer);
					} else {

						h = d.cssSelect('.metadrawer').first();

						if(h) {

						    d.store('drawerstatus','open');
						    p.cssSelect('.actionsymbol').replaceContent(closearrow);
						    d.animate({'height':{'value':h.offsetHeight,'unit':'px'}},{duration:dur,easing:BBX.easing.easeOutExpo});
						    p.addEvent('mouseout',slammer);
						    p.addEvent('mouseout',ieSlammer);
						}
					}
				}
			}
			
			
			
			
			
		
		
			// this o is returned to become BBX.folks.drawer
			var o = {
		
				init : function(elm) {
//					$("#content.grid").relayEvent('click','a.info',drawer);
					var createOn, d, shareBlock;
					if(elm !== undefined) {
						BBX.log('here 4');
						createOn = $(elm).cssSelect('.controlblock');
						d = $(elm).cssSelect('.metadrawer');
//						BBX.log('d:');
//						BBX.log(d);
					} else {
						createOn = $(".grid #content .controlblock");
						d = $(".grid #content .metadrawer");
					}
//					BBX.log('here 5');
					createOn.create('a',{className:'tool info'},true,BBX.langdata.getData('details') + ' <span class="actionsymbol">' + openarrow + '</span>').addEvent('click',drawer);
//					BBX.log('here 6');

				

				},
				
				dinit: function() {
					$(".grid #content .info").remove();
					$(".grid #content .item").removeEvent('mouseout',slammer);
					
					$(".grid #content .scrollcontrol").remove();
				}
				
				
			
			};

			return o;
		}(),
		
		
		layout:function() {
		
			function swap() {
				
			
				var c = $("body").first();
				if(c.hasClass('grid')) {
					BBX.folks.drawer.dinit();
					c.addClass('list').removeClass('grid');
				} else if(c.hasClass('list')) {
					c.addClass('grid').removeClass('list');
					BBX.folks.drawer.init();
				}
			
			}
			
			// this o is returned to become BBX.folks.layout
			var o = {
			
				init:function() {
					var layout, body;
					
					
					layout = $('#content>.contenttools .layout');
					
					layout.addContent('<a class="togrid listgrid" title="'+BBX.langdata.getData('grid')+'">'+BBX.langdata.getData('grid')+'</a><a class="tolist listgrid" title="'+BBX.langdata.getData('list')+'">'+BBX.langdata.getData('list')+'</a>');
					$("#content>.contenttools .layout a.listgrid").addEvent('click',swap);	
				},
				
				doswap:function() {
					swap();
				},
				
						/*
				findGridRowLength()
				
				Figures out how wide the position grid should be to show the same number of boxes per row
				as are currently displayed in the user's dashboard.
				
				*/
				
				findGridRowLength:function() {

					if($('body').first().hasClass('widescreen')) {
					    return BBX.configdata.getVal('gridrowlength.widescreen');
					} else {
					    return BBX.configdata.getVal('gridrowlength.normal');
					}

					
				},
				
				/*
				findGridSize() 
				
				Finds out how many sites are being displayed per page in the grid.
				
				*/
				findGridSize:function() {
				    if($('body').first().hasClass('widescreen')) {

					return BBX.configdata.getVal('gridsize.widescreen');
				    } else {
					return BBX.configdata.getVal('gridsize.normal');

				    }
				},
				
				
								/**
				findPageNum()
				
				Finds the current page number based on the status of the pagination display
				OR find the page number of the position passed in to pos
				
				*/
				findPageNum:function(pos) {
					if(pos == undefined || pos === null) {
					    if($('body').first().hasClass('mydash')) {
						    var pgs = $('#content .pagination .curpager span').first();
						    if(pgs !== null && pgs !== undefined) {
							return pgs.innerHTML.trim();
						    } else {
							return 1;
						    }
					    } else {
						    return 1;
					    }
					} else {
					    return Math.floor(pos/o.findGridSize()) + 1;


					}
				
				}
			
			
			};

			return o;
		
		}(),
		
		
		
		
		sitemanager: function() {
		
			var o = {
		
				init:function(elm) {
				
					var mine, coll, md;
					
					md = $('.mydash');
					if(md.length > 0) {
						coll = $(".mydash #content li:empty");	
						coll.each(o.setEmpty);
					} 
					
					
					
					
					$$('addTool').addEvent('click',o.initAdd);
					
					if(elm !== undefined) {
						mine = $(elm).cssSelect('.controlblock');
					} else {
						mine = $('#content .xfolkentry[data-bbx-myusid] .controlblock');
								
					}
					
					BBX.log('mine:');
					//BBX.log(mine);
					
					
				
					
					mine.create('a',{className:'tool edittool'},true,BBX.langdata.getData('edit')).addEvent('click',o.initAdd);
					mine.create('a',{className:'tool removetool'},true,BBX.langdata.getData('delete')).addEvent('click',o.remove);
					
					BBX.log('mine done');
			

				},
				
				setEmpty:function(elm,idx,set) {
					$(elm).replaceContent($(elm).create('span',{className:'emptyboxmsg'},false,BBX.langdata.getData('empty site box')).addEvent('click',o.initAdd));
				},
				
				unsetEmpty:function(elm) {
					$(elm).removeEvent('click',o.initAdd);
				},
				
				initAdd:function(e) {
					BBX.dialog.show(e,'addeditsite');
				},
				
				remove:function(e) {
					e.preventDefault();
					
					var t,item,data = '';
					
					t = $(this);
					item = $(BBX.traverse.getAncestorByClass(t,'xfolkentry'));
					
					function handleRemoveResponse(resp) {
						BBX.log('in callback');
						var r = eval(resp);
						BBX.log(r);
						
						if(r.removed == 1) {
							if(this.getAttribute('data-bbx-myusid') == r.usid) {
								o.setEmpty(this.parentNode);
							} else {
								BBX.log(this.getAttribute('data-bbx-myusid'));
							}
						}
					}
					
					if(item.getAttribute('data-bbx-myusid') !== undefined) {
						data += 'usid='+item.getAttribute('data-bbx-myusid');
						data += '&o=json';
						
						item.ajax({'method':'POST','url':'/remove','callback':handleRemoveResponse,'params':data});
					}
					
					
				
				},
				
				
				
				/**
				buildFolksEntry(data) 
				@param object data : An object representing the data required to build the folksonomy entry.
				    The data object may contain the following members:
				    {
					sid int : The BonzoBox Site ID
					myusid int : The current user's UserSite ID for this site.
					mydashpos int : An integer saying what position this site should occupy on the 
							dashboard.
					surl string : The URL of the site.
					sname string : The site title
					thumburl string : The URL of the site's thumbnail image.
					thumbalttext string : Alt text for the thumbnail image.
					sdesc string : The site's description
					desclink object { // we can link to another user's description
					    text string : The actual linked description
					    linkhtml string (html) : An HTML link to link to the description author's BonzoBox.
					}
					stags array [
					    tag object : {
						url string : The tag's URL on BonzoBox
						tag string : The tag's actual text, (ie the actual tag)
					    }
					    ....
					]	
				    }
				    
				Builds a folksonomy entry as a DOM object, and attaches the appropriate event handlers.
				
				return (DOM object) : The completed folksonomy entry.
				*/
				buildFolksEntry:function(data) {
				
					var folk, tag, html = '', doc = $('body').first();
					folk = doc.create('div',{'className':'xfolkentry item'},false);
					
					folk.setAttribute('data-bbx-sid',data.sid);
					if(data.myusid !== undefined) {
					    folk.setAttribute('data-bbx-myusid',data.myusid);
					}

					if(data.mydashpos !== undefined) {
					    folk.setAttribute('data-bbx-mydashpos', data.mydashpos);
					}
					
					
					if(data.thumburl != undefined) {
					    html += '<a class="taggedlink" href="/out/?u=' + data.surl + '" title="' + decodeURIComponent(data.sname) + '" draggable="false">';
					    html += '<img src="' + decodeURIComponent(data.thumburl) + '" width="253" height="197" alt="'+decodeURIComponent(data.thumbalttext) + '" draggable="false" class="thumb" />';
					    html += '</a>';
					}

					if(data.isprivate == 1) {	// this is a == comparison on purpose.
						html += '<span class="privateflag">' + BBX.langdata.getData('private') + '</span>';
					}

					html += '<h5 class="title"><a href="/out/?u=' + data.surl + '" title="' + decodeURIComponent(data.sname) + '" class="value">'+ decodeURIComponent(data.sname) + '</a></h5>';

					html += '<div class="controlblock"><a class="tool visit" href="/out/?u=' + data.surl + '">' + BBX.langdata.getData('visit') + '</a></div>';

					html += '<div class="shareblock">' + BBX.langdata.getData('share') + '</div>';
					html += '<div class="metacabinet"><div class="metadrawer"><div class="metaslider">';
					
					
					
					if(data.sdesc !== undefined && data.sdesc.length > 0) {
						html += '<p class="description">' + decodeURIComponent(data.sdesc) + '</p>';
					}
					
					BBX.log('mark 8');
					
					if(data.desclink !== undefined) {
						html += '<p class="guest description"><span class="value">' + decodeURIComponent(data.desclink.text) + '</span><br />';
						html += decodeURIComponent(data.desclink.linkhtml);
						html += '</p>';
					}
					
					BBX.log('mark 12');
					BBX.log(data);
					if(data.stags.length > 0) {
						BBX.log('mark 13');
						html += '<h6>' + BBX.langdata.getData('tagged') + '</h6>';
						html += '<ul class="tags">';
						
						for(var i=0;i<data.stags.length;i++) {
							tag = data.stags[i];
							html += '<li><a rel="tag" href="' + decodeURIComponent(tag.url) + '">'+decodeURIComponent(tag.tag) + '</a></li>';
						}
						
						html += '</ul>';	
					}
					
					BBX.log('mark 16');
					
					html += '</div></div></div></div>';
					
					BBX.log('mark 17');
					folk.addContent(html);
					BBX.log('mark 18');
					
					return folk;
				} 
				
				
				
				
				
				
				
				
				
				
			};
			
			return o;
		
		}(),




		share: function() {

		    // will be returned to become BBX.folks.share
		    var o = {


			shareFacebook:function(e, elm) {
			    if(FB) {


				var box, forapi, name, regexS, regex, results, fullurl, domain, domainend, siteurl;


				if(elm !== undefined && $(elm).hasClass('xfolkentry')) {
				    box = $(elm);
				} else {
				    box = $(BBX.traverse.getAncestorByClass(this,'xfolkentry'));
				}



				forapi = {
				    'sid' : box.getAttribute('data-bbx-sid'),
				    'picture' : box.cssSelect('.thumb').first().src,
				    'link' : 'http://' + BBX.configdata.getVal('domain') + BBX.utils.getHref(box.cssSelect('.taggedlink').first()),
				    'name' : box.cssSelect('h5 .value').first().innerHTML
				};


				if(box.cssSelect('.description').length > 0) {
				    forapi.description = box.cssSelect('.description').first().firstChild.nodeValue;
				}


				name = 'u'.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
				regexS = "[\\?&]"+name+"=([^&#]*)";
				regex = new RegExp( regexS );
				results = regex.exec( forapi.link );
				if(results !== null) {
				    fullurl = decodeURIComponent(results[1]);
				    
				    forapi.siteurl = fullurl;

				    domainend = fullurl.indexOf('/',10);
				    if(domainend > -1) {
					domain = fullurl.substring(0, fullurl.indexOf('/', 10));
				    } else {
					domain = fullurl;
				    }

				    domain = domain.replace('http://','');
				    domain = domain.replace('https://','');

				    forapi.caption = domain;
				}




	/*
				data.method = 'stream.publish';
				data.user_message_prompt = 'Share ' + data.name + ' on Facebook';
				data.display = 'popup';

				data.title = data.name;
	*/

				BBX.dialog.show(e,'fbshare', forapi);


				




			    }



			},


			shareEmail:function(e, elm) {
			    var box, data = {};

			    if(elm !== undefined && $(elm).hasClass('xfolkentry')) {
				box = $(elm);
			    } else {
				box = $(BBX.traverse.getAncestorByClass(this,'xfolkentry'));
			    }

			 //   BBX.log(box.cssSelect('.title .value'));

			    data.sid = box.getAttribute('data-bbx-sid');
			    data.sname = box.cssSelect('.title .value').first().innerHTML;
			    data.domobj = this;
			    data.box = box;

			    BBX.dialog.show(e,'emailshare', data);

			    e.preventDefault();



			},


			init:function(elm) {
			    var shareblock;
			    BBX.log('in share init');

			    if(elm !== undefined) {
				    shareblock = $(elm).cssSelect('.shareblock');
			    } else {
				    shareblock = $('#content .xfolkentry .shareblock');
			    }

				
			    shareblock.create('a', {className:'sharelink share-facebook'}, true, BBX.langdata.getData('post to facebook')).addEvent('click', o.shareFacebook);

			    if(BBX.user.isLoggedIn()) {
				shareblock.create('a', {className:'sharelink share-email'}, true, BBX.langdata.getData('email')).addEvent('click', o.shareEmail);
			    }


			    
			}


		    };






		    return o;
		}(),

		init: function() {
		    o.drawer.init();
		    o.layout.init();
		    o.sitemanager.init();
		    o.share.init();




		}
		
		


	



	};
	
	
	
	
	
	

	
	
	
	
		


	return o;

}();

DOMAssistant.DOMReady(BBX.folks.init);

