/************************************/
/* Erweiterung für JD Power 2008/03 */
/* -> Mouseovers konfiguriertbar    */
/* -> hl = "hilite"                 */
/* -> ll = "lolite"                 */
/************************************/
var g_homemenu_hl_fontcolor = "#CC0000"; //"rgb(204, 0, 0)";
var g_homemenu_hl_background_color = "transparent";
var g_homemenu_hl_background_color_Level5 = "#FFFFFF";
var g_homemenu_ll_background_color_Level5 = "#EEF2F5";
var g_homemenu_ll_fontcolor_level0 = "#ffffff";
var g_homemenu_ll_fontcolor_level1 = "#000000";
var g_homemenu_ll_background_color = "#eef2f5";
var g_homemenu_ll_background_image_level0 = "url(/images/arrows.gif)"; //"url(/images/arrow-white.gif)";
var g_homemenu_ll_background_image_level1 = "url(/images/arrows.gif)"; //"url(/images/arrow-gray.gif)";
var g_homemenu_ll_background_position_level0 = "0 -592px";
var g_homemenu_ll_background_position_level1 = "0 -592px";
var g_homemenu_Fadeout = true;
var g_jdpowerphase = "none";
var g_kbaseClassicStyle = true; 

//var g_psyma_navi_clicked = null;

// var g_timeout = -1;
var g_timeout = 1;
/* var g_timeoutTime = 80; */
var g_timeoutTime = 250; 
var g_openZoom = 0;

var g_imageNr = 1;
var g_req;
var g_is_home = false;

var g_currentKBase = null; // KBase instance handle.

var g_pageWidth = 839;
var g_maxShowScrollingItems = 4;
var g_formContainerWidth = 430;
var g_timeoutHide1 = 0;
var g_timeoutHide2 = 0;
var g_timeoutHide3 = 0;
var g_timeoutHide4 = 0;
var g_timeoutHead = 0;
var g_currentNav1 = "";
var g_currentNav2 = "";
var g_currentNav3 = "";
var g_currentNav4 = "";

var g_currentHi1 = "";
var g_currentHi2 = "";
var g_currentHi3 = "";
var g_currentHi4 = "";

var G_MAXSUBLAYERS = 30;
var G_MAXITEMS_MAINNAVI = 30;

var g_blackValue = 0;
var g_blackTimeout = 0;
var g_navShadeMax = .35;

var g_currentModelLink = '';
var g_is_opera = false;
var g_is_ie = false;
var g_is_ie5 = false;
var g_is_ie5_5 = false;
var g_is_ie6 = false;
var g_is_ie7 = false;
var g_is_ie8 = false;
var g_is_safari = false;
var g_is_mac = false;
var g_is_linux = false;
var g_contextDebug = "";
var g_fallbackImage = "";
var g_is_iPad = false;
var g_home_head_id = "homeHead";

var g_newWinFocus;
var g_page_nxid;

var z_wm_custnum = '';
var z_wm_page_name = '';
var z_wm_group_name = '';
var z_wm_campaign_key = '';
var z_wm_milestone = '';

/////////////////////////////////////////////////////////
// Homepage Menü - Position der Baureihengrafik berechnen
var g_home_modelnavi_background_xPos = 0;               // X-Position der HD Grafik für die Baureihen
var g_home_modelnavi_gridsize = 50;                     // Höheneinheit des Grids - alle 50px sitzt der Y-Achsen Nullpunkt der nächsten Baureihengrafik
var g_home_modelnavi_num_modelranges = 5;               // Anzahl Baureihen in der Grafik
var g_home_modelnavi_num_modelranges_background = g_home_modelnavi_num_modelranges + 1; // der HG der Baureihen befindet sich nach dem letzter Baureihengrafik (wird für der platzverbrauch wie eine zusätzliche Bauriehe gerechnet)
///
// Gibt die CSS background-position für eine Baureihe zurück (string).
// modelno: Position der Baureihe im Menü -> 1 = erste eingepflegte Baureihe
// hl     : true  -> die Y-Position für die Highlight/Mouse-Over Grafik der Baureihe wird zurückgegeben
//          false -> die Y-Position für die normale Grafik der Baureihe wird zurückgegeben
function get_homenavi_background_position(modelno, hl) {
	yPos = get_Background_ypos(modelno, hl)+50;
	yPos.toString();
    return g_home_modelnavi_background_xPos.toString() + "px" + " " + yPos + "px";
}
function get_Background_ypos(modelno, hl) {
    // Berechnung: y-Höhe des Grids*2 [noramle grafik + HL grafik] * (eingepflegte Baureihe -1) [da die erste Baureihe den Nullpunkt bei 0 hat)
    var tmpYPos = g_home_modelnavi_gridsize * 2 * (modelno - 1)
    if (hl == true)
        tmpYPos = tmpYPos + g_home_modelnavi_gridsize; // HL-Grafik wird unter der normalen Grafik eingepflegt
    return (-1 * tmpYPos); // * -1, da das HG Bild nach Oben verschoben wird um das nächste Bild anzuzeigen
}
/////////////////////////////////////////////////////////


// test for jQuery first
if (typeof(jQuery) != 'undefined') {
    $(document).ready(function() {
        initAll();
        initAll2();
        if (typeof (wiredminds) != 'undefined' && typeof (WIREDMINDSEXEC) == 'function')
            WIREDMINDSEXEC();
        else
            log("Skipping Wiredminds.");
    });
}
else {
    log("jQuery not available. You must load the jquery core library before this document.");
}

function initAll() {
    g_is_home = $("body[class*='home']").length > 0;
    log("HOMEPAGE: " + g_is_home);

    g_is_iPad = (navigator.userAgent.toLowerCase()).indexOf('ipad') != -1; ;
    //var swap = ($('div.introImage > img').length > 1); // && ($('.introImageIpad').length > 0);
    var swap = ($('div.introImage > img, div.introImage > div.slideshowWrapper').length > 1);
    if (g_is_iPad /*&& g_is_home*/ && (swap == true)) {
        $('#homeHead').remove();
        $('div.introImage > img').each(function () {
            if (!jQuery(this).hasClass('introImageIpad')) {
                jQuery(this).remove();
            }
        });
        $('div.introImage > div.slideshowWrapper').each(function () {
            if (!jQuery(this).hasClass('slideshowIpad')) {
                jQuery(this).remove();
            }
        });
        $('#homeHeadTablet, .introImageIpad, .slideshowIpad').css({ 'display': 'block' });
        g_home_head_id = "homeHeadTablet";
    }
    else {
            $('#homeHeadTablet, .introImageIpad, .slideshowIpad').remove();
            if (!g_is_iPad && g_is_home) {
                g_home_head_id = "homeHead";
        }
    }

    if (g_is_home) {
        ipadModifikations();
        moveTeaserbar();
        // Wird für Porsche-Stadt nicht benötigt
        // originTeaser();
    }

    initSlideShow();

    checkKBase();
    //if (CURRENTPOOL == 'canada') 
    getNXid();
    positionFooter();

    sniffAll();
    if (g_is_home) {
        initHome();
    }

    fixIE7Buttons();

    HideIfLoggedIn("ifLoggedOut");
    ShowIfLoggedIn("ifLoggedIn");
    //HideIfLoggedIn("ifmetaloggedout");
    //ShowIfLoggedIn("ifmetaLoggedin");

    initGallerySubtitles();
    
    initDealerSearch();
    // Wird für Porsche-Stadt nicht benötigt
    // specialSpotlightTrackings();

}
function fixIE7Buttons() {
    if (g_is_ie7) {
        $('a > img, a > span, a > span > img').css({ 'cursor': 'pointer' });
        //$('a > img, a > span, a > span > img').css({ 'cursor': 'pointer' });
        $('a > img').click(function () {
            //log('1 - click');
            $(this).parent().trigger('click');
        });
        $('a > span').click(function () {
            //log('2 - click');
            $(this).parent().trigger('click');
        });
        $('a > span > img').click(function () {
            //log('3 - click');
            $(this).parent().trigger('click');
        });
    }
}
function originTeaser() {
    var serviceUrl = '';
    var buttonText = '';
    var originText = '';
    var originTextSubclaim = '';
  
           serviceUrl = "http://test.origin.porsche.com/de/response.php"
            originText = 'Origin';
            originTextSubclaim = 'Share the world of Porsche';

    buttonText = '<img alt="' + originText + '" class="originClaim" src="/germany/ImageMachines/PageTitle.ashx/rendered.gif?text=' + originText + '&mode=origin"/>';
    buttonText += '<span title="' + originText + '" class="originSubclaim">' + originTextSubclaim + '</span>';
    //buttonText += '<img alt="' + originText + '" class="originSubclaim" src="/germany/ImageMachines/PageTitle.ashx/rendered.gif?text=' + originTextSubclaim + '&mode=originsubclaim"/>';
    //add Button
    $('#content').append('<div class="originTeaser hidden dropShadowDark"></div><div class="originButton dropShadowDark">' + buttonText + '</div>');

    jQuery('.originTeaser').porscheOrigin({ url: serviceUrl, count: 4, fadeSpeed: 150 });

    $('.originButton').click(function () {
        $('.originTeaser').toggleClass('hidden');
        $('.originButton').toggleClass('originButtonActive');
        if ($('.originTeaser').hasClass('hidden')) {
            dimHeadline(true);
        }
        else {
            dimHeadline(false);
        }
    });
    $('.topnav, #dealersearchShadow').mouseenter(function () {
        if (!$('.originTeaser').hasClass('hidden')) {
            $('.originTeaser').addClass('hidden');
            $('.originButton').removeClass('originButtonActive');
        }
    });
}

function checkKBase() {
    // setup kBase link behaviour
    if ($('.tabContent2').length!=0) return;

    $('ul.galleryKBase li.kbase a,ul.knowledgeBases li.kbase a').bind('click', function (e) {
        var itemIndex = $('ul.galleryKBase li.kbase a').index($(this));
        log("kbase clicked. itemIndex: " + itemIndex);
        clickKnowledgebase($(this).attr("href"), itemIndex);
        e.preventDefault(); // don't really click on the <a>.
    });

    handleDirectKBaseUrl();
    // if there is a direct kbase query,
    // open it.
}

function handleDirectKBaseUrl() {
    var query = getQueryString();
    log(query);
    var regex = /kbase=\/(kbase|event2).aspx((\?|\&)(pool|type|lang|id|callpath|marketpool|marketlang|gtabindex|itemindex)=.*){3,10}/ig;
    if (query.match(regex)) {
        var kbaseIndex = query.indexOf("kbase=") + ("kbase=").length;
        //log(kbaseIndex);
        var kbaseUrl = query.substring(kbaseIndex);
        var itemIndex = getQueryVariable('itemindex');
        if (itemIndex == '' || isNaN(parseInt(itemIndex)) || parseInt(itemIndex)<=0) {
            itemIndex = null;
        }
        else {
            itemIndex = parseInt(itemIndex)-1;
        }

        clickKnowledgebase(kbaseUrl, itemIndex);
    }
}

function getNXid() {

    for (var i = 0; i < document.getElementsByTagName('meta').length; i++) {
        if (document.getElementsByTagName('meta')[i].getAttribute('name') == 'nxid') {
            g_page_nxid = document.getElementsByTagName('meta')[i].getAttribute('content');
        }
    }
    log("nxid:" + g_page_nxid);
}


function getQueryString() {
    return window.location.search.substring(1);
}

function getQueryVariable(qv) {
    var pairs = getQueryString().split("&");
    for (i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split("=");
        if (pair[0] == qv) {
            return pair[1];
        }
    }
    return '';
}


// this is a porschewebsite hack and would probably not work in other cases..
// paints a grey border below the introImage div. 
// Used by the flash videos which are triggered on the same page by a button (not hmoepage).
function setIntroImageBorder() {
    log("setIntroImageBorder entered");
    var elm = document.getElementById('introImage');
    if (elm) {
        elm.style.borderBottom = 'solid 1px #CECECE';
        elm.style.width = '615px';
    }
}



function flash_onVideoStop() {
    var divLogo = document.getElementById('porscheWappen');
    var divHomeMenuShadow = document.getElementById('homeShadow');
    var divHomeMenu = document.getElementById('homemenue');

    if (divLogo)
        divLogo.style.display = 'block';
    if (divHomeMenu)
        divHomeMenu.style.display = 'block';
    if (divHomeMenuShadow)
        divHomeMenuShadow.style.display = 'block';
}

function flash_onVideoStart() {
    var divLogo = document.getElementById('porscheWappen');
    var divHomeMenuShadow = document.getElementById('homeShadow');
    var divHomeMenu = document.getElementById('homemenue');

    if(divLogo)
        divLogo.style.display = 'none';
    if(divHomeMenu)
        divHomeMenu.style.display = 'none';
    if(divHomeMenuShadow)
        divHomeMenuShadow.style.display = 'none';
}


// finds the first Element carrying the class name and changes its visibility.
function showHideByClassName(clsName, visible)
{
    var visibility = (visible == true) ? 'visible' : 'hidden';
    var display = (visible == true) ? 'block' : 'none';
    $("." + clsName).css({
        'visibility': visibility,
        'display': display
    });
}

//shows Navigation bar and shopping buttons
function showHomepageNavigation()
{
    // we don't use showHideClassByName here because of speed issues in IE6..
    // document.getElementById('topnav1').parentNode.style.visibility = 'visible';
    showHideByClassName("homeNavigation", true);
    showHideByClassName('shoppingButtons', true);
    showHideByClassName("shoppingShade", true);
}


// extracts pool name from the url. 
// Use the global variable if available.
function getPoolName() {
    if (typeof (CURRENTPOOL) != "undefined" && CURRENTPOOL != '') {
        //log('CURRENTPOOL:' + CURRENTPOOL);
        //log('CURRENTLANGUAGE:' + CURRENTLANGUAGE);
        return CURRENTPOOL;
    }
    else {
        // use the (brute) force
        var url = window.location.href;
        var startIndex = url.indexOf(window.location.hostname);
        var str = url.substr(startIndex, url.length - 1);
        retVal = str.split("/")[1];
        return retVal;
    }
}

// extracts site language from the url.
// determine default language, if no language is given.
// Example: http://www.porsche.com/japan/ ,where 'jp' is the implicit language)
// Use the global variable if available.
function getPoolLang(poolName) {
    // for importer pools
    if (typeof (CURRENTLANGUAGE) != "undefined" && CURRENTLANGUAGE != '') {
        return CURRENTLANGUAGE;
    }
    else {
        // use the (brute) force
        var url = window.location.href;
        var startIndex = url.indexOf(window.location.hostname);
        var str = url.substr(startIndex, url.length - 1);
        var lang = str.split("/")[2];
        if (
		lang == "de" ||
		lang == "en" ||
		lang == "es" ||
		lang == "fr" ||
		lang == "it" ||
		lang == "jp" ||
		lang == "nl" ||
		lang == "ko" ||
		lang == "th" ||
		lang == "zh" ||
		lang == "pt" ||
		lang == "tr"
		) {
            return (lang);
        }
        else {
            // check if the market has a default lang;
            switch (poolName) {
                case "china":
                    lang = "zh";
                    break;
                case "belgium":
                    lang = "en";
                    break;
                case "korea":
                    lang = "ko";
                    break;
                case "netherlands":
                    lang = "nl";
                    break;
                case "swiss":
                    lang = "de";
                    break;
                case "taiwan":
                    lang = "zh";
                    break;
                case "thailand":
                    lang = "th";
                    break;
                case "pco":
                    lang = "de";
                    break;
                case "turkey":
                    lang = "tr";
                    break;
                default:
                    lang = "none";
                    break;
            }
            return (lang);
        }
    }
}




function fitFrameFromParent(iHeight) {
    //log("test: " + iHeight);
    var elm = document.getElementById("mainframe");
    var footer = document.getElementById("footer");
    var search = document.getElementById("search");

    if (elm) {
        elm.style.height = (iHeight + 40 + 140) + "px";
        if (search) { search.style.display = "none"; }
        if (footer) footer.style.bottom = "-1px";
        if (search) { search.style.display = "block"; }
    }
}


function positionFooter()
{
    var footer = document.getElementById("footer");
    var search = document.getElementById("search");
    
    if (!g_is_home) setDocumentSize();

    var elm = document.getElementById("formcontrol");
    if (elm) {

        if ($('#formcontrol').Length) {
            $('#formcontrol').attr("style", "min-height:680px");
            footer.style.position = "relative";
        }
    }

    if (footer) { footer.style.bottom = "-1px"; }
    // Wird für Porsche-Stadt nicht benötigt
    // if (search) { search.style.bottom = "-1px"; }
}

function setDocumentSize() {

    var size = 350; //160 + 105 + 85;
    if ($('#menu3').length > 0) {
        size = $('#menu3').height() - 147 + $('#footer').height();
    }


        var elm = document.getElementsByTagName("a");

        // navi height
        if (elm) {
            for (i = 0; i < elm.length; i++) {
                var className = elm[i].className;

                switch (true) {
                    case containsStr(className, "navigationBelowHome"):
                        size += 24;
                        break;
                    case containsStr(className, "subNavigationChapter"):
                    case containsStr(className, "subSubNavigation"):
                    case containsStr(className, "subSubNavigationActive"):
                        size += 20; // 1 line: 16, 2 lines: 31;					
                        break;
                }
            }
        }
//    }

    // content height
    var childs = $("#content").children(":visible");
    // log(childs);
    var total = 0;
    for (var j = 0; j < childs.length; j++) {
        total += parseInt($(childs[j]).height());
    }
    //log('#menu3 :' + size);
    //log('#content :' + total);

    //size = (size < total ? total : size);
    $("#content").height(size < total ? total : size);
 
   
}

function containsStr(s, find) {
    if(s)return (s.indexOf(find) != -1);
}

function overHome()
{
    if (!(g_currentKBase && g_currentKBase.isOpen && g_is_safari)) {
        if (g_timeout != -1) { clearTimeout(g_timeout); }
        showNavHomeSub();
    }
}

function outHome()
{
    if (!(g_currentKBase && g_currentKBase.isOpen && g_is_safari)) {
        g_timeout = setTimeout("hideNavHomeSub()", g_timeoutTime);
    }
}

function overNavHomeSub()
{
    if (g_timeout != -1) { clearTimeout(g_timeout); }
}

function outNavHomeSub()
{
    if (g_timeout != -1) { clearTimeout(g_timeout); }
    g_timeout = setTimeout("hideNavHomeSub()", g_timeoutTime);
}

function showNavHomeSub()
{
    showLr("navigationHomeSub");
    showLr("navigationShade");
    setBackground("navigationHome", "rgb(242,242,242)");
}

function hideNavHomeSub()
{
    hideLr("navigationHomeSub");
    hideLr("navigationShade");
    setBackground("navigationHome", "rgb(255,255,255)");
}

function setBackground(id, sBack)
{
    var elm = document.getElementById(id);
    if(elm)elm.style.backgroundColor = sBack;
}

/* DIV Popup */
g_divPopupOpen = 0;
g_divPopupShadeborder = 8;
g_divPopupContentBorder = 15;
g_divPopupNaviSpace = 30;
g_divPopupHasCloseButton = false;

function openDivPopup(sUrl, imgWidth, imgHeight)
{
  if (g_divPopupOpen == 0)
  {
    g_divPopupHasCloseButton = true;
    // magic numbers follow, do not try at home
    var divHeight = imgHeight + (g_divPopupContentBorder * 2) + g_divPopupNaviSpace;
    var divWidth = imgWidth + (g_divPopupContentBorder * 2);
    var shadeHeight = imgHeight + (g_divPopupContentBorder * 2) + (g_divPopupShadeborder * 2) + g_divPopupNaviSpace + 2;
    var shadeWidth = imgWidth + (g_divPopupContentBorder * 2) + (g_divPopupShadeborder * 2) + 2;

    var elmShade = document.getElementById("divPopupShade");
    var elmDivPop = document.getElementById("divPopup");
    elmShade.className = 'bannerlibShade';
    elmDivPop.className = 'bannerlib';

    var imgX = g_pageWidth / 2 - imgWidth / 2;
    var imgY = Math.round( (viewportGetHeight() - imgHeight)/2 ) + viewportGetScrollY();

    if (imgY < 0) { imgY = 0; }
    if (imgX < 0) { imgX = 0; }

    elmShade.style.left = (imgX - g_divPopupShadeborder) + "px";
    elmShade.style.top = (imgY - g_divPopupShadeborder) + "px";
    elmShade.style.width = shadeWidth + "px";
    elmShade.style.height = shadeHeight + "px";

    elmDivPop.style.left = imgX + "px";
    elmDivPop.style.top = imgY + "px";
    elmDivPop.style.height = divHeight + "px";
    elmDivPop.style.width = divWidth + "px";

    var elmCloseButton = document.getElementById("closeButtonDivPopup");
    if (elmCloseButton) {
      elmCloseButton.style.left = (imgWidth - 19) + "px";
    }

    g_divPopupOpen = sUrl;

    prepareFillDivPopup(sUrl);
  }
}

function openDivPopupTemplate(sUrl, sType)
{
    if (g_divPopupOpen == 0)
    {
        g_divPopupHasCloseButton = true;
        var cssClassName = sType;
        var imgWidth, imgHeight;
        switch(sType)
        {
          case 'bannerlib':
            imgWidth = 758;
            imgHeight = 640;
            break;
          case 'bannerlibsky':
            imgWidth = 192;
            imgHeight = 670;
            break;
          case 'bannerlibfull':
            imgWidth = 498;
            imgHeight = 126;
            break;
          case 'bannerlibhalf':
            imgWidth = 264;
            imgHeight = 126;
            break;
          case 'bannerlibrect':
            imgWidth = 210;
            imgHeight = 216;
            break;
          case 'bannerlibmrect':
            imgWidth = 330;
            imgHeight = 316;
            break;
          case 'bannerlibpopuph':
            imgWidth = 230;
            imgHeight = 366;
            break;
          case 'bannerlibpopupr':
            imgWidth = 280;
            imgHeight = 316;
            break;
        }
        // magic numbers follow, do not try at home
        var divHeight = imgHeight;
        var divWidth = imgWidth;
        var shadeHeight = imgHeight + (g_divPopupShadeborder * 2) + 2;
        var shadeWidth = imgWidth + (g_divPopupShadeborder * 2) + 2;

        var elmShade = document.getElementById("divPopupShade");
        var elmDivPop = document.getElementById("divPopup");
        elmShade.className = cssClassName + 'Shade';
        elmDivPop.className = cssClassName;

        var imgX = g_pageWidth / 2 - imgWidth / 2;
        var imgY = Math.round( (viewportGetHeight() - imgHeight)/2 ) + viewportGetScrollY();

        if (imgY < 0) { imgY = 0; }
        if (imgX < 0) { imgX = 0; }

        elmShade.style.left = (imgX - g_divPopupShadeborder) + "px";
        elmShade.style.top = (imgY - g_divPopupShadeborder) + "px";
        elmShade.style.width = shadeWidth + "px";
        elmShade.style.height = shadeHeight + "px";

        elmDivPop.style.left = imgX + "px";
        elmDivPop.style.top = imgY + "px";
        elmDivPop.style.height = divHeight + "px";
        elmDivPop.style.width = divWidth + "px";

        var elmCloseButton = document.getElementById("closeButtonDivPopup");
        if (elmCloseButton) {
            elmCloseButton.style.left = (imgWidth - 19) + "px";
        }

        g_divPopupOpen = sUrl;

        prepareFillDivPopup(sUrl);
    }
}

function closeDivPopup()
{
    var elm = document.getElementById("divPopup");
    elm.innerHTML = "<p>&nbsp;</p>";
    elm.style.display = "none";

    hideLr("divPopupShade");
    g_divPopupOpen = 0;

    if (g_is_safari) {
        var introElm = document.getElementById("introImage");
        if (introElm) {
            introElm.style.visibility = "visible";
        }
    }
}

