////////////////////////////////////////////////////////////////
// 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();
});

// ***************************************
// 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.find("li.nav-primary-item > .nav-secondary-wrap").css("display", "none");
	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");
};

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");
		navWrap.css("width", String(subNavWidth * 1.62) + '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;
	});
};


// ********************************************
// Custom HNSITE.Data.Sources
// ********************************************
if (typeof HNSITE.Data == 'undefined') HNSITE.Data = {};
if (typeof HNSITE.Data.Sources == 'undefined') HNSITE.Data.Sources = {};


// ********************************************
// 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() {
	// homepage init stuff
	var jSearchPanel = $j('#page-contents').find('div.basic-search-content-wrap');
	jSearchPanel.find(".type-grouping input:radio").bind("change", HNSITE.Pages.Home.Search.Init);
	jSearchPanel.find(".make-grouping select:first").bind("change", HNSITE.Pages.Home.Search.LoadModel);
	jSearchPanel.find(".submit-grouping > a").bind("click", HNSITE.Pages.Home.Search.Post);
	HNSITE.Pages.Home.Search.Init();
	HNSITE.Pages.Home.Slideshow.Init();
};

HNSITE.Pages.Home.Slideshow = {
	Timer: {},
	
	Init: function() {
		var slides = $j("#slideshow").find("> .slides > div.single-slide");
		HNSITE.Pages.Home.Slideshow.Timer = setTimeout(HNSITE.Pages.Home.Slideshow.Slide, 4000);
	},
	
	Slide: function() {
		var slides = $j("#slideshow").find("> .slides > div.single-slide"),
			selected = slides.filter(".selected").first(),
			next = (selected.next().length) ? selected.next() : slides.first();
		
		selected.toggleClass("selected", 500);
		next.toggleClass("selected", 500);
		HNSITE.Pages.Home.Slideshow.Timer = setTimeout(HNSITE.Pages.Home.Slideshow.Slide, 4000);
	},
	
	Stop: function() {
		clearTimeout(HNSITE.Pages.Home.Slideshow.Timer);
	}
};

// <summary>
// Basic search page methods to load selectbox data, construct url, and redirect to browse page.
// </summary>
HNSITE.Pages.Home.Search = {
	
	// Preloads makes into make dropdown
	Init: function () {
		var jSearchPanel = $j('#page-contents').find('div.basic-search-content-wrap'),
			selectMake = jSearchPanel.find(".make-grouping select:first")[0],
			selectModel = jSearchPanel.find(".model-grouping select:first")[0],
			jsonPostData = {
				'return': 'make',
				'groupby': 'make',
				'param_new-used': jSearchPanel.find(".type-grouping input:radio:checked").val()
			};
		
		$j.getJSON('/framework/data-services/json-query.asp', jsonPostData, function(responseData) {
			HNSITE.Utils.SelectBox.Empty(selectMake);
			HNSITE.Utils.SelectBox.Empty(selectModel);
			HNSITE.Utils.SelectBox.Add(selectMake, "Any Make", "");
			HNSITE.Utils.SelectBox.Add(selectModel, "Any Model", "");
			$j.each(responseData, function(index, value) {
				if (value.make.length)
					HNSITE.Utils.SelectBox.Add(selectMake, value.make, value.make);
			});
		});
	},
	
	// Use as onchange for make dropdown to load correct models
	LoadModel: function() {
		var jSearchPanel = $j('#page-contents').find('div.basic-search-content-wrap'),
			selectModel = jSearchPanel.find(".model-grouping select:first")[0],
			make = jSearchPanel.find(".make-grouping select:first").val(), 
			jsonPostData = {
				'return': 'model',
				'groupby': 'model',
				'param_make': make, 
				'param_new-used': jSearchPanel.find(".type-grouping input:radio:checked").val()
			};
		
		if (make.length) {
			$j.getJSON('/framework/data-services/json-query.asp', jsonPostData, function(responseData) {
				HNSITE.Utils.SelectBox.Empty(selectModel);
				HNSITE.Utils.SelectBox.Add(selectModel, "Any Model", "");
				$j.each(responseData, function(index, value) {
					if (value.model.length) {
						// This must be html decoded.. if more instances found, create html encode/decode class?
						value.model = value.model.replace("&amp;", "&");
						HNSITE.Utils.SelectBox.Add(selectModel, value.model, value.model);
					}
				});
			});
		}
	},
	
	// Loop through values, construct url, and redirect
	Post: function() {
		var jSearchPanel = $j('#page-contents').find('div.basic-search-content-wrap'),
			searchUrl = "/exton-cars/", 
			searchParam = "", 
			type = jSearchPanel.find(".type-grouping input:radio:checked").val();
		
		// Always want type first in the url
		if (!type.length)
			searchUrl = searchUrl.concat("type_used/");
		else 
			searchUrl = searchUrl.concat("type_" + type + "/");
		
		if (HNSITE.UI.Validation.SimpleValidate({ context: jSearchPanel[0] })) {
			jSearchPanel.find('.label-field-grouping input,select').not('[name=type]').each(function(){
				if (!this.value.blank()) {
					searchParam = HNSITE.Utils.BrowsePageEscape(this.value.toLowerCase());
					if (this.type == 'radio' || this.type == 'checkbox') {
						if (this.checked) 
							searchUrl = searchUrl.concat(this.name + '_' + searchParam + '/');
					} 
					else 
						searchUrl = searchUrl.concat(this.name + '_' + searchParam + '/');
				}
			});
			
			window.location = searchUrl;
		}
		
		return false;
	}
	
};

// ============================================
// 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 Sloan Ford!</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 Sloan Ford!</p>'
	});
	
	$j("#page-contents").find("div.page-content").find("div.widget-content-inner-wrap").equalizeCols();
};

// ============================================
// Service Page
if (typeof HNSITE.Pages.Service == 'undefined') HNSITE.Pages.Service = {};

HNSITE.Pages.Service.Initializer = function() {
	// Setup our service 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 Sloan Ford!</p>'
	});
};

// ============================================
// Financing Page
if (typeof HNSITE.Pages.Financing == 'undefined') HNSITE.Pages.Financing = {};

HNSITE.Pages.Financing.Initializer = function() {
	// Setup our financing inquiry form
	HNSITE.UI.Custom.StandardForm.Initializer({
		formName: 'financing',
		submitClass: 'financing-form-submit',
		postFile: 'https://ssl.homenetinc.com/sloanford_com/www/financing.asp',
		thanksMessage: '<p>Thank you for your submission.  A representative will be in touch with you shortly.</p>'
	});
};

// ============================================
// Sitemap Page
if (typeof HNSITE.Pages.Sitemap == 'undefined') HNSITE.Pages.Sitemap = {};

HNSITE.Pages.Sitemap.Initializer = function() {
	// Setup our sitemap 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 Sloan Ford!</span>'
	});
};

// ============================================
// 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");
};
