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


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

Sparcq.Components.prototype.init = function(args) {
	if (args) {
	}

	this.ratingLists = {};
	this.ratingBoxes = {};
	this.notificationWindow = {};
	this.userLists = {};
	this.commentLists = {};
	this.intervals = {};
	this.intervalTime = 7000;
	this.maxActiveTime = 60000 * 60;
	this.currentActiveTime = 0;
	this.storedDescriptions = {};
	this.storedDescriptionsLoad = {};
};

Sparcq.Components.prototype.retrieveWikiText = function(el,class_to_check) {
	el = jQuery(el);	
	el.attr('onmouseover',null);
	el = jQuery('.' + class_to_check,el);
	var desc_el = jQuery('.desc_text',el);
	if (desc_el && desc_el.length) {
		return false;
	}
	var title = jQuery('span.the_title',el).html(); 
	var loading_html = "<div class='desc_text'>loading description, this may take a moment...</div>";
	if (this.storedDescriptions[title]) {
		el.html(this.storedDescriptions[title]);
		el.show();
		return false;
	}
	el.html(loading_html);
	el.show();
	var matching_host = SPARCQ.HOSTNAME;
	var self = this;
	SPARCQ.API.getWikiEntry(title, {
		onSuccess: function(ret) {
		
			var xml_res = ret.parse.text['*'];
			//remove images before we embed...
			xml_res = xml_res.replace(/<img[^>]+>/gi,"");

			el.html(xml_res);	

			var summ = undefined;
			jQuery('p',el).each(function() {
				if (summ) return;
				var cur_p = jQuery(this);
				var its_p = cur_p.parent();
				if (its_p && its_p.hasClass(class_to_check) ) {
					summ = cur_p;	
				}
			});
			
			jQuery('a',summ).each(function() {
				if (this.href) {
					if ( this.href.match(matching_host) ) {
						var new_href = this.href;
						if ( new_href.match(/\/wiki\/([a-z])+:(.*)/i) ) {
							this.href = new_href.replace(matching_host,'http://en.wikipedia.org');
						} else if (new_href.match(/wiki/) ) {
							this.href = new_href.replace("/wiki/","/");
						} else {
							jQuery(this).html("");
							this.href = new_href.replace(matching_host,'http://en.wikipedia.org');
						}
					}
				}
			});

			self.storedDescriptions[title] = '<div class="desc_text"><span class="the_title">' + title + "</span>" + summ.html() + "</div>";
			el.html(self.storedDescriptions[title]);
		}
	});

	return false;
};

Sparcq.Components.prototype.statusUpdate = function(message) {
	$('#ajax_message').html(message);
	$('#ajax_bar').fadeIn('slow', function(){
		$('#ajax_bar').fadeTo(5000, 1, function(){
			$('#ajax_bar').fadeOut('slow');
		});
	});
}

Sparcq.Components.prototype.getYourRatingItemHtml = function(item) {
		return Sparcq.SQ.parseHtml('' +
		'<div class="itemContainer">' + 
		'	<div class="item">' +  
		'		<div class="boowhoo_large bw_container">' +
		'			<div class="boowhoo_large bwl %%item_rating_color_class%%">%%item_rating%%</div>' +
		'		</div>' +
		'		<div class="desc_container">' +
		'			<div class="title">%%item_page_link%%</div>' +
		'			<div class="statistics"><span class="average">%%item_average%%</span> average / %%item_total_ratings%%</div>' +
		'			<div class="rate"><img src="' + Sparcq.SQ.uriFor('/images/layout/interact/buttons/re_rate.png') + '" alt="" /><input type="hidden" value="%%item_name%%" /></div>' +
		'		</div>' +
		'		<div class="clearBoth"></div>' +
		'	</div>' +
		'</div>',{
			//item_name: item.name,
			item_rating: item.rating,
			item_total_ratings: Sparcq.SQ.getCountDisplay('rating',item.total_ratings),
			item_average: item.average_rating,
			item_page_link: Sparcq.SQ.getWikiLink(item.name,'/' + item.name),
			item_name: item.name,
			item_rating_color_class: this.getItemRatingColorClass(item.rating)
		});
};

Sparcq.Components.prototype.getRatingItemHtml = function(item) {
	if(item.average_rating == '10.0') { 
		item.average_rating = '10 ';
	}

	return Sparcq.SQ.parseHtml('<div class="frontRatingContainer">' + 
			'<span class="frontItemRating">%%item_rating%%</span><span class="frontItem"><a href="%%item_detail_page%%">%%item_name%%</a></span> ' + 
			'<span class="rateParen">(</span> ' +
			'<a class="rateThis" href="#">rate' +
			'<div class="item_name" style="display:none;">%%item_name%%</div>' +
			'</a>' +
			' <span class="rateParen">)</span>' +
			'</div>',{
				item_name: item.name,
				item_rating: item.average_rating,
				item_detail_page: Sparcq.SQ.getWikiURI('/'+item.name)
			});
	
};