function prepareFillDivPopup(sUrl)
{
    if(sUrl.indexOf('?') > -1)sUrl += "&" + getCachePrevent();
    else sUrl += "?" + getCachePrevent();
    if (window.XMLHttpRequest) {
        g_req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        g_req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    g_req.onreadystatechange = fillDivPopup;
    g_req.open("GET", sUrl, true);
    g_req.send(null);
}

function fillDivPopup()
{
    if (g_req.readyState == 4)
    {
        if (g_req.status == 200)
        {
            if (g_is_safari) {
                var introElm = document.getElementById("introImage");
                if (introElm) {
                    introElm.style.visibility = "hidden";
                }
            }

            var s = "";
        
            var elmKB = document.getElementById("divPopup");
            var divPopWidth = elmKB.style.width;
            divPopWidth = divPopWidth.replace(/px/,'');
            var divPopHeight = elmKB.style.height;
            divPopHeight = divPopHeight.replace(/px/,'');

            divPopPageHeight = divPopHeight - (2 * g_divPopupContentBorder)
            divPopPageWidth = divPopWidth - (2 * g_divPopupContentBorder)

            divPopWidth-=17;
            divPopHeight-=17;

            s += "";
            if(g_divPopupHasCloseButton == true)
            {
              s += "<div style=\"left:" + divPopWidth + "px;\" class=\"closeButton\" id=\"closeButtonDivPopup\" onclick=\"closeDivPopup();\"><img src=\"/Images/close-button.gif\" alt=\"[X]\" title=\"Close\" /></div>";
            }            
            s += g_req.responseText;
            s = replStr(s, "<content>", "");
            s = replStr(s, "</content>", "");

            var sRun = getTextBetween(s, "// <![CDATA[", "// ]]>");
            sRun = replStr(sRun, ",wmode=opaque", ",");

            elmKB.innerHTML = s;

            var elmShade = document.getElementById("divPopupShade");
            elmKB = document.getElementById("divPopup");

            if (screen.width <= 800) {
                var imgHeight = 350;
                var elmWrapper = document.getElementById("divPopupWrapper");
                elmWrapper.style.height = (imgHeight - 80) + "px";
            }

            g_maxDivPage = getMaxDivPage('page');
            for(i=1;i<=g_maxDivPage;i++)
            {
              pageElm = document.getElementById('page' + i);
              if(pageElm)
              {
                pageElm.style.width = divPopPageWidth + 'px';
                pageElm.style.height = divPopPageHeight + 'px';
              }
            }
            naviElm = document.getElementById('divPopupNavi');
            if(naviElm)
            {
              naviElm.style.top = divPopPageHeight + 'px';
              naviElm.style.left = g_divPopupContentBorder + (divPopPageWidth/2 - 90/2) + 'px';
            }

            elmKB.style.display = "block";
            elmShade.style.display = "block";

            if (sRun != "") { eval(sRun); }
        }
        else
        {
            alert("Can't retrieve XML: " + g_req.statusText);
        }
    }
}

function getMaxDivPage(sName)
{
    var max = 0;
    var testElm = null;

    do
    {
      max++;
      testElm = document.getElementById(sName + max);
    }
    while(testElm != null)
    max--;
    return max;
}

g_currentDivPage = 1;
g_maxDivPage = 0;
function prevDivPage(sName)
{
    if(g_maxDivPage == 0)
    {
      g_maxDivPage = getMaxDivPage(sName);
    }
    var n = g_currentDivPage;
    n--;
    if (n <= 0){ n = g_maxDivPage;}

    if(n != g_currentDivPage)
    {
      showLr(sName + n);
      hideLr(sName + g_currentDivPage);
    }
    g_currentDivPage = n;
    return false;
}

function nextDivPage(sName)
{
    if(g_maxDivPage == 0)
    {
      g_maxDivPage = getMaxDivPage(sName);
    }
    var n = g_currentDivPage;
    n++;
    if (n > g_maxDivPage){ n = 1; }

    if(n != g_currentDivPage && g_maxDivPage > 1)
    {
      showLr(sName + n);
      hideLr(sName + g_currentDivPage);
    }
    g_currentDivPage = n;
    return false;
}

function clickKnowledgebase(sUrl, itemIndex) {
    if (sUrl == '') return;
    log("clickKnowledgebase entered.");
    if (g_currentKBase == null || (g_currentKBase != null && !g_currentKBase.isOpen )) {
        g_currentKBase = new KBase();
    }
    if (itemIndex >= 0) g_currentKBase.currentItemIndex = itemIndex;
    g_currentKBase.open(sUrl, itemIndex);
}



function KBase() {
    var self = this;    
    this.oldModelPage = (g_kbaseClassicStyle == true); // 
    //log("oldModelPage: " + this.oldModelPage);
    this.isOpen = false;
    this.currentPool = getPoolName();
    this.currentLanguage = getPoolLang(this.currentPool);
    this.isCuttingEdge = true;
    this.navigationBarTop = -1;
    this.navigationBarWidth = 857;
    this.navigationBarLeft = 106;
    this.flashContainerId = 'introImageKBase_flash';

    this.animateContent = function(isEnter, callback) {
        log("entering animateContent..");
        /*
        **  Animation Begin
        */
        var easing, animStartX, animEndX, transStart, transEnd;
        easing = 600;
        animStartX = 0;

        // cosmetic stuff. We'll show the bars again after the animation has ended.        
        if (isEnter) {
            animEndX = 0;
            transStart = 0.01;
            transEnd = 1.0;
        }
        else {
            if (self.prevRequested) {
                animEndX = self.contentWidth;
            }
            else {
                animEndX = -(self.contentWidth);
            }
            transStart = 1.0;
            transEnd = 0.01;
        }

        $("#knowledgeBase .animationWrapper")
            .css('opacity', transStart)
            .animate({
                opacity: transEnd,
                left: animEndX
            }, easing, 'swing', function() {

            //log("animateContent - Animation ended. Running callback : " + callback);            
                if (typeof (callback) == 'function') {
                    callback();
                }
            });
        /*
        ** Animation End
        */

    }

    this.clear = function() {
        $('#knowledgeBase').empty();
    }

    this.showLoadingScreen = function() {
        if ($('#knowledgeBase .loading').length == 0) {
            $("#knowledgeBase").append("<div class=\"loading\"></div>");
        }
        $('#knowledgeBase .loading').show();
    }

    this.hideLoadingScreen = function() {
        $("#knowledgeBase .loading").hide();
    }

    this.show = function(sUrl) {
        if (self.isCuttingEdge && self.isOpen) {
            var animStartX = self.prevRequested ? -(self.contentWidth) : self.contentWidth;

            $('#knowledgeBase .animationWrapper').css('left', animStartX + 'px');
            $("#knowledgeBaseShade, #knowledgeBase").css('visibility', 'visible');
            self.animateContent(true, null);
        }
        else {
            $('#knowledgeBase .animationWrapper').css('left', '0px');
            $("#knowledgeBaseShade,#knowledgeBase").css({ 'visibility': 'visible', 'display': 'block' });
            self.isOpen = true;
            log("kbase is open");
        }

        /** CALCULATE HEIGHT */
        if ($('#introImageKBase_flash').length != 0) {
            var flashElm = $('#introImageKBase_flash').get(0);
            $('#introImageKBase_flash').parent().css({ "height": $(flashElm).attr("height") + "px", "width": $(flashElm).attr("width") + "px" });
        }
         var scrolPaneCSSclass = 'kbase-scroll-pane';
        $('#knowledgebaseWrapper')
                    .addClass(scrolPaneCSSclass)
                    .jScrollPane({ 'showArrows': 'true', 'horizontalScrollbar' : 'false' });
    }

    this.prevRequested = false;
    this.nextRequested = false;

    this.contentTop = -1;
    this.contentHeight = -1;
    this.contentWidth = $('#knowledgeBase').width();

    this.currentItemIndex = 0;

    this.open = function(sUrl, itemIndex) {
        log("open - sUrl: " + sUrl);
        log("open - itemIndex: " + itemIndex);

        if (itemIndex != null && !isNaN(itemIndex)) {
            self.currentItemIndex = itemIndex;
            log('[KBase - open] self.currentItemIndex: ' + self.currentItemIndex);
        }
        if (self.isCuttingEdge) {
            if (self.isOpen) {
                // do animations
                self.animateContent(false, function() { self.showLoadingScreen(); self.retrieve(sUrl); });
            }
            else {
                self.retrieve(sUrl);
            }
        }
        else {
            self.retrieve(sUrl);
        }

    }
    
    // retrieve and show content
    this.retrieve = function (sUrl) {
        log("retrieve - sUrl: " + sUrl);
        $.ajax({
            url: sUrl,
            dataType: "html",
            success: function (data) {
                //**debug**
                //if (self.isOpen) return;
                // browser hacks
                ieToggleDropDowns(true);

                // empty current content..
                // this also clears the "loading" screen.
                self.clear();

                //attach Content
                var animationWrapper = $("<div class=\"animationWrapper\"></div>");
                //add "CLOSE" Text;
                var closestr = '';
                if (self.isCuttingEdge){// && !self.oldModelPage) {
                    closestr = '<span class="closeLabel"></span>';
                }
                $("<div class=\"closeButton\" id=\"closeButtonKbase\">" + closestr + "<img src=\"/Images/close-button.gif\" alt=\"[X]\" title=\"Close\" /></div>")
                    .click(self.closebuttonCallback)
                    .appendTo(animationWrapper);

                animationWrapper.appendTo('#knowledgeBase');
                $(data.replace(/\<\/?content\>/g, '')).appendTo('.animationWrapper');

                // bind necessary localized texts
                var i18n = new I18N();
                i18n.resolveText('js_apps', 'kbase', 'closeLabel', '.closeLabel'); // class="closeLabel"
                i18n.doProcessing();

                self.toggleMilkyBackground("on");

                if (self.isCuttingEdge) {
                    //$("#knowledgeBaseShade, #knowledgeBase").css('display','block');
                    $("#knowledgeBaseShade, #knowledgeBase").fadeIn(350);
                }
                else {
                    // hide content for a moment.
                    $("#knowledgeBaseShade, #knowledgeBase").css({
                        'visibility': 'hidden',
                        'display': 'block'
                    });
                }
                if (!self.oldModelPage) {
                    self.setupNavigationBar();
                }
                // content is inserted into DOM, set the dimensions accordingly
                self.adjustDimensions();

                // ta-daa!
                self.hideLoadingScreen();
                self.show(sUrl);

            },
            error: function (xhttpreq, errorTxt, exception) {
                // something went badly. Show error message..
                alert("Unable to retrieve content: " + errorTxt + ". Please try again.");
            }
        });
    }
    this.runVideo = function(sShowflashScript) { ; };
    this.stopVideo = function(sShowflashScript) { ; };

    this.closebuttonCallback = function() {
        self.close();
    }

    this.navigationElementSelector = "ul li.kbase";
    this.navigationItemCollection = null;
    this.setupNavigationBar = function() {
        if (!self.isCuttingEdge) return;

        self.navigationItemCollection = $(self.navigationElementSelector);

        if (self.navigationItemCollection.length > 1) {
            var navBlock;
            if ($('#kbNavi').length == 0) {
                log('Drawing navigation first time..');
                $('<div id=\"kbNavi\"></div>').insertBefore('#knowledgeBaseShade');
            }
            // calculate navigation bar position
            self.navigationBarTop = ($(window).height() - $('#kbNavi').height()) / 2 + viewportGetScrollY();


            $('#kbNavi')
                .css({ 'top': self.navigationBarTop + 'px',
                    'width': self.navigationBarWidth + 'px',
                    'left': self.navigationBarLeft + 'px'
                });

            // set-up next/prev links
            var prev, next;
            var prevLink = self.getPrev();
            var nextLink = self.getNext();
            var xOffset = '89px'; // $('#kbPrev').width() + 'px';
            log("xOffset: " + xOffset);

            // **
            // PREVIOUS
            //**
            if (prevLink) {
                // first time: create "previous" element
                log("prevLink found");
                var prevtitle = $(prevLink).find("span").text();
                if ($('#kbPrev').length == 0) {
                    prev = $('<div id=\"kbPrev\"><a title="' + prevtitle + '" href="javascript:void(0);"></a></div>')
                    .click(function() { self.clickPrev(); })
                    .appendTo('#kbNavi')
                    ;
                }
                else {
                    // link exists, update only its title
                    $('#kbPrev a').attr('title', prevtitle);
                }
                // finally, slide out, make it visible
                $('#kbPrev').animate({ 'left': 0 }, 200, 'swing');
            }
            else {
                // no previous link. Slide it back in 
                // remember: the animation will run only if the element exists.
                $('#kbPrev').animate({ 'left': xOffset }, 200, 'swing');
            }

            // **
            // NEXT
            // **
            if (nextLink) {
                log("nextLink found");
                // first time: create "next" element
                var nexttitle = $(nextLink).find("span").text();
                if ($('#kbNext').length == 0) {
                    next = $('<div id="kbNext"><a title="' + nexttitle + '"  href="javascript:void(0);"></a></div>')
                    .click(function() { self.clickNext(); })
                    .appendTo('#kbNavi')
                    ;
                }
                else {
                    // link exists, update only its title
                    $('#kbNext a').attr('title', nexttitle);
                }
                // slide out.
                $('#kbNext').animate({ 'right': 0 }, 200, 'swing');
            }
            else {
                // no next link. Slide it back in 
                $('#kbNext').animate({ 'right': xOffset }, 200, 'swing');
            }
        }
    }

    // private function, use getNext/getPrev instead
    // KBase
    this.getSibling = function(isNext) {        
        var nextItemIndex = self.currentItemIndex + ((isNext) ? 1 : -1);
        log("self.currentItemIndex, nextItemIndex: " + self.currentItemIndex + " , " + nextItemIndex);

        if ((nextItemIndex < 0) || (self.navigationItemCollection.length <= nextItemIndex))
            return false;

        return self.navigationItemCollection[nextItemIndex];
    }

    this.getNext = function() {
        return this.getSibling(true);
    }
    
    this.getPrev = function() {
        return this.getSibling(false);
    }

    this.clickNext = function() {
        log("clickNext.");
        self.nextRequested = true;
        self.prevRequested = false;
        log("currentItemIndex: " + self.currentItemIndex);
        $(self.navigationItemCollection[self.currentItemIndex + 1]).find('a').trigger("click");
    }

    this.clickPrev = function() {
        log("clickPrev.");
        self.prevRequested = true;
        self.nextRequested = false;
        //console.dir(self.navigationItemCollection);
        log("currentItemIndex: " + self.currentItemIndex);
        $(self.navigationItemCollection[self.currentItemIndex - 1]).find('a').trigger("click");
    }

    this.toggleMilkyBackground = function(onOff) {
        if (onOff == "on") {
            // if it's already there, back off.
            if ($('#kbaseMilkyBG').length != 0) return;
            // insert semi-transparent milky background
            $('#knowledgeBase').parent().append('<div id=\"kbaseMilkyBG\"></div>');
        }
        else {
            $('#kbaseMilkyBG').remove();
        }
    }

    this.imgWidth = 656;
    this.imgHeight = 535;
    this.minContainerHeight = 575;
    this.name = "KBASE";
    this.kbWrapperHeightDiff = 67;    // height of old kbHeading/navigation
    this.kbShadeMarginTopBottom = 16; // minimum gap between browser window top/bottom and kbase shade
    this.shadeBorderWidth = 8;             // kbase shade border width
    this.kbMagicHightModifier = 1;

    this.getContentHeight = function() {
        log("$('#knowledgebaseWrapper').outerHeight(true): " + $('#knowledgebaseWrapper').outerHeight(true));
        return ($('#knowledgebaseWrapper').outerHeight(true) + 47);
    }
    this.setKbWrapperHeight = function(kbHeight) {
        if ($("#knowledgebaseWrapper").length > 0) {
            $("#knowledgebaseWrapper").height(kbHeight - this.kbWrapperHeightDiff);
        }
    }

    this.adjustDimensions = function() {
        log("entering setKBaseDimensions");

        var maxContainerHeight, contentHeight, kbHeight, shadeHeight;

        // settings max and min height a kbase container can have.
        maxContainerHeight = $(window).height() - (2 * self.kbShadeMarginTopBottom) - (2 * self.shadeBorderWidth);
        if (maxContainerHeight < 0) maxContainerHeight = 0;

        contentHeight = this.getContentHeight();

        if ($('#' + self.flashContainerId).length > 0) {
            var flashHeight = $('#' + self.flashContainerId).attr("height");
            log("flashHeight: " + flashHeight);
            if (flashHeight != '' && typeof (flashHeight) != 'undefined') {
                contentHeight += flashHeight;
            }
        }

        // Adjust container height according to content height
        if (contentHeight > maxContainerHeight)
            kbHeight = maxContainerHeight;
        else if (contentHeight < self.minContainerHeight)
            kbHeight = self.minContainerHeight;
        else
            kbHeight = contentHeight;

        kbHeight += self.kbMagicHightModifier; // BU: don't ask why.

        shadeHeight = kbHeight + (2 * self.shadeBorderWidth);

        this.setKbWrapperHeight(kbHeight);

        var elmShade = document.getElementById("knowledgeBaseShade");
        var elmKB = document.getElementById("knowledgeBase");

        var pageWidth;
        if ($('.page').length > 0)
            pageWidth = $('.page').width();
        else
            pageWidth = $('body').width(); // Comparemodels falls into this category.

        var imgX = pageWidth / 2 - self.imgWidth / 2;
        var imgY = Math.round(($(window).height() - shadeHeight) / 2) + viewportGetScrollY() + 8;

        if (imgY < 0) { imgY = 0; }
        if (imgX < 0) { imgX = 0; }

        // set KBase container height
        if (self.isCuttingEdge && self.contentHeight != -1 && kbHeight != self.contentHeight) {
            var diffH = "+=" + (kbHeight - self.contentHeight);
            var diffT = "+=" + (imgY - self.contentTop);

            // roll the animation
            $("#knowledgeBase,#knowledgeBaseShade").animate({
                'height': diffH,
                'top': diffT
            }, 300, 'swing');
        }
        else {
            // set KBase-Shade dimensions
            elmShade.style.left = (imgX - self.shadeBorderWidth) + "px";
            elmShade.style.top = (imgY - self.shadeBorderWidth) + "px";
            elmShade.style.height = shadeHeight + "px";

            // set KBase Dimensions
            elmKB.style.left = imgX + "px";
            elmKB.style.top = imgY + "px";
            elmKB.style.height = kbHeight + "px";
        }

        self.contentTop = imgY;
        self.contentHeight = kbHeight;
    }

    this.close = function() {
        // **********************
        // Closing KBase layer
        // **********************

        // turn off milky background layer
        log("closing KBase");

        // remove navigation (prev/next)
        $('#kbNavi').remove();

        // IE Hack for dropdowns
        ieToggleDropDowns(false);

        if (self.isCuttingEdge) {
            //$("#knowledgeBaseShade, #knowledgeBase").css('display','block');
            $("#knowledgeBaseShade, #knowledgeBase").fadeOut("fast", function() {
                //$("#knowledgeBaseShade, #knowledgeBase").empty().hide();
                self.toggleMilkyBackground("off");
            });
        }
        else {
            $("#knowledgeBaseShade, #knowledgeBase").empty().hide();
            self.toggleMilkyBackground("off");
        }

        this.isOpen = false;
        //$("html").css({ "overflow-y": "scroll" });
        log("KBase.isOpen: " + this.isOpen);
    }
}

/*
GalleryPlayer Screen (03_galerie-film_03-01.jpg)

Video    : 640 x 360
A.rechts :  23
A.links  :  23
A.oben   :        48
A.unten  :        55
---------------------
           686 x 463

Player Modellstartseite (03-2_modellstartseite.jpg)

Video    : 792 x 445
*/

function VidBase(videoWidth, videoHeight, showLoadingBGI) {
    var self = this;
    self = new KBase();
    self.name = "VIDBASE";
    self.oldModelPage = false;
    self.flashContainerId = 'galleryFlashContainer_flash';

    self.containerWidth = (videoWidth != null && !isNaN(videoWidth)) ? videoWidth : 792;
    self.containerPaddingLeft = 23;
    self.containerPaddingRight = 23;
    self.imgWidth = self.containerWidth + self.containerPaddingLeft + self.containerPaddingRight;
    self.containerHeight = (videoHeight != null && !isNaN(videoHeight)) ? videoHeight : 455;
    self.containerPaddingTop = 48;
    self.containerPaddingBottom = 55;
    self.showLoadingBGI = (showLoadingBGI != null && showLoadingBGI == true) ? true : false;
    self.imgHeight = self.containerHeight + self.containerPaddingTop + self.containerPaddingBottom;
    self.minContainerHeight = self.imgHeight;
    self.kbWrapperHeightDiff = 0;
    self.kbShadeMarginTopBottom = 8;
    self.kbMagicHightModifier = 0;
    self.navigationElementSelector = "#content > .tabContent2 > ul.galleryFilms > li > a";
    self.navigationBarWidth = self.imgWidth + (self.shadeBorderWidth * 2) + (2 * 70);
    self.navigationBarLeft = 36;

    self.stopVideo = function() {
        flashPlayer_cmdStop(self.flashContainerId);
    }

    self.closebuttonCallback = function() {
        self.stopVideo();
        self.close();
    }

    self.showLoadingScreen = function() { ; }; 
    self.hideLoadingScreen = function() { ; };

    this.open = self.open;
    self.getContentHeight = function() {
        return $('#knowledgeBase').outerHeight(true);
    }

    self.getSibling = function(isNext) {
        var nextItemIndex = self.currentItemIndex + ((isNext) ? 1 : -1);
        log("self.currentItemIndex, nextItemIndex: " + self.currentItemIndex + " , " + nextItemIndex);

        if ((nextItemIndex < 0) || (self.navigationItemCollection.length <= nextItemIndex))
            return false;

        return self.navigationItemCollection[nextItemIndex];
    }

    self.clickNext = function() {
        log("clickNext.");
        self.nextRequested = true;
        self.prevRequested = false;
        self.stopVideo();
        $(self.navigationItemCollection[self.currentItemIndex + 1]).trigger("click");
    }
    self.clickPrev = function() {
        log("clickPrev.");
        self.prevRequested = true;
        self.nextRequested = false;
        self.stopVideo();
        $(self.navigationItemCollection[self.currentItemIndex - 1]).trigger("click");
    }
    self.createFlashContainer = function(targetContainerSelector) {
        var newContainer = $("<div></div>").css({
            "background-color": "white",
            "padding": self.containerPaddingTop + "px " + self.containerPaddingRight + "px " + self.containerPaddingBottom + "px " + self.containerPaddingLeft + "px",
            "height": self.containerHeight + "px",
            "width": self.containerWidth + "px"
        }).attr("id", self.flashContainerId.replace(/_flash/, ''));

        if (self.showLoadingBGI) {
            newContainer.css({
            "background-image": "url(/images/loading.gif)",
            "background-position": "center center",
            "background-repeat": "no-repeat"
            });
        }

        $(newContainer).appendTo(targetContainerSelector);
    }

    self.runVideo = function(sShowflashScript) {
        if (sShowflashScript.indexOf('show') < 0) {
            if ($("#" + self.flashContainerId).length == 0) {
                $("<div id='" + self.flashContainerId + "'></div>").appendTo($("#" + self.flashContainerId.replace(/_flash/, '')));
            }
            var params = {
                loop: "true",
                menu: "false",
                quality: "high",
                allowScriptAccess: "sameDomain",
                wmode: "transparent",
                allowfullscreen: "true",
                base: (sShowflashScript.indexOf('pano.swf') > -1) ? sShowflashScript.replace('/pano.swf', '') : ''
            };
            swfobject.embedSWF(sShowflashScript, self.flashContainerId, self.containerWidth, self.containerHeight, '9', null, null, params, null); //, expressinstall, flashvars, params, attributes);
        }
        else {
            window.setTimeout("eval(" + sShowflashScript.replace(/\);/, ')') + ")", 500);
        }
    }

    self.retrieve = function(sShowflashScript) {
        log("retrieve - sUrl: " + sShowflashScript);
        ieToggleDropDowns(true);

        // empty current content..
        // this also clears the "loading" screen.
        self.clear();

        //attach Content
        var animationWrapper = $("<div class=\"animationWrapper\"></div>");
        //add "CLOSE" Text;
        var closestr = '';
        if (self.isCuttingEdge) {
            closestr = '<span class="closeLabel"></span>';
        }
        $("<div class=\"closeButton\" id=\"closeButtonKbase\">" + closestr + "<img src=\"/Images/close-button.gif\" alt=\"[X]\" title=\"Close\" /></div>")
                .click(self.closebuttonCallback)
                .appendTo(animationWrapper);

        animationWrapper.appendTo('#knowledgeBase');
        $("#knowledgeBase").css({ "width": self.imgWidth + "px" });
        $("#knowledgeBaseShade").css({ "width": (self.imgWidth + 16) + "px" });

        self.createFlashContainer(".animationWrapper");

        // bind necessary localized texts
        var i18n = new I18N();
        i18n.resolveText('js_apps', 'kbase', 'closeLabel', '.closeLabel'); // class="closeLabel"
        i18n.doProcessing();

        self.toggleMilkyBackground("on");

        if (self.isCuttingEdge) {
            $("#knowledgeBaseShade, #knowledgeBase").fadeIn(350);
        }
        else {
            $("#knowledgeBaseShade, #knowledgeBase").css({
                'visibility': 'hidden',
                'display': 'block'
            });
        }

        self.setupNavigationBar();
        // content is inserted into DOM, set the dimensions accordingly
        self.adjustDimensions();

        // ta-daa!
        //self.hideLoadingScreen();
        self.show(sShowflashScript);
        this.runVideo(sShowflashScript);
    }
}


function PanoramaBase(videoWidth, videoHeight) {
    var self = this;
    self = new VidBase(videoWidth, videoHeight, true, true);
    self.name = "PANORAMABASE";
    self.navigationElementSelector = "#content > .tabContent2 > ul.galleryPanorama > li.flash > a";

    this.open = self.open;
}

function getTextBetween(sAll, sStart, sEnd) {
    var sPart = "";
    var posStart = sAll.indexOf(sStart);
    var posEnd = sAll.indexOf(sEnd);
    if (posStart >= 0 && posEnd >= 0 && posEnd > posStart) {
        sPart = sAll.substring(posStart + sStart.length, posEnd);
    }
    return sPart;
}

function clickZoomable(id, imgWidth, imgHeight) {
    var pageWidth = g_pageWidth;

    if ($) {
        if ($('.page').length > 0)
            pageWidth = $('.page').width();
        else
            pageWidth = $('body').width(); // Comparemodels falls into this category.

        if ($('#kbaseMilkyBG').length == 0) {
            // insert semi-transparent milky background
            $('#knowledgeBase').parent().append('<div id=\"kbaseMilkyBG\"></div>');
        }

    }

    if (g_openZoom == 0) {
        var shadeborder = 8;

        var elmShade = document.getElementById("zoomImageShade");
        var elmImage = document.getElementById("zoomImage" + id);
        var elemMilky = document.getElementById("kbaseMilkyBG");
        var elmCloseButton = document.getElementById("closeButton" + id);

        var imgX = pageWidth / 2 - imgWidth / 2;
        var imgY = Math.round((viewportGetHeight() - imgHeight) / 2) + viewportGetScrollY();

        if (imgY < 0) { imgY = 0; }
        // if (imgX < 0) { imgX = 0; }

        elmShade.style.left = (imgX - shadeborder) + "px";
        elmShade.style.width = (imgWidth + shadeborder * 2) + "px";
        elmShade.style.top = (imgY - shadeborder) + "px";
        elmShade.style.height = (imgHeight + shadeborder * 2) + "px";

        elmImage.style.left = imgX + "px";
        elmImage.style.top = imgY + "px";
        if (elmCloseButton) {
            elmCloseButton.style.left = (imgWidth - 19) + "px";
        }

        elmImage.style.display = "block";
        elmShade.style.display = "block";
        if (elemMilky) {
            elemMilky.style.display = "block";
        }

        g_openZoom = id;
    }
}

function clickZoomed() {
    hideLr("zoomImageShade");
    hideLr("zoomImage" + g_openZoom);
    var elemMilky = document.getElementById("kbaseMilkyBG");
    if (elemMilky) {
        elemMilky.style.display = "none";
    }
    g_openZoom = 0;
}

function showLr(id) {
    var elm = document.getElementById(id);
    if (elm) {
        elm.style.display = "block";
    }
}

function hideLr(id) {
    var elm = document.getElementById(id);
    if (elm) {
        elm.style.display = "none";
    }
}

function toggleLr(id) {
    var elm = document.getElementById(id);
    if (!elm) return;

    if (elm.style.display != "block") showLr(id);
    else hideLr(id);
}



/* Expandable module */

function expandCollapse(id)
{
    var elm = document.getElementById("expandable_" + id);

    if (elm)
    {
        /* Hack alert -- footer will be hidden temporarily
        to recalculate bottom position correctly.
        */

        var footer = document.getElementById("footer");
        footer.style.display = "none";

        if (elm.style.height != "auto")
        {
            collapseAllElements();
            showElement(id);        
        }
        else
        {
            collapseElement(id);
        }

        positionFooter();
        footer.style.display = "block";
    }
}

function showElement(id) {
    var elm = document.getElementById("expandable_" + id);
    elm.style.height = "auto";

    var h3 = document.getElementById("expandableHead_" + id);
    if (h3) {                
        h3.style.backgroundColor = "rgb(102,102,102)";                 
        h3.style.color = "rgb(255,255,255)";              
        h3.style.backgroundImage = "url(/images/arrow-lightgray-down.gif)";            
        h3.style.backgroundPosition = "9px 9px";
    }
}

function collapseElement(id) {
    var elm = document.getElementById("expandable_" + id);
    elm.style.height = "19px";

    var h3 = document.getElementById("expandableHead_" + id);
    if (h3) {
        h3.style.backgroundColor = "rgb(204,204,204)";                
        h3.style.color = "rgb(0,0,0)";
        h3.style.backgroundImage = "url(/images/arrow-gray.gif)";          
        h3.style.backgroundPosition = "11px 7px";
    }
}

function collapseAllElements() {


    var all = document.getElementsByTagName("*");
    var expandable_id;

    for (i = 0; i < all.length; i++) {

        if (all[i].className == "expandable") {
            expandable_id = all[i].id.split("_");
            collapseElement(expandable_id[1]);
        }

    }
    
  /*    
    var i=1;
    do {
        var elm = document.getElementById("expandable_" + i);
        if (elm) collapseElement(i);
        i++;
    } while(elm);
  */  
}

function viewportGetHeight()
{
    var retval = 0;

    if (window.innerHeight)
        retval = window.innerHeight - 18;
    else if (document.documentElement && document.documentElement.clientHeight) 
        retval = document.documentElement.clientHeight;
    else if (document.body && document.body.clientHeight) 
        retval = document.body.clientHeight;

    return retval;    
}

function viewportGetWidth()
{
    var retval = 0;

    if (window.innerWidth)
        retval = window.innerWidth - 18;
    else if (document.documentElement && document.documentElement.clientWidth) 
        retval = document.documentElement.clientWidth;
    else if (document.body && document.body.clientWidth) 
        retval = document.body.clientWidth;

    return retval;    
}

function viewportGetScrollY()
{
    var retval = 0;

    if (typeof window.pageYOffset == "number")
        retval = window.pageYOffset;
    else if (document.documentElement && document.documentElement.scrollTop)
        retval = document.documentElement.scrollTop;
    else if (document.body && document.body.scrollTop) 
        retval = document.body.scrollTop; 
    else if (window.scrollY)
        retval = window.scrollY;

    return retval;
}

