Sparcq = ( this["Sparcq"] || {}  );

if (!Sparcq.Session) {
	Sparcq.Session = function (settings) {
		this.init(settings);
	};
}

Sparcq.Session.prototype.init = function(args) {
	if (args) {
		if (args.fb_api_key) {
			this.fbApiKey = args.fb_api_key;
		}
	}
	this.authFunction = null;
	this.sessionConnected = false;
	this.sessionConnectionChecked = false;
	this.sessionConnectionVerified = false;
	this.loggedIn = false;
	this.ratingUserCookie = 'recent_user_ratings';
	this.maxRatingsToStore = 20;
	this.ratingCookie = 'recent_ratings';
	this.currentRatingCount = 0;
	this.loginRedirectCookie = 'login-redirect';
	this.sessionCookie = 'sparcq-session';
	this.spanSessionParamsCookie = 'span_session_params';
	this.cookieDays = 60;
	this.authCookieDays = 7;
	this.spoonfeedOption = false;
	this.onLoginQueue = [];
	this.attemptedFbLogin = false;
	this.currentWhatsThis = null;
	this.whatsThisKeys = new Array(new Array('title', 'summary', 'avg', 'tot'), new Array(null, null, null, null));
	this.tagline = 1;
	this.showComments = false;
	this.spoonfedItems = [];
};

Sparcq.Session.prototype.initPersistentStore = function() {
	if (!Sparcq.SQ.getJSONCookie(this.spanSessionParamsCookie)) {
		this.resetStoredParams();
	}
};

Sparcq.Session.prototype.resetStoredParams = function() {
	Sparcq.SQ.storeJSONCookie(this.spanSessionParamsCookie,{
		spoonfeed: true
	},{
		expires: this.cookieDays
	});
	return Sparcq.SQ.getJSONCookie(this.spanSessionParamsCookie);
};

Sparcq.Session.prototype.setStoredParam = function(pname,val) {
	var sspc = Sparcq.SQ.getJSONCookie(this.spanSessionParamsCookie);
	if (!sspc) {
		sspc = this.resetStoredParams();
	}
	sspc[pname] = val;
	Sparcq.SQ.storeJSONCookie(this.spanSessionParamsCookie,sspc,{
		expires: this.cookieDays
	});
};

Sparcq.Session.prototype.getStoredParam = function(pname) {
	var sspc = Sparcq.SQ.getJSONCookie(this.spanSessionParamsCookie);	
	if (!sspc) {
		this.resetStoredParams();
	}
	return sspc[pname];
};

Sparcq.Session.prototype.setupRecommendations = function() {
	jQuery('#recommendations').each(function() {
		var el = jQuery(this);
		SPARCQ.COMPONENTS.initRecommendationList(el);
	});
};

Sparcq.Session.prototype.setupRatingBoxItemProfile = function() {
	var self = this;
	this.clickedRating = 0;
		
	$('.rateOptionItemP').click( function() {
		if (!SPARCQ.SESSION.promptIfNotLoggedIn())
			return false;
		
		// Define the rating that was just chosen
		var rating = Number($(this).attr('id').substring(1,3) + '.' + $(this).attr('id').substring(3));
		var item = $("#currentItemItemProfile").html();
		if (self.clickedRating == 0) {
			self.rateItemItemProfile(rating, item);
			
			//$('.ratingLoader', '#rating_box_item_detail').fadeOut('slow');
			//$('.ratingLoader', '#rating_box_item_detail').show();
			//$('.rate', '#rating_box_item_detail').css('display','none');
			//$('.boowhoo_large', '#rating_box_item_detail').css('visibility', 'hidden');
			coverItem = jQuery("#rating_box_item_detail");
			boxLoader = jQuery('.boxLoader.cloneable').clone();
			boxLoader.attr('id','rating_box_cover');
			boxLoader.width(coverItem.width() + 'px');
			boxLoader.height( ( coverItem.height() + 10) + 'px');
			jQuery('img',boxLoader).css('padding-top',( coverItem.height() / 2 - 16 ) + 'px' );
			boxLoader.removeClass("cloneable");
			//boxLoader.width(coverItem.width());
			//boxLoader.height(coverItem.height());
			//boxLoader.show();
			boxLoader.appendTo($("#rating_box_item_detail"));
			
		}
		self.clickedRating++;
		
	});
};

Sparcq.Session.prototype.handleRatingItemProfileReturn = function(ret,ct) {
	if ( ret ) {
		var topic = ret.parsed_return;
		jQuery('.predict','#rating_box_item_detail').html('You rated ' + topic.rated_value );
		var avg_rating_sq = $('.bw_container .bwl', '#rating_box_item_detail');
		avg_rating_sq.html(topic.average || 'N/A');

		var cc = SPARCQ.COMPONENTS.getItemRatingColorClass(topic.average || 5) 
		avg_rating_sq.removeClass();
		avg_rating_sq.addClass('boowhoo_large bwl ' + cc);

		$('.title', '#rating_box_item_detail').html(topic.readable_title);

		$('.rate', '#rating_box_item_detail').css('display','none');
		$('.predict', '#rating_box_item_detail').css('padding-top','8px');
		
		var boxLoader = jQuery('#rating_box_cover');
		boxLoader.fadeOut();
		SPARCQ.COMPONENTS.ratings.refresh();
	}
}

Sparcq.Session.prototype.getRatingCookie = function() {
	return (this.loggedIn) ? this.ratingUserCookie : this.ratingCookie;
};

Sparcq.Session.prototype.rateItemItemProfile = function(val,item_name) {
	var cur_val = this.storeRating(this.getRatingCookie(),item_name,val);
	var self = this;

	if (this.loggedIn) {
		SPARCQ.API.callMethod('topic.addRating', {
			params: {
				entry_title: item_name,
				rating: val,
				sparcq_member_id: this.getMemberId()
			},
			onSuccess: function(ret) {
				self.handleRatingItemProfileReturn(ret);
			},
			onError: function(ret,id) {
				SPARCQ.COMPONENTS.showError('error rating item ' + id);
			}
		}); 
	} 
	
};