Sparcq.Components.prototype.handleRateListLoad = function(valid_ret,id) {
	var rl = this.ratingLists[id];
	if (!this.ratingLists[id]) {
		//error out
	}
	var ret	= valid_ret.parsed_return;
	var ris = [];
	var counter = 0;
	if (!ret.length) {
		jQuery('.ratingItems',rl.obj).html('no items yet!');
	}
	if (rl.item_list) {
		//return;
	}
	for (var i=0;i<ret.length;i++) {
		ris.push(ret[i]);
		if (i == 0) {
			jQuery('.ratingItems',rl.obj).html(this.getRatingItemHtml(ret[i]));
		} else {
			jQuery('.ratingItems',rl.obj).append(this.getRatingItemHtml(ret[i]));
		}
	}
	//add rate events
	jQuery('.ratingItems .rateThis',rl.obj).each(function() {
		jQuery(this).unbind('click');
		jQuery(this).click(function() { 
			var item_name = jQuery('div.item_name', this).text();
			if (SPARCQ.PAGE == 'share' || SPARCQ.PAGE == 'main') {
				SPARCQ.SESSION.getNextItem(item_name);
			} else {
				Sparcq.SQ.redirect(Sparcq.SQ.uriFor('/en/share',{},'rate:' + item_name));
			}
		});
	});


	rl.loading = false;
	//this.itemLists[id] = {
	//	items: ris,
	//	interval_id: 
	//}
	rl.item_list = ris;
	//if (rl.interval_id) return;
	var self = this;
	if (this.currentActiveTime < this.maxActiveTime) {
		rl.interval_id = setTimeout(function() {
			self.initSiteRateList('just_rated',id);
		},this.intervalTime);
		this.currentActiveTime += this.intervalTime;
	} else {
	}
}

Sparcq.Components.prototype.handleUserRateListLoad = function(valid_ret,id) {
	var rl = this.ratingLists[id];
	if (!this.ratingLists[id]) {
		//error out
	}
	var ret	= valid_ret.parsed_return.topics;
	var ris = [];
	var counter = 0;
	if (!ret || !ret.length) {
		jQuery('.ratingItems',rl.obj).html('no ratings yet!');
		//return;
	}

	for (var i=0;i<ret.length;i++) {
		ris.push(ret[i]);
		if (i == 0) {
			jQuery('.ratingItems',rl.obj).html(this.getYourRatingItemHtml(ret[i]));
		} else {
			jQuery('.ratingItems',rl.obj).append(this.getYourRatingItemHtml(ret[i]));
		}
	}
	//add rate events
	var self = this;
	jQuery('.ratingItems .itemContainer',rl.obj).each(function() {
		self.addRateEventLinkToHome(jQuery(this));	
	});
	
	if (ris.length) {
		var rrl = jQuery('.recentRatingsLink');
		if (rrl) {
			rrl.html(Sparcq.SQ.parseHtml(rrl.html(),{
				recent_ratings_url: Sparcq.SQ.userURL(SPARCQ.SESSION.getMemberId(),{ anchor:  'recent_ratings' })
			}));
			rrl.show();
		}
	}

	rl.loading = false;
}

Sparcq.Components.prototype.addUserItem = function(vars,container) {
	var new_user_item = jQuery('.default_user_list_display_item',container).clone();
	new_user_item.appendTo(container);
	new_user_item.removeClass('default_user_list_display_item');
	
	jQuery($('.loading')).hide();

	new_user_item.show();
	new_user_item.html(Sparcq.SQ.parseHtml(new_user_item.html(),{
		user_name: vars.name,
		user_link: Sparcq.SQ.getUserLink(vars.name,vars.id),
		user_id: vars.id,
		user_pic: '<img class="avatar" src="' + Sparcq.SQ.imageCachePath(vars.pic || '/images/layout/placeholders/userProfilePic_25x25.png') + '" />'
	}));
};

Sparcq.Components.prototype.handleUserListLoad = function(valid_ret,id) {
	var rl = this.ratingLists[id];
	if (!this.ratingLists[id]) {
		//error out
	}
	var ret	= valid_ret.parsed_return;
	if (!ret.length) {
		jQuery('.frontTopUsers',rl.obj).html('No users yet!');	
	}
	for (var i=0;i<ret.length;i++) {
		this.addUserItem(ret[i],rl.obj);
	}	

	rl.loading = false;
}


Sparcq.Components.prototype.showRatingList = function() {
	this.comments.hide();
	this.ratings.show();
};



Sparcq.Components.prototype.showCommentList = function() {
	this.ratings.hide();	
	this.comments.show();
};