function showGalleryFlash(pool, movieFolder, bandwidth, flashParams)
{
    var elmImg = document.getElementById("galleryImage");
    if (elmImg) {
        g_fallbackImage = elmImg.src;
    }
    var url;

    if (g_kbaseClassicStyle == false) /*(pool == 'usa'
        || pool == 'germany'
        || pool == "uk"
        || pool == "spain"
        || pool == "italy" 
        || pool == "france"
        || pool == "portugal"
        || pool == "belgium"
        || pool == "pbe-master"
        || (pool.indexOf("pcb-") >= 0)
        ) */
    {
        //log(flashParams);
        flashParams = flashParams.replace(/\/\//g, '/');
        //log(flashParams);
         if (
               (flashParams.indexOf('/all/media/flash/videos/models/911/997-2nd-c2/911-technikfilm/us-english/large.flv') > -1)
            || (flashParams.indexOf('/all/media/flash/videos/models/cayenne/9pa-e2-v6/technikfilm/nodi/us-english/large.flv') > -1)
            || (flashParams.indexOf('/all/media/flash/videos/models/panamera/970-g1-s/G1_technikfilm/us-english/large.flv') > -1)
          ) {
            flashParams = flashParams.replace(/\=/, '=http://special.porsche.com');
        }

        log("showGalleryFlash - " + url);
        url = "/all/media/flash/galleryPlayer.swf";
        showFlash(url, "galleryFlashContainer", "792", "455", "8", "#FFFFFF",
            "loop=true,menu=true,quality=high,wmode=transparent",
            "pool=" + pool + "," + flashParams + ",autostart=false");
    }
    else {
        url = "/all/media/flash/videoplayer.swf";
        showFlash(url, "galleryContent", "595", "317", "7", "#FFFFFF",
            "loop=true,menu=true,quality=high,wmode=opaque",
            "pool=" + pool + ",id=" + movieFolder + ",bandwidth=" + bandwidth + ",eventhandler=flashEnded," + flashParams);
    }
}

function showGalleryPanoramaFlash(url, flashParams)
{
    var elmImg = document.getElementById("galleryImage");
    if (elmImg) {
        g_fallbackImage = elmImg.src;
    }
   
    showFlash(url, "galleryContent", "595", "317", "7", "#FFFFFF","loop=true,menu=true,quality=high,wmode=opaque","eventhandler=flashEnded," + flashParams);
}

function flashEnded()
{
    if (g_fallbackImage != "") {
        var elmContent = document.getElementById("galleryContent");
        elmContent.innerHTML = "<img src=\"" + g_fallbackImage + "\" alt=\"\" id=\"galleryImage\" />";
    }
}

function showFlash(url, id, width, height, version, bgcolor, playerparamstr, flashparamstr) {
    var flashElmId = id + "_flash";

    width = "" + width;
    height = "" + height;
    version = "" + version;

    var elm = $('#' + id).get(0) || $('.' + id).get(0);
    if (!elm) {
        return;
    }

    var flashvars = JSONify(flashparamstr + ',posx=296,cdnhost=http://special.porsche.com/'); //
    if (playerparamstr.indexOf('allowScriptAccess') < 0) {
        playerparamstr = 'allowScriptAccess=always,' + playerparamstr;
    }
    var params = JSONify('allowfullscreen=true,' + playerparamstr); // + ',wmode=opaque'
    var attributes = false;

    params.bgcolor = bgcolor;
    params.align = "middle";

    var expressinstall = "/all/media/flash/expressInstall.swf";
    if (g_is_home) {
        expressinstall = false;
    }

    var playFlash = true;

//    log("showFlash - " + url);
    var is_mp4 = false;
    if (typeof (flashvars.videopath) != 'undefined') {
        is_mp4 = ((document.location.href.indexOf('germany/models/') > -1) && flashvars.videopath.indexOf('.large.flv' > -1));
    }
    log(is_mp4);
    if (g_is_iPad && is_mp4) {
        var tmp = flashvars.videopath.replace('.flv', '.mp4');
        var title = flashvars.headline;
        var buttonText = flashvars.playbuttontext;
        var height = parseInt(params.height) - 60;

        var linkHtml = '<a target="_blank" href="' + tmp + '" class="greybutton" style="left:478px;margin-right:16px; margin-top: 0; position:relative; top: -39px;"><span><img title="' + buttonText + '" alt="' + buttonText + '" src="/germany/ImageMachines/LinkblockTitle.ashx?text=' + encodeURIComponent(buttonText) + '&amp;mode=greybutton"/></span></a>';
        $('#introImageKBase').append(linkHtml);
    }
    else {
        if (g_is_home) {
            if (!swfobject.hasFlashPlayerVersion(version)) {
                // fall back to regular page (without flash)
                fallBackFromFlash(getPoolName());
                playFlash = false; // on the homepage, if flash check fails, do not attempt to run  flash..
            }
            else {
                // prepare the homepage before loading flash animation.
                //hideHomepageNavigation();
                //hideHomepageClaim();
            }
        }
        else {
            if ((swfobject.getFlashPlayerVersion().major + '') == '0') // no Flash installed
                playFlash = false;
        }

    // go
    if (playFlash) {
        $(elm).html("<div id=\"" + flashElmId + "\"></div>");
//        log("url: " + url); 
//        log("flashElmId: " + flashElmId); 
//        log("width: " + width); 
//        log("height: " + height); 
//        log("version: " + version); 
//        log("expressinstall: " + expressinstall); 
//        log("flashvars: " + $(flashvars)); 
//        log("params: " + $(params));
//        log("attributes: " + attributes);
        swfobject.embedSWF(url, flashElmId, width, height, version, expressinstall, flashvars, params, attributes);
        }
    }
}

// parses an array into a json string, 
// evals it and returns an object.
function JSONify(str) {
    
    //alert("JSONify ing: " + str);
    if (str == undefined || str == null) return "{}";
    var json = "{";
    var trap = false;
    var params = str.split(",");
    for (var i = 0; i < params.length; i++) {
        var param = params[i].split("=");
        if (param[0] == undefined || param[0] == null || param[0] == "") {
            trap = true;
            continue;
        }
        else {
            if (i > 0 && !trap) {
                json += ",";
                trap = false;
            }
            json += param[0] + ":\"" + param[1] + "\"";
        }
    }
    json += "}";
    return eval('(' + json + ')');
   
}


function swfIsVideoPlayer(url) {
    var retVal = false;
    var FILENAME = 'videoplayer.swf';
    var foundSWF = url.substr(url.lastIndexOf('/') + 1);

    if (foundSWF && (foundSWF.toLowerCase() == FILENAME))
        retVal = true;

    return retVal;
}



/* Gallery module */

var g_lastNumber = 1;

function setImage(elm, n)
{
    if (g_lastNumber != n)
    {
        var lastElm = document.getElementById("thumbnail" + g_lastNumber);
        lastElm.className = "";
        lastElm.style.border = "1px solid #ccc";

        var thisElm = document.getElementById("thumbnail" + n);
        thisElm.className = "selected";
        thisElm.style.border = "1px solid rgb(204,0,0)";

        g_lastNumber = n;

        sHref = elm.href;
        document.getElementById("galleryImage").src = sHref;
        
        showGallerySubtitle(n);
        showGalleryClaim(n);
    }
    return false;
}

function setThumbnail(elm, n)
{
    if (g_lastNumber != n)
    {
        var lastElm = document.getElementById("thumbnail" + g_lastNumber);
        lastElm.className = "";
        lastElm.style.border = "1px solid #ccc";

        var thisElm = document.getElementById("thumbnail" + n);
        thisElm.className = "selected";
        thisElm.style.border = "1px solid rgb(204,0,0)";

        g_lastNumber = n;
    }

    return false;
}

function prevgalleryImage(img, imgMax)
{
    var lastElm = document.getElementById("thumbnail" + g_lastNumber);
    if (lastElm) {    
        lastElm.className = "";
        lastElm.style.border = "1px solid #ccc";
    }

    var n = --g_lastNumber;
    if (n < 1) { n = getMaxNumberGallery(); }

    var thisElm = document.getElementById("thumbnail" + n);
    if (thisElm) {     
        thisElm.className = "selected";
        thisElm.style.border = "1px solid rgb(204,0,0)";
    }

    var elm = document.getElementById("href" + n);
    sHref = elm.href;
    document.getElementById("galleryImage").src = sHref;

    g_lastNumber = n;
    
    showGallerySubtitle(n);
    showGalleryClaim(n);
    
    return false;
}

function nextgalleryImage()
{
    var lastElm = document.getElementById("thumbnail" + g_lastNumber);
    if (lastElm) {
        lastElm.className = "";
        lastElm.style.border = "1px solid #ccc";
    }

    var n = ++g_lastNumber;
    var max = getMaxNumberGallery();
    if (n > max) { n = 1; }

    var thisElm = document.getElementById("thumbnail" + n);
    if (thisElm) {    
        thisElm.className = "selected";
        thisElm.style.border = "1px solid rgb(204,0,0)";
    }

    var elm = document.getElementById("href" + n);
    sHref = elm.href;
    document.getElementById("galleryImage").src = sHref;

    g_lastNumber = n;
    
    showGallerySubtitle(n);
    showGalleryClaim(n);

    return false;
}

function initGallerySubtitles()
{
    var n = getGalleryItemNo();
    if (n == -1) n=1;
        
    var subtitles = document.getElementById("gallerySubtitles")               	
    if (subtitles) {
        showGallerySubtitle(n);
        subtitles.style.display = "block";
    }

    var claims = document.getElementById("galleryClaims")
    if (claims) {
        showGalleryClaim(n);	        
        claims.style.display = "block";
    }
}


function getGalleryItemNo() 
{
    var no = -1;
    
    var regex = /itemindex=(\d*)/;
    var result = regex.exec(document.URL);
    
    if (result != null) { 
        no = result[1]
    }            
    
    return no;          
}

function showGallerySubtitle(n)
{
    var subtitles = document.getElementById("gallerySubtitles");

    if (subtitles) {   
        var tabSubtitles = subtitles.getElementsByTagName("div");
                            
        var tab = document.getElementById("gallerySubtitlesTab" + getGallerySubtitleTabNo());
        if (tab) 
        {
            tabSubtitles = tab.getElementsByTagName("div");	
            tab.style.display = "block";				
        }

        /************************/
        /* STV: JDPower 2008-11 */
        var currentPool = getPoolName();
        var gallerySubtitleDisplayStyle = "block";
        if (currentPool == "usa"){
            if (getPageTitle() == "Gallery")
                gallerySubtitleDisplayStyle = "inline";
        }
        /************************/

        if (tabSubtitles) 
        {            
            for (var i = 0; i < tabSubtitles.length; i++) {
                tabSubtitles[i].style.display = (i == n - 1) ? gallerySubtitleDisplayStyle : "none";				
            }
        }
    }
}
function getPageTitle() {
    for (var i = 0; i < document.getElementsByTagName('meta').length; i++) {
        if (document.getElementsByTagName('meta')[i].getAttribute('name') == 'titel') {
            pageTitle = document.getElementsByTagName('meta')[i].getAttribute('content');
}
}
}


function showGalleryClaim(n) {
    var claims = document.getElementById("galleryClaims");	   
    if (claims) 
    {    	
        var tabClaims = claims.getElementsByTagName("div");  
        
        var tab = document.getElementById("galleryClaimsTab" + getGallerySubtitleTabNo());
        if (tab) 
        {
            // zuerst nach Div suchen
            tabClaims = tab.getElementsByTagName("div");
            // 15.03.2006 by BU + MIP 
            // wenn kein <Div> vorhanden dann <Img> nehmen
            if (tabClaims.length == 0) {
                tabClaims = tab.getElementsByTagName("img");
            }
            tab.style.display = "block";				
        }

        /************************/
        /* STV: JDPower 2008-11 */
        var currentPool = getPoolName();
        var galleryClaimDisplayStyle = "block";
        if (currentPool == "usa")
            galleryClaimDisplayStyle = "inline";
        /************************/
        
        if (tabClaims) {            
            for (var i = 0; i < tabClaims.length; i++) {
                tabClaims[i].style.display = (i == n - 1) ? galleryClaimDisplayStyle : "none";                
            }
        }
    }    
}


function getGalleryClaimTab()
{   
    var claim = document.getElementById("galleryClaims");
    return claim;	
}


function getGallerySubtitleTab()
{    
    var tab = document.getElementById("gallerySubtitles");    
    return tab;          
}


function getGallerySubtitleTabNo()
{
    var no = 1;
    
    var regex = /tabindex=(\d)/;
    var result = regex.exec(document.URL);
    
    if (result != null) { 
        no = result[1]
    }            
    
    return no;          
}

function getMaxNumberGallery()
{
    var max = 0;
    for (var i = 50; i >= 1 && max == 0; i--) {
        var testElm = document.getElementById("thumbnail" + i);
        if (testElm) {
            max = i;
            break;
        }
    }

    return max;
}

function showWallpaper(img, iWidth, iHeight)
{
    gotoUrlNewWin(img);
}


/* Open Selection Shop item in a window */
function openSelectionShopItem(dept_id, pf_id)
{
    gotoUrlNewWinSizeScrollableWithMenu('http://shop.eu.porsche.com/germany/product2.asp?dept_id=' + dept_id + '&pf_id=' + pf_id + '&comefrom=teq911', 870, 700)
}

function openPDDSShop(poolId) {
    switch (poolId) {
        case "germany":
            gotoUrlNewWinSizeScrollableWithMenuR('http://shop.porsche.com/germany/',870,700);
            break;
        
        case "usa":
            openPDDSPopup('http://shop.porsche.com/usa/',false);
            break;
        
        case "uk":
            openPDDSPopup('http://shop.porsche.com/uk/', false);
            break;
        
        case "france":
            openPDDSPopup('http://shop.porsche.com/france/', false);
            break;

        case "italy":
            openPDDSPopup('http://shop.porsche.com/italy/', false);
            break;

        case "australia":
            openPDDSPopup('http://shop.porsche.com/australia/', false);
            break;
    }
}

function openPDDSPopup(s, isRedesign) {
    var sWidth
    var sHeight;
    var sOffset;
    
    var resizable = 'no';
    var locationbar = 'no';
    var toolbar = 'no';
    var menubar = 'no';

    if (isRedesign) {
        sWidth = 890;
        sHeight = 750;
        resizable = 'yes';
        locationbar = 'yes';
        toolbar = 'yes';
        menubar = 'yes';
    }
    else {
        sWidth = 890;
        sHeight = 725;
    }
        
    
    if (screen.height < 768) {
        if (sHeight > 450) sHeight = 430;
        if (sWidth > 783) sWidth = 790;
        sOffset = 0;
    }
    else if (screen.height < 1024) {
        if (sHeight > 550) sHeight = 550;
        sOffset = 10;
    }
    else {
        sOffset = 40;
    }


    newWin = window.open(s, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=40,top=40,dependent=yes,location=" + locationbar + ",menubar=" + menubar + ",toolbar=" + toolbar + ",resizable=" + resizable + ",scrollbars=yes,status=no");
}

function openConfiguration() {
    var sWidth = 980;
    var sHeight = 680;
    sWidth -= g_is_ie ? 15 : 20;
    sHeight -= 25;

    var sUrl = getQueryVariableEx('viewurl') + '';
    log('vor replace: ' + sUrl);
    sUrl = sUrl.replace(/\|/g, '&');
    sUrl = sUrl.replace(/viewurl\=/g, '');
    log('nach replace: ' + sUrl);
    var open = (sUrl.indexOf('https://ppnlite.porsche.com/' == 0) || sUrl.indexOf('http://cc.porsche.com/' == 0));
    open &= (sUrl.indexOf('hookURL') != -1)
    log(sUrl);

    if (open) {
        gotoUrlNewWinSizeByName(sUrl, sWidth, sHeight, "PVA");
    }
    else {
        configureCar('cc');
    }
}
function getQueryVariableEx(qv) {
    var pairs = getQueryString().split("&");
    for (i = 0; i < pairs.length; i++) {
        if (pairs[i].indexOf(qv) == 0) {
            return pairs[i];
        }
    }
    return '';
}
// sMarket = Language / market version e.g. 'us' for PCNA market
// sModel = The Model typecode e.g. '987110'
// sMode = '2D', '3D' or null
function openCC(sMarketId, sModel, sMode, blnOpenWindow)
{
    var sWidth = 980;
    var sHeight = 680;
    sWidth -= g_is_ie ? 15 : 20;
    sHeight -= 25;
    var sUrl = '';
    var sHostName = '';
    var sOriginHostName = '';
    var sLang = '';
    var iViewMode=2;
    var sTestFolder = '';
    if(blnOpenWindow == null)blnOpenWindow = true;
    if(g_is_mac == true && sMode != null)sMode='2D';
    
      switch(window.location.hostname) {
          case "intranet.porsche.com":
              sHostName = "http://cc.web.porsche.de";
              sOriginHostName = "http://cc.web.porsche.de";
              break;
        case "preview.porsche.com":
              sHostName = "https://ppnlite.porsche.com";
              sOriginHostName = "https://ppnlite.porsche.com";
              sTestFolder = '_uat';
              break;
        default:
              sHostName = "http://cc.porsche.com";
              OriginHostName = "http://origin-cc.porsche.com";
              break;
      }

      iViewMode = 2; //if(sMode == '2D')
      if (sMode == '3D') {
          iViewMode = 3;
      }
    
   if(sMode == null) {
      if(sModel == null) {
          sUrl = sHostName + "/icc_pcna{TESTFOLDER}/ui/pva/index.jsp?sprache={LANG}&modelRange=null&ORDERTYPE=null"; //&hookURL={HOOK}";
      }
      else {
       // sUrl = sHostName + "/icc_pcna{TESTFOLDER}/colorConfigurator.do?userID={USER}&lang={LANG}&PARAM={PARAM}&ORDERTYPE={MODEL}";
          sUrl = sHostName + "/icc_pcna{TESTFOLDER}/ccCall.do?userID={USER}&lang={LANG}&PARAM={PARAM}&ORDERTYPE={MODEL}&vLevel={MODE}&view=exterior"; //&hookURL={HOOK}";
      }
    }
    else {
      if(sModel == null) {
        //sUrl = sHostName + "/icc_pcna{TESTFOLDER}/preConfiguration.do?userID={USER}&lang={LANG}&PARAM={PARAM}&PRECONFIG_ID=default&vLevel={MODE}";
          sUrl = sHostName + "/icc_pcna{TESTFOLDER}/ccCall.do?userID={USER}&lang={LANG}&PARAM={PARAM}&vLevel={MODE}"; //&ORDERTYPE=null&view=exterior&hookURL={HOOK}";
      }
      else {
        //sUrl = sHostName + "/icc_pcna{TESTFOLDER}/preConfiguration.do?userID={USER}&lang={LANG}&PARAM={PARAM}&PRECONFIG_ID=default&vLevel={MODE}";
          sUrl = sHostName + "/icc_pcna{TESTFOLDER}/ccCall.do?userID={USER}&lang={LANG}&PARAM={PARAM}&vLevel={MODE}&ORDERTYPE={MODEL}&view=exterior"; //&hookURL={HOOK}";
      }
    }

    switch (sMarketId) {
        case "us":
            sUser = "US";
            sLang = "us";
            sParam = "parameter_internet_us";
            break;
//        case "swiss-de":
//            sUser = "CHSD";
//            sLang = "sd";
//            sParam = "parameter_internet_sd";
//            sUrl = sHostName + "/icc_euro/ui/pva/index.jsp?market=CHSD&sprache=sd&vLevel={MODE}&PARAM={PARAM}";
//            if (sModel != null) {
//                sUrl += "&ORDERTYPE=" + sModel + "&view=exterior";
//            }
//            break;
//        case "swiss-fr":
//            sUser = "CHSF";
//            sLang = "sf";
//            sParam = "parameter_internet_sf";
//            sUrl = sHostName + "/icc_euro/ui/pva/index.jsp?market=CHSD&sprache=sd&vLevel={MODE}&PARAM={PARAM}";
//            if (sModel != null) {
//                sUrl += "&ORDERTYPE=" + sModel + "&view=exterior";
//            }
//            break;
//        case "swiss-it":
//            sUser = "CHSI";
//            sLang = "si";
//            sParam = "parameter_internet_sf";
//            sUrl = sHostName + "/icc_euro/ui/pva/index.jsp?market=CHSD&sprache=sd&vLevel={MODE}&PARAM={PARAM}";
//            if (sModel != null) {
//                sUrl += "&ORDERTYPE=" + sModel + "&view=exterior";
//            }
//            break;
        default:
            //sUrl = sHostName + "/icc_pcna{TESTFOLDER}/colorConfigurator.do?userID=US&lang=us&PARAM=parameter_internet_us&ORDERTYPE=" + sModel;
            sUrl = sHostName + "/icc_pcna{TESTFOLDER}/ccCall.do?userID=US&lang=us&PARAM=parameter_internet_us&ORDERTYPE=" + sModel + "&vLevel={MODE}&view=exterior";//&hookURL={HOOK}";
            break;
    }

    if (sUrl != '') {
        sUrl = sUrl.replace(/{USER}/g, sUser);
        sUrl = sUrl.replace(/{LANG}/g, sLang);
        sUrl = sUrl.replace(/{PARAM}/g, sParam);
        sUrl = sUrl.replace(/{MODEL}/g, sModel);
        sUrl = sUrl.replace(/{MODE}/g, iViewMode);
        sUrl = sUrl.replace(/{TESTFOLDER}/g, sTestFolder);
        // sUrl = sUrl.replace(/{HOOK}/g, document.location.toString());
        //sUrl = sUrl.replace(/{HOOK}/g, encodeURIComponent(document.location.toString()));
        // sUrl = sUrl.replace(/{HOOK}/g, "null");

        var screenParam = getScreenXYUrlParam();

        // CC Down Hack
        //sUrl = sHostName + "/maintenance/CC_down.html";
        // removed 08/12/2010 miki. #0010734
        //if (sUrl && sUrl.length > 0)
        // {
        //   sUrl += screenParam;
        //  sUrl += "&RT=" + new Date().getTime();
        // }

        if (sModel != null) {
            if ((sModel.indexOf('99745') > -1) || (sModel.indexOf('99765') > -1)) {
                sUrl += "&option1=710";
            }
        }
        if (blnOpenWindow) {
            gotoUrlNewWinSizeByName(sUrl, sWidth, sHeight, "PVA"); 
        }
        else {
            window.location.href = sUrl;
        }
    }
}

function PluginInfo(s, f) {
    this.shockwave = { req: s, version: "", installed: false };
    this.flash = { req: f, version: "", installed: false };
    this.setVersion = function (key, version) {
        var cP = this[key];
        if (cP) {
            cP.version = version;
            cP.installed = this.compVersion(cP.version, cP.req);
        }
    }
    this.getVersion = function (key) {
        if (this[key].version)
            return this[key].version;
        return "";
    }
    this.isInstalled = function (key) {
        if (key && this[key])
            return this[key].installed;
        return false;
    }
    // Vergleich von Versionsnummern (die kürzere bestimmt die zu vergleichende Länge)
    this.compVersion = function (cV, reqV) {
        rV = false;
        if (cV) {
            rV = true;
            var cArr = cV.split(".");
            var rArr = reqV.split(".");
            var min = cArr.length < rArr.length ? cArr.length : rArr.length;
            for (var i = 0; (rV == true && i < min); i++) {
                var cComp = parseInt(cArr[i]);
                var rComp = parseInt(rArr[i]);
                if (cComp > rComp)
                    break;
                else if (cComp < rComp)
                    rV = false;
            }
        }
        return rV;
    }
}
// Flash Player Version Detection - Rev 1.5
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion() {
    var version;
    var axo;
    var e;

    // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

    try {
        // version will be set for 7.X or greater players
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        version = axo.GetVariable("$version");
    } catch (e) {
    }

    if (!version) {
        try {
            // version will be set for 6.X players only
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

            // installed player is some revision of 6.0
            // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
            // so we have to be careful. 

            // default to the first public version
            version = "WIN 6,0,21,0";

            // throws if AllowScripAccess does not exist (introduced in 6.0r47)     
            axo.AllowScriptAccess = "always";

            // safe to call for 6.0r47 or greater
            version = axo.GetVariable("$version");

        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 4.X or 5.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = axo.GetVariable("$version");
        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 3.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = "WIN 3,0,18,0";
        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 2.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            version = "WIN 2,0,0,11";
        } catch (e) {
            version = "";
        }
    }

    return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer() {
    // NS/Opera version >= 3 check for Flash plugin in plugin array
    var flashVer = "";

    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            var descArray = flashDescription.split(" ");
            var tempArrayMajor = descArray[2].split(".");
            var versionMajor = tempArrayMajor[0];
            var versionMinor = tempArrayMajor[1];
            if (descArray[3] != "") {
                tempArrayMinor = descArray[3].split("r");
            } else {
                tempArrayMinor = descArray[4].split("r");
            }
            var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
            flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
        }
    }
    // MSN/WebTV 2.6 supports Flash 4
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    // WebTV 2.5 supports Flash 3
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    // older WebTV supports Flash 2
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    else if (isIE && isWin && !isOpera) {
        flashVer = ControlVersion();
    }
    return flashVer;
}

function CheckFlashInstalled() {
    var fString = GetSwfVer();
    var arr = fString.split(" ");
    if (arr.length > 1)
        return arr[1].replace(/,/g, ".");
    return fString;
}

var plgInVersion = "";
if (navigator.mimeTypes && navigator.mimeTypes["application/x-director"] && navigator.mimeTypes["application/x-director"].enabledPlugin) {
    if (navigator.plugins && navigator.plugins["Shockwave for Director"] && (versionIndex = navigator.plugins["Shockwave for Director"].description.indexOf("version ")) != -1) {
        var desc = navigator.plugins["Shockwave for Director"].description;
        var idx = desc.indexOf("version");
        if (idx > -1) plgInVersion = desc.substr(idx + 7);
    }
}

function isMac() {
    var nvgt = window.navigator;
    var platform = null;
    if (typeof (nvgt.platform) != 'undefined') {
        platform = nvgt.platform.toLowerCase();
        if (platform.indexOf('mac') != -1)
            return true;
    }
}

function plugigns() {
    var pluginInfo = new PluginInfo("11.5", "9.0");
    if (plgInVersion) {
        pluginInfo.setVersion("shockwave", plgInVersion);
    }
    pluginInfo.setVersion("flash", CheckFlashInstalled());
    if (plgInVersion && !pluginInfo.isInstalled("shockwave"))
        return "http://www.macromedia.com/shockwave/download/";
    if (!pluginInfo.isInstalled("flash"))
        return "http://www.adobe.com/go/getflashplayer";
    return null;
}

function ccbaseurl(marketID) {
    var url = '';
    var testFolder = '';
    var HostName = "";
    if (window.location.hostname == "intranet.porsche.com") {
        HostName = "http://cc.web.porsche.de";
    } else if (window.location.hostname == "preview.porsche.com" || window.location.hostname == 'localhost') {
        HostName = "https://ppnlite.porsche.com";
        testFolder = '_uat';
    } else {
        HostName = "http://cc.porsche.com";
    }
    switch (marketID) {
        case "US":
        case "CA":
        case "USCCF":
            url = HostName + "/icc_pcna" + testFolder ;
            break;
       default:
            url = HostName + "/icc_euro" + testFolder;
            break;
    }
    return url; 
}

function ccLoadConfig(marketID, lang) {
    var hookURL = escape(window.location.href);
    var sUrl = ccbaseurl(marketID);

    if (marketID == 'me')
    {
       sUrl = "/all/transitional/middle-east/models/countryselector/default.htm?t=";
    }
    else
      sUrl += "/ccCall.do?userID=" + marketID + "&lang="+ lang + "&PARAM=parameter_internet_"+ lang + "&hookURL=" + hookURL + "&loadConfig=1";         

    var screenParam = getScreenXYUrlParam();
    if (sUrl && sUrl.length > 0) {
        sUrl += screenParam;
        sUrl += "&RT=" + new Date().getTime();
    }
    document.location.href = sUrl;
}
/* Payment Estimator */
function openPE(model, type) {
    gotoUrlNewWinSimple('/usa/accessoriesandservices/porschefinancialservices/paymentestimator/?model=' + model + '&type=' + type);    
}

// CC Modellstartseite Jumppage Script
function openModelJumpPage(modelid, y, u, l, o, c) {
    var user = u;
    var lang = l;
    var options = o;
    var customid = c;
    if (customid.indexOf('&amp;') == -1) {
        customid = '&amp;customid=' + customid;
    }
    //var hookURL = escape(window.location.href.replace(window.location.search, ''));
    var hookURL = escape(window.location.href.replace(window.location.search, '') + "/all/");
    var baseurl = ccbaseurl(user);
    var uri = baseurl + "/ccCall.do?userID=" + user + "&amp;lang=" + lang + "&amp;PARAM=parameter_internet_" + lang + "&amp;hookURL=" + hookURL + "&amp;ORDERTYPE=" + modelid + options + customid;

    if (y != '') {
        uri += "&amp;MODELYEAR=" + y;
    }
    if (g_is_iPad) // (isMac())
    {
        document.location.href = (uri + "&amp;vLevel=5").replace(/&amp;/g, String.fromCharCode(38));
    }
    else {
        //Plugins?
        var install = plugigns();
        if (install != null) {
            $('#cluetip').hide();
            var u2 = uri + "&amp;vLevel=1";
            $('#x2D').attr('href', u2.replace(/&amp;/g, String.fromCharCode(38)));
            $('#noplug').attr('href', install);
            $('#chooseview').css('display', 'block');
        }
        else {
            document.location.href = (uri + "&amp;vLevel=2").replace(/&amp;/g, String.fromCharCode(38));
        }
    }
}

/* Windows module */

function configureCar(marketId, modelcode, tmp, modelrange) {
    /* For new CC inner size is important, but gotoUrlNewWinSizeByName() calcs outer size */
    var sWidth = 980;
    var sHeight = 680;
    sWidth -= g_is_ie ? 15 : 20;
    sHeight -= 25;

    if (configureCar_redirectPool(sWidth, sHeight, modelrange) == true) {
        return;
    }

    if (marketId.toLowerCase() == 'pap' && CURRENTCONDITION.toLowerCase() == 'singapore') {
        marketId = 'sg';
    } 
    var testFolder = '';

	/* R.W. Anpassung für den Intranet Server, um unterschiedliche CC URL's auszuliefern.*/
	var HostName = "";
	if (window.location.hostname == "intranet.porsche.com") {
		HostName = "http://cc.web.porsche.de";
		OriginHostName = "http://cc.web.porsche.de";
	} else if (window.location.hostname == "preview.porsche.com") {
        HostName = "https://ppnlite.porsche.com"; // (marketId == 'us' ? "https://preview.porsche.com" : "https://ppnlite.porsche.com");
        OriginHostName = "https://ppnlite.porsche.com";
		testFolder = '_uat';
	} else {
		HostName = "http://cc.porsche.com";
		OriginHostName = "http://origin-cc.porsche.com";
	}
		
    var sUrl = '';
    var ccURL =  HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_cc&lang=cc&userID=cc";
    switch (marketId) {
        case "de":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=de&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;

        case "us":
            /* JDPower Test */
            //sUrl = "/all/usa/startcc/default.htm?t=";
            sUrl = "http://cc.porsche.com/icc_pcna/ccCall.do?&vLevel=2&PARAM=parameter_internet_us&lang=us&userID=US"       
            if (window.location.hostname == "preview.porsche.com") {
				sUrl = "https://ppnlite.porsche.com/icc_pcna" + testFolder + "/ui/pva/index.jsp?sprache=us";
			}

//            sUrl = "/all/usa/startcc/default.htm?t=";
//			if (window.location.hostname == "preview.porsche.com") {
//				sUrl = "https://ppnlite.porsche.com/icc_pcna" + testFolder + "/ui/pva/index.jsp?sprache=us";
//			}
            //sUrl = OriginHostName + "/icc_pcna/ccCall.do?&vLevel=2&PARAM=parameter_internet_us&lang=us&userID=US"
            //srl = HostName + "/icc_pcna" + testFolder + "/ui/pva/pva.jsp?PARAM=parameter_internet_us&LANG=us&USER=US"
            //sUrl = HostName + "/icc_pcna/ui/pva/index.jsp?sprache=us&modelRange=null";
            break;

        case "ca":
            //sUrl = HostName + "/icc_pcna" + testFolder + "/ui/pva/index.jsp?sprache=ca&modelRange=null";
            sUrl = "http://cc.porsche.com/icc_pcna/ccCall.do?&vLevel=2&PARAM=parameter_internet_ca&lang=ca&userID=CA";
            break;

        case "ca-fr":
            //sUrl = HostName + "/icc_pcna" + testFolder + "/ui/pva/index.jsp?market=USCCF&sprache=cf&modelRange=null";
            sUrl = "http://cc.porsche.com/icc_pcna/ccCall.do?&vLevel=2&PARAM=parameter_internet_cf&lang=cf&userID=USCCF";
            break;

        case "fr":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=fr&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;

        case "it":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=it&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;

        case "en":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=en&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;

        case "sp":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=sp&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;

        case "mx":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=mx&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;
            
        case "hk":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=hk&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;

        case "ru":
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;

        case "ae":
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;
        
        case "me":
            sUrl = "/all/transitional/middle-east/models/countryselector/default.htm?t=";
            break;
        
        case "du":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=du&market=PDA&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDA";
            break;
        case "ba":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=ba&market=PDB&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDB";
            break;
        case "va":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=va&market=PDD&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDD";
            break;
        case "kw":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=kw&market=PDK&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDK";
            break;
        case "oa":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=oa&market=PDO&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDO";
            break;
        case "qu":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=qu&market=PDT&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDT";
            break;	
        case "ks":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=ks&market=PDS&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDS";
            break;
        case "sa":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=sa&market=PDR&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDR";
            break;
	    case "ao":
	        //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=ao&market=PDG&modelRange=null";
	        sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDG";
            break;
        case "jo":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=jo&market=PDJ&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDJ";
            break;
        case "lb":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=lb&market=PDL&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDL";
            break;
        case "ni":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=ni&market=PDF&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDF";
            break;

        case "eg":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=eg&market=PDE&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDE";
            break;
        case "gh":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=gh&market=MEG&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=MEG";
            break;
        case "il":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=il&market=PDH&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDH";
            break;
        case "pdh":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=il&market=PDH&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDH";
            break;
        case "ir":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=ir&market=PDU&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDU";
            break;
        case "pk":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=pk&market=PDV&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDV";
            break;
        case "sy":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=sy&market=MEY&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=MEY";
            break;
        case "ye":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=ye&market=PDM&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDM";
            break;
        
        case "jp":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=pj&modelRange=null";
            marketId = "pj";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;

        case "zh":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cn";
            marketId = "cn";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;
        case "ce":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=ce&market=PACCE";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PACCE";
            break;
        case "ba":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?market=PDB&sprache=ba";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDB";
            break;
        case "va":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?market=PDD&sprache=va";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDD";
            break;
        case "kw":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?market=PDK&sprache=kw";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDK";
            break;
        case "oa":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?market=PDO&sprache=oa";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDO";
            break;
        case "qu":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?market=PDT&sprache=qu";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDT";
            break;
        case "ks":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?market=PDS&sprache=ks";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDS";
            break;
        case "cur":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc";
            sUrl = ccURL;
            break;
        case "pap":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=pap";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "sg":
            //            sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=sg&modelRange=null";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;
        case "ind":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=ind";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "mal":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=mal";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "nca":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=nca";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "sri":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=sri";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "phi":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=phi";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "du":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=du&market=PDA";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDA";
            break;
        case "sa":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=sa&market=PDR";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=PDR";
            break;
        case "prt":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=po";
            marketId = "po";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_" + marketId + "&lang=" + marketId + "&userID=" + marketId;
            break;
        case "swiss-de":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?market=CHSD&sprache=sd";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_sd&lang=sd&userID=CHSD";
            break;
        case "swiss-fr":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?market=CHSF&sprache=sf";
            sUrl = HostName + "/icc_euro/ccCall.do?&vLevel=2&PARAM=parameter_internet_sf&lang=sf&userID=CHSF";
            break;
        case "swiss-it":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?market=CHSI&sprache=si";
            sUrl = HostName + "/icc_euro/ccCall.do?userID=CHSI&lang=si&PARAM=parameter_internet_si&vLevel=2";
            break;
        case "bef":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=bef";
            sUrl = ccURL + "&customID=" + marketId;
            break;			
        case "ben":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=ben";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "arg":
           // sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=arg";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "bar":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=bar";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "bul":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=bul";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        case "chi":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=chi";
            sUrl = ccURL + "&customID=" + marketId;
            break;


        case "bra":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=bra";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "bru":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=bru";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "cos":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=cos";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "dom":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=dom";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "ecu":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=ecu";
            sUrl = ccURL + "&customID=" + marketId;
            break;


        case "els":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=els";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "fin":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=fin";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "gua":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=gua";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "hai":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=hai";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "hon":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=hon";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "isl":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=isl";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "kai":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=kai";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "kol":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=kol";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "lux":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=lux";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "nie":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=nie";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "pan":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=pan";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "par":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=par";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "per":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=per";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "pue":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=pue";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "swe":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=swe";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "stm":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=stm";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "tri":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=tri";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "tue":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=tue";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "uru":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=uru";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "ven":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=ven";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "vie":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=vie";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "wed":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=wed";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "wef":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=wef";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "wei":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=wei";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "wie":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=wie";
            sUrl = ccURL + "&customID=" + marketId;
            break;

        case "zyp":
            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=cc&customID=zyp";
            sUrl = ccURL + "&customID=" + marketId;
            break;
        default:
            sUrl = ccURL;


            //sUrl = HostName + "/icc_euro" + testFolder + "/ui/pva/index.jsp?sprache=" + marketId + "&modelRange=null";
            break;
    }
    
    var screenParam = getScreenXYUrlParam();

    if (sUrl && sUrl.length > 0) {
        sUrl += screenParam;
        sUrl += "&RT=" + new Date().getTime();
    }

    // CC Down Hack
    //sUrl = HostName + "/maintenance/CC_down.html";
    
    //log(sUrl);
    gotoUrlNewWinSizeByName(sUrl, sWidth, sHeight, "PVA");
}

function configureCar_redirectPool(sWidth, sHeight, modelrange) {
    var currentHost = window.location.hostname;
    var currentUrl = window.location.href;
    var startpage = "/modelstart/all/";
    var path = currentHost + '/' + CURRENTPOOL;
    if (typeof (CURRENTCONDITION) == "undefined") {
        CURRENTCONDITION = '';
    }
    if (CURRENTLANGUAGE != "none") {
        if (CURRENTCONDITION != '') {
            path = path + '/' + '_' + CURRENTCONDITION + '_' + '/' + CURRENTLANGUAGE;
        }
        else {
            path = path + '/' + CURRENTLANGUAGE;
        }
    } else if (CURRENTCONDITION != '') {
        path = path + '/' + '_' + CURRENTCONDITION + '_';
    }
    var target = "";
    var redirectPool = false;

    if (modelrange == null) {
        if (currentUrl.indexOf(path + "/models") != -1) {
            target = path + startpage;
            log("if...: " + target);
            if (currentUrl.indexOf(path + "/models/911") != -1) {
                target = target + "?modelrange=911";
            } else if (currentUrl.indexOf(path + "/models/boxster") != -1) {
                target = target + "?modelrange=boxster";
            } else if (currentUrl.indexOf(path + "/models/cayman") != -1) {
                target = target + "?modelrange=cayman";
            } else if (currentUrl.indexOf(path + "/models/cayenne") != -1) {
                target = target + "?modelrange=cayenne";
            } else if (currentUrl.indexOf(path + "/models/panamera") != -1) {
                target = target + "?modelrange=panamera";
            }
        }
    }
    else if (modelrange != '') {
        switch (modelrange) {
            case "911":
            case "boxster":
            case "cayman":
            case "cayenne":
            case "panamera":
                target = path + startpage + "?modelrange=" + modelrange;
                break;
        }
        //log("if modelrange ...: " + target);
    }

    if (target != "") {
        switch (CURRENTPOOL) {
	    case "australia":
            case "canada":
            case "china":
            case "germany":
            case "france":
            case "germany":
            case "italy":
            case "international":
            case "japan":
            case "latin-america-en":
            case "latin-america-es":
            case "portugal":
            case "russia":
            case "spain":
            case "swiss":
            case "uk":
                redirectPool = true;
                break;
            case "middle-east":
                if (CURRENTCONDITION == '') {
                    redirectPool = false;
                }
                else {
                    redirectPool = true;
                }
                break;
            default:
                redirectPool = false;
                break;
        }
        
    }
    //log(redirectPool);
    if (redirectPool == true) {
        //log("goto...: " + window.location.protocol + '//' + target);
        //gotoUrlNewWinSizeByName(window.location.protocol + '//' + target, sWidth, sHeight, "PVA");
        gotoUrlNewWinSizeScrollable(window.location.protocol + '//' + target, 960, 680)
    }

    return redirectPool;
}


function getScreenXYUrlParam()
{
    var clientWidth = screen.width;
    var clientHeight = screen.height;
    return  '&screen='+clientWidth+'x'+clientHeight;
}

/*
Function compareModels
Description: 
    Wrapper for compareModelMulti with empty model parameters. Is mainly used to open the CM Popup from the shopping buttons.
Input: 
    marketId: name of the market to be loaded in compare models.
Output: void
*/
function compareModels(marketId) {
    if (marketId == 'usa') {
        compareModelMulti(marketId, '', '', '', true, 'iframe', null);
    }
    else {
        compareModelMulti(marketId, '', '', '', true, 'popup', null);
    }
}

/*
Function compareModelWith
Description:
    Wrapper for compareModelMulti to Open compare models tool (select page) with the given market name and two models to be compared to each other. 
Input:
    marketId: market name
    model1: First model's id.
    model2: Second model's id.	
Output: void.	
*/
function compareModelWith(marketId, model1, model2) {
    if (marketId == 'usa') {
        compareModelMulti(marketId, model1, model2, '', false, 'iframe', null);
    }
    else {
        compareModelMulti(marketId, model1, model2, '', false);
    }
}


/*
Function compareModelMulti
Description:
    Opens a popup window of variable size. 
    to load the compare models page for a given market, and three model IDs.
    The size can be adjusted for each market (pool) by setting the oneSizeFitsAll to false 
    and defining windowSizeX and windowSizeY for each pool.
Input:
    marketId: market (pool) name to be opened in the compare models tool.
    model1: First model's id.
    model2: Second model's id.	
    model3: Third model's id.
    openSelect: true if Select page is to be opened, false if compare page.
    (If further models are to be added, make the necessary changes in the url "cmUrl" and the window sizes.)
Output: void.	
*/
function compareModelMulti(marketId, model1, model2, model3, openSelect, windowMode, tab) {
    windowSizeX = 1003;
    windowSizeY = 625;
    oneSizeFitsAll = true;

    if (openSelect)
        cmPage = "Select"
    else
        cmPage = "Compare";

    // tab to open. default is empty (first tab).
    var tabString = "";
    if (tab && !isNaN(tab)) tabString = "&compTab=" + tab;


    if (!windowMode) windowMode = "popup";

    // create load the url.
    cmUrl = "/all/comparemodels/" + cmPage + ".aspx?pool=" + marketId + "&model1=" + model1 + "&model2=" + model2 + "&model3=" + model3 + "" + tabString;

    switch (windowMode) {
        case 'popup':
            // make the window sizes pool dependent, if desired.
            if (!oneSizeFitsAll)
                switch (marketId) {
                case "usa":
                    windowSizeX = 1003;
                    windowSizeY = 625;
                    break;
                case "canada":
                    windowSizeX = 975;
                    windowSizeY = 625;
                    break;
            }
            gotoUrlNewWinSize(cmUrl, windowSizeX, windowSizeY);
            break;
        case 'iframe':
            var settings = {
                width: 1024,
                height: 660,
                name: 'comparemodels'
            }
            var cmPane = new Overlay(cmUrl, settings);
            cmPane.show();
            break;
    }


}


function findADealerUSA() {
    var settings = {
        width: 1064,
        height: 731,
        name: 'findadealer',
        scrolling: 'auto'
    }
    var layer = new Overlay('http://www.porschedealer.com/dealer/usLocator/', settings);
    layer.show();
}


function Overlay(_url, _settings) {
    var self = this;

    this.settings = _settings;
    this.pane = null;
    this.shade = null;
    this.paneCSSClass = 'overlayPane';
    this.shadeCSSClass = 'overlayShade';
    this.borderWidth = 8;
    this.closeHandler = function (event) {
        log("event.type: " + event.type);
        if (event.type == 'keypress') {
            log("pressed key code: " + event.which);
            if (event.which == 0) self.close();
        }
        else {
            self.close();
        }

    }
    this.show = function () {
        iframehtml = '<div class="' + this.paneCSSClass + '">' +
                            '<div class="closeButton"><span class="closeLabel"></span><img src="/Images/close-button.gif" alt="[X]" title="" /></div>' +
                            '<iframe ' +
                            'width="' + this.settings.width + '"' +
                            'height="' + this.settings.height + '"' +
                            'frameborder="0"' +
                            'marginheight="0"' +
                            'marginheight="0"' +
                            'scrolling="' + (this.settings.scrolling == null ? 'no' : this.settings.scrolling) + '"' +
                            'name="' + this.settings.name + '"' +
                            'src="' + _url + '"' +
                            '></iframe></div>';
        $('body')
            .append('<div class="' + this.shadeCSSClass + '"></div>')
            .append(iframehtml);

        // bind necessary localized texts
        var i18n = new I18N();
        i18n.resolveText('js_apps', 'kbase', 'closeLabel', '.closeLabel'); // class="closeLabel"
        i18n.doProcessing();
        // add css classes
        this.pane = $('.' + this.paneCSSClass);
        this.shade = $('.' + this.shadeCSSClass);
        // define close behaviour



        $(".closeButton").unbind('click', self.closeHandler).bind('click', self.closeHandler);
        $(window).unbind('keypress', self.closeHandler).bind('keypress', self.closeHandler);

        var done = function () {
            self.reposition();
            self.pane.fadeIn(1200);
            //self.pane.animate({'visibility':'visible'}, 600, 'linear');

            $(window).resize(function () { self.reposition() });
            log('panel class: ' + self.paneCSSClass + '. Fade complete.');
        }
        this.fadeInBG(done);

    }

    this.reposition = function () {
        
//        var refContainer = g_is_home ? $('#homemenue') : ($('#menu3').length>0 ? $('#menu3') : $('#page'));
//        log("setting offset");
//        var _left = refContainer.offset().left - self.borderWidth;
//        log("left: " + _left);
//        var _top = ($(window).height() - self.pane.height()) / 2;
//        log("top: " + _top);        
        //        self.pane.css({ 'left': _left + 'px', 'top': _top + 'px' });

        var _left = ($(window).width() - self.pane.width() - self.borderWidth) / 2;
        var _top = ($(window).height() - self.pane.height()) / 2;
        if (_top < 10)
            _top = 10;
        self.pane.css({ 'left': _left + 'px', 'top': _top + 'px' });
    }

    this.close = function () {
        log("closing");
        //remove pane and shade
        self.pane.remove();
        self.shade.remove();
        // unbind window events
        $(window).unbind('keypress', self.closeHandler);
    }

    this.fadeInBG = function(callback) {
        log("fading in BG");
        this.shade.show();
        callback();
    }

}


function gotoUrlNewWinSimple(s, trackingname)
{
    if (trackingname != null) {
    click_track(trackingname);
    }
    var newWin = window.open('', "newWin" + getRandomInt(10000));
    newWin.document.location = s;
}

function gotoUrlNewWin(s)
{
    sWidth = 826;
    sHeight = 610;

    sWidth += 20;
    sHeight += 25;
    newWin = window.open(s, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=40,top=40,dependent=yes,location=no,resizable=no,scrollbars=no,status=no");
}

function gotoUrlNewWinSize(s, sWidth, sHeight)
{
    sWidth += 20;
    sHeight += 25;
    newWin = window.open(s, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=40,top=40,dependent=yes,location=no,resizable=no,scrollbars=no,status=no");
}

    
function gotoUrlNewWinSizeCloseOnBlur(s, sWidth, sHeight)
{
    sWidth += 20;
    sHeight += 25;
    g_newWinFocus = window.open(s, "newWinCloseOnBlur", "width=" + sWidth + ",height=" + sHeight + ",left=40,top=40,location=no,resizable=no,scrollbars=no,status=no");	   	   	
    g_newWinFocus.focus();	    
    
    window.onfocus = function()
    {
        if (g_newWinFocus)
        {
            g_newWinFocus.close()
            g_newWinFocus = null;	    	
        }
    }
}		

function gotoUrlNewWinSizeScrollable(s, sWidth, sHeight)
{
    sWidth += 20;
    sHeight += 25;
    newWin = window.open(s, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=40,top=40,dependent=yes,location=no,resizable=no,scrollbars=yes,status=no");
}


function gotoUrlNewWinSizeScrollableWithMenu(s, sWidth, sHeight)
{
    sWidth += 20;
    sHeight += 50;

    if (screen.height < 768) {
        if (sHeight > 450) sHeight = 430;
        if (sWidth > 783) sWidth = 790;
        sOffset = 0;
    }
    else if (screen.height < 1024) {
        if (sHeight > 550) sHeight = 550;
        sOffset = 10;
    }
    else {
        sOffset = 40;
    }

    newWin = window.open(s, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=" + sOffset + ",top=" + sOffset + ",dependent=yes,location=yes,menubar=yes,toolbar=yes,resizable=no,scrollbars=yes,status=yes");
}

function gotoUrlNewWinSizeScrollableWithMenuR(s, sWidth, sHeight)
{
    sWidth += 20;
    sHeight += 50;

    if (screen.height < 768) {
        if (sHeight > 450) sHeight = 430;
        if (sWidth > 783) sWidth = 790;
        sOffset = 0;
    }
    else if (screen.height < 1024) {
        if (sHeight > 550) sHeight = 550;
        sOffset = 10;
    }
    else {
        sOffset = 40;
    }

    newWin = window.open(s, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=" + sOffset + ",top=" + sOffset + ",dependent=yes,location=yes,menubar=yes,toolbar=yes,resizable=yes,scrollbars=yes,status=yes");
}


function gotoUrlNewWinDefaultSize(s)
{
    sWidth = 570;
    sHeight = 610;

    sWidth += 20;
    sHeight += 25;
    newWin = window.open(s, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=40,top=40,dependent=yes,location=no,resizable=no,scrollbars=no,status=no");
}

function gotoUrlNewWinSizeCentered(s, iWidth, iHeight)
{
    iWidth += 20;
    iHeight += 25;    
    iLeft = Math.round((screen.width - iWidth) / 2);
    iTop = Math.round((screen.height - iHeight) / 2);
    newWin = window.open(s, "newWin" + getRandomInt(10000), "width=" + iWidth + ",height=" + iHeight + ",left=" + iLeft + ",top=" + iTop + ",dependent=yes,location=no,resizable=no,scrollbars=no,status=no");
}

function gotoUrlNewWinSizeScrollableResizeable(s, sWidth, sHeight)
{
    sWidth += 20;
    sHeight += 25;
    newWin = window.open(s, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=40,top=40,dependent=yes,location=no,resizable=yes,scrollbars=yes,status=no");
}

function gotoUrlNewWinSizeByName(s, sWidth, sHeight, sName)
{
    sWidth += g_is_ie ? 15 : 20;
    sHeight += 25;
    newWin = window.open(s, sName, "width=" + sWidth + ",height=" + sHeight + ",left=40,top=40,dependent=yes,location=no,resizable=no,scrollbars=no,status=no");
}

function openLeanWin(sUrl, sWidth, sHeight)
{
    sWidth += 20;
    sHeight += 25;
    newWin = window.open(sUrl, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=140,top=140,dependent=yes,location=no,resizable=no,scrollbars=no,status=no,menubar=no,toolbar=no");
}

function gotoUrlFullscreen(sUrl, bScroll, trackingname) {
    var width = screen.width;
    var height = screen.height;
    var left = 0;
    var top = 0;
    if (trackingname != null) {
        log('start tracking');
        click_track(trackingname);
    }
    
    if (screen.width > 1920)
    {
        width = 1920;
        height = 1200;
        left = Math.round((screen.width - width) / 2);
        top = Math.round((screen.height - height) / 2);
    }
    
    var scrollbars = 0;
    if (bScroll) scrollbars = 1;
    
    var sProps = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=" + scrollbars + ",resizable=0,left=" + left + ",top=" + top + ",width=" + (width - 10) + ",height=" + (height - 55);	
    var site = window.open(sUrl,"porschemicrosite", sProps);
    site.focus();		
}

function gotoUrlFullscreenResizable(sUrl) {
    var width = screen.width;
    var height = screen.height;
    var left = 0;
    var top = 0;
    
    if (screen.width > 1920)
    {
        width = 1920;
        height = 1200;
        left = Math.round((screen.width - width) / 2);
        top = Math.round((screen.height - height) / 2);
    }
    
    var sProps = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,left=" + left + ",top=" + top + ",width=" + width + ",height=" + height;	
    var site = window.open(sUrl,"porschemicrosite_rs", sProps);
    site.focus();
}


function openDealerLocator(refForm, sWidth, sHeight, sName, sUrl, windowoptions) {
    if (!sUrl) sUrl = "";

    var topOffset = 40;

    if (sHeight > (self.screen.availHeight + topOffset - 40)) {
        sHeight = self.screen.availHeight - 40;
        topOffset = 0;
    }
    var options = "width=" + sWidth + ",height=" + sHeight + ",left=40,top=" + topOffset + ",dependent=yes,location=no,resizable=no,scrollbars=no,status=no";
    if (windowoptions) options = windowoptions;
    newWin = window.open(sUrl, sName, options);

    if (refForm) {
        refForm.target = sName;
        return true;
    }
    newWin.focus();
}

function openModelAdvisor(siteId)
{
    var iWidth = 831;
    var iHeight = 503;
    window.open("/all/modeladvisor/" + siteId + ".aspx", "newWin" + getRandomInt(10000) , "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,left=" + Math.round((screen.width - iWidth) / 2) + ",top=" + Math.round((screen.height - iHeight) / 2) + ",,width=" + iWidth + ",height=" + iHeight);
}



function getRandomInt(max)
{
    return Math.round( Math.random() * (max-1) );
}


/* Ad-Tracker module */

function getAdTrackerNumber()
{
    var axel = Math.random() + "";
    var a = axel * 10000000000000;
    return a;
}



/* Home module */

function initHome() {
    log("initHome running");
    // teaser bar scroller
    // Wird für Porsche-Stadt nicht benötigt
    // setupTeaserbar();

    if (!g_is_ie) {
        // FF 3.x opacity+cleartype bugfix
        $('.subnav,.topnavlink').each(function() {
            $(this).append('&#160;');
        });
    }
}

function bannerLinkToHi(sId) {
    var elm = document.getElementById(sId);
    if (elm) {
        elm.style.color = "#c00";
        //elm.style.backgroundImage = "url(/images/arrow-red.gif)";
        elm.style.backgroundPosition = "0 -150px;";
    }
}

function bannerLinkToLo(sId) {
    var elm = document.getElementById(sId);
    if (elm) {
        elm.style.color = "rgb(102,102,102)";
        //elm.style.backgroundImage = "url(/images/arrow-gray.gif)";
        elm.style.backgroundPosition = "210px -292px;";
    }
}

function navShadeIn(level) {
    if (level == 1) {
        if (g_timeoutHide1 != 0) { clearTimeout(g_timeoutHide1); }
    }
    else if (level == 2) {
        if (g_timeoutHide1 != 0) { clearTimeout(g_timeoutHide1); }
        if (g_timeoutHide2 != 0) { clearTimeout(g_timeoutHide2); }
    }
    else if (level == 3) {
        if (g_timeoutHide1 != 0) { clearTimeout(g_timeoutHide1); }
        if (g_timeoutHide2 != 0) { clearTimeout(g_timeoutHide2); }
        if (g_timeoutHide3 != 0) { clearTimeout(g_timeoutHide3); }
    }
}

function navShadeOut(level) {
    if (level == 1) {
        g_timeoutHide1 = setTimeout("hideNav(1,\"" + g_currentNav1 + "\",\"" + g_currentHi1 + "\")", g_timeoutTime);
    }
    else if (level == 2) {
        g_timeoutHide1 = setTimeout("hideNav(1,\"" + g_currentNav1 + "\",\"" + g_currentHi1 + "\")", g_timeoutTime);
        g_timeoutHide2 = setTimeout("hideNav(2,\"" + g_currentNav2 + "\",\"" + g_currentHi2 + "\")", g_timeoutTime);
    }
    else if (level == 3) {
        g_timeoutHide1 = setTimeout("hideNav(1,\"" + g_currentNav1 + "\",\"" + g_currentHi1 + "\")", g_timeoutTime);
        g_timeoutHide2 = setTimeout("hideNav(2,\"" + g_currentNav2 + "\",\"" + g_currentHi2 + "\")", g_timeoutTime);
        g_timeoutHide3 = setTimeout("hideNav(3,\"" + g_currentNav3 + "\",\"" + g_currentHi3 + "\")", g_timeoutTime);
    }
}

function overNav(level, sName, sSelf) {
    if (level == 0 || level == "0") {
        //echo("level in 0");
		
        if (g_timeoutHide1 != 0) { clearTimeout(g_timeoutHide1); }

        hideSubLayers(g_currentNav1);
        loliteLr(level, g_currentHi1);

        if (g_currentNav1 != "") { hideSubLayers(g_currentNav1); }
        if (g_currentHi1 != "") { loliteLr(level, g_currentHi1); }

        showNav(level + 1, sName, sSelf);
        g_currentNav1 = sName;
        g_currentHi1 = sSelf;
		
    }
    else if (level == 1 || level == "1") {
        //echo("level in 1");

        if (g_timeoutHide1 != 0) { clearTimeout(g_timeoutHide1); }
        if (g_timeoutHide2 != 0) { clearTimeout(g_timeoutHide2); }

        if (g_currentNav2 != "") { hideSubLayers(g_currentNav2); }
        if (g_currentHi2 != "") { loliteLr(level, g_currentHi2); }

        showNav(level + 1, sName, sSelf);
        g_currentNav2 = sName;
        g_currentHi2 = sSelf;
    }
    else if (level == 2 || level == "2") {
        //echo("level in 2");

        if (g_timeoutHide1 != 0) { clearTimeout(g_timeoutHide1); }
        if (g_timeoutHide2 != 0) { clearTimeout(g_timeoutHide2); }
        if (g_timeoutHide3 != 0) { clearTimeout(g_timeoutHide3); }

        if (g_currentNav3 != "") { hideSubLayers(g_currentNav3); }
        if (g_currentHi3 != "") { loliteLr(level, g_currentHi3); }

        showNav(level + 1, sName, sSelf);
        g_currentNav3 = sName;
        g_currentHi3 = sSelf;
    }
    else if (level == 3 || level == "3") {
        //echo("level in 3");

        if (g_timeoutHide1 != 0) { clearTimeout(g_timeoutHide1); }
        if (g_timeoutHide2 != 0) { clearTimeout(g_timeoutHide2); }
        if (g_timeoutHide3 != 0) { clearTimeout(g_timeoutHide3); }
        if (g_timeoutHide4 != 0) { clearTimeout(g_timeoutHide4); }

        if (g_currentNav4 != "") { hideSubLayers(g_currentNav4); }

        showNav(level + 1, sName, sSelf);
        g_currentNav4 = sName;
    }
}

var loadImage_timeOut = 150; // ms the user has to spend on a navigation link before the image starts to load.
var loadImage_timeOutHandler;

function loadImage(sName, sUrl) {
    var fn = function () { $('#' + sName + "_image").attr('src', sUrl); }
    window.clearTimeout(loadImage_timeOutHandler);
    loadImage_timeOutHandler = window.setTimeout(fn, loadImage_timeOut);
}

function outNav(level) {
    if (level == 0 || level == "0") {
        //log("level out 0");
		
        g_timeoutHide1 = setTimeout("hideNav(1,\"" + g_currentNav1 + "\",\"" + g_currentHi1 + "\")", g_timeoutTime);
    }
    else if (level == 1 || level == "1") {
        //log("level out 1");
        g_timeoutHide1 = setTimeout("hideNav(1,\"" + g_currentNav1 + "\",\"" + g_currentHi1 + "\")", g_timeoutTime);
        g_timeoutHide2 = setTimeout("hideNav(2,\"" + g_currentNav2 + "\",\"" + g_currentHi2 + "\")", g_timeoutTime);
    }
    else if (level == 2 || level == "2") {
        //log("level out 2");
        g_timeoutHide1 = setTimeout("hideNav(1,\"" + g_currentNav1 + "\",\"" + g_currentHi1 + "\")", g_timeoutTime);
        g_timeoutHide2 = setTimeout("hideNav(2,\"" + g_currentNav2 + "\",\"" + g_currentHi2 + "\")", g_timeoutTime);
        g_timeoutHide3 = setTimeout("hideNav(3,\"" + g_currentNav3 + "\",\"" + g_currentHi3 + "\")", g_timeoutTime);
    }
    else if (level == 3 || level == "3") {
        //log("level out 3");        
        g_timeoutHide1 = setTimeout("hideNav(1,\"" + g_currentNav1 + "\",\"" + g_currentHi1 + "\")", g_timeoutTime);
        g_timeoutHide2 = setTimeout("hideNav(2,\"" + g_currentNav2 + "\",\"" + g_currentHi2 + "\")", g_timeoutTime);
        g_timeoutHide3 = setTimeout("hideNav(3,\"" + g_currentNav3 + "\",\"" + g_currentHi3 + "\")", g_timeoutTime);
        g_timeoutHide4 = setTimeout("hideNav(4,\"" + g_currentNav4 + "\",\"" + g_currentHi4 + "\")", g_timeoutTime);
    }
    else {
        //echo("level out is else: " + level);
    }    
}

function dimHeadline(doOn) {
    var elem = document.getElementById(g_home_head_id);
    if (elem) {
        if (doOn) {
            elem.style.Opacity = "1.00";
            elem.style.opacity = "1.00";
            elem.style.filter = "alpha(opacity=100)";
        }
        else {
            elem.style.Opacity = ".40";
            elem.style.opacity = ".40";
            elem.style.filter = "alpha(opacity=40)";
        }
    }
}

function showNav(level, sName, sSelf) {    
    dimHeadline(false);
    hiliteLr(level - 1, sSelf);
    var foundOne = showSubLayers(sName);
    if (foundOne) {
        showLr("navshade" + level);
    }
    else {
        hideLr("navshade" + level);
    }
    if (level == 3) {
            // displaying flyout, hide the dealer search container.
            $('#dealersearchShadow, .originButton').hide();
            $('#introImage img').fadeTo(150, 0.5);
       
    }
}

function hideNav(level, sName, sSelf)
{
    if (level == 1) {
        g_timeoutHide1 = 0; g_currentNav1 = ""; g_currentSelf1 = "";
        dimHeadline(true);
    }
    if (level == 2) {
        g_timeoutHide2 = 0; g_currentNav2 = ""; g_currentSelf2 = ""; 
    }
    if (level == 3) { g_timeoutHide3 = 0; g_currentNav3 = ""; g_currentSelf3 = ""; }
    if (level == 4) { g_timeoutHide4 = 0; g_currentNav4 = ""; }

    loliteLr(level - 1, sSelf);
    hideLr("navshade" + level);
    hideSubLayers(sName);
    if (level == 3) {
        $('#introImage img').fadeTo(100, 1);
        $('#dealersearchShadow, .originButton').show();
    }
}

function fadeAllOut(elem)
{
  if(elem == undefined)
    return;

  if(g_jdpowerphase == "none")
   return;

  var ID = elem.id
  var i = 0;
  var which = parseInt(ID.replace('link', '').replace('topnav', ''));
  for (; i <= G_MAXITEMS_MAINNAVI; i++)
  {
    if((i <= 5) && (which != i))
    {
      fadeOut('topnavlink' + i.toString());
    }
    if((i >= 6) && (which != i))
      fadeOut('topnavlink' + i.toString());
  }
}
function fadeAllIn(elem)
{
  if(elem == undefined)
    return;

  if(g_jdpowerphase == "none")
   return;

  var ID = elem.id
  var i = 0;
  var which = parseInt(ID.replace('link', '').replace('topnav', ''));
  for (; i <= G_MAXITEMS_MAINNAVI; i++)
  {
    if((i <= 5) && (which != i))
    {
      fadeIn('topnavlink' + i.toString());
    }
    if((i >= 6) && (which != i))
      fadeIn('topnavlink' + i.toString());
  }
}
function fadeOut(ID)
{
  var elem = document.getElementById(ID);
  
  if(elem)
  {    
    elem.style.Opacity = ".5"; 
    elem.style.opacity = ".5"; 
    if (g_is_ie) {
        if (g_is_ie7) elem.parentNode.style.filter = "Alpha(opacity=50)";
        else if (g_is_ie8)  {
            $(elem).parent().addClass('iefade');
            //elem.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 50;
        }
    }
    
  }
}
function fadeIn(ID)
{
  var elem = document.getElementById(ID);
  if(elem)
  {
    elem.style.Opacity = "0.50"; 
    elem.style.opacity = "0.50"; 
    
    if (g_is_ie) {
        if (g_is_ie7) elem.parentNode.style.filter = "Alpha(opacity=100)";
        else if (g_is_ie8) {
            $(elem).parent().removeClass('iefade');
            //elem.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
        }
    }
    //elem.style.filter = "Alpha(opacity=100)";
  }
}







function hiliteLr(level, sName) {
  
    var elem = document.getElementById(sName);
    if (elem) {
        if (level == 0 || level == "0") {
        	//////////////////////
            var itemNo = parseInt(sName.replace('topnavlink', '').replace('topnav', ''));
            
            
               var topNavi = document.getElementById("topnav" + itemNo.toString());
                topNavi.style.backgroundPosition = get_homenavi_background_position(g_home_modelnavi_num_modelranges_background, true); //"0px -550px";
					elem.style.color = "#fff";
                    elem.style.backgroundPosition = "0 -350px";
                    elem.style.Opacity = "1.00";
                    elem.style.opacity = "1.00";
                    elem.style.filter = "alpha(opacity=100)";
            
            fadeAllOut(elem);
            //////////////////////
        }
        else {
            elem.style.color = g_homemenu_hl_fontcolor; //"rgb(204, 0, 0)";
            elem.style.backgroundColor = g_homemenu_hl_background_color_Level5; // "#FFFFFF";
            if (!(elem.className.indexOf("final") >= 0)) {
                elem.style.backgroundPosition = "0px -50px";
            }
            elem.style.Opacity = "1.00";
            elem.style.opacity = "1.00";
            elem.style.filter = "alpha(opacity=100)";
        }
    }
}



function hiliteLrJDP(level, sName) {
    var elem = document.getElementById(sName);
    
    //log("hiliteJDP level=" + level + " : sName=" + sName);
    if (elem) {
        var itemNo = parseInt(sName.replace('topnavlink', '').replace('topnav', ''));
        elem.style.backgroundPosition = navBGPos(elem, itemNo, level, true);
        if (level == 0 || level == "0") {
                //log("hiliteJDP level=" + level + " : itemNo <= 5");
                var topNavi = document.getElementById("topnav" + itemNo.toString());
                topNavi.style.backgroundPosition = get_homenavi_background_position(g_home_modelnavi_num_modelranges_background, true); //"0px -550px";
				elem.style.backgroundPosition = get_homenavi_background_position(itemNo, true); //img;
            
            fadeAllOut(elem);
        }
        else if (level == 2) {
            //elem.style.color = '#fff';
            $(elem).find("a").andSelf().css('color', '#fff');
        }
        else {
            $(elem).find("a").andSelf().css('color', '#fff');
            elem.style.Opacity = "1.00";
            elem.style.opacity = "1.00";
            elem.style.filter = "alpha(opacity=100)";
        }
    }
}

var navBGPos = function (elem, itemNo, level, mouseover) {
    var pos;

    //var itemNo;
    var lint = parseInt(level, 10);
    switch (lint) {
        case 0:
           if (mouseover) pos = "0px -150px"; else pos = "0px -100px";
            
        case 1:
            if (isNaviFinal(elem))
                pos = mouseover ? "0px -250px" : "0px -200px";
            else
                pos = mouseover ? "0px -50px" : "0px -150px";
            break;
        case 2:
            if (isNaviFinal(elem))
                pos = mouseover ? "0px -250px" : "0px -200px";
            else
                pos = mouseover ? "0px -50px" : "0px -150px";
            break;

    }
    return pos;
}

function isNaviFinal(elem) {
    return $(elem).hasClass('final');
}

function loliteLr(level, sName) {
    

    var elem = document.getElementById(sName);
    if (elem) {
        if (level == 0 || level == "0") {

            //////////////////////
            var itemNo = parseInt(sName.replace('topnavlink', '').replace('topnav', ''));
            

              /*  var topNavi = document.getElementById("topnav" + itemNo.toString()); // NOP
                topNavi.style.backgroundPosition = get_homenavi_background_position(g_home_modelnavi_num_modelranges_background, false); //"0px -500px";
                elem.style.backgroundPosition = get_homenavi_background_position(itemNo, false);
            */
			elem.style.color = "#000";
            elem.style.Opacity = "0.5";
            elem.style.opacity = "0.5";
            elem.style.filter = "alpha(opacity=50)";    
			   elem.style.backgroundColor = g_homemenu_ll_background_color;
			   if (!(elem.className.indexOf("final") >= 0)) {
                    elem.style.backgroundPosition = g_homemenu_ll_background_position_level0;
               
            }

               
            fadeAllIn(elem);
            //////////////////////
        }
        else {
            elem.style.color = g_homemenu_ll_fontcolor_level1;
            elem.style.backgroundColor = g_homemenu_ll_background_color_Level5; // "#EEF2F5"; // "#FFFFFF";
            if (!(elem.className.indexOf("final") >= 0)) {
                elem.style.backgroundPosition = g_homemenu_ll_background_position_level1;
            }
        }
    }
}


function loliteLrJDP(level, sName) {
    var elem = document.getElementById(sName);
    if (elem) {
        var itemNo = parseInt(sName.replace('topnavlink', '').replace('topnav', ''));
        //log("elem: " + elem + ",  itemNo: " + itemNo + ", level: " + level);
        elem.style.backgroundPosition = navBGPos(elem, itemNo, level, false);

        if (level == 0 || level == "0") {

                //log("loliteLrJDP level=" + level + " : if g_jdpowerphase == 200803 branch");                
                var topNavi = document.getElementById("topnav" + itemNo.toString());
                topNavi.style.backgroundPosition = get_homenavi_background_position(g_home_modelnavi_num_modelranges_background, false); //"0px -550px";
                elem.style.backgroundPosition = get_homenavi_background_position(itemNo, false); //img;
                
               
               

            
            fadeAllIn(elem);
        }
        else {
            //log("loliteLrJDP level=" + level + " : else branch, elem.style.backgroundPosition: " + elem.style.backgroundPosition);
            $(elem).find("a").andSelf().css('color', g_homemenu_ll_fontcolor_level1);
            //elem.style.color = g_homemenu_ll_fontcolor_level1;
        }
    }
}

function showSubLayers(sName) {
    var i = 0;
    var foundOne = false;

    for (i = 1; i <= G_MAXSUBLAYERS; i++) {
        var s = "nav_" + sName + "_" + i;
        var elem = document.getElementById(s);
        if (elem) {
            foundOne = true;
        }
        else {
            continue;
        }

        showLr(s);
    }

    return foundOne;
}



function hideSubLayers(sName)
{
    var i = 0;
    var foundOne = false;

    for (i = 1; i <= G_MAXSUBLAYERS; i++)
    {
        var s = "nav_" + sName + "_" + i;
        var elem = document.getElementById(s);
        if (elem)
        {
            foundOne = true;
        }
        else
        {
            continue;
        }

        hideLr(s);
    }

    return foundOne;
}

function setModel(s)
{
    g_currentModelLink = s;
}

function gotoModel()
{
    if (g_currentModelLink != '')
    {
        gotoUrl(g_currentModelLink);
    }
}

function gotoUrl(s)
{
    //g_psyma_navi_clicked = true;
    document.location.href = s;
}

function gotoUrlDropDown(e)
{
    if (e.options)
    {
        var url = e.options[e.options.selectedIndex].value;
        if(url != '')gotoUrl(url);			
    }
}

function gotoUrlTimeout(s, timeout)
{
  setTimeout("gotoUrl('" + s + "')", timeout)
}
function nogo()
{
    //
}

function selectAllInput(elm)
{
    if (elm)
    {
        elm.focus();
        elm.select();
    }
}

function changedCountry(elmThis)
{
    if (document.getElementById)
    {
        var sUrl = elmThis.value;

        if (sUrl != "") {
            var queryString = '';
            if (sUrl.toLowerCase().indexOf('javascript:') == -1) {
                queryString = getQueryString().replace('?', '&');
                if (queryString != '') {
                    queryString = '?' + queryString;
                }
            }
            //log(queryString);
            document.location.href = sUrl + queryString;
        }
    }
}

function sniffAll()
{
    /* JavaScript Browser Sniffer
       Eric Krok, Andy King, Michel Plungjan Jan. 31, 2002
       see http://www.webreference.com/ for more information
       This program is free software */

    var agt=navigator.userAgent.toLowerCase();
    var appVer = navigator.appVersion.toLowerCase();

    var is_minor = parseFloat(appVer);
    var is_major = parseInt(is_minor);

    var is_opera = (agt.indexOf("opera") != -1);

    /*
    var is_opera6 = (agt.indexOf("opera 6") != -1 || agt.indexOf("opera/6") != -1);
    var is_opera7 = (agt.indexOf("opera 7") != -1 || agt.indexOf("opera/7") != -1);
    var is_opera6up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5);
    var is_opera7up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5 && !is_opera6);
    */

    var iePos  = appVer.indexOf('msie');
    if (iePos !=-1) {
       is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)));
       is_major = parseInt(is_minor);
    }

	
    var is_konq = false;
    var kqPos   = agt.indexOf('konqueror');
    if (kqPos !=-1) {                 
       is_konq  = true;
       is_minor = parseFloat(agt.substring(kqPos+10,agt.indexOf(';',kqPos)));
       is_major = parseInt(is_minor);
    }

    var is_getElementById   = (document.getElementById) ? "true" : "false";
    var is_getElementsByTagName = (document.getElementsByTagName) ? "true" : "false";
    var is_documentElement = (document.documentElement) ? "true" : "false";

    var is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false;
    var is_khtml  = (is_safari || is_konq);

    var is_gecko = ((!is_khtml)&&(navigator.product)&&(navigator.product.toLowerCase()=="gecko"))?true:false;
    var is_gver  = 0;
    if (is_gecko) is_gver=navigator.productSub;

    var is_moz   = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) &&
                    (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)  &&
                    (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)     &&
                    (is_gecko) && 
                    ((navigator.vendor=="")||(navigator.vendor=="Mozilla")));

    var is_mac = ((agt.indexOf('macintosh')!=-1))?true:false;
    var is_linux = (navigator.platform.toLowerCase().indexOf('linux')!=-1)?true:false;
    var is_win = (navigator.platform.toLowerCase().indexOf('win')!=-1)?true:false;
    
    if (is_moz) {
       var is_moz_ver = (navigator.vendorSub)?navigator.vendorSub:0;
       if(!(is_moz_ver)) {
           is_moz_ver = agt.indexOf('rv:');
           is_moz_ver = agt.substring(is_moz_ver+3);
           is_paren   = is_moz_ver.indexOf(')');
           is_moz_ver = is_moz_ver.substring(0,is_paren);
       }
       is_minor = is_moz_ver;
       is_major = parseInt(is_moz_ver);
    }

    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)
                && (!is_khtml) && (!(is_moz)));

    if ((navigator.vendor)&&
        ((navigator.vendor=="Netscape6")||(navigator.vendor=="Netscape"))&&
        (is_nav)) {
       is_major = parseInt(navigator.vendorSub);
       is_minor = parseFloat(navigator.vendorSub);
    }

    var is_nav2 = (is_nav && (is_major == 2));
    var is_nav3 = (is_nav && (is_major == 3));
    var is_nav4 = (is_nav && (is_major == 4));
    var is_nav4up = (is_nav && is_minor >= 4); 
    var is_navonly  = (is_nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );

    var is_nav6   = (is_nav && is_major==6);
    var is_nav6up = (is_nav && is_minor >= 6);

    var is_nav5   = (is_nav && is_major == 5 && !is_nav6);
    var is_nav5up = (is_nav && is_minor >= 5);

    var is_nav7   = (is_nav && is_major == 7);
    var is_nav7up = (is_nav && is_minor >= 7);

    var is_ie   = ((iePos!=-1) && (!is_opera) && (!is_khtml));
    var is_ie3  = (is_ie && (is_major < 4));

    var is_ie4   = (is_ie && is_major == 4);
    var is_ie4up = (is_ie && is_minor >= 4);
    var is_ie5   = (is_ie && is_major == 5);
    var is_ie5up = (is_ie && is_minor >= 5);
    
    var is_ie5_5  = (is_ie && (agt.indexOf("msie 5.5") !=-1));
    var is_ie5_5up =(is_ie && is_minor >= 5.5);
    
    var is_ie6   = (is_ie && is_major == 6);
    var is_ie6up = (is_ie && is_minor >= 6);

    var is_ie7   = (is_ie && is_major == 7);
    var is_ie8   = (is_ie && is_major == 8);
    // OS
    g_is_win = is_win;
    g_is_mac = is_mac;
    g_is_linux = is_linux;
    
    g_is_ie = is_ie;
    g_is_opera = is_opera;
    g_is_ie5 = is_ie5;
    g_is_ie5_5 = is_ie5_5;
    g_is_ie6 = is_ie6;
    
    g_is_ie7 = is_ie7;
    g_is_ie8 = is_ie8;
    
    g_is_safari = is_safari;
}



/* Module Motorschaubild */

function showDetail(item) {
    getDiagramDetail(item).style.display = "block";
}
    
function hideDetail(item) {
    getDiagramDetail(item).style.display = "none";
}    
    
function getDiagramDetail(item) {
    return document.getElementById("engineDiagramDetail" + item.getAttribute("id").substr(17,2));
}

function switchDiagramPage()
{
   var page1 = document.getElementById("engineDiagramPage1");     
   var page2 = document.getElementById("engineDiagramPage2");
     
   if (page1 && page2) {
        var show2ndPage = ((page1.style.display == "") || (page1.style.display == "block"));
        
        var control = document.getElementById("engineDiagramControl");
                
        if (show2ndPage) {
                page1.style.display = "none";
                page2.style.display = "block";
                control.innerHTML = "<a href=\"javascript:switchDiagramPage();\">&lt; 2/2</a>";
        } else {
                page1.style.display = "block";
                page2.style.display = "none";
                control.innerHTML = "<a href=\"javascript:switchDiagramPage();\">1/2 &gt;</a>";                
        }
   } 
}

var g_currentDiagramPage = 1;

function nextDiagramPage(diagramID)
{
    showDiagramPage(g_currentDiagramPage + 1, diagramID);
}
function previousDiagramPage(diagramID)
{
    showDiagramPage(g_currentDiagramPage - 1, diagramID);
}
function showDiagramPage(pageToDisplay, diagramID)
{
    if(!pageToDisplay)
        pageToDisplay = 1;
    if(!diagramID)
        diagramID = "";

    var pageToShow = null;
    var pageCount = 1;
    var page = document.getElementById(diagramID + "Page" + pageCount);
    while(page){
        pageCount++;
        page = document.getElementById(diagramID + "Page" + pageCount);
    }
    var maxPages = pageCount - 1;

    var pageToHide = document.getElementById(diagramID + "Page" + g_currentDiagramPage);
    if(pageToHide)
        pageToHide.style.display = "none";

    pageToShow = document.getElementById(diagramID + "Page" + pageToDisplay);
    if(pageToShow)
        pageToShow.style.display = "block";

    var pages = pageToDisplay + "&#160;/&#160;" + maxPages;
    var previous = (pageToDisplay == 1) ? "&#160;" : "&#160;&#160;&lt;&#160;&#160;";
    var next = (pageToDisplay == maxPages) ? "&#160;&#160;&#160;&#160;&#160;&#160;" : "&#160;&#160;&gt;&#160;&#160;";
    var control = document.getElementById(diagramID + "Control");
    if(control)
    {
        if(maxPages == 1)
            control.innerHTML = previous + pages + next;
        else if (pageToDisplay == maxPages)
            control.innerHTML = "<a href=\"javascript:previousDiagramPage('" + diagramID + "');\">" + previous + "</a>" + pages + next;
        else if(pageToDisplay == 1)
            control.innerHTML = previous + pages + "<a href=\"javascript:nextDiagramPage('" + diagramID + "');\">" + next + "</a>";
        else
            control.innerHTML = "<a href=\"javascript:previousDiagramPage('" + diagramID + "');\">" + previous + "</a>"
                             + pages
                             + "<a href=\"javascript:nextDiagramPage('" + diagramID + "');\">" + next + "</a>";

        g_currentDiagramPage = pageToDisplay;
    }
}
  
/* Module Image Switch */

function updateImageSwitch(elm, state)
{
    var elmChild = null;
    
    if (elm.childNodes[0].style != undefined) {
        elmChild = elm.childNodes[0];
    } else {
        elmChild = elm.childNodes[1];
    }

    switch (state) {
        case "active":    

            var i = 1;
            do {
                var elmInactive = document.getElementById("switchImage" + i);
                if (elmInactive != null) {
                    updateImageSwitch(elmInactive, "inactive");
                }
                i++;
            } while (elmInactive != null)

            elm.style.color = "rgb(204,0,0)";
            elm.style.background = "white url(/images/arrow-red.gif) no-repeat left 3px";
            elmChild.style.display = "block";                      
            break;
        case "inactive":
            elm.style.color = "rgb(102,102,102)";
            elm.style.background = "white url(/images/arrow-gray.gif) no-repeat left 3px";
            elmChild.style.display = "none";                                      
    }
}

/* Macht ein Redirect zur Value des ausgewählten Elements der angegebenen Select Box */
function RedirectToOptionValue(name)
{
  obj = document.getElementById(name);
  if(obj)
  {
    link = obj.options[obj.selectedIndex].value;
    if(link.length > 0)
    {
      document.location.href = link;
    }
  }
}


/* SSO Cookie Check (to support caching) */

function ShowIfLoggedIn(id)
{
    if ( isLoggedIn() ) {
        var elm = document.getElementById(id);
        if (elm) {
            elm.style.display = "inline";
        }
    }
}

function HideIfLoggedIn(id)
{
    if ( isLoggedIn() ) {
        var elm = document.getElementById(id);
        if (elm) {
            elm.style.display = "none";
        }
    }
}

function isLoggedIn()
{
    var status = getCookie("SSO_LOGIN");
    if (status == null || status=='false') { status = false; }
    return status;
}

function getCookie(name)
{
    var thisCookie = document.cookie;
    var index = thisCookie.indexOf(name + "=");
    if (index == -1) return null;
    index = thisCookie.indexOf("=", index) + 1;
    var endstr = thisCookie.indexOf(";", index);
    if (endstr == -1) endstr = thisCookie.length;
    return unescape(thisCookie.substring(index, endstr));
}

function replStr(str,oldStr,newStr)
{ var strPos=str.indexOf(oldStr);
  return (strPos>=0) ?
    str.substring(0,strPos) + newStr +
       replStr( str.substring(strPos +
       oldStr.length), oldStr, newStr ) :
    str
}

function gotoUrlIE(url) 
{
    ;
}

function submitSDSTrainingSearchForm()
{
    var sfsForm = document.getElementById("SDSTrainingSearchForm");
    if (sfsForm.month.options.selectedIndex != 0)
        sfsForm.submit();
}

//
// Function ieToggleDropDowns: 
//
// Description: Toggles dropdown visibility in case of a dynamic layer 
// covering them pops up, and has a z-index higher than these. IE does not handle them correctly.
//
// Input: 
// 		strAttr: String Array, whose elements are the <DIV> id's to toggle. See function: getListIEDropDowns() 
//		boolHide: Boolean toggle. true, if the layer should be made visible, false otherwise.
// Returns : none.
function ieToggleDropDowns(boolHide) {
    // collection of dropdowns
    var strArr = getListIEDropDowns();
    if (strArr.length > 0) {
        for (i=0; i < strArr.length; i++) {
            dd = document.getElementById(strArr[i]);
            if (dd) 
                if (boolHide) 
                {
                    dd.style.visibility = 'hidden'
                }
                else
                {
                    dd.style.visibility = 'visible';
                }
        }
    }
}

//
// Function getListIEDropDowns():
//
// Description: Builds an array of Dropdowns whose visibility should be toggled 
// in case of a dynamic layer covering them.
// Input: none.
// Returns: String array of <DIV> id's.
function getListIEDropDowns() {
    return (new Array("monthDropDown", "modelprice", "modelpower"));
}


function showGalleryQuicktime(src) {
    g_fallbackImage = $('#galleryImage').attr('src');
    showQuicktime(src, 'galleryContent', '595', '317');
}


function showQuicktime(src, layer , width, height)
{
    var elm = document.getElementById(layer);
    if (elm && isQTInstalled())
    {
        var qtstring = '';
        qtstring += '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="'+width+'" height="'+height+'" id="galleryQuicktimeMovie">' 
        qtstring += '<param name="src" value="'+src+'"><embed height='+height+' width='+width+' src="'+src+'" type="video/quicktime" pluginspage="www.apple.com/quicktime/download" enablejavascript="true" name="galleryQuicktimeMovie" />'
        qtstring += '</object>'
        
        elm.innerHTML = qtstring;
    }
}


function showFullscreenQuicktime(src)
{
    if (isQTInstalled())
    {
        sWidth = window.screen.availWidth;
        sHeight = window.screen.availHeight;
        var doc = window.open("/all/transitional/all/panoramaPopup/panoramaPopup.asp?qt=" + src, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=0,top=0,dependent=yes,location=no,resizable=yes,scrollbars=no,status=no");			
        doc.focus();
    }
}

function showFullscreenQuicktimeObject(src)
{
    if (isQTInstalled())
    {
        sWidth = window.screen.availWidth;
        sHeight = window.screen.availHeight;
        var doc = window.open("/all/transitional/all/panoramaPopup/objectPopup.asp?qt=" + src, "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=0,top=0,dependent=yes,location=no,resizable=yes,scrollbars=no,status=no");			
        doc.focus();
    }
}
function showPanoramaPopup(pool, id, lang, panoramaversion, width, height, callpath)
{
    sWidth = window.screen.availWidth;
    sHeight = window.screen.availHeight;
    
    if(width && width > 0)
    {
        sWidth = width;		
    }
    
    if(height && height > 0)
    {
        sHeight = height;		
    }
    
    var url = "/panoramaPopup.aspx?Pool=" + pool + "&ID=" + id + "&Lang=" + lang + "&Panoramaversion=" + panoramaversion;	
    if (callpath && callpath.length > 0)
    {
        url += "&callpath=" + callpath;
    }
    
    var doc = window.open(url , "newWin" + getRandomInt(10000), "width=" + sWidth + ",height=" + sHeight + ",left=0,top=0,dependent=yes,location=no,resizable=yes,scrollbars=no,status=no");			
    doc.focus();
}
function writePopupQuicktimeObject(src,width,height)
{
    if (isQTInstalled())
    {
        var s = '';								
    
        var sWidth = '100%';
        var sHeight = '100%';
    
        var divWidth = "100%";
        var divHeight = "87%";
        
        if (width && width > 0)
        {
            sWidth = width;
            divWidth = width;
        }
        
        if (height && height > 0)
        {			
            sHeight = height + 15;
            divHeight = height + 15;
            
            if ( viewportGetHeight() > (sHeight + 50) )
            {
              spacerHeight = (viewportGetHeight() - sHeight) * 0.43;					  
              s += '<div style="height: ' + spacerHeight + 'px; width:100%; font-size:1px;"></div>\n';
            }
            else
            {
              document.body.style.overflow = 'auto';
            }			
        }	
        
        s += '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="'+sWidth+'" height="'+sHeight+'" codebase="http://www.apple.com/qtactivex/qtplugin.cab" id="quicktimePlugin">';
        s += '	<param name="scale" value="tofit"><param name="controller" value="true"><param name="cache" value="false"><param name="bgcolor" value="#E9E9E9"><param name="volume" value="30"><param name="kioskmode" value="false"><param name="moviename" value="spincontrolled">';
        s += '	<param name="src" value="'+src+'">';
        s += '	<embed src="'+src+'" ';
        s += '		width="'+sWidth+'" ';
        s += '		height="'+sHeight+'" ';
        s += '		type="video/quicktime" ';
        s += '		controller="true"';
        s += '		cache="false" ';
        s += '		volume="30"';
        s += '		kioskmode="false"';
        s += '		scale="tofit" ';
        s += '		pluginspage="http://www.apple.com/quicktime/download/" ';
        s += '		bgcolor="#E9E9E9"';
        s += '		moviename="spincontrolled"';
        s += '		/>';
        s += '</object>';
        
        var elm = document.getElementById('panorama');	
        if(elm)
        {
            elm.style.width = divWidth;
            elm.style.height = divHeight;		
            elm.innerHTML = s;
        }			
        
    }
    else
    {
        document.getElementById('noPlugin').style.display = 'block';
        document.getElementById('claim').style.display = 'none';
    }	
}
function myreplace(text,from,to) 
{
    ti = text.indexOf(from);
    text = text.substring(0,ti)+to+text.substr(ti+from.length);

    return text;
} 
function writePopupFlashObject(src,width,height)
{	
    if (swfobject.hasFlashPlayerVersion("6"))
    {
        var sWidth = '100%';
        var sHeight = '100%';
        
        var divWidth = '100%';
        var divHeight = '87%';
        
        if (width && width > 0)
        {
            sWidth = width;
            divWidth = width;
        }
        
        if (height && height > 0)
        {
            sHeight = height;
            divHeight = height;
        }

        var elm = document.getElementById('panorama');	
        if(elm)
        {
            elm.style.width = divWidth;
            elm.style.height = divHeight;
        }	
            
        // show flash
        showFlash(src, 'panorama', sWidth, sHeight, 6, '#E9E9E9', 'loop=true,menu=true,quality=high,wmode=opaque', null)
        
    }
    else
    {
        document.getElementById('noPlugin').style.display = 'block';
        document.getElementById('claim').style.display = 'none';
    }	
}
// gehört zu jeder gescheiten JS-Bibliothek.
function trim(str)
{
    return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

/* Toggleable language selector */

function writeLanguageSelector(pool, codes, texts, urls, selectedCode, containerId, defaultText)
{
    if (document.addEventListener) 
    {
            document.addEventListener("DOMFocusIn", langSelectorCheckBlur, true);
    }
    document.onmousedown = langSelectorCheckBlur;
    listId = 'HomeLangSelect';
    var i;
    var selectedIndex = 0;
    
    for (i=0; i<codes.length; i++)
    {
        if (codes[i] == selectedCode) 
        {
            selectedIndex = i;
            break;
        }
    }
    var html = "";
    html += "<div class=\"langSelect\" onclick=\"toggleLr('" + listId + "')\">\n";
    html += "<div id='langSelectDiv'><div type=\"text\" class=\"langSelectCurrent\">" + (defaultText == undefined ? texts[selectedIndex] : defaultText)  + "</div>\n";
    html += "<div class=\"langSelectArrow\"></div></div>\n";
    html += "</div>\n";
    
    html += "<ul id=\"" + listId + "\" class=\"langSelectList\">\n";
    for (i=0; i< codes.length; i++)
    {
        html += "<li onmouseover=\"mOverLangList(this, '"+ pool + "');\" onmouseout=\"mOutLangList(this, '"+ pool + "');\"><a href=\"" + urls[i] + "\">" + texts[i] + "</a></li>\n";
    }
    html += "</ul>\n";
    
    var container = document.getElementById(containerId);
    container.innerHTML = html;
}

function mOverLangList(elm, pool)
{
    if (!elm) return;
    poolid = pool.toLowerCase();
    switch(poolid)
    {
        case 'pco':
            elm.style.backgroundColor = '#E9E9E9';
            break;
        default:
            elm.style.backgroundColor = '#E9E9E9';
            break;
    }
}


function mOutLangList(elm, pool)
{
    if (!elm) return;
    poolid = pool.toLowerCase();
    switch(poolid)
    {
        case 'pco':
            elm.style.backgroundColor = '#FFFFFF';
            break;
        default:
            elm.style.backgroundColor = '#FFFFFF';
            break;
    }
}

if (window.Node && Node.prototype && !Node.prototype.contains) 
{
    Node.prototype.contains = function (arg)
    {
        return !!(this.compareDocumentPosition(arg) & 16);
    };
}

function langSelectorCheckBlur(e)
{
    element = document.getElementById("langSelectDiv");	
    dropdownList = document.getElementById("HomeLangSelect");
    e = e || window.event;
    var target = e.target || e.srcElement || false;
    if (!target) {
        return;
    }

    if (target == element || element.contains(target) || target == dropdownList || dropdownList.contains(target)) 
    {		
    }
    else
    {
        hideLr("HomeLangSelect");
    }
    
}

function checkClassic(data)
{
    var now = new Date();
    var result = new Array();
    
    // wenn das Produktionsjahr länger als 10 Jahre zurückliegt, und im 11. Jahr schon August ist, dann kommt der wagen zu Classic
    for(i = 0; i < data.length; i++)
    {
        var diff = now.getFullYear() - data[i][3];
        if(diff > 10)
        {
            if(diff == 11 && now.getMonth() < 8) {}
            else result.push(data[i]);
        }
    }
    return result;	
}

/* Start dealer search */
function porscheCenterSearchHandleError(errCode, errorMessage, fallBackMessage) {
    preInitPorscheCenterSearch();
    var msg;
    if (errorMessage && trim(errorMessage) != '') {
        msg = errorMessage;
        log("INFO: Text \"" + errCode + "\" gefunden.");
    }
    else {
        msg = fallBackMessage; // fallback error message.
        log("FEHLER: Text \"" + errCode + "\" nicht gefunden! Falls zurück auf den generischen Text '" + escape(fallBackMessage) + "'");
    }
    $("<p class=\"error\"></p>").text(msg).appendTo("#porscheCenterSearchResults");    
}


function preInitPorscheCenterSearch() {

    setupFadeEffectsDealerSearch(true);
    
    // loading sequence;
    $("#porscheCenterSearchResults").addClass("loading");
    
    
}

function setupFadeEffectsDealerSearch(fadeIn) {
    var currentPool = getPoolName();
    var fadeFactor = (fadeIn ? 0.3 : 1.0);
    var fadeSpeed = 150;
    var elements;
    if (currentPool == 'usa') {
        elements = "a.homeHead";
    }
    else {
        elements = "a.homeHead, #p_searchSite *";
    }
    $(elements).fadeTo(fadeSpeed, fadeFactor);

    if (g_is_home || currentPool != 'usa') return;

    var fadeTo = 0.2;
    if (fadeIn == false) {
        fadeTo = 1.0;
    }

    if ($.browser.msie) {
//        $('#dealersearchShadow').siblings("*:not(.modelInfoLayer, .related_hidden, script, .introImage, #teasershadow)").animate({ 'opacity': fadeTo }, 'fast', 'linear');
        //        $('.content .introImage img, .content .introImage #introFlash').animate({ 'opacity': fadeTo }, 'fast', 'linear');
        $('#dealersearchShadow').siblings("*:not(.modelInfoLayer, .related_hidden, script, .introImage, #teasershadow)").animate({ 'opacity': fadeTo }, 'fast', 'linear', function() { if (!fadeIn) $(this).css('opacity',''); });
        $('.content .introImage img, .content .introImage #introFlash').animate({ 'opacity': fadeTo }, 'fast', 'linear', function() { if (!fadeIn) $(this).css('opacity', ''); });

        $('.tabContent2 > ul[class^="gallery"], ul.downloads a, .modelTeaser > li > a, .modelInform > li > a').animate({ 'opacity': fadeTo }, 'fast', 'linear', function() { if (!fadeIn) $(this).css('opacity', ''); });
    }
    else {
        $('#dealersearchShadow').siblings("*:not(.modelInfoLayer, .related_hidden, script, .introImage, #teasershadow)").fadeTo('fast', fadeTo);
        $('.content .introImage img, .content .introImage #introFlash').fadeTo('fast', fadeTo);
    }

    
}

// initDealerSearchbox helper function
function initPorscheCenterResultsDisplay(searchBlockId) {
    // hide introfacts elements
    $('.introFactsShade, .introFactsContent').hide();
    
    // cancel the "loading.." sequence.
    $('#porscheCenterSearchResults').removeClass('loading');

    // make site search almost transparent 
    // to draw the focus on the center search.
    $('#porscheCenterSearchResults').show();
    
    // setup region click sensing to close the layer when clicked "outside".
    handleClickOutside($("#" + searchBlockId), "PCSearchClickedOutsideEvents()", true);
    //$(".porscheCenterSearchBG").show();
}

function PCSearchClickedOutsideEvents() {
    // reset site search visibility
    setupFadeEffectsDealerSearch(false);
    // hide result container.
    $('#porscheCenterSearchResults').hide();
    // back to normal size
    $('#dealersearchShadow').removeClass('expanded');
    // if they are available, re-display intro-facts elements.
    $('.introFactsShade, .introFactsContent').show();

}

function handleClickOutside(obj, doEvent, bindOnce) {
    
    var elm;
    if (obj.length && obj.length > 0)
        elm = obj[0];
    else
        elm = obj;
  
    //
    // *******************************
    //  click management 
    // ******************************* 
    //
    $(document).click(function(e) { // when anywhere in the doc is clicked
        var clickedOutside = true; // start searching assuming we clicked outside
        $(e.target).parents().andSelf().each(function() { // search parents and self
            // if the original element selector is the click's target or a parent of the target
            // we have not clicked outside the box
            if (this == elm) {
                clickedOutside = false; // found
                log("ClickedOutside = false. Returning..")
                return false; // stop searching
            }
        });
        if (clickedOutside) {
            log("ClickedOutside = true. executing " + doEvent);
            eval(doEvent);
            //$(elm).fadeOut("fast");
            if (bindOnce) {
                // unbind this listener, we're done with it
                $(document).unbind('click', arguments.callee);
            }
        }
    });
}

//function setupDealerSearchFormSubmitEvent(searchBlockId, baseURL) {
//    if (getPoolName() == 'usa') return;
//    // bind form submit event
//    $("#porscheCenterSearchForm").submit(function() {
//        log("Porsche Center search form submitted");
//        var searchKeywords = $("#" + searchBlockId + " .searchfield").val();
//        log("searching for: " + searchKeywords);
//        openDealerLocator(null, 980, 725, 'dealer', baseURL + "?geoip=true&searchKey=" + encodeURIComponent(searchKeywords));
//        PCSearchClickedOutsideEvents();
//        return false;
//    });
//}

function getPoolLangUrl(pool, lang) {
    return (lang != 'none') ? pool + '/' + lang : pool;
}



// dealer search box on the homepage
function initDealerSearch() {
    var self = this;
    this.pool = getPoolName();
    this.lang = getPoolLang(this.pool);

    var validPools = ['uk', 'usa', 'canada', 'australia']
    /**** 
    2010-12-13 BU: Porsche Center search only for PCNA and PCGB
    ****/
    if (!ArrayContainsItem(validPools, this.pool)) {
        return;
    }

    this.hasFlash = (typeof(swfobject)!='undefined' && swfobject.hasFlashPlayerVersion("10"));
    this.timeOutHandler = null;
    this.inputDelay = 500;
    this.maxInputLength = (this.pool == "canada" ? 7 : 5);
    var resultCount = 2; // how many results maximum.
    var baseURL = "/all/dealer2/" + getPoolLangUrl(this.pool, this.lang) + "/";

    // Setup Dealer Vicinity Search
    var searchBlockId = "dealersearch";
    this.inventoryLocator = null;

    if (this.pool != "usa" && this.pool != "canada") {
        // bind form submit event
        $("#porscheCenterSearchForm").submit(function() {
            log("Porsche Center search form submitted");
            var searchKeywords = $(".zipcode", this).val();
            log("searching for: " + searchKeywords);
            openDealerLocator(null, 980, 725, 'dealer', baseURL + "?geoip=true&searchKey=" + encodeURIComponent(searchKeywords));
            PCSearchClickedOutsideEvents();
            return false;
        });

    }


    this.inventoryLocatorPCNA = function (_container, _pool, _lang) {
        var self = this;
        this.container = _container;  //$('#' + _container);

        this.models = '';

        this.pool = _pool;
        this.lang = _lang;

        this.setModelRange = function () {
            var url = window.location.pathname;
            var modelRanges = ['911', 'boxster', 'cayman', 'cayenne', 'panamera'];
            var mr;
            for (mr in modelRanges) {
                //log("modelRanges[mr]: " + modelRanges[mr]);
                var re = new RegExp("^\/usa\/models\/" + modelRanges[mr] + "\/", "ig");
                if (re.test(url)) {
                    this.models = modelRanges[mr];
                    //log("mr: " + modelRanges[mr]);
                    return;
                }
            }
        }

        this.setModelRange();

        this.debugMode = window.location.hostname == "www.porsche.com" ? 0 : 1; // set to 0 when live
        this.url = getFlashUrl(this.pool);


        function getFlashUrl(pool) {
            //var url = "http://www.porschedealer.com/inventory/InventoryBannerHome.swf";
            //var url = "http://pd.gstockco.com/inventory/HInventoryBannerUSA.swf";
            var url = "/all/media/flash/inventorylocator/HInventoryBannerUSA.swf";
            if (pool == 'canada')
            //url = "http://www.porschedealer.com/inventory/InventoryBannerCanada.swf";
                url = "/all/media/flash/inventorylocator/HInventoryBannerCanada.swf";
            return url;
        }


        this.preInitFlash = function () {
            log("entering preInitFlash()");
            if ($("#" + this.container).length == 0) {
                // layout setup
                $("<div id=\"" + this.container + "\"></div>").append().appendTo("#" + searchBlockId);
            }

        }

        this.postInitFlash = function () {
        }

        this.campaignId = (self.pool == "usa" ? 7 : 9); // USA:7, Canada:9


        this.initFlash = function (zip) {
            // set background with larger box shadow
            log('expanding results container');
            $('#' + searchBlockId).parent().addClass('expanded');


            $('#' + this.container).html('<div id="' + this.container + '_flash"></div>');

            // title
            //var title = "<h5>" + $("input[name='vehiclesNearYou']").val() + "</h5>";
            var title = '<h5><img src="/usa/ImageMachines/LinkBlockTitle.ashx/rendered.gif?text=' + encodeURIComponent($("input[name='vehiclesNearYou']").val()) + '" alt="" /></h5>';
            //title += '<div class="separator"></div>';
            $(title).prependTo("#porscheCenterSearchResults");

            this.zipCode = zip;
            log("zipcode: " + this.zipCode);

            if (!swfobject) {
                log("!!! swfobject not loaded !!!");
                return false;
            }


            var flash = {
                url: this.url,
                width: 575,
                height: 135,
                minver: '10',
                vars: {
                    campaign_id: this.campaignId,
                    debug_mode: this.debugMode,
                    zipcode: this.zipCode,
                    postal_code: this.zipCode,
                    lang: this.lang,
                    models: this.models
                },
                params: {
                    bgcolor: '#FFF',
                    wmode: 'transparent'
                },
                attrs: {
                    id: this.container + '_flash',
                    name: this.container + '_flash',
                    background: 'transparent'
                }
            }

            // insert flash object
            swfobject.embedSWF(flash.url, this.container + "_flash", flash.width, flash.height, flash.minver, false, flash.vars, flash.params, flash.attrs);

            this.postInitFlash();
            return true;
        }


    }



    this.doDealerSearch = function () {
        var searchResultContainer = $("#porscheCenterSearchResults");

        if (searchResultContainer.length == 0) {
            //log("First time call. setting up searchResultContainer");
            // layout setup
            $("<div id=\"porscheCenterSearchResults\"><ul></ul></div>").appendTo("#" + searchBlockId);

            // title
            var title = "<h5>" + $("input[name='porscheCentersNearYou']").val() + "</h5>";
            $("<p></p>").html(title).prependTo("#porscheCenterSearchResults");

            preInitPorscheCenterSearch();

            //load and display results
            //var searchUrl = "/all/dealer2/search.aspx?siteid=" + self.pool + "&market=" + self.pool + "&language=" + self.lang + "&mode=nearestbyip&locationtype=centre&maxresults=" + resultCount;
            var searchUrl = "/all/dealer2/GetLocationsWebService.asmx/GetLocations?market=" + self.pool + "&siteId=" + self.pool + "&language=" + self.lang + "&_locationType=Search.LocationTypes.DealerNoServiceCentre&searchMode=nearestbyip&searchKey=" + resultCount;
            var dealerXPath = 'Location';

            $("body").css("cursor", "progress");
            $.ajax({
                url: searchUrl,
                dataType: "xml",
                success: function (data) {
                    // process resulting html here
                    var dealersFound = false;
                    $(data).find(dealerXPath).each(function () {
                        // raise flag "at least one dealer found!"
                        if (!dealersFound) dealersFound = true;
                        // Porsche center URL (Google Porsche Center Search)
                        var winOptions;
                        var pcUrl = '';

                        //pcUrl = "/all/dealer2/" + getPoolLangUrl(self.pool, self.lang) + "/location.aspx?locationId=" + $(this).attr("nr") + "&locationtype=centre";
                        pcUrl = "/all/dealer2/" + getPoolLangUrl(self.pool, self.lang) + "/location.aspx?locationId=" + $(this).find('Id').text();
                        winOptions = false;

                        // build Porsche center link
                        var link = $("<a href=\"" + pcUrl + "\" class=\"porscheCenterLink\">" + $(this).find('Name').text() + "</a>");

                        // wrap link in <li> and append the whole thing to the <ul>.
                        $("<li></li>")
                        .hover(function () { $(this).addClass('focused'); }, function () { $(this).removeClass('focused'); })
                        .append(link).appendTo('#porscheCenterSearchResults ul');
                        // setup porsche center link click function.
                        $(link).click(function () {
                            /* Porsche center link Click events */
                            try {
                                click_track('Klick-Startseite/Search/Dealer');
                            }
                            catch (e) {
                                log("ERROR: WIREDMINDS tracking failed.");
                            }

                            openDealerLocator(null, 980, 725, 'dealer', pcUrl, winOptions);
                            return false; // we don't want to open the link in the current window.
                        });
                    }); //.each
                    if (!dealersFound) {
                        // We could not find any dealers,
                        // display an appropriate message
                        //log("No centers found");
                        porscheCenterSearchHandleError('noCentersFound', $("input[name='noCentersFound']").val(), "NO PORSCHE CENTERS FOUND.");
                    }
                    else {
                        $(".porscheCenterSearchBG").css("height", "60px"); /* STV: Hompage IE 7 */
                    }
                }, //success: function(data)
                error: function (request, error) {
                    log("HTTP-FEHLER: Typ '" + error + "'");

                    porscheCenterSearchHandleError('errorInProcess', $("input[name='errorInProcess']").val(), "HTTP-ERROR.");
                },
                complete: function () {
                    $("body").css("cursor", "default");
                    preInitPorscheCenterSearch();
                    initPorscheCenterResultsDisplay(searchBlockId);
                }
            }); // $.ajax

        }
        else {
            //log("Search container exists");
            preInitPorscheCenterSearch();
            initPorscheCenterResultsDisplay(searchBlockId);
        }
    }




    if (self.pool == "usa" || self.pool == "canada") {
        // setup input box for the inventory locator

        // only if it has Flash we are restricting the input
        $("#porscheCenterSearchForm .zipcode").attr({
            'maxlength': self.maxInputLength,
            'autocomplete': 'off'
        });

        //log("self.maxLength: " + self.maxInputLength);

        $("#porscheCenterSearchForm .zipcode")
        .focus(function () {
            $(this).addClass('focused');

            if (self.pool == "usa" && this.value.length == 5) {
                $('#' + searchBlockId).parent().addClass('expanded');
            }
            // empty default value
            if (this.value == this.defaultValue) this.value = "";

            if (self.hasFlash) {
                // make site search almost transparent 
                // to draw the focus on the center search.
                setupFadeEffectsDealerSearch(true);

                // hide introfacts elements
                $('.introFactsShade, .introFactsContent').hide();
                // show results container
                
                $('#porscheCenterSearchResults').show();
                
                // setup region click sensing to close the layer when clicked "outside".
                handleClickOutside($("#" + searchBlockId), "PCSearchClickedOutsideEvents()", true);
            }
            else {
                self.doDealerSearch();
            }
        })
        .blur(function () {
            // reset default value if lost focus
            $(this).removeClass('focused');
            if (!this.value.length) {
                this.value = this.defaultValue;
            }
        })
        .keydown(function (e) {
            //log("keyDown");

            var c = e.keyCode;
            //log("keycode: " + c);
            if ((c >= 48 && c <= 57) || c == 8 || c == 27 || c == 13 || c == 46 || (c >= 35 && c <= 40) || (c >= 96 && c <= 105)) {
                //log("keydown allowed");
            }
            else {
                if (self.pool == "usa")
                    e.preventDefault();
            }
        })
        .keyup(function (e) {
            // handle content change of the input box.
            // if and only if the length is exactly 5 characters,
            // fire the search.
            // cancel the "loading.." sequence.
            // Escape key also cancels the box.

            // handle ESC key.
            if (e.keyCode == 27) {
                $(this).blur();
                PCSearchClickedOutsideEvents();
                e.preventDefault();
            }

            if (!self.hasFlash) return;

            var inputVal = this.value;

            if (self.inventoryLocator == null) {
                self.inventoryLocator = new self.inventoryLocatorPCNA('porscheCenterSearchResults', self.pool, self.lang);
                self.inventoryLocator.preInitFlash();
            }

            if (!$('#' + self.inventoryLocator.container).hasClass('loading')) {
                $('#' + self.inventoryLocator.container).empty();
                $('#' + self.inventoryLocator.container).addClass('loading');
            }
            inputVal = trim(inputVal);

            var len = inputVal.length;
            //log("length: " + len);
            if (self.pool == 'canada') {
                var regexCanada = inputVal.match(/^[a-zA-Z]\d[a-zA-Z][\s\-]?\d[a-zA-Z]\d$/);
                if (!regexCanada) return;
                if (!inputVal.match(/[\s\-]/)) {
                    //log("no space or dash, inserting one");
                    inputVal = trim(inputVal).substr(0, 3) + " " + trim(inputVal).substring(3);
                }

                //log("inputVal korrigiert: " + inputVal);
            }
            else {
                if (len < self.maxInputLength) return;
            }

            window.clearTimeout(self.timeOutHandler);
            self.timeOutHandler = window.setTimeout(
                function () {
                    //log("run inventory locator");
                    $('#' + self.inventoryLocator.container).removeClass('loading');
                    self.inventoryLocator.initFlash(trim(inputVal));
                }, self.inputDelay);

        });

    }
    else {
        /**
        ***  Setup for ROTW
        **/
        $("#porscheCenterSearchForm .zipcode")
        .focus(function() {
            $(this).addClass('focused');
            // empty default value
            if (this.value == this.defaultValue) this.value = "";
            self.doDealerSearch();
        })
        .blur(function() {
            // reset default value if lost focus
            $(this).removeClass('focused');
            if (!this.value.length) {
                this.value = this.defaultValue;
            }
        })
        .keyup(function(e) {
            // handle content change of the input box.
            // if and only if the length is exactly 5 characters,
            // fire the search.
            // cancel the "loading.." sequence.
            // Escape key also cancels the box.

            // handle ESC key.
            if (e.keyCode == 27) {
                $(this).blur();
                PCSearchClickedOutsideEvents();
                e.preventDefault();
            }
        })
        ;


    }
    
    


    return false;
}


// Quicktime detection script
function isQTInstalled() {
    var qtInstalled = false;
    qtObj = false;
    if (navigator.plugins && navigator.plugins.length) {
        for (var i = 0; i < navigator.plugins.length; i++) {
            var plugin = navigator.plugins[i];
            if (plugin.name.indexOf("QuickTime") > -1) {
                qtInstalled = true;
            }
        }
    } else {
        execScript('on error resume next: qtObj = IsObject(CreateObject("QuickTimeCheckObject.QuickTimeCheck.1"))', 'VBScript');
        qtInstalled = qtObj;
    }
    return qtInstalled;
}


// Console logging for firebug.
// keep it silent on other browsers.
function log(str) {
    try {
        console.log(str);
    }
    catch (e) {
    }
}
// Class Hashtable
function Hashtable() {
    this.length = 0;
    this.items = new Array();
    for (var i = 0; i < arguments.length; i += 2) {
        if (typeof (arguments[i + 1]) != 'undefined') {
            this.items[arguments[i]] = arguments[i + 1];
            this.length++;
        }
    }

    this.removeItem = function(in_key) {
        var tmp_value;
        if (typeof (this.items[in_key]) != 'undefined') {
            this.length--;
            tmp_value = this.items[in_key];
            delete this.items[in_key];
        }

        return tmp_value;
    }

    this.getItem = function(in_key) {
        return this.items[in_key];
    }

    this.setItem = function(in_key, in_value) {
        if (typeof (in_value) != 'undefined') {
            if (typeof (this.items[in_key]) == 'undefined') {
                this.length++;
            }

            this.items[in_key] = in_value;
        }

        return in_value;
    }

    this.hasItem = function(in_key) {
        return typeof (this.items[in_key]) != 'undefined';
    }
}
// Ziel URL für button.swf
function getButtonTarget() {
    return buttonTarget;
}

function getCachePrevent() {
    return "rand=" + escape(Math.round(Math.random() * 10000));
}

function conditionLinkFix(ids) {
    var conditionMatched = window.location.href.match(/_.+_/ig);
    var elmIds = ids.split(/[\s,;]+/);
    $.each(elmIds, function() {
        if (!conditionMatched) $("#" + this).css({ 'left': '-10000px', 'visibility': 'hidden' });
    });
}

/* ** 200803.js ********************************************************************************** */
/* Style Variablen für Hauptnavi überschreiben */
g_homemenu_hl_fontcolor = "#CC0000"; //"rgb(204, 0, 0)";
g_homemenu_hl_background_color = "transparent";
g_homemenu_hl_background_color_Level5 = "#FFFFFF";
g_homemenu_ll_fontcolor_level0 = "#ffffff";
g_homemenu_ll_fontcolor_level1 = "#000000";
g_homemenu_ll_background_color = "#eef2f5";

//g_homemenu_ll_background_image_level0 = "url(/images/arrow-black.gif)";
//g_homemenu_ll_background_image_level1 = "url(/images/arrow-black.gif)";
g_homemenu_ll_background_position_level0 = "210px -592px";
g_homemenu_ll_background_position_level1 = "210px -592px";

var g_homemenu_hl_background_position_level1 = "0 -50px";

 
    g_homemenu_ll_background_color = '#f9f9f9';
    g_homemenu_ll_background_position_level0 = "0 -0px";
    g_homemenu_ll_background_position_level1 = "0 -0px";
    g_homemenu_hl_fontcolor = '#fff';    


g_jdpowerphase = "200803";

/* Hauptmenü: Anzahl der Menüeinträge in Subnavi erhöhen */
G_MAXSUBLAYERS = 30;


// 15.04.2010 miki: JS 4 Sharebar
// JScript source code
function sharethis(href, encoding) {
    var link;
    if (encoding == null)
        link = href.replace('URL', encodeURIComponent(document.location.toString()));
    else
        link = href.replace('URL', document.location.toString());

    link = link.replace('TITEL', document.title);

    window.open(link, 'share');
}
function addToFavorites() {

    var url = document.location.toString();
    var title = document.title;


    if (document.all)
        window.external.AddFavorite(url, title);
    else if (window.sidebar) // firefox
        window.sidebar.addPanel(title, url, "");
}

jQuery(document).ready(function () {
    jQuery(".sharelayer").hide();
    jQuery(".followlayer").hide();

    jQuery(".sharing").hover(
    function () {
        jQuery(".sharelayer,.followlayer").fadeIn(100);

    },
    function () {
        jQuery(".sharelayer,.followlayer").fadeOut(100);
    }
    );

});



/*END DEALER SEARCH */
// Wiredminds tracking
function click_track_hp(value) {
    // trackt einen Besucher Klick nur auf der Homepage
     if (g_is_home) {
         click_track(value);
    }
}

//function click_track(value) {
//    // trackt einen Besucher Klick
//   // if (g_is_home) {   // wm_cd1= value;
//        try {
//            wiredminds.count(value);
//        }
//        catch (e) {
//            log("wiredminds tracking gescheitert! Value: " + value);
//        }
//   // }
//}

function click_trackevent(value) {
    // trackt einen Besucher Event Klick
        try {
            wiredminds.event(value);
        }
        catch (e) {
            log("wiredminds event tracking gescheitert! Value: " + value);
        }  
}

/*******************************************************************************************************************************/

///* START: JQuery */
//$(document).ready(function() {
//    initAll2();
//});

function initAll2() {
    $("#navigation-sitemap-link").mouseover(function() { showSitemap(); });
    //$("#navigation-modelrangeoverview-link").mouseover(function() { showModels(); })
    $("#navigation-modelrangeoverview-link, #navigation-wappen, #navigation-sub, #navigation-bluebox, #footer, #content").mouseover(function() { showContent(); });
    $("#metamyporsche, #metalogin, #metasitesearch, #metadealersearch").mouseover(function() { activeMetaDrop(this); });

    checkLoginError();
    initInfoLayerClueTip();
    
}

var g_destroyOldTeaserBar = false;
function setupTeaserbar() {
    if ($('ul.teaserBar').length > 0) {
        if (g_destroyOldTeaserBar) {
            $('#teaserbarNavLeft,#teaserbarNavRight,#teaserBarWrapper').remove();
            //$('.innerContent').append('<a class="prevPage browse left disabled" id="teaserbarNavLeft" /><div id="teaserBarWrapper" /><a class="nextPage browse right" id="teaserbarNavRight" />');
            $('.innerContent').append('<div id="teaserBarBackground" class="dropShadow"><a class="prevPage browse left disabled" id="teaserbarNavLeft" /><div id="teaserBarWrapper"></div><a class="nextPage browse right" id="teaserbarNavRight" /></div>');
        }

        $('ul.teaserBar').addClass('items').appendTo('#teaserBarWrapper').show();
        $('#teaserBarWrapper').addClass('scrollable').scrollable({ "clickable": false, "size": (g_maxShowScrollingItems), "speed": 300 }); //$("#clone").scrollable({ "clickable": true, "size": (4), api: true });
        var api = $("#teaserBarWrapper").data("scrollable");
        if (api.getSize() <= g_maxShowScrollingItems) {
            log("less items scrolling disabled");
            $('#teaserbarNavRight').addClass("disabled");
        }

        $('#teaserbarNavLeft').click(function () {
            click_track('Klick-Startseite/Teaser/Previous Teaser');
        });
        $('#teaserbarNavRight').click(function () {
            click_track('Klick-Startseite/Teaser/Next Teaser');
        });
    }
}

/* For compatibility with the older version */
function moveTeaserbar() {
    g_destroyOldTeaserBar = true;
}

function showContent() {
    $("#navigation-sitemap, #navigation-sitemap-shadow, #navigation-modelrangeoverview, #navigation-modelrangeoverview-shadow").hide();
    $("#navigation-modelrangeoverview-link, #navigation-sitemap-link, #navigation-sub, #navigation-bluebox, #menu1, #footer").removeClass("fadeout"); //.css("opacity", "1.0");
    $("#metamyporschecontainer, #metalogincontainer, #metasitesearchcontainer, #metadealersearchcontainer").hide();
    $("#metamyporsche, #metalogin, #metasitesearch, #metadealersearch").parent().removeClass("active");
    $("#metamyporsche, #metalogin").parent().removeClass("activeborderleft");
    $("#metadealersearch").removeClass("activeborderright");
    if (g_is_ie6) {
        ieToggleDropDowns(getListIEDropDowns(), false);
    }
}
function hideContent(element) {
    //$("#navigation-sub, #navigation-bluebox, #footer, #menu1" + element).addClass("fadeout"); 
}
function showSitemap() {
    $("#navigation-sitemap-link").removeClass("fadeout");
    $("#navigation-modelrangeoverview, #navigation-modelrangeoverview-shadow").hide();
    hideContent(", #navigation-modelrangeoverview-link");
    var height = 0 + $("#navigation-sitemap").height();
    height = height + 32 // padding top + bottom;
    //$("#navigation-sitemap-shadow").height(height);
    $("#navigation-sitemap-shadow, #navigation-sitemap").show();
    //$("#navigation-sitemap").show();
}
function showModels() {
    // wenn "Modelle" = aktiver Menüpunkt, dann nicht das Flyout-Script ausführen
    if (!$("#navigation-modelrangeoverview-link").hasClass("active")) {
        $("#navigation-modelrangeoverview-link").removeClass("fadeout");
        $("#navigation-sitemap, #navigation-sitemap-shadow").hide();
        hideContent(", #navigation-sitemap-link");
        var height = 0 + $("#navigation-modelrangeoverview").height();
        height = height + 32 // padding;
        //        $("#navigation-modelrangeoverview-shadow").height(height);
        $("#navigation-modelrangeoverview-shadow").show();
        $("#navigation-modelrangeoverview, #navigation-modelrangeoverview-shadow").show();
    }
    else {
        showContent();
    }
}

function activeMetaDrop(element) {

    //drops ausblenden
    //$("#metamyporschecontainer, #metalogincontainer, #metasitesearchcontainer, #metadealersearchcontainer").hide();
    $('#metadrops .metacontainer').hide();
    $("#metamyporsche, #metalogin, #metasitesearch, #metadealersearch").parent().removeClass("active");
    $("#metamyporsche, #metalogin").parent().removeClass("activeborderleft");
    $("#metadealersearch").removeClass("activeborderright");

    if (g_is_ie6) {
        if (element.id == 'metalogin' || element.id == 'metadealersearch')
            ieToggleDropDowns(getListIEDropDowns(), true);
        else
            ieToggleDropDowns(getListIEDropDowns(), false);
    }

    // wenn element an erster Stelle steht wird ein Border eingeblendet
    if ($(element).hasClass("metafirst")) {
        $(element).parent().addClass("activeborderleft");
    }
    //wenn es dealersearch ist 
    if ($(element).hasClass("metadealersearch")) {
        $(element).addClass("activeborderright");
    }

    $(element).parent().addClass("active");

    var container = element.id + "container";
    $("#" + container).show();

}

function checkLoginError() {
    var errorcode = getUrlParamValue('error');
    if (errorcode == 1 || errorcode == 2) {
        $("#metalogincontent").addClass("errorCon");
        $("#metaloginshadow").addClass("errorSha");
        $("#metalogincontainer").show();
        $("#metalogin").addClass("activeborderleft");

        if (errorcode == 1)
            $("#metaloginerror1").show();
        if (errorcode == 2)
            $("#metaloginerror2").show();
    }
}

var g_clueTip_ModelLayer_TimeoutId = null;
var g_clueTip_ModelLayer_TimeoutMillisec = 1000;

function initInfoLayerClueTip() {
    if ($('a.modelLink').length == 0) {
        return;
    }
    var footnotes = ($('#content p.footnote, .page .footnote-container p.footnote').length > 0);
    var footnotecontent = false;
    if (footnotes == true) {
        $('#content p.footnote, innerContent, .page .footnote-container p.footnote').each(function () {
            var text = $.trim($(this).html());
            if ((text != '') && (text != '&nbsp;') && (text != '&#160;')) {
                footnotecontent = true;
            }
        });
    }

    var cluetipWidth = (footnotes && footnotecontent) ? 750 : 450;
    $('a.modelLink').cluetip({
                                width: cluetipWidth
                              , height: 'auto' //SELECT_INFOLAYER_HEIGHT
                              , positionBy: 'mouse' // can be  'auto', 'mouse', 'bottomTop', 'fixed'
                              , fx: {
                                  open: 'fadeIn', // can be 'show' or 'slideDown' or 'fadeIn'
                                  openSpeed: 'fast'
                              }
                              , local: true
                              , cursor: 'pointer'
                              , showTitle: false
                              , dropShadow: false
                              , topOffset: 20
                              , leftOffset: 10
                              , sticky: true
                              , mouseOutClose: true
                              //, onShow: copyDisclaimer
                              , onShow: initTP
                              , onClose: clueTipModelLayerClearTimeout

                              , hoverIntent: {
                                  sensitivity: 7
                                  , interval: 75
                              }
                              , closeText: ''
    });

    //                          $('#cluetip').hover(
    //                            function() {
    //                                log("ct mouseover");
    //                            }, 
    //                            function() {
    //                                log("ct mouseout");
    //                                $(this).hide();
    //                            }
    //                          );
    //

    //$('#cluetip').mouseover(clueTipModelLayerClearTimeout);
    $('#cluetip').bind('mouseenter', clueTipModelLayerClearTimeout);
    $('a.modelLink, a.modelLink img').mouseout(clueTipModelLayerSetTimeout);
    $('a.modelLink, a.modelLink img').bind('mouseenter', clueTipModelLayerClearTimeout);
    //                          $('a.modelLink, a.modelLink img, a.modelLink span').mouseout(clueTipModelLayerSetTimeout);
    //                          $('a.modelLink img, a.modelLink span').bind('mouseenter', function() { $('#cluetip').show(); });
    //                          $('a.modelLink, a.modelLink img, a.modelLink span').bind('mouseenter', clueTipModelLayerClearTimeout);
}
function initTP()
{
    clueTipModelLayerClearTimeout();
    copyDisclaimer();
}
function copyDisclaimer() {
    var footnotes = ($('#content p.footnote, .page .footnote-container p.footnote').length > 0);
    var footnotecontent = false;
    if (footnotes == true) {
        $('#content p.footnote, .page .footnote-container p.footnote').each(function () {
            var text = $.trim($(this).html());
            if ((text != '') && (text != '&nbsp;') && (text != '&#160;')) {
                footnotecontent = true;
            }
        });
    }

    if (footnotes && footnotecontent) {
        $('#cluetip').addClass('wideTT');
        $('#cluetip-inner .modeldisclaimer').append($('#content p.footnote, .page .footnote-container p.footnote').clone());
        $('#cluetip-inner .modeldisclaimer').css({ 'display': 'block' });
    }
    else {
        $('#cluetip').addClass('narrowTT');
    }
}

function clueTipModelLayerSetTimeout() {
    clueTipModelLayerClearTimeout();
    g_clueTip_ModelLayer_TimeoutId = window.setTimeout("$('#cluetip').hide()", g_clueTip_ModelLayer_TimeoutMillisec);
    //log("cluetip timeout set to " + g_clueTip_ModelLayer_TimeoutMillisec);
}
function clueTipModelLayerClearTimeout() {
    window.clearTimeout(g_clueTip_ModelLayer_TimeoutId);
    //log("cluetip timeout cleared!");
}

/* END: JQuery */


function switchFooter() {
    var elem = document.getElementById("ifLoggedOut");
    var elem2 = document.getElementById("ifLoggedIn");

    if (elem && elem2) {
        elem.style.display = (elem.style.display == 'inline' || elem.style.display == '') ? 'none' : 'inline';
        elem2.style.display = (elem.style.display == 'inline') ? 'none' : 'inline';
    }
    //wechsel Loginstatus in der meta Navi
    var elem3 = document.getElementById("ifmetaLoggedOut");
    var elem4 = document.getElementById("ifmetaLoggedIn");

    if (elem3 && elem4) {
        elem3.style.display = (elem3.style.display == 'inline' || elem3.style.display == '') ? 'none' : 'inline';
        elem4.style.display = (elem3.style.display == 'inline') ? 'none' : 'inline';
    }
}
/* ModelFilter */
function filter() {
    var val1 = (document.getElementById("modeltype")            == null) ? '' : document.getElementById("modeltype").value;
    var val2 = (document.getElementById("modeldrivetrain")      == null) ? '' : document.getElementById("modeldrivetrain").value;
    var val3 = (document.getElementById("modelprice")           == null) ? '' : document.getElementById("modelprice").value;
    var val4 = (document.getElementById("modelpower")           == null) ? '' : document.getElementById("modelpower").value;
    var val5 = (document.getElementById("modelfuelconsumption") == null) ? '' : document.getElementById("modelfuelconsumption").value;

    for (var i in tmpHashtable.items) {
        var element = document.getElementById(i);
        if (!element)
            continue;
        var code = tmpHashtable.items[i];
        i = "#" + i;
        if (!$(i).hasClass("fadeout"))
            $(i).addClass("fadeout");

        var c1 = code.slice(0, 1); var c2 = code.slice(1, 2); var c3 = code.slice(2, 3); var c4 = code.slice(3, 4); ; var c5 = code.slice(4, 5);
        var w1 = val1; var w2 = val2; var w3 = val3; var w4 = val4; var w5 = val5;

        if (val1 == '' || val1 == 0) w1 = c1;
        if (val2 == '' || val2 == 0) w2 = c2;
        if (val3 == '' || val3 == 0) w3 = c3;
        if (val4 == '' || val4 == 0) w4 = c4;
        if (val5 == '' || val5 == 0) w5 = c5;

        if (w1 == c1 && w2 == c2 && w3 == c3 && w4 == c4 && (w5 == c5 || c5 == 9)) {
            $(i).removeClass("fadeout");
        }
    }
}
function filterreset() {
    if (document.getElementById("modeltype") != null) {
        document.getElementById("modeltype").selectedIndex = 0;
    }
    if (document.getElementById("modeldrivetrain") != null) {
        document.getElementById("modeldrivetrain").selectedIndex = 0;
    }
    if (document.getElementById("modelprice") != null) {
        document.getElementById("modelprice").selectedIndex =  0;
    }
    if (document.getElementById("modelpower") != null) {
        document.getElementById("modelpower").selectedIndex = 0;
    }
    if (document.getElementById("modelfuelconsumption") != null) {
        document.getElementById("modelfuelconsumption").selectedIndex = 0;
    }
    if (document.getElementById("modelrange") != null) {
        document.getElementById("modelrange").selectedIndex = 0;
        changemodel('');
    }
}


/* START DEALER SEARCH */



/* END DEALER SEARCH */

//Parameter aus Url auslesen |erwartet parametername|liefert wert des Parameters
function getUrlParamValue(parametername) {
    parametername = parametername.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

    var regexpQ = "[\\?&]" + parametername + "=([^&#]*)";
    var regexp = new RegExp(regexpQ);
    var paramValue = regexp.exec(window.location.href);

    if (paramValue == null)
        return "";
    else
        return paramValue[1];
}


/* image gallery */
var WIDTH = 1162; //height preview image
var HEIGHT = 600; //height preview image
var M_WIDTH = 11; //min height preview image
var M_HEIGHT = 6; //min height preview image
var Z_WIDTH = 3000; //height zoomed image
var Z_HEIGHT = 1560; //height zoomed image
var Z_BTN_MARGINLEFT = "-75px";
var scrollerInit = false;
var scrollerItemsDone = false;

function scaleImage() {
    var oWidth = WIDTH;
    var oHeight = HEIGHT;
    var containerHeight = $(window).height() - 120 - 23; /* 137 */ // -> IE6 = 0px: $("#imageZoom").height();
    containerHeight = (containerHeight < M_HEIGHT) ? M_HEIGHT : containerHeight;
    $("#imageZoom").css("width", $(window).width());
    $("#imageZoom, #imageZoom .nav").css("height", containerHeight);
    var newWidth = oWidth * (containerHeight / oHeight) + 1.00;
    newWidth = (newWidth < M_WIDTH) ? M_WIDTH : newWidth;
    var newWidthStr = parseInt(newWidth.toString()) + "px";
    var marginInt = - parseInt((newWidth / 2).toString());
    var marginStr = "-" + parseInt((newWidth / 2).toString()) + "px";
    var windowWidth = $(window).width();
    var marginStrBtn = "-" + parseInt(((newWidth / 2)).toString()) + "px";
    var leftStrBtn = "50%";
    if (newWidth > windowWidth) {
        marginStrBtn = '0px';
        leftStrBtn = "0px";
    }
    if ($("#previewImage").attr("src").indexOf('filetype=normal') > -1) {
        $("#previewImage").css({ "width": newWidthStr, "height": containerHeight + "px" });
        $("#previewImage").css({ position: "absolute", "left": "50%", "margin-left": marginStr });
        var imgPos = $("#previewImage").position() ;
        log(imgPos);
        var nav1Left = imgPos.left + marginInt < 0 ? 0 : imgPos.left + marginInt;
        
        var winWidth = $(window).width();
        var navWidth = $('.nav').eq(0).width();
        var arrowHeight = $('.nav .arrow').eq(0).height() == 0 ? 100 : $('.nav .arrow').eq(0).height();
        log("containerHeight: " + containerHeight);
        log("arrowHeight: " + arrowHeight);

        var imgPosRightEdge = imgPos.left + marginInt + newWidth;
        var nav2Left = newWidth >= winWidth ? winWidth - navWidth : imgPosRightEdge - navWidth;
        
        $(' #imageZoom .navleft').css('left', nav1Left.toString() + 'px');
        $(' #imageZoom .navright').css('left', nav2Left.toString() + 'px');
        $('#imageZoom .nav .arrow').css('top', (containerHeight - arrowHeight)/2);
        if (CURRENTPOOL == 'usa') {
            $("#zoomBtn").css({ "left": "50%", "margin-left": '-75px' });
        }
        else
            $("#zoomBtn").css({ "left": leftStrBtn, "margin-left": marginStrBtn });
    }
}

function copyItems() {
    if (scrollerItemsDone == false) {
        scrollerItemsDone = true;
        $(".tabContent2 ul li").each(function() {
            var listItem = jQuery(this);
            if (listItem.children("h3").length == 0) {
                listItem.clone().appendTo($("#triggers")).children().attr("href", "#");
            }
        });
        $("#triggers li a").each(function () {
            jQuery(this).click(function () {
                var REL = jQuery(this).attr("rel");
                var TITLE = jQuery(this).children().eq(0).attr('title');
                TITLE = (TITLE == '[+]') ? '' : TITLE;
                $('#imagetitle').html(TITLE);
                $("#previewImage").trigger("swap", [REL]);

                // check for boundaries
                var scrollIndex = $('#triggers li a').index($(this));
                imageScrollerCheckBoundaries(scrollIndex);


            });
        });
        $("#clone").addClass("scrollable");
        $("#clone").css("width", (4 * 177));
        $("#clone").scrollable({ "clickable": true, "size": (4), api: true });
    }
}

function imageScrollerCheckBoundaries(scrollIndex) {
    var api = $('#clone').data('scrollable');
    var count = api.getSize();
    log("count = " + count);
    log("scrollIndex = " + scrollIndex);
    if (scrollIndex == 0) {
        //first item in the list. don't display "previous" arrow
        $('#imageZoom .navleft').addClass('hidden');
    }
    else {
        $('#imageZoom .navleft').removeClass('hidden');
    }

    if (scrollIndex == count - 1) {
        // last item in the list. Don't display "next" arrow
        $('#imageZoom .navright').addClass('hidden');
    }
    else
        $('#imageZoom .navright').removeClass('hidden');
}

function openOverlay(scrollerItems, scrollIndex) {
    copyItems();
    $("html").css("overflow-y", "hidden");
    $("#overlayTest, #gallery, #teaserBG, #imageZoom, #imgClose, #closeBar, #closeText, #imagetitle").show();
    $("#clone").scrollable().click(scrollIndex);
    imageScrollerCheckBoundaries(scrollIndex);
    scaleImage();
}
function closeOverlay() {
    $("#overlayTest, #gallery, #teaserBG, #imageZoom, #imgClose, #closeBar, #closeText, #imagetitle").hide();
    $("html").css("overflow-y", "scroll");
    $("#previewImage").trigger("swap", "/images/transparent/trans.gif");
}

var g_galleryZoomInTimeoutHandle = null;
var g_galleryNavblockTimeout = 500;
function initScroller() {
    log('initScroller()');

    if (CURRENTPOOL == 'usa') {


        $('.zoomIn, #previewImage').click(function () {
            // we haven't clicked yet;
            var isNormalImage = $("#previewImage").attr("src").indexOf('filetype=normal') != -1;
            if (isNormalImage) {
                //g_galleryZoomInTimeoutHandle = window.setTimeout(function () { $('.nav').fadeOut(250) }, 1000);
                $('.nav').fadeOut(150);
            }
        });

        $("#imageZoom").hover(
            function () {
                // skip navigation arrows when in zoom mode.
                if ($("#previewImage").attr("src").indexOf('filetype=normal') != -1) {
                    log('showing left/right arrows');
                    window.clearTimeout(g_galleryZoomInTimeoutHandle);
                    $('.nav').fadeIn(250);
                }
            },
            function () {
                log('hiding left/right arrows');
                g_galleryZoomInTimeoutHandle = window.setTimeout(function () { $('.nav').fadeOut(250) }, g_galleryNavblockTimeout);
            }

        );
    }

    $(".tabContent2 ul li a").each(function () {
        var itemlink = jQuery(this);
        itemlink.attr("rel", itemlink.attr("href"));
        itemlink.attr("href", "#");
        jQuery(this).click(function () {
            var REL = jQuery(this).attr("rel");
            var TITLE = jQuery(this).children().eq(0).attr('title');
            TITLE = (TITLE == '[+]') ? '' : TITLE;
            $('#imagetitle').html(TITLE);
            // load zoom image (minizoompan)
            $("#previewImage").trigger("swap", [REL]);

            var scrollIndex = $(".tabContent2 ul li a").index(jQuery(this)); //.index();
            openOverlay(4, scrollIndex);

        });
    });
}

function addOverlay() {
    var closeBtn = "<a id='closeText' href='javascript:closeOverlay();'><span class='closeLabel'></span></a>";
    jQuery("body").prepend("<div id='overlayTest'></div><div id='closeBar'></div>" + closeBtn + "<div id='imageZoom'><div class=\"navleft nav\"><div class=\"bg\" /><div class=\"arrow\" /></div> <div class=\"navright nav\"><div class=\"bg\" /><div class=\"arrow\" /></div><img id='previewImage' alt='zoom' style='' src='/images/transparent/trans.gif' /><div id='zoomBtn' class='zoomIn'>&#160;</div></div><div id='imagetitle'>&#160;</div><div class='simple_overlay' id='gallery'><!-- 'previous page' action --> <a class='prevPage browse left' id='prevPage'></a><div id='clone'><ul id='triggers' class='galleryPictures8 items'></ul></div><!-- 'next page' action --> <a class='nextPage browse right' id='nextPage'></a></div><div id='teaserBG'></div>");
    jQuery('#imageZoom .nav .arrow').hover(
        function () { $(this).addClass('hover') },
        function () { $(this).removeClass('hover') }
    ).
    click(function () {
        var api = $('#clone').data('scrollable');
        var activeItem = $('#triggers li.active');
        var nextItem;
        if ($(this).parent().hasClass('navleft')) {
            nextItem = activeItem.prev();
        }
        else {
            nextItem = activeItem.next();
        }




        //var nextItem = $(this).parent().hasClass('navleft') ? activeItem.prev() : activeItem.next();
        nextItem.find('a').andSelf().click();
        //nextItem.click();
    })
    ;

}

var kbaseIntroHeight = 103;

$(document).ready(function () {
    var i18n = new I18N();
    $('.blueboxitem > a').wrapInner('<span></span>');
    if (jQuery("ul.modelHeader").length != 0) {
        jQuery(".introImage").append("<div id='teasershadow'></div>");
    }
    if (jQuery(".tabContent2 .galleryKBase, .tabContent2 .MRfeatures").length != 0) {
        $(".tabContent2").append($(".related"));
    }

    if (jQuery("#stopMovie").length != 0) {
        // bind necessary localized texts
        i18n.resolveText('js_apps', 'kbase', 'closeLabel', '.closeButtonFlash'); // class="closeButtonFlash"
        i18n.doProcessing();
    }

    if (jQuery(".tabContent2 .galleryKBase").length != 0) {

        // setup hover effect on tabs
        var kBaseHoverSettings = {
            timeoutHandle: null,
            delay: 200,
            speed: 120,
            effect: 'linear'
        }
        $.tools.tabs.addEffect("slide", function (i, done) {
            /* here you'll write your effect. the 'this' variable points to the API */
            var self = this;

            var scrollSettings = {
                root: ($.browser.webkit) ? $('body').eq(0) : $('html').eq(0),
                duration: 600,
                scrollOffset: 48
            }

            var slideSettings = {
                durationUp: 600,
                durationDown: 600,
                durationContentSlide: 900
            }

            var heightSettings = {
                closeButton: 32,
                loading: 200
            }

            var pane = self.getPanes().eq(i);

            var loadContent = function () {

                // Function: scroll back to headline
                var scrollToHeadline = function (callback) {
                    //log("begin scrollToHeadline");
                    var scrollPixels = pane.parent().offset().top - scrollSettings.scrollOffset;
                    //log('scrollPixels: ' + scrollPixels + ', root scroll position: ' + scrollSettings.root.scrollTop());
                    if (scrollPixels != scrollSettings.root.scrollTop()) {
                        //log('begin scroll animation');
                        scrollSettings.root.animate({ "scrollTop": scrollPixels }, scrollSettings.duration, 'swing', function () {
                            callback();
                        });
                    }
                    else {
                        //log("scroll already in position");
                        callback();
                    }
                }

                var ajaxEvent = function (url) {
                    log("entered ajaxEvent");

                    $.ajax({
                        url: url,
                        dataType: 'html',
                        success: function (data) {
                            // remove "loading" view.
                            pane.parent().animate({ "height": kbaseIntroHeight }, "fast", "swing", function () {
                                //pane.children("div:first-child").fadeOut("fast");
                                var content = data.replace(/\<\/?content\>/g, '');
                                content += '<div class="kbaseTabClose"><a href="javascript:void(0);"><span class="collapseLabel"></span></a></div>';


                                /*
                                ** INSERTING CONTENT INTO PANE
                                */
                                pane.html(content);


                                // Get rid of old stuff.
                                $('#knowledgebaseWrapper').removeClass('knowledgebaseWrapper');
                                $('#introImageKBase').removeClass('introImage');
                                // move image description from content to intro image (so that it does not scroll out of view)
                                if ($('.innerContent > *:first-child').hasClass('footnote')) {
                                    var childList = $('.innerContent').children();
                                    for (var i = 0; i < childList.length; i++) {
                                        if (jQuery(childList[i]).hasClass('footnote')) {
                                            $('.innerContent').parent().find('.introImage').append($('.innerContent > *:first-child'));
                                        }
                                        else {
                                            break;
                                        }
                                    }

                                }

                                // add scroll pane
                                var scrolPaneCSSclass = 'scroll-pane';
                                if ($('.innerContent').find('.engineDiagram').length > 0) {
                                    scrolPaneCSSclass = 'scroll-pane-enginediagram';
                                }

                                $('.innerContent', pane)
                                        .addClass(scrolPaneCSSclass)
                                        .removeClass('innerContent')
                                        .jScrollPane({ 'showArrows': 'true' });

                                // add font toggler
                                if (isJDP20112()) {
                                    var toggler = $('<div class="fontsizeToggler"></div>');
                                    $('#knowledgebaseWrapper .introImage, #introImageKBase').after(toggler);
                                    $('<a href="javascript:void(0)" class="small">A</a><a href="javascript:void(0)" class="medium">A</a><a href="javascript:void(0)" class="large">A</a>').appendTo(toggler);

                                    $('a', toggler).click(function () {
                                        $(this).addClass('active');
                                        $(this).siblings().removeClass('active');
                                        var fSize = $(this).css('font-size');
                                        //log('fSize :' + fSize);
                                        $('#knowledgebaseWrapper p').css('font-size', fSize);
                                        var api = $('.' + scrolPaneCSSclass).data('jsp');
                                        api.reinitialise();
                                    });

                                    $('a.small', toggler).click();


                                }

                                /** CALCULATE HEIGHT */
                                if ($('#introImageKBase_flash', pane).length != 0) {
                                    var flashElm = $('#introImageKBase_flash', pane).get(0);
                                    $('#introImageKBase_flash').parent().css({ "height": $(flashElm).attr("height") + "px", "width": $(flashElm).attr("width") + "px" });
                                }

                                var paneHeight = pane.height() + heightSettings.closeButton;

                                log("ajax // paneHeight: " + paneHeight);

                                // slide down after loading final content
                                pane.parent().animate({ "height": paneHeight }, slideSettings.durationContentSlide, "swing", function () {
                                    // set i18n texts
                                    i18n.resolveText('js_apps', 'kbase', 'closeLabel', '.collapseLabel'); // class="closeLabel"
                                    i18n.doProcessing();


                                    //Simulate click on the manual close link beneath the kbase content.
                                    pane.find('.kbaseTabClose').click(function () {
                                        log('begin close');
                                        scrollToHeadline(function () {
                                            self.getCurrentTab().click();
                                        });
                                    });

                                    scrollToHeadline(function () { done.call(); });


                                });


                            }); //animate


                        } // success
                    }); // $.ajax
                } // var ajaxEvent

                // load unless already loaded.
                if (pane.is(":empty")) {
                    // load the URL specified in the tab's href attribute
                    var url = $('#kbaseLink' + (i + 1)).eq(0).attr("href");

                    // set "loading animation" until ajax request has completed.
                    pane.html('<div class="kbase-loading"></div>');

                    // calculate content height
                    var paneHeight = heightSettings.loading + heightSettings.closeButton;
                    //log('paneHeight: ' + paneHeight);

                    // slide down (loading screen)
                    pane.parent().animate({ "height": paneHeight }, 200, "linear", ajaxEvent(url));
                }
                else {
                    scrollToHeadline(function () { done.call(); });
                }

            } // end loadContent




            /**************************/
            /* SLIDE-DOWN definition
            /**************************/

            var slideDown = function () {
                $('.kbaseTabClose', pane.parent()).show();
                if (!pane.is(":empty")) {
                    /** CALCULATE HEIGHT */
                    var paneHeight = pane.height() + $('.kbaseTabClose').height();
                    //var paneHeight = heightSettings.loading + heightSettings.closeButton;
                    log('paneHeight: ' + paneHeight);
                    // slide down
                    pane.parent().animate({ "height": paneHeight }, slideSettings.durationContentSlide, "swing");
                }
                pane.parent().slideDown(slideSettings.durationDown, loadContent);
            };




            /**************************/
            /* SLIDE-UP definition
            /**************************/

            var durationSlideUp;
            // index of the previously opened item.
            var lo = pane.data("lastopen");

            // stop Video-playback, if any
            flashPlayer_cmdStop("introImageKBase_flash");

            var removeCloseButton = function () {
                self.getPanes().eq(lo).parent().find('.kbaseTabClose').hide();
            }

            // remove Buttons.
            removeCloseButton();

            if (typeof (lo) == 'undefined' || (i == lo && pane.data('status') == 'closed')) {
                durationSlideUp = 0;
                // dont slide up
            }
            else {
                durationSlideUp = slideSettings.durationUp;

                var slideUpCallback = function () {
                    // IE7 has a problem with the content pane
                    // in combination with the scroller plugin,
                    // so we delete its content after we close the pane.
                    if (($.browser.msie) && ($.browser.version < 8.0)) {
                        self.getPanes().eq(lo).empty();
                    }
                }

                if (!(i == lo && pane.data('status') == 'open')) {
                    // on modern browsers, this works better, so
                    // empty content pane only when we are opening another one.
                    var paneToEmpty = this.getPanes().eq(lo);
                    slideUpCallback = function () {
                        paneToEmpty.empty();
                    };
                }
                self.getPanes().eq(lo).parent().animate({ "height": kbaseIntroHeight }, durationSlideUp, "swing", slideUpCallback);
            }
            pane.data('status', 'closed');


            // set close/collapse label
            if (pane.parent().find('.kbaseHead .kbaseTabClose').length == 0) {
                pane.parent().find('.kbaseHead').append('<div class="kbaseTabClose"><a href="javascript:void(0);"><span class="collapseLabel"></span></a></div>');
                i18n.resolveText('js_apps', 'kbase', 'closeLabel', '.collapseLabel');
                i18n.doProcessing();
            }

            if (pane.data("clickonsame") != true) {
                log('"clickonsame" != true');
                window.setTimeout(slideDown, durationSlideUp);
                pane.data('status', 'open');
            }
            else {
                done.call();
            }

        });

        $(".tabContent2").tabs(".tabContent2 .galleryKBase div.kbaseContent",
            {
                tabs: '.kbaseHead',
                effect: 'slide',
                initialIndex: null,
                onBeforeClick: function (event, i) {

                    // save last tab information in every tab
                    this.getPanes().data("lastopen", this.getIndex());

                    var pane = this.getPanes().eq(i);
                    if (typeof (pane.data('status')) == 'undefined')
                        pane.data('status', 'closed');

                    if (this.getIndex() === i && pane.data("clickonsame") != true) {
                        pane.data("clickonsame", true);
                        pane.siblings().data("clickonsame", false);
                    }
                    else {
                        this.getPanes().data("clickonsame", false);
                    }



                },
                onClick: function (event, i) {
                    var pane = this.getPanes().eq(i);
                    //log("pane.data('status'): " + pane.data('status'));
                    if (pane.data('status') == 'closed') {
                        //log("closing");
                        //log("this.getConf().current: " + this.getConf().current);
                        //$('.kbaseHead').removeClass(this.getConf().current);
                        var tab = this.getCurrentTab();
                        var cur = this.getConf().current;
                        window.setTimeout(function () { tab.removeClass(cur); }, 1);
                        //event.preventDefault();

                    }

                }

            });
        if (getQueryVariable('topic') != '') {
            $('#' + getQueryVariable('topic')).click();
        }

    }
    if (jQuery("ul.galleryPictures").length != 0) {
        addOverlay();
        // load texts
        i18n = new I18N();
        i18n.resolveText('js_apps', 'kbase', 'closeLabel', '.closeLabel');
        initScroller();
        $("body").bind("resize", scaleImage);
        $("#overlayTest").click(function () { closeOverlay(); });
        $("#imageZoom").miniZoomPan({
            sW: WIDTH,
            sH: HEIGHT,
            lW: Z_WIDTH,
            lH: Z_HEIGHT,
            loaderContent: "<img src='/images/loading4.gif' style='width: 16px; height: 16px;' />",
            callback: function () {
                scaleImage();
                // insert Texts into DOM to refer to later in the plugin.
                // e.g. "click to zoom in / zoom out" etc.

                i18n.resolveText('js_apps', 'gallery', 'clicktozoomin', '#previewImage|attr:title'); // class="closeLabel"
                i18n.doProcessing();

            }
        });
        if (($.browser.msie == true) && ($.browser.version < 7.0)) {
            $("#overlayTest, #closeBar, #imgClose, #imageZoom, #gallery, #teaserBG").addClass("ie6fixedposition");
        }
    }
    if (jQuery("ul.galleryWallpapers").length != 0) {
        jQuery("#wallpaperDownloads").bind('swapUrl', function (evt, uri, e, ofs, pos) {
            jQuery(this).children("li").children("a").each(function () {
                var attrID = jQuery(this).attr("id");
                var wpUrl = uri.replace(/preview.jpg/, "wallpaper-" + attrID + ".jpg").replace(/filetype=preview/, 'filetype=' + attrID);
                jQuery(this).attr("href", wpUrl);
            });
            jQuery(this).css("top", (ofs.top + 80) + "px");
            jQuery(this).css("left", (pos.left + 100) + "px");
            jQuery(this).show();
        });
        jQuery("#wallpaperDownloads").mouseleave(function () {
            jQuery(this).hide();
        });
        jQuery("ul.galleryWallpapers li").each(function () {
            jQuery(this).mouseenter(function (e) {
                var stringURL = jQuery(this).children("a").children("img").attr("src");
                var ofs = jQuery(this).offset();
                var pos = jQuery(this).position();
                var ofsLeft = this.offsetLeft;
                var ofsTop = this.offsetTop;
                var image = jQuery(this).children("a").children("img");
                if ($(image).hasClass("i320x480")) {
                    jQuery("#i320x480").parent().removeClass("wHidden");
                }
                else {
                    if (!jQuery("#i320x480").parent().hasClass("wHidden")) {
                        jQuery("#i320x480").parent().addClass("wHidden");
                    }
                }
                if ($(image).hasClass("i640x960")) {
                    jQuery("#i640x960").parent().removeClass("wHidden");
                }
                else {
                    if (!jQuery("#i640x960").parent().hasClass("wHidden")) {
                        jQuery("#i640x960").parent().addClass("wHidden");
                    }
                }
                if ($(image).hasClass("i1024x1024")) {
                    jQuery("#i1024x1024").parent().removeClass("wHidden");
                }
                else {
                    if (!jQuery("#i1024x1024").parent().hasClass("wHidden")) {
                        jQuery("#i1024x1024").parent().addClass("wHidden");
                    }
                }
                jQuery("#wallpaperDownloads").trigger("swapUrl", [stringURL, e, ofs, pos]);
            })
        });
    }
});

function openPanoLayer() {
    if ($('#introFlash').length == 0)
        return;

    if ($('#panoramaShadow').length == 0) {

        var tmp = document.location.href;
        var modelrange = "";
        if (tmp.indexOf('/models/911') > -1) {
            modelrange = "911";
        }
        else if (tmp.indexOf('/models/boxster') > -1) {
            modelrange = "boxster";
        }
        else if (tmp.indexOf('/models/cayman') > -1) {
            modelrange = "cayman";
        } 
        else if (tmp.indexOf('/models/cayenne') > -1) {
            modelrange = "cayenne";
        } 
        else if (tmp.indexOf('/models/panamera') > -1) {
            modelrange = "panamera";
        }

        addTabs(modelrange);
    }

    modelhomeHideElements();
    //jQuery("#introFlash").hide();
    //$('#panoramaShadow').css({ 'z-index': '1' }).fadeTo('slow', 0.8);
    //$('#panoTabs, #panoContent, #stopMovie').css({ 'z-index': '2' }).fadeTo('slow', 1.0);
    $('#panoramaShadow, #panoTabs, #panoContent').show();
    jQuery("#stopMovie").show();
}

function addTabs(modelrange) {

    $('#introImage').append('<div id="panoramaShadow"></div><ul class="tabs2 pano' + modelrange + '" id="panoTabs"></ul><div id="panoContent"></div>');

    var tabs = $('#panoTabs');
    tabs.append('<li class="tab1" id="exterior"><a href="#"></a></li><li class="tab2" id="interior"><a href="#"></a></li>');
    if ((modelrange == 'cayenne') || (modelrange == 'panamera')) {
        tabs.append('<li class="tab3" id="interior2"><a href="#"></a></li>');
    }
//    if (modelrange == '911') {
//        $("#interior").remove();
//    }
    $("#exterior > a").text(CURRENTPOOL == 'germany' ? 'Exterieur' : 'Exterior');
    $("#interior > a").text(CURRENTPOOL == 'germany' ? 'Interieur' : 'Interior');
    $("#interior2 > a").text(CURRENTPOOL == 'germany' ? 'Interieur (hinten)' : 'Interior 2');
    tabs.children('li').each(function () {
        $(this).click(function () {
            if ($(this).hasClass('selected')) {
                return false;
            }
            $('#panoTabs li').removeClass('selected');
            $(this).addClass('selected');
            $('#panoContent').empty();
            $('#panoContent').append('<div id="panoContent_flash"></div>');
            var view = this.id;
            var tmp = document.location.href;
            var folder = modelrange;
            if (tmp.indexOf('911-turbo') > -1) {
                folder = '911-TurboS';
            }
            else if ((tmp.indexOf('911') > -1) && (tmp.indexOf('cabriolet') > -1)) {
                folder = '911-Carrera4S-Cab';
            }
            showFlash('http://special.porsche.com/all/media/flash/panoramas/' + folder + '/' + view + '/pano.swf', 'panoContent_flash', '670', '380', '9', 'transparent', 'loop=true,allowScriptAccess=always,menu=false,quality=high,wmode=transparent,allowFullscreen=true,base=http://special.porsche.com/all/media/flash/panoramas/' + folder + '/' + view + '/', 'test=1');
        });
    });
    tabs.children('li:first').click();
}
function closePanoLayer()
{
    //$('#panoramaShadow, #panoTabs, #panoContent').fadeTo('slow', 0.0).css({'z-index':'0'});
    $('#panoramaShadow, #panoTabs, #panoContent').hide();
    //jQuery("#introFlash").show();
    modelhomeShowElements();
    jQuery("#stopMovie").hide();
}
function modelhomeHideElements() {
    jQuery("#teasershadow, ul.modelHeader, #dealersearchShadow").hide();
//    jQuery("ul.modelHeader, #dealersearchShadow").fadeTo('fast', 0.0);
//    jQuery("#teasershadow").hide();
}
function modelhomeShowElements() {
    jQuery("#teasershadow, ul.modelHeader, #dealersearchShadow").show();
//    jQuery("ul.modelHeader, #dealersearchShadow").fadeTo('fast', 1.0);
//    jQuery("#teasershadow").show();
}

// ...
function mr_getFlashMovie(movieName) { var isIE = navigator.appName.indexOf("Microsoft") != -1; return (isIE) ? window[movieName] : document[movieName]; }
/* Events: werden vom Player aufgerufen */
function flashPlayer_onStart() {
    // wird vom Flash Player aufgerufen nachdem der Start Button geklickt wurde
    //console.log("flashPlayer_onStart");
    modelhomeHideElements()
    jQuery("#stopMovie").show();
}
function flashPlayer_onStop() {
    // wird vom Flash Player aufgerufen nachdem der Stopp Button geklickt wurde
    //console.log("flashPlayer_onStop");
    modelhomeShowElements();
    jQuery("#stopMovie").hide();
}
function flashPlayer_onPause() {
    // wird vom Flash Player aufgerufen nachdem der Pause Button geklickt wurde, bzw das Video im Flash angehalten wurde
    //console.log("flashPlayer_onPause");
}
function flashPlayer_onPlay() {
    // wird vom Flash Player aufgerufen nachdem der Play Button geklickt wurde, bzw das Video im Flash fortgeetzt wurde
    //console.log("flashPlayer_onPlay");
    jQuery("#teasershadow, ul.modelHeader").hide();
    jQuery("#stopMovie").show();
}
/* Steuerung: wird vom HTML aus aufgerufen */
function flashPlayer_cmdStart() {
    // der Flash Player startet das Video
    //console.log("flashPlayer_cmdStart");
}
/*function flashPlayer_cmdStop() {
// der Flash Player beendet das Video
//console.log("flashPlayer_cmdStop");
mr_getFlashMovie("introFlash_flash").flashPlayer_cmdStop();
}*/
function flashPlayer_cmdStop(sFlashObjID) {
    // der Flash Player beendet das Video
    //console.log("flashPlayer_cmdStop");
    if ((sFlashObjID == null) || (sFlashObjID == ''))
        sFlashObjID = "introFlash_flash";

    if (document.getElementById(sFlashObjID)) {
        if (typeof (document.getElementById(sFlashObjID).flashPlayer_cmdStop) == "function")
            mr_getFlashMovie(sFlashObjID).flashPlayer_cmdStop();
    }

    closePanoLayer();
}
function flashPlayer_cmdPause() {
    // der Flash Player hält das aktuell geladene Video an
    //console.log("flashPlayer_cmdPause");
}
function flashPlayer_cmdPlay() {
    // der Flash Player setzt das aktuell geladene Video fort
    //console.log("flashPlayer_cmdPlay");
}

function runExternalScript(url, supportsHttps) {
    var proto = (("https:" == document.location.protocol) && supportsHttps) ? "https://" : "http://";
    var script   = document.createElement("script");
    script.type  = "text/javascript";
    script.src   = proto + url;
    document.body.appendChild(script);
}


function track(trackingURL) {
//takes an imageURL 2 load a TrackingImg

    $("<div style=\"position:absolute;\"><img src=\"" + trackingURL + "\"  style=\"display:none !important;width:1px; height:1px;\" /></div>").appendTo('body');

}



function I18N() {
    var self = this;

    this.q = new textSetQueue();

    this.pool = getPoolName();

    this.language = getPoolLang(this.pool);

    this.textlistContainer = "i18n";

    this.textlistPool = this.pool;

    this.textlistLanguage = this.language;

    this.currentTextListId = '';

    this.getGroupId = function(tlId, group) {
        return 'textlist_' + self.clearAttr(tlId) + '_' + self.clearAttr(group);
    }
    this.getTextId = function(tlId, group, textname) {
        return self.getGroupId(tlId, group) + '_' + self.clearAttr(textname);
    }

    this.clearAttr = function(attr) {
        return attr.replace(/\s+/g, '_');
    }

    this.requiredGroups = [];
    this.insertTLGroups = function(pool, lang) {
        id = self.currentTextListId;

        log('insertTLGroup().. ');
        if ($("#" + self.textlistContainer).length == 0) {
            $("<div id=\"" + self.textlistContainer + "\" style=\"display:none !important;\"></div>").appendTo('body');
        }

        log("ajax request firing..");
        $.ajax({
            url: '/all/cms2js/gettext.aspx?i=' + id + '&p=' + pool + '&l=' + lang,// + '&c=0',

            success: function(data) {
                //log("ajax - success");
                /* 
                Convert text list into a structured HTML block
                <div id="textlist_(textlistid)_(groupname)">
                <span id="textlist_(textlistid)_(groupname)_(textname)">Content</span>
                </div>
                */
                $.each(
                    self.requiredGroups,
                    function(intIndex, groupKey) {
                        var arrTlGrp = groupKey.split('|');

                        var id = arrTlGrp[0];
                        var groupName = arrTlGrp[1];

                        // go through all groups in self.requiredGroups
                        var blockId = self.getGroupId(id, groupName);
                        $('<div class=\"textlist_hidden\" id=\"' + blockId + '\"></div>').appendTo("#" + self.textlistContainer);

                        $(data).find("group[name='" + groupName + "']").children('text').each(function() {
                            //log(intIndex + ". Text name:" + $(this).attr('name'));
                            $('<span id=\"' + self.getTextId(id, groupName, $(this).attr('name')) + '\">' + $(this).text() + '</span>').appendTo('#' + blockId);
                        });
                    });
            },

            complete: function(XMLHttpRequest, textStatus) {
                //log("ajax - complete");

                /************************/
                // Process item queue
                /************************/
                while (self.q.dataQueue.length > 0) {
                    // pop item from array
                    var textItem = self.q.dequeue();
                    // set the corresponding text.
                    self.setText(textItem.selector, textItem.textId);
                }
                // clear group list
                self.requiredGroups = [];
            }
        });
    }

    // sets the Text of a given element from the
    // Text-Container readily available in the DOM tree.
    this.setText = function(targetdomselector, sourceId) {
        //log('targetdomselector: '+ targetdomselector);
        var target;
        // Parse Dom selector for anything other than inner Text setting.        
        var actionType = 'text';
        var actionParam = '';

        var t1 = targetdomselector.split('|');
        if (t1.length == 2) {
            // check for attribute setting.
            if (t1[1].indexOf(':') != -1) {
                var t2 = t1[1].split(':');
                if (t2[0] == "attr" && t2[1].length > 0) {
                    actionType = t2[0];
                    actionParam = t2[1];
                }
            }
            target = t1[0];
        }
        else {
            target = targetdomselector;
        }
        var html = $('#' + sourceId).html();
        if (html != null) {
            //log('html=' + html);
            switch (actionType) {
                case 'text':
                    //log('setting Text : selector="' + target + '" sourceId: "' + sourceId + '"');
                    $(target).html(html);
                    break;
                case 'attr':
                    //log('setting Attribute : target="' + target + '" actionParam="' + actionParam + '" sourceId: "' + sourceId + '"');
                    $(target).attr(actionParam, html);
            }
        }
    }

    // request text handling
    this.resolveText = function(textlistid, groupname, textname, domselector) {
        this.currentTextListId = textlistid;
        // read text with the given id from textlist group.
        var elm = $('#' + self.getGroupId(textlistid, groupname));
        var textContainerId = self.getTextId(textlistid, groupname, textname);
        //log("i18n.resolveText | textContainerId:" + textContainerId);

        if (elm.length == 0) {
            // the text item we are looking for hasnt been fetched yet, so fetch the textlist group (async)
            // and put it already in the main queue.
            // if there are any items requested meanwhile, put them in the queue.
            var groupKey = textlistid + "|" + groupname;
            if (!ArrayContainsItem(self.requiredGroups, groupKey)) {
                // add group to List of required groups
                self.requiredGroups.push(groupKey);
            }
            this.q.enqueue(domselector, textContainerId);
            // insert group into DOM
        }
        else {
            self.setText(domselector, textContainerId);
        }
    }

    this.toDo = function() { return this.requiredGroups.length > 0; }

    // If there are any required textlist groups
    // go get them (multiple, see usage of property "this.requiredGroups").
    this.doProcessing = function() {
        //log("doProcessing: this.requiredGroups.length=" + this.requiredGroups.length);
        if (this.toDo())
            this.insertTLGroups(self.textlistPool, self.textlistLanguage);
    }

    function textSetItem(_jqSelector, _textId) {
        this.selector = _jqSelector;
        this.textId = _textId;
    }

    function textSetQueue() {
        var self = this;
        this.dataQueue = [];
        this.dataQueueBuffered = [];

        this.enqueue = function(selector, textId) {
            self.dataQueue.push(new textSetItem(selector, textId));
        }

        this.dequeue = function() {
            return self.dataQueue.pop();
        }

        this.enqueueBuffered = function(selector, textId) {
            self.dataQueueBuffered.push(new textSetItem(selector, textId));
        }

        this.dequeueBuffered = function() {
            self.dataQueueBuffered.pop();
        }

    }
}
function ArrayContainsItem(arr, obj) {
    if (!($.isArray(arr))) {
        log("ArrayContainsItem: not an array");
        return false;
    }
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == obj) return true;
    }
    return false;
}





// Tracking 4 Canada 20/09/2010 miki
function specialSpotlightTrackings() {
    
    var ebRand = Math.random() + '';
    ebRand = ebRand * 1000000;
    var actID = null;


    if (CURRENTPOOL == 'usa') {

       switch (g_page_nxid) {
        
            case 'b50edbdb-f3f0-4b97-a9b1-734877fefeb8': actID = 138112; break; // Homepage
            case 'panamera': actID = 144258; break; // Panamera Models Landing Page
            case '970-g1-s-hy': actID = 138110; break; // Panamera Hybrid Landing Page
            case '970-g1-s-hy-microsite': actID = 144259; break; //  Panamera Hybrid Web Special Entrance
            case '987-2nd-c7r': actID = 106760; break;
            case '970-g1-s-hy': actID = 138112; break; //panamera s hybrid
            case '991-c2': actID = 165981; /* 145875;*/break;  // 911(991) Carrera Modelpage
            case 'newslettersubscribe': actID = 165984; break;  // Newsletter Subscribe, Page 1
            case 'newsletter-tellafriend': actID = 165985; break;  // Newsletter Tell a Friend, Page 1
            default: return; // actID = null;
      }
   }

    if (CURRENTPOOL == 'canada') {
        switch (g_page_nxid) {
            case 'home': actID = 79149;  break;
            case 'aps594': actID = 79150; break;
            case '987-2nd-bo': actID = 79151; break;
            case '987-2nd-bos': actID = 79152; break;
            case '987-2nd-bo-spyder': actID = 79153; break;
            case 'cayman': actID = 79154; break;
            case '987-2nd-c7': actID = 79155; break;
            case '987-2nd-c7s': actID = 79156; break;
            case '911': actID = 79157; break;
            case '997-2nd-c2': actID = 79158; break;
            case '997-2nd-c2s': actID = 79159; break;
            case '997-2nd-c2cab': actID = 79160; break;
            case '997-2nd-c2scab': actID = 79161; break;
            case '997-2nd-c4': actID = 79162; break;
            case '997-2nd-c4s': actID = 79163; break;
            case '997-2nd-c4cab': actID = 79164; break;
            case '997-2nd-c4scab': actID = 79165; break;
            case '997-2nd-ta4': actID = 79166; break;
            case '997-2nd-ta4s': actID = 79167; break;
            case '997-2nd-tu': actID = 79168; break;
            case '997-2nd-tus': actID = 79169; break;
            case '997-2nd-tucab': actID = 79170; break;
            case '997-2nd-tuscab': actID = 79171; break;
            case '997-2nd-gt3': actID = 79172; break;
            case '997-2nd-gt3rs': actID = 79173; break;
            case '997-2nd-gt2rs-microsite': actID = 79174; break;
            case 'panamera': actID = 79175; break;
            case '970-g1-v6': actID = 79176; break;
            case '970-g1-4': actID = 79177; break;
            case '970-g1-s': actID = 79178; break;
            case '970-g1-4s': actID = 79179; break;
            case '970-g1-tu': actID = 79180; break;
            case 'aps882': actID = 79181; break;
            case '9pa-e2-v6': actID = 79182; break;
            case '9pa-e2-s': actID = 79183; break;
            case '9pa-e2-s-hy': actID = 79184; break;
            case '9pa-e2-tu': actID = 79185; break;
            case 'n5': actID = 79186; break;
            case '79482b1a-6789-4df1-90e7-440f10ce0baf': actID = 79187; break;
            case '6ecb1f51-7c8d-4aef-9fa7-ff83e2302b9e': actID = 79188; break;
            case 'n11': actID = 79189; break;
            case 'a93f98e0-2f56-4f9f-9938-b17728b3bb89': actID = 79190; break;
            //case '': actID = 79191; break; build your car
            case 'dialogarea': actID = 79192; break;
            //case '': actID = 79193; break; Find a dealer

            default: return; // actID = null;
        }
    }
    if (actID != null) {
       
        var trackingUrl = 'http://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?cn=as&ActivityID=' + actID + '&ns=1' + '&rnd=' + ebRand;
        track(trackingUrl);
    }
}

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

});
function initSlideShow() {
    if ($.tools != null) {
        $.tools.tabs.addEffect("burn", function (i, done) {
            var conf = this.getConf(),
            speed = conf.fadeOutSpeed,
            panes = this.getPanes();
            if (speed) {
                panes.fadeOut(speed);
            } else {
                panes.hide();
            }
            setTimeout(function () { panes.eq(i).fadeIn(conf.fadeInSpeed, function () { setTimeout(done, 1000) }); }, 1000);
        });

        if ($("div.slideshow").length > 0) {
            try {
                $('.introImage .banderole').css({ 'top': 'auto' });
                slideshowStart(slideshowOptions);
            }
            catch (e) {
                slideshowStart();
            }
        }
    }
}