Sparcq.Session.prototype.setupRatingButtons = function() {
	var self = this;
	var initialCalloutFaded = 0;
	
	function rateCalloutFade() {
		if($('#rate_callout').length) {
			if ($('#rate_callout').css('display') == 'block') {
				$('#rate_callout').fadeOut(250);
				initialCalloutFaded++;
			}
		}
	}

	function rateCalloutReturn() {
		if($('#rate_callout').css('display') != 'block') {
			if(initialCalloutFaded < 3) {
				$('#rate_callout').fadeIn(250);
			}
		}
	}
		
	if ( this.isSpoonfeeding() ) { 
		if (location.hash && location.hash.substring(0,6) == '#rate:') {
			this.getNextItem(unescape(location.hash.substring(6)));
		} else {
			this.getNextItem();
		}
	}
	
	$('#currentItem').mouseover( function() { rateCalloutReturn(); } );
	$('#currentItem').mouseout( function() { if(initialCalloutFaded != 0) { rateCalloutFade(); } } );

	$('#currentItem').unbind('click');
	$('#currentItem').click(
		function() {
			rateCalloutFade();
		}
	);
	
	$('.rateOption').unbind('click');
	$('.rateOption').click( function() {
		// Define the rating that was just chosen
		var rating = Number($(this).attr('id').substring(1,3) + '.' + $(this).attr('id').substring(3));
		var item = $("#currentItem").val();
		self.rateItem(rating, item);
		
		rateCalloutFade();
	});

	$('.rateThis').unbind('click');
	$('.rateThis').click( function() {
		if ( self.isSpoonfeeding() ) {
			self.getNextItem($(this).attr('title'), true);
		}
	});

	$('.maxRate').unbind('click');
	$('.maxRate').click( function() {
		if($(this).attr('id') == 'boo') {
			self.rateItem(0, $("#currentItem").val());
		} else {
			self.rateItem(10, $("#currentItem").val());
		}
		
		rateCalloutFade();
	});
	
	if($('.comment_container').length) {
		/*
		alert(self.getStoredParam('showComments'));
		if(self.getStoredParam('showComments') == true) self.setStoredParam('showComments', false);
		else self.setStoredParam('showComments', true);
		*/
		
		if(!self.getStoredParam('showComments')) {
			$('.comment_container').hide();
			$('#toggleCommentBoxText').html('would you like to <a id="toggleCommentBox" href="#c">include a comment</a> with your rating?');
		} else {
			$('#toggleCommentBoxText').html('<a id="toggleCommentBox" href="#c">no comment</a>');
		}

		$('#toggleCommentBoxText').click( function() {
			$('.comment_container').toggle();
			
			if(self.getStoredParam('showComments') == true) {
				self.setStoredParam('showComments', false);
				$('#toggleCommentBoxText').html('would you like to <a id="toggleCommentBox" href="#c">include a comment</a> with your rating?');
			} else {
				self.setStoredParam('showComments', true);
				$('#toggleCommentBoxText').html('<a id="toggleCommentBox" href="#c">no comment</a>?');
			}
		});
	}
};

Sparcq.Session.prototype.loadFbJS = function() {
	//should be loaded already
	jQuery.getScript('http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php');
};



Sparcq.Session.prototype.popWhatsThis = function(rating_container) {
	var cur_val = jQuery('#currentItem',rating_container).val();
	
	function loadBox() {
		var html = "<div class=\"title\"><a href=\"/" + Sparcq.SQ.getWikiURI(self.whatsThisKeys['title']) + "\">" + self.whatsThisKeys['title'] + "</a>" + " avg: " + self.whatsThisKeys['avg'] + " / tot: " + self.whatsThisKeys['tot'] + "<\/div>";
		html += "<div class=\"summary\">" + self.whatsThisKeys['summary'] + "</div>";
		html += "<div class=\"readMore\">still curious? <a href=\"/" + Sparcq.SQ.getWikiURI(self.whatsThisKeys['title']) + "\">read on &raquo;</a></div>";
		if (self.currentWhatsThis == cur_val) {		
			jQuery('#current_tooltip').html(html);
		}
		
		$('.summary a').hover(
			function(e) {
				var offset = $(this).offset();
				console.debug('item left: ' + offset.left + ', top: ' + offset.top);
				console.debug('mous left: ' + e.pageX + ', top: ' + e.pageY)
				$('#miniRate').css({
					left: e.pageX - 121 + 'px',
					top: e.pageY - 20 + 'px'
				});
			}, function(e) {
				//console.debug('topic link blur');
			}
		);
	}
	
	if (cur_val && cur_val.length) {
		
		this.currentWhatsThis = cur_val;
		var self = this;
		
		if (this.whatsThisKeys['title'] != cur_val) {
			self.whatsThisKeys['title'] = cur_val;
			self.whatsThisKeys['avg'] = '-';
			self.whatsThisKeys['tot'] = '-';
			self.whatsThisKeys['summary'] = '<p>loading summary...</p>';
			
			SPARCQ.API.callMethod('topic.getDetail', {
				params: {
					entry_title: cur_val,
					summary: 1
				},
				onSuccess: function(ret) {
					self.whatsThisKeys['summary'] = ret.parsed_return.summary;
					self.whatsThisKeys['avg'] = ret.parsed_return.average;
					self.whatsThisKeys['tot'] = ret.parsed_return.total_ratings;
					loadBox();
				}, 
				onError: function(ret) {
					self.whatsThisKeys['summary'] = 'Error during load!';
					loadBox();
				}
			});
		}
		
		loadBox();
		
		/*
		var html = "<div class=\"title\"><a href=\"/" + cur_val + "\">" + cur_val + "</a>" + " avg: " + this.whatsThisKeys[cur_val].avg + " / tot: " + 'tot' + "<\/div>";
		html += "<div class=\"summary\">" + this.whatsThisKeys[cur_val] + "</div>";
		html += "<div class=\"readMore\">still curious? <a href=\"/" + cur_val + "\">read on &raquo;</a></div>";
		jQuery('#current_tooltip').html(html);
		*/

		return true;
	}
	return false;
};