Sparcq.Components.prototype.loadComments = function(comment_type,id) {
	
	this.comments = new Sparcq.Comments({
		start_hidden: true,
		comment_type: comment_type,
		id: id
	});

	var self = this;
	$('#ratings_comments_box').load(function(evt,box_type) {
		if (!box_type) {
			self.showCommentList();
		} else {
			if (box_type == 'ratings') {
				self.showRatingList();
			} else {
				self.showCommentList();
			}
		}
	});


};



Sparcq.Components.prototype.initRatingsCommentsBox = function(type) {
	//if (type && type == 'item') {
	//	this.initRecentUserRatingsList(jQuery('.pastUserRatings'));
	//} else {
		this.initRecentRatingsList(jQuery('.pastRatings'));
		this.loadComments('user',SPARCQ.UID);
	//}
};

Sparcq.Components.prototype.addRatedItemDiscover = function(vars,clone_item,remove_class) {
	var new_rate_item = clone_item.clone();
	new_rate_item.appendTo(jQuery('#discover_list'));
	new_rate_item.removeClass(remove_class);

	var template_html = new_rate_item.html();
	new_rate_item.html(Sparcq.SQ.parseHtml(
		template_html,{
			total_ratings: Sparcq.SQ.getCountDisplay('rating',vars.total_ratings),
			average_rating: vars.average_rating,
			//rating: vars.rating,
			//item_rating_color_class: this.getItemRatingColorClass(vars.rating),
			title_link: Sparcq.SQ.getWikiLink(vars.name,'/' + vars.name),
			item_name: vars.name
		}));

	this.addRateInPlaceEvent(new_rate_item,true);
	new_rate_item.show();
	return new_rate_item;
};

Sparcq.Components.prototype.initRecentUserRatingsList = function(el,topic) {
	this.ratings = new Sparcq.Ratings({
		el: el,
		topic: topic,
		type: 'user_ratings'
	});
};

Sparcq.Components.prototype.addRatedItemRecent = function(vars,clone_item,list_el,remove_class,unshift) {
	var new_rate_item = clone_item.clone();
	if (unshift) {
		new_rate_item.prependTo(list_el);
	} else {
		new_rate_item.appendTo(list_el);
	}
	new_rate_item.removeClass(remove_class);

	var template_html = new_rate_item.html();
	new_rate_item.html(Sparcq.SQ.parseHtml(
		template_html,{
			total_ratings: Sparcq.SQ.getCountDisplay('rating',vars.total_ratings),
			average_rating: vars.average_rating,
			rating: vars.rating,
			item_rating_color_class: this.getItemRatingColorClass(vars.rating),
			title_link: Sparcq.SQ.getWikiLink(vars.name,'/' + vars.name)
		}));

	this.addRateInPlaceEvent(new_rate_item);
	new_rate_item.show();
	return new_rate_item;
};


Sparcq.Components.prototype.handleRecentRatingListLoad = function(valid_ret,id) {
	
	var rl = this.ratingLists[id];
	if (!this.ratingLists[id]) {
		//error out
	}
	var ret	= valid_ret.parsed_return.topics;
	var ris = [];
	var counter = 0;
	var list_el = jQuery('#userRatings');
	var clone_el = jQuery('.default_user_rating_rate',list_el);
	


	for (var i=0;i<ret.length;i++) {
		ris.push(ret[i]);
		var new_item = this.addRatedItemRecent(ret[i],clone_el,list_el,'default_user_rating_rate');
	}
	jQuery('#userRatings').show();
	//add rate events
	/*
	jQuery('.ratingItems .rateThis',rl.obj).each(function() {
		jQuery(this).click(function() { 
			SPARCQ.SESSION.getNextItem(jQuery(this).attr('title'));
		});
	});
	*/
	rl.loading = false;
	
	//handle updates to push in new ratings
	var self = this;
	$('#userRatings').load(function(evt,topic) {
		var new_item = self.addRatedItemRecent({
			average_rating: topic.average,
			total_ratings: topic.total_ratings,
			rating: topic.rated_value,
			name: topic.title
		},clone_el,list_el,'default_user_rating_rate',true);
	});

};



Sparcq.Components.prototype.setupRecentRatingsList = function(el) {
	
	var rl = { 
		obj: el,
		loading: true
	};
	var id = el.attr('id');
	this.ratingLists[id] = rl;


	var self = this;

	SPARCQ.API.callMethod('user.getRecentRatings', {
		params: {
			sparcq_member_id: SPARCQ.SESSION.getMemberId(),
			return_count: 7
		},
		onSuccess: function(ret) {
			self.handleRecentRatingListLoad(ret,id);
			//self.showMessage('loaded a rated list component');
		},
		onError: function(ret,id) {
			self.showError('error getting user recent ratings');
		}
	});
};

