/*
	Copyright DTDigital         :: www.dtdigital.com.au ::
	Unauthorised modification / use is a criminal offence, and
	will be prosecuted to the fullest extent permitted by law.
	All Rights Reserved
*/

/**********************************************************************
***********************************************************************

  This script is for any scripts that are used in multiple 
  Honda sites. By referencing them once here it will make 
  things much easier to update in the future.

***********************************************************************
**********************************************************************/

var DTD = DTD || {};
DTD.Honda = DTD.Honda || {};
DTD.Honda.Utility = DTD.Honda.Utility || {};

// Global vars
var lowStock = '<a class="low-stock noScroll" href="#stock-announcement-message" title="View stock annoucement"><strong>Low Stock Availability</strong> Please click here to read this important announcement about stock availability.</a>'

var _jQueryLoaded = (typeof(jQuery) == "function");
if (_jQueryLoaded) {
	$(function() {
		
		InitRolloverNavigation();
		ClearInput();
		numbersOnlyInput();
		
		// Inpage links
		$.localScroll({
			offset	: {top:-20, left:0},
			filter	: ':not(.noScroll, .enterPostcode, .page-nav-item)',
			lazy	: true,
			duration: 500
		});
		
		// Makes links open in new window
		$("a[rel=external], a.external-link").attr("target", "_blank");
		
		$('a#print-link').click(function() {
			window.print();	
			return false;
		});
		
		// External dealer hiding elements when query string is present
		var hideThese = $(".noshow"),
			showThese = $(".show"),
			changeThese = $(".textchange"),
			queryString = location.search.substring(1, location.search.length);
			
		if(queryString.indexOf("show=false") != -1) {
			$.each(hideThese, function(){
				$(this).css({ display: "none"});
			});
			$("a").each(function(){
				var currentLink = $(this).attr("href");
				if (currentLink && currentLink.indexOf("#") != 0 && currentLink.indexOf("show=false") == -1) {
					if(currentLink.indexOf("?") != -1) {
						$(this).attr("href", currentLink + "&show=false");
					} else {
						$(this).attr("href", currentLink + "?show=false");
					}
				}
			});
			$.each(showThese,function(){
				$(this).css({ display: "block"});
			});
			$.each(changeThese,function(){
				$(this).text("Range &amp; Specifications");
			});
		}

        // IE 6 PNG fix for elements:
        // Elements to "fix" are stored in array for readability, converted back to string to feed into fix.
        var DD_fix =
			[
			 	".brochure-promo img",
			 	".fCar a",
				".highlight-box img",
				".nextSteps img",
				".nextSteps .img",
				".carThumbnail",
				".offer-alert",
				".active-offer",
				".png"
			].toString();
        (typeof DD_belatedPNG == "object") ? DD_belatedPNG.fix(DD_fix) : "";
		
		// Replace all old in page 'back to top' links to #bodycontainer with links to #header
		$('a[href*="bodycontainer"]').attr('href','#header');
		
		/* ===== Common namespaces ===== */
		/* ===== Utility ===== */
		(function (module, $, undefined) {

			var Events = {
				bind: function () {
					if (!this.o) this.o = $({});
					this.o.bind.apply(this.o, arguments);
				},
				trigger: function () {
					if (!this.o) this.o = $({});
					this.o.trigger.apply(this.o, arguments);
				}
			};

			module.StateMachine = function () {};
			module.StateMachine.fn = module.StateMachine.prototype;

			$.extend(module.StateMachine.fn, Events);

			module.StateMachine.fn.add = function (controller) {

				this.bind("change", function (e, current) {

					if (controller == current) {
						controller.activate();
					} else {
						controller.deactivate();
					}
				});

				controller.active = $.proxy(function () {
					this.trigger("change", controller);
				}, this);
			};

		}(window.DTD.Honda.Utility = window.DTD.Honda.Utility || {}, jQuery));
		
	});
}

var _RolloverNavigationLoaded = false;
function InitRolloverNavigation()
{
	if (_jQueryLoaded && !_RolloverNavigationLoaded)
	{
		$(".rollover-navigation a").each(function()
		{
			$(this).find("img.navitem_prejs").each(function()
			{
				$(this).attr("class", "navitem_off");
			
				var newImage = $(this).clone();
		
				var newImageSrc = newImage.attr("src").replace("_0.gif", "_1.gif");
				newImage.attr("src", newImageSrc);
		
				newImage.attr("class", "navitem_hover");
		
				newImage.insertAfter(this);
			});
			
			$(this).focus(
				function()
				{
					$(this).toggleClass("hover");
				}
			).blur(
				function()
				{
					$(this).toggleClass("hover");
				}
			);
		});
		
		_RolloverNavigationLoaded = true;
	}
}

