var shareUrl = self.location.href;
var shareTitle = document.title;
var selectedHighlightUrl = "";
var swf_corelib = buildValidServerRelativeUrl("/_common/files/swf/libraries/bmw_as3_corelib_1_1.swf");
var swf_components = buildValidServerRelativeUrl("/_common/files/swf/components/bmw_as3_components_2_0.swf");
var salesNavigationTopPos = 634;
var co2DisclaimerCookieName = "";

function inArray(value,thisArray) {
  for (var i = 0; i < thisArray.length; i++) {
    if (thisArray[i] === value) {
      return true;
     }
  }
  return false;
};

function initStandardPage() {
  checkClient();
  checkWindowSize();
  salesNavigationCheckPosition();

  $(window).resize(function(){
    checkWindowSize();
    salesNavigationCheckPosition();
  });

  $(window).scroll(function(){
    checkWindowSize();
    salesNavigationCheckPosition();
  });

  highlightNavigations();
  highlightVehicleNavigation();
}


function co2DisclaimerCheck() {
  var tempArray = self.location.href.split("/");
  for(i = tempArray.length - 1; i >= 0; i--) {
    if(!tempArray[i-3]) {
      break;
    }
    else if(tempArray[i] == "showroom") {
      co2DisclaimerCookieName = "co2disclaimer_" + tempArray[i-3] + "_" + tempArray[i-2] + "_" + tempArray[i-1];
      break;
    }
  }
  if(!getCookieValue(co2DisclaimerCookieName)) {
    $("#co2Disclaimer").show();
  }
}

function divisible(number,divider) {
   var temp = 0;
   var result = false;
   temp = number % divider;
   if(temp == 0) {
     result = true;
   }
   return result;
}

function highband_check(url) {
  selectedHighlightUrl = url;
  if(!highbandUser) {
    $("#bandwidth_advice_curtain").show();
    $("#bandwidth_advice").show();
  }
  else {
   self.location.href = url;
  }
}

function closeBandwidthAdvice() {
  $("#bandwidth_advice_curtain").hide();
  $("#bandwidth_advice").hide();
}

function shareThis(url,service) {
  url = url.replace("{#share_url}", encodeURIComponent(shareUrl));
  url = url.replace("{#share_title}", encodeURIComponent(shareTitle));

  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/share.html") + "?source=" + self.location.pathname + "&target=" + encodeURIComponent(service);
    trackAbsolute(trackingUrl,'');
  }
  window.open(url,"share");
  return false;
}

function dialogBoxesSetDimensions() {
  $('.dialogbox,.shadowbox').each(function() {
    $(this).find(".content").css("height","auto");
    var contentWidth = $(this).find(".content").width();
    var contentHeight = $(this).find(".content").height();
    $(this).find(".leftBorder").css("height",contentHeight + 18);
    $(this).find(".rightBorder").css("height",contentHeight + 18);
    $(this).find(".content").css("height",contentHeight);
    $(this).find(".content").css("width",contentWidth);
    $(this).find(".topBorder").css("width",contentWidth - 6 + 24);
    $(this).find(".bottomBorder").css("width",contentWidth - 4 + 24);
    contentWidth = $(this).width();
    contentHeight = $(this).height();

    if( $(this).hasClass("nobottom") ) {
      contentHeight += 10;
    }


    $(this).find("img.background").attr("width", contentWidth - 6).attr("height", contentHeight - 10).show();
  });
}

function favoriteDelete(deleteOid) {
  $("#deleteDialogLayer").css("visibility","hidden");
  $("#deleteDialogLayer").css("top","-500px");
  $("#deleteDialogLayer").css("left","-500px");
  $("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete").removeClass("dialogButtonShareActive").removeClass("dialogButtonDownloadActive").removeClass("dialogButtonFavoriteActive").removeClass("dialogButtonDeleteActive");
  resetToggle("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete");

  if(typeof(favoriteData) != "undefined") {
    var newCookieString = "";
    if(getCookieValue("favorites")) {
      var favoritesArray = getCookieValue("favorites").split(";");
      for(i = 0; i < favoritesArray.length; i++) {
        if(favoritesArray[i] != deleteOid) {
          newCookieString += favoritesArray[i];
          if(i != favoritesArray.length - 1) {
            newCookieString += ";";
          }
        }
      }
      setCookie("favorites", newCookieString, "Sun, 31-Dec-2100 00:00:00 GMT", "/");
    }
  }
}

function favoritesSaved() {
  var dummy = new Array();
  if(getCookieValue("favorites")) {
    var favoritesArray = getCookieValue("favorites").split(";");
    return favoritesArray;
  }
  else {
    return dummy;
  }
}


//document.ready start
$(document).ready(function() {

  if(!highbandUser) {
    $("a.highlight_link").click(function () {
      highband_check($(this).attr("href"));
      return false;
    });
  }

  //favorites start
  if(typeof(favoriteData) != "undefined" && typeof(pageOid) != "undefined") {
    if(!favoriteData[pageOid]) {
      $(".dialogButtonFavorite").hide();
    }
    else {
      if(isCookiesEnabled()) {
        var pageAlreadyBookmarked = false;
        if(getCookieValue("favorites")) {
          var favoritesArray = getCookieValue("favorites").split(";");
          for(i = 0; i < favoritesArray.length; i++) {
            if(favoritesArray[i] == pageOid) {
              $("#favoriteNotActive").hide();
              $("#favoriteActive").show();
              $("a.dialogButtonFavorite, a.dialogButtonFavoriteActive").css('background-position','0px -295px');
              break;
            }
          }
        }
      }
    }
  }
  else {
    $(".dialogButtonFavorite").hide();
  }

  $("a.dialogButtonFavorite").click(
    function() {

      $("#favoriteDialogLayer").css("top","-1500px");

      var pageAlreadyBookmarked = false;
      if(isCookiesEnabled()) {
        if(getCookieValue("favorites")) {
          var favoritesArray = getCookieValue("favorites").split(";");
          for(i = 0; i < favoritesArray.length; i++) {
            if(favoritesArray[i] == pageOid) {
              pageAlreadyBookmarked = true;
            }
          }
          if(!pageAlreadyBookmarked) {
            favoritesArray.push(pageOid);
          }
        }
        else {
          var favoritesArray = new Array(pageOid);
        }
        if(!pageAlreadyBookmarked) {
          var cookieString = "";
          for(i = 0; i < favoritesArray.length; i++) {
            cookieString += favoritesArray[i];
            if(i != favoritesArray.length - 1) {
              cookieString += ";";
            }
          }
          setCookie("favorites", cookieString, "Sun, 31-Dec-2100 00:00:00 GMT", "/");
          if(confTrackingEnabled) {
            var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/bookmark.html") + "?url=" + self.location.pathname + "&action=bookmark_save";
            trackAbsolute(trackingUrl);
          }
        }
        $("#favoriteNotActive").hide();
        $("#favoriteActive").show();
        $("#favoriteNoCookie").hide();
        $("a.dialogButtonFavorite, a.dialogButtonFavoriteActive").css('background-position','0px -295px');
      }
      else {
        $("#favoriteActive").hide();
        $("#favoriteNotActive").hide();
        $("#favoriteNoCookie").show();
      }
      dialogBoxesSetDimensions();

      var topPos = $("a.dialogButtonFavorite").offset().top - ($("#favoriteDialogLayer").height() - 5);
      $("#favoriteDialogLayer").css("top", topPos + "px");

  });
  //favorites end

// ******** NAVIGATION START ******** //
  //start: salesnavi event-steuerung

  $(".sales_navigation_layer").mouseenter(function(event) {
    if($(event.target).attr("class")== "sales_navigation_layer"){
      $("#" + event.currentTarget.id.replace(/button/g, "layer") + " div").mouseleave();
    }
  });

  $("#sales_navigation ul a").mouseenter(function(event) {
    var activeLayerName = "#" + event.currentTarget.id.replace(/button/g, "layer");
    $(".sales_navigation_layer").hide();
    $("#sales_navigation ul a.first").css("width","97px");
    $("#sales_navigation ul a:gt(0)").css("width","98px");
    $(activeLayerName).css("left", $("#" + event.currentTarget.id).offset().left );
    salesNavigationButtonWidth = "150px";
    if( $("#" + event.currentTarget.id).hasClass("first")) {
      salesNavigationButtonWidth = "149px";
    }
    $("#" + event.currentTarget.id).css("width",salesNavigationButtonWidth);
    $(activeLayerName + " div").mouseleave(function(event) {
      salesNavigationButtonWidth = "98px";
      try {
        if( $("#" + $(event.currentTarget).parent().get(0).id.replace(/layer/g, "button")).hasClass("first")) {
          salesNavigationButtonWidth = "97px";
        }
        salesNavigationButtonElement = $("#" + $(event.currentTarget).parent().get(0).id.replace(/layer/g, "button"));
        salesNavigationLayerElement = $("#" + $(event.currentTarget).parent().get(0).id);

        if( $(event.relatedTarget).parent().attr("id") ) {
          if($(event.relatedTarget).parent().attr("id").indexOf("sales_navigation_select") == -1 && $(event.relatedTarget).attr("id").indexOf("sales_navigation_select") == -1) {
            closeSalesNavLayer(salesNavigationButtonWidth, salesNavigationLayerElement, salesNavigationButtonElement);
          }
        }
        else {
          closeSalesNavLayer(salesNavigationButtonWidth, salesNavigationLayerElement, salesNavigationButtonElement);
        }

      }
      catch(e) {}
    })

    $(activeLayerName).show();
    $(activeLayerName).height($(activeLayerName + " .box").height()+25);
    $(activeLayerName).css("top", salesNavigationTopPos - ($(activeLayerName + " .box").height() + 25));

  })
  //end: salesnavi event-steuerung

  //start: salesnavi selectboxes event-steuerung
  $("a.sales_navigation_selectbox").toggle(
    function (event) {
      $(".sales_navigation_dropdown").hide();
      resetToggle("a.sales_navigation_selectbox",this);
      var newTopPos = ($(this).offset().top) - ($("#sales_navigation_" + event.target.id).height()) - 6;
      $("#sales_navigation_" + event.target.id).css("top",newTopPos).css("left",$(this).offset().left);
      $("#sales_navigation_" + event.target.id).show();
      $("#sales_navigation_" + event.target.id).mouseleave(function(event){
        if($(event.relatedTarget).parent().attr("class") != "box" && $(event.relatedTarget).parent().attr("class") != "sales_navigation_layer" ) {
          closeSalesNavLayer(salesNavigationButtonWidth, salesNavigationLayerElement, salesNavigationButtonElement);
        }
      });
    },
    function (event) {
      $("#sales_navigation_" + event.target.id).hide();
    }
  );
  $(".sales_navigation_dropdown a").click(function (event) {
    var elementID = $(this).parent().attr("id").replace(/sales_navigation_/g, "");
    $("#" + elementID).html( $(this).html() );

    if($(this).parent().attr("id") == "sales_navigation_select_models") {
      replaceParameterInLink("sales_navigation_configuration_link", "{color_value}", sales_navigation_configuration_last_value_color, "{model_value}", $(this).attr("href"), sales_navigation_configuration_link_original);
      replaceParameterInLink("sales_navigation_accessory_link", "{color_value}", sales_navigation_configuration_last_value_color, "{model_value}", $(this).attr("href"), sales_navigation_accessory_link_original);
      sales_navigation_configuration_last_value_model = $(this).attr("href");
    }
    else if($(this).parent().attr("id") == "sales_navigation_select_colors") {
      replaceParameterInLink("sales_navigation_configuration_link", "{color_value}", $(this).attr("href"), "{model_value}", sales_navigation_configuration_last_value_model, sales_navigation_configuration_link_original);
      replaceParameterInLink("sales_navigation_accessory_link", "{color_value}", $(this).attr("href"), "{model_value}", sales_navigation_configuration_last_value_model,  sales_navigation_accessory_link_original);
      sales_navigation_configuration_last_value_color = $(this).attr("href");
    }
    else if($(this).parent().attr("id") == "sales_navigation_select_compare_1") {
      replaceParameterInLink("sales_navigation_compare_link", "{model1}", $(this).attr("href"), "{model2}", sales_navigation_compare_last_value_2, sales_navigation_compare_link_original);
      sales_navigation_compare_last_value_1 = $(this).attr("href");
    }
    else if($(this).parent().attr("id") == "sales_navigation_select_compare_2") {
      replaceParameterInLink("sales_navigation_compare_link", "{model1}", sales_navigation_compare_last_value_1, "{model2}", $(this).attr("href"), sales_navigation_compare_link_original);
      sales_navigation_compare_last_value_2 = $(this).attr("href");
    }
    return false;
  });
  //end: salesnavi selectboxes event-steuerung

  //start salesnavi highlighting

  for(i = 1; i <= 7; i++) {
    $("#sales_navigation_layer_" + i + " a").each(function() {
      var linkUrl = $(this).attr("href").split("?");
      if( self.location.pathname.indexOf(linkUrl[0]) != -1 && !$("#sales_navigation_button_" + i).hasClass("blue")) {
        $("#sales_navigation_button_" + i).css("color","#1d6ad4");
        $(this).addClass("standard_active").removeClass("standard");
      }
    });
  }

  //extra compare
  if($("#sales_navigation_compare_link").attr("href")) {
    var myTempTestUrl = $("#sales_navigation_compare_link").attr("href").split("?");
    if( self.location.pathname.indexOf(myTempTestUrl[0]) != -1 ) {
      $("#sales_navigation_button_compare").css("color","#1d6ad4");
      $(this).addClass("standard_active").removeClass("standard");
    }
  }

  //end salesnavi highlighting


// ******** NAVIGATION END ******** //

// ******** PREPARE DIALOG BOXES START ******** //
  var dialogBoxexIEStyles = "<style type=\"text/css\">"
  + ".dialogbox .topBorder, .shadowbox .topBorder {background-image:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/files/img/dialogbox/dialogbox_top.png', sizingMethod='scale');}"
  + ".dialogbox .rightBorder, .shadowbox .rightBorder {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/files/img/dialogbox/dialogbox_right.png', sizingMethod='crop');}"
  + ".dialogbox .bottomBorder, .shadowbox .bottomBorder {background-image:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/files/img/dialogbox/dialogbox_bottom.png', sizingMethod='crop');}"
  + ".dialogbox .bottomBorder .bottomArrowImage, .shadowbox .bottomBorder .bottomArrowImage {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/files/img/dialogbox/dialogbox_bottom_arrow.png', sizingMethod='crop');}"
  + ".dialogbox .bottomBorder .bottomArrowImageRight, .shadowbox .bottomBorder .bottomArrowImageRight {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/files/img/dialogbox/dialogbox_bottom_arrow.png', sizingMethod='crop');}"
  + ".dialogbox .leftBorder, .shadowbox .leftBorder {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/files/img/dialogbox/dialogbox_left.png', sizingMethod='crop');}"
  + ".dialogbox .corner, .shadowbox .corner {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/files/img/dialogbox/dialogbox_corner.png', sizingMethod='crop');}"
  + "<style>";

  jQuery.each(jQuery.browser, function(i, val) {
    if(i == "msie" && jQuery.browser.version.substr(0,1) == "6")
     $("body").append(dialogBoxexIEStyles);
  });

  if(typeof(share_services_active) == "boolean" &&  share_services_active) {
    var sharelayerCode = '<div class="dialogbox" id="shareDialogLayer"><div class="content"><div class="sharecontent"><strong>' + share_services_headline + '</strong><table width="210" cellspacing="0" cellpadding="0" border="0">'
    for(i=0; i < share_services.length; i++ ) {
      if(i == 0 || divisible(i,2)) {
        sharelayerCode += '<tr valign="top">';
      }
      sharelayerCode += '<td width="22"><img src="' + getWcmsPrefix() + share_services[i][2] + '" width="17" height="16"></td>';
      sharelayerCode += '<td width="83"><a href="" onClick="javascript:shareThis(\'' + share_services[i][1] + '\',\'' + share_services[i][0] + '\');return false;" class="standard">' + share_services[i][0] + '</a></td>';
      if(!divisible(i,2)) {
        sharelayerCode += '</tr>';
      }
      if(divisible(i,2) && (i + 1 == share_services.length)) {
        sharelayerCode += '<td></td><td></td></tr>';
      }
    }
    sharelayerCode += '</table></div></div></div>';
    $("body").append(sharelayerCode);
  }
  else {
    $("a.dialogButtonShare").hide();
  }

  $(".dialogbox").prepend('<img class="background" src="' + getWcmsPrefix() + '/_common/files/img/dialogbox/dialogbox_background.gif" height="10" width="10">');
  $(".shadowbox").prepend('<img class="background" src="' + getWcmsPrefix() + '/_common/html/img/palette/1x1_ffffff.gif" height="10" width="10">');
  $(".dialogbox").append('<div class="bottomBorder"><div class="bottomArrowImage"></div></div><div class="corner"></div>');
  $(".shadowbox").not(".nobottom").append('<div class="bottomBorder"></div><div class="corner"></div>');
  $(".dialogbox .content, .shadowbox .content").append('<div class="topBorder"></div><div class="leftBorder"></div><div class="rightBorder"></div>');


  dialogBoxesSetDimensions();

  $("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete").hover(
    function (event) {

      dialogBoxesSetDimensions();

      var layerName = "#" + event.target.id + "Layer";
      var topPos = $(this).offset().top - ($(layerName).height() - 5);
      var leftPos = $(this).offset().left - 4;
      var layerWidth = $(layerName).width();
      if(1020 - leftPos - layerWidth < 0) {
        leftPos = leftPos - layerWidth + 22;
        $(layerName + " .bottomArrowImage").addClass("bottomArrowImageRight").removeClass("bottomArrowImage");
      }
      $(layerName).css("top", topPos ).css("left", leftPos);
      $(layerName).css("visibility","visible");
      $("#" + event.target.id).addClass( $("#" + event.target.id).attr("class") + "Active");
      $(layerName).bind("mouseleave", function(){
        $(layerName).css("visibility","hidden");
        $(layerName).css("top","-500px");
        $(layerName).css("left","-500px");
        $("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete").removeClass("dialogButtonShareActive").removeClass("dialogButtonDownloadActive").removeClass("dialogButtonFavoriteActive").removeClass("dialogButtonDeleteActive");
        $(".dialogbox").unbind("mouseleave", function(){});
      });
      return false;
    },
    function (event) {
      if( $(event.relatedTarget).attr("class") != "bottomArrowImage" && $(event.relatedTarget).attr("class") != "bottomArrowImageRight" && $(event.relatedTarget).attr("class") != "bottomBorder" && $(event.relatedTarget).attr("class") != "dialogbox" ) {
        var layerName = "#" + event.target.id + "Layer";
        $(layerName).css("visibility","hidden");
        $(layerName).css("top","-500px");
        $(layerName).css("left","-500px");
        $("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete").removeClass("dialogButtonShareActive").removeClass("dialogButtonDownloadActive").removeClass("dialogButtonFavoriteActive").removeClass("dialogButtonDeleteActive");
      }
      return false;
    }
  );
// ******** PREPARE DIALOG BOXES END ******** //
});
//document.ready end


// ******** NAVIGATION START ******** //
var salesNavigationButtonWidth, salesNavigationLayerElement, salesNavigationButtonElement;