Sparcq.Components.prototype.doTagSearch = function(q,args) {
	var success_callback = args.onSuccess;
	var error_callback = (args.onError) ? args.onError : this.throwError;

	SPARCQ.API.callMethod('user.searchRecommendedTopicTags', {
		params: {
			sparcq_member_id: SPARCQ.SESSION.getMemberId(),
			q: q,
			return_count: 20
		},
		onSuccess: function(resp,rt_string) {
			if (resp && resp.response.result) {
				resp = resp.response.result.tags;
			}
			success_callback.call(this,resp);
		},
		onError: function(error_obj,rt_string) {
			error_callback.call(this,{
				error_obj: error_obj,
				return_type: rt_string,
				request_params: { q: q }
			});
		}
	});
}

Sparcq.Components.prototype.initFilter = function(type) {
	var self = this;
	var textDelay = 2000;

	switch(type) {
		case 'discover':
			$('.slider.range.average').slider({
				animate: true,
				range: true,
				values: [0, 100],
				min: 0,
				step: 5,
				max: 100,
				slide: function(e, ui) {
					$('.current.average').html(ui.values[0]/10 + ' - ' + ui.values[1]/10);
				},
				change: function(e, ui) {
					self.ratings.filterRecommendationsBy('average_rating', ui.values[0] + ',' + ui.values[1]);
				}
			});
			
			$('.slider.range.popularity').slider({
				animate: true,
				range: true,
				values: [0, 100000000],
				min: 0,
				max: 100000000,
				slide: function(e, ui) {
					$('.current.popularity').html(ui.values[0] + ' - ' + ui.values[1]);
				},
				change: function(e, ui) {
					self.ratings.filterRecommendationsBy('total_ratings',ui.values[0] + ',' + ui.values[1]);
				}
			});

			jQuery('.filter input[name=name]')
				.data('timeout', null)
				.keyup(function(evt){
					var textField = this;

					clearTimeout(jQuery(this).data('timeout'));
					if (evt.keyCode == 13) {
						evt.preventDefault();
						self.ratings.filterRecommendationsBy(textField.name,jQuery(this).val());
					}
					else {
						jQuery(this).data(
							'timeout',
							setTimeout(
								function() {
									self.ratings.filterRecommendationsBy(textField.name,jQuery(textField).val());
								},
								textDelay
								)
							);
					}
				})
				.blur(function() {
					clearTimeout(jQuery(this).data('timeout'));
					self.ratings.filterRecommendationsBy(this.name,jQuery(this).val());
				})
				.val('');

			jQuery('.filter input[name=tags]').autocomplete(function (ret) {
					self.doTagSearch(this,ret);
				},
				{
					delay: 400,
					formatItem: function(row,position,listSize,searchTerm) {
						return row ? row.text + ' (' + row.number_of_entries + ' entries)' : '';
					},
					formatResult: function(row,position,listSize,searchTerm) {
						return row ? row.text : '';
					},
					max: 20,
					minChars: 3,
					multiple: true,
					mustMatch: true,
					selectFirst: true
			}).update(function() {
				self.ratings.filterRecommendationsBy('tags',jQuery('.filter input[name=tags]').val());
			});
		break;
	}
};

Sparcq.Components.prototype.initRecentRatingsList = function(el) {


	this.ratings = new Sparcq.Ratings({
		el: el,
		type: 'item_ratings'
	});

		
};

Sparcq.Components.prototype.initSharePageRecentRatingsList = function(el) {
	this.ratings = new Sparcq.Ratings({
		el: el,
		type: 'item_ratings',
		numPerPage: 5,
		sort_by: 'cr_date DESC'
	});
};

Sparcq.Components.prototype.initUserRateList = function(list_type,id) {
	var self = this;

	SPARCQ.API.callMethod('user.getRecentRatings', {
		params: {
			sparcq_member_id: SPARCQ.SESSION.getMemberId(),
			return_count: 6,
			sort_by: 'cr_date DESC'
		},
		onSuccess: function(ret) {
			self.handleUserRateListLoad(ret,id);
			//self.showMessage('loaded a rated list component');
		},
		onError: function(ret,id) {
			self.showError('error getting user recent ratings');
		}
	}); 

};

Sparcq.Components.prototype.initSiteRateList = function(list_type,id) {
	var self = this;
	SPARCQ.API.callMethod('site.getTopList', {
		params: {
			list_type: list_type 
		},
		onSuccess: function(ret) {
			self.handleRateListLoad(ret,id);
			//self.showMessage('loaded a rated list component');
		},
		onError: function(ret,id) {
			self.showError('error getting site top list');
		}
	}); 

}

Sparcq.Components.prototype.initRecommendationList = function(el) {
	
	this.ratings = new Sparcq.Ratings({
		el: el,
		type: 'recommendation_list',
		numPerPage: 10,
		showPagingResults: true
	});


};

