var agt=navigator.userAgent.toLowerCase();
var isMac = ((agt.indexOf('macintosh')!=-1))?true:false;
var isExplorer = ((agt.indexOf('msie')!=-1))?true:false;
var isIE6 = ((navigator.userAgent.indexOf("MSIE 6.") != -1) && (navigator.userAgent.indexOf("Opera") == -1));
var isOpera = ((agt.indexOf('opera')!=-1))?true:false;
var info;


// Variables for product page
currentProductNumber = "";
currentProductInfoTextId = "";
defaultProductImageUrl = "";
defaultProductPrice = "";
defaultProductPriceNet = "";

$(document).ready(function() {
    initAll();
});

function initAll()
{
	//FillPreviewBasket();
	positionFooter();
    
    //HideIfLoggedIn("ifLoggedOut");
    //ShowIfLoggedIn("ifLoggedIn");
    
    //LoadPersonalizedContent();
    TurnHoverInfoScriptingOn();
    //AdjustSubNavigation();
}

/* Flash Homepage Banner*/

var flashFallbackImage = null;
var flashHomepageBanner = null;
var flashHomepageBannerLink = null;

function ShowFlashHomepageBanner()
{
    if (flashHomepageBanner != null && flashHomepageBanner != "")
    {        
        var requiredMajorVersion = 8;        
        var requiredMinorVersion = 0;        
        var requiredRevision = 0;

        var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

        if (hasRequestedVersion && !isMac) 
        {
            var rootPath = "/all/media/flash/shop/homepagebanner/";
            var params = flashHomepageBanner.split(";");
        
	        var so = new SWFObject(rootPath + params[0], "main", "839", "359", "8", "#FFFFFF",false); 
	        so.addParam("loop","true");
	        so.addParam("menu","true");
	        so.addParam("quality","high");
	        so.addParam("wmode","opaque");
	        so.addVariable("xmlPath",rootPath + params[1]);	        
	        if (flashHomepageBannerLink != null)
	        {
	            so.addVariable("targetLink",flashHomepageBannerLink);
	        }
	        so.write("flashhomepagebanner");        	
        } 
        else 
        {  
            ShowFlashFallback();
        }
    }
    else 
    {  
       ShowFlashFallback();
    }
}

function ShowFlashFallback()
{
    var element = document.getElementById("flashhomepagebanner");
    if (element)
    {
        var alternateContent = '<img src="'+flashFallbackImage+'" alt="" id=\"flashfallbackimage\" style=\"display:block;\"/>';	     
      
        if (flashHomepageBannerLink != null && flashHomepageBannerLink != '')	            
            alternateContent = '<a href="' + flashHomepageBannerLink + '">' + alternateContent + '</a>';	            

        element.innerHTML = alternateContent;
    }
}






function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/* HoverInfo */


function positionFooter()
{
    var footer = document.getElementById("footer");
    var shippingpriceinfo = document.getElementById("shippingpriceinfo");
    var search = document.getElementById("search");
    
   setDocumentSize();

    if (footer) { footer.style.bottom = "-1px"; }
    if (search) { search.style.bottom = "-1px"; }
    if (shippingpriceinfo) { shippingpriceinfo.style.bottom = "26px"; }
}

