// Trim functie aan string toevoegen, tenzij de browser deze native al heeft
if (!String.prototype.trim) {
    String.prototype.trim = function() {
        var result = this.replace(/^\s\s*/, '');
        var ws = /\s/;
        var i = result.length;
        while (ws.test(result.charAt(--i)));
        return result.slice(0, i + 1);
    }
}

$(function() {
    ombouw.init();

    if (location.host !== 'werco2011.juicedev.nl') {
        // Ajax errors mailen
        $(document).ajaxError(function(e, jqxhr, settings, exception) {
            mailError(JSON.stringify(jqxhr), JSON.stringify(settings));
        });
    }

    $('div#newsLetterForm > input').bind({
        focus: function() {
            if ($(this).val() === $(this).prop('defaultValue')) {
                $(this).val('');
            }
        },
        blur: function() {
            if ($(this).val() === '') {
                $(this).val($(this).prop('defaultValue'));
            }
        },
        keydown: function(e) {
            if (e.which === 13) {
                e.preventDefault();
                $(this).next('div').click();
            }
        }
    });

    $('div#newsLetterForm > div').click(function() {
        goTo('/inschrijven-nieuwsbrief.aspx?email=' + $('div#newsLetterForm > input').val());

        //    // Oude messages die nog staan verwijderen
        //    $('div.newsLetterMsg').remove();

        //    var form = $('div#newsLetterForm');

        //    if (!form.data('busy')) {
        //        form.data('busy', true);

        //        addNewsletterSignup(
        //            $('div#newsLetterForm > input').val(),
        //            footerNewsletterSignupCallback,
        //            function() {
        //                form.data('busy', false);
        //            }
        //        );
        //    }
    });
});

var ombouw = {
    // Initializes the homepage
    // search transform and resetinput
    init: function() {
        // Geselecteerde menu item zetten
        var selectedMenuItem = $('ul#topNav').data('selected');
        $('ul#topNav > li > a[href="' + selectedMenuItem + '"]').parent().addClass('selected');

        if ($.browser.opera) {
            $("body").addClass("opera");
        }

        $("#search select").change(function() {
            var elem = $('#search .trans-element > li > span');

            elem.removeAttr('title');
            $('span.dots', elem).remove();

            if (elem.prop('scrollWidth') > elem.outerWidth()) {
                elem.attr('title', elem.text());
                $(elem).append($('<span class="dots" />').text('...'));
            }
        }).transformSelect();

        $('div#searchBtn').click(function() {
            var search = $('input#searchInput');

            if (search.val().trim() !== '' && search.val() !== search.prop('defaultValue')) {
                goTo('/reizen.aspx#traveltype=' + $('select#searchType').val() + '&search=' + search.val());
            }
        });
        $('input#searchInput').bind({
            keydown: function(e) {
                if (e.which === 13) {
                    $('div#searchBtn').click();
                }
            },
            focus: function() {
                if ($(this).val() === $(this).prop('defaultValue')) {
                    $(this).val('');
                }
            },
            blur: function() {
                if ($(this).val().trim() === '') {
                    $(this).val($(this).prop('defaultValue'));
                }
            }
        });
              
        if ($(".suggestInput").length !=0) {
            //Vul elke suggestieve input met zijn "data-value"
            $(".suggestInput").each(function () {
                if ($(this).val() == '') {
                    $(this).val($(this).data("value"))
                }
            });
            
            //Bij het focussen verwijder de tekst als deze "standaard" is
            $(".suggestInput").focus(function () {
                if ($(this).val() == $(this).data("value")) {
                    $(this).val('')
                }
            });
            
            //Bij het verliezen van focus: orgineel terug plaatsen als er geen tekst ingevuld is...
            $(".suggestInput").blur(function () {
                if ($(this).val() == '') {
                    $(this).val($(this).data("value"))
                }
            });
        }
        
        //Stel de "bel me terug" knop in
        if ($(".callbackbtn").length != 0) {
            $(".callbackbtn").unbind("click");
            $(".callbackbtn").click(function() {
                var target = "/bel-mij-terug.aspx"
                if ($(".callbackInput").val() != $(".callbackInput").data("value")) {
                    target += "?phone=" + $(".callbackInput").val();
                } 
                goTo(target);
            });
        }

        //Stel de "aanmelden" (nieuwsbrief) knop in
        if ($(".newsbtn").length != 0) {
            $(".newsbtn").unbind("click");
            $(".newsbtn").click(function() {
                var target = "/inschrijven-nieuwsbrief.aspx"
                if ($(".newsInput").val() != $(".newsInput").data("value")) {
                    target += "?email=" + $(".newsInput").val();
                }
                goTo(target);
            });
        }
    }
}

// Voegt een nieuwsbrief aanmelding toe. Optioneel zijn de callbacks voor zowel
// success als complete te zetten.
function addNewsletterSignup(email, callbackSuccess, callbackComplete) {
    var settings = {
        type: 'POST',
        url: '/Ajax.aspx/HandleNewsletterSignup',
        data: JSON.stringify({ email: email }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json'
    };

    // Callbacks toevoegen, maar alleen als deze goed gezet zijn
    if (typeof callbackSuccess === 'function') {
        $.extend(settings, { success: callbackSuccess });
    }
    if (typeof callbackComplete === 'function') {
        $.extend(settings, { complete: callbackComplete });
    }
    
    // Aanmelding versturen via Ajax met de aangeleverde settings
    $.ajax(settings);
}

function footerNewsletterSignupCallback(response) {
    var data = (typeof response.d) === 'string' ? eval('(' + response.d + ')') : response.d;

    var form = $('div#newsLetterForm');

    // Zwevend boxje maken met info
    var msgBox = $('<div></div>');
    msgBox.addClass('newsLetterMsg');
    msgBox.css('opacity', 0);
    msgBox.text(data.message);
    msgBox.appendTo('body');
    msgBox.css({
        'left': (form.offset().left + ((form.width() - msgBox.outerWidth()) / 2)) + 15,
        'top': (form.offset().top - msgBox.outerHeight()) - 5
    });

    if (data.success === true) {
        msgBox.addClass('success');

        msgBox.fadeTo(400, 0.8);

        setTimeout(function() {
            msgBox.fadeOut();
        }, 5000);
    }
    else {
        msgBox.addClass('error');

        msgBox.fadeTo(400, 0.8);

        setTimeout(function() {
            msgBox.fadeOut();
        }, 5000);
    }
}

// Navigeren en posten
function goTo(url) {
    location.assign(url);
}

function postTo(url) {
    $('form#aspnetForm').attr('action', url).submit();
}

function post() {
    postTo(location.href);
}

// Overige functies
function mailError(message, varString) {
    $.ajax({
        type: 'POST',
        url: '/Ajax.aspx/MailError',
        data: JSON.stringify({ message: message, variablen: varString }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function() { }
    });
}

// Centreert een image verticaal
function centerImg() {
    var container = $(this).parent();
    while (container.css('display') !== 'block') {
        // Container moet een block element zijn
        container = container.parent();
    }
    $(this).css('margin-top', (container.height() - $(this).height()) / 2);
}

