var clear;

$(document).ready(function(){
    
    var isIE6 = $.browser.msie && parseFloat($.browser.version) < 7;
    
    $('#line').css('width', $('#menuLinks').width());
    
    if(!isIE6) $('.subMenu').css('opacity', '0');
    
    makeActiveLink();
    
    animateLine('#menuLinks .active', true);
    
    $('#menuLinks > li').mouseenter(function(){
        animateLine($(this).children('a'))
    });
    $('#menuLinks > li').mouseleave(function(){
        animateLine('#menuLinks .active')
    });
    
    $('.subMenu li').each(function(){
        if ($(this).children('ul').length == 1) {
            $(this).append('<div></div>');
        } 
    });
    
    $('#menuLinks').mouseleave(function(){
        clear = setTimeout( function(){
            $('#menuLinks .subMenu:visible').each(function(){
                if(!isIE6) {
                    $(this).stop().animate({
                        opacity: 0
                    }, 100, function() {
                        $(this).hide()
                    });
                } else {
                    $(this).hide();
                }
            });
        },500);
    });
    
    $('#dContent input').live('keyup',function(e){
        $(this).attr('value', $(this).val());
    });
    
    
    $('#menuLinks li').mouseenter(function(){
        $(this).siblings('li').find('.subMenu:visible').each(function(){
            if(!isIE6) {
                $(this).stop().animate({
                    opacity: 0
                }, 100, function() {
                    $(this).hide()
                });
            } else {
                $(this).hide();
            }
        });
        
        $(this).children('.subMenu').each(function(){
            if(!isIE6) {
                $(this).stop().show().animate({
                    opacity: 1
                }, 100);
            } else {
                $(this).show();
            }
        });
        
        clearTimeout(clear);
    });
    
    $('.subMenu li').mouseleave(function(){
        if($(this).attr('class') != 'bottom'){
            $(this).css({
                background: '#FFF'
            });
        }
    })
    .mouseenter(function(){
        if($(this).attr('class') != 'bottom'){
            $(this).css({
                background: '#F6F6F6'
            });
        }
    });
    
    $('#wallImageNav a').click(function(){
        wallImage.load($(this).attr('id').substr(5));
        clearInterval(interval);
    });
    
    $('#startBlocks .block').live('mouseenter', function(){
        $(this).removeClass('block').addClass('block_hover');
    });
    
    $('#startBlocks .block_hover').live('mouseleave', function(){
        $(this).removeClass('block_hover').addClass('block');
    });
    
    wallImage.resize();
    
    $(window).resize(function(){
        wallImage.resize();
    });
    
    if ($('#wallImageNav').length) { 
        var interval = setInterval ( "wallImage.next()", 8000);
    } 
    
    

    $('.thover').click(function(){
        var that = this;
        $('.desc:visible').stop().fadeToggle("fast", function(){
            $(this).parent().parent().parent('.thover').animate({
                height:50
            });
        });
        
        if($(this).outerHeight() == 51) {
            
            $(this).stop().animate({
                height :  70 + $(this).find('.desc').outerHeight()
            }, {
                complete : function(){
                    $(this).find('.desc').stop().fadeToggle("fast");
                }
            });
        } else {
            
        }
    });
    
    $('#b1 input[type=checkbox]:checked').each(function(){
        checked(this);
    });
    
    if ($('.firstList').length){
        checked2();
    }
    
    $('.firstList').change(function(){
        checked2();
    })
   
    $('#b1 input[type=checkbox]').live('click', function(){
        checked(this);
    });
    
    var page = 1;
    
    var pages = [];
    var modules = [];
    var info = [];
    var totaalBedrag;
    var regex = [];
    regex['voorzetsel'] = '';
    regex['voornaam'] = '';
    regex['tussenvoegsel'] = '';
    regex['achternaam'] = '';
    regex['email'] = '([a-zA-Z0-9-_+]+)@([a-zA-Z0-9]+).([a-zA-Z]{2,4})';
    regex['telefoon'] = '[0-9]{6,20}';
    regex['bedrijfsnaam'] = '';
    regex['factuuradres'] = '';
    regex['postcode'] = '[0-9]{4}[a-zA-Z]{2}';
    regex['plaats'] = '';
    regex['bank'] = '';
    regex['rekeningnummer'] = '[0-9]{6,20}';
    regex['naamrek'] = '';
    
    $('.prev').click(function(){
        page--;
        $('.blockContainer').stop().animate({
            'left': -(428 * (page-1))
        });
        
        $('.stappen div').each(function(){
            if ($(this).hasClass('active')){
                $(this).removeClass('active');
                $(this).prev().addClass('active');
                return false;
            } 
        });
        
        if(page == 1) $(this).hide();
        if(page == 2) $('.next').show();
        $('#send').hide();
        
    });
    
    $('#b2 :input').mouseenter(function(){
        
        if ($(this).is(":focus")) {
            } else if ($(this).css('border-top-style') == '1px solid #DD4B39'){
            } else {
                $(this).css('border', '1px solid #777');
            }
    }).mouseleave(function(){
        if ($(this).is(":focus")) {
            } else if ($(this).css('border-top-style') == '1px solid #DD4B39'){
            } else {
                $(this).css('border', '1px solid #CCC');
            }
    }).focus(function(){
        $(this).css('border', '1px solid #4d90fe');
    }).blur(function(){
        $(this).css('border', '');
    })
    
    
    $('#send').mouseup(function(){
              
        if ($('#validAg').is(':checked') ) {
            if ($('#rechapta').contents().find('#recaptcha_response_field').val() != '') {
                
                var bill = $('#bill').html().replace(/\u20ac/g, '&euro;');
                $.ajax({
                    type    : 'POST',
                    dataType: 'json',
                    url     : 'http://www.telemos.nl/templates/resources/send/verzonden.php',
                    data    : {
                        recaptcha_challenge_field : $('#rechapta').contents().find('#recaptcha_challenge_field').val(),
                        recaptcha_response_field : $('#rechapta').contents().find('#recaptcha_response_field').val(),
                        contact : $('#summary').html(),
                        pakket :  bill
                    },
                    succes  : function(i){
                        console.log(i);
                    },
                    error : function(i) {
                        if (i.responseText == 'incorrect-captcha-sol') {
                            $('#rechapta').attr('src', $('#rechapta').attr('src'));
                            alert('Validatie incorrect, probeert u het nog eens');
                            
                        } else if (i.responseText == 'mail sent'){
                            $('#leftColumn').html('Hartelijk dank voor uw inschrijving.');
                        }
                    }
                });
            } else {
                alert('Voer de reChapta validatie in.')
            }
        } else {
            alert('U bent nog niet akkoord gegaan met de algemene voorwaarden.')
        }
            
    });
        
    $('.next').click(function(){
        page++;
                
        if(page == 2) {
            $('.stappen div').each(function(){
                if ($(this).hasClass('active')){
                    $(this).removeClass('active');
                    $(this).next().addClass('active');
                    return false;
                } 
            });
            $('.prev').show();
            $('.blockContainer').stop().animate({
                'left': -(428 * (page-1))
            });
        }
        
        
        
        if(page == 3) {
            var input = $('#b2 :input').serializeArray();
            $('.attent').remove();
            $('#b2 :input').css('border', '');
            var first = true;
            var x = 0;
            $.each( input, function(k, v){
                if (v.value != "" || v.name == 'tussenvoegsel') {
                    var thisregex = new RegExp(regex[v.name],"g");
                    if (thisregex.test(v.value)) {
                        x++;
                        if (x == input.length) {
                            $('.stappen div').each(function(){
                                if ($(this).hasClass('active')){
                                    $(this).removeClass('active');
                                    $(this).next().addClass('active');
                                    return false;
                                } 
                            });
                            $('#send').show();
                            $('.next').hide();
                            var a = '';
                            if (input[3].value != '') a = ' ';
                                
                            a = 
                                '<h3>Factuur adres</h3>' 
                                + input[0].value + ' ' + input[1].value + a + input[2].value + ' ' + input[3].value + '<br/>' 
                                + input[6].value + '<br/>'
                                + input[7].value + '<br/>'
                                + input[8].value + ' ' + input[9].value + '<br/><br/>'
                                + '<h3>Rekening nummer</h3>' 
                                + 'Bankrekening ' + input[11].value + ' (' + input[10].value + ')<br/>' 
                                + 't.n.v. '+ input[12].value + '<br/><br/>'
                                + '<h3>Contactgegevens</h3>' 
                                + input[4].value + '<br/>' 
                                + input[5].value + '<br/>';
                            
                            $('#summary').html(a);
                                
                            $('.blockContainer').stop().animate({
                                'left': -(428 * (page-1))
                            });
                        }
                    } else {
                        if (first) {
                            page--;
                            first = false;
                        }
                        $("#"+v.name).css('border', '1px solid #DD4B39');
                        $("#"+v.name).parent().append('<div class="attent">Voer een geldig ' + v.name + ' in</div>');
                    }
                } else {
                    if (first) {
                        page--;
                        first = false;
                    }
                    $("#"+v.name).css('border', '1px solid #DD4B39');
                    $("#"+v.name).parent().append('<div class="attent">Veld is leeg</div>');
                }
            });
            
        }
        
    });
      
});