function setDocumentSize() {
	var size = 500; //160 + 105 + 85;

	var elm = document.getElementsByTagName("a");
	
	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"):			
				    if (document.body.className != "home")					
					    size += 20; // 1 line: 16, 2 lines: 31;					
				break;		
			}
		}
	}	
	
	var elm = document.getElementById("categoryItems");
	
	if (elm != null) {
		elm = elm.getElementsByTagName("div");
		var countCateroryItems = Math.ceil(elm.length/2);
		
		var heightOfCategoryItem = 128;
		var offset = 184;
		if (((countCateroryItems * heightOfCategoryItem)+offset)>size)
		{
			size = (countCateroryItems * heightOfCategoryItem);
			size += offset; // Offset
		}
		
	}
	
	/* Homepage Thumbnails (highlights */
	var elm = document.getElementById("homepageProductThumbnails");
	
	if (elm != null) {
		elm = elm.getElementsByTagName("a");
		var countThumbsPerRow = 6;
		var countThumbnailItems = elm.length;
		var countThumbnailRows = Math.ceil(countThumbnailItems/countThumbsPerRow);
		
		var heightOfThumbnailItem = 128;
		var offset = 159;
		if (document.body.className == "home" && document.getElementById('shippingpriceinfo'))
		{
			offset += 240;
		}
		
		if (((countThumbnailRows * heightOfThumbnailItem)+offset)>size)
		{
			size = (countThumbnailRows * heightOfThumbnailItem);
			size += offset; // Offset
		}
		
	}
	
	var elm = document.getElementById('productDescription');
	if(elm && elm.innerHTML.length > 120)
	{	   
	    var textHeight = ((elm.innerHTML.length / 60) -2) * 15;	    
	    size += textHeight;
	}

	var elm = document.getElementsByTagName("div");
	
	if (elm) {
		for (i = 0; i < elm.length; i++){
			if (elm[i].className == "content") {
				//elm[i].style.border = "1px solid red";
				elm[i].style.minHeight = size + "px";
				elm[i].style.height = size + "px";
				break;			
			}
		}
	}
}
/*
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 = GetCookieValue("SSO_LOGIN");
    if (status == null || status=='false') { status = false; }
    return status;
}
*/
function containsStr(s, find) {
	return (s.indexOf(find) != -1);
}

function selectAllInput(elm)
{
    if (elm)
    {
        elm.focus();
        elm.select();
    }
}

function showProductImageLayer()
{
    return false;
	ieToggleDropDowns(getListIEDropDowns(), true);
	
	var elmShade = document.getElementById("productImageLayerShade");
    var elmContent = document.getElementById("productImageLayer");
	
	currentImage = 0;
	
	switchProductImage(currentImage);

    elmShade.style.display = "block";
    elmContent.style.display = "block";

}

function hideProductImageLayer()
{
	// IE Hack for dropdowns
	ieToggleDropDowns(getListIEDropDowns(), false);
	
	var elmShade = document.getElementById("productImageLayerShade");
    var elmContent = document.getElementById("productImageLayer");

    elmShade.style.display = "none";
    elmContent.style.display = "none";
}



function changeVariantSelection(elmCalling)
{
	var elmFields = new Array(variantTypes.length);
	var values = new Array(variantTypes.length);
	var elmProductIDField = document.getElementById("ProductID");
	elmProductIDField.value = "";


	for (i=0; i<variantTypes.length; i++)
	{
		elmFields[i] = document.getElementById(variantTypes[i]);
		values[i] = elmFields[i].value;
	}

	for(i=0;i<variantList.length;i++)
	{
		// The first option field was changed, fill the second one (if any)
		if (variantList[i][0] == values[0])
		{
			// Changed the first level
			if (elmCalling == elmFields[0])			
			{
				// There is a second level, which now is to be filled
				if(isArray(variantList[i][1]) && elmFields[1] != null)
				{
					emptySelectList(elmFields[1]);
					for (j=1; j<variantList[i].length; j++) 
					{
						appendOption(elmFields[1], variantList[i][j][0], variantList[i][j][0]);
						// Pre-select the first product (if available)
						if (j == 1)
						{
							showVariant(variantList[i][j]) ;
						}		
					}
				}
				// there is no second level
				else
				{
					showVariant(variantList[i]) ;
				}
			}
			// Changed the second level
			else 
			{
				if(isArray(variantList[i][1]) && elmFields[1] != null)
				{
					for (j=1; j<variantList[i].length; j++) 
					{
						if (variantList[i][j][0] == values[1])
						{
							showVariant(variantList[i][j]) ;
						}
					}
				}
			}
		}
	}
}