Sparcq.Components.prototype.initUserList = function(el) {
	var rl = { 
		obj: el,
		loading: true
	};
	var id = el.attr('id');
	this.ratingLists[id] = rl;
	

	var self = this;
	SPARCQ.API.callMethod('site.getTopUsers', {
		onSuccess: function(ret) {
			self.handleUserListLoad(ret,id);
			SPARCQ.SESSION.setupAvatars();
			//self.showMessage('loaded a rated list component');
		},
		onError: function(ret,id) {
			self.showError('error getting site top users');
		}
	});
};

Sparcq.Components.prototype.initRateList = function(el) {
	var rl = { 
		obj: el,
		loading: true
	};
	var id = el.attr('id');
	this.ratingLists[id] = rl;
	
	switch(id) {
		case 'mostAdored':
			this.initSiteRateList('most_adored',id);
		break;
		case 'justRated':
			this.initSiteRateList('just_rated',id);
		break;
	}
	
};

Sparcq.Components.prototype.initLoggedInRateList = function(el) {
	var rl = { 
		obj: el,
		loading: true
	};
	var id = el.attr('id');
	this.ratingLists[id] = rl;
	
	switch(id) {
		case 'profileRecentRatings':
			this.initUserRateList('profile_recent_ratings',id);
		break;
	}
	
};


Sparcq.Components.prototype.loadTopicPageComponents = function(topic) {
// Commented out by JK
//	jQuery('#item_detail_title').html(topic.title);
//	jQuery('#item_detail_container').html(topic.summary);
	this.loadComments('topic',topic.topic_id);
	//this.handleRatingListLoadTEMP();
	this.initRecentUserRatingsList(jQuery('.pastUserRatings'),topic);
	this.currentTopic = topic;
	this.initSidebarItemDetail();
};

Sparcq.Components.prototype.initSidebarItemDetail = function(topic) {
	if (!topic) {
		if (this.currentTopic) { 
			topic = this.currentTopic;
		} else {
			return;
		}
	} 
	this.initSidebarItemDetailRatingBox(topic);
};



Sparcq.Components.prototype.initTagEvents = function(topic) {
	var topic = topic || this.currentTopic;
	if (!topic) return;
	var th = jQuery('.tags');
	var tal = jQuery('.tag_add_link',th);
	var tef = jQuery('.tag_enter_fields',th);
	var ts = jQuery('.tag_submitting',th);
	var tl = jQuery('.tagList',th);
	tal.click(function() {
		tal.hide();
		tef.show();
		return false;
	});

	jQuery("span[class='tag_del']").each(
		function() {
			var member_id = SPARCQ.SESSION.getMemberId();
			var pieces = this.id.split(/\-/);
			var mem_id = pieces[1];
			var tag_id = pieces[2];
			if ( member_id == mem_id ) {
				jQuery(this).html("<div class='delete'><a class='tag_delete' id='" + tag_id + "' href='#'>[X]</a></div>");
				// Put in a delete box for the users who can delete their own tags
				jQuery("a[class='tag_delete']").live("click", deleteTag);
			}
		}
	);

	function deleteTag(tag_element) {
		var tag_id = tag_element.target.id;
		SPARCQ.API.callMethod('topic.deleteTags', {
			params: {
				sparcq_member_id: SPARCQ.SESSION.getMemberId(),
				entry_id: SPARCQ.TOPIC_ID,
				tag_id: tag_id
			},
			onSuccess: function(ret) {
				finish_delete_tag(tag_id);
			},
			onError: function(ret) {
				self.showError('error deleting tag');
			}
		});
	}


	function create_tag_and_or_update_events(tag_name, tag_id, total_tagged) {
		var found = 0;
		var tag_multiplier = parseFloat(jQuery('#tag_multiplier').html());
		var tag_to_update = null;
		jQuery('.tag_holder',tl).each(function() {
			var tag_there_name = jQuery('a', jQuery(this));
			if (tag_there_name) {
				if (tag_there_name.html() == tag_name) {
					//only update because already there...
					found = 1;
					tag_to_update = jQuery(this);
				}
			}
		});
		if (!found) {
			tag_to_update = jQuery('.default_tag_holder',tl).clone();
			tag_to_update.removeClass('default_tag_holder');
			tag_to_update.addClass('tag_holder');
			tag_to_update.prepend('<span id="tag-' + SPARCQ.SESSION.getMemberId() + '-' + tag_id + '" class="tag_del"><div class="delete"><a class="tag_delete" id="' + tag_id + '" href="#">[X]</a></div></span>');
			jQuery('.name', tag_to_update).html(Sparcq.SQ.getLink(tag_name,'/en/tag',{ t: tag_name}));
			jQuery('.count', tag_to_update).html(total_tagged);
			jQuery('.bg',tag_to_update).css('width', Math.ceil(total_tagged * tag_multiplier) + '%');
			tag_to_update.appendTo(tl);
			tag_to_update.show();
			// Put in a delete box for the users who can delete their own tags
			jQuery("a[class='tag_delete']").live("click", deleteTag);
		}
		if (!tag_to_update) return;
	}

	function finish_add_tag(tag_name,ret) {
		ts.hide();
		tal.show();
		create_tag_and_or_update_events(tag_name, ret.response.result.tag_id,ret.response.result.total_tagged);
		jQuery('input:first',tef).val('');
	}

	// Since we don't want to reload the page, hide the tag we just deleted (after deleting it)
	function finish_delete_tag(tag_id) {
		jQuery("#tag-" + SPARCQ.SESSION.getMemberId() + "-" + tag_id).parent().hide();
	}
	
	function add_tag() {
		if (!SPARCQ.SESSION.promptIfNotLoggedIn(function() { add_tag(); }) ) {
			return false;
		}
		var tag_name = jQuery('input:first',tef).val();
		if (!tag_name) {
			alert('please enter some text!');
			return false;
		}
		tef.hide();
		ts.show();
		SPARCQ.SESSION.tagAndReturn(topic.topic_id,tag_name,{
			success: function(ret) { finish_add_tag(tag_name, ret) },
			error: function(ret) {
				alert('Failed to tag item!');
				ts.hide();
				tal.show();
			}
		});
		return false;
	}

	jQuery('.tag_holder',tl).each(function() {
		var tag_item = jQuery(this);
		//add delete event here..
	});

	SPARCQ.API.initOpenSearchElement(jQuery('input:first',tef));
	
	jQuery('input:last',tef).click(function(){
		return add_tag();
	});
};

