function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+'\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+'\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+'  '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+'\n'; }
  } if (errors) alert('Dit is geen geldig e-mailadres.\nProbeer nog eens');
  document.MM_returnValue = (errors == '');
}

function SelectForm(name,bool)
{
    var object = document.getElementById(name);

    for (var i=0;i<object.options.length;i++)
    {
        object.options[i].selected = bool;
    }

    return true;
}

function LayerHandler()
{
    clearTimeout(timeOut);

    var i, j = 0, object, arguments = LayerHandler.arguments;

    for (i=0;i<activeLayers.length;i++)
    {
        if ((object = MM_findObj(activeLayers[i])) != null)
        {
            object.style.visibility = 'hidden';
        }
    }

    activeLayers.length = 0;

    for (i=0;i<(arguments.length-1);i+=5)
    {
        if ((object = MM_findObj(arguments[i])) != null)
        {
            object.style.visibility = (arguments[i+1] ? 'visible' : 'hidden');
            arguments[i+1] && arguments[i+2] && (activeLayers[j++] = arguments[i]);

            var x = is_nav ? arguments[i+3].x : arguments[i+3].offsetLeft;
            var y = is_nav ? arguments[i+3].y : arguments[i+3].offsetTop;

            object.style.left = x + arguments[i+3].width + 'px';
            object.style.top = y + 'px';
        }
    }
}

// Debug stuff

function logMessage()
{
    var Message = logMessage.arguments.length

    if (DebugWindow == null)
    {
        // Create
        DebugWindow = document.createElement('div');
        DebugWindow.id = "DebugWindow";

        // Style
        DebugWindow.style.position = "absolute";
        DebugWindow.style.width = "400px";
        DebugWindow.style.left = "800px";
        DebugWindow.style.top = "10px";
        DebugWindow.style.backgroundColor = "yellow";
        DebugWindow.style.border = "1px solid orange";
        DebugWindow.style.padding = "10px";

        document.body.appendChild(DebugWindow);
    }

    for (var Iterator = 0 ; Iterator < logMessage.arguments.length ; Iterator++)
    {
        var LogEntry = document.createElement('div');
        LogEntry.appendChild(document.createTextNode(logMessage.arguments[Iterator]));

        DebugWindow.appendChild(LogEntry);
    }
}
var DebugWindow = null;

// Products stuff

function SelectPrice(counter,object,bool)
{
    if (object.options.length > 0)
    {
        var list = new Array(); list = object.options[object.selectedIndex].value.split('|');
        var increment = list[5];
        var shipping = list[4];
        var discount = list[3];
        var priceOld = list[2];
        var price = list[1];
    }
    else
    {
        var price = priceOld = discount = shipping = 0; var increment = '';
    }

    document.getElementById("price" + counter).value = FormatNumber(priceOld);

    RegisterPrice(counter,price,priceOld,discount,shipping,increment);
    bool && CalculateTotal();
}

function RegisterPrice(title,counter,price,priceOld,discount,shipping,increment)
{
    var ProductEntry = new Product();
    ProductEntry.ID = counter;
    ProductEntry.Title = title;
    ProductEntry.Price = price;
    ProductEntry.PriceOld = priceOld;
    ProductEntry.Discount = discount;
    ProductEntry.Shipping = shipping;
    ProductEntry.Increment = eval("new Array(" + increment + ");");

    var Collection = Basket.AddProduct(ProductEntry);
}

