////////////////////////////////////////////////////////////////
// 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();
	// Custom controls
	HNSITE.UI.Custom.Navigation.Initializer();
	HNSITE.UI.Custom.NewModelSelector.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 = {};

// ============================================
// 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");
	// 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 item = $j(this);
			if (item.hasClass("nav-link-large"))
				item.css("width", "118px");
			else if (item.hasClass("nav-link-medium"))
				item.css("width", "108px");
			else if (item.hasClass("nav-link-small-two-line"))
				item.css("width", "98px");
			else
				item.css("width", "84px");
		});
	}
};

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");
	}
};

// ============================================
// New Model Selector (homepage)
if (typeof HNSITE.UI.Custom.NewModelSelector == 'undefined') HNSITE.UI.Custom.NewModelSelector = {};

HNSITE.UI.Custom.NewModelSelector = {

	// <summary>
	// Initialize this control
	// </summary>
	Initializer: function() {
		if ($j("#new-model-selector").length == 1)
			this.Setup();
	}, 
	
	// <summary>
	// Setup the New Model Selector
	// </summary>
	Setup: function() {
		var self = this;
		
		// Wireup events to control hiding of the model selector
		$j("#new-model-selector").bind("mouseleave", function() {
			$j(this).data('current-category', null);
			self.CloseBubbleFlyup();
			$j(this).find("a.vehicle-category").removeClass("selected");
			if ($j("> .opened-category-wrap", this).css("display") == 'block')
				$j("> .opened-category-wrap", this).hide();
		});
		
		// Wireup events to populate the panel based on category of button being hovered
		$j("#new-model-selector > .category-selector-wrap").delegate("a.vehicle-category", "click", self.PopulateCategory);
		
		// Wireup the individual models with the category panel that was hovered over and opened
		$j("#new-model-selector > .model-bubble-flyup-wrap").bind("mouseleave", function() {
			self.CloseBubbleFlyup();
		});
		$j("#new-model-selector > .opened-category-wrap")
			.find(".vehicle-photos")
			.delegate("a.model", "mouseenter", self.CreateBubbleFlyup)
			.delegate("a.model", "click", function(event) {
				event.preventDefault();
				$j("#new-model-selector > .model-bubble-flyup-wrap").hide();
				location.href = this.href;
			});
			
		// iPad cant hover outside to close it so let them click anywhere outside to trigger the behavior
		if (/ipad/.test(navigator.platform.toLowerCase())) {
			$j(document).bind("touchstart", function(event) {
				if (!$j(event.target).parents().andSelf().is('#new-model-selector'))
					$j("#new-model-selector").triggerHandler("mouseleave");
			});
		}
	},
	
	// <summary>
	// Binding method used to populate a vehicle class category based on which button they rollover
	// </summary>
	PopulateCategory: function(event) {
		// When a model is selected but bubble never hovered so its still there, everything is fine except if we change
		// categories then the positioning of cars changes with wrong vehicle in bubble still showing so always fade out first here
		HNSITE.UI.Custom.NewModelSelector.CloseBubbleFlyup();
	
		var that = this,
			categoryDataRequest = {},
			jOpenCategoryWrap = $j("#new-model-selector > .opened-category-wrap"),
			jCategorySelectorWrap = $j("#new-model-selector > .category-selector-wrap"), 
			selectedCategoryTitle = $j(that).find("span.text > span").text(),
			selectedCategory = (selectedCategoryTitle.left(4).toLowerCase() == 'suvs') ? 'suvs' : selectedCategoryTitle.toLowerCase();
		
		// Prevent re-triggering an already opened panel which just causes a flash and followed by the re-appearance of same content 
		if ($j("#new-model-selector").data('current-category') == selectedCategory)
			return;
		
		// Populate and display the correct category selector panel
		$j("#new-model-selector").data('current-category', selectedCategory);
		$j(that).siblings("a.vehicle-category").removeClass("selected").end().addClass("selected");
		jOpenCategoryWrap.children(".opened-category-header").find("h2").text(selectedCategoryTitle);
		if (selectedCategory.toLowerCase() == 'hybrids') {
			categoryDataRequest['field'] = 'is_hybrid';
			categoryDataRequest['value'] = 'true';
		}
		else {
			categoryDataRequest['field'] = 'category';
			categoryDataRequest['value'] = selectedCategory;
		}
		HNSITE.Data.Sources.NewModels.QueryByCategory({
			data: categoryDataRequest, 
			complete: function(vehicles) {
				var categoryHtml = '', vehicleName = '', vehicleUrl = '';
				jOpenCategoryWrap.find(".vehicle-photos").hide().empty();
				for (var i = 0; i < vehicles.length; i++) {
					vehicleUrl = HNSITE.UI.Custom.NewModelSelector.GetModelPageUrl(vehicles[i].make, vehicles[i].model);
					vehicleName = vehicles[i].make + ' ' + vehicles[i].model;
					categoryHtml = categoryHtml + String('<a href="{0}" class="model" rel="{1}"><img src="{2}" alt="{3}" /></a>').format(vehicleUrl, vehicles[i].id, vehicles[i].photo_thumb, vehicleName);
				}
				jOpenCategoryWrap.find(".vehicle-photos").html(categoryHtml);
				jOpenCategoryWrap.find(".vehicle-photos").fadeIn(400);
			}
		});
		if (jOpenCategoryWrap.css("display") != 'block')
			jOpenCategoryWrap.show();
	}, 
	
	// <summary>
	// Create the events for the flyup bubble that contains the specific model information for each vehicle
	// </summary>
	CreateBubbleFlyup: function() {
		// Capture needed containers and make sure our default state is okay
		var button = $j(this), 
			flyupContainer = $j("#new-model-selector > .model-bubble-flyup-wrap");
		if (flyupContainer.length != 1) return;
		if (flyupContainer.css("display") == 'block')
			flyupContainer.stop(true, true).hide();
		// Wireup to our data source for leasing specials
		HNSITE.Data.Sources.NewModels.SingleResultQuery({
			data: {
				field: 'id',
				value: button.attr("rel")
			},
			complete: function(vehicle) {
				// Substitute content into container before displaying
				flyupContainer.find(".model-name").html(vehicle.year + ' ' + vehicle.model);
				flyupContainer.find(".starting-msrp").html('Starting at ' + HNSITE.Utils.FormatCurrency(vehicle.msrp) + ' MSRP');
				flyupContainer.find(".stock-photo img").attr({
					src: vehicle.photo_normal, 
					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").html(String(vehicle.comments).ellipsis(180));
				flyupContainer.find(".more-model-info").attr('href', button.attr('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("%7Bmake%7D", vehicle.make).replace("%7Bmodel%7D", vehicle.model).toLowerCase());

				// Position and display the flyup centered above the button (reposition on viewport edges for smaller resolutions)
				var paddingOffsetX = (HNSITE.Settings.Browser.CheckVersion.IsIE === true && HNSITE.Settings.Browser.Version == 6) ? -15 : 7, 
					offsetY = 13, 
					coords = {
						x: button.offset().left - $j("#new-model-selector > .category-selector-wrap").offset().left - (flyupContainer.outerWidth() / 2) + (button.outerWidth() / 2) + paddingOffsetX,
						y: 0 - flyupContainer.outerHeight() - $j("#new-model-selector > .category-selector-wrap").height() - offsetY
					};
				flyupContainer.find(".pointer").css('left', '50%');
				flyupContainer.css('left', coords.x + 'px').css('top', coords.y + 'px').show();
			}
		});
	}, 
	
	// <summary>
	// Check if the flyup bubble is still open and if so then fades it out again to reset it
	// </summary>
	CloseBubbleFlyup: function() {
		var flyupContainer = $j("#new-model-selector > .model-bubble-flyup-wrap");
		if (flyupContainer.length != 1) return;
		flyupContainer.fadeOut("def");
	},
	
	// <summary>
	// Returns a new model page url to make sure they are all consistent
	// </summary>
	GetModelPageUrl: function(make, model) {
		return 'http://' + document.domain + '/new-' + String(make).toLowerCase() + '-models/' + String(model).replace(' ', '-').toLowerCase() + '.asp';
	}
	
};

// ============================================
// Gift Card Widget (initing on each page locally for now)
if (typeof HNSITE.UI.Custom.GiftCard == 'undefined') HNSITE.UI.Custom.GiftCard = {};

HNSITE.UI.Custom.GiftCard.Initializer = function() {
	$j("#signin_menu > .get-balance-wrap > input.get-balance").click(function(e) { 
		var that = this;
		// Validate the input
		var jSerial = $j("#signin_menu input.gift-card-number").first(), jPin = $j("#signin_menu input.gift-card-pin").first();
		var gcSerial = String(jSerial.val()).replace(/^\s+|\s+$/g, ''), gcPin = String(jPin.val()).replace(/^\s+|\s+$/g, '');
		if (/^[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}$/.test(gcSerial) == false) {
			$j("#signin_menu > .messages").css("visibility", "visible").text('Serial Number entered incorrectly');
			return false;
		}
		if (/^[0-9]{4}$/.test(gcPin) == false) {
			$j("#signin_menu > .messages").css("visibility", "visible").text('Pin Number entered incorrectly');
			return false;
		}
		// Begin posting after validating data
		$j(that).hide().after('<img src="/js/giftcards/images/loading.gif" class="loading" width="128px" height="15px" />').siblings(".loading");
		gcSerial = gcSerial.replace(/(-| ){1}/g, '');
		$j.ajax({
			type: 'POST',
			global: false,
			cache: false,
			data: {serial: gcSerial, pin: gcPin},
			url: "/js/giftcards/giftcards-proxy.asp",
			dataType: "xml",
			success: function(xml) {
				if ($j(xml).find("ErrorResponse").size() > 0) {
					$j(that).parent().children(".loading").remove().end().find("input.get-balance").show();
					$j("#signin_menu > .messages").css("visibility", "visible").text( $j(xml).find("Message").text() );
				}
				else {
					var results = String($j(xml).find("Return").text()).replace('&quot;', '"');
					results = $j.parseJSON(results);
					var balance = (function formatCurrency(num) {
						num = isNaN(num) || num === '' || num === null ? 0.00 : num;
						return parseFloat(num).toFixed(2);
					})(results.balances.total_cash_value);
					if ($j("#signin_menu > .messages").css("visibility") == 'visible')
						$j("#signin_menu > .messages").css("visibility", "hidden");
					$j(that).parent().empty().text('Your remaining balance: $' + String(balance));
				}
			},
			error: function(data) { 
				$j("#signin_menu > .messages").css("visibility", "visible").text('Error connecting to server. Please try again.');
			}
		});
	});
};

// ============================================
// 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(),
		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: false})) {
			$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();
			if ($j.isPlainObject(options.staticPostData)) {
				formData = formData + (($j.isEmptyObject(options.staticPostData)) ? '' : '&' + $j.param(options.staticPostData));
			}
			$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) {
						// Thank the user and show successful
						formTag.html(options.thanksMessage);
						// Execute optional Google Analytics tracker
						if (typeof(options.googleTrackVirtual) != 'undefined') {
							if (typeof(pageTracker) != 'undefined') {
								pageTracker._trackPageview(options.googleTrackVirtual);
							} else if (typeof _gaq != 'undefined') {
								_gaq.push(["_trackPageview", options.googleTrackVirtual]);
							}
						}
						// Execute optional AdWords conversion
						if (typeof(options.adwordsConversionVars) != 'undefined') {
							// Create image source url
							var adwordImage = "http://www.googleadservices.com/pagead/conversion/{0}/?label={1}&amp;guid=ON&amp;script=0".format(options.adwordsConversionVars.google_conversion_id, options.adwordsConversionVars.google_conversion_label);
							if (options.adwordsConversionVars.google_conversion_value) {
								adwordImage += "&amp;value={0}".format(options.adwordsConversionVars.google_conversion_value);
							}
							// Insert on page
							$j("body").append('<img src="{0}" height="1" width="1" style="border-style:none;" alt="" />'.format(adwordImage));
						}
					}
					$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>
// New Models Data Source (mainly for homepage vehicle selector)
// 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.NewModels = (function() {
	var _dataSource = "/framework/data-services/new-models.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 SingleResultQuery = function(transaction) {
		_getData(function() {
			var result = HNSITE.Data.FilterByProperty(_cachedData, transaction.data.field, transaction.data.value)[0];
			transaction.complete(result);
		});
	};
	var QueryByCategory = function(transaction) {
		_getData(function() {
			var result = HNSITE.Data.FilterByProperty(_cachedData, transaction.data.field, transaction.data.value);
			transaction.complete(result);
		});
	};
	return { 
		StartCaching: StartCaching,
		SingleResultQuery: SingleResultQuery,
		QueryByCategory: QueryByCategory,
		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() {
	// Search Our Inventory tabs
	$j("#search-inventory ul.scrollable-results").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;
	});
	
	// 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"));
	});
	
	// Promotional Accordion
	HNSITE.Pages.Home.PromoAccordion.Init();
	
	// Monthly Incentives
	$j("#monthly-incentives div.widget-content").jScrollPane({
		scrollbarWidth: 12, 
		showArrows: true
	});
	/*
	$j("div.monthly-incentives-wrap", "#monthly-incentives").live("mouseenter mouseleave click", function(e) {
		if (e.type == 'mouseenter')
			$j(this).addClass("hover");
		else if (e.type == 'mouseleave')
			$j(this).removeClass("hover");
		else if (e.type == 'click') {
			$j(this).removeClass("hover");
			location.href = $j(this).find("> .special-info > h4 > a").attr("href");
		}
	});
	*/
};

