function init_survey() {}

//ensure the availability of a console:
var debugConsole = window.console;
if (!window.console) {
	 /* logging impossible, but ensure availability of objects */ 
	debugConsole = {
	    log:   function() {},
	    error: function() {},
	    debug: function() {},
	    print: function() {},
	    isDummy: true
	};

	try {
	    window.console = debugConsole;
	} catch (e) { /* ignore */ }

	// please see the functions LOG and LOG_ERR

} else {
    if(!debugConsole.error) {
	    debugConsole.error = debugConsole.log;
    }
}

/** Utility function to determine the URL parameters. To avoid circular dependencies,
 * do not use the functions LOG() or LOG_ERR() found in this file.
 * @param url
 * @return map */
function getURLParams(url) {
	var params = {};
	var theUrl = url;
	if(!theUrl) {
		theUrl = window.location.href;
	}
	if(!getURLParams.parameters) {
		getURLParams.parameters = {};
	}
	if(getURLParams.parameters[theUrl]) {
		return getURLParams.parameters[theUrl];
	}
	if(theUrl.indexOf('?') < 0) {
		return params;
	}
	var splittedUrl = theUrl.split('?');
	var rawParams;
	if(splittedUrl && splittedUrl[1]) {
		rawParams = splittedUrl[1].split('#')[0];
		rawParams = rawParams.split('&');
		var cursor = "";
		for(var i = 0; i < rawParams.length; i++) {
			cursor = rawParams[i].split('=');
			if(cursor[1]) {
				if(!params[cursor[0]]) {
					params[cursor[0]] = cursor[1];
				} else if(params[cursor[0]] != cursor[1]) {
					debugConsole.log('\t***** ERROR ***** URL "' + 
							theUrl + 
							'" contains an inconsistent parameter duplication! Key: "' +
							cursor[0] +
							'" Value 1: "' +
							params[cursor[0]] +
							'" Value 2: "' + 
							cursor[1] + '"');
				}
			}
		}
	}
	getURLParams.parameters[theUrl] = params;
	return params;
}

function loggingEnabled() {
	return getURLParams()['enableJSLogging'] != null;
}

/** Write the given message to the console, if logging is enabled. */
function LOG(message, relatedObjects, messageType) {
	if(loggingEnabled()) {
		var logFun = debugConsole.log;
		if(messageType == 'error') {
			logFun = debugConsole.error;
			message = '\t***** ERROR *****\n' + message + '\n';
		}
		message = 'at ' + (new Date().getTime()) + ': ' + message;
		if(relatedObjects || messageType == 'error') {
			logFun(message, relatedObjects);
		} else {
			logFun(message);
		}
	}
}

/** Write the given message as an error to the console, if logging is enabled. */
function LOG_ERR(message, relatedObjects) {
	LOG(message, relatedObjects, "error");
}

/** If e.g. the urlString 'http://some.server.mercedes-benz.com/some/handle.flash.html'
 * is given, this method will remove the host part and the part after the bare
 * handle. Thus the resulting string would be '/some/handle'. If the urlString
 * would be relative ('/some/handle.flash.html') or ie6-relative-for-some-cases
 * ('some/handle.flash.html'), the resulting handle would still be '/some/handle'. */
