﻿$(function() {
    // new product detail
    if ($.fn.transformSelect) {
        $(".prodSettingRight select").transformSelect();
    }
    if ($("#accessoiresScroller").length > 0) {
        initProductDetailScroller();
    }
    $("#specs li ul").each(function() {
        $(this).find("li:even").addClass("dark");
    });
    if ($.fn.fancybox) {
        $(".fancyboxPopup").fancybox();
    }

    // Fix IMG click within A
    $('a img').click(function() {
        var a = $(this).closest('a');
        if (a.attr('href') != '' && a.attr('href') != '#' && a.attr('target') != '_blank' && !a.hasClass('lightbox')) {
            document.location = a.attr('href');
        }
    });

    $('a.prodMore[href^="#"]').each(function() {
        if ($(this).attr('href').length > 1) {
            var targetId = $(this).attr('href').substring(1);
            var targetElem = $('#' + targetId);

            if (targetElem.length === 0) {
                targetElem = $('a[name="' + targetId + '"]');
            }

            if (targetElem.length > 0) {
                $(this).click(function(e) {
                    e.preventDefault();

                    $('html, body').animate({
                        'scrollTop': targetElem.offset().top
                    }, 'slow');
                });
            }
        }
    });

    // Rechtermuis click disablen
    if (location.host !== 'matrabike.juicedev.nl') {
        $(this).bind('contextmenu', function(e) {
            e.preventDefault();
        });
    }

    $('.compareButton').click(function(e) {
        redirect($(this).attr('data-link'));
    });

    // Initialisatie Lightbox
    $('a.lightbox').lightBox(); // Select all links with lightbox class

    setValue('#zoekField');
    setValue('#nieuwsbriefField');

    // Linker zoekveld
    $('input#zoekBtnLeft').click(function() {
        doZoeken($('input#zoekField').val());
    });
    $('input#zoekField').keydown(function(e) {
        if (e.which == 13) {
            e.preventDefault();
            $('input#zoekBtnLeft').click();
        }
    });

    $('#nieuwsbriefField').keydown(function(e) {
        if (e.which == 13) {
            e.preventDefault();
            doNieuwsbrief();
        }
    });

    initButton('/winkelmandje.aspx', 'winkelmandje');
    placeRotator();

    // Topnav init, hover, submenu, etc
    initMenu();

    /*
    Product framemaat berekenen
    */
    if ($('.frameTitle').length > 0) {
        $('.frameTitle a').click(toggleFrameSizeBlock).eq(0).trigger('click');
        $('.frameClose > a').click(hideFrameSizeBlock);
        $('.framemaatBtn').click(showFrameSizeBlock);

        if ($('[kinderfiets]').attr('kinderfiets') == 'True') {
            $('.frameTitle > span').hide();
            $('.frameTitle > a').removeClass('selected');
            $('.frameTitle > span').eq(2).show();
            $('.frameTitle > a').eq(2).addClass('selected');
        }
    }

    /*
    Mobile browsing
    */
    var maxResolution = { width: 800, height: 600 };
    if ((screen.height < maxResolution.height && screen.width < maxResolution.width)) {
        // Verwijder flash
        $('object').remove();
        //Zet producten onder elkaar i.p.v. langs elkaar
        $('#right .title, #right .row').css({ width: 490 });
    }

    $('.validateBestelform').click(function() {
        if ($('form').eq(0).valid()) {
            $('form').eq(0).attr('action', '/bestellen.aspx?stap=2');
            $('form').eq(0).submit();
        }
    });

    $('.confirmOrder').click(function() {
        $('form').eq(0).attr('action', '/bestellen.aspx?stap=4');
        $('form').eq(0).submit();
    });

    // from validatie
    $('form').eq(0).validate({
        errorPlacement: function(error, element) {
            error.appendTo(element.parent('td').next('td'));
        }
    });

    var errorCount = 0;
    //Coupon inleveren
    $('#verzilverBtn').click(function() {
        $.ajax({
            type: 'POST',
            url: '/winkelmandje.aspx/GetCoupon',
            data: '{ "couponcode": "' + $('#verzilverInput').val() + '" }',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(response) {
                var data = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

                if (data.success == false) {
                    errorCount++;

                    if (errorCount < 2) {
                        alert('Dit is geen geldige couponcode. Probeer het nogmaals.');
                    }
                    else if (errorCount >= 2) {
                        alert('Dit is geen geldige couponcode.');
                        window.location.href = '/winkelmandje.aspx?couponerror=true';
                    }
                }
                else {
                    if (data.isPPFCoupon === true && data.isGratisBezorging === true) {
                        alert('Deze coupon is niet geldig in combinatie met andere acties. De gratis\nverzendkosten actie zal vervallen.');
                    }
                    window.location.href = '/winkelmandje.aspx';
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(xhr.statusText);
                alert(thrownError);
            }
        });
    });

    $('input#verzilverInput').keydown(function(e) {
        if (e.which === 13) {
            e.preventDefault();

            $('span#verzilverBtn').trigger('click');
        }
    });

    $('input#nieuwsbriefButton').click(doNieuwsbrief);

    // Do Zoom
    $(".zoomKop").click(function() {
        $('.left .img a').trigger('click');
    });

    // Anchor
    $("a.anchorLink").anchorAnimate()

    //Voeg onclick toe voor alle uitgaande links
    //BV:http://www.fietsned.nl/
    $("a[href^='http://']:not([href^='http://www.matrabike.nl'])").click(function() { // href beging met http:// en begint niet met http://www.matrabike.nl        
        pageTracker._trackPageview("/exit/" + $(this).attr("href"));
    });

    //Voeg onclick toe voor alle pdf's
    //BV: http://www.matrabike.nl/itemhandler.aspx?path=ROOT/customers/matrabike/documents/handleidingen/montage AXA montagebeugel.pdf
    $("a[href$='.pdf']").click(function() { // href eindigt op .pdf
        var regexp = /(\w|[-. ])+$/
        a = regexp.exec($(this).attr("href"));
        pageTracker._trackPageview('/download/' + a[0]);
    });

    // Add the page method call as an onclick handler for the div.
    initDropDowns();
    initSetDropDowns(0);

    $(".bestelBtn").click(function(e) {
        e.preventDefault();

        if (typeof $(this).data('extraids') !== 'undefined') {
            $('input#extraids').val($(this).data('extraids'));
        }

        submitAddWinkelmandje();
    });

    //validate
    $("#aspnetForm").validate({
        errorPlacement: function(error, element) {
            error.appendTo(element.parent("div").next("div"));
        }
    });
});

function toggleFrameSizeBlock() {
    // Ouden disabled
    $('.frameTitle > span').hide();
    $('.frameTitle > a').removeClass('selected');

    // Nieuwe enabled
    $(this).parent().find('span').eq(1).show();
    $(this).parent().find('a').eq(0).addClass('selected');

    var height = $(this).closest('.frameOverlay').innerHeight();
    if (height > $('.resizeLeft').innerHeight()) {
        $('.resizeLeft').height(height - 10);
    }
    return false;
}
function hideFrameSizeBlock() {
    $(this).closest(".frameOverlay").hide();
    return false;
}
function hideFrameSizeBlock2() {
    $(".frameOverlay").hide();
    return false;
}
function showFrameSizeBlock() {
    $(".frameOverlay").show();
    return false;
}

function backToNormal(obj) {
    if (obj.value == "geen geldig e-mail adres")
        obj.value = "";
    //alert(obj.style.backgroundColor);
    obj.style.backgroundColor = "";
}

function ReturnValidate() {
    if (document.MM_returnValue == true) {
        url = document.location;
        document.aspnetForm.action = url;
        document.aspnetForm.submit();
    }
}

function ValidateContact() {
    MM_validateForm('Voorletters', '', 'R',
                    'Achternaam', '', 'R',
                    'Adres', '', 'R',
                    'Postcode', '', 'R',
                    'Plaats', '', 'R',
                    'Telefoonnummer', '', 'R',
                    'E-mail', '', 'RisEmail',
                    'Bericht', '', 'R');
    ReturnValidate();
}

function ValidateBankkeuze() {
    if ($("#iDEAL").is(":checked")) {
        MM_validateForm('bankkeuze', '', 'R');
        if (document.MM_returnValue == false) {
            $("#meldingbankkeuze").show();
        }
        else {
            $("#meldingbankkeuze").hide();
        }
    }
    else {
        document.MM_returnValue = true;
    }
    if (document.MM_returnValue == true) {
        document.aspnetForm.action = '/bestellen.aspx?stap=3';
        document.aspnetForm.submit();
    }
}

function doPostBack() {
    url = document.location;
    document.aspnetForm.action = url;
    document.aspnetForm.submit();
}

var timeoutAantallen;

function aantallenAanpassen() {
    clearTimeout(timeoutAantallen);
    setTimeout(submitAantallenAanpassen, 500);
}

function submitAantallenAanpassen() {
    $("#mode").val('aantallenaangepast');
    $("#aspnetForm").submit();
    //MM_findObj('mode').value='aantallenaangepast';
    //url = document.location;
    //document.aspnetForm.action = url;
    //document.aspnetForm.submit();
}

function validateBestellen() {
    MM_validateForm('jclc_Firstname', '', 'R',
                    'jclc_Lastname', '', 'R',
                    'jclc_a_Streetline1', '', 'R',
                    'jclc_a_Number1', '', 'R',
                    'jclc_a_Zipcodepart1', '', 'R',
                    'jclc_a_City', '', 'R',
                    'jclc_Phonenumber1', '', 'R',
                    'jclc_Emailfirst', '', 'RisEmail');
    if (document.MM_returnValue) {
        url = "/bestellen.aspx?stap=3";
        document.aspnetForm.action = url;
        document.aspnetForm.submit();
    }

}

function validateTellAFriend() {
    MM_validateForm('uwNaam', '', 'R',
                    'uwEmailadres', '', 'RisEmail',
                    'vriendNaam', '', 'R',
                    'vriendEmailadres', '', 'RisEmail');
    if (document.MM_returnValue) {
        document.aspnetForm.action = document.location;
        document.aspnetForm.submit();
    }
}

function showAll() {
    document.getElementById('showAll').value = 'true';
    doPostBack();
}

function sortering(sort) {
    $("#sortering").val(sort);
    doPostBack();
}

function initButton(loc, name) {
    var obj = document.getElementById(name);
    if (obj) {
        obj.onmouseover = function() {
            document.body.style.cursor = 'pointer';
        }
        obj.onclick = function() {
            document.location = loc;
        }
        obj.onmouseout = function() {
            document.body.style.cursor = 'default';
        }
        obj.onmouseup = function() {
            document.body.style.cursor = 'wait';
        }
    }
}

function placeRotator() {
    var d = "";
    d = d + ('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="206" height="135" id="Rotator" align="middle">');
    d = d + ('<param name="allowScriptAccess" value="sameDomain" />');
    d = d + ('<param name="allowFullScreen" value="false" />');
    d = d + ('<param name="movie" value="/flash/rotator.swf" />');
    d = d + ('<param name="quality" value="high" />');
    d = d + ('<param name="bgcolor" value="#ffffff" />');
    d = d + ('<embed src="/flash/rotator.swf" quality="high" bgcolor="#ffffff" width="206" height="135" name="Rotator" ');
    d = d + (' align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="https://get.adobe.com/nl/flashplayer" />');
    d = d + ('</object>');
    try {
        document.getElementById("box").innerHTML = d;
    }
    catch (err) { }
}

function goBack() {
    history.go(-1);
}

function optimizeSearchString(zoekstr) {
    /* 
    Alles eruit filteren behalve:
    - 0-9 (0-9)
    - a-z (a-z)
    - A-Z (A-Z)
    - Koppelstreepje (-)
    - Spaties (\s)
    Extra uitleg
    - begin met / Start regex
    - Eind met / Eind regex
    - Achter de laatste / nog een letter dus g staat voor global. Dus over hele string uitvoeren
    */
    zoekstr = zoekstr.replace(/[^0-9a-z''A-Z[.]-\s]/g, "");
    zoekstr = zoekstr.replace(/\s+/g, " ");
    zoekstr = trim(zoekstr);
    return zoekstr;
}

function doZoeken(searchString) {
    //if (trim($('#zoekField').val()) != 'Zoeken naar...') {
    //    redirect('/Zoeken/' + optimizeSearchString($('#zoekField').val()) + '.aspx');
    //}
    //else if (trim($('#searchField').val()) != 'Zoeken naar...') {
    //    redirect('/Zoeken/' + optimizeSearchString($('#searchField').val()) + '.aspx');
    //}
    if (trim(searchString) !== 'Zoeken naar...') {
        redirect('/Zoeken/' + optimizeSearchString(searchString) + '.aspx');
    }
}

function doNieuwsbrief() {
    if (checkEmail('nieuwsbriefField')) {
        doPostBack();
    }
    else {
        alert('Het door u ingevulde e-mail adres is geen geldig e-mail adres.');
    }
}

function redirect(loc) {
    document.location = loc;
}

/*
setValue 
Onclick de waarde weghalen. En onBlur terug zetten.
@param val klasse of id van het object (.class, #id)
*/
function setValue(val) {
    $(val).click(
		function() {
		    if (this.value == this.defaultValue) this.value = '';
		}
	);
    $(val).blur(
		function() {
		    if (this.value == '') this.value = this.defaultValue;
		}
	);
}

function BerekenFramemaat() {
    var FrameFaktor = 0;
    var FrMaat = 0;
    var FrameMaat = 0;
    var GeveerdeZadelpen = $("#zadelpen").is(':checked');
    var sAdvies = "";
    var iBeenlengte = $("#binnenbeenlengte").val();
    iBeenlengte = iBeenlengte.replace(',', '.');

    if (IsNumeric(iBeenlengte) && iBeenlengte >= 60 && iBeenlengte <= 110) {
        FrameFaktor = $("#typefiets").val();
        FrameMaat = FrameFaktor * iBeenlengte;
        switch (FrameFaktor) {
            case "0.227":
                sAdvies = sAdvies + 'De dichtstbijzijnde framemaat is voor uw ingevuld.';
                FrMaat = (FrameMaat * 2.54);
                break;
            case "0.665":
                sAdvies = sAdvies + 'De dichtstbijzijnde framemaat is voor uw ingevuld.';
                FrMaat = FrameMaat;
                break;
            case "0.685":
                sAdvies = sAdvies + 'De dichtstbijzijnde framemaat is voor uw ingevuld.';
                FrMaat = FrameMaat;
                break;

        }
        if (GeveerdeZadelpen == true) {
            FrMaat = FrMaat - 4;
        }

        // Select the right index after calculating
        var index = 99999999999999999;
        var diff = 999999999999999999;
        $("#jclc_framemaat").find("option").each(function(i) {
            if (parseInt($(this).val()) != 0 && $(this).val() != "") {
                var newDiff = (FrMaat - parseInt($(this).val()));
                // Make it positive
                if (newDiff < 0)
                    newDiff = newDiff - newDiff - newDiff;

                if (newDiff < diff) {
                    diff = newDiff;
                    index = i;
                }
            }
        });
        $("#jclc_framemaat").find("option").eq(index).attr("selected", "selected");

        $("#jclc_framemaat").trigger('change');

        // put down the data
        if (document.location.href.indexOf('Framematen.aspx') > 0) {
            //Framematen CMS pagina, geef de framemaat weer
            $("#framemaat").html('<b>De framemaat die het beste bij u past is: ' + FrMaat.toFixed(0) + ' cm</b>');
        }
        else {
            //Productpagina, vul de dichtstbijzijnde framemaat in 
            $("#framemaat").html('<b>' + sAdvies + '</b>');
        }
        hideFrameSizeBlock2();
    }
    else {
        alert('De beenlengte moet tussen de 60 en 110 centimeter liggen');
    }
}

//Test ClickValue heeft uitgewezen dat tabel in dit geval beter werkt dan een rekentool. De rekentool dus uitcommenten en wellicht later verwijderen
//function BerekenFramemaatLichaamslengte() {
//    var TypeFiets = "";
//    var FrMaat = 0;
//    var FrameMaat = 0;
//    var GeveerdeZadelpen = $("#LLzadelpen").is(':checked');
//    var sAdvies = "";
//    var iLichaamslengte = $("#LLlichaamslengte").val();
//    iLichaamslengte = iLichaamslengte.replace(',', '.');
//    
//    //Onderstaande functionaliteit is op basis van de tabel hieronder
//    //Lichaamslengte	Stadsfiets/Hybride	Mountainbike	Racefiets
//    //155-160 cm	    43/46 cm	        41 cm	        45 cm
//    //161-165 cm	    46/50 cm	        46 cm	        50 cm
//    //166-170 cm	    50/53 cm	        46 cm	        52 cm
//    //171-175 cm	    53/55 cm	        51 cm	        55 cm
//    //176-180 cm	    55/56 cm	        51 cm	        55 cm
//    //181-185 cm	    57/61 cm	        51 cm	        59 cm
//    //186-190 cm	    61 cm	            56 cm	        60 cm
//    //191+ cm	        61 cm	            56 cm	        60 cm

//    if (IsNumeric(iLichaamslengte) && iLichaamslengte >= 100 && iLichaamslengte <= 300) {
//        TypeFiets = $("#LLtypefiets").val();
//        switch (TypeFiets) {
//            case "Mountainbike / crosshybride":
//                sAdvies = sAdvies + 'De dichtstbijzijnde framemaat is voor uw ingevuld.';
//                if (iLichaamslengte <= 160) {
//                    FrameMaat = 41;
//                }
//                else {
//                    if (iLichaamslengte <= 170) {
//                        FrameMaat = 46;
//                    }
//                    else {
//                        if (iLichaamslengte <= 185) {
//                            FrameMaat = 51;
//                        }
//                        else {
//                            FrameMaat = 56;
//                        }
//                    }
//                }

//                FrMaat = (FrameMaat * 2.54); //inch ipv cm
//                break;
//            case "Racefiets":
//                sAdvies = sAdvies + 'De dichtstbijzijnde framemaat is voor uw ingevuld.';
//             
//                if (iLichaamslengte <= 160) {
//                    FrameMaat = 45;
//                }
//                else {
//                    if (iLichaamslengte <= 165) {
//                        FrameMaat = 50;
//                    }
//                    else {
//                        if (iLichaamslengte <= 170) {
//                            FrameMaat = 52;
//                        }
//                        else {
//                            if (iLichaamslengte <= 180) {
//                                FrameMaat = 55;
//                            }
//                            else {
//                                if (iLichaamslengte <= 185) {
//                                    FrameMaat = 59;
//                                }
//                                else {
//                                    FrameMaat = 60;
//                                }
//                            }
//                        }
//                    }
//                }
//                
//                FrMaat = FrameMaat;
//                break;
//            case "Stadsfiets / hybridefiets":
//                sAdvies = sAdvies + 'De dichtstbijzijnde framemaat is voor uw ingevuld.';
//              
//                if (iLichaamslengte <= 160) {
//                    FrameMaat = 44.5;
//                }
//                else {
//                    if (iLichaamslengte <= 165) {
//                        FrameMaat = 48;
//                    }
//                    else {
//                        if (iLichaamslengte <= 170) {
//                            FrameMaat = 51.5;
//                        }
//                        else {
//                            if (iLichaamslengte <= 175) {
//                                FrameMaat = 54;
//                            }
//                            else {
//                                if (iLichaamslengte <= 180) {
//                                    FrameMaat = 55.5;
//                                }
//                                else {
//                                    if (iLichaamslengte <= 185) {
//                                        FrameMaat = 59;
//                                    }
//                                    else {
//                                        FrameMaat = 61;
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//                
//                FrMaat = FrameMaat;
//                break;
//        }
//          
//        if (GeveerdeZadelpen == true) {
//            FrMaat = FrMaat - 4;
//        }

//        // Select the right index after calculating
//        var index = 99999999999999999;
//        var diff = 999999999999999999;
//        $("#jclc_framemaat").find("option").each(function(i) {
//            if (parseInt($(this).val()) != 0 && $(this).val() != "") {
//                var newDiff = (FrMaat - parseInt($(this).val()));
//                // Make it positive
//                if (newDiff < 0)
//                    newDiff = newDiff - newDiff - newDiff;

//                if (newDiff < diff) {
//                    diff = newDiff;
//                    index = i;
//                }
//            }
//        });
//        $("#jclc_framemaat").find("option").eq(index).attr("selected", "selected");

//        $("#jclc_framemaat").trigger('change');

//        // put down the data
//        $("#framemaat").html('<b>' + sAdvies + '</b>');
//        hideFrameSizeBlock2();
//    }
//    else {
//        alert('De lichaamslengte moet tussen de 100 en 300 centimeter liggen');
//    }
//}

function IsNumeric(sText) {
    var ValidChars = ".,0123456789";
    var IsNumber = true;
    var Karakter;

    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Karakter = sText.charAt(i);
        if (ValidChars.indexOf(Karakter) == -1)
            IsNumber = false;

    }
    return IsNumber;
}

