////////////////////////////////////////////////////////////////
// HomeNet JS Core Site Library
// Customization Core for Website
// (c) 2010, HomeNet Automotive LLC
////////////////////////////////////////////////////////////////

if (typeof HNSITE == 'undefined') HNSITE = {};
if (typeof HNSITE.UI == 'undefined') HNSITE.UI = {};

// ***************************************
// Execute main document initializer
//  - only add the initializers needed and used on this site
//  - basically these are our "live" events for permanent elements and for transforming
//    and binding UI components like buttons or image rollovers
//  - HNSITE.UI.Initializer will contain all wiring events with default context of 'document' so
//    we want to run each time for ajax content but if a site doesnt need as many of our default UI components
//    then just pick and choose which methods to run from it instead of using HNSITE.UI.Initializer
// ***************************************
$j(function() {
	// Persistent and Live Initializers
	HNSITE.UI.Initializer();
	// Navigation menu
	HNSITE.UI.Custom.Navigation.Initializer();
	// Social media icon 
	$j("#footer div.social-media-icons a").live("click", function() {
		window.open(this.href);
		return false;
	});
});

// ***************************************
// Custom UI Wiring Initializers
//  - define any custom site UI components that have initializers
//  - makes Ajax loaded content easy to rebind with our custom site UI components
//  - merges into HNSITE.UI.Initializer defined in hnsite-core to form a single complete UI initializer
// ***************************************
HNSITE.UI.InitCustom = function(container) {
    // Nothing here yet
};


// ********************************************
// Custom HNSITE.UI Classes
// ********************************************
if (typeof HNSITE.UI.Custom == 'undefined') HNSITE.UI.Custom = {};

// ============================================
// Side Search Cookie Setter (by request, allow us to set side search cookie for starting open panel)
if (typeof HNSITE.UI.Custom.SideSearchCookie == 'undefined') HNSITE.UI.Custom.SideSearchCookie = {};

HNSITE.UI.Custom.SideSearchCookie.Set = function(tabFieldName) {
	var tabFieldMap = {
		'make': 0, 
		'model': 1
	};
	if (typeof tabFieldMap[tabFieldName] != 'undefined')
		HNSITE.Data.Cookies.Create('sideSearchOpenedTab', String(tabFieldMap[tabFieldName]), {expires: 7, path: '/'});
};

// ============================================
// Container Printing Functions
if (typeof HNSITE.UI.Custom.Printer == 'undefined') HNSITE.UI.Custom.Printer = {};

