<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Tell a friend example" summary="Tell a friend example using OpenSocial" description="Tell a friend example using OpenSocial" author="Tom Kleijn" author_email="tom@elektronaut.nl" thumbnail="http://www.apikooien.nl/examples/opensocial/telll_a_friend/opensocial.jpg" screenshot="http://www.apikooien.nl/examples/opensocial/telll_a_friend/opensocial.jpg" height="380">
	<Require feature="opensocial-0.7"/>
	<Require feature="dynamic-height"/>
	<Require feature="views" />
	</ModulePrefs>
		<Content type="html" view="profile,canvas">
  			<![CDATA[
			<style>
			body {
				font-size:12px;
				font-family:Arial, Helvetica, sans-serif;
			}
			
			h1 {
				font-size: 16px;
			}
			
			h2 {
				font-size: 14px;
			}				
			
			div.friends {
				height: 175px;
				width: 350px;
				margin: 10px;
				overflow: auto;
			}
			
			</style>
	
			<input type="button" value="tell a friend!" onClick="navigate()">
			
			<script type="text/javascript">
				function navigate(navigateview) {
					var params = {};
					var availableviews = gadgets.views.getSupportedViews();
					gadgets.views.requestNavigateTo(availableviews['canvas'], params);
				}
			</script>
			]]>
		</Content>

  <Content type="html" view="canvas">
  <![CDATA[

	<style>
	body {
		font-size:12px;
		font-family:Arial, Helvetica, sans-serif;
	}
	
	h1 {
		font-size: 16px;
	}
	
	h2 {
		font-size: 14px;
	}				
	
	div.friends {
		height: 175px;
		width: 350px;
		margin: 10px;
		overflow: auto;
	}
	
	</style>

    <h1>Tell a friend</h1>
	
	<script type="text/javascript">

	function loadData(req) {
	        req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
	
	        var params = {};
			params[opensocial.DataRequest.PeopleRequestFields.FIRST] = 0;
	        params[opensocial.DataRequest.PeopleRequestFields.MAX] = 10000;
	        params[opensocial.DataRequest.PeopleRequestFields.SORT_ORDER] = opensocial.DataRequest.SortOrder.NAME;
	
	        // Retrieve the friends of the VIEWER
	        req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, params), 'viewerfriends');
	
	        req.send(onLoadData);
	}
	
	function onLoadData(data) {
	        var viewer = data.get('viewer').getData();
	        var viewerfriends = data.get('viewerfriends').getData();
	
	        var viewerId = viewer.getField(opensocial.Person.Field.ID);
	
	        var sViewerThumbnail = viewer.getField(Hyves.Person.Field.THUMBNAIL_URL_SMALL);
	             
	        html = new Array();
			html.push('<h4>Subject</h4>');
			html.push('<input type="text" id="subject" value="This is the subject">');
			html.push('<h4>Message</h4>');
			html.push('<textarea id="messagebody" style="width: 350px; height: 75px">Test [b]message[/b] [i]body[/i] with a [url=http://www.hyves.nl]link[/url] and a smiley :) :P </textarea>');
	        html.push('<h4>Select friends</h4>');
			html.push('<input type="hidden" id="theviewer" value="' + viewerId +'"'); // Used for the demo version. Send the message only to the VIEWER's inbox
			
			// This input field is used to filter the results based on the users input
			html.push('<label for="filt">Filter results</label>');
			html.push('<input name="filt" onkeyup="filter(this, \'filterable\', \'1\')" type="text">');
			
			// This form will hold your friends
			html.push('<form name="myfriends" id="myfriends">');
			html.push('<div class="friends">');
			html.push('<table celpadding=0 cellspacing=0 id="filterable">');
			html.push('<thead>');
			html.push('<tr>');
			html.push('<th colspan=3></th>');
			html.push('</tr>');
			html.push('</thead>');
			html.push('<tbody>');
			
			// For echt friend create a row
			viewerfriends.each(function(person) {
	                
					// Retrieve the user information of the friends
					var sFriendId  = person.getField(opensocial.Person.Field.ID);
	                var sGivenName = person.getField(opensocial.Person.Field.NAME).getField(opensocial.Name.Field.GIVEN_NAME);
					var sGetFamName = person.getField(opensocial.Person.Field.NAME).getField(opensocial.Name.Field.FAMILY_NAME);      
	                var sThumbnail = person.getField(Hyves.Person.Field.THUMBNAIL_URL_SQUARE_LARGE);
					
					// If the family name is empty do not display it
					if(sGetFamName == null) {
						var sFamName = " ";
					} else {
						sFamName = sGetFamName;
					}
					
					html.push('<tr class="checkrow">');
					html.push('<td>');
					html.push('<input type="checkbox" name="friend" value="' + sFriendId + '" >');
					html.push('</td>');
					html.push('<td>');
	                html.push('<img src="' + sThumbnail + '" border="0" height="42px">');
					html.push('</td>');
					html.push('<td>'); 
	                html.push(sGivenName + " " + sFamName);
					html.push('</td>');
					html.push('</tr>');
	                
	        });
			
			html.push('</tbody>');
			html.push('</table>');
			html.push('</div>');
			html.push('<input type="button" value="versturen" onClick="tellFriend()">');
			html.push('</form>');
			html.push('<em style="font-size: 11px">Note: While in sandbox mode you can only send 20 messages each month. Use them wisely ;-)</em>');
			
			// Create the HTML and adjust the height
	        document.getElementById('message').innerHTML = html.join('');
	        gadgets.window.adjustHeight();
	}
	
	function init() {
	        function getViewer() {
	                if (opensocial.hasPermission(opensocial.Permission.VIEWER)) {
	                        var req = opensocial.newDataRequest();
	                        loadData(req);
	                } else {
	                        document.getElementById('message').innerHTML = 'No permission to see the viewer';
	                }
	        }
	        opensocial.requestPermission([opensocial.Permission.VIEWER], 'This reason sentence is not used at the moment', getViewer);
	}
	
	function tellFriend() {
		var selectedFriends = "";
		//For each checkbox see if it has been checked, record the value.
		for (i = 0; i < document.getElementById('myfriends').friend.length; i++)
		if (document.getElementById('myfriends').friend[i].checked){
	        selectedFriends += document.getElementById('myfriends').friend[i].value;
			selectedFriends += ",";
		}

	    // we do not allow VIEWER_FRIENDS and OWNER_FRIENDS as recipients		
		// For this demo we only send the message to the VIEWER To send it to all the selected friend, uncomment the following line
	    var recipients = [selectedFriends]; // A single reciepient should be set as ['6c7ec0b62fca4e5f'] and multiple reciepients are called like [6c7ec0b62fca4e5f,6c7ec0b62fca4e5f,6c7ec0b62fca4e5f]
	   
	    // The next line is used to send the message only to the VIEWER
		// var recipients 	= document.getElementById('theviewer').value;
		
		// Retrieve the values for the title and body from the input fields
		var title 		= document.getElementById('subject').value;
	    var body 		= document.getElementById('messagebody').value;
	
	    var opt_params = {};
	
	    // the opensocial.Message.Field.TYPE field will be ignored
	    opt_params[opensocial.Message.Field.TITLE] = title;
	
	    // create the message object
	    var message = opensocial.newMessage(body, opt_params);
	
	    // callback is optional
	    var callback = function(responseItem){
	    // responseItem contains id's of the people who were send a message     
	            if(responseItem.hadError()) {
	                    var sErrorcode = responseItem.getErrorCode();
	                    alert(sErrorcode);
	            } else {        
	                    var aData = responseItem.getData();
	                    var sResult = '';
	                    if(aData.length != 0) { 
	                            for (var i=0;i<aData.length;i++) {
	                                    sResult += aData[i]+' ';
	                            }
	                            reloadPage(recipients);
	                    }
	            }
	    };
	
	// Actually send the message
	opensocial.requestSendMessage(recipients, message, callback);
	}

	
	function reloadPage(recipients) {
		// This function is called when the message is succesfully send
		// It reloads the page and shows a succes message
		html = new Array();
		html.push('<h2>Success!</h2>');
		html.push('The message has been send to the following recipients:<br/><br/>');
		
        var params = {};
		var hyverIds = [recipients];
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPeopleRequest(hyverIds, params), 'hyvers');
	 	
		req.send(function(response) {
		var hyvers = response.get('hyvers').getData();
		
			hyvers.each(function(hyver) {
				var sThumbnail = hyver.getField(Hyves.Person.Field.THUMBNAIL_URL_SQUARE_LARGE);
				var sGivenName = hyver.getField(opensocial.Person.Field.NAME).getField(opensocial.Name.Field.GIVEN_NAME);
				var sProfile = hyver.getField(opensocial.Person.Field.PROFILE_URL);
				html.push('<a href="' + sProfile + '" target="_blank"><img src="' + sThumbnail + '" border="0" title="' + sGivenName  +  '" ></a>');
			});
			
			html.push('<em>Note:<br>While in sandbox mode you can only send 20 messages each month<br>In sandbox mode you can only send messages to other API-developers</em>');
			document.getElementById('message').innerHTML = html.join('');
	    	gadgets.window.adjustHeight();
		})

		
	}
	
	// Filter the results on the users input
	function filter (phrase, _id){
	var words = phrase.value.toLowerCase().split(" ");
	var table = document.getElementById(_id);
	var ele;
	for (var r = 1; r < table.rows.length; r++){
		ele = table.rows[r].innerHTML.replace(/<[^>]+>/g,"");
	        var displayStyle = 'none';
	        for (var i = 0; i < words.length; i++) {
		    if (ele.toLowerCase().indexOf(words[i])>=0)
			displayStyle = '';
		    else {
			displayStyle = 'none';
			break;
		    }
	        }
		table.rows[r].style.display = displayStyle;
	}
}

	
	gadgets.util.registerOnLoadHandler(init);

  	</script>
	
	<div id="message"></div>
	
  ]]>
  </Content>
  
</Module>

