var screwyBrowsers = new Array( 'Explorer');
var useFades = !screwyBrowsers.include( BrowserDetect.browser );

var topHeight = 360;

var cartContent = [];
var activeCategory = 'root';
var activeProduct = null;
var contentMode = true;
var shopMode = false;
var orderMode = false;
var contactMode = false;
var productsLoaded = false;
var jar = new CookieJar({
expires:3600,   // seconds
path: '/'
});

function initLayout() {
    loadShopLayout();
    showContentPanel();
    recalcLayoutTimed();

    $$('#menuHome', '#menuProducts', '#menuContact', '#menuDisclaimer').each(
        function(e) {
            e.onmouseover = shopMenuMouseOver;
            e.onmouseout = shopMenuMouseOut;
            e.style.cursor = 'pointer';
        }
    );
    
    $('menuHome').onclick = showContentPanel;
    $('menuProducts').onclick = showShopPanel;
    $('menuSearch').setOn = shopMenuMouseOver;
    $('menuSearch').setOff = shopMenuMouseOut;
    $('menuSearch').onclick = function() { $('menuSearchQuery').focus(); };
    $('menuSearchQuery').onfocus = function() { $('menuSearch').setOn(); };
    $('menuSearchQuery').onblur = function() { $('menuSearch').setOff(); };
    $('menuSearchQuery').onkeypress = function( event ) {
        if(!event) event = window.event;
        if( event.keyCode == 13 )
            loadSearch( this.value );
    }


    $('menuContact').onclick = showContactForm;

    new Effect.Fade( $('shopLoadingShader') );

    Droppables.add('shopCartArea', {
     accept: 'productDragable',
      onDrop: function(element) {
        Droppables.remove(element);
        addItemToCart();
      }
    });

}

function loadShopLayout() {
    for ( var el in shopLayoutSettings ) {
    try {
        if( typeof(shopLayoutSettings[el].background) != 'undefined' )
            $(el).style.background = shopLayoutSettings[el].background;
        if( typeof(shopLayoutSettings[el].opacity) != 'undefined' )
            $(el).setOpacity( shopLayoutSettings[el].opacity );
    }
    catch(e)
    {}
    }
}

function recalcLayoutTimed() {
    setTimeout( recalcLayout, 10 );
}