function ProductCollection()
{
    this.Collection = new Array();

    this.IsValidProduct = function(Product)
    {
        for (var Property in Product)
        {
            if (typeof Product[Property] == undefined)
                return false
        }
        return true;
    }

    this.AddProduct = function(Product)
    {
        if (!this.IsValidProduct(Product))
        {
            alert("Incomplete product data specified");
            return;
        }

        Product.UpdateQuantity();
        this.Collection.push(Product);
    }

    this.GetProductPosition = function(Product, Collection)
    {
        if (!Collection)
            Collection = this.Collection;

        for (var Iterator = 0 ; Iterator < Collection.length ; Iterator++)
        {
            if (Collection[Iterator].ID == Product.ID)
                return Iterator;
        }
        return null;
    }

    this.UpdateQuantities = function(Pieces)
    {
        for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
            this.Collection[Iterator].UpdateQuantity(Pieces)
    }

    this.GetTotal = function()
    {
        var Total = 0;
        for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
            Total += this.Collection[Iterator].GetTotal();

        return Total;
    }

    this.GetCount = function(Unique)
    {
        var Count = 0;
        for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
        {
            if (Unique && this.Collection[Iterator].Quantity > 0)
            {
                Count++;
            }
            else
            {
                Count += this.Collection[Iterator].Quantity;
            }
        }
        return Count;
    }

    this.GetCollection = function(Seperate)
    {
        if (!Seperate)
        {
            return this.Collection;
        }

        var Collection = new Array();
        for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
        {
            for (var IQuantity = 0 ; IQuantity < this.Collection[Iterator].Quantity ; IQuantity++)
            {
                Collection.push(this.Collection[Iterator].Clone());
            }
        }
        return Collection;
    }

    this.GetCountryShipping = function(GetIfOtherCountry)
    {
        if (document.getElementById('country') != null)
        {
            var CountryElement = document.getElementById("country");
            // 0 = ID, 1 = Other, 2 = Price
            var Data = CountryElement.options[CountryElement.options.selectedIndex].value.split("|");

            return (GetIfOtherCountry)? Data[1] : Data[2];
        }
        return 0;
    }

    this.GetShipping = function()
    {
        var Shipping = this.GetCountryShipping();

        for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
        {
            if (this.Collection[Iterator].Quantity > 0)
            {
                Shipping *= this.Collection[Iterator].Shipping;
            }
        }

        return Shipping;
    }

    this.GetDiscount = function()
    {
        // 10 Euro korting coupon
        /*
        if (document.getElementById("couponYes").checked)
        {
            return 10; // 10 euro korting van coupon
        }
        */

        // Zomeractie 2008
        /*
        if (document.getElementById('summerDiscountLabel'))
        {
            var basketTotal = 0;
            var productCount = 0;

            for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
            {
                if (this.Collection[Iterator].Quantity > 0
                    && this.Collection[Iterator].GetOffer() == 0)
                {
                    basketTotal += this.Collection[Iterator].Price * this.Collection[Iterator].Quantity;
                    productCount++;
                }
            }

            // Contoleer of we meer dan 1 uniek product in de mand hebben zitten
            if (productCount > 1)
            {
                // Wijzig het label van de actie
                document.getElementById('summerDiscountLabel').innerHTML = 'Zomeractie korting (20%)';

                // Bereken 20% op de huidige prijs
                return Math.round(0.20 * basketTotal * 100) / 100;
            }
            else
            {
                // Wijzig het label van de actie
                document.getElementById('summerDiscountLabel').innerHTML = 'Zomeractie korting (15%)';

                // Bereken 15% op de huidige prijs
                return Math.round(0.15 * basketTotal * 100) / 100;
            }
        }
        */

        // Elk 2e Sleepzz product voor 50% (22-09-2008)
        // Doorloop alle niet-Sleepzz en niet-Atroflex producten en bereken de standaard korting
        /*
        var Discount = 0;
        
        for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
        {
            if (this.Collection[Iterator].Quantity > 0)
            {
                if (!this.Collection[Iterator].Title.match(/^Atroflex /i))
                {
                    // Bereken voor de overige producten de standaard korting
                    Discount += this.Collection[Iterator].GetDiscount();
                }
            }
        }
        */

        // Goedkoopste product gratis actie
        /*
        if ((obj = document.getElementById("firstItemFreeYes")) != undefined
            && obj.checked)
        {
            var lowestPrice = 0;

            for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
            {
                if (this.Collection[Iterator].Quantity > 0)
                {
                    if (lowestPrice == 0
                        || this.Collection[Iterator].Price < lowestPrice)
                    {
                        lowestPrice = this.Collection[Iterator].Price;
                    }
                }

            }

            // Actie is alleen geldig als we meer dan 1 product bestellen
            if (Basket.GetCount(true) > 1)
            {
                return lowestPrice;
            }
            else
            {
                return 0;
            }
        }
        else
        {
        }
        */

        var Discount = 0;

        // Januarikorting (15% korting bij 1 of 2 producten, 20% korting bij 3 producten of 25% korting bij 4 producten)
        /*
        if (document.getElementById("januaryDiscount").checked)
        {
            return this.getJanuaryDiscountPercentage() * this.GetTotal();
        }
        */

        // Bereken de standaard discount
        var Discount = 0;
        for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
        {
            Discount += this.Collection[Iterator].GetDiscount();
        }
        return Discount;
    }
	
	this.getJanuaryDiscountPercentage = function(verbose)
	{
		if (verbose)
		{
			return this.getJanuaryDiscountPercentage() * 100;
		}
        switch (this.GetCount())
        {
            case 0: return 0;
            case 1:
            case 2: return 0.15;
			case 3: return 0.2;
        }           
        return 0.25;
	}

    this.GetAtroflexDiscount = function()
    {
        // Elk 2e atroflex product voor 50% (22-09-2008)
        var atroflexPrices = new Array();
        var atroflexQuantity = 0;
        var Discount = 0;

        // Doorloop alle atroflex producten
        for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
        {
            if (this.Collection[Iterator].Quantity > 0)
            {
                if (this.Collection[Iterator].Title.match(/^atroflex /i) && !this.Collection[Iterator].Title.match(/^atroflex Melatonine 625$/i))
                {
                    // Gebruik voor dit artikel altijd de oude prijs, voorkom extra korting
                    this.Collection[Iterator].Price = this.Collection[Iterator].PriceOld;

                    // Voeg de prijs van het product toe aan de stack
                    for (var iPrice = 0; iPrice < this.Collection[Iterator].Quantity; iPrice++)
                    {
                        atroflexPrices.push(this.Collection[Iterator].Price);
                    }
                    atroflexQuantity += this.Collection[Iterator].Quantity;
                }
            }
        }

        // Sorteer de prijzen, zodat de laagste prijzen bovenaan staan
        atroflexPrices.sort(function(a,b){return (a - b)});

        var atroflexDiscountItems = Math.floor(atroflexQuantity / 2);

        for (var iProduct = 0; iProduct < atroflexDiscountItems; iProduct++)
        {
            // Reken voor de goedkoopste producten 50% korting
            Discount += atroflexPrices.shift() * 0.50;
        }

        return Discount;
    }

    this.GetOffer = function()
    {
        var Offer = 0;
        for (var Iterator = 0 ; Iterator < this.Collection.length ; Iterator++)
            Offer += this.Collection[Iterator].GetOffer();

        return Offer;
    }

    // Temp
    this.ShowDiscountType = function(Type)
    {
        var Element = document.getElementById("regulars");
        if (Element != undefined)
        {
            var DiscountTypes = new Array();

            var Message = DiscountTypes[Type];
            if (Message != undefined && Element.innerHTML != Message)
            {
                Element.innerHTML += Message;
            }
        }
    }

    this.GetComboCount = function(Collection)
    {
        if (!Collection)
            Collection = this.GetCollection(true);

        var Map = new Array();
        for (var Iterator = 0 ; Iterator < Collection.length ; Iterator++)
        {
            Collection[Iterator].Combined = false;
            var ProductMap = new Array(Collection[Iterator]);

            for (var IReverse = Collection.length - 1 ; IReverse > Iterator ; IReverse--)
            {
                if (Collection[IReverse].ID != Collection[Iterator].ID)
                    ProductMap.push(Collection[IReverse]);
            }
            Map.push(ProductMap);
        }

        var Count = 0;
        var LastCombo;

        while (LastCombo == undefined || LastCombo.length > 0)
        {
            var LastCombo = new Array();
            for (var IMap = 0 ; IMap < Map.length ; IMap++)
            {
                var UsedInLastCombo = false;
                for (var Iterator = 0 ; Iterator < LastCombo.length ; Iterator++)
                {
                    if (LastCombo[Iterator] == Map[IMap][0].ID)
                        UsedInLastCombo = true;
                }

                if (!Map[IMap][0].Combined && !UsedInLastCombo && Map[IMap].length > 1)
                {
                    for (var Iterator = 1 ; Iterator < Map[IMap].length ; Iterator++)
                    {
                        if (!Map[IMap][Iterator].Combined)
                        {
                            Map[IMap][0].Combined = Map[IMap][Iterator].Combined = true;
                            LastCombo = [Map[IMap][0].ID, Map[IMap][Iterator].ID];
                            Count++;
                            break;
                        }
                    }
                }
            }
        }
        return Count;
    }

    this.GetComboDiscount = function(Percentage)
    {
        var Collection = this.GetCollection(true);
        var ComboCount = this.GetComboCount(Collection);

        if (ComboCount > 0)
        {
            var DiscountProducts = new Array();
            for (var IDiscount = 0 ; IDiscount < ComboCount ; IDiscount++)
            {
                var HighestProduct = undefined;
                for (var Iterator = 0 ; Iterator < Collection.length ; Iterator++)
                {
                    if (HighestProduct == undefined || Collection[Iterator].PriceOld > HighestProduct.PriceOld)
                        HighestProduct = Collection[Iterator];
                }

                var Position = this.GetProductPosition(HighestProduct, Collection);
                DiscountProducts.push(Collection[Position]);
                Collection.splice(Position, 1);
            }

            var Discount = 0;
            for (var Iterator = 0 ; Iterator < DiscountProducts.length ; Iterator++)
                Discount += DiscountProducts[Iterator].PriceOld * (Percentage / 100);

            return Discount;
        }
        return 0;
    }
}

