////////////////////////////////////////////////////////////////
// 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("#carvenience-opener").bind("click", function() {
		HNSITE.Modules.Carvenience.Show({ openTab: 'account' });
	});
	
	// Carvenience testing
	HNSITE.Modules.Carvenience.Configure({
		draggable: true, 
		tabs: [
			{name: 'My Account', content: '/framework/module-user/carvenience-account-basic.asp', shorthand: 'account', bindings: HNSITE.Modules.User.Carvenience.BasicAccountTab},
			{name: 'Virtual Garage', content: '/framework/module-virtualgarage/carvenience-virtualgarage.asp', shorthand: 'vg', bindings: HNSITE.Modules.VirtualGarage.Carvenience.VirtualGarage}
		]
	});
});

// ***************************************
// 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) {
	var viewedVehicles = $j("#viewed-vehicles-widget");
    // Check for viewed vehicles section, if no vehicles, remove
	if (!viewedVehicles.find("div.widget-content").find("a").length) {
		if (!viewedVehicles.prev().length) {
			viewedVehicles.next().removeClass("widget-separater");
		}
		viewedVehicles.remove();
	}
};


// ********************************************
// 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() {
	$j('#nav').find('div.dropdownButton').hover(function(){
		$j(this).children().slideDown('fast');
	},function(){
		$j(this).children().slideUp('fast');
	});
};
HNSITE.UI.Custom.Navigation.Over = function(e) {};
HNSITE.UI.Custom.Navigation.Out = function(e) {};

// ============================================
// 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.Slideshow = {
	Timer: {},
	
	Init: function() {
		var slideshow = $j("#slideshow"),
			slides = slideshow.find(".single-slide");
		if (slides.length < 5) {
			slideshow.find(".numbers > div").eq(slides.length-1).nextAll().hide();
		}
		
		slideshow.find(".numbers > div").click(function() {
			HNSITE.Pages.Home.Slideshow.Show($j(this).data("index"));
		});
		HNSITE.Pages.Home.Slideshow.Timer = setTimeout(HNSITE.Pages.Home.Slideshow.Slide, 4000);
	},
	
	Slide: function(next) {
		var slideshow = $j("#slideshow"),
			slides = slideshow.find("> .slides > div.single-slide"),
			selected = slides.filter(".selected").first(),
			next = (typeof next == "object") ? next : ((selected.next().length) ? selected.next() : slides.first());
		
		next.addClass("next");
		selected.fadeOut(500, function() {
			next.removeClass("next").addClass("selected");
			selected.removeClass("selected").show();
			slideshow.find(".numbers > div").removeClass("selected").eq(next.index()).addClass("selected");
		});
		HNSITE.Pages.Home.Slideshow.Timer = setTimeout(HNSITE.Pages.Home.Slideshow.Slide, 4000);
	},
	
	Stop: function() {
		clearTimeout(HNSITE.Pages.Home.Slideshow.Timer);
	},
	
	Show: function(index) {
		HNSITE.Pages.Home.Slideshow.Stop();
		HNSITE.Pages.Home.Slideshow.Slide($j("#slideshow").find(".single-slide").eq(index));
	}
};

// <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('#page-contents').find("div.stock-search input").bind("keydown", function(event) {
			if (event.which === 13) {
				HNSITE.Pages.Home.Search.Stock.call(this);
			}
		});
		$j('#page-contents').find("div.stock-search a").bind("click", HNSITE.Pages.Home.Search.Stock);
		
		$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 = "/inventory/browse/", 
			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;
	},
	
	Stock: function() {
		var field = $j(this).parents("div.stock-search").find("input"),
			value = field.val();
		
		$j.getJSON("/framework/data-services/stock-number-search.asp", {stock: value}, function(data) {
			if (data.exists) {
				window.location.href = "/inventory/browse/type_{0}/stocknumber_{1}/".format(data.type, value);
			} else {
				field.attr("title", "This stock number does not exist");
				HNSITE.UI.Tooltips.TipOver(field);
				setTimeout(function() {
					HNSITE.UI.Tooltips.TipOut(field);
				}, 2000);
			}
		});
	}
	
};

HNSITE.Pages.Home.Initializer = function() {
	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();

	// Extend inventory rows to full length
	var inventory = $j('#usedInventory').find('.make-column');
	while (inventory.first().children().length > inventory.last().children().length) {
		var insertClass = "make" + ((!(inventory.last().children().length % 2)) ? "" : " alt");
		inventory.last().append("<div class='"+insertClass+"'>&nbsp;</div>");
	}
	
	HNSITE.Pages.Home.Slideshow.Init();
};


// ============================================
// 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 us!</span>'
	});
};

// ============================================
// 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/adamsautomotive_com/www/financing.asp',
		thanksMessage: '<p>Thank you for your submission.  A representative will be in touch with you shortly.</p>'
	});
};

// ============================================
// 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 Adams Automotive!</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: '/contactus.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 Adams Automotive!</p>'
	});
};

// ============================================
// Warranty Page
if (typeof HNSITE.Pages.Warranty == 'undefined') HNSITE.Pages.Warranty = {};

HNSITE.Pages.Warranty.Initializer = function() {
	// Setup our contact us inquiry form
	HNSITE.UI.Custom.StandardForm.Initializer({
		formName: 'warranty',
		submitClass: 'warranty-form-submit',
		postFile: '/warranty_form.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 Adams Automotive!</p>'
	});
};

// ============================================
// 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_appt.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 Adams Automotive!</p>'
	});
};
