/* Copyright (c) 2007 MOJO CHEN
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var linkxdApp = {
	
	load : function(){
		console.log('linkxdApp load : ' + new Date());
		linkxdApp.invokeSocialReq();
	},
	
	invokeSocialReq : function(){
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
		//req.add(req.newFetchPersonRequest('OWNER'), 'owner');
		//req.add(req.newFetchPeopleRequest('OWNER_FRIENDS'), 'ownerFriends');
		req.send(linkxdApp.onSocialLoad);
	},
	
	onSocialLoad : function(data){
		
		var viewer = data.get('viewer').getData(); // person
		var owner = data.get('owner').getData(); // person
		
		var ownerFriends = data.get("ownerFriends").getData().asArray() || []; 

		var result = 
			['<p>viewer:' , viewer.getDisplayName(),
			'</p><p>owner:', owner.getDisplayName(),
			'</p><p>ownerFriends:',ownerFriends.length,'</p>'];
		
		
		dojo.xhrGet ({
            url: 'app.json',
            handleAs: 'json', 
			// IMPORTANT: tells Dojo to automatically parse the HTTP response into a JSON object
                
            load: function (data) {            	
				var totalUsdGold = data.usdGold * ownerFriends.length;
				var totalTwdGold = totalUsdGold * data.usdTwd;
				var totalEurGold = totalTwdGold / data.eurTwd;
				var totalOil = totalUsdGold / data.usdOil;
				
				console.log('Total Gold USD:'+totalUsdGold.toFixed(2));
				console.log('Total Gold TWD:'+totalTwdGold.toFixed(2));
				console.log('Total Gold EUR:'+totalEurGold.toFixed(2));
				console.log('Total Gold OIL:'+totalOil.toFixed(2));
				
				result.push('<p>Total Gold USD:'+totalUsdGold.toFixed(2)+'</p>');
				result.push('<p>Total Gold TWD:'+totalTwdGold+'</p>');
				result.push('<p>Total Gold EUR:'+totalEurGold.toFixed(2)+'</p>');
				result.push('<p>Total Gold OIL:'+totalOil.toFixed(2)+'</p>');
				
				var div = dojo.byId('linkxd');
				div.innerHTML = result.join('');
				div.style.border = "solid red 2px";
				//div.style.color = "#C0C0C0";
				div.style.width = "300px";
             },
                
             error: function (error) {
                console.error('Error: ', error);
              }
                
            });
		
			
	}	
}

dojo.addOnLoad(linkxdApp.load);