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

Sparcq.SQ = {};

Sparcq.SQ.imageCachePath = function(path) {
	if (path.slice(0,1) != '/') {
		if (path.slice(0,5) == 'http:') {
			return path;
		}
		path = "/" + path;
	}
	return SPARCQ.IMAGE_CACHE_HOSTNAME + path;
};

Sparcq.SQ.uriFor = function(path,args,anchor) {
	if (path && path.substr(0,1) == '#') { 
		return path;
	}
	path = encodeURI(path);
	if (args) {
		path_sep = '?';
		for (var i in args) {
			path += path_sep + i + '=' + encodeURIComponent(args[i]);
			path_sep = '&';
		}
	}
	anchor = (anchor) ? '#' + anchor : '';
	return SPARCQ.HOSTNAME + path + anchor;
};
Sparcq.SQ.userURL = function(id_or_username,args,anchor) {
	return Sparcq.SQ.uriFor('/u/' + id_or_username,args,anchor);
};
Sparcq.SQ.getUserLink = function(display,id_or_username,args,attribs) {
	var astr = '';	
	var anchor = null;
	if (attribs) {
		for (var i in attribs) {
			if (i == 'anchor') {
				anchor = attribs[i];
			} else {
				astr += ' ' + i + '="' + attribs[i] + '"';
			}
		}
	}
	return '<a href="' + Sparcq.SQ.userURL(id_or_username,args,anchor) + '"' + astr + '>'+ display + '</a>';
};
Sparcq.SQ.getLink = function(display,path,args,attribs) {
	var astr = '';
	
	var anchor = null;
	if (attribs) {
		for (var i in attribs) {
			if (i == 'anchor') {
				anchor = attribs[i];
			} else {
				astr += ' ' + i + '="' + attribs[i] + '"';
			}
		}
	}
	return '<a href="' + Sparcq.SQ.uriFor(path,args,anchor) + '"' + astr + '>'+ display + '</a>';
}
Sparcq.SQ.getWikiLink = function(display,path,args,attribs) {
	path = path.replace(/ /g,'_');
	return Sparcq.SQ.getLink(display,path,args,attribs);
};
Sparcq.SQ.getWikiURI = function(name) {
	return encodeURI(name.replace(/ /g,'_'));
};
Sparcq.SQ.redirect = function(url) {
	location.href=url;
};
Sparcq.SQ.loginRedirect = function() {
	location.href='/';
};
Sparcq.SQ.strPadLeft = function(str,len,pad) {

	if (typeof(pad) == "undefined") {var pad = ' ';}

	if (len + 1 >= str.length) {
		str = Array(len + 1 - str.length).join(pad) + str;
	}
	return str;

};
Sparcq.SQ.parseHtml = function(html,template_vars) {
	if (html) {
		for (var tv in template_vars) {
			html = html.replace(new RegExp('%%' + tv + '%%',"g"),template_vars[tv]);
		}
	}
	return html;
};

Sparcq.SQ.setCookie = function(ck,val,opts) {
	if (!opts) opts = {}; 
	opts.path = opts.path || '/';
	opts.domain = opts.domain || SPARCQ.HOSTNAME.slice(7);
	jQuery.cookie(Sparcq.SQ.getCookieName(ck),val,opts);
};


Sparcq.SQ.getOutsideCookie = function(ck,default_val) {
	return Sparcq.SQ.getCookie(ck,default_val,1);
};

Sparcq.SQ.getCookieName = function(ck,skip_domain_check) {
	if ( !skip_domain_check ) {
		ck += '_' + SPARCQ.HOSTNAME.slice(7).replace(/\./g,'_');
	}
	return ck;
}

Sparcq.SQ.getCookie = function(ck,default_val,skip_domain_check) {
	var opts = {};
	
	var val = jQuery.cookie(Sparcq.SQ.getCookieName(ck,skip_domain_check));
	
	if (!val && default_val) {
		val = default_val;
	}
	return val;
}

Sparcq.SQ.storeJSONCookie = function(ck,val,opts) {	
	var store_val = jQuery.toJSON(val);
	Sparcq.SQ.setCookie(ck,store_val,opts);
	return 1;
};

Sparcq.SQ.deleteCookie = function(ck) {
	Sparcq.SQ.setCookie(ck,'');
}

Sparcq.SQ.getJSONCookie = function(ckname,default_val) {
	var cur_val = Sparcq.SQ.getCookie(ckname);
	if (!cur_val) {
		if (default_val) {
			return default_val;
		} else {
			return null;
		}
	} else {
		return jQuery.evalJSON(cur_val);
	}
};

Sparcq.SQ.stringifyObject = function(msg,is_nested) {
	var res_msg = '';
	if (msg && typeof(msg) == 'object') {
		if (!is_nested) {
			res_msg += 'Sparcq.SQ.stringifyObject(): ';
		}
		res_msg += '{<div>';
		for (var i in msg) {
			if (typeof(msg[i]) == 'function') {
				res_msg += String(i) + ': function()<br />';
			} else if (typeof(msg[i]) == 'object') {
				res_msg += String(i) + ': ' + Sparcq.SQ.stringifyObject(msg[i],1); 
			} else { 
				res_msg += String(i) + ': ' + String(msg[i]) + "<br />";
			}
		}
		res_msg += '</div>}<br />';
	} else {
		return msg;
	}
	return res_msg;
};