function initVariantSelection()
{
	var elmFields = new Array(variantTypes.length);
	var elmProductIDInputField = document.getElementById("ProductID");
	var elmPrice = document.getElementById("price");
	var elmPriceNet = document.getElementById("netprice");
	var elmProductImage = document.getElementById("productimage");
	
	// Save the default values for elements likely to change
	if(elmProductImage && elmProductImage.src)defaultProductImageUrl = elmProductImage.src;
	defaultProductPrice = elmPrice.innerHTML;
	defaultProductPriceNet = elmPriceNet.innerHTML;
	
	// Reset the default fields
	elmProductIDInputField.value = "";
	currentProductInfoTextId = "";

	for (i=0; i<variantTypes.length; i++)
	{
		elmFields[i] = document.getElementById(variantTypes[i]);
		emptySelectList(elmFields[i]);
	}

	if (elmFields.length > 0 && elmFields[0] != null)
	{	
		for (i=0; i<variantList.length; i++)
		{
			// Add first level variants
			appendOption(elmFields[0], variantList[i][0], variantList[i][0]);
			
			// Check for second level variants
			if(isArray(variantList[i][1]) && elmFields[1] != null && (i == 0))
			{
				for (j=1; j<variantList[i].length; j++) 
				{	
					// Add second level variants
					appendOption(elmFields[1], variantList[i][j][0], variantList[i][j][0]);
					
					// Pre-select first variant
					if (j == 1)
					{
						showVariant(variantList[i][j]);
					}		
				}
			}
			// There is no second level
			else
			{
				if (i == 0) 
				{
					showVariant(variantList[i]);
				}
			}
		}
	}
}

function showVariant(arrCurrentVariant)
{
	var elmPrice = document.getElementById("price");
	var elmPriceNet = document.getElementById("netprice");
	var elmProductImage = document.getElementById("productimage");
	var elmArticlenumber = document.getElementById("articlenumber");
	var elmProductIDInputField = document.getElementById("ProductID");

	if (isArray(arrCurrentVariant))
	{
		// Product is available
		if (arrCurrentVariant[2]) 
		{
			elmProductIDInputField.value = arrCurrentVariant[1];
			currentProductNumber = arrCurrentVariant[1];
			switchAvailability(true);
		}
		else 
		{
			//elmProductIDInputField.value = "";
      elmProductIDInputField.value = arrCurrentVariant[1];
			currentProductNumber = arrCurrentVariant[1];
			switchAvailability(false);
		}
		
		// article Number
		elmArticlenumber.innerHTML = currentProductNumber;
		
		// price
		if (arrCurrentVariant[3] != null && arrCurrentVariant[3] != "") elmPrice.innerHTML = arrCurrentVariant[3];
		else elmPrice.innerHTML = defaultProductPrice;

		// netprice
		if (arrCurrentVariant[4] != null && arrCurrentVariant[4] != "") elmPriceNet.innerHTML = arrCurrentVariant[4];
		else elmPriceNet.innerHTML = defaultProductPriceNet;

		// imageUrl
		var imageUrl = defaultProductImageUrl;
		if(arrCurrentVariant[5] != null && arrCurrentVariant[5] != "")
		{
			var regAmperson = new RegExp("&amp;", "gi");
			imageUrl = arrCurrentVariant[5].replace(regAmperson, "&");
		}
		if(elmProductImage && elmProductImage.src)elmProductImage.src = imageUrl;

		// description
		if (arrCurrentVariant[6] != null && arrCurrentVariant[6] != "") currentProductInfoTextId = arrCurrentVariant[6];
		else currentProductInfoTextId = "";
		

	}
}



function switchAvailability(available)
{
	var elmLabelAvailability = document.getElementById("availability");
	var elmAddToBasket = document.getElementById("addtobasket");
	
	if(available)
	{
		elmLabelAvailability.style.display = "none";
		if(elmAddToBasket!=null)
			elmAddToBasket.style.display = "block";
	}
	else
	{
		elmLabelAvailability.style.display = "block";
		if(elmAddToBasket!=null)
			elmAddToBasket.style.display = "none";
	}
}

function showPrebookMessage()
{
	alert(currentProductNumber);
}

