// JavaScript Document

var divVisible = 0;
var divTimeout = 0;
var divSubTimeout = 0;
var divStockTimeout = 0;
var menuHeight = 3;
var menuWidth = 4;
var divCatVisible = 0;
var divCatVisible2 = 0;
var lastmenu;
var lastSubMenu;
var lastDivMenuVisible = 0;
var selectedCat;

var bareboneConfigDdlsString;

function setSWF(height, width, filename, bgcolor) {
    document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="' + width + '"  height="' + height + '" id="banner" align="middle">');
	document.write('<param name="allowScriptAccess" value="sameDomain" />');
	document.write('<param name="movie" value="' + filename + '" />');
	document.write('<param name="quality" value="high" />');
	document.write('<PARAM NAME="WMODE" VALUE="transparent">');
	document.write('<param name="bgcolor" value="' + (bgcolor == null ? '' : bgcolor) + '" />');
	document.write('<embed src="' + filename + '"  quality="high" bgcolor="' + (bgcolor == null ? '' : bgcolor) + '" PWMODE="transparent" width="' + width + '"  height="' + height + '"  name="banner" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	document.write('</object>');
}

function bareboneConfigInit(obj)
{
  
  bareboneConfigDdlsString = obj;
}


    
function bareboneConfigSel(obj)
{
	var bareboneConfigDdls = bareboneConfigDdlsString;

	var prodPrice = parseFloat(document.getElementById('productPriceHF').value);
	var prodPrice2 = parseFloat(document.getElementById('productPrice2HF').value);
	var vat = prodPrice / prodPrice2;
	for (var i=0;i<bareboneConfigDdls.length;i++)
	{
		var ddl = document.getElementById(bareboneConfigDdls[i]);
		if(ddl) prodPrice += parseFloat(ddl.options[ddl.selectedIndex].value.split(';')[1]);
	}

	var priceElement = document.getElementById('price');
	var price2Element = document.getElementById('price2');
	priceElement.innerHTML = priceElement.innerHTML.replace(/[.,\d]+/, formatNumber(prodPrice, 2));
	price2Element.innerHTML = price2Element.innerHTML.replace(/[.,\d]+/, formatNumber(prodPrice / vat, 2));
	
	//Ajustar o simulador de crédito
	var creditPriceLabel = document.getElementById('creditSimulatorProductPriceLabel');
	var creditPrice = document.getElementById('creditSimulatorProductPrice');
	var creditEntrance = document.getElementById('financingEntrance');
	if(creditPriceLabel && creditPrice && creditEntrance)
	{
		creditPriceLabel.innerHTML = creditPriceLabel.innerHTML.replace(/[.,\d]+/, formatNumber(prodPrice, 2));
		creditPrice.value = creditPrice.value.replace(/[.,\d]+/, formatNumber(prodPrice, 2));
		
	}
}


function MM_jumpMenu2(targ,selObj,restore)
{ 
    selectedCat = selObj.options[selObj.selectedIndex].value;
    
    if (selectedCat == "#")
        hideDiv('jumpMenu');
    else   
        showDiv('jumpMenu');
}

function stripSpecialChars(string) {
	marks = "/:?'<>|\\";
	str = string;

	for (i = 0; i < marks.length; i++) {

		mark = marks.charAt(i);

		while (str.indexOf(mark) != -1) {
			point = str.indexOf(mark);
			first_part = str.substring(0, point);
			second_part = str.substring(point + 1, str.length);
			str = first_part + second_part;
		}
	}
	return str;
}

function redirectToPDF(targ, url) {
    
    url = selectedCat+url+".pdf";
    url = stripSpecialChars(url);
    
    window.open("products_pdfs/"+url);
}

function showDivSubMenu(obj, div) {       	
    hideDivNow(lastSubMenu);
    clearTimeout(divSubTimeout);
    if (document.getElementById && document.getElementById(div)!= null)
	{   
		var style2 = document.getElementById(div).style;
		var leftMargin = -10;
		var topMargin = 23;
			
	    if (style2.display == "none" || style2.display == "")
		{
			style2.display = "block";
		}
		else
		{
			style2.display = "none";
		}
		lastSubMenu = div;
		menuPos =  findPos (obj); // (mouseX(event) - leftMargin);
		style2.left = (menuPos[0] + leftMargin) + "px";
		style2.top = (menuPos[1] + topMargin) + "px";
	}
}

function hideDivSubMenu(div) {
  divSubTimeout = setTimeout('hideDivNow("'+div+'")',1000);
}

function showDivStockDescription(obj, div) {              
    obj = document.getElementById(obj);
    
    if (document.getElementById && document.getElementById(div)!= null)
	{   
		var style2 = document.getElementById(div).style;
		var leftMargin = 100;
		var topMargin = -10;
		style2.display = "block";	
		menuPos =  findPos (obj); // (mouseX(event) - leftMargin);
		style2.left = (menuPos[0] + leftMargin) + "px";
		style2.top = (menuPos[1] + topMargin) + "px";
	}
}

function hideDivStockDescription(div) {
    clearTimeout(divStockTimeout);
    if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		style2.display = "none";
	}
}