function stripUrlToHandle(/*relative or absolute*/ urlString) {
	var stripped = urlString.replace(/^[^\/]*\/\/[^\/]*\//, '/').replace(/\..*/, '');
	if(stripped.charAt(0) != '/') {
		stripped = '/' + stripped;
	}
	return stripped;
}

/** @param json See <a href="http://json.org">json.org</a>.
 * @return Serializes a json-object into a string. */
function json2string(json) {
    if(json == null) {
        return 'null';
    }
    var type = typeof json;
    if(type == 'string') {
        return '"' + json + '"';
    }
    if(
        type == 'number' ||
        type == 'boolean'
    ) {
        return json.toString();
    }
    var objDelimiter = ['{','}'];
    var isArray = json instanceof Array;
    if(isArray) {
        objDelimiter = ['[',']'];
    }
    var result = objDelimiter[0];
    for(var key in json) {
        if(!isArray) {
            result += '"' + key + '":';
        }
        // recursion:
        result += json2string(json[key]);
        result += ',';
    }
    if(result.length > 1) {
        result = result.substring(0,result.length - 1);
    }
    result += objDelimiter[1];
    return result;
}

/* for backward compatibility / facelift */
function setPositions() {
	var footer = getLayer("ms-footer");
	
	if(footer) {
		footer.style.display = "block";
	}
}

if (typeof handleScroll == "undefined") {
	function handleScroll() {}
}
if (typeof setDocumentPosition == "undefined") {
	function setDocumentPosition() {}
}
function initPage(statustext) {
	setStatusText(escape(statustext));
}

/*** showroom ***/
var showroomImg = new Object();
var showroomTo = null;
function showModel(id, imgSrc) {
	try {
		if(showroomTo != null) {
			clearTimeout(showroomTo);
		}
		showroomTo = setTimeout("showNewModel('" + id + "', '" + imgSrc + "')", 100);
	} catch(e) {}
}

function showNewModel(id, imgSrc) {
	try {
	getLayer("showroom$initial").style.display = "none";
	getLayer("showroom$img").style.display = "block";
	if(!showroomImg[id]) {
		showroomImg[id] = new Image(480, 255);
		showroomImg[id].src = imgSrc;
	}
	getLayer("showroom$img").getElementsByTagName("img")[0].src = showroomImg[id].src;
	getLayer("showroom$facts").style.display = "block";
	getLayer("showroom$factsinner").innerHTML = getLayer(id).innerHTML;
	} catch(e) {}
}


/* HPC */
var ishpc = false;

function setApplicationType(type) {
	if(document.all && !window.opera) {
		embflashlayer = getLayer("embflashie");
	} else {
		embflashlayer = getLayer("embflash");
	}

	if(type != null && type != "") {
		if(type == "hpc") {
			ishpc = true;

			if(location.href.indexOf(".skipintro") != -1) {
				embflashlayer.SetVariable("nowelcome", true);
				embflashlayer.setVariableFl10("nowelcome", true);
			} else {
				embflashlayer.SetVariable("nowelcome", false);
				embflashlayer.setVariableFl10("nowelcome", false);
			}
      addEvent(embflashlayer, "mouseover", ms_restartFlash);
		}
	}
}

/**
 * sets the default status text
 */
function setStatusText(statusText) {
	window.status = unescape(statusText);
	window.defaultStatus = unescape(statusText);
}

/**
 * opens a popup window
 */
var popUps = new Array();
var DEF_POPUP_ATTR = "width=440,height=550,left=20,top=20,scrollbars=yes,resizable=no,status=no";
var DEF_POPUP_NAME = "emb_popup";
function openChild(source, name, attributes) {
	if(!source) {
		return;
	}
	attributes = attributes || DEF_POPUP_ATTR;
	name = name || DEF_POPUP_NAME;
	if (!popUps[name] || popUps[name].closed==true) {
		window.open(source,name,attributes);
	} else {
		popUps[name].close();
		popUps[name] = window.open(source,name,attributes);
	}
}

var focusTimout;
function jsCallFromFlash(flashcall) {
	if(flashcall != null && flashcall != "") {
		var flashcall = flashcall.replace("return false;", "");
		eval(flashcall);
		if((flashcall.indexOf("window.open") >= 0) && neww) {
		  if(document.all && !window.opera) var embFlashLayer = getLayer("embflashie");
    	else var embFlashLayer = getLayer("embflash");
    	embFlashLayer.stopChapter();
    	focusTimeout = window.setTimeout("addFocusEvent()", 500);
    }
	}
}

function addFocusEvent()
{
  window.clearTimeout(focusTimeout);
  addEvent(window, "focus", resumeChapter);
}

function resumeChapter()
{
  removeEvent(window, "focus", resumeChapter);
  if(document.all && !window.opera) var embFlashLayer = getLayer("embflashie");
  else var embFlashLayer = getLayer("embflash");
  embFlashLayer.playChapter();
}

function jsCall(style)
{
  if(document.all && !window.opera) var embFlashLayer = getLayer("embflashie");
  else var embFlashLayer = getLayer("embflash");
  if(style == "stop") embFlashLayer.stopChapter();
  else embFlashLayer.playChapter();
}

/**
	some common helper functions
*/

function getLayer( strID )
{
	if( document.all && !window.opera )
		return document.all[ strID ];
	else
		return document.getElementById( strID );
}

function setClass(element, className) {
	if(element == null || className == null) {
		return;
	}

	if(document.all && !window.opera) {
		element.className = className;
	} else{
		element.setAttribute("class", className);
	}
}

function removeClass(element) {
	if(element == null) {
		return;
	}

	if(document.all && !window.opera) {
		element.className = "";
	} else{
		element.removeAttribute("class");
	}
}

function getClassName(element) {
	if(element == null) {
		return "";
	}
	var className = document.all && !window.opera ? element.className : element.getAttribute("class");
	return className == null ? "" : className;
}

/**
* set events, w3c-compatible and ie
*/
function addEvent(obj, eventType, func, useCaption)
{
	if (!obj || !eventType || !func) {
		return false;
	} else if (obj.addEventListener) {
		obj.addEventListener(eventType, func, useCaption);
		return true;
	} else if (obj.attachEvent) {
    var retVal = obj.attachEvent("on"+eventType, func);
		return retVal;
	} else {
		return false;
	}
}

/**
* remove events, w3c-compatible and ie
*/
function removeEvent(obj, eventType, func, useCaption)
{
	if (!obj || !eventType || !func) {
		return false;
	} else if (obj.removeEventListener) {
		obj.removeEventListener(eventType, func, useCaption);
		return true;
	} else if (obj.detachEvent) {
		var retVal = obj.detachEvent("on"+eventType, func);
		return retVal;
	} else {
		return false;
	}
}


/**
 * special handling for ie 6, to place the bottom of the window
 */
if(document.all && !window.opera) {
	try {
		if (navigator.appName=="Microsoft Internet Explorer" && navigator.appVersion.indexOf("MSIE")>0) {		
			var str = navigator.appVersion;
			var ind = parseInt(str.indexOf("MSIE"))+5;
			var ver = parseInt(str.substring(ind, ind+1));
			if (ver<7) {
				addEvent(window, "load", initFooterIE);
			}
		}
	} catch(e) {}
}

function initFooterIE() {
	window.onscroll = positionFooter;
	window.onresize = positionFooter;
	positionFooter();
}

/*
 * Bug 32187 iPad: Footer verrutscht; start
 * Set footer's position to 1000px for iPad/iPod/iPhone 
 */
if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
	addEvent(window, "load", initFooterIPad);
}

