 (function () {

 NC.widget.PeopleManager = function() {
	/* private variables and methods */
	var starimage = new Array( '',
		'<img src="../imagesv2/badges/one_star_2.png">',
		'<img src="../imagesv2/badges/two_stars_2.png">',
		'<img src="../imagesv2/badges/three_stars_2.png">',
		'<img src="../imagesv2/badges/four_stars_2.png">',
		'<img src="../imagesv2/badges/five_stars_2.png">');
	var connectImages = new Array(
		'connectedness_3_0.png',
		'connectedness_3_1.png',
		'connectedness_3_2.png',
		'connectedness_3_3.png',
		'connectedness_3_4.png',
		'connectedness_3_5.png'
	);
	var connectResults = null;
	var searchTitle = "";
	var resultsDiv = 'centercontent';
	var progressDiv = 'SearchProgress';
	var containerDivName = 'MainFrame';
	var rewritePage = false;
	var refreshPage = false;
	var searchTemplate = 
	'							<div id="ContentContainer"> ' + 
	'								<div id="LeftColumnWide" class="leftcolumnwide">'+
	'									<div class="contentbody" id="centercontent">'+
	'									</div>  '+
	'									<div id="MessageDiv">'+
	'										<div id="ProfileScoreDiv">' +
	'										</div>' +	
	'									</div>'+
	'								</div>'+
	'									<div class="rightcolumnwide"> '+
	'									<div id="StreamDiv"> '+
	'									</div> '+
	'								</div> '
	'							</div>';
 	
 	 	return {
 	 		/* public methods */

			showProgress: function() {
				var elMessageDiv = document.getElementById(progressDiv);
				elMessageDiv.innerHTML = '<img src="../imagesv2/circle-ball-dark-antialiased.gif" border="0">';
			},
	
			hideProgress: function() {
				var elMessageDiv = document.getElementById(progressDiv);
				elMessageDiv.innerHTML = '';
			},

			getResultsDiv: function() {
				return resultsDiv;
			},
			
			getRefreshPage: function() {
				return refreshPage;
			},
			
			showResults: function( results, peopleSearchUrl) {
				if (rewritePage) {
					var containerDiv = document.getElementById( containerDivName);
					if (containerDiv != null) {
						containerDiv.innerHTML = searchTemplate;
						NC.util.Event.onContentReady( containerDivName, function() {
							NC.widget.PeopleManager._showResults(results, peopleSearchUrl);
						});
					}
				}
				else {
					NC.widget.PeopleManager._showResults(results, peopleSearchUrl);
				}
			},

			StrFbUid			: "fbUid",
			StrFbName			: "fbName",
			StrEducationName	: "fbEducationName",
			StrWorkName			: "fbWorkName",
			StrFbProfileUrl		: "fbProfile",
			StrPictureUrl		: "fbPictureUrl",

			StrFbValues			: "values",
			NetworkFacebook		: 1,
			NetworkLinkedIn		: 2,
			NetworkTwitterq		: 4,
			
			getConnectImages: function() {
				return connectImages;
			},
			
			getConnectResults: function() {
				return connectResults;
			},
			
			formatConnectionData: function( d, addFBLinks, shareUrl) {
				var iNetwork = parseInt( d.networktype);
				var content = '';
				content += '<div class="person">';
					content += '<div class="picture">';
						var pictureUrl = "";
						var profileUrl = "";
						if (iNetwork & this.NetworkFacebook) {
							pictureUrl = 'http://graph.facebook.com/' + d.fbUid + '/picture';
							d.fbPictureUrl = pictureUrl;
							profileUrl = d.fbProfile;
						}
						else if (iNetwork & this.NetworkLinkedIn) {
							pictureUrl = d.lnPictureUrl;
							if (pictureUrl == null || pictureUrl.length == 0) {
								pictureUrl = '../imagesv2/nullpic.gif';
							}
							profileUrl = d.lnProfile;
						}
						content += '<img border="0" height="50" src="' + pictureUrl + '">';
					content += '</div>';
					content += '<div class="info">';
						content += '<div class="name">';
							if (profileUrl.length > 2) {
								content += '<a target="_blank" href="' + profileUrl + '">' + d.fbName + '</a>';
							}
							else {
								content += d.fbName;
							}
						if (iNetwork & this.NetworkFacebook) {
							content += '&nbsp;<a target="_blank" href="' + d.fbProfile + '">' + '<img border="0" width="12" src="../imagesv2/ext/f_logo_16.png">' + '</a>'
						}
						if (iNetwork & this.NetworkLinkedIn) {
							content += '&nbsp;<a target="_blank" href="' + d.lnProfile + '">' + '<img border="0" width="12" src="../imagesv2/ext/LinkedIn_Logo16px.png">' + '</a>'
						}
						content += '</div>';
						content += '<div class="detail">';
							if (!(typeof d.fbWorkName == 'undefined')) {
								content += "<b>Match:</b> " + d.fbWorkName;
							}
							if (!(typeof d.fbEducationName == 'undefined')) {
								content += "<b>Match:</b> " + d.fbEducationName;
							}
						content += '</div>'; // end detail div
						var profileDivId = 'p' + d.fbUid;
						content += '<div id="' + profileDivId + '" class="profile"></div>';
					content += '</div>';  // end info div
					content += '<div style="clear:both"></div>';
					if (typeof addFBLinks != 'undefined' && addFBLinks == true) {
							var iSp = d.fbName.indexOf( ' ');
							var firstname = d.fbName;
							if (iSp != -1) {
								firstname = firstname.substr( 0, iSp);
							}
						content += '<div id="actions" class="action">';
						if (iNetwork & this.NetworkFacebook) {
							if (d.nodetype == 'root') {
							// nothing right now
							}
							else 
								if (d.nodetype == 'friend') {
									content += '<a href="#" onclick="NC.util.Facebook.showShareMapDialog(\'' + d.fbUid + '\', \'' + shareUrl + '\')">Share this map with ' + firstname + '</a> ';
									if (d.subscriber == '0') {
										content += '<br><a href="#" onclick="NC.util.Facebook.showInviteThrongDialog(\'' + d.fbUid + '\', \'' + shareUrl + '\')">Invite to Throng</a> ';
									}
								}
								else 
									if (d.nodetype == 'fof') {
										content += '<a href="#" onclick="NC.util.Facebook.showAddFriendDialog(\'' + d.fbUid + '\')">Friend ' + firstname + '</a>';
									}
							content += '<span id="ProfileEmail"></span>' + '<br>' +
							'<span style="font-weight:normal;font-size:10px;">Click ' +
							firstname +
							' to message via Facebook.</span>';
						}
						
						content += '</div';
					}
				content += "</div>";
				var rval = {};
				rval.content = content;
				rval.profileDivId = profileDivId;
				return rval;
			},
			
			showAllConnections: function( event, resumeId) {
				var data = NC.widget.PeopleManager.getConnectResults()[resumeId];
				if (data.length > 0) {
					var target = NC.util.Event.getTarget(event);
					var region = NC.util.Region.getRegion(target);
					var panel = new NC.widget.Popup('NCSocialGraphDisplay');
					panel.show(region.left, region.bottom + 10, 300, -1 /*100 * data.length*/, function(element){
						var content = '';
						for (var c = 0; c < data.length; c++) {
							if (c > 0) {
								content += '<hr>';
							}
							var rval = NC.widget.PeopleManager.formatConnectionData(data[c]);
							content += rval.content;
						}
						element.innerHTML = content;
					});
				}
				else {
					// show a promo
				}
				
			},
			
			showConnection: function( event, resumeId, i) {
				var data = NC.widget.PeopleManager.getConnectResults()[resumeId];
				var target = NC.util.Event.getTarget( event);
				var region = NC.util.Region.getRegion(target);
				var panel = new NC.widget.Popup('NCSocialGraphDisplay');
				panel.show(region.left, region.bottom + 5, 300, -1, function( element) {
					var rval = NC.widget.PeopleManager.formatConnectionData( data[i]);
					element.innerHTML =  rval.content;
					NC.util.Event.onContentReady( rval.profileDivId, function() {
						var callback =
						{
			  				success:function( o) {
								var json = NC.lang.JSON.parse(o.responseText);
								var el = document.getElementById( rval.profileDivId);
								el.innerHTML = json.profile;
								if (json.refCode.length > 0) {
									var profileEl = document.getElementById( "ProfileEmail");
									// add this back when we are sure we have the  email
//									profileEl.innerHTML = '<a href="#" onclick=""> Email ' + firstname + '</a>';
								}
			  				},
			  				failure:function( o) {
			  				},
							scope: this    				
						};
						var url = './getFbProfileData.php?fbuid=' + data[i].fbUid;
						var connection = new NC.util.AjaxConnection( 'GET', url, null);
						connection.executeMethod( callback);
					});
				});
			},

 			_showResults: function( results, peopleSearchUrl) {
				connectResults = [];
				if (results != null && results.length > 0) {
					var oDiv = document.getElementById(resultsDiv);
					var content = '<div class="peoplelistcontainer">';
					
					var inviteForm = 'inviteForm.php';
					var inviteFormName = 'JsInviteForm';
					var inviteFormHandler = 'do_invite.php';
					var inviteLabel = "Invite";
					var baseInviteAction = 'javascript:NC.widget.CandidateManager.showInvitePopup(  \'' +
					inviteForm +
					'\', \'' +
					inviteFormName +
					'\', \'' +
					inviteFormHandler +
					'\',' +
					'\'' +
					'' +
					'\', null,';//
					var updates = new Array();
					var socialGraphUpdates = new Array();
					for (var i = 0; i < results.length; i++) {
						content += '<div>';
						/*
		 content += 'Confidential ';
		 content += results[i].categoryname + '&nbsp;';
		 content += results[i].ncscore + '&nbsp;';
		 content += results[i].mgrcategory + '&nbsp;';
		 content += results[i].mgrstars+ '&nbsp;';
		 content += results[i].location;
		 */
						var badge = results[i].badge;
						if (typeof(badge) != "undefined" && badge.length > 0) {
							badge = decode64(badge);
						}
						var candidateName = results[i].name;
						var names = candidateName.split(" ");
						var firstName = '';
						var lastName = '';
						switch (names.length) {
							case 1:
								candidateName = names[0];
								lastName = candidateName;
								break;
								
							case 2:
								candidateName = names[0] + ' ' + names[1];
								firstName = names[0];
								lastName = names[1];
								break;
								
							case 3:
							default:
								candidateName = names[0] + ' ' + names[2];
								firstName = names[0];
								lastName = names[2];
						}
						content += '<div class="detailed">';
						content += '<div class="badgeheader">';
						content += results[i].ncscore;
						content += '</div>';
						content += '<div class="nameheader">' + candidateName + '</div>';
						content += '<div class="detailheaderlefttall">';
						content += ', ' + results[i].categoryname + "&nbsp;&nbsp;";
						if (results[i].mgrcategory == 2) {
							content +=  starimage[results[i].mgrstars];
						}
						content += '</div>';
						
						// add action icons
						if (NC.LoggedIn == 1) {
							var actionDivId = "action" + results[i].resumeid;
							content += '<div class="detailheaderright" id="' + actionDivId + '">';
							var Content_PeopleSearchResult = 17; // from class.content.php
							var Conversation_StrNotes = 'Notes'; // from class.conversation.php
							var conversationIcon = '../imagesv2/notepencil_14px.png';
							/*
			 if (NC.widget.StateManager.isPaidSearchSubscriber()) {
			 */
							if (true) {
								content += '&nbsp;<a href="#" onclick="NC.widget.ConversationManager.showConversationPopup( event, ' + Content_PeopleSearchResult + ',' + results[i].resumeid + ', \'' + Conversation_StrNotes + '\')">' + '<img border="0" alt="View and add notes" src="' + conversationIcon + '">' + '</a>';
								var argList = results[i].resumeid;
								argList += ', ' + Content_PeopleSearchResult;
								argList += ', \'' + candidateName + '\'';
								argList += ', true'
								content += '&nbsp;<a href="#" onclick="NC.widget.TagManager.showTagPopup(event,' + argList + ')">' + '<img border="0" alt="View and edit tags" src="../imagesv2/hashtag_14px.png">' + '</a>';
							}
							else {
								content += '&nbsp;<a href="#" onclick="NC.widget.QueryManager.showPromoPopup(\'' + actionDivId + '\', \'search_subscribePromo.php\');">' + '<img border="0" alt="View and add notes" src="' + conversationIcon + '">' + '</a>';
								content += '&nbsp;<a href="#" onclick="NC.widget.QueryManager.showPromoPopup(\'' + actionDivId + '\', \'search_subscribePromo.php\');">' + '<img border="0" alt="View and edit tags" src="../imagesv2/hashtag_14px.png">' + '</a>';
							}
							content += '</div>';
							if (results[i].email != undefined && results[i].email.length > 0) {
								content += '<div class="detailheaderright">';
								content += '&nbsp;<a href="#" onclick="NC.widget.QueryManager.showEmailContactPopup(event, ' + results[i].resumeid + ',\'' + candidateName + '\')">' + '<img border="0" alt="Email contact" src="../imagesv2/secure_email_14px.png">' + '</a>';
								content += '</div>';
							}
						}
						
						
						
						content += '<div style="clear:both"></div>';
						content += '<div class="detailheaderfarleft">';
						content += results[i].location + ', since ' + results[i].date;
						content += '</div>';
						content += '<div style="clear:both"></div>';
						var d = 'Profile' + results[i].resumeid;
						var r = {};
						r.divname = d;
						r.resumeid = results[i].resumeid;
						updates[updates.length] = r;
						content += '<div class="profile" id="' + d + '"></div>';
						//					var inviteFaceBookAction = baseInviteAction  +  '3, ' + results[i].resumeid + ')"'; 
						var inviteTwitterAction = 'http://twitter.com/search/users?q=' + encodeURI(candidateName) + '&category=people&source=find_on_twitter';
						var inviteFaceBookActionName = 'http://www.facebook.com/search/?ref=ffs&q=' + encodeURI(candidateName) + '&o=2048&init=ffs';
						//					var inviteFaceBookActionEmail = 'http://www.facebook.com/search/?ref=ffs&q=' + encodeURI(candidateName) + '&o=2048&init=ffs';
						//					var inviteLinkedInAction = baseInviteAction  +  '4, ' + results[i].resumeid + ')"'; 
						var inviteLinkedInAction = 'http://www.linkedin.com/search/fpsearch?fname=' + encodeURI(firstName) + '&lname=' + encodeURI(lastName) +
						'&searchLocationType=Y&page_num=1&search=&pplSearchOrigin=MDYS&viewCriteria=1&sortCriteria=R&redir=redir';
						var findGoogleAction = 'http://www.google.com/search?hl=en&site=&q=' + encodeURI(candidateName + ' ' + results[i].location) + '&btnG=Search';
						content += '<div class="action">';
						content += 'Connect: <a target="_blank" href="' + inviteFaceBookActionName + '">Facebook</a> ';
						content += '<a  target="_blank" href="' + inviteLinkedInAction + '">LinkedIn</a> ';
						content += '| Follow: <a target="_blank" href="' + inviteTwitterAction + '">Twitter</a> ';
						content += '| Search:<a  target="_blank" href="' + findGoogleAction + '">Google</a> ';
						content += '</div>';
						// add social action div
						var sd = 'Social' + results[i].resumeid;
						var sr = {};
						sr.divname = sd;
						sr.resumeid = results[i].resumeid;
						socialGraphUpdates[socialGraphUpdates.length] = sr;
						content += '<div class="socialgraphaction" id=' + sd + '>';
						content += '</div>'
						content += '<div style="clear:both"></div>';
						content += '</div>';
						content += '</div>';
					}
					content += '</div>';
					/*
	 if (searchTitle == null) {
	 searchTitle = 'Connect with these professionals';
	 }
	 */
					explanation = '<p>Click on the LinkedIn, Facebook, Twitter or Google link in the blue bar to find and connect with these people.</p>';
					//					content =  '<h2>' + searchTitle + '</h2>' /* + explanation */ + content;
					searchTitle = ""; // reset - single use only
					oDiv.innerHTML = content;
					searchTitle = null;
					NC.util.Event.onContentReady(resultsDiv, function(){
						for (var u = 0; u < updates.length; u++) {
							var div = document.getElementById(updates[u].divname);
							var url = './getprofile.php?rid=' + updates[u].resumeid;
							var updater = new NC.util.AjaxUpdate('GET', url, updates[u].divname, updates[u].divname, null);
							updater.doUpdate(true);
						}
						/*	start social matching code		
						for (var u = 0; u < Math.min(socialGraphUpdates.length, 7); u++) {
							var url = './matchSocialGraph.php?rid=' + socialGraphUpdates[u].resumeid + '&div=' + socialGraphUpdates[u].divname;
							var callback = {
								success: function(o){
									var r = NC.lang.JSON.parse(o.responseText);
									if (r.data.length > 0) {
										var connectStrength = Math.min(5, r.data.length);
										var content = '';
										content += '<a href="#" onclick="NC.widget.NetworkManager.showNetworkBrowser(\'NCNetworkWrapper\', true, null, \'';
										for (var i = 0; i < r.data.length; i++) {
											if (i > 0) {
												content += ',';
											}
											content += r.data[i].fbUid;
										}
										var title = "Value Graph";
										content += '\',\'' + title + '\')">';
										//									content += '<a href="#" onmouseover="NC.widget.PeopleManager.showAllConnections(event, ' + r.resumeId + ')">';
										//									content += '<img src="../imagesv2/' + NC.widget.PeopleManager.getConnectImages()[connectStrength] + '" border ="0"></a>&nbsp;';
										content += '<img src="../imagesv2/throng_20x20.png" border ="0"></a>&nbsp;';
										NC.widget.PeopleManager.getConnectResults()[r.resumeId] = r.data;
										var maxpics = 8;
										for (var i = 0; i < Math.min(r.data.length, maxpics); i++) {
											content += '<a href="#" onmouseover="NC.widget.PeopleManager.showConnection(event, ' + r.resumeId + ',' + i + ')">';
											var iNetwork = parseInt( r.data[i].networktype);
											var pictureUrl = "";
											if (iNetwork & NC.widget.PeopleManager.NetworkFacebook) {
												pictureUrl = 'http://graph.facebook.com/' + r.data[i].fbUid + '/picture';
											}
											else if (iNetwork & NC.widget.PeopleManager.NetworkLinkedIn) {
												pictureUrl = r.data[i].lnPictureUrl;
											}
											if (pictureUrl == null || pictureUrl.length == 0) {
												pictureUrl = '../imagesv2/nullpic.gif';
											}
											content += '<img border="0" height="20" src="' + pictureUrl + '">';
										}
										if (r.data.length > maxpics) {
											content += '<img src="../imagesv2/more_connections.png" border ="0"></a>&nbsp;';
										}
										var div = document.getElementById(r.divname);
										div.innerHTML = content;
									}
								},
								failure: function(o){
								},
								scope: this
							};
							var connection = new NC.util.AjaxConnection('GET', url, null);
							connection.executeMethod(callback);
						} // end - get social match results
					 end social matching code */
					});
				}
				else { // no results
					var i = peopleSearchUrl.indexOf('?');
					var query = '';
					if (i != -1) {
						query = peopleSearchUrl.substring(i + 1);
					}
					var helpUrl = './searchHelp.php?q=' + encodeURI(query);
					var updater = new NC.util.AjaxUpdate('GET', helpUrl, resultsDiv, resultsDiv, null);
					updater.doUpdate(true);
				}
			},
			
			execPeopleSearch: function( peopleSearchUrl, onResultsAvailable) {
					var callback =
					{
		  				success:function( o) {
							this.hideProgress();
							var results = null;
							if (o.responseText.length > 2) {
								var responseJson = NC.lang.JSON.parse(o.responseText);
								results = responseJson.data;
								if (responseJson.originalquery != responseJson.modifiedquery) {
									NC.widget.QueryManager.showHint('We modified your query. The results shown are for "' + 
										responseJson.modifiedquery + '"');
								}
							}
							NC.widget.PeopleManager.showResults(results, peopleSearchUrl);
							if (results != null && onResultsAvailable != null) {
								onResultsAvailable();
							}
							/* get available searches and start promo */
							var callback1 = {
								success: function(o){
									var r = NC.lang.JSON.parse(o.responseText);
									var availableSearches = r.MaxSearches - r.WeeklySearches;
									availableSearches = availableSearches > 0 ? availableSearches : "no";
									// now show promo
									/*
									var promo = new NC.promo.PremiumSearchPromo( "SearchOffer", null, availableSearches);
									NC.promo.PromoManager.setPromo( promo); 									   
									promo.start();
									*/
								},
								
								failure: function(o){
								},
								
								scope: this
							};
							updateUrl = 'getAvailableSearchCount.php';
							var connection1 = new NC.util.AjaxConnection('GET', updateUrl, '');
							connection1.executeMethod(callback1);
		  				},
		  				failure:function( o) {
							this.hideProgress();
//							alert( "failed to get search results");
							return null;
		  				},
						scope: this    				
					};

					this.showProgress();
//					var updater = new NC.util.AjaxUpdate( 'GET', './searchProgress.php', resultsDiv,  resultsDiv, null);
//					updater.doUpdate( true);
					

					var connection = new NC.util.AjaxConnection( 'GET', peopleSearchUrl, null);
					connection.executeMethod( callback);
					
					NC.widget.QueryManager.setHintShown( false); // if the hint was used, make it a real query
			},
			
			setSearchTitle: function( title) {
				searchTitle = title;
			},
			
 	 		initPeopleSearch: function( formDiv, _resultsDiv, _rewritePage, _refreshPage, onResultsAvailable ) { 
				resultsDiv = _resultsDiv;
				rewritePage = _rewritePage;
				refreshPage = _refreshPage;
				var pars = '';
				var formSource = './peoplesearchform.php';
				this.peopleSearchDialog = new NC.widget.ValidatedModalDialog(
					formSource, 
					pars, 
					formDiv, 
					'PeopleSearchForm',
			 		function( updateUrl, updateParms, updateTarget) // submission function
			 		{
						NC.widget.QueryManager.clearHint();
						if (NC.widget.PeopleManager.getRefreshPage()) {
							//	use this code to refresh the entire window and show google ads relevant to the search
							updateUrl = window.location.pathname;
							if (updateUrl.indexOf('?') == -1) {
								updateUrl += '?';
							}
							else 
								(updateUrl += '&');
							updateUrl += updateParms;
							window.location.href = updateUrl;
						}
						else {
							//							updateParms += 'pc=' + NC.widget.CategoryManager.getSelectedCategory();
							updateUrl += '?' + updateParms;
							NC.widget.PeopleManager.execPeopleSearch(updateUrl, onResultsAvailable);
						}
			 		}, 
			 		'./peoplesearch.php', // update url
			 		'', // update target
			 		function( form, errorDiv) // validation function
			 		{
						if (NC.widget.QueryManager.isEditHintShown() ||
							NC.widget.QueryManager.getQueryText().length == 0) { // no query entered
							NC.widget.QueryManager.hidePromoAnimation();
							NC.widget.QueryManager.showHint( "Please enter a query. Type into the text box or click one or more buttons.");
							return false;
						}
						else {
							return true;
						}
			 		},
			 		'NCError',
			 		false // not a popup
				);	
//				this.peopleSearchDialog.show( 0, 0, 0);	// not a popup - size does not matter
 	 		},
			
			getPeopleSearchDialog: function() {
				return this.peopleSearchDialog;
			},
			
			BasicHelp: 0,
			DetailedHelp: 1,
			ExampleHelp: 2,
			
			getHelpUrl: function ( type) {
				var helpUrl =  './peopleSearchHelp.php';
				if (type == this.DetailedHelp) {
					helpUrl = './peopleSearchDetailedHelp.php';
				}
				else if (type == this.ExampleHelp) {
					helpUrl = './peopleSearchExamples.php';
				}
				return helpUrl;
			},
			
			showHelpRewrite: function( type) {
				var helpUrl = this.getHelpUrl( type);
				var containerDiv = document.getElementById( containerDivName);
				if (containerDiv != null) {
					containerDiv.innerHTML = searchTemplate;
					NC.util.Event.onContentReady( containerDivName, function() {
						var updater = new NC.util.AjaxUpdate( 'GET', helpUrl, resultsDiv,  resultsDiv, null);
						updater.doUpdate( true);
					});
				}
			},
			
			showHelp: function( type) {
				var helpUrl = this.getHelpUrl( type);
				var updater = new NC.util.AjaxUpdate( 'GET', helpUrl, resultsDiv,  resultsDiv, null);
				updater.doUpdate( true);
			},
			
			showCategories: function() {
				var updater = new NC.util.AjaxUpdate( 'GET', './categoryHelp.php', resultsDiv,  resultsDiv, null);
				updater.doUpdate( true);
			}
 	 	}
  }	
();

})(); 	
 