Sparcq.Session.prototype.setupAutocompleters = function() {
	var self = this;
	jQuery('.rating_container').each(function() {
		var el = jQuery(this);
		var whats_this = jQuery('.whats_this',el);
		whats_this.show();
		jQuery('a',whats_this).tooltip({
			tip: '#current_tooltip',
			position: 'bottom right',
			cancelDefault: true,
			delay:500,
			effect: 'fade',
			onBeforeShow: function() { return self.popWhatsThis(el) }
		});
	
		var wiki_ac = jQuery('.object_autocompleter',el);
		SPARCQ.API.initOpenSearchElement(wiki_ac);
		//SPARCQ.API.initSparcqAutocomplete(wiki_ac);
		
		wiki_ac.focus( function() {
			var curItem = $(this).val();
			var originalItem = $(this).attr('alt');
			if (originalItem == curItem) {
				$(this).val('');
			}
			$(this).attr('alt',curItem);
				
		});
		wiki_ac.blur( function() {
			if($(this).val() == '') {
				$(this).val($(this).attr('alt'));
			}
		});

	});
};

Sparcq.Session.prototype.setupRateLists = function() {
	jQuery('.rateListContainer').each(function() {
		var el = jQuery(this);
		SPARCQ.COMPONENTS.initRateList(el);
	});
};

Sparcq.Session.prototype.setupUserLists = function() {
	jQuery('.userListContainer').each(function() {
		var el = jQuery(this);
		SPARCQ.COMPONENTS.initUserList(el);
	});
};

Sparcq.Session.prototype.setupUserRateLists = function() {
	jQuery('.rateListContainer').each(function() {
		var el = jQuery(this);
		SPARCQ.COMPONENTS.initLoggedInRateList(el);
	});
};

Sparcq.Session.prototype.setupUserInfoBoxes = function() {
	switch(SPARCQ.PAGE) {
		case 'user_detail':
			//SPARCQ.COMPONENTS.initUserDetails();
			SPARCQ.COMPONENTS.initRatingsCommentsBox('user');
			SPARCQ.COMPONENTS.initDynamicUserDetails();
			break;
		case 'share':
			SPARCQ.UID = SPARCQ.SESSION.getMemberId();
			SPARCQ.COMPONENTS.initSharePageRecentRatingsList(jQuery('.pastRatings'));
			break;
	}
};

Sparcq.Session.prototype.setupMenu = function() {
	var menu = jQuery('#sub_menu_holder');
	if (menu) {
		var template_html = menu.html();
		menu.html(Sparcq.SQ.parseHtml(
			template_html, {
				user_detail_link: Sparcq.SQ.userURL(this.getMemberId())
		}));
		$('.logged_in_menu_item').show();
		menu.show();

	}
};

Sparcq.Session.prototype.setupAvatars = function() {
	var label = $('#avatarLabel');
	label.css({ 'opacity': '0', 'display': 'block' });
	
	$('.avatar').hover(
		function() {
			var el = $(this);
			var off = el.offset();
			label.css({ 'left': off.left + 20 + 'px', 'top': off.top - 10 + 'px' }).html(el.parent().attr('title')).stop(true, false).animate({ 'opacity': '1' }, 250);
		},
		function() {
			label.animate({ 'opacity': '0' }, 250);
		}
	);
}

Sparcq.Session.prototype.showAlphaWindow = function() {
	if (!this.loggedIn) {
		var self = this;
		setTimeout(function() { self.showAlphaPrompt();	}, 2000);
	}
};

Sparcq.Session.prototype.setupButtons = function() {
	//this.setupMenu();
	// need to break this out, doing some extra calls on pages that aren't rate centric
	

	switch(SPARCQ.PAGE) {
		case 'share':
			this.setupRatingButtons();
			SPARCQ.COMPONENTS.loadSimilarUsers();
			break;
		case 'main':
			this.setupRatingButtons();
			break;
		case 'rate':
			this.setupRatingButtons();
			//move to post login check...
			//SPARCQ.COMPONENTS.setupRecentRatingsList(jQuery('#userRatings'));
			//move to post login check...
			break;
		case 'item_detail':
			var topic_name = jQuery('#topic_to_load').html();
			SPARCQ.COMPONENTS.loadTopicPageComponents({
				topic_id: SPARCQ.TOPIC_ID,
				title: topic_name
			});
			//SPARCQ.COMPONENTS.initSidebarItemDetail();
			break;
			
		case 'connect':
		    SPARCQ.COMPONENTS.loadSimilarUsers();
		    break;
		    
		case 'account':
		    SPARCQ.COMPONENTS.loadAccount();
		    break;
		    
		case 'reference':
			SPARCQ.COMPONENTS.loadSimilarUsers();
			break;
			
		case 'discover':
			SPARCQ.COMPONENTS.initFilter('discover');
			break;

		case 'tag':
		case 'search':
			$('.rating_item').each(function() {
				Sparcq.SQ.addRateInPlaceEvent($(this));
			});
			break;
	}


	this.setupAutocompleters();
	this.setupRateLists();
	this.setupUserLists();
	this.setupSearchBox();
	this.setupTagList();

	//move to post login check...
	//this.setupRecommendations();
	//move to post login check...
	
	this.setupUserInfoBoxes();
};

Sparcq.Session.prototype.setupTagList = function() {
	if($('.tag').length) {
		$('.tag').hover(
			function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			}
		);
	}
};

Sparcq.Session.prototype.setupSearchBox = function() {
	$('#searchBox').focus( function() {
		if($(this).val() == $(this).attr('alt')) {
			$(this).val('');
			$(this).removeClass('default');
			$(this).addClass('active');
		}
	});

	$('#searchBox').blur( function() {
		if($(this).val() == '') {
			$(this).removeClass('active');
			$(this).addClass('default');
			$(this).val($(this).attr('alt'));
		}
	});

	$('#searchForm').submit( function() {
		var sb = $('#searchBox').val();
		if (sb == 'search') {
			return false;
		}
		
		Sparcq.SQ.redirect(Sparcq.SQ.uriFor('/en/search', { q: sb }));
		return false;
	});



};

Sparcq.Session.prototype.executePostLogin = function() {
	var default_post_login = '/';
	var nrto = Sparcq.SQ.getCookie(this.loginRedirectCookie);
	var rto = (nrto && nrto != '') ? nrto : default_post_login;
	Sparcq.SQ.setCookie(this.loginRedirectCookie,'');
	Sparcq.SQ.redirect(rto);
}

Sparcq.Session.prototype.checkPostLoginRedirect = function() {
	var default_post_login = '/';
	var nrto = Sparcq.SQ.getCookie(this.loginRedirectCookie);
	var rto = (nrto && nrto != '') ? nrto : default_post_login;
	Sparcq.SQ.setCookie(this.loginRedirectCookie,'');
	if (SPARCQ.PAGE == 'main')
		Sparcq.SQ.redirect('/en/share');
	//Sparcq.SQ.redirect(rto);
};

Sparcq.Session.prototype.handleEndSession = function(ret) {
	this.clearSessionData();
	if (SPARCQ.AUTH_REQUIRED) {
		Sparcq.SQ.redirect('/');
		this.setLoggedOut();
	} else {
		this.setLoggedOut(true);
	}
};

Sparcq.Session.prototype.executeLogout = function() {
	
	var self = this;
	SPARCQ.API.callMethod('user.endSession', {
		params: {
			//default stuff will be passed with every api call... 
		},
		onSuccess: function(ret) {
			self.handleEndSession(ret);			
		},
		onError: function(ret,rt) {
			self.handleEndSession(ret);			
		}
	}); 

	
};


Sparcq.Session.prototype.performPostLoginActions = function(page_login) {
	if (this.onLoginQueue.length) {
		var seen_funcs = {};
		for (var i=0; i < this.onLoginQueue.length; i++) {
			var cur_func = this.onLoginQueue[i];
			var stringed_func = String(cur_func);
			if (!seen_funcs[stringed_func]) {
				seen_funcs[stringed_func] = 1;
				cur_func.call();
			} else {
			}
		}
		this.onLoginQueue = [];
	} else if (page_login) {
		this.checkPostLoginRedirect();
	}
	
	
};

Sparcq.Session.prototype.doSessionTimeout = function() {
	Sparcq.SQ.deleteCookie(this.sessionCookie);
	this.showAlertPrompt('Your session has expired. Please login again to access Sparcq.','/');
};

Sparcq.Session.prototype.showAlertPrompt = function(msg,redirect_on_ok) {
	if (!this.alertPrompt) {
		this.alertPrompt = $('#dialog_confirm');
		jQuery('.jqmClose_container',this.alertPrompt).hide();
		this.alertPrompt.jqm({
			modal: true,
			onHide: function(h) {
				h.w.hide();
				h.o.remove();
			}
		});
	}
	msg = msg || '';
	jQuery('.jqmCustomMessage',this.alertPrompt).html(msg);	
	jQuery('.okButton input', this.alertPrompt).unbind('click');
	var self = this;
	jQuery('.okButton input', this.alertPrompt).click(function() {
		self.alertPrompt.jqmHide();
		if (redirect_on_ok) {
			Sparcq.SQ.redirect('/');
		}
	});
	this.alertPrompt.jqmShow(); 

}



Sparcq.Session.prototype.executePostLoginFacebook = function() {
	//this.hideLoginPrompt();
	this.setFbCredentials();
	this.createSession();
	this.attemptedFbLogin = true;
	//this.updateLoginBox();
	//this.performPostLoginActions();
	//this.checkPostLoginRedirect();
};

Sparcq.Session.prototype.createSession = function() {
	var self = this;
	SPARCQ.API.callMethod('user.authenticate', {
		params: {
			//default stuff will be passed with every api call... 
		},
		onSuccess: function(ret) {
			self.handleCreateSession(ret);
		},
		onError: function(ret,rt) {
			alert('error calling api for to create session');
		}
	}); 
};

Sparcq.Session.prototype.setLoggedIn = function(show_alert) {
	var page_login = (this.sessionConnectionChecked) ? true : false;
	this.sessionConnected = true;
	this.sessionConnectionChecked = true;
	this.loggedIn = true;
	this.updateLoginBox();
	this.hideLoginPrompt();
	this.performPostLoginActions(page_login);
};

Sparcq.Session.prototype.setLoggedOut = function(show_alert) {
	this.loggedIn = false;
	this.sessionConnected = false;
	this.sessionConnectionChecked = true;
	this.updateLoginBox();
	this.hideLoginPrompt();
	if (show_alert) {
		alert('you were logged out!');
	}
};

Sparcq.Session.prototype.handleCreateSession = function(ret) {
	var user = ret.parsed_return;
	var res = (ret.response) ? ret.response.result : {};
	if (res.is_valid) {
		var token = res.token;
		this.storeSessionData({
			token: token,
			user: user,
			session_key: this.sessionKey
		});
		this.setLoggedIn();
		
	} else {
		this.setLoggedOut();
		alert("Sorry, we cannot validate your privileges to use Sparcq.\n\nPlease try again later if you believe you have been granted access to Sparcq.");
	}
};

Sparcq.Session.prototype.storeSessionData = function(ret) {
	if ( typeof(ret) != 'undefined' ) {
		Sparcq.SQ.storeJSONCookie(this.sessionCookie,ret,{
			expires: this.authCookieDays
		});
	}	
	this.sessionData = Sparcq.SQ.getJSONCookie(this.sessionCookie);
};


Sparcq.Session.prototype.checkConnection = function() {
	var cn = Sparcq.SQ.getJSONCookie(this.sessionCookie);
	if (cn) {
		this.storeSessionData();
		this.setLoggedIn();
		this.doLoggedInActions();
	} else {
		this.sessionConnectionVerified = true;
		this.setLoggedOut();
		this.doLoggedOutActions();
	}

};

Sparcq.Session.prototype.load = function(args) {
	this.checkConnection();
	this.validateSession();
	var self = this;
	setInterval(function() {
		self.validateSession();
	},60000 * 5);
	this.initPersistentStore();	
	this.setupStoreBasedEvents();
	this.setupButtons();
	this.loadSiteDetails();
};

Sparcq.Session.prototype.loadSiteDetails = function() {
	var self = this;
	var sd = jQuery('#site_details');
	if (!sd) return;
	SPARCQ.API.callMethod('site.getDetail', {
			params: {
			},
			onSuccess: function(ret) {
				if (ret && ret.parsed_return) {
					sd.html(ret.parsed_return.total_ratings + ' total ratings since June 2009');
				} else {
					sd.hide();
				}
			},
			onError: function(ret,id) {
				sd.hide();
			}
		});


};