function toggleAfwijkend() {
    if ($("#afwijkendAdres").is(":hidden")) {
        $("#afwijkendCheck").attr('checked', true);
    } else {
        $("#afwijkendAdres").attr('checked', false);
    }
    $("#afwijkendAdres").toggle();

}

/* 
------------------------------------
-------- Makkelijke functies -------
------------------------------------
*/

function optimizeSearchString(zoekstr) {
    /* 
    Alles eruit filteren behalve:
    - 0-9 (0-9)
    - a-z (a-z)
    - A-Z (A-Z)
    - Koppelstreepje (-)
    - Spaties (\s)
    Extra uitleg
    - begin met / Start regex
    - Eind met / Eind regex
    - Achter de laatste / nog een letter dus g staat voor global. Dus over hele string uitvoeren
    */
    zoekstr = zoekstr.replace(/[^0-9a-z''A-Z-\s]/g, '');
    zoekstr = zoekstr.replace(/\s+/g, ' ');
    zoekstr = trim(zoekstr);
    return zoekstr;
}

function trim(value) {
    value = value.replace(/^\s+/, '');
    value = value.replace(/\s+$/, '');
    return value;
}

function checkEmail(veld) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/i.test($('input#' + veld).val())) {
        return true;
    }
    return false;
}

function OpenInformatie() {
    document.getElementById('InformationBox').style.display = 'block';
}