function slideshowStart(options)
{
    if(options == undefined)
        options = {};

    // default values
    var defaults = { "background" : "#FFFFFF", "transition" : "fade", "loop" : true, "lifeSpan" : "4000", "loopStart" : 0 };

    // option values
    background = (options.background != undefined) ? options.background : defaults.background;
    transition = (options.transition != undefined) ? options.transition : defaults.transition;
    loop = (options.loop != undefined) ? options.loop : defaults.loop;
    loopStart = (options.loopStart != undefined) ? options.loopStart : defaults.loopStart;
    lifeSpan = (options.lifeSpan != undefined) ? options.lifeSpan : defaults.lifeSpan;

    $(".slideshow").css("background-color", background);	
    $(".slidetabs").tabs(".slideshow > div", {	
        effect: transition,
        fadeInSpeed: 500,	
        fadeOutSpeed: 500,	
        rotate: loop,
        initialIndex: loopStart
    }).slideshow({
        autoplay: true,
        autopause: false,		
        clickable: false,
        interval: lifeSpan
    });	
}

///// IPAD MODIFIKATIONS //// IMPORTANT // DO NOT CHANGE PLACE IN default.js MUST BE AT END PLACE NEW FUNCTIONS BEFORE!!!!!!!!!
function ipadModifikations() {
    var iPad = (navigator.userAgent.toLowerCase()).indexOf('ipad') != -1;
    var iPadBanner = typeof (window['ipadbanner']) != "undefined" && typeof (window['ipadclaim']) != "undefined";
    try {
        var teasercount = $('.teaserBar li').length;
        //log("count teasers:" + teasercount);
        //if user agent = ipad
        if (iPad) {
            if (iPadBanner) {
                //log("iPad.");
                //change Banner2IpadStuff
                //$("div.introImage > img").attr("src", ipadbanner.replace(/\&amp;/g, '&'));
                //$("a.homeHead img").removeAttr("style");
                //$("#homeHead").css({ "top": "43px", "left": "320px" });
                //$("a.homeHead img").attr("src", ipadclaim.replace(/\&amp;/g, '&'));
                //$("#homeHead").attr("href", "javascript:gotoUrlFullscreen(\'/microsite/ipad/" + CURRENTPOOL + ".aspx\',\'true\')");
                
                // first 8 teasers are for iPad, remove the next 8.
                if ($('.teaserBar li').length == 16) {
                    log("removing last 8 teasers");
                    for (i = 9; i <= 16; i++) {
                        $('.teaserBar li.teaser' + i).remove();
                    }
                }
            }
        }
        else {
            //log("non-iPad.");
            if (iPadBanner) {
                // remove the iPad teasers (first 8)
                if (teasercount == 16) {
                    log("removing first 8 teasers");
                    for (i = 1; i <= 8; i++) {
                        $('.teaserBar li.teaser' + i).remove();
                    }
                }

            }
        }
    }
    catch (e) {
    }
}
///// IPAD MODIFIKATIONS //// IMPORTANT // DO NOT CHANGE PLACE IN default.js MUST BE AT END PLACE NEW FUNCTIONS BEFORE!!!!!!!!!
function submitForm(action) {
    if(action == "reset")
    {
        if ($('#formcomponentform').length > 0) {
            document.forms["formcomponentform"].reset();
        }
        return false;
    }
    else
    {
        if ($('#formcomponentform').length > 0) {
            $('#formcomponentform').append('<div><input type="hidden" name="' + action + '" value="' + action + '" /></div>');
        }
        else {
            return false;
        }

        $('#formcomponentform').submit();
        return true;
    }
}
function previewText(srcElementID, multiline) {

    var ml = (multiline ? '<br></br>' : '');

    $('#' + srcElementID + 'preview').html( $('#' + srcElementID).attr('value')
                                            .replace(/ /g, '� ')
                                            .replace(/\</g, '')
                                            .replace(/\>/g, '')
                                            .replace(/\n/g, ml)
                                          );
    $('#messagehidden').attr({ 'value': $('#message').attr('value').replace(/ /g, '� ').replace(/\</g, '').replace(/\n/g, ml) });

}
function previewKey(e) {
  ;
}
/* Teaser Scroller */
var g_firstVisible = 1;
var g_lastvisible = 4;
var g_LastTeaser = 0;
var g_teaserWidth = 167 + 9;
var g_xposLastVisibleTeaser = g_teaserWidth * (g_lastvisible - g_firstVisible);

