<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs 
    title="Centrl" 
    title_url="http://centrl.com/opensocial/centrl/centrl.xml"
    description="See where your friends are, chat with users from Facebook, MySpace, Bebo, Hi5, Ning, Friendster, iGoogle and Orkut. Discover what's going on around you and get money-saving offers!"
    author="Murat Aktihanoglu"
    author_email="murat@centrl.com"
    author_affiliation="Centrl Inc."
    author_location="New York, NY, USA"
    thumbnail="http://centrl.com/images/logo/color/150x150.png"
    screenshot="http://centrl.com/images/screenshot.jpg"
    icon="http://centrl.com/images/logo/icon/16x16.ico"
    height="580">
    <Require feature="opensocial-0.7" />
    <Require feature="dynamic-height"/>
  </ModulePrefs>
  <Content type="html">
  <![CDATA[
  
    <div id='main'>
    </div>
    
    <script type="text/javascript">
    
        var b_hi5canvas = true;
        
        function request() {
            var req = opensocial.newDataRequest();

            if ( document.URL.match("orkut") )
            {
                var opt_params = { };
                opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
                                                                opensocial.Person.Field.PROFILE_URL
                                                                ];
                req.add(req.newFetchPersonRequest('VIEWER',opt_params), "viewer");
            }
            else
            {
                req.add(req.newFetchPersonRequest('VIEWER'), "viewer");
            }
            
            req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS), 'viewerFriends');

            
            //req.add(req.newFetchPersonRequest('OWNER'), "owner");
            
            req.send(response);
        }
        
        function sendFriendsListToServer(data, id, idPrefix, token)
        {
            // tell centrl server all the friends of this user
            var friendsList = '';
            var viewerFriends = data.get('viewerFriends').getData();
            
            //alert('For '+id+', token is '+token);
            
            // TODO - if this is too long, break it into chunks
            // maximum size of acceptable HTTP POST request is 2MB with Apache
            
            viewerFriends.each(
                function(person) 
                {
                    if ( friendsList.length > 0 )
                    {
                        friendsList += ',';
                    }
                    
                    friendsList += idPrefix + person.getId();
                }
            );
            
            //alert(friendsList);
            
            if ( friendsList.length > 0 )
            {
                var url     = 'http://api.centrl.com/contact/set/';
                
                var params = {};
                params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
                params[gadgets.io.RequestParameters.POST_DATA]= 'token='+token+'&id='+id+'&contactid='+friendsList;
                
                //alert('Calling contact/set with '+params[gadgets.io.RequestParameters.POST_DATA]);
                
                gadgets.io.makeRequest(
                    url, 
                    function tokenResponse(obj)
                    {
                        //alert(obj.text);
                    }, 
                    params
                );
            }       
        }

        
        function getTokenFromServerAndSendContacts(data, id, idPrefix, src, viewername, width, height)
        {
        
            // get token from server
            var url     = 'http://api.centrl.com/authentication/get';
            var token   = '';
            
            var params = {};
            params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
            params[gadgets.io.RequestParameters.POST_DATA]= 'publickey=abcdefghijklmnopqrstuvwxyz&network=Centrl.com&version=0.1';
            gadgets.io.makeRequest(
                url, 
                function tokenResponse(obj)
                {
                    //alert(obj.text);
                    
                    var jsonResponse = eval( "(" + obj.text + ")");        
                
                    token = jsonResponse.response.information.token;
                    
                    //alert('calling function with '+id+' and '+token);
                    
                    setHtmlWithToken( src+'&token='+token, viewername, width, height );
                    
                    sendFriendsListToServer(data, id, idPrefix, token);                
                }, 
                params
            );

        }



        function response(data) 
        {
            // do something with the viewer data
            var viewer = data.get("viewer").getData();

            var viewername = viewer.getDisplayName();

            //var owner = data.get("owner").getData();
            
            //var ownername = owner.getDisplayName();
            
            // get the container's name with this hack
            var idPrefix = "or";
            var containerUrl = document.URL;
            
            var networkid = viewer.getField(opensocial.Person.Field.ID);
            
            
            //var width  = gadgets.window.getViewportDimensions().width;
            //var height = gadgets.window.getViewportDimensions().height;  
            
            var width = 480;
            var height = 400;
            if ( containerUrl.match("orkut") )
            {
                idPrefix = "or";
                snName = "Orkut";
                width = 750;
                height = 600;

                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);


                var profile = viewer.getField(opensocial.Person.Field.PROFILE_URL);
                //alert(networkid+' - '+profile);
                
                var index = profile.indexOf('uid=');
                
                networkid = profile.substr(index+4);           
                
            }
            else if ( containerUrl.match("ning") )
            {
                //width = 540;
                height = 500;
                
                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
               
                idPrefix = "ni";
                snName = "Ning";
            }
            else if ( containerUrl.match("pulse") )
            {
                idPrefix = "pu";
                snName = "Pulse";
            }
            else if ( containerUrl.match("itimes") )
            {
                idPrefix = "it";
                snName = "itimes";
                
                height = 600;

                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
                
            }
            else if ( containerUrl.match("viadeo") )
            {
                idPrefix = "vi";
                snName = "viadeo";
                
                height = 600;

                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
                
            }
            else if ( containerUrl.match("imeem") )
            {
                idPrefix = "im";
                snName = "imeem";
                
                height = 600;

                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
                
            }
            else if ( containerUrl.match("netlog") )
            {
                idPrefix = "ne";
                snName = "Netlog";
                
                height = 600;

                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
                
            }
            else if ( containerUrl.match("friendster") )
            {
                idPrefix = "fr";
                snName = "Friendster";
                width = 950;
                height = 600;
                
                
                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
            }
            else if ( containerUrl.match("hi5") )
            {
                idPrefix = "hi";
                snName = "Hi5";
                width = 950;
                height = 600;
                
                
                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
                
                if ( width < 500 )
                {
                    b_hi5canvas = false;
                }
                
                
            }
            else if ( containerUrl.match("fanbox") )
            {
                idPrefix = "fa";
                snName = "FanBox";
                width = 950;
                height = 600;
                
                
                width  = gadgets.window.getViewportDimensions().width;
                height  = gadgets.window.getViewportDimensions().height;
                //gadgets.window.adjustHeight(height);
                
            }
            else if ( containerUrl.match("mixi") )
            {
                idPrefix = "mi";
                snName = "Mixi";
                width = 750;
                height = 600;
                
                
                width  = gadgets.window.getViewportDimensions().width;
                height  = gadgets.window.getViewportDimensions().height;
                //gadgets.window.adjustHeight(height);
                
            }
            else if ( containerUrl.match("google") )
            {
                height = 500;
                
                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
               
                idPrefix = "ig";
                snName = "iGoogle";
            }
            else if ( containerUrl.match("sonico") )
            {
                height = 500;
                
                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
               
                idPrefix = "si";
                snName = "Sonico";
            }
            else if ( containerUrl.match("hyve") )
            {
                height = 500;
                
                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
               
                idPrefix = "hy";
                snName = "Hyves";
            }
            else if ( containerUrl.match("quepasa") )
            {
                height = 500;
                
                width  = gadgets.window.getViewportDimensions().width;
                gadgets.window.adjustHeight(height);
               
                idPrefix = "qu";
                snName = "QuePasa";
            }
            else
            {
                // where are we??
                alert("where are we???");
            }
            
            
            if ( networkid == null || networkid == '' || networkid == 'xn_anonymous' )
            {
                var found = false;
                // get last id from the cookie
                if (document.cookie.length>0)
                {
                    c_start=document.cookie.indexOf("unypeid=");
                    if (c_start!=-1)
                    { 
                        c_start=c_start + 8; 
                        c_end=document.cookie.indexOf(";",c_start);
                        if (c_end==-1)
                        {
                            c_end=document.cookie.length;
                        }
                        networkid = unescape(document.cookie.substring(c_start,c_end));
                        found = true;
                    } 
                 }

                if ( !found )
                {
                    // if no cookie, create an id
                    networkid = Math.floor(99999999*Math.random());
                    
                    // put this in the cookie
                    var exdate=new Date();
                    exdate.setDate(exdate.getDate()+365);
                    document.cookie="unypeid=" +escape(networkid)+ ";expires=" + exdate.toGMTString();                    
                }               
                
            }
            
            var id = idPrefix + networkid;
            
            var thumb = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL);
             
            //var profile = viewer.getField(opensocial.Person.Field.PROFILE_URL);
            //profile = 'http://sandbox.orkut.com' + profile;

            //if ( !ownername )
            //{
            //  ownername = id;
            //}
            if ( !viewername )
            {
              viewername = id;
            }

            var src = 'http://centrl.com/centrl.php?id=' + id + '&name=' + viewername + '&pic=' + thumb + '&network=' + snName + '&mode=loggedin&width=' + width + '&height=' + height;

            // when this function gets the token, it will set the html, etc
            getTokenFromServerAndSendContacts(data, id, idPrefix, src, viewername, width, height);
        }
        
        function setHtmlWithToken(srcWithToken, viewername, width, height)
        {
            var html = '<iframe id="mapsframe" name="mapsframe" ' + 
                'src="'+srcWithToken+'" ' + 
                'frameborder="0" style="width: ' + width + 'px; height: ' + height + 'px;"/>';

            //alert('ownername:' + ownername + '-id:' + id + '-thumb:'+ thumb + '-profile:' + profile + '-viewername' + viewername );
            
            //alert(html);

            document.getElementById('main').innerHTML = html;
            
            var containerUrl = document.URL;
            if ( containerUrl.match("ning") )
            {
                postActivity(viewername+' is playing inside Centrl!');
            }
            else if ( containerUrl.match("orkut") )
            {
                OrkutpostActivity(' is playing inside Centrl!');
            }
            else if ( containerUrl.match("hi5") )
            {
                if ( b_hi5canvas )
                {
                    postActivity(viewername+' is playing inside <a href="/apps/entry/centrl.com/opensocial/centrl/centrl.xml">Centrl</a>! Join your friend <a href="/apps/entry/centrl.com/opensocial/centrl/centrl.xml">now</a>!');
                }
            }            
            else if ( containerUrl.match("fanbox") )
            {
                postActivity(viewername+' is playing inside Centrl!');
            }
            else if ( containerUrl.match("friendster") )
            {
                postActivity(viewername+' is playing inside Centrl!');
            }
            
        }
        
        function OrkutpostActivity(title)
        {
            var params = {};
            params[opensocial.Activity.Field.TITLE] = title;
            var activity = opensocial.newActivity(params);
            opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, 
                function(response) {
                
                    if (response.hadError())
                    {
                        // code comes back as 'unauthorized!!!
                        //alert("Error creating activity: Code: "+response.getErrorCode()+" Message: "+response.getErrorMessage());
                    }
                    else 
                    {
                        //alert("Activity successfully created.");
                    }
                }
            );
        }
        
        function postActivity(title)
        {
            var params = {};
            params[opensocial.Activity.Field.TITLE] = title;
            var activity = opensocial.newActivity(params);
            opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH);
        }
    
        /*****function writeActivity() {
          var streamTitle = 'Unype Virtual World';
          var stream_params = {'url': 'http://unype.com' };
          var stream = opensocial.newStream('', streamTitle, stream_params);
          
          var title = 'Playing inside Unype Virtual World';
          var link =  'http://unype.com';
          var activity_params = {'url' : link}
          var activity = opensocial.newActivity(stream, title, activity_params)
          opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, getActivities);
        }**/ 
        
        // http://code.google.com/apis/opensocial/docs/javascript/index.html
        //function getActivities() 
        //{
        //}
        
        //var containerUrlHack = document.URL;
        //if ( containerUrlHack.match("orkut") )
        //{
            // doesn't work in Ning
          //  gadgets.util.registerOnLoadHandler(request);
        //}
        //else //if ( containerUrl.match("ning") )
        //{
            _IG_RegisterOnloadHandler(request);
        //}
        
    </script>

  ]]>
  </Content>
</Module>