$(document).ready(function() {
	/* Global Search Field */
	$("#globalSearch").hover(
		function(){$(this).parent().addClass("searchHover")},
		function (){$(this).parent().removeClass("searchHover")}
	);
	$("#searchInput").click(function(){
			$(this).val("");
			$(this).css("color","#000");
		 });

	// UK Fleet page specific - tabbing
	$(".tabItem").click(function() {
		var idx = $(".tabItem").index(this);
		var ct = $(".tabMainContent:eq("+idx+")");
		$(ct).siblings().hide();
		$(ct).show();
		$(this).siblings().removeClass("tabbed");
		$(this).addClass("tabbed");
	})

	/**
	 * CTA buttons object create:
	 * Initializes all buttons that are already in the DOM.
	 * (Append corners where needed, apply the size className
	 * make all grouped buttons equal in height for each group)
	 * Provides a global object: 'oCtaButtons'
	 * It has the methods:
	 * oCtaButtons.refreshGroup(buttons)
	 *     Update all buttons passed by the buttons parameter
	 *     buttons may be a DOM node (or an array of nodes),
	 *     a css selector or a jQuery selection of buttons
	 *     Passed buttons will be treated as a single group.
	 *
	 * oCtaButtons.refresh(buttons)
	 *     Update all buttons passed by the buttons param
	 *     buttons may be a button DOM-node (or an array of them), 
	 *     or the jquery selection of one or more buttons
	 *
	 */

	/*
	 * IE6 SUPPORT INFO:
	 * All items in between the "IE6 SUPPORT" / "END IE6 SUPPORT" comments
	 * may simply be removed if support for IE6 (and lower) is no longer desired
	 */
	window.oCtaButtons = (function () {
		/* Initialize some variables */
		var $allButtons  = $("a.button"),
		$groupedBtns = $allButtons.filter(".grouped"),
		sCornerWrappers = '' +
			'<span class="corner topLeft"></span>\n' +
			'<span class="corner bottomLeft"></span>\n' +
			'<span class="corner topRight"></span>\n' +
			'<span class="corner bottomRight"></span>\n';
			
		/* IE6 SUPPORT */
		var isIElte6 = /MSIE (\d+\.\d+);/.test(navigator.userAgent) && (RegExp.$1) * 1.0 <= 6;

		function setIElte6ClassByHeight($button, sSizeClassName) {
			/* remove any old ie sizeClassNames */
			$button.get(0).className = $button.get(0).className.replace(/ +cta\d+size\d+/g, '');
			/* and set the new one */
			if (/ *(cta\d+) */.test($button.get(0).className)) {
				$button.addClass(RegExp.$1 + sSizeClassName);
			}
		}
		/* END IE6 SUPPORT */

		function setSizeClass($buttons) {
		//~ var aSizeSteps = [20, 30, 45, 70, 105, 160];
			var aSizeSteps = [25, 40, 60, 90, 130, 200];
			$buttons.each(function () {
				var $currentButton = $(this),
				sSizeClassName = '',
				iSizeIndex = 1;

				while (iSizeIndex <= aSizeSteps.length && $currentButton.innerHeight() > aSizeSteps[iSizeIndex - 1]) {
					iSizeIndex += 1;
				}
				sSizeClassName = 'size' + iSizeIndex;
				$currentButton.get(0).className = $currentButton.get(0).className.replace(/ +size\d+/g, ''); /* only works if sizeX is NOT the first className */
				$currentButton.addClass(sSizeClassName);

				/* IE6 SUPPORT */
				if (isIElte6) {
					$currentButton
						.toggleClass("oddHeight", $currentButton.innerHeight() % 2 !== 0 )
						.toggleClass("oddWidth",  $currentButton.innerWidth() % 2 !== 0 );
					setIElte6ClassByHeight($currentButton, sSizeClassName);
				}
				/* END IE6 SUPPORT */
			});
		}

		function updateButtonGroup($buttons) {
			var iGroupHeight = 0,
			iAddPaddingTop,
			iAddPaddingBottom;

			$buttons.each(function () {
				iGroupHeight = Math.max(iGroupHeight, $(this).height());
			}).each(function () {
				var $currentButton = $(this),
				iHeightDifference = iGroupHeight - $currentButton.height();

				if (iHeightDifference % 2) {
					iAddPaddingTop    = (iHeightDifference - 1) / 2;
					iAddPaddingBottom = iAddPaddingTop + 1;
				} else {
					iAddPaddingTop = iAddPaddingBottom = iHeightDifference / 2; 
				}
				$currentButton.css({
					paddingTop:    parseInt($currentButton.css("paddingTop"), 10) + iAddPaddingTop + "px",
					paddingBottom: parseInt($currentButton.css("paddingTop"), 10) + iAddPaddingBottom + "px"
				});
				/* set all size related classNames */
				setSizeClass($currentButton);
				/* append corners if button is not static */
				if (!$currentButton.hasClass(".static") && !$currentButton.children(".topLeft, .topRight, bottomLeft, .bottomRight").addClass("corner").length) {
					$currentButton.append(sCornerWrappers);
				}
			});
		}

		function updateButtons($buttons) {
			$buttons.each(function () {
				var $currentButton = $(this);
				/* set all size related classNames */
				setSizeClass($currentButton);
				/* append corners if button is not static */
				if (!$currentButton.hasClass(".static") && !$currentButton.children(".topLeft, .topRight, bottomLeft, .bottomRight").addClass("corner").length) {
					$currentButton.append(sCornerWrappers);
				}
			});
		}

		/* resize all button groups (starting at group1, incrementing the group number until groupN can not be found) */
		var sGroupName = "group1";

		/* If the current group classname exists */
		while ($groupedBtns.hasClass(sGroupName)) {
			updateButtonGroup($groupedBtns.filter("." + sGroupName));
			sGroupName = "group".concat(sGroupName.match(/group(\d+)/)[1] * 1 + 1);
		}
		updateButtons($allButtons.not(".grouped"));

		return {
			refreshGroup: function ($buttonGroup) {
				var $standardButton = $('<a class="button jsStandardButton"></a>').appendTo('body').hide();
				if (!$buttonGroup || !$buttonGroup.jquery) {
					$buttonGroup = $($buttonGroup);
				}

				/* Reset the paddings top/bottom. creates a testbutton, gets its paddings
				and removes it. Resets the group's padding to those values */
				$buttonGroup.css({
					paddingTop:    parseInt($standardButton.css("paddingTop"), 10),
					paddingBottom: parseInt($standardButton.css("paddingBottom"), 10) 
				});
				$standardButton.remove();
				updateButtonGroup($buttonGroup);
			},
			refresh: function (oButton) {
				$(oButton).each(function () {
					var $currentButton = $(this);
					if (!$currentButton.hasClass(".static") && !$currentButton.children(".topLeft, .topRight, bottomLeft, .bottomRight").addClass("corner").length) {
						$currentButton.append(sCornerWrappers);
					}
					setSizeClass($currentButton);
				});
			}
		}
	})();

});