function appendOption(elmSelect, text, value)
{
  var elmOptNew = document.createElement('option');
  elmOptNew.text = text;
  elmOptNew.value = value;

  try {
    elmSelect.add(elmOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elmSelect.add(elmOptNew); // IE only
  }
}

function emptySelectList(elmSelect)
{
  while (elmSelect.length > 0)
  {
    elmSelect.remove(elmSelect.length - 1);
  }
}

function setPaymentFormTarget(form, ccMode, creditcardUrl, defaultUrl)
{
	// more than one payment type is available as a choice.
	if(form.paymentmethod[1])
	{
		if(form.paymentmethod[1].checked || ccMode=="direct" || form.sfpCardNumber == null) 
		{
			form.action = defaultUrl;
		}
		else
		{
			form.action = creditcardUrl;
		}
	}
  else
  {
	// this is the case where we have only one payment type.
	// and thus no radio buttons for the payment types to choose from.
	if(form.paymentmethod.value == "cc")
	{
		// credit card url to check.
		form.action = creditcardUrl;
	}
	else
	{
		// bank account
		form.action = defaultUrl;
	}
  }
	return true;
}


function isArray(obj){return(typeof(obj.length)=="undefined")?false:true;}

//
// 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(strArr, boolHide) {
	// collection of dropdowns
	
	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("size","color"));
}



function FillPreviewBasket()
{
	var articlecount = GetCookieValue("shop-basket-articlecount");
    var price = GetCookieValue("shop-basket-price");
	
	// Check if this is the homepage
	var isHomepage = false;
	
	var elm = document.getElementsByTagName("body");
	if (elm) 
	{
		for (i = 0; i < elm.length; i++)
		{
			if (elm[i].className == "home")
			{
				isHomepage = true;
				break;
			}
		}
	}

	if (articlecount == "") {
		articlecount = 0; // IE and maybe other browsers misses cookie information on first start.
	}
	
	if (articlecount == 0)
	{
		WriteHtmlContent("shop-basket-articlecount-inactive", articlecount);
		WriteHtmlContent("shop-basket-price-inactive", price);
		var spanBasket = document.getElementById("previewShoppingBasketInactive");
		if (spanBasket) spanBasket.style.display = "block";
	}

	else if (articlecount > 0)
	{
		var spanBasket = document.getElementById("previewShoppingBasketInactive");
		if (spanBasket) spanBasket.style.display = "none";
		
		WriteHtmlContent("shop-basket-articlecount-active", articlecount);
		WriteHtmlContent("shop-basket-price-active", price);
		var spanBasket = document.getElementById("previewShoppingBasketActive");
		if (spanBasket) spanBasket.style.display = "block";

		var proceedtocashierLink = document.getElementById("proceedtocashierLink");
		if (proceedtocashierLink) proceedtocashierLink.style.display = "block";

	}
		
}

function GetCookieValue(name)
{
	var i=0;
    var suche = name + "=";
	var basketText = "";
	while(i<document.cookie.length)
	{
		if(document.cookie.substring(i, i+suche.length)==suche)
		{
			var ende = document.cookie.indexOf(";", i+suche.length);
			ende = (ende>-1) ? ende : document.cookie.length;
			var cook = document.cookie.substring(i+suche.length, ende);
			basketText = unescape(cook);
			i = document.cookie.length;
		}
		i++;
	}
	return basketText;
}

function WriteHtmlContent(name, value)
{
	var divText = document.getElementById(name);
	if (divText)
	{
		divText.innerHTML = value;
	}
}

function gotoUrlNewWinSimple(s)
{
    newWin = window.open(s, "newWin" + getRandomInt(10000));
}


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 getRandomInt(max)
{
    return Math.round( Math.random() * (max-1) );
}


function SubmitBasketForm(inputfield)
{
	if(inputfield.value!="")
	{
		var editbasketscript = document.getElementById("editbasketscript"); 
		editbasketscript.value = "true";
		
		var basket = document.getElementById("formcontrol"); 
		basket.submit();
	}
}

function SubmitBasketFormPlusMinus(position, value)
{
	var editbasketscript = document.getElementById("editbasketscript"); 
	editbasketscript.value = "true";
	var plusminusposition = document.getElementById("plusminusposition"); 
	plusminusposition.value = position;
	var plusminusvalue = document.getElementById("plusminusvalue"); 
	plusminusvalue.value = value;
}

function GoArticleReminder(url)
{
	var elmProductIDInputField = document.getElementById("ProductID");
	url += "&article_variantid=" + encodeURI(elmProductIDInputField.value);

	location.href = url;
}


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,menubar=no,toolbar=no,location=no,resizable=no,scrollbars=yes,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 TurnHoverInfoScriptingOn() {
    if (document.layers) {
        document.captureEvents(Event.MOUSEMOVE);
    }
    document.onmousemove = moveDiv;
}