function showMainDiv(div, catId)
{
    hideMainDiv(lastDivMenuVisible);
    if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		style2.display = "block";
		style2.width = (155 * menuWidth)-35+"px";
		style2.height = (90 * menuHeight)-40+"px";
		divCatVisible = catId;
		lastDivMenuVisible = div;
		showCat(catId);
	} 
}

function showSubMainDiv(div, mainCat)
{
    hideDivNow(divCatVisible2);
    if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		style2.display = "block";				
		
		subHeight = document.getElementById(div).offsetHeight;
		mainHeight = document.getElementById(mainCat).offsetHeight;
		
	    topMargin = Math.abs(((mainHeight-40) - subHeight) /2);	
		style2.width = (155 * (menuWidth-1))+"px";
		
		style2.marginTop = topMargin;	
		divCatVisible2 = div;
		showCat(div);
	} 
}

function showCat(div)
{
    if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		style2.display = "block";
	}
}

function hideMainDiv(div)
{
    hideDivNow(div); // main 
	hideDivNow(divCatVisible); // categories
	hideDivNow(divCatVisible2); // subcategories
}

function hideSubMainDiv(div)
{
    hideDivNow(div); // main 
	hideDivNow(divCatVisible2); // categories
}


function showHideDiv(div)
{
	if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		if (style2.display == "none" || style2.display == "")
		{
			style2.display = "block";
		}
		else
		{
			style2.display = "none";
		}
	}
}

function hideDivNow(div) 
{    
	if (document.getElementById && document.getElementById(div)!= null)
	{
	    divVisible = 0;
		var style2 = document.getElementById(div).style;
		style2.display = "none";	
	}
}


function showMenuDiv(div)
{
 clearTimeout(divTimeout);
 if (!divVisible) // only if div is not visible
 {
    divVisible = 1;  
        
	if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		style2.display = "block";
	}
 }
}

function showMenu(obj, div)
{   

    obj = obj.offsetParent;
    if (lastmenu == div)
       clearTimeout(divTimeout); 
    else 
       hideDivNow(lastmenu);
   
	if (!divVisible) // only if div is not visible
    {      
        divVisible = 1; // flags div as visible
        lastmenu = div; // stores last menu visited (this one)
        
	    if (document.getElementById)
	    {
		    var leftMargin = 160;
		    var topMargin = -2;
		    var style2 = document.getElementById(div).style;
		    style2.display = style2.display ? "" : "block";
		    menuPos =  findPos (obj); // (mouseX(event) - leftMargin);
		    style2.left = (menuPos[0] + leftMargin) + "px";
		    style2.top = (menuPos[1] + topMargin) + "px";
	    }
	}
}

function hideMenuDiv(div)
{
   divTimeout=setTimeout('hideDivNow("'+div+'")',500);
}

function hideDiv(div)
{
	if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		style2.display = "none";
	}
}