/* Query Functions */
/* Splitting a query string into its values.
 * Returns object (default) or array (values only) if second parameter is set to true
 */
 function splitQueryString(url,arr) {
		if(url) {
			var s = url.substring(url.indexOf("?")+1,url.length);

		var f = s.split("&");
		var o;
		//arr = true;
		var temp = 13;
		if(arr) o = new Array();
		else o = new Object();
		for(var i=0;i<f.length;i++) {
			var e = f[i].split("=");
			if(arr) {
				o.push(e[1]);
			}
			else o[e[0]] = e[1];
		}
		return o;
		}
	}

/* Load Flash */

function ActivateFlashIE(width, height, bgcolor, wmode, movie, xml)
{
	 document.write("<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,79,0' width='" + width + "' height='" + height + "'>");
	 document.write("<param name='width' value='" + width + "'>");
	 document.write("<param name='height' value='" + height + "'>");
	 document.write("<param name='movie' value=" + movie + ">");
	 document.write("<param name='type' value='application/x-shockwave-flash'>");
	 document.write("<param name='flashvars' value='" + xml + "'>");
	 document.write("<param name='allowScriptAccess' value='sameDomain'>");
	 document.write("<param name='bgcolor' value='" + bgcolor + "'>");
	 document.write("<param name='pluginspage' value='http://www.macromedia.com/go/getflashplayer'>");
	 document.write("<param name='quality' value='high'>");
	 document.write("<param name='wmode' value='" + wmode + "'>");
	 document.write("<embed src='" + movie + "' flashvars='" + xml + "' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer'  type='application/x-shockwave-flash' width='" + width + "' height='" + height + "'  wmode='" + wmode + "'></embed></object>");
}