function initFooterIPad(){

		if (getLayer("ms-footer")){
			ms_footer = getLayer("ms-footer");
		}
		if (getLayer("nav5")){
			ms_footer = getLayer("nav5");
		}
		if (ms_footer){
			ms_footer.style.position ="absolute";
			ms_footer.style.top ="2000px";
			ms_footer.style.width ="1000px";
			ms_footer.style.marginBottom = "0px";
			ms_footer.style.marginTop = "100%";

		}
}
/*
 * Bug 32187 iPad: Footer verrutscht; end
 */

function positionFooter() {
	try {
		var toolbarHeight = 0;
		if (getLayer("cms_position")){
			if (getLayer("CFCToolBarDiv")) {
				 toolbarHeight = getLayer("CFCToolBarDiv").offsetHeight;
			}
		}
		//var ms_footer = null;
		if (getLayer("ms-footer")){
			ms_footer = getLayer("ms-footer");
		}
		if (getLayer("nav5")){
			ms_footer = getLayer("nav5");
		}
		if (ms_footer){
			var topValue = document.documentElement.clientHeight + document.documentElement.scrollTop - ms_footer.offsetHeight - toolbarHeight;
			ms_footer.style.position = "absolute";
			ms_footer.style.display = "block";		
			if( 
					getLayer("CFCToolBarDiv")!=null  			// only on author-instance bug#32643
					&&
					MSFlyoutTruck==null		// exception for truck-templates bug#32944
				) { 				
					topValue = topValue - 44; 			
			}
			ms_footer.style.top = topValue;
			ms_footer.style.visibility = "visible"; 
		}
	} catch(e) {
		//alert(e.description);
	}
}