function closeSalesNavLayer(buttonWidth, layerElement, buttonElement) {
  $(".sales_navigation_dropdown").hide();
  resetToggle("a.sales_navigation_selectbox");
  buttonElement.css("width",buttonWidth);
 layerElement.hide();
}

function resetToggle(selector,currentObject) {
  $(selector).each(function() {
    if(currentObject != this) {
      this.lastToggle = undefined;
    }
  });
}

function replaceParameterInLink(linkId, oldValue1, newValue1, oldValue2, newValue2, originalPattern) {
  var newLink = originalPattern.replace(oldValue1, newValue1);
  newLink = newLink.replace(oldValue2, newValue2);

  if(newLink.indexOf("http://") == -1) {
    newLink = getWcmsPrefix() + newLink;
  }


  $("#"+ linkId).attr("href", newLink);
}

function zipCodeSearchAction(url, target) {
  if(document.contact_search_form.zipcode.value) {
    if(confTrackingEnabled) {
      var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_zipcode.html") + "?source=" + self.location.pathname + "&zipcode=" + document.contact_search_form.zipcode.value;
      trackAbsolute(trackingUrl);
    }
    url = url.replace("{zipcode}",document.contact_search_form.zipcode.value);
    if(target == "_self") {
      self.location.href = getWcmsPrefix() + url;
    }
    else {
      window.open(target, url);
    }
  }
}

function vehicle_navigation_teaser_init() {
  var teaser_number = (vehicle_navigation_teaser_db.length - 1) * (Math.random());
  teaser_number = Math.round(teaser_number);
  try{
    if(vehicle_navigation_teaser != "r" && vehicle_navigation_teaser <= vehicle_navigation_teaser_db.length) {
      teaser_number = vehicle_navigation_teaser - 1;
    }
  }
  catch(e) {}
  $("#vehicle_navigation #teaser").css("display","block");
  vehicle_navigation_teaser_write(teaser_number);
}


function vehicle_navigation_teaser_write(teaser_number) {
  var new_teaser_number = teaser_number + 1;
  if(vehicle_navigation_teaser_db.length < new_teaser_number + 1) {
    new_teaser_number = 0;
  }
  var teaser_class = "";
  if (vehicle_navigation_teaser_db[teaser_number][5] == "true") {
    teaser_class = "highlight_link";
  }

  var onClickCode = "";
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/teaser_showroom.html") + "?source=" + self.location.pathname + "&target=" + encodeURIComponent(vehicle_navigation_teaser_db[teaser_number][4]);
    onClickCode = "trackAbsolute('" + trackingUrl + "','');"
  }

  var code = '          <a id="vehicle_navigation_teaser_stage" href="' + getWcmsPrefix() + vehicle_navigation_teaser_db[teaser_number][4] + '" onclick="' + onClickCode + '" class="' + teaser_class + '"><img src="' + getWcmsPrefix() + vehicle_navigation_teaser_db[teaser_number][0] + '" width="176" height="90" alt=""></a>\n';
  if(vehicle_navigation_teaser_db.length > 1) {
     code += '          <a class="vehicleNavigationTeaserButton" onclick="vehicle_navigation_teaser_write(' + new_teaser_number + ');return false;" href=""></a>\n';
  }
     code += '          <div id="teaser_text">\n'
           + '            <strong>' + vehicle_navigation_teaser_db[teaser_number][2] + '</strong>\n'
           + '            <div style="height:3px;"></div>\n'
           + '            <a href="' +  getWcmsPrefix() + vehicle_navigation_teaser_db[teaser_number][4] + '" style="display:block" onclick="' + onClickCode + '" class="standard ' + teaser_class + '">' + vehicle_navigation_teaser_db[teaser_number][3] + '</a>\n'
           + '          </div>\n';

  $("#vehicle_navigation #teaser").html(code);

  if(vehicle_navigation_teaser_db[teaser_number][1] != "") {
    var vehicle_navigation_teaser_flash = new SWFObject(getWcmsPrefix() + vehicle_navigation_teaser_db[teaser_number][1], "vntflash", "176", "90", "9.0.115", "#ffffff");
    vehicle_navigation_teaser_flash.addParam("quality","autohigh");
    vehicle_navigation_teaser_flash.addParam("allowScriptAccess", "sameDomain");
    vehicle_navigation_teaser_flash.addParam("wmode", "transparent");
    vehicle_navigation_teaser_flash.write("vehicle_navigation_teaser_stage");
  }

  if(!highbandUser) {
    $("#vehicle_navigation #teaser a.highlight_link").click(function () {
      highband_check($(this).attr("href"));
      return false;
    });
  }

}

function salesNavigationCheckPosition() {
  if($("#sales_navigation").size() != 0) {
    var documentHeight = $(window).height();
    if(documentHeight < 660) {
      var newTopPos = documentHeight - 68 + $(window).scrollTop()
      if(newTopPos > 591) {
        newTopPos = 591;
      }
      $("#sales_navigation").css("top", newTopPos);
      salesNavigationTopPos = Number($("#sales_navigation").css("top").substring(0, $("#sales_navigation").css("top").indexOf("px"))) + 44;
    }
    else {
      $("#sales_navigation").css("top", "591px");
      salesNavigationTopPos = 634;
    }

    $(".sales_navigation_layer").each(function() {
      $(this).height($("#" + this.id + " .box").height() + 25);
      $(this).css("top", salesNavigationTopPos - ($("#" + this.id + " .box").height() + 25));
    });
  }
}


function highlightVehicleNavigation() {
  var success = false;
  var pageFolder = extractFolders(self.location.href);

  $('#vehicle_navigation ul a').each(function() {
    var naviLinkFolder = extractFolders($(this).attr("href"));
    if(naviLinkFolder[1] == pageFolder[1] && naviLinkFolder[2] == pageFolder[2] && success == false) {
      $(this).css("color","#1d6ad4");
      success = true;
    }
  })

  if(!success) {
    $('#vehicle_navigation ul a').each(function() {
      var naviLinkFolder = extractFolders($(this).attr("href"));
      if(naviLinkFolder[1] == pageFolder[0] && naviLinkFolder[2] == pageFolder[1] && success == false) {
        $(this).css("color","#1d6ad4");
        success = true;
      }
    })
  }
}


function highlightMgmbHPageNavigation() {
  var success = false;
  var pageFolder = extractFolders(self.location.href);
  $('#overview_linklist div a').each(function() {
    var naviLinkFolder = extractFolders($(this).attr("href"));
    if(naviLinkFolder[1] == pageFolder[1] && naviLinkFolder[2] == pageFolder[2] && success == false) {
      $(this).css("color","#1d6ad4");
      success = true;
    }
  })

  if(!success) {
    $('#overview_linklist div a').each(function() {
      var naviLinkFolder = extractFolders($(this).attr("href"));
      if(naviLinkFolder[1] == pageFolder[0] && naviLinkFolder[2] == pageFolder[1] && success == false) {
        $(this).css("color","#1d6ad4");
        success = true;
      }
    })
  }
}

function extractFolders(myString) {
  var splitArray  = myString.split("/");
  var resultArray = new Array(splitArray[splitArray.length - 4], splitArray[splitArray.length - 3], splitArray[splitArray.length - 2]);
  return resultArray;
}


function salesNaviTrackingConfigure() {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_configure.html") + "?source=" + self.location.pathname + "&model=" + sales_navigation_configuration_last_value_model + "&color=" + sales_navigation_configuration_last_value_color;
    trackAbsolute(trackingUrl);
  }
}

function salesNaviTrackingAccessory() {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_accessory.html") + "?source=" + self.location.pathname + "&model=" + sales_navigation_configuration_last_value_model + "&color=" + sales_navigation_configuration_last_value_color;
    trackAbsolute(trackingUrl);
  }
}

function salesNaviTrackingCompare() {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_compare.html") + "?source=" + self.location.pathname + "&model1=" + sales_navigation_compare_last_value_1 + "&model2=" + sales_navigation_compare_last_value_2;
    trackAbsolute(trackingUrl);
  }
}

function salesNaviTrackingLink(url) {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_link.html") + "?source=" + self.location.pathname + "&target=" + url;
    trackAbsolute(trackingUrl);
  }
}


// ******** NAVIGATION END ******** //


// ******** Highlights page START ******** //

function highlightsCloseHighlightLink() {
  if(typeof(close_back_link_url_default) != "undefined") {
    var targetUrl = close_back_link_url_default;
    if(typeof(close_back_link_pattern) != "undefined" && typeof(close_back_link_url_individual) != "undefined") {
      if(document.referrer.indexOf(close_back_link_pattern) != -1) {
        targetUrl = close_back_link_url_individual;
      }
    }
    self.location.href = targetUrl;
  }
}

// ******** Highlights page END ******** //

// ******** Start page START ******** //
function startPageShowHeadlines() {
  $("#start_headlines").show();
}
function startPageHideHeadlines() {
  $("#start_headlines").hide();
}

// ******** Start page END ******** //


// ******** Highlight page START ******** //

function initHighlightPage(){
  mainNavigation.initFolding( 10, 20 );
  flashObject.write("highlightsMainContainer");
  $("#highlightsMainContainer").show();
  co2DisclaimerCheck();
  if($("#co2Disclaimer h4").height() > 15){
    $("#co2DisclaimerContent").height("65px");
  }
  setTimeout(function(){
    $("#co2Disclaimer").hide();
  }, 30000);
  $("#closeCo2Disclaimer").click(function(){
    if($("#co2Disclaimer h4").height() > 15){
      $("#co2DisclaimerContent").height("65px");
    }
    $("#co2Disclaimer").hide();
    if(co2DisclaimerCookieName) {
      setCookie(co2DisclaimerCookieName, "true", "", "/");
    }
  });

  if(confTrackingEnabled) {
    $("#highlightDownloadDialogLayer a").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( trackingPages["download"][0] ) + '?file=' + escape( buildValidServerRelativeUrl($(this).attr("href"))) + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
  }
}

// ******** Highlight page END ******** //


// ******** Content page START ******** //
function contentPageChangeTeaser(){
  saveContentTeaserHTML = $("#contentTeaser" + activeContentTeaser).html();
  $("#contentTeaser" + activeContentTeaser).html($("#contentTeaser0").html());
  $(".mediaStage").hide();
  $("#mediaStage" + activeContentTeaser).show();
  if(mediaType[activeContentTeaser]["type"] == "flash"){
    stageFlash = new SWFObject(mediaType[activeContentTeaser]["url"], "mainFlashMovie", "687", "250", "9.0.115", "#ffffff");
    stageFlash.addParam("quality","autohigh");
    stageFlash.addParam("allowScriptAccess", "sameDomain");
    stageFlash.addParam("wmode", "transparent");
    teaseFlashObject = stageFlash.write("mediaContainer" + activeContentTeaser);
    if(teaseFlashObject){
      var contentPageFolderPath = self.location.pathname.substring(0,self.location.pathname.lastIndexOf("/"));
      var contentPageClickEventPath = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/click_event.html";
      var trackingUrl = buildValidServerRelativeUrl( contentPageClickEventPath ) + '?target=' + escape(contentPageFolderPath + '/film_' + activeContentTeaser + '/start.html') + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
    }
  }else if(mediaType[activeContentTeaser]["type"] == "video"){
    stageFlash = new SWFObject(mediaType[activeContentTeaser]["player"], "mainFlashMovie", "687", "250", "9.0.115", "#ffffff");
    stageFlash.addParam("quality","autohigh");
    stageFlash.addParam("allowScriptAccess", "sameDomain");
    stageFlash.addParam("wmode", "transparent");
    stageFlash.addVariable("prm_flv_url", mediaType[activeContentTeaser]["url"]);
    stageFlash.addVariable("prm_corelib", mediaType[activeContentTeaser]["corelib"]);
    stageFlash.addVariable("prm_components", mediaType[activeContentTeaser]["components"]);
    stageFlash.addVariable("prm_stage_width", "687");
    stageFlash.addVariable("prm_stage_height", "250");
    stageFlash.addVariable("prm_tracking_enabled", "true");
    stageFlash.addVariable("prm_version", "high");
    teaseFlashObject = stageFlash.write("mediaContainer" + activeContentTeaser);
    if(teaseFlashObject){
      var contentPageClickEventPath = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/click_event.html";
      var trackingUrl = buildValidServerRelativeUrl( contentPageClickEventPath ) + '?target=' + escape(contentPageFolderPath + '/film_' + activeContentTeaser + '/start.html') + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
    }
  }else if(mediaType[activeContentTeaser]["type"] == "ani"){
    currentAnimationImage = 0;
    maxAnimationImage = $("#mediaContainer" + activeContentTeaser + " .animationContainer .animationImage").size()-1;
    window.clearTimeout(contentPageAnimationTimer);
    contentPageAnimationTimer = null;
    contentPageAnimationTimer = window.setTimeout("contentPageAnimateImages('next')", 1500);
  }
}

function contentPageAnimateImages(direction){
  $("#mediaContainer" + activeContentTeaser + " .animationImage:eq(" + currentAnimationImage+ ")").fadeOut(1000);
  if(direction == "next"){
    if(currentAnimationImage < maxAnimationImage){
      currentAnimationImage++;
    }else{
      currentAnimationImage = 0;
    }
  }else{
    if(currentAnimationImage > 0){
      currentAnimationImage--;
    }else{
      currentAnimationImage = maxAnimationImage;
    }
  }
  $("#mediaContainer" + activeContentTeaser + " .animationCounter").html((currentAnimationImage<9?"0":"") + (currentAnimationImage+1) + " / " + (maxAnimationImage<9?"0":"")+ (maxAnimationImage+1));
  $("#mediaContainer" + activeContentTeaser + " .animationImage:eq(" + currentAnimationImage+ ")").fadeIn(1000,function(){
    if(contentPageAnimationTimer != null){
      contentPageAnimationTimer = window.setTimeout("contentPageAnimateImages('next')", 3000);
    }
  });
}

var contentPageAnimationTimer = null;
var contentPageControlerTimer = null;
var currentAnimationImage = 0;
var maxAnimationImage = 0;

