/* setup namespaces */
if (typeof(BCNTRY.cpi) == 'undefined') {BCNTRY.cpi = {};}
if (typeof(BCNTRY.wall) == 'undefined') {BCNTRY.wall = {};}
if (typeof(BCNTRY.wall.ucp) == 'undefined') {BCNTRY.wall.ucp = {};}
if (typeof(BCNTRY.pdp) == 'undefined') {BCNTRY.pdp = {};}

	BCNTRY.wall.ucp = {

		//badge hover
		badgeHelpPopup: null,
		badgeHelpIconMouseOver: function(target,description) {
			if ( !this.badgeHelpPopup ) {
				this.badgeHelpPopup = new BCNTRY.community.widget.HelpPopup('badge_help_template');
				this.badgeHelpPopup.render();
			}
			this.badgeHelpPopup.cfg.setProperty('context', [target, 'tl', 'bl']);
			this.badgeHelpPopup.setBody('<p>' + description + '</p>');
			this.badgeHelpPopup.show();
		},
		badgeHelpIconMouseOut: function(evt) {
			 var mouse_coords = ye.getXY(evt);
			 if ( this.badgeHelpPopup && !this._coordsInContainer(mouse_coords, this.badgeHelpPopup) ) {
				this.badgeHelpPopup.hide();
			 }
		},
		_coordsInContainer: function(mouse_coords, container) {
			var region = yd.getRegion(container.id);
			return this._coordsInRegion(mouse_coords, region);
		},

		_coordsInRegion: function(mouse_coords, region) {
			return (mouse_coords[1] >= region.top
				&& mouse_coords[0] >= region.left
				&& mouse_coords[1] <= region.bottom
				&& mouse_coords[0] <= region.right
			);
		 }
		//end badge hover
	};