function CloseInformatie() {
    document.getElementById('InformationBox').style.display = 'none';
}

jQuery.fn.anchorAnimate = function(settings) {
    settings = jQuery.extend({
        speed: 1100
    }, settings);

    return this.each(function() {
        var caller = this
        $(caller).click(function(event) {
            event.preventDefault()
            var locationHref = window.location.href
            var elementClick = $(caller).attr("href")

            var destination = $(elementClick).offset().top;
            $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, settings.speed, function() {
                window.location.hash = elementClick
            });
            return false;
        })
    })
}

function TVerzendStepBack() {
    triggerAction('StepBack');
}

function triggerAction(value) {
    document.getElementById('Action').value = value;
    var split = $("form").eq(0).attr('action').split('');
    var newStep = split[split.length - 1] - 1;
    //submitform();   
    $("form").eq(0).attr('action', '/bestellen.aspx?stap=' + newStep);
    $("form").eq(0).submit();
}

function submitform() {
    //var theForm = document.forms['aspnetForm'];
    //if (!theForm) {
    //    theForm = document.aspnetForm;
    //}
    var theForm = $('form#aspnetForm');
    theForm.submit();
}

// Bestellen afhalen bestelling
$(function() {
    $(".afhaalShow, .vest").hide();
    $(".afhaalHide").show();

    //Toon of verberg de vestigingen als voor afhalen of niet gekozen wordt
    $("[name=bezorgwijze]").click(function() {
        if ($(".afhalen").is(":checked")) {
            $(".afhaalShow").show();
            $(".afhaalHide").hide();
            if ($(".vest" + this.selectedIndex).length > 0) {
                $(".vest" + this.selectedIndex).show();
            }
            else {
                $(".vest0").show();
            }
            //Als rembours gechecked is en er wordt gekozen voor afhalen, dan iDEAL checken
            if ($("#Rembours").is(":checked")) {
                $("#Rembours").removeAttr("checked");
                $("#iDEAL").attr("checked", "checked");
                $(".uwBank").show();
            }
        }
        else {
            $(".afhaalShow, .vest").hide();
            $(".afhaalHide").show();
        }
    });

    //Toon het adres van de gekozen vestiging
    $(".vestiging").change(function() {
        $(".vest").hide();
        $(".vest" + this.selectedIndex).show();
    });

    //Toon en verberg de dropdown met banken als voor iDEAL gekozen is of niet
    $("[name=betaalmethoden]").click(function() {
        if ($("#iDEAL").is(":checked")) {
            $(".uwBank").show();
        }
        else {
            $(".uwBank").hide();
        }
    });

    if ($('div#instrVideoContainer').length > 0) {
        $('div#instrVideoContainer').flash({
            swf: 'http://www.youtube.com/v/gKxgkrfpHtc&amp;hl=en&amp;fs=1&amp;rel=0&amp;border=0&amp;color1=0xB1B1B1&amp;color2=0xCACACA',
            height: 344,
            width: 425
        });
    }

    $('a.instrVideoLink').click(function(e) {
        e.preventDefault();

        var link = $(this).attr('href');
        link = link.replace(new RegExp('watch\\?v=', 'i'), 'v/');

        $('div#instrVideoContainer').flash({
            swf: link,
            height: 344,
            width: 425
        });
    });
});