function positionMBTitle() {
	var titleLayer = getLayer("ms-mb-title");
	var menuLayer = getLayer("ms-navi-home");
	var left = 0; // used as margin

	// Error handling
	if (titleLayer == undefined || menuLayer == undefined) {
		return;
	}

	// Add menu position and width
	left += menuLayer.offsetLeft;
	left += menuLayer.offsetWidth;

	// Set position tags
	menuLayer.style.position = "absolute";
	menuLayer.style.cssFloat = "none";
	titleLayer.style.position = "absolute";
	titleLayer.style.cssFloat = "none";

	// Set left position
	titleLayer.style.left = left + "px";
	titleLayer.style.top = "8px";
}

// stop flash if popup has been opened
function ms_checkFlashstop() {
	if(document.all && !window.opera) {
		embflashlayer = getLayer("embflashie");
	} else {
		embflashlayer = getLayer("embflash");
	}

	if(window.ms_setT998Cookie) {
		return;
	}
	if(embflashlayer == null || (!embflashlayer)) {
		ms_openT998Popup();
	} else {
		if(!window.ms_update) {
			ms_stopFlash();
		}
	}
}


function ms_stopFlash() {
	if(document.all && !window.opera) {
		embflashlayer = getLayer("embflashie");
	} else {
		embflashlayer = getLayer("embflash");
	}

	try{
		if(embflashlayer.PercentLoaded() != 100) {
			setTimeout("ms_checkFlashstop()", 500);
			return;
		}
	}
	catch(err){
	}
	
  if(ms_openT998Popup()) {
		embflashlayer.StopPlay();
		ms_checkPopupClose();
	}
}

function ms_openT998Popup() {
	if(!window.set_cookie) {
		return;
	}
	var ms_popupLink = document.cookie;
	if(ms_popupLink == null) {
		return false;
	}
	var ms_expTime = new Date();
  	set_cookie("$ms_externalFlash", "none", 1000 * 60 * 60 * 24, "/content");
	ms_popupLink = ms_popupLink.match(/\$ms_externalFlash=[^;]+/);
	if(ms_popupLink == null || ms_popupLink == "" || !ms_popupLink.length) {
		return false;
	}
	ms_popupLink = ms_popupLink[0].match(/=.+/)[0].substr(1);
	if(ms_popupLink == "none") {
    return false;
	}
	window["$ms_extPopup"] = window.open(unescape(ms_popupLink), "daimler");
	return true;
}

addEvent(window, "load", ms_checkFlashstop);

// checks, if opened popup has been closed to start flash again
function ms_checkPopupClose() {
	if(window["$ms_extPopup"] && !window["$ms_extPopup"].closed) {
		setTimeout("ms_checkPopupClose()", 500);
		return;
	}
	ms_restartFlash();
}

// go on with flash if popup has been closed
function ms_restartFlash() {
	if(document.all && !window.opera) {
		embflashlayer = getLayer("embflashie");
	} else {
		embflashlayer = getLayer("embflash");
	}

	if(embflashlayer == null || (!embflashlayer)) {
		return;
	}

	if((ishpc) && window["$ms_extPopup"]) {
		embflashlayer.Play();
	}

	if(!ishpc) {
		embflashlayer.Play();
	}
}