function Product()
{
    this.ID;
    this.Title;
    this.Price;
    this.PriceOld;
    this.Discount;
    this.Shipping;
    this.Increment;

    this.Quantity = 0;

    this.GetProductElement = function(Identifier)
    {
        var Element = document.getElementById(Identifier + this.ID);
        return (typeof Element != undefined)? Element : null;
    }

    this.UpdateQuantity = function(Pieces)
    {
        var QuantityElement = this.GetProductElement("quantity")
        if (Pieces != undefined)
            this.Quantity = QuantityElement.value = Pieces;
        else if (!QuantityElement.value)
            this.UpdateQuantity(0);
        else
            this.Quantity = Math.abs(parseInt(QuantityElement.value));
    }

    this.GetTotal = function()
    {
        var Total = this.Quantity * this.PriceOld;
        this.GetProductElement("subtotal").value = FormatNumber(Total);
        return Total;
    }

    this.GetOffer = function()
    {
        return Math.abs(this.PriceOld - this.Price) * this.Quantity;
    }

    this.GetDiscount = function()
    {
        // Gebruik de kortingsstaffel, indien aanwezig
        if (this.Increment.length && this.Quantity > 0)
        {
            return this.Increment[
                Math.min(
                    Math.max(
                        this.Quantity - 1,
                        0
                    ),
                    this.Increment.length - 1
                )];
        }
        else
        {
            return this.Quantity * this.Discount;
        }
    }

    this.Clone = function()
    {
        var Clone = new this.constructor();
        for (var Property in this)
            Clone[Property] = this[Property];

        return Clone;
    }
}

