/*
 * Used on all pages where the footer lead form appear
 */

var FooterHome = {};

$(document).ready(function() {

    // hover images for consumption profiles
    FooterHome.consumption_options_hover_img();

    // custom style radio buttons
    //$('#aanhef_1, #aanhef_2').customInput();

    // select profile
    //FooterHome.select_consumption_profile($('.home-footer-p2'));
    $('.home-footer-p1, .home-footer-p2, .home-footer-p3, .home-footer-p4, .home-footer-p5, .home-footer-p6').click(function(){
        FooterHome.select_consumption_profile($(this));
    });

    // fill out street name
    $('#l_postcode, #l_huisnummer').bind('blur', FooterHome.postcodelookup);

    // submit form
    $('#btn_submit_footer').click(function(event) {
        event.preventDefault();
        // validate and submit
        FooterHome.submit_leads_form();
    })

    // change tabs in footer
    FooterHome.tabs_show_hide();

    // set style of top menu
    FooterHome.set_active_menu_tab();

    // placeholders
    $('#lead_form_footer label').inFieldLabels({fadeDuration: 300, fadeOpacity: 0.4});

    // custom radio
    $('#lead_form_footer').customRadioCheckbox();
    $('#form_call').customRadioCheckbox();
    
});

FooterHome.consumption_options_hover_img = function() {
    $('.home-footer-p1, .home-footer-p2, .home-footer-p3, .home-footer-p4,  .home-footer-p5, .home-footer-p6').each(function() {

        // add active class to the selected image
        $(this).click(function() {
            $('.home-footer-p1, .home-footer-p2, .home-footer-p3, .home-footer-p4, .home-footer-p5, , .home-footer-p6').each(function() {
                $(this).removeClass('active');
                $(this).attr('src', $(this).attr('src').replace(/b{0,1}\.png/, '') + '.png');
            });
            $(this).addClass('active');
            $(this).attr('src', $(this).attr('src').replace(/b{0,1}\.png/, '') + 'b.png');
        });

        $(this).mouseover(function() {
            if (!$(this).hasClass('active'))
                $(this).attr('src', $(this).attr('src').replace(/b{0,1}\.png/, '') + 'b.png');
        });

        $(this).mouseout(function() {
            if (!$(this).hasClass('active'))
                $(this).attr('src', $(this).attr('src').replace(/b{0,1}\.png/, '') + '.png');
        });
    });
}

FooterHome.select_consumption_profile = function(profile_field) {

    var profile = profile_field.attr('class');
    profile = profile.replace(/\s|active/g, '');

    var sjv = $('#l_sjv');
    var sjv_piek = $('#l_sjv_piek');
    var sjv_dal = $('#l_sjv_dal');
    var sjv_gas = $('#l_sjv_gas');

    switch(profile) {
        case 'home-footer-p1':
            sjv_piek.val(900);
            sjv_dal.val(900);
            sjv_gas.val(900);
            break;
        case 'home-footer-p2':
            sjv_piek.val(1250);
            sjv_dal.val(1250);
            sjv_gas.val(1100);
            break;
        case 'home-footer-p3':
            sjv_piek.val(1500);
            sjv_dal.val(1500);
            sjv_gas.val(1600);
            break;
        case 'home-footer-p4':
            sjv_piek.val(1800);
            sjv_dal.val(1800);
            sjv_gas.val(1800);
            break;
        case 'home-footer-p5':
            sjv_piek.val(5000);
            sjv_dal.val(5000);
            sjv_gas.val(5000);
            break;
        case 'home-footer-p6':
            sjv_piek.val(7500);
            sjv_dal.val(7500);
            sjv_gas.val(7500);
            break;
    }
    sjv.val(parseInt(sjv_piek.val()) + parseInt(sjv_dal.val()));

    // set style
    $('.home-footer-p1, .home-footer-p2, .home-footer-p3, .home-footer-p4, .home-footer-p5, .home-footer-p6').each(function() {
        $(this).removeClass('active');
    });
    profile_field.addClass('active');
}

// show toev options if address is not completely filled out
FooterHome.submit_leads_form = function() {
    if (FooterHome.val_consumption_profile()
    && FooterHome.val_title()
    && $("#lead_form_footer").validationEngine('validate')
    ) {
        $.ajax({
            url: '/includes/toev_check.php',
            data: {
                postcode: $('#l_postcode').val(),
                house_num: $('#l_huisnummer').val(),
                toevoeging: $('#l_toevoeging').val(),
                format_3: 1
            },
            dateType: 'html',
            //context: this,
            type: 'POST',
            success: function(response) {
                if (response.length > 0) {
                    $('#toev_radio_footer').html(response); // toev selection html
                    $('#toev_opt_div_footer').show();
                    //$('#submit_leads_form').val('skip');
                } else {
                    // empty response - either address is ok or not found
                    // in both cases go on with submit
                    $('#lead_form_footer').submit();
                }
            },
            error: function () {
                // error at checking address
                // try to save the lead anyway
                $('#lead_form_footer').submit();
            }
        });
    }
}