function recalcLayout() {
    winWidth = document.viewport.getWidth();
    winHeight = document.viewport.getHeight();
    if (winWidth < 1024) winWidth = 1024;
    if (winHeight < 768) winHeight = 768;
    bodyMargin = Math.round( 20 * Math.max( 1, (winWidth-1024) / 120 ) );
    showcaseItemHeight = 285;
    izitokoBarHeight = 35;
    menuBarHeight = 36;
    contentMenuWidth = 243;
    cartAreaWidth = 548;

    $('izitokoBar').setStyle( { 'height': izitokoBarHeight+'px', 'width':  '100%' } );
    $('topArea').setStyle( { 'top': izitokoBarHeight+'px', 'left': bodyMargin+'px', 'width': (winWidth-(bodyMargin*2))+'px', 'height': topHeight+'px' } );
    $('topBackground').setStyle( { 'top': izitokoBarHeight+'px', 'left': bodyMargin+'px', 'width': (winWidth-bodyMargin-bodyMargin)+'px', 'height': topHeight+'px' } );

    $('shopMenuBar').setStyle( { 'top': (izitokoBarHeight+topHeight)+'px', 'left': (bodyMargin-8)+'px', 'height': menuBarHeight+'px', 'width': (winWidth-(bodyMargin*2)+8+9)+'px' } );
    $('shopMenuBackground').setStyle( { 'top': (izitokoBarHeight+topHeight)+'px', 'left': bodyMargin+'px', 'height': menuBarHeight+'px', 'width': (winWidth-(bodyMargin*2))+'px' } );
    
    $('topShadeLeft').setStyle( { 'position': 'absolute', 'top': '0px', 'left': '0px', 'height': (topHeight-27)+'px' } );
    $('topShadeBottomLeft').setStyle( { 'position': 'absolute', 'top': (topHeight-27)+'px', 'left': '0px' } );
    $('topShadeBottom').setStyle( { 'position': 'absolute', 'top': (topHeight-27)+'px', 'left': '35px', 'width': (winWidth-(bodyMargin*2)-35-34)+'px' } );
    $('topShadeBottomRight').setStyle( { 'position': 'absolute', 'top': (topHeight-27)+'px', 'left': (winWidth-(bodyMargin*2)-34)+'px' } );
    $('topShadeRight').setStyle( { 'position': 'absolute', 'top': '0px', 'left': (winWidth-(bodyMargin*2)-34)+'px', 'height': (topHeight-27)+'px' } );
    
    $('showcaseArea').setStyle( { 'top': (topHeight - showcaseItemHeight)+'px', 'left': '35px', 'width': (winWidth-(bodyMargin*2)-35-34)+'px', 'height': (topHeight-27-(topHeight-showcaseItemHeight))+'px' } );
    $('showcaseTitle').setStyle( { 'top': '0px', 'left': '35px', 'width': (winWidth-(bodyMargin*2)-35-34)+'px', 'height': (topHeight-27)+'px' } );
    $('showcaseBackground').setStyle( { 'top': '0px', 'left': '35px', 'width': (winWidth-(bodyMargin*2)-35-34)+'px', 'height': (topHeight-27)+'px' } );

    if (!productsLoaded)
    {
        $('shopLogoContainer').setStyle( { 'marginTop': (topHeight/2) - ($('shopTitle').getHeight()) + 'px' } );
        $('shopTitle').setStyle( { 'top': (topHeight/2) - ($('shopTitle').getHeight()) + 'px', 'left': Math.round((winWidth-(bodyMargin*2)-35-34-$('shopTitle').getWidth())/2)+'px' } );
        $('shopSubTitle').setStyle( { 'top': (topHeight/2) -($('shopTitle').getHeight())+ ($('shopTitle').getHeight())+ 15 + 'px', 'left': Math.round((winWidth-(bodyMargin*2)-35-34-$('shopSubTitle').getWidth())/2)+'px' } );
    }
    else{
        $('shopTitle').setStyle( { 'top': '10px', 'left': Math.round((winWidth-(bodyMargin*2)-35-34-$('shopTitle').getWidth())/2)+'px' } );
        $('shopSubTitle').setStyle( { 'top': ($('shopTitle').getHeight()+15)+'px', 'left': Math.round((winWidth-(bodyMargin*2)-35-34-$('shopSubTitle').getWidth())/2)+'px' } );
    }
    $('shopContactForm').setStyle( { 'top': '0px', 'left': '0px', 'width': (winWidth-(bodyMargin*2))+'px' } );

    $('shopCartArea').setStyle( { 'top': '65px', 'left': '20px', 'width': (cartAreaWidth-40)+'px' } );
    $('shopCartBackground').setStyle( { 'top': '20px', 'left': '0px', 'width': cartAreaWidth+'px', 'height': ($('shopCartArea').getHeight() + 95 + 38)+'px' } );
    $('shopCartTop').setStyle( { 'top': '0px', 'left': '0px' } );
    $('shopCartMiddle').setStyle( { 'top': '95px', 'left': '0px', 'height': ($('shopCartArea').getHeight()) + 'px' } );
    $('shopCartBottom').setStyle( { 'top': ($('shopCartArea').getHeight() + 95) + 'px', 'left': '0px' } );
    
    $('shopProductArea').setStyle( { 'top': '60px', 'left': (cartAreaWidth+24)+'px', 'width': (winWidth-(bodyMargin*2)-cartAreaWidth-40)+'px' } );
    $('shopProductBackground').setStyle( { 'top': '19px', 'left': cartAreaWidth+'px', 'width': (winWidth-(bodyMargin*2)-cartAreaWidth)+'px' } );
    $('shopProductTopLeft').setStyle( { 'top': '0px', 'left': '0px' } );
    $('shopProductTopCenter').setStyle( { 'top': '0px', 'left': '190px', 'width': (winWidth-(bodyMargin*2)-cartAreaWidth-190-54)+'px' } );
    $('shopProductTopRight').setStyle( { 'top': '0px', 'left': ($('shopProductTopCenter').getWidth())+'px' } );
    $('shopProductMiddleLeft').setStyle( { 'top': '42px', 'left': '-190px', 'height': $('shopProductArea').getHeight()+'px' } );
    $('shopProductMiddleCenter').setStyle( { 'top': '42px', 'left': '0px', 'width': (winWidth-(bodyMargin*2)-cartAreaWidth-190-38)+'px', 'height': $('shopProductArea').getHeight()+'px' } );
    $('shopProductMiddleRight').setStyle( { 'top': '42px', 'left': (190+$('shopProductMiddleCenter').getWidth())+'px', 'height': $('shopProductArea').getHeight()+'px' } );
    $('shopProductBottomLeft').setStyle( { 'top': ($('shopProductArea').getHeight())+'px', 'left': '0px' } );
    $('shopProductBottomCenter').setStyle( { 'top': $('shopProductBottomLeft').style.top, 'left': '0px', 'width': (winWidth-(bodyMargin*2)-cartAreaWidth-190-54) + 'px' } );
    $('shopProductBottomRight').setStyle( { 'top': $('shopProductBottomLeft').style.top, 'left': (190+$('shopProductBottomCenter').getWidth())+'px' } );
    
    $('shopOrderPanel').setStyle( { 'top': '0px', 'left': cartAreaWidth+'px', 'width': (winWidth-(bodyMargin*2)-cartAreaWidth)+'px' } );

    if( contentMode )
        bottomHeight = Math.max( $('shopContentMenu').getHeight(), $('shopContentText').getHeight(), (winHeight-topHeight-menuBarHeight-izitokoBarHeight) );
    else if( shopMode )
        bottomHeight = Math.max($('shopCartBackground').getHeight() + 20, $('shopProductArea').getHeight()+ 20 + 42 + 55, (winHeight-topHeight-menuBarHeight-izitokoBarHeight) );
    else if( contactMode )
        bottomHeight = Math.max($('shopContactForm').getHeight() + 70 + 38, (winHeight-topHeight-menuBarHeight-izitokoBarHeight) );
    else
        bottomHeight = Math.max( $('shopCartBackground').getHeight()+20, $('shopOrderPanel').getHeight(), (winHeight-topHeight-menuBarHeight-izitokoBarHeight) );


    $('shopContentMenu').setStyle( { 'top': '0px', 'left': '0px', 'width': contentMenuWidth+'px', 'height': bottomHeight+'px' } );
    $('shopContentMenuItems').setStyle( { 'top': '0px', 'left': '0px', 'width': contentMenuWidth+'px', 'height': bottomHeight+'px' } );    
    $('shopContentText').setStyle( { 'top': '0px', 'left': contentMenuWidth+15+'px', 'width': (winWidth-(bodyMargin*2)-contentMenuWidth)-15 +'px' } );

    $('bottomArea').setStyle( { 'top': (topHeight+izitokoBarHeight+menuBarHeight)+'px', 'left': bodyMargin+'px', 'width': (winWidth-(bodyMargin*2))+'px' } );
    $('bottomBackground').setStyle( { 'top': (topHeight+izitokoBarHeight+menuBarHeight)+'px', 'left': bodyMargin+'px', 'width': (winWidth-(bodyMargin*2))+'px', 'height': bottomHeight+'px' } );
    
    //var menuComps = [ 'menuLeft', 'menuHome', 'menuProducts', 'menuSearch', 'menuSpacer', 'menuContact', 'menuDisclaimer', 'menuRight' ];
    
    var menuComps = [ 'menuLeft', 'menuHome', 'menuProducts', 'menuSearch', 'menuSpacer', 'menuContact', 'menuRight' ];
    var menuWidth = winWidth - (bodyMargin*2) + 8 + 9;
    var menuPos = 0;
    var menuContentWidth = 0;
    
    for( var n = 0; n < menuComps.length; n++ ) {
        if( menuComps[n] != 'menuSpacer' )
            menuContentWidth += $(menuComps[n]).getWidth();
    }
    
    for( var n = 0; n < menuComps.length; n++ ) {
        var el = $(menuComps[n]);
        el.setStyle( { 'position': 'absolute', 'top': '0px', 'left': menuPos+'px' } );

        if( menuComps[n] == 'menuSpacer' )
            el.setStyle( { 'width': (menuWidth - menuContentWidth - ((menuComps.length-1)*2)) + 'px' } );
        
        menuPos += el.getWidth();
        
        if( n < (menuComps.length-1) ) {
            el = el.next();
            el.setStyle( { 'position': 'absolute', 'top': '0px', 'left': menuPos+'px' } );
            menuPos += el.getWidth();
        }
    }
    $('mainborderleft').setStyle ({'position': 'absolute', 'height' : (bottomHeight + topHeight + menuBarHeight ) + 'px', 'left': bodyMargin-25 + 'px'});
    $('mainborderright').setStyle ({'position': 'absolute', 'height' : (bottomHeight + topHeight + menuBarHeight ) + 'px', 'left': winWidth-(bodyMargin) + 'px' });
}