function checked(obj) {
    var a1 = $(obj).siblings('label').children('a').text();
    var a2 = a1.replace(" ", "_");
        
    var c1 = $(obj).siblings('label').text()
    .substr(a1.length+3, $(obj).siblings('label').text().length-a1.length-4);
        
    var c2 = parseInt(c1.substr(1, c1.length-3));
        
    var c3 = parseInt($('.eindBedrag span').text()
    .substr(1, $('.eindBedrag span').text().length-3));
        
    if($(obj).attr('checked')){
        $(obj).attr('checked', 'checked');
        $('#kosten').append(' \n\
            <p id="'+ a2 + '">     \n\
            '+ a1 + '              \n\
            <span>'+ c1 + '</span> \n\
            </p>')
        $('.eindBedrag span').html('&euro;' + (c3 + c2) + ',-');
    } else {
        $(obj).removeAttr('checked');
        $('#' + a2).remove();
        $('.eindBedrag span').html('&euro;' + (c3 - c2) + ',-');
    }
}

function checked2() {
    var c3 = parseInt($('.eindBedrag span').text()
    .substr(1, $('.eindBedrag span').text().length-3));
    
    var c2 =  $('.firstList option:selected').val()*10;
    
    var c1 = parseInt($('#gebr span').text().substr(1, $('#gebr span').text().length-3) );
    
    if ($('#gebr').length) { 
        c3 = c3 - c1;
        $('#gebr').remove();
    }
    $('#kosten').append(' \n\
            <p id="gebr">'+ $('.firstList option:selected').val() +' Gebruiker(s)\n\
            <span>&euro;'+ ($('.firstList option:selected').val()*10) + ',-</span> \n\
            </p>')
        $('.eindBedrag span').html('&euro;' + (c2 + c3) + ',-');
}

