/*
 * Pollection Inc. (c) 2008
 */


var Pollection = new Object();
theGadget = null;

function PollectionGadgetInit(_page, _preUrlLoad, _postUrlLoad, _installPlatform, _acceptPlaquePlatform, _skipPlaquePlatform) 
{
	// Quit if this function has already been called
	if (arguments.callee.done)
		return;

	// Flag this function so we don't do the same thing twice
	arguments.callee.done = true;

	theGadget = new Pollection.Gadget(_page, _preUrlLoad, _postUrlLoad, _installPlatform, _acceptPlaquePlatform, _skipPlaquePlatform);
}


Pollection.Gadget = Class.create({
	domain : null,			// provider domain (hi5.com, etc)
	params : null, 			// url params
	prefs : '',				// view params
	ownerId : null,			// owner id
	viewerId : null,		// viewer id
	ownerObj : null,		// Hi5 JSON owner object
	viewerObj : null,		// Hi5 JSON viewer object
	page: null,				// Page from our servers to load
	preUrlLoad : null,		// function to call before loading any url from our servers
	postUrlLoad : null,		// function to call after loading any url from our servers
	authToken : null,		// synd specific auth token (e.g., Hi5AuthToken)
	
	friends : null,			// Open Social friends info, keyed on friend id
	markup : null,			// the page markup for gadget
	pendingReqs : 2,		// number of still pending requests
	errorFlag : false,		// there was at least one fatal error
	
	viral : null,			// the viral info from server-side
	
	gaFrom : null,			// name of the reference for GA call
	gaPage : null,			// name of the page for GA call
	vToken : null,			// viral token in the URL
	
	/*
	 * Platform Specific Viral Functionality
	 */
	installPlatform : null,
	acceptPlaquePlatform : null,
	skipPlaquePlatform : null,
	
	initialize : function(_page, _preUrlLoad, _postUrlLoad, _installPlatform, _acceptPlaquePlatform, _skipPlaquePlatform)
	{
		this.pendingReqs = 0;
		this.page = _page;
		this.preUrlLoad = _preUrlLoad;
		this.postUrlLoad = _postUrlLoad;
		this.installPlatform = _installPlatform;
		this.acceptPlaquePlatform = _acceptPlaquePlatform;
		this.skipPlaquePlatform = _skipPlaquePlatform;
		
		this.viral = {};
		
		this.gaFrom = '';
		this.gaPage = _page;
		
		this.domain = opensocial.getEnvironment().getDomain();
		this.params = gadgets.util.getUrlParameters();
		try {
			if (this.domain != 'myspace.com') 
			{
				// Hi5 & Orkut
				this.prefs = gadgets.json.parse(this.params['view-params']);
			} 
			else 
			{
				// MySpace
				this.prefs = gadgets.json.parse(this.params['p']);
      		}
      		if (!this.prefs)
      		{
		      this.prefs = {};
      		}
    	} 
    	catch (e) 
    	{
      		// bad news
      		this.prefs = {};
    	}
    	
		if (this.domain == 'orkut.com') 
		{
			this.ownerId  = this.params.gadgetOwner;
			this.viewerId = this.params.gadgetViewer;
		}
		else if (this.domain == 'hi5.com') 
		{
		var hi5JSON = null;
			if (typeof(this.params.hi5) == 'undefined')
			{
				// in IE 6 & 7 the hi5 info is not passed on profile view!
				this.getOwner();
				this.getViewer();
			}
			else
			{
				hi5JSON = eval('(' + this.params.hi5 + ')');
				this.ownerObj  = hi5JSON.owner;
				this.viewerObj = hi5JSON.viewer;
				this.ownerId = this.ownerObj.id;
				this.viewerId = this.viewerObj.id;
			}
		} 
		else if (this.domain == 'myspace.com') 
		{
			var osEnv = opensocial.getEnvironment().getParams();
			this.ownerId = osEnv.ownerid;
			this.viewerId = this.ownerId;
		}
		
		if (this.domain == 'hi5.com') 
		{
			// var view_params = gadgets.views.getParams();
        	this.authToken = this.prefs.Hi5AuthToken;
        	delete this.prefs.Hi5AuthToken;        	
		}

		var url = g_callbackUrl + '/play.php';
		if (this.params.view != 'profile' && typeof(this.prefs) == 'object') 
		{
			if (this.prefs.from)
			{
				this.gaFrom = this.prefs.from; 
			}
			if (this.prefs.page)
			{
				this.gaPage = this.prefs.page;
			}
			if (this.prefs.vtoken)
			{
				this.vToken = this.prefs.vtoken;
			}
			
			var extraParams = $H(this.prefs).toQueryString();
			if (extraParams.length > 0) {
				url += (url.indexOf('?') == -1) ? '?' : (url.lastIndexOf('?') != url.length -1) ? '&' : '';
				url += extraParams;
			}
    	}
		
		if (this.params.view != 'preview')
		{
			this.getFriends(); this.pendingReqs++;
			this.loadUrl(url); this.pendingReqs++;
		}
		else
		{
			g_pageTracker._trackPageview('preview [' + this.gaFrom + ']');
		}
	},
	loadUrl : function(url)
	{
		var ret = this.preUrlLoad();
		if (ret == true) return; //returning true will skip the actual loading; for things such as preview
		
		var params = {};
	    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.HTML;
		params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
		
		function loadUrlOnFetch(response)
		{
			clearTimeout(loadUrlTimer);
			
			if (typeof(response.text) == 'undefined' || response.text == null || response.text.length < 1) 
			{
				this.errorFlag = true;
			}
			else if (typeof(response.text) == 'string') 
			{
				$('loadNotice').hide();
				this.markup = response.text;		
				this.postUrlLoad();
			}
			this.pendingReqs--;
			this.render();
		}
		
		function LoadUrlOnTimeout()
		{
			$('loadNotice').show();
		}
		
		loadUrlTimer = setTimeout(LoadUrlOnTimeout.bind(this), 3000);
		gadgets.io.makeRequest(url, loadUrlOnFetch.bind(this), params);
	},
	getOwner : function()
	{
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPeopleRequest(opensocial.DataRequest.PersonId.OWNER), 'os_owner');
		
		function onOSOwnerFetch(response)
		{
			var os_owner = response.get('os_owner');
			if (os_owner.hadError())
			{
				this.ownerObj  = null;
				this.ownerId = null;
				this.errorFlag = true;
			}
			else 
			{
				this.ownerObj  = os_owner.getData();
				this.ownerId = this.ownerObj.getId();
			}
			this.pendingReqs--;
			this.render();
		}
		
		req.send(onOSOwnerFetch.bind(this));
	},
	getViewer : function()
	{
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPeopleRequest(opensocial.DataRequest.PersonId.VIEWER), 'os_viewer');
		
		function onOSViewerFetch(response)
		{
			var os_viewer = response.get('os_viewer');
			if (os_viewer.hadError())
			{
				this.viewerObj  = null;
				this.viewerId = null;
				this.errorFlag = true;
			}
			else 
			{
				this.viewerObj  = os_viewer.getData();
				this.viewerId = this.viewerObj.getId();
			}
			this.pendingReqs--;
			this.render();
		}
		
		req.send(onOSViewerFetch.bind(this));
	},
	getFriends : function()
	{
		var params = {};
		params[opensocial.DataRequest.PeopleRequestFields.FIRST] = 0;
		params[opensocial.DataRequest.PeopleRequestFields.MAX] = 200;
		
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, params), 'os_data');
		
		function onOSDataFetch(response)
		{
			var os_data = response.get('os_data');
			if (os_data.hadError())
			{
				this.friends = null;
				this.errorFlag = true;
			}
			else 
			{
				os_data = os_data.getData().asArray();
				this.friends = $H();
				Debug.info('OS Records Received: ' + os_data.length);
				for (var i = 0; i < os_data.length; ++i) 
				{
					this.friends.set(os_data[i].getId(), os_data[i]);
				}
			}
			this.pendingReqs--;
			this.render();
		}
		
		req.send(onOSDataFetch.bind(this));
	},
	render : function()
	{
		if (this.pendingReqs > 0)
			return;

		$('canvas').hide();
		if (this.errorFlag)
		{
			$('loadError').show();
			return;
		}

		function onUpdateComplete()
		{
			clearTimeout(updateTimer);
			
			if(typeof(_gViralBag) != 'undefined')
			{
				this.viral = _gViralBag;
			}
			
			if (this.viral && this.viral.install) {
				this.installPlatform();
			}
 
			if (this.viral && this.viral.plaque) {
				g_pageTracker._trackPageview('Viral [' + this.gaFrom + ']');
				$('viral').show();
			} else if (this.vToken == 'plaque') {
				g_pageTracker._trackPageview('Plaque [' + this.gaFrom + ']');
				$('viral').show();
			} else {
				g_pageTracker._trackPageview(this.gaPage + ' [' + this.gaFrom + ']');
				$('canvas').show();
			}
		}
		
		// let's give $('canvas').update enough time to evaluate JS code
		$('canvas').update(this.markup);
		updateTimer = setTimeout(onUpdateComplete.bind(this), 100);
	},
	acceptPlaque : function()
	{
		this.acceptPlaquePlatform();
		
		g_pageTracker._trackPageview(this.gaPage + ' [ViralAccept--' + this.gaFrom + ']');
		$('viral').hide();
		$('canvas').show();
	},
	skipPlaque : function()
	{
		this.skipPlaquePlatform();
		
		g_pageTracker._trackPageview(this.gaPage + ' [ViralSkip--' + this.gaFrom + ']');
		$('viral').hide();
		$('canvas').show();
	},
	href : function (_page, _from, _vtoken, baseUrl)
	{
		if(typeof(baseUrl) == 'undefined') {
			baseUrl = g_appUrl;
		}
		
		var appParam = { 
			page: _page,
			from: _from,
			vtoken: _vtoken
		};
		
		if (this.domain != 'myspace.com') 
		{
			// Hi5 & Orkut
			return baseUrl + '&view-params=' + escape(Object.toJSON(appParam).replace(/\s/g,''));
		} 
		else 
		{
			// MySpace
			return baseUrl + '&appParams=' + escape(Object.toJSON(appParam).replace(/\s/g,''));
  		}
	}
});
