if (typeof Number.prototype.toEur !== 'function') {
    Number.prototype.toEur = function() {
        return '\u20ac ' + this.toFixed(2).replace('.', ',');
    };
}

if (typeof String.prototype.toEur !== 'function') {
    String.prototype.toEur = function() {
        return '\u20ac ' + parseFloat(this).toFixed(2).replace('.', ',');
    };
}

$('.loginopener').live("click", function () {
    if ($('div#login .loginopener').hasClass('active')) {
        $('p.balloon').fadeIn(0);
        $('#login').children('div#loginsub').slideUp('fast', function () {
            $('#login').removeClass('active').corner('bottom 7px');
            $('div#login .loginopener').removeClass('active');
        });
    }
    else {        
        $('p.balloon').fadeOut(0);
        $('#login').children('div#loginsub').slideDown('fast', function () {
            $('#login').children('div#loginsub').children('*').fadeIn('fast', function () {
                $('#login').children('div#loginsub').children('input:first').focus();
            });
        });
        $('#login').addClass('active').uncorner();
        $('div#login .loginopener').addClass('active');    
    }   
});

$('.login-close').live("click", function () {
    if ($('div#login .loginopener').hasClass('active')) {
        $('p.balloon').fadeIn(0);
        $('#login').children('div#loginsub').slideUp('fast', function () {
            $('#login').removeClass('active').corner('bottom 7px');
            $('div#login .loginopener').removeClass('active');
        });
    }
    else {
        $('p.balloon').fadeOut(0);
        $('#login').children('div#loginsub').slideDown('fast', function () {
            $('#login').children('div#loginsub').children('*').fadeIn('fast', function () {
                $('#login').children('div#loginsub').children('input:first').focus();
            });
        });
        $('#login').addClass('active').uncorner();
        $('div#login .loginopener').addClass('active');
    }  
});

function invokeControls(element, text, optionstring, whatPlan) {
    $.ajax({
        type: "POST",
        url: "/SimpelBundelService.asmx/" + optionstring,
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: function(response) {
            if (response.d == '') {
                $('div#frontpage_mid').html('<h2 class="frontpage">Fout tijdens inladen van de gegevens.</h2>');
            }
            else {
                addControls(element, text, response.d, whatPlan);
            }
        },
        error: function(response) {
            $('div#frontpage_mid').html('<h2 class="frontpage">Fout tijdens inladen van de gegevens.</h2>');
        }
    });
}

function addControls(element, text, subscriptions, whatPlan) {
    var controls = element.children('div.front_controls');
    //controls toevoegen
    controls.append('<img src="static/images/frontpage/plus_active.png" alt="plus" id="' + element.attr('id').replace('front_', 'control_') + '_plus" class="plus" />');
    controls.append('<img src="static/images/frontpage/min_active.png" alt="min" id="' + element.attr('id').replace('front_', 'control_') + '_min" class="min" />');
    $(element).data('plan', subscriptions);
    $(element).data('currentplan', whatPlan);
    
    $(element).find('.box_left').append('<dl class="plans"></dd>')
    
    //tooltip PLUS
    controls.children('.plus').bind("mouseenter mouseleave", function() {
        $(this).siblings('span.uitleg').text('meer ' + text).toggleClass('front_showttp').css('top', $(this).position().top + 'px');
    });

    //tooltip MIN
    controls.children('.min').bind("mouseenter mouseleave", function() {
    $(this).siblings('span.uitleg').text('minder ' + text).toggleClass('front_showttp').css('top', $(this).position().top + 'px');
    });

    var element_count = 0;
    for (elements in subscriptions) { element_count = subscriptions[elements].Index; }
    if (!whatPlan || element_count < whatPlan || whatPlan < -1) {
        var whatPlan = 0;
    }

    controls.children('.min').bind('click', function() {
        var newval = parseFloat(element.data('currentplan')) - 1;
        if (newval <= -1) {
            return;
        }
        element.data('currentplan', newval);
        updatePricing(element, newval);
        BuildOverzicht(element, text, newval);
    });
    
    controls.children('.plus').bind('click', function(){
        var newval = parseFloat(element.data('currentplan')) + 1;
        if (newval > element_count) {
            return;
        }
        element.data('currentplan', newval);
        updatePricing(element, newval);
        BuildOverzicht(element, text, newval);
    });
    BuildOverzicht(element, text, whatPlan);
    updatePricing(element, whatPlan);
}