var Basket = new ProductCollection();

// 10 Euro korting coupon
//function showHideDiscount()
//{
//  if (document.getElementById('couponYes').checked)
//  {
//      document.getElementById('couponPriceContainer').style.visibility = "visible";
//      document.getElementById('couponPrice').value = "10.00";
//      document.getElementById('discountPriceContainer').style.visibility = "hidden";
//  }
//  else
//  {
//      document.getElementById('couponPriceContainer').style.visibility = "hidden";
//        document.getElementById('discountPriceContainer').style.visibility = "visible";
//  }
//}
//
//// 10 Euro korting coupon
//function enableDisableCoupon(total)
//{
//  if (total < 25)
//  {
//        document.getElementById('couponYes').disabled = true;
//      document.getElementById('couponLabel').style.color = 'gray';
//
//      if (document.getElementById('couponYes').checked)
//      {
//            document.getElementById('couponNo').checked = true;
//          showHideDiscount();
//        }
//  }
//  else
//  {
//      document.getElementById('couponYes').disabled = false;
//      document.getElementById('couponLabel').style.color = '#000';
//  }
//}

function ajustJanuaryDiscount()
{
	var radioElement = document.getElementById("januaryDiscount");
    if (radioElement && radioElement.checked)
    {
        document.getElementById("januaryDiscountPercentage").innerHTML = Basket.getJanuaryDiscountPercentage(true); 
        document.getElementById("januaryDiscountPrice").value = FormatNumber(Basket.GetDiscount());
    }
}

// Goedkoopste product gratis actie
function showHideDiscount()
{	
  /*
  if (obj = document.getElementById('firstItemFreeYes'))
  {
      if (obj.checked)
      {
          document.getElementById('firstItemFreePriceContainer').style.visibility = "visible";
          document.getElementById('firstItemFreePrice').value = FormatNumber(Basket.GetDiscount());
          document.getElementById('discountPriceContainer').style.visibility = "hidden";
      }
      else
      {
          document.getElementById('firstItemFreePriceContainer').style.visibility = "hidden";
          document.getElementById('discountPriceContainer').style.visibility = "visible";
      }
  }
  */
}