function afterAjaxContent() {
    recalcLayoutTimed();
}

function shopMenuMouseOver() {
    $(this).down().style.visibility = 'hidden';
    $(this).down().next().style.visibility = 'visible';

    $(this).previous().down().style.visibility = 'hidden';
    $(this).previous().down().next().style.visibility = 'visible';

    $(this).next().down().style.visibility = 'hidden';
    $(this).next().down().next().style.visibility = 'visible';
}

function shopMenuMouseOut() {
    $(this).down().style.visibility = 'visible';
    $(this).down().next().style.visibility = 'hidden';

    $(this).previous().down().style.visibility = 'visible';
    $(this).previous().down().next().style.visibility = 'hidden';

    $(this).next().down().style.visibility = 'visible';
    $(this).next().down().next().style.visibility = 'hidden';
}

function loadCategory( cat ) {
    new Ajax.Request( '/-1/phpblock/getcategory', {
        method: 'get',
        parameters: { 'cat': cat, 'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            activeCategory = cat;
            refreshShowcase( transport.responseText.evalJSON() );
        }
    } );
}

function loadProduct( prod ) {
    new Ajax.Request( '/-1/phpblock/getproduct', {
        method: 'get',
        parameters: { 'prod': prod, 'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            refreshProductInfo( transport.responseText.evalJSON() );
        }
    } );
}

function loadSearch( query ) {
    new Ajax.Request( '/-1/phpblock/searchinshop', {
        method: 'get',
        parameters: { 'query': query, 'current': activeCategory || 'root', 'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            activeCategory = null;
            refreshShowcase( transport.responseText.evalJSON() );
        }
    } );
}

function refreshShowcase( items ) {
    var box = $('showcaseContent');
    box.show().update('');
    var offset = 15;
    
    for( var n = 0; n < items.length; n++ ) {
        var el = new Element( 'div', { 'class': 'showcaseItem' } );
        var img = new Element( 'img', { 'src': items[n].image + '?rand='+ (new Date().getTime()), 'width': items[n].width, 'height': items[n].height} );
        if( items[n].height < 200 ) {
            var vertSpace, vertTop;
            vertSpace = 200 - items[n].height;
            vertTop = Math.round( vertSpace / 2 );
            img.setStyle( { 'marginTop': vertTop+'px', 'marginBottom': (vertSpace-vertTop)+'px' } );
        }
        var title = new Element( 'div', { 'class': 'itemTitle' } ).update( items[n].name );
        el.insert( img );
        el.insert( title );
        el.setStyle( { 'position': 'absolute', 'left': offset + 'px', 'cursor': 'pointer', 'display': 'none' } );
        el.item = items[n];
        el.onclick = itemClick;
        
        if( items[n].type != 'item' ) {
            el.setAttribute( 'title', items[n].comment );
        }
        
        box.insert( el );

        useFades ? new Effect.Appear( el, { delay: n * 0.2 } ) : el.show();
        
        offset += 215;
    }
}

function refreshProductInfo( item ) {

    var pricePart = '';
    var orderPart = '';
    var drag = '';

    if (item.notOnStock == "1")
    orderPart += '<br /><div class="shopWarning">Niet op voorraad!</div><br />';

    if (item.notBuyable != "1")
    {
        orderPart += '<a id="btnAddToCart" onclick="addItemToCart()" href="javascript:void(0)" style="text-align: left; font-size: 90%;"><img width="16" border=0 height="16" style="margin-top: 15px; margin-right: 5px" src="wp/images/shop/addtocart.png" />Toevoegen</a>';
        drag = 'productDragable';
    }
    if (item.price)
    pricePart += 'Prijs: <span style="font-weight: bolder">'+item.priceFormatted+'</span>';
    
    $('productMainImage').update( '<img class="' + drag + '" src="'+item.mainImage.path+'" width="'+Math.round(item.mainImage.width/2)+'" height="'+Math.round(item.mainImage.height/2)+'"/><br /><br />' + pricePart + '<br />' + orderPart );
    $('productName').update( item.name );
    $('productDescription').update( item.comment );
    activeProduct = item;
    $('productImages').update('');
    
    new Draggable($('productMainImage').down(0), { revert: true, endeffect: false});
    for( var n = 0; n < item.images.length; n++ ) {
        var img = new Element( 'img', { 'class': 'productImageThumb', 'src': item.images[n].thumbPath, 'align': 'absMiddle' } );
        img.image = item.images[n];
        img.onclick = function() {
            popup.openImage( this.image.path, this.image.width, this.image.height );
        };
        $('productImages').insert( img );
    }

    recalcLayoutTimed();
}

function itemClick() {
    if( this.item.type == 'cat' || this.item.type == 'back' ) {
        var id = this.item.id;
        useFades ?
            new Effect.DropOut( $('showcaseContent'), { afterFinish: function() { loadCategory(id); } } )
            : loadCategory(id);
    }
    else {
        showShopPanel();
        loadProduct( this.item.id );
    }
}

