// take care variables are definitly defined
var technologyguideDatabasePath = false;
var confCountryTopic  = null;
var confLanguageTopic = null;
var modulnavHeightTeasermode = 274;

// Country-Language
confCountryId  = "RO";
confLanguageId = "ro";

// Perso Engine
confPersoEngineEnabled = false;
// confPersoEnginePid = 	"";
// confPersoEngineEventController = "";
// confPersoEngineProfileController = "";

// Perso Engine + SILO
confPersoEngineSSOEnabled = false;
confPersoEngineSSOController = "?pid=&sys=&lan=ro";
// confPersoSsoSalutation = "";
// confPersoSsoLogin = "";
// confPersoSsoLogout = "";

// Tracking
confTrackingEnabled = false;
gDcsId  = "-";
gDomain = "-";

// Browser Check
confBrowserCheckEnabled = false;
confBrowserCheckHighendEnabled = false;
confIncompatibleBrowserUrl  = "/ro/ro/general/incompatible.html";

// Technology Guide
technologyguideEnabled = false;
technologyguideDatabasePath = "/ro/ro/insights/technology/technology_guide/_narrowband/js/database.js";

// SEO
seoEnabled = false;

// ID-Modules
confIdModuleImage = "/ro/ro/_common/shared/img/id_moduls.png";
confIdModuleImageGrey = "/ro/ro/_common/shared/img/id_moduls_grey.png";
confIdModuleImageService = "/ro/ro/_common/shared/img/id_moduls_service.png";
// confIdModuleImageFinance = "";

// Height Of Modulnavigation
modulnavHeightTeasermode = 274;

// Date format
confDateFormat = "DD.MM.YYYY";

// Price and hundreds delimiter
confPriceDelimiter    = ".";
confHundredsDelimiter = ",";

// Topnavi X displayed
topnaviXenabled = "false";

// tracking page urls
var trackingPages=new Array();
trackingPages["download"] = new Array("/ro/ro/_common/shared/tracking_redirect/download.html", "download");
trackingPages["external"] = new Array("/ro/ro/_common/shared/tracking_redirect/external.html", "external");
trackingPages["small_standard"] = new Array("/ro/ro/_common/shared/tracking_redirect/teaser_small_standard.html", "teaser_small_standard");
trackingPages["large"] = new Array("/ro/ro/_common/shared/tracking_redirect/teaser_large.html", "teaser_large");
trackingPages["main"] = new Array("/ro/ro/_common/shared/tracking_redirect/teaser_main.html", "teaser_main");
trackingPages["small_text"] = new Array("/ro/ro/_common/shared/tracking_redirect/teaser_small_text.html", "teaser_small_text");
trackingPages["medium_label"] = new Array("/ro/ro/_common/shared/tracking_redirect/teaser_medium_label.html", "teaser_medium_label");
trackingPages["click_event"] = new Array("/ro/ro/_common/shared/tracking_redirect/click_event.html", "click_event");
trackingPages["3seriestouring"] = new Array("/ro/ro/_common/shared/tracking_redirect/experience/3seriestouring.html", "3seriestouring");
trackingPages["bandwidth"] = new Array("/ro/ro/_common/shared/tracking_redirect/bandwidth.html", "bandwidth");
trackingPages["quicklinks"] = new Array("/ro/ro/_common/shared/tracking_redirect/quicklinks.html", "quicklinks");


//Bandwidth layer
var bandwidth_bottomnavi_link_high = "Conţinut broadband";
var bandwidth_bottomnavi_link_low = "Conţinut prin modem/ ISDN";
var bandwidth_headline_high = "Afişaţi conţinutul pentru conexiunile broadband.";
var bandwidth_copy_high = "Website-ul internaţional BMW, include o gamă largă de secvenţe video, animaţii şi muzică – ideal pentru conexiunile broadband şi DSL. Vă rugăm reţineţi că dacă folosiţi o conexiune prin modem sau ISDN, încărcarea conţinutului broadband va dura considerabil mai mult. ";
var bandwidth_link_high = "Afişaţi conţinutul pentru conexiunile broadband";
var bandwidth_headline_low = "Pentru conexiuni prin modem şi ISDN.";
var bandwidth_copy_low = "Website-ul internaţional BMW, include toate imaginile şi informaţiile, dar fără sunet sau secvenţe video – ideal pentru conexiunile prin modem sau ISDN. ";
var bandwidth_link_low = "Afişaţi conţinutul pentru conexiunile prin modem şi ISDN";
var bandwidth_save_headline = "Setaţi conexiunea internet";
var bandwidth_save_copy = "Afişaţi întotdeauna următorul conţinut:";
var bandwidth_save_button = "Salvaţi";
var bandwidth_save_select = "Vă rugăm selectaţi";
var bandwidth_save_highband = "Conţinut broadband";
var bandwidth_save_lowband = "Conţinut prin modem/ ISDN";
var bandwidth_save_auto = "Verificaţi automat";
var bandwidth_save_confirm = "Conexiunea dumneavoastră internet a fost salvată.";
var bandwidth_save_error_no_selection = "Vă rugăm selectaţi o versiune de conţinut.";
var bandwidth_save_error_no_cookies = "Ne pare rău, nu putem salva setările dumneavoastră, pentru că browser-ul dumneavoastră nu acceptă cookies.";

// enhanced bandwidth detection
var enhanced_bandwidth_detection = false;
var enhanced_bandwidth_detection_threshold = "0";















topnavi_mode = "closed";
var topnavi_open_layer = 0;
var mainNaviIsAnimating = false;
var moduleNavigationOpen = true;
var mainNavigationOpen = false;
var navigationHighlightComplete = false;
var shareUrl = self.location.href;
var shareTitle = document.title;
var selectedHighlightUrl = "";
var swf_corelib = buildValidServerRelativeUrl("/_common/rebrush/swf/libraries/bmw_as3_corelib_1_1.swf");
var swf_components = buildValidServerRelativeUrl("/_common/rebrush/swf/components/bmw_as3_components_2_0.swf");
var salesNavigationTopPos = 634;
var co2DisclaimerCookieName = "";
var scrollerDefaultSize = 1024;
var ecomlight = false;

function checkWindowSize() {}

function trackingCookie(){
  return false
}

var modulenaviIEStyles = "<style type=\"text/css\">" +
  "#module_navigation td.shadow_right {" +
  "  background: none;" +
  "  filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/rebrush/img/dialogbox/dialogbox_right.png', sizingMethod='crop');" +
  "}" +
  "#module_navigation td.shadow_bottom {" +
  "background: none;" +
  "  filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/rebrush/img/backgrounds/module_navigation_bottom_bg.png', sizingMethod='crop');" +
  "}" +
  "</style>";

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

function redraw(obj) {
  if(document.all) {
    elm = document.getElementById(obj);
    elm.style.display = "none";
    var redrawFix = elm.offsetHeight;
    elm.style.display = "block";
  }
}

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

function initStandardPage() {
  checkClient();
  salesNavigationCheckPosition();
  $(window).resize(function(){
    salesNavigationCheckPosition();
  });
  $(window).scroll(function(){
    salesNavigationCheckPosition();
  });
  highlightVehicleNavigation();

  $("a.shareButton").hover(
    function (event) {
      setCurtain(1);
      var layerName = "#shareDialogLayer";
      var topPos = $(this).offset().top - ($(layerName).height() - 1) + 5;
      var leftPos = event.pageX -262 + 18;
      $(layerName + " .bottomArrowImage").addClass("bottomArrowImageRight").removeClass("bottomArrowImage");
      $(layerName).css("top", topPos ).css("left", leftPos);
      $(layerName).css("visibility","visible");
      $("a.shareButton").addClass("shareButtonActive");
      $(layerName).bind("mouseleave", function(){
        $(layerName).css("visibility","hidden");
        $(layerName).css("top","-500px");
        $(layerName).css("left","-500px");
        setCurtain(0);
        $("a.shareButton").removeClass("shareButtonActive");
        $(layerName).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" ) {
        setCurtain(0);
        $("#shareDialogLayer").css("visibility","hidden").css("top","-500px").css("left","-500px");
        $("a.shareButton").removeClass("shareButtonActive");
      }
      return false;
    }
  );

  $("a.shareButton").mousemove(function(event) {
    var leftPos = event.pageX;
    leftPos = leftPos - 262 + 10;
    $("#shareDialogLayer").css("left", leftPos);
  });


  if(typeof confPersoEngineSSOEnabled == "boolean"){
    if(confPersoEngineSSOEnabled){
      persoSsoLoadJs();
    }
  }
}


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) {
  var trackingParam = "cm=" + service;
  var currentShareUrl = shareUrl;
  if(shareUrl.indexOf("?") != -1) {
     currentShareUrl = currentShareUrl + "&" + trackingParam;
  }
  else {
     currentShareUrl = currentShareUrl + "?" + trackingParam;
  }
  url = url.replace("{#share_url}", escape(currentShareUrl));
  url = url.replace("{#share_title}", escape(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();
    var paddingTop = 0;
    var paddingBottom = 0;
    var paddingLeft = 0;
    var paddingRight = 0;
    if($(this).find(".content").css("paddingTop")) {
      paddingTop = Number($(this).find(".content").css("paddingTop").replace("px",""));
    }
    if($(this).find(".content").css("paddingBottom")) {
      paddingBottom = Number($(this).find(".content").css("paddingBottom").replace("px",""));
    }
    if($(this).find(".content").css("paddingLeft")) {
      paddingLeft = Number($(this).find(".content").css("paddingLeft").replace("px",""));
    }
    if($(this).find(".content").css("paddingRight")) {
      paddingRight = Number($(this).find(".content").css("paddingRight").replace("px",""));
    }
    var paddingV = paddingTop + paddingBottom;
    var paddingH = paddingLeft + paddingRight;
    $(this).find(".leftBorder").css("height",contentHeight + paddingV);
    $(this).find(".rightBorder").css("height",contentHeight + paddingV);
    $(this).find(".content").css("height",contentHeight);
    $(this).find(".content").css("width",contentWidth);
    $(this).find(".topBorder").css("width",contentWidth - 6 + paddingH);
    $(this).find(".bottomBorder").css("width",contentWidth - 4 + paddingH);
    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() {
  initMainNavigation();
  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 {
          if( $(event.relatedTarget).attr("id").indexOf("sales_navigation_select") < 0) {
            closeSalesNavLayer(salesNavigationButtonWidth, salesNavigationLayerElement, salesNavigationButtonElement);
          }
        }

      }
      catch(e) {}
    });

    $(activeLayerName).show();
    $(activeLayerName).height($(activeLayerName + " .box").height()+25);

    var topPos = salesNavigationTopPos - ($(activeLayerName + " .box").height() + 25);

    jQuery.each(jQuery.browser, function(i, val) {
      if(i == "msie" && jQuery.browser.version.substr(0,1) == "6") {
        topPos += 1;
      }
    });

    $(activeLayerName).css("top", topPos);

  });
  //end: salesnavi event-steuerung

  //start: salesnavi selectboxes event-steuerung
  $("a.sales_navigation_selectbox").click( function (event) {
    var tempId = $(this).attr("id");
    if($("#sales_navigation_"+tempId).css("display")=="block"){
     $(".sales_navigation_dropdown").scrollTop(0);
     $(".sales_navigation_dropdown").hide();
    }else{
    $(".sales_navigation_dropdown").scrollTop(0);
    $(".sales_navigation_dropdown").hide();
      if($(this).hasClass('downward')) {
        var newTopPos = $(this).offset().top + 16;
      }
      else {
        var newTopPos = ($(this).offset().top) - ($("#sales_navigation_"+tempId).height()) - 10;
      }



      $("#sales_navigation_" + tempId).css("top",newTopPos).css("left",$(this).offset().left);
      $("#sales_navigation_" + tempId).scrollTop(0);
      $("#sales_navigation_" + tempId).show();

      if(tempId.indexOf("select_golocal_") > -1) {
        $(document).keydown(function(event) {
          if(event) {
            $('#sales_navigation_' + tempId + ' a').removeClass("blue");
            var keyPressed = String.fromCharCode(event.keyCode);
            $('#sales_navigation_' + tempId + ' a').each(function(){
              if( $(this).html().substr(0,1) ==  keyPressed) {
                var position = $(this).position();
                $('#sales_navigation_' + tempId).scrollTop(position.top + $('#sales_navigation_' + tempId).scrollTop());
                $(this).addClass("blue").focus();
                return false;
              }
            });


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

  $(".sales_navigation_dropdown a").click(function (event) {
    var elementID = $(this).parent().attr("id").replace(/sales_navigation_/g, "");

    if($(this).parent().attr("id").indexOf("sales_navigation_select_golocal_") > -1 ) {
      var trackingUrl = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/external.html" + "?target=" + $(this).attr("href") + "&source=" + escape(self.location.href);
      trackPage(trackingUrl);
      window.open($(this).attr("href"),"golocal");
    }
    else {
      $("#" + 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("blueButton")) {
        $("#sales_navigation_button_" + i).css("color","#0044cc");
        $(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","#0044cc");
      $(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/rebrush/img/dialogbox/dialogbox_top.png', sizingMethod='scale');}" +
  ".dialogbox .rightBorder, .shadowbox .rightBorder {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/rebrush/img/dialogbox/dialogbox_right.png', sizingMethod='crop');}" +
  ".dialogbox .bottomBorder, .shadowbox .bottomBorder {background-image:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/rebrush/img/dialogbox/dialogbox_bottom.png', sizingMethod='crop');}" +
  ".dialogbox .bottomBorder .bottomArrowImage, .shadowbox .bottomBorder .bottomArrowImage {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/rebrush/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/rebrush/img/dialogbox/dialogbox_bottom_arrow.png', sizingMethod='crop');}" +
  ".dialogbox .leftBorder, .shadowbox .leftBorder {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/rebrush/img/dialogbox/dialogbox_left.png', sizingMethod='crop');}" +
  ".dialogbox .corner, .shadowbox .corner {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/_common/rebrush/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/rebrush/img/palette/1x1_ffffff.gif" height="10" width="10">');
  $(".shadowbox").prepend('<img class="background" src="' + getWcmsPrefix() + '/_common/rebrush/img/palette/1x1_ffffff.gif" height="10" width="10">');
  $(".dialogbox").append('<div class="bottomBorder"><div class="bottomArrowImage"></div></div><div class="corner"></div>');
  $(".dialogbox .content").append('<div class="topBorder"></div><div class="leftBorder"></div><div class="rightBorder"></div>');

  $(".shadowbox").not(".nobottom").append('<div class="bottomBorder"></div><div class="corner"></div>');
  $(".shadowbox .content").not(".notop").append('<div class="topBorder"></div>');
  $(".shadowbox .content").not(".noleft").append('<div class="leftBorder"></div>');
  $(".shadowbox .content").not(".noright").append('<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 ******** //

// ******** MODULENAVI START ******** //
  $('<img />').attr('src', getWcmsPrefix() + '/_common/rebrush/img/standard_elements/arrow_up-h.gif');
  $('<img />').attr('src', getWcmsPrefix() + '/_common/rebrush/img/standard_elements/arrow_down.gif');
  $('<img />').attr('src', getWcmsPrefix() + '/_common/rebrush/img/standard_elements/arrow_down-h.gif');

  moduleNavigationInit();
// ******** MODULENAVI END ******** //


// handheld-fix for bottomnavigation

function moveBottomNavigation(){
  if(window.orientation==0){
    if(initialCallPortrait){
     heightPortrait = $(document).height();
     initialCallPortrait=false;
    }
    endHeight = heightPortrait;
   }else{
    if(initialCallLandscape){
     heightLandscape = $(document).height(); ;
     initialCallLandscape=false;
    }
     endHeight = heightLandscape;
   }
   $("#bottomNavigation").css("top", ""+endHeight+"px");
   $("#bottomNavigation").css("display", "block");
   $("#bottomNavigation").css("visibility", "visible");
}

var supportsOrientationChange = "onorientationchange" in window,
  orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

if(supportsOrientationChange){
  $("#bottomNavigation").css("position", "absolute");
  $("#bottomNavigation").css("display", "none");
  $("#bottomNavigation").css("visibility", "hidden");
  var initialCallPortrait= true;
  var initialCallLandscape= true;
  var heightPortrait= "";
  var heightLandscape= "";
  var endHeight = "";
  var isInitialCall = true;

  if(isInitialCall){
    isInitialCall = false;
    moveBottomNavigation()
  }
   window.addEventListener(orientationEvent, function() {
    $("#bottomNavigation").css("display", "block");
    $("#bottomNavigation").css("visibility", "visible");
    moveBottomNavigation();

}, false);
};

});
//document.ready end


function moduleNavigationInit() {
  $("#module_navigation ul a[href='']").click(function(e) {

    if(typeof $(this).next().tagName() == "string") {

      if($(this).next().tagName() == "ul") {
        if($(this).next().css("display") == "block") {
          $(this).next().css("display","none");
        }
        else {
          $("#module_navigation ul ul").not($(this).parent().parent()).css("display","none");
          $(this).next().css("display","block");
        }
      }
    }

    redraw("module_navigation");
    return false;
  });

  $("#module_navigation .control").click(function() {
    if(moduleNavigationOpen) {
      moduleNavigationOpen = false;
      var aniTop = 0 - ($("#module_navigation").height() - 97);
      $("#module_navigation").animate({top: aniTop},"fast");
      $("#module_navigation .control div").removeClass().addClass("down");
    }
    else {
      moduleNavigationOpen = true;
      $("#module_navigation").animate({top: "76px"},"fast");
      $("#module_navigation .control div").removeClass().addClass("up");
    }
  });


  $("#module_navigation .control").hover(
    function () {
      if(moduleNavigationOpen) {
        $("#module_navigation .control div").removeClass().addClass("upHigh");
      }
      else {
        $("#module_navigation .control div").removeClass().addClass("downHigh");
      }

    },
    function () {
      if(moduleNavigationOpen) {
        $("#module_navigation .control div").removeClass().addClass("up");
      }
      else {
        $("#module_navigation .control div").removeClass().addClass("down");
      }
    }
  );
}
// ******** MAIN NAVIGATION START ******** //

function foldMainNavi(status){
  if(moduleNavigationOpen){
    foldModuleNavi(true);
  }
  if(status === undefined){
    if($("#mainNavigationContainer").css("top") == "0px"){
      mainNavigationHide();
      startAutoFoldMainNavi();
    }else{
      mainNavigationShow();
      stopAutoFoldMainNavi();
    }
  }else if(status){
    mainNavigationHide();
      startAutoFoldMainNavi();
  }else if(!status){
    mainNavigationShow();
      stopAutoFoldMainNavi();
  }
}

function startAutoFoldMainNavi(){
  $(document).bind("mousemove", function(mouseEvent){

    if(($("#mainNavigationContainer").css("top").replace("px", "") == -48) && (mouseEvent.pageY <= 48)){
      if(!mainNaviIsAnimating && !moduleNavigationOpen && !mainNavigationOpen){
        mainNaviIsAnimating = true;
        $("#mainNavigationContainer").stop().animate({top: "0px"}, function(){
          mainNaviIsAnimating = false;
        });
      }
    }

    if(($("#mainNavigationContainer").css("top").replace("px", "") == 0) && (mouseEvent.pageY >= 100)){
      if(!mainNaviIsAnimating && !moduleNavigationOpen && !mainNavigationOpen){
        mainNaviIsAnimating = true;
        $("#mainNavigationContainer").stop().animate({top: "-48px"}, function(){
          mainNaviIsAnimating = false;
        });
      }
    }
  });
}

function stopAutoFoldMainNavi(){
  $(document).unbind("mousemove");
}

function mainNavigationShow(){
  $("#mainNavigationContainer").animate({top: "0px"});
}

function mainNavigationHide(){
  $("#mainNavigationContainer").animate({top: "-48px"});
}

function initMainNavigation() {

  if(getWcmsPrefix() != "/bmw_edit"){
    highlightNavigations();
  }

  var searchBoxInputTopNavi = $("#searchBox #searchBoxText");
  $(searchBoxInputTopNavi).attr("defaultText", $(searchBoxInputTopNavi).val());
  $(searchBoxInputTopNavi).focus(function (e) {
    if($(searchBoxInputTopNavi).val() == $(searchBoxInputTopNavi).attr("defaultText")){
      $(searchBoxInputTopNavi).val("");
    }
  }).blur(function (e) {
    if($(searchBoxInputTopNavi).val() == ""){
      $(searchBoxInputTopNavi).val($(searchBoxInputTopNavi).attr("defaultText"));
    }
  });

  var searchBoxInputQuicklinks = $("#searchBoxQuicklinks .searchBoxText");
  $(searchBoxInputQuicklinks).attr("defaultText", $(searchBoxInputQuicklinks).val());
  $(searchBoxInputQuicklinks).focus(function (e) {
    if($(searchBoxInputQuicklinks).val() == $(searchBoxInputQuicklinks).attr("defaultText")){
      $(searchBoxInputQuicklinks).val("");
    }
  }).blur(function (e) {
    if($(searchBoxInputQuicklinks).val() == ""){
      $(searchBoxInputQuicklinks).val($(searchBoxInputQuicklinks).attr("defaultText"));
    }
  });

  $(".layer_content_text .topicHeader a.blue").each(function(i,e){
    $($(".layer_content_text .topicHeader a.blue")).parent().next().find("a").addClass("blue");
  });

  $(".layer_content_models .model img").each(function(i,e){
    $(this).attr("src",$(this).attr("preload"));
  });

  $(".layer_content_models .model a").hover(function(){
    var currentClass = $(this).next().find("a");
    if(currentClass.hasClass("blue")){
      currentClass.addClass("fixed");
    }
    currentClass.addClass("blue");
  }, function(){
    var currentClass = $(this).next().find("a");
    if(!currentClass.hasClass("fixed")){
      currentClass.removeClass("blue");
    }
  });

  $(".topnavi_models_low a.nonVehicle").each(function(i,e){
    $("#" + $(this).attr("id").replace("topnavi_link","topnavi_layer")).css("left", "247px");
  });

  $(".topnavi_models_low a, .topnavi_models_high a").click( function () {
    if($(this).attr("href") != ""){
      return true;
    }
    var currentId = $(this).attr("id");
    if(topnavi_mode == "closed") {
      setCurtain(1);
      $("#" + currentId.replace("topnavi_link","topnavi_highlight")).css("visibility","visible");
      $("#" + currentId.replace("topnavi_link","topnavi_layer")).css("visibility","visible");
      topnavi_mode = "open";
      mainNavigationOpen = true;
      return false;
    } else {
      setCurtain(0);
      $("#" + currentId).css("visibility","hidden");
      $("#" + currentId.replace("topnavi_highlight","topnavi_layer")).css("visibility","hidden");
      topnavi_mode = "closed";
      mainNavigationOpen = false;
      return false;
    }
  });

  $(".topnavi_models_low a").mouseenter( function () {
    var currentId = $(this).attr("id");
    if($(this).attr("href") != ""){
      topnaviCloseAll(currentId.replace("topnavi_link_",""));
      return true;
    }
    if(topnavi_mode == "open") {
      topnaviCloseAll(currentId.replace("topnavi_link_",""));
      $("#" + currentId.replace("topnavi_link","topnavi_highlight")).css("visibility","visible");
      $("#" + currentId.replace("topnavi_link","topnavi_layer")).css("visibility","visible");
    }
  });

  $(document).click( function () {
    topnaviCloseAll(null);
    topnavi_mode = "closed";
    mainNavigationOpen = false;
    setCurtain(0);
  });
}


function topnaviCloseAll(outside) {
  $(".topnavi_layer").not("#topnavi_layer_" + outside).css("visibility","hidden");
  $(".topnavi_models_high .shadowbox").not("#topnavi_layer_"+ outside).css("visibility","hidden");
}

function findHighlightLink(currentHighlightLinks){
  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;
  if((getWcmsPrefix() == "/bmw_edit") && (evaluatedLinks.length == 1)){
    if (evaluatedLinks[0] == -2) {
      highlightedIndex = 0;
    }
  }else{
    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){
    currentHighlightLinks.eq(highlightedIndex).addClass("blue");
    return true;
  }else{
    return false;
  }
}

function highlightNavigations(){
  findHighlightLink($("#module_navigation .content ul li a[href!='']"));
  findHighlightLink($("#bottomLinks .linklist_horizontal a[href!='']"));
  if(!findHighlightLink($("#topnavi .small a[href!='']"))){
    findHighlightLink($(".topnavi_models_low a[href!='']"));
    findHighlightLink($(".layer_content_text a[href!='']"));
    findHighlightLink($(".layer_content_models a[href!='']"));
    if($(".topnavi_layer:has(a.blue)").size() > 0){
      $("#" + $(".topnavi_layer:has(a.blue)").attr("id").replace("topnavi_layer", "topnavi_link")).addClass("blue");

      if($(".topnavi_layer .layer_content_models a.blue").attr("href") == $(".topnavi_layer .layer_content_models a.blue").next().find("a").attr("href")){
        $(".topnavi_layer .layer_content_models a.blue").next().find("a").addClass("blue");
      }

    }
  }
  $("#module_navigation ul:has(a.blue)").show().prev("a").addClass("blue");
  navigationHighlightComplete = true;
}

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


// ******** MODULENAVI START ******** //
function foldModuleNavi(value) {
  if(navigationHighlightComplete){
    moduleNavigationOpen = value;
    if($("#module_navigation .control").size() != 0){
      $("#module_navigation .control").click();
    }else{
      if(moduleNavigationOpen) {
        moduleNavigationOpen = false;
      }
    }
  }else{
    navigationHighlightComplete = true;
    window.setTimeout("foldModuleNavi(" + value + ")", 1000);
  }
}
// ******** MODULENAVI END ******** //

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

function closeSalesNavLayer(buttonWidth, layerElement, buttonElement) {
  $(".sales_navigation_dropdown").scrollTop(0);
  $(".sales_navigation_dropdown").hide();
  $(document).unbind('keydown');
  resetToggle("a.sales_navigation_selectbox");
  buttonElement.css("width",buttonWidth);
 layerElement.hide();
}

function resetToggle(selector,currentObject) {
  $(selector).each(function() {
    if(currentObject != this) {
      jQuery.data( 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");
  if($("#mgmbh_body").size() == 0){
    vehicle_navigation_teaser_write(teaser_number);
  }else{
    vehicle_navigation_teaser_write_mgmbh(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 = '          <strong>' + vehicle_navigation_teaser_db[teaser_number][2] + '</strong>\n' +
             '          <div id="teaser_image">\n' +
             '            <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 += '            <div id="teaser_image_icon">\n' +
             '              <a class="vehicle_navigation_teaser_button" onclick="vehicle_navigation_teaser_write(' + new_teaser_number + ');return false;" href=""></a>' +
             '<span id="teaser_image_icon_counter">' + (teaser_number+1) + '&nbsp;/&nbsp;' + vehicle_navigation_teaser_db.length + '</span>\n' +
             '            </div>\n';
  }
     code += '          </div>\n' +
             '          <div id="teaser_text">\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 vehicle_navigation_teaser_write_mgmbh(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="180" height="90" alt=""></a>\n';
  if(vehicle_navigation_teaser_db.length > 1) {
     code += '          <a class="vehicleNavigationTeaserButton" onclick="vehicle_navigation_teaser_write_mgmbh(' + 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", "180", "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","#0044cc");
      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","#0044cc");
        success = true;
      }
    });
  }
}

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

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





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

  $('#mgmbh_body #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) {
    $('#mgmbh_body #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 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 extractFoldersMGmbH(myString) {
  var splitArray  = myString.split("/");
  var resultArray = new Array(splitArray[splitArray.length - 4], splitArray[splitArray.length - 3], splitArray[splitArray.length - 2], splitArray[splitArray.length - 1]);
  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(){
    $("#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();
    });
    $("#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);
          $("#contentTeaserList .contentTeaser img").hover(function(){$(this).next().children().addClass("active")},function(){$(this).next().children().removeClass("active")});
        }
        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').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#mainNavigationContainer').height() - $('div#sales_navigation').height())/2 + $('div#mainNavigationContainer').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#mainNavigationContainer').height() - $('div#sales_navigation').height())/2 + $('div#mainNavigationContainer').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#mainNavigationContainer').height() - $('div#sales_navigation').height())/2 + $('div#mainNavigationContainer').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: transGif, width: lightboxContent[thisNumber]["width"], height: lightboxContent[thisNumber]["height"], alt: ""}).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) {
    if(i != "remove") {
      compare_model_short.push(i);
    }
  }
  //compare_model_short.sort();
  var dropdownCode = "";
  for(i = 0; i <= (compare_model_short.length - 1); 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);
    }


try {
    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>';
      }
    }

}
catch(e) {}

  }
  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 ******** //


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 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 allowClose = true;
var modulNaviOverImage = true;
var idmodulsSpecial = "";
var minFlashVersion = 7;
var indexParameters = "";
var query = {};
var parameterArray = [];

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 useCurtain = false;
var htmlDialogOpen = false;
var currentObj = "";


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 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 getWindowInformation(attributeName){
  var windowInformation = [];
  windowInformation['winWidth'] = $(window).width();
  windowInformation['winHeight'] = $(window).height();
  windowInformation['docWidth'] = $(document).width();
  windowInformation['docHeight'] = $(document).height();
  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 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 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 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]++;
}


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

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

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, text);
  selectedBandwidth = userBandwidth;
}

function setCurtain(mode){
  if ((useCurtain) && (useCurtain == "true")) {
    if (mode == 1) {
      $('#iFrameContainer, #externalContentIFrame').hide().css('left',window.screen.width * 2 * -1);
      $('#curtain').show();

      if(ecomlight) {
        $(".topnavi_layer").css("display","block");
        $('html').css('overflow-y','auto');
        ecomLightSetIFrameDimensions();
        $("#externalContentIFrame").css("display","none");
      }
    } else {
      $('#curtain').hide();
      if(ecomlight) {
        $(".topnavi_layer").css("display","none");
        $('html').css('overflow-y','hidden');
        $("#externalContentIFrame").css("display","block");
        ecomLightSetIFrameDimensions();
      }
      if (typeof leftPos != 'undefined') {
        $('#iFrameContainer, #externalContentIFrame').hide().css('left', leftPos);
      } else {
        $('#iFrameContainer, #externalContentIFrame').hide().css('left', 0);
      }
      $('#iFrameContainer, #externalContentIFrame').show();
    }
  }
}

function ecomLightSetIFrameDimensions() {
  var iframe_width  = $(window).width() - iframe_pos_left;
  var iframe_height = $(window).height() - iframe_pos_top - 30;
  iframe_width = (iframe_width < 1000) ? 1000 : iframe_width;
  $("#externalContentIFrame").css("height", iframe_height).css("width", iframe_width);
  //$("#curtain").css("height", iframe_height).css("width", iframe_width - 40);
  $("#curtain").css("width", iframe_width - 40);
  $("#innerCurtain").css("height", iframe_height).css("width", iframe_width);
  }

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 = "vhigh";
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 = "vhigh";
       }
     }
   }
}
if (detectedBandwidth == "vhigh") {
  highbandUser = true;
}

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);
  $("#changeVersionLink").removeClass("blue");
  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:#0044cc">' + 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>' +
  '      <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="#0044CC" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + P0044CCGif + '" width="182" height="1"></td>' +
  '        </tr>' +
  '        <tr>' +
  '          <td bgcolor="#0044CC"><img src="' + P0044CCGif + '" width="1" height="16"></td>' +
  '          <td valign="middle" onClick="toggleBandwithPulldown();" onMouseover="directOrder[ \'Bandwidth\' ]=true;" onMouseout="directOrder[ \'Bandwidth\' ]=false;" style="cursor:pointer;"><span id="selectedValueBandwidth">&nbsp; ' + bandwidthSelectedOption + '</span></td>' +
  '          <td><a href="javascript:toggleBandwithPulldown();" onMouseover="directOrder[ \'Bandwidth\' ]=true;" onMouseout="directOrder[ \'Bandwidth\' ]=false;" onFocus="this.blur();"><img src="' + pulldownGif + '" width="18" height="16" border="0"></a></td>' +
  '          <td bgcolor="#0044CC"><img src="' + P0044CCGif + '" width="1" height="16"></td>' +
  '        </tr>' +
  '        <tr>' +
  '          <td colspan="4" bgcolor="#0044CC" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + P0044CCGif + '" width="182" height="1"></td>' +
  '        </tr>' +
  '      </table>' +
  '      <div id="selectBoxContentBandwidth" class="selectBoxContent" style="top:17px;display:none; visibility:hidden; background-color:#ffffff; position:absolute; top:58px; left:0px; z-index:2;">' +
  '        <table cellspacing="0" cellpadding="0" border="0" width="182">' +
  '          <tr>' +
  '            <td width="1" bgcolor="#0044CC" 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="#0044CC" 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="#0044CC" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + P0044CCGif + '" width="182" height="1"></td></tr>' +
  '        </table>' +
  '      </div>' +
  '    <a href="javascript:setUserBandwidth(selectedBandwidth);" id="bandwidthBoxlink">' + bandwidth_save_button + '</a><br>' +
  '    <div id="bandwidthReply"></div>' +
  '  </div>' +
  '</div>';
  }

  var bandwidthlayerPos = $(window).scrollTop();
  $("#bandwidthlayer").css("top", 162 + bandwidthlayerPos);
  writeIntoLayer("bandwidthlayer", layerContent);
  setVisibility("bandwidthlayer", 1);

  if((confCountryTopic=="de")&&(confLanguageTopic=="de")){
    document.getElementById("bandwidthlayer").style.display="block";
  }
  preload();
  $("#changeVersionLink").addClass("blue");
  bandwidthLayerState = 1;
}

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

function toggleBandwithPulldown() {
  if($("#selectBoxContentBandwidth").css("display") == "none" || $("#selectBoxContentBandwidth").css("visibility") == "hidden") {
    $("#selectBoxContentBandwidth").css("visibility","visible").css("display","block");

  }
  else {
    $("#selectBoxContentBandwidth").css("visibility","hidden").css("display","none");
  }
}


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 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

  selectBoxes = new Array();
  directOrder = new Array();

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


function setOption(text, value, formField, notify, index, formName) {
  formFieldValue = value;
  activeText = text;
  setVisibility('selectBoxContent'+formField,0);
  writeIntoLayer('selectedValue'+formField, 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) {
        if(document.forms[0][formField]) {
          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;

//  SWFObject v2.2
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();

//Perso Engine
personIndex = 0;
pImages  = new Array();
validPersoType  = false;

function createPersoEvent(persoType,persoSeries,persoBodytype,persoModel,persoColor,persoRim){
  persoType = persoType.replace(/\s+/g,"");
  if ((persoType.length >= 2) && (persoType.length <=3))
  {
    if (persoType.substr(0, 1) == "E" || persoType.substr(0, 1) == "e")
    {
      validPersoType = true;
      persoType = persoType.toUpperCase();
    }
  }
  if(confPersoEngineEnabled && validPersoType) {
    persoParamters  = "pid=" + confPersoEnginePid;
    persoParamters += "&eid=" + persoType;
    if(persoSeries && persoSeries != "null") {
      persoParamters += "&s=" + persoSeries;
    }
    if(persoBodytype && persoBodytype != "null") {
      persoParamters += "&b=" + persoBodytype;
    }
    if(persoModel && persoModel != "null") {
      persoParamters += "&m=" + persoModel;
    }
    if(persoColor && persoColor != "null") {
      persoParamters += "&c=" + persoColor;
    }
    if(persoRim && persoRim != "null") {
      persoParamters += "&r=" + persoRim;
    }
    persoParamters += "&z=" + Math.random();
    pImages[personIndex] = new Image;
    pImages[personIndex].src = confPersoEngineEventController + '?' + persoParamters;
    personIndex++;
  }
}

$(document).ready(function(){
  if(confPersoEngineEnabled && persoEventType != "") {
    createPersoEvent(persoEventType,persoSeries,persoBodytype,persoModel,persoColor,persoRim);
  }
});

//Image Slide Show

function displaySlide(slideIndex){
  var slide;
  if(!highbandUser) {
    prepareBigImage(slideIndex);
  }
  for (var x = 0; x< slideCount; x++){
    if(oneTextOnly) {
      slide = 0;
    }
    else {
      slide = x;
    }
    if(document.getElementById("completeText" + x)!= null && !oneTextOnly){
      document.getElementById("completeText" + x).style.visibility = "hidden";
    }
    if(x == slideIndex){
      if(highbandUser && flashDetected) {
        if(typeof(document.getElementById("imageSlideShowSwf").scrollTo) == "function") {
          document.getElementById("imageSlideShowSwf").scrollTo(slideIndex);
        }
      }
      else {
        document.images["displayedImage"].src = imageDatabase.images[slideIndex];
      }
      document.getElementById("completeText" + slide).style.visibility = "visible";
    }
  }
  setImgBorderPermanent(slideIndex);
  if(confTrackingEnabled) {
    var trackingUrl = window.location.pathname.replace(/\./g, "_slide_" + slideIndex + ".");
    trackAbsolute(trackingUrl,'');
  }
}

function setImgBorder(divNr){
  posX = 317 + ((divNr * 33) + divNr)
  moveObject('imgBorder',posX,361);
  content='<a href="javascript:displaySlide('+divNr+');" onmouseout="deleteImgBorder();"><img src="' + highlightBoxSmall + '" border="0" width="37" height="29"></a><br>';
  writeIntoLayer('imgBorder' ,content);
  setVisibility("imgBorder",1);
}

function setImgBorderPermanent(divNr){
  if (slideCount > 1) {
    posX = 317 + ((divNr * 33) + divNr)
    moveObject('imgBorderPermanent',posX,361);
    setVisibility("imgBorderPermanent",1);
    setVisibility("imgBorder",0);
  }
}

function deleteImgBorder(){
  setVisibility("imgBorder",0);
}

function prepareBigImage(id) {
  setClassName("equipmentBody","loading");
  setVisibility("bigImageLoader",1);
  preLoadBigImage(id);
}

function preLoadBigImage(id) {
  myId = id;
  bigImage = new Image();
  bigImage.onabort = slideShowLoadUpdate;
  bigImage.onerror = slideShowLoadUpdate;
  bigImage.onload = slideShowLoadUpdate;
  bigImage.src = imageDatabase.images[id];
}

function slideShowLoadUpdate() {
  if (checkObject()) {
    setVisibility("bigImageLoader",0);
    setClassName("equipmentBody","");
    document.images["displayedImage"].src = bigImage.src;
  }
}

function checkObject() {
  actualImageSrc = imageDatabase.images[myId];
  if (bigImage.src == getFullPath(self.location.href, actualImageSrc)) {
    return true;
  }
  else {
    return false;
  }
}

function imageSlideShowGetFlashContent()  {
  return imageDatabase;
}

//URL Variables
var loadingBoxGif      = buildValidServerRelativeUrl( "/_common/rebrush/img/standard_elements/loading_box.gif" );
var lensGif            = buildValidServerRelativeUrl( "/_common/rebrush/img/standard_elements/lens.gif" );
var lensMouseOverGif   = buildValidServerRelativeUrl( "/_common/rebrush/img/standard_elements/lens-h.gif" );
var transGif           = buildValidServerRelativeUrl( "/_common/rebrush/img/palette/1x1_trans.gif" );
var p999999Gif         = buildValidServerRelativeUrl( "/_common/rebrush/img/palette/1x1_999999.gif" );
var P003399Gif         = buildValidServerRelativeUrl( "/_common/rebrush/img/palette/1x1_0044cc.gif" );
var p003399Gif         = P003399Gif;
var p8c8c8cGif         = buildValidServerRelativeUrl( "/_common/rebrush/img/palette/1x1_8c8c8c.gif" );
var pff0000Gif         = buildValidServerRelativeUrl( "/_common/rebrush/img/palette/1x1_ff0000.gif" );
var pafafafGif         = buildValidServerRelativeUrl( "/_common/rebrush/img/palette/1x1_afafaf.gif" );
var P0044CCGif         = buildValidServerRelativeUrl( "/_common/rebrush/img/palette/1x1_0044CC.gif" );
var closeGif           = buildValidServerRelativeUrl( "/_common/rebrush/img/standard_elements/close.gif" );
var close2Gif          = buildValidServerRelativeUrl( "/_common/rebrush/img/standard_elements/close-h.gif" );
var backgroundGif      = buildValidServerRelativeUrl( "/_common/html/img/modul_navigation/scroller_background.gif" );
var scrollerUpGif      = buildValidServerRelativeUrl( "/_common/html/img/modul_navigation/scroller_up.gif" );
var scrollerDownGif    = buildValidServerRelativeUrl( "/_common/html/img/modul_navigation/scroller_down.gif" );
var dropperGif         = buildValidServerRelativeUrl( "/_common/html/img/modul_navigation/dropper.gif" );
var dropperGifUp0      = buildValidServerRelativeUrl( "/_common/html/img/modul_navigation/dropper_up.gif" );
var dropperGifUp1      = buildValidServerRelativeUrl( "/_common/html/img/modul_navigation/dropper_up-h.gif" );
var dropperGifDown0    = buildValidServerRelativeUrl( "/_common/html/img/modul_navigation/dropper_down.gif" );
var dropperGifDown1    = buildValidServerRelativeUrl( "/_common/html/img/modul_navigation/dropper_down-h.gif" );
var pulldownGif        = buildValidServerRelativeUrl( "/_common/rebrush/img/forms/pulldown.gif" );
var pulldownBlackGif   = buildValidServerRelativeUrl( "/_common/rebrush/img/forms/pulldown_black.gif" );
var pulldownErrorGif   = buildValidServerRelativeUrl( "/_common/rebrush/img/forms/pulldown_error.gif" );
var highlightBoxSmall  = buildValidServerRelativeUrl("/_common/rebrush/img/standard_elements/highlight_box_37x29.gif" );
var downloadJSP        = buildValidServerRelativeUrl( "/_common/shared/jsp/download.jsp" );
var videoTeaserFlashWrapper = buildValidServerRelativeUrl( "/_common/flash/wrapper_modules.swf" );
var videoTeaserFlashmodule = buildValidServerRelativeUrl( "/_common/flash/modules/teaser/video_teaser.swf" );

/* modelfinder */
var modelfinder_layer_open = "";

function closeModelfinderLayer() {
  $("#modelfinder #navigation a").removeClass("standard_active");
  modelfinder_layer_open = "";
  $("#modelfinder_layer").css("visibility","hidden");
  $("#modelfinder_infolayer").css("visibility","hidden");
  $("#modelfinder_layer_big").css("visibility","hidden");
}

function modelfinderGetLayer(type,index) {
  $("#modelfinder_layer_big").css("visibility","hidden");
  $("#modelfinder_infolayer").css("visibility","hidden");

  if(modelfinder_layer_open == type && !index && index != 0) {
    closeModelfinderLayer();
  }
  else {
    modelfinder_layer_open = type;
    $("#modelfinder #navigation a").removeClass("standard_active");
    $("#modelfinder #navigation #" + type).addClass("standard_active");

    if(!index) {
      index = -1;
    }
    var type_pointer = 2;
    if(type == "series") {
      type_pointer = 0;
    }
    else if(type == "bodytype") {
      type_pointer = 1
    }
    var content = '<div class="column_extra"><ul class="linklist_bold">';
    for (i = 0; i < models[type + "_order"].length; i++) {
      if(models[type][i] != "" && models[type][models[type + '_order'][i]]){
        if(index == -1) {
          index = i;
        }
        var myclass = "";
        if (models[type + "_order"][i] == index) {
          myclass = "active";
        }
        content += '<li><a href="" class="' + myclass + '" onclick="modelfinderGetLayer(\'' + type +'\',' + models[type + "_order"][i] + '); return false;">' + models[type][models[type + '_order'][i]]  + '</a></li>';
      }
    }
    content += '</ul></div>';
    var totalcounter = 0;
    for(i = 0; i < models.length; i++) {
      if(models[i][type_pointer] == index) {
        totalcounter++;
      }
    }
    var counter = 0;
    for(i = 0; i < models.length; i++) {
      if(models[i][type_pointer] == index) {
        counter++;
        var myclass = "column";

        if (totalcounter >7 && totalcounter < 10) {
          if(counter == 4 || counter == 7) {
          content += '<div style="clear:left"></div>';
            myclass = "column_extra_margin";
          }
        }
        else if(divisible(counter,4) ) {
          content += '<div style="clear:left"></div>';
          myclass = "column_extra";
          if(totalcounter == 4 || totalcounter == 5 || totalcounter == 6) {
            myclass = "column_extra_margin";
          }
        }
        content += '' +
        '<div class="' + myclass + '">' +
        '<a href="' + models[i][19] + '" onmouseover="$(\'#mflink' + i + '\').addClass(\'blue\')" onmouseout="$(\'#mflink' + i + '\').removeClass(\'blue\')"><img src="' + models[i][8] + '" width="199" height="80" alt="" border="0"></a>' +
        '<div class="text">' +
        '<p class="mfhead"><a id="mflink' + i + '" href="' + models[i][19] + '">' + models[i][3] + '</a></p>' +
        '<p class="mfcopy">' + models[i][6] + '</p>' +
        '<ul class="linklist">';
        for(j = 10; j < 17; j+=3) {
          if(models[i][j] && models[i][j+2]) {
            content += '<li><a href="' + models[i][j] + '" target="' + models[i][j+1] + '" class="standard">' + models[i][j+2] + '</a></li>';
          }
        }
        content += '' +
        '</ul>' +
        '</div>' +
        '<a href="" onclick="modelfinder_showinfo(this, '+ i +');return false;" class="info_button"><img src="' + transGif + '" width="13" height="12" alt=""></a>' +
        '</div>';
      }
    }
    $("#modelfinder_layer .sizer").html(content);

    if(confTrackingEnabled) {
      trackingUrl = mfUrl + "/modelfinder_" + type + "_" + models[type][index].replace(/\s/g, "_").toLowerCase() + ".html";
      trackAbsolute(trackingUrl,document.title);
    }

    $("#modelfinder_layer").css("visibility","visible");
  }
  return false;
}


function modelfinder_showinfo(thisbutton,id) {
  var position = $(thisbutton).offset();
  $("#modelfinder_infolayer .mfhead").html(models[id][3]);
  $("#modelfinder_infolayer .mfcopy").html(models[id][5]);
  $("#modelfinder_infolayer").css("top",Math.round(position.top - 10));
  jQuery.each(jQuery.browser, function(i, val) {
    if(i == "msie" && Number(jQuery.browser.version.substr(0,1)) < "8") {
      $("#modelfinder_infolayer").css("top",Math.round(position.top - 12));
    }
  });
  $("#modelfinder_infolayer").css("left",position.left - 183);
  $("#modelfinder_infolayer").css("visibility","visible");
  shadowBoxSetDimensions("#modelfinder_infolayer");
}


function shadowBoxSetDimensions(filter) {
  $(filter).find(".content").css("height","auto");
  var contentWidth = $(filter).find(".content").width();
  var contentHeight = $(filter).find(".content").height();
  var paddingLeft = $(filter).find(".content").css("paddingLeft").replace("px","");
  var paddingTop = $(filter).find(".content").css("paddingTop").replace("px","");
  paddingLeft = paddingLeft * 2;
  paddingTop = paddingTop * 2;
  $(filter).find(".leftBorder").css("height",contentHeight + paddingTop);
  $(filter).find(".rightBorder").css("height",contentHeight + paddingTop);
  $(filter).find(".content").css("height",contentHeight);
  $(filter).find(".content").css("width",contentWidth);
  $(filter).find(".topBorder").css("width",contentWidth - 6 + paddingLeft);
  $(filter).find(".bottomBorder").css("width",contentWidth - 4 + paddingLeft);
  contentWidth = $(filter).width();
  contentHeight = $(filter).height();
  if( $(filter).hasClass("nobottom") ) {
    contentHeight += 10;
  }
  $(filter).find("img.background").attr("width", contentWidth - 6).attr("height", contentHeight - 10).show();
}


function modelfinderShowModel(id) {
  closeModelfinderLayer();
  if(confTrackingEnabled) {
    trackingUrl = mfUrl + "/modelfinder_infolayer_" + models[id][3].replace(/\s/g, '_').toLowerCase() + ".html";
    trackAbsolute(trackingUrl,document.title);
  }

  $("#modelfinder_layer_big .image").html('<img src="' + models[id][9] + '" width="622" height="376" alt="">');
  var content = '<h1>' + models[id][3] + '</h1>' +
  '<p>' + models[id][5] + '</p>' +
  '<p class="copyshort">' + models[id][6] + '</p>' +
  '<ul class="linklist">';
  for(j = 10; j < 17; j+=3) {
    if(models[id][j] && models[id][j+2]) {
      content += '<li><a href="' + models[id][j] + '" target="' + models[id][j+1] + '" class="standard">' + models[id][j+2] + '</a></li>';
     }
   }
   content += '' +
   '</ul>';
  $("#modelfinder_layer_big .text").html(content);
  $("#modelfinder_layer_big").css('visibility','visible');
}

function overvieInitTeaser(){
  standardTeaserArray = teaser.smallStandard.getSequence();
  teaserCounter = 0;
  for (var i=0; i < standardTeaserArray.length; i++){
    for (var j=0; j < teaser.smallStandard.length; j++){
      if(teaser.smallStandard[j] == standardTeaserArray[i]){
        setVisibility("smallStandardTeaser" + j, null, 'block');
        teaserCounter++;
        break;
      }
    }
    if(teaserCounter==3){
      break;
    }
  }
}

function effdynModelfinderInit() {
    var blocks = new Array();
    var rows = new Array();
    var lastTop = -1;
    $("#effdynModelfinder .block").each(function(i) {
      var newWidth = $(this).find(".model").length * 119;
      jQuery.each(jQuery.browser, function(i, val) {
        if(i == "msie" && jQuery.browser.version.substr(0,1) == "6") {
          newWidth+=3;
        }
      });
      $(this).css("width", newWidth); //1px mehr wegen ie6
      if( $(this).offset().top > lastTop) {
        lastTop =  $(this).offset().top;
        rows.push($(this).height());
      }
      else {
        if( $(this).height() > rows[rows.length-1] ) {
          rows[rows.length-1] = $(this).height();
        }
      }
      blocks.push(rows.length-1);
    });
    $("#effdynModelfinder .block").each(function(i) {
      $(this).css("height",rows[blocks[i]]);
    });
  }

/* teleservice */
  function toggleFaq(){
    if(layerstatus == 0){
      layerstatus = 1;
      $("#faqContent").show();
    }else{
      layerstatus = 0;
      $("#faqContent").hide();
    }
  }
  function moveTeaser(){
    setVisibility("contentText", 0);
    moveObject("teaserStory1", 227, 476);
    moveObject("teaserStory2", 393, 476);
    moveObject("teaserStory3", 559, 476);
    resizeLayer("teaserStory1", 150);
    resizeLayer("teaserStory2", 150);
    resizeLayer("teaserStory3", 150);
    setClassName("teaserStoryHead1" ,"borderless teaserHeadSmall" );
    setClassName("teaserStoryHead2" ,"borderless teaserHeadSmall" );
    setClassName("teaserStoryHead3" ,"borderless teaserHeadSmall" );
    setVisibility("teaserStoryImage1", 1);
    setVisibility("teaserStoryImage2", 1);
    setVisibility("teaserStoryImage3", 1);
  }
  function highlightLinks(storyNumber, linkNumber){
    if(activeLinkId != ""){
      setClassName(activeLinkId ,"arrow" );
    }
    activeLinkId = "story" + storyNumber + "Link" + linkNumber;
    setClassName(activeLinkId ,"arrow linkHighlight" );
  }
  function highlightFactsLinks(storyNumber, linkNumber){
    if(activeFacsLinkId != ""){
      setClassName(activeFacsLinkId, "arrow");
    }
    activeFacsLinkId = "facts" + storyNumber + "Link" + linkNumber;
    setClassName(activeFacsLinkId ,"arrow linkHighlight" );
  }
  function showStory(storyNumber){
    moveTeaser();
    highlightLinks(storyNumber, 1);
    if(activeFactsDetails != ""){
      $("#" + activeFactsDetails).hide();
      $("#" + activeFactsLinks).hide();
      activeFactsDetails = "";
      activeFactsLinks = "";
    }
    window.setTimeout('buildSWFTag("prm_story=' + storyNumber + '")', timeoutValue);
  }
  function showFacts(factsNumber){
    moveTeaser()
    highlightLinks(factsNumber,2);
    highlightFactsLinks(factsNumber, 1);
    window.setTimeout('buildSWFTag("prm_story=' + factsNumber + '&prm_facts=1")', timeoutValue);
    if(activeFactsDetails != ""){
      $("#" + activeFactsDetails).hide();
      $("#" + activeFactsLinks).hide();
    }
    activeFactsDetails = "facts" + factsNumber + "Content1";
    activeFactsLinks = "factsLinks" + factsNumber;
    window.setTimeout('$("#' + activeFactsDetails + '").show();', timeoutValue);
    window.setTimeout('$("#' + activeFactsLinks + '").show();', timeoutValue);
    //window.setTimeout('setVisibility('  + activeFactsDetails + ', 1, \'block\');', timeoutValue);
    //window.setTimeout('setVisibility('  + activeFactsLinks + ', 1, \'block\');', timeoutValue);
  }
  function showFactsDetails(factsNumber, chapterNumber){
    highlightFactsLinks(factsNumber, chapterNumber);
    if(activeFactsDetails != ""){
      $("#" + activeFactsDetails).hide();
      $("#" + activeFactsLinks).hide();
    }
    activeFactsDetails = "facts" + factsNumber + "Content" + chapterNumber;
    activeFactsLinks = "factsLinks" + factsNumber;
    $("#" + activeFactsDetails).show();
    $("#" + activeFactsLinks).show();
    callExternalInterface(chapterNumber)
  }
  function callExternalInterface(factsNumber) {
    thisMovie("mainFlash").startFactsSlideshow(factsNumber);
  }
  function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
      return window[movieName]
    }
    else {
      return document[movieName]
    }
  }

/* technology guide*/
TLInfoState = 0;

String.prototype.toRegExpString = function () {
  return this.replace(/([\^\$\.\*\+\?\=\!\:\|\\\/\(\)\[\]\{\}])/g, "\\$1");
};

function technologyGuideToggleRelatedModels(order) {
  if (TLInfoState == 0) {
    TLInfoState = 1;
    setVisibility('relatedModels',1);
    document.getElementById("linkRelatedModels").style.color="#0044cc";
  }
  else if(TLInfoState == 1 || order == 1){
    TLInfoState = 0;
    setVisibility('relatedModels',0);
    document.getElementById("linkRelatedModels").style.color="#4c4c4c";
  }
}

function technologyGuideGetRelatedModelsContent() {
  var contentPart = new Array();

  for(i=0;i<=TLmodelMatching.length;i++) {
    if(relatedModelsArray[TLmodelMatching[i]]) {
      contentPart.push('<li><a href="../' + buildValidServerRelativeUrl(TLmodels[TLmodelMatching[i]][2]) + '" class="arrowWhite"><img src="' + transGif + '" alt="" class="arrowWhite">' + TLmodels[TLmodelMatching[i]][1] + '</a></li>');
    }
  }
  var rmHeadline = '<h2>' + TLrelatedModelsHeadline + '</h2>';
  var content = TLrelatedModelsCopy + '<div style="height:12px;overflow:hidden;"></div>';
  content += '<table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td width="180" valign="top"><ul class="linkList">';
  var tableBreak = Math.ceil(contentPart.length/2);
  if(contentPart.length == 1) {
    tableBreak = -1;
  }

  for(i=0;i<contentPart.length;i++) {
    if(i == tableBreak) {
      content += '</ul></td><td width="12">&nbsp;</td><td width="180" valign="top"><ul class="linkList">';
    }
    content += contentPart[i];
  }
  content += '</ul></td></table>';
  writeIntoLayer("relatedModelsContent",content);
  writeIntoLayer("relatedModelsHeadline",rmHeadline);
}


function technologyGuideReplace(searchtext, keyword, stringBeforeKeyword, stringAfterKeyword, doesIgnoreCase) {
  var txt = String(searchtext);
  var key = String(keyword);
  var txtBefore = String(stringBeforeKeyword);
  var txtAfter = String(stringAfterKeyword);
  var iFlag = ((Boolean(doesIgnoreCase)) ? ("i") : (""));
  var doSurgery = function (str, $1, $2, $3) {return (txtBefore + $1 + $2 + $3 + txtAfter);};
  var regXSearch = new RegExp(("(\\b|\\s)\(" + key.toRegExpString().replace((/\s+/g), "\\s+") + "[a-zA-Z]{0,4})(\\b|\\s|\\.|\\:|,|;)"), iFlag);
  return txt.replace(regXSearch, doSurgery);
}


function technologyGuideToggleLayer(obj,img,infoParam, page) {
  if (currentObj != "") {
    setVisibility(currentObj,null,"none");
    document.getElementById("showroomIFrame").src=buildValidServerRelativeUrl("/_common/shared/blank_frame.html");
      if (TLInfoState == 1) {
        switchImage(img,0);
      }
      else {
        switchImage(img,1);
      }
  }
  if (currentObj == "" || currentObj != obj) {
  if(page!=""){
    document.getElementById("showroomIFrame").src=page;
  }
    setVisibility(obj,null,"block");
    if (infoParam == 1) {
      TLInfoState = 1;
      switchImage(img,1);
    } else {
      TLInfoState = 0;
      switchImage(img,0);
    }
    currentObj = obj;
    currentImg = img;
    } else {
      currentObj = "";
      currentImg = "";
  }
}


function technologyGuidePrepareCopytext() {
  var myCopytext = document.getElementById("copyTextP").innerHTML;
  for(i=0;i<TLdatabase.length;i++) {
    if(TLdatabase[i][6] == "") {
      var source = self.location.pathname;
      var address = buildValidServerRelativeUrl(TLbaseUrl+'articles/_narrowband/iframes/'+ getFileName(TLdatabase[i][4]) + '.htm?source='+source+'&article='+getFileName(TLdatabase[i][4]));
      var textBefore = '<a href="javascript:technologyGuideToggleLayer(\'showroomLayer\',\'closeIm3\',\'0\', \''+address+'\');" onMouseOver=\"switchImage(\'closeIm3\',1);\" onMouseOut=\"switchImage(\'closeIm3\',0);\"  class=\"TLcontextlink\">';
      var textBeyond = '</a>';
      myCopytext = technologyGuideReplace(myCopytext, TLdatabase[i][1], textBefore, textBeyond);
    }
  }
  document.getElementById("copyTextP").innerHTML = myCopytext;
}


function technologyGuideCheckDatabase(startCounter) {
 if((startCounter*100)< 5000){
  try {
    if (!TLjsLoaded) {
      throw "unloaded";
    }else if (TLjsLoaded==true){
      throw "loaded";
    }
  } catch (e) {
    if (e == "loaded") {
      technologyGuidePrepareCopytext();
     return;
    }
  } finally {
    startCounter++;

  }
  setTimeout("technologyGuideCheckDatabase(" + startCounter + ")", 100);
 }
}

function addJavascriptLibrary(scriptUrl,scriptId) {
  var head = document.getElementsByTagName('head').item(0);
  var scriptTag = document.getElementById(scriptId);
  if ( scriptTag ) {head.removeChild(scriptTag);}
  script = document.createElement('script');
  script.src = scriptUrl;
  script.type = 'text/javascript';
  script.id = scriptId;
  head.appendChild(script);
  technologyGuideCheckDatabase(0);
}

function technologyGuideGetItReplaced(searchtext, keyword, stringBeforeKeyword, stringAfterKeyword, doesIgnoreCase) {
  var txt = String(searchtext);
  var key = String(keyword);
  var txtBefore = String(stringBeforeKeyword);
  var txtAfter = String(stringAfterKeyword);
  var iFlag = ((Boolean(doesIgnoreCase)) ? ("i") : (""));
  var doSurgery = function (str, $1) {return (txtBefore + $1 + txtAfter);};
  var regXSearch = new RegExp(("\\b\(" + key.toRegExpString().replace((/\s+/g), "\\s+") + "[a-zA-Z]{0,4})\\b"), iFlag);
  return txt.replace(regXSearch, doSurgery);
}

// image basic

imageBasicInfoState = 0;
imageBasicLegalDisclaimerState = 0;

function imageBasicToggleInfo(order) {
  if (imageBasicInfoState == 0) {
    if(imageBasicLegalDisclaimerState == 1){
      imageBasicLegalDisclaimerState = 0;
      setVisibility('legalDisclaimer',0);
    }
    imageBasicInfoState = 1;
    setVisibility('info',1);
    switchImage('infoImg',1);
  }
  else if(imageBasicInfoState == 1 || order == 1){
    imageBasicInfoState = 0;
    setVisibility('info',0);
    switchImage('infoImg',0);
  }
}

function imageBasicToggleLegalDisclaimer(order) {
  if (imageBasicLegalDisclaimerState == 0) {
    if(imageBasicInfoState == 1){
      imageBasicInfoState = 0;
      setVisibility('info',0);
      switchImage('infoImg',0);
    }
    imageBasicLegalDisclaimerState = 1;
    setVisibility('legalDisclaimer',1);
  }
  else if(imageBasicLegalDisclaimerState == 1 || order == 1){
    imageBasicLegalDisclaimerState = 0;
    setVisibility('legalDisclaimer',0);
  }
}

function selectBoxNotify(formField,formFieldValue) {
  if(formFieldValue.indexOf('http://') != -1 || formFieldValue.indexOf('https://') != -1) {
    window.open(formFieldValue,"_blank");
    trackExternalLink(formFieldValue);
  }
  else if(formFieldValue != "") {
    location.href = getFullPath(window.location.href,formFieldValue);
  }
}

function writeSelectBox( formField, keyValueArray, zIndex, elementWidth, visibleEntries, selectedValue, notify, error, readonly, direction, elementClass ) {
  var formValue = "";
  entryFound = false;
  var pulldownImage  = pulldownGif;
  if( error == true ){
    pulldownImage = pulldownErrorGif;
  }
  for( i=0; i < keyValueArray.length; i++ ){
    if( keyValueArray[i+1] == selectedValue ){
      selectText = keyValueArray[i];
      formValue  = keyValueArray[i+1];
      entryFound = true;
      break;
    }
    i++;
  }
  if( !entryFound ){
    selectText = keyValueArray[0];
    formValue  = keyValueArray[1];
  }
  selectBoxes.push( formField );
  directOrder[formField] = false;
  selectBox = '';
  deep = (visibleEntries * 16) + 14;
  elementClass = ( elementClass != undefined )? elementClass:"";
  if( readonly == true ){
    selectBox += '<input type="text" class="defaultReadonly '+elementClass+'" readonly="readonly" value="' + selectText + '" '+'/'+'>';
    selectBox += '<input type="hidden" name="' + formField + '" value="' + formValue + '" '+'/'+'>';
  }else{
    selectBox += '<div id="'+ formField +'" class="selectBoxContainer '+elementClass+'" style="z-index:' + zIndex +'; width:' + elementWidth + 'px">';
    selectBox += '<div class="selectBoxTitle" onClick="setVisibilityOnly(\'selectBoxContent' + formField + '\');" onMouseover="directOrder[\'' + formField + '\']=true;" onMouseout="directOrder[\'' + formField + '\']=false;">';
    selectBox += '<div id="selectedValue' + formField + '" class="selectBoxCaption">' + selectText + '<'+'/div>';
    selectBox += '<div class="selectBoxButton"><img src="' + pulldownImage + '" width="18" height="16" alt="' + selectText + '" '+'/'+'><'+'/div>';
    selectBox += '<'+'/div>';
    selectBox += '<div id="selectBoxContent' + formField + '" class="selectBoxDropdown" style="height:'+deep+'px">';
    selectBox += '<div class="selectBoxDropdownList" style="height:'+deep+'px">';
    for( i=0; i < keyValueArray.length; i++ ){
      keyValueArray[i+1] = keyValueArray[i+1].replace(/'/g,"\\\'");
      var tempValue = keyValueArray[i].replace(/'/g,"\\\'");
      selectBox += '<a href="javascript://" onclick="setOption(\'' + tempValue + '\',\'' + keyValueArray[i+1] + '\',\'' + formField + '\',' + notify + ',' + zIndex +');return false;" class="selectboxEntry">' + keyValueArray[i] + '<'+'/a>';
      i++;
    }
    selectBox += '<'+'/div>';
    selectBox += '<'+'/div>';
    selectBox += '<input type="hidden" name="' + formField + '" value="' + formValue + '" '+'/'+'>';
    selectBox += '<'+'/div>';
  }
  return selectBox;
}

function setVisibilityOnly(elementId, visibilityValue, displayValue, initialSet){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    if (typeof visibilityValue == 'undefined') {
      currentState = getDivInformation(elementId, 'visibility');
      if (currentState == '') {
        if (initialSet) {
          currentState = 'visible';
        } else {
          currentState = 'hidden';
        }
      }
      if (currentState == 'hidden') {
        elementId.style.visibility = 'visible';
      } else if (currentState == 'visible') {
        elementId.style.visibility = 'hidden';
      }
    } else if (visibilityValue == 1) {
      elementId.style.visibility = 'visible';
    } else if (visibilityValue == 0) {
      elementId.style.visibility = 'hidden';
    }
  }
}


// overview 1st level template
var currentLargeTeaserName    = "";
var currentLargeTeaserName    = "";
var currentLargeTeaserImage   = "";
var nextLargeTeaserImage      = "";
var largeBasicTeasersPreload  = new Image();
var largeBasicTeasers         = new Array();
var largeTeaserArray          = new Array();
var largeFlashTeasers         = new Array();

function overviewInitTeaser(){
  var standardTeaserListOrignal = new Array();
  $(".smallStandard").each(function(i,e){
    standardTeaserListOrignal[standardTeaserListOrignal.length] = $(e).attr("id");
  })
  standardTeaserArray = randomizeTeaser(standardTeaserListOrignal, false);
  teaserCounter = 0;
  var teaserAmount = standardTeaserArray.length;
  if(teaserAmount > 3) {
    teaserAmount = 3;
  }
  for (var i=0; i < teaserAmount; i++){
    $("#" + standardTeaserArray[i]).show();
  }
}

function getContentOverview1st()  {
  return largeFlashTeasers[currentlargeFlashTeasers];
}


//wallpaper
  wallpaperId = "";
  function wallpaperRestoreThumbs() {
    for (i=0;i<thumbs.length;i++) {
      imgWallpaper = "wallpaper" + i;
      var divLense     = "lense" + i;
      document.images[imgWallpaper].src = thumbs[i];
      setVisibility(divLense,1);
    }
  }
  function wallpaperRestoreLenses() {
    for (i=0;i<thumbs.length;i++) {
      var divLense     = "lense" + i;
      setVisibility(divLense,1);
    }
  }
  function wallpaperOpenDialog(thisDialog) {
    setVisibility("dialog" + thisDialog,1);
    for(i=0;i<thumbs.length;i++) {
      if (i != thisDialog) {
        var layerName = "dialog" + i;
        setVisibility(layerName,0);
      }
    }
  }
  function wallpaperPreLoadBigImage(id) {
    wallpaperId = id;
    bigImage          = new Image();
    bigImage.onabort  = wallpaperLoadUpdate;
    bigImage.onerror  = wallpaperLoadUpdate;
    bigImage.onload   = wallpaperLoadUpdate;
    bigImage.src      = big_standard_url[id];
  }
  function wallpaperLoadUpdate() {
    if (wallpaperCheckObject()) {
      setVisibility("bigImageLoader",0);
      setClassName("wallpaperBody","");
      rewriteBigImageNavi(wallpaperId);
      document.images["bigImageDummy"].src = bigImage.src;
      setVisibility("bigImageLayer",1);
      setVisibility("bigImageNavi",1);
      foldModuleNavi(true);
      wallpaperRestoreLenses();
      wallpaperRestoreThumbs();
    }
  }
  function wallpaperCheckObject() {
    actualImageSrc = big_standard_url[wallpaperId].replace(/\.\.\//g,"");
    if(bigImage.src.indexOf(actualImageSrc) != -1) {
      return true;
    }
    else {
      return false;
    }
  }
  function wallpaperNextImage(currentId, direction) {
    setVisibility("bigImageLoader",1);
    setClassName("wallpaperBody","loading");
    if(direction == "next") {
      if(currentId >= thumbs.length-1) {thisId = 0;} else {thisId = currentId + 1;}
    }
    else {
      if(currentId == 0) {thisId = thumbs.length-1;} else {thisId = currentId - 1;}
    }
    wallpaperPreLoadBigImage(thisId);
  }
  function wallpaperCloseMediaView() {
    wallpaperRestoreLenses();
    wallpaperRestoreThumbs();
    setVisibility('bigImageLayer',0);
    setVisibility('bigImageNavi',0);
    foldModuleNavi(false);
  }
  function abortPreload() {
    setVisibility("bigImageLoader",0);
    setClassName("wallpaperBody","");
  }
  function closeNaviEvent() {
    setClassName("bigImageNavi","bigImageNaviTop");
  }
  function openNaviEvent() {
    setClassName("bigImageNavi","bigImageNaviBottom");
  }
  function setBigImageLayer() {
    getWindowInformation('winHeight');
    topSize = (getWindowInformation('winHeight') - 14 - 29) - 768;
    if(topSize < 0) {
      moveObject(bigImageLayer,0,topSize);
    }
  }

function teaserLottery() {
  if (teaser) {
    Math.randomize = function() {var minValue=0,maxValue=0;if(arguments.length==1){maxValue=((isNaN(Number(arguments[0])))?(0):(parseInt(arguments[0])));}else if(arguments.length==2){minValue=((isNaN(Number(arguments[0])))?(0):(parseInt(arguments[0])));maxValue=((isNaN(Number(arguments[1])))?(0):(parseInt(arguments[1])));}if(maxValue<minValue){var tmpValue=minValue;minValue=maxValue;maxValue=tmpValue;}Math.randomize.startValue=(((Math.randomize.startValue*Math.randomize.a)+Math.randomize.b)%Math.randomize.c);return((minValue==maxValue)?(Math.randomize.startValue/Math.randomize.c):(minValue+Math.floor((maxValue-minValue+1)*Math.randomize.startValue/Math.randomize.c)));};Math.randomize.a=4096;Math.randomize.b=150889;Math.randomize.c=714025;Math.randomize.startValue=(((new Date()).getTime())%Math.randomize.c);
    Array.prototype.remove = function(obj) {var arr=this,i=0;while(i<arr.length){if(arr[i]===obj){arr=arr.slice(0,i).concat(arr.slice(i+1,arr.length));--i;}++i;}for(i=0;i<arr.length;++i){this[i]=arr[i];}this.length=arr.length;};
    if (teaser.large) {
      teaser.large.weighting = 3;
      teaser.large.firstEntryIsFix = true;
      teaser.large.getSequence = function() {
        var arr = [];
        var teaserArr = teaser.large;
        var amplifier = teaserArr.weighting;
        var fixDifference = ((teaserArr.firstEntryIsFix) ? (0) : (1));
        var arrLength = (((teaserArr.length-1+fixDifference) <= (4+fixDifference)) ? (teaserArr.length-1+fixDifference) : (4+fixDifference));
        var fixEntries = ((teaserArr.firstEntryIsFix) ? ([teaserArr[0]]) : (null));
        var lotteryPot = [], i;
        for (i=(1-fixDifference); i<teaserArr.length; ++i) {
          lotteryPot[lotteryPot.length] = i;
        }
        while (arr.length < arrLength) {
          i = lotteryPot[Math.floor(Math.pow(Math.randomize(),amplifier)*lotteryPot.length)];
          lotteryPot.remove(i);
          arr[arr.length] = teaserArr[i];
        }
        if (fixEntries) {
          arr = fixEntries.concat(arr);
        }
        return arr;
      };
    }
    if (teaser.main) {
      teaser.main.weighting = 3;
      teaser.main.firstEntryIsFix = true;

      teaser.main.getSequence = function() {
        var arr = [];
        var teaserArr = teaser.main;
        var amplifier = teaserArr.weighting;
        var fixDifference = ((teaserArr.firstEntryIsFix) ? (0) : (1));
        var arrLength = (((teaserArr.length-1+fixDifference) <= (4+fixDifference)) ? (teaserArr.length-1+fixDifference) : (4+fixDifference));
        var fixEntries = ((teaserArr.firstEntryIsFix) ? ([teaserArr[0]]) : (null));
        var lotteryPot = [], i;
        for (i=(1-fixDifference); i<teaserArr.length; ++i) {
          lotteryPot[lotteryPot.length] = i;
        }
        while (arr.length < arrLength) {
          i = lotteryPot[Math.floor(Math.pow(Math.randomize(),amplifier)*lotteryPot.length)];
          lotteryPot.remove(i);
          arr[arr.length] = teaserArr[i];
        }
        if (fixEntries) {
          arr = fixEntries.concat(arr);
        }
        return arr;
      };
    }
    if (teaser.smallStandard) {

      teaser.smallStandard.weighting = 3;

      teaser.smallStandard.getSequence = function() {
        var arr = [];
        var teaserArr = teaser.smallStandard;
        var amplifier = teaserArr.weighting;
        var arrLength = ((teaserArr.length <= 6) ? (teaserArr.length) : (6));
        var lotteryPot = [], i;
        for (i=0; i<teaserArr.length; ++i) {
          lotteryPot[lotteryPot.length] = i;
        }
        while (arr.length < arrLength) {
          i = lotteryPot[Math.floor(Math.pow(Math.randomize(),amplifier)*lotteryPot.length)];
          lotteryPot.remove(i);
          arr[arr.length] = teaserArr[i];
        }
        return arr;
      };
    }
    if (teaser.smallText) {
      teaser.smallText.weighting = 3;
      teaser.smallText.getSequence = function() {
        var arr = [];
        var teaserArr = teaser.smallText;
        var amplifier = teaserArr.weighting;
        var arrLength = ((teaserArr.length <= 2) ? (0) : (((teaserArr.length-3) <= 3) ? (teaserArr.length-3) : (3)));
        var fixEntries = [], i;
        if (teaserArr.length <= 2) {
          for (i=0; i<teaserArr.length; ++i) {
            fixEntries[i] = teaserArr[i];
          }
        } else {
          fixEntries = [teaserArr[0],teaserArr[1],teaserArr[2]];
          var lotteryPot = [];
          for (i=3; i<teaserArr.length; ++i) {
            lotteryPot[lotteryPot.length] = i;
          }
        }
        while (arr.length < arrLength) {
          i = lotteryPot[Math.floor(Math.pow(Math.randomize(),amplifier)*lotteryPot.length)];
          lotteryPot.remove(i);
          arr[arr.length] = teaserArr[i];
        }
        arr = fixEntries.concat(arr);
        return arr;
      };
    }
  }
}

//homepage
var largeTeaserOIDListOrignal = new Array();
var largeTeaserOIDListRandom = new Array();
var currentLargeTeaser = 0;
var maxLargeTeaser = 4;
var largeTeaserRule = 3;
var largeTeaserAutoRotateActive = true;
var largeTeaserDefaultTime = 16;
var largeTeaserInterval;
var currentlargeFlashTeasers = 0;

var wideTeaserRule = 1;
var wideTeaserOIDListOrignal = new Array();
var wideTeaserOIDListRandom = new Array();
var currentWideTeaser = 0;
var maxWideTeaser = 4;

var standardTeaserRule = 1;
var standardTeaserOIDListOrignal = new Array();
var standardTeaserOIDListRandom = new Array();

function initHome() {
  initTeaserList1();
  initTeaserList2();
  initTeaserList3();
  //initStandardTeaser(); //edex
  initStandardSalesTeaser();
  checkFacebookAvailability();
}

function initOverview() {
  initTeaserList1();
  initTeaserList2();
  initStandardTeaser();
  initStandardSalesTeaser();
}

function initLandingpage() {
  initStandardTeaser();
  initStandardSalesTeaser();
  foldMainNavi(true);
}

/*
function initStandardTeaser() {
  $(".standardTeaser").each(function(i,e){

    if($(this).find(".text").size() > 0) {
      $(this).find(".content .media").mouseover(function() {
        $(this).hide();
      });
      $(this).find(".content .text").mouseleave(function() {
        $(this).next(".media").show();
      });
    }
  });
} */

function initStandardSalesTeaser() {
  $(".standardSalesTeaser .eventArea").each(function() {
    var teaserImage = $(this).parents(".standardSalesTeaser").find("img");
    var text = $(this).parents(".standardSalesTeaser").find(".text");
    var twoButtons = false;
    if($(this).parents(".standardSalesTeaser").find(".button").size() == 2) {
      twoButtons = true;
    }
    var twoImages = false;
    if(teaserImage.attr("preload")) {
      twoImages = true;
    }

    if(twoImages || twoButtons) {
      if(twoImages) {
        $('<img />').attr("src", getWcmsPrefix() + teaserImage.attr("preload"));
        var original = teaserImage.attr("src");

        if( getWcmsPrefix() == "/bmw_edit") {
          if(original.indexOf("/bmw_edit/") == -1) {
            original = "/bmw_edit" + original;
          }
        }
      }
      $(this).hover(
        function () {
          if(twoImages) {
            teaserImage.attr("src",teaserImage.attr("preload"));
          }
          if(twoButtons) {
            text.show();
          }
        },
        function() {
          if(twoImages) {
            teaserImage.attr("src",original);
          }
          if(twoButtons) {
            text.hide();
          }
        }
      );
    }
  });
}

function initTeaserList1(alternativeHeight){
  if($(window).width() > 1024){
    $(".teaserLargeContainer, .teaserLargeStandardContainer").width("1024px");
  }
  $(window).resize(function() {
    if($(window).width() > 1024){
      $(".teaserLargeContainer, .teaserLargeStandardContainer").width("1024px");
    }else{
      $(".teaserLargeContainer, .teaserLargeStandardContainer").width("1004px");
    }
  });
  $(".teaserLarge").each(function(i,e){
    largeTeaserOIDListOrignal[largeTeaserOIDListOrignal.length] = $(e).attr("id");
  })

  switch (largeTeaserRule) {
    case 1:
      largeTeaserOIDListRandom = randomizeTeaser(largeTeaserOIDListOrignal, false);
      break;
    case 2:
      largeTeaserOIDListRandom = randomizeSimpleTeaser(largeTeaserOIDListOrignal, false);
      break;
    case 3:
      largeTeaserOIDListRandom = sameOrderTeaser(largeTeaserOIDListOrignal);
      break;
    case 4:
      largeTeaserOIDListRandom = randomizeSimpleTeaser(largeTeaserOIDListOrignal, true);
      break;
    case 5:
      largeTeaserOIDListRandom = randomizeTeaser(largeTeaserOIDListOrignal, true);
      break;
    default:
      largeTeaserOIDListRandom = randomizeTeaser(largeTeaserOIDListOrignal, false);
      break;
  }

  maxLargeTeaser = largeTeaserOIDListRandom.length-1;
  if(maxLargeTeaser != -1){
    $(".teaserLargeContainer .skip, .teaserLargeStandardContainer .skip").html((currentLargeTeaser + 1) + " / " + (maxLargeTeaser+1));
    if(maxLargeTeaser >= 1){
      $(".teaserLargeContainer .skip, .teaserLargeStandardContainer .skip").show();
    }

    $.each(largeTeaserOIDListRandom, function(i,e) {
      $('<img />').attr('src', largeBasicTeasers[ $.inArray(e, largeTeaserOIDListOrignal) ]);
    });

    useLageFlashTeaser = false;
    currentlargeFlashTeasers = $.inArray(largeTeaserOIDListRandom[currentLargeTeaser], largeTeaserOIDListOrignal);
    if(highbandUser && (largeFlashTeasers[currentlargeFlashTeasers].swfurl != "none")){
      var largeTeaserSwfUrl =  getWcmsPrefix() + "/_common/rebrush/swf/wrapper_modules_autorotate.swf";
      if(largeFlashTeasers[currentlargeFlashTeasers].swfurl == ""){
        largeTeaserSwfUrl =  getWcmsPrefix() + "/_common/rebrush/swf/large_teaser_as3.swf";
      }
      var largeTeaserSwfHeight =  "280";
      if(alternativeHeight != undefined){
        largeTeaserSwfHeight =  alternativeHeight;
      }
      var teaserSWFObject = new SWFObject(largeTeaserSwfUrl, "largeTeaserFlashObject", "1024", largeTeaserSwfHeight, "8", "#FFFFFF");
      teaserSWFObject.addParam("allowScriptAccess", "sameDomain");
      teaserSWFObject.addParam("wmode", "transparent");
      teaserSWFObject.addParam("quality", "BEST");
      teaserSWFObject.addVariable("defaultTimeToRun", largeTeaserDefaultTime);
      teaserSWFObject.addVariable("nextTeaserFunction", "startLargeTeaserTimer()");
      if(teaserSWFObject.write("largeTeaserFlash")){
        $("#largeTeaserFlash").show();
        useLageFlashTeaser = true;
      }
    }
    if(!useLageFlashTeaser){
      $("#" + largeTeaserOIDListRandom[currentLargeTeaser]).show();
      $("#largeTeaserBasic img").attr("src", largeBasicTeasers[$.inArray(largeTeaserOIDListRandom[currentLargeTeaser], largeTeaserOIDListOrignal)]);
      $("#largeTeaserBasic").show();
    }
    $(".teaserLargeContainer .skip, .teaserLargeStandardContainer .skip").html((currentLargeTeaser + 1) + " / " + (maxLargeTeaser+1));
    $("#largeTeaserOverlay").fadeOut(500);

    $(".teaserLargeContainer .skip, .teaserLargeStandardContainer .skip").bind("click", showNextLargeTeaser);

    if(largeTeaserAutoRotateActive && maxLargeTeaser  > 0){
      startLargeTeaserTimer();
    }
  }
}

function trackingLargeTeaser(teaserId, linkId, linkUrl, linkTarget){
  trackingCookie('ta_large;tc_flash;tb_' + $("#id" + teaserId + " a").size() + ';to_' + teaserId, $("#id" + teaserId + " " + linkId)[0]);
  if(linkTarget == "_blank"){
    window.open(linkUrl, "_blank");
  }else if(linkTarget == "popup"){
    window.open(linkUrl, "_blank");
  }else{
    top.location.href = linkUrl;
  }
}

function initTeaserList2(){
  $(".standardTeaserContainer div[id^='id']").each(function(i,e){
    standardTeaserOIDListOrignal[standardTeaserOIDListOrignal.length] = $(e).attr("id");
  })
  switch (standardTeaserRule) {
    case 1:
      standardTeaserOIDListRandom = randomizeTeaser(standardTeaserOIDListOrignal, false);
      break;
    case 2:
      standardTeaserOIDListRandom = randomizeSimpleTeaser(standardTeaserOIDListOrignal, false);
      break;
    case 3:
      standardTeaserOIDListRandom = standardTeaserOIDListOrignal;
      break;
    default:
      standardTeaserOIDListRandom = randomizeTeaser(standardTeaserOIDListOrignal, false);
      break;
  }
  $("#" + standardTeaserOIDListRandom[0]).css("visibility" , "visible");
}

function initTeaserList3(){
  $(".doubleTeaserContainer .doubleTeaser").each(function(i,e){
    wideTeaserOIDListOrignal[wideTeaserOIDListOrignal.length] = $(e).attr("id");
  })
  maxWideTeaser = wideTeaserOIDListOrignal.length-1;
  if(maxWideTeaser < -1){ //edex !=
    $(".doubleTeaserContainer .skip").html((currentWideTeaser + 1) + " / " + (maxWideTeaser+1));
    if(maxWideTeaser > 0){
      $(".doubleTeaserContainer .skip").show();
    }
    switch (wideTeaserRule) {
      case 1:
        wideTeaserOIDListRandom = randomizeTeaser(wideTeaserOIDListOrignal, false);
        break;
      case 2:
        wideTeaserOIDListRandom = randomizeSimpleTeaser(wideTeaserOIDListOrignal, false);
        break;
      case 3:
        wideTeaserOIDListRandom = wideTeaserOIDListOrignal;
        break;
      default:
        wideTeaserOIDListRandom = randomizeTeaser(wideTeaserOIDListOrignal, false);
        break;
    }
    $("#" + wideTeaserOIDListRandom[currentWideTeaser]).css("visibility" , "visible");

    $(".doubleTeaserContainer .skip").click(function(){
      $("#" + wideTeaserOIDListRandom[currentWideTeaser]).css("visibility" , "hidden");
      currentWideTeaser++;
      if(currentWideTeaser > maxWideTeaser){
        currentWideTeaser = 0;
      }
      $(".doubleTeaserContainer .skip").html((currentWideTeaser + 1) + " / " + (maxWideTeaser+1));
      $("#" + wideTeaserOIDListRandom[currentWideTeaser]).css("visibility" , "visible");
    });
  }
}
function getContent()  {
  return largeFlashTeasers[currentlargeFlashTeasers];
}

function startLargeTeaserTimer()  {
  if(largeTeaserAutoRotateActive){
    var currentRunTime = largeTeaserDefaultTime;
    largeTeaserInterval = window.setTimeout("showNextLargeTeaser()", (1000 * currentRunTime));
  }
}

function showNextLargeTeaser(){
  $(".teaserLargeContainer .skip, .teaserLargeStandardContainer .skip").unbind("click");
  if(largeTeaserAutoRotateActive){
    window.clearTimeout(largeTeaserInterval);
  }
  $("#largeTeaserOverlay").fadeIn(500, function(){
    $("#" + largeTeaserOIDListRandom[currentLargeTeaser]).hide();
    useLageFlashTeaser = false;
    currentLargeTeaser++;
    if(currentLargeTeaser > maxLargeTeaser){
      currentLargeTeaser = 0;
    }
    currentlargeFlashTeasers = $.inArray(largeTeaserOIDListRandom[currentLargeTeaser], largeTeaserOIDListOrignal);
    if(highbandUser && (largeFlashTeasers[currentlargeFlashTeasers].swfurl != "none")){
      var largeTeaserSwfUrl =  getWcmsPrefix() + "/_common/rebrush/swf/wrapper_modules_autorotate.swf";
      if(largeFlashTeasers[currentlargeFlashTeasers].swfurl == ""){
        largeTeaserSwfUrl =  getWcmsPrefix() + "/_common/rebrush/swf/large_teaser_as3.swf";
      }
      var largeTeaserSwfHeight =  "280";
      var teaserSWFObject = new SWFObject(largeTeaserSwfUrl, "largeTeaserFlashObject", "1024", largeTeaserSwfHeight, "8", "#FFFFFF");
      teaserSWFObject.addParam("allowScriptAccess", "sameDomain");
      teaserSWFObject.addParam("wmode", "transparent");
      teaserSWFObject.addParam("quality", "BEST");
      teaserSWFObject.addVariable("defaultTimeToRun", largeTeaserDefaultTime);
      teaserSWFObject.addVariable("nextTeaserFunction", "startLargeTeaserTimer()");
      if(teaserSWFObject.write("largeTeaserFlash")){
        $("#largeTeaserBasic").hide();
        $("#largeTeaserFlash").show();
        $("#largeTeaserOverlay").fadeOut(500);
        useLageFlashTeaser = true;
      }
    }
    if(!useLageFlashTeaser){
      $("#largeTeaserFlash").hide();
      $("#largeTeaserBasic img").attr("src", largeBasicTeasers[$.inArray(largeTeaserOIDListRandom[currentLargeTeaser], largeTeaserOIDListOrignal)]);
      $("#largeTeaserBasic").show();
      $("#" + largeTeaserOIDListRandom[currentLargeTeaser]).show();
      $("#largeTeaserOverlay").fadeOut(500);
      if(largeTeaserAutoRotateActive){
        startLargeTeaserTimer();
      }
    }
    $(".teaserLargeContainer .skip, .teaserLargeStandardContainer .skip").html((currentLargeTeaser + 1) + " / " + (maxLargeTeaser+1));
  });
  $(".teaserLargeContainer .skip, .teaserLargeStandardContainer .skip").bind("click", showNextLargeTeaser);
}

Math.randomize = function() {var minValue=0,maxValue=0;if(arguments.length==1){maxValue=((isNaN(Number(arguments[0])))?(0):(parseInt(arguments[0])));}else if(arguments.length==2){minValue=((isNaN(Number(arguments[0])))?(0):(parseInt(arguments[0])));maxValue=((isNaN(Number(arguments[1])))?(0):(parseInt(arguments[1])));}if(maxValue<minValue){var tmpValue=minValue;minValue=maxValue;maxValue=tmpValue;}Math.randomize.startValue=(((Math.randomize.startValue*Math.randomize.a)+Math.randomize.b)%Math.randomize.c);return((minValue==maxValue)?(Math.randomize.startValue/Math.randomize.c):(minValue+Math.floor((maxValue-minValue+1)*Math.randomize.startValue/Math.randomize.c)));};Math.randomize.a=4096;Math.randomize.b=150889;Math.randomize.c=714025;Math.randomize.startValue=(((new Date()).getTime())%Math.randomize.c);
Array.prototype.remove = function(obj) {
  var arr=this,k=0;
  while(k<arr.length){
    if(arr[k]===obj){
      arr=arr.slice(0,k).concat(arr.slice(k+1,arr.length));
      --k;
    }
    ++k;
  }
  for(k=0;k<arr.length;++k){
    this[k]=arr[k];
  }
  this.length=arr.length;
};

function sameOrderTeaser(teaserList){
  var teaserListLength = 15;
  var returnList = new Array();
  if(teaserList.length < 15){
    teaserListLength = teaserList.length;
  }
  for (i=0; i<teaserListLength; ++i) {
    returnList[returnList.length] = teaserList[i];
  }
  return returnList;
}

function randomizeSimpleTeaser(teaserList, firstFix){
  var teaserListLength = 15;
  var workList = new Array(teaserList.length);
  for (var i=0; i<teaserList.length; ++i) {
    workList[i] = teaserList[i];
  }
  var returnList = new Array();
  if(workList.length < 15){
    teaserListLength = workList.length;
  }
  if(firstFix){
    returnList[returnList.length] = workList[0];
    workList.remove(workList[0]);
    teaserListLength--;
  }
  for (var i=0; i<teaserListLength; ++i) {
    var currentNumber = Math.floor(Math.random()*workList.length);
    returnList[returnList.length] = workList[currentNumber];
    workList.remove(workList[currentNumber]);
  }
  return returnList;
}

function randomizeTeaser(teaserList, firstFix){
  var arr = [];
  var teaserArr = teaserList;
  var amplifier = 3;
  var fixDifference = ((firstFix) ? (0) : (1));
  var arrLength = (((teaserArr.length-1+fixDifference) <= (4+fixDifference)) ? (teaserArr.length-1+fixDifference) : (4+fixDifference));
  var fixEntries = ((firstFix) ? ([teaserArr[0]]) : (null));
  var lotteryPot = [], i;
  for (i=(1-fixDifference); i<teaserArr.length; ++i) {
    lotteryPot[lotteryPot.length] = i;
  }
  while (arr.length < arrLength) {
    i = lotteryPot[Math.floor(Math.pow(Math.randomize(),amplifier)*lotteryPot.length)];
    lotteryPot.remove(i);
    arr[arr.length] = teaserArr[i];
  }
  if (fixEntries) {
    arr = fixEntries.concat(arr);
  }
  return arr;
}

var videoTeasers = [];
var currentVideoTeaser = false;

function showVideoTeaser(videoTeaserId, videoTeaserWidth, videoTeaserHeight, layerTop, layerLeft){
  for(var thisVideoTeaser in videoTeasers) {
   setVisibility(thisVideoTeaser,0);
   var myElement = thisVideoTeaser + "FlashID";
   if(document.getElementById(myElement)){
     document.getElementById(myElement).stopVideo();
   }
  }
  currentVideoTeaser = "videoTeaser" + videoTeaserId;
  var videoTeaser = new SWFObject(videoTeaserFlashWrapper, "videoTeaser" + videoTeaserId + "FlashID", videoTeaserWidth, videoTeaserHeight + 16, "8.0.22", "#ffffff");
  videoTeaser.addParam("quality", "high");
  videoTeaser.addParam("allowScriptAccess", "always");
  videoTeaser.addParam("wmode", "transparent");
  videoTeaser.addVariable("prm_contentgetter", "videoTeaserGetContent");

  var originalObj = document.getElementById(currentVideoTeaser);
  var clonedObj = originalObj.cloneNode(true);
  originalObj.parentNode.removeChild(originalObj);
  document.body.appendChild(clonedObj);
  videoTeaser.write("videoTeaser" + videoTeaserId + "Player");
  setVisibility("videoTeaser" + videoTeaserId, 1, 'block');
}

function videoTeaserGetContent(){
  if (currentVideoTeaser) {
    return videoTeasers[currentVideoTeaser];
  }
}

function videoTeaserTracking(fileName, videoStatus){
  var trackingUrl = self.location.href.substring(0, self.location.href.lastIndexOf("/"));
  var pageName = self.location.href.substring(self.location.href.lastIndexOf("/") + 1, self.location.href.lastIndexOf("."));
  var flvName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.lastIndexOf("."));
  trackingUrl = trackingUrl + "/" + pageName + "_video_" + flvName + "_" + videoStatus + ".html";
  if (confTrackingEnabled) {
    trackAbsolute(trackingUrl, '', true);
  }
}




// jquery.jsonp 2.1.2 (c)2010 Julian Aubourg | MIT License
// http://code.google.com/p/jquery-jsonp/
(function(e,b){function d(){}function t(C){c=[C]}function m(C){f.insertBefore(C,f.firstChild)}function l(E,C,D){return E&&E.apply(C.context||C,D)}function k(C){return/\?/.test(C)?"&":"?"}var n="async",s="charset",q="",A="error",r="_jqjsp",w="on",o=w+"click",p=w+A,a=w+"load",i=w+"readystatechange",z="removeChild",g="<script/>",v="success",y="timeout",x=e.browser,f=e("head")[0]||document.documentElement,u={},j=0,c,h={callback:r,url:location.href};function B(C){C=e.extend({},h,C);var Q=C.complete,E=C.dataFilter,M=C.callbackParameter,R=C.callback,G=C.cache,J=C.pageCache,I=C.charset,D=C.url,L=C.data,P=C.timeout,O,K=0,H=d;C.abort=function(){!K++&&H()};if(l(C.beforeSend,C,[C])===false||K){return C}D=D||q;L=L?((typeof L)=="string"?L:e.param(L,C.traditional)):q;D+=L?(k(D)+L):q;M&&(D+=k(D)+escape(M)+"=?");!G&&!J&&(D+=k(D)+"_"+(new Date()).getTime()+"=");D=D.replace(/=\?(&|$)/,"="+R+"$1");function N(S){!K++&&b(function(){H();J&&(u[D]={s:[S]});E&&(S=E.apply(C,[S]));l(C.success,C,[S,v]);l(Q,C,[C,v])},0)}function F(S){!K++&&b(function(){H();J&&S!=y&&(u[D]=S);l(C.error,C,[C,S]);l(Q,C,[C,S])},0)}J&&(O=u[D])?(O.s?N(O.s[0]):F(O)):b(function(T,S,U){if(!K){U=P>0&&b(function(){F(y)},P);H=function(){U&&clearTimeout(U);T[i]=T[o]=T[a]=T[p]=null;f[z](T);S&&f[z](S)};window[R]=t;T=e(g)[0];T.id=r+j++;if(I){T[s]=I}function V(W){(T[o]||d)();W=c;c=undefined;W?N(W[0]):F(A)}if(x.msie){T.event=o;T.htmlFor=T.id;T[i]=function(){T.readyState=="loaded"&&V()}}else{T[p]=T[a]=V;x.opera?((S=e(g)[0]).text="jQuery('#"+T.id+"')[0]."+p+"()"):T[n]=n}T.src=D;m(T);S&&m(S)}},0);return C}B.setup=function(C){e.extend(h,C)};e.jsonp=B})(jQuery,setTimeout);

function checkFacebookAvailability(){
    $.jsonp({
      "url": "https://graph.facebook.com/22893372268/posts?fields=message,type&access_token=&callback=?&error=?",
      "data": {
          "alt": "json-in-script"
      },
      "success": function(userProfile) {
         $('iframe.facebookIframe').css("display","block");
         $('iframe.facebookIframe').css("visibility","visible");
      },
      "error": function(d,msg) {
      }
    });

}


function submitSiteSearch(defaultText) {
  if( document.forms.search && document.forms.search.searchBoxText != undefined && document.forms.search.searchBoxText.value != defaultText && document.forms.search.searchBoxText.value != "") {
    document.forms.search.submit();
  }else if( document.forms.topnaviSearch && document.forms.topnaviSearch.searchBoxText != undefined && document.forms.topnaviSearch.searchBoxText.value != defaultText && document.forms.topnaviSearch.searchBoxText.value != "") {
    document.forms.topnaviSearch.submit();
  }
}

// ******** OPK datasheet START ******** //
var compare_model = new Array();
var datasheet_model_selected = new Array();
datasheet_model_selected = "";
var datasheet_model_short = new Array();

function datasheetSetTableHeight() {
  newCategoryLayerHeight = Math.round($("#sales_navigation").offset().top - $("#datasheet_innertable").offset().top - 39);
  $("#datasheet_innertable").css("height", newCategoryLayerHeight + "px");
}

function datasheetInit() {
  datasheet_model = compare_model;
  for(i in datasheet_model) {
    if(typeof datasheet_model[i] != "function"){
      datasheet_model_short.push(i);
    }
  }
  var dropdownCode = "";
  for(i = 0; i <= (datasheet_model_short.length - 1); i++) {
    dropdownCode += '<a href="" model="' + datasheet_model_short[i] + '">' + datasheet_model[datasheet_model_short[i]]["model_name"] + '</a>';
  }
  $(".dropdown_content").html(dropdownCode);

  datasheet_model_selected = datasheet_model_short[0];

  splitSearchString();
  if (query.model_1 && inArray(query.model_1,datasheet_model_short)) {
    datasheet_model_selected = query.model_1;
  }


  datasheetWriteSelectboxes();
  datasheetWriteTable();

  $(window).resize(function() {
    datasheetSetTableHeight();
  });

  $(".closeDatasheetInfoLayer").click(function(){
    $("#datasheetInfoLayer").hide();
  });

  $("#openDatasheetInfoLayer").click(function(){
    newCategoryLayerHeight = Math.round($("#sales_navigation").offset().top - $("#datasheet_innertable").offset().top - 39);
    $("#datasheetInfoLayer").css("top",newCategoryLayerHeight + "px").show();
  });

  $("#datasheet_select .select").click(function () {
    if($("#datasheet_select .dropdown").css("display") == "none"){
      $("#datasheet_select .dropdown").show();
    }else{
      $("#datasheet_select .dropdown").hide();
    }
  });

  $(".dropdown_content a").click(
    function () {
      datasheet_model_selected = $(this).attr("model");
      datasheetWriteSelectboxes();
      datasheetWriteTable();
      $("#datasheet_select .dropdown").hide();
      return false;
    }
  );
  $(document).click(function(e){
    if($(e.target).attr("id") != "datasheet_select_box"){
      $("#datasheet_select .dropdown").hide();
    }
  });
}


function datasheetWriteSelectboxes() {
  $("#datasheet_select .select").html(datasheet_model[datasheet_model_selected]["model_name"]);
  $("#datasheet_select").show();
  if(datasheet_model[datasheet_model_selected]["configure_link"]) {
    $("#datasheet_select .configure a").attr("href", datasheet_model[datasheet_model_selected]["configure_link"]);
    $("#datasheet_select .configure").show();
  }
}

function datasheetWriteTable() {
  var datasheetTableCode = ''+
  '       <div class="modelImageContainer">' +
  '         <a class="modelImageMagnifier" href="javascript:void(0)"></a>' +
  '         <a class="datasheetPrint" href="javascript:void(0)"></a>' +
  '         <img class="modelImageSmall" src="" width="308" height="169">' +
  '       </div>' +
  '       <div class="dataTableColumnLeft">';

  var datasheetTableBreak = Math.floor(datasheetDisplaySections.length /2);

  for(h = 0; h < datasheetDisplaySections.length; h++) {
    var datasheetDisplayCurrentSection = false;
    if(datasheetTableBreak == h){
      datasheetTableCode += ''+
      '      </div>' +
      '      <div class="dataTableColumnRight">';
    }
    datasheetTableCode += '' +
    '        <table width="338" border="0" cellspacing="0" cellpadding="0">' +
    '          <tr>' +
    '            <td width="11"></td>' +
    '            <td width="192"></td>' +
    '            <td width="10"></td>' +
    '            <td width="120"></td>' +
    '            <td width="5"></td>' +
    '          </tr>';
    for(i = 0; i < datasheet_model[datasheet_model_selected].length; i++) {

      if(datasheetDisplaySections[h] == datasheet_model[datasheet_model_selected][i][0]){
        datasheetDisplayCurrentSection = true;
      }else if(datasheetDisplayCurrentSection && (datasheet_model[datasheet_model_selected][i][0] == "")) {
        datasheetDisplayCurrentSection = true;
      }else if(datasheet_model[datasheet_model_selected][i][0] != "" && datasheetDisplaySections[h] != datasheet_model[datasheet_model_selected][i][0]){
        datasheetDisplayCurrentSection = false;
      }
      if(datasheetDisplayCurrentSection){
        if(datasheet_model[datasheet_model_selected][i][0] != "") {
          datasheetTableCode += '' +
          '          <tr class="mc_table_headline">' +
          '            <td></td>' +
          '            <td colspan="4">' + datasheet_model[datasheet_model_selected][i][0] + '</td>' +
          '          </tr>' +
          '          <tr class="mc_table_seperator">' +
          '            <td colspan="5"></td>' +
          '          </tr>';
        }else if(datasheet_model[datasheet_model_selected][i][1] != "") {
          datasheetTableCode += '' +
          '          <tr class="mc_table_entry">' +
          '            <td></td>' +
          '            <td class="leftalign">' + datasheet_model[datasheet_model_selected][i][1] + '</td>' +
          '            <td></td>' +
          '            <td>' + datasheet_model[datasheet_model_selected][i][2] + '</td>' +
          '            <td></td>' +
          '          </tr>' +
          '          <tr class="mc_table_seperator">' +
          '            <td colspan="5"></td>' +
          '          </tr>';
        }
      }
    }
    datasheetTableCode += '        </table>';
  }
  datasheetTableCode += '       </div>';

  $("#datasheet_innertable").html(datasheetTableCode);
  if(datasheetTableCode != ""){
    $(".modelImageSmall").attr("src",datasheetImageList[$.inArray(datasheet_model_selected, datasheet_model_short) ]["small"]);
    $(".modelImageZoom").attr("src",datasheetImageList[$.inArray(datasheet_model_selected, datasheet_model_short) ]["large"]);

    $(".modelImageMagnifier").click(function(){
      $("#datasheet_innertable").hide();
      $("#openDatasheetInfoLayer").hide();
      $("#datasheetZoomImage").show();
    });

    $(".modelImageMinifier").click(function(){
      $("#datasheetZoomImage").hide();
      $("#datasheet_innertable").show();
      $("#openDatasheetInfoLayer").show();
    });

    $(".datasheetPrint").click(function(){
      window.print();
    });
  }
  $("#datasheetHiddenPrintLayer").html($("#datasheetInfoLayerBg").html());
  var tableContent = $("#datasheet_innertable").html();
  tableContent = tableContent.replace(/width=["]338["]/g, "width=\"645\"");
  tableContent = tableContent.replace(/width=["]120["]/g, "width=\"249\"");
  tableContent = tableContent.replace(/width=["]192["]/g, "width=\"370\"");
  tableContent = tableContent.replace(/width=338/g, "width=645");
  tableContent = tableContent.replace(/width=120/g, "width=249");
  tableContent = tableContent.replace(/width=192/g, "width=370");
  $("#datasheetHiddenPrintLayer").prepend(tableContent);
  $("#datasheetHiddenPrintLayer").prepend($("#datasheetZoomImage").html());
  $("#datasheetHiddenPrintLayer").prepend("<div class=\"printSubhead\">" + $("#datasheet_select .select").html() +"</div>");
  $("#datasheetHiddenPrintLayer").prepend("<div class=\"printHead\">" + $("#datasheet_head").html() +"</div>");
  $("#datasheetHiddenPrintLayer").prepend("<div class=\"printIdModuls\"><img src=\"" + buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/img/id_moduls_grey.png") + "\"></div>");

  datasheetSetTableHeight();
}

// ******** OPK datasheet END ******** //


function trackDownloadLink(fileName) {
  var fileParam = getFullPath(self.location.href, fileName);
  trackTeaserClick('/' + confCountryTopic + '/' + confLanguageTopic + '/_common/shared/tracking_redirect/download.html', 'download', fileParam);
  return true;
}

function showSiloDialog(transferId, topPos, leftPos, layerWidth, layerHeight, type) {
  var siloJsp  = "";
  if(type == "campaign"){
    siloJsp  = "/_common/silo/campaign/campaign_subscribe.jsp";
  }else if(type == "reminder"){
    siloJsp  = "/_common/silo/campaign/campaign_reminder.jsp";
  }
  var siloCode = "<div id=\"siloDialog\" style=\"position:absolute; top:" + topPos + "; left:" + leftPos + "; width:" + layerWidth + "; height:" + layerHeight + "; z-index:850;overflow:hidden;\">";
  siloCode    += "<iframe id=\"siloDialogIFrame\" name=\"siloDialogIFrame\"  style=\"background:transparent; width:" + layerWidth + "; height:" + layerHeight + "; border: none;\" allowtransparency=\"true\" src=\"";
  siloCode    += buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + siloJsp + "?transfer=" + transferId);
  siloCode    += "\" frameborder=\"0\" scrolling=\"no\"></iframe></div>";
  $("#siloDialog").remove();
  $("body").append(siloCode);
  $("#siloDialog").show();
}

// -> Fluid Positions
//The Following should be implement in a  seperate file or added to a common one. You may should also remove all the comments.

/**
 * Fluid Positions
 *
 *
 * @author Orlando Hohmeier, Interone GmbH
 *
 * @requires jQuery (http://jquery.com/)
 *
 * @example
 *
 * Visible Stage: var stage = positionutil.getVisibleStage("flashmovie")
 * console.log("Stage Offset: " + stage.left + " / " + stage.top);
 * console.log("Stage Dimensions: " + stage.width + " / "+ stage.height);
 *
 *
 */
function highlightFluidPositions(callback) {

  // Create object and define namespace which is used to call
  var _ = {};
  _.namespace = 'highlightFluidPositions';

  // Vars
  _.updatePositionsCallback;
  _.updatePositionInterval;

  // Save as window.namespace
  window[_.namespace] = _;

  /**
   * Init
   *
   * @param {}
   *            f updatePositionCallback
   * @return {}
   */
  _.init = function(f) {

    if (typeof f == "function") {
      _.updatePositionsCallback = f;
    }

    // Register Events (Resize & Scroll)
    $(window).bind('resize', _.updatePositions);
    $(window).bind('scroll', _.updatePositions);
  }

  /**
   * Get Visible Stage
   *
   * @param {}
   *            id
   * @return {}
   */
  _.getVisibleStage = function(id) {
    var stage = new Object();
    var browser = $(window);
    var object = $("#" + id);
    if(object.offset() !=null){
    // Offset
    stage.left = object.offset().left - browser.scrollLeft();
    stage.top = object.offset().top - browser.scrollTop();
    // Dimensions
    if (object.width() + stage.left < browser.width()) {
      stage.width = object.width();
    } else {
      stage.width = browser.width() - stage.left;
    }
    if (object.height() + stage.top < browser.height()) {
      stage.height = object.height();
    } else {
      stage.height = browser.height() - stage.top;
    }

    return stage;
   }
  }

  /**
   * Update Positions
   *
   */
  _.updatePositions = function() {
    if (_.updatePositionsCallback) {
      if (_.updatePositionInterval) {
        self.clearInterval(_.updatePositionInterval);
      }
      _.updatePositionInterval = self.setInterval(_.namespace+ ".updatePositionIntervalHandler()", 200);
    }
  }

  /**
   * Update
   *
   */
  _.updatePositionIntervalHandler = function() {
    if (_.updatePositionInterval) {
      self.clearInterval(_.updatePositionInterval);
    }
    _.updatePositionsCallback();
  }

  /**
   * Function to get the Flash Object
   *
   * @param {}
   *            #id
   * @return {} Object
   */
  _.getFlashObject = function(id) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
      return window[id];
    } else {
      return document[id];
    }
  };

  /**
   * Init
   *
   */
  _.init(callback);
};


//The Following should be implement in a script tag as it is.
/**
 * Update Positions
 *
 */
function highlightUpdatePositions() {
  var flashId = "mainFlash";
  var stage = highlightFluidPositions.getVisibleStage(flashId);
  var flashObject = highlightFluidPositions.getFlashObject(flashId);
  var bottomNavigation = $("#bottomNavigation")
  if (stage && flashObject) {
    if(stage.height > 400){
      if(stage.height < $(flashObject).height()){
        stage.height -= bottomNavigation.height();
      }
      //Send the stage size to the flashObject
      try {
        flashObject.setWindowSize(stage.width, stage.height);
      } catch (e) {
        //Catch errors
      }
      //Caluclate and apply new positions to the html controls.
      $("#highlightDialogButtons").css({top:stage.height-30});
      $("#highlightCloseButton").css({top:stage.height-38});
    }
  }
}

//videolayer
var videoLayerCode = '' +
'<div id="videoLightboxLayerCurtain">&nsbp;</div>' +
'<div id="videoLightboxLayer">' +
'  <div id="innerDiv">' +
'    <div id="left">' +
'      <a href="" onclick="javasscript:videoLayerPlayPrevious();return false;">&nbsp;</a>' +
'    </div>' +
'    <div id="content">' +
'      <div id="videoLightboxFlash">' +
'      </div>' +
'      <div id="title">' +
'        <span></span>' +
'      </div>' +
'      <div id="downloads">' +
'        <div id="core">' +
'        </div>' +
'      </div>' +
'      <div id="closeButtonLayer">' +
'        <a href="" onclick="videoLayerClose(); return false;" class="closeLink"></a>' +
'      </div>' +
'    </div>' +
'    <div id="right">' +
'      <a href="" onclick="javasscript:videoLayerPlayNext();return false;">&nbsp;</a>' +
'    </div>' +
'  </div>' +
'</div>' +
'<!--[if IE 6]>' +
'<style type="text/css">' +
'#videoLightboxLayer #innerDiv #left a  {' +
'  cursor:pointer;' +
'  background:none;' +
'  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\'' + getWcmsPrefix() + '/_common/files/img/gallery/media_gallery_arrow_left_white.png\', sizingMethod=\'crop\');' +
'}' +
'#videoLightboxLayer #innerDiv #left a:hover  {' +
'  background:none;' +
'  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\'' + getWcmsPrefix() + '/_common/files/img/gallery/media_gallery_arrow_left_blue.png\', sizingMethod=\'crop\');' +
'}' +
'#videoLightboxLayer #innerDiv #right a {' +
'  cursor:pointer;' +
'  background:none;' +
'  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\'' + getWcmsPrefix() + '/_common/files/img/gallery/media_gallery_arrow_right_white.png\', sizingMethod=\'crop\');' +
'}' +
'#videoLightboxLayer #innerDiv #right a:hover  {' +
'  background:none;' +
'  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\'' + getWcmsPrefix() + '/_common/files/img/gallery/media_gallery_arrow_right_blue.png\', sizingMethod=\'crop\');' +
'}' +
'</style>' +
'<![endif]-->';


var videoLayerPlayerSwf = buildValidServerRelativeUrl("/_common/rebrush/swf/flv_player.swf");
var videoLayerVideoList = new Array();
var videoLayerCurrentVideo = 0;
var videoLayerHasClosedModulenavigation = false;
var videoLayerSubtitleArray = new Array();
var videoLayerCodeAdded = false;


function videoLayerInit() {
  if(arguments.length > 0) {
    videoLayerVideoList = arguments;
    if(!videoLayerCodeAdded) {
      $("body").append(videoLayerCode);
      $("#videoLightboxLayer, #videoLightboxLayerCurtain").css("height", $(window).height());
      $("#videoLightboxLayerCurtain").css("height", $(document).height());
      videoLayerCodeAdded = true;
    }
    $("#videoLightboxLayer").css("top",$(window).scrollTop());
    $('<img />').attr('src', getWcmsPrefix() + '/_common/files/img/gallery/media_gallery_arrow_left_blue.png');
    $('<img />').attr('src', getWcmsPrefix() + '/_common/files/img/gallery/media_gallery_arrow_right_blue.png');
    if(videoLayerVideoList.length == 1) {
      $("#videoLightboxLayer #left, #videoLightboxLayer #right").hide();
    }
    else {
      $("#videoLightboxLayer #left, #videoLightboxLayer #right").show();
    }

    $("#videoLightboxLayer #innerDiv").css("width","1px").css("height","1px").css("marginLeft","1px").css("marginTop","1px").css("top","50%").css("left","50%");
    $("#videoLightboxLayer #innerDiv #content").css("width","1px").css("height","1px").css("top","0px").css("left","29px");

    if(videoLayerPlay(videoLayerVideoList[0])) {
      if(moduleNavigationOpen) {
        foldModuleNavi(true);
        videoLayerHasClosedModulenavigation = true;
      }
    }
    trackingCookieClear();
    layerTracking('videolayer');
  }
}


function videoLayerPlay(videoId) {
  var videoWidth = videos[videoId].dimension[0];
  var videoHeight = videos[videoId].dimension[1];
  var videoSource = buildValidServerRelativeUrl(videos[videoId].flv);
  if(videoWidth && videoHeight && videoSource) {
    if(moduleNavigationOpen) {
      foldModuleNavi(true);
      videoLayerHasClosedModulenavigation = true;
    }
    if(videos[videoId].downloads) {
      var outerDivHeight = videoHeight + 75;
      var innerDivHeight = videoHeight + 55;
      $("#videoLightboxLayer #downloads").show();
    }
    else {
      var outerDivHeight = videoHeight + 25;
      var innerDivHeight = videoHeight;
      $("#videoLightboxLayer #downloads").hide();
    }

    var marginLeft = ((videoWidth + 78) / 2) * -1;
    var marginTop = ((outerDivHeight) / 2) * -1;

    var outerDivWidth = videoWidth + 78;
    var innerDivWidth = videoWidth;
    var downloadCode = "";


    if(videos[videoId].downloads) {
      downloadCode = '<p>' + videos[videoId].download_headline + '</p><table cellspacing="0" cellpadding="0" border="0">';
      var tdCounter = Math.ceil(videos[videoId].downloads.length / 2);
      var downloadCounter = 0;
      for(i = 0; i < 2; i++) {
        downloadCode += '<tr>';
        for(k = 0; k < tdCounter; k++) {
          if(downloadCounter < videos[videoId].downloads.length) {
            downloadCode += '<td><a href="' + buildValidServerRelativeUrl(videos[videoId].downloads[downloadCounter][1]) + '" class="standard">' + videos[videoId].downloads[downloadCounter][0] + '</a></td>';
            downloadCounter++;
          }
          else {
            downloadCode += '<td></td>';
          }
        }
        downloadCode += '</tr>';
      }
    }
    $("#videoLightboxLayerCurtain").css("filter", "alpha(opacity=50)");
    $("#videoLightboxLayerCurtain").fadeIn(500);
    $("#videoLightboxLayer").show();
    $("#videoLightboxFlash").css("visibility","hidden");

    $("#videoLightboxLayer #innerDiv").animate({
      width:outerDivWidth,
      height:outerDivHeight,
      marginLeft:marginLeft,
      marginTop:marginTop
    }, 500);



    $("#videoLightboxLayer #innerDiv #content").animate({
      width:innerDivWidth,
      height:innerDivHeight
    }, 500, function(){$("#videoLightboxFlash").css("visibility","visible");});
    if(videos[videoId].headline) {
      $("#videoLightboxLayer #title span").html(videos[videoId].headline).show();
    }
    else {
      $("#videoLightboxLayer #title span").hide();
    }
    $("#videoLightboxLayer #downloads #core").html(downloadCode);
    var videoPlayer = new SWFObject(videoLayerPlayerSwf, "bmw_video", videoWidth, videoHeight, "9.0.115", "#ffffff");
    videoPlayer.addParam("quality", "autohigh");
    videoPlayer.addParam("allowScriptAccess", "always");
    videoPlayer.addParam("wmode", "opaque");
    videoPlayer.addVariable("prm_flv_url", videoSource);
    videoPlayer.addVariable("prm_corelib", swf_corelib);
    videoPlayer.addVariable("prm_components", swf_components);
    videoPlayer.addVariable("prm_stage_width", videoWidth);
    videoPlayer.addVariable("prm_stage_height", videoHeight);
    videoPlayer.addVariable("prm_tracking_enabled", "false");
    videoPlayer.addVariable("prm_version", "high");
    if(videos[videoId].subtitles) {
      videoLayerSubtitleArray = videos[videoId].subtitles;
      videoPlayer.addVariable("prm_subtitle_getter", "videoLayerSubtitleGetter");
    }
    return(videoPlayer.write("videoLightboxFlash"));
  }
  else {
    return false;
  }
}


function videoLayerPlayNext() {
  if(videoLayerCurrentVideo + 1 < videoLayerVideoList.length ) {
    videoLayerCurrentVideo++;
  }
  else {
    videoLayerCurrentVideo = 0;
  }
  videoLayerPlay(videoLayerVideoList[videoLayerCurrentVideo]);
}


function videoLayerPlayPrevious() {
  if(videoLayerCurrentVideo - 1 >= 0 ) {
    videoLayerCurrentVideo--;
  }
  else {
    videoLayerCurrentVideo = videoLayerVideoList.length - 1;
  }
  videoLayerPlay(videoLayerVideoList[videoLayerCurrentVideo]);
}

function videoLayerClose() {
  $("#videoLightboxFlash").html("");
  $("#videoLightboxLayerCurtain").fadeOut(500);
  $("#videoLightboxLayer #innerDiv").animate({
    width:"1px",
    height:"1px",
    marginLeft:"1px",
    marginTop:"1px"
  }, 500);
  $("#videoLightboxLayer #innerDiv #content").animate({
    width:"1px",
    height:"1px"
  }, 500, function(){$("#videoLightboxLayer").hide(); });
  if(videoLayerHasClosedModulenavigation) {
    foldModuleNavi(false);
  }
  videoLayerHasClosedModulenavigation = false;
}

function videoLayerSubtitleGetter() {
  return videoLayerSubtitleArray;
}

var kitLayerFlash = new Array();

function kitWideShowLayer(layerId) {
  $('.kitWideTeaserLayer').css('visibility','hidden');
  //var topPos = Math.floor(($(window).height() - 426) / 2) + $(window).scrollTop();
  //var leftPos = Math.floor(($(window).width() - 706) / 2);
  //if(topPos < 100) {topPos = 100;}
  //if(leftPos < 30) {leftPos = 30;}

  var topPos = $(window).scrollTop() + 136;
  var leftPos = 256;

  if(kitLayerFlash[layerId]) {
    var kitLayerFlashObject = new SWFObject(getWcmsPrefix() + kitLayerFlash[layerId], "flashObject" + layerId, "334", "264", "9", "#ffffff");
    kitLayerFlashObject.addParam("quality","high");
    kitLayerFlashObject.addParam("allowScriptAccess","never");
    kitLayerFlashObject.addParam("wmode","opaque");
    kitLayerFlashObject.write(layerId + "Stage");
  }
  $('#' + layerId).css('top',topPos  + "px").css('left',leftPos + "px").css('visibility','visible');
}

function layerTracking(oid) {
  var layerUrl = self.location.pathname.substring(0,self.location.pathname.lastIndexOf("."));
  var layerUrl = layerUrl + "_layer_" + oid + ".html";
  trackPage(layerUrl);
}

function kitSetLayerDimensions() {
  $('.kitWideTeaserLayer').each(function() {
    var leftHeight = $(this).find('.left').height();
    $(this).find(".right").css('height', leftHeight - 15 + "px");
    $(this).find(".sizer").css('height', leftHeight + 19 + "px");
    $(this).find(".content").css('height', leftHeight + 19 + "px");
    dialogBoxesSetDimensions();
  });
}

function getNavigationDetails(){
  var cookieName = "BMWNavigation";
  var cookieValue = "";
  if( confCountryTopic != null && confLanguageTopic != null){
    cookieValue += "stage:;";
    cookieValue += "country:" + confCountryTopic + ";";
    cookieValue += "language:" + confLanguageTopic + ";";
    setCookie(cookieName, cookieValue, "", "/");
  }
}

$(document).ready(function() {
  var cookieHosts = /^(http\:\/\/)(origin\.bmw)|(liintra)/g;
  if(cookieHosts.test(self.location.href)){
    getNavigationDetails();
  }
});