Sparcq.Session.prototype.isSpoonfeeding = function() {
	if (!this.spoonfeedOption || this.getStoredParam('spoonfeed')) return true;
	return false;
};

Sparcq.Session.prototype.setupStoreBasedEvents = function() {
	var spoonfeed_item = jQuery('.spoon_container input');
	if (spoonfeed_item && spoonfeed_item.length) {
		this.spoonfeedOption = true;
		if (this.getStoredParam('spoonfeed')) {
			spoonfeed_item.attr('checked', true);
		} else {
			spoonfeed_item.attr('checked', false);	
		}
		var self = this;
		spoonfeed_item.click(function() {
			var si = jQuery(this);
			if (spoonfeed_item.attr('checked')) {
				self.setStoredParam('spoonfeed',true);
				self.setupRatingButtons();
				$('.button.skipItem').css({visibility: 'visible'});
			} else {
				self.getNextItem(' ');
				self.setStoredParam('spoonfeed',false);
				$('.button.skipItem').css({visibility: 'hidden'});
			}
		});
	}
};

Sparcq.Session.prototype.handleAddRatingsReturn = function(ret) {
	var topics = ret.parsed_return;
	this.resetCookie(this.ratingCookie);
	for (i=0; i<topics.length;i++) {
		var topic = topics[i];
		this.addToCookie(this.ratingUserCookie,{
			entry_title: topic.title,
			topic_id: topic.topic_id,
			average: topic.average
		});
	}
};



Sparcq.Session.prototype.doLoggedInActions = function() {
	var ck = this.getCookie(this.ratingCookie);
	var json_string = jQuery.toJSON(ck);
	var self = this;
	if (ck.length) {
		//save ratings
		SPARCQ.API.callMethod('topic.addRatings', {
			params: {
				ratings: json_string,
				sparcq_member_id: this.getMemberId()
			},
			onSuccess: function(ret) {
				self.handleAddRatingsReturn(ret);
			},
			onError: function(ret,id) {
				SPARCQ.COMPONENTS.showError('error rating items from cookie ');
			}
		});
	}

	switch (SPARCQ.PAGE) {
		case 'item_detail':
			//this is called after topic load for now
			//SPARCQ.COMPONENTS.initSidebarItemDetail();
			break;
		case 'rate':
			SPARCQ.COMPONENTS.setupRecentRatingsList(jQuery('#userRatings'));
			break;
		default:
			break;
	}

	this.setupRecommendations();
	this.setupUserRateLists();

	if (SPARCQ.PAGE != 'main') {
		this.setupMenu();
	}
};


Sparcq.Session.prototype.doLoggedOutActions = function() {
	if (SPARCQ.AUTH_REQUIRED) {
		this.loginRedirectCookie = 'login-redirect';
		Sparcq.SQ.setCookie(this.loginRedirectCookie,location.href);
		Sparcq.SQ.loginRedirect();
	}
};

Sparcq.Session.prototype.doAfterLoginStatusActions = function() {
	if (this.loggedIn) {
		this.doLoggedInActions();
	} else {
		this.doLoggedOutActions();
	}
}

Sparcq.Session.prototype.promptIfNotLoggedIn = function(callback,custom_msg,is_alpha_window) {
	if (this.loggedIn) {
		return true;
	}
	var msg = custom_msg || 'You must be logged in to perform this action!';
	this.showLoginPrompt(msg);
	if (callback)
		this.onLoginQueue.push(callback);
	return false;
};

Sparcq.Session.prototype.updateLoginBox = function() {
	var el = jQuery('#login_status_box');
	var login_text = 'Do you want to save your ratings?';
	var extra_login_box = '';
	var link_text = null;
	var custom_login_text = jQuery('#custom_login_text',el);
	if (custom_login_text) {
		if (custom_login_text.html()) {
			login_text = custom_login_text.html();
		}
	}
	var custom_link_text = jQuery('#custom_link_text',el);
	if (custom_link_text) {
		if (custom_link_text.html()) {
			link_text = custom_link_text.html();
		}
	}
	if (el) {
		if (this.loggedIn) {
			el.html(extra_login_box + 'Welcome, <a href="/u/'+ SPARCQ.SESSION.getMemberId() +'">' + this.getUserData('name') + ' <img src="/images/icons/arrow_down.png" /></a> ');
			$('#profile_link').html('<a href="/en/profile">profile &laquo;</a>').show();
			$('#settings_link').html('<a href="/en/settings">settings &laquo;</a>').show();
			$('#logout_link').html(this.getLogoutHtml()).show();
		} else {
			el.html(extra_login_box + login_text + ' ' + this.getLoginHtml(link_text));
		}
	}
	this.addLoginBoxEvents();
};

Sparcq.Session.prototype.addLoginBoxEvents = function() {
	var self = this;
	$('#lbox_logout').click(function() {
		var el = jQuery(this);
		el.unbind('click');
		self.executeLogout();
		return false;
	});
	$('#lbox_login').click(function() {
		var el = jQuery(this);
		el.unbind('click');
		self.showLoginPrompt();
		return false;
	});
};

Sparcq.Session.prototype.getLogoutHtml = function() {
	return '<a id="lbox_logout" href="#">logout &laquo;</a>';
};
Sparcq.Session.prototype.getLoginHtml = function(login_text) {
	if (!login_text) {
		login_text = 'login';
	}
	return '<a id="lbox_login" href="#">' + login_text + '</a>';
};

Sparcq.Session.prototype.getUserData = function(prop_name) {
	if (!this.sessionData) return null;
	var usdata = this.sessionData['user'];
	if (usdata) {
		return usdata[prop_name];
	}
};

Sparcq.Session.prototype.getMemberId = function() {
	if (this.sessionData && this.sessionData.user) { 
		return this.sessionData.user.id;
	}
	return null;
}


Sparcq.Session.prototype.performAnonymousUserInit = function() {
	this.getProgress();
};