function addItemToCart() {
    var product = activeProduct;
    
    var iconWidth = Math.round(product.mainImage.width/2);
    var iconHeight = Math.round(product.mainImage.height/2);
    
    var item = new Element( 'div', { 'class': 'cartItem' } ).setStyle( 'display:none' );
    var prodImg = new Element( 'img', { 'src': product.mainImage.path, 'width': iconWidth, 'height': iconHeight, 'title': product.name } );
    var delImg = new Element( 'img', { 'class': 'cartItemDelete', 'src': '/wp/images/shop/cartdelete.png', 'width': 20, 'height': 20, 'title': 'Dit Item Verwijderen' } );
    delImg.onclick = function() {
        removeItemFromCart( this.up('.cartItem') );
    };
    
    item.insert( prodImg );
    item.insert( delImg );
    item.item = product;
    
    cartContent.push( product );
    updateCart();
    
    $('shopCartArea').insert( item );

    item.show();

    recalcLayoutTimed();
}

function removeItemFromCart( cartItem ) {
    for( var n = 0; n < cartContent.length; n++ ) {
        if( cartContent[n] === cartItem.item ) {
            cartContent.splice( n, 1 );
            break;
        }
    }
    updateCart();
    
    cartItem.remove();

    recalcLayoutTimed();
}

function updateCart() {
    var total = 0;
    var ids = [];
    
    for( var n = 0; n < cartContent.length; n++ ) {
        total += parseInt(cartContent[n].price);
        ids.push( cartContent[n].id );
    }

    $('cartTotalPrice').update( '&euro; ' + ((total / 100)+'').replace( /\./, ',' ) + (total % 100 ? (total % 100 % 10 ? '':'0'):',00') );
    $('cartContentInput').value = ids.join(',');
}

function clearCart() {
    cartContent = [];
    var arr =  $('shopCartArea').childElements();
       arr.each(function(node){
          if (node.id != "shopCartHeader")
        node.remove();
       });

    updateCart();
}

function showShopPanel() {    
    pvcehck = checkToggleProductView("shop");
    $('shopContentMenu').hide();
    $('shopContentMenuItems').hide();
    $('shopContentText').hide();
    $('shopContactForm').hide();
    $('shopCartArea').show();
    $('shopCartBackground').show();
    $('shopProductArea').show();
    $('shopProductBackground').show();
    $('shopOrderPanel').hide();

    contentMode = false;
    shopMode = true;
    orderMode = false;
    contactMode = false;
    if (!pvcehck) recalcLayout();
}

function showOrderPanel() {
    if (!$('cartContentInput').value)
    {
        alert('Uw winkelwagen is nog leeg.');
        return;
    }
    pvcehck = checkToggleProductView("order");
    $('shopContentMenu').hide();
    $('shopContentMenuItems').hide();
    $('shopContentText').hide();
    $('shopContactForm').hide();
    $('shopCartArea').show();
    $('shopCartBackground').show();
    $('shopProductArea').hide();
    $('shopProductBackground').hide();
    $('shopOrderPanel').show();

    contentMode = false;
    shopMode = false;
    orderMode = true;
    contactMode = false;

    //reset data on toggle
    loadDeliveryMethodInfo(-1);
    //calc prices
    reloadOrderOverview();
    $('inpDeliveryMethod').options[0].selected = true;

    //hide all othes panes
    showOrderStep1();    
    
    customerLogin = jar.get("customerLogin");
    if (customerLogin)
    {
    new Ajax.Request( '/-1/phpblock/getcustomerlogin', {
        method: 'get',
        parameters: { 'email': customerLogin.email, 'password': customerLogin.password,  'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            refreshCustomerLoginData( transport.responseText.evalJSON() );
        }
    } );
    $('option_customeraccountyes').checked = true;
    $('option_customeraccountcreateno').checked = true;
    }
    showBusinessFields();
    showLoginFields();
    showDeliveryAddress();

    $('btProceedStep2').enable();
    $('btBackStep1').enable();

    if (!pvcehck) recalcLayout();
}
function showContactForm()
{
    pvcehck = checkToggleProductView("contact");
    $('shopContentMenu').hide();
    $('shopContentMenuItems').hide();
    $('shopContentText').hide();
    $('shopContactForm').show();
    $('shopCartArea').hide();
    $('shopCartBackground').hide();
    $('shopProductArea').hide();
    $('shopProductBackground').hide();
    $('shopOrderPanel').hide();

    contentMode = false;
    shopMode = false;
    orderMode = false;
    contactMode = true;
    if (!pvcehck) recalcLayout();
}

function showContentPanel() {    
    pvcehck = checkToggleProductView("content");
    $('shopContentMenu').show();
    $('shopContentMenuItems').show();
    $('shopContentText').show();
    $('shopContactForm').hide();
    $('shopCartArea').hide();
    $('shopCartBackground').hide();
    $('shopProductArea').hide();
    $('shopProductBackground').hide();
    $('shopOrderPanel').hide();

    var menuItems = $$('.shopContentMenuItemContainer');
    if (menuItems && menuItems[0] && !$('tekstvak').innerHTML)
    {
        WPRequest(menuItems[0].childElements()[0].href);
    }
    contentMode = true;
    shopMode = false;
    orderMode = false;
    contactMode = false;
    if (!pvcehck) recalcLayout();
}

function checkToggleProductView(mode)
{
    if (mode == "shop" && !productsLoaded)
    {
    
        new Effect.Move($('shopTitle'), {x: 0, y: -((topHeight/2) - ($('shopTitle').getHeight()))+10, mode: 'relative', afterFinish: function() { loadCategory( 'root' ); } });
        new Effect.Move($('shopSubTitle'), {x: 0, y: -((topHeight/2) - ($('shopTitle').getHeight())), mode: 'relative'});
        new Effect.Move($('shopLogoContainer'), {x:0, y: -((topHeight/2) - ($('shopTitle').getHeight()))+10, mode: 'relative'});
        productsLoaded = true;
        return true;
    }
    return false;
}