// Menu
var menuTimer = false;
function initMenu() {
    // Data opslaan
    $("#topNav a").each(function() {
        $(this).data('is-selected', $(this).parent().hasClass("selected"));

        if ($(this).parent().hasClass("selected")) {
            $text = $(this).find(".roundCenter").html();
        }
        else {
            $text = $(this).html();
        }
        $(this).data('text', $text);
    });

    // Submenu hiden
    $(".topNavSub").hide();

    $(".topNavSub").hover(
        function() {
            clearTimeout(menuTimer);
        }, function() {
            menuTimer = setTimeout(menuHide, 500);
        }
    );

    // Hover instellen
    $("#topNav a").hover(function() {
        // Timeout clearen indien nodig
        clearTimeout(menuTimer);

        // Remove selection
        menuRemoveSelected();

        // Hide alle submenu's
        $(".topNavSub").hide();

        // Make me hover!
        menuSelect($(this));

        // Activate sub menu
        $parent = $(this).parent();

        // Submenu instellen
        $(".topNavSub").each(function() {
            if ($($parent).attr("pos") == $(this).attr("pos")) {
                $(this).find("a:last").each(function() {
                    $(this).css({ 'background-image': 'none' });
                });

                $(this).show();
                $parentPos = $($parent).position();
                $(this).css({ left: ($parentPos.left + 8) });

                $(this).data('visible', true);
            }
        });
    },
    function() {
        menuTimer = setTimeout(menuHide, 500);
    });
}