HNSITE.UI.Custom.Printer.PrintContainer = function(options) {
	if ($j("#printer").length > 0)
		document.body.removeChild($j("#printer")[0]);
		
	var iframe = document.createElement('IFRAME');
	var doc = null;
	$j(iframe).attr('id', 'printer').attr('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
	document.body.appendChild(iframe);
	doc = iframe.contentWindow.document;
	var links = window.document.getElementsByTagName('link');
	for(var i = 0; i < links.length; i++) {
		if(links[i].rel.toLowerCase() == 'stylesheet')
			doc.write('<link type="text/css" rel="stylesheet" href="' + links[i].href + '"></link>');
	}
	doc.write('<div class="' + $j(options.target).attr("class") + '">' + $j(options.target).html() + '</div>');
	doc.close();
	iframe.contentWindow.focus();
	iframe.contentWindow.print();
	if (typeof options.callback == 'function') options.callback();
};

// ============================================
// Navigation Menu
if (typeof HNSITE.UI.Custom.Navigation == 'undefined') HNSITE.UI.Custom.Navigation = {};

HNSITE.UI.Custom.Navigation.Initializer = function() {
	// Collapse our subnavigation menus and set events
	var primaryMenu = $j("#navigation ul.nav-primary");
	primaryMenu.children("li.nav-primary-item.disallow-expansion").data('expand', 'false');
	// primaryMenu.find("li.nav-primary-item > .nav-secondary-wrap").css("display", "none"); - trying defaulting on and checking seo over time
	primaryMenu.delegate("li.nav-primary-item", "mouseenter", HNSITE.UI.Custom.Navigation.Over)
			   .delegate("li.nav-primary-item", "mouseleave", HNSITE.UI.Custom.Navigation.Out)
	// Append our last child class to help with borders on the subnav
	primaryMenu.find("ul.nav-secondary > li:last-child").children("a").addClass("last-subnav-link");
	// For IE6&7 users we need to define menu item widths (for 6, has list width bugs; and 7, width 100% bugs)
	if (HNSITE.Settings.Browser.CheckVersion.IsIE === true 
		&& (HNSITE.Settings.Browser.Version == 6 || HNSITE.Settings.Browser.Version == 7)) {
		primaryMenu.find("li.nav-primary-item").each(function() {
			if ($j(this).hasClass("nav-link-large"))
				$j(this).css("width", "130px");
			else if ($j(this).hasClass("nav-link-medium"))
				$j(this).css("width", "115px");
			else
				$j(this).css("width", "85px");
		});
	}
};

HNSITE.UI.Custom.Navigation.Over = function(e) {
	var self = $j(this);
	if (self.has(".nav-secondary-wrap").length) {
		var navWrap = self.children(".nav-secondary-wrap").first();
		if (navWrap.css("display") == 'block') return;
		var thisLink = self.children("a.nav-primary-link");
		var subNavWidth = thisLink.outerWidth();
		if (self.children("a.nav-primary-link").is(".active-page") == false)
			thisLink.addClass("primary-hover");
		if (navWrap.closest("li.nav-primary-item").data('expand') === 'false')
			navWrap.css("width", String(subNavWidth-2) + 'px').stop(true, true).slideDown(200);
		else
			navWrap.css("width", String(Math.round(subNavWidth*1.88)) + 'px').stop(true, true).slideDown(200);
	}
	else {
		if (self.children("a.nav-primary-link").is(".active-page") == false)
			self.children("a.nav-primary-link").addClass("primary-hover");
	}
};

HNSITE.UI.Custom.Navigation.Out = function(e) {
	var self = $j(this);
	if (self.has(".nav-secondary-wrap").length) {
		self.children(".nav-secondary-wrap").slideUp(200, function() {
			if (self.children("a.nav-primary-link").is(".active-page") == false)
				self.children("a.nav-primary-link").removeClass("primary-hover");
		});
	}
	else {
		if (self.children("a.nav-primary-link").is(".active-page") == false)
			self.children("a.nav-primary-link").removeClass("primary-hover");
	}
};

// ============================================
// Standard Page Form
if (typeof HNSITE.UI.Custom.StandardForm == 'undefined') HNSITE.UI.Custom.StandardForm = {};

HNSITE.UI.Custom.StandardForm.Initializer = function(options) {
	options = options || {};
	if (typeof options.formName != 'string' || typeof options.submitClass != 'string' || typeof options.postFile != 'string') return;
	//var formTag = $j("form[name='" + options.formName + "']").first(); - weird IE6/7 bug, cant use name attribute in selection of form
	var formTag = $j("form").first();
	var formSubmitButton = $j("a." + options.submitClass, formTag).first();
	if (formTag.size() == 0 || formSubmitButton.size() == 0) return;
	formSubmitButton.bind("click", function() {
		if (HNSITE.UI.Validation.SimpleValidate({context: formTag, scrollToField: true})) {
			$j("body").css('cursor', 'wait');
			$j(this).hide().after('<div class="hnsite-ui-loading-small-button"></div>');
			var staticFormData = "r=" + HNSITE.Utils.Stamp() + "&ref=" + encodeURIComponent(location.href) + "&postback=true&";
			var formData = staticFormData + formTag.serialize();
			$j.ajax({
				type: 'POST',
				global: false,
				cache: false,
				url: options.postFile,
				data: formData,
				error: function(data) {
					$j("body").css('cursor', 'auto');
				},
				success: function(jsonData) {
					var postSuccessful = (jsonData.result == 'success') ? true : false;
					if (postSuccessful) {
						// Scroll page up to top and show thank you message
						HNSITE.UI.ScrollPageUp({
							completed: function() {
								formTag.fadeOut("def", function() {
									formTag.parent().children("h3").first().text('Thank You');
									formTag.parent().append(options.thanksMessage);
								});
							}
						});
						// Execute optional Google Analytics tracker
						if (typeof options.googleTrackVirtual  != 'undefined' && typeof pageTracker != 'undefined')
							pageTracker._trackPageview(options.googleTrackVirtual);
					}
					$j("body").css('cursor', 'auto');
				},
				dataType: 'json'
			});
		}
		return false;
	});
};


// ********************************************
// Custom HNSITE.Data.Sources
// ********************************************
if (typeof HNSITE.Data == 'undefined') HNSITE.Data = {};
if (typeof HNSITE.Data.Sources == 'undefined') HNSITE.Data.Sources = {};

// <summary>
// Homepage Lease Specials Data Source
// This is a more complex implementation of asynchronous patterns where we create public services using a custom hardcoded json
// data feed file. The beauty of this implementation is we cache the json results internally so that its available throughout the
// current page load and to save http requests we do not even fetch the json data until the first time a method is called 
// </summary>
HNSITE.Data.Sources.LeaseSpecials = (function() {
	var _dataSource = "/framework/data-services/home-lease-specials.json.asp";
	var _isDataCached = false;
	var _cachedData;
	var _getData = function(execute) {
		if (_isDataCached === true) {
			if (typeof execute == 'function') execute();
		}
		else {
			$j.get(_dataSource, { r: HNSITE.Utils.Stamp() }, function(jsonData) {
				_cachedData = jsonData;
				_isDataCached = true;
				if (typeof execute == 'function') execute();
			}, "json");
		}
	};
	var StartCaching = function() { _getData(); };
	var GetAllResults = function() { return ((typeof _cachedData != 'undefined') ? _cachedData : false); };
	var Query = function(transaction) {
		_getData(function() {
			var result = HNSITE.Data.FilterByProperty(_cachedData, transaction.data.field, transaction.data.value)[0];
			transaction.complete(result);
		});
	};
	return { 
		StartCaching: StartCaching,
		Query: Query,
		GetAllResults: GetAllResults
	};
})();


// ********************************************
// HNSITE.Pages
//  - always will be custom per site and per page
//  - each needs an Initializer to setup everything which is called via document.ready on each page locally
//  - for pages needing a lot of code, seperate just its own page namespace in seperate file to include
// ********************************************
if (typeof HNSITE.Pages == 'undefined') HNSITE.Pages = {};

// ============================================
// Home Page
if (typeof HNSITE.Pages.Home == 'undefined') HNSITE.Pages.Home = {};

HNSITE.Pages.Home.Initializer = function() {

	// Model Lineup Bubbles
	HNSITE.Pages.Home.ModelBubbles.Init();
	
	// Search Our Inventory tabs
	// -> Setup the tabs
	$j("#search-inventory-tab-make > ul").jScrollPane({scrollbarWidth: 12, showArrows: true});
	$j("div.tab-content", "#search-inventory").slice(1).css("display", "none");
	$j("#search-inventory > .widget-toolbar-outer-wrap").find("ul.widget-toolbar li a").live("click", function() {
		// Gather selectors for the current and requested tab button and correlating content container
		var newTabContentID = '#' + $j(this).attr("rel");
		if ($j(newTabContentID).css("display") == 'block') return false;
		var oldActiveTabHandle = $j(this).closest("ul").find("a.active").first();
		var oldTabContentID = '#' + oldActiveTabHandle.attr("rel");
		// Toggle all classes and slide out the old content and in with the new
		oldActiveTabHandle.removeClass("active");
		$j(this).addClass("active");
		$j(oldTabContentID).fadeOut(400, function() {
			$j(newTabContentID).fadeIn(120);
		});
		return false;
	});
	// -> Custom functionality within the tabs here
	$j("#search-inventory-tab-used-volvos > ul.search-result-row").delegate("li a", "click", function(e) {
		HNSITE.UI.Custom.SideSearchCookie.Set('model');
		location.href = this.href;
	});
	
	// Franchise Selector bubble information boxes
	HNSITE.Pages.Home.FranchiseSelector.Init();
	
	// Promotional Slideshow
	HNSITE.Pages.Home.PromoSlideshow.Init();
	
	// Model button popup for more details
	HNSITE.Utils.PreloadImages([ 
		"/images/body-styles/convertible-over.png", 
		"/images/body-styles/coupes-over.png", 
		"/images/body-styles/hybrid-over.png", 
		"/images/body-styles/minivans-over.png", 
		"/images/body-styles/price-over.png", 
		"/images/body-styles/sedans-over.png", 
		"/images/body-styles/suv-over.png", 
		"/images/body-styles/trucks-over.png", 
		"/images/body-styles/wagons-over.png"
	]);
	$j("#search-inventory-tab-body a.body-style").live("mouseenter", function() {
		var bodyNode = $j(this).children(".body-style-icon");
		var bodyOverClass = String(bodyNode.attr("class").split(' ').slice(-1)) + "-over";
		bodyNode.data("overclass", bodyOverClass).addClass(bodyOverClass);
	}).live("mouseleave", function() {
		var bodyNode = $j(this).children(".body-style-icon");
		bodyNode.removeClass(bodyNode.data("overclass"));
	});
	
	// Lease Specials
	$j("div.lease-special-wrap", "#LeaseSpecials").live("mouseenter mouseleave click", function(e) {
		if (e.type == 'mouseover')
			$j(this).addClass("hover");
		else if (e.type == 'mouseout')
			$j(this).removeClass("hover");
		else if (e.type == 'click') {
			$j(this).removeClass("hover");
			location.href = $j(this).find("> .special-info > h4 > a").attr("href");
		}
	});
};

HNSITE.Pages.Home.ModelBubbles = {
	_timeoutID: null,
	_isInsideBubble: false,
	_CloseBubble: function(skipFading) {
		skipFading = (typeof skipFading == 'undefined') ? false : true;
		clearTimeout(this._timeoutID);
		var flyupContainer = $j("#showcase-model-flyup");
		if (flyupContainer.css("display") == 'block' && this._isInsideBubble === false) {
			// Hide the bubble flyup
			if (!skipFading)
				flyupContainer.stop(true, true).fadeOut("def");
			else
				flyupContainer.stop(true, true).hide();
			// Reset all buttons (not best place but only way to handle the model photo triggering for now to remove the selected class)
			$j("#showcase div.model-name").children("a.showcase-model-button").removeClass("selected");
		}
	},
	Init: function() {
		var that = this;
		
		// Wireup the bubble for controlling the transfer of hovering
		$j("#showcase-model-flyup").bind({
			mouseenter: function() {
				that._isInsideBubble = true;
			}, 
			mouseleave: function() {
				that._isInsideBubble = false;
				that._CloseBubble();
			}
		});
		
		// Wireup model photos to trigger the button behavior as well
		$j("#showcase div.model-photo").live("mouseenter", function() {
			$j(this).siblings(".model-name").children("a.showcase-model-button").trigger("mouseover");
		});
		
		// Wireup all the model name buttons which trigger the display of the bubble with populated content for each
		$j("#showcase a.showcase-model-button").live("mouseenter", function() {
			var button = $j(this), flyupContainer = $j("#showcase-model-flyup");
			
			// Prevent animation queue build-up if hovering quickly between buttons
			that._CloseBubble(true);
				
			// Query our service to populate and display the bubble with the correct model information
			button.addClass("selected");
			HNSITE.Data.Sources.LeaseSpecials.Query({
				data: {
					field: 'model',
					value: button.find(".text").text()
				},
				complete: function(vehicle) {
					// Substitute content into container before displaying
					flyupContainer.find(".model-name").html(vehicle.model);
					flyupContainer.find(".starting-msrp").html('Starting at ' + HNSITE.Utils.FormatCurrency(vehicle.msrp) + ' MSRP');
					flyupContainer.find(".stock-photo img").attr({
						src: vehicle.photo, 
						alt: vehicle.make + ' ' + vehicle.model
					});
					if (HNSITE.Settings.Browser.CheckVersion.IsIE === true && (HNSITE.Settings.Browser.Version <= 6))
						flyupContainer.find(".stock-photo img").ifixpng();
					flyupContainer.find(".model-comments").text(String(vehicle.comments).ellipsis(105));
					flyupContainer.find("div.buy-lease-display span.actual-price-value").text(HNSITE.Utils.FormatCurrency(vehicle.actual_price));
					flyupContainer.find("div.buy-lease-display span.msrp-value").text(HNSITE.Utils.FormatCurrency(vehicle.msrp));
					flyupContainer.find("div.buy-lease-display span.savings-value").text(HNSITE.Utils.FormatCurrency(Number(vehicle.msrp) - Number(vehicle.actual_price)));
					if (vehicle.lease_available == 'true') {
						flyupContainer.find("div.buy-lease-inner-wrap").children(":not(.buy-info)").show().end().children(".buy-info").removeClass("only-option");
						flyupContainer.find("div.buy-lease-display span.down-payment-value").text(vehicle.lease_down);
						flyupContainer.find("div.buy-lease-display span.monthly-payment-value").text(vehicle.lease_monthly);
					}
					else {
						flyupContainer.find("div.buy-lease-inner-wrap").children(":not(.buy-info)").hide().end().children(".buy-info").addClass("only-option");
					}
					flyupContainer.find(".actions > a.more-info").attr('href', button[0].href);
					var btnViewInventory = flyupContainer.find(".actions > a.view-inventory");
					if (btnViewInventory.data('linkTemplate') == null)
						btnViewInventory.data('linkTemplate', btnViewInventory[0].href);
					btnViewInventory.attr('href', String(btnViewInventory.data('linkTemplate')).replace("%7Bmodel%7D", vehicle.model).toLowerCase());
					btnViewInventory.find("span.text > span").text('View ' + vehicle.model + ' Inventory');
					// Position and display the flyup centered above the button (reposition on viewport edges for smaller resolutions)
					// (notes - using margin for adjusting pointer, negative margin set ideally should reset that but made it looking nice this way
					//  already and effect is the same and a little faster despite its only slight ugliness)
					var margin = 10, coords = {
						x: button.offset().left - (flyupContainer.outerWidth() / 2) + (button.outerWidth() / 2),
						y: button.offset().top - flyupContainer.outerHeight()
					};
					if ($j("#root").offset().left > ($j("#root").offset().left + coords.x)) {
						coords.x = margin;
						flyupContainer.find(".pointer").css('left', String(Math.round(button.offset().left) + margin) + 'px');
					}
					else if (coords.x + flyupContainer.outerWidth() > $j("body").outerWidth()) {
						coords.x = $j("body").outerWidth() - flyupContainer.outerWidth() - margin;
						flyupContainer.find(".pointer").css('left', String(flyupContainer.outerWidth() - Math.round($j("body").outerWidth() - button.offset().left - (button.outerWidth() / 2)) + margin) + 'px');
					}
					else {
						flyupContainer.find(".pointer").css('left', '50%');
					}
					flyupContainer.css('left', coords.x + 'px').css('top', coords.y + 'px').show();
				}
			});
		}).live("mouseleave", function() {
			$j(this).removeClass("selected");
			that._timeoutID = setTimeout(function() {that._CloseBubble();}, 150);
		}).live("click", function(e) {
			e.preventDefault();
			$j(this).removeClass("selected");
			$j("#showcase-model-flyup").hide();
			location.href = this.href;
		});
	}
};

HNSITE.Pages.Home.PromoSlideshow = {
	_isPaused: false,
	Pause: function() { this._isPaused = true; },
	UnPause: function() { this._isPaused = false; },
	Init: function() {
		// Initialize slides and cache selectors
		var self = this, 
			slides = $j("#custom-slideshow > .slides-content > a"), 
			dots = $j("#custom-slideshow > .slideshow-indicators > .dot"),
			overlay = $j("#custom-slideshow > .slideshow-overlay");
		slides.eq(0).css("display", "block");
		overlay.children("a").attr('href', slides.first().get(0).href);
		var ChangeSlides = function(index) {
			var activeSlide = slides.filter(".active");
			var nextSlide = (typeof index == 'number') ? slides.eq(index) : 
							((activeSlide.next().length) ? activeSlide.next() : slides.first());
			var dots = $j("#custom-slideshow > .slideshow-indicators > .dot");
			activeSlide.fadeOut("def", function() {
				nextSlide.addClass("active").fadeIn('def');
				overlay.children("a").attr('href', nextSlide[0].href);
				activeSlide.removeClass("active");
				dots.eq( slides.index(nextSlide) ).addClass("active");
				dots.eq( slides.index(activeSlide) ).removeClass("active");
				self.UnPause();
			});
		};
		// Wireup our functionality and timers
		dots.live("mouseenter mouseleave click", function(e) {
			if (e.type == 'mouseover')
				$j(this).toggleClass("hover");
			else if (e.type == 'mouseout')
				$j(this).toggleClass("hover");
			else if (e.type == 'click') {
				self.Pause();
				ChangeSlides(dots.index(this));
			}
		});
		setInterval(function() {
			if (self._isPaused === false) {
				self.Pause();
				ChangeSlides();
			}
		}, 7000);
	}
};

HNSITE.Pages.Home.FranchiseSelector = {
	Init: function() {
		// Cache our selectors we will use frequently
		var self = this,
			bubbleBoxes = $j("div.franchise-info-bubble", "#showcase"),
			menuItems = $j("ul.frachise-sites > li", "#showcase");
		// Setup our default state on page load
		bubbleBoxes.slice(1).css("display", "none");
		menuItems.first().children("a").addClass("hover");
		// Define our event handler for hovering menu items
		menuItems.bind("mouseenter", function(e) {
			var activeMenuItem = menuItems.has("a.hover"),
				nextMenuItem = $j(this);
			if (activeMenuItem[0] == this) return;
			bubbleBoxes.eq(menuItems.index(activeMenuItem)).stop(true, true).fadeOut(200);
			activeMenuItem.children("a").removeClass("hover");
			nextMenuItem.children("a").addClass("hover");
			bubbleBoxes.eq(menuItems.index(nextMenuItem)).fadeIn(200);
		});
	}
};

// ============================================
// WYSIWYG Editor Pages to add some common stylings
if (typeof HNSITE.Pages.Wysiwyg == 'undefined') HNSITE.Pages.Wysiwyg = {};

HNSITE.Pages.Wysiwyg.Initializer = function() {
	var tables = $j("#page-contents table");
	tables.find("td").css("padding", "3px");
	tables.find("tr:even").addClass("hnsite-ui-row-even");
	tables.find("tr:odd").addClass("hnsite-ui-row-odd");
};

// ============================================
// Parts Page
if (typeof HNSITE.Pages.Parts == 'undefined') HNSITE.Pages.Parts = {};

HNSITE.Pages.Parts.Initializer = function() {
	// Setup our parts inquiry form
	HNSITE.UI.Custom.StandardForm.Initializer({
		formName: 'request-parts',
		submitClass: 'part-form-submit',
		postFile: '/parts.asp',
		thanksMessage: '<p>We have successfully received your parts request and will be in contact with you shortly. ' + 
					   'If you have questions at any time, please call us and we will put you in touch with one of our ' + 
					   'parts department specialists. Thanks again for choosing Alan Byer Volvo!</p>'
	});
};

// ============================================
// Contact Us Page
if (typeof HNSITE.Pages.ContactUs == 'undefined') HNSITE.Pages.ContactUs = {};

HNSITE.Pages.ContactUs.Initializer = function() {
	// Setup our contact us inquiry form
	HNSITE.UI.Custom.StandardForm.Initializer({
		formName: 'contact-us',
		submitClass: 'contact-us-form-submit',
		postFile: '/contact-us.asp',
		thanksMessage: '<p>We have successfully received your inquiry and will be in contact with you as soon as possible. ' + 
					   'If you have questions in the meantime, please call us and we will put you in touch with one of our ' + 
					   'customer service specialists. Thank you for choosing Alan Byer Volvo!</p>'
	});
};

// ============================================
// Service Page
if (typeof HNSITE.Pages.Service == 'undefined') HNSITE.Pages.Service = {};

HNSITE.Pages.Service.Initializer = function() {
	// Setup our contact us inquiry form
	HNSITE.UI.Custom.StandardForm.Initializer({
		formName: 'request-service',
		submitClass: 'service-form-submit',
		postFile: '/service.asp',
		thanksMessage: '<p>We have successfully received your service request and will be in contact with you shortly. ' + 
					   'If you have questions at any time, please call us and we will put you in touch with one of our ' + 
					   'service department specialists. Thanks again for choosing Alan Byer Volvo!</p>'
	});
};

// ============================================
// New Models Page
if (typeof HNSITE.Pages.NewModels == 'undefined') HNSITE.Pages.NewModels = {};

HNSITE.Pages.NewModels.Initializer = function() {
	// More New Models side panel
	$j("div.widget-new-models-more div.new-model-wrap", "#page-contents").live("mouseover mouseout click", function(e) {
		if (e.type == 'mouseover')
			$j(this).addClass("hover");
		else if (e.type == 'mouseout')
			$j(this).removeClass("hover");
		else if (e.type == 'click') {
			$j(this).removeClass("hover");
			location.href = $j(this).find("> .model-summary > h4 > a").attr("href");
		}
	});
};

// ============================================
// Tags testing area
if (typeof HNSITE.Pages.Tags == 'undefined') HNSITE.Pages.Tags = {};

HNSITE.Pages.Tags.Initializer = function() {
	// Initialize the hovercard tags
	var hoverCard = $j("#ui-hovercard");
	$j("span.ui-hovercard-tag").bind({
		"mouseenter": function(e) {
			var me = $j(this);
			hoverCard.find(".hovercard-content").html('<div class="loading-image"></div><div class="loading-text">Loading ' + me.text() + '...</div>')
			hoverCard.css({
				top: String(me.offset().top + me.outerHeight()) + 'px',
				left: String(me.offset().left - (me.outerWidth() / 2) + Number(hoverCard.children(".hovercard-arrow").css("margin-left").replace("px", ""))) + 'px'
			}).fadeIn(300);
		},
		"mouseleave": function(e) {
			$j("#ui-hovercard").fadeOut(225);
		}
	});
};