function CalculateTotal(reset)
{
    Basket.UpdateQuantities((reset)? 0 : undefined);

    var Count = Basket.GetCount();
    var Total = Basket.GetTotal();

    // Elk 2e Sleepzz product voor 50% (22-09-2008)
    // var AtroflexDiscount = Basket.GetAtroflexDiscount();

    var Offer = Basket.GetOffer();

    // var Discount = Basket.GetComboDiscount(50); // 50% korting elk duurste 2e product
    // var HasComboDiscount = (Discount > 0);

    // 10 Euro korting coupon
//    enableDisableCoupon(Total);

    // Goedkoopste product gratis actie
    // showHideDiscount();

//    // Als geen combinatie korting heeft, de oude vaste % korting toepassen
//    if (!HasComboDiscount)
//    {
        Basket.ShowDiscountType(0);
        Discount = Basket.GetDiscount();
//    }
//    else
//        Basket.ShowDiscountType(1);

    // Januari actie (decomment)
    var DiscountTotal = Offer + Discount;
//    var DiscountTotal = Discount;
 
    // + AtroflexDiscount;
    var SubTotal = Total - DiscountTotal;

//    var Shipping = (HasComboDiscount)? 0 :
//        (Count > 0 && (SubTotal < 60 || !Basket.GetCountryShipping(true)))? Basket.GetShipping() : 0;
    //var Shipping = (Count > 0 && (SubTotal < 60 || !Basket.GetCountryShipping(true)))? Basket.GetShipping() : 0;
    var Shipping = (Count > 0 && (Count < 2 || Basket.GetCountryShipping(true)) != 0)? Basket.GetShipping() : 0;

    document.getElementById("total1").value = FormatNumber(Total);
	
	// Januari actie (decomment)
    document.getElementById("offer").value = FormatNumber(Offer);

    if (document.getElementById("discount"))
    {
        document.getElementById("discount").value = FormatNumber(Discount);
    }
    /*
    if (document.getElementById("atroflexDiscount"))
    {
        document.getElementById("atroflexDiscount").value = FormatNumber(AtroflexDiscount);
    }
    */
	
	// ajustJanuaryDiscount();
	
    document.getElementById("total2").value = FormatNumber(DiscountTotal);
    document.getElementById("shipping").value = FormatNumber(Shipping);

    document.getElementById("total3").value = FormatNumber(SubTotal + Shipping);

    return Count;
}

function FormatNumber(number)
{
    major   = Math.floor(number);
    minor   = Math.round(100*(number - Math.floor(number))); minor == 100 && major++ && (minor = 0);

    return major + "." + Math.floor(minor/10) + Math.floor(minor%10);
}

function SetCookie(name,value,expires)
{
    document.cookie = name + "=" + value + ";expires=" + new Date(expires*1000);
}

function HandleKey(name,object,max)
{
    if (object.value.match(/^\d+$/))
    {
        object.value = (max > 0 ? Math.min(object.value,max) : object.value/1);
        SetCookie(name,object.value,".(time() + 3*24*3600).");
        CalculateTotal();
    }
    else
    {
        object.value = 0;
    }
}

function SubmitList(enull,eint)
{
    var total = document.getElementById("total1").value;
    var country = (document.getElementById("country") ? document.getElementById("country").value.split("|") : new Array(0,0));
    var other = country[1], shipping = country[2];

    if (total > 0)
    {
        if (other > 0 && total < 50)
        {
            alert(enull);

            return false;
        }
        else
        {
            return true
        }
    }
    else
    {
        alert(eint);

        return false;
    }
}

function openWindow(link,name,features,position,width,height,views)
{
    var top = (position == "center" ? (screen.height - height)/2 : (position.match(/^top/) ? 0 : screen.height - height));
    var left = (position == "center" ? (screen.width - width)/2 : (position.match(/left$/) ? 0 : screen.width - width));

    features += (features ? "," : "") + "top=" + top + ",left=" + left + ",width=" + width + ",height=" + height;

    var myWindow = window.open(link,name,features);

    link && SetCookie("cms[" + name + "][views]",++views,(new Date()).getTime()/1000 + 365*24*3600);

    return myWindow;
}

function PopUp(title,image,width,height)
{
    myWindow = openWindow('',(new Date()).getTime(),'','topleft',width,height);

    myWindow.document.write("<HTML>\n<HEAD>\n<TITLE>" + title + "</TITLE>\n</HEAD>\n<BODY>\n<CENTER>\n<A HREF=\"javascript: window.close();\">\n<IMG SRC='" + image + "' BORDER=0>\n</A></CENTER>\n</BODY>\n</HTML>\n");
}

// geuractie

function HandleScents(mode)
{
    for (var i=1;i<=12;i++)
    {
        document.getElementById('scentID' + i) && (document.getElementById('scentID' + i).disabled = mode);
    }
}
