/***********************************************************************
    Init
***********************************************************************/
window.onscroll = function()
{
    again = window.setTimeout('positionMenu()', 1000);
}

window.onresize = function()
{
    again = window.setTimeout('positionMenu()', 10);
}

$(document).ready(function ()
{
    if ($('#page') != null && $('#page').hasClass('subtree_level_2_node_id_100')) {
        $('#content > p').click(function()
        {
            $(this).toggleClass('open');
        });
    }
    if ($('#page') != null && $('#page').hasClass('subtree_level_3_node_id_166')) {
        tabs();
        if ($('#tab2') != null) {
            $('#tab2 .notice select').change(function()
            {
                if ($(this).val() == $(this).children().length - 1) {
                    $(this).next().css('display', 'inline');
                } else {
                    $(this).next().removeAttr('style');
                }
            });
        }
    }
    $('a.replace-this-link').each(function()
    {
        var str = 'mailto:' + replaceEmail($(this).attr('href'));
        $(this).attr('href', str);
    });
    $('a.replace-this-link span').each(function()
    {
        var str = replaceEmail($(this).html());
        $(this).html(str);
    });
});

/***********************************************************************
    Replace EMail
***********************************************************************/

function replaceEmail(str)
{
    return str.replace(/\/replace-this-link\//g, '@');
}

/***********************************************************************
    Preview
***********************************************************************/

function showPreview(e)
{
    if ($(e) != null && $('#preview') != null) {
        $('#preview').html($(e).html());
        $('#preview').click(function()
        {
            hidePreview();
        });
        $('#preview').attr('style', $(e).attr('style'));
        $('#preview').removeClass('hide');
        var pageScroll = 0;
        if (self.pageYOffset) {
            pageScroll = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            pageScroll = document.documentElement.scrollTop;
        } else if (document.body) {
            pageScroll = document.body.scrollTop;
        }
        var width = parseInt($('#preview').css('width'));
        $('#preview').css('margin-left', -1*width/2);
        $('#preview').css('top', pageScroll + 30);
    }
}

function hidePreview()
{
    if ($('#preview') != null) {
        $('#preview').addClass('hide');
        $('#preview').removeAttr('style');
        $('#preview').html('');
    }
}

/***********************************************************************
    Navigation
***********************************************************************/
var stylePosition = 139;
var theoreticalPosition = stylePosition;
var again;

function positionMenu()
{
    // parameters
    var spaceTop = 10;
    var repeatInterval = 33;
    var moveDivisor = 300;
    var maxAcceleration = 0.5;
    var currentAcceleration = 0;

    // page scroll
    var pageScroll = 0;
    if (self.pageYOffset) {
        pageScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        pageScroll = document.documentElement.scrollTop;
    } else if (document.body) {
        pageScroll = document.body.scrollTop;
    }
    if (typeof pageScroll == "undefined") pageScroll = document.body.scrollTop;
    if (typeof pageScroll == "undefined") return;

    var thisLayer = document.getElementById("left");
    if (!thisLayer || !thisLayer.style) return;

    if (pageScroll > stylePosition - spaceTop) {
        var idealPosition = pageScroll + spaceTop;
        var diff = (pageScroll + spaceTop - theoreticalPosition) / moveDivisor;
    } else {
        var idealPosition = stylePosition;
        var diff = (stylePosition - theoreticalPosition) / moveDivisor;
    }
    if (diff > maxAcceleration) diff = maxAcceleration;
    if (diff < -maxAcceleration) diff = -maxAcceleration;
    currentAcceleration += diff;
    theoreticalPosition += currentAcceleration;
    thisLayer.style.top = Math.round(theoreticalPosition) + 'px';
    if (idealPosition != Math.round(theoreticalPosition)) again = window.setTimeout("positionMenu()", repeatInterval);
}

/***********************************************************************
    Tabs
***********************************************************************/

function tabs(child)
{
    if (child == null) {
        child = 0;
    }
    var tabs, i, c, tabnav;
    tabs = document.getElementById('applicationform').getElementsByTagName('div');
    c=0;
    for (i=0;i<tabs.length;i++) {
        if (tabs[i].className != 'tabs' && tabs[i].className != 'tabshidden') {
            continue;
        }
        tabnav = document.getElementById('tabnav-' + c);
        if (child==c) {
            tabs[i].className = 'tabshidden';
            tabs[i].className = 'tabs';
        } else {
            tabs[i].className = 'tabs';
            tabs[i].className = 'tabshidden';
        }
        if (tabnav != null) {
            switch (true) {
                case (child==c):
                    tabnav.setAttribute('class', 'current');
                    break;
                case (c > child):
                    tabnav.removeAttribute('onclick');
                    tabnav.setAttribute('class', 'disabled');
                    break;
                default:
                    tabnav.setAttribute('onclick', 'tabs('+c+');');
                    tabnav.removeAttribute('class');
            }
        }
        c++;
    }
}

/***********************************************************************
    Form Validation
***********************************************************************/

function checkTab(e, next)
{
    if (e == 2) {
        if (!checkTab(0)) {
            tabs(0);
            return false;
        }
        if (!checkTab(1)) {
            tabs(1);
            return false;
        }
        tabs(2);
    }
    if (!checkForm('#tab' + e)) {
        return false;
    }
    if (next >= 0) {
        tabs(e+1);
    }
    return true;
}

function checkForm(e)
{
    var error = 0;
    var emailerror = 0;
    var message = '';
    var file = false;
    var fileerror = false;
    var checkbox = false;

    if ($(e) == null) {
        return false;
    }
    $(e + ' .required').each(function()
    {
        if ((!$(this).hasClass('checkbox') && $(this).val() && $(this).val() != 0) || ($(this).hasClass('checkbox') && $(this).attr('checked'))) {
            if ($(this).hasClass('validate-email') && !checkEmail($(this).val())) {
                $(this).addClass('missing');
                error++;
                emailerror++;
                message += (SITEACCESS == 'en') ? "The e-mail address you entered is invalid.\n" : "Die angegebene E-Mail-Adresse ist fehlerhaft.\n";
            } else if ($(this).hasClass('file') && !checkFile($(this).val())) {
                $(this).addClass('missing');
                error++;
                fileerror = true;
            } else {
                $(this).removeClass('missing');
            }
        } else {
            if ($(e).attr('id') != null && $(e).attr('id') == 'tab2') {
                if ($(this).hasClass('file')) {
                    file = true;
                }
                if ($(this).hasClass('checkbox')) {
                    checkbox = true;
                }
            }
            $(this).addClass('missing');
            error++;
        }
    });
    if (error > 0) {
        if ($(e).attr('id') != null && $(e).attr('id') == 'tab1') {
            message += (SITEACCESS == 'en') ? "Please give us some details in each area. Thank you.\n" : "Bitte machen Sie zu jedem Bereich mindestens eine Angabe. Danke.\n";
        } else if ($(e).attr('id') != null && $(e).attr('id') == 'tab2') {
            if (file == true) {
                message += (SITEACCESS == 'en') ? "Please upload all required documents, grouped as indicated. Thank you.\n" : "Bitte laden Sie Ihre Unterlagen vollständig und in der angegebenen Aufteilung hoch. Danke.\n";
            }
            if (fileerror == true) {
                message += (SITEACCESS == 'en') ? "Please use Word documents (.doc) or PDF files (.pdf). Thank You.\n" : "Die Datei konnte nicht gespeichert werden. Bitte laden Sie nur Word- oder PDF-Dokumente hoch (Dateigröße max. 5 MB). Danke.\n";
            }
            if (checkbox == true) {
                message += (SITEACCESS == 'en') ? "Please confirm you have read our privacy statement. Thank you.\n" : "Bitte bestätigen Sie, dass Sie die Hinweise zum Datenschutz gelesen haben. Danke.\n";
            }
        } else {
            if (error > emailerror) {
                message += (SITEACCESS == 'en') ? "Please fill in at least all the mandatory fields. Thank you.\n" : "Bitte füllen Sie mindestens alle Pflichtfelder aus. Danke.\n";
            }
        }
        alert(message);
        return false;
    }
    return true;
}

function checkEmail(str)
{
    if (str.length < 6) return false;
    if (str.indexOf("@") == -1 || str.indexOf("@") == 0 || str.lastIndexOf("@") > str.length-5) return false;
    if (str.indexOf(".") == -1 || str.indexOf(".") == 0 || str.lastIndexOf(".") > str.length-3) return false;
    if (str.lastIndexOf(".") < str.lastIndexOf("@") + 2) return false;
    if (str.indexOf("\"") == 0 && str.lastIndexOf("\"") != str.lastIndexOf("@")-1) return false;
    if (str.indexOf("\"") == 0 && str.lastIndexOf("\"") == 0) return false;
    var pattern = /^.+\@(\S+\.)+([a-zA-Z]{2,6})+$/;
    if (!pattern.test (str)) return false;
    var domOK = true;
    var forbidden = "!#$%&'()*+,;:<=>?^`{|}~¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿/\_[]÷— ";
    for (i = str.lastIndexOf("@"); i < str.length; i++) if (forbidden.indexOf(str.charAt(i)) != -1) domOK = false;
    return true;
}

function checkFile(str)
{
    if (str.length < 5) return false;
    var exts = 'pdf|doc|docx';

    var re = new RegExp("^.+\.(" + exts+ ")$", "i");
    return (re.test(str)) ? true : false;
}