Sparcq.Components.prototype.initSidebarItemDetailRatingBox = function(topic) {
	/*
	this.handleSidebarItemDetailRatingBox({
		name: topic.title,
		average_rating: 7.8,
		predicted_rating: 8.7,
		item_rating_color_class: this.getItemRatingColorClass(7.8)
	});
	*/

	var self = this;
	SPARCQ.API.callMethod('topic.getPredictedRating', {
		params: {
			entry_id: topic.topic_id,
			sparcq_member_id: SPARCQ.SESSION.getMemberId() 
		},
		onSuccess: function(ret) {
			var topic = ret.parsed_return;
			self.handleSidebarItemDetailRatingBox(topic);
		},
		onError: function(ret,rt) {
			alert('error loading topic prediction');
		}
	});
};

Sparcq.Components.prototype.loadAccount = function() {	
	this.account = new Sparcq.Account({
	});	
	this.account.loadAccount();
};

Sparcq.Components.prototype.loadSimilarUsers = function() {
	
	if (!this.similarUsers) {
		this.similarUsers = new Sparcq.SimilarUsers({
		});
	}
};

Sparcq.Components.prototype.loadTrustGuestimate = function() {

	if (!this.trustGuestimate) {
		this.trustGuestimate = new Sparcq.TrustGuestimate({
		});
	}
	this.trustGuestimate.loadSimilarUsers( 1 );
};

Sparcq.Components.prototype.handleSidebarItemDetailRatingBox = function(ret) {
	var sb = $('#sidebar');
	var rating_box = ('#rating_box_item_detail',sb);

	var rating_verb = 'rate';
	var prediction = (ret.prediction) ? ret.prediction : {};	
	if (prediction.already_voted) {
		rating_verb = 're-rate';
	}
	if (typeof(prediction.predicted_rating != 'undefined')) {
		prediction.predicted_rating = Math.round(prediction.predicted_rating * 100) / 100;
	}
	var template_html = rating_box.html();

	rating_box.html(Sparcq.SQ.parseHtml(
		template_html, {
			rating_verb: rating_verb,
			item_name: ret.title,
			predicted_rating: (prediction.predicted_rating || 'N/A'),
			average_rating: ret.average || 'N/A',
			item_rating_color_class: this.getItemRatingColorClass(ret.average || 5) 
	}));

	if (prediction.already_voted) {
		//jQuery('.rateBox .rate',rating_box).html('');
		jQuery('.predict',rating_box).html('You rated ' + prediction.user_rating );
		//jQuery('.predict',rating_box).hide();
	}

	SPARCQ.SESSION.setupRatingBoxItemProfile();
	sb.show();
	this.initTagEvents();
};

Sparcq.Components.prototype.loadTopic = function(topic_name) {
	var self = this;
	SPARCQ.API.callMethod('topic.getDetail', {
		params: {
			entry_title: topic_name 
		},
		onSuccess: function(ret) {
			var topic = ret.parsed_return;
			self.handleLoadTopic(topic);
		},
		onError: function(ret,rt) {
			alert('error loading topic');
		}
	}); 


};