function reloadOrderOverview()
{
    var totalProducts = 0;
    for( var n = 0; n < cartContent.length; n++ ) {
        totalProducts += parseInt(cartContent[n].price);
    }
    $('tdSubProducts').update( '&euro; ' + ((totalProducts / 100)+'').replace( /\./, ',' ) + (totalProducts % 100 ? (totalProducts % 100 % 10 ? '':'0'):',00') );

    var totalDelivery = parseInt($('deliveryPriceInput').value) + parseInt($('deliveryCountryPriceInput').value);
    if (totalDelivery && !isNaN(totalDelivery))
    {
        $('trDelivery').show();
        $('tdSubDelivery').update( '&euro; ' + ((totalDelivery / 100)+'').replace( /\./, ',' ) + (totalDelivery % 100 ? (totalDelivery % 100 % 10 ? '':'0'):',00') );
    }
    else
    {
        totalDelivery = 0;
        $('trDelivery').hide();
    }
    var totalPayment = parseInt($('paymentPriceInput').value);
    if (totalPayment && !isNaN(totalPayment))
    {    
        $('trPayment').show();
        $('tdSubPayment').update( '&euro; ' + ((totalPayment / 100)+'').replace( /\./, ',' ) + (totalPayment % 100 ? (totalPayment % 100 % 10 ? '':'0'):',00') );
    }
    else
    {
        totalPayment = 0;
        $('trPayment').hide();
    }
    var total = totalProducts + totalDelivery + totalPayment;
    $('tdTotal').update( '&euro; ' + ((total / 100)+'').replace( /\./, ',' ) + (total % 100 ? (total % 100 % 10 ? '':'0'):',00') );
    recalcLayout();
}

function proceedOrderStep1()
{
    if ($("inpDeliveryMethod").getValue() == -1)
    {
        alert("Je bent vergeten een verzend- of afhaaloptie selecteren.");
        return;
    }
    else
    {
        //we selected a delivery method
        if (($('paymentMethodContainer').visible()) && ($('inpPaymentMethod').getValue() == -1))
        {
            alert("Je bent vergeten betaalmethode te kiezen.");
            return;
        }

        if ($("inpDeliveryCountry").getValue() == -1 && $('inpDeliveryCountry').disabled == false)
        {
        alert("Je bent vergeten een bestemming te kiezen voor je gekozen bezorgmethode.");
        return;
        }
    }
    loginData = jar.get("customerLogin");
    if ($('option_doUseAltAddr').checked && (!loginData || !loginData.loggedIn))
    {
        alert("Je moet inloggen om dmv een gebruikersaccount te kunnen bestellen.");
        return;
    }
    showOrderStep2();
}

function proceedOrderStep2()
{

    if ($('option_customeraccountcreateyes').checked && ($('inpCreateAccountPassword').getValue() != $('inpCreateAccountPassword').getValue()))
    {
        alert("Wachtwoord en wachtwoord bevestigen komen niet overeen!");
        return;
    }

    if(!facFieldsComplete())
    {
    alert("Je hebt niet alle adres velden ingevuld.");
    return;
    }
    
    if(hasAlternateDeliveryAddress() && !delFieldsComplete())
    {
    alert("Je hebt niet alle bezorgadres velden ingevuld.");
    return;
    }
    showOrderStep3();
}

function showOrderStep1()
{    
    //check for weight & dimensions
    var totalWeight = 0;
    var totalVolume = 0;

    for( var n = 0; n < cartContent.length; n++ ) {
     if (cartContent[n].bHasWeight)
        totalWeight += parseInt(cartContent[n].weight);
      if (cartContent[n].bHasDimensions)
        totalVolume += parseInt(cartContent[n].width) * parseInt(cartContent[n].height) * parseInt(cartContent[n].depth);
    }

    if (totalWeight || totalVolume)
    {
    new Ajax.Request( '/-1/phpblock/getdisableddeliverymethods', {
        method: 'get',
        parameters: { 'weight': totalWeight , 'volume': totalVolume,  'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            disableImpossibleDMs( transport.responseText.evalJSON() );
        }
    } );
    }
    else resetDMs();
    
    $('divFinalizeOrder').hide();
    $('divClientData').hide();
    $('divOrderOverview').show();
    $('divDeliveryPayment').show();
    $('shopOrderPanel').scrollTop = 0;
    recalcLayout();
}

function disableImpossibleDMs(disabledMethods) {

  resetDMs();
  for( var n = 0; n < disabledMethods.length; n++ ) {
   $('dm' + disabledMethods[n]).disabled=true;
  }
}

function resetDMs()
{
$$('.dmoption').each(function(s) {s.disabled = false; });
}

function showOrderStep2()
{        
    $('divFinalizeOrder').hide();
    $('divDeliveryPayment').hide();
    $('divClientData').show();
    $('shopOrderPanel').scrollTop = 0;

    //load client data from cookie if exists
    customerLogin = jar.get("customerLogin");
    if (customerLogin)
    {
        showHideElement('saveChangesContainer', true);
        new Ajax.Request( '/-1/phpblock/getcustomerclientdata', {
        method: 'get',
        parameters: { 'email': customerLogin.email, 'password': customerLogin.password, 'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            reloadCustomerClientData( transport.responseText.evalJSON(), customerLogin );
        }
        } );
    }
    else
    {
        showHideElement('saveChangesContainer', false);
        //no login? use stored cookie
        reloadCustomerClientData(jar.get("customerData"), customerLogin );
    }
    recalcLayout();
    //new Effect.Fade( $('divOrderOverview'), {duration: 1.0});
    //new Effect.Appear($('divClientData'), {duration: 1.0, beforeStart: function() {$('shopOrderPanel').scrollTop = 0;} });
}

function showOrderStep3()
{

    var inputs = $(document.forms['orderForm']).getInputs();
    for( var n = 0; n < inputs.length; n++ ) {
        if( (!inputs[n].present()) && inputs[n].hasAttribute('required') ) {
            alert( 'U heeft een verplicht veld niet ingevuld' );
            inputs[n].focus();
            return;
        }
    }

    validateClientData();
}