Sparcq.Session.prototype.getSessionKey = function() {
	if (this.sessionKey) return this.sessionKey;
	if (this.sessionData && this.sessionData['session_key']) {
		this.sessionKey = this.sessionData['session_key'];
		return this.sessionKey;
	}
};
Sparcq.Session.prototype.getSessionType = function() {
	return this.sessionType;
};
Sparcq.Session.prototype.getSessionUid = function() {
	return this.sessionUid;
};

Sparcq.Session.prototype.getToken = function() {
	if (this.sessionData && this.sessionData['token']) {
		return this.sessionData['token'];
	}
	return null;
};

Sparcq.Session.prototype.clearSessionData = function() {
	this.loggedIn = false;
	this.sessionKey = null;
	this.sessionType = null;
	this.seesionUid = null;
	this.storeSessionData('');
};

Sparcq.Session.prototype.getFbCookie = function(name) {
	if (this.fbApiKey && name) {
		return Sparcq.SQ.getOutsideCookie(this.fbApiKey + '_' + name);
	}
	return false;
}

Sparcq.Session.prototype.setFbCredentials = function() {	
	if (this.fbApiKey) {
		var session_key = this.getFbCookie('session_key');
		var uid = this.getFbCookie('user');
		if (session_key && uid) {	
			this.sessionKey = session_key;
			this.sessionUid = uid;
			this.sessionType = 'facebook';
		}
	}
};


Sparcq.Session.prototype.storeRating = function(cookie_name,item_name,val) {	
	var new_val = this.addToCookie(cookie_name,{
		entry_title: item_name,
		rating: val
	});
	return new_val;
}



Sparcq.Session.prototype.rateItem = function(val,item_name) {
	//SPARCQ.COMPONENTS.showMessage('start rating');
	//add to cookie no matter what
	var ck_to_use = (this.loggedIn) ? this.ratingUserCookie : this.ratingCookie;
	var cur_val = this.storeRating(ck_to_use,item_name,val);

	//SPARCQ.COMPONENTS.showMessage('rated ' + item_name + ' a ' + val);
	//SPARCQ.COMPONENTS.showMessage('recent ratings...');
	//var max_rs = 20;
	//for (var i=cur_val.length-1;(i>=0 && i >= (cur_val.length-max_rs)) ;i--) {
	//	SPARCQ.COMPONENTS.showMessage(cur_val[i].item + ': ' + cur_val[i].val);
	//}

	var self = this;
	this.currentRatingCount++;
	var crt = this.currentRatingCount;
	this.hideRatingResults();
	this.hideProgress();

	if (this.loggedIn) {
		var comment_textarea = jQuery('#item_comment');
		var text_val = '';
		if ( comment_textarea && comment_textarea.val() ) {
			text_val = comment_textarea.val().replace(/^\s+|\s+$/g,'');
			comment_textarea.val('');
		}
		SPARCQ.API.callMethod('topic.addRating', {
			params: {
				entry_title: item_name,
				rating: val,
				sparcq_member_id: this.getMemberId(),
				comment_text: text_val
			},
			onSuccess: function(ret) {
				self.handleRatingReturn(ret,crt);
			},
			onError: function(ret,id) {
				SPARCQ.COMPONENTS.showError('error rating item ' + id);
			}
		});
		if (text_val) {
			SPARCQ.TRACKING.trackComment(item_name);
		}
	} else {
		this.getRatingResults(item_name,val);
		this.getProgress();
	}

		
	if ( this.isSpoonfeeding() ) { 
		this.getNextItem();
	} else {
		// just clear the rated item value if not spoonfeeding
		 $('#currentItem').attr('alt', '').val('');
	}
}


Sparcq.Session.prototype.addToCookie = function(ck,obj) {
	var cur_val = this.getCookie(ck);
	cur_val.push(obj);
	if (cur_val.length > this.maxRatingsToStore) cur_val = cur_val.slice(1);
	var store_val = jQuery.toJSON(cur_val);
	Sparcq.SQ.setCookie(ck,store_val);
	return this.getCookie(ck);
};

Sparcq.Session.prototype.resetCookie = function(ck) {
	Sparcq.SQ.setCookie(ck,jQuery.toJSON([]));	
};

Sparcq.Session.prototype.getCookie = function(ck) {
	return Sparcq.SQ.getJSONCookie(ck,[]);
};

Sparcq.Session.prototype.executeRatingProgressFinished = function() {
	if (this.loggedIn) {
		this.resetCookie(this.ratingCookie);	
		this.showDashboardTeaser();
		if (SPARCQ.PAGE == 'main')
			Sparcq.SQ.redirect(Sparcq.SQ.uriFor('/en/share'));
	} else {
		this.promptIfNotLoggedIn(function () {
				Sparcq.SQ.redirect(Sparcq.SQ.uriFor('/en/share'));
			},
			"Now that we've learned a few things about you, login to get some recommedations!"
		);
	}
};

Sparcq.Session.prototype.showDashboardTeaser = function() {
	if (this.dashboardTeaser) {
		this.dashboardTeaser.show();
	} else {
		this.dashboardTeaser = jQuery("#dashboardTeaser");
	}
	if (!this.dashboardTeaser) return;
	var template_html = this.dashboardTeaser.html();	
	/*
	this.loginTeaser.html(Sparcq.SQ.parseHtml(
		template_html, {
			fb_login_link: this.getFbLoginFbml() + ''

	}));
	*/
	this.dashboardTeaser.show();
};


Sparcq.Session.prototype.showLoginTeaser = function() {
	if (this.loginTeaser) {
		this.loginTeaser.show();
	} else {
		this.loginTeaser = jQuery("#loginTeaser");
	}
	if (!this.loginTeaser) return;
	var template_html = this.loginTeaser.html();	
	this.loginTeaser.html(Sparcq.SQ.parseHtml(
		template_html, {
			fb_login_link: this.getFbLoginFbml() + ''

	}));
	this.loginTeaser.show();
};