// Prevent input if not a number
function numbersOnlyInput() {
	$("input.numbersOnly").keypress(function(e) {
		//if the letter is not digit then display error and don't type anything
		if( e.which!=8 && e.which!=0 && e.which!=13 && (e.which<48 || e.which>57)) {
			return false;
		}
	});
}
// Prevent input if not a number (allows .)
function floatOnlyInput() {
	$("input.floatOnly").keypress(function(e) {
		//if the letter is not digit or decimal point then display error and don't type anything
		if( e.which!=8 && e.which!=0 && e.which!=13 && e.which!=46 && (e.which<48 || e.which>57)) {
			return false;
		}
	});
}

// Clear inputs' default text on focus, replace it on blur if input is empty
function ClearInput() {
	var clearInputPrevious = '';
	// clear input on focus
	$('input:text').focus(function(){
		if($(this).val()==$(this).attr('title'))
		{
			clearInputPrevious = $(this).val();
			$(this).val('');
		}
	});
	// if field is empty afterward, add text again
	$('input:text').blur(function(){
		if($(this).val()=='')
		{
			$(this).val(clearInputPrevious);
		}
	});
}

// Brochure popups from brochures.aspx in showrooms/brochures sites
function popup(mylink, windowname) {
    if (typeof (mylink) == 'string') {
        href = mylink;
    } else { href = mylink.href; }

    params = 'width=' + screen.width;
    params += ', height=' + screen.height;
    params += ', top=0, left=0, toolbar=0,location=0,statusbar=0,menubar=0,resizable=0,scrollbars=0'
    params += ', fullscreen=yes,';

    popupWindow = window.open(href, windowname, params);
    if (window.focus) { popupWindow.focus() }
    return false
}

// In group of checkboxes, disables remaining checkboxes after 3 are selected
function countCheckboxes() {
	$("ul.countchecked input[type=checkbox]").click(function() {

		var checkedCheckboxes = $("ul.countchecked input[type=checkbox]:checked").size();

		if (checkedCheckboxes == 3) {
			$("ul.countchecked input[type=checkbox]:not(:checked)").attr({ disabled: "disabled" }).next("label").attr({ style: "color:#b2b2b2" });
		} else {
			$("ul.countchecked input[type=checkbox]:not(:checked)").removeAttr("disabled").next("label").removeAttr("style");
		}
		
		if (checkedCheckboxes != 0) {
			$('.countchecked').parents('.field01').removeClass('error_highlight').children('.validator').remove();
		}
		
	});
}

// Code for splitting dynamic model checkboxes into columns of equal height
function splitCheckboxes() {
	var models = $('ul.countchecked li').size(),	// get all models
		colBreak1 = Math.floor(models/3),			// divide models by amount of columns required
		colBreak2 = colBreak1,						// these vars are the number of models until a column is ended
		mod = models%3;								// get remainder of above division
	
	if (mod == 0) {									// an if statement to match the models list indexes with the amount of models
		colBreak1 -= 1;								// if there are 0 extra models (all columns even), take 1 from each column break to give first 2 columns an extra model
		colBreak2 -= 1;
	} else if (mod == 1) {
		colBreak2 -= 1;								// if there is 1 extra model, take 1 only from the second column break, as the first column needs the extra model
	}												// if there are 2 extras, they already have the correct values
	
	$('ul.countchecked').after('<ul class="list01 countchecked countchecked2"></ul>');	// insert new list after original
	$('ul.countchecked li:gt(' + colBreak1 + ')').appendTo($('ul.countchecked2'));		// take all models from first list after first break, move to second list
	$('ul.countchecked2').after('<ul class="list01 countchecked countchecked3"></ul>');	// insert new list after original
	$('ul.countchecked2 li:gt(' + colBreak2 + ')').appendTo($('ul.countchecked3'));		// take all models from second list after second break, move to third list
}

// Trigger for stock announcment popup
$('.low-stock, .stock-announcement-inner').live('click', function(e) {
	$('a.fancybox-fade').trigger('click');
	e.preventDefault();
});

// Compare heights of common elements within area, add any excess height for alignment eg. Special Offers listings
// compareHeight(elementToCompare, paddingProperty, containingElement);
function compareHeight(element, paddingProp, searchArea) {
	var maxHeight = 0,
		heightCompare = [];
	searchArea.find(element).each(function() {
		var thisHeight = $(this).height();
		heightCompare.push(thisHeight);
	});
	maxHeight = Math.max.apply(Math, heightCompare);
	searchArea.find(element).each(function() {
		var thisHeight = $(this).height();
		paddingValue = maxHeight - thisHeight;
		paddingValue != 0 ? $(this).css(paddingProp, paddingValue) : '' ;
	});
}