Sparcq.Components.prototype.handleLoadUserDetails = function(user) {
	this.handleLoadUserDetailsMain(user);
	this.handleLoadUserDetailsSidebar(user);
};

Sparcq.Components.prototype.getItemRatingColorClass = function(rating) {
	return 'bwl_' + Sparcq.SQ.strPadLeft(String(Math.round(rating)),2,'0');
}


Sparcq.Components.prototype.addRateEventLinkToHome = function(new_rate_item) {
	var rate_holder = jQuery('.rate',new_rate_item);
	var rate_img = jQuery('img',rate_holder);
	rate_img.click(function() {
		var item_name = jQuery('input',rate_holder).val();
		Sparcq.SQ.redirect(Sparcq.SQ.uriFor('/en/share',{},'rate:' + item_name));
	});
}

Sparcq.Components.prototype.addRateInPlaceEvent = function(new_rate_item,hide_on_rate) {
	jQuery(new_rate_item).each(function() {
		var rate_holder = jQuery('.rate',jQuery(this));
		var rate_img = jQuery('img',rate_holder);
		var cur_item = jQuery(this);
		rate_img.click(function() { 
			//SPARCQ.SESSION.getNextItem(jQuery(this).attr('title'));
			//var rh = rate_img.html();
			rate_img.hide();
			//init rating scale
			var clone_rb = $('.rating_container_for_dynamic_support').clone();
			clone_rb.appendTo(rate_holder);
			clone_rb.removeClass('rating_container_for_dynamic_support');
			clone_rb.show();
			
			function ripe_handleRateItemCancel(ret) {
				clone_rb.remove();
				rate_img.show();
			}
			
			function ripe_handleRateItemError(ret) {
				clone_rb.remove();
				rate_img.show();
				alert('Failed to Rate Item');
			}
			
			function ripe_handleRateItem(ret) {
				if (hide_on_rate) {			
					cur_item.fadeOut('slow');
				} else {
					rate_img.attr('src',rate_img.attr('src').replace('/rate.png','/re_rate.png'));
					clone_rb.remove();
					rate_img.show();
				}
			}

			$('.rateOptionItemP',clone_rb).click( function() {
				var rating = Number($(this).attr('id').substring(1,3) + '.' + $(this).attr('id').substring(3));
				var item_name = jQuery('input',rate_holder).val();
				clone_rb.html('rating item...');
				if (rating && item_name) {
					SPARCQ.SESSION.rateAndReturn(item_name,rating,{
						success: ripe_handleRateItem,
						error: ripe_handleRateItemError 
					});
				} else {
					ripe_handleRateItemError();
				}
			});

			$('.rate_cancel',clone_rb).click( function() {
				ripe_handleRateItemCancel();
				return false;
			});
		});
	});

};


Sparcq.Components.prototype.handleLoadUserDetailsMain = function(user) {
	var el = jQuery('#user_profile_main_detail');
	var template_html = el.html();

	el.html(Sparcq.SQ.parseHtml(
		template_html, {
			user_name: user.name,
			//profile_info: (user.description) ? user.description : ' ', 
			//trendsetter_link: Sparcq.SQ.getLink(user.trendsetter_rating,'#'),
			//user_affected_count: user.total_influence.user_affected_count,
			//user_affected_description: user.total_influence.description,
			user_join_date: user.member_since.readable_date,
			user_since_duration: user.member_since.since
			//trust_rating: user.trust_rating.pct + '%',
			//trust_rating_description: user.trust_rating.description
	}));
	el.show();
};

Sparcq.Components.prototype.handleLoadUserDetailsSidebar = function(user) {
	var el = jQuery('#sidebar');
	var pic = jQuery('.profile_picture', el);
	if (user.picture) {
		pic.html('<img src="' + user.picture + '" />');
	}
	var template_html = el.html();
	el.html(Sparcq.SQ.parseHtml(
		template_html, {
			user_name: user.name,
			lifetime_ratings: user.total_ratings,
			total_comments: user.total_comments,
			facebook_link: 'http://www.facebook.com/profile.php?id=' + user.handle
	}));
	el.show();
};

Sparcq.Components.prototype.handleDynamicUserDetails = function(user) {
	var el = jQuery('#user_dynamic_details');
	var template_html = el.html();
	
	if (SPARCQ.SESSION.getMemberId() && SPARCQ.SESSION.getMemberId() != SPARCQ.UID) {
		var count = user.items_in_common;
		el.html(Sparcq.SQ.parseHtml(
			template_html, {
				trust_rating: user.trust_rating.pct + '%',
				trust_rating_description: user.trust_rating.description,
				items_in_common: Sparcq.SQ.getCountDisplay('item',count) + ' in common with you'
		}));
		// $('#user_dynamic_details_PL').css('display', 'none');
		$('#user_dynamic_details_labels').css('display', 'block');
		el.show();
	} else {
		el.html('');
		// $('#user_dynamic_details_PL').css('display', 'none');
	}

	for (var network in user.social) {
		jQuery('#social ul.' + network).html(this.getSocialProfileLinksHtml(user.social[network]));
		jQuery('#social .socialSection.' + network).show();
	}
	jQuery('#social').show();

	SPARCQ.FB.actionOnLoginStatus(function(uid) {
		SPARCQ.SOCIAL.fbFlag = true;
	});

    //SPARCQ.JOB.doJobs();
};