Sparcq.Session.prototype.showAlphaPrompt = function(msg) {
	var self = this;
	if (!this.alphaPrompt) {
		this.alphaPrompt = $('#dialog');
		jQuery('.jqmClose_container',this.alphaPrompt).hide();
		this.alphaPrompt.jqm({
			modal: true,
			ajax: '/en/alpha_popup',
			target: 'div.jqmAlertContent',
			onHide: function(h) {
				h.w.hide();
				h.o.remove();
				self.addLoginBoxEvents();	
			}
		});
	}
	msg = msg || '';
	jQuery('.jqmCustomMessage',this.alphaPrompt).html(msg);	
	this.alphaPrompt.jqmShow(); 
}

Sparcq.Session.prototype.showLoginPrompt = function(msg) {
	var self = this;
	if (!this.loginPrompt) {
		this.loginPrompt = $('#dialog');
		this.loginPrompt.jqm({
			ajax: '/en/alpha_popup',
			target: 'div.jqmAlertContent',
			onHide: function(h) {
				h.w.hide();
				h.o.remove();
				self.addLoginBoxEvents();	
			}
		});
	}
	msg = msg || '';
	jQuery('.jqmCustomMessage',this.loginPrompt).html(msg);	
	this.loginPrompt.jqmShow(); 
}


Sparcq.Session.prototype.hideLoginPrompt = function() {
	if (!this.loginPrompt) return;
	this.loginPrompt.jqmHide(); 
}

Sparcq.Session.prototype.getProgress = function(total_ratings) {
	// for now just check what's in th cookie
	var count = null;
	if (total_ratings) {
		if (total_ratings >= 10) {
			this.executeRatingProgressFinished();
			return;
		} else {
			count = total_ratings;
		}
	} else {
		var cur_val = this.getCookie(this.ratingCookie);
		count = cur_val.length;
		if (count >= 10) {
			this.executeRatingProgressFinished();	
			return;
		}
		if (count < 1) {
			//nothing to show
			return;	
		}
	}

	var how_well = [
		'as well as our<br />second cousins<br />(not enough)',
		'as well as our<br />next-door neighbor',
		'as well as our<br />train schedule<br />(we\'re trying)',
		'as well as our<br />car mechanic',
		'as well as our<br />grocer',
		'as well as our<br />tax adviser',
		'as well as our<br />veterinarian<br />(getting warmer)',
		'as well as our<br />cell phone',
		'as well as our<br />brothers'
	];

	if (count >= 0 && count <= 10) {
		jQuery('#ratingProgress .ratingCopy').html(how_well[count-1]);
		jQuery('#progressBar').removeClass('main');
		jQuery('#progressBar').removeClass('rate');
		jQuery('#progressBar').removeClass('home');
		jQuery('#progressBar').removeClass('discover');
		for (var i = 10; i < 100; i+=10) {
			jQuery('#progressBar').removeClass('p' + i);
		}

		jQuery('#progressBar').addClass('p' + count*10);
	} 

	this.showProgress();
}

Sparcq.Session.prototype.showProgress = function() {

	
	$("#ratingProgress").fadeIn('slow');
}
Sparcq.Session.prototype.hideProgress = function() {
	$("#ratingProgress").hide();
}

Sparcq.Session.prototype.getNextItem = function(item,ignore_id) {
	$('#skipItem').unbind('click').fadeOut();

	if (item) {
		this.handleGetNextItem({
			title: item 
		});
	} else {
		if (this.spoonfedItems.length > 0) {
			var firstItem = this.spoonfedItems.pop();
			this.handleGetNextItem(firstItem);
			return;
		}
		var self = this;
		var params = {return_count: 10};
		if (this.getMemberId()) {
			params.sparcq_member_id = this.getMemberId()
		}

		SPARCQ.API.callMethod('user.getNextTopic', {
			params: params, 
			onSuccess: function(ret) {
				var list = new Array();
				for (i = 0; i < ret.response.result.topics.length; i++)
					list.push(ret.response.result.topics[i]);
				self.spoonfedItems = list;
				var firstItem = self.spoonfedItems.pop();
				self.handleGetNextItem(firstItem);
			},
			onError: function(ret,rt) {
				alert('error calling api for next topic');
			}
		}); 
	}
}

Sparcq.Session.prototype.handleRatingResults = function(ret,rated_value) {
	this.showRatingResults(ret.title, rated_value, ret.average);
}

Sparcq.Session.prototype.getRatingResults = function(item_name,val) {
	var self = this;

	SPARCQ.API.callMethod('topic.getDetail', {
		params: {
			entry_title: item_name 
		},
		onSuccess: function(ret) {
			var topic = ret.parsed_return;
			self.handleRatingResults(topic,val);
		},
		onError: function(ret,rt) {
			alert('error calling api for session data');
		}
	}); 

}

Sparcq.Session.prototype.hideRatingResults = function(item,val,avg) {	
		$("#ratingResponse").hide;
}

Sparcq.Session.prototype.showRatingResults = function(item,val,avg) {	
		if (avg == 'N/A') avg = val;
		$("#ratingResponseValue").text(val);
		$("#ratingResponseItem").html('<a href="/' + Sparcq.SQ.getWikiURI(item) + '">' + item + '</a>');
		$("#ratingResponseAvg").text(avg);
		$("#reRateLink").attr("title", item);
		$("#ratingResponse").fadeIn('slow');
}

Sparcq.Session.prototype.updateSharePageRecentRatings = function(topic) {
	SPARCQ.COMPONENTS.ratings.addRatedItemItem(topic,1,'top',function(el) {
		$(this).css('opacity', 0);
		$(this).slideDown('slow', function() {
			$(this).animate({'opacity': 1}, 'slow', function() {
				$('.sub.home .pastRatings .rating_item:last-child').fadeOut('slow',function() {
					$(this).remove();
				});
			});
		});
	});
}

Sparcq.Session.prototype.handleGetNextItem = function(ret) {
	// how long should the train take, in ms
	var duration = 500;
	var self = this;

	if (!ret || !ret.title) {
		return;
	}

	$('#currentItem_roll').attr('alt', ret.title).val(ret.title);

	function moveFields(negPos, duration) {
		$('#currentItem').animate({
			left: negPos
		}, duration);
		$('#currentItem_roll').animate({
			left: "0px"
		}, duration);
	}

	if ($('#currentItem').attr('alt') != '') {
		var fieldWidth = $('#currentItem').css('width');
		var negPos = "-" + fieldWidth;
		
		moveFields(negPos);		
		
		setTimeout(function() {
			$('#currentItem').attr('alt', ret.title).val(ret.title).css('left', '0px');
			$('#currentItem_roll').css('left', fieldWidth);			
		}, duration);

	} else {
		$('#currentItem').attr('alt', ret.title).val(ret.title)
	}

	$('#skipItem').fadeIn('fast', function () {
		$(this).click( function() {
			self.getNextItem();
			return false;
		});
	});
}