/*
 * Set a cookie
 */
function setCookie(sParamName, sParamValue, iDaysToExpire, sPath) {
	if (!sParamName ) { return; }
	sParamValue   = sParamValue || null;
	sPath         = sPath || '/';
	iDaysToExpire = parseInt(iDaysToExpire) || 365;

	var date = new Date();
	date.setTime( date.getTime() + (iDaysToExpire*24*60*60*1000) );
	document.cookie = sParamName + "=" + sParamValue + "; expires=" + date.toGMTString() + "; path=" + sPath;
}

/*
 * Find the value of sParamName in a cookie and return it.
 */
function getCookieParam (sParamName) {
	if(document.cookie) {
		var re = new RegExp(sParamName + '=([^;$]*)');
		return re.test(document.cookie) ? re.exec(document.cookie)[1] : false;
	}
	return false;
}

/**
 * dealer search box START
 */
$(document).ready(function() {
	var sDealerSearchDefaultVal = $("#searchItem").val();
	$("#searchItem").val(getCookieParam("searchItem") || sDealerSearchDefaultVal);
	/**
	 * if the dealer search box is not yet inside the metaNAvi li
	 * that triggers the search box, go ahead and put it there.
	 * Also make shure that the list item in question is positioned relative (acting as offsetParent)
	 */
	if (!$("#dealerSearchWrp").is("#metaNavi > li.dealerSearch #dealerSearchWrp")) {
		$("#metaNavi > li.dealerSearch").css({position: 'relative'}).append($("#dealerSearchWrp"));
	}

	$("#metaNavi .dealerSearch > a").click(function(event){
		var $dSearch = $("#dealerSearchWrp");
		$("#searchItem").removeClass("warning");
		$dSearch.show();

		/* if the dealer search box would get cut off on the right
		   (viewport too small) -> reposition it to the left */
		var offsetX  = $dSearch.offset().left;

		if (offsetX + $dSearch.outerWidth() > $(window).width()) {
			$("#dealerSearchWrp").css({left: parseInt($dSearch.css("left")) - offsetX - $dSearch.outerWidth() + $(window).width() + 'px'});
		}
		return false;
	});

	$("#searchItem").closest("form").submit(function (event){
		$searchItem = $("#searchItem");
		if($searchItem.val() &&  $searchItem.val() != sDealerSearchDefaultVal) {
			/* if input is not empty set the cookie and submit the form */
			setCookie("searchItem", $searchItem.val());
		} else {
			/* show the error and do not submit otherwise */
			$searchItem.addClass("warning");
			event.preventDefault();
		}
	});

	$("#dealerSearchWrp .closeAction").click(function(){
		$("#dealerSearchWrp").hide();
	});

	/* disable the link and submit the form instead */
	$("#dealerSearchWrp a.button").click(function(event){
		event.preventDefault();
		$("#dealerSearchForm").submit();
	});

	$("#searchItem").focus(function(){
		if($(this).val() == sDealerSearchDefaultVal) {
			$(this).val("");
		}
	});

	$("#searchItem").blur(function(){
		if($(this).val() == "") {
			$(this).val(sDealerSearchDefaultVal);
		}
	});

});
/* end dealer search box END
 */