function showDiv(div)
{
	if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		style2.display = "block";
	}
}

function MM_jumpMenu(targ,selObj,restore)
{ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
  
}

function showShippingMode(targ,selObj,restore)
{
	var sId = selObj.options[selObj.selectedIndex].value;
	for (i=0; i< selObj.options.length; i++)
	{
		var id = selObj.options[i].value;
		hideDiv("shippingDiv_" + id);	
		hideDiv("paymentDiv_" + id);	
	}
	if (sId != null && sId != "0")
	{
		showHideDiv("shippingDiv_" + sId);
		showHideDiv("paymentDiv_" + sId);

		if (sId == "1") // || sId == "2")
		{
		    var cartTotal = parseFloat(document.getElementById("cartTotalValue").value);
		    var pointsTotal = parseFloat(document.getElementById("pointsTotalValue").value);
		    
		    if ((cartTotal - pointsTotal) > 250)
		    {
		        document.getElementById("payment_" + sId).disabled = true;
		    }
		    else
		    {
		        document.getElementById("payment_" + sId).disabled = false;
		    }
		}
	}
	if (sId == "0")
	{
		showHideDiv("shippingDiv_0");
		showHideDiv("paymentDiv_0");
	}
}

function findPos(obj) {
	var posleft = postop = 0;
	if (obj.offsetParent)
	{
		posleft = obj.offsetLeft
		postop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			posleft += obj.offsetLeft
			postop += obj.offsetTop
		}
	}
	return [posleft,postop];
}

function validateOrder()
{	
	if (document.getElementById)
	{
		var shipping = document.getElementById("shipping");
		if(shipping == null || shipping.value == "0")
		{
			showHideDivRedBorder("orderStep_2")
			showHideDiv("orderStep_2_error");
			return false;
		}
		else
		{
			var shipping = document.getElementById("shipping");
			var destination = document.getElementById("destination_" + shipping.value);
			if(destination == null || destination.value == "-1")
			{
				showHideDivRedBorder("orderStep_3")
				showHideDiv("orderStep_3_error");
				return false;
			}	
			
			var radioPayment = document.forms["orderForm"].elements["payment_" + shipping.value];
			var flagClear = false;
			if (radioPayment.length == null)
			{
				if (radioPayment.checked == true)
				{
					flagClear = true;
				}
			}
			else
			{
				for(var i = 0; i < radioPayment.length; i++) 
				{
					var	payment = radioPayment[i];
					if (payment.checked == true)
					{
						flagClear = true;
					}
				}
			}
			
			if (flagClear == false)
			{
				showHideDivRedBorder("orderStep_4");
				showHideDiv("orderStep_4_error");
				return false;
			}
			
			var termsAndConditions = document.forms["orderForm"].elements["termsAndConditions"];
			if (termsAndConditions.checked != true)
			{
				showHideDivRedBorder("orderStep_5");
				showHideDiv("orderStep_5_error");
				return false;
			}
		}
	}
	return true;
}

function showHideDivRedBorder(div)
{
	if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		if (style2.border == null || style2.border == "")
		{
			style2.border = "solid 2px #FF0000";
		}
		else
		{
			style2.border = "";
		}
	}
}

function hideDivRedBorder(div)
{
	if (document.getElementById && document.getElementById(div)!= null)
	{
		var style2 = document.getElementById(div).style;
		style2.border = "";
	}
}

function cleanStepAllStepsErrors()
{
	hideDivRedBorder("orderStep_2");
	hideDiv("orderStep_2_error");
	hideDivRedBorder("orderStep_3");
	hideDiv("orderStep_3_error");
	hideDivRedBorder("orderStep_4");
	hideDiv("orderStep_4_error");
	hideDivRedBorder("orderStep_5");
	hideDiv("orderStep_5_error");
}