// ============================================
// Promotional Accordion (homepage)
HNSITE.Pages.Home.PromoAccordion = {

	Init: function(container) {	
		// Wireup the accordion slides
		$j("#promotion-accordion").children(".collapsible-header").bind("movenext", function() {
			var that = this;
			$j(that).siblings(".collapsible-header").next().slideUp(150, function() {
				if ($j(that).next().css('display') != 'block')
					$j(that).next().slideToggle(200);
			});
		})
		.bind("click", function() {
			var landingPage = $j(this).next().find("a.landing-page-url").attr('href');
			window.location = landingPage;
		});
		
		$j("#promotion-accordion").find(".first-collapsible-content").hide().end()
			.find(".collapsible-content").last().show();
			
		// Start our autoplay 
		this.AutoPlay();
	}, 
	
	AutoPlay: function() {
		setInterval(function() {
			var nextHeader = $j("#promotion-accordion").children(".collapsible-content:visible").prevAll(".collapsible-content").first().prev();
			if (nextHeader.length != 0)
				nextHeader.triggerHandler("movenext");
			else
				$j("#promotion-accordion").children(".collapsible-header").last().triggerHandler("movenext");
		}, 7000);
	}
	
};

// ============================================
// 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: 'request-parts-submit',
		postFile: '/new-castle-car-parts.asp',
		thanksMessage: '<span class="thank-you-message">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. <br /><br />Thanks again for choosing Price Toyota!</span>'
	});
};