function setLastTeaser()
{
  var elem = document.getElementsByTagName("li");
  if (elem)
  {
    var i = 0;
    for (i = 0; i < elem.length; i++)
    {
      if (elem[i].className)
      {
        if (elem[i].className.indexOf("teaser") >= 0)
        {
          // PS4 rendert kein id Attribut
          if (!elem[i].id)
          {
            elem[i].id = elem[i].className;
          }
          elem[i].style.left = (g_LastTeaser * g_teaserWidth).toString()+"px";
          g_LastTeaser++;
        }
      }
    }
  }
}

function showHideTeaserNavbar()
{
    var leftNav = document.getElementById("teaserbarNavLeft");
    if(g_firstVisible == 1)
        leftNav.style.display = "none";
    else
        leftNav.style.display = "block";

    var rightNav = document.getElementById("teaserbarNavRight");
    if(g_lastvisible == g_LastTeaser)
        rightNav.style.display = "none";
    else
        rightNav.style.display = "block";
}
function moveTeaserbar()
{
    var wrapper = document.getElementById("teaserBarWrapper");
    if(!wrapper)
        return;
    var elem = document.getElementsByTagName("ul");
    if(!elem)
        return;
    var i = 0;
    for(i; i < elem.length; i++)
    {
        if(elem[i].className.indexOf("teaserBar") >= 0)
            break;
    }
    var teaserBar = elem[i];
    if(!teaserBar)
        return;
    wrapper.appendChild(teaserBar);
    teaserBar.style.display = 'block';
    if (g_LastTeaser == 0)
    {
        setLastTeaser();
    }
    showHideTeaserNavbar();
}
function scrollTeaserBar(direction)
{
    if(!direction)
        return;
    if (g_LastTeaser == 0)
    {
        setLastTeaser();
    }

  var numTeasers = 4;

  if(direction == 'next')
  {
    if(g_lastvisible < g_LastTeaser)
    {
      if((g_lastvisible + 4) > g_LastTeaser)
      {
        // weniger als 4 ï¿½brig:
        numTeasers = g_LastTeaser - g_lastvisible;
      }
      g_lastvisible += numTeasers;
      g_firstVisible = g_lastvisible - 4 + 1;
      numTeasers = -numTeasers;
      scrollTeaserBarBy( numTeasers * g_teaserWidth);
    }
  }

  if(direction == 'previous')
  {
    if(g_lastvisible > 4)
    {
      if((g_lastvisible - 4) >= 1)
      {
        // weniger als 4 ï¿½brig:
        numTeasers = g_lastvisible - 4;
      }
      g_lastvisible -= numTeasers;
      g_firstVisible = g_lastvisible - 4 + 1;
      scrollTeaserBarBy( numTeasers * g_teaserWidth);
    }
  }
}
function scrollTeaserBarBy(px)
{
    var elem = document.getElementsByTagName("ul");
    if(!elem)
        return;
    var i = 0;
    for(i; i < elem.length; i++)
    {
        if(elem[i].className.indexOf("teaserBar") >= 0)
            break;
    }
    var teaserBar = elem[i];
    if(!teaserBar)
        return;

    var step = getStep(px);
    if(px < 0)
    {
        step = -step;
        if(px < step)
        {
            teaserBar.style.left = (teaserBar.offsetLeft + step).toString() + "px";
            px -= step;
            window.setTimeout('scrollTeaserBarBy(' + px.toString() + ')', 10);
        }
        else
        {
            teaserBar.style.left = (teaserBar.offsetLeft + px).toString() + "px";
            showHideTeaserNavbar();
        }
    }
    else
    {
        if(px > step)
        {
            teaserBar.style.left = (teaserBar.offsetLeft + step).toString() + "px";
            px -= step;
            window.setTimeout('scrollTeaserBarBy(' + px.toString() + ')', 10);
        }
        else
        {
            teaserBar.style.left = (teaserBar.offsetLeft + px).toString() + "px";
            showHideTeaserNavbar();
        }
    }
}