function menuRemoveSelected() {
    // Back to basic
    $("#topNav .selected a").each(function() {
        $(this).parent().removeClass("selected");
        $(this).html($(this).data('text'));
    });
}

function menuHide() {
    // Remove selection
    menuRemoveSelected();

    // Selecteer standaard waarde
    $("#topNav a").each(function() {
        if ($(this).data("is-selected"))
            menuSelect($(this));
    });

    // Submenu hiden
    $(".topNavSub").hide();
}

function menuSelect(obj) {
    $(obj).parent().addClass("selected");
    var html = '<span class="roundLeft"></span><span class="roundCenter">';
    html += $(obj).data('text');
    html += '</span><span class="roundRight"></span>';
    $(obj).html(html);
}

function changeSelect() {
    $.ajax({
        type: "POST",
        url: "/product.aspx/GetPageChanges",
        data: '{ "prodId": "' + $('#prodid').val() + '", "kleur": "' + $('#jclc_kleur').val() + '", "framemaat": "' + $('#jclc_framemaat').val() + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var data = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            $("#prodChoice").html(data.html);
            if (jQuery.fn.transformSelect) {
                $("#prodChoice select").transformSelect();
            }

            var el = $(data.image);
            el.hide().appendTo("body");
            el.find("img").eq(0).load(function() {
                $("#image").html(el);
                el.show();
                $("a.lightbox").lightBox();
            });
            initDropDowns();
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(xhr.statusText);
            alert(thrownError);
        }
    });
}

