////////////////////////////////////////////////////////////////
// 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();
	
	$j("#nav-search").bind("click", function() {
		HNSITE.Modules.Carvenience.Show({ openTab: 'search' });
	});
	
	// 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 = {};

// ============================================
// 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.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() {
			var self = $j(this);
			if (self.hasClass("nav-link-large"))
				self.css("width", "135px");
			else if (self.hasClass("nav-link-medium"))
				self.css("width", "120px");
			else
				self.css("width", "100px");
		});
	}
};

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();
	
	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;
	});
};


// ********************************************
// 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() {
	// Franchise Selector bubble information boxes
	HNSITE.Pages.Home.FranchiseSelector.Init();
	
	// Promotional Slideshow
	HNSITE.Pages.Home.PromoSlideshow.Init();
};

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, 
			slideshow = $j("#custom-slideshow"),
			slides = slideshow.find(".slides-content > a"), 
			overlay = slideshow.find(".slideshow-overlay");
		slides.css("display", "none").eq(0).css("display", "block").addClass("active");
		if (slides.eq(0).hasClass("use-overlay")) {
			overlay.children("a").attr('href', slides.first().get(0).href).end().show();
		} else {
			overlay.hide();
		}
		var ChangeSlides = function(index) {
			var activeSlide = slides.filter(".active"),
				nextSlide = (typeof index == 'number') ? slides.eq(index) : 
							((activeSlide.next().length) ? activeSlide.next() : slides.first());
			activeSlide.fadeOut("def", function() {
				nextSlide.addClass("active").fadeIn('def');
				if (nextSlide.hasClass("use-overlay")) {
					overlay.children("a").attr('href', nextSlide[0].href);
					overlay.show();
				} else {
					overlay.hide();
				}
				activeSlide.removeClass("active");
				self.UnPause();
			});
		};
		// Wireup our functionality and timers
		setInterval(function() {
			if (self._isPaused === false) {
				self.Pause();
				ChangeSlides();
			}
		}, 7000);
		
		// Preload coupon images
		$j(window).load(function() {
			HNSITE.Utils.PreloadImages((function() {
				var images = [];
				slides.find("div.outer-coupon-wrapper").each(function() {
					var url = /url\("(.*)"\)/.exec($j(this).css("background-image"))[1];
					if (HNSITE.UI.Validation.Regex.IsURI.test(url)) {
						images.push(url);
					}
				});
				return images;
			})());
		});
	}
};

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 CNY Auto!</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 CNY Auto!</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 CNY Auto!</p>'
	});
	
	$j("#show-auto-detailing-services").click(function(event) {
		event.preventDefault();
		$j(this).parent().next().children("div").show();
	});
};

// ============================================
// Review Page
if (typeof HNSITE.Pages.Reviews == 'undefined') HNSITE.Pages.Reviews = {};

HNSITE.Pages.Reviews.Initializer = function() {
	// Setup our contact us inquiry form
	HNSITE.UI.Custom.StandardForm.Initializer({
		formName: 'send-review',
		submitClass: 'form-submit',
		postFile: '/reviews.asp',
		thanksMessage: '<p>Thanks for choosing CNY Auto!</p>'
	});
};

// ============================================
// Sitemap Page
if (typeof HNSITE.Pages.Sitemap == 'undefined') HNSITE.Pages.Sitemap = {};

HNSITE.Pages.Sitemap.Initializer = function() {
	// Setup our contact us inquiry form
	HNSITE.UI.Custom.StandardForm.Initializer({
		formName: 'sitemap-inquiry',
		submitClass: 'sitemap-inquiry-submit',
		postFile: '/sitemap.asp',
		thanksMessage: '<span class="thank-you-message">We have successfully received your message and will be in contact with you shortly. ' + 
					   'If you have questions at any time, please call us.<br /><br />Thanks again for choosing CNY Auto!</span>'
	});
};
