/*! $Id: global.js 5845 2009-09-02 10:57:46Z mseckert $ */
/*global $: false, window: false, modelName: false, modelYear: false, doPassVar: false, write: false */
"use strict";

$(document).ready(function () {
	/* Global Search Field */
	var defaultValue = $("#searchInput").addClass("default").val();
	$("#globalSearch").hover(
		function () {
			$(this).parent().addClass("searchHover");
		}, function () {
			$(this).parent().removeClass("searchHover");
		}
	);
	$("#searchInput").focus(function () {
		if ($(this).val() === defaultValue) {
			$(this).val("").removeClass("default");
		}
	}).blur(function () {
		if (!$(this).val()) {
			$(this).val(defaultValue);
		}
		if ($(this).val() === defaultValue) {
			$(this).addClass("default");
		}
	});

	// UK Fleet page specific - tabbing
	$(".tabItem").click(function () {
		var idx = $(".tabItem").index(this),
			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: 'oCtaHelper'
	 * It has the methods:
	 * oCtaHelper.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.
	 *
	 * oCtaHelper.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.oCtaHelper = (function () {
		/* Initialize some variables */
		var sGroupName,
			isIElte6,
			$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 */
		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) */
		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);
			},
			/*
			 * Does only the namechange from ctaX to ctaY for all button classnames that may 
			 * be. Always use this method - DO NOT REPLACE THE CLASSNAMES MANUALLY, since some
			 * classnames you may not be aware of are set under certain conditions (e.g. ieLte6 fix classes
			 * such as .ctaXsizeN).
			 */
			setType: function (oButton, sTypeClass) {
				return $(oButton).each(function () {
					this.className = this.className.replace(/cta\d+/g, sTypeClass);
				});
			},
			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) {
	var s, f, o, i, e;

	if (url) {
		s = url.substring(url.indexOf("?") + 1, url.length);
		f = s.split("&");
		//arr = true;
		if (arr) {
			o = [];
		}
		else {
			o = {};
		}
		for (i = 0; i < f.length; i += 1) {
			e = f[i].split("=");
			if (arr) {
				o.push(e[1]);
			}
			else {
				o[e[0]] = e[1];
			}
		}
		return o;
	}
}


// Write prices in soccercards from JSON:
// First deactivate all teasers "Already from" in case file couldn't be loaded or the file has an error:
function writeModelPricesInSoccercards(filename)
{
	var file = "/" + filename + ".json";
	var alreadyFromTranslation = $(".soccercard > li > .boxTop > .wrapper > .teaser").html();
	$(".soccercard > li > .boxTop > .wrapper > .teaser").empty();
	$.getJSON(file, 
		  function(data){
			$.each(data.models, function(i, item)
			{
				$("#sc_minprice_" + item.model).append(alreadyFromTranslation + "<span class='price nobr'>" + item.minprice + "</span>");
			});
		  });
}


/* 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) {
	var date = new Date();
	if (!sParamName) {
		return;
	}
	sParamValue   = sParamValue || null;
	sPath         = sPath || '/';
	iDaysToExpire = parseInt(iDaysToExpire, 10) || 365;

	//date.setTime(date.getTime() + (iDaysToExpire * 24 * 60 * 60000));
	date.setTime(date.getTime() + (iDaysToExpire * 86400000));
	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"),
			offsetX;

		$("#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 */
		offsetX  = $dSearch.offset().left;

		if (offsetX + $dSearch.outerWidth() > $(window).width()) {
			$("#dealerSearchWrp").css({left: parseInt($dSearch.css("left"), 10) - offsetX - $dSearch.outerWidth() + $(window).width() + 'px'});
		}
		return false;
	});

	$("#searchItem").closest("form").submit(function (event) {
		var $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 */