function initContentPage(){

    co2DisclaimerCheck();
    if($("#co2DisclaimerBg h4").height() > 15){
      $("#co2DisclaimerContent").height("67px");
    }
    setTimeout(function(){
      $("#co2Disclaimer").hide();
    }, 30000);
    $("#co2DisclaimerReopenLink").click(function(){
      $("#co2Disclaimer").show();
      if($("#co2Disclaimer h4").height() > 15){
        $("#co2DisclaimerContent").height("65px");
      }
    });
    $("#closeCo2Disclaimer").click(function(){
      $("#co2Disclaimer").hide();
      if(co2DisclaimerCookieName) {
        setCookie(co2DisclaimerCookieName, "true", "", "/");
      }
    });

    $("#contentText #moreContent").click(function(){
      $("#downloadDialog" + activeContentTeaser).hide();
      $(this).hide();
      $("#contentPageContainer #contentText p").height("auto");
      $("#contentPageContainer #contentText").animate({
        top: "10px",
        paddingTop:"23px",
        height: "357px"},
        "normal",
        "swing",
        function(){
          $("#contentPageContainer .hiddenLongText").slideDown(
            "normal",
            function(){
              shareUrl = self.location.href;
              shareTitle = document.title;
              $("#lessContent").show();
            });
        }
      );

      $("#contentPageContainer #contentTeaserList").attr("topPos", $("#contentPageContainer #contentTeaserList").css("top") );
      var contentTeaserListTop = "55px";
      if($("#contentTeaserList").hasClass("zeroTeaser")){
        contentTeaserListTop = "46px"
      }
      $("#contentPageContainer #contentTeaserList").animate({
        top: contentTeaserListTop},
        "normal",
        "swing"
      );
    });

    $("#contentText #lessContent").click(function(){
      $(this).hide();
      $("#contentPageContainer .hiddenLongText").slideUp(
        "normal",
        function(){
          $("#contentPageContainer #contentText").animate({
            top: "261px",
            paddingTop:"6px",
            height: "133px"},
            "normal",
            "swing",
            function(){
              $("#contentPageContainer #contentText p").height("62px");
              $("#moreContent").show();
              if($("#downloadDialog" + activeContentTeaser + "Layer li").size() != 0){
                $("#downloadDialog" + activeContentTeaser).show();
              }
              shareUrl = self.location.href;
              shareTitle = document.title;
              self.location.href = "#media" + activeContentTeaser;
            }
          );
         $("#contentPageContainer #contentTeaserList").animate({
          top: $("#contentPageContainer #contentTeaserList").attr("topPos")},
          "normal",
          "swing"
        );
        }
      );
    });

    $("#contentTeaserList .contentTeaser img").hover(function(){$(this).next().children().addClass("active")},function(){$(this).next().children().removeClass("active")});

    $("#contentTeaserList .contentTeaser").each(function(i, e){

      $(this).click(function(){
        shareUrl = self.location.href;
        shareTitle = document.title;
        if($("#contentPageContainer #contentTeaserList").css("top") == "55px"){
          $("#lessContent").click();
        }
        if(mediaType[activeContentTeaser]["type"] == "flash" && teaseFlashObject){
          $("#mediaContainer" + activeContentTeaser).html("")
        }
        if(activeContentTeaser != 0){
          $("#contentTeaser" + activeContentTeaser).html(saveContentTeaserHTML);
        }
        if(activeContentTeaser == i){
          activeContentTeaser = 0;
        }else{
          activeContentTeaser = i;
        }
        self.location.href = "#media" + activeContentTeaser;
        contentPageChangeTeaser();
      });
    });

    if(self.location.href.indexOf("#more") != -1){
      if($("#moreContent").html() != null){
        $("#contentPageContainer #contentTeaserList").attr("topPos", $("#contentPageContainer #contentTeaserList").css("top") );
        $("#contentPageContainer #contentText").addClass("more");
        $("#contentPageContainer #contentTeaserList").addClass("more");
        $("#contentPageContainer #contentText p").height("auto");
        $("#contentPageContainer .hiddenLongText").show();
        $("#contentText #moreContent").hide();
        $("#contentText #lessContent").show();
      }
    }

    if(self.location.href.indexOf("#media") != -1 && typeof(activeContentTeaser) != "undefined"){
      activeContentTeaser = self.location.href.substring(self.location.href.indexOf("#media")+6);
      if(($("#mediaStageSingle").html() == null) && (activeContentTeaser < mediaType.length)){
        contentPageChangeTeaser();
      }
    }

    if(mediaType.length > 0){
      if((mediaType[activeContentTeaser]["type"] == "flash") || (mediaType[activeContentTeaser]["type"] == "video")){
        contentPageChangeTeaser();
      }
    }

    for(i=0; i < 4; i++) {
      if($("#downloadDialog" + i + "Layer li").size() != 0){
        $("#mediaStage" + i + " .contentDownloadLink").show();
      }
    }

      if((mediaType.length > 0) && (mediaType[activeContentTeaser]["type"] == "ani")){
        maxAnimationImage = $("#mediaContainer" + activeContentTeaser + " .animationContainer .animationImage").size()-1;
        $("#mediaContainer" + activeContentTeaser + " .animationCounter").html("0" + (currentAnimationImage+1) + " / 0" + (maxAnimationImage+1));

        var animationContainerIsAnimated1 = false;
        var animationContainerIsAnimated2 = false;

        $(".mediaContainer .animationContainer").mouseenter(function(){
          if(!animationContainerIsAnimated1){
            animationContainerIsAnimated1 = true;
            $("#mediaContainer" + activeContentTeaser + " .animationControl").animate(
              {top:"225px"},
              500,
              "swing",
              function(){
                animationContainerIsAnimated1 = false;
              }
            );
          }
        });

        $(".mediaContainer .animationContainer").mouseleave(function(){
          if(!animationContainerIsAnimated2){
            animationContainerIsAnimated2 = true;
            contentPageControlerTimer = setTimeout(function(){
              $("#mediaContainer" + activeContentTeaser + " .animationControl").animate({
                top:"260px"},
                500,
                "swing",
                function(){
                  animationContainerIsAnimated2 = false;
                  window.clearTimeout(contentPageControlerTimer);
                }
              )}, 100);
            }
          }
        );

        $(".mediaContainer .animationPause").click(function(){
          window.clearTimeout(contentPageAnimationTimer);
          contentPageAnimationTimer = null;
          $("#mediaContainer" + activeContentTeaser + " .animationPause").hide();
          return false;
        });

        $(".mediaContainer .animationPlay").click(function(){
          $("#mediaContainer" + activeContentTeaser + " .animationPause").show();
          contentPageAnimationTimer = window.setTimeout("contentPageAnimateImages('next')", 1000);
          return false;
        });

        $(".mediaContainer .animationNext").click(function(){
          window.clearTimeout(contentPageAnimationTimer);
          contentPageAnimationTimer = null;
          $("#mediaContainer" + activeContentTeaser + " .animationPause").hide();
          contentPageAnimateImages("next")
          return false;
        });

        $(".mediaContainer .animationPrevious").click(function(){
          window.clearTimeout(contentPageAnimationTimer);
          contentPageAnimationTimer = null;
          $("#mediaContainer" + activeContentTeaser + " .animationPause").hide();
          contentPageAnimateImages("previous")
          return false;
        });
        contentPageAnimationTimer = window.setTimeout("contentPageAnimateImages('next')", 1000);
      } // type == ani


// add tracking
  if(confTrackingEnabled) {
    var contentPageFolderPath = self.location.pathname.substring(0,self.location.pathname.lastIndexOf("/"));
    var contentPageName = self.location.href.substring(self.location.href.lastIndexOf("/"), self.location.href.indexOf(".htm"));
    var contentPageClickEventPath = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/click_event.html";
    var contentPageDownloadPath   = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/download.html";
    var contentPageRelatedPath    = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/related.html";

    $("#relatedLinks ul li a:not(#co2DisclaimerReopenLink)").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( contentPageRelatedPath ) + '?target=' + escape( buildValidServerRelativeUrl($(this).attr("href"))) + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
    $("div[id^='downloadDialog'] ul li a").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( contentPageDownloadPath ) + '?file=' + escape( buildValidServerRelativeUrl($(this).attr("href"))) + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
    $("a#moreContent").click(function () {
      var trackingUrl = buildValidServerRelativeUrl(contentPageFolderPath + contentPageName + '/read_more.html');
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
    $("#contentTeaserList .contentTeaser").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( contentPageClickEventPath ) + '?target=' + escape(contentPageFolderPath + '/contentTeaser' + activeContentTeaser + '.html') + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
  }
}// initContentPage

// ******** Content page END******** //

// ******** Favorites page START ******** //
function showFavorites() {
  var favoritesValidCounter = 0;
  var favoritesSavedArray = new Array();
  favoritesSavedArray = favoritesSaved();
  if(typeof(favoriteData) != "undefined" || favoritesSavedArray.length > 0) {

    for(i = 0; i < favoritesSavedArray.length; i++) {
      if(favoriteData[favoritesSavedArray[i]]) {
        favoritesValidCounter++;
      }
    }
  if(favoritesValidCounter > 0) {
    var categories = new Array();
    var oldCat = "";
    var cat = "";
    for(i = 0; i < favoritesSavedArray.length; i++) {
      if( favoriteData[favoritesSavedArray[i]] ) {
        cat = favoriteData[favoritesSavedArray[i]][0];
        if(cat != oldCat) {
          categories.push(cat);
          oldCat = cat;
        }
      }
    }
    categories = arrayUnique(categories);
    categories.sort();
    var code = "";
    var code  = '<div id="favoritesGalleryLayer">\n';
    for(i = 0; i < categories.length; i++) {
      code += '<div class="category" style="clear:both;">\n' +
              '  <span class="headline">' + categories[i] + '</span>\n';
      for (y = 0;  y < favoritesSavedArray.length; y++) {
        if(favoriteData[favoritesSavedArray[y]]) {
          if(favoriteData[favoritesSavedArray[y]][0] == categories[i]) {
            var favUrl = favoriteData[favoritesSavedArray[y]][1];
            var favThumbUrl = favoriteData[favoritesSavedArray[y]][2];
            var favDescription = favoriteData[favoritesSavedArray[y]][3];
            code += '<div class="favoritesBoxContainer">\n' +
                  '  <div class="favoritesThumbContainer">\n' +
                  '    <div id="mediaStageSingle" class="mediaStage">\n' +
                  '      <a href="' + getWcmsPrefix() + favUrl + '" onclick="trackFavoriteClick(\'' + favUrl + '\')">\n' +
                  '        <img src="' + getWcmsPrefix()+ favThumbUrl + '" width="110" height="62" alt="">\n' +
                  '      </a>\n' +
                  '    </div>\n' +
                  '    <div class="closefavoritesBox">\n' +
                  '      <a href="" onclick="favoriteDelete(\'' + favoritesSavedArray[y] + '\');self.location.reload();return false;" class="dialogButtonDelete" id="deleteDialog">&nbsp;</a>\n' +
                  '    </div>\n' +
                  '  </div>\n' +
                  '  <div class="favoritesContentText">\n' +
                  '    <p>' + favDescription + '</p>\n' +
                  '  </div>\n' +
                  '</div>\n';

          }
        }
      }
      code += '</div>\n';
    }
    code += '</div>\n';
    $("#favoritesDiv").html(code);
  }
  else  {
     var code = '<div id="favoritesGalleryLayer">\n' +
                '  <div class="categoryFirst">\n' +
                '    <span class="headline">' + favoritesHeadline + '</span>\n' +
                '      <p style="width:405px;">' + favoritesCopytext + '</p> \n' +
                '  </div>\n' +
                '</div>\n';
     $("#favoritesDiv").html(code);
   }
}  else  {
     var code = '<div id="favoritesGalleryLayer">\n' +
                '  <div class="categoryFirst">\n' +
                '    <span class="headline">' + favoritesHeadline + '</span>\n' +
                '      <p style="width:405px;">' + favoritesCopytext + '</p> \n' +
                '  </div>\n' +
                '</div>\n';
     $("#favoritesDiv").html(code);
   }
}

function trackFavoriteClick(favUrl) {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/bookmark.html") + "?url=" + favUrl + "&action=bookmark_select";
    trackAbsolute(trackingUrl,'');
  }
}
// ******** Favorites page END ******** //


// ******** media gallery page START ******** //
function mediaGalleryInitialise() {
  var lightboxAnimation, thisParameterNumber, visibleLightboxObjectNumber, newCategoryLayerHeight, newIconLayerTop;
  var $imageObj = $('div#mediaGalleryLightboxLayer div#lightbox img#bigImage');
  var $flashObj = $('div#mediaGalleryLightboxLayer div#lightbox div#flashLayer');
  var startPageTitle = document.title;
  var startPageUrl = self.location.href;

  if(confTrackingEnabled) {
    var contentPageDownloadPath   = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/download.html";
    $("div#mediaGalleryLightboxLayer div.downloadLayer ul.linklist li a").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( contentPageDownloadPath ) + '?file=' + escape( buildValidServerRelativeUrl($(this).attr("href"))) + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
  }

  function mediaGallerySetCategoryLayerHeight() {
    newCategoryLayerHeight = Math.round($('div#sales_navigation').offset().top - $('div#mediaGalleryCategoriesLayer').offset().top - 42);
    newIconLayerTop = Math.round($('div#sales_navigation').offset().top + 14);
    $('div#mediaGalleryCategoriesLayer').css('height',newCategoryLayerHeight+'px');
    $('div#mediaGalleryDialogButtons').css('top',newIconLayerTop+'px');
  }
  mediaGallerySetCategoryLayerHeight();
  $(window).resize(function() {
    mediaGallerySetCategoryLayerHeight();
  });

  $("a#sales_navigation_button_favs").mouseover(function() {
    var newHeight = Math.round($('div#sales_navigation').offset().top - $('div#mediaGalleryCategoriesLayer').offset().top - 63);
    var newTop = Math.round($('div#sales_navigation').offset().top - 41);
    $('div#mediaGalleryCategoriesLayer').css('height',newHeight+'px');
    $('div#mediaGalleryDialogButtons').css('top',newTop+'px');
  });
  $('div#sales_navigation_layer_favs').mouseout(function() {
    $('div#mediaGalleryCategoriesLayer').css('height',newCategoryLayerHeight+'px');
    $('div#mediaGalleryDialogButtons').css('top',newIconLayerTop+'px');
  });

  $('div.category img').each(function(i) {
    if(lightboxContent[i]["subheadline"] != '') {
      $('div.category div.thumbImageBox').parent().addClass('hasSubheadline');
    }
  }).mousemove(function(e) {
    $('div.dialogbox').each(function(i) {
      $('div#mediaGalleryThumbnailsMouseoverLayer'+i).css({
        left: Math.round(e.pageX - 10) + 'px',
        top: Math.round(e.pageY - $('div#mediaGalleryThumbnailsMouseoverLayer'+i).height() - 5) + 'px'
      });
    });
  }).hover(
    function() {
      var thisThumbImage = $('div.category img').index(this);
      if(lightboxContent[thisThumbImage]["hoverText"] != '') {
        $('div#mediaGalleryThumbnailsMouseoverLayer'+thisThumbImage).css('visibility','visible');
      }
    },
    function() {
      $('div.dialogbox').css('visibility','hidden');
    }
  );

  $('div.category').each(function(i) {
    if($(this).hasClass('hasSubheadline')) {
      var newCategoryHeight = $('div.category:eq('+ i +')').children().next().height();
      $('div.category:eq('+ i +')').css('height',newCategoryHeight+'px');
    }
  });

  function mediaGalleryShareIconIsDisplayedCheck() {
    if(typeof(share_services_active) == "boolean" &&  share_services_active) {
      if($('a.dialogButtonShare').attr('id') == 'shareDialog') {
        $('a.dialogButtonShare').attr('id','');
      }
      if($('div#mediaGalleryLightboxLayer div#lightbox').is(':visible')) {
        $('div#mediaGalleryDialogButtons a.dialogButtonShare, div#textLayer img.shareButton').hide();
        $('div#textLayer a.dialogButtonShare').attr('id','shareDialog');
        $('div#mediaGalleryDialogButtons img.shareButton, div#textLayer a.dialogButtonShare').show();
        shareUrl = self.location.href;
        shareTitle = document.title;
      } else {
        $('div#mediaGalleryDialogButtons img.shareButton, div#textLayer a.dialogButtonShare').hide();
        $('div#mediaGalleryDialogButtons a.dialogButtonShare').attr('id','shareDialog');
        $('div#mediaGalleryDialogButtons a.dialogButtonShare, div#textLayer img.shareButton').show();
        shareUrl = startPageUrl;
        shareTitle = startPageTitle;
      }
    } else {
      $('a.dialogButtonShare, img.shareButton').hide();
    }
  }
  mediaGalleryShareIconIsDisplayedCheck();

  function mediaGalleryInitLightbox() {
    $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer').children().remove();
    $('div#mediaGalleryLightboxLayer div#lightbox').css({
      left: Math.round(($('div#stage').width() - ($('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left))/2 + $('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left) + 'px',
      top: Math.round(($('div#stage').height() - $('div#mainNavigation').height() - $('div#sales_navigation').height())/2 + $('div#mainNavigation').height()) + 'px',
      width: '1px',
      height: '1px'
    });

    $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').hover(
      function() {
        $('div#mediaGalleryLightboxLayer img.leftWhiteArrow').css('display','none');
        $('div#mediaGalleryLightboxLayer img.leftBlueArrow').css('display','block');
      },
      function() {
        $('div#mediaGalleryLightboxLayer img.leftBlueArrow').css('display','none');
        $('div#mediaGalleryLightboxLayer img.leftWhiteArrow').css('display','block');
      }
    );
    $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').hover(
      function() {
        $('div#mediaGalleryLightboxLayer img.rightWhiteArrow').css('display','none');
        $('div#mediaGalleryLightboxLayer img.rightBlueArrow').css('display','block');
      },
      function() {
        $('div#mediaGalleryLightboxLayer img.rightBlueArrow').css('display','none');
        $('div#mediaGalleryLightboxLayer img.rightWhiteArrow').css('display','block');
      }
    );

    $('div.category img').each(function(i) {
      var lightboxContentWidth = lightboxContent[i]["width"];
      var lightboxContentHeight = lightboxContent[i]["height"];
      if(lightboxContentWidth > 612 || lightboxContentHeight > 383) {
        var differenceValue = (lightboxContentWidth > 612) ? Math.round(lightboxContentWidth - 612) : Math.round(lightboxContentHeight - 383);
        lightboxContent[i]["width"] = Math.round(lightboxContentWidth - differenceValue);
        lightboxContent[i]["height"] = Math.round(lightboxContentHeight - differenceValue);
        if(lightboxContent[i]["width"] > 612 || lightboxContent[i]["height"] > 383) {
          var differenceValue = (lightboxContent[i]["width"] > 612) ? Math.round(lightboxContent[i]["width"] - 612) : Math.round(lightboxContent[i]["height"] - 383);
          lightboxContent[i]["width"] = Math.round(lightboxContent[i]["width"] - differenceValue);
          lightboxContent[i]["height"] = Math.round(lightboxContent[i]["height"] - differenceValue);
        }
      }
    });
  }
  mediaGalleryInitLightbox();

  for(i=0; i < $('div.category img').length; i++) {
    $('div.category img:eq('+ i +')').wrap('<a href="#mediaID-'+ i +'" onfocus="this.blur();"></a>');
  }

  function mediaGalleryWriteLightboxContentObject(nbr, arrowFunc) {
    $('div#mediaGalleryLightboxLayer div#lightbox').removeClass("lightboxNoPreloader");
    switch (lightboxContent[nbr]["type"]) {
      case 'image':
        $imageObj.attr({src: lightboxContent[nbr]['src'], width: lightboxContent[nbr]["width"], height: lightboxContent[nbr]["height"], alt: ""});
        break;
      case 'embed':
        $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer').children().remove();
        var embedObjContent = '';
        embedObjContent += '<object id="videoLayer" width="'+ lightboxContent[nbr]["width"] +'" height="'+ lightboxContent[nbr]["height"] +'">\r\n';
        embedObjContent += '  <param name="FlashVars" value="'+ lightboxContent[nbr]["embedParameter"] +'" />\r\n';
        embedObjContent += '  <param name="movie" value="'+ lightboxContent[nbr]["src"] +'" />\r\n';
        embedObjContent += '  <param name="wmode" value="transparent" />\r\n';
        embedObjContent += '  <embed src="'+ lightboxContent[nbr]["src"] +'" type="application/x-shockwave-flash" wmode="transparent" width="'+ lightboxContent[nbr]["width"] +'" height="'+ lightboxContent[nbr]["height"] +'" allowfullscreen="false" FlashVars="'+ lightboxContent[nbr]["embedParameter"] +'" />\r\n';
        embedObjContent += '</object>\r\n';
        $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer').html(embedObjContent);
        $('div#mediaGalleryLightboxLayer div#lightbox object#videoLayer').attr({width: lightboxContent[nbr]["width"], height: lightboxContent[nbr]["height"]});
        break;
      case 'flash':
        $('div#mediaGalleryLightboxLayer div#lightbox').addClass("lightboxNoPreloader");
        var flashLayer = new SWFObject(lightboxContent[nbr]["src"], "bmw_video", String(lightboxContent[nbr]["width"]), String(lightboxContent[nbr]["height"]), "9.0.115", "#ffffff");
        flashLayer.addParam("quality", "autohigh");
        flashLayer.addParam("allowScriptAccess", "sameDomain");
        flashLayer.addParam("wmode", "transparent");
        if(lightboxContent[nbr]["flashParameter"] != 'undefined') {
          flashLayer.addVariable("prm_flv_url", lightboxContent[nbr]["flashParameter"]);
          flashLayer.addVariable("prm_corelib", swf_corelib);
          flashLayer.addVariable("prm_components", swf_components);
          flashLayer.addVariable("prm_stage_width", String(lightboxContent[nbr]["width"]));
          flashLayer.addVariable("prm_stage_height", String(lightboxContent[nbr]["height"]));
          flashLayer.addVariable("prm_tracking_enabled", "true");
          flashLayer.addVariable("prm_version", "high");
        }
        flashLayer.write("flashLayer");
        break;
      default:
        break;
    }

    if(arrowFunc == 'true') {
      switch (lightboxContent[nbr]["type"]) {
        case 'image':
          $imageObj.fadeIn(200);
          break;
        case 'flash':
          $('div#flashLayer').css('display','block');
          break;
        default:
          break;
      }
      shareUrl = self.location.href;
      shareTitle = document.title;
      mediaGalleryReadImageParameter();
      initArrowLinks(nbr); /* visibleLightboxObjectNumber */
    }
  }

  function mediaGalleryHandleLayerVisibility() {
    $('div#lightbox > *').hide();
    $('div#lightbox div#closeButtonLayer, div#lightbox div#textLayer, div#mediaGalleryLightboxLayer img.leftWhiteArrow, div#mediaGalleryLightboxLayer img.rightWhiteArrow').show();
    if(lightboxContent[visibleLightboxObjectNumber]["type"] == 'image') {
      $imageObj.show();
    } else if(lightboxContent[visibleLightboxObjectNumber]["type"] == 'flash') {
      $flashObj.show();
    } else if(lightboxContent[visibleLightboxObjectNumber]["type"] == 'embed') {
      $('div#embedLayer').show();
    }
    mediaGalleryShareIconIsDisplayedCheck();
    initDownloadLinkList();
    lightboxAnimation = "finished";
  }

  if(startPageUrl.indexOf("?media_id=") != -1) {
    startPageUrl = startPageUrl.replace("?media_id=", "#");
    self.location.href = startPageUrl;
  }

  function mediaGalleryReadImageParameter() {
    var startNbr = Math.round(self.location.href.lastIndexOf("#mediaID-") + 9);
    var endNbr = (self.location.href.lastIndexOf("?") > self.location.href.lastIndexOf("#mediaID-")) ? self.location.href.lastIndexOf("?") : self.location.href.length;
    thisParameterNumber = ($('div.category img').length - 1 < self.location.href.substring(startNbr, endNbr)) ? 0 : self.location.href.substring(startNbr, endNbr);
  }

  if(self.location.href.lastIndexOf('#') != -1) {
    var titleEndNbr = document.title.lastIndexOf('#');
    document.title = document.title.slice(0, titleEndNbr);
    if(self.location.href.lastIndexOf("#mediaID-") != -1) {
      mediaGalleryReadImageParameter();
      for(i=0; i < lightboxContent.length; i++) {
        if(lightboxContent[i]['parameter'] == '#mediaID-'+thisParameterNumber) {
          visibleLightboxObjectNumber = i;
        }
        lightboxContent[i]["isVisible"] = 'false';
      }
      lightboxContent[visibleLightboxObjectNumber]["isVisible"] = 'true';
      initArrowLinks(visibleLightboxObjectNumber);
      $('div.downloadLayer').css('display','none');
      $('div.downloadLayer:eq('+ visibleLightboxObjectNumber +')').css('display','block');
      $('div#mediaGalleryLightboxLayer div#lightbox').addClass("lightboxNoPreloader");
      mediaGalleryWriteLightboxContentObject(visibleLightboxObjectNumber, 'false');
      $('div#mediaGalleryLightboxLayer').css('display','block');
      $('div#mediaGalleryLightboxLayer div#blackLayer').css({opacity: '0.5'});
      $('div#mediaGalleryLightboxLayer div#blackLayer').fadeIn(200, mediaGallerySetLightboxPosition(mediaGalleryHandleLayerVisibility,lightboxContent[visibleLightboxObjectNumber]["width"],lightboxContent[visibleLightboxObjectNumber]["height"]));
    } else {
      var endNbr = self.location.href.lastIndexOf('#');
      self.location.href = self.location.href.slice(0, endNbr);
    }
  }

  function mediaGallerySetLightboxPosition(callBackFunction, bigImageWidth, bigImageHeight) {
    $('div#mediaGalleryCategoriesLayer').css('overflow','hidden');
    var lightboxLeft = Math.round(($('div#stage').width() - ($('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left))/2 + $('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left - (bigImageWidth + 20)/2);
    var lightboxTop = Math.round(($('div#stage').height() - $('div#mainNavigation').height() - $('div#sales_navigation').height())/2 + $('div#mainNavigation').height() - (bigImageHeight + 75)/2);
    var lightboxWidth = Math.round(bigImageWidth + 20);
    var lightboxHeight = Math.round(bigImageHeight + 75);
    $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').animate({
      left: Math.round(lightboxLeft - $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').width() - 9) + 'px',
      top: Math.round(lightboxTop + lightboxHeight/2 - $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').height()/2) + 'px'
    }, 400);
    $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').animate({
      left: Math.round(lightboxLeft + lightboxWidth + 9) + 'px',
      top: Math.round(lightboxTop + lightboxHeight/2 - $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').height()/2) + 'px'
    }, 400);
    $('div#mediaGalleryLightboxLayer div#lightbox').animate({
      left: Math.round(($('div#stage').width() - ($('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left))/2 + $('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left - (bigImageWidth + 20)/2) + 'px',
      top: Math.round(($('div#stage').height() - $('div#mainNavigation').height() - $('div#sales_navigation').height())/2 + $('div#mainNavigation').height() - (bigImageHeight + 75)/2) + 'px',
      width: bigImageWidth + 20 + 'px',
      height: bigImageHeight + 75 + 'px'
    }, 400, callBackFunction);
  }

  function initDownloadLinkList() {
    for(a=0; a < $('div.downloadLayer').length; a++) {
      $('div.downloadLayer:eq('+ a +') ul.linklist').css('display','block');
    }
  }

  $('div#mediaGalleryCategoriesLayer div.category img').click(function() {
    mediaGalleryShareIconIsDisplayedCheck();
    visibleLightboxObjectNumber = $('div.category img').index(this);
    for(i=0; i < lightboxContent.length; i++) {
      lightboxContent[i]["isVisible"] = 'false';
    }
    lightboxContent[visibleLightboxObjectNumber]["isVisible"] = 'true';
    var thisCategoryNumber = lightboxContent[visibleLightboxObjectNumber]["category"];
    document.title = startPageTitle;

    $('div#mediaGalleryLightboxLayer div#lightbox').addClass("lightboxNoPreloader");
    $('div.downloadLayer').css('display','none');
    $('div.downloadLayer:eq('+ visibleLightboxObjectNumber +')').css('display','block');
    mediaGalleryReadImageParameter();
    initArrowLinks(visibleLightboxObjectNumber);
    mediaGalleryWriteLightboxContentObject(visibleLightboxObjectNumber, 'false');
    $('div#mediaGalleryLightboxLayer').css('display','block');
    $('div#mediaGalleryLightboxLayer div#blackLayer').css({opacity: '0.5'});
    $('div#mediaGalleryLightboxLayer div#blackLayer').fadeIn(200, handleLightboxPosition);

    function handleLightboxPosition() {
      mediaGallerySetLightboxPosition(showLightboxContent,lightboxContent[visibleLightboxObjectNumber]['width'],lightboxContent[visibleLightboxObjectNumber]['height']);
    }
    function showLightboxContent() {
      $('div#lightbox div#closeButtonLayer').fadeIn(100);
      $('div#lightbox img, div#mediaGalleryLightboxLayer div#lightbox div#textLayer').fadeIn(300);
      mediaGalleryHandleLayerVisibility();
      $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').css({
        left: Math.round($('div#mediaGalleryLightboxLayer div#lightbox').offset().left - $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').width() - 9) + 'px',
        top: Math.round($('div#mediaGalleryLightboxLayer div#lightbox').offset().top + $('div#mediaGalleryLightboxLayer div#lightbox').height()/2 - $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').height()/2) + 'px'
      });
      $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').css({
        left: Math.round($('div#mediaGalleryLightboxLayer div#lightbox').offset().left + $('div#mediaGalleryLightboxLayer div#lightbox').width() + 9) + 'px',
        top: Math.round($('div#mediaGalleryLightboxLayer div#lightbox').offset().top + $('div#mediaGalleryLightboxLayer div#lightbox').height()/2 - $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').height()/2) + 'px'
      });
      $('div#mediaGalleryLightboxLayer img.leftWhiteArrow, div#mediaGalleryLightboxLayer img.rightWhiteArrow').css('display','block');
    }
  });

  $('div#mediaGalleryLightboxLayer a.closeLink').click(function() {
    $('div#mediaGalleryCategoriesLayer').css('overflow','auto');
    if(lightboxAnimation == "finished") {
      lightboxAnimation = "start";
      $('div#mediaGalleryLightboxLayer div#lightbox').fadeOut(200);
      $('div#toggleLightboxLayer').css('display','none');
      $('div#mediaGalleryLightboxLayer div#blackLayer').fadeOut(250, hideMediaGalleryLightboxLayer);
    }
    function hideMediaGalleryLightboxLayer() {
      var flashLayer = new SWFObject("", "", "1", "1", "9.0.115", "#ffffff");
      flashLayer.write("flashLayer");
      $('div#mediaGalleryLightboxLayer').fadeOut(200, hideLightboxContent);
    }
    function hideLightboxContent() {
      mediaGalleryShareIconIsDisplayedCheck();
      $('div#mediaGalleryLightboxLayer div#lightbox > *, div#mediaGalleryLightboxLayer img').css('display','none');
      $('div#mediaGalleryLightboxLayer div#lightbox, div#toggleLightboxLayer').css('display','block');
      $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer, div#mediaGalleryLightboxLayer div#lightbox div#embedLayer > *').css('display','block');
      document.title = startPageTitle;
      mediaGalleryInitLightbox();
    }
  });

  $('div#toggleLightboxLayer img').click(function() {
    mediaGalleryReadImageParameter();
    for(i=0; i < lightboxContent.length; i++) {
      if(lightboxContent[i]['parameter'] == '#mediaID-'+thisParameterNumber) {
        visibleLightboxObjectNumber = i;
      }
      lightboxContent[i]["isVisible"] = 'false';
    }

    var thisNumber;
    if($(this).hasClass('lightboxArrowLeft')) {
      thisNumber = (visibleLightboxObjectNumber == 0) ? Math.round(lightboxContent.length - 1) : Math.round(visibleLightboxObjectNumber - 1);
    } else if($(this).hasClass('lightboxArrowRight')) {
      thisNumber = (visibleLightboxObjectNumber == Math.round($('div.category img').length - 1)) ? 0 : Math.round(visibleLightboxObjectNumber + 1);
    }

    lightboxContent[thisNumber]["isVisible"] = 'true';
    initDownloadLinkList();
    var thisCategoryNumber = lightboxContent[thisNumber]["category"];
    document.title = startPageTitle;
    $flashObj.css('display','none');
    $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer').children().remove();
    $('div.downloadLayer').css('display','none');
    $('div.downloadLayer:eq('+ thisNumber +')').css('display','block');
    $('div#lightbox img#bigImage').fadeOut(200, mediaGallerySetLightboxPosition(showPreviousLightboxContent,lightboxContent[thisNumber]["width"],lightboxContent[thisNumber]["height"]));
    function showPreviousLightboxContent() {
      $imageObj.attr({src: lightboxContent[thisNumber]['src'], width: lightboxContent[thisNumber]["width"], height: lightboxContent[thisNumber]["height"], alt: ""});
      $imageObj.hide();
      mediaGalleryWriteLightboxContentObject(thisNumber, 'true');
    }
  });

  function initArrowLinks(thisNumber) {
    var previousImageNumber = (thisNumber - 1 < 0) ? $('div.category img').length - 1 : thisNumber - 1;
    var nextImageNumber = (thisNumber + 1 > $('div.category img').length - 1) ? 0 : thisNumber + 1;
    if($('div#mediaGalleryLightboxLayer img.lightboxArrowRight').parent().is('a')) {
      $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').parent().attr('href',lightboxContent[nextImageNumber]["parameter"]);
      $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').parent().attr('href',lightboxContent[previousImageNumber]["parameter"]);
    } else {
      $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').wrap('<a href="'+ lightboxContent[nextImageNumber]["parameter"] + '" onfocus="this.blur();"></a>');
      $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').wrap('<a href="'+ lightboxContent[previousImageNumber]["parameter"] + '" onfocus="this.blur();"></a>');
    }
  }
}
// ******** media gallery page END ******** //


// ******** compare START ******** //
var compare_model = new Array();
var compare_model_selected = new Array();
compare_model_selected[1] = "";
compare_model_selected[2] = "";
var compare_model_short = new Array();

var compare_icon_class = new Array();
compare_icon_class[1] = "icon_standard_equipment";
compare_icon_class[2] = "icon_extra_equipment";
compare_icon_class[3] = "icon_original_equipment";
compare_icon_class[4] = "icon_not_available";


function compareSetTableHeight() {
  newCategoryLayerHeight = Math.round($("#sales_navigation").offset().top - $("#compare_innertable").offset().top - 52);
  $("#compare_innertable").css("height", newCategoryLayerHeight + "px");
  $("#compareInfoLayer").css("top",newCategoryLayerHeight + "px");
}

function compareInit() {
  for(i in compare_model) {
    compare_model_short.push(i);
  }
  //compare_model_short.sort();
  var dropdownCode = "";
  for(i = 0; i < compare_model_short.length; i++) {
    dropdownCode += '<a href="" model="' + compare_model_short[i] + '">' + compare_model[compare_model_short[i]]["model_name"] + '</a>';
  }
  $(".dropdown_content").html(dropdownCode);

  compare_model_selected[1] = compare_model_short[0];
  if(compare_model_short.length > 1) {
    compare_model_selected[2] = compare_model_short[1];
  }
  else {
    $("#compare_select_2").hide();
  }

  splitSearchString();
  if (query.model_1 && inArray(query.model_1,compare_model_short)) {
    compare_model_selected[1] = query.model_1;
  }
  if (query.model_2 && inArray(query.model_2,compare_model_short)) {
    compare_model_selected[2] = query.model_2;
;
  }
}


function compareWriteSelectboxes(model_1, model_2) {
  $("#compare_select_1 .select").html(compare_model[model_1]["model_name"]);
  $("#compare_select_1").show();
  if(compare_model[model_1]["configure_link"]) {
    $("#compare_select_1 .configure a").attr("href", compare_model[model_1]["configure_link"]);
    $("#compare_select_1 .configure").show();
  }
  if(model_2) {
    $("#compare_select_2 .select").html(compare_model[model_2]["model_name"]);
    $("#compare_select_2").show();
    if(compare_model[model_2]["configure_link"]) {
      $("#compare_select_2 .configure a").attr("href", compare_model[model_2]["configure_link"]);
      $("#compare_select_2 .configure").show();
    }
  }
}

function compareWriteTable(model_1,model_2) {
  var compareTableCode = '' +
  '        <table width="687" border="0" cellspacing="0" cellpadding="0">' +
  '          <tr>' +
  '            <td width="10"></td>' +
  '            <td width="209"></td>' +
  '            <td width="15"></td>' +
  '            <td width="219"></td>' +
  '            <td width="15"></td>' +
  '            <td width="219"></td>' +
  '          </tr>';
  for(i = 0; i < compare_model[model_1].length; i++) {

    if(!model_2) {
      compare_model[model_2] = new Array();
      compare_model[model_2][i] = new Array("","","",false,false);
    }

    if(compare_model[model_1][i][0] != "" && ((compare_model[model_1][i][0] == compare_model[model_2][i][0]) || !model_2)) {
      compareTableCode += '' +
      '          <tr class="mc_table_headline">' +
      '            <td></td>' +
      '            <td colspan="5">' + compare_model[model_1][i][0] + '</td>' +
      '          </tr>' +
      '          <tr class="mc_table_seperator">' +
      '            <td colspan="6"></td>' +
      '          </tr>';
    }

    else if(compare_model[model_1][i][1] != "" && ((compare_model[model_1][i][1] == compare_model[model_2][i][1]) || !model_2)) {

      if(!compare_model[model_1][i][3] && (!compare_model[model_2][i][3] || !model_2)) {
        compareTableCode += '' +
        '          <tr class="mc_table_entry">' +
        '            <td></td>' +
        '            <td class="leftalign">' + compare_model[model_1][i][1] + '</td>' +
        '            <td></td>';

        if(compare_model[model_1][i][4]) {
          compareTableCode += '            <td><div class="compare_table_icon ' + compare_icon_class[compare_model[model_1][i][4]] + '"></div></td>';
          compareTableCode += '            <td></td>';
          if(model_2) {
            compareTableCode += '            <td><div class="compare_table_icon ' + compare_icon_class[compare_model[model_2][i][4]] + '"></div></td>';
          }
          else {
             compareTableCode += '            <td></td>';
          }
        }
        else {
          compareTableCode += '            <td>' + compare_model[model_1][i][2] + '</td>';
          compareTableCode += '            <td></td>';
          compareTableCode += '            <td>' + compare_model[model_2][i][2] + '</td>';
        }

        compareTableCode += '' +
        '          </tr>' +
        '          <tr class="mc_table_seperator">' +
        '            <td colspan="6"></td>' +
        '          </tr>';

      }



      else if(compare_model[model_1][i][3] && (compare_model[model_2][i][3] || !model_2)) {
        compareTableCode += '' +
        '          <tr class="mc_table_entry">' +
        '            <td></td>' +
        '            <td colspan="5" class="leftalign">' +
        '              ' + compare_model[model_1][i][1] +
        '            </td>' +
        '          </tr>' +
        '          <tr class="mc_table_seperator">' +
        '            <td colspan="6"></td>' +
        '          </tr>';
      }
    }



  }
  compareTableCode += '</table>';
  $("#compare_innertable").html(compareTableCode);
  compareSetTableHeight();
}

// ******** compare END ******** //

// ******** test reports START ******** //
function initTestReportsContentHeight() {
  var newHeight = Math.round($('div#sales_navigation').offset().top - $('div#test_reports_content').offset().top - 42);
  $('div#test_reports_content').css('height',newHeight + 'px');
}
// ******** test reports END ******** //

var modulenaviAnimation = false;
var closeGif           = buildValidServerRelativeUrl( "/_common/html/img/standard_elements/close.gif" );
var close2Gif          = buildValidServerRelativeUrl( "/_common/html/img/standard_elements/close-h.gif" );
var transGif           = buildValidServerRelativeUrl( "/_common/html/img/palette/1x1_trans.gif" );
var p003399Gif         = buildValidServerRelativeUrl( "/_common/html/img/palette/1x1_003399.gif" );
var pulldownGif        = buildValidServerRelativeUrl( "/_common/html/img/forms/pulldown.gif" );

resetModulNaviTimer = 5000;
hideCo2LayerTimer = 5000;
selectBoxes = new Array();
var i, e;
var browserAtributeLength, browserId, platform;
var imgCountTotal, lowImageSrc, highImageSrc, currentImg, currentState, currentAct, currentPerm, checkLoad;
var slideAmount;
var divNum, documentLeftScroll, documentTopScroll, mouseX, mouseY, loopDragging;
var speedHorizontal, speedVertical, currentBack, goup, godown, speed, currentObjNo;
var setDivPosition, setBackPosition, currentObjId, currentSpeed, currenDirection, currentDelay;
var diffWidth, diffHeight, lastWidth, lastHeight, currentDiv;
var popupWindow, winUrl;
var ua = navigator.userAgent.toLowerCase();
var an = navigator.appName.toLowerCase();
var framesetPage = "index_narrowband.html";
var framesetPageHighend = "index_highend.html";
var currentStep = 0;
var windowWidth = 0;
var windowHeight = 0;
var browserVersion = 0;
var loaded = 0;
var divLeft = 0;
var divTop = 0;
var looping = -1;
var slideCount = -1;
var writeBrowser = "";
var tempAct = "";
var slideNumber = "";
var slideDescription = "";
var preLoadArray = [];
var preLoadCounter = [];
var highImages = [];
var lowImages = [];
var slideText = [];
var permanentActive = [];
var slideImages = [];
var allowedDomain = ["://www.bmw.", "://bmw.", "://origin.bmw.", "://secure.bmw.", "://wcms10.bmwgroup.com", "://liintra.muc", "://ltintra.muc", "://www-at.bmw", "://www-nl.bmw", "://www-be.bmw", "://www-lu.bmw", "://www-pt.bmw", "://www-ie.bmw", "://www-jp.bmw", "://www-fr.bmw", "://www-cz.bmw", "://www-sk.bmw", "://www-se.bmw", "://www-it.bmw", "://ecom.bmwgroup", "://ecomi.bmwgroup", "localhost"]
var supportedOS = false;
var supportedVersion = false;
var currentLoop = false;
var dragAllowed = false;
var divIsMoving = false;
var flashversion = false;
var topFrame = null;
var contentFrame = null;
var bottomFrame = null;
var historyFrame = null;
var hiddenFrame = null;
var allowClose = true;
var modulNaviOverImage = true;
var idmodulsSpecial = "";
var minFlashVersion = 7;
var isMainnavigation = false;
var indexParameters = "";
var query = {};
var parameterArray = [];
var scrollerDefaultSize = 1024;
var scrollerCheckElements = [];
var scrollerSize = scrollerDefaultSize;
var scrollerBgImage;
var scrollerSliderImage;
var scrollerImageUp;
var scrollerImageDown;
var persoEventType = "";
var persoSeries, persoBodytype, persoModel, persoColor, persoRim;
var cookieName = "bmw_bbDetection";
var chosenConnection = "";
var akamaiCookieName = "bandwidth";
var prmContent = "";
var divsToBeAltered = [];
var useCurtain = false;
var htmlDialogOpen = false;
var mainNaviOpen = false;


function arrayUnique (a) {
  var o = {};
  for(var i = 0 ; i < a.length; i++)
  o[a[i]] = true;
  var tmp = new Array();
  for(var i in o) tmp[tmp.length] = i;
  return tmp;
}

if (typeof browser != 'object') {
  browser = [['Opera', 'opera ', '9.0', 'windows', 'mac os x', 'other'], ['Safari', 'safari/', '125', '', 'mac os x', ''], ['Netscape', 'netscape/', '7.1', 'windows', 'mac os x', 'other'], ['Firefox', 'firefox/', '1.0', 'windows', 'mac os x', 'other'], ['Mozilla', 'rv:', '1.7', 'windows', 'mac os x', 'other'], ['MSIE', 'msie ', '5.5', 'windows', '', ''], ['Netscape4', 'mozilla/', '4.0', '', '', '']];
}

function ssoCloseDialog(){
}

function checkClient(){
  var browserLength = browser.length;
  for (i = 0; i < browserLength; i++) {
    browserAtributeLength = browser[i].length;
    if (ua.indexOf(browser[i][1]) != -1) {
      browserId = browser[i][0];
      for (e = 3; e < browserAtributeLength; e++) {
        if (browser[i][e] != '' && (ua.indexOf(browser[i][e]) != -1 || browser[i][e] == 'other')) {
          supportedOS = true;
          platform = browser[i][e];
          break;
        } else {
          supportedOS = false;
        }
      }
      browserVersion = ua.split(browser[i][1]);
      browserVersion = parseFloat(browserVersion[1].slice(0, 3));
      if (browserVersion >= browser[i][2]) {
        supportedVersion = true;
      } else {
        supportedVersion = false;
      }
      break;
    } else {
      browserId = 'unknown';
    }
  }
  browserId = ((browserId == "MSIE") ? (((/\s+msie\s+7\.\d+/).test(navigator.appVersion.toLowerCase())) ? ("MSIE7") : (browserId)) : (browserId));
  browserId = ((browserId == "MSIE") ? (((/\s+msie\s+8\.\d+/).test(navigator.appVersion.toLowerCase())) ? ("MSIE8") : (browserId)) : (browserId));
}

function checkBrowser(incompatibleBrowserUrl){
  checkClient();
  return true;
}
function checkFrameset(){
}

function removeClassName(obj, cssClass){
  if (typeof obj != 'object') {
    obj = document.getElementById(obj);
  }
  if (hasClassName(obj, cssClass)) {
    obj.className = obj.className.replace(new RegExp(cssClass), '');
  }
}

function replaceClassName(obj, oldCssClass, newCssClass){
  if (typeof obj != 'object') {
    obj = document.getElementById(obj);
  }
  if (hasClassName(obj, oldCssClass)) {
    obj.className = obj.className.replace(new RegExp(oldCssClass), newCssClass);
  }
}

function hasClassName(obj, cssClass){
  if (typeof obj != 'object') {
    obj = document.getElementById(obj);
  }
  return (obj.className.indexOf(cssClass) != -1);
}

function addClassName(obj, cssClass){
  if (typeof obj != 'object') {
    obj = document.getElementById(obj);
  }
  if (!hasClassName(obj, cssClass)) {
    obj.className += ' ' + cssClass;
  }
}

function pageHandler(){
  splitSearchString();
  if (query.content) {
    if (query.content.indexOf("://") != -1) {
      var domainIsAllowed = false;
      for (i = 0; i < allowedDomain.length; i++) {
        if (query.content.indexOf(allowedDomain[i]) != -1) {
          domainIsAllowed = true;
          break;
        }
      }
      if (domainIsAllowed) {
        initContentURL = query.content;
        indexParameters = "";
        for (var x in query) {
          if (x == "content")
            continue;
          if (indexParameters == "") {
            indexParameters += "?";
          } else {
            indexParameters += "&";
          }
          indexParameters += x + "=" + query[x];
        }
      }
    } else {
      initContentURL = query.content;
      indexParameters = "";
      for (x in query) {
        if (x == "content")
          continue;
        if (indexParameters == "") {
          indexParameters += "?";
        } else {
          indexParameters += "&";
        }
        indexParameters += x + "=" + query[x];
      }
    }
  }
}

function preload(){
  if (typeof slideImagesCollection != 'undefined') {
    slideAmount = slideImagesCollection.length;
  }
  for (i = 0; i < slideAmount; i++) {
    slideImages[i] = new Image();
    slideImages[i].src = slideImagesCollection[i];
  }
  loaded = 2;
  imgCountTotal = document.images.length;
  for (i = 0; i < imgCountTotal; i++) {
    if (typeof document.getElementsByTagName('img')[i].getAttribute('preload') == 'string') {
      lowImageSrc = document.getElementsByTagName('img')[i].src;
      if (document.getElementsByTagName('img')[i].getAttribute('preload').indexOf('/') != -1) {
        highImageSrc = document.getElementsByTagName('img')[i].getAttribute('preload');
      } else {
        var highImageUrl = lowImageSrc.split('/');
        var fileLevel = highImageUrl.length;
        var highImagePath = '';
        for (e = 0; e < fileLevel - 1; e++) {
          highImagePath += highImageUrl[e] + '/';
        }
        highImageSrc = highImagePath + document.getElementsByTagName('img')[i].getAttribute('preload');
      }
      highImages[document.images[i].id] = new Image();
      highImages[document.images[i].id].src = highImageSrc;
      lowImages[document.images[i].id] = new Image();
      lowImages[document.images[i].id].src = lowImageSrc;
    }
    if (i < imgCountTotal - 1) {
      loaded = 3;
    }
    if (i == imgCountTotal - 1) {
      loaded = 1;
    }
  }
}

function switchImage(imgId, state, act, permanent, dropPerm){
  currentImg = imgId;
  currentState = state;
  currentAct = act;
  currentPerm = permanent;
  if (typeof dropPerm == 'string' && dropPerm != 'all') {
    document.getElementsByTagName('img')[dropPerm].src = lowImages[dropPerm].src;
    delete permanentActive[dropPerm];
    if (dropPerm == tempAct) {
      tempAct = '';
    }
  } else if (dropPerm == 'all') {
    dropPermanentAll();
  }
  if (loaded == 1) {
    clearTimeout(checkLoad);
    if (tempAct != '' && imgId != tempAct && act == 1 && !permanentActive[tempAct]) {
      document.getElementsByTagName('img')[tempAct].src = lowImages[tempAct].src;
    }
    if ((tempAct == '' || imgId != tempAct) && !permanentActive[imgId]) {
      if (state == 1) {
        document.getElementsByTagName('img')[imgId].src = highImages[imgId].src;
      } else {
        document.getElementsByTagName('img')[imgId].src = lowImages[imgId].src;
      }
    }
    if (act == 1) {
      tempAct = imgId;
    }
    if (permanent == 1) {
      permanentActive[imgId] = imgId;
    }
  } else if (loaded == 2) {
    checkLoad = setTimeout('switchImage(currentImg,currentState,currentAct,currentPerm)', 50);
  } else if (loaded == 3) {
    preload();
    checkLoad = setTimeout('switchImage(currentImg,currentState,currentAct,currentPerm)', 50);
  }
}

function dropPermanentAll(){
  for (var dropImg in permanentActive) {
    if (lowImages[dropImg].src) {
      document.getElementsByTagName('img')[dropImg].src = lowImages[dropImg].src;
    }
    delete permanentActive[dropImg];
  }
  if (tempAct != '') {
    if (lowImages[dropImg].src) {
      document.getElementsByTagName('img')[tempAct].src = lowImages[tempAct].src;
    }
    tempAct = '';
  }
}

function setSlideshow(direction, delay){
  currenDirection = direction;
  currentDelay = delay;
  if (direction == "forward") {
    slideCount++;
    if (slideCount > slideAmount - 1) {
      slideCount = 0;
    }
  } else if (direction == "backward") {
    slideCount--;
    if (slideCount < 0) {
      slideCount = slideAmount - 1;
    }
  } else {
    slideCount = 0;
  }
  if (delay) {
    looping = setTimeout("setSlideshow(currenDirection,currentDelay)", currentDelay);
  } else {
    clearTimeout(looping);
    looping = -1;
  }
  document.getElementById('slideshow').src = slideImages[slideCount].src;
}

function toggleSlideshow(direction, delay){
  if (!direction) {
    direction = currenDirection;
  }
  if (!delay) {
    delay = currentDelay;
  }
  if (looping > -1) {
    clearTimeout(looping);
    looping = -1;
  } else {
    setSlideshow(direction, delay);
  }
}

function setClassName(elementId, newClassName){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    elementId.className = newClassName;
  }
}

function setColor(elementId, newColor){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    elementId.style.color = newColor;
  }
}

function getAbsoluteLeft(elementId){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  var currentLeft = 0;
  if (elementId) {
    while (elementId.offsetParent !== null) {
      currentLeft += elementId.offsetLeft;
      elementId = elementId.offsetParent;
    }
    currentLeft += elementId.offsetLeft;
  }
  return currentLeft;
}

function getAbsoluteTop(elementId){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  var currentTop = 0;
  if (elementId) {
    while (elementId.offsetParent !== null) {
      currentTop += elementId.offsetTop;
      elementId = elementId.offsetParent;
    }
    currentTop += elementId.offsetTop;
  }
  return currentTop;
}

function getDivInformation(elementId, attributeName){
  divInformation = [];
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    divInformation['offsetLeft'] = elementId.offsetLeft;
    divInformation['offsetTop'] = elementId.offsetTop;
    divInformation['styleLeft'] = parseInt(elementId.style.left);
    divInformation['styleTop'] = parseInt(elementId.style.top);
    divInformation['width'] = elementId.offsetWidth;
    divInformation['height'] = elementId.offsetHeight;
    divInformation['visibility'] = elementId.style.visibility;
    divInformation['display'] = elementId.style.display;
    divInformation['zIndex'] = elementId.style.zIndex;
    return divInformation[attributeName];
  }
}

function writeIntoLayer(elementId, content){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    elementId.innerHTML = content;
  }
}

lastPositions = [];
currentPositions = [];
currentPositions['navigation'] = [,];
function moveObject(elementId, newLeft, newTop, speed, backLink){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    if (newLeft) {
      divLeft = newLeft;
    } else if ((typeof newLeft == 'undefined' || typeof newLeft == 'string') && (typeof backLink == 'undefined' || backLink == 0)) {
      divLeft = getDivInformation(elementId, 'offsetLeft');
    }
    if (newTop) {
      divTop = newTop;
    } else if ((typeof newTop == 'undefined' || typeof newTop == 'string') && (typeof backLink == 'undefined' || backLink == 0)) {
      divTop = getDivInformation(elementId, 'offsetTop');
    }
    if (!lastPositions[elementId.id]) {
      lastPositions[elementId.id] = [, ];
    }
    if (typeof backLink != 'undefined' && backLink == 1 && newLeft == lastPositions[elementId.id][0] && newTop == lastPositions[elementId.id][1]) {
      currentBack = backLink;
      divLeft = currentPositions[elementId.id][0];
      divTop = currentPositions[elementId.id][1];
    }
    if (!divIsMoving) {
      currentPositions[elementId.id] = [getDivInformation(elementId, 'offsetLeft'), getDivInformation(elementId, 'offsetTop')];
    }
    if (speed) {
      var horizontalRange = currentPositions[elementId.id][0] - divLeft + "px";
      var verticalRange = currentPositions[elementId.id][1] - divTop + "px";
      currentObjId = elementId;
      currentSpeed = speed;
      currentStep++;
      if (newLeft != '' || newLeft == 0) {
        if (horizontalRange > 0) {
          elementId.style.left = (currentPositions[elementId.id][0] - Math.round(currentStep * speed)) + 'px';
          if (divLeft - getDivInformation(elementId, 'offsetLeft') > 5) {
            elementId.style.left = divLeft + 'px';
          }
        } else if (horizontalRange < 0) {
          elementId.style.left = (currentPositions[elementId.id][0] + Math.round(currentStep * speed)) + 'px';
          if (divLeft - getDivInformation(elementId, 'offsetLeft') < 5) {
            elementId.style.left = divLeft + 'px';
          }
        }
      }
      if (newTop != '' || newTop == 0) {
        if (verticalRange > 0) {
          elementId.style.top = (currentPositions[elementId.id][1] - Math.round(currentStep * speed)) + 'px';
          if (divTop - getDivInformation(elementId, 'offsetTop') > 5) {
            elementId.style.top = divTop + 'px';
          }
        } else if (verticalRange < 0) {
          elementId.style.top = (currentPositions[elementId.id][1] + Math.round(currentStep * speed)) + 'px';
          if (divTop - getDivInformation(elementId, 'offsetTop') < 5) {
            elementId.style.top = divTop + 'px';
          }
        }
      }
      if (getDivInformation(elementId, 'offsetLeft') == newLeft && getDivInformation(elementId, 'offsetTop') == newTop) {
        divIsMoving = false;
        currentStep = 0;
        currentBack = 0;
        divLeft = 0;
        divTop = 0;
        lastPositions[elementId.id] = [newLeft, newTop];
        clearTimeout(setDivPosition);
      } else {
        divIsMoving = true;
        setDivPosition = setTimeout('moveObject(currentObjId,divLeft,divTop,currentSpeed)', 10);
      }
    } else {
      if (divLeft != '' || divLeft == 0) {
        elementId.style.left = divLeft + 'px';
      }
      if (divTop != '' || divTop == 0) {
        elementId.style.top = divTop + 'px';
      }
      currentBack = 0;
      divLeft = 0;
      divTop = 0;
      lastPositions[elementId.id] = [newLeft, newTop];
    }
  }
}

function mousePosition(currentEvent){
  if (window.event) {
    currentEvent = window.event;
  }
  mouseX = currentEvent.clientX;
  mouseY = currentEvent.clientY;
}

function getWindowInformation(attributeName){
  var windowInformation = [];
  windowInformation['winWidth'] = document.body.clientWidth;
  if (document.body.clientHeight == 0) {
    windowInformation['winHeight'] = window.innerHeight;
  } else {
    windowInformation['winHeight'] = document.body.clientHeight;
  }
  windowInformation['docWidth'] = document.body.scrollWidth;
  windowInformation['docHeight'] = document.body.scrollHeight;
  windowInformation['scrollLeft'] = document.body.scrollLeft;
  windowInformation['scrollTop'] = document.body.scrollTop;
  return windowInformation[attributeName];
}

function getCurrentStyle(nodeObject, propertyName){
  var propertyValue;
  if (document.documentElement && document.defaultView) {
    propertyValue = document.defaultView.getComputedStyle(nodeObject, "").getPropertyValue(propertyName);
  } else if (document.documentElement && document.documentElement.currentStyle) {
    var regX = /([ a-z ]*)\-([ a-z ])([ a-z ]*)/;
    while (regX.test(propertyName)) {
      regX.exec(propertyName);
      propertyName = RegExp.$1 + RegExp.$2.toUpperCase() + RegExp.$3;
    }
    propertyValue = nodeObject.currentStyle[propertyName];
  }
  return propertyValue;
}

var currentState, currentDisplayState;
function setVisibility(elementId, visibilityValue, displayValue, initialSet){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    if (typeof visibilityValue == 'undefined' && typeof displayValue == 'undefined') {
      currentState = getDivInformation(elementId, 'visibility');
      currentDisplayState = getDivInformation(elementId, 'display');
      if (currentState == '') {
        if (initialSet) {
          currentState = 'visible';
        } else {
          currentState = 'hidden';
        }
      }
      if (currentDisplayState == '') {
        if (initialSet) {
          currentDisplayState = initialSet;
        } else {
          currentDisplayState = 'none';
        }
      }
      if (currentState == 'hidden') {
        elementId.style.visibility = 'visible';
      } else if (currentState == 'visible') {
        elementId.style.visibility = 'hidden';
      }
      if (currentDisplayState == 'none') {
        elementId.style.display = 'block';
        elementId.style.visibility = 'visible';
      } else if (currentDisplayState == 'block' || currentDisplayState == 'inline') {
        elementId.style.display = 'none';
      }
    } else if (visibilityValue == 1) {
      elementId.style.visibility = 'visible';
    } else if (visibilityValue == 0) {
      elementId.style.visibility = 'hidden';
    }
    if (displayValue) {
      elementId.style.display = displayValue;
    }
  }
}

function setZIndex(elementId, newZIndex){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    elementId.style.zIndex = newZIndex;
  }
}

function resizeLayer(elementId, newWidth, newHeight){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    currentDiv = elementId;
    lastWidth = getDivInformation(elementId, 'width');
    lastHeight = getDivInformation(elementId, 'height');
    if (newWidth) {
      if (typeof newWidth == 'string') {
        elementId.style.width = newWidth;
      } else {
        elementId.style.width = newWidth + 'px';
      }
    }
    if (newHeight) {
      if (typeof newHeight == 'string') {
        elementId.style.height = newHeight;
      } else {
        elementId.style.height = newHeight + 'px';
      }
    }
  }
}

function clipLayer(elementId, newTop, newRight, newBottom, newLeft){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    currentDiv = elementId;
    lastWidth = getDivInformation(elementId, 'width');
    lastHeight = getDivInformation(elementId, 'height');
    elementId.style.clip = "rect(" + newTop + "px " + newRight + "px " + newBottom + "px " + newLeft + "px)";
  }
}

function getClipping(elementId){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    return elementId.style.clip;
  }
}

function restoreLayer(){
  if (typeof currentDiv == 'object') {
    if (typeof currentDiv.style.width != 'undefined') {
      currentDiv.style.width = lastWidth + 'px';
    }
    if (typeof currentDiv.style.height != 'undefined') {
      currentDiv.style.height = lastHeight + 'px';
    }
    if (typeof currentDiv.style.clip != 'undefined') {
      currentDiv.style.clip = "rect(" + 0 + "px " + lastWidth + "px " + lastHeight + "px " + 0 + "px)";
    }
  }
}

function centerPopup(popupUrl, popupName, popupWidth, popupHeight, reopen, showScrollbar, popupLeftPos, popupTopPos, myLocation){
  if(!popupLeftPos) {popupLeftPos = 5;}
  if(!popupTopPos)  {popupTopPos = 15;}
  if(!showScrollbar){showScrollbar = 0;}

  if(popupUrl.indexOf("centerPopupShowScrollbar") > -1) {
    showScrollbar = 1;
  }

  if(!myLocation)   {myLocation = "no";}
  var popup_left = (window.screen.width / 2) - (popupWidth / 2 + popupLeftPos);
  var popup_top = (window.screen.height / 2) - (popupHeight / 2 + popupTopPos);
  if ((typeof popupWindow != 'object') || (typeof popupWindow == 'object' && popupWindow.closed)) {
    if (document.all) {
      var xyPos = 'left=' + popup_left + ',top=' + popup_top;
    } else {
      var xyPos = 'screenX=' + popup_left + ',screenY=' + popup_top;
    }
    popupWindow = window.open(popupUrl, popupName, "toolbar=no,location=" + myLocation + ",directories=no,status=no,menubar=no,scrollbars=" + showScrollbar + ",resizable=no,width=" + popupWidth + ",height=" + popupHeight + ",copyhistory=no," + xyPos + "");
    popupWindow.opener = self;
    popupWindow.focus();
    winUrl = popupUrl;
    windowWidth = popupWidth;
    windowHeight = popupHeight;
  } else {
    if ((winUrl != popupUrl) || reopen) {
      popupWindow.location.href = popupUrl;
    }
    if ((windowWidth + windowHeight > 0) && (popupWidth != windowWidth || popupHeight != windowHeight || popupLeftPos != diffWidth || popupTopPos != diffHeight)) {
      var newWidth = popupWidth - windowWidth;
      var newHeight = popupHeight - windowHeight;
      popupWindow.resizeBy(newWidth, newHeight);
      popupWindow.moveTo(popup_left, popup_top);
    }
    popupWindow.focus();
    winUrl = popupUrl;
    windowWidth = popupWidth;
    windowHeight = popupHeight;
  }
  diffWidth = popupLeftPos;
  diffHeight = popupTopPos;
}

function openPopupLink(popupUrl, popupString){
  var params = popupString.split(",");
  if (params.length == 3) {
    centerPopup(popupUrl, params[0], params[1], params[2], false, false);
  } else {
    centerPopup(popupUrl, "searchwin", 800, 600, false, false);
  }
}

function openPopupParams(popupUrl, popupName, popupParams){
  if ((typeof popupWindow != 'object') || (typeof popupWindow == 'object' && popupWindow.closed)) {
    if (popupParams) {
      popupWindow = window.open(popupUrl, popupName, popupParams);
    } else {
      popupWindow = window.open(popupUrl, popupName);
    }
    popupWindow.opener = self;
    popupWindow.focus();
    winUrl = popupUrl;
  } else {
    if (winUrl != popupUrl) {
      popupWindow.location.href = popupUrl;
    }
    popupWindow.focus();
    winUrl = popupUrl;
  }
}

function splitSearchString(){
  if (self.location.search.indexOf("=") == -1)
    return;
  parameterArray = self.location.search.substring(1).split("&");
  for (var i = 0; i < parameterArray.length; i++) {
    pair = parameterArray[i].split("=");
    query[unescape(pair[0])] = (pair[1] ? unescape(pair[1]) : "");
  }
}

function getCookieValue(name){
  var arg = name + "=";
  var alen = arg.length;
  var i = 0;
  while (i < document.cookie.length) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      var endstr = document.cookie.indexOf(";", j);
      if (endstr == -1) {
        endstr = document.cookie.length;
      }
      return unescape(document.cookie.substring(j, endstr));
    }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) {
      break;
    }
  }
  return false;
}

function getCookie(name){
  return getCookieValue(name);
}

function onLoadFunctions(){
}

function onUnloadFunctions(){
}

var resizeDivs = new Array("mainNavigationContainer","mainContainer", "mainImages", "mainImage");

function checkWindowSize() {
  if(browserId == "MSIE") {
    $(".metaNavigation").hide().show();
  }

  resizeDivs = arrayUnique(resizeDivs);
  var i;
  var newSize;
  if (getWindowInformation('winWidth') < scrollerSize) {
    for (i = 0; i < resizeDivs.length; i++) {
      if (document.getElementById(resizeDivs[i])) {
        newSize = 1000 - document.getElementById(resizeDivs[i]).offsetLeft;
        resizeLayer(resizeDivs[i], newSize + "px");
        if(resizeDivs[i] != "mainNavigationContainer" && resizeDivs[i] != "completePageContent") {
          document.getElementById(resizeDivs[i]).style.overflow = "hidden";
        }
      }
    }
  } else {
    if (document.getElementById('mainNavi')) {
      resizeLayer('mainNavi', '100%');
    }
    for (i = 0; i < resizeDivs.length; i++) {
      if (document.getElementById(resizeDivs[i])) {
        if(!document.getElementById(resizeDivs[i]).offsetLeft) {
          resizeLayer(resizeDivs[i], '100%');
        }
      }
    }
  }
}

function myAlert(alertText){
  if (top.location.search.indexOf("debug") != -1) {
    alert(alertText);
  }
}

function buildLinkList(){
  var links = new Array(document.getElementsByTagName('a').length);
  for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
    links[i] = document.getElementsByTagName('a')[i].href;
  }
  return links;
}

function evaluateHighlighting(contentUrl, linkList){
  var navLinkFull = "";
  var navLinkPath = "";
  var navLinkFile = "";
  var navLinkQuery = "";
  var navLinkPathParts = [];
  var contentLinkFull = "";
  var contentLinkPath = "";
  var contentLinkFile = "";
  var contentLinkQuery = "";
  var contentLinkPathParts = [];
  var evaluatedLinks = [];
  if (contentUrl.indexOf('?') != -1) {
    contentLinkFull = contentUrl.substring(0, contentUrl.lastIndexOf('?'));
    contentLinkQuery = contentUrl.substring(contentUrl.lastIndexOf('?'), contentUrl.length);
    if (contentLinkQuery.indexOf("&") != -1) {
      contentLinkQuery = contentLinkQuery.substring(0, contentLinkQuery.indexOf("&"));
    }
  } else {
    contentLinkFull = contentUrl;
  }
  if (contentLinkFull.charAt(contentLinkFull.length - 1) == '/') {
    contentLinkFull = contentLinkFull.substring(0, contentLinkFull.length - 1);
  }
  if (contentLinkFull.lastIndexOf('/') < contentLinkFull.lastIndexOf('.')) {
    contentLinkFile = contentLinkFull.substring(contentLinkFull.lastIndexOf('/') + 1, contentLinkFull.length);
    contentLinkPath = contentLinkFull.substring(0, contentLinkFull.lastIndexOf('/'));
  } else {
    contentLinkPath = contentLinkFull;
    contentLinkFile = "";
  }
  contentLinkPathParts = contentLinkPath.split('/');
  for (var i = 0; i < linkList.length; i++) {
    navLinkFull = linkList[i];
    if (navLinkFull.indexOf('javascript:') != -1 || navLinkFull == '') {
      evaluatedLinks.push(999);
      continue;
    }
    if (navLinkFull.indexOf('?') != -1) {
      navLinkQuery = navLinkFull.substring(navLinkFull.lastIndexOf('?'), navLinkFull.length);
      if (navLinkQuery.indexOf("&") != -1) {
        navLinkQuery = navLinkQuery.substring(0, navLinkQuery.indexOf("&"));
      }
      navLinkFull = navLinkFull.substring(0, navLinkFull.lastIndexOf('?'));
    } else {
      navLinkQuery = "";
    }
    if (navLinkFull.charAt(navLinkFull.length - 1) == '/') {
      navLinkFull = navLinkFull.substring(0, navLinkFull.length - 1);
    }
    if (navLinkFull.lastIndexOf('/') < navLinkFull.lastIndexOf('.')) {
      navLinkFile = navLinkFull.substring(navLinkFull.lastIndexOf('/') + 1, navLinkFull.length);
      navLinkPath = navLinkFull.substring(0, navLinkFull.lastIndexOf('/'));
    } else {
      navLinkPath = navLinkFull;
      navLinkFile = "";
    }
    navLinkPathParts = navLinkPath.split('/');

    var contentIndex = 0;
    var navIndex = 0;
    var bestmatchFound = false;
    var charMatch = null;

    while (navLinkPathParts[navIndex] == contentLinkPathParts[contentIndex]) {
      navIndex++;
      contentIndex++;
      if (contentIndex == contentLinkPathParts.length && navIndex == navLinkPathParts.length) {
        if (navLinkFile == contentLinkFile) {
          if (navLinkQuery == contentLinkQuery) {
            evaluatedLinks.push(-2);
            bestmatchFound = true;
          } else {
            evaluatedLinks.push(-1);
          }
        } else {
          charMatch = stringCompare(navLinkFile, contentLinkFile);
          evaluatedLinks.push(0.99 - (charMatch / 100));
        }
        break;

      } else if (contentIndex == contentLinkPathParts.length) {
        evaluatedLinks.push(999);
        break;

      } else if (navIndex == navLinkPathParts.length) {
        if (confCountryTopic != null &&
        confLanguageTopic != null &&
        navLinkPathParts.length >= 2 &&
        navLinkPathParts[navLinkPathParts.length - 1] == confLanguageTopic &&
        navLinkPathParts[navLinkPathParts.length - 2] == confCountryTopic) {
          evaluatedLinks.push(999);
        } else if (confCountryTopic != null && navLinkPath.indexOf("/" + confCountryTopic + "/") == -1) {
          evaluatedLinks.push(999);
        } else {
          evaluatedLinks.push(contentLinkPathParts.length - contentIndex);
        }
        break;

      } else if (navLinkPathParts[navIndex] != contentLinkPathParts[contentIndex]) {
        evaluatedLinks.push(999);
        break;
      }
    }
    if (bestmatchFound) {
      break;
    }
  }
  return evaluatedLinks;
}

function stringCompare(comparator1, comparator2){
  var shorter = null;
  var longer = null;
  if (comparator1.length > comparator2.length) {
    longer = comparator1.toLowerCase();
    shorter = comparator2.toLowerCase();
  } else {
    longer = comparator2.toLowerCase();
    shorter = comparator1.toLowerCase();
  }
  var matchCount = 0;
  for (var x = 0; x < shorter.length; x++) {
    if (shorter.charAt(x) == longer.charAt(x)) {
      matchCount++;
    } else {
      break;
    }
  }
  return matchCount;
}

function buildValidServerRelativeUrl(simpleServerRelativeUrl){
  if (simpleServerRelativeUrl == '') {
    return '';
  }
  if (simpleServerRelativeUrl.charAt(0) != '/') {
    return simpleServerRelativeUrl;
  }
  var validServerRelativeUrl = '';
  var simpleSeverrelativeUrlNoParams = '';

  if (simpleServerRelativeUrl.indexOf('?') != -1) {
    simpleSeverrelativeUrlNoParams = simpleServerRelativeUrl.substring(0, simpleServerRelativeUrl.indexOf('?'));
  } else {
    simpleSeverrelativeUrlNoParams = simpleServerRelativeUrl;
  }
  if (self.location.href.indexOf('/bmw_edit/') != -1 && simpleSeverrelativeUrlNoParams.indexOf('/bmw_edit/') == -1) {
    validServerRelativeUrl = '/bmw_edit' + simpleServerRelativeUrl;
  } else if (self.location.href.indexOf('/bmw_qa/') != -1 && simpleSeverrelativeUrlNoParams.indexOf('/bmw_qa/') == -1) {
    validServerRelativeUrl = '/bmw_qa' + simpleServerRelativeUrl;
  } else if (self.location.href.indexOf('/bmw_prod/') != -1 && simpleSeverrelativeUrlNoParams.indexOf('/bmw_prod/') == -1) {
    validServerRelativeUrl = '/bmw_prod' + simpleServerRelativeUrl;
  } else {
    validServerRelativeUrl = simpleServerRelativeUrl;
  }
  return validServerRelativeUrl;
}

function getFullPath(basePath, relativePath){
  var fullPath = basePath.substring(0, (basePath.lastIndexOf("/") + 1));
  var regXHostPath = /((^(https{0,1}\:\/\/[ ^\/ ]*\/))|(^(file\:\/\/[ ^\: ]*\:\/))|(^([ a-z ]+\:\\))|(^([ a-z ]+\:\/))|(^(\\\\))|(^(\/\/)))/i;
  if (regXHostPath.test(relativePath)) {
    fullPath = relativePath;
  } else {
    var regXGoingUp = /(\.\.\/)/g, goingUpArr = [], i;
    if (regXGoingUp.test(relativePath)) {
      goingUpArr = relativePath.match(regXGoingUp);
    }
    for (var i = 0; i < goingUpArr.length; ++i) {
      fullPath = fullPath.substring(0, (fullPath.lastIndexOf("/", (fullPath.length - 2)) + 1));
    }
    fullPath += relativePath.replace(regXGoingUp, "");
  }
  return fullPath;
}

function getServerRelativeContentUrl(){
  var contentPage = self.location.href;
  var substract = self.location.host;
  return contentPage.substring(contentPage.indexOf(substract) + substract.length, contentPage.length);
}

function setModuleHeader(hasLink){
  var headerHTML = "";
  if (hasLink) {
    headerHTML = '<a href="javascript:moveMenu();" style="position:relative;display:block;margin-top:1px;">' + moduleHeader + '</a>';
  } else {
    headerHTML = '<span style="position:relative;display:block;margin-top:1px;">' + moduleHeader + '</span>';
  }
  if (typeof document.getElementsByTagName('div')['moduleHeaderContainerSeo'] == 'object') {
    writeIntoLayer('moduleHeaderContainerSeo', headerHTML);
    setVisibility('moduleHeaderContainerSeo', 1);
  } else {
    moveObject(document.getElementsByTagName('div')['naviClipAreaSeo'], null, 0);
  }
}

function download(fileUrl){
  if (confPersoEngineEnabled) {
    if (typeof parent.persoDownloadEventType != "undefined") {
      if (parent.persoDownloadEventType) {
        var persoDownloadEventType = parent.persoDownloadEventType;
        var persoSeries = parent.persoSeries;
        var persoBodytype = parent.persoBodytype;
        var persoModel = parent.persoModel;
        var persoColor = parent.persoColor;
        var persoRim = parent.persoRim;
        parent.createPersoEvent(persoDownloadEventType, persoSeries, persoBodytype, persoModel, persoColor, persoRim);
      }
    } else if (typeof self.persoDownloadEventType != "undefined") {
      if (self.persoDownloadEventType) {
        var persoDownloadEventType = self.persoDownloadEventType;
        var persoSeries = self.persoSeries;
        var persoBodytype = self.persoBodytype;
        var persoModel = self.persoModel;
        var persoColor = self.persoColor;
        var persoRim = self.persoRim;
        createPersoEvent(persoDownloadEventType, persoSeries, persoBodytype, persoModel, persoColor, persoRim);
      }
    }
  }
  var downloadUrl = buildValidServerRelativeUrl(fileUrl) + "?download=true";
  self.location.href = downloadUrl;
}

function writeFramesetTitle(titleText){
}

function preloader(ticketId){
  preLoadCounter[ticketId] = 0;
  preload[ticketId] = [];
  for (var j = 0; j < preLoadArray[ticketId].length; j++) {
    preload[ticketId][j] = new Image();
    preload[ticketId][j].onabort = function(){
      loadUpdate(ticketId, j);
    }
    preload[ticketId][j].onerror = function(){
      loadUpdate(ticketId, j);
    }
    preload[ticketId][j].onload = function(){
      loadUpdate(ticketId, j);
    }
    preload[ticketId][j].src = preLoadArray[ticketId][j];
  }
}

function loadUpdate(ticketId, imageId){
  preLoadCounter[ticketId]++;
  if (preLoadCounter[ticketId] == preLoadArray[ticketId].length) {
    preLoadReady(ticketId);
  }
}

function preLoadReady(ticketId){
}

function showCo2(){
  setVisibility('co2HeaderOn', 1);
  setVisibility('co2HeaderOff', 0);
  setVisibility('co2body', 1);
}

function hideCo2(){
  setVisibility('co2HeaderOn', 0);
  setVisibility('co2HeaderOff', 1);
  setVisibility('co2body', 0);
}

function stopPlayingMp3(){
}

function setElementClass(elementTagName, currentClass, newClass){
  for (var i = 0; i < document.getElementsByTagName(elementTagName).length; i++) {
    if (document.getElementsByTagName(elementTagName)[i].className == currentClass) {
      document.getElementsByTagName(elementTagName)[i].className = newClass;
    }
  }
}

function dialogClosed(){
}

function setCookie(name, value, expires, path, domain, secure){
  document.cookie = name + "=" + escape(value) +
  ((expires) ? "; expires=" + expires : "") +
  ((path) ? "; path=" + path : "") +
  ((domain) ? "; domain=" + domain : "") +
  ((secure) ? "; secure" : "");
}

function setBandwidthOption(text, userBandwidth, formField){
  setVisibility('selectBoxContent' + formField, 0, 'none');
  writeIntoLayer('selectedValue' + formField, "&nbsp; " + text);
  selectedBandwidth = userBandwidth;
}

function getCorrectPath(URL1){
  targetUrl = "http://" + window.location.hostname + "" + buildValidServerRelativeUrl(URL1);
  self.location.href = buildValidServerRelativeUrl(targetUrl);
}

function changeLinksAccordingToStage(){
  var prefix = "";
  if (self.location.href.indexOf('/bmw_edit/') != -1) {
    prefix = "/bmw_edit";
  } else if (self.location.href.indexOf('/bmw_qa/') != -1) {
    prefix = "/bmw_qa";
  } else if (self.location.href.indexOf('/bmw_prod/') != -1) {
    prefix = "/bmw_prod";
  }
  if (prefix != "") {
    divsToBeAltered.push("naviClipAreaSeo");
    divsToBeAltered.push("metaNavigationText");
    divsToBeAltered.push("metaNavigationLogin");
    divsToBeAltered.push("mainNavi");
    divsToBeAltered.push("mainNavigationContainer");
    divsToBeAltered.push("vehicle_navigation");
    divsToBeAltered.push("sales_navigation");
    divsToBeAltered.push("sales_navigation_layer_config");
    divsToBeAltered.push("sales_navigation_layer_compare");
    divsToBeAltered.push("sales_navigation_layer_contact");
    divsToBeAltered.push("sales_navigation_layer_1");
    divsToBeAltered.push("sales_navigation_layer_2");
    divsToBeAltered.push("sales_navigation_layer_3");
    divsToBeAltered.push("sales_navigation_layer_4");
    divsToBeAltered.push("sales_navigation_layer_5");
    divsToBeAltered.push("sales_navigation_layer_6");

    for (var x = 0; x < divsToBeAltered.length; x++) {
      if (document.getElementById(divsToBeAltered[x]) && document.getElementById(divsToBeAltered[x]) != null && document.getElementById(divsToBeAltered[x]).getElementsByTagName('a').length != 0) {
        if (divsToBeAltered[x] != "downloadMainTeaser") {
          for (var i = 0; i < document.getElementById(divsToBeAltered[x]).getElementsByTagName('a').length; i++) {
            evaluatedLink = document.getElementById(divsToBeAltered[x]).getElementsByTagName('a')[i].href;
            if (evaluatedLink.indexOf('javascript:') == -1 && evaluatedLink != '' && evaluatedLink.indexOf(prefix) == -1) {
              toBeReplaced = "http://" + window.location.hostname;
              document.getElementById(divsToBeAltered[x]).getElementsByTagName('a')[i].href = evaluatedLink.replace(toBeReplaced, prefix);
            }
          }
        }
        for (var i = 0; i < document.getElementById(divsToBeAltered[x]).getElementsByTagName('img').length; i++) {
          evaluatedLink = document.getElementById(divsToBeAltered[x]).getElementsByTagName('img')[i].src;
          toBeReplaced = "http://" + window.location.hostname;
          if (evaluatedLink.indexOf(prefix) == -1) {
            document.getElementById(divsToBeAltered[x]).getElementsByTagName('img')[i].src = evaluatedLink.replace(toBeReplaced, prefix);
          }
        }
      }
    }
  }
  changeLinksAccordingToStageDone = true;
}

function setCurtain(mode){
  if ((useCurtain) && (useCurtain == "true")) {
    if (mode == 1) {
      setVisibility(document.getElementById('iFrameContainer'), 0);
      moveObject(document.getElementById('iFrameContainer'), ((window.screen.width * 2) * (-1)));
      setVisibility(document.getElementById('curtain'), null, 'block');
    } else {
      setVisibility(document.getElementById('curtain'), null, 'none');
      if (typeof leftPos != 'undefined') {
        moveObject(document.getElementById('iFrameContainer'), leftPos);
      } else {
        moveObject(document.getElementById('iFrameContainer'), 0);
      }
      setVisibility(document.getElementById('iFrameContainer'), 1);
    }
  }
}

function trackTeaserClick(trackingPage, trackingPageTitel, targetPageUrl){
  if (confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl(trackingPage) + '?target=' + escape(buildValidServerRelativeUrl(targetPageUrl)) + '&source=' + escape(self.location.pathname);
    trackAbsolute(trackingUrl, trackingPageTitel, false, false);
  }
  return true;
}

function trackDownloadClick(trackingPage, trackingPageTitel, targetFileUrl){
  if (confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl(trackingPage) + '?file=' + escape(buildValidServerRelativeUrl(targetFileUrl)) + '&source=' + escape(self.location.pathname);
    trackAbsolute(trackingUrl, trackingPageTitel, false, false);
  }
  return true;
}

splitSearchString();
highbandUser = false;
var detectedBandwidth = "low";
var userbandwidth = getCookieValue("userbandwidth");

var bandwidth = getCookieValue("bandwidth");

if (query.bandwidth) {
  if (query.bandwidth == "vhigh") {
    detectedBandwidth = "vhigh";
  }
} else if (userbandwidth) {
  detectedBandwidth = userbandwidth;
} else if (bandwidth) {
  detectedBandwidth = bandwidth;

   if(typeof enhanced_bandwidth_detection != "undefined" && typeof enhanced_bandwidth_detection_threshold != "undefined"){
     if(enhanced_bandwidth_detection) {
       bandwidth = getCookieValue("bw");
       if(bandwidth >= enhanced_bandwidth_detection_threshold) {
         detectedBandwidth = "vhigh";
       }
       else {
        detectedBandwidth = "low";
       }
     }
   }
}
if (detectedBandwidth == "vhigh") {
  highbandUser = true;
}
// workaround for iPad
if (ua.indexOf('ipad') > -1 && ua.indexOf('safari') > -1 && (confCountryTopic=="de")) {
  highbandUser = false;
}

var selectedBandwidth = "";
function setUserBandwidth(selectedBandwidth){
  var replyText = bandwidth_save_error_no_selection;
  var replyColor = "#000000";

  if (!isCookiesEnabled()) {
    replyText = bandwidth_save_error_no_cookies;
    replyColor = "#ff0000";
  } else if (selectedBandwidth == "vhigh" || selectedBandwidth == "low") {
    setCookie("userbandwidth", selectedBandwidth, "Sun, 31-Dec-2100 00:00:00 GMT", "/");
    replyText = bandwidth_save_confirm;
    closeBandwidthLayer();
    self.location.reload();
  } else if (selectedBandwidth == "auto") {
    setCookie("userbandwidth", "", "Wed, 31-Dec-1980 00:00:00 GMT", "/");
    replyText = bandwidth_save_confirm;
    closeBandwidthLayer();
    self.location.reload();
  } else if (selectedBandwidth == "") {
    replyText = bandwidth_save_error_no_selection;
    replyColor = "#ff0000";
  }
  document.getElementById("bandwidthReply").style.color = replyColor;
  writeIntoLayer("bandwidthReply", replyText);
}

function isCookiesEnabled(){
  document.cookie="bmwCookieEnabled=true";
  if(document.cookie.indexOf("bmwCookieEnabled=true")!= -1) {
    var expire=new Date();
    document.cookie = "bmwCookieEnabled=;expires=" + expire.toGMTString();
    return true;
  } else {
    return false;
  }
}

function resetBandwidthReply(){
  writeIntoLayer("bandwidthReply", "");
}

function changeBandwidth(){
  var reloadUrl = self.location.href;
  var bandwidthParameter;
  if (highbandUser) {
    bandwidthParameter = "bandwidth=low";
  } else {
    bandwidthParameter = "bandwidth=vhigh";
  }
  if (reloadUrl.indexOf("bandwidth=") != -1) {
    if (reloadUrl.indexOf("bandwidth=low") != -1 && bandwidthParameter == "bandwidth=vhigh") {
      reloadUrl = reloadUrl.replace(/bandwidth=low/g, "bandwidth=vhigh");
    } else {
      reloadUrl = reloadUrl.replace(/bandwidth=vhigh/g, "bandwidth=low");
    }
  } else {
    if (reloadUrl.indexOf("?") != -1) {
      if (reloadUrl.charAt(self.location.href.length) != "&") {
        reloadUrl += "&";
      }
    } else {
      reloadUrl += "?";
    }
    reloadUrl += bandwidthParameter;
  }
  if (reloadUrl.indexOf("#") != -1) {
    var pos_jumper = reloadUrl.indexOf("#");
    var jumper_to_end = reloadUrl.substr(pos_jumper);
    var jumper_link = jumper_to_end;
    var pos_jumper_end = jumper_to_end.length;
    if(jumper_to_end.indexOf("?") != -1){
      var pos_jumper_end = jumper_to_end.indexOf("?");
      jumper_link = jumper_to_end.substr(0, pos_jumper_end);
    }else if(jumper_to_end.indexOf("&") != -1){
      var pos_jumper_end = jumper_to_end.indexOf("&");
      jumper_link = jumper_to_end.substr(0, pos_jumper_end);
    }
    reloadUrl = reloadUrl.replace(jumper_link, "");
    reloadUrl += jumper_link;
  }

  self.location.href = reloadUrl;
}

function closeBandwidthLayer(){
  setCurtain(0);
  setVisibility("bandwidthlayer", 0);
  if((confCountryTopic=="de")&&(confLanguageTopic=="de")){
  document.getElementById("bandwidthlayer").style.display="none";
  }
  setVisibility("selectBoxContentBandwidth", 0);
  document.getElementById('changeVersionLink').className = "menu";
  bandwidthLayerState = 0;
}

function showBandwidthLayer(){
  setCurtain(1);
  selectedBandwidth = "";
  if (highbandUser) {
    bandwidth_headline = bandwidth_headline_low;
    bandwidth_copy = bandwidth_copy_low;
    bandwidth_link = bandwidth_link_low;
  } else {
    bandwidth_headline = bandwidth_headline_high;
    bandwidth_copy = bandwidth_copy_high;
    bandwidth_link = bandwidth_link_high;
  }

  var bandwidthSelectedOption = bandwidth_save_select;

  if(userbandwidth == "low") {
    bandwidthSelectedOption = bandwidth_save_lowband;
    selectedBandwidth='low';
  }
  else if (userbandwidth == "vhigh") {
    bandwidthSelectedOption = bandwidth_save_highband;
    selectedBandwidth='vhigh';
  }
  else {
    bandwidthSelectedOption = bandwidth_save_auto;
    selectedBandwidth='auto';
  }

  if((confCountryTopic=="de")&&(confLanguageTopic=="de")){
  var bandwidth_save_copy_2ndline = "Einstellung &#228;ndern in:";
  selectedBandwidthCopy = "";
  if(userbandwidth == "low"){
    selectedBandwidthCopy = "Basis-Inhalte";
  }else if (userbandwidth == "vhigh") {
    selectedBandwidthCopy = "Mulitimedia-Inhalte";
  }else {
    selectedBandwidthCopy = "Automatisch pr&uuml;fen";
  }
  var layerContent = '' +
  '  <div id="bandwidthClose"><a href="javascript:closeBandwidthLayer();" onmouseover="switchImage(\'closeImg\',1);" onmouseout="switchImage(\'closeImg\',0);"><img src="' + closeGif + '" id="closeImg" preload="' + close2Gif + '" width="13" height="12"></a></div>' +

  '  <div id="bandwidthlayerRight" class="strictMode">' +
  '    <b>' + bandwidth_save_headline + '</b>&nbsp;<b style="color:#003399">' + selectedBandwidthCopy + '</b>' +
  '    <div style="height:6px; overflow:hidden;"></div>' + bandwidth_save_copy +'<div style="height:7px; overflow:hidden;"></div>'+ bandwidth_save_copy_2ndline + '<div style="height:7px; overflow:hidden;"></div>' +
  '    <div style="height:2px; overflow:hidden;"></div>' +
  '    <div style="position:relative; z-index:1000;">';

  if(userbandwidth == "low"){
   layerContent +='<a href="javascript://" class="bwb_l" onclick="setUserBandwidth(\'vhigh\');selectedBandwidth=\'vhigh\';">' + bandwidth_save_highband + '</a><a href="javascript://" class="bwb_r" onclick="setUserBandwidth(\'auto\');selectedBandwidth=\'auto\';">' + bandwidth_save_auto + '</a>';
  }else if(userbandwidth == "vhigh"){
   layerContent +=' <a href="javascript://" class="bwb_l" onclick="setUserBandwidth(\'low\');selectedBandwidth=\'low\';">' + bandwidth_save_lowband + '</a><a href="javascript://" class="bwb_r" onclick="setUserBandwidth(\'auto\');selectedBandwidth=\'auto\';">' + bandwidth_save_auto + '</a>';
  }else{
   layerContent +='<a href="javascript://" class="bwb_l" onclick="setUserBandwidth(\'vhigh\');selectedBandwidth=\'vhigh\';">' + bandwidth_save_highband + '</a><a href="javascript://" class="bwb_r" onclick="setUserBandwidth(\'low\');selectedBandwidth=\'low\';">' + bandwidth_save_lowband + '</a>';
  }

 layerContent +='      </div>' +
  '    </div>' +
  '    <div id="bandwidthReply"></div>' +
  '  </div>' +
  '</div>';

  document.getElementById("bandwidthlayer").className="strictMode";

  }else{

  var layerContent = '' +
  '  <div id="bandwidthClose"><a href="javascript:closeBandwidthLayer();" onmouseover="switchImage(\'closeImg\',1);" onmouseout="switchImage(\'closeImg\',0);"><img src="' + closeGif + '" id="closeImg" preload="' + close2Gif + '" width="13" height="12"></a></div>' +
  '  <div id="bandwidthlayerLeft">' +
  '    <h3>' + bandwidth_headline + '</h3>' +
  '    <div style="height:6px; overflow:hidden;"></div>' + bandwidth_copy +
  '    <div style="height:15px; overflow:hidden;"></div>' +
  '    <a href="javascript:changeBandwidth();" class="standard" target="_self">' + bandwidth_link + '</a>' +
  '  </div>' +
  '  <div id="bandwidthlayerSeperator"></div>' +
  '  <div id="bandwidthlayerRight">' +
  '    <h3>' + bandwidth_save_headline + '</h3>' +
  '    <div style="height:6px; overflow:hidden;"></div>' + bandwidth_save_copy +
  '    <div style="height:2px; overflow:hidden;"></div>' +
  '    <div style="position:relative; z-index:1000;">' +
  '      <table width="182" cellspacing="0" cellpadding="0" border="0" bgcolor="#ffffff">' +
  '        <colgroup><col width="1"><col width="162"><col width="18"><col width="1"></colgroup>' +
  '        <tr>' +
  '          <td colspan="4" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + p003399Gif + '" width="182" height="1"></td>' +
  '        </tr>' +
  '        <tr>' +
  '          <td bgcolor="#003399"><img src="' + p003399Gif + '" width="1" height="16"></td>' +
  '          <td valign="middle" onClick="setVisibility(\'selectBoxContentBandwidth\');" onMouseover="directOrder[ \'Bandwidth\' ]=true;" onMouseout="directOrder[ \'Bandwidth\' ]=false;" style="cursor:pointer;"><span id="selectedValueBandwidth">&nbsp; ' + bandwidthSelectedOption + '</span></td>' +
  '          <td><a href="javascript:setVisibility(\'selectBoxContentBandwidth\');" onMouseover="directOrder[ \'Bandwidth\' ]=true;" onMouseout="directOrder[ \'Bandwidth\' ]=false;" onFocus="this.blur();"><img src="' + pulldownGif + '" width="18" height="16" border="0"></a></td>' +
  '          <td bgcolor="#003399"><img src="' + p003399Gif + '" width="1" height="16"></td>' +
  '        </tr>' +
  '        <tr>' +
  '          <td colspan="4" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + p003399Gif + '" width="182" height="1"></td>' +
  '        </tr>' +
  '      </table>' +
  '      <div id="selectBoxContentBandwidth" class="selectBoxContent" style="top:17px;display:none;visibility:hidden;background-color:#ffffff">' +
  '        <table cellspacing="0" cellpadding="0" border="0" width="182">' +
  '          <tr>' +
  '            <td width="1" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + transGif + '"></td>' +
  '            <td width="180" valign="top">' +
  '              <div id="block1Select" style="width:180px; background-color:#ffffff; height:70px; overflow:auto;">' +
  '                <div style="height:7px; overflow:hidden;"></div>' +
  '                <a href="javascript://" class="selectboxEntry" onclick="setOption(\'' + bandwidth_save_highband + '\',\'\',\'Bandwidth\',\'\',\'\',\'none\');selectedBandwidth=\'vhigh\';resetBandwidthReply();">&nbsp; ' + bandwidth_save_highband + '</a>' +
  '                <a href="javascript://" class="selectboxEntry" onclick="setOption(\'' + bandwidth_save_lowband + '\',\'\',\'Bandwidth\',\'\',\'\',\'none\');selectedBandwidth=\'low\';resetBandwidthReply();">&nbsp; ' + bandwidth_save_lowband + '</a>' +
  '                <a href="javascript://" class="selectboxEntry" onclick="setOption(\'' + bandwidth_save_auto + '\',\'\',\'Bandwidth\',\'\',\'\',\'none\');selectedBandwidth=\'auto\';resetBandwidthReply();">&nbsp; ' + bandwidth_save_auto + '</a><br>' +
  '              </div>' +
  '            </td>' +
  '            <td width="1" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + transGif + '" width="1" height="1"></td>' +
  '          </tr>' +
  '          <tr><td colspan="3" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + p003399Gif + '" width="182" height="1"></td></tr>' +
  '        </table>' +
  '      </div>' +
  '    </div>' +
  '    <a href="javascript:setUserBandwidth(selectedBandwidth);" id="bandwidthBoxlink">' + bandwidth_save_button + '</a><br>' +
  '    <div id="bandwidthReply"></div>' +
  '  </div>' +
  '</div>';

  }

  bandwidthlayerPos = getWindowInformation('scrollTop');
  if (bandwidthlayerPos > 0) {
    document.getElementById("bandwidthlayer").style.top = (162 + bandwidthlayerPos) + "px";
  }
  writeIntoLayer("bandwidthlayer", layerContent)
  setVisibility("bandwidthlayer", 1);
   if((confCountryTopic=="de")&&(confLanguageTopic=="de")){
  document.getElementById("bandwidthlayer").style.display="block";
  }
  preload();
  document.getElementById('changeVersionLink').className = "menu linkHighlight";
  bandwidthLayerState = 1;
}

var bandwidthLayerState = 0;
function toggleBandwidthLayer(){
  if (bandwidthLayerState == 0) {
    showBandwidthLayer();
  } else {
    closeBandwidthLayer()
  }
}


function getFileName(file){
  var result, pathDiv, fileNameExt, extPos;
  pathDiv = (file.indexOf("/") >= 0) ? "/" : "\\"
  fileNameExt = file.substring(file.lastIndexOf(pathDiv) + 1);
  extPos = fileNameExt.lastIndexOf('.');
  result = (extPos > 1) ? fileNameExt.substring(0, extPos) : fileNameExt;
  return result;
}

function scrollToTop(){
  window.scrollTo(0, 0);
}


function alterCSSClass( className, cssArgument, cssValue ) {
  var cssRules = ( document.all )? 'rules':( document.getElementById )? 'cssRules':false;
  if ( cssRules != false ) {
    for ( var i = 0; i < document.styleSheets.length; i++ ) {
      var currentStyle = document.styleSheets[ i ];
      for ( var j = 0; j < currentStyle[ cssRules ].length; j++ ) {
        var currentRule = currentStyle[ cssRules ][ j ];
        if ( currentRule.selectorText == className ) {
          currentRule.style[ cssArgument ] = cssValue;
        }
      }
    }
  }
}

function setMainNavigationFolded(state, foldingSteps, foldInterval) {
}

function checkBottomNavi() {
  var currentWindowWith = getWindowInformation("winWidth");
  if(currentWindowWith < 982) {
    document.getElementById('metaNavigationInline').style.width = currentWindowWith + "px";
  }
  else {
    document.getElementById('metaNavigationInline').style.width = "982px";
  }
  persoSsoLoadJs();
}

//Perso SSO
var persoSsoShowBottomLogin = true;
var persoSsoTimer;
var persoSsoTimerMilliseconds = 100;
var persoSsoLoginFromBottomNavi = null;
var persoSsoSalutationHTML = "Willkommen #1 #2 #3 #4!"
var persoSsoLoginText = "Login"
var persoSsoLogoutText = "Logout"

function persoSsoLoadJs(){
  if(typeof confPersoEngineSSOEnabled == "boolean"){
    if(confPersoEngineSSOEnabled){
      var e = document.createElement("script");
      e.src = confPersoEngineProfileController + "?rtyp=js&pid=" + confPersoEnginePid;
      e.type="text/javascript";
      document.getElementsByTagName("head")[0].appendChild(e);
      e = document.createElement("script");
      e.src = getWcmsPrefix() + "/_common/silo/user_status.js.jsp?country="+confCountryId+"&language="+confLanguageId;
      e.type="text/javascript";
      document.getElementsByTagName("head")[0].appendChild(e);
      persoSsoTimer = setTimeout('persoSsoCheckJs()', persoSsoTimerMilliseconds);
    }
  }
}

function persoSsoCheckJs(){
  if(typeof perso_profile == "object"){
    if((typeof perso_profile.data_loaded == "boolean") && (typeof silo_user_status == "string")){
      if(persoSsoShowBottomLogin && document.getElementById("metaNavigationLogin") == null){
        persoSsoBuildBottomLoginHtml();
      }
      clearTimeout(persoSsoTimer);
      if (silo_sync_perso_sso_done) {
        if(silo_user_status != "no_user"){
          setVisibility("persoSsoLogout", 1, 'block');
          setVisibility("persoSsoLogin", 0, 'none');
        } else {
          setVisibility("persoSsoLogin", 1, 'block');
          setVisibility("persoSsoLogout", 0, 'none');
        }
      } else {
        if(perso_profile.login_status != "not_logged_in"){
          setVisibility("persoSsoLogout", 1, 'block');
          setVisibility("persoSsoLogin", 0, 'none');
        }else if(perso_profile.login_status != "logged_in"){
          setVisibility("persoSsoLogin", 1, 'block');
          setVisibility("persoSsoLogout", 0, 'none');
        }
      }
      if(document.getElementById("persoSsoSalutation") != null){
        if(typeof perso_profile.userdata == "object"){
          if(typeof confPersoSsoSalutation == "string"){
            persoSsoSalutationHTML = confPersoSsoSalutation;
          }
          if((typeof perso_profile.userdata.salutation == "string") && (perso_profile.userdata.salutation != "")){
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#1/, perso_profile.userdata.salutation);
          }else{
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#1/, "");
          }
          if((typeof perso_profile.userdata.title == "string") && (perso_profile.userdata.title != "")){
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#2/, perso_profile.userdata.title);
          }else{
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#2/, "");
          }
          if((typeof perso_profile.userdata.firstname == "string") && (perso_profile.userdata.firstname != "")){
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#3/, perso_profile.userdata.firstname);
          }else{
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#3/, "");
          }
          if((typeof perso_profile.userdata.lastname == "string") && (perso_profile.userdata.lastname != "")){
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#4/, perso_profile.userdata.lastname);
          }else{
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#4/, "");
          }
          writeIntoLayer('persoSsoSalutation', persoSsoSalutationHTML);
          setVisibility("persoSsoSalutation", 1, 'block');
        }
      }
    }else{
      persoSsoTimer = setTimeout('persoSsoCheckJs()', persoSsoTimerMilliseconds);
    }
  }else{
    persoSsoTimer = setTimeout('persoSsoCheckJs()', persoSsoTimerMilliseconds);
  }
}

function persoSsoSendEvent(eventId, sessionId, rememberMe){
  if(typeof confPersoEngineSSOEnabled == "boolean"){
    if(confPersoEngineSSOEnabled){
      rememberMe = (rememberMe != "")?"&rme="+rememberMe:"";
      img = new Image();
      img.src = confPersoEngineSSOController + '&eid=' + eventId + '&sid=' + sessionId + rememberMe;
      return img;
    }
  }
  return null;
}

function persoSsoBuildBottomLoginHtml(){
  var newDiv = document.createElement("div");
  newDiv.id = "metaNavigationLogin";
  newDiv.style.paddingTop = "5px";
  newDiv.style.paddingLeft = "30px";
  document.getElementById("metaNavigationInline").appendChild(newDiv);

  var newA1 = document.createElement("a");
  newA1.id = "persoSsoLogin";
  newA1.href = "javascript:persoSSOLogin();";
  document.getElementById("metaNavigationLogin").appendChild(newA1);
  addClassName("persoSsoLogin", "hidden");

  var newImg1 = document.createElement("img");
  newImg1.src = "/_common/narrowband/img/palette/1x1_trans.gif";
  document.getElementById("persoSsoLogin").appendChild(newImg1);
  addClassName(newImg1, "arrow");
  if(typeof confPersoSsoLogin == "string"){
    persoSsoLoginText = confPersoSsoLogin;
  }
  var aText1 = document.createTextNode(persoSsoLoginText);
  document.getElementById("persoSsoLogin").appendChild(aText1);

  var newA1 = document.createElement("a");
  newA1.id = "persoSsoLogout";
  newA1.href = "javascript:persoSSOLogout();";
  document.getElementById("metaNavigationLogin").appendChild(newA1);
  addClassName("persoSsoLogout", "hidden");

  var newImg2 = document.createElement("img");
  newImg2.src = "/_common/narrowband/img/palette/1x1_trans.gif";
  document.getElementById("persoSsoLogout").appendChild(newImg2);
  addClassName(newImg2, "arrow");

  if(typeof confPersoSsoLogout == "string"){
    persoSsoLogoutText = confPersoSsoLogout;
  }
  var aText1 = document.createTextNode(persoSsoLogoutText);
  document.getElementById("persoSsoLogout").appendChild(aText1);
  changeLinksAccordingToStage();
}

function persoSsoBuildLoginIframe(){
  if(document.getElementById("profileDialog") == null){
    var newDiv = document.createElement("div");
    newDiv.id = "profileDialog";
    newDiv.style.position = "absolute";
    newDiv.style.top = "101px";
    newDiv.style.left = "296px";
    newDiv.style.width = "690px";
    newDiv.style.height = "555px";
    newDiv.style.visibility = "hidden";
    newDiv.style.overflow = "hidden";
    newDiv.style.zIndex = "1000";
    document.getElementsByTagName("body")[0].appendChild(newDiv);

    var newIframe = document.createElement("iframe");
    newIframe.id = "profileDialogIFrame";
    newIframe.name = "profileDialogIFrame";
    newIframe.scrolling = "no";
    newIframe.src = "";
    newIframe.style.background = "transparent";
    newIframe.style.width = "690px";
    newIframe.style.height = "555px";
    newIframe.style.border = "none";

    var allowtrans = document.createAttribute("allowtransparency");
    allowtrans.nodeValue = "true";
    newIframe.setAttributeNode(allowtrans);

    var frameBd = document.createAttribute("frameborder");
    frameBd.nodeValue = "0";
    newIframe.setAttributeNode(frameBd);

    document.getElementById("profileDialog").appendChild(newIframe);
  }
}

function persoSSOLogin(){
  persoSsoLoginFromBottomNavi = true;
  persoSsoBuildLoginIframe();
  document.getElementById("profileDialogIFrame").src = getWcmsPrefix() + "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/silo/login/login_flash.jsp?transfer=profile";
  setVisibility("profileDialog",1);
}

function persoSSOLogout(){
  persoSsoBuildLoginIframe();
  document.getElementById("profileDialogIFrame").src = getWcmsPrefix() + "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/silo/login/logout.jsp?transfer=profile";
  setVisibility("profileDialog",1);
}

function persoSSOShowLogout(){
  setVisibility("persoSsoLogout", 1, 'block');
  setVisibility("persoSsoLogin", 0, 'none');
}

function persoSSOShowLogin(){
  setVisibility("persoSsoLogin", 1, 'block');
  setVisibility("persoSsoLogout", 0, 'none');
}

function getWcmsPrefix(){
  var prefix = "";
  if (self.location.href.indexOf('/bmw_edit/') != -1) {
    prefix = "/bmw_edit";
  } else if (self.location.href.indexOf('/bmw_qa/') != -1) {
    prefix = "/bmw_qa";
  } else if (self.location.href.indexOf('/bmw_prod/') != -1) {
    prefix = "/bmw_prod";
  }
  return prefix;
}
//Perso SSO

var isFolding, resetModulNaviTimer, moduleHeader;
function moduleNaviReset(){}

function highlightNavigations(moduleNaviFolded, initModuleNavigation, startCounter){
  changeLinksAccordingToStage();
  if (document.getElementById('mainNavigation') !== undefined) {
    mainNavigation = new MainNavigation('mainNavigation');
    mainNavigation.init();
  }
  if (document.getElementById('moduleNavigation') != undefined) {
    moduleNavigation = new ModuleNavigation('moduleNavigation', moduleNaviFolded);
    moduleNavigation.init();
    clearTimeout(isFolding);
  }
  if (browserId == "Firefox" && platform == "mac os x" && document.getElementsByTagName('embed').length > 0) {
    document.getElementById('moduleNavigation').style.MozOpacity = "1";
    document.getElementById('moduleNavigation').style.opacity = "1";
  }
  highlightBottomNavigation();
}
function highlightBottomNavigation(){
  var currentLinkList = document.getElementById('metaNavigationInline').getElementsByTagName('a');
  var links = new Array(currentLinkList.length);
  for (var i = 0; i < currentLinkList.length; i++) {
    if (currentLinkList[i].href.indexOf('javascript:') == -1 && currentLinkList[i].href.indexOf('http://') == -1) {
      links[i] = 'http://' + window.location.hostname + '' + currentLinkList[i].href;
    } else {
      links[i] = currentLinkList[i].href;
    }
  }
  var evaluatedLinks = evaluateHighlighting(location.href, links);
  var highlightedIndex = -1;
  var bestmatch = 999;
  for (var i = 0; i < evaluatedLinks.length; i++) {
    if (evaluatedLinks[i] < bestmatch) {
      bestmatch = evaluatedLinks[i];
      highlightedIndex = i;
      if (evaluatedLinks[i] == -2) {
        break;
      }
    }
  }
  if (highlightedIndex != -1) {
    currentLinkList[highlightedIndex].style.color = '#003399';
  }
}

function resetBottomNavigation(){}

function openChooseBandLayer(headline, copy, linktext_start, linktext_back){
  var chooseBandLayer = '<' + 'div id="contentHiBand">' +
  '<' + 'h2>' + headline + '</h2>' +
  '<' + 'span id="vSpace" style="padding-bottom:2px;"></span>' +
  '<' + 'p>' + copy + '</p>' +
  '<' + 'span id="vSpace" style="padding-bottom:19px;"></span>' +
  '<' + 'ul class="linkList">' +
  '<' + 'li><' + 'a href="javascript:changeToHiEndVersion();"><' + 'img src="' + transGif + '" class="arrow" alt="" />' + linktext_start + '</a></li>' +
  '<' + 'li><' + 'a href="javascript:closeChooseBandLayer();"><' + 'img src="' + transGif + '" class="arrow" alt="" />' + linktext_back + '</a></li>' +
  '</ul>' + '</div>' +
  '<' + 'div style="position:absolute; top:2px; right:2px; width:13px; height:12px;">' +
  '<' + 'a href="javascript:closeChooseBandLayer();" onMouseOver="document.getElementsByTagName(\'img\')[\'closeImgHighendLayer\'].src=\'' + close2Gif + '\';" onMouseOut="document.getElementsByTagName(\'img\')[\'closeImgHighendLayer\'].src=\'' + closeGif + '\';">' +
  '<' + 'img src="' + closeGif + '" id="closeImgHighendLayer" preload="' + close2Gif + '" width="13" height="12" />' + '</a>' +
  '</div>';
  var pos = getWindowInformation('scrollTop');
  var newDiv = document.createElement('div');
  newDiv.id = 'changeToHighend';
  newDiv.style.position = 'absolute';
  newDiv.style.top = 157 + pos + 'px';
  newDiv.style.left = '194px';
  newDiv.style.width = '632px';
  newDiv.style.height = '305px';
  newDiv.style.border = '1px solid #acacac';
  newDiv.style.backgroundColor = '#ffffff';

  newDiv.style.zIndex = 922;
  newDiv.innerHTML = chooseBandLayer;

  if (!document.getElementById('changeToHighend')) {
    document.getElementsByTagName('body')[0].appendChild(newDiv);
    document.getElementById('changeVersionLink').className = 'menu linkHighlight';
    setCurtain(1);
    curtainInUse = true;
  } else {
    closeChooseBandLayer();
    setCurtain(0);
    curtainInUse = false;
  }
}

var mainNavigation = { nodeAction:function(){} };
var MainNavigation = (function(){
  var _maxFold = 75;
  var hoverActive = false;
  var menuActive = false;
  var foldingActive = false;
  var oldMenuObject;
  var mnContainer;
  var idModules;
  var eventObj;
  var foldIntId;
  var mouseIntId;
  var _foldingSteps = 1;
  var _foldInterval = 10;
  var currentTop;
  var currentMouseY = 400;
  return (function(mainNavigationId){
    var self = this;
    this.init = function(){
      mnContainer = document.getElementById('mainNavigationContainer');
      idModules = document.getElementById('idModuls');
      var mnTopicUsedVehicles = document.getElementById('topic_usedvehicle');
      var mnTopicOwner = document.getElementById('topic_owner');
      var mnTopicInsights = document.getElementById('topic_insights');
      var mnTopicMseries = document.getElementById('topic_mseries');
      var mnTopicXseries = document.getElementById('topic_xseries');

      var firstWidth = 0;
      if(mnTopicUsedVehicles != null) {
        firstWidth = mnTopicUsedVehicles.offsetWidth + 1;
      }

      var secondWidth = 0;
      if(mnTopicOwner != null) {
        var secondWidth = mnTopicOwner.offsetWidth + 1;
      }

      if(mnTopicOwner != null) {
        mnTopicOwner.getElementsByTagName('div')[0].style.left = -firstWidth + "px";
      }
      if(mnTopicInsights != null) {
        mnTopicInsights.getElementsByTagName('div')[0].style.left = -(firstWidth + secondWidth) + "px";
      }
      /* DE only */
      if(confCountryId=='DE' && (location.host.indexOf("//nl-")==-1 && location.host.indexOf("//ah-")==-1)){
        if(mnTopicXseries != null) {
          firstWidth = mnTopicXseries.offsetLeft + 1;
          mnTopicXseries.getElementsByTagName('div')[0].style.left = -firstWidth + "px";
        }
        if(mnTopicMseries != null) {
          firstWidth = mnTopicMseries.offsetLeft + 1;
          mnTopicMseries.getElementsByTagName('div')[0].style.left = -firstWidth + "px";
        }
      }
      /* end DE only */

      if (window.addEventListener) {
        document.addEventListener("click", function(){self.closeMenu(); }, false);
      } else if (window.attachEvent) {
        document.attachEvent("onclick", function(){self.closeMenu(); });
      }
      highlightNavigation();
    };
    this.initFolding = function(foldingSteps, foldInterval){
      if( modulenaviAnimation != false ){
        _foldingSteps = (foldingSteps !== undefined && typeof foldingSteps == 'number') ? foldingSteps : _foldingSteps;
        _foldInterval = (foldInterval !== undefined && typeof foldInterval == 'number' && foldInterval > 200) ? foldInterval : _foldInterval;
      }

      if(!foldingActive){
        mnContainer.style.top = 0;
        currentTop = parseInt(mnContainer.style.top, 10);
        eventObj = (window.document.compatMode && window.document.compatMode == "CSS1Compat") ? window.document.documentElement : window.document.body || null;
        $(document).mousemove(onMouseMoveEvent);
        mouseIntId = window.setInterval( function(){ triggerFolding(); }, 200 );
        foldingActive = true;
      }
      triggerFolding();
    };
    this.stopFolding = function(){
      mnContainer.style.top = 0;
      document.onmousemove = undefined;
      foldingActive = false;
      idModules.style.position = 'absolute';
      window.clearInterval(mouseIntId);
      window.clearInterval(foldIntId);
    }
    var highlightNavigation = function(){
      var mnObj = document.getElementById(mainNavigationId);
      var currentHighlightLinks = mnObj.getElementsByTagName('a');
      var linksMain = [];
      for (var i = 0; i < currentHighlightLinks.length; i++) {
        if (currentHighlightLinks[i].href.indexOf('javascript:') == -1 && currentHighlightLinks[i].href.indexOf('http://') == -1) {
          linksMain[i] = 'http://' + window.location.hostname + '' + currentHighlightLinks[i].href;
        } else {
          linksMain[i] = currentHighlightLinks[i].href;
        }
      }
      var evaluatedLinks = evaluateHighlighting(window.location.href, linksMain);
      var highlightedIndex = -1;
      var bestmatch = 999;
      for (var j = 0; j < evaluatedLinks.length; j++) {
        if (evaluatedLinks[j] < bestmatch) {
          bestmatch = evaluatedLinks[j];
          highlightedIndex = j;
          if (evaluatedLinks[j] == -2) {
            break;
          }
        }
      }
      if (highlightedIndex != -1) {
        var currentLink = currentHighlightLinks[highlightedIndex];
        addClassName(currentLink, 'mainNaviHighlight');
        var currentNavParent = currentLink.getAttribute('navParent');
        if (currentNavParent) {
          addClassName(document.getElementById(currentNavParent), 'mainNaviHighlight');
        }
        if ( hasClassName( currentLink, 'topicHeader' ) ) {
          if (currentHighlightLinks[ highlightedIndex + 1 ] ) {
            addClassName(currentHighlightLinks[highlightedIndex + 1], 'mainNaviHighlight');
          }
        }
      }
    };
    var onMouseMoveEvent = function(e){
      if (!e) {
        e = window.event;
      }
      currentMouseY = e.pageY ? e.pageY : e.clientY + eventObj.scrollTop;
    };
    var triggerFolding = function(){
      var currentHover = currentTop + parseInt(mnContainer.offsetHeight, 10) + 30;
      if (currentMouseY < currentHover && currentTop < 0) {
        window.clearInterval(foldIntId);
        foldIntId = window.setInterval( function(){ moveDown(); }, _foldInterval);
      } else if (currentMouseY > currentHover && currentTop > -_maxFold) {

        window.clearInterval(foldIntId);
        foldIntId = window.setInterval( function(){ moveUp(); }, _foldInterval);
      }
    };
    var moveDown = function(){
      currentTop = parseInt(mnContainer.style.top, 10);
      if (currentTop < 0) {
        var nextPos = (currentTop + (_maxFold / _foldingSteps));
        mnContainer.style.top = ( nextPos > 0 )?  '0px':nextPos + 'px';
        idModules.style.top = ( nextPos > 0 )?  '0px': nextPos * (-1);

      } else {
        window.clearInterval(foldIntId);
      }
    };
    var moveUp = function(){
      currentTop = parseInt(mnContainer.style.top, 10);
      if (currentTop > -_maxFold) {
        var nextPos = (currentTop - (_maxFold / _foldingSteps));
        mnContainer.style.top = ( nextPos < -_maxFold )?  -_maxFold + 'px':nextPos + 'px';
        idModules.style.top = "75px";
      } else {
        window.clearInterval(foldIntId);
      }
    };

    this.closeMenu = function(){
      if (!hoverActive && oldMenuObject !== undefined) {
        this.nodeAction(oldMenuObject, 'click');
      }
    };
    this.nodeAction = function(nodeObject, eventType){
      if(confCountryId=='JP'){

      if ((oldMenuObject == nodeObject && eventType == 'click')) {
        setCurtain(0);
        if (foldingActive && eventType == 'click') {
          mouseIntId = window.setInterval(function(){ triggerFolding(); }, 200);
        }
        removeClassName(nodeObject.parentNode, 'active');
        oldMenuObject = undefined;
        menuActive = false;
        mainNaviOpen = false;
      } else {
        if( eventType == 'mouseover' ){
          setCurtain(1);
          if (foldingActive) {
            clearInterval(mouseIntId);
          }
        }
        if (eventType == 'mouseover' || (eventType == 'mouseover' && menuActive)) {
          if (oldMenuObject !== undefined) {
            removeClassName(oldMenuObject.parentNode, 'active');
          }
          addClassName(nodeObject.parentNode, 'active');
          oldMenuObject = nodeObject;
          menuActive = true;
          mainNaviOpen = true;
        }
      }

      }else{
      if ((oldMenuObject == nodeObject && eventType == 'click')) {
        setCurtain(0);
        if (foldingActive && eventType == 'click') {
          mouseIntId = window.setInterval(function(){ triggerFolding(); }, 200);
        }
        removeClassName(nodeObject.parentNode, 'active');
        oldMenuObject = undefined;
        menuActive = false;
        mainNaviOpen = false;
      } else {
        if( eventType == 'click' ){
          setCurtain(1);
          if (foldingActive) {
            clearInterval(mouseIntId);
          }
        }
        if (eventType == 'click' || (eventType == 'mouseover' && menuActive)) {
          if (oldMenuObject !== undefined) {
            removeClassName(oldMenuObject.parentNode, 'active');
          }
          addClassName(nodeObject.parentNode, 'active');
          oldMenuObject = nodeObject;
          menuActive = true;
          mainNaviOpen = true;
        }
      }
      }
      if (eventType == 'mouseover') {
        hoverActive = true;
      } else if (eventType == 'mouseout') {
        hoverActive = false;
      }

      return false;
    };
  });
})();

  selectBoxes = new Array();
  directOrder = new Array();
  function checkSelectBoxStatus() {
    for(j=0;j<selectBoxes.length;j++) {
      if(!directOrder[selectBoxes[j]]) {
        setVisibility('selectBoxContent'+selectBoxes[j],0,'none');
      }
    }
  }

  function selectBoxNotify(formField) {
   ;
  }
   function setOption(text, value, formField, notify, index, formName) {
    formFieldValue = value;
    activeText = text;
    setVisibility('selectBoxContent'+formField,0,'none');
    writeIntoLayer('selectedValue'+formField, "&nbsp; " + text);

    if(formName != 'none') {
      if(typeof formName != 'undefined' && formName!=null && formName!=""){
        if(document.forms.length > 0) {
          document.forms[formName][formField].value = formFieldValue;
        }
      }else{
        if(document.forms.length > 0) {
          document.forms[0][formField].value = formFieldValue;
        }
      }
    }

    if(notify) {
      selectBoxNotify(formField,formFieldValue,index);
    }
  }

//SWF Object 1.5
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