function updatePricing(element, todo) {
    if (undefined == todo || undefined == element || isNaN(todo)) { alert('error: ' + todo); return; }
    var subscriptions = element.data('plan');
    var high = 0;
    var low = 999;
    for (i in subscriptions) {
        if (subscriptions[i].Index > high) { high = subscriptions[i].Index; }
        if (subscriptions[i].Index < low) { low = subscriptions[i].Index; }        
        if (subscriptions[i].Index == todo) {
            $(element).find('.front_eur').html('\u20ac ' + parseFloat(subscriptions[i].Price).toFixed(2).replace('.', ',<sup class="front_eurcts">'));
            $(element).find('.front_aantal').html(subscriptions[i].NumOf);
            $(element).find('.front_aantal').data('planID', subscriptions[i].ID);
        }

    }
    $(element).find('.front_controls img').fadeTo(0, 1.0);
    if (todo >= high) {
        $(element).find('.front_controls img.plus').fadeTo(0, 0.4);
    }
    if (todo <= low) {
        $(element).find('.front_controls img.min').fadeTo(0, 0.4);
    }
    
    
    reCalc();
}

function BuildOverzicht(element, text, whatPlan) {
    var subscriptions = $(element).data('plan');
    $(element).data('currentplan', whatPlan);
    
       
    var element_count = 0;
    for (elements in subscriptions) { element_count++; }
    if (whatPlan < subscriptions[0].Index) {
        return;
    }
    if (!whatPlan || element_count < whatPlan || whatPlan < -1 || whatPlan == 0) {
        var whatPlan = 1;
        var css = { 'margin-bottom' : '5px' };
        for(i in subscriptions){
            subscriptions[i].active = false;
        }
    } else {
        for(i in subscriptions){
            if(subscriptions[i].Index == whatPlan){
                subscriptions[i].active = true;
            } else {
                subscriptions[i].active = false;
            }    
        }
        var css = { 'margin-bottom' : '0px' };
    }   
    
    var toAppend = new Array();
    var activeclass = '';
    var x = 0;
    var active_item;
    var active_found = false; 
    for (var i = 0; i < subscriptions.length; i++) {
        if (subscriptions[i].Index != 0) {
            if (subscriptions[i].active) {
                activeclass = ' class="activeplan" ';
                active_item = x;
                active_found = true;
            } else {
                activeclass = ''; 
            }
            toAppend[x] = '<dt' + activeclass + ' ind="' + subscriptions[i].Index + '">' + subscriptions[i].NumOf + '</dt><dd' + activeclass + ' ind="' + subscriptions[i].Index + '"><span class="prijs">' + subscriptions[i].Price.toEur() + '</span><span class="text">' + text + '</span></dd>';
            x++;
        }
    }

    if (active_found) {
        while (toAppend[1].substring(11, 21) != 'activeplan') {
            toAppend.unshift(toAppend.pop());
        }
    }
    
    $(toAppend.join('\n')).appendTo($(element).find('dl.plans').empty()).filter('dd, dt').css(css).bind('click', function() {
        BuildOverzicht(element, text, $(this).attr('ind'));
        updatePricing(element, $(this).attr('ind'));
    });

//    $(element).find('dl.plans').empty().append(toAppend);
//    $(element).find('dl.plans').children('dt, dd').bind('click', function(){
//        BuildOverzicht(element, text, $(this).attr('ind'));
//        updatePricing(element, $(this).attr('ind'));
//    });
}



function reCalc() {
    var totaal = 0;
    $('.front_eur:last').text('\u20ac 0');
    $('.front_eur:not(:last)').each(function() {
        totaal += parseFloat($(this).text().replace(/(\D|[,.])+/gi, '').replace(',', '.'));
    });

    var options = '';
    $('.front_aantal').each(function() {
        options += $(this).siblings('h3.front_title').text() + ':';         //titel
        options += parseFloat($(this).text()) + ':';                  //hoeveel
        options += parseFloat($(this).parent('div').siblings('.box_right').children('span.front_eur').text().substr(2).replace(',', '.'))*100 + ':';
        options += $(this).data('planID') + ','; 
        
    });
    //laatste komma eruit
    $('#fields > input').val(options.substr(0,options.length-1));
    
    totaal = '\u20ac ' + totaal.toFixed(2);
    $('.front_eur:last').html(totaal.replace('.', ',<sup class="front_eurcts">') + '</sup>');
    $('#ctl00_cphContent_link_bestel').unbind('click');
}