function changeBackground(divElement, whichGif) {
	if(navigator.appVersion.toLowerCase().indexOf("msie 6")!=-1) {
		if(whichGif==1) {
			document.getElementById(divElement).style.backgroundImage='url(/css/css_ng/btn_PCN2lightBlue.gif)';
		} else {
			document.getElementById(divElement).style.backgroundImage='url(/css/css_ng/btn_PCN2blue.gif)';
		}
	}
}

function checkForEnter(event, form){
	
	if (event && (event.which == 13 || event.keyCode == 13)) {    
    	form.submit();   
    }
   	else{
    	return true;
    } 
}

//called by Flash to implement internal links
function flashLinkInternal(href, trackingCode) {

	  if (trackingCode != "") {
		  embTrackingManager().sendLinkEvent(trackingCode);
	  }
	  location.href = href;
}

//called by Flash to implement external Links
function flashLinkExternal(href, windowParams, windowName, trackingCode) {

	  if (trackingCode != "") {
		  embTrackingManager().sendLinkEvent(trackingCode);
	  }
	  var neww = window.open(href,windowName,windowParams); 
	  if(neww) {
		  neww.focus();
	  } 
}
	
//called by Flash to implement external Links on Layers
function flashLinkExternalLayer(linkXML,trackingCode) {
    window.embGetLayerManager().loadNewLayer(linkXML);
}	
	
/**
 * This function requires two URL parameter lists without the prefix
 * up to the url-path (the part before the '?') and without an URL fragment
 * (the part after the '#'). 
 * @param paramList1
 * 			...for example ?one=1&two=2
 * @param paramList2
 * 			...for example ?one=1&three=3
 * @return
 * 			...for example ?one=1&two=2&three=3
 * @throws
 * 			...an exception if the parameter lists contain invalid values. For
 * 			example the first list contains some_key=valueA and the second
 * 			parameter list contains the same key with a different value, thus
 * 			some_key=valueB. Also an exception will be thrown, if one of the
 * 			parameter lists does contain something else then parameters.
 */
function mergeURLParameters(paramList1, paramList2) {

	// error handling for wrong parts
	var funIsParamList = function(paramList) {
		var qMarkPosition = paramList.indexOf('?'); 
		if(qMarkPosition != 0) {
			if(qMarkPosition > 0) {
				throw "Parameter list contains illegal prefix for a merge: " + paramList;
			}
		}
		var sharpPosition = paramList.indexOf('#');
		if(sharpPosition >= 0) {
			throw "Parameter list may not contain an URL fragment: " + paramList;
		}
	}
	
	funIsParamList(paramList1);
	funIsParamList(paramList2);
	
	// remove question marks
	var hadQuestionMark = false;
	var funReplaceQuestionMark = function(pList) {
		if(pList.indexOf('?') != -1) {
			hadQuestionMark = true;
			return pList.replace( /\?/, '');
		}
		return pList;
	}
	paramList1 = funReplaceQuestionMark(paramList1);
	paramList2 = funReplaceQuestionMark(paramList2);
	
	var merged = {};
	var paramArr1 = paramList1.split( /&/ );
	var paramArr2 = paramList2.split( /&/ );
	
	var funBuildMergeMap = function(map, arr) {
		var keyCursor;
		var valCursor;
		var itemArr;
		for(var i in arr) {
			itemArr = arr[i].split( /=/ );
			if(itemArr) {
				keyCursor = itemArr[0];
				valCursor = itemArr[1];
			}
			if(keyCursor && valCursor) {
				if(map[keyCursor] && map[keyCursor] != valCursor) {
					throw "Invalid values for key '" +
						keyCursor                    + 
						"'! Value 1: '"              + 
						map[keyCursor]               + 
						"', value 2: '"              +
						valCursor                    +
						"'!";
				} else {
					map[keyCursor] = valCursor;
				}
			}
		}
	}
	
	funBuildMergeMap(merged, paramArr1);
	funBuildMergeMap(merged, paramArr2);
	
	// serialize again, but merged:
	var result = hadQuestionMark ? "?" : "";
	for(var key in merged) {
		result += key + "=" + merged[key] + "&";
	}

	return result.substring(0, result.length - 1);
	
}