Sparcq.Components.prototype.getSocialProfileLinksHtml = function ( links ) {
    if ( !links ) {
        return '';
    }
    var html = '';
    for ( i = 0; i < links.length; i++ ) {
        var link = links[i];
        html += "<li" +
            ( link.className ? " class=\"" + link.className + "\"" : "" ) +
			"> &middot; " +
            "<a href=\"" + link.href + "\"" +
            ( link.onClick ? " onClick=\"" + link.onClick + "\"" : "" ) + 
			//( link.target ? " target=\"" + link.target + "\"" : "" ) +
			" target=\"_blank\"" +
			">" +
            link.text +
            "</a></li>\n";
    }
    return html;
}


Sparcq.Components.prototype.initUserDetails = function() {
	var self = this;
	SPARCQ.API.callMethod('user.getDetail', {
		params: {
			uid: SPARCQ.UID
		},
		onSuccess: function(ret) {
			var user = ret.parsed_return;
			self.handleLoadUserDetails(user);
			//self.handleLoadTopic(topic);
		},
		onError: function(ret,rt) {
			alert('error loading user');
		}
	});
};

Sparcq.Components.prototype.initDynamicUserDetails = function() {
	var self = this;
	SPARCQ.API.callMethod('user.getDetail', {
		params: {
			uid: SPARCQ.UID,
			sparcq_member_id: SPARCQ.SESSION.getMemberId(),
			return_fields: 'trust_rating,member_since,items_in_common,links'
		},
		onSuccess: function(ret) {
			var user = ret.parsed_return;
			self.handleDynamicUserDetails(user);
			//self.handleLoadTopic(topic);
		},
		onError: function(ret,rt) {
			alert('error loading user');
		}
	});
};

Sparcq.Components.prototype.showError = function(msg,ht) {
	if (!this.notificationWindow.showError) {
		var self = this;
		setTimeout(function() {self.showError(msg); },2000);
		return;
	}
	this.notificationWindow.showError(msg,ht || 5);
}

Sparcq.Components.prototype.showMessage = function(msg,ht) {
	if (!this.notificationWindow.showMessage) {
		var self = this;
		setTimeout(function() {self.showMessage(msg); },2000);
		return;
	}
	this.notificationWindow.showMessage(msg, ht || 5);
}

Sparcq.Components.prototype.initNotificationWindow = function(el) {
		var _nw  = {};
		_nw.container_el = el;
		_nw._id_counter = 1;
		_nw._appendItem = function(msg,classname,hide_timeout) {
			this._id_counter++;
			var item_id = 'nw_msg_' + this._id_counter;
			this.container_el.append(
				Sparcq.SQ.parseHtml('<div id="%%item_id%%" class="%%classname%%">%%msg%%</div>',
				{msg: msg,item_id:item_id,classname:classname})
			);
			var self = this;
			setTimeout(function() { self.remove(item_id); },hide_timeout*1000);
		};
		_nw.showError = function(msg,hide_timeout) {
			this._appendItem(Sparcq.SQ.stringifyObject(msg),'error',hide_timeout);
		};
		_nw.showMessage = function(msg,hide_timeout) {
			this._appendItem(Sparcq.SQ.stringifyObject(msg),'message',hide_timeout);
		};
		_nw.remove = function(el_id) {
			jQuery('#' + el_id).remove();
		};
		this.notificationWindow = _nw;
		
};

Sparcq.Components.prototype.queryGeonamesDB = function(q,args,maxRows) {
	var success_callback = args.onSuccess;
	var error_callback = (args.onError) ? args.onError : this.throwError;
	var url = 'http://ws.geonames.org/searchJSON?' +
		'&maxRows=' + maxRows +
		'&lang=en' +
		'&style=medium' +
		'&featureClass=P' +
		'&name_startsWith=' + encodeURIComponent(q) +
		'&callback=?';

	$.jsonp({
		url: url,
		success: function(resp,rt_string) {
			if (resp && resp.geonames) {
				resp = resp.geonames;
			}
			success_callback.call(this,resp);
		},
		error: function(error_obj,rt_string) {
			error_callback.call(this,{
				error_obj: error_obj,
				return_type: rt_string,
				request_params: { q: q }
			});
		},
		timeout: 15000
	});
};