Sparcq.Session.prototype.storeTotalRatings = function(tr) {
	if (this.loggedIn && this.sessionData) {
		if (this.sessionData.user) {
			this.sessionData.user.total_ratings = tr;
			this.storeSessionData(this.sessionData);
		}
	}
};

Sparcq.Session.prototype.showAvatars = function(a) {
	// options
	var repeatMove = 3;
	var pauseDurat = 2500;
	var containerHolds = 4;
	var maxAvatars = 13;
	var currentAva = 0;

	if (a.length && a.length == 1 && a[0]['user_id'] == this.getMemberId()) {
		return;
	}

	if(a.length > maxAvatars) var numMoves = maxAvatars;
	else var numMoves = a.length;

	// build and set html
	var content = '';
	
	switch(SPARCQ.PAGE) {
		case 'share':
			// display scroller
			$('.avatarScroller').css({ 'display': 'block' });
			
			for	(var x = 0; x < numMoves; x++) {
				if (a[x]['user_id'] == this.getMemberId()) {
					continue;
				}
				if(currentAva < maxAvatars) {
					content += Sparcq.SQ.getUserLink('<img class="avatar" src="' + Sparcq.SQ.imageCachePath(a[x]['pic'] || '/images/layout/placeholders/userProfilePic_50x50.png')  + '" />',a[x]['user_id'],{},{title: a[x]['name']});
					currentAva++;
				}
			}
			
			$('#avatars').html(content).animate({ 'opacity': '1' }, 250);
		break;
		
		case 'main':
			// clear the current contents
			$('#topUsers').html('<div class="colTitle"></div><div class="frontTopUsers" style="margin:7px 0 0 0; "></div>');

			// modify top users to show peeps
			$('#topUsers .colTitle').html('peeps who like that');
			$('#justRated').animate({ 'width': '260px' }, 250);
			$('#topUsers').animate({ 'width': '250px' }, 250);
			
			for	(var x = 0; x < numMoves; x++) {
				if (a[x]['user_id'] == this.getMemberId()) {
					continue;
				}
				if(currentAva < maxAvatars) {
					content += Sparcq.SQ.getUserLink('<img class="avatar" src="' + Sparcq.SQ.imageCachePath(a[x]['pic'] || '/images/layout/placeholders/userProfilePic_50x50.png')  + '" />',a[x]['user_id'],{},{title: a[x]['name']});
					currentAva++;
				}
			}
			
			$('.frontTopUsers').html(content).animate({ 'opacity': '1' }, 250);
			
		break;
	}
	
	this.setupAvatars();
}

Sparcq.Session.prototype.handleRatingReturn = function(ret,ct) {
	if (ct != this.currentRatingCount) { 
		SPARCQ.COMPONENTS.showMessage('skip show rating because already processing another ' + ct + ' != ' + this.currentRatingCount);
		return;
	}
	if ( ret ) {
		var topic = ret.parsed_return;
		this.showRatingResults(topic.title,topic.rated_value,topic.average);
		this.getProgress(ret.response.result.extra.total_ratings);
		this.storeTotalRatings(ret.response.result.extra.total_ratings);
		jQuery('#userRatings').trigger('load',topic);
		if (SPARCQ.PAGE == 'share') {
			this.updateSharePageRecentRatings(topic);
			SPARCQ.COMPONENTS.loadSimilarUsers();
		}
		/* 
		probably throw this on the account page later
		if (ret.response.result.extra && ret.response.result.extra.total_ratings == 5) {
			this.showPermissionsPrompt();	
		}

		*/
		
		// to do: replace with dynamic grab of profile images slash links
		this.showAvatars(topic.recent_user_ratings);
	}
}

Sparcq.Session.prototype.tagAndReturn = function(entry_id,tag_name,callbacks) {
	var self = this;
	if (this.loggedIn) {
		SPARCQ.API.callMethod('topic.addTags', {
			params: {
				entry_id: entry_id,
				tag_text: tag_name,
				sparcq_member_id: this.getMemberId()
			},
			onSuccess: callbacks.success, 
			onError: callbacks.error 
		}); 
	}
}

Sparcq.Session.prototype.deleteRatingAndReturn = function(item_name,callbacks) {
	var self = this;
	//alert('delete ' + item_name);
	if (this.loggedIn) {
		SPARCQ.API.callMethod('topic.deleteRating', {
			params: {
				entry_title: item_name,
				sparcq_member_id: this.getMemberId()
			},
			onSuccess: callbacks.success, 
			onError: callbacks.error 
		}); 
	}
}

Sparcq.Session.prototype.rateAndReturn = function(item_name,val,callbacks) {
	var cur_val = this.storeRating(this.getRatingCookie(),item_name,val);
	var self = this;
	if (this.loggedIn) {
		SPARCQ.API.callMethod('topic.addRating', {
			params: {
				entry_title: item_name,
				rating: val,
				sparcq_member_id: this.getMemberId()
			},
			onSuccess: callbacks.success, 
			onError: callbacks.error 
		}); 
	}
}


Sparcq.Session.prototype.validateSession = function() {
	if (!this.loggedIn) return;
	
	var self = this;
	SPARCQ.API.callMethod('user.isValidSession', {
		params: {
			//default stuff will be passed with every api call... 
			sparcq_member_id: this.getMemberId()
		},
	
		onSuccess: function(ret) {
			if (ret && ret.response && ret.response.result) {
				if (ret.response.result.is_valid) {
					self.replenishSession(ret);
				} else {
					self.doSessionTimeout();
				}
			}
		},
		onError: function(ret,rt) {
			//#TODO - timeout only if actually received a valid response
		}
	}); 

}

Sparcq.Session.prototype.replenishSession = function(ret) {
};


