<?xml version="1.0" encoding="UTF-8"?>
<Module>
	<ModulePrefs title="External Collaborators" description="External Collaborators"
		width="190">
		<Require feature="opensocial-0.9" />
		<Require feature="dynamic-height" />
		<Require feature="osapi" />
		<Require feature="orng" />
		<Require feature="jsonld" />
		<Require feature="views" />
		<Require feature="start-hidden" />
		<Require feature="oauthpopup" />
		<OAuth>
			<Service name="pumpit.info">
				<Access url="https://pumpit.info/oauth/access_token" method="GET" />
				<Request url="https://pumpit.info/oauth/request_token" method="GET" />
				<Authorization url="https://pumpit.info/oauth/authorize" />
			</Service>
		</OAuth>
	</ModulePrefs>

	<!-- ==================== START COMBINED VIEWS ==================== -->

	<Content type="html" view="verify, small, canvas">
    <![CDATA[	
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>    
    <script type="text/javascript" src="js/environment.js" ></script>
    <script type="text/javascript" src="js/ontology.js" ></script>
    <script type="text/javascript" src="js/jsonld.js" ></script>
   	<script type="text/javascript">	        
		var COLLABORATED_ON = R2R('collaboratedOn');
	
		function getProductionURI(uri) {
			if (uri.indexOf("http://stage-profiles.ucsf.edu/profiles200") !== -1) {
				return uri.replace("http://stage-profiles.ucsf.edu/profiles200", "http://profiles.ucsf.edu");
			}
			else if (uri.indexOf("http://stage-profiles.ucsd.edu") !== -1) {
				return uri.replace("http://stage-profiles.ucsd.edu", "http://profiles.ucsd.edu");
			}
			else if (uri.indexOf("http://profilesstage.sc-ctsi.org") !== -1) {
				return uri.replace("http://profilesstage.sc-ctsi.org", "http://profiles.sc-ctsi.org");
			}
			return uri;
		}
			
		function getStageURI(uri) {
			if (uri.indexOf("http://profiles.ucsf.edu") !== -1) {
				return uri.replace("http://profiles.ucsf.edu", "http://stage-profiles.ucsf.edu/profiles200");
			}
			else if (uri.indexOf("http://profiles.ucsd.edu") !== -1) {
				return uri.replace("http://profiles.ucsd.edu", "http://stage-profiles.ucsd.edu");
			}
			else if (uri.indexOf("http://profiles.sc-ctsi.org") !== -1) {
				return uri.replace("http://profiles.sc-ctsi.org", "http://profilesstage.sc-ctsi.org");
			}
			return uri;
		}

		function readData(callback) {
			osapi.jsonld.getOwnerProperties([PRNS('fullName')]).execute(function(result) {
				if (!result.error) {
					$("#see-all").data("ownerURI", getProductionURI(result.uris[0])).show();
					var params = {};
					params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
					var url = 'http://stage-r2r.ucsf.edu/crosslinks/coauthors?researcherURI=' + getProductionURI(result.uris[0]) + '&format=JSON-LD';
					gadgets.io.makeRequest(url, callback, params);
				}
			}); /* end osapi.appdata.get */			
		}
		// ========================================		
    </script>
	]]>
	</Content>
	<Content type="html" view="small" preferred_width="190"
		preferred_height="300">
	<![CDATA[<!--HTML-->
    <!DOCTYPE html>
    
	<!-- #includes -->
	<link rel="stylesheet" href="css/gadget.css" type="text/css" media="screen, projection" >
	<script type="text/javascript">
	
		// ========================================		
		function displayData(collaboratorsStr) {
			//var collaborators = gadgets.json.parse(collaboratorsStr.data);				
			// if links data exists
			var peopleFrame = gadgets.json.parse('[{"http://ucsf.edu/ontology/r2r#contributedTo": {}}]');
			//var peopleFrame = gadgets.json.parse('[{"@type": "http://xmlns.com/foaf/0.1/Person"}]');
			jsonld.frame(gadgets.json.parse(collaboratorsStr.data), peopleFrame, function(err, collaborators) {				
				if (collaborators && collaborators['@graph'] && collaborators['@graph'].length) {
					collaborators = collaborators['@graph'];
					// need to tell container that it is OK to show us
					gadgets.orng.showGadget();

					// put ones with the most publications at the top, since these are all shared publications
					collaborators.sort(function(a, b) {
						return getPropertyAsArray(b, COLLABORATED_ON).length - getPropertyAsArray(a, COLLABORATED_ON).length;
					});
										
					var list_data = "<div>";					
					for (var i = 0; i<5 && i< collaborators.length;i++) {
						var person = collaborators[i];
						list_data += '<div class="col-item">';
						var imageURL = person[R2R('thumbnail')] || person[PRNS('mainImage')] || ENV_PROFILES_URL + "/Profile/Images/default_img.png";
						if (imageURL) {
							list_data += '<img src="' + imageURL + '" width="20px" height="22px"/>';
						} 
												
						list_data += "<a href='" + person['@id'] + "' target='_blank' onClick=\"gadgetEventTrack('go_to_website', '" + 
							person[FOAF('homepage')] + "')\"> " + person[RDFS('label')] + "</a>";
						list_data += "</div>";
						
					}
	       			// close the table
	       			list_data += "</div>";
	                  
	          		// put appdata table markup in designated div
					$("#collaborators_list").append(list_data);					
					$("#see-all span").text(collaborators.length);
					
	          		setTimeout(function(){
						var h = $("#collaborators_list").height() + 30;
						gadgets.window.adjustHeight(h);
			    	}, 1);
				}				
			});
		}
		// ========================================
		
		function gadgetEventTrack(action, label, value) {		
			var message = {'action' : action};
			if (label) {message.label = label;}
			if (value) {message.value = value;}
			
			gadgets.orng.reportGoogleAnalyticsEvent(message);
		}	
	
	   	gadgets.util.registerOnLoadHandler(function() {
			readData(displayData);
	    	$(document).ready(function () {
	    		$("#see-all").click(function() {
			        event.preventDefault();
			        var ownerURI = $("#see-all").data("ownerURI");
			    	gadgets.views.requestNavigateTo('canvas', {}, getStageURI(ownerURI));	
	    		});
	    	});
			
		});
    </script>
    
	<style>
    	.links_title { font-family:Verdana, Arial; font-size: 14px; }
    	.links_body { font-family:Arial; font-size: 12px; }
    	.links_credit { font-family:Arial; font-size:10px; }
		.links_save_button { height:20px; font-size:11px; } 
    	a, a:visited { color: #0088CC; text-decoration: none; font-size: 13px;}
    	a:hover { color: #005580; text-decoration: underline; }
    	.col-item{min-height:22px;} 
    </style>

    <div id="collaborators_list" style="padding:0px 0px 10px 20px;"></div>     
    <div>
    	<a id="see-all" href="#" style="display:none">
    		<img style="margin-right:2px;position:relative;top:1px;border:0" src="images/icon_squareArrow.gif" width="11" height="11"/>
    		See all (<span></span>) people
    	</a>
    </div>	
    
    ]]></Content>
	<Content type="html" view="verify">
    <![CDATA[	
   	<script type="text/javascript">	    
   		function checkData() {
   			// see if we already have this person/app combination internally in the system
   			osapi.orng.getAppInstance().execute(function(result) {
   				// if we do NOT have this in the system, then automatically add this to the persons if they have data from the service
   				if (typeof result !== 'string') {
					readData(registerApp); 					
   				}
   			});
   		}
   	    
		function registerApp(collaboratorsStr) {
			//var collaborators = gadgets.json.parse(collaboratorsStr.data);				
			// if links data exists
			var peopleFrame = gadgets.json.parse('[{"http://ucsf.edu/ontology/r2r#contributedTo": {}}]');
			//var peopleFrame = gadgets.json.parse('[{"@type": "http://xmlns.com/foaf/0.1/Person"}]');
			jsonld.frame(gadgets.json.parse(collaboratorsStr.data), peopleFrame, function(err, collaborators) {				
				if (collaborators && collaborators['@graph'] && collaborators['@graph'].length) {
					// need to tell container that it is OK to show us
					osapi.orng.addAppToOwner().execute(function(result) {
					});
				}
				else {
					// this does a "hard delete" and removes the app instance
					osapi.orng.removeAppFromOwner().execute(function(result) {
					});					
				}				
			});
		}

	   	gadgets.util.registerOnLoadHandler(checkData);
    </script>
	]]>
	</Content>
	<Content type="html" view="canvas" preferred_height="120"
		preferred_width="800">
    <![CDATA[
	   	<script type="text/javascript">
	   		var map;
		   	function loadScript() {
		  		var script = document.createElement('script');
			  	script.type = 'text/javascript';
			  	script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +'callback=initialize';
			  	document.body.appendChild(script);
			}
				    
			function initialize() {
		   		var mapOptions = {
		          center: new google.maps.LatLng(39.622, -98.571),
		          zoom: 3
		        };
		        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
		        				
	    	}		   	
			function readData2(ownerUri, callback) {
				var params = {};
				params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
				var url = 'http://stage-r2r.ucsf.edu/crosslinks/coauthors?researcherURI=' + getProductionURI(ownerUri) + '&format=JSON-LD';
				gadgets.io.makeRequest(url, callback, params);
			}
	    	
	    	var publications = {};
   	    	function loadPubs(callback) {
				var options = {};
				options.output = "full";  
		    	osapi.jsonld.getOwner(options).execute(function(data) {
		    		// in this case the owner will be the first and only item returned
				var ownerUri = data.uris[0];
		    		framePerson(data, function(owner) {
			    		var publications = owner[VIVO('authorInAuthorship')];
			    		if (publications instanceof Array) {
				    		for (var i in publications) {
				    			var pub = publications[i][VIVO('linkedInformationResource')];
				    			if(pub) {
				    				loadPub(pub);
				    			}					    						    			
				    		}
			    		}
			    		else if (publications) {
			    			var pub = publications[VIVO('linkedInformationResource')];
			    			loadPub(pub);
			    		}
			    		
			    		if(callback) {
			    			//var ownerUri = getProductionURI(owner['@id']);
			    			readData2(ownerUri, callback);
			    		}
		    		});
	   	    	});
  	    	};	
  	    	    			   	    	
	      	function loadPub(pub) {
				// check if this is an object first!
				if (pub == null || typeof pub != 'object') {
					return;
				}
				var publication = {};
	      		publication.id = pub['@id'].substring(pub['@id'].lastIndexOf('/') +1);

				publication.authorList = pub[PRNS('hasAuthorList')];
				publication.publicationVenue = pub[PRNS('hasPublicationVenue')];
				publication.pd = pub[PRNS('publicationDate')];
	      		publication.year = pub[PRNS('year')];
				publication.label = pub[RDFS('label')];
				publication.pmid = pub[BIBO('pmid')]; 
				
				publication.title = publication.authorList + '; <span class="label">' + publication.label + '</span>; ' + publication.publicationVenue + '; ' + 

publication.year;
				publications[publication.pmid] = publication;	 
	      	}	      	
	    	
	    	function findPublication(pmUrl) {
	    		var id = getPubId(pmUrl);
	    		return publications[id];
	    	}
	    	
	    	function getPubId(pmUrl) {
	    		var parts = pmUrl.split("/");
	    		return parts[parts.length-1];
	    	}
	    	
	    	var CONTRIBUTED_TO = R2R('contributedTo');
	    	function getPubCount(person) {
				var pubs = person[CONTRIBUTED_TO];
	    		if(pubs instanceof Array) {
	    			return pubs.length;
	    		}
	    		
	    		return 1;
	    	}

		// for demo
		function getURIFromID(base, id) {
			return id.indexOf("://") == -1 ? base + id : id;
		}

		function getWebfinger(item, uri, viewerWebfinger) {
			osapi.jsonld.getRDF(uri).execute(function(result) {
				if (!result.error) {
					var base = result.base;
			    		framePerson(result, function(result) {
						if (result && result[ORNG('hasActivityStreamsDemo')]) {
						osapi.jsonld.getRDF(getURIFromID(base, result[ORNG('hasActivityStreamsDemo')]['@id'])).execute(function(result) {
							if (result.jsonld['orng:hasApplicationInstanceData'] instanceof Array) {
							   for (var i = 0; i < result.jsonld['orng:hasApplicationInstanceData'].length; i++) {
								var id = result.jsonld['orng:hasApplicationInstanceData'][i]['@id'];
								osapi.jsonld.getRDF(getURIFromID(base, id)).execute(function(result) {
									if (result.jsonld['rdfs:label'] == 'webfinger') {
										var webfinger = result.jsonld['orng:applicationInstanceDataValue'];
										$(item).click(function() {
											follow(viewerWebfinger, webfinger);
										});
						   				$(item).show();
									}
								});
							   }
							}
							else if (result.jsonld['orng:hasApplicationInstanceData']) {
								var id = result.jsonld['orng:hasApplicationInstanceData']['@id'];
								osapi.jsonld.getRDF(getURIFromID(base, id)).execute(function(result) {
									if (result.jsonld['rdfs:label'] == 'webfinger') {
										var webfinger = result.jsonld['orng:applicationInstanceDataValue'];
										$(item).click(function() {
											follow(viewerWebfinger, webfinger);
										});
						   				$(item).show();
									}
								});
							}

						});
						}
					});
				}
			}); /* end osapi.appdata.get */			
		}

		function getViewerWebfinger() {
//			osapi.jsonld.getViewerProperties([ORNG('hasActivityStreamsDemo')]).execute(function(result) {
			var options = {};
			options.output = "full";  
			osapi.jsonld.getViewer(options).execute(function(result) {
				if (!result.error) {
					var base = result.base;
			    		framePerson(result, function(viewer) {
						if (viewer[ORNG('hasActivityStreamsDemo')]) {
						osapi.jsonld.getRDF(base + viewer[ORNG('hasActivityStreamsDemo')]['@id']).execute(function(result) {
							if (result.jsonld['orng:hasApplicationInstanceData'] instanceof Array) {
							   for (var i = 0; i < result.jsonld['orng:hasApplicationInstanceData'].length; i++) {
								id = result.jsonld['orng:hasApplicationInstanceData'][i]['@id'];
								osapi.jsonld.getRDF(getURIFromID(base, id)).execute(function(result) {
									if (result.jsonld['rdfs:label'] == 'webfinger') {
										var viewerWebfinger = result.jsonld['orng:applicationInstanceDataValue'];
										init(viewerWebfinger);
									}
								});
							   }
							}
							else if (result.jsonld['orng:hasApplicationInstanceData']) {
								var id = result.jsonld['orng:hasApplicationInstanceData']['@id'];
								osapi.jsonld.getRDF(getURIFromID(base, id)).execute(function(result) {
									if (result.jsonld['rdfs:label'] == 'webfinger') {
										var viewerWebfinger = result.jsonld['orng:applicationInstanceDataValue'];
										init(viewerWebfinger);
									}
								});
							}
						});
						} else {init('erictest@pumpit.info');}
					});
				}
				else {
					init('erictest@pumpit.info');
				}
			}); /* end osapi.appdata.get */			
		}
	    	
		   	gadgets.util.registerOnLoadHandler(
				getViewerWebfinger
			);

			function init(viewerWebfinger) {		
		   		gadgets.window.adjustHeight(900);
		   		gadgets.orng.showGadget();
		   		loadScript();
		   		
				loadPubs(function(collaboratorsStr) {
					var peopleFrame = gadgets.json.parse('[{"http://ucsf.edu/ontology/r2r#contributedTo": {}}]');
					jsonld.frame(gadgets.json.parse(collaboratorsStr.data), peopleFrame, function(err, collaborators) {				
						if (collaborators && collaborators['@graph'] && collaborators['@graph'].length) {
							collaborators = collaborators['@graph'];
							// need to tell container that it is OK to show us
							gadgets.orng.showGadget();
		
							// put ones with the most publications at the top, since these are all shared publications
							collaborators.sort(function(a, b) {
								return getPubCount(b) - getPubCount(a);
							});
									
							$(".total-count").text(collaborators.length);	                  
								
							for (var i = 0; i< collaborators.length;i++) {
								var person = collaborators[i];
								var imageURL = person[R2R('thumbnail')] || person[PRNS('mainImage')] || ENV_PROFILES_URL + 

"/Profile/Images/default_img.png";
								
								var name = person[RDFS('label')];
								var webSite = person[R2R('fromRNWebSite')];
								var lat = webSite[PRNS('latitude')];
								var long = webSite[PRNS('longitude')];
								var university = webSite[RDFS('label')];
												
						        var myLatlng = new google.maps.LatLng(lat, long);
						        var marker = new google.maps.Marker({
				    				position: myLatlng,
				    				map: map,
				    				title: university
								});
								
								var profileUrl=person['@id'];
								var pmUrl = "pubId";
								
								var pubs = person[R2R('contributedTo')];
								var pubs_count = 1;
								if(pubs instanceof Array) {
									pubs_count = pubs.length;
									pmUrl = "http://www.ncbi.nlm.nih.gov/pubmed/?term="								

	
									for(var p=0;p<pubs.length;p++) {
										pmUrl += getPubId(pubs[p]['@id']) + ",";
									}
								}
								else {
									pmUrl = pubs['@id'];
								}
								
								var pub = null;//findPublication(pmUrl);
								
								addColoborator(name, profileUrl, imageURL, webSite, pmUrl, pubs_count, pub?pub.title:"", 
									university, viewerWebfinger);			

					
							}	
				   			$("a.follow").each(function() {					
				   				var item = $(this).parents(".col");
				   				var uri = $(item).find(".col-name").attr("href");
								getWebfinger(this, getStageURI(uri), viewerWebfinger);
				   			});	
								
						}				
					});
				});		   		 
		   	}	
		   	
		   	function addColoborator(name, profileUrl, imageURL, webSite, pmUrl, pubs_count, pubTitle, university, viewerWebfinger) {
		   		var html = '<div class="col">';
		   		    html +='<img src="' + imageURL + '"></img><div><a href="' + profileUrl + '" target="_blank" class="col-name">'+name+
					'</a><span class="org">'+university+'</span>';
		   		    //html +='<div class="pm-title">'+ pubTitle +'</div>';
		   		    html +='. <a href="' + pmUrl + '" target="_blank">See '+ pubs_count +' coauthored papers in PubMed</a>';
		   		    
		   		    if (viewerWebfinger) {
		   		    	html += '<a class="follow" style="display:none">Follow</a>'
		   		    }
		   		    		   				
		   		    html +='</div><div style="clear:both"/></div>';
		   		    
		   		$("#coll-list").append(html);    
		   	}	 

    function showOneSection(toshow) {
      var sections = [ 'main', 'approval', 'waiting' ];
      for (var i=0; i < sections.length; ++i) {
        var s = sections[i];
        var el = document.getElementById(s);
        if (s === toshow) {
          el.style.display = "block";
        } else {
          el.style.display = "none";
        }
      }
    }

    function showResults(result) {
	var content = result.actor.displayName + ' is now following ' + result.object.displayName;	
	$('#main').html(content);
    }


		   	function follow(viewerWebfinger, tofollow) {
	var username = viewerWebfinger.split('@')[0];
      var params = {};
      url = "https://pumpit.info/api/user/" + username + "/feed";
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
      params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
      params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "pumpit.info";
      params[gadgets.io.RequestParameters.OAUTH_USE_TOKEN] = "always";
      params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;

  var postdata = {
    verb: "follow",
    object : {
        "id": "acct:" + tofollow,
        "objectType": "person"
    }
  };
params['HEADERS'] = {};
params['HEADERS']['Content-Type'] = 'application/json';
  params[gadgets.io.RequestParameters.POST_DATA] = gadgets.json.stringify(postdata);//gadgets.io.encodeValues(postdata);

      gadgets.io.makeRequest(url, function (response) {
        if (response.oauthApprovalUrl) {
          // Create the popup handler. The onOpen function is called when the user
          // opens the popup window. The onClose function is called when the popup
          // window is closed.
            var onOpen = function() {
              showOneSection('waiting');
            };
            var onClose = function() {
              fetchData();
            };
            var popup = new gadgets.oauth.Popup(response.oauthApprovalUrl,
                null, onOpen, onClose);
            $('personalize').onclick = popup.createOpenerOnClick();
$('#personalize').attr('href', response.oauthApprovalUrl);
            $('approvaldone').onclick = popup.createApprovedOnClick();
            showOneSection('approval');
        } else if (response.data) {
            showOneSection('main');
            showResults(response.data);
        } else {
            // The response.oauthError and response.oauthErrorText values may help debug
            // problems with your gadget.
            var main = document.getElementById('main');
            var err = document.createTextNode('OAuth error: ' +
              response.oauthError + ': ' + response.oauthErrorText);
            main.appendChild(err);
            showOneSection('main');
        }
      }, params);
    }


  	 
	    </script>
	    <style type="text/css">
	    	#map-canvas { height: 450px}
	    	
	    	.content{width: 600px;margin-left: 100px;}
	    	.content a {text-decoration: none; color: #0088CC !important; cursor:pointer;}
	    	.map-wrap{width:600px;height: 450px; margin-bottom: 20px;}
	    	.list-wrap{font-size: 13px;line-height: 20px;}	    	 
	    	.title{font-weight: bold;} 
	    	.descr{margin: 10px;color: #777;}
	    	#coll-list {margin-left: 10px; height: 300px; overflow-y: auto;}
	    	.col {margin-bottom: 5px;}
	    	.col div {padding-top: 8px;}
	    	.col img {width: 20px;float: left; margin-right: 10px;}
	    	.org {margin-left: 10px;} 
	    	.pm-title{margin-left: 30px; width: 500px;}
	    	.pm-link{margin-left: 50px;}
	    	.follow {margin-left: 10px;}	    	
	    </style>
	    
  <div id="main" style="display: none">
  </div>

  <div id="approval" style="display: none">
    <img src="http://gadget-doc-examples.googlecode.com/svn/trunk/images/new.gif">
    <a href="#" id="personalize" target="_blank">Authorize this Gadget</a>
  </div>

  <div id="waiting" style="display: none">
    Please click
    <a href="#" id="approvaldone">I've approved access</a>
    once you've approved access to your data.
  </div>
   		<div class="content">
   			<div class="map-wrap">	
	   			<div id="map-canvas"></div>
	   		</div>		
   			<div class="list-wrap">
   				<div class="title">External Collaborators (<span class="total-count">0</span>) found</div>
   				<div class="descr">External Collaborators are people at other institutions who have published with this person. They are sorted by most total 

publications to least. Click on a name to see their profile page in a new window.</div>
   				<div id="coll-list">
   				</div>
	   		</div>	
	   		<div class="debug"></div>	
   		</div>
	]]>
	</Content>
</Module>