var shareUrl = self.location.href;
var shareTitle = document.title;
var selectedHighlightUrl = "";
var swf_corelib = buildValidServerRelativeUrl("/sync/showroom_rebrush/_common/files/swf/libraries/bmw_as3_corelib_1_1.swf");
var swf_components = buildValidServerRelativeUrl("/sync/showroom_rebrush/_common/files/swf/components/bmw_as3_components_2_0.swf");
var salesNavigationTopPos = 634;
var co2DisclaimerCookieName = "";

function inArray(value,thisArray) {
  for (var i = 0; i < thisArray.length; i++) {
    if (thisArray[i] === value) {
      return true;
     }
  }
  return false;
};

function initStandardPage() {
  checkClient();
  checkWindowSize();
  salesNavigationCheckPosition();

  $(window).resize(function(){
    checkWindowSize();
    salesNavigationCheckPosition();
  });

  $(window).scroll(function(){
    checkWindowSize();
    salesNavigationCheckPosition();
  });

  highlightNavigations();
  highlightVehicleNavigation();
}


function co2DisclaimerCheck() {
  var tempArray = self.location.href.split("/");
  for(i = tempArray.length - 1; i >= 0; i--) {
    if(!tempArray[i-3]) {
      break;
    }
    else if(tempArray[i] == "showroom") {
      co2DisclaimerCookieName = "co2disclaimer_" + tempArray[i-3] + "_" + tempArray[i-2] + "_" + tempArray[i-1];
      break;
    }
  }
  if(!getCookieValue(co2DisclaimerCookieName)) {
    $("#co2Disclaimer").show();
  }
}

function divisible(number,divider) {
   var temp = 0;
   var result = false;
   temp = number % divider;
   if(temp == 0) {
     result = true;
   }
   return result;
}

function highband_check(url) {
  selectedHighlightUrl = url;
  if(!highbandUser) {
    $("#bandwidth_advice_curtain").show();
    $("#bandwidth_advice").show();
  }
  else {
   self.location.href = url;
  }
}

function closeBandwidthAdvice() {
  $("#bandwidth_advice_curtain").hide();
  $("#bandwidth_advice").hide();
}

function shareThis(url,service) {
  url = url.replace("{#share_url}", encodeURIComponent(shareUrl));
  url = url.replace("{#share_title}", encodeURIComponent(shareTitle));

  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/share.html") + "?source=" + self.location.pathname + "&target=" + encodeURIComponent(service);
    trackAbsolute(trackingUrl,'');
  }
  window.open(url,"share");
  return false;
}

function dialogBoxesSetDimensions() {
  $('.dialogbox, .shadowbox').each(function() {

    $(this).find(".content").css("height","auto");
    var contentWidth = $(this).find(".content").width();
    var contentHeight = $(this).find(".content").height();
    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("src", "http://www.bmw.com/_common/html/img/palette/1x1_ffffff.gif");
    $(this).find("img.background").attr("width", contentWidth - 6).attr("height", contentHeight - 10).show();
  });
}

function favoriteDelete(deleteOid) {
  $("#deleteDialogLayer").css("visibility","hidden");
  $("#deleteDialogLayer").css("top","-500px");
  $("#deleteDialogLayer").css("left","-500px");
  $("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete").removeClass("dialogButtonShareActive").removeClass("dialogButtonDownloadActive").removeClass("dialogButtonFavoriteActive").removeClass("dialogButtonDeleteActive");
  resetToggle("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete");

  if(typeof(favoriteData) != "undefined") {
    var newCookieString = "";
    if(getCookieValue("favorites")) {
      var favoritesArray = getCookieValue("favorites").split(";");
      for(i = 0; i < favoritesArray.length; i++) {
        if(favoritesArray[i] != deleteOid) {
          newCookieString += favoritesArray[i];
          if(i != favoritesArray.length - 1) {
            newCookieString += ";";
          }
        }
      }
      setCookie("favorites", newCookieString, "Sun, 31-Dec-2100 00:00:00 GMT", "/");
    }
  }
}

function favoritesSaved() {
  var dummy = new Array();
  if(getCookieValue("favorites")) {
    var favoritesArray = getCookieValue("favorites").split(";");
    return favoritesArray;
  }
  else {
    return dummy;
  }
}


//document.ready start
$(document).ready(function() {

  if(!highbandUser) {
    $("a.highlight_link").click(function () {
      highband_check($(this).attr("href"));
      return false;
    });
  }

  //favorites start
  if(typeof(favoriteData) != "undefined" && typeof(pageOid) != "undefined") {
    if(!favoriteData[pageOid]) {
      $(".dialogButtonFavorite").hide();
    }
    else {
      if(isCookiesEnabled()) {
        var pageAlreadyBookmarked = false;
        if(getCookieValue("favorites")) {
          var favoritesArray = getCookieValue("favorites").split(";");
          for(i = 0; i < favoritesArray.length; i++) {
            if(favoritesArray[i] == pageOid) {
              $("#favoriteNotActive").hide();
              $("#favoriteActive").show();
              $("a.dialogButtonFavorite, a.dialogButtonFavoriteActive").css('background-position','0px -295px');
              break;
            }
          }
        }
      }
    }
  }
  else {
    $(".dialogButtonFavorite").hide();
  }

  $("a.dialogButtonFavorite").click(
    function() {

      $("#favoriteDialogLayer").css("top","-1500px");

      var pageAlreadyBookmarked = false;
      if(isCookiesEnabled()) {
        if(getCookieValue("favorites")) {
          var favoritesArray = getCookieValue("favorites").split(";");
          for(i = 0; i < favoritesArray.length; i++) {
            if(favoritesArray[i] == pageOid) {
              pageAlreadyBookmarked = true;
            }
          }
          if(!pageAlreadyBookmarked) {
            favoritesArray.push(pageOid);
          }
        }
        else {
          var favoritesArray = new Array(pageOid);
        }
        if(!pageAlreadyBookmarked) {
          var cookieString = "";
          for(i = 0; i < favoritesArray.length; i++) {
            cookieString += favoritesArray[i];
            if(i != favoritesArray.length - 1) {
              cookieString += ";";
            }
          }
          setCookie("favorites", cookieString, "Sun, 31-Dec-2100 00:00:00 GMT", "/");
          if(confTrackingEnabled) {
            var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/bookmark.html") + "?url=" + self.location.pathname + "&action=bookmark_save";
            trackAbsolute(trackingUrl);
          }
        }
        $("#favoriteNotActive").hide();
        $("#favoriteActive").show();
        $("#favoriteNoCookie").hide();
        $("a.dialogButtonFavorite, a.dialogButtonFavoriteActive").css('background-position','0px -295px');
      }
      else {
        $("#favoriteActive").hide();
        $("#favoriteNotActive").hide();
        $("#favoriteNoCookie").show();
      }
      dialogBoxesSetDimensions();

      var topPos = $("a.dialogButtonFavorite").offset().top - ($("#favoriteDialogLayer").height() - 5);
      $("#favoriteDialogLayer").css("top", topPos + "px");

  });
  //favorites end

// ******** NAVIGATION START ******** //
  //start: salesnavi event-steuerung

  $(".sales_navigation_layer").mouseenter(function(event) {
    if($(event.target).attr("class")== "sales_navigation_layer"){
      $("#" + event.currentTarget.id.replace(/button/g, "layer") + " div.box").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.box").mouseleave(function(event) {
      salesNavigationButtonWidth = "98px";
      try {
        if( $("#" + $(event.currentTarget).parent().get(0).id.replace(/layer/g, "button")).hasClass("first")) {
          salesNavigationButtonWidth = "97px";
        }
        salesNavigationButtonElement = $("#" + $(event.currentTarget).parent().get(0).id.replace(/layer/g, "button"));
        salesNavigationLayerElement = $("#" + $(event.currentTarget).parent().get(0).id);

        if( $(event.relatedTarget).parent().attr("id") ) {
          if($(event.relatedTarget).parent().attr("id").indexOf("sales_navigation_select") == -1 && $(event.relatedTarget).attr("id").indexOf("sales_navigation_select") == -1) {
            closeSalesNavLayer(salesNavigationButtonWidth, salesNavigationLayerElement, salesNavigationButtonElement);
          }
        }
        else {
          closeSalesNavLayer(salesNavigationButtonWidth, salesNavigationLayerElement, salesNavigationButtonElement);
        }

      }
      catch(e) {}
    })

    $(activeLayerName).show();
    $(activeLayerName).height($(activeLayerName + " .box").height() + 25);
    $(activeLayerName).css("top", salesNavigationTopPos - ($(activeLayerName + " .box").height() + 25));

  })
  //end: salesnavi event-steuerung

  //start: salesnavi selectboxes event-steuerung
  $("a.sales_navigation_selectbox").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, "");
    $("#" + elementID).html( $(this).html() );

    if($(this).parent().attr("id") == "sales_navigation_select_models") {
      replaceParameterInLink("sales_navigation_configuration_link", "{color_value}", sales_navigation_configuration_last_value_color, "{model_value}", $(this).attr("href"), sales_navigation_configuration_link_original);
      replaceParameterInLink("sales_navigation_accessory_link", "{color_value}", sales_navigation_configuration_last_value_color, "{model_value}", $(this).attr("href"), sales_navigation_accessory_link_original);
      sales_navigation_configuration_last_value_model = $(this).attr("href");
    }
    else if($(this).parent().attr("id") == "sales_navigation_select_colors") {
      replaceParameterInLink("sales_navigation_configuration_link", "{color_value}", $(this).attr("href"), "{model_value}", sales_navigation_configuration_last_value_model, sales_navigation_configuration_link_original);
      replaceParameterInLink("sales_navigation_accessory_link", "{color_value}", $(this).attr("href"), "{model_value}", sales_navigation_configuration_last_value_model,  sales_navigation_accessory_link_original);
      sales_navigation_configuration_last_value_color = $(this).attr("href");
    }
    else if($(this).parent().attr("id") == "sales_navigation_select_compare_1") {
      replaceParameterInLink("sales_navigation_compare_link", "{model1}", $(this).attr("href"), "{model2}", sales_navigation_compare_last_value_2, sales_navigation_compare_link_original);
      sales_navigation_compare_last_value_1 = $(this).attr("href");
    }
    else if($(this).parent().attr("id") == "sales_navigation_select_compare_2") {
      replaceParameterInLink("sales_navigation_compare_link", "{model1}", sales_navigation_compare_last_value_1, "{model2}", $(this).attr("href"), sales_navigation_compare_link_original);
      sales_navigation_compare_last_value_2 = $(this).attr("href");
    }
    return false;
  });
  //end: salesnavi selectboxes event-steuerung

  //start salesnavi highlighting

  for(i = 1; i <= 7; i++) {
    $("#sales_navigation_layer_" + i + " a").each(function() {
      var linkUrl = $(this).attr("href").split("?");
      if( self.location.pathname.indexOf(linkUrl[0]) != -1 && !$("#sales_navigation_button_" + i).hasClass("blue")) {
        $("#sales_navigation_button_" + i).css("color","#1d6ad4");
        $(this).addClass("standard_active").removeClass("standard");
      }
    });
  }

  //extra compare
  if($("#sales_navigation_compare_link").attr("href")) {
    var myTempTestUrl = $("#sales_navigation_compare_link").attr("href").split("?");
    if( self.location.pathname.indexOf(myTempTestUrl[0]) != -1 ) {
      $("#sales_navigation_button_compare").css("color","#1d6ad4");
      $(this).addClass("standard_active").removeClass("standard");
    }
  }

  //end salesnavi highlighting


// ******** NAVIGATION END ******** //

// ******** PREPARE DIALOG BOXES START ******** //
  var dialogBoxexIEStyles = "<style type=\"text/css\">"
  + ".dialogbox .topBorder, .shadowbox .topBorder {background-image:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/sync/showroom_rebrush/_common/files/img/dialogbox/dialogbox_top.png', sizingMethod='scale');}"
  + ".dialogbox .rightBorder, .shadowbox .rightBorder {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/sync/showroom_rebrush/_common/files/img/dialogbox/dialogbox_right.png', sizingMethod='crop');}"
  + ".dialogbox .bottomBorder, .shadowbox .bottomBorder {background-image:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/sync/showroom_rebrush/_common/files/img/dialogbox/dialogbox_bottom.png', sizingMethod='crop');}"
  + ".dialogbox .bottomBorder .bottomArrowImage, .shadowbox .bottomBorder .bottomArrowImage {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/sync/showroom_rebrush/_common/files/img/dialogbox/dialogbox_bottom_arrow.png', sizingMethod='crop');}"
  + ".dialogbox .bottomBorder .bottomArrowImageRight, .shadowbox .bottomBorder .bottomArrowImageRight {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/sync/showroom_rebrush/_common/files/img/dialogbox/dialogbox_bottom_arrow.png', sizingMethod='crop');}"
  + ".dialogbox .leftBorder, .shadowbox .leftBorder {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/sync/showroom_rebrush/_common/files/img/dialogbox/dialogbox_left.png', sizingMethod='crop');}"
  + ".dialogbox .corner, .shadowbox .corner {background-image:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + getWcmsPrefix() + "/sync/showroom_rebrush/_common/files/img/dialogbox/dialogbox_corner.png', sizingMethod='crop');}"
  + "<style>";

  jQuery.each(jQuery.browser, function(i, val) {
    if(i == "msie" && jQuery.browser.version.substr(0,1) == "6")
     $("body").append(dialogBoxexIEStyles);
  });

  if(typeof(share_services_active) == "boolean" &&  share_services_active) {
    var sharelayerCode = '<div class="dialogbox" id="shareDialogLayer"><div class="content"><div class="sharecontent"><strong>' + share_services_headline + '</strong><table width="210" cellspacing="0" cellpadding="0" border="0">'
    for(i=0; i < share_services.length; i++ ) {
      if(i == 0 || divisible(i,2)) {
        sharelayerCode += '<tr valign="top">';
      }
      sharelayerCode += '<td width="22"><img src="' + getWcmsPrefix() + share_services[i][2] + '" width="17" height="16"></td>';
      sharelayerCode += '<td width="83"><a href="" onClick="javascript:shareThis(\'' + share_services[i][1] + '\',\'' + share_services[i][0] + '\');return false;" class="standard">' + share_services[i][0] + '</a></td>';
      if(!divisible(i,2)) {
        sharelayerCode += '</tr>';
      }
      if(divisible(i,2) && (i + 1 == share_services.length)) {
        sharelayerCode += '<td></td><td></td></tr>';
      }
    }
    sharelayerCode += '</table></div></div></div>';
    $("body").append(sharelayerCode);
  }
  else {
    $("a.dialogButtonShare").hide();
  }

  $(".dialogbox").prepend('<img class="background" src="' + getWcmsPrefix() + '/sync/showroom_rebrush/_common/files/img/dialogbox/dialogbox_background.gif" height="10" width="10">');
  $(".shadowbox").prepend('<img class="background" src="' + getWcmsPrefix() + '/_common/html/img/palette/1x1_ffffff.gif" height="10" width="10">');
  $(".dialogbox").append('<div class="bottomBorder"><div class="bottomArrowImage"></div></div><div class="corner"></div>');
  $(".shadowbox").not(".nobottom").append('<div class="bottomBorder"></div><div class="corner"></div>');
  $(".dialogbox .content, .shadowbox .content").append('<div class="topBorder"></div><div class="leftBorder"></div><div class="rightBorder"></div>');


  dialogBoxesSetDimensions();

  $("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete").hover(
    function (event) {

      dialogBoxesSetDimensions();

      var layerName = "#" + event.target.id + "Layer";
      var topPos = $(this).offset().top - ($(layerName).height() - 5);
      var leftPos = $(this).offset().left - 4;
      var layerWidth = $(layerName).width();
      if(1020 - leftPos - layerWidth < 0) {
        leftPos = leftPos - layerWidth + 22;
        $(layerName + " .bottomArrowImage").addClass("bottomArrowImageRight").removeClass("bottomArrowImage");
      }
      $(layerName).css("top", topPos ).css("left", leftPos);
      $(layerName).css("visibility","visible");
      $("#" + event.target.id).addClass( $("#" + event.target.id).attr("class") + "Active");
      $(layerName).bind("mouseleave", function(){
        $(layerName).css("visibility","hidden");
        $(layerName).css("top","-500px");
        $(layerName).css("left","-500px");
        $("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete").removeClass("dialogButtonShareActive").removeClass("dialogButtonDownloadActive").removeClass("dialogButtonFavoriteActive").removeClass("dialogButtonDeleteActive");
        $(".dialogbox").unbind("mouseleave", function(){});
      });
      return false;
    },
    function (event) {
      if( $(event.relatedTarget).attr("class") != "bottomArrowImage" && $(event.relatedTarget).attr("class") != "bottomArrowImageRight" && $(event.relatedTarget).attr("class") != "bottomBorder" && $(event.relatedTarget).attr("class") != "dialogbox" ) {
        var layerName = "#" + event.target.id + "Layer";
        $(layerName).css("visibility","hidden");
        $(layerName).css("top","-500px");
        $(layerName).css("left","-500px");
        $("a.dialogButtonShare, a.dialogButtonDownload, a.dialogButtonFavorite, a.dialogButtonDelete").removeClass("dialogButtonShareActive").removeClass("dialogButtonDownloadActive").removeClass("dialogButtonFavoriteActive").removeClass("dialogButtonDeleteActive");
      }
      return false;
    }
  );
// ******** PREPARE DIALOG BOXES END ******** //
});
//document.ready end


// ******** NAVIGATION START ******** //
var salesNavigationButtonWidth, salesNavigationLayerElement, salesNavigationButtonElement;

function closeSalesNavLayer(buttonWidth, layerElement, buttonElement) {
  $(".sales_navigation_dropdown").hide();
  resetToggle("a.sales_navigation_selectbox");
  buttonElement.css("width",buttonWidth);
 layerElement.hide();
}

function resetToggle(selector,currentObject) {
  $(selector).each(function() {
    if(currentObject != this) {
      this.lastToggle = undefined;
    }
  });
}

function replaceParameterInLink(linkId, oldValue1, newValue1, oldValue2, newValue2, originalPattern) {
  var newLink = originalPattern.replace(oldValue1, newValue1);
  newLink = newLink.replace(oldValue2, newValue2);

  if(newLink.indexOf("http://") == -1) {
    newLink = getWcmsPrefix() + newLink;
  }


  $("#"+ linkId).attr("href", newLink);
}

function zipCodeSearchAction(url, target) {
  if(document.contact_search_form.zipcode.value) {
    if(confTrackingEnabled) {
      var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_zipcode.html") + "?source=" + self.location.pathname + "&zipcode=" + document.contact_search_form.zipcode.value;
      trackAbsolute(trackingUrl);
    }
    url = url.replace("{zipcode}",document.contact_search_form.zipcode.value);
    if(target == "_self") {
      self.location.href = getWcmsPrefix() + url;
    }
    else {
      window.open(target, url);
    }
  }
}

function vehicle_navigation_teaser_init() {
 if(!hideTeaser){
 if(vehicle_navigation_teaser_page_db.length>0){
  dbToUse=vehicle_navigation_teaser_page_db;
 }else{
  dbToUse=vehicle_navigation_teaser_db;
 }
  var teaser_number = (dbToUse.length - 1) * (Math.random());
  teaser_number = Math.round(teaser_number);
  try{
    if(vehicle_navigation_teaser != "r" && vehicle_navigation_teaser <= dbToUse.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(dbToUse.length < new_teaser_number + 1) {
    new_teaser_number = 0;
  }
  var teaser_class = "";
  var teaser_class2 = "standard";
  if (dbToUse[teaser_number][5] == "true") {
    teaser_class = "highlight_link";
    teaser_class2 = "standard highlight_link";
  }

  if(dbToUse[teaser_number][4].indexOf('/connecteddrive/2010/model_selector/index.html') != -1) {
    teaser_class2 = "teaser_link_cd_model_selector";
  }

  var onClickCode = "";
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/teaser_showroom.html") + "?source=" + self.location.pathname + "&target=" + encodeURIComponent(dbToUse[teaser_number][4]);
    onClickCode = "trackAbsolute('" + trackingUrl + "','');";
  }

  var url = dbToUse[teaser_number][4];
  var target = '_blank';
  if(url.indexOf('javascript:') != -1) {
  	target = '';
	}
  if(url.indexOf('http://') == -1 && url.indexOf('javascript:') == -1) {
    url = getWcmsPrefix() + url;
    target = '';
  }


  var code = '          <strong>' + dbToUse[teaser_number][2] + '</strong>\n' +
             '          <div id="teaser_image">\n' +
             '            <a id="vehicle_navigation_teaser_stage" href="' + url + '" target="' + target + '" onclick="' + onClickCode + '" class="' + teaser_class + '"><img src="' + getWcmsPrefix() + dbToUse[teaser_number][0] + '" width="176" height="90" alt=""></a>\n';

  if(dbToUse.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;' + dbToUse.length + '</span>\n' +
             '            </div>\n';
  }
     code += '          </div>\n' +
             '          <div id="teaser_text">\n' +
             '            <a href="' +  url + '" style="display:block" target="' + target + '" onclick="' + onClickCode + '" class="' + teaser_class2 + '"><span>' + dbToUse[teaser_number][3] + '</span></a>\n' +
             '          </div>\n';

  $("#vehicle_navigation #teaser").html(code);

  if(dbToUse[teaser_number][1] != "") {
    var vehicle_navigation_teaser_flash = new SWFObject(getWcmsPrefix() + dbToUse[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';
  }

    var url = vehicle_navigation_teaser_db[teaser_number][4];
    var target = '_blank';
    if(url.indexOf('javascript:') != -1) {
    	target = '';
  	}
    if(url.indexOf('http://') == -1 && url.indexOf('javascript:') == -1) {
      url = getWcmsPrefix() + url;
      target = '';
    }


     code += '          <div id="teaser_text">\n' +
             '            <strong>' + vehicle_navigation_teaser_db[teaser_number][2] + '</strong>\n' +
             '            <div style="height:3px;"></div>\n' +
             '            <a href="' +  url + '" target="' + target + '" 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","#1d6ad4");
      success = true;
    }
  })

  if(!success) {
    $('#vehicle_navigation ul a').each(function() {
      var naviLinkFolder = extractFolders($(this).attr("href"));
      if(naviLinkFolder[1] == pageFolder[0] && naviLinkFolder[2] == pageFolder[1] && success == false) {
        $(this).css("color","#1d6ad4");
        success = true;
      }
    })
  }
}


function highlightMgmbHPageNavigation() {
  var success = false;
  var pageFolder = extractFolders(self.location.href);
  $('#overview_linklist div a').each(function() {
    var naviLinkFolder = extractFolders($(this).attr("href"));
    if(naviLinkFolder[1] == pageFolder[1] && naviLinkFolder[2] == pageFolder[2] && success == false) {
      $(this).css("color","#1d6ad4");
      success = true;
    }
  })

  if(!success) {
    $('#overview_linklist div a').each(function() {
      var naviLinkFolder = extractFolders($(this).attr("href"));
      if(naviLinkFolder[1] == pageFolder[0] && naviLinkFolder[2] == pageFolder[1] && success == false) {
        $(this).css("color","#1d6ad4");
        success = true;
      }
    })
  }
}

function extractFolders(myString) {
  var splitArray  = myString.split("/");
  var resultArray = new Array(splitArray[splitArray.length - 4], splitArray[splitArray.length - 3], splitArray[splitArray.length - 2]);
  return resultArray;
}


function salesNaviTrackingConfigure() {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_configure.html") + "?source=" + self.location.pathname + "&model=" + sales_navigation_configuration_last_value_model + "&color=" + sales_navigation_configuration_last_value_color;
    trackAbsolute(trackingUrl);
  }
}

function salesNaviTrackingAccessory() {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_accessory.html") + "?source=" + self.location.pathname + "&model=" + sales_navigation_configuration_last_value_model + "&color=" + sales_navigation_configuration_last_value_color;
    trackAbsolute(trackingUrl);
  }
}

function salesNaviTrackingCompare() {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_compare.html") + "?source=" + self.location.pathname + "&model1=" + sales_navigation_compare_last_value_1 + "&model2=" + sales_navigation_compare_last_value_2;
    trackAbsolute(trackingUrl);
  }
}

function salesNaviTrackingLink(url) {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/sales_navigation_link.html") + "?source=" + self.location.pathname + "&target=" + url;
    trackAbsolute(trackingUrl);
  }
}


// ******** NAVIGATION END ******** //


// ******** Highlights page START ******** //

function highlightsCloseHighlightLink() {
  if(typeof(close_back_link_url_default) != "undefined") {
    var targetUrl = close_back_link_url_default;
    if(typeof(close_back_link_pattern) != "undefined" && typeof(close_back_link_url_individual) != "undefined") {
      if(document.referrer.indexOf(close_back_link_pattern) != -1) {
        targetUrl = close_back_link_url_individual;
      }
    }
    self.location.href = targetUrl;
  }
}

// ******** Highlights page END ******** //

// ******** Start page START ******** //
function startPageShowHeadlines() {
  $("#start_headlines").show();
}
function startPageHideHeadlines() {
  $("#start_headlines").hide();
}

// ******** Start page END ******** //


// ******** Highlight page START ******** //

function initHighlightPage(){
  mainNavigation.initFolding( 10, 20 );
  flashObject.write("highlightsMainContainer");
  $("#highlightsMainContainer").show();
  co2DisclaimerCheck();
  if($("#co2Disclaimer h4").height() > 15){
    $("#co2DisclaimerContent").height("65px");
  }
  setTimeout(function(){
    $("#co2Disclaimer").hide();
  }, 30000);
  $("#closeCo2Disclaimer").click(function(){
    if($("#co2Disclaimer h4").height() > 15){
      $("#co2DisclaimerContent").height("65px");
    }
    $("#co2Disclaimer").hide();
    if(co2DisclaimerCookieName) {
      setCookie(co2DisclaimerCookieName, "true", "", "/");
    }
  });

  if(confTrackingEnabled) {
    $("#highlightDownloadDialogLayer a").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( trackingPages["download"][0] ) + '?file=' + escape( buildValidServerRelativeUrl($(this).attr("href"))) + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
  }
}

// ******** Highlight page END ******** //


// ******** Content page START ******** //
function contentPageChangeTeaser(){
  saveContentTeaserHTML = $("#contentTeaser" + activeContentTeaser).html();
  $("#contentTeaser" + activeContentTeaser).html($("#contentTeaser0").html());
  $(".mediaStage").hide();
  $("#mediaStage" + activeContentTeaser).show();
  if(mediaType[activeContentTeaser]["type"] == "flash"){
    stageFlash = new SWFObject(mediaType[activeContentTeaser]["url"], "mainFlashMovie", "687", "250", "9.0.115", "#ffffff");
    stageFlash.addParam("quality","autohigh");
    stageFlash.addParam("allowScriptAccess", "sameDomain");
    stageFlash.addParam("wmode", "transparent");
    teaseFlashObject = stageFlash.write("mediaContainer" + activeContentTeaser);
    if(teaseFlashObject){
      var contentPageFolderPath = self.location.pathname.substring(0,self.location.pathname.lastIndexOf("/"));
      var contentPageClickEventPath = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/click_event.html";
      var trackingUrl = buildValidServerRelativeUrl( contentPageClickEventPath ) + '?target=' + escape(contentPageFolderPath + '/film_' + activeContentTeaser + '/start.html') + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
    }
  }else if(mediaType[activeContentTeaser]["type"] == "video"){
    stageFlash = new SWFObject(mediaType[activeContentTeaser]["player"], "mainFlashMovie", "687", "250", "9.0.115", "#ffffff");
    stageFlash.addParam("quality","autohigh");
    stageFlash.addParam("allowScriptAccess", "sameDomain");
    stageFlash.addParam("wmode", "transparent");
    stageFlash.addVariable("prm_flv_url", mediaType[activeContentTeaser]["url"]);
    stageFlash.addVariable("prm_corelib", mediaType[activeContentTeaser]["corelib"]);
    stageFlash.addVariable("prm_components", mediaType[activeContentTeaser]["components"]);
    stageFlash.addVariable("prm_stage_width", "687");
    stageFlash.addVariable("prm_stage_height", "250");
    stageFlash.addVariable("prm_tracking_enabled", "true");
    stageFlash.addVariable("prm_version", "high");
    teaseFlashObject = stageFlash.write("mediaContainer" + activeContentTeaser);
    if(teaseFlashObject){
      var contentPageClickEventPath = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/click_event.html";
      var trackingUrl = buildValidServerRelativeUrl( contentPageClickEventPath ) + '?target=' + escape(contentPageFolderPath + '/film_' + activeContentTeaser + '/start.html') + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
    }
  }else if(mediaType[activeContentTeaser]["type"] == "ani"){
    currentAnimationImage = 0;
    maxAnimationImage = $("#mediaContainer" + activeContentTeaser + " .animationContainer .animationImage").size()-1;
    window.clearTimeout(contentPageAnimationTimer);
    contentPageAnimationTimer = null;
    contentPageAnimationTimer = window.setTimeout("contentPageAnimateImages('next')", 1500);
  }
}

function contentPageAnimateImages(direction){
  $("#mediaContainer" + activeContentTeaser + " .animationImage:eq(" + currentAnimationImage+ ")").fadeOut(1000);
  if(direction == "next"){
    if(currentAnimationImage < maxAnimationImage){
      currentAnimationImage++;
    }else{
      currentAnimationImage = 0;
    }
  }else{
    if(currentAnimationImage > 0){
      currentAnimationImage--;
    }else{
      currentAnimationImage = maxAnimationImage;
    }
  }
  $("#mediaContainer" + activeContentTeaser + " .animationCounter").html((currentAnimationImage<9?"0":"") + (currentAnimationImage+1) + " / " + (maxAnimationImage<9?"0":"")+ (maxAnimationImage+1));
  $("#mediaContainer" + activeContentTeaser + " .animationImage:eq(" + currentAnimationImage+ ")").fadeIn(1000,function(){
    if(contentPageAnimationTimer != null){
      contentPageAnimationTimer = window.setTimeout("contentPageAnimateImages('next')", 3000);
    }
  });
}

var contentPageAnimationTimer = null;
var contentPageControlerTimer = null;
var currentAnimationImage = 0;
var maxAnimationImage = 0;

function initContentPage(){

    co2DisclaimerCheck();
    if($("#co2DisclaimerBg h4").height() > 15){
      $("#co2DisclaimerContent").height("67px");
    }
    setTimeout(function(){
      $("#co2Disclaimer").hide();
    }, 30000);
    $("#co2DisclaimerReopenLink").click(function(){
      $("#co2Disclaimer").show();
      if($("#co2Disclaimer h4").height() > 15){
        $("#co2DisclaimerContent").height("65px");
      }
    });
    $("#closeCo2Disclaimer").click(function(){
      $("#co2Disclaimer").hide();
      if(co2DisclaimerCookieName) {
        setCookie(co2DisclaimerCookieName, "true", "", "/");
      }
    });

    $("#contentText #moreContent").click(function(){
      $("#downloadDialog" + activeContentTeaser).hide();
      $(this).hide();
      $("#contentPageContainer #contentText p").height("auto");
      $("#contentPageContainer #contentText").animate({
        top: "10px",
        paddingTop:"23px",
        height: "357px"},
        "normal",
        "swing",
        function(){
          $("#contentPageContainer .hiddenLongText").slideDown(
            "normal",
            function(){
              shareUrl = self.location.href;
              shareTitle = document.title;
              $("#lessContent").show();
            });
        }
      );

      $("#contentPageContainer #contentTeaserList").attr("topPos", $("#contentPageContainer #contentTeaserList").css("top") );
      var contentTeaserListTop = "55px";
      if($("#contentTeaserList").hasClass("zeroTeaser")){
        contentTeaserListTop = "46px"
      }
      $("#contentPageContainer #contentTeaserList").animate({
        top: contentTeaserListTop},
        "normal",
        "swing"
      );
    });

    $("#contentText #lessContent").click(function(){
      $(this).hide();
      $("#contentPageContainer .hiddenLongText").slideUp(
        "normal",
        function(){
          $("#contentPageContainer #contentText").animate({
            top: "261px",
            paddingTop:"6px",
            height: "133px"},
            "normal",
            "swing",
            function(){
              $("#contentPageContainer #contentText p").height("62px");
              $("#moreContent").show();
              if($("#downloadDialog" + activeContentTeaser + "Layer li").size() != 0){
                $("#downloadDialog" + activeContentTeaser).show();
              }
              shareUrl = self.location.href;
              shareTitle = document.title;
              self.location.href = "#media" + activeContentTeaser;
            }
          );
         $("#contentPageContainer #contentTeaserList").animate({
          top: $("#contentPageContainer #contentTeaserList").attr("topPos")},
          "normal",
          "swing"
        );
        }
      );
    });

    $("#contentTeaserList .contentTeaser img").hover(function(){$(this).next().children().addClass("active")},function(){$(this).next().children().removeClass("active")});

    $("#contentTeaserList .contentTeaser").each(function(i, e){

      $(this).click(function(){
        shareUrl = self.location.href;
        shareTitle = document.title;
        if($("#contentPageContainer #contentTeaserList").css("top") == "55px"){
          $("#lessContent").click();
        }
        if(mediaType[activeContentTeaser]["type"] == "flash" && teaseFlashObject){
          $("#mediaContainer" + activeContentTeaser).html("")
        }
        if(activeContentTeaser != 0){
          $("#contentTeaser" + activeContentTeaser).html(saveContentTeaserHTML);
        }
        if(activeContentTeaser == i){
          activeContentTeaser = 0;
        }else{
          activeContentTeaser = i;
        }
        self.location.href = "#media" + activeContentTeaser;
        contentPageChangeTeaser();
      });
    });

    if(self.location.href.indexOf("#more") != -1){
      if($("#moreContent").html() != null){
        $("#contentPageContainer #contentTeaserList").attr("topPos", $("#contentPageContainer #contentTeaserList").css("top") );
        $("#contentPageContainer #contentText").addClass("more");
        $("#contentPageContainer #contentTeaserList").addClass("more");
        $("#contentPageContainer #contentText p").height("auto");
        $("#contentPageContainer .hiddenLongText").show();
        $("#contentText #moreContent").hide();
        $("#contentText #lessContent").show();
      }
    }

    if(self.location.href.indexOf("#media") != -1 && typeof(activeContentTeaser) != "undefined"){
      activeContentTeaser = self.location.href.substring(self.location.href.indexOf("#media")+6);
      if(($("#mediaStageSingle").html() == null) && (activeContentTeaser < mediaType.length)){
        contentPageChangeTeaser();
      }
    }

    if(mediaType.length > 0){
      if((mediaType[activeContentTeaser]["type"] == "flash") || (mediaType[activeContentTeaser]["type"] == "video")){
        contentPageChangeTeaser();
      }
    }

    for(i=0; i < 4; i++) {
      if($("#downloadDialog" + i + "Layer li").size() != 0){
        $("#mediaStage" + i + " .contentDownloadLink").show();
      }
    }

      if((mediaType.length > 0) && (mediaType[activeContentTeaser]["type"] == "ani")){
        maxAnimationImage = $("#mediaContainer" + activeContentTeaser + " .animationContainer .animationImage").size()-1;
        $("#mediaContainer" + activeContentTeaser + " .animationCounter").html("0" + (currentAnimationImage+1) + " / 0" + (maxAnimationImage+1));

        var animationContainerIsAnimated1 = false;
        var animationContainerIsAnimated2 = false;

        $(".mediaContainer .animationContainer").mouseenter(function(){
          if(!animationContainerIsAnimated1){
            animationContainerIsAnimated1 = true;
            $("#mediaContainer" + activeContentTeaser + " .animationControl").animate(
              {top:"225px"},
              500,
              "swing",
              function(){
                animationContainerIsAnimated1 = false;
              }
            );
          }
        });

        $(".mediaContainer .animationContainer").mouseleave(function(){
          if(!animationContainerIsAnimated2){
            animationContainerIsAnimated2 = true;
            contentPageControlerTimer = setTimeout(function(){
              $("#mediaContainer" + activeContentTeaser + " .animationControl").animate({
                top:"260px"},
                500,
                "swing",
                function(){
                  animationContainerIsAnimated2 = false;
                  window.clearTimeout(contentPageControlerTimer);
                }
              )}, 100);
            }
          }
        );

        $(".mediaContainer .animationPause").click(function(){
          window.clearTimeout(contentPageAnimationTimer);
          contentPageAnimationTimer = null;
          $("#mediaContainer" + activeContentTeaser + " .animationPause").hide();
          return false;
        });

        $(".mediaContainer .animationPlay").click(function(){
          $("#mediaContainer" + activeContentTeaser + " .animationPause").show();
          contentPageAnimationTimer = window.setTimeout("contentPageAnimateImages('next')", 1000);
          return false;
        });

        $(".mediaContainer .animationNext").click(function(){
          window.clearTimeout(contentPageAnimationTimer);
          contentPageAnimationTimer = null;
          $("#mediaContainer" + activeContentTeaser + " .animationPause").hide();
          contentPageAnimateImages("next")
          return false;
        });

        $(".mediaContainer .animationPrevious").click(function(){
          window.clearTimeout(contentPageAnimationTimer);
          contentPageAnimationTimer = null;
          $("#mediaContainer" + activeContentTeaser + " .animationPause").hide();
          contentPageAnimateImages("previous")
          return false;
        });
        contentPageAnimationTimer = window.setTimeout("contentPageAnimateImages('next')", 1000);
      } // type == ani


// add tracking
  if(confTrackingEnabled) {
    var contentPageFolderPath = self.location.pathname.substring(0,self.location.pathname.lastIndexOf("/"));
    var contentPageName = self.location.href.substring(self.location.href.lastIndexOf("/"), self.location.href.indexOf(".htm"));
    var contentPageClickEventPath = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/click_event.html";
    var contentPageDownloadPath   = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/download.html";
    var contentPageRelatedPath    = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/related.html";

    $("#relatedLinks ul li a:not(#co2DisclaimerReopenLink)").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( contentPageRelatedPath ) + '?target=' + escape( buildValidServerRelativeUrl($(this).attr("href"))) + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
    $("div[id^='downloadDialog'] ul li a").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( contentPageDownloadPath ) + '?file=' + escape( buildValidServerRelativeUrl($(this).attr("href"))) + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
    $("a#moreContent").click(function () {
      var trackingUrl = buildValidServerRelativeUrl(contentPageFolderPath + contentPageName + '/read_more.html');
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
    $("#contentTeaserList .contentTeaser").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( contentPageClickEventPath ) + '?target=' + escape(contentPageFolderPath + '/contentTeaser' + activeContentTeaser + '.html') + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
  }
}// initContentPage

// ******** Content page END******** //

// ******** Favorites page START ******** //
function showFavorites() {
  var favoritesValidCounter = 0;
  var favoritesSavedArray = new Array();
  favoritesSavedArray = favoritesSaved();
  if(typeof(favoriteData) != "undefined" || favoritesSavedArray.length > 0) {

    for(i = 0; i < favoritesSavedArray.length; i++) {
      if(favoriteData[favoritesSavedArray[i]]) {
        favoritesValidCounter++;
      }
    }
  if(favoritesValidCounter > 0) {
    var categories = new Array();
    var oldCat = "";
    var cat = "";
    for(i = 0; i < favoritesSavedArray.length; i++) {
      if( favoriteData[favoritesSavedArray[i]] ) {
        cat = favoriteData[favoritesSavedArray[i]][0];
        if(cat != oldCat) {
          categories.push(cat);
          oldCat = cat;
        }
      }
    }
    categories = arrayUnique(categories);
    categories.sort();
    var code = "";
    var code  = '<div id="favoritesGalleryLayer">\n';
    for(i = 0; i < categories.length; i++) {
      code += '<div class="category" style="clear:both;">\n' +
              '  <span class="headline">' + categories[i] + '</span>\n';
      for (y = 0;  y < favoritesSavedArray.length; y++) {
        if(favoriteData[favoritesSavedArray[y]]) {
          if(favoriteData[favoritesSavedArray[y]][0] == categories[i]) {
            var favUrl = favoriteData[favoritesSavedArray[y]][1];
            var favThumbUrl = favoriteData[favoritesSavedArray[y]][2];
            var favDescription = favoriteData[favoritesSavedArray[y]][3];
            code += '<div class="favoritesBoxContainer">\n' +
                  '  <div class="favoritesThumbContainer">\n' +
                  '    <div id="mediaStageSingle" class="mediaStage">\n' +
                  '      <a href="' + getWcmsPrefix() + favUrl + '" onclick="trackFavoriteClick(\'' + favUrl + '\')">\n' +
                  '        <img src="' + getWcmsPrefix()+ favThumbUrl + '" width="110" height="62" alt="">\n' +
                  '      </a>\n' +
                  '    </div>\n' +
                  '    <div class="closefavoritesBox">\n' +
                  '      <a href="" onclick="favoriteDelete(\'' + favoritesSavedArray[y] + '\');self.location.reload();return false;" class="dialogButtonDelete" id="deleteDialog">&nbsp;</a>\n' +
                  '    </div>\n' +
                  '  </div>\n' +
                  '  <div class="favoritesContentText">\n' +
                  '    <p>' + favDescription + '</p>\n' +
                  '  </div>\n' +
                  '</div>\n';

          }
        }
      }
      code += '</div>\n';
    }
    code += '</div>\n';
    $("#favoritesDiv").html(code);
  }
  else  {
     var code = '<div id="favoritesGalleryLayer">\n' +
                '  <div class="categoryFirst">\n' +
                '    <span class="headline">' + favoritesHeadline + '</span>\n' +
                '      <p style="width:405px;">' + favoritesCopytext + '</p> \n' +
                '  </div>\n' +
                '</div>\n';
     $("#favoritesDiv").html(code);
   }
}  else  {
     var code = '<div id="favoritesGalleryLayer">\n' +
                '  <div class="categoryFirst">\n' +
                '    <span class="headline">' + favoritesHeadline + '</span>\n' +
                '      <p style="width:405px;">' + favoritesCopytext + '</p> \n' +
                '  </div>\n' +
                '</div>\n';
     $("#favoritesDiv").html(code);
   }
}

function trackFavoriteClick(favUrl) {
  if(confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl("/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/bookmark.html") + "?url=" + favUrl + "&action=bookmark_select";
    trackAbsolute(trackingUrl,'');
  }
}
// ******** Favorites page END ******** //


// ******** media gallery page START ******** //
function mediaGalleryInitialise() {
  var lightboxAnimation, thisParameterNumber, visibleLightboxObjectNumber, newCategoryLayerHeight, newIconLayerTop;
  var $imageObj = $('div#mediaGalleryLightboxLayer div#lightbox img#bigImage');
  var $flashObj = $('div#mediaGalleryLightboxLayer div#lightbox div#flashLayer');
  var startPageTitle = document.title;
  var startPageUrl = self.location.href;

  if(confTrackingEnabled) {
    var contentPageDownloadPath   = "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/shared/tracking_redirect/download.html";
    $("div#mediaGalleryLightboxLayer div.downloadLayer ul.linklist li a").click(function () {
      var trackingUrl = buildValidServerRelativeUrl( contentPageDownloadPath ) + '?file=' + escape( buildValidServerRelativeUrl($(this).attr("href"))) + '&source=' + escape(self.location.pathname);
      trackAbsolute(trackingUrl, '', false, false);
      return true;
    });
  }

  function mediaGallerySetCategoryLayerHeight() {
    newCategoryLayerHeight = Math.round($('div#sales_navigation').offset().top - $('div#mediaGalleryCategoriesLayer').offset().top - 42);
    newIconLayerTop = Math.round($('div#sales_navigation').offset().top + 14);
    $('div#mediaGalleryCategoriesLayer').css('height',newCategoryLayerHeight+'px');
    $('div#mediaGalleryDialogButtons').css('top',newIconLayerTop+'px');
  }
  mediaGallerySetCategoryLayerHeight();
  $(window).resize(function() {
    mediaGallerySetCategoryLayerHeight();
  });

  $("a#sales_navigation_button_favs").mouseover(function() {
    var newHeight = Math.round($('div#sales_navigation').offset().top - $('div#mediaGalleryCategoriesLayer').offset().top - 63);
    var newTop = Math.round($('div#sales_navigation').offset().top - 41);
    $('div#mediaGalleryCategoriesLayer').css('height',newHeight+'px');
    $('div#mediaGalleryDialogButtons').css('top',newTop+'px');
  });
  $('div#sales_navigation_layer_favs').mouseout(function() {
    $('div#mediaGalleryCategoriesLayer').css('height',newCategoryLayerHeight+'px');
    $('div#mediaGalleryDialogButtons').css('top',newIconLayerTop+'px');
  });

  $('div.category img').each(function(i) {
    if(lightboxContent[i]["subheadline"] != '') {
      $('div.category div.thumbImageBox').parent().addClass('hasSubheadline');
    }
  }).mousemove(function(e) {
    $('div.dialogbox').each(function(i) {
      $('div#mediaGalleryThumbnailsMouseoverLayer'+i).css({
        left: Math.round(e.pageX - 10) + 'px',
        top: Math.round(e.pageY - $('div#mediaGalleryThumbnailsMouseoverLayer'+i).height() - 5) + 'px'
      });
    });
  }).hover(
    function() {
      var thisThumbImage = $('div.category img').index(this);
      if(lightboxContent[thisThumbImage]["hoverText"] != '') {
        $('div#mediaGalleryThumbnailsMouseoverLayer'+thisThumbImage).css('visibility','visible');
      }
    },
    function() {
      $('div.dialogbox').css('visibility','hidden');
    }
  );

  $('div.category').each(function(i) {
    if($(this).hasClass('hasSubheadline')) {
      var newCategoryHeight = $('div.category:eq('+ i +')').children().next().height();
      $('div.category:eq('+ i +')').css('height',newCategoryHeight+'px');
    }
  });

  function mediaGalleryShareIconIsDisplayedCheck() {
    if(typeof(share_services_active) == "boolean" &&  share_services_active) {
      if($('a.dialogButtonShare').attr('id') == 'shareDialog') {
        $('a.dialogButtonShare').attr('id','');
      }
      if($('div#mediaGalleryLightboxLayer div#lightbox').is(':visible')) {
        $('div#mediaGalleryDialogButtons a.dialogButtonShare, div#textLayer img.shareButton').hide();
        $('div#textLayer a.dialogButtonShare').attr('id','shareDialog');
        $('div#mediaGalleryDialogButtons img.shareButton, div#textLayer a.dialogButtonShare').show();
        shareUrl = self.location.href;
        shareTitle = document.title;
      } else {
        $('div#mediaGalleryDialogButtons img.shareButton, div#textLayer a.dialogButtonShare').hide();
        $('div#mediaGalleryDialogButtons a.dialogButtonShare').attr('id','shareDialog');
        $('div#mediaGalleryDialogButtons a.dialogButtonShare, div#textLayer img.shareButton').show();
        shareUrl = startPageUrl;
        shareTitle = startPageTitle;
      }
    } else {
      $('a.dialogButtonShare, img.shareButton').hide();
    }
  }
  mediaGalleryShareIconIsDisplayedCheck();

  function mediaGalleryInitLightbox() {
    $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer').children().remove();
    $('div#mediaGalleryLightboxLayer div#lightbox').css({
      left: Math.round(($('div#stage').width() - ($('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left))/2 + $('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left) + 'px',
      top: Math.round(($('div#stage').height() - $('div#mainNavigation').height() - $('div#sales_navigation').height())/2 + $('div#mainNavigation').height()) + 'px',
      width: '1px',
      height: '1px'
    });

    $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').hover(
      function() {
        $('div#mediaGalleryLightboxLayer img.leftWhiteArrow').css('display','none');
        $('div#mediaGalleryLightboxLayer img.leftBlueArrow').css('display','block');
      },
      function() {
        $('div#mediaGalleryLightboxLayer img.leftBlueArrow').css('display','none');
        $('div#mediaGalleryLightboxLayer img.leftWhiteArrow').css('display','block');
      }
    );
    $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').hover(
      function() {
        $('div#mediaGalleryLightboxLayer img.rightWhiteArrow').css('display','none');
        $('div#mediaGalleryLightboxLayer img.rightBlueArrow').css('display','block');
      },
      function() {
        $('div#mediaGalleryLightboxLayer img.rightBlueArrow').css('display','none');
        $('div#mediaGalleryLightboxLayer img.rightWhiteArrow').css('display','block');
      }
    );

    $('div.category img').each(function(i) {
      var lightboxContentWidth = lightboxContent[i]["width"];
      var lightboxContentHeight = lightboxContent[i]["height"];
      if(lightboxContentWidth > 612 || lightboxContentHeight > 383) {
        var differenceValue = (lightboxContentWidth > 612) ? Math.round(lightboxContentWidth - 612) : Math.round(lightboxContentHeight - 383);
        lightboxContent[i]["width"] = Math.round(lightboxContentWidth - differenceValue);
        lightboxContent[i]["height"] = Math.round(lightboxContentHeight - differenceValue);
        if(lightboxContent[i]["width"] > 612 || lightboxContent[i]["height"] > 383) {
          var differenceValue = (lightboxContent[i]["width"] > 612) ? Math.round(lightboxContent[i]["width"] - 612) : Math.round(lightboxContent[i]["height"] - 383);
          lightboxContent[i]["width"] = Math.round(lightboxContent[i]["width"] - differenceValue);
          lightboxContent[i]["height"] = Math.round(lightboxContent[i]["height"] - differenceValue);
        }
      }
    });
  }
  mediaGalleryInitLightbox();

  for(i=0; i < $('div.category img').length; i++) {
    $('div.category img:eq('+ i +')').wrap('<a href="#mediaID-'+ i +'" onfocus="this.blur();"></a>');
  }

  function mediaGalleryWriteLightboxContentObject(nbr, arrowFunc) {
    $('div#mediaGalleryLightboxLayer div#lightbox').removeClass("lightboxNoPreloader");
    switch (lightboxContent[nbr]["type"]) {
      case 'image':
        $imageObj.attr({src: lightboxContent[nbr]['src'], width: lightboxContent[nbr]["width"], height: lightboxContent[nbr]["height"], alt: ""});
        break;
      case 'embed':
        $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer').children().remove();
        var embedObjContent = '';
        embedObjContent += '<object id="videoLayer" width="'+ lightboxContent[nbr]["width"] +'" height="'+ lightboxContent[nbr]["height"] +'">\r\n';
        embedObjContent += '  <param name="FlashVars" value="'+ lightboxContent[nbr]["embedParameter"] +'" />\r\n';
        embedObjContent += '  <param name="movie" value="'+ lightboxContent[nbr]["src"] +'" />\r\n';
        embedObjContent += '  <param name="wmode" value="transparent" />\r\n';
        embedObjContent += '  <embed src="'+ lightboxContent[nbr]["src"] +'" type="application/x-shockwave-flash" wmode="transparent" width="'+ lightboxContent[nbr]["width"] +'" height="'+ lightboxContent[nbr]["height"] +'" allowfullscreen="false" FlashVars="'+ lightboxContent[nbr]["embedParameter"] +'" />\r\n';
        embedObjContent += '</object>\r\n';
        $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer').html(embedObjContent);
        $('div#mediaGalleryLightboxLayer div#lightbox object#videoLayer').attr({width: lightboxContent[nbr]["width"], height: lightboxContent[nbr]["height"]});
        break;
      case 'flash':
        $('div#mediaGalleryLightboxLayer div#lightbox').addClass("lightboxNoPreloader");
        var flashLayer = new SWFObject(lightboxContent[nbr]["src"], "bmw_video", String(lightboxContent[nbr]["width"]), String(lightboxContent[nbr]["height"]), "9.0.115", "#ffffff");
        flashLayer.addParam("quality", "autohigh");
        flashLayer.addParam("allowScriptAccess", "sameDomain");
        flashLayer.addParam("wmode", "transparent");
        if(lightboxContent[nbr]["flashParameter"] != 'undefined') {
          flashLayer.addVariable("prm_flv_url", lightboxContent[nbr]["flashParameter"]);
          flashLayer.addVariable("prm_corelib", swf_corelib);
          flashLayer.addVariable("prm_components", swf_components);
          flashLayer.addVariable("prm_stage_width", String(lightboxContent[nbr]["width"]));
          flashLayer.addVariable("prm_stage_height", String(lightboxContent[nbr]["height"]));
          flashLayer.addVariable("prm_tracking_enabled", "true");
          flashLayer.addVariable("prm_version", "high");
        }
        flashLayer.write("flashLayer");
        break;
      default:
        break;
    }

    if(arrowFunc == 'true') {
      switch (lightboxContent[nbr]["type"]) {
        case 'image':
          $imageObj.fadeIn(200);
          break;
        case 'flash':
          $('div#flashLayer').css('display','block');
          break;
        default:
          break;
      }
      shareUrl = self.location.href;
      shareTitle = document.title;
      mediaGalleryReadImageParameter();
      initArrowLinks(nbr); /* visibleLightboxObjectNumber */
    }
  }

  function mediaGalleryHandleLayerVisibility() {
    $('div#lightbox > *').hide();
    $('div#lightbox div#closeButtonLayer, div#lightbox div#textLayer, div#mediaGalleryLightboxLayer img.leftWhiteArrow, div#mediaGalleryLightboxLayer img.rightWhiteArrow').show();
    if(lightboxContent[visibleLightboxObjectNumber]["type"] == 'image') {
      $imageObj.show();
    } else if(lightboxContent[visibleLightboxObjectNumber]["type"] == 'flash') {
      $flashObj.show();
    } else if(lightboxContent[visibleLightboxObjectNumber]["type"] == 'embed') {
      $('div#embedLayer').show();
    }
    mediaGalleryShareIconIsDisplayedCheck();
    initDownloadLinkList();
    lightboxAnimation = "finished";
  }

  if(startPageUrl.indexOf("?media_id=") != -1) {
    startPageUrl = startPageUrl.replace("?media_id=", "#");
    self.location.href = startPageUrl;
  }

  function mediaGalleryReadImageParameter() {
    var startNbr = Math.round(self.location.href.lastIndexOf("#mediaID-") + 9);
    var endNbr = (self.location.href.lastIndexOf("?") > self.location.href.lastIndexOf("#mediaID-")) ? self.location.href.lastIndexOf("?") : self.location.href.length;
    thisParameterNumber = ($('div.category img').length - 1 < self.location.href.substring(startNbr, endNbr)) ? 0 : self.location.href.substring(startNbr, endNbr);
  }

  if(self.location.href.lastIndexOf('#') != -1) {
    var titleEndNbr = document.title.lastIndexOf('#');
    document.title = document.title.slice(0, titleEndNbr);
    if(self.location.href.lastIndexOf("#mediaID-") != -1) {
      mediaGalleryReadImageParameter();
      for(i=0; i < lightboxContent.length; i++) {
        if(lightboxContent[i]['parameter'] == '#mediaID-'+thisParameterNumber) {
          visibleLightboxObjectNumber = i;
        }
        lightboxContent[i]["isVisible"] = 'false';
      }
      lightboxContent[visibleLightboxObjectNumber]["isVisible"] = 'true';
      initArrowLinks(visibleLightboxObjectNumber);
      $('div.downloadLayer').css('display','none');
      $('div.downloadLayer:eq('+ visibleLightboxObjectNumber +')').css('display','block');
      $('div#mediaGalleryLightboxLayer div#lightbox').addClass("lightboxNoPreloader");
      mediaGalleryWriteLightboxContentObject(visibleLightboxObjectNumber, 'false');
      $('div#mediaGalleryLightboxLayer').css('display','block');
      $('div#mediaGalleryLightboxLayer div#blackLayer').css({opacity: '0.5'});
      $('div#mediaGalleryLightboxLayer div#blackLayer').fadeIn(200, mediaGallerySetLightboxPosition(mediaGalleryHandleLayerVisibility,lightboxContent[visibleLightboxObjectNumber]["width"],lightboxContent[visibleLightboxObjectNumber]["height"]));
    } else {
      var endNbr = self.location.href.lastIndexOf('#');
      self.location.href = self.location.href.slice(0, endNbr);
    }
  }

  function mediaGallerySetLightboxPosition(callBackFunction, bigImageWidth, bigImageHeight) {
    $('div#mediaGalleryCategoriesLayer').css('overflow','hidden');
    var lightboxLeft = Math.round(($('div#stage').width() - ($('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left))/2 + $('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left - (bigImageWidth + 20)/2);
    var lightboxTop = Math.round(($('div#stage').height() - $('div#mainNavigation').height() - $('div#sales_navigation').height())/2 + $('div#mainNavigation').height() - (bigImageHeight + 75)/2);
    var lightboxWidth = Math.round(bigImageWidth + 20);
    var lightboxHeight = Math.round(bigImageHeight + 75);
    $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').animate({
      left: Math.round(lightboxLeft - $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').width() - 9) + 'px',
      top: Math.round(lightboxTop + lightboxHeight/2 - $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').height()/2) + 'px'
    }, 400);
    $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').animate({
      left: Math.round(lightboxLeft + lightboxWidth + 9) + 'px',
      top: Math.round(lightboxTop + lightboxHeight/2 - $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').height()/2) + 'px'
    }, 400);
    $('div#mediaGalleryLightboxLayer div#lightbox').animate({
      left: Math.round(($('div#stage').width() - ($('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left))/2 + $('div#vehicle_navigation').width() + $('div#vehicle_navigation').position().left - (bigImageWidth + 20)/2) + 'px',
      top: Math.round(($('div#stage').height() - $('div#mainNavigation').height() - $('div#sales_navigation').height())/2 + $('div#mainNavigation').height() - (bigImageHeight + 75)/2) + 'px',
      width: bigImageWidth + 20 + 'px',
      height: bigImageHeight + 75 + 'px'
    }, 400, callBackFunction);
  }

  function initDownloadLinkList() {
    for(a=0; a < $('div.downloadLayer').length; a++) {
      $('div.downloadLayer:eq('+ a +') ul.linklist').css('display','block');
    }
  }

  $('div#mediaGalleryCategoriesLayer div.category img').click(function() {
    mediaGalleryShareIconIsDisplayedCheck();
    visibleLightboxObjectNumber = $('div.category img').index(this);
    for(i=0; i < lightboxContent.length; i++) {
      lightboxContent[i]["isVisible"] = 'false';
    }
    lightboxContent[visibleLightboxObjectNumber]["isVisible"] = 'true';
    var thisCategoryNumber = lightboxContent[visibleLightboxObjectNumber]["category"];
    document.title = startPageTitle;

    $('div#mediaGalleryLightboxLayer div#lightbox').addClass("lightboxNoPreloader");
    $('div.downloadLayer').css('display','none');
    $('div.downloadLayer:eq('+ visibleLightboxObjectNumber +')').css('display','block');
    mediaGalleryReadImageParameter();
    initArrowLinks(visibleLightboxObjectNumber);
    mediaGalleryWriteLightboxContentObject(visibleLightboxObjectNumber, 'false');
    $('div#mediaGalleryLightboxLayer').css('display','block');
    $('div#mediaGalleryLightboxLayer div#blackLayer').css({opacity: '0.5'});
    $('div#mediaGalleryLightboxLayer div#blackLayer').fadeIn(200, handleLightboxPosition);

    function handleLightboxPosition() {
      mediaGallerySetLightboxPosition(showLightboxContent,lightboxContent[visibleLightboxObjectNumber]['width'],lightboxContent[visibleLightboxObjectNumber]['height']);
    }
    function showLightboxContent() {
      $('div#lightbox div#closeButtonLayer').fadeIn(100);
      $('div#lightbox img, div#mediaGalleryLightboxLayer div#lightbox div#textLayer').fadeIn(300);
      mediaGalleryHandleLayerVisibility();
      $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').css({
        left: Math.round($('div#mediaGalleryLightboxLayer div#lightbox').offset().left - $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').width() - 9) + 'px',
        top: Math.round($('div#mediaGalleryLightboxLayer div#lightbox').offset().top + $('div#mediaGalleryLightboxLayer div#lightbox').height()/2 - $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').height()/2) + 'px'
      });
      $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').css({
        left: Math.round($('div#mediaGalleryLightboxLayer div#lightbox').offset().left + $('div#mediaGalleryLightboxLayer div#lightbox').width() + 9) + 'px',
        top: Math.round($('div#mediaGalleryLightboxLayer div#lightbox').offset().top + $('div#mediaGalleryLightboxLayer div#lightbox').height()/2 - $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').height()/2) + 'px'
      });
      $('div#mediaGalleryLightboxLayer img.leftWhiteArrow, div#mediaGalleryLightboxLayer img.rightWhiteArrow').css('display','block');
    }
  });

  $('div#mediaGalleryLightboxLayer a.closeLink').click(function() {
    $('div#mediaGalleryCategoriesLayer').css('overflow','auto');
    if(lightboxAnimation == "finished") {
      lightboxAnimation = "start";
      $('div#mediaGalleryLightboxLayer div#lightbox').fadeOut(200);
      $('div#toggleLightboxLayer').css('display','none');
      $('div#mediaGalleryLightboxLayer div#blackLayer').fadeOut(250, hideMediaGalleryLightboxLayer);
    }
    function hideMediaGalleryLightboxLayer() {
      var flashLayer = new SWFObject("", "", "1", "1", "9.0.115", "#ffffff");
      flashLayer.write("flashLayer");
      $('div#mediaGalleryLightboxLayer').fadeOut(200, hideLightboxContent);
    }
    function hideLightboxContent() {
      mediaGalleryShareIconIsDisplayedCheck();
      $('div#mediaGalleryLightboxLayer div#lightbox > *, div#mediaGalleryLightboxLayer img').css('display','none');
      $('div#mediaGalleryLightboxLayer div#lightbox, div#toggleLightboxLayer').css('display','block');
      $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer, div#mediaGalleryLightboxLayer div#lightbox div#embedLayer > *').css('display','block');
      document.title = startPageTitle;
      mediaGalleryInitLightbox();
    }
  });

  $('div#toggleLightboxLayer img').click(function() {
    mediaGalleryReadImageParameter();
    for(i=0; i < lightboxContent.length; i++) {
      if(lightboxContent[i]['parameter'] == '#mediaID-'+thisParameterNumber) {
        visibleLightboxObjectNumber = i;
      }
      lightboxContent[i]["isVisible"] = 'false';
    }

    var thisNumber;
    if($(this).hasClass('lightboxArrowLeft')) {
      thisNumber = (visibleLightboxObjectNumber == 0) ? Math.round(lightboxContent.length - 1) : Math.round(visibleLightboxObjectNumber - 1);
    } else if($(this).hasClass('lightboxArrowRight')) {
      thisNumber = (visibleLightboxObjectNumber == Math.round($('div.category img').length - 1)) ? 0 : Math.round(visibleLightboxObjectNumber + 1);
    }

    lightboxContent[thisNumber]["isVisible"] = 'true';
    initDownloadLinkList();
    var thisCategoryNumber = lightboxContent[thisNumber]["category"];
    document.title = startPageTitle;
    $flashObj.css('display','none');
    $('div#mediaGalleryLightboxLayer div#lightbox div#embedLayer').children().remove();
    $('div.downloadLayer').css('display','none');
    $('div.downloadLayer:eq('+ thisNumber +')').css('display','block');
    $('div#lightbox img#bigImage').fadeOut(200, mediaGallerySetLightboxPosition(showPreviousLightboxContent,lightboxContent[thisNumber]["width"],lightboxContent[thisNumber]["height"]));
    function showPreviousLightboxContent() {
      $imageObj.attr({src: lightboxContent[thisNumber]['src'], width: lightboxContent[thisNumber]["width"], height: lightboxContent[thisNumber]["height"], alt: ""});
      $imageObj.hide();
      mediaGalleryWriteLightboxContentObject(thisNumber, 'true');
    }
  });

  function initArrowLinks(thisNumber) {
    var previousImageNumber = (thisNumber - 1 < 0) ? $('div.category img').length - 1 : thisNumber - 1;
    var nextImageNumber = (thisNumber + 1 > $('div.category img').length - 1) ? 0 : thisNumber + 1;
    if($('div#mediaGalleryLightboxLayer img.lightboxArrowRight').parent().is('a')) {
      $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').parent().attr('href',lightboxContent[nextImageNumber]["parameter"]);
      $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').parent().attr('href',lightboxContent[previousImageNumber]["parameter"]);
    } else {
      $('div#mediaGalleryLightboxLayer img.lightboxArrowRight').wrap('<a href="'+ lightboxContent[nextImageNumber]["parameter"] + '" onfocus="this.blur();"></a>');
      $('div#mediaGalleryLightboxLayer img.lightboxArrowLeft').wrap('<a href="'+ lightboxContent[previousImageNumber]["parameter"] + '" onfocus="this.blur();"></a>');
    }
  }
}
// ******** media gallery page END ******** //


// ******** compare START ******** //
var compare_model = new Array();
var compare_model_selected = new Array();
compare_model_selected[1] = "";
compare_model_selected[2] = "";
var compare_model_short = new Array();

var compare_icon_class = new Array();
compare_icon_class[1] = "icon_standard_equipment";
compare_icon_class[2] = "icon_extra_equipment";
compare_icon_class[3] = "icon_original_equipment";
compare_icon_class[4] = "icon_not_available";


function compareSetTableHeight() {
  newCategoryLayerHeight = Math.round($("#sales_navigation").offset().top - $("#compare_innertable").offset().top - 52);
  $("#compare_innertable").css("height", newCategoryLayerHeight + "px");
  $("#compareInfoLayer").css("top",newCategoryLayerHeight + "px");
}

function compareInit() {
  for(i in compare_model) {
    compare_model_short.push(i);
  }
  //compare_model_short.sort();
  var dropdownCode = "";
  for(i = 0; i < compare_model_short.length; i++) {
    dropdownCode += '<a href="" model="' + compare_model_short[i] + '">' + compare_model[compare_model_short[i]]["model_name"] + '</a>';
  }
  $(".dropdown_content").html(dropdownCode);

  compare_model_selected[1] = compare_model_short[0];
  if(compare_model_short.length > 1) {
    compare_model_selected[2] = compare_model_short[1];
  }
  else {
    $("#compare_select_2").hide();
  }

  splitSearchString();
  if (query.model_1 && inArray(query.model_1,compare_model_short)) {
    compare_model_selected[1] = query.model_1;
  }
  if (query.model_2 && inArray(query.model_2,compare_model_short)) {
    compare_model_selected[2] = query.model_2;
;
  }
}


function compareWriteSelectboxes(model_1, model_2) {
  $("#compare_select_1 .select").html(compare_model[model_1]["model_name"]);
  $("#compare_select_1").show();
  if(compare_model[model_1]["configure_link"]) {
    $("#compare_select_1 .configure a").attr("href", compare_model[model_1]["configure_link"]);
    $("#compare_select_1 .configure").show();
  }
  if(model_2) {
    $("#compare_select_2 .select").html(compare_model[model_2]["model_name"]);
    $("#compare_select_2").show();
    if(compare_model[model_2]["configure_link"]) {
      $("#compare_select_2 .configure a").attr("href", compare_model[model_2]["configure_link"]);
      $("#compare_select_2 .configure").show();
    }
  }
}

function compareWriteTable(model_1,model_2) {
  var compareTableCode = '' +
  '        <table width="687" border="0" cellspacing="0" cellpadding="0">' +
  '          <tr>' +
  '            <td width="10"></td>' +
  '            <td width="209"></td>' +
  '            <td width="15"></td>' +
  '            <td width="219"></td>' +
  '            <td width="15"></td>' +
  '            <td width="219"></td>' +
  '          </tr>';
  for(i = 0; i < compare_model[model_1].length; i++) {

    if(!model_2) {
      compare_model[model_2] = new Array();
      compare_model[model_2][i] = new Array("","","",false,false);
    }

    if(compare_model[model_1][i][0] != "" && ((compare_model[model_1][i][0] == compare_model[model_2][i][0]) || !model_2)) {
      compareTableCode += '' +
      '          <tr class="mc_table_headline">' +
      '            <td></td>' +
      '            <td colspan="5">' + compare_model[model_1][i][0] + '</td>' +
      '          </tr>' +
      '          <tr class="mc_table_seperator">' +
      '            <td colspan="6"></td>' +
      '          </tr>';
    }

    else if(compare_model[model_1][i][1] != "" && ((compare_model[model_1][i][1] == compare_model[model_2][i][1]) || !model_2)) {

      if(!compare_model[model_1][i][3] && (!compare_model[model_2][i][3] || !model_2)) {
        compareTableCode += '' +
        '          <tr class="mc_table_entry">' +
        '            <td></td>' +
        '            <td class="leftalign">' + compare_model[model_1][i][1] + '</td>' +
        '            <td></td>';

        if(compare_model[model_1][i][4]) {
          compareTableCode += '            <td><div class="compare_table_icon ' + compare_icon_class[compare_model[model_1][i][4]] + '"></div></td>';
          compareTableCode += '            <td></td>';
          if(model_2) {
            compareTableCode += '            <td><div class="compare_table_icon ' + compare_icon_class[compare_model[model_2][i][4]] + '"></div></td>';
          }
          else {
             compareTableCode += '            <td></td>';
          }
        }
        else {
          compareTableCode += '            <td>' + compare_model[model_1][i][2] + '</td>';
          compareTableCode += '            <td></td>';
          compareTableCode += '            <td>' + compare_model[model_2][i][2] + '</td>';
        }

        compareTableCode += '' +
        '          </tr>' +
        '          <tr class="mc_table_seperator">' +
        '            <td colspan="6"></td>' +
        '          </tr>';

      }



      else if(compare_model[model_1][i][3] && (compare_model[model_2][i][3] || !model_2)) {
        compareTableCode += '' +
        '          <tr class="mc_table_entry">' +
        '            <td></td>' +
        '            <td colspan="5" class="leftalign">' +
        '              ' + compare_model[model_1][i][1] +
        '            </td>' +
        '          </tr>' +
        '          <tr class="mc_table_seperator">' +
        '            <td colspan="6"></td>' +
        '          </tr>';
      }
    }



  }
  compareTableCode += '</table>';
  $("#compare_innertable").html(compareTableCode);
  compareSetTableHeight();
}

// ******** compare END ******** //

// ******** test reports START ******** //
function initTestReportsContentHeight() {
  var newHeight = Math.round($('div#sales_navigation').offset().top - $('div#test_reports_content').offset().top - 42);
  $('div#test_reports_content').css('height',newHeight + 'px');
}
// ******** test reports END ******** //

var modulenaviAnimation = false;
var closeGif           = buildValidServerRelativeUrl( "/_common/html/img/standard_elements/close.gif" );
var close2Gif          = buildValidServerRelativeUrl( "/_common/html/img/standard_elements/close-h.gif" );
var transGif           = buildValidServerRelativeUrl( "/_common/html/img/palette/1x1_trans.gif" );
var p003399Gif         = buildValidServerRelativeUrl( "/_common/html/img/palette/1x1_003399.gif" );
var pulldownGif        = buildValidServerRelativeUrl( "/_common/html/img/forms/pulldown.gif" );

resetModulNaviTimer = 5000;
hideCo2LayerTimer = 5000;
selectBoxes = new Array();
var i, e;
var browserAtributeLength, browserId, platform;
var imgCountTotal, lowImageSrc, highImageSrc, currentImg, currentState, currentAct, currentPerm, checkLoad;
var slideAmount;
var divNum, documentLeftScroll, documentTopScroll, mouseX, mouseY, loopDragging;
var speedHorizontal, speedVertical, currentBack, goup, godown, speed, currentObjNo;
var setDivPosition, setBackPosition, currentObjId, currentSpeed, currenDirection, currentDelay;
var diffWidth, diffHeight, lastWidth, lastHeight, currentDiv;
var popupWindow, winUrl;
var ua = navigator.userAgent.toLowerCase();
var an = navigator.appName.toLowerCase();
var framesetPage = "index_narrowband.html";
var framesetPageHighend = "index_highend.html";
var currentStep = 0;
var windowWidth = 0;
var windowHeight = 0;
var browserVersion = 0;
var loaded = 0;
var divLeft = 0;
var divTop = 0;
var looping = -1;
var slideCount = -1;
var writeBrowser = "";
var tempAct = "";
var slideNumber = "";
var slideDescription = "";
var preLoadArray = [];
var preLoadCounter = [];
var highImages = [];
var lowImages = [];
var slideText = [];
var permanentActive = [];
var slideImages = [];
var allowedDomain = ["://www.bmw.", "://bmw.", "://origin.bmw.", "://secure.bmw.", "://wcms10.bmwgroup.com", "://liintra.muc", "://ltintra.muc", "://www-at.bmw", "://www-nl.bmw", "://www-be.bmw", "://www-lu.bmw", "://www-pt.bmw", "://www-ie.bmw", "://www-jp.bmw", "://www-fr.bmw", "://www-cz.bmw", "://www-sk.bmw", "://www-se.bmw", "://www-it.bmw", "://ecom.bmwgroup", "://ecomi.bmwgroup", "localhost"]
var supportedOS = false;
var supportedVersion = false;
var currentLoop = false;
var dragAllowed = false;
var divIsMoving = false;
var flashversion = false;
var topFrame = null;
var contentFrame = null;
var bottomFrame = null;
var historyFrame = null;
var hiddenFrame = null;
var allowClose = true;
var modulNaviOverImage = true;
var idmodulsSpecial = "";
var minFlashVersion = 7;
var isMainnavigation = false;
var indexParameters = "";
var query = {};
var parameterArray = [];
var scrollerDefaultSize = 1024;
var scrollerCheckElements = [];
var scrollerSize = scrollerDefaultSize;
var scrollerBgImage;
var scrollerSliderImage;
var scrollerImageUp;
var scrollerImageDown;
var persoEventType = "";
var persoSeries, persoBodytype, persoModel, persoColor, persoRim;
var cookieName = "bmw_bbDetection";
var chosenConnection = "";
var akamaiCookieName = "bandwidth";
var prmContent = "";
var divsToBeAltered = [];
var useCurtain = false;
var htmlDialogOpen = false;
var mainNaviOpen = false;


function arrayUnique (a) {
  var o = {};
  for(var i = 0 ; i < a.length; i++)
  o[a[i]] = true;
  var tmp = new Array();
  for(var i in o) tmp[tmp.length] = i;
  return tmp;
}

if (typeof browser != 'object') {
  browser = [['Opera', 'opera ', '9.0', 'windows', 'mac os x', 'other'], ['Safari', 'safari/', '125', '', 'mac os x', ''], ['Netscape', 'netscape/', '7.1', 'windows', 'mac os x', 'other'], ['Firefox', 'firefox/', '1.0', 'windows', 'mac os x', 'other'], ['Mozilla', 'rv:', '1.7', 'windows', 'mac os x', 'other'], ['MSIE', 'msie ', '5.5', 'windows', '', ''], ['Netscape4', 'mozilla/', '4.0', '', '', '']];
}

function ssoCloseDialog(){
}

function checkClient(){
  var browserLength = browser.length;
  for (i = 0; i < browserLength; i++) {
    browserAtributeLength = browser[i].length;
    if (ua.indexOf(browser[i][1]) != -1) {
      browserId = browser[i][0];
      for (e = 3; e < browserAtributeLength; e++) {
        if (browser[i][e] != '' && (ua.indexOf(browser[i][e]) != -1 || browser[i][e] == 'other')) {
          supportedOS = true;
          platform = browser[i][e];
          break;
        } else {
          supportedOS = false;
        }
      }
      browserVersion = ua.split(browser[i][1]);
      browserVersion = parseFloat(browserVersion[1].slice(0, 3));
      if (browserVersion >= browser[i][2]) {
        supportedVersion = true;
      } else {
        supportedVersion = false;
      }
      break;
    } else {
      browserId = 'unknown';
    }
  }
  browserId = ((browserId == "MSIE") ? (((/\s+msie\s+7\.\d+/).test(navigator.appVersion.toLowerCase())) ? ("MSIE7") : (browserId)) : (browserId));
  browserId = ((browserId == "MSIE") ? (((/\s+msie\s+8\.\d+/).test(navigator.appVersion.toLowerCase())) ? ("MSIE8") : (browserId)) : (browserId));
}

function checkBrowser(incompatibleBrowserUrl){
  checkClient();
  return true;
}
function checkFrameset(){
}

function removeClassName(obj, cssClass){
  if (typeof obj != 'object') {
    obj = document.getElementById(obj);
  }
  if (hasClassName(obj, cssClass)) {
    obj.className = obj.className.replace(new RegExp(cssClass), '');
  }
}

function replaceClassName(obj, oldCssClass, newCssClass){
  if (typeof obj != 'object') {
    obj = document.getElementById(obj);
  }
  if (hasClassName(obj, oldCssClass)) {
    obj.className = obj.className.replace(new RegExp(oldCssClass), newCssClass);
  }
}

function hasClassName(obj, cssClass){
  if (typeof obj != 'object') {
    obj = document.getElementById(obj);
  }
  return (obj.className.indexOf(cssClass) != -1);
}

function addClassName(obj, cssClass){
  if (typeof obj != 'object') {
    obj = document.getElementById(obj);
  }
  if (!hasClassName(obj, cssClass)) {
    obj.className += ' ' + cssClass;
  }
}

function pageHandler(){
  splitSearchString();
  if (query.content) {
    if (query.content.indexOf("://") != -1) {
      var domainIsAllowed = false;
      for (i = 0; i < allowedDomain.length; i++) {
        if (query.content.indexOf(allowedDomain[i]) != -1) {
          domainIsAllowed = true;
          break;
        }
      }
      if (domainIsAllowed) {
        initContentURL = query.content;
        indexParameters = "";
        for (var x in query) {
          if (x == "content")
            continue;
          if (indexParameters == "") {
            indexParameters += "?";
          } else {
            indexParameters += "&";
          }
          indexParameters += x + "=" + query[x];
        }
      }
    } else {
      initContentURL = query.content;
      indexParameters = "";
      for (x in query) {
        if (x == "content")
          continue;
        if (indexParameters == "") {
          indexParameters += "?";
        } else {
          indexParameters += "&";
        }
        indexParameters += x + "=" + query[x];
      }
    }
  }
}

function preload(){
  if (typeof slideImagesCollection != 'undefined') {
    slideAmount = slideImagesCollection.length;
  }
  for (i = 0; i < slideAmount; i++) {
    slideImages[i] = new Image();
    slideImages[i].src = slideImagesCollection[i];
  }
  loaded = 2;
  imgCountTotal = document.images.length;
  for (i = 0; i < imgCountTotal; i++) {
    if (typeof document.getElementsByTagName('img')[i].getAttribute('preload') == 'string') {
      lowImageSrc = document.getElementsByTagName('img')[i].src;
      if (document.getElementsByTagName('img')[i].getAttribute('preload').indexOf('/') != -1) {
        highImageSrc = document.getElementsByTagName('img')[i].getAttribute('preload');
      } else {
        var highImageUrl = lowImageSrc.split('/');
        var fileLevel = highImageUrl.length;
        var highImagePath = '';
        for (e = 0; e < fileLevel - 1; e++) {
          highImagePath += highImageUrl[e] + '/';
        }
        highImageSrc = highImagePath + document.getElementsByTagName('img')[i].getAttribute('preload');
      }
      highImages[document.images[i].id] = new Image();
      highImages[document.images[i].id].src = highImageSrc;
      lowImages[document.images[i].id] = new Image();
      lowImages[document.images[i].id].src = lowImageSrc;
    }
    if (i < imgCountTotal - 1) {
      loaded = 3;
    }
    if (i == imgCountTotal - 1) {
      loaded = 1;
    }
  }
}

function switchImage(imgId, state, act, permanent, dropPerm){
  currentImg = imgId;
  currentState = state;
  currentAct = act;
  currentPerm = permanent;
  if (typeof dropPerm == 'string' && dropPerm != 'all') {
    document.getElementsByTagName('img')[dropPerm].src = lowImages[dropPerm].src;
    delete permanentActive[dropPerm];
    if (dropPerm == tempAct) {
      tempAct = '';
    }
  } else if (dropPerm == 'all') {
    dropPermanentAll();
  }
  if (loaded == 1) {
    clearTimeout(checkLoad);
    if (tempAct != '' && imgId != tempAct && act == 1 && !permanentActive[tempAct]) {
      document.getElementsByTagName('img')[tempAct].src = lowImages[tempAct].src;
    }
    if ((tempAct == '' || imgId != tempAct) && !permanentActive[imgId]) {
      if (state == 1) {
        document.getElementsByTagName('img')[imgId].src = highImages[imgId].src;
      } else {
        document.getElementsByTagName('img')[imgId].src = lowImages[imgId].src;
      }
    }
    if (act == 1) {
      tempAct = imgId;
    }
    if (permanent == 1) {
      permanentActive[imgId] = imgId;
    }
  } else if (loaded == 2) {
    checkLoad = setTimeout('switchImage(currentImg,currentState,currentAct,currentPerm)', 50);
  } else if (loaded == 3) {
    preload();
    checkLoad = setTimeout('switchImage(currentImg,currentState,currentAct,currentPerm)', 50);
  }
}

function dropPermanentAll(){
  for (var dropImg in permanentActive) {
    if (lowImages[dropImg].src) {
      document.getElementsByTagName('img')[dropImg].src = lowImages[dropImg].src;
    }
    delete permanentActive[dropImg];
  }
  if (tempAct != '') {
    if (lowImages[dropImg].src) {
      document.getElementsByTagName('img')[tempAct].src = lowImages[tempAct].src;
    }
    tempAct = '';
  }
}

function setSlideshow(direction, delay){
  currenDirection = direction;
  currentDelay = delay;
  if (direction == "forward") {
    slideCount++;
    if (slideCount > slideAmount - 1) {
      slideCount = 0;
    }
  } else if (direction == "backward") {
    slideCount--;
    if (slideCount < 0) {
      slideCount = slideAmount - 1;
    }
  } else {
    slideCount = 0;
  }
  if (delay) {
    looping = setTimeout("setSlideshow(currenDirection,currentDelay)", currentDelay);
  } else {
    clearTimeout(looping);
    looping = -1;
  }
  document.getElementById('slideshow').src = slideImages[slideCount].src;
}

function toggleSlideshow(direction, delay){
  if (!direction) {
    direction = currenDirection;
  }
  if (!delay) {
    delay = currentDelay;
  }
  if (looping > -1) {
    clearTimeout(looping);
    looping = -1;
  } else {
    setSlideshow(direction, delay);
  }
}

function setClassName(elementId, newClassName){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    elementId.className = newClassName;
  }
}

function setColor(elementId, newColor){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    elementId.style.color = newColor;
  }
}

function getAbsoluteLeft(elementId){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  var currentLeft = 0;
  if (elementId) {
    while (elementId.offsetParent !== null) {
      currentLeft += elementId.offsetLeft;
      elementId = elementId.offsetParent;
    }
    currentLeft += elementId.offsetLeft;
  }
  return currentLeft;
}

function getAbsoluteTop(elementId){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  var currentTop = 0;
  if (elementId) {
    while (elementId.offsetParent !== null) {
      currentTop += elementId.offsetTop;
      elementId = elementId.offsetParent;
    }
    currentTop += elementId.offsetTop;
  }
  return currentTop;
}

function getDivInformation(elementId, attributeName){
  divInformation = [];
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    divInformation['offsetLeft'] = elementId.offsetLeft;
    divInformation['offsetTop'] = elementId.offsetTop;
    divInformation['styleLeft'] = parseInt(elementId.style.left);
    divInformation['styleTop'] = parseInt(elementId.style.top);
    divInformation['width'] = elementId.offsetWidth;
    divInformation['height'] = elementId.offsetHeight;
    divInformation['visibility'] = elementId.style.visibility;
    divInformation['display'] = elementId.style.display;
    divInformation['zIndex'] = elementId.style.zIndex;
    return divInformation[attributeName];
  }
}

function writeIntoLayer(elementId, content){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    elementId.innerHTML = content;
  }
}

lastPositions = [];
currentPositions = [];
currentPositions['navigation'] = [,];
function moveObject(elementId, newLeft, newTop, speed, backLink){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    if (newLeft) {
      divLeft = newLeft;
    } else if ((typeof newLeft == 'undefined' || typeof newLeft == 'string') && (typeof backLink == 'undefined' || backLink == 0)) {
      divLeft = getDivInformation(elementId, 'offsetLeft');
    }
    if (newTop) {
      divTop = newTop;
    } else if ((typeof newTop == 'undefined' || typeof newTop == 'string') && (typeof backLink == 'undefined' || backLink == 0)) {
      divTop = getDivInformation(elementId, 'offsetTop');
    }
    if (!lastPositions[elementId.id]) {
      lastPositions[elementId.id] = [, ];
    }
    if (typeof backLink != 'undefined' && backLink == 1 && newLeft == lastPositions[elementId.id][0] && newTop == lastPositions[elementId.id][1]) {
      currentBack = backLink;
      divLeft = currentPositions[elementId.id][0];
      divTop = currentPositions[elementId.id][1];
    }
    if (!divIsMoving) {
      currentPositions[elementId.id] = [getDivInformation(elementId, 'offsetLeft'), getDivInformation(elementId, 'offsetTop')];
    }
    if (speed) {
      var horizontalRange = currentPositions[elementId.id][0] - divLeft + "px";
      var verticalRange = currentPositions[elementId.id][1] - divTop + "px";
      currentObjId = elementId;
      currentSpeed = speed;
      currentStep++;
      if (newLeft != '' || newLeft == 0) {
        if (horizontalRange > 0) {
          elementId.style.left = (currentPositions[elementId.id][0] - Math.round(currentStep * speed)) + 'px';
          if (divLeft - getDivInformation(elementId, 'offsetLeft') > 5) {
            elementId.style.left = divLeft + 'px';
          }
        } else if (horizontalRange < 0) {
          elementId.style.left = (currentPositions[elementId.id][0] + Math.round(currentStep * speed)) + 'px';
          if (divLeft - getDivInformation(elementId, 'offsetLeft') < 5) {
            elementId.style.left = divLeft + 'px';
          }
        }
      }
      if (newTop != '' || newTop == 0) {
        if (verticalRange > 0) {
          elementId.style.top = (currentPositions[elementId.id][1] - Math.round(currentStep * speed)) + 'px';
          if (divTop - getDivInformation(elementId, 'offsetTop') > 5) {
            elementId.style.top = divTop + 'px';
          }
        } else if (verticalRange < 0) {
          elementId.style.top = (currentPositions[elementId.id][1] + Math.round(currentStep * speed)) + 'px';
          if (divTop - getDivInformation(elementId, 'offsetTop') < 5) {
            elementId.style.top = divTop + 'px';
          }
        }
      }
      if (getDivInformation(elementId, 'offsetLeft') == newLeft && getDivInformation(elementId, 'offsetTop') == newTop) {
        divIsMoving = false;
        currentStep = 0;
        currentBack = 0;
        divLeft = 0;
        divTop = 0;
        lastPositions[elementId.id] = [newLeft, newTop];
        clearTimeout(setDivPosition);
      } else {
        divIsMoving = true;
        setDivPosition = setTimeout('moveObject(currentObjId,divLeft,divTop,currentSpeed)', 10);
      }
    } else {
      if (divLeft != '' || divLeft == 0) {
        elementId.style.left = divLeft + 'px';
      }
      if (divTop != '' || divTop == 0) {
        elementId.style.top = divTop + 'px';
      }
      currentBack = 0;
      divLeft = 0;
      divTop = 0;
      lastPositions[elementId.id] = [newLeft, newTop];
    }
  }
}

function mousePosition(currentEvent){
  if (window.event) {
    currentEvent = window.event;
  }
  mouseX = currentEvent.clientX;
  mouseY = currentEvent.clientY;
}

function getWindowInformation(attributeName){
  var windowInformation = [];
  windowInformation['winWidth'] = document.body.clientWidth;
  if (document.body.clientHeight == 0) {
    windowInformation['winHeight'] = window.innerHeight;
  } else {
    windowInformation['winHeight'] = document.body.clientHeight;
  }
  windowInformation['docWidth'] = document.body.scrollWidth;
  windowInformation['docHeight'] = document.body.scrollHeight;
  windowInformation['scrollLeft'] = document.body.scrollLeft;
  windowInformation['scrollTop'] = document.body.scrollTop;
  return windowInformation[attributeName];
}

function getCurrentStyle(nodeObject, propertyName){
  var propertyValue;
  if (document.documentElement && document.defaultView) {
    propertyValue = document.defaultView.getComputedStyle(nodeObject, "").getPropertyValue(propertyName);
  } else if (document.documentElement && document.documentElement.currentStyle) {
    var regX = /([ a-z ]*)\-([ a-z ])([ a-z ]*)/;
    while (regX.test(propertyName)) {
      regX.exec(propertyName);
      propertyName = RegExp.$1 + RegExp.$2.toUpperCase() + RegExp.$3;
    }
    propertyValue = nodeObject.currentStyle[propertyName];
  }
  return propertyValue;
}

var currentState, currentDisplayState;
function setVisibility(elementId, visibilityValue, displayValue, initialSet){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    if (typeof visibilityValue == 'undefined' && typeof displayValue == 'undefined') {
      currentState = getDivInformation(elementId, 'visibility');
      currentDisplayState = getDivInformation(elementId, 'display');
      if (currentState == '') {
        if (initialSet) {
          currentState = 'visible';
        } else {
          currentState = 'hidden';
        }
      }
      if (currentDisplayState == '') {
        if (initialSet) {
          currentDisplayState = initialSet;
        } else {
          currentDisplayState = 'none';
        }
      }
      if (currentState == 'hidden') {
        elementId.style.visibility = 'visible';
      } else if (currentState == 'visible') {
        elementId.style.visibility = 'hidden';
      }
      if (currentDisplayState == 'none') {
        elementId.style.display = 'block';
        elementId.style.visibility = 'visible';
      } else if (currentDisplayState == 'block' || currentDisplayState == 'inline') {
        elementId.style.display = 'none';
      }
    } else if (visibilityValue == 1) {
      elementId.style.visibility = 'visible';
    } else if (visibilityValue == 0) {
      elementId.style.visibility = 'hidden';
    }
    if (displayValue) {
      elementId.style.display = displayValue;
    }
  }
}

function setZIndex(elementId, newZIndex){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    elementId.style.zIndex = newZIndex;
  }
}

function resizeLayer(elementId, newWidth, newHeight){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    currentDiv = elementId;
    lastWidth = getDivInformation(elementId, 'width');
    lastHeight = getDivInformation(elementId, 'height');
    if (newWidth) {
      if (typeof newWidth == 'string') {
        elementId.style.width = newWidth;
      } else {
        elementId.style.width = newWidth + 'px';
      }
    }
    if (newHeight) {
      if (typeof newHeight == 'string') {
        elementId.style.height = newHeight;
      } else {
        elementId.style.height = newHeight + 'px';
      }
    }
  }
}

function clipLayer(elementId, newTop, newRight, newBottom, newLeft){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    currentDiv = elementId;
    lastWidth = getDivInformation(elementId, 'width');
    lastHeight = getDivInformation(elementId, 'height');
    elementId.style.clip = "rect(" + newTop + "px " + newRight + "px " + newBottom + "px " + newLeft + "px)";
  }
}

function getClipping(elementId){
  if (typeof elementId != 'object') {
    elementId = document.getElementById(elementId);
  }
  if (elementId) {
    return elementId.style.clip;
  }
}

function restoreLayer(){
  if (typeof currentDiv == 'object') {
    if (typeof currentDiv.style.width != 'undefined') {
      currentDiv.style.width = lastWidth + 'px';
    }
    if (typeof currentDiv.style.height != 'undefined') {
      currentDiv.style.height = lastHeight + 'px';
    }
    if (typeof currentDiv.style.clip != 'undefined') {
      currentDiv.style.clip = "rect(" + 0 + "px " + lastWidth + "px " + lastHeight + "px " + 0 + "px)";
    }
  }
}

function centerPopup(popupUrl, popupName, popupWidth, popupHeight, reopen, showScrollbar, popupLeftPos, popupTopPos, myLocation){
  if(!popupLeftPos) {popupLeftPos = 5;}
  if(!popupTopPos)  {popupTopPos = 15;}
  if(!showScrollbar){showScrollbar = 0;}

  if(popupUrl.indexOf("centerPopupShowScrollbar") > -1) {
    showScrollbar = 1;
  }

  if(!myLocation)   {myLocation = "no";}
  var popup_left = (window.screen.width / 2) - (popupWidth / 2 + popupLeftPos);
  var popup_top = (window.screen.height / 2) - (popupHeight / 2 + popupTopPos);
  if ((typeof popupWindow != 'object') || (typeof popupWindow == 'object' && popupWindow.closed)) {
    if (document.all) {
      var xyPos = 'left=' + popup_left + ',top=' + popup_top;
    } else {
      var xyPos = 'screenX=' + popup_left + ',screenY=' + popup_top;
    }
    popupWindow = window.open(popupUrl, popupName, "toolbar=no,location=" + myLocation + ",directories=no,status=no,menubar=no,scrollbars=" + showScrollbar + ",resizable=no,width=" + popupWidth + ",height=" + popupHeight + ",copyhistory=no," + xyPos + "");
    popupWindow.opener = self;
    popupWindow.focus();
    winUrl = popupUrl;
    windowWidth = popupWidth;
    windowHeight = popupHeight;
  } else {
    if ((winUrl != popupUrl) || reopen) {
      popupWindow.location.href = popupUrl;
    }
    if ((windowWidth + windowHeight > 0) && (popupWidth != windowWidth || popupHeight != windowHeight || popupLeftPos != diffWidth || popupTopPos != diffHeight)) {
      var newWidth = popupWidth - windowWidth;
      var newHeight = popupHeight - windowHeight;
      popupWindow.resizeBy(newWidth, newHeight);
      popupWindow.moveTo(popup_left, popup_top);
    }
    popupWindow.focus();
    winUrl = popupUrl;
    windowWidth = popupWidth;
    windowHeight = popupHeight;
  }
  diffWidth = popupLeftPos;
  diffHeight = popupTopPos;
}

function openPopupLink(popupUrl, popupString){
  var params = popupString.split(",");
  if (params.length == 3) {
    centerPopup(popupUrl, params[0], params[1], params[2], false, false);
  } else {
    centerPopup(popupUrl, "searchwin", 800, 600, false, false);
  }
}

function openPopupParams(popupUrl, popupName, popupParams){
  if ((typeof popupWindow != 'object') || (typeof popupWindow == 'object' && popupWindow.closed)) {
    if (popupParams) {
      popupWindow = window.open(popupUrl, popupName, popupParams);
    } else {
      popupWindow = window.open(popupUrl, popupName);
    }
    popupWindow.opener = self;
    popupWindow.focus();
    winUrl = popupUrl;
  } else {
    if (winUrl != popupUrl) {
      popupWindow.location.href = popupUrl;
    }
    popupWindow.focus();
    winUrl = popupUrl;
  }
}

function splitSearchString(){
  if (self.location.search.indexOf("=") == -1)
    return;
  parameterArray = self.location.search.substring(1).split("&");
  for (var i = 0; i < parameterArray.length; i++) {
    pair = parameterArray[i].split("=");
    query[unescape(pair[0])] = (pair[1] ? unescape(pair[1]) : "");
  }
}

function getCookieValue(name){
  var arg = name + "=";
  var alen = arg.length;
  var i = 0;
  while (i < document.cookie.length) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      var endstr = document.cookie.indexOf(";", j);
      if (endstr == -1) {
        endstr = document.cookie.length;
      }
      return unescape(document.cookie.substring(j, endstr));
    }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) {
      break;
    }
  }
  return false;
}

function getCookie(name){
  return getCookieValue(name);
}

function onLoadFunctions(){
}

function onUnloadFunctions(){
}

var resizeDivs = new Array("mainNavigationContainer","mainContainer", "mainImages", "mainImage");

function checkWindowSize() {
  if(browserId == "MSIE") {
    $(".metaNavigation").hide().show();
  }

  resizeDivs = arrayUnique(resizeDivs);
  var i;
  var newSize;
  if (getWindowInformation('winWidth') < scrollerSize) {
    for (i = 0; i < resizeDivs.length; i++) {
      if (document.getElementById(resizeDivs[i])) {
        newSize = 1000 - document.getElementById(resizeDivs[i]).offsetLeft;
        resizeLayer(resizeDivs[i], newSize + "px");
        if(resizeDivs[i] != "mainNavigationContainer" && resizeDivs[i] != "completePageContent") {
          document.getElementById(resizeDivs[i]).style.overflow = "hidden";
        }
      }
    }
  } else {
    if (document.getElementById('mainNavi')) {
      resizeLayer('mainNavi', '100%');
    }
    for (i = 0; i < resizeDivs.length; i++) {
      if (document.getElementById(resizeDivs[i])) {
        if(!document.getElementById(resizeDivs[i]).offsetLeft) {
          resizeLayer(resizeDivs[i], '100%');
        }
      }
    }
  }
}

function myAlert(alertText){
  if (top.location.search.indexOf("debug") != -1) {
    alert(alertText);
  }
}

function buildLinkList(){
  var links = new Array(document.getElementsByTagName('a').length);
  for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
    links[i] = document.getElementsByTagName('a')[i].href;
  }
  return links;
}

function evaluateHighlighting(contentUrl, linkList){
  var navLinkFull = "";
  var navLinkPath = "";
  var navLinkFile = "";
  var navLinkQuery = "";
  var navLinkPathParts = [];
  var contentLinkFull = "";
  var contentLinkPath = "";
  var contentLinkFile = "";
  var contentLinkQuery = "";
  var contentLinkPathParts = [];
  var evaluatedLinks = [];
  if (contentUrl.indexOf('?') != -1) {
    contentLinkFull = contentUrl.substring(0, contentUrl.lastIndexOf('?'));
    contentLinkQuery = contentUrl.substring(contentUrl.lastIndexOf('?'), contentUrl.length);
    if (contentLinkQuery.indexOf("&") != -1) {
      contentLinkQuery = contentLinkQuery.substring(0, contentLinkQuery.indexOf("&"));
    }
  } else {
    contentLinkFull = contentUrl;
  }
  if (contentLinkFull.charAt(contentLinkFull.length - 1) == '/') {
    contentLinkFull = contentLinkFull.substring(0, contentLinkFull.length - 1);
  }
  if (contentLinkFull.lastIndexOf('/') < contentLinkFull.lastIndexOf('.')) {
    contentLinkFile = contentLinkFull.substring(contentLinkFull.lastIndexOf('/') + 1, contentLinkFull.length);
    contentLinkPath = contentLinkFull.substring(0, contentLinkFull.lastIndexOf('/'));
  } else {
    contentLinkPath = contentLinkFull;
    contentLinkFile = "";
  }
  contentLinkPathParts = contentLinkPath.split('/');
  for (var i = 0; i < linkList.length; i++) {
    navLinkFull = linkList[i];
    if (navLinkFull.indexOf('javascript:') != -1 || navLinkFull == '') {
      evaluatedLinks.push(999);
      continue;
    }
    if (navLinkFull.indexOf('?') != -1) {
      navLinkQuery = navLinkFull.substring(navLinkFull.lastIndexOf('?'), navLinkFull.length);
      if (navLinkQuery.indexOf("&") != -1) {
        navLinkQuery = navLinkQuery.substring(0, navLinkQuery.indexOf("&"));
      }
      navLinkFull = navLinkFull.substring(0, navLinkFull.lastIndexOf('?'));
    } else {
      navLinkQuery = "";
    }
    if (navLinkFull.charAt(navLinkFull.length - 1) == '/') {
      navLinkFull = navLinkFull.substring(0, navLinkFull.length - 1);
    }
    if (navLinkFull.lastIndexOf('/') < navLinkFull.lastIndexOf('.')) {
      navLinkFile = navLinkFull.substring(navLinkFull.lastIndexOf('/') + 1, navLinkFull.length);
      navLinkPath = navLinkFull.substring(0, navLinkFull.lastIndexOf('/'));
    } else {
      navLinkPath = navLinkFull;
      navLinkFile = "";
    }
    navLinkPathParts = navLinkPath.split('/');

    var contentIndex = 0;
    var navIndex = 0;
    var bestmatchFound = false;
    var charMatch = null;

    while (navLinkPathParts[navIndex] == contentLinkPathParts[contentIndex]) {
      navIndex++;
      contentIndex++;
      if (contentIndex == contentLinkPathParts.length && navIndex == navLinkPathParts.length) {
        if (navLinkFile == contentLinkFile) {
          if (navLinkQuery == contentLinkQuery) {
            evaluatedLinks.push(-2);
            bestmatchFound = true;
          } else {
            evaluatedLinks.push(-1);
          }
        } else {
          charMatch = stringCompare(navLinkFile, contentLinkFile);
          evaluatedLinks.push(0.99 - (charMatch / 100));
        }
        break;

      } else if (contentIndex == contentLinkPathParts.length) {
        evaluatedLinks.push(999);
        break;

      } else if (navIndex == navLinkPathParts.length) {
        if (confCountryTopic != null &&
        confLanguageTopic != null &&
        navLinkPathParts.length >= 2 &&
        navLinkPathParts[navLinkPathParts.length - 1] == confLanguageTopic &&
        navLinkPathParts[navLinkPathParts.length - 2] == confCountryTopic) {
          evaluatedLinks.push(999);
        } else if (confCountryTopic != null && navLinkPath.indexOf("/" + confCountryTopic + "/") == -1) {
          evaluatedLinks.push(999);
        } else {
          evaluatedLinks.push(contentLinkPathParts.length - contentIndex);
        }
        break;

      } else if (navLinkPathParts[navIndex] != contentLinkPathParts[contentIndex]) {
        evaluatedLinks.push(999);
        break;
      }
    }
    if (bestmatchFound) {
      break;
    }
  }
  return evaluatedLinks;
}

function stringCompare(comparator1, comparator2){
  var shorter = null;
  var longer = null;
  if (comparator1.length > comparator2.length) {
    longer = comparator1.toLowerCase();
    shorter = comparator2.toLowerCase();
  } else {
    longer = comparator2.toLowerCase();
    shorter = comparator1.toLowerCase();
  }
  var matchCount = 0;
  for (var x = 0; x < shorter.length; x++) {
    if (shorter.charAt(x) == longer.charAt(x)) {
      matchCount++;
    } else {
      break;
    }
  }
  return matchCount;
}

function buildValidServerRelativeUrl(simpleServerRelativeUrl){
  if (simpleServerRelativeUrl == '') {
    return '';
  }
  if (simpleServerRelativeUrl.charAt(0) != '/') {
    return simpleServerRelativeUrl;
  }
  var validServerRelativeUrl = '';
  var simpleSeverrelativeUrlNoParams = '';

  if (simpleServerRelativeUrl.indexOf('?') != -1) {
    simpleSeverrelativeUrlNoParams = simpleServerRelativeUrl.substring(0, simpleServerRelativeUrl.indexOf('?'));
  } else {
    simpleSeverrelativeUrlNoParams = simpleServerRelativeUrl;
  }
  if (self.location.href.indexOf('/bmw_edit/') != -1 && simpleSeverrelativeUrlNoParams.indexOf('/bmw_edit/') == -1) {
    validServerRelativeUrl = '/bmw_edit' + simpleServerRelativeUrl;
  } else if (self.location.href.indexOf('/bmw_qa/') != -1 && simpleSeverrelativeUrlNoParams.indexOf('/bmw_qa/') == -1) {
    validServerRelativeUrl = '/bmw_qa' + simpleServerRelativeUrl;
  } else if (self.location.href.indexOf('/bmw_prod/') != -1 && simpleSeverrelativeUrlNoParams.indexOf('/bmw_prod/') == -1) {
    validServerRelativeUrl = '/bmw_prod' + simpleServerRelativeUrl;
  } else {
    validServerRelativeUrl = simpleServerRelativeUrl;
  }
  return validServerRelativeUrl;
}

function getFullPath(basePath, relativePath){
  var fullPath = basePath.substring(0, (basePath.lastIndexOf("/") + 1));
  var regXHostPath = /((^(https{0,1}\:\/\/[ ^\/ ]*\/))|(^(file\:\/\/[ ^\: ]*\:\/))|(^([ a-z ]+\:\\))|(^([ a-z ]+\:\/))|(^(\\\\))|(^(\/\/)))/i;
  if (regXHostPath.test(relativePath)) {
    fullPath = relativePath;
  } else {
    var regXGoingUp = /(\.\.\/)/g, goingUpArr = [], i;
    if (regXGoingUp.test(relativePath)) {
      goingUpArr = relativePath.match(regXGoingUp);
    }
    for (var i = 0; i < goingUpArr.length; ++i) {
      fullPath = fullPath.substring(0, (fullPath.lastIndexOf("/", (fullPath.length - 2)) + 1));
    }
    fullPath += relativePath.replace(regXGoingUp, "");
  }
  return fullPath;
}

function getServerRelativeContentUrl(){
  var contentPage = self.location.href;
  var substract = self.location.host;
  return contentPage.substring(contentPage.indexOf(substract) + substract.length, contentPage.length);
}

function setModuleHeader(hasLink){
  var headerHTML = "";
  if (hasLink) {
    headerHTML = '<a href="javascript:moveMenu();" style="position:relative;display:block;margin-top:1px;">' + moduleHeader + '</a>';
  } else {
    headerHTML = '<span style="position:relative;display:block;margin-top:1px;">' + moduleHeader + '</span>';
  }
  if (typeof document.getElementsByTagName('div')['moduleHeaderContainerSeo'] == 'object') {
    writeIntoLayer('moduleHeaderContainerSeo', headerHTML);
    setVisibility('moduleHeaderContainerSeo', 1);
  } else {
    moveObject(document.getElementsByTagName('div')['naviClipAreaSeo'], null, 0);
  }
}

function download(fileUrl){
  if (confPersoEngineEnabled) {
    if (typeof parent.persoDownloadEventType != "undefined") {
      if (parent.persoDownloadEventType) {
        var persoDownloadEventType = parent.persoDownloadEventType;
        var persoSeries = parent.persoSeries;
        var persoBodytype = parent.persoBodytype;
        var persoModel = parent.persoModel;
        var persoColor = parent.persoColor;
        var persoRim = parent.persoRim;
        parent.createPersoEvent(persoDownloadEventType, persoSeries, persoBodytype, persoModel, persoColor, persoRim);
      }
    } else if (typeof self.persoDownloadEventType != "undefined") {
      if (self.persoDownloadEventType) {
        var persoDownloadEventType = self.persoDownloadEventType;
        var persoSeries = self.persoSeries;
        var persoBodytype = self.persoBodytype;
        var persoModel = self.persoModel;
        var persoColor = self.persoColor;
        var persoRim = self.persoRim;
        createPersoEvent(persoDownloadEventType, persoSeries, persoBodytype, persoModel, persoColor, persoRim);
      }
    }
  }
  var downloadUrl = buildValidServerRelativeUrl(fileUrl) + "?download=true";
  self.location.href = downloadUrl;
}

function writeFramesetTitle(titleText){
}

function preloader(ticketId){
  preLoadCounter[ticketId] = 0;
  preload[ticketId] = [];
  for (var j = 0; j < preLoadArray[ticketId].length; j++) {
    preload[ticketId][j] = new Image();
    preload[ticketId][j].onabort = function(){
      loadUpdate(ticketId, j);
    }
    preload[ticketId][j].onerror = function(){
      loadUpdate(ticketId, j);
    }
    preload[ticketId][j].onload = function(){
      loadUpdate(ticketId, j);
    }
    preload[ticketId][j].src = preLoadArray[ticketId][j];
  }
}

function loadUpdate(ticketId, imageId){
  preLoadCounter[ticketId]++;
  if (preLoadCounter[ticketId] == preLoadArray[ticketId].length) {
    preLoadReady(ticketId);
  }
}

function preLoadReady(ticketId){
}

function showCo2(){
  setVisibility('co2HeaderOn', 1);
  setVisibility('co2HeaderOff', 0);
  setVisibility('co2body', 1);
}

function hideCo2(){
  setVisibility('co2HeaderOn', 0);
  setVisibility('co2HeaderOff', 1);
  setVisibility('co2body', 0);
}

function stopPlayingMp3(){
}

function setElementClass(elementTagName, currentClass, newClass){
  for (var i = 0; i < document.getElementsByTagName(elementTagName).length; i++) {
    if (document.getElementsByTagName(elementTagName)[i].className == currentClass) {
      document.getElementsByTagName(elementTagName)[i].className = newClass;
    }
  }
}

function dialogClosed(){
}

function setCookie(name, value, expires, path, domain, secure){
  document.cookie = name + "=" + escape(value) +
  ((expires) ? "; expires=" + expires : "") +
  ((path) ? "; path=" + path : "") +
  ((domain) ? "; domain=" + domain : "") +
  ((secure) ? "; secure" : "");
}

function setBandwidthOption(text, userBandwidth, formField){
  setVisibility('selectBoxContent' + formField, 0, 'none');
  writeIntoLayer('selectedValue' + formField, "&nbsp; " + text);
  selectedBandwidth = userBandwidth;
}

function getCorrectPath(URL1){
  targetUrl = "http://" + window.location.hostname + "" + buildValidServerRelativeUrl(URL1);
  self.location.href = buildValidServerRelativeUrl(targetUrl);
}

function changeLinksAccordingToStage(){
  var prefix = "";
  if (self.location.href.indexOf('/bmw_edit/') != -1) {
    prefix = "/bmw_edit";
  } else if (self.location.href.indexOf('/bmw_qa/') != -1) {
    prefix = "/bmw_qa";
  } else if (self.location.href.indexOf('/bmw_prod/') != -1) {
    prefix = "/bmw_prod";
  }
  if (prefix != "") {
    divsToBeAltered.push("naviClipAreaSeo");
    divsToBeAltered.push("metaNavigationText");
    divsToBeAltered.push("metaNavigationLogin");
    divsToBeAltered.push("mainNavi");
    divsToBeAltered.push("mainNavigationContainer");
    divsToBeAltered.push("vehicle_navigation");
    divsToBeAltered.push("sales_navigation");
    divsToBeAltered.push("sales_navigation_layer_config");
    divsToBeAltered.push("sales_navigation_layer_compare");
    divsToBeAltered.push("sales_navigation_layer_contact");
    divsToBeAltered.push("sales_navigation_layer_1");
    divsToBeAltered.push("sales_navigation_layer_2");
    divsToBeAltered.push("sales_navigation_layer_3");
    divsToBeAltered.push("sales_navigation_layer_4");
    divsToBeAltered.push("sales_navigation_layer_5");
    divsToBeAltered.push("sales_navigation_layer_6");

    for (var x = 0; x < divsToBeAltered.length; x++) {
      if (document.getElementById(divsToBeAltered[x]) && document.getElementById(divsToBeAltered[x]) != null && document.getElementById(divsToBeAltered[x]).getElementsByTagName('a').length != 0) {
        if (divsToBeAltered[x] != "downloadMainTeaser") {
          for (var i = 0; i < document.getElementById(divsToBeAltered[x]).getElementsByTagName('a').length; i++) {
            evaluatedLink = document.getElementById(divsToBeAltered[x]).getElementsByTagName('a')[i].href;
            if (evaluatedLink.indexOf('javascript:') == -1 && evaluatedLink != '' && evaluatedLink.indexOf(prefix) == -1) {
              toBeReplaced = "http://" + window.location.hostname;
              document.getElementById(divsToBeAltered[x]).getElementsByTagName('a')[i].href = evaluatedLink.replace(toBeReplaced, prefix);
            }
          }
        }
        for (var i = 0; i < document.getElementById(divsToBeAltered[x]).getElementsByTagName('img').length; i++) {
          evaluatedLink = document.getElementById(divsToBeAltered[x]).getElementsByTagName('img')[i].src;
          toBeReplaced = "http://" + window.location.hostname;
          if (evaluatedLink.indexOf(prefix) == -1) {
            document.getElementById(divsToBeAltered[x]).getElementsByTagName('img')[i].src = evaluatedLink.replace(toBeReplaced, prefix);
          }
        }
      }
    }
  }
  changeLinksAccordingToStageDone = true;
}

function setCurtain(mode){
  if ((useCurtain) && (useCurtain == "true")) {
    if (mode == 1) {
      setVisibility(document.getElementById('iFrameContainer'), 0);
      moveObject(document.getElementById('iFrameContainer'), ((window.screen.width * 2) * (-1)));
      setVisibility(document.getElementById('curtain'), null, 'block');
    } else {
      setVisibility(document.getElementById('curtain'), null, 'none');
      if (typeof leftPos != 'undefined') {
        moveObject(document.getElementById('iFrameContainer'), leftPos);
      } else {
        moveObject(document.getElementById('iFrameContainer'), 0);
      }
      setVisibility(document.getElementById('iFrameContainer'), 1);
    }
  }
}

function trackTeaserClick(trackingPage, trackingPageTitel, targetPageUrl){
  if (confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl(trackingPage) + '?target=' + escape(buildValidServerRelativeUrl(targetPageUrl)) + '&source=' + escape(self.location.pathname);
    trackAbsolute(trackingUrl, trackingPageTitel, false, false);
  }
  return true;
}

function trackDownloadClick(trackingPage, trackingPageTitel, targetFileUrl){
  if (confTrackingEnabled) {
    var trackingUrl = buildValidServerRelativeUrl(trackingPage) + '?file=' + escape(buildValidServerRelativeUrl(targetFileUrl)) + '&source=' + escape(self.location.pathname);
    trackAbsolute(trackingUrl, trackingPageTitel, false, false);
  }
  return true;
}

splitSearchString();
highbandUser = false;
var detectedBandwidth = "low";
var userbandwidth = getCookieValue("userbandwidth");

var bandwidth = getCookieValue("bandwidth");

if (query.bandwidth) {
  if (query.bandwidth == "vhigh") {
    detectedBandwidth = "vhigh";
  }
} else if (userbandwidth) {
  detectedBandwidth = userbandwidth;
} else if (bandwidth) {
  detectedBandwidth = bandwidth;

   if(typeof enhanced_bandwidth_detection != "undefined" && typeof enhanced_bandwidth_detection_threshold != "undefined"){
     if(enhanced_bandwidth_detection) {
       bandwidth = getCookieValue("bw");
       if(bandwidth >= enhanced_bandwidth_detection_threshold) {
         detectedBandwidth = "vhigh";
       }
       else {
        detectedBandwidth = "low";
       }
     }
   }
}
if (detectedBandwidth == "vhigh") {
  highbandUser = true;
}
// workaround for iPad
if (ua.indexOf('ipad') > -1 && ua.indexOf('safari') > -1 && (confCountryTopic=="de")) {
  highbandUser = false;
}

var selectedBandwidth = "";
function setUserBandwidth(selectedBandwidth){
  var replyText = bandwidth_save_error_no_selection;
  var replyColor = "#000000";

  if (!isCookiesEnabled()) {
    replyText = bandwidth_save_error_no_cookies;
    replyColor = "#ff0000";
  } else if (selectedBandwidth == "vhigh" || selectedBandwidth == "low") {
    setCookie("userbandwidth", selectedBandwidth, "Sun, 31-Dec-2100 00:00:00 GMT", "/");
    replyText = bandwidth_save_confirm;
    closeBandwidthLayer();
    self.location.reload();
  } else if (selectedBandwidth == "auto") {
    setCookie("userbandwidth", "", "Wed, 31-Dec-1980 00:00:00 GMT", "/");
    replyText = bandwidth_save_confirm;
    closeBandwidthLayer();
    self.location.reload();
  } else if (selectedBandwidth == "") {
    replyText = bandwidth_save_error_no_selection;
    replyColor = "#ff0000";
  }
  document.getElementById("bandwidthReply").style.color = replyColor;
  writeIntoLayer("bandwidthReply", replyText);
}

function isCookiesEnabled(){
  document.cookie="bmwCookieEnabled=true";
  if(document.cookie.indexOf("bmwCookieEnabled=true")!= -1) {
    var expire=new Date();
    document.cookie = "bmwCookieEnabled=;expires=" + expire.toGMTString();
    return true;
  } else {
    return false;
  }
}

function resetBandwidthReply(){
  writeIntoLayer("bandwidthReply", "");
}

function changeBandwidth(){
  var reloadUrl = self.location.href;
  var bandwidthParameter;
  if (highbandUser) {
    bandwidthParameter = "bandwidth=low";
  } else {
    bandwidthParameter = "bandwidth=vhigh";
  }
  if (reloadUrl.indexOf("bandwidth=") != -1) {
    if (reloadUrl.indexOf("bandwidth=low") != -1 && bandwidthParameter == "bandwidth=vhigh") {
      reloadUrl = reloadUrl.replace(/bandwidth=low/g, "bandwidth=vhigh");
    } else {
      reloadUrl = reloadUrl.replace(/bandwidth=vhigh/g, "bandwidth=low");
    }
  } else {
    if (reloadUrl.indexOf("?") != -1) {
      if (reloadUrl.charAt(self.location.href.length) != "&") {
        reloadUrl += "&";
      }
    } else {
      reloadUrl += "?";
    }
    reloadUrl += bandwidthParameter;
  }
  if (reloadUrl.indexOf("#") != -1) {
    var pos_jumper = reloadUrl.indexOf("#");
    var jumper_to_end = reloadUrl.substr(pos_jumper);
    var jumper_link = jumper_to_end;
    var pos_jumper_end = jumper_to_end.length;
    if(jumper_to_end.indexOf("?") != -1){
      var pos_jumper_end = jumper_to_end.indexOf("?");
      jumper_link = jumper_to_end.substr(0, pos_jumper_end);
    }else if(jumper_to_end.indexOf("&") != -1){
      var pos_jumper_end = jumper_to_end.indexOf("&");
      jumper_link = jumper_to_end.substr(0, pos_jumper_end);
    }
    reloadUrl = reloadUrl.replace(jumper_link, "");
    reloadUrl += jumper_link;
  }

  self.location.href = reloadUrl;
}

function closeBandwidthLayer(){
  setCurtain(0);
  setVisibility("bandwidthlayer", 0);
  if((confCountryTopic=="de")&&(confLanguageTopic=="de")){
  document.getElementById("bandwidthlayer").style.display="none";
  }
  setVisibility("selectBoxContentBandwidth", 0);
  document.getElementById('changeVersionLink').className = "menu";
  bandwidthLayerState = 0;
}

function showBandwidthLayer(){
  setCurtain(1);
  selectedBandwidth = "";
  if (highbandUser) {
    bandwidth_headline = bandwidth_headline_low;
    bandwidth_copy = bandwidth_copy_low;
    bandwidth_link = bandwidth_link_low;
  } else {
    bandwidth_headline = bandwidth_headline_high;
    bandwidth_copy = bandwidth_copy_high;
    bandwidth_link = bandwidth_link_high;
  }

  var bandwidthSelectedOption = bandwidth_save_select;

  if(userbandwidth == "low") {
    bandwidthSelectedOption = bandwidth_save_lowband;
    selectedBandwidth='low';
  }
  else if (userbandwidth == "vhigh") {
    bandwidthSelectedOption = bandwidth_save_highband;
    selectedBandwidth='vhigh';
  }
  else {
    bandwidthSelectedOption = bandwidth_save_auto;
    selectedBandwidth='auto';
  }

  if((confCountryTopic=="de")&&(confLanguageTopic=="de")){
  var bandwidth_save_copy_2ndline = "Einstellung &#228;ndern in:";
  selectedBandwidthCopy = "";
  if(userbandwidth == "low"){
    selectedBandwidthCopy = "Basis-Inhalte";
  }else if (userbandwidth == "vhigh") {
    selectedBandwidthCopy = "Multimedia-Inhalte";
  }else {
    selectedBandwidthCopy = "Automatisch pr&uuml;fen";
  }
  var layerContent = '' +
  '  <div id="bandwidthClose"><a href="javascript:closeBandwidthLayer();" onmouseover="switchImage(\'closeImg\',1);" onmouseout="switchImage(\'closeImg\',0);"><img src="' + closeGif + '" id="closeImg" preload="' + close2Gif + '" width="13" height="12"></a></div>' +

  '  <div id="bandwidthlayerRight" class="strictMode">' +
  '    <b>' + bandwidth_save_headline + '</b>&nbsp;<b style="color:#003399">' + selectedBandwidthCopy + '</b>' +
  '    <div style="height:6px; overflow:hidden;"></div>' + bandwidth_save_copy +'<div style="height:7px; overflow:hidden;"></div>'+ bandwidth_save_copy_2ndline + '<div style="height:7px; overflow:hidden;"></div>' +
  '    <div style="height:2px; overflow:hidden;"></div>' +
  '    <div style="position:relative; z-index:1000;">';

  if(userbandwidth == "low"){
   layerContent +='<a href="javascript://" class="bwb_l" onclick="setUserBandwidth(\'vhigh\');selectedBandwidth=\'vhigh\';">' + bandwidth_save_highband + '</a><a href="javascript://" class="bwb_r" onclick="setUserBandwidth(\'auto\');selectedBandwidth=\'auto\';">' + bandwidth_save_auto + '</a>';
  }else if(userbandwidth == "vhigh"){
   layerContent +=' <a href="javascript://" class="bwb_l" onclick="setUserBandwidth(\'low\');selectedBandwidth=\'low\';">' + bandwidth_save_lowband + '</a><a href="javascript://" class="bwb_r" onclick="setUserBandwidth(\'auto\');selectedBandwidth=\'auto\';">' + bandwidth_save_auto + '</a>';
  }else{
   layerContent +='<a href="javascript://" class="bwb_l" onclick="setUserBandwidth(\'vhigh\');selectedBandwidth=\'vhigh\';">' + bandwidth_save_highband + '</a><a href="javascript://" class="bwb_r" onclick="setUserBandwidth(\'low\');selectedBandwidth=\'low\';">' + bandwidth_save_lowband + '</a>';
  }

 layerContent +='      </div>' +
  '    </div>' +
  '    <div id="bandwidthReply"></div>' +
  '  </div>' +
  '</div>';

  document.getElementById("bandwidthlayer").className="strictMode";

  }else{

  var layerContent = '' +
  '  <div id="bandwidthClose"><a href="javascript:closeBandwidthLayer();" onmouseover="switchImage(\'closeImg\',1);" onmouseout="switchImage(\'closeImg\',0);"><img src="' + closeGif + '" id="closeImg" preload="' + close2Gif + '" width="13" height="12"></a></div>' +
  '  <div id="bandwidthlayerLeft">' +
  '    <h3>' + bandwidth_headline + '</h3>' +
  '    <div style="height:6px; overflow:hidden;"></div>' + bandwidth_copy +
  '    <div style="height:15px; overflow:hidden;"></div>' +
  '    <a href="javascript:changeBandwidth();" class="standard" target="_self">' + bandwidth_link + '</a>' +
  '  </div>' +
  '  <div id="bandwidthlayerSeperator"></div>' +
  '  <div id="bandwidthlayerRight">' +
  '    <h3>' + bandwidth_save_headline + '</h3>' +
  '    <div style="height:6px; overflow:hidden;"></div>' + bandwidth_save_copy +
  '    <div style="height:2px; overflow:hidden;"></div>' +
  '    <div style="position:relative; z-index:1000;">' +
  '      <table width="182" cellspacing="0" cellpadding="0" border="0" bgcolor="#ffffff">' +
  '        <colgroup><col width="1"><col width="162"><col width="18"><col width="1"></colgroup>' +
  '        <tr>' +
  '          <td colspan="4" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + p003399Gif + '" width="182" height="1"></td>' +
  '        </tr>' +
  '        <tr>' +
  '          <td bgcolor="#003399"><img src="' + p003399Gif + '" width="1" height="16"></td>' +
  '          <td valign="middle" onClick="setVisibility(\'selectBoxContentBandwidth\');" onMouseover="directOrder[ \'Bandwidth\' ]=true;" onMouseout="directOrder[ \'Bandwidth\' ]=false;" style="cursor:pointer;"><span id="selectedValueBandwidth">&nbsp; ' + bandwidthSelectedOption + '</span></td>' +
  '          <td><a href="javascript:setVisibility(\'selectBoxContentBandwidth\');" onMouseover="directOrder[ \'Bandwidth\' ]=true;" onMouseout="directOrder[ \'Bandwidth\' ]=false;" onFocus="this.blur();"><img src="' + pulldownGif + '" width="18" height="16" border="0"></a></td>' +
  '          <td bgcolor="#003399"><img src="' + p003399Gif + '" width="1" height="16"></td>' +
  '        </tr>' +
  '        <tr>' +
  '          <td colspan="4" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + p003399Gif + '" width="182" height="1"></td>' +
  '        </tr>' +
  '      </table>' +
  '      <div id="selectBoxContentBandwidth" class="selectBoxContent" style="top:17px;display:none;visibility:hidden;background-color:#ffffff">' +
  '        <table cellspacing="0" cellpadding="0" border="0" width="182">' +
  '          <tr>' +
  '            <td width="1" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + transGif + '"></td>' +
  '            <td width="180" valign="top">' +
  '              <div id="block1Select" style="width:180px; background-color:#ffffff; height:70px; overflow:auto;">' +
  '                <div style="height:7px; overflow:hidden;"></div>' +
  '                <a href="javascript://" class="selectboxEntry" onclick="setOption(\'' + bandwidth_save_highband + '\',\'\',\'Bandwidth\',\'\',\'\',\'none\');selectedBandwidth=\'vhigh\';resetBandwidthReply();">&nbsp; ' + bandwidth_save_highband + '</a>' +
  '                <a href="javascript://" class="selectboxEntry" onclick="setOption(\'' + bandwidth_save_lowband + '\',\'\',\'Bandwidth\',\'\',\'\',\'none\');selectedBandwidth=\'low\';resetBandwidthReply();">&nbsp; ' + bandwidth_save_lowband + '</a>' +
  '                <a href="javascript://" class="selectboxEntry" onclick="setOption(\'' + bandwidth_save_auto + '\',\'\',\'Bandwidth\',\'\',\'\',\'none\');selectedBandwidth=\'auto\';resetBandwidthReply();">&nbsp; ' + bandwidth_save_auto + '</a><br>' +
  '              </div>' +
  '            </td>' +
  '            <td width="1" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + transGif + '" width="1" height="1"></td>' +
  '          </tr>' +
  '          <tr><td colspan="3" bgcolor="#003399" style="height:1px;font-size:0px;line-height:0px;"><img style="display:block;" src="' + p003399Gif + '" width="182" height="1"></td></tr>' +
  '        </table>' +
  '      </div>' +
  '    </div>' +
  '    <a href="javascript:setUserBandwidth(selectedBandwidth);" id="bandwidthBoxlink">' + bandwidth_save_button + '</a><br>' +
  '    <div id="bandwidthReply"></div>' +
  '  </div>' +
  '</div>';

  }

  bandwidthlayerPos = getWindowInformation('scrollTop');
  if (bandwidthlayerPos > 0) {
    document.getElementById("bandwidthlayer").style.top = (162 + bandwidthlayerPos) + "px";
  }
  writeIntoLayer("bandwidthlayer", layerContent)
  setVisibility("bandwidthlayer", 1);
   if((confCountryTopic=="de")&&(confLanguageTopic=="de")){
  document.getElementById("bandwidthlayer").style.display="block";
  }
  preload();
  document.getElementById('changeVersionLink').className = "menu linkHighlight";
  bandwidthLayerState = 1;
}

var bandwidthLayerState = 0;
function toggleBandwidthLayer(){
  if (bandwidthLayerState == 0) {
    showBandwidthLayer();
  } else {
    closeBandwidthLayer()
  }
}


function getFileName(file){
  var result, pathDiv, fileNameExt, extPos;
  pathDiv = (file.indexOf("/") >= 0) ? "/" : "\\"
  fileNameExt = file.substring(file.lastIndexOf(pathDiv) + 1);
  extPos = fileNameExt.lastIndexOf('.');
  result = (extPos > 1) ? fileNameExt.substring(0, extPos) : fileNameExt;
  return result;
}

function scrollToTop(){
  window.scrollTo(0, 0);
}


function alterCSSClass( className, cssArgument, cssValue ) {
  var cssRules = ( document.all )? 'rules':( document.getElementById )? 'cssRules':false;
  if ( cssRules != false ) {
    for ( var i = 0; i < document.styleSheets.length; i++ ) {
      var currentStyle = document.styleSheets[ i ];
      for ( var j = 0; j < currentStyle[ cssRules ].length; j++ ) {
        var currentRule = currentStyle[ cssRules ][ j ];
        if ( currentRule.selectorText == className ) {
          currentRule.style[ cssArgument ] = cssValue;
        }
      }
    }
  }
}

function setMainNavigationFolded(state, foldingSteps, foldInterval) {
}

function checkBottomNavi() {
  var currentWindowWith = getWindowInformation("winWidth");
  if(currentWindowWith < 982) {
    document.getElementById('metaNavigationInline').style.width = currentWindowWith + "px";
  }
  else {
    document.getElementById('metaNavigationInline').style.width = "982px";
  }
  persoSsoLoadJs();
}

//Perso SSO
var persoSsoShowBottomLogin = true;
var persoSsoTimer;
var persoSsoTimerMilliseconds = 100;
var persoSsoLoginFromBottomNavi = null;
var persoSsoSalutationHTML = "Willkommen #1 #2 #3 #4!"
var persoSsoLoginText = "Login"
var persoSsoLogoutText = "Logout"

function persoSsoLoadJs(){
  if(typeof confPersoEngineSSOEnabled == "boolean"){
    if(confPersoEngineSSOEnabled){
      var e = document.createElement("script");
      e.src = confPersoEngineProfileController + "?rtyp=js&pid=" + confPersoEnginePid;
      e.type="text/javascript";
      document.getElementsByTagName("head")[0].appendChild(e);
      e = document.createElement("script");
      e.src = getWcmsPrefix() + "/_common/silo/user_status.js.jsp?country="+confCountryId+"&language="+confLanguageId;
      e.type="text/javascript";
      document.getElementsByTagName("head")[0].appendChild(e);
      persoSsoTimer = setTimeout('persoSsoCheckJs()', persoSsoTimerMilliseconds);
    }
  }
}

function persoSsoCheckJs(){
  if(typeof perso_profile == "object"){
    if((typeof perso_profile.data_loaded == "boolean") && (typeof silo_user_status == "string")){
      if(persoSsoShowBottomLogin && document.getElementById("metaNavigationLogin") == null){
        persoSsoBuildBottomLoginHtml();
      }
      clearTimeout(persoSsoTimer);
      if (silo_sync_perso_sso_done) {
        if(silo_user_status != "no_user"){
          setVisibility("persoSsoLogout", 1, 'block');
          setVisibility("persoSsoLogin", 0, 'none');
        } else {
          setVisibility("persoSsoLogin", 1, 'block');
          setVisibility("persoSsoLogout", 0, 'none');
        }
      } else {
        if(perso_profile.login_status != "not_logged_in"){
          setVisibility("persoSsoLogout", 1, 'block');
          setVisibility("persoSsoLogin", 0, 'none');
        }else if(perso_profile.login_status != "logged_in"){
          setVisibility("persoSsoLogin", 1, 'block');
          setVisibility("persoSsoLogout", 0, 'none');
        }
      }
      if(document.getElementById("persoSsoSalutation") != null){
        if(typeof perso_profile.userdata == "object"){
          if(typeof confPersoSsoSalutation == "string"){
            persoSsoSalutationHTML = confPersoSsoSalutation;
          }
          if((typeof perso_profile.userdata.salutation == "string") && (perso_profile.userdata.salutation != "")){
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#1/, perso_profile.userdata.salutation);
          }else{
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#1/, "");
          }
          if((typeof perso_profile.userdata.title == "string") && (perso_profile.userdata.title != "")){
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#2/, perso_profile.userdata.title);
          }else{
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#2/, "");
          }
          if((typeof perso_profile.userdata.firstname == "string") && (perso_profile.userdata.firstname != "")){
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#3/, perso_profile.userdata.firstname);
          }else{
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#3/, "");
          }
          if((typeof perso_profile.userdata.lastname == "string") && (perso_profile.userdata.lastname != "")){
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#4/, perso_profile.userdata.lastname);
          }else{
            persoSsoSalutationHTML = persoSsoSalutationHTML.replace(/\#4/, "");
          }
          writeIntoLayer('persoSsoSalutation', persoSsoSalutationHTML);
          setVisibility("persoSsoSalutation", 1, 'block');
        }
      }
    }else{
      persoSsoTimer = setTimeout('persoSsoCheckJs()', persoSsoTimerMilliseconds);
    }
  }else{
    persoSsoTimer = setTimeout('persoSsoCheckJs()', persoSsoTimerMilliseconds);
  }
}

function persoSsoSendEvent(eventId, sessionId, rememberMe){
  if(typeof confPersoEngineSSOEnabled == "boolean"){
    if(confPersoEngineSSOEnabled){
      rememberMe = (rememberMe != "")?"&rme="+rememberMe:"";
      img = new Image();
      img.src = confPersoEngineSSOController + '&eid=' + eventId + '&sid=' + sessionId + rememberMe;
      return img;
    }
  }
  return null;
}

function persoSsoBuildBottomLoginHtml(){
  var newDiv = document.createElement("div");
  newDiv.id = "metaNavigationLogin";
  newDiv.style.paddingTop = "5px";
  newDiv.style.paddingLeft = "30px";
  document.getElementById("metaNavigationInline").appendChild(newDiv);

  var newA1 = document.createElement("a");
  newA1.id = "persoSsoLogin";
  newA1.href = "javascript:persoSSOLogin();";
  document.getElementById("metaNavigationLogin").appendChild(newA1);
  addClassName("persoSsoLogin", "hidden");

  var newImg1 = document.createElement("img");
  newImg1.src = "/_common/narrowband/img/palette/1x1_trans.gif";
  document.getElementById("persoSsoLogin").appendChild(newImg1);
  addClassName(newImg1, "arrow");
  if(typeof confPersoSsoLogin == "string"){
    persoSsoLoginText = confPersoSsoLogin;
  }
  var aText1 = document.createTextNode(persoSsoLoginText);
  document.getElementById("persoSsoLogin").appendChild(aText1);

  var newA1 = document.createElement("a");
  newA1.id = "persoSsoLogout";
  newA1.href = "javascript:persoSSOLogout();";
  document.getElementById("metaNavigationLogin").appendChild(newA1);
  addClassName("persoSsoLogout", "hidden");

  var newImg2 = document.createElement("img");
  newImg2.src = "/_common/narrowband/img/palette/1x1_trans.gif";
  document.getElementById("persoSsoLogout").appendChild(newImg2);
  addClassName(newImg2, "arrow");

  if(typeof confPersoSsoLogout == "string"){
    persoSsoLogoutText = confPersoSsoLogout;
  }
  var aText1 = document.createTextNode(persoSsoLogoutText);
  document.getElementById("persoSsoLogout").appendChild(aText1);
  changeLinksAccordingToStage();
}

function persoSsoBuildLoginIframe(){
  if(document.getElementById("profileDialog") == null){
    var newDiv = document.createElement("div");
    newDiv.id = "profileDialog";
    newDiv.style.position = "absolute";
    newDiv.style.top = "101px";
    newDiv.style.left = "296px";
    newDiv.style.width = "690px";
    newDiv.style.height = "555px";
    newDiv.style.visibility = "hidden";
    newDiv.style.overflow = "hidden";
    newDiv.style.zIndex = "1000";
    document.getElementsByTagName("body")[0].appendChild(newDiv);

    var newIframe = document.createElement("iframe");
    newIframe.id = "profileDialogIFrame";
    newIframe.name = "profileDialogIFrame";
    newIframe.scrolling = "no";
    newIframe.src = "";
    newIframe.style.background = "transparent";
    newIframe.style.width = "690px";
    newIframe.style.height = "555px";
    newIframe.style.border = "none";

    var allowtrans = document.createAttribute("allowtransparency");
    allowtrans.nodeValue = "true";
    newIframe.setAttributeNode(allowtrans);

    var frameBd = document.createAttribute("frameborder");
    frameBd.nodeValue = "0";
    newIframe.setAttributeNode(frameBd);

    document.getElementById("profileDialog").appendChild(newIframe);
  }
}

function persoSSOLogin(){
  persoSsoLoginFromBottomNavi = true;
  persoSsoBuildLoginIframe();
  document.getElementById("profileDialogIFrame").src = getWcmsPrefix() + "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/silo/login/login_flash.jsp?transfer=profile";
  setVisibility("profileDialog",1);
}

function persoSSOLogout(){
  persoSsoBuildLoginIframe();
  document.getElementById("profileDialogIFrame").src = getWcmsPrefix() + "/" + confCountryTopic + "/" + confLanguageTopic + "/_common/silo/login/logout.jsp?transfer=profile";
  setVisibility("profileDialog",1);
}

function persoSSOShowLogout(){
  setVisibility("persoSsoLogout", 1, 'block');
  setVisibility("persoSsoLogin", 0, 'none');
}

function persoSSOShowLogin(){
  setVisibility("persoSsoLogin", 1, 'block');
  setVisibility("persoSsoLogout", 0, 'none');
}

function getWcmsPrefix(){
  var prefix = "";
  if (self.location.href.indexOf('/bmw_edit/') != -1) {
    prefix = "/bmw_edit";
  } else if (self.location.href.indexOf('/bmw_qa/') != -1) {
    prefix = "/bmw_qa";
  } else if (self.location.href.indexOf('/bmw_prod/') != -1) {
    prefix = "/bmw_prod";
  }
  return prefix;
}
//Perso SSO

var isFolding, resetModulNaviTimer, moduleHeader;
function moduleNaviReset(){}

function highlightNavigations(moduleNaviFolded, initModuleNavigation, startCounter){
  changeLinksAccordingToStage();
  if (document.getElementById('mainNavigation') !== undefined) {
    mainNavigation = new MainNavigation('mainNavigation');
    mainNavigation.init();
  }
/*
  if (document.getElementById('moduleNavigation') != undefined) {
    moduleNavigation = new ModuleNavigation('moduleNavigation', moduleNaviFolded);
    moduleNavigation.init();
    clearTimeout(isFolding);
  }
*/
  if (browserId == "Firefox" && platform == "mac os x" && document.getElementsByTagName('embed').length > 0) {
    document.getElementById('moduleNavigation').style.MozOpacity = "1";
    document.getElementById('moduleNavigation').style.opacity = "1";
  }
  highlightBottomNavigation();
}
function highlightBottomNavigation(){
  var currentLinkList = document.getElementById('metaNavigationInline').getElementsByTagName('a');
  var links = new Array(currentLinkList.length);
  for (var i = 0; i < currentLinkList.length; i++) {
    if (currentLinkList[i].href.indexOf('javascript:') == -1 && currentLinkList[i].href.indexOf('http://') == -1) {
      links[i] = 'http://' + window.location.hostname + '' + currentLinkList[i].href;
    } else {
      links[i] = currentLinkList[i].href;
    }
  }
  var evaluatedLinks = evaluateHighlighting(location.href, links);
  var highlightedIndex = -1;
  var bestmatch = 999;
  for (var i = 0; i < evaluatedLinks.length; i++) {
    if (evaluatedLinks[i] < bestmatch) {
      bestmatch = evaluatedLinks[i];
      highlightedIndex = i;
      if (evaluatedLinks[i] == -2) {
        break;
      }
    }
  }
  if (highlightedIndex != -1) {
    currentLinkList[highlightedIndex].style.color = '#003399';
  }
}

function resetBottomNavigation(){}

function openChooseBandLayer(headline, copy, linktext_start, linktext_back){
  var chooseBandLayer = '<' + 'div id="contentHiBand">' +
  '<' + 'h2>' + headline + '</h2>' +
  '<' + 'span id="vSpace" style="padding-bottom:2px;"></span>' +
  '<' + 'p>' + copy + '</p>' +
  '<' + 'span id="vSpace" style="padding-bottom:19px;"></span>' +
  '<' + 'ul class="linkList">' +
  '<' + 'li><' + 'a href="javascript:changeToHiEndVersion();"><' + 'img src="' + transGif + '" class="arrow" alt="" />' + linktext_start + '</a></li>' +
  '<' + 'li><' + 'a href="javascript:closeChooseBandLayer();"><' + 'img src="' + transGif + '" class="arrow" alt="" />' + linktext_back + '</a></li>' +
  '</ul>' + '</div>' +
  '<' + 'div style="position:absolute; top:2px; right:2px; width:13px; height:12px;">' +
  '<' + 'a href="javascript:closeChooseBandLayer();" onMouseOver="document.getElementsByTagName(\'img\')[\'closeImgHighendLayer\'].src=\'' + close2Gif + '\';" onMouseOut="document.getElementsByTagName(\'img\')[\'closeImgHighendLayer\'].src=\'' + closeGif + '\';">' +
  '<' + 'img src="' + closeGif + '" id="closeImgHighendLayer" preload="' + close2Gif + '" width="13" height="12" />' + '</a>' +
  '</div>';
  var pos = getWindowInformation('scrollTop');
  var newDiv = document.createElement('div');
  newDiv.id = 'changeToHighend';
  newDiv.style.position = 'absolute';
  newDiv.style.top = 157 + pos + 'px';
  newDiv.style.left = '194px';
  newDiv.style.width = '632px';
  newDiv.style.height = '305px';
  newDiv.style.border = '1px solid #acacac';
  newDiv.style.backgroundColor = '#ffffff';

  newDiv.style.zIndex = 922;
  newDiv.innerHTML = chooseBandLayer;

  if (!document.getElementById('changeToHighend')) {
    document.getElementsByTagName('body')[0].appendChild(newDiv);
    document.getElementById('changeVersionLink').className = 'menu linkHighlight';
    setCurtain(1);
    curtainInUse = true;
  } else {
    closeChooseBandLayer();
    setCurtain(0);
    curtainInUse = false;
  }
}

var mainNavigation = { nodeAction:function(){} };
var MainNavigation = (function(){
  var _maxFold = 75;
  var hoverActive = false;
  var menuActive = false;
  var foldingActive = false;
  var oldMenuObject;
  var mnContainer;
  var idModules;
  var eventObj;
  var foldIntId;
  var mouseIntId;
  var _foldingSteps = 1;
  var _foldInterval = 10;
  var currentTop;
  var currentMouseY = 400;
  return (function(mainNavigationId){
    var self = this;
    this.init = function(){
      mnContainer = document.getElementById('mainNavigationContainer');
      idModules = document.getElementById('idModule');
      var mnTopicUsedVehicles = document.getElementById('topic_usedvehicle');
      var mnTopicOwner = document.getElementById('topic_owner');
      var mnTopicInsights = document.getElementById('topic_insights');
      var mnTopicMseries = document.getElementById('topic_mseries');
      var mnTopicXseries = document.getElementById('topic_xseries');

      var firstWidth = 0;
      if(mnTopicUsedVehicles != null) {
        firstWidth = mnTopicUsedVehicles.offsetWidth + 1;
      }

      var secondWidth = 0;
      if(mnTopicOwner != null) {
        var secondWidth = mnTopicOwner.offsetWidth + 1;
      }

      if(mnTopicOwner != null) {
        mnTopicOwner.getElementsByTagName('div')[0].style.left = -firstWidth + "px";
      }
      if(mnTopicInsights != null) {
        mnTopicInsights.getElementsByTagName('div')[0].style.left = -(firstWidth + secondWidth) + "px";
      }
      /* DE only */
      if(confCountryId=='DE' && (location.host.indexOf("//nl-")==-1 && location.host.indexOf("//ah-")==-1)){
        if(mnTopicXseries != null) {
          firstWidth = mnTopicXseries.offsetLeft + 1;
          mnTopicXseries.getElementsByTagName('div')[0].style.left = -firstWidth + "px";
        }
        if(mnTopicMseries != null) {
          firstWidth = mnTopicMseries.offsetLeft + 1;
          mnTopicMseries.getElementsByTagName('div')[0].style.left = -firstWidth + "px";
        }
      }
      /* end DE only */

      if (window.addEventListener) {
        document.addEventListener("click", function(){self.closeMenu(); }, false);
      } else if (window.attachEvent) {
        document.attachEvent("onclick", function(){self.closeMenu(); });
      }
      highlightNavigation();
    };
    this.initFolding = function(foldingSteps, foldInterval){
      if( modulenaviAnimation != false ){
        _foldingSteps = (foldingSteps !== undefined && typeof foldingSteps == 'number') ? foldingSteps : _foldingSteps;
        _foldInterval = (foldInterval !== undefined && typeof foldInterval == 'number' && foldInterval > 200) ? foldInterval : _foldInterval;
      }

      if(!foldingActive){
        mnContainer.style.top = 0;
        currentTop = parseInt(mnContainer.style.top, 10);
        eventObj = (window.document.compatMode && window.document.compatMode == "CSS1Compat") ? window.document.documentElement : window.document.body || null;
        $(document).mousemove(onMouseMoveEvent);
        mouseIntId = window.setInterval( function(){ triggerFolding(); }, 200 );
        foldingActive = true;
      }
      triggerFolding();
    };
    this.stopFolding = function(){
      mnContainer.style.top = 0;
      document.onmousemove = undefined;
      foldingActive = false;
      idModules.style.position = 'absolute';
      window.clearInterval(mouseIntId);
      window.clearInterval(foldIntId);
    }
    var highlightNavigation = function(){
      var mnObj = document.getElementById(mainNavigationId);
      var currentHighlightLinks = mnObj.getElementsByTagName('a');
      var linksMain = [];
      for (var i = 0; i < currentHighlightLinks.length; i++) {
        if (currentHighlightLinks[i].href.indexOf('javascript:') == -1 && currentHighlightLinks[i].href.indexOf('http://') == -1) {
          linksMain[i] = 'http://' + window.location.hostname + '' + currentHighlightLinks[i].href;
        } else {
          linksMain[i] = currentHighlightLinks[i].href;
        }
      }
      var evaluatedLinks = evaluateHighlighting(window.location.href, linksMain);
      var highlightedIndex = -1;
      var bestmatch = 999;
      for (var j = 0; j < evaluatedLinks.length; j++) {
        if (evaluatedLinks[j] < bestmatch) {
          bestmatch = evaluatedLinks[j];
          highlightedIndex = j;
          if (evaluatedLinks[j] == -2) {
            break;
          }
        }
      }
      if (highlightedIndex != -1) {
        var currentLink = currentHighlightLinks[highlightedIndex];
        addClassName(currentLink, 'mainNaviHighlight');
        var currentNavParent = currentLink.getAttribute('navParent');
        if (currentNavParent) {
          addClassName(document.getElementById(currentNavParent), 'mainNaviHighlight');
        }
        if ( hasClassName( currentLink, 'topicHeader' ) ) {
          if (currentHighlightLinks[ highlightedIndex + 1 ] ) {
            addClassName(currentHighlightLinks[highlightedIndex + 1], 'mainNaviHighlight');
          }
        }
      }
    };
    var onMouseMoveEvent = function(e){
      if (!e) {
        e = window.event;
      }
      currentMouseY = e.pageY ? e.pageY : e.clientY + eventObj.scrollTop;
    };
    var triggerFolding = function(){
      var currentHover = currentTop + parseInt(mnContainer.offsetHeight, 10) + 30;

		//needed for bmw.de-rebrush
	    var winurl=window.location.href;
		if((winurl.indexOf('/de/de/')!=-1)&&(winurl.indexOf('/de/de/impulse')==-1)&&(winurl.indexOf('/de/de/cooperations')==-1)){
			currentHover = currentTop + parseInt(mnContainer.offsetHeight, 10) + 120;
		}

      if (currentMouseY < currentHover && currentTop < 0) {
        window.clearInterval(foldIntId);
        foldIntId = window.setInterval( function(){ moveDown(); }, _foldInterval);
      } else if (currentMouseY > currentHover && currentTop > -_maxFold) {

        window.clearInterval(foldIntId);
        foldIntId = window.setInterval( function(){ moveUp(); }, _foldInterval);
      }
    };
    var moveDown = function(){
      currentTop = parseInt(mnContainer.style.top, 10);
      if (currentTop < 0) {
        var nextPos = (currentTop + (_maxFold / _foldingSteps));
        mnContainer.style.top = ( nextPos > 0 )?  '0px':nextPos + 'px';
        idModules.style.top = ( nextPos > 0 )?  '0px': nextPos * (-1);

			//needed for bmw.de-rebrush
			var winurl=window.location.href;
			if((winurl.indexOf('/de/de/')!=-1)&&(winurl.indexOf('/de/de/impulse')==-1)&&(winurl.indexOf('/de/de/cooperations')==-1)){
				document.getElementById('navigationBackground').style.top = ( nextPos > 0 )?  '0px':nextPos + 'px';
			}

      } else {
        window.clearInterval(foldIntId);
      }
    };
    var moveUp = function(){
      currentTop = parseInt(mnContainer.style.top, 10);
      if (currentTop > -_maxFold) {
        var nextPos = (currentTop - (_maxFold / _foldingSteps));
        mnContainer.style.top = ( nextPos < -_maxFold )?  -_maxFold + 'px':nextPos + 'px';
        idModules.style.top = "75px";

			//needed for bmw.de-rebrush
			var winurl=window.location.href;
			if((winurl.indexOf('/de/de/')!=-1)&&(winurl.indexOf('/de/de/impulse')==-1)&&(winurl.indexOf('/de/de/cooperations')==-1)){
				document.getElementById('navigationBackground').style.top =  ( nextPos < -_maxFold )?  -_maxFold+30 + 'px':nextPos+30 + 'px';
			}

      } else {
        window.clearInterval(foldIntId);
      }
    };

    this.closeMenu = function(){
      if (!hoverActive && oldMenuObject !== undefined) {
        this.nodeAction(oldMenuObject, 'click');
      }
    };
    this.nodeAction = function(nodeObject, eventType){
      if(confCountryId=='JP'){

      if ((oldMenuObject == nodeObject && eventType == 'click')) {
        setCurtain(0);
        if (foldingActive && eventType == 'click') {
          mouseIntId = window.setInterval(function(){ triggerFolding(); }, 200);
        }
        removeClassName(nodeObject.parentNode, 'active');
        oldMenuObject = undefined;
        menuActive = false;
        mainNaviOpen = false;
      } else {
        if( eventType == 'mouseover' ){
          setCurtain(1);
          if (foldingActive) {
            clearInterval(mouseIntId);
          }
        }
        if (eventType == 'mouseover' || (eventType == 'mouseover' && menuActive)) {
          if (oldMenuObject !== undefined) {
            removeClassName(oldMenuObject.parentNode, 'active');
          }
          addClassName(nodeObject.parentNode, 'active');
          oldMenuObject = nodeObject;
          menuActive = true;
          mainNaviOpen = true;
        }
      }

      }else{
      if ((oldMenuObject == nodeObject && eventType == 'click')) {
        setCurtain(0);
        if (foldingActive && eventType == 'click') {
          mouseIntId = window.setInterval(function(){ triggerFolding(); }, 200);
        }
        removeClassName(nodeObject.parentNode, 'active');
        oldMenuObject = undefined;
        menuActive = false;
        mainNaviOpen = false;
      } else {
        if( eventType == 'click' ){
          setCurtain(1);
          if (foldingActive) {
            clearInterval(mouseIntId);
          }
        }
        if (eventType == 'click' || (eventType == 'mouseover' && menuActive)) {
          if (oldMenuObject !== undefined) {
            removeClassName(oldMenuObject.parentNode, 'active');
          }
          addClassName(nodeObject.parentNode, 'active');
          oldMenuObject = nodeObject;
          menuActive = true;
          mainNaviOpen = true;
        }
      }
      }
      if (eventType == 'mouseover') {
        hoverActive = true;
      } else if (eventType == 'mouseout') {
        hoverActive = false;
      }

      return false;
    };
  });
})();

  selectBoxes = new Array();
  directOrder = new Array();
  function checkSelectBoxStatus() {
    for(j=0;j<selectBoxes.length;j++) {
      if(!directOrder[selectBoxes[j]]) {
        setVisibility('selectBoxContent'+selectBoxes[j],0,'none');
      }
    }
  }

  function selectBoxNotify(formField) {
   ;
  }
   function setOption(text, value, formField, notify, index, formName) {
    formFieldValue = value;
    activeText = text;
    setVisibility('selectBoxContent'+formField,0,'none');
    writeIntoLayer('selectedValue'+formField, "&nbsp; " + text);

    if(formName != 'none') {
      if(typeof formName != 'undefined' && formName!=null && formName!=""){
        if(document.forms.length > 0) {
          document.forms[formName][formField].value = formFieldValue;
        }
      }else{
        if(document.forms.length > 0) {
          document.forms[0][formField].value = formFieldValue;
        }
      }
    }

    if(notify) {
      selectBoxNotify(formField,formFieldValue,index);
    }
  }

//SWF Object 1.5
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;


// ******** 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 = "";
  var dropdownCounter = 0;
  for(i = 0; i <= (datasheet_model_short.length - 1); i++) {
    dropdownCounter++;
    dropdownCode += '<a href="" model="' + datasheet_model_short[i] + '">' + datasheet_model[datasheet_model_short[i]]["model_name"] + '</a>';
  }
  $(".dropdown_content").html(dropdownCode);
  if(dropdownCounter <= 1) {
    $("#datasheet_select").remove();
  }
  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();
}

/*de-rebrush-includes*/

var selfurl=self.location.href;
if((selfurl.indexOf('/de/de/')!=-1)&&(selfurl.indexOf('/de/de/impulse')==-1)&&(selfurl.indexOf('de/de/_common/silo/impulse/')==-1)&&(selfurl.indexOf('/de/de/cooperations')==-1)){
	document.write('<scr');
	document.write('ipt src="'+buildValidServerRelativeUrl("/de/_common/js/rebrush_scripts_strict.js")+'" type="text/javascript">');
	document.write('</scr');
	document.write('ipt>');
	document.write('<link rel="STYLESHEET" type="text/css" href="'+buildValidServerRelativeUrl("/de/_common/css/rebrush_styles_strict.css")+'">');
}

var ecslServiceUrl = 'http://bmwfs-ecsl-live.dc.ham.mcon.net/SFLightHtmlService';
var ecslCurrentVehicles;
var ecslCurrentVehicle;
var ecslCurrentCalculations;
var ecslCurrentCalculation;
var ecslCurrentDepositAmount;
var ecslCurrentDepositPercent;
var ecslCurrentTerm
var ecslCurrentMileage;
var ecslCountry;
var ecslLanguage;
var ecslSenderId = 'eCOM-BaseSystem';
var ecslClientId = 'HTMLClient';
var ecslFormat = 'html';
var ecslBrand = 'BMW';

function ecslInit() {
  ecslCountry = confCountryTopic.toUpperCase();
  ecslLanguage = confLanguageTopic;
  ecslQueryVehicles();
  $("#ecslDepositSlider").slider({
    range: 'min',
    slide: function(event, ui) {
      $('#ecslInfoLayer').css('visibility','hidden');
      $("#ecslDepositValue").text(ecslFormatNumber(ecslCurrentDepositAmount.allowedValues[ui.value]));
    },
    change: function(event, ui) {
      if (event.originalEvent != undefined) {
        ecslQueryDetailCalc();
      }
    }
  });
  $("#ecslTermSlider").slider({
    range: 'min',
    slide: function(event, ui) {
      $('#ecslInfoLayer').css('visibility','hidden');
      $("#ecslTermValue").text(ecslCurrentTerm.allowedValues[ui.value]);
    },
    change: function(event, ui) {
      if (event.originalEvent != undefined) {
        ecslQueryDetailCalc();
      }
    }
  });
  $("#ecslMileageSlider").slider({
    range: 'min',
    slide: function(event, ui) {
      $('#ecslInfoLayer').css('visibility','hidden');
      $("#ecslMileageValue").text(ecslFormatNumber(ecslCurrentMileage.allowedValues[ui.value]));
    },
    change: function(event, ui) {
      if (event.originalEvent != undefined) {
        ecslQueryDetailCalc();
      }
    }
  });
}

function ecslGetHeader() {
  return 'country:"' + ecslCountry + '",language:"' + ecslLanguage + '",senderId:"' + ecslSenderId + '",clientId:"' + ecslClientId + '",format:"' + ecslFormat + '"';
}

function ecslGetVehicle() {
  return 'brand:"' + ecslCurrentVehicle.brand + '",modelCode:"' + ecslCurrentVehicle.modelCode + '",modelName:"' + ecslCurrentVehicle.modelName + '",totalPrice:{modelPrice:' + ecslCurrentVehicle.totalPrice.modelPrice.value + ',optionsPrice:' + ecslCurrentVehicle.totalPrice.optionsPrice.value + '}';
}

function ecslGetCalculation() {
  return '"productId":"' + ecslCurrentCalculation.productId + '","financeParameters":[' + ecslGetFinanceParameters() + ']';
}

function ecslGetFinanceParameters() {
  var params = '';
  for (var idx=0, max = ecslCurrentCalculation.financeParameter.length; idx < max; idx++) {
    if (idx > 0) params += ',';
    var param = ecslCurrentCalculation.financeParameter[idx];
    var id = '"id":"'+param.id+'"';
    var value = '"value":'+param.value;
    if (param.id == 'DepositAmount') {
      value = '"value":'+ecslCurrentDepositAmount.allowedValues[$("#ecslDepositSlider").slider('option','value')];
    } else if (param.id == 'DepositPercent') {
      value = '"value":'+ecslCurrentDepositPercent.allowedValues[$("#ecslDepositSlider").slider('option','value')];
    } else if (param.id == 'Term') {
      value = '"value":'+ecslCurrentTerm.allowedValues[$("#ecslTermSlider").slider('option','value')];
    } else if (param.id == 'Mileage') {
      value = '"value":'+ecslCurrentMileage.allowedValues[$("#ecslMileageSlider").slider('option','value')];
    }
    var valueDataType = '"valueDataType":"'+param.valueDataType+'"';
    params += '{'+id+','+value+','+valueDataType+'}';
  }
  return params;
}

function ecslGetVehicleRequest() {
  return '{header:{' + ecslGetHeader() + '},vehicles:{brand:"' + ecslBrand + '",seriesCode:"' + ecslSeriesCode + '"}}';
}

function ecslGetDefCalcRequest() {
  return '{header:{' + ecslGetHeader() + '},vehicle:{' + ecslGetVehicle() + '}}';
}

function ecslGetDetCalcRequest() {
  return '{header:{' + ecslGetHeader() + '},vehicle:{' + ecslGetVehicle() + ',calculation:{' + ecslGetCalculation() + '}}}';
}

function ecslSetCurrentVehicle(vehicle) {
   ecslCurrentVehicle = vehicle;
   ecslInitVehicleOutput();
}

function ecslSetCurrentCalculation(calculation) {
  ecslCurrentCalculation = calculation;
  ecslInitFinanceProductOutput();
  ecslInitSliders();
}

function ecslAdjustCurrentCalculation(response) {
   ecslAdjustCalculation(response);
   ecslInitFinanceProductOutput();
   ecslInitSliders();
}

function ecslAdjustCalculation(response) {
  if (response.status.statusCode == 'OK' || response.status.statusCode == 'Warning') {
    var calculation = response.calculation;
    if (calculation.productId == ecslCurrentCalculation.productId) {
      ecslCurrentCalculation.financePayment.basePayment.value =
      calculation.financePayment.basePayment.value;
      ecslCurrentCalculation.financePayment.optionsFactor = calculation.financePayment.optionsFactor;
      for (var i=0, max = calculation.financeParameter.length; i < max; i++) {
        for (var j=0, max2 = ecslCurrentCalculation.financeParameter.length; j < max2; j++) {
          if (ecslCurrentCalculation.financeParameter[j].id == calculation.financeParameter[i].id) {
            ecslCurrentCalculation.financeParameter[j].value = calculation.financeParameter[i].value;
            ecslCurrentCalculation.financeParameter[j].allowedValues = calculation.financeParameter[i].allowedValues;
            break;
          }
        }
      }
    }
    $('#ecslErrorMessage').hide();
  } else {
    $('#ecslErrorMessage').text(response.status.errorText).show();
    $('#sales_navigation_layer_ecsl').height($('#sales_navigation_layer_ecsl .box').height() + 25);
    $('#sales_navigation_layer_ecsl').css("top", salesNavigationTopPos - ($('#sales_navigation_layer_ecsl .box').height() + 25));
  }
}

function ecslHideOutput() {
  $('#ecslInterestRate').hide();
  $('#ecslBallonAmount').hide();
}

function ecslInitVehicleOutput() {
  $('#ecslPriceValue').text(ecslCurrentVehicle.totalPrice.modelPrice.value);
  $('#ecslPriceLabel').text(ecslCurrentVehicle.totalPrice.modelPrice.label);
}

function ecslInitFinanceProductOutput() {
  ecslHideOutput();
  for (var idx=0, max = ecslCurrentCalculation.financeParameter.length; idx < max; idx++) {
    if (ecslCurrentCalculation.financeParameter[idx].id == 'InterestRate') {
      $('#ecslInterestRateName').text(ecslCurrentCalculation.financeParameter[idx].name);
      $('#ecslInterestRateValue').text(ecslFormatNumber(ecslCurrentCalculation.financeParameter[idx].value * 100));
      $('#ecslInterestRateLabel').text(ecslCurrentCalculation.financeParameter[idx].label);
      $('#ecslInterestRate').show();
    }
    if (ecslCurrentCalculation.financeParameter[idx].id == 'BallonAmount') {
      $('#ecslBallonAmountName').text(ecslCurrentCalculation.financeParameter[idx].name);
      $('#ecslBallonAmountValue').text(ecslFormatNumber(ecslCurrentCalculation.financeParameter[idx].value));
      $('#ecslBallonAmountLabel').text(ecslCurrentCalculation.financeParameter[idx].label);
      $('#ecslBallonAmount').show();
    }
  }
  $('#ecslMonthlyRateName').text(ecslCurrentCalculation.financePayment.basePayment.name);
  $('#ecslMonthlyRateValueLabel').text(ecslFormatNumber(ecslCurrentCalculation.financePayment.basePayment.value) + ' ' +  ecslCurrentCalculation.financePayment.basePayment.label);
  $('#ecslMonthlyRate').show();
  ecslHideCurtain();
}

function ecslInitSliderSteps(slider, param) {
  $(slider).slider('option', 'range', 'min');
  $(slider).slider('option', 'min', 0);
  $(slider).slider('option', 'max', param.allowedValues.length-1);
  for (var idx = 0, max = param.allowedValues.length; idx < max; idx++) {
    if (param.allowedValues[idx] == param.value) {
      $(slider).slider('option', 'value', idx);
      break;
    }
  }
}

function ecslInitSliders() {
  var milageFound = false;
  for (var idx=0, max = ecslCurrentCalculation.financeParameter.length; idx < max; idx++) {
    var param = ecslCurrentCalculation.financeParameter[idx];

    if (param.id == 'DepositAmount') {
      ecslCurrentDepositAmount = param;
      $('#ecslDepositName').text(param.name);
      $('#ecslDepositValue').text(ecslFormatNumber(param.value));
      $('#ecslDepositLabel').text(param.label);
      ecslInitSliderSteps('#ecslDepositSlider', param);
    }
    else if (param.id == 'DepositPercent') {
      ecslCurrentDepositPercent = param;
    }
    else if (param.id == 'Term') {
      ecslCurrentTerm = param;
      $('#ecslTermName').text(param.name);
      $('#ecslTermValue').text(param.value);
      $('#ecslTermLabel').text(param.label);
      ecslInitSliderSteps('#ecslTermSlider', param);
    }
    else if (param.id == 'Mileage') {
      ecslCurrentMileage = param;
      $('#ecslMileageName').text(param.name);
      $('#ecslMileageValue').text(ecslFormatNumber(param.value));
      $('#ecslMileageLabel').text(param.label);
      ecslInitSliderSteps('#ecslMileageSlider', param);
      milageFound = true;
    }
  }
  if(!milageFound) {
    $('#ecslMileage').hide();
  }
  else {
    $('#ecslMileage').show();
  }
}

function ecslFillVehicles(response) {
  var numVehicles = response.vehicles.length;
  $('#sales_navigation_select_ecsl_vehicle').html('');
  for (var idx=0; idx < numVehicles; idx++) {
    if(idx == 0) {
      $('#select_ecsl_vehicle').html(response.vehicles[idx].modelName);
    }
    $('#sales_navigation_select_ecsl_vehicle').append('<a href="' + response.vehicles[idx].modelCode + '" entryNumber="' + idx + '">' + response.vehicles[idx].modelName + '</a>');
  }

  $('#sales_navigation_select_ecsl_vehicle a').click(function(e) {
    e.preventDefault();
    $('#ecslErrorMessage').hide();
    $('#ecslInfoLayer').css('visibility','hidden');
    $("#select_ecsl_vehicle").html($(this).html());
    $('#sales_navigation_select_ecsl_vehicle').hide();

    ecslSetCurrentVehicle(ecslCurrentVehicles[$(this).attr('entryNumber')]);
    ecslQueryFinanceProducts();
  });


  ecslCurrentVehicles = response.vehicles;
  ecslSetCurrentVehicle(response.vehicles[0]);
  ecslQueryFinanceProducts();
}

function ecslFillFinanceProducts(response) {
  var numFinProds = response.calculations.length;
   $('#sales_navigation_select_ecsl_fp').html('');
  for (var idx = 0; idx < numFinProds; idx++) {
    if(idx == 0) {
      $('#select_ecsl_fp').html(response.calculations[idx].productName);
    }
    $('#sales_navigation_select_ecsl_fp').append('<a href="' + 1 + '" entryNumber="' + idx + '">' + response.calculations[idx].productName + '</a>');
    $('#sales_navigation_select_ecsl_fp a').click(function(e) {
      e.preventDefault();
      $('#ecslErrorMessage').hide();
      $('#ecslInfoLayer').css('visibility','hidden');
      $("#select_ecsl_fp").html($(this).html());
      $('#sales_navigation_select_ecsl_fp').hide();
      ecslSetCurrentCalculation( ecslCurrentCalculations[$(this).attr('entryNumber')] );
    });
   }
   ecslCurrentCalculations = response.calculations;
   ecslSetCurrentCalculation(response.calculations[0]);

}

function ecslQueryVehicles() {
  $.ajax({
    dataType: 'jsonp',
    data: 'method=getModels&data='+ecslGetVehicleRequest(),
    jsonp: 'getModelsCallback',
    url: ecslServiceUrl,
    sucess: function(response) {
      ecslFillVehicles(response);
    }
  });
}

function getModelsCallback(response) {
  ecslFillVehicles(response);
}

function ecslQueryFinanceProducts() {
  ecslHideOutput();
  ecslShowCurtain();
  $.ajax({
    dataType: 'jsonp',
    data: 'method=getDefaultCalculations&data='+ecslGetDefCalcRequest(),
    jsonp: 'getDefaultCalculationsCallback',
    url: ecslServiceUrl,
    sucess: function(response) {
      ecslFillFinanceProducts(response);
    }
  });
}

function getDefaultCalculationsCallback(response) {
  ecslFillFinanceProducts(response);
}

function ecslQueryDetailCalc() {
  $.ajax({
    dataType: 'jsonp',
    data: 'method=getDetailCalculation&data='+ecslGetDetCalcRequest(),
    jsonp: 'getDetailCalculationCallback',
    url: ecslServiceUrl,
    sucess: function(response) {
      ecslAdjustCurrentCalculation(response);
    }
  });
}

function getDetailCalculationCallback(response) {
  ecslAdjustCurrentCalculation(response);
}

function ecslFormatNumber(number) {
  var n = ""+number;
  var s = 0;
  if( n.indexOf("-") > -1 ) s=1;
  n = n.replace(".", ",");
  var idx = n.indexOf(',');
  if (idx != -1) {
    if (idx == n.length-2) n += "0";
  } else {
    idx = n.length;
    n += ",00";
  }
  for(sIdx = idx-3; sIdx > s; sIdx-=3 ) {
    n = n.substring( 0, sIdx ) + "." + n.substring( sIdx );
  }
  return n;
}

function ecslShowVehicleInfo() {
  $('#modelName').text(ecslCurrentVehicle.modelName);
  $('#seriesName').text(ecslCurrentVehicle.seriesName);
  $('#editionName').text(ecslCurrentVehicle.editionName);
  $('#modelCode').text(ecslCurrentVehicle.modelCode);
  $('#seriesCode').text(ecslCurrentVehicle.seriesCode);
  $('#brand').text(ecslCurrentVehicle.brand);
  $('#additionalInfos_vehicle').empty();
  for (var idx=0, max = ecslCurrentVehicle.additionalInfos.length; idx < max; idx++) {
    $('#additionalInfos_vehicle').append('<li>'
    + ecslCurrentVehicle.additionalInfos[idx].id+":"
    + '<br/>name='+ecslCurrentVehicle.additionalInfos[idx].name
    + '<br/>value='+ecslCurrentVehicle.additionalInfos[idx].value
    + '<br/>label='+ecslCurrentVehicle.additionalInfos[idx].label
    + '</li>')
  }
  $('#vehicleInfo').dialog('open');
}

function ecslShowInfo() {
  if($('#ecslInfoLayer').css('visibility') == 'visible') {
    $('#ecslInfo').removeClass('ecslOfferActive');
    $('#ecslInfoLayer').css('visibility','hidden');
  }
  else {
    $('#ecslInfo').addClass('ecslOfferActive');
    $('#ecslInfoLayer').css('top', $('#ecslbox').offset().top - 2 + "px" );
    $('#ecslInfoLayer').css('left', $('#ecslbox').offset().left + 180 + "px" );

    for (var idx = 0; idx < ecslCurrentCalculation.additionalInfos.length; idx++) {
      if (ecslCurrentCalculation.additionalInfos[idx].id == 'disclaimerText') {
        $('#ecslDisclaimerText').text(ecslCurrentCalculation.additionalInfos[idx].value);
      } else if (ecslCurrentCalculation.additionalInfos[idx].id == 'productName') {
        $('#ecslProductName').text(ecslCurrentCalculation.additionalInfos[idx].value);
      } else if (ecslCurrentCalculation.additionalInfos[idx].id == 'shortProductText') {
        $('#shortProductText').text(ecslCurrentCalculation.additionalInfos[idx].value);
      }
    }
    for (var idx=0; idx < ecslCurrentCalculation.financeParameter.length; idx++) {
      if (ecslCurrentCalculation.financeParameter[idx].id == 'DepositAmount') {
        $('#ecslFpInfoDepositAmountValue').text(ecslFormatNumber(ecslCurrentCalculation.financeParameter[idx].value));
        $('#ecslFpInfoDepositAmountLabel').text(ecslCurrentCalculation.financeParameter[idx].label);
      }
      else if (ecslCurrentCalculation.financeParameter[idx].id == 'DepositPercent') {
        $('#ecslFpInfoDepositPercentValue').text(ecslFormatNumber(ecslCurrentCalculation.financeParameter[idx].value));
      }
      else if (ecslCurrentCalculation.financeParameter[idx].id == 'Term') {
        $('#ecslFpInfoTermValue').text(ecslCurrentCalculation.financeParameter[idx].value);
        $('#ecslFpInfoTermLabel').text(ecslCurrentCalculation.financeParameter[idx].label);
      }
      else if (ecslCurrentCalculation.financeParameter[idx].id == 'FinancedAmount') {
        $('#ecslInfoAdd1Name').text(ecslCurrentCalculation.financeParameter[idx].name);
        $('#ecslInfoAdd1Value').text(ecslFormatNumber(ecslCurrentCalculation.financeParameter[idx].value));
        $('#ecslInfoAdd1Label').text(ecslCurrentCalculation.financeParameter[idx].label);
      }
      else if (ecslCurrentCalculation.financeParameter[idx].id == 'ServiceChargeAmount') {
        $('#ecslInfoAdd2Name').text(ecslCurrentCalculation.financeParameter[idx].name);
        $('#ecslInfoAdd2Value').text(ecslFormatNumber(ecslCurrentCalculation.financeParameter[idx].value));
        $('#ecslInfoAdd2Label').text(ecslCurrentCalculation.financeParameter[idx].label);
      }
      else if (ecslCurrentCalculation.financeParameter[idx].id == 'TotalCredit') {
        $('#ecslInfoAdd3Name').text(ecslCurrentCalculation.financeParameter[idx].name);
        $('#ecslInfoAdd3Value').text(ecslFormatNumber(ecslCurrentCalculation.financeParameter[idx].value));
        $('#ecslInfoAdd3Label').text(ecslCurrentCalculation.financeParameter[idx].label);
      }
      else if (ecslCurrentCalculation.financeParameter[idx].id == 'NominalInterestRate') {
        $('#ecslInfoAdd4Name').text(ecslCurrentCalculation.financeParameter[idx].name);
        $('#ecslInfoAdd4Value').text(ecslCurrentCalculation.financeParameter[idx].value);
        $('#ecslInfoAdd4Label').text(ecslCurrentCalculation.financeParameter[idx].label);
      }
    }
/*
    for (var idx = 0; idx < ecslCurrentCalculation.additionalInfos.length; idx++) {
      if (ecslCurrentCalculation.additionalInfos[idx].id == 'shortDisclaimerText') {
        $('#ecslShortDisclaimer').text(ecslCurrentCalculation.additionalInfos[idx].value);
        break;
      }
    }
*/

    dialogBoxesSetDimensions();
    ecslInfoSetDimensions();
    $('#ecslInfoLayer').css('visibility','visible');
  }
}


function ecslShowCurtain() {
  var boxheight = $('#ecslbox').height() + 25;
  $('#ecslCurtainLoading').css('bottom', (boxheight - 44) / 2);
  $('#ecslCurtain').css('height', boxheight).show();
}

function ecslHideCurtain() {
  $('#ecslCurtain').hide();
}


function ecslInfoSetDimensions() {
  var contentHeight = $('#ecslInfoLayer .content').height() + 15;
  $('#ecslInfoLayer img.background').attr("height", contentHeight);
}

/**
 * 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});
    }
  }
}


function showSiloLayer(transferId, topPos, leftPos, layerWidth, layerHeight, type, country, language) {
  var server = "";
  if(typeof(country) !== 'undefined' && typeof(language) !== 'undefined'){
    server="https://secure.bmw.com";
  } else {
  	 if(typeof(country) !== 'undefined') {
  	 		language = confLanguageTopic;
  	 } else {
  	 		country = confCountryTopic;
  	 		language = confLanguageTopic;
  	 }
  }  
  var siloJsp  = "";
  if(type == "reminder"){
    siloJsp  = server + "/_common/silo/pages/reminder_so/reminder.jsp" + "?transfer=" + transferId + "&country=" + country + "&language=" + language + "&hide_close_icon=true&httpIframe=true";
  } else if(type == "registration"){
    siloJsp  = server + "/_common/silo/pages/form-tabs/controller.jsp" + "?transfer=" + transferId + "&country=" + country + "&language=" + language + "&hide_close_icon=true&httpIframe=true";
  } else {
    return;
  }
  if (parseInt(layerWidth)>685){
	  layerWidth = "685px"
  }
  var siloCode = "<div id=\"siloDialog\" style=\"position:absolute; top:" + topPos + "; left:" + leftPos + "; width:" + layerWidth + "; height:" + layerHeight + "; z-index:850;overflow:hidden;\">";
  siloCode    += "<div id=\"closeAllButton\" style=\"display:block;position:absolute;top:9px;left: " + (parseInt(layerWidth) - 27) + "px;\"><a href=\"javascript:closeSiloLayer();\" onmouseover=\"switchImage('closeButton', 1);\" onmouseout=\"switchImage('closeButton', 0);\" ><img src=\"" +  getWcmsPrefix() + "/_common/html/img/standard_elements/close.gif\" preload=\"" +  getWcmsPrefix() + "/_common/html/img/standard_elements/close-h.gif\" id=\"closeButton\" width=\"13\" height=\"12\" alt=\"\"></a><br></div>";
  siloCode    += "<iframe id=\"siloDialogIFrame\" onLoad=\"$('#closeAllButton').show();\" name=\"siloDialogIFrame\"  style=\"background:transparent; width:" + layerWidth + "; height:" + layerHeight + "; border: none;\" allowtransparency=\"true\" src=\"";
  siloCode    += buildValidServerRelativeUrl(siloJsp);
  siloCode    += "\" frameborder=\"0\" scrolling=\"no\"></iframe></div>";
  $("#siloDialog").remove();
  $("body").append(siloCode);
  $("#siloDialog").show();
  preload();
}

function closeSiloLayer() {
  $("#siloDialog").hide();
}


var currentLargeTeaserName    = "";
var currentLargeTeaserImage   = "";
var nextLargeTeaserImage      = "";
var largeBasicTeasersPreload  = new Image();
var largeBasicTeasers         = new Array();
var largeTeaserArray          = new Array();
var largeFlashTeasers         = new Array();

var largeTeaserOIDListOrignal = new Array();
var largeTeaserOIDListRandom = new Array();
var currentLargeTeaser = 0;
var maxLargeTeaser = 4;
var largeTeaserRule = 1;
var largeTeaserAutoRotateActive = false;
var largeTeaserDefaultTime = 15;
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();
  initStandardSalesTeaser();
  checkFacebookAvailability();
}

function initOverview() {
  initTeaserList1();
  initTeaserList2();
  initStandardTeaser();
  initStandardSalesTeaser();
}

function initLandingpage() {
  initStandardTeaser();
  initStandardSalesTeaser();
  foldMainNavi(true);
}

var myWcmsPrefix = "";
if (self.location.href.indexOf('/bmw_edit/') != -1) {
  myWcmsPrefix = "/bmw_edit";
} else if (self.location.href.indexOf('/bmw_qa/') != -1) {
  myWcmsPrefix = "/bmw_qa";
} else if (self.location.href.indexOf('/bmw_prod/') != -1) {
  myWcmsPrefix = "/bmw_prod";
}

function initStandardTeaser() {
  $(".standardTeaser").each(function(i,e){

    var currentImageSrc = $(this).find(".media img").attr("src");
    if(currentImageSrc != ""){
      if((currentImageSrc.indexOf('/') == 0) && (currentImageSrc.indexOf(myWcmsPrefix) != 0)){
        $(this).find(".media img").attr("src", myWcmsPrefix + currentImageSrc);
      }
    }

    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() + "/sync/showroom_rebrush/_common/rebrush/swf/wrapper_modules_autorotate.swf";
      if(largeFlashTeasers[currentlargeFlashTeasers].swfurl == ""){
        largeTeaserSwfUrl =  getWcmsPrefix() + "/sync/showroom_rebrush/_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();
      startLargeTeaserTimer();
    }
    $(".teaserLargeContainer .skip, .teaserLargeStandardContainer .skip").html((currentLargeTeaser + 1) + " / " + (maxLargeTeaser+1));
    $("#largeTeaserOverlay").fadeOut(500);

    $(".teaserLargeContainer .skip, .teaserLargeStandardContainer .skip").bind("click", showNextLargeTeaser);

  }
}

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){
    $(".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 && maxLargeTeaser  > 0){
    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() + "/sync/showroom_rebrush/_common/rebrush/swf/wrapper_modules_autorotate.swf";
      if(largeFlashTeasers[currentlargeFlashTeasers].swfurl == ""){
        largeTeaserSwfUrl =  getWcmsPrefix() + "/sync/showroom_rebrush/_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)]).load(function() {
        $("#largeTeaserBasic").show();
        $("#" + largeTeaserOIDListRandom[currentLargeTeaser]).show();
        $("#largeTeaserOverlay").fadeOut(500);
      });
      if(largeTeaserAutoRotateActive){
        startLargeTeaserTimer();
      }
    }
    
/*    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 = 5;
  var returnList = new Array();
  if(teaserList.length < 5){
    teaserListLength = teaserList.length;
  }
  for (i=0; i<teaserListLength; ++i) {
    returnList[returnList.length] = teaserList[i];
  }
  return returnList;
}

function randomizeSimpleTeaser(teaserList, firstFix){
  var teaserListLength = 5;
  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 < 5){
    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);
  }
}

/* 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 endBrace = key.substr(key.length-1) == ')';
  if (endBrace) key = key.substr(0, key.length-1);
  var doSurgery = function (str, $1) {return (txtBefore + $1 + txtAfter);};
  var regXSearch = new RegExp(("(" + key.toRegExpString().replace((/\s+/g), "\\s+") + (endBrace ? "[^a]{1,1}" : "[a-zA-Z]{0,4}")+")"), iFlag);
  return txt.replace(regXSearch, doSurgery);
}



/*!
 * jQuery UI 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function(c,j){function k(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this)}).length}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.4",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,
b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==="hidden")return false;b=b&&b==="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,h,i){return c.ui.isOverAxis(a,d,h)&&c.ui.isOverAxis(b,e,i)},keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,
CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable",
"off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,
"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.each(["Width","Height"],function(a,b){function d(f,g,l,m){c.each(e,function(){g-=
parseFloat(c.curCSS(f,"padding"+this,true))||0;if(l)g-=parseFloat(c.curCSS(f,"border"+this+"Width",true))||0;if(m)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0});return g}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight,outerWidth:c.fn.outerWidth,outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c.style(this,h,d(this,f)+"px")})};c.fn["outer"+
b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c.style(this,h,d(this,f,true,g)+"px")})}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");if("area"===b){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&k(a)}return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==
b?a.href||!isNaN(d):!isNaN(d))&&k(a)},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}})(jQuery);
;/*!
 * jQuery UI Widget 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function(b,j){var k=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){b(this).triggerHandler("remove")});return k.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend(true,{},c.options);
b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==j){h=i;return false}}):
this.each(function(){var g=b.data(this,a);if(g){d&&g.option(d);g._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});
this._create();this._init()},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c}b.each(d,function(f,
h){e._setOption(f,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=
b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
;/*!
 * jQuery UI Mouse 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Mouse
 *
 * Depends:
 *	jquery.ui.widget.js
 */
(function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(a._preventClickEvent){a._preventClickEvent=false;b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&&
this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();
return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);c.browser.safari||a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mouseDistanceMet(a)&&
this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=a.target==this._mouseDownEvent.target;this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-
a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery);
;/*
 * jQuery UI Position 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Position
 */
(function(c){c.ui=c.ui||{};var m=/left|center|right/,n=/top|center|bottom/,p=c.fn.position,q=c.fn.offset;c.fn.position=function(a){if(!a||!a.of)return p.apply(this,arguments);a=c.extend({},a);var b=c(a.of),d=(a.collision||"flip").split(" "),e=a.offset?a.offset.split(" "):[0,0],g,h,i;if(a.of.nodeType===9){g=b.width();h=b.height();i={top:0,left:0}}else if(a.of.scrollTo&&a.of.document){g=b.width();h=b.height();i={top:b.scrollTop(),left:b.scrollLeft()}}else if(a.of.preventDefault){a.at="left top";g=h=
0;i={top:a.of.pageY,left:a.of.pageX}}else{g=b.outerWidth();h=b.outerHeight();i=b.offset()}c.each(["my","at"],function(){var f=(a[this]||"").split(" ");if(f.length===1)f=m.test(f[0])?f.concat(["center"]):n.test(f[0])?["center"].concat(f):["center","center"];f[0]=m.test(f[0])?f[0]:"center";f[1]=n.test(f[1])?f[1]:"center";a[this]=f});if(d.length===1)d[1]=d[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(a.at[0]==="right")i.left+=g;else if(a.at[0]==="center")i.left+=
g/2;if(a.at[1]==="bottom")i.top+=h;else if(a.at[1]==="center")i.top+=h/2;i.left+=e[0];i.top+=e[1];return this.each(function(){var f=c(this),k=f.outerWidth(),l=f.outerHeight(),j=c.extend({},i);if(a.my[0]==="right")j.left-=k;else if(a.my[0]==="center")j.left-=k/2;if(a.my[1]==="bottom")j.top-=l;else if(a.my[1]==="center")j.top-=l/2;j.left=parseInt(j.left);j.top=parseInt(j.top);c.each(["left","top"],function(o,r){c.ui.position[d[o]]&&c.ui.position[d[o]][r](j,{targetWidth:g,targetHeight:h,elemWidth:k,
elemHeight:l,offset:e,my:a.my,at:a.at})});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(j,{using:a.using}))})};c.ui.position={fit:{left:function(a,b){var d=c(window);b=a.left+b.elemWidth-d.width()-d.scrollLeft();a.left=b>0?a.left-b:Math.max(0,a.left)},top:function(a,b){var d=c(window);b=a.top+b.elemHeight-d.height()-d.scrollTop();a.top=b>0?a.top-b:Math.max(0,a.top)}},flip:{left:function(a,b){if(b.at[0]!=="center"){var d=c(window);d=a.left+b.elemWidth-d.width()-d.scrollLeft();var e=b.my[0]==="left"?
-b.elemWidth:b.my[0]==="right"?b.elemWidth:0,g=-2*b.offset[0];a.left+=a.left<0?e+b.targetWidth+g:d>0?e-b.targetWidth+g:0}},top:function(a,b){if(b.at[1]!=="center"){var d=c(window);d=a.top+b.elemHeight-d.height()-d.scrollTop();var e=b.my[1]==="top"?-b.elemHeight:b.my[1]==="bottom"?b.elemHeight:0,g=b.at[1]==="top"?b.targetHeight:-b.targetHeight,h=-2*b.offset[1];a.top+=a.top<0?e+b.targetHeight+h:d>0?e+g+h:0}}}};if(!c.offset.setOffset){c.offset.setOffset=function(a,b){if(/static/.test(c.curCSS(a,"position")))a.style.position=
"relative";var d=c(a),e=d.offset(),g=parseInt(c.curCSS(a,"top",true),10)||0,h=parseInt(c.curCSS(a,"left",true),10)||0;e={top:b.top-e.top+g,left:b.left-e.left+h};"using"in b?b.using.call(a,e):d.css(e)};c.fn.offset=function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(){c.offset.setOffset(this,a)});return q.call(this)}}})(jQuery);
;/*
 * jQuery UI Button 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Button
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function(a){var g,i=function(b){a(":ui-button",b.target.form).each(function(){var c=a(this).data("button");setTimeout(function(){c.refresh()},1)})},h=function(b){var c=b.name,d=b.form,e=a([]);if(c)e=d?a(d).find("[name='"+c+"']"):a("[name='"+c+"']",b.ownerDocument).filter(function(){return!this.form});return e};a.widget("ui.button",{options:{text:true,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",i);this._determineButtonType();
this.hasTitle=!!this.buttonElement.attr("title");var b=this,c=this.options,d=this.type==="checkbox"||this.type==="radio",e="ui-state-hover"+(!d?" ui-state-active":"");if(c.label===null)c.label=this.buttonElement.html();if(this.element.is(":disabled"))c.disabled=true;this.buttonElement.addClass("ui-button ui-widget ui-state-default ui-corner-all").attr("role","button").bind("mouseenter.button",function(){if(!c.disabled){a(this).addClass("ui-state-hover");this===g&&a(this).addClass("ui-state-active")}}).bind("mouseleave.button",
function(){c.disabled||a(this).removeClass(e)}).bind("focus.button",function(){a(this).addClass("ui-state-focus")}).bind("blur.button",function(){a(this).removeClass("ui-state-focus")});d&&this.element.bind("change.button",function(){b.refresh()});if(this.type==="checkbox")this.buttonElement.bind("click.button",function(){if(c.disabled)return false;a(this).toggleClass("ui-state-active");b.buttonElement.attr("aria-pressed",b.element[0].checked)});else if(this.type==="radio")this.buttonElement.bind("click.button",
function(){if(c.disabled)return false;a(this).addClass("ui-state-active");b.buttonElement.attr("aria-pressed",true);var f=b.element[0];h(f).not(f).map(function(){return a(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed",false)});else{this.buttonElement.bind("mousedown.button",function(){if(c.disabled)return false;a(this).addClass("ui-state-active");g=this;a(document).one("mouseup",function(){g=null})}).bind("mouseup.button",function(){if(c.disabled)return false;a(this).removeClass("ui-state-active")}).bind("keydown.button",
function(f){if(c.disabled)return false;if(f.keyCode==a.ui.keyCode.SPACE||f.keyCode==a.ui.keyCode.ENTER)a(this).addClass("ui-state-active")}).bind("keyup.button",function(){a(this).removeClass("ui-state-active")});this.buttonElement.is("a")&&this.buttonElement.keyup(function(f){f.keyCode===a.ui.keyCode.SPACE&&a(this).click()})}this._setOption("disabled",c.disabled)},_determineButtonType:function(){this.type=this.element.is(":checkbox")?"checkbox":this.element.is(":radio")?"radio":this.element.is("input")?
"input":"button";if(this.type==="checkbox"||this.type==="radio"){this.buttonElement=this.element.parents().last().find("label[for="+this.element.attr("id")+"]");this.element.addClass("ui-helper-hidden-accessible");var b=this.element.is(":checked");b&&this.buttonElement.addClass("ui-state-active");this.buttonElement.attr("aria-pressed",b)}else this.buttonElement=this.element},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible");this.buttonElement.removeClass("ui-button ui-widget ui-state-default ui-corner-all ui-state-hover ui-state-active  ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only").removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html());
this.hasTitle||this.buttonElement.removeAttr("title");a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments);if(b==="disabled")c?this.element.attr("disabled",true):this.element.removeAttr("disabled");this._resetButton()},refresh:function(){var b=this.element.is(":disabled");b!==this.options.disabled&&this._setOption("disabled",b);if(this.type==="radio")h(this.element[0]).each(function(){a(this).is(":checked")?a(this).button("widget").addClass("ui-state-active").attr("aria-pressed",
true):a(this).button("widget").removeClass("ui-state-active").attr("aria-pressed",false)});else if(this.type==="checkbox")this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed",true):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed",false)},_resetButton:function(){if(this.type==="input")this.options.label&&this.element.val(this.options.label);else{var b=this.buttonElement.removeClass("ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only"),
c=a("<span></span>").addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(),d=this.options.icons,e=d.primary&&d.secondary;if(d.primary||d.secondary){b.addClass("ui-button-text-icon"+(e?"s":d.primary?"-primary":"-secondary"));d.primary&&b.prepend("<span class='ui-button-icon-primary ui-icon "+d.primary+"'></span>");d.secondary&&b.append("<span class='ui-button-icon-secondary ui-icon "+d.secondary+"'></span>");if(!this.options.text){b.addClass(e?"ui-button-icons-only":"ui-button-icon-only").removeClass("ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary");
this.hasTitle||b.attr("title",c)}}else b.addClass("ui-button-text-only")}}});a.widget("ui.buttonset",{_create:function(){this.element.addClass("ui-buttonset");this._init()},_init:function(){this.refresh()},_setOption:function(b,c){b==="disabled"&&this.buttons.button("option",b,c);a.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){this.buttons=this.element.find(":button, :submit, :reset, :checkbox, :radio, a, :data(button)").filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass("ui-corner-left").end().filter(":last").addClass("ui-corner-right").end().end()},
destroy:function(){this.element.removeClass("ui-buttonset");this.buttons.map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy");a.Widget.prototype.destroy.call(this)}})})(jQuery);
;/*
 * jQuery UI Slider 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var a=this,b=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");b.disabled&&this.element.addClass("ui-slider-disabled ui-disabled");
this.range=d([]);if(b.range){if(b.range===true){this.range=d("<div></div>");if(!b.values)b.values=[this._valueMin(),this._valueMin()];if(b.values.length&&b.values.length!==2)b.values=[b.values[0],b.values[0]]}else this.range=d("<div></div>");this.range.appendTo(this.element).addClass("ui-slider-range");if(b.range==="min"||b.range==="max")this.range.addClass("ui-slider-range-"+b.range);this.range.addClass("ui-widget-header")}d(".ui-slider-handle",this.element).length===0&&d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");
if(b.values&&b.values.length)for(;d(".ui-slider-handle",this.element).length<b.values.length;)d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");this.handles=d(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(c){c.preventDefault()}).hover(function(){b.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){if(b.disabled)d(this).blur();
else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(c){d(this).data("index.ui-slider-handle",c)});this.handles.keydown(function(c){var e=true,f=d(this).data("index.ui-slider-handle"),h,g,i;if(!a.options.disabled){switch(c.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:e=
false;if(!a._keySliding){a._keySliding=true;d(this).addClass("ui-state-active");h=a._start(c,f);if(h===false)return}break}i=a.options.step;h=a.options.values&&a.options.values.length?(g=a.values(f)):(g=a.value());switch(c.keyCode){case d.ui.keyCode.HOME:g=a._valueMin();break;case d.ui.keyCode.END:g=a._valueMax();break;case d.ui.keyCode.PAGE_UP:g=a._trimAlignValue(h+(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:g=a._trimAlignValue(h-(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(h===
a._valueMax())return;g=a._trimAlignValue(h+i);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(h===a._valueMin())return;g=a._trimAlignValue(h-i);break}a._slide(c,f,g);return e}}).keyup(function(c){var e=d(this).data("index.ui-slider-handle");if(a._keySliding){a._keySliding=false;a._stop(c,e);a._change(c,e);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");
this._mouseDestroy();return this},_mouseCapture:function(a){var b=this.options,c,e,f,h,g;if(b.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c=this._normValueFromMouse({x:a.pageX,y:a.pageY});e=this._valueMax()-this._valueMin()+1;h=this;this.handles.each(function(i){var j=Math.abs(c-h.values(i));if(e>j){e=j;f=d(this);g=i}});if(b.range===true&&this.values(1)===b.min){g+=1;f=d(this.handles[g])}if(this._start(a,
g)===false)return false;this._mouseSliding=true;h._handleIndex=g;f.addClass("ui-state-active").focus();b=f.offset();this._clickOffset=!d(a.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:a.pageX-b.left-f.width()/2,top:a.pageY-b.top-f.height()/2-(parseInt(f.css("borderTopWidth"),10)||0)-(parseInt(f.css("borderBottomWidth"),10)||0)+(parseInt(f.css("marginTop"),10)||0)};this._slide(a,g,c);return this._animateOff=true},_mouseStart:function(){return true},_mouseDrag:function(a){var b=
this._normValueFromMouse({x:a.pageX,y:a.pageY});this._slide(a,this._handleIndex,b);return false},_mouseStop:function(a){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(a,this._handleIndex);this._change(a,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(a){var b;if(this.orientation==="horizontal"){b=
this.elementSize.width;a=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{b=this.elementSize.height;a=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}b=a/b;if(b>1)b=1;if(b<0)b=0;if(this.orientation==="vertical")b=1-b;a=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+b*a)},_start:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);
c.values=this.values()}return this._trigger("start",a,c)},_slide:function(a,b,c){var e;if(this.options.values&&this.options.values.length){e=this.values(b?0:1);if(this.options.values.length===2&&this.options.range===true&&(b===0&&c>e||b===1&&c<e))c=e;if(c!==this.values(b)){e=this.values();e[b]=c;a=this._trigger("slide",a,{handle:this.handles[b],value:c,values:e});this.values(b?0:1);a!==false&&this.values(b,c,true)}}else if(c!==this.value()){a=this._trigger("slide",a,{handle:this.handles[b],value:c});
a!==false&&this.value(c)}},_stop:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("stop",a,c)},_change:function(a,b){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("change",a,c)}},value:function(a){if(arguments.length){this.options.value=
this._trimAlignValue(a);this._refreshValue();this._change(null,0)}return this._value()},values:function(a,b){var c,e,f;if(arguments.length>1){this.options.values[a]=this._trimAlignValue(b);this._refreshValue();this._change(null,a)}if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;e=arguments[0];for(f=0;f<c.length;f+=1){c[f]=this._trimAlignValue(e[f]);this._change(null,f)}this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(a):this.value();
else return this._values()},_setOption:function(a,b){var c,e=0;if(d.isArray(this.options.values))e=this.options.values.length;d.Widget.prototype._setOption.apply(this,arguments);switch(a){case "disabled":if(b){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled");this.element.addClass("ui-disabled")}else{this.handles.removeAttr("disabled");this.element.removeClass("ui-disabled")}break;case "orientation":this._detectOrientation();
this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case "value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case "values":this._animateOff=true;this._refreshValue();for(c=0;c<e;c+=1)this._change(null,c);this._animateOff=false;break}},_value:function(){var a=this.options.value;return a=this._trimAlignValue(a)},_values:function(a){var b,c;if(arguments.length){b=this.options.values[a];
return b=this._trimAlignValue(b)}else{b=this.options.values.slice();for(c=0;c<b.length;c+=1)b[c]=this._trimAlignValue(b[c]);return b}},_trimAlignValue:function(a){if(a<this._valueMin())return this._valueMin();if(a>this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=a%b;a=a-c;if(Math.abs(c)*2>=b)a+=c>0?b:-b;return parseFloat(a.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var a=
this.options.range,b=this.options,c=this,e=!this._animateOff?b.animate:false,f,h={},g,i,j,l;if(this.options.values&&this.options.values.length)this.handles.each(function(k){f=(c.values(k)-c._valueMin())/(c._valueMax()-c._valueMin())*100;h[c.orientation==="horizontal"?"left":"bottom"]=f+"%";d(this).stop(1,1)[e?"animate":"css"](h,b.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(k===0)c.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},b.animate);if(k===1)c.range[e?"animate":"css"]({width:f-
g+"%"},{queue:false,duration:b.animate})}else{if(k===0)c.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},b.animate);if(k===1)c.range[e?"animate":"css"]({height:f-g+"%"},{queue:false,duration:b.animate})}g=f});else{i=this.value();j=this._valueMin();l=this._valueMax();f=l!==j?(i-j)/(l-j)*100:0;h[c.orientation==="horizontal"?"left":"bottom"]=f+"%";this.handle.stop(1,1)[e?"animate":"css"](h,b.animate);if(a==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},
b.animate);if(a==="max"&&this.orientation==="horizontal")this.range[e?"animate":"css"]({width:100-f+"%"},{queue:false,duration:b.animate});if(a==="min"&&this.orientation==="vertical")this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},b.animate);if(a==="max"&&this.orientation==="vertical")this.range[e?"animate":"css"]({height:100-f+"%"},{queue:false,duration:b.animate})}}});d.extend(d.ui.slider,{version:"1.8.4"})})(jQuery);
;


//videolayer
var videoLayerCode = '' +
'<div id="videoLightboxLayerCurtain">&nsbp;</div>' +
'<div id="videoLightboxLayer">' +
'  <div id="VLinnerDiv">' +
'    <div id="VLleft">' +
'      <a href="" onclick="javasscript:videoLayerPlayPrevious();return false;">&nbsp;</a>' +
'    </div>' +
'    <div id="VLcontent">' +
'      <div id="videoLightboxFlash">' +
'      </div>' +
'      <div id="VLtitle">' +
'        <span></span>' +
'      </div>' +
'      <div id="VLdownloads">' +
'        <div id="VLcore">' +
'        </div>' +
'      </div>' +
'      <div id="VLcloseButtonLayer">' +
'        <a href="" onclick="videoLayerClose(); return false;" class="VLcloseLink"></a>' +
'      </div>' +
'    </div>' +
'    <div id="VLright">' +
'      <a href="" onclick="javasscript:videoLayerPlayNext();return false;">&nbsp;</a>' +
'    </div>' +
'  </div>' +
'</div>' +
'<!--[if IE 6]>' +
'<style type="text/css">' +
'#videoLightboxLayer #VLinnerDiv #VLleft a  {' +
'  cursor:pointer;' +
'  background:none;' +
'  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\'' + getWcmsPrefix() + '/sync/showroom_rebrush/_common/files/img/gallery/media_gallery_arrow_left_white.png\', sizingMethod=\'crop\');' +
'}' +
'#videoLightboxLayer #VLinnerDiv #VLleft a:hover  {' +
'  background:none;' +
'  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\'' + getWcmsPrefix() + '/sync/showroom_rebrush/_common/files/img/gallery/media_gallery_arrow_left_blue.png\', sizingMethod=\'crop\');' +
'}' +
'#videoLightboxLayer #VLinnerDiv #VLright a {' +
'  cursor:pointer;' +
'  background:none;' +
'  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\'' + getWcmsPrefix() + '/sync/showroom_rebrush/_common/files/img/gallery/media_gallery_arrow_right_white.png\', sizingMethod=\'crop\');' +
'}' +
'#videoLightboxLayer #VLinnerDiv #VLright a:hover  {' +
'  background:none;' +
'  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\'' + getWcmsPrefix() + '/sync/showroom_rebrush/_common/files/img/gallery/media_gallery_arrow_right_blue.png\', sizingMethod=\'crop\');' +
'}' +
'</style>' +
'<![endif]-->';


var videoLayerPlayerSwf = buildValidServerRelativeUrl("/sync/showroom_rebrush/_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() + '/sync/showroom_rebrush/_common/files/img/gallery/media_gallery_arrow_left_blue.png');
    $('<img />').attr('src', getWcmsPrefix() + '/sync/showroom_rebrush/_common/files/img/gallery/media_gallery_arrow_right_blue.png');
    if(videoLayerVideoList.length == 1) {
      $("#videoLightboxLayer #VLleft, #videoLightboxLayer #VLright").hide();
    }
    else {
      $("#videoLightboxLayer #VLleft, #videoLightboxLayer #VLright").show();
    }

    $("#videoLightboxLayer #VLinnerDiv").css("width","1px").css("height","1px").css("marginLeft","1px").css("marginTop","1px").css("top","50%").css("left","50%");
    $("#videoLightboxLayer #VLinnerDiv #VLcontent").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 #VLdownloads").show();
    }
    else {
      var outerDivHeight = videoHeight + 25;
      var innerDivHeight = videoHeight;
      $("#videoLightboxLayer #VLdownloads").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 #VLinnerDiv").animate({
      width:outerDivWidth,
      height:outerDivHeight,
      marginLeft:marginLeft,
      marginTop:marginTop
    }, 500);



    $("#videoLightboxLayer #VLinnerDiv #VLcontent").animate({
      width:innerDivWidth,
      height:innerDivHeight
    }, 500, function(){$("#videoLightboxFlash").css("visibility","visible");});
    if(videos[videoId].headline) {
      $("#videoLightboxLayer #VLtitle span").html(videos[videoId].headline).show();
    }
    else {
      $("#videoLightboxLayer #VLtitle span").hide();
    }
    $("#videoLightboxLayer #VLdownloads #VLcore").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", "true");
    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 #VLinnerDiv").animate({
    width:"1px",
    height:"1px",
    marginLeft:"1px",
    marginTop:"1px"
  }, 500);
  $("#videoLightboxLayer #VLinnerDiv #VLcontent").animate({
    width:"1px",
    height:"1px"
  }, 500, function(){$("#videoLightboxLayer").hide(); });
  if(videoLayerHasClosedModulenavigation) {
    foldModuleNavi(false);
  }
  videoLayerHasClosedModulenavigation = false;
}

function videoLayerSubtitleGetter() {
  return videoLayerSubtitleArray;
}