function ShowLogin(element){
    //slidedown
    element.children('span:first').toggle(function () {
        $('p.balloon').fadeOut(0);
        element.children('div#loginsub').slideDown('fast', function () {
            element.children('div#loginsub').children('*').fadeIn('fast', function () {
                element.children('div#loginsub').children('input:first').focus();
            });
        });
        element.addClass('active').uncorner();
        $('div#login .loginopener').addClass('active');
    },
    //slideup
    function () {
        $('p.balloon').fadeIn(0);
        element.children('div#loginsub').slideUp('fast', function () {
            element.removeClass('active').corner('bottom 7px');
            $('div#login .loginopener').removeClass('active');
        });
    });
}

function showLightBox(id){
    //lightbox popup venster tonen
    if ($.browser.msie && $.browser.version < 9) {
        $('body').children('#' + id).css({
            'background': 'transparent url(/static/images/frontpage/bg_lightbox.png)',
            'display': 'block'
        });
        $('body').children('#' + id).children('div#lightbox').fadeIn(100);
    } else {
        $('body').children('#' + id).show().children('div#lightbox').fadeIn(100);
    }
}

function hideLightBox(id) {
    if ($.browser.msie && $.browser.version < 9) {
        $('body').children('#' + id).children('div#lightbox').fadeOut(100, function() {
            $('body').children('#' + id).css({
                'background': 'transparent url(/static/images/frontpage/bg_lightbox.png)',
                'display': 'none'
            });
        });
    } else {
        $('body').children('#' + id).children('div#lightbox').fadeOut(100, function() {
            $(this).parent('#' + id).hide();
        });
    }
}

function firstCaps(string) {
    var lastSpace = -2;
    var outputString = "";
    for (a = 0; a < string.length; a++) {
        thisLetter = string.substring(a, a + 1);
        if (thisLetter == " ") {
            lastSpace = a;
        }

        if (a == 0 || a == lastSpace + 1) {
            outputString += thisLetter.toUpperCase();
        }
        else {
            outputString += thisLetter.toLowerCase();
        }
    }
    return outputString;
}    

function initLightBox(triggerelement, id, sourcepage, callbackfunction) { 
    /* 
    deze functie laadt gegevens in om te weergeven in de lightbox,
    maakt de lightbox klaar om weer te geven en zorgt voor de 
    binding.
    */

    if(id==undefined || id=='lightbox'){
        id = 'lightbox_container_element';
    }

    if (sourcepage == undefined) {
        var sourcepage = "/lightbox1.aspx #lightbox"
    }

    
    $('body').append('<div class="lightboxcontainer" id="'+ id +'"></div>');
    var container = $('body > div#' + id);
    //gegevens inladen
    if (!callbackfunction || undefined == callbackfunction) {
        container.load(sourcepage);
    } else {
        container.load(sourcepage, function() {
            eval(callbackfunction);
        });
    }
    
    //trigger binden: show
    triggerelement.data('toDisplay', id);
    triggerelement.bind('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
        var expand = $(this).data('toDisplay');
        showLightBox(expand);
        $('.button, select').corner('3px')
    });

    //trigger binden: close
    $('body > .lightboxcontainer .lightboxclose').live('click', function(event) {
        event.preventDefault();
        hideLightBox(container.attr('id'));
    });

    //preloading
    var sources = ['/static/images/frontpage/shadowtop.png', '/static/images/frontpage/shadowbottom.png', '/static/images/frontpage/vinkje.png', '/static/images/frontpage/vinkje.png', '/static/images/frontpage/bg_lightbox.png', '/static/images/frontpage/lightbox_close.png', '/static/images/zakelijk/lightbox_close_zakelijk.png']
    var x = 0;
    while (x < sources.length) {
        $('body').append('<img src=' + sources[x] + ' alt="preloading.." style="visibility: hidden; display: block; width: 1px height: 1px; position: absolute; bottom: 0px; right: 0px;">');
        x++;
    }
}