Sparcq.SQ.getCountDisplay = function(sing_noun,item_count) {
	if (!item_count) return "0 " + sing_noun + 's';
	if (item_count == 1) return item_count + " " + sing_noun;
	return item_count + " " + sing_noun + 's';
}

Sparcq.SQ.scrollToElement = function(el,offset) {
	offset = offset || 0;
	var scroll_time = 1000;
	if($.browser.opera){
		$('html').animate({
				scrollTop: el.offset().top + offset
			}, scroll_time);
	} else { 
		$('html,body').animate({
				scrollTop: el.offset().top + offset
			}, scroll_time);
	}
};

Sparcq.SQ.setSimilarUserItemHtml = function(clone, item) {
	var html = this.parseHtml(clone.html(),{
		name: item.name,
		item_rating: item.item_rating,
		item_rating_color_class: this.getItemRatingColorClass(item.item_rating),
		rating: item.rating ? item.rating + '% trusted' : '',
		pic: item.pic_square ? this.imageCachePath(item.pic_square) : this.defaultUserIcon,
		id: item.id,
		total_comments: this.getCountDisplay('comment',item.total_comments),
		total_ratings: this.getCountDisplay('total rating',item.items_rated),
		location: item.location ? '<div>' + item.location + '</div>' : '',
		common: (item.items_in_common && item.items_in_common == 1) ?
			item.items_in_common + ' item in common' :
			(item.items_in_common) ? item.items_in_common + ' items in common' : '',
		social: this.getProfileLinks(item.profile_links)
	});
	clone.html(html);
};

Sparcq.SQ.setListItemHtml = function(clone, item) {
	var tag_list = this.getTagList(item.tags,item.name);
	
	clone.html(this.parseHtml(
		clone.html(),{
			total_ratings: this.getCountDisplay('rating',item.total_ratings),
			average_rating: item.average_rating,
			rating: item.rating,
			item_rating_color_class: this.getItemRatingColorClass(item.rating),
			tag_links: tag_list,
			comments_link: this.getLink(this.getCountDisplay('comment',item.total_comments), '/' + item.name, null, { anchor: 'comments' }),
			title_link: this.getWikiLink(item.name,'/' + item.name),
			item_name: item.name,
			item_name_escaped: item.name.replace(/ /g,'_'),
			item_id: item.id
		}));
}

Sparcq.SQ.getTagList = function(tags,item_name,max_to_show,chars_to_show) {
	var tag_list = '';
	var tags_to_show = max_to_show || 10;
	var chars_to_show = chars_to_show || 60;
	var chars_will_be_seen = 0;
	var loop_length = (tags) ? tags.length : 0
	
	for (var i = 0; i < loop_length; i++) {
		chars_will_be_seen += tags[i]['text'].length;
		if (i == 0)  {
			tag_list = 'tags: ';
		}
		if (chars_will_be_seen <= chars_to_show) {
			if (i > 0) {
				tag_list += ', ';
			}
			tag_list += this.getLink(tags[i]['text'],'/en/tag',{ t: tags[i]['text'] } );
			if (i >= (tags_to_show-1)) {
				if (tags.length > tags_to_show ) {
					tag_list += ', ' + this.getWikiLink('more...','/' + item_name,{},{ anchor: 'tags' } );
					//tag_list += '...';
				}
				break;
			}
		} else {
			if (i < tags.length) {
				tag_list += ', ' + this.getWikiLink('more...','/' + item_name,{},{ anchor: 'tags' } );
			}
			break;
		}
	}

	return tag_list;
};

Sparcq.SQ.getProfileLinks = function(links) {
	var html = '';

	for (var i in links) {
		html += '<a href="' + links[i].href + '" target="_blank">' +
		'<img border="0" ' +
		'alt="' + links[i].text + '" ' +
		'title="' + links[i].text + '" ' +
		'src="/images/aquaticus/16x16/' + links[i].network + '.png"/>' +
		'</a>';
	}

	return html;
};

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

Sparcq.SQ.addRateInPlaceEvent = function(new_rate_item,hide_on_rate) {
	var rate_holder = jQuery('.rate',new_rate_item);
	var rate_img = jQuery('img',rate_holder);
	var self = this;

	rate_img.click(function() {
		if (!SPARCQ.SESSION.promptIfNotLoggedIn())
			return false;

		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_handleRateItemError(ret) {
			clone_rb.remove();
			rate_img.show();
			alert('Failed to Rate Item');
		}

		function ripe_handleRateItemCancel(ret) {
			clone_rb.remove();
			rate_img.show();
		}

		function ripe_handleRateItem(ret) {
			if (hide_on_rate) {
				//for some reason fade out isn't working here...
				new_rate_item.slideUp(400, function() {
					new_rate_item.remove();
					self.checkNoRecommendationsLeftOnPage();
				});

			} 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('div.item_name',rate_holder).text();
			clone_rb.html('rating item...');
			if ( (rating || rating == 0 ) && 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;
		});

	});
};