function changeSetSelect() {
    var elem = $(this).closest('div.combinatieSet');

    var setNr = elem.data('setnr');
    var kleur = $('#jclc_kleur_set' + setNr).val();
    var framemaat = $('#jclc_framemaat_set' + setNr).val();

    $.ajax({
        type: 'POST',
        url: '/product.aspx/UpdateSetHTML',
        data: '{ "prodId": "' + $('#prodid').val() + '", "setNr": ' + setNr + ', "kleur": "' + kleur + '", "framemaat": "' + framemaat + '" }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(response) {
            var data = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

            var html = $(data.html);
            $('select', html).transformSelect();

            $('div.combinatieSet[data-setnr="' + setNr + '"]').replaceWith(html);

            initSetDropDowns(setNr);
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(xhr.statusText);
            alert(thrownError);
        }
    });
}

function initDropDowns() {
    $('#jclc_kleur, #jclc_framemaat, #jclc_type').change(changeSelect);
}

function initSetDropDowns(setNr) {
    if (setNr > 0) {
        $('.combinatieSet[data-setnr="' + setNr + '"] select').change(changeSetSelect);
    }
    else {
        $('.combinatieSet select').change(changeSetSelect);
    }
}

function submitAddWinkelmandje() {
    if ($('#aspnetForm').valid()) {
        document.aspnetForm.action = '/winkelmandje.aspx';
        document.aspnetForm.submit();
    }
}