function formatNumber(number, decimalPlaces)
{
    if (decimalPlaces == null)
    {
        decimalPlaces = 2;
    }

    var temp = number.toFixed(decimalPlaces).replace(".", ",");
    var res = "";

    var idx = ((temp.indexOf(",") == -1)? temp.length : temp.indexOf(","));

    for (var i = 0; i < idx; i++)
    {
        if (((idx - i) % 3) == 0 && i != 0)
        {
            res += ".";
        }
        res += temp.charAt(i);
    }

    res += ",";
    
    for (var i = idx + 1; i < temp.length; i++)
    {
        res += temp.charAt(i);
    }

    var zeros = new Array(decimalPlaces);
    for (var i = 0; i < (decimalPlaces + 1); i++)
    {
        var sZeros = "";
        for (var j = 0; j < (decimalPlaces - i); j++)
        {
            sZeros += "0";
        }
        zeros[i] = sZeros;
    }
    res += zeros[temp.length - idx - 1];
    
    return res;
}

//To determine the price when selecting extras
function determineAndSetPrice(priceLabel, priceValue, rmaExpressValue, rmaExpressSelection, insuranceValue, insuranceSelection)
{
    var price = parseFloat(document.getElementById(priceValue).value.replace(",", "."));
    
    if (document.getElementById(rmaExpressSelection) != null && document.getElementById(rmaExpressSelection).checked)
    {
        price += parseFloat(document.getElementById(rmaExpressValue).value.replace(",", "."));
    }
    if (document.getElementById(insuranceSelection) != null && document.getElementById(insuranceSelection).checked)
    {
        price += parseFloat(document.getElementById(insuranceValue).value.replace(",", "."));
    }

    document.getElementById(priceLabel).innerHTML = formatNumber(price) + " &euro;";
}

function completeQueryString(aElem, keyValuePairs)
{
    var completion = "";

    if (keyValuePairs != null)
    {
        for (var i = 0; i < keyValuePairs.length; i += 2)
        {
            completion += "&" + keyValuePairs[i] + "=" + keyValuePairs[i + 1];
        }

        if (aElem.href.indexOf("?") == -1)
        {
            completion = completion.replace(/^&/, "?");
        }
    }
    
    setTimeout("window.location.href = \"" + aElem.href + completion + "\";", 0);
}

function recalculateCartTotals(checkbox)
{
    var cartTotal = parseFloat(document.getElementById("cartTotalValue").value.replace(".", "").replace(",", "."));
    var pointsTotal = parseFloat(document.getElementById("pointsTotalValue").value.replace(".", "").replace(",", "."));
    var pointsCouponIds = document.getElementById("availablePointsCouponIds").value.split(",");
    if (pointsCouponIds.length == 1 && pointsCouponIds[0] == "")
    {
        pointsCouponIds = [];
    }

    var usedPoints = 0;
    for (var i = 0; i < pointsCouponIds.length; i++)
    {
        if (document.getElementById("pointsCoupon" + pointsCouponIds[i] + "Check").checked)
        {
            usedPoints += parseFloat(document.getElementById("pointsCoupon" + pointsCouponIds[i] + "AvPoints").value.replace(",", "."));
        }
    }

    // It is not possible to use more points than the cart total.
    if (usedPoints > cartTotal)
    {
        showDiv("excessiveDiscountWarning");
        checkbox.checked = false;
        recalculateCartTotals(checkbox)
        return;
    }

    document.getElementById("cartTotalElem").innerHTML = formatNumber(cartTotal - usedPoints) + " &euro;";
    document.getElementById("pointsCouponDiscountTotalElem").innerHTML = formatNumber(usedPoints) + " &euro;";
    if (usedPoints == 0)
    {
        document.getElementById("pointsTotalElem").innerHTML = formatNumber(pointsTotal, 1);
    }
    else
    {
        document.getElementById("pointsTotalElem").innerHTML = formatNumber(0, 1);
    }
}

function addListener(element, type, handler, bubbling)
{
    bubbling = bubbling || false;
    if(window.addEventListener) // Standard
    {
        element.addEventListener(type, handler, bubbling);
        return true;
    }
    else if(window.attachEvent) // IE
    {
        element.attachEvent('on' + type, handler);
        return true;
    }
    else
    {
        return false;
    }
}