function delFieldsUsed()
{
    return ($('inpDel_Company').getValue() || $('inpDel_Initials').getValue() || $('inpDel_Name').getValue() ||  $('inpDel_Prefix').getValue() || $('inpDel_ZipCode').getValue() || $('inpDel_StreetNr').getValue() || $('inpDel_Street').getValue() || $('inpDel_City').getValue() || $('inpDel_Address_ex').getValue() || $('inpDel_Country').getValue());
}

function delFieldsComplete()
{
    return ($('inpDel_Initials').getValue() && $('inpDel_Name').getValue() && $('inpDel_ZipCode').getValue() && $('inpDel_StreetNr').getValue() && $('inpDel_Street').getValue() && $('inpDel_City').getValue() && $('inpDel_Country').getValue());
}

function facFieldsComplete()
{
    return ($('inpInitials').getValue() && $('inpName').getValue() && $('inpZipCode').getValue() && $('inpStreetNr').getValue() && $('inpStreet').getValue() && $('inpCity').getValue() && $('inpCountry').getValue());
}

function reloadCustomerClientData(customerClientData, customerLogin)
{
    if(customerClientData)
    {
        jar.put("customerClientData", customerClientData);
        $('inpEmail').setValue(customerClientData.email);
        $('inpCompany').setValue(customerClientData.company);
        $('inpInitials').setValue(customerClientData.initials);
        $('selGender').setValue(customerClientData.gender);
        $('inpName').setValue(customerClientData.familyname);
        $('inpPrefix').setValue(customerClientData.middlename)
        $('inpZipCode').setValue(customerClientData.postalcode);
        $('inpStreetNr').setValue(customerClientData.addressnumber);
        $('inpStreet').setValue(customerClientData.addressstreet);
        $('inpCity').setValue(customerClientData.city);
        $('inpAddress_ex').setValue(customerClientData.addressextra);
        $('inpCountry').setValue(customerClientData.country);
        $('inpBirthday').setValue(customerClientData.birthday);
        $('inpDel_Company').setValue(customerClientData.deliverycompany);
        $('inpDel_Initials').setValue(customerClientData.deliveryinitials);
        $('selDel_Gender').setValue(customerClientData.deliverygender);
        $('inpDel_Name').setValue(customerClientData.deliveryfamilyname);
        $('inpDel_Prefix').setValue(customerClientData.deliverymiddlename)
        $('inpDel_ZipCode').setValue(customerClientData.deliverypostalcode);
        $('inpDel_StreetNr').setValue(customerClientData.deliveryaddressnumber);
        $('inpDel_Street').setValue(customerClientData.deliveryaddressstreet);
        $('inpDel_City').setValue(customerClientData.deliverycity);
        $('inpDel_Address_ex').setValue(customerClientData.deliveryaddressextra);
        $('inpDel_Country').setValue(customerClientData.deliverycountry);
        $('inpPhone').setValue(customerClientData.phone);
        $('inpCellPhone').setValue(customerClientData.mobile);
    
        //check / uncheck whatever we need
        $('option_doUseAltAddr').checked = delFieldsUsed();
        $('option_notUseAltAddr').checked = !delFieldsUsed();
    
        var hasCompany = Boolean($('inpCompany').getValue());
    
        $('option_business').checked = hasCompany;
        $('option_personal').checked = !hasCompany;
    }

    if (customerLogin && (customerLogin.loggedIn))
        $('createaccountcontainer').hide();
    else
        $('createaccountcontainer').show();

    //show the fields we need
    showCreateAccountFields();
    showDeliveryAddress();
    showBusinessFields();
}
function loadDeliveryMethodInfo( dmId ) {
    if ( parseInt(dmId) > 0)
    {
    new Ajax.Request( '/-1/phpblock/getdeliverymethodinfo', {
        method: 'get',
        parameters: { 'dmid': dmId, 'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            refreshDmInfo( transport.responseText.evalJSON() );
        }
    } );
    }
    else
    {    
        $('deliveryPriceInput').value = 0;
        $('deliveryCountryPriceInput').value = 0;
        $('paymentPriceInput').value = 0;

        $('inpPaymentMethod').disabled = true;    
        $('inpDeliveryCountry').disabled = true;

        $('inpPaymentMethod').options.length = 1;
        $('inpDeliveryCountry').options.length = 1;

        $('divDeliveryMethodDesc').update('Je moet een bezorg of ophaalmogelijkheid selecteren voordat je verder kan gaan met je bestelling.')
    }
    
}

function onSelectDeliveryCountry (dcId)
{
    new Ajax.Request( '/-1/phpblock/getdeliverycountryinfo', {
        method: 'get',
        parameters: { 'dcid': dcId, 'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            refreshDcInfo( transport.responseText.evalJSON() );
        }
    } );
}

function onSelectPaymentMethod(pmId)
{
    if (pmId != "-1")
    {
    new Ajax.Request( '/-1/phpblock/getpaymentmethodinfo', {
        method: 'get',
        parameters: { 'pmid': pmId, 'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            refreshPmInfo( transport.responseText.evalJSON() );
        }
    } );
    }
    else
    {
        $('divPaymentMethodDesc').update('Je moet een betaalmethode selecteren voordat je verder kan gaan met je bestelling.')
    }
}

function showHideElement(sID, bShow) {
    var oDV = $(sID);
    if (oDV != undefined)
    {
    if (bShow)
    oDV.show();
    else
    oDV.hide();
    }
}

function isBusinessOrder() {
    return $('option_business').checked;
}

function hasCustomerAccount () {
    return $('option_customeraccountyes').checked;
}
function hasAlternateDeliveryAddress() {
    return $('option_doUseAltAddr').checked;
}

function wantsCreateAccount() {
    return $('option_customeraccountcreateyes').checked;
}

function showBusinessFields() {
    showHideElement('tabelCompany',isBusinessOrder());
}

function showDeliveryAddress() {
    var bShow = hasAlternateDeliveryAddress();
    showHideElement('dvPackageData',bShow);
    showHideElement('dvPackage',bShow);

}

function showCreateAccountFields()
{
    showHideElement('tabelCreateAccount',wantsCreateAccount());
    recalcLayoutTimed();
}