function getStep(px)
{
  // abs()
  if(px < 0)
    px = -px;

  if(px >= 300)
    return 50;

  if(px >= 50)
    return 20;

  if(px >= 15)
    return 5;

  return 2;
}


	// Eine Liste aller geÃ¶ffneten Popups
	var PopupList = new Array();

	//
	// Ãffnen eines Fensters.
	//
	function js_popup(str_url, str_name, str_window, int_width, int_height, int_x, int_y, str_features)
		{
		str_features = str_features + ',width=' + int_width + ',height=' + int_height;
	   
		if (int_x=='false')
		  str_features = str_features + ',left=' + (screen.width/2 - int_width/2) + ',top=' + (screen.height/2 - int_height/2);
		else
		  str_features = str_features + ',left=' + int_x + ',top=' + int_y;
		
		if (PopupList[str_window] && PopupList[str_window].closed == false)
			{
			obj_window = PopupList[str_window];
			obj_window.location.href = str_url;
			obj_window.resizeTo(int_width, int_height);
			}
		else
			{
			obj_window = window.open(str_url, str_window, str_features);
			PopupList[str_window] = obj_window;
			}
		obj_window.focus();
		}
	
	
	
//Bookmarks
jQuery(document).ready(function () {
    jQuery(".sharelayer").hide();
    
    jQuery(".sharing").hover(
    function () {
        jQuery(".sharelayer").fadeIn(100);
        jQuery('#sharelayer').css('display', 'block');
        jQuery('#sharelayer').css('opacity', '1');        
    },
    function () {
        jQuery(".sharelayer").fadeOut(100);
        jQuery('#sharelayer').css('display', 'none');       
    }
    );

});