/* Start mini profile */
(function(){

	var dialogs = {};
	var ids = 0;
	var connection = false;

	function asyncRequest(url, callback, args) { 
		// Only allow one connection at a time
		if (connection) { return; }
		connection = true; 

		yd.addClass(document.body, 'yui-busy');

		var _parse_query_params = function(p) {
			var params = [];
			for (var i in p) {
				params.push( i + "=" + encodeURIComponent(p[i]));
			}
			return params.join("&");
		};

		yc.asyncRequest('POST', url, {
			timeout: ajax_timeout,
			success: function(o) {
				var json_data = o.responseText;
				var resultObj = {};
				try {
					resultObj = eval( '(' + json_data + ')' );
					if (resultObj.success && callback) {
						callback.success(resultObj.attributes);
					}
					else if (callback) {
						callback.error(resultObj);
					}
				}
				catch(e) {
					if (callback) {
						callback.failure(o, e);
					}
				}
				yd.removeClass(document.body, 'yui-busy');
				connection = false;
			},
			failure: function(o) {
				if (callback) {
					callback.failure(o);
				}
				yd.removeClass(document.body, 'yui-busy');
				connection = false;
			}
		}, _parse_query_params(args));
	}

	function createHTML(id, content) {
		var t = document.createElement('div');
		t.id = id;
		yd.addClass(t, 'none');
		yd.addClass(t, 'mini_profile');
		t.innerHTML = '<div class="hd"></div><div class="bd">'+content+'</div><div class="mini_profile_bottom"></div>';
		yd.insertBefore(t, 'unique_content');
	}

	function coordsInRegion(mouse_coords, region) {
		return (mouse_coords[1] > region.top
			&& mouse_coords[0] > region.left
			&& mouse_coords[1] < region.bottom
			&& mouse_coords[0] < region.right
		);
	}

	function coordsInDialog(mouse_coords, dialog) {
		var region = yd.getRegion(dialog.id);
		var arrow_region = yd.getRegion(dialog.arrow);
		return coordsInRegion(mouse_coords, region) ||
			coordsInRegion(mouse_coords, arrow_region);
	}

	if (typeof(BCNTRY.profile) == 'undefined') { BCNTRY.profile = {}; }
	if (typeof(BCNTRY.profile.widget) == 'undefined') { BCNTRY.profile.widget = {}; }

	BCNTRY.profile.widget.MiniProfile = function(el, args) {
		this.init(el, args);
	}

	var MP = BCNTRY.profile.widget.MiniProfile;

	BCNTRY.profile.widget.MiniProfile._getElFromEvt = function(evt) {
		var el = ye.getTarget(evt);
		if (el.nodeName.toUpperCase() !== 'A') {
			el = el.parentNode;
		}
		return el;
	};

	BCNTRY.profile.widget.MiniProfile.mouseClick = function(evt) {
		var el = MP._getElFromEvt(evt);
		dialogs[el].ignoreError = true;
	};


	BCNTRY.profile.widget.MiniProfile.mouseOver = function(evt) {
		var el = MP._getElFromEvt(evt);
		var username = el.href.match(/profile\/(\d+)/)[1];
		dialogs[el] = dialogs[el] || {};
		var d = dialogs[el];
		d.active = true;

		setTimeout(function() {
			// If they moved their mouse, don't worry about displaying it
			if (!d.active) { return; }

			d.element = el;
			if (!d.dialog) {
				ids++;
				d.id = 'mini_profile_'+ids;

				asyncRequest('/'+BCNTRY.site.catalog+'/profile/'+username+'/mini_profile', {
					success: function(result) {

						try {

						// Profiles without images have a smaller width
						var dialog_width = '443px';
						if (result.image_url) {
							result.image_url = '<img class="user_thumb" src="'+result.image_url+'" />';
						}
						if (result.site_rank.has_tier) {
							result.site_rank.tier_icon_el = '<img src="'+result.site_rank.tier_icon_url+'" alt="'+result.site_rank.tier_text+'" />';
						}
						if (typeof(result.badges) != 'undefined' && result.badges.length > 0) {
							for (var i = 0; i < result.badges.length; i++) {
								result.badges[i].image_html = '<img class="user_badge" src="'+result.badges[i].image_url+'" alt="'+result.badges[i].text+'" />';
							}
						}
						result.passions = result.passions.slice(0,3);
						for(var i=0; i < result.passions.length; i++) {
							result.passions[i] = result.passions[i].name;
						}

						// TODO: Implement this (next iteration?)
						//result.accolades = [{name: 'The North Face - Top Reviewer'},
						//	{name: 'Armani - Top Reviewer'}];
						result.accolades = [];

						// Create/render the dialog
						var content;
						try {
							content = TrimPath.processDOMTemplate('mini_profile_content', result);
						}
						catch(e) {
							content = e.message;
						}
						createHTML(d.id, content);
						yd.removeClass(d.id, 'none');
						d.dialog = new BCNTRY.profile.widget.MiniProfile( d.id, {
							context: [el, 'bl', 'tr'],
							width: dialog_width
						});
						d.dialog.render();
						d.arrow = yd.getElementsByClassName('arrow', 'div', d.id)[0];

						// When they click anywhere in the mini-profile, take them to the profile page
						ye.on(d.id, 'click', function(evt) {
							//omniture tracking
							template_links_tl('tr_template', 'PDP: Profile Link');
							window.location.href = result.profile_url;
						});

						// Hide the dialog when they move the mouse outside of it
						var mouseOutFunc = function(evt) {
							var mouse_coords = ye.getXY(evt);
							if ( !coordsInDialog(mouse_coords, d) ) {
								d.dialog.hide();
							}
						}
						ye.on(d.id, 'mouseout', mouseOutFunc);
						ye.on(d.arrow, 'mouseout', mouseOutFunc);

						// Again, if they moved their mouse, don't worry about displaying it
						if (d.active) {
							d.dialog.show();
						}
						else {
							d.dialog.hide();
						}
						} catch(e) { alert(e.message) }

						track_pdp_mini_proflile_popup();
					},
					failure: function(o) {
						if (!d.ignoreError) {
							alert(o.statusText);
						}
					}
				});
			}
			else {
				d.dialog.cfg.setProperty('context', [el, 'bl', 'tr']);
				d.dialog.show();
			}
		}, 250);
	};

	BCNTRY.profile.widget.MiniProfile.mouseOut = function(evt) {
		var el = MP._getElFromEvt(evt);
		dialogs[el] = dialogs[el] || {};
		var d = dialogs[el];
		d.active = false;

		var mouse_coords = ye.getXY(evt);

		if ( d.dialog && !coordsInDialog(mouse_coords, d) ) {
			d.dialog.hide();
		}
	};

	YAHOO.extend(BCNTRY.profile.widget.MiniProfile, YAHOO.widget.Dialog);

	BCNTRY.cpi._loading_image_url = '';
	BCNTRY.cpi.loading_image_url = function() {
		if (BCNTRY.cpi._loading_image_url === '') {
            BCNTRY.cpi._loading_image_url = $('loading_image_preload').src;
        }
		return BCNTRY.cpi._loading_image_url;
	};
	BCNTRY.cpi.load_large_image = function(el) {
		// This needs to work on either an <a> tag or an outer <span>
		if (el.tagName == 'SPAN') {
			el = el.firstChild;
		}

    	var img_url = el.href;
		if (!$('large_product_image').src.match(img_url)) {
			$('large_product_image').alt = '';
			$('large_product_image').src = BCNTRY.cpi.loading_image_url();
			$('large_product_image').src = img_url;
		}
	};


})();
ye.onDOMReady(function() {
	// Add listeners to for the mini profile
	var els = yd.getElementsByClassName('user_profile_link', 'a', 'unique_content', function(el) {
		ye.on(el, 'mouseover', BCNTRY.profile.widget.MiniProfile.mouseOver, el, true);
		ye.on(el, 'mouseout', BCNTRY.profile.widget.MiniProfile.mouseOut, el, true);
		ye.on(el, 'click', BCNTRY.profile.widget.MiniProfile.mouseClick, el, true);
	});

});