// get street name via postcode
FooterHome.postcodelookup = function() {
	if (!$('#l_postcode') || $('#l_postcode').val() == '') return;
    if (!$('#l_huisnummer') || $('#l_huisnummer').val() == '') return;

    $.ajax({
        url: '/services/postcodelookup_json.php',
        data: {
            query: $('#l_postcode').val().replace(/ /g, '') + $('#l_huisnummer').val().replace(/\D/g, '')
        },
        dataType: 'json',
        //context: this,
        type: 'POST',
        success: function(response) {
            if (response.straatnaam) {
                $('#l_straatnaam').val(response.straatnaam);
                $('#l_woonplaats').val(response.plaatsnaam);
            }
        },
        error: function () {
        }
    });
}
FooterHome.select_toev_option = function (info) {
    if (info.huisnummertoevoeging) $('#l_toevoeging').val(info.huisnummertoevoeging);
    if (info.ean) $('#l_ean_electricity').val(info.ean);
    if (info.beheerderean) $('#l_beheerderean').val(info.beheerderean);
    $('#toev_opt_div_footer').hide();
    $('#lead_form_footer').submit();

    // check meter type
    // @todo-ico
}
FooterHome.val_title = function() {
    if (!$('#aanhef_1, #aanhef_2').is(':checked')) {
        $('#tr_aanhef').validationEngine('showPrompt', 'Kies \'De heer\' of \'Mevrouw\'.', 'red');
        return false;
    }
    
    $('#tr_aanhef').validationEngine('hidePrompt');
    return true;
}
FooterHome.val_consumption_profile = function() {
    if ($('#div_profile img.active').length == 0) {
        $('#div_profile').validationEngine('showPrompt', 'Kies een verbruiksprofiel. Klik op een van de plaatjes.', 'red');
        return false;
    }

    $('#div_profile').validationEngine('hidePrompt');
    return true;
}
// Show/hide tabs at the footer
FooterHome.tabs_show_hide = function() {
    $('ul.tabNav a').click(function() {
        var curChildIndex = $(this).parent().prevAll().length + 1;
        $(this).parent().parent().children('.current').removeClass('current');
        $(this).parent().addClass('current');
        $(this).parent().parent().next('.tabContainer').children('.current').show('fast',function() {
            $(this).removeClass('current');
            $(this).parent().children('div:nth-child('+curChildIndex+')').hide('normal',function() {
                $(this).addClass('current');
            });
        });

        // show/hide profiles
        if (curChildIndex == 2) {
            $('#profiles_consumer').hide();
            $('#profiles_business').show();
            $('#l_zakelijk').val('ja');
        }
        if (curChildIndex == 1) {
            $('#profiles_consumer').show();
            $('#profiles_business').hide();
            $('#l_zakelijk').val('nee');
        }
        return false;
    });
}
function val_postcode_footer(field, rules, i, options) {
    if (!$(field).val().replace(/\s/g, '').match(/^\d{4}[a-z]{2}$/i))
        return 'Postcode niet correct.';
}
function val_phone_footer(field, rules, i, options) {
    var phone = $(field).val().replace(/\D/g, '');
    if ((!phone.match(/^0[0-9]{9}$/)) || phone == '0000000000' || phone == '0123456789')
        return 'Vul een 10-cijferig telefoonnummer in';
}
FooterHome.set_active_menu_tab = function() {
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (obj, fromIndex) {
            if (fromIndex == null) {
                fromIndex = 0;
            } else if (fromIndex < 0) {
                fromIndex = Math.max(0, this.length + fromIndex);
            }
            for (var i = fromIndex, j = this.length; i < j; i++) {
                if (this[i] === obj)
                    return i;
            }
            return -1;
        };
    }
    // set active tab
    // @todo-ico move to header .js file if exists
    var page = $('#current_page_name').val();
    var css_class = 'navigatieknop1';
    if (['aanmelden'].indexOf(page) != -1) css_class = 'navigatieknop2';
    if (['groene_energie', 'groene_stroom_en_gas', 'duurzaam_energie_opwekken', 'onbeperkt_salderen', 'faq_zelf_opwek'].indexOf(page) != -1) css_class = 'navigatieknop4';
    if (['productenentarieven', 'offerteaanvraag', 'tarievenelektriciteit', 'tarievengas', 'stroometiket', 'prijshistorieelektriciteit',
        'prijshistoriegas'].indexOf(page) != -1) css_class = 'navigatieknop3';
    if (['klantenservice', 'meterstandendoorgeven_bijdeoverstap', 'meterstandendoorgeven_bijverhuizing', 'meterstandendoorgeven_bijjaarafrekening', 'meterstandendoorgeven_bijopzegging',
        'directregelen_overstappen', 'directregelen_meterstandendoorgeven', 'directregelen_voorschotbedragwijzigen',
        'directregelen_persoonsgegevenswijzigen', 'directregelen_betaalmethodewijzigen', 'directregelen_verlengencontracten',
        'faq_aanmelding', 'faq_meterstanden', 'faq_voorschotbedrag', 'faq_facturatieenincasso', 'faq_netbeheerder', 'faq_verhuizing',
        'facturenenbetalen_vastrechtbijoverstap', 'facturenenbetalen_voorschotbedrag', 'facturenenbetalen_uitlegfactuur',
        'facturenenbetalen_uitlegjaarafrekening', 'facturenenbetalen_incassotraject', 'overbudgetenergie_wiezijnwij', 'overbudgetenergie_waarstaanwijvoor',
        'overbudgetenergie_gedragscodewerving', 'overbudgetenergie_werkenbij', 'contact_contactgegevens', 'contact_klachten',
        'contact_storingsnummer'].indexOf(page) != -1) css_class = 'navigatieknop5';
    $('.'+css_class).removeClass(css_class).addClass(css_class+'b');
}
