(function(){
	//<script type="text/javascript">
	//<!--script type="text/javascript" src="http://www.thehouseofbusiness.com/wd/wd_shrubbery.js"></script-->
	
	/*
	 * NOTE: paste this code in the page box (without the quotes): '<div id="wd_pagebody">&nbsp;</div>'.
	 * Also be aware that this script runs in 'ning' context, while many wd pages are loaded inside an iframe,
	 * effectively creating a new and 'blank' context (which also has a different URL so no xss).
	 */
	
	var root_url = 'http://www.thehouseofbusiness.com/wd';
	var ningroot_url = 'http://network.thehouseofbusiness.com';
	var adminEmail = 'info@thehouseofbusiness.com';
	//var ningroot_url = 'http://network.thehob.biz';
	//var adminEmail = 'info@thehob.biz';
	
	var entryURLBase = root_url + '/wd_view.php';
	var formURLBase = root_url + '/wd_form.php';
	var adminURLBase = root_url + '/wd_admin.php';
	var ajaxURLBase = root_url + '/wd_ajax.php';
	
	var embeddedViewBase = 'http://hobhub.biz/page/business-directory';
	
	var viewRE = new RegExp( /^http:\/\/hobhub.biz\/page\/business-directory/ );
	var formRE = new RegExp( /^http:\/\/hobhub.biz\/page\/create-business-page/ );
	var adminRE = new RegExp( /^http:\/\/hobhub.biz\/page\/db-admin/ );
	var skypeRE = new RegExp( /^http:\/\/hobhub.biz\/page\/skype-directory/ );
	var profileRE = new RegExp( /^http:\/\/hobhub.biz\/profiles?\// );
	
	/* Load the given file as javascript by adding a script tag to the head in the DOM.
	 * Note that something like $('head').append('<script ...></script>') works as well, but seems not
	 * debuggable (breakpoints are forgotten on page reload).
	 */
	function loadJsFile( filename ) {
		var loaderNode = document.createElement( 'script' );
		loaderNode.setAttribute( 'type', 'text/javascript' );
		loaderNode.setAttribute( 'src' , filename );
		document.getElementsByTagName( 'head' )[0].appendChild( loaderNode );
	}
	
	//NOTE: Robustness of this approach is questionable.
	function getProfileId() {
		var profileId = '';
		
		//approach one
		var addFriendElem = document.getElementById( 'add-as-friend-link' );
		if ( addFriendElem != null ) profileId = addFriendElem.getAttribute( '_screenName' );
		
		//approach two
		if ( profileId == '' ) {
			var links = x$('a[href^="http://hobhub.biz/"]').filter(function() {
				return this.href.match(/user=.+$/);
			});
			if ( links.length > 0 ) {
				linkHref = links.eq(0).attr('href');
				profileId = linkHref.substr( linkHref.indexOf( 'user=' ) + 5 );
			}
		}
		
		//approach three
		if ( profileId == '' ) {
			profileId = x$('div.module_user_thumbnail img').attr('_screenname');
		}
		
		//approach four
		if ( profileId == '' ) {
			//profileId = xn.track._globals.screen_name; //don't use this, it is the viewer id
		}
		
		return profileId;
	}
	
	function getViewerId() {
		var viewerId = '';
		if ( typeof ning != 'undefined' && ning != null
				&& typeof ning.CurrentProfile != 'undefined' && ning.CurrentProfile != null
				&& typeof ning.CurrentProfile.id != 'undefined' && ning.CurrentProfile.id != null ) {
			viewerId = ning.CurrentProfile.id;
		}
		return viewerId;
	}
	
	function fetchContactBarHtml( hookElem, user_id, viewer_id ) {
		if ( viewer_id != null && viewer_id != '' ) {
			var ajaxURLBase = 'http://www.thehouseofbusiness.com/wd/wd_ajax.php';
		
			x$.getJSON( ajaxURLBase + '?jsoncallback=?',
				{ op: 'get_contactbar', userid: user_id, viewerid: viewer_id },
				function( jsondata ) {
					var status = jsondata.status;
					var errorText = ( typeof jsondata.errorText != 'undefined' ) ? jsondata.errorText : '';
					
					//wrapperDiv.style.display = 'none';
					if ( status == 'success' ) {
						var barData = jsondata.barData;
						x$(hookElem).html( barData );
					} else if ( status == 'error' ) {
						var msg = 'Contactbar problem: JSONP request returned an error';
						if ( errorText != '' ) msg += ": '" + errorText + "'";
						console.log( msg );
						x$(hookElem).html( '<span style="font-style: italic;">Sorry, no contact bar information available.</span>' ).fadeOut( 3500 );
					} else {
						//console.error( 'Contact error: JSONP request did not return a valid result.' );
						x$(hookElem).html( '<span style="font-style: italic;">Sorry, no contact bar information could be retrieved.</span>' ).fadeOut( 3500 );
					}
					wrapperDiv.style.display = 'block';
				}
			);
		} else {
			x$(hookElem).html( '<span style="font-style: italic;">Login to see all of this persons\' contact options including: business details, email, phone and messenger acounts.</span>' );
		}
	}
	
	
	function injectAjaxDivWithMessage( msg )
	{
		if ( typeof msg == 'undefined' || msg == null ) msg = 'Please wait a moment while content is being loaded...';
		var injectHook = '<div id="wd_ajaxTarget"><span style="margin-left: 2em; font-style: italic;">' + msg + '</span></div>';
		x$( '#wd_pagebody' ).parent().css( 'border', '0px' ); //this element (div w. class:description) suddenly got a border...
		x$( '#wd_pagebody' ).parent().html( injectHook );
		return x$('#wd_ajaxTarget');
	}
	
	function gup( name )
	{
	  name = name.replace( /[\[]/, "\\\[" ).replace( /[\]]/ , "\\\]" );
	  var regexS = "[\\?&]" + name + "=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
	    return "";
	  else
	    return results[1];
	}
	
	function getIframeElement( url, minHeight, maxHeight, scrolling )
	{
		styleTag = '';
		if ( minHeight > 0 && maxHeight > 0 ) {
			styleTag = ' style="min-height: ' + minHeight + 'px; max-height: ' + maxHeight + 'px;"';
		} else if ( minHeight == 0 && maxHeight > 0 ) {
			styleTag = ' style="max-height: ' + maxHeight + 'px;"';
		} else if ( minHeight > 0 && maxHeight == 0 ) {
			styleTag = ' style="min-height: ' + minHeight + 'px;"';
		}
		
		scrollingType = scrolling ? "vertical" : "no";
		
		return '<iframe id="wdFrame" name="wdFrame"' + styleTag + ' src ="' + url + '" width="100%" frameborder="0" scrolling="' + scrollingType + '"><p>Your browser does not support iframes.</p></iframe>';
	}
	
	
	
	x$(document).ready(function() {
		//Note: be careful what code is executed here.
		var docHead = x$('head');
		docHead.append('<link rel="stylesheet" type="text/css" href="http://www.thehouseofbusiness.com/wd/css/wd_safe_styles.css" />');
		loadJsFile( 'http://www.thehouseofbusiness.com/wd/script/wd_jq.js' );
		loadJsFile( 'http://www.thehouseofbusiness.com/wd/script/popupscript.js' );
	});
	
	
	
	var ningArgs = '';
	if ( typeof ning != "undefined" ) {
		var args = new Array( );
		if ( typeof ning["CurrentApp"] != "undefined" && ning["CurrentApp"] != null ) {
			if ( typeof ning["CurrentApp"]["id"] != "undefined" ) args.push( "net_id=" + ning["CurrentApp"]["id"] );
			if ( typeof ning["CurrentApp"]["url"] != "undefined" ) args.push( "net_url=" + ning["CurrentApp"]["url"] );
			if ( typeof ning["CurrentApp"]["owner"] != "undefined" ) args.push( "net_owner=" + ning["CurrentApp"]["owner"] );
		}
		if ( typeof ning["CurrentProfile"] != "undefined" && ning["CurrentProfile"] != null ) {
			if ( typeof ning["CurrentProfile"]["id"] != "undefined" ) args.push( "user_id=" + ning["CurrentProfile"]["id"] );
			if ( typeof ning["CurrentProfile"]["profileUrl"] != "undefined" ) args.push( "profile_url=" + ning["CurrentProfile"]["profileUrl"] );
		}
		
		var ningArgs = args.join( '&' );
	}
	
	if ( formRE.test( window.location ) ) {
		replElem = injectAjaxDivWithMessage();
		var edit_id = gup( 'edit_id' );
		if ( edit_id != '' ) {
			if ( ningArgs != '' ) ningArgs += '&edit_id=' + edit_id;
			else { var ningArgs = 'edit_id=' + edit_id; }
		}
		var formURL = formURLBase + ( ( ningArgs != '' ) ? '?' + ningArgs : '' );
		var replaceText = getIframeElement( formURL, 2300, 0, true );
		replElem.html( replaceText );
		
		
	} else if ( adminRE.test( window.location ) ) {
		replElem = injectAjaxDivWithMessage();
		var adminURL = adminURLBase + ( ( ningArgs != '' ) ? '?' + ningArgs : '' );
		var replaceText = getIframeElement( adminURL, 1300, 0, true );
		replElem.html( replaceText );
		
		
	} else if ( viewRE.test( window.location ) ) {
		replElem = injectAjaxDivWithMessage();
		var op = gup( 'op' );
		var offset = gup( 'offset' );
		var user_id = gup( 'id' );
		var qm = gup( 'qm' );
		var qc = gup( 'qc' );
		var no_mlm = gup( 'no_mlm' );
		
		var vArgList = new Array();
		if ( op != '' ) vArgList.push( "op=" + op );
		if ( user_id != '' ) vArgList.push( "id=" + user_id );
		if ( offset != '' ) vArgList.push( "offset=" + offset );
		if ( qm != '' ) vArgList.push( "qm=" + qm );
		if ( qc != '' ) vArgList.push( "qc=" + qc );
		if ( no_mlm != '' ) vArgList.push( "no_mlm=" + no_mlm );
		if ( ningArgs != '' ) vArgList.push( ningArgs );
		
		var vArgs = vArgList.join( '&' );
		var entryURL = entryURLBase + ( ( vArgs != '' ) ? ( '?' + vArgs ) : '' );
	
		var replaceText = getIframeElement( entryURL, 1500, 0, true );
		replElem.html( replaceText );
		
		
	/*
	 * If a valid profileId can be found, attempt to find the main content column node ('parentNode')
	 * and the node inside of it just below the page title and assign it to 'beforeNode'.
	 * Then inject a new div with a loading message above beforeNode and finally try to load the actual
	 * contact bar which replaces the message.
	 */
	} else if ( profileRE.test( window.location ) ) {
			var profileId = getProfileId(); var viewerId = getViewerId();
			
//	console.log('profile detected (u=' + profileId + ', v=' + viewerId + ')');
		if ( typeof profileId != "undefined" && profileId != null ) {
			var childIsH1 = ( x$('#xg_layout_column_2 > h1').length > 0 ) ? true : false;
	//console.log( childIsH1 );
			
			var beforeNode = '';
			//var jqBeforeNode = '';
			var parentNode = document.getElementById( 'xg_layout_column_2' );
			if ( parentNode != null ) {
				if ( childIsH1 ) {
					beforeNode = parentNode.getElementsByTagName( 'h1' )[0].nextSibling;
					//jqBeforeNode = x$('document#xg_layout_column_2 > h1').next();
				} else {
					beforeNode = parentNode.getElementsByTagName( 'div' )[0].nextSibling;
					//jqBeforeNode = x$('document#xg_layout_column_2 > div').next();
				}
			}
	//else console.log('no parentNode');
	//if ( beforeNode == "undefined" ) console.log( 'no beforeNode' );
			
			var wrapperDiv = document.createElement( 'div' );
			wrapperDiv.setAttribute( 'id', 'wd_contactbar' );
			wrapperDiv.innerHTML = '<span style="font-style: italic;">Contact bar is being loaded...</span>';
			
			if ( typeof beforeNode != 'undefined' && beforeNode != null ) {
				parentNode.insertBefore( wrapperDiv, beforeNode );
				//jqWrapperDiv.insertBefore( jqBeforeNode );
	//console.log( 'Contact bar element has been attached.' );
			} else {
	//console.error( 'Contact bar error: could not find element to attach contact bar to.' );
			}
			fetchContactBarHtml( wrapperDiv, profileId, viewerId );
	//console.log('profile code finished');
		}
		
		
	} else if ( skypeRE.test( window.location ) ) {
		replElem = injectAjaxDivWithMessage();
		var skypeURL = ajaxURLBase + '?op=get_skypepage';
		var replaceText = getIframeElement( skypeURL, 1300, 0, true );
		replElem.html( replaceText );
	}
	//</script>
	
	
	
	//NOTE: this code should be run after the contactbar has been inserted, otherwise it can't place the ad_html.
	//Code extracted from page (which cannot find getProfileId() anymore now that the script is wrapped.)
	var profileId = getProfileId(); var viewerId = getViewerId();
//console.log('[TMPC] profile detected (u=' + profileId + ', v=' + viewerId + ')');
	if ( profileId == viewerId ) {
		x$("#wd_contactbar").after("<div id='socialmedia'></div>");
		var ad_html = '<iframe src="http://www.thehob.biz/hobtopsoc.php" width="780" height="250" scrolling="no" frameborder="0" overflow="hidden"></iframe>';
		x$("#socialmedia").html(ad_html);
	}
})();

