/*! $Id: global.js 13344 2012-01-13 15:56:52Z jharth $ */
/*global $: false, jQuery: false, window: false, modelName: false, modelYear: false, doPassVar: false, write: false, s_gi: false, s_account: false */
"use strict";

$(document).ready(function () {
	/***
	* Global Search Field
	*/
	(function () {
		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
	* if display != none, all others have to use the refresh methods described below.
	* (Init/refresh appends corners where needed, applies the size className
	* and makes all grouped buttons equal in height and/or width, depending on their classNames
	* (see below) for each group.
	* Grouped buttons that are to be initialized on DOM ready need to have classNames indicating
	* they are grouped, and their group number: "grouped groupN" where N is the group number, starting
	* at 1. There may be no missing group numbers, for the init process will stop if groupN+1 is not found.
	*
	* Button groups that are refreshed manually with refreshGroup() may lack those classNames - the method will
	* treat all buttons passed to it as a single group.
	*
	* Default behaviour is to make all buttons of a group equal in height. Width adjustment is triggered
	* by giving the buttons in a group either one of the two optional classes "groupWidth" (additional width adjustment)
	* or "groupWidthOnly" (width adjustment only). It is possible to mix those two classNames inside a group.
	*
	* Provides a global object: 'oCtaHelper', supporting 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
	*
	* oCtaHelper.setType(oButton, sTypeClass)
	*     changes the button type from ctaX to ctaY for all button classnames there 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).
	*     buttons may be a button DOM-node (or an array of them),
	*     or the jquery selection of one or more buttons
	*     sTypeClass is the className of the new buttonType (e.g. cta3)
	*
	*/

	/*
	* 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.ieLte6Helper = (function () {
		return {
			isIElte6: ((/MSIE (\d+\.\d+);/).test(navigator.userAgent) && (RegExp.$1) * 1.0 <= 6)
		};
	}());

	window.oCtaHelper = (function () {
		/* Initialize some variables */
		var sGroupName,
			isIElte6,
			$allButtons     = $("a.button"), /* extending the selector may have serious impact on the performance */
			$groupedBtns    = $allButtons.filter(".grouped"),
			$singleButtons  = $allButtons.not(".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 = window.ieLte6Helper.isIElte6;
		/* END IE6 SUPPORT */
		function setSizeClass($buttons) {
			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.children(".corner")
					.toggleClass("oddHeightFix", $currentButton.innerHeight() % 2 !== 0)
					.toggleClass("oddWidthFix",  $currentButton.innerWidth() % 2 !== 0);
					/** set ieLte6 sizeclasses **/
					$currentButton.get(0).className = $currentButton.get(0).className.replace(/ +cta\d+size\d+/g, '');
					/* and set the new one */
					if (/ *(cta\d+) */.test($currentButton.get(0).className)) {
						$currentButton.addClass(RegExp.$1 + sSizeClassName);
					}
				}
				/* END IE6 SUPPORT */
			});
		}

		function applyCorners($button) {
			/* append corners to a single button (if button is not static) */
			if (!$button.hasClass("static") && !$button.children(".topLeft, .topRight, bottomLeft, .bottomRight").addClass("corner").length) {
				$button.append(sCornerWrappers);
			}
		}
		function setPaddings($button, iSizeDifference, sPaddingType) {
			var sPaddingName, iAddPadding1 = 0, iAddPadding2 = 0;

			if (iSizeDifference % 2) {
				iAddPadding1 = (iSizeDifference - 1) / 2;
				iAddPadding2 = iAddPadding1 + 1;
			} else {
				iAddPadding1 = iAddPadding2 = iSizeDifference / 2;
			}
			sPaddingName = sPaddingType === 'height' ? "paddingTop" : "paddingLeft";
			$button.css(sPaddingName, parseInt($button.css(sPaddingName), 10) + iAddPadding1 + "px");

			sPaddingName = sPaddingType === 'height' ? "paddingBottom" : "paddingRight";
			$button.css(sPaddingName, parseInt($button.css(sPaddingName), 10) + iAddPadding2 + "px");
		}
		function updateButtonGroup($buttons) {
			var iGroupHeight = 0,
				iGroupWidth  = 0;
			$buttons.each(function () {
				var $currentButton = $(this);
				if (!$currentButton.hasClass('groupWidthOnly')) {
					iGroupHeight = Math.max(iGroupHeight, $currentButton.height());
				}
				if ($currentButton.is('.groupWidth, .groupWidthOnly')) {
					iGroupWidth  = Math.max(iGroupWidth,  $currentButton.width());
				}
			}).each(function () {
				var $currentButton = $(this);
				/* resize paddings to make height = groupHeight */
				if (!$currentButton.hasClass('groupWidthOnly')) {
					setPaddings($currentButton, iGroupHeight - $currentButton.height(), 'height');
				}
				/* resize paddings to make width = groupWidth */
				if ($currentButton.is('.groupWidth, .groupWidthOnly')) {
					setPaddings($currentButton, iGroupWidth - $currentButton.width(), 'width');
				}
				/* set all size related classNames */
				applyCorners($currentButton);
				setSizeClass($currentButton);
			});
		}

		/* 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);
		}
		setSizeClass($singleButtons);
		applyCorners($singleButtons);

		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);
			},
			setType: function (oButtons, sTypeClass) {
				return $(oButtons).each(function () {
					this.className = this.className.replace(/cta\d+/g, sTypeClass);
				});
			},
			refresh: function (oButtons) {
				$(oButtons).each(function () {
					var $currentButton = $(this);
					setSizeClass($currentButton);
					applyCorners($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",
		alreadyFromTranslation = $(".soccercard > li > .boxTop > .wrapper > .teaser").html();
	$(".soccercard > li > .boxTop > .wrapper > .teaser").empty();
	$.getJSON(file,
		function (data) {
			$.each(data.models, function (i, item) {
				if (item && item.model) { //IE Bugfix: "'model' is null or not an object"
					$("#sc_minprice_" + item.model).append(alreadyFromTranslation + "<span class='price nobr noWrap'>" + item.minprice + "</span>");
						if (item.minpriceSecond) {
						$("#sc_minprice_" + item.model).append(" <span class='price'>/</span><br/><span class='price nobr'>" + item.minpriceSecond + "</span>");
					}
				}
			});
		}
	);
}

/*
* 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 () {
    if (0 === $("#metaNav .dealerSearch, #metaNavi .dealerSearch").length)
    {
        return;
    }

	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 */
/* start omniture tagging for various elements in meta and footer navigation, brochure request cta at soccercard and modeloverview, download pdf 
at modeloverview and technical data */
jQuery(document).ready(function () {
	var	sAccount			=	window.s_account ||	"",
		sAccountListIndex	=	sAccount.indexOf(","),
		omnitureTagId		=	sAccount;

	if (-1 !== sAccountListIndex) {
		omnitureTagId = sAccount.substring(0, sAccountListIndex);
	}

	if ("" !== omnitureTagId) {
		jQuery("#navi-support-brochure-request").click(function () {
			s_gi(omnitureTagId).tl(this, 'e', 'Brochure Request Utility Nav');
		});
		jQuery("#navi-support-contact-overview").click(function () {
			s_gi(omnitureTagId).tl(this, 'e', 'Contact Overview Utility Nav');
		});
		jQuery("#navi-meta1-contact-overview").click(function () {
			s_gi(omnitureTagId).tl(this, 'e', 'Contact Overview Footer Nav');
		});
		jQuery("#navi-meta1-sitemap").click(function () {
			s_gi(omnitureTagId).tl(this, 'e', 'Sitemap Footer Nav');
		});
		jQuery("a[id*=Brochure-Request]").click(function () {
				s_gi(omnitureTagId).tl(this, 'e', this.id.replace(/-/g,' '));
		});
		jQuery("ul#navigationLvl1 ul.soccercard a.button[id]").click(function () {
				var s = s_gi(omnitureTagId);
				s.prop28 = this.id;
				s.linkTrackVars="prop28";
				jQuery(window).unload(function () { 
					s.tl();} 
					);
		});	
		jQuery("#model-overview-price-pdf").click(function () {
			var s = s_gi(omnitureTagId);
			s.linkTrackVars = "eVar2,events";
			s.linkTrackEvents = "event46";
			s.eVar2 = "Price List Download";
			s.events = "event46";
			s.tl(this, "e", "Model Overview Pricelist Download");
		});
		jQuery("#model-technical-data-price-pdf").click(function () {
			var s = s_gi(omnitureTagId);
			s.linkTrackVars = "eVar2,events";
			s.linkTrackEvents = "event46";
			s.eVar2 = "Price List Download";
			s.events = "event46";
			s.tl(this, "e", "Features & Specs Pricelist Download");
		});
	}
});
/* end omniture tagging for brochure request in meta navigation */
/* start bluestreak-tagging */
jQuery(document).ready(function () {
	if( typeof(bluestreakTaggingLink) != "undefined" ) {
		var bluestreakTaggingURL = bluestreakTaggingLink || "";
		/*var oPricePdfDownloadTrackingConfig = function (t) {
				return {
					pdfDownloadClicked: function (data) {
							t.call(bluestreakTaggingURL);
						}
					}
				}
		
		var pageTracking = new WebAppTracker(oPricePdfDownloadTrackingConfig);	*/	 
		
			jQuery("#model-technical-data-price-pdf").click(function () {
				if ("" !== bluestreakTaggingURL)
					{	
					jQuery("body").append("<img src='" + bluestreakTaggingURL +"' width=1 height=1 border=0>");
						/*pageTracking.setTrackingEvent('pdfDownloadClicked');*/
					}
										 
				});
			jQuery("#model-overview-price-pdf").click(function () {
				if ("" !== bluestreakTaggingURL)
					{	
					jQuery("body").append("<img src='" + bluestreakTaggingURL +"' width=1 height=1 border=0>");
						/*pageTracking.setTrackingEvent('pdfDownloadClicked');*/
					}
			});
			
			jQuery("ul#navigationLvl1 ul.soccercard a[id*=SoccerCard-PDF]").click(function () {
				if ("" !== bluestreakTaggingURL)
					{	
					jQuery("body").append("<img src='" + bluestreakTaggingURL +"' width=1 height=1 border=0>");
					}
			});
		}
		
		if( typeof(bluestreakTaggingFrame) != "undefined" ) {
		var bluestreakTaggingFrameURL = bluestreakTaggingFrame || "";
		
			jQuery("#model-technical-data-price-pdf").click(function () {
				if ("" !== bluestreakTaggingFrameURL)
					{	
						jQuery("body").append("<!--suppress HtmlDeprecatedTag --><iframe scrolling='no' frameborder='0' width='1' height='1' src='" + bluestreakTaggingFrameURL +"'");
					}
										 
				});
			jQuery("#model-overview-price-pdf").click(function () {
				if ("" !== bluestreakTaggingFrameURL)
					{	
						jQuery("body").append("<!--suppress HtmlDeprecatedTag --><iframe scrolling='no' frameborder='0' width='1' height='1' src='" + bluestreakTaggingFrameURL +"'");
					}
			});
			jQuery("ul#navigationLvl1 ul.soccercard a[id*=SoccerCard-PDF]").click(function () {
				if ("" !== bluestreakTaggingFrameURL)
					{	
						jQuery("body").append("<!--suppress HtmlDeprecatedTag --><iframe scrolling='no' frameborder='0' width='1' height='1' src='" + bluestreakTaggingFrameURL +"'");
					}
			});
		}	
});
/* end bluestreak-tagging */
/* mediamind tagging for pdf-downloads */
jQuery(document).ready(function () {
	if( typeof(mediamindPdfTaggingId) != "undefined" ) {
		var mediamindPdfId = mediamindPdfTaggingId || "";
		
				/*var ebRand = Math.random()+'';
				ebRand = ebRand * 1000000;*/
		
			jQuery("#model-technical-data-price-pdf").click(function () {
				if ("" !== mediamindPdfId)
					{	
					var jIFrame = jQuery('<iframe width="1" height="1" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000"/>');
					jIFrame.attr("src", "http://tagging.bpinteractive.com/mediamind.jspx?ActivityID=" + mediamindPdfId);
					jIFrame.appendTo("body");
					/*jQuery("body").append("<iframe src='http://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&amp;ActivityID=" + mediamindPdfId +"&amp;ifrm=1&amp;rnd=" + ebRand +"' width='0' height='0' marginwidth='0' marginheight='0' hspace='0' vspace='0' frameborder='0' scrolling='no' bordercolor='#000000'></iframe>");*/
					}
										 
				});
			jQuery("#model-overview-price-pdf").click(function () {
				if ("" !== mediamindPdfId)
					{
					var jIFrame = jQuery('<iframe width="1" height="1" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000"/>');
					jIFrame.attr("src", "http://tagging.bpinteractive.com/mediamind.jspx?ActivityID=" + mediamindPdfId);
					jIFrame.appendTo("body");	
					/*jQuery("body").append("<iframe src='http://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&amp;ActivityID=" + mediamindPdfId +"&amp;ifrm=1&amp;rnd=" + ebRand +"' width='0' height='0' marginwidth='0' marginheight='0' hspace='0' vspace='0' frameborder='0' scrolling='no' bordercolor='#000000'></iframe>");*/
					}
			});
			
			jQuery("ul#navigationLvl1 ul.soccercard a[id*=SoccerCard-PDF]").click(function () {
				if ("" !== mediamindPdfId)
					{
					var jIFrame = jQuery('<iframe width="1" height="1" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000"/>');
					jIFrame.attr("src", "http://tagging.bpinteractive.com/mediamind.jspx?ActivityID=" + mediamindPdfId);
					jIFrame.appendTo("body");
					/*jQuery("body").append("<iframe src='http://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&amp;ActivityID=" + mediamindPdfId +"&amp;ifrm=1&amp;rnd=" + ebRand +"' width='0' height='0' marginwidth='0' marginheight='0' hspace='0' vspace='0' frameborder='0' scrolling='no' bordercolor='#000000'></iframe>");*/
					}
			});
		}
		
			
});
/* end mediamind-tagging */
/* model overview priceInfo-layer */

function displayInfoLayer(element) {

var infoLayer = element.length;
var layerID = element.substring(1,infoLayer);
var layerNR = element.substring(infoLayer-1,infoLayer);

if(document.getElementById(layerID).parentNode.offsetLeft > 500 || (layerNR == 3 && document.getElementById(layerID).parentNode.offsetParent.tagName == 'LI'))
	{
	$("" + element + " div.priceInfoCopyContainer").addClass('infoLayerRight');
	}
	else
	{
	$("" + element + " div.priceInfoCopyContainer").removeClass('infoLayerRight');
	}
$(element).removeClass('buttonHide');

}

function hideInfoLayer(element) {
$(element).addClass('buttonHide');
}

/**
* Check for mobile devices
*/
function isIOS(){
	return (
		(navigator.platform.indexOf("iPad") != -1) ||
		(navigator.platform.indexOf("iPhone") != -1) ||
		(navigator.platform.indexOf("iPod") != -1)
	);
}


function isMobile(){
	return (
		isIOS() ||
		(navigator.userAgent.match(/Android/i))
	);
}
/* added from assets2 global.js for CTA-Navi New Captiva*/
$(document).ready(function () {
    $('.lvl2CTA a').hover(
        function () {
            $(this).addClass('hover');
        },
        function () {
            $(this).removeClass('hover');
        }
    );
});

/* dependant popin function*/
function onLoadOverlayRedirectFactory(targetElement, configFile){

    var sourceReferrer = document.referrer;
    var sourceURL = document.location.href;
    var configData;
    var layerURL;

    jQuery.ajax({
        url: configFile,
        type: "GET",
        dataType: "json",
        success: function(data) {
                configData = data;
                compareReferrer();
            },
        error: function(msg) {
            if ('object' === typeof(console)) {
                console.log(' Error: ' + msg);
            }
        }
    });

    function compareReferrer(){
        var redirectURL , matched;
        var serviceURL = configData.serviceURL ;
        $("body").append('<div id="wrapperOnLoadOverlay"></div>');
        $.each(configData.map, function() {
            matched++;
            if(this.regex==='true'){
                var regexp =  new RegExp(this.referrer);
                if (regexp.test(sourceReferrer)) {
                    getOverlay(this);
                }
            }
            else {
                if(sourceReferrer === this.referrer){
                    getOverlay(this);
                }
            }
        });

        function getOverlay(that){
            layerURL = that.layerURL;
            var toLoad = layerURL+ ' ' + targetElement;
            $('#wrapperOnLoadOverlay').load(toLoad);
            serviceURL = serviceURL.replace("$(locale)",configData.locale);
            serviceURL = serviceURL.replace("$(map.local)",that.locale);
            serviceURL = serviceURL.replace("$(sourceURL)",sourceURL);
            jQuery.ajax({
                url: serviceURL,
                type: "GET",
                dataType: "json",
                success: function(data) {
                        startOverlay(data);
                    },
                error: function(msg) {
                        if ('object' === typeof(console)) {
                            console.log(' Error: ' + msg);
                        }
                    }
            });
        }

    }

    function startOverlay(targetURL) {
        var $targetElement = $(targetElement);
        var $buttonList = $targetElement.find('.button');

        window.oCtaHelper.refresh($buttonList);
        $buttonList.attr('href',targetURL);
        $targetElement.overlay({
            top: 185,
            mask: {
                color: '#000',
                loadSpeed: 50,
                opacity: 0.5
            },
            fixed: false,
            load: true
        });
    }

}
/* glossary pages reset cookie */
$(document).ready(function () {
  deleteLastPageCookie();
});
function deleteLastPageCookie() {
	var	sAccount			=	window.s_account ||	"";
	if ("" !== sAccount) {
		var s = s_gi(sAccount);
		if (s.channel !== 'glossary') {
			document.cookie = "lastPageBeforeGlossary=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
		}
	}
}

if ("undefined" === typeof com)
{
    var com;
}
com = com || {};
com.chevroleteurope = com.chevroleteurope || {};
com.chevroleteurope.dealerlocator = com.chevroleteurope.dealerlocator || {};

//=============================================================================
// Define DealerLocator Class
com.chevroleteurope.dealerlocator.FlyOut = com.chevroleteurope.dealerlocator.FlyOut || (function ()
{
    "use strict";

    var cookieName = "partnerLocatorQueryValue";
    var jWindow = jQuery(window);

    //noinspection LocalVariableNamingConventionJS
    var FlyOut = function(model)
    {
        this.uri = model.uri || null;

        this.htmlId = model.htmlId || null;

        this.flyOutFragmentSelector = "#partnerLocatorFlyOutFragment";
        this.flyOutContainerSelector = "div.partnerLocatorFlyOutContainer";
        this.flyOutSelector = "div.partnerLocatorFlyOut";

        this.inputWarningCssClass = "warning";

        this.isBroken = false;
        this.isLoading = false;

        this.onPartnerLocatorClickProxy = jQuery.proxy(onPartnerLocatorClick, this);
        this.onDocumentReadyProxy = jQuery.proxy(onDocumentReady, this);
        this.onLoadFlyOutCompleteProxy = jQuery.proxy(onLoadFlyOutComplete, this);
        this.onFlyOutFormSubmitProxy = jQuery.proxy(onFlyOutFormSubmit, this);
        this.onFlyOutCloseClickProxy = jQuery.proxy(onFlyOutCloseClick, this);
        this.onFlyOutSubmitClickProxy = jQuery.proxy(onFlyOutSubmitClick, this);
        this.onFlyOutInputFocusProxy = jQuery.proxy(onFlyOutInputFocus, this);
        this.onFlyOutInputBlurProxy = jQuery.proxy(onFlyOutInputBlur, this);

        jQuery(document).ready(this.onDocumentReadyProxy);
    };

    FlyOut.prototype.uri = null;
    FlyOut.prototype.htmlId = null;

    FlyOut.prototype.jPartnerLocator = null;

    FlyOut.prototype.isBroken = null;
    FlyOut.prototype.isLoading = null;

    FlyOut.prototype.inputWarningCssClass = null;

    FlyOut.prototype.flyOutFragmentSelector = null;
    FlyOut.prototype.jFlyOutFragment = null;

    FlyOut.prototype.flyOutContainerSelector = null;
    FlyOut.prototype.jFlyOutContainer = null;

    FlyOut.prototype.flyOutSelector = null;
    FlyOut.prototype.jFlyOut = null;

    FlyOut.prototype.jForm = null;
    FlyOut.prototype.jInput = null;
    FlyOut.prototype.jCloseButton = null;
    FlyOut.prototype.jSubmitButton = null;

    var attachPartnerLocatorEventHandlers = function ()
    {
        this.jPartnerLocator.bind("click", this.onPartnerLocatorClickProxy);
    };

    var detachPartnerLocatorEventHandlers = function ()
    {
        this.jPartnerLocator.unbind("click", this.onPartnerLocatorClickProxy);
    };

    var attachFlyOutEventHandlers = function ()
    {
        this.jForm.bind("submit", this.onFlyOutFormSubmitProxy);
        this.jCloseButton.bind("click", this.onFlyOutCloseClickProxy);
        this.jSubmitButton.bind("click", this.onFlyOutSubmitClickProxy);
        this.jInput.bind("focus", this.onFlyOutInputFocusProxy);
        this.jInput.bind("blur", this.onFlyOutInputBlurProxy);
    };

    var detachFlyOutEventHandlers = function ()
    {
        this.jForm.unbind("submit", this.onFlyOutFormSubmitProxy);
        this.jCloseButton.unbind("click", this.onFlyOutCloseClickProxy);
        this.jSubmitButton.unbind("click", this.onFlyOutSubmitClickProxy);
        this.jInput.unbind("focus", this.onFlyOutInputFocusProxy);
        this.jInput.unbind("blur", this.onFlyOutInputBlurProxy);
    };

    FlyOut.prototype.onDocumentReadyProxy = null;
    var onDocumentReady = function (event)
    {
        this.jPartnerLocator = jQuery("#" + this.htmlId);
        this.jFlyOutContainer = jQuery(this.flyOutContainerSelector);
        attachPartnerLocatorEventHandlers.call(this);
    };

    FlyOut.prototype.onPartnerLocatorClickProxy = null;
    var onPartnerLocatorClick = function (event)
    {
        if (!this.isBroken)
        {
            if (!this.isLoading)
            {
                openFlyOut.call(this);
            }
            event.preventDefault();
            return false;
        }
    };

    var isFieldPrePopulated = function (jInput)
    {
        var dInput = jInput.get(0),
            currentValue = jInput.val(),
            trimmedValue = jQuery.trim(currentValue),
            isDefaultValue = currentValue === dInput.defaultValue,
            isEmpty = 0 === trimmedValue.length;
        return isDefaultValue || isEmpty;
    };

    var positionFlyOut = function (jFlyOut)
    {
        /* if the dealer search box would get cut off on the right
         (view port too small) -> reposition it to the left */
        var flyOutOffsetLeft = jFlyOut.offset().left;
        var flyOutOuterWidth = jFlyOut.outerWidth();
        var windowWidth = jWindow.width();

        if (flyOutOffsetLeft + flyOutOuterWidth > windowWidth)
        {
            var cssPropertyName = "left";
            var oldCssLeftValue = jFlyOut.css(cssPropertyName),
                oldCssLeft = parseInt(oldCssLeftValue, 10),
                newCssLeft = oldCssLeft - flyOutOffsetLeft - flyOutOuterWidth + windowWidth,
                newCssLeftValue = newCssLeft + "px";
            jFlyOut.css(cssPropertyName, newCssLeftValue);
        }
    };

    var loadFlyOut = function ()
    {
        this.isLoading = true;
        var url = this.uri + " " + this.flyOutFragmentSelector;
        this.jFlyOutContainer.load(url, this.onLoadFlyOutCompleteProxy);
    };

    FlyOut.prototype.onLoadFlyOutCompleteProxy = null;
    var onLoadFlyOutComplete = function (responseText, textStatus, XMLHttpRequest) {
        if ("success" !== textStatus && "notmodified" !== textStatus)
        {
            this.isBroken = true;
            this.isLoading = false;
            return;
        }
        initializeFlyOut.call(this);
        showFlyOut.call(this);
        this.isLoading = false;
    };

    var initializeFlyOut = function ()
    {
        var jFlyOutFragment = this.jFlyOutContainer.find(this.flyOutFragmentSelector);
        this.jFlyOutFragment = jFlyOutFragment;

        var jFlyOut = jFlyOutFragment.find(this.flyOutSelector);
        this.jFlyOut = jFlyOut;

        this.jForm = jFlyOut.find("form");
        this.jInput = jFlyOut.find("input[name='query']");
        this.jCloseButton = jFlyOut.find("span.close");
        this.jSubmitButton = jFlyOut.find("a.search");

        jFlyOut.unwrap();

        oCtaHelper.refresh(this.jSubmitButton);

        attachFlyOutEventHandlers.call(this);
    };

    FlyOut.prototype.onFlyOutFormSubmitProxy = null;
    var onFlyOutFormSubmit = function (event)
    {
        if (isFieldPrePopulated(this.jInput))
        {
            showWarning.call(this);
            event.preventDefault();
            return false;
        }
        storeCookieValue.call(this);
    };

    FlyOut.prototype.onFlyOutCloseClickProxy = null;
    var onFlyOutCloseClick = function (event)
    {
        hideFlyOut.call(this);
        event.preventDefault();
        return false;
    };

    FlyOut.prototype.onFlyOutSubmitClickProxy = null;
    var onFlyOutSubmitClick = function (event)
    {
        this.jForm.submit();
        event.preventDefault();
        return false;
    };

    FlyOut.prototype.onFlyOutInputFocusProxy = null;
    var onFlyOutInputFocus = function (event)
    {
        if (isFieldPrePopulated(this.jInput))
        {
            hideInputLabel.call(this);
        }
    };

    FlyOut.prototype.onFlyOutInputBlurProxy = null;
    var onFlyOutInputBlur = function (event)
    {
        if (isFieldPrePopulated(this.jInput))
        {
            showInputLabel.call(this);
        }
    };

    var openFlyOut = function ()
    {
        var jFlyOut = this.jFlyOutContainer.find(this.flyOutSelector);
        if (0 === jFlyOut.length)
        {
            loadFlyOut.call(this);
        }
        else
        {
            showFlyOut.call(this);
        }
    };

    var restoreCookieValue = function ()
    {
        var cookieValue = getCookieParam(cookieName),
            trimmedCookieValue = jQuery.trim(cookieValue),
            isString = "string" === cookieValue,
            isEmpty = 0 === trimmedCookieValue.length;
        if (isString && !isEmpty)
        {
            this.jInput.val(cookieValue);
        }
    };

    var storeCookieValue = function ()
    {
        var currentValue = this.jInput.val(),
            trimmedValue = jQuery.trim(currentValue),
            isString = "string" === currentValue,
            isEmpty = 0 === trimmedValue.length;
        if (isString && !isEmpty)
        {
            setCookie(cookieName, currentValue);
        }
    };

    var showFlyOut = function ()
    {
        restoreCookieValue.call(this);
        hideWarning.call(this);
        positionFlyOut(this.jFlyOut);
        this.jFlyOut.show();
    };

    var hideFlyOut = function ()
    {
        this.jFlyOut.hide();
    };

    var showWarning = function ()
    {
        this.jInput.addClass(this.inputWarningCssClass);
    };

    var hideWarning = function ()
    {
        this.jInput.removeClass(this.inputWarningCssClass);
    };

    var showInputLabel = function ()
    {
        var dTarget = this.jInput.get(0),
            defaultValue = dTarget.defaultValue;
        this.jInput.val(defaultValue);
    };

    var hideInputLabel = function ()
    {
        this.jInput.val("");
    };

    return FlyOut;

}());