// ============================================
// Service Page
if (typeof HNSITE.Pages.Service == 'undefined') HNSITE.Pages.Service = {};

HNSITE.Pages.Service.Initializer = function() {
	// Initialize the date picker
	$j("form:first input.date-picker").datepicker();
	// Setup our service inquiry form
	HNSITE.UI.Custom.StandardForm.Initializer({
		formName: 'request-service',
		submitClass: 'request-service-submit',
		postFile: '/new-castle-car-service.asp',
		thanksMessage: '<span class="thank-you-message">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. <br /><br />Thanks again for choosing Price Toyota!</span>'
	});
};

// ============================================
// Body Shop Page
if (typeof HNSITE.Pages.BodyShop == 'undefined') HNSITE.Pages.BodyShop = {};

HNSITE.Pages.BodyShop.Initializer = function() {
	// Initialize the date picker
	$j("form:first input.date-picker").datepicker();
	// Setup our body shop inquiry form
	HNSITE.UI.Custom.StandardForm.Initializer({
		formName: 'request-body-shop-appointment',
		submitClass: 'request-body-shop-appointment-submit',
		postFile: '/delaware-valley-body-shop.asp',
		thanksMessage: '<span class="thank-you-message">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 ' + 
					   'body shop specialists. <br /><br />Thanks again for choosing Price Toyota!</span>'
	});
};

// ============================================
// 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-submit',
		postFile: '/contact-price-toyota.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 and we will put you in touch with one of our ' + 
					   'custom service specialists. <br /><br />Thanks again for choosing Price Toyota!</span>'
	});
};

// ============================================
// 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 Price Toyota!</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");
};