function refreshPmInfo(pmInfo)
{

    if (pmInfo.description.length)
    {
        $('divPaymentMethodDesc').update(pmInfo.description);
        if (parseInt(pmInfo.cost) == -1)
        {
            pmInfo.cost = 0;
        }
    }
    else
    {
        $('divPaymentMethodDesc').update('Voor deze betaalmethode is geen beschrijving beschikbaar.');
    }

    $('paymentPriceInput').value = pmInfo.cost;
    
    reloadOrderOverview();
}

function refreshDcInfo ( dcInfo )
{
    $('deliveryCountryPriceInput').value = dcInfo.price;
    reloadOrderOverview();
}

function refreshDmInfo (dmInfo)
{
if (dmInfo.description.length)
{
    $('divDeliveryMethodDesc').update(dmInfo.description);
}
else
{
    $('divDeliveryMethodDesc').update('Voor deze bezorgmethode of afhaalmogelijkheid is geen beschrijving beschikbaar.');
}
$('deliveryCountryPriceInput').value = 0;
$('deliveryPriceInput').value = parseInt(dmInfo.cost);
reloadOrderOverview();

if ($('inpDeliveryCountry').options.length > 1)

$('inpPaymentMethod').options.length = 1;
$('inpDeliveryCountry').options.length = 1;

if (parseInt(dmInfo.rembours) == 1)
{
    //hide payment and country
    $('inpDeliveryCountry').disable();
    $('inpPaymentMethod').disable();
    showHideElement('paymentMethodContainer', 0);
}
else
{
    $('inpDeliveryCountry').enable();
    showHideElement('paymentMethodContainer', 1);
    $('inpPaymentMethod').enable();
    

    for( var n = 0; n <dmInfo.paymentMethods.length; n++ ) {
    $('inpPaymentMethod').options[$('inpPaymentMethod').options.length] =  new Option(dmInfo.paymentMethods[n].name, dmInfo.paymentMethods[n].id, false, false);
    }
}
if (dmInfo.type == 1 && dmInfo.rembours != 1)
{
    $('inpDeliveryCountry').disabled= false;

    for( var n = 0; n <dmInfo.deliveryCountries.length; n++ ) {
    $('inpDeliveryCountry').options[$('inpDeliveryCountry').options.length] =  new Option(dmInfo.deliveryCountries[n].country, dmInfo.deliveryCountries[n].id, false, false);
    }
}
if (parseInt(dmInfo.rembours) != 1)
{
    if (dmInfo.type == 2)
    {
    $('inpDeliveryCountry').disable();
    showHideElement('deliveryCountryContainer', 0);
    //$('deliveryCountryContainer').reset();
    }
    else
    {
    $('inpDeliveryCountry').enable();
    showHideElement('deliveryCountryContainer', 1);
    }
}
}

function loginCustomer(email, password)
{
    if(email && password)
    {
    $('loginbutton').disable();
        new Ajax.Request( '/-1/phpblock/getcustomerlogin', {
        method: 'get',
        parameters: { 'email': email, 'password': password,  'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            refreshCustomerLoginData( transport.responseText.evalJSON() );
        }
        } );
    }
    else
    {
        alert("Je moet zowel een gebruikersnaam en wachtwoord opgeven om in te kunnen loggen.");
        return;
    }

}

function showLoginFields() {
    
    $('loginbutton').enable();
    var hasAccount = hasCustomerAccount();
    showHideElement('tabelLogin',hasAccount);
    loginData = jar.get("customerLogin");
    if (!hasAccount && loginData)
    {
        //logout
        jar.remove("customerLogin");
        $('loginDetailsContainer').hide();
    }
    else if (hasAccount && loginData)
    {
        updateLoginInfo(loginData.email);
    }
    if (!hasAccount)
    {
        $('option_customeraccountcreateyes').checked = true;
    }
    else
    {
        $('option_customeraccountcreateno').checked = true;
    }
    recalcLayoutTimed();

}

function updateLoginInfo(email)
{
$('tabelLogin').hide();
$('loginDetailsContainer').update('Je bent ingelogd onder ' + email);
$('loginDetailsContainer').show();
recalcLayout();
}

function refreshCustomerLoginData(loginData)
{
if (loginData.loggedIn)
{
jar.remove("customerLogin");
jar.put("customerLogin",loginData);
updateLoginInfo(loginData.email);
}
else
{
    alert("Onjuist emailadres of wachtwoord. Probeer het nogmaals.");
    $('loginbutton').enable();
}
}

//validate functions

function validateEmailFree(obj)
{
    if(obj.value)
    {
    $('loginbutton').disable();
        new Ajax.Request( '/-1/phpblock/validateemailfree', {
        method: 'get',
        parameters: { 'email': obj.value,  'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            reponseValidateEmailFree( transport.responseText.evalJSON(), obj );
        }
        } );
    }
}

function validateEmail(obj)
{
    if(obj.value)
    {
    $('loginbutton').disable();
        new Ajax.Request( '/-1/phpblock/validateemail', {
        method: 'get',
        parameters: { 'email': obj.value,  'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            reponseValidateEmail( transport.responseText.evalJSON(), obj );
        }
        } );
    }
}

function reponseValidateEmailFree(response, obj)
{
    if(!response.emailFree)
    {
        alert("Op " + obj.value + " is reeds een account geregistreerd!");
        obj.className = 'inpBoxRed';
    }
    else
    {
        obj.className = 'inpBox';
    }
}
function reponseValidateEmail (response, obj)
{
    if(!response.validEmail)
    {
        alert(obj.value + " is geen geldig emailadres!");
        obj.className = 'inpBoxRed';
    }
    else
    {
        obj.className = 'inpBox';
    }         
}

//date
function validateDate(obj)
{
    if(obj.value)
    {
        new Ajax.Request( '/-1/phpblock/validatedate', {
        method: 'get',
        parameters: { 'date': obj.value,  'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            reponseValidateDate( transport.responseText.evalJSON(), obj );
        }
        } );
    }
}

function reponseValidateDate(response, obj)
{
    if(!response.validDate)
    {
        alert(obj.value + " is geen geldige datum!");
        obj.className = 'inpBoxRed';
    }
    else
    {
        obj.className = 'inpBox';
    }     
}