function makeActiveLink () {
    var URISegments = document.URL.substr(7).split("/");
    
    $.each(URISegments, function(k,v){
        if (v != ''){ 
            $("#menuLinks > li > a:contains('" + (v.charAt(0).toUpperCase() + 
                this.slice(1)) + "')").addClass('active');
        }
    });
    
    if (!$('#menuLinks > li > .active').length) {
        $("#menuLinks > li > a:contains('Home')").addClass('active');
    } 
}

function animateLine(i, css) {
    var menuOffset = $('#menuLinks').offset();
    var activeOffset = $(i).offset();
    
    if (!css) { 
        $('#yellowLine').stop().animate({ 
            'width' : $(i).parent().width(),
            'left' : activeOffset.left - menuOffset.left - 30 // door de padding die nodig was voor ie6
        }, Math.abs((activeOffset.left - menuOffset.left) - parseInt($('#yellowLine').css('left')))*2.5);
    } else {
        $('#yellowLine').css({
            'width' : $(i).parent().width(),
            'left' : activeOffset.left - menuOffset.left - 30 // door de padding die nodig was voor ie6
        });
    }
}

var wallImage = {
    resize : function () {
        var x_scale = $(window).width() / 2250;
        var y_scale = $(window).height() / 1250;
        
        if (x_scale >= y_scale) {
            $('#wallImage').css({
                width: 2250 * x_scale,
                marginTop: -(1250 * x_scale / 2),
                marginLeft: -(2250 * x_scale / 2)
            });
        } else {
            $('#wallImage').css({
                width: 2250 * y_scale,
                marginTop: -(1250 * y_scale / 2),
                marginLeft: -(2250 * y_scale / 2)
            });
        }
        
    },
    load : function (i) {
        $('#wallImageNav .active').removeClass('active');
        $('#Image'+ i).addClass('active');
        
        $('#wallImage .active').css('display', 'none').removeClass('active');
        $('#wallImage' + i).css('display', 'block').addClass('active');
        
        $('#wallImageText .active').css('display', 'none').removeClass('active');
        $('#wallImageText' + i).css('display', 'block').addClass('active');
        
    },
    next : function () {
        
        var ID = parseInt($('#wallImage .active').attr('id').substr(9));

        if (ID >= $("#wallImage").children().length) {
            ID = 1;
        } else {
            ID++;
        }
        wallImage.load(ID);
    }
}