//Wiredminds tracking
function click_track(value) {
    // trackt einen Besucher Klick
    if (g_is_home) {   // wm_cd1= value;
        try {
            wiredminds.count(value);
        }
        catch (e) {
            log("wiredminds tracking gescheitert! Value: " + value);
        }

    }
}


function sharethis(href, encoding) {
    var link;
    if (encoding == null)
        link = href.replace('URL', encodeURIComponent(document.location.toString()));
    else
        link = href.replace('URL', document.location.toString());

    link = link.replace('TITEL', document.title);

    window.open(link, 'share');
}

/**
 * jQuery
 */
$(document).ready(function()
{
	/*
	 * Hinzufügen der Klasse last des letzten li-Elements für die Formatierung
	 * der Blue-Box-Navigation
	 */
	$("ul.navigation-bluebox li.blueboxitem a").last().addClass('last');
	
	/*
	 * Umfrage-Layer Funktion
	 */
			
	// Zufallszahl zwischen 1 und 10
	var randomnumber = Math.floor(Math.random()*11);
	// Umfrage-Layer anzeigen 
	if (randomnumber >= 5) 
	{		
		$("#umfrageLayerPsyma").remove();		
	}	
	
	$(".umfrageCloseButton").click(function(){
		$('#umfrageLayer').remove();
	});
	
		
	if (jQuery.colorbox) {
		
		$(".layerPopup_660_575").colorbox({
			 iframe:true,
			 transition: "none",
			 innerWidth:660, 
			 innerHeight:575, 
			 overlayClose: false,
			 close: "",
			 scrolling: false
		});
		$(".layerPopup_820_550").colorbox({
			 iframe:true,
			 transition: "none",
			 innerWidth:820, 
			 innerHeight:550, 
			 overlayClose: false,
			 close: "",
			 scrolling: false
		});
		$(".layerPopup_840_840").colorbox({
			 iframe:true,
			 transition: "none",
			 innerWidth:840, 
			 innerHeight:840, 
			 overlayClose: false,
			 close: "",
			 scrolling: false
		});
		$(".layerPopup_1024_768").colorbox({
			 iframe:true,
			 transition: "none",
			 innerWidth:1024, 
			 innerHeight:768, 
			 overlayClose: false,
			 close: "",
			 scrolling: false
		});
		
	}		
			
});

function js_email_javascript(prefix, user, host, suffix, suffix2)
 	{
 	document.write(prefix+user+'@'+host+suffix+user+'@'+host+suffix2);
 	}