//phone
function validatePhone(obj)
{
    if(obj.getValue())
    {
        new Ajax.Request( '/-1/phpblock/validatephone', {
        method: 'get',
        parameters: { 'phone': obj.value,  'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            reponseValidatePhone( transport.responseText.evalJSON(), obj );
        }
        } );
    }
}

function reponseValidatePhone(response, obj)
{
    if(!response.validPhone)
    {
        alert(obj.value + " is geen geldig telefoonnummer!");
        obj.className = 'inpBoxRed';
    }
    else
    {    
        obj.className = 'inpBox';
    }     
}

//address number
function validateAddressNumber(obj)
{
    if(obj.value)
    {
        new Ajax.Request( '/-1/phpblock/validateaddressnumber', {
        method: 'get',
        parameters: { 'addressnumber': obj.value,  'rand': (new Date).getTime() },
        onSuccess: function(transport) {
            reponseValidateAddressNumber( transport.responseText.evalJSON(), obj );
        }
        } );
    }
}

function reponseValidateAddressNumber(response, obj)
{
    if(!response.validAddressNumber)
    {
        alert(obj.value + " is geen geldig huisnummer!");
        obj.className = 'inpBoxRed';
    }
    else
    {
        obj.className = 'inpBox';
    }
}

//complete clientdata
function validateClientData()
{
    new Ajax.Request( '/-1/phpblock/validateclientdata', {
        method: 'post',
        parameters: $(document.forms['orderForm']).serialize(),
        onSuccess: function(transport) {    
        reponseValidateClientData( transport.responseText.evalJSON());
        //reponseValidateClientData( transport.responseText);
    }
    } );
}

function reponseValidateClientData(response)
{
    var ErrorMessage = "";
    if(!response.validEmail)
    {
        ErrorMessage += "\n-Het opgegeven emailadres is niet correct.";
    }
    if(!response.validAddressNumber)
    {
        ErrorMessage += "\n-Het opgegeven huisnummer is niet correct.";
    }
    if(!response.validPhone && $('inpPhone').getValue())
    {
        ErrorMessage += "\n-Het opgegeven telefoonnummer is niet correct.";
    }
    if(!response.validMobile && $('inpCellPhone').getValue())
    {
        ErrorMessage += "\n-Het opgegeven mobiele telefoonnummer is niet correct.";
    }
    if(($('inpBirthday').getValue()) && !response.validBirthDay)
    {
        ErrorMessage += "\n-De opgegeven geboortedatum is niet correct.";
    }
    if((!$('option_customeraccountyes').checked && $('option_customeraccountcreateyes').checked) && !response.ValidPassword)
    {
        ErrorMessage += "\n-Het opgegeven wachtwoord is niet voldoende complex.";
    }
    if ((!$('option_customeraccountyes').checked && $('option_customeraccountcreateyes').checked) && ($('inpEmail').getValue() != $('inpEmail2').getValue()))
    {
        ErrorMessage += "\n-Email-adres en email-adres bevestigen komen niet overeen.";
    }
    if ((!$('option_customeraccountyes').checked && $('option_customeraccountcreateyes').checked) && ($('inpCreateAccountPassword').getValue() != $('inpCreateAccountPassword2').getValue()))
    {
        ErrorMessage += "\n-Wachtwoord en wachtwoord bevestigen komen niet overeen.";
    }
    if ($('option_customeraccountcreateyes').checked && response.EmailInUse)
    {
        ErrorMessage += "\n-Op het door jou opgegeven emailadres is reeds een account aangemaakt.";
    }

    if(delFieldsUsed() && !delFieldsComplete())
    {
        ErrorMessage += "\n-Je hebt niet alle bezorgadres velden ingevuld.";
    
    }
    //we have complete delivery fields, check data
    else if (delFieldsUsed())
    {    
        if(!response.validDeliveryAddressNumber)
        {
            ErrorMessage += "\n-Het opgegeven verzendadres huisnummer is niet correct.";
        }
    }
    
    if (ErrorMessage)
    {
        alert("Er zijn problemen met de ingevulde gegevens:" + ErrorMessage );
    }
    else
    {
        $('btProceedStep2').disable();
        $('btBackStep1').disable();
        new Ajax.Request( '/-1/phpblock/orderform-backend', {
        method: 'post',
        parameters: $(document.forms['orderForm']).serialize(),
        onSuccess: function(transport) {
            //alert(transport.responseText);
            clearCart();
            $(document.forms['orderForm']).reset();
            $('divClientData').hide();
            $('divDeliveryPayment').hide();
            $('divOrderOverview').hide();
            $('divFinalizeOrder').show();
            recalcLayoutTimed();
            $('shopOrderPanel').scrollTop = 0;
            $('btBackStep1').disable();
            $('btProceedStep2').disable();
        }
        } );
    }

}

function vkCreatepayment(orderid, bankid)
{
    $('submitbank').disable();
    new Ajax.Request( '/-1/phpblock/virtuelekassa-pay', {
        method: 'post',
        parameters: {
        'bankid': bankid,
        'orderid': orderid
        },
        onSuccess: function(transport) {
            //alert(transport.responseText);
        }
    });
}

//registrations part of order

function applyRegistrations()
{
    loginData = jar.get("customerLogin");
    if (loginData)
    {
        new Ajax.Request( '/-1/phpblock/updatecustomerregistrations', {
        method: 'post',
        parameters: {
            'email': loginData.email,
            'password': loginData.password,
            'registercustomer': $('inpCheckTokoRegister').checked,
            'registermailings': $('inpCheckTokoRegisterMailings').checked,
            'registersms': $('inpCheckTokoRegisterSMS').checked
        }
        });
    }
}

function toggleRegistrationChecks()
{
    if ($('inpCheckTokoRegister').checked == true)
    {
        $('inpCheckTokoRegisterMailings').enable();
        $('inpCheckTokoRegisterSMS').enable();
    }
    else
    {
        $('inpCheckTokoRegisterMailings').disable();
        $('inpCheckTokoRegisterSMS').disable();
    }
}