function SelectboxCalc(discount) {
    $('.totaalkosten').text('');
    var discount = (!isNaN(discount)) ? discount : 0;
    var options = [];
    $('#abonnement_kiezen_block input:checked').each(function () {
        var properties = $(this).next('label');
        options.push({
            amount: properties.find('.amounttag').text(),
            price: parseFloat(properties.find('.pricetag').text().replace(/\D+/gi, ''))
        });
    });

    $('.dit_kies_ik > table').each(function () {
        var totaal = 0;
        for (var i in options) {
            if (undefined != options[i].price || options[i].price != 0) {
                $(this).find('.box_kosten:eq(' + i + ')').html('<strong>\u20ac ' + ((options[i].price / 100).toFixed(2) + '').replace('.', ',') + '</strong>');
                totaal += options[i].price;
            } else {
                $(this).find('.box_kosten:eq(' + i + ')').html('<strong>\u20ac 0,00</strong>');
            }
            $(this).find('.box_hoeveelheid:eq(' + i + ')').text(options[i].amount);
        }
        $(this).parent().find('.totaalkosten').text(((totaal / 100) - discount).toFixed(2).replace('.', ','));

        //Extention to also calculate the values in the page itself for Initial Invoice
        var totalinitialinvoice = ((totaal / 100) - discount);
        $('.subscriptioncost').text(totalinitialinvoice.toFixed(2).replace('.', ','));
        $('.totalcostfirstpayment').text((totalinitialinvoice + (parseFloat($('.registrationcost').text().replace(/\D+/gi, '')) / 100)).toFixed(2).replace('.', ','));
    });    
}

function doTooltip(elementarr) {
    $('body .tooltipcontainer').remove();
    $('body').append('<div class="tooltipcontainer" style="background-color: white;" />');
    elementarr.each(function(index) {
        if ($(this).attr('title')) {
            $(this).data('tooltiptext', $(this).attr('title'));
        }
        $(this).data('tooltipbind', index);
        $(this).removeAttr('title');
        $(this).removeAttr('alt');
        $('body .tooltipcontainer').append('<div id="tooltip' + index + '" class="tooltipdiv"></div>');
        var selector = 'body > div.tooltipcontainer > #tooltip' + index;
        $(selector).html($(this).data('tooltiptext'));
        //$(selector).offset({ 'top': pos.top - 17, 'left': pos.left + 20 });
        $(selector).corner('4px');
        var pos = $(this).offset();
        $(selector).css({ 'position': 'absolute', 'left': (pos.left + 40) + 'px', 'top': (pos.top - 10) + 'px', 'display': 'none' });
    });

    elementarr.bind('mouseover', function(index) {
        var selector = 'body > div.tooltipcontainer > #tooltip' + $(this).data('tooltipbind');
        var pos = $(this).offset();
        $(selector).css({ 'position': 'absolute', 'left': (pos.left + 40) + 'px', 'top': (pos.top - 10) + 'px', 'display': 'none' });
        $(selector).stop();
        $(selector).fadeTo('fast', 1.0);
    });

    elementarr.bind('mouseleave', function() {
        var selector = 'body > div.tooltipcontainer > #tooltip' + $(this).data('tooltipbind');
        $(selector).fadeOut('slow');
    });

    elementarr.trigger('mouseover, mouseleave');
}


function setAbbo(element) {
    var total = element.children('.front_box_1').children('.front2').length;
        var count = 0;
        element.children('.front_box_1').children('.front2').each(function() {
        if ($(this).children('em:first').html() == 0) {
                $(this).remove();            
                count+=1;
            }
        });

    var result = total - count;

        switch (result) {
            case 1:
                element.find('.front2').css({ 'position': 'relative', 'top': '28px' });
                break;
            case 2:
                element.find('.front2').css({ 'position': 'relative', 'top': '14px' });
                break;
            default:
                //niks doen
        }
}

$('.newToolTip > img').live('click', function () {
    $(this).closest('.newToolTip').toggleClass('active');
});

$('.newToolTip-close').live('click', function (event) {
    $(this).closest('.newToolTip').removeClass('active');
    event.preventDefault();
});