function showInfo(elem)
{
  if(info == null)initInfo();
  info.show(elem);
}

function hideInfo(elem)
{
  if(info == null)initInfo();
  info.hide(elem);
}

function initInfo()
{
  info = new InfoDiv();
  info.setClipping(0,0,-1,-1);
  info.enableFollowMouse(true);
}

function moveDiv(e)
{
	var eventX = (document.all) ? event.clientX : e.pageX;
	var eventY = (document.all) ? event.clientY : e.pageY;
	if(document.all) {
		eventX += getScrollLeft()
		eventY += getScrollTop()
	}
	if(info!=null)info.moveVisible(eventX, eventY)
}

function insertPDSImage(elemId, imagePath)
{
    //container = getElementsByClassName("page", "div")[0];
    container = $("div.page")[0];
	var img = document.createElement("img");
	var imgSrc = document.createAttribute("src");
	imgSrc.nodeValue = imagePath;
	var imgId = document.createAttribute("id");
	imgId.nodeValue = elemId;	
	img.setAttributeNode(imgSrc);
	img.setAttributeNode(imgId);

	try
	{
		var imgStyle = document.createAttribute("style");
		imgStyle.nodeValue="position:absolute;right:0pt;bottom:22px;display:none";
		img.setAttributeNode(imgStyle);
	}
	catch(e)
	{
		
		img.style.position = "absolute";
		if (isIE6)
		{
			img.style.right = "-1px";
			img.style.bottom = "21px";
		}
		else
		{
			img.style.right = "0px";
			img.style.bottom = "22px";
		}
		img.style.display = "none";
		img.style.border = "none";
	}

	container.appendChild(img);
	return img;
}

function highlightPDSImage(show) {
    return;
}

function openLoadingOptions(url) {
    //debug
    //url = 'https://shopprev.porsche.com/germany/beladungsvarianten/';
    initOverlay();
    var layerId = "loadingOptionsWrapper";

    var xOffset = 0;
    var yOffset = 0;

    // inject content
    $(document.body).append("<div id=\"" + layerId + "\"><div class=\"closeButton\" id=\"closeButtonLayer\"><img src=\"/Images/close-button.gif\" alt=\"[X]\" /></div><iframe class=\"layerContent\" src=\"" + url + "\"></iframe></div>");
    // setup close button functionality
    $("#closeButtonLayer").click(function() { closePDDSLayer(layerId); }).hover(function() { $(this).css("cursor", "pointer") }, function() { $(this).css("cursor", "auto") });

    // adjust size and position
    var w = $("#" + layerId).width();
    var h = $("#" + layerId).height();
    var winSize = getWindowSize();
    var _left = Math.floor((winSize.x - w) / 2) + xOffset;
    if (_left <= 0) _left = 0;
    var _top = Math.floor((winSize.y - h) / 2) + yOffset;
    if (_top <= 30) _top = 30;
    $("#" + layerId).css({ "left": _left + "px", "top": _top + "px" })

    // show time
    //$('#' + layerId).css("display", "block");
    $('#' + layerId).fadeIn("fast");
 
}

function closePDDSLayer(id) {
    $("#" + id).fadeOut("fast", function() { $("#TB_overlay").remove(); $("#TB_HideSelect").remove(); $(this).remove() });
}



// Um den Hintergrund abzufaden und nicht klickbar zu machen.
function initOverlay() {
    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
        $(document.body, "html").css({ height: "100%", width: "100%" });
        $("html").css("overflow", "hidden");
        if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
            $(document.body).append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div>");
        }
    } else {//all others
        if (document.getElementById("TB_overlay") === null) {
            $(document.body).append("<div id=\"TB_overlay\"></div>");
        }
    }

    if (tb_detectMacXFF()) {
        $("#TB_overlay").addClass("TB_overlayMacFFBGHack"); //use png overlay so hide flash
    } else {
        $("#TB_overlay").addClass("TB_overlayBG"); //use background and opacity
    }
}

function tb_detectMacXFF() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
        return true;
    }
}

function getWindowSize() {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    var size = new Object();
    size.x = myWidth;
    size.y = myHeight;
    return size;
}