function submitUrl(url, target) {
    document.aspnetForm.action = url;
    if (target != '') {
        document.aspnetForm.target = target;
    }
    document.aspnetForm.submit();
}

/**
----------------------
INIT SCROLLER
----------------------
*/
var productDetailSpeed = 5000;
var isRestart = false;

function initProductDetailScroller() {
    productDetailScrollerStart();
    $("#accessoiresScrollerDown").hover(
        function() {
            productDetailSpeed = 1000;
            productDetailScrollerRestart();
        },
        function() {
            productDetailSpeed = 5000;
            productDetailScrollerRestart();
        }
    );

    $("#accessoiresScroller").hover(
        function() {
            isRestart = true;
            $("#accessoiresScroller").stop(true, false);
        },
        function() {
            productDetailSpeed = 5000;
            productDetailScrollerRestart();
        }
    );
}

function productDetailScrollerRestart() {
    isRestart = true;
    $("#accessoiresScroller").stop(true, false);
    productDetailScrollerStart();
}

function productDetailScrollerStart() {
    // Zorg ervoor dat hij niet bij een restart, nog 20px moet en daar 3 seconden over doet
    var speed = productDetailSpeed;
    if (isRestart) {
        speed = (1 - ($("#accessoiresScroller").scrollTop() / 111)) * productDetailSpeed;
        isRestart = false;
    }

    // Scrollen
    $("#accessoiresScroller").animate({ scrollTop: 111 }, speed, "linear", function() {
        $("#accessoiresScroller").animate({ "scrollTop": 0 }, 0);
        $("#accessoiresScrollerInner").append($("#accessoiresScroller").find(".accItem:eq(0)"));
        initProductDetailScroller();
    });
}

