var cName = 'doorkeeperGlDk';
var redirect = true;

if (typeof isDoorkeeperPage != 'undefined') {
    if (isDoorkeeperPage == true) {
        redirect = false;
    }
}

if (!$.cookie(cName) && redirect == true) {
    document.location.href = "/doorkeeper.aspx?gotoUrl=" + encodeURI(document.location.href);
}

$(document).ready(function () {

    $(".disclaimer").fancybox({ 'padding': 0 });

    // door keeper age validation
    $("#doorkeeperButton").live("click", function (event) {
        event.preventDefault();
        var country = jQuery("#doorkeeperCountry").val();
        var day = jQuery("#doorkeeperDay").val();
        var month = jQuery("#doorkeeperMonth").val();
        var year = jQuery("#doorkeeperYear").val();
        //var age = 18;
        var ready = true;
        if (getUrlParameter('gotoUrl') != "") {
            var targetUrl = getUrlParameter('gotoUrl');
        } else {
            var targetUrl = "/";
        }
        if (day == '' || month == '' || year == '' || country == '')
            var ready = false;
        var mydate = new Date();
        mydate.setFullYear(year, month - 1, day);
        var currdate = new Date();

        age = countries[country] * 1;
        currdate.setFullYear(currdate.getFullYear() - age);

        if (countries[country] == 'not') {
            ready = false;
            alert("We regret to inform you that due to the websites contents, your country is not allowed to see it.");
        }
        else if ((currdate - mydate) < 0) {
            $('#showAllowedAge').text(age);
            if (country == "Denmark")
                alert("Beklager. Du skal være " + age + " år for at se websitet.");
            else
                alert("We regret to inform you that you have to be " + age + " years old to view this website.");
            location.href = "http://www.alkoholdialog.dk"
        }
        else if (ready == false) {
            if (country == "Denmark" || country == "")
                alert('Angiv venligst din nationalitet og fødselsdato');
            else
                alert('Please select your nationality and birthday');
        }
        else {
            $.cookie('doorkeeperGlDk', 'access')

            if ($('#rememberMe').attr('checked')) {
                $.cookie('doorkeeperValuesGlDk', $('#doorkeeperCountry').val() + ',' + $('#doorkeeperYear').val() + ',' + $('#doorkeeperMonth').val() + ',' + $('#doorkeeperDay').val(), { expires: 500 })
            }
            else {
                $.cookie("doorkeeperValuesGlDk", null);
            }
            document.location.href = targetUrl;
        }
    });

    if (typeof countries != 'undefined') {

        $.each(countries, function (key, value) {
            $('#doorkeeperCountry').append('<option value="' + key + '">' + key + '</option>');
        });
    }
    initPage();

    makeScrollOnKeyPressed()
    $('.drop-country li a').each(function (index, value) {
        if ($.trim($(this).text()) == "Denmark" || $.trim($(this).text()) == "Danmark") {
            selectMe('doorkeeperCountry', index, 0);
        }
    });

    if ($.cookie('doorkeeperValuesGlDk')) {
        var arrDoorkeeperValues = $.cookie('doorkeeperValuesGlDk').split(",");
        if (arrDoorkeeperValues.length == 4) {
            $('.drop-country li a').each(function (index, value) {
                if ($.trim($(this).text()) == arrDoorkeeperValues[0]) {
                    selectMe('doorkeeperCountry', index, 0);
                }
            });
            $('#optionsDiv3 li a').each(function (index, value) {//year
                if ($.trim($(this).text()) == arrDoorkeeperValues[1]) {
                    selectMe('doorkeeperYear', index, 3);
                }
            });


            var strSelectedMonth = $('#doorkeeperMonth option[value=' + arrDoorkeeperValues[2] + ']').text();
            $('#optionsDiv2 li a').each(function (index, value) {//month
                if ($.trim($(this).text()) == strSelectedMonth) {
                    selectMe('doorkeeperMonth', index, 2);
                }
            });
            $('#optionsDiv1 li a').each(function (index, value) {//date
                if ($.trim($(this).text()) == arrDoorkeeperValues[3]) {
                    selectMe('doorkeeperDay', index, 1);
                }
            });
            $('#rememberMe').attr('checked', true);
        }
    }

    var currentLanguage = 0;
    var arrLangData = new Array();
    arrLangData[0] = {
        'firstTextImage': '/images/text_doorkeeper.png',
        'firstTextAlt': 'Du skal være mindst 18 år for at besøge denne hjemmeside - Vælg venligst nationalitet og fødselsdato:',
        'selectDefaultDag': 'Dag',
        'selectDefaultMaaned': 'Måned',
        'selectDefaultAar': 'År',
        'textHuskMig': 'Husk mig næste gang',
        'imgFlag': '/images/flag-en.gif',
        'TextLanguageVersion': 'English version',
        'btnImage': '/images/btn_submit_doorkeeper.png',
        'btnAlt': 'Besøg siden',
        'textBottomImage': '/images/doorkeeper_bottom.png',
        'textBottomAlt': 'Gammel Dansk. Ufattelig hyggelig',
        'idTextEnjoyResponsibly': 'enjoyResponsiblyDansk',
        'idHTMLDisclaimers': 'disclaimersDansk',
        'monthMay': 'Maj',
        'monthOctober': 'Okt'
    };


    arrLangData[1] = {
        'firstTextImage': '/images/text_doorkeeper_en.png',
        'firstTextAlt': 'You have to be at least 18 years old to visit this website - Please choose your nationality and date of birth:',
        'selectDefaultDag': 'Date',
        'selectDefaultMaaned': 'Month',
        'selectDefaultAar': 'Year',
        'textHuskMig': 'Remember me',
        'imgFlag': '/images/flag-dk.gif',
        'TextLanguageVersion': 'Dansk version',
        'btnImage': '/images/btn_submit_doorkeeper_en.png',
        'btnAlt': 'Visit the website',
        'textBottomImage': '/images/doorkeeper_bottom_en.png',
        'textBottomAlt': 'Gammel Dansk. Unbelievably hyggelig',
        'idTextEnjoyResponsibly': 'enjoyResponsiblyEnglish',
        'idHTMLDisclaimers': 'disclaimersEnglish',
        'monthMay': 'May',
        'monthOctober': 'Oct'
    };
    $("#swapLanguage").live("click", function (event) {
        if (currentLanguage == 0) {//if danish, go english
            currentLanguage = 1;
            //alert("uu");
            if (getUrlParameter('lang') != "en") {
                existingGoToUrl = getUrlParameter('gotoUrl');
                newUrl = window.location.href.replace("=" + existingGoToUrl, "=/frontpage.aspx");
                newUrl += "?lang=en";
                document.location.href = newUrl;
            }
        }
        else {//if english, go danish
            currentLanguage = 0;
            existingGoToUrl = getUrlParameter('gotoUrl');
            newUrl = window.location.href.replace("=" + existingGoToUrl, "=/");
            newUrl += "?lang=da";
            document.location.href = newUrl;
        }
        $("#door-photo").attr("src", arrLangData[currentLanguage]['firstTextImage']).attr("alt", arrLangData[currentLanguage]['firstTextAlt']);
        $("#rememberLabel").html(arrLangData[currentLanguage]['textHuskMig']);
        $("#swapLanguage").html("<img src='" + arrLangData[currentLanguage]['imgFlag'] + "' alt='" + arrLangData[currentLanguage]['TextLanguageVersion'] + "' /> <span>" + arrLangData[currentLanguage]['TextLanguageVersion'] + "</span>");
        $("#doorkeeperButton").attr('style', 'background: url(' + arrLangData[currentLanguage]['btnImage'] + ') no-repeat;');
        $("#visitBtn").text(arrLangData[currentLanguage]['btnAlt']);
        $("#slogan").attr("src", arrLangData[currentLanguage]['textBottomImage']).attr("alt", arrLangData[currentLanguage]['textBottomAlt']);
        $('#enjoyResponsibly').text($('#' + arrLangData[currentLanguage]['idTextEnjoyResponsibly']).text());
        $('#disclamerHolder').html($('#' + arrLangData[currentLanguage]['idHTMLDisclaimers']).html());
        $('#mySelectText1').text(arrLangData[currentLanguage]['selectDefaultDag']);
        $('#mySelectText2').text(arrLangData[currentLanguage]['selectDefaultMaaned']);
        $('#mySelectText3').text(arrLangData[currentLanguage]['selectDefaultAar']);
        $('#optionsDiv2 ul:first li:nth-child(6) a').text(arrLangData[currentLanguage]['monthMay']);
        $('#optionsDiv2 ul:first li:nth-child(11) a').text(arrLangData[currentLanguage]['monthOctober']);
        $('#optionsDiv1 ul:first li:nth-child(1) a').text(arrLangData[currentLanguage]['selectDefaultDag']);
        $('#optionsDiv2 ul:first li:nth-child(1) a').text(arrLangData[currentLanguage]['selectDefaultMaaned']);
        $('#optionsDiv3 ul:first li:nth-child(1) a').text(arrLangData[currentLanguage]['selectDefaultAar']);
    });
    if (getUrlParameter('lang') == "en") {
        $("#swapLanguage").click();
    }


    if (navigator.userAgent.match(/android/i) || navigator.userAgent.match(/ipad/i) || navigator.userAgent.match(/iphone/i) || navigator.userAgent.match(/symbion/i)) {
        $('.optionsDivInvisible').closest('body').addClass('bodyMobile');
    }

});


function getUrlParameter(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}





function makeScrollOnKeyPressed() {
    $('.country .selectButton').keypress(function (event) {
        var arrKeys = new Array();
        arrKeys[65] = 'A';
        arrKeys[66] = 'B';
        arrKeys[67] = 'C';
        arrKeys[68] = 'D';
        arrKeys[69] = 'E';
        arrKeys[70] = 'F';
        arrKeys[71] = 'G';
        arrKeys[72] = 'H';
        arrKeys[73] = 'I';
        arrKeys[74] = 'J';
        arrKeys[75] = 'K';
        arrKeys[76] = 'L';
        arrKeys[77] = 'M';
        arrKeys[78] = 'N';
        arrKeys[79] = 'O';
        arrKeys[80] = 'P';
        arrKeys[81] = 'Q';
        arrKeys[82] = 'R';
        arrKeys[83] = 'S';
        arrKeys[84] = 'T';
        arrKeys[85] = 'U';
        arrKeys[86] = 'V';
        arrKeys[87] = 'W';
        arrKeys[88] = 'X';
        arrKeys[89] = 'Y';
        arrKeys[90] = 'Z';

        arrKeys[97] = 'a';
        arrKeys[98] = 'b';
        arrKeys[99] = 'c';
        arrKeys[100] = 'd';
        arrKeys[101] = 'e';
        arrKeys[102] = 'f';
        arrKeys[103] = 'g';
        arrKeys[104] = 'h';
        arrKeys[105] = 'i';
        arrKeys[106] = 'j';
        arrKeys[107] = 'k';
        arrKeys[108] = 'l';
        arrKeys[109] = 'm';
        arrKeys[110] = 'n';
        arrKeys[111] = 'o';
        arrKeys[112] = 'p';
        arrKeys[113] = 'q';
        arrKeys[114] = 'r';
        arrKeys[115] = 's';
        arrKeys[116] = 't';
        arrKeys[117] = 'u';
        arrKeys[118] = 'v';
        arrKeys[119] = 'w';
        arrKeys[120] = 'x';
        arrKeys[121] = 'y';
        arrKeys[122] = 'z';
        //alert(event.keyCode);

        var letterToShow = arrKeys[event.which].toUpperCase();
        var match = 0;
        var elementToScrollDownTo = 1;

        $('.drop-country li a').each(function (index, value) {
            if (index > 0) {
                if (match != 1) {
                    if ($(this).text().substring(0, 1) == letterToShow) {
                        match = 1;
                        elementToScrollDownTo = $(this).parent();
                    }
                }
            }

        });

        $('.drop-country').scrollTop(0);
        var rowpos = $(elementToScrollDownTo).position();
        $('.drop-country').scrollTop(rowpos.top);
    })
}


function initPage() {
    initCustomForms();

    clearFormFields({
        clearInputs: true,
        clearTextareas: true,
        passwordFieldText: true,
        addClassFocus: "focus",
        filterClass: "default"
    });
}


//custom form variables
var _selectHeight = 26;

var _forms = document.getElementsByTagName('form');
var inputs = new Array();
var selects = new Array();
var labels = new Array();
var buttons = new Array();
var selects = new Array();
var all_selects = false;
var active_select = null;
var agt = navigator.userAgent.toLowerCase();
var selectText = "please select";
var IN_CFORMS = true;

//Custom form functions
function initCustomForms() {
    if (!document.getElementById) { return false; }
    getElements();
    replaceSelects();

    var _selects = document.getElementsByTagName('select');
    var _SelctClassName = [];
    if (_selects) {
        for (var i = 0; i < _selects.length; i++) {
            if (_selects[i].className != '' && _selects[i].className != 'outtaHere')
                _SelctClassName[i] = ' drop-' + _selects[i].className;
        }
        for (var i = 0; i < _SelctClassName.length; i++) {
            var _selectDrop = document.getElementById('optionsDiv' + i);
            if (_selectDrop) {
                if (_SelctClassName[i])
                    _selectDrop.className += _SelctClassName[i];
            }
        }
    }
}

// getting all the required elements
function getElements() {
    for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
        for (var nfl = 0; nfl < document.forms[nf].getElementsByTagName("label").length; nfl++) { labels.push(document.forms[nf].getElementsByTagName("label")[nfl]); }
        for (var nfs = 0; nfs < document.forms[nf].getElementsByTagName("select").length; nfs++) { selects.push(document.forms[nf].getElementsByTagName("select")[nfs]); }
    }
}

function replaceSelects() {
    for (var q = 0; q < selects.length; q++) {
        if (!selects[q].replaced && selects[q].offsetWidth) {
            selects[q]._number = q;
            //create and build div structure
            var selectArea = document.createElement("div");
            var left = document.createElement("span");
            left.className = "left";
            selectArea.appendChild(left);

            var disabled = document.createElement("span");
            disabled.className = "disabled";
            selectArea.appendChild(disabled);

            selects[q]._disabled = disabled;
            var center = document.createElement("span");
            var button = document.createElement("a");
            var text = document.createTextNode(selectText);
            center.id = "mySelectText" + q;

            var stWidth = selects[q].offsetWidth;
            selectArea.style.width = stWidth + "px";
            if (selects[q].parentNode.className.indexOf("type2") != -1) {
                button.href = "javascript:showOptions(" + q + ",true)";
            } else {
                button.href = "javascript:showOptions(" + q + ",false)";
            }
            button.className = "selectButton";
            selectArea.className = "selectArea";

            selectArea.className += " " + selects[q].className;
            selectArea.id = "sarea" + q;
            center.className = "center";
            center.appendChild(text);
            selectArea.appendChild(center);
            selectArea.appendChild(button);

            //hide the select field
            selects[q].className += " outtaHere";
            //insert select div
            selects[q].parentNode.insertBefore(selectArea, selects[q]);
            //build & place options div

            var optionsDiv = document.createElement("div");

            var optionsList = document.createElement("ul");
            optionsDiv.innerHTML += "<div class='select-top'><div></div></div>";
            optionsDiv.appendChild(optionsList);

            selects[q]._options = optionsList;

            optionsDiv.style.width = stWidth + "px";
            optionsDiv._parent = selectArea;

            optionsDiv.className = "optionsDivInvisible";
            optionsDiv.id = "optionsDiv" + q;


            populateSelectOptions(selects[q]);
            optionsDiv.innerHTML += "<div class='select-bottom'><div class='select-bottom-left'></div><div class='select-bottom-right'></div></div>";
            document.getElementsByTagName("body")[0].appendChild(optionsDiv);
            selects[q].replaced = true;
        }
        all_selects = true;
    }
}

//collecting select options
function populateSelectOptions(me) {
    me._options.innerHTML = "";

    for (var w = 0; w < me.options.length; w++) {
        var optionHolder = document.createElement('li');
        var optionLink = document.createElement('a');
        var optionTxt;
        if (me.options[w].title.indexOf('image') != -1) {
            optionTxt = document.createElement('img');
            optionSpan = document.createElement('span');
            optionTxt.src = me.options[w].title;
            optionSpan = document.createTextNode(me.options[w].text);
        } else {
            optionTxt = document.createTextNode(me.options[w].text);
        }


        optionLink.href = "javascript:showOptions(" + me._number + "); selectMe('" + me.id + "'," + w + "," + me._number + ");";

        if (me.options[w].title.indexOf('image') != -1) {
            optionLink.appendChild(optionTxt);
            optionLink.appendChild(optionSpan);
        } else {
            optionLink.appendChild(optionTxt);
        }
        optionHolder.appendChild(optionLink);
        me._options.appendChild(optionHolder);
        //check for pre-selected items
        if (me.options[w].selected) {
            selectMe(me.id, w, me._number);
        }
    }
    //me.getElementsByTagName("");
    if (me.disabled) {
        me._disabled.style.display = "block";
    }
    else {
        me._disabled.style.display = "none";
    }
}

//selecting me
function selectMe(selectFieldId, linkNo, selectNo) {
    selectField = selects[selectNo];
    for (var k = 0; k < selectField.options.length; k++) {
        if (k == linkNo) {
            selectField.options[k].selected = true;
        }
        else {
            selectField.options[k].selected = false;
        }
    }

    //show selected option
    textVar = document.getElementById("mySelectText" + selectNo);
    var newText;
    var optionSpan;
    if (selectField.options[linkNo].title.indexOf('image') != -1) {
        newText = document.createElement('img');
        newText.src = selectField.options[linkNo].title;
        optionSpan = document.createElement('span');
        optionSpan = document.createTextNode(selectField.options[linkNo].text);
    } else {
        newText = document.createTextNode(selectField.options[linkNo].text);
    }
    if (selectField.options[linkNo].title.indexOf('image') != -1) {
        if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
        textVar.replaceChild(newText, textVar.childNodes[0]);
        textVar.appendChild(optionSpan);
    } else {
        if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
        textVar.replaceChild(newText, textVar.childNodes[0]);
    }
    if (selectField.onchange && all_selects) {
        eval(selectField.onchange());
    }
}
//showing options
function showOptions(g) {
    _elem = document.getElementById("optionsDiv" + g);
    var divArea = document.getElementById("sarea" + g);
    if (active_select && active_select != _elem) {
        active_select.className = active_select.className.replace('optionsDivVisible', ' optionsDivInvisible');
        active_select.style.height = "auto";
    }
    if (_elem.className.indexOf("optionsDivInvisible") != -1) {
        _elem.style.left = "-9999px";
        _elem.style.top = findPosY(divArea) + _selectHeight + 'px';
        _elem.className = _elem.className.replace('optionsDivInvisible', '');
        _elem.className += " optionsDivVisible";
        /*if (_elem.offsetHeight > 200)
        {
        _elem.style.height = "200px";
        }*/
        _elem.style.left = findPosX(divArea) + 'px';

        active_select = _elem;
        if (document.documentElement) {
            document.documentElement.onclick = hideSelectOptions;
        }
        else {
            window.onclick = hideSelectOptions;
        }
    }
    else if (_elem.className.indexOf("optionsDivVisible") != -1) {
        _elem.style.height = "auto";
        _elem.className = _elem.className.replace('optionsDivVisible', '');
        _elem.className += " optionsDivInvisible";
    }
}

function hideSelectOptions(e) {
    if (active_select) {
        if (!e) e = window.event;
        var _target = (e.target || e.srcElement);
        if (isElementBefore(_target, 'selectArea') == 0 && isElementBefore(_target, 'optionsDiv') == 0) {
            active_select.className = active_select.className.replace('optionsDivVisible', '');
            active_select.className = active_select.className.replace('optionsDivInvisible', '');
            active_select.className += " optionsDivInvisible";
            active_select = false;

            if (document.documentElement) {
                document.documentElement.onclick = function () { };
            }
            else {
                window.onclick = null;
            }
        }
    }
}

function isElementBefore(_el, _class) {
    var _parent = _el;
    do {
        _parent = _parent.parentNode;
    }
    while (_parent && _parent.className != null && _parent.className.indexOf(_class) == -1)

    if (_parent.className && _parent.className.indexOf(_class) != -1) {
        return 1;
    }
    else {
        return 0;
    }

}

function findPosY(obj) {
    var posTop = 0;
    while (obj.offsetParent) { posTop += obj.offsetTop; obj = obj.offsetParent; }
    return posTop;
}
function findPosX(obj) {
    var posLeft = 0;
    while (obj.offsetParent) { posLeft += obj.offsetLeft; obj = obj.offsetParent; }
    return posLeft;
}

function clearFormFields(o) {
    if (o.clearInputs == null) o.clearInputs = true;
    if (o.clearTextareas == null) o.clearTextareas = true;
    if (o.passwordFieldText == null) o.passwordFieldText = false;
    if (o.addClassFocus == null) o.addClassFocus = false;
    if (!o.filter) o.filter = "default";
    if (o.clearInputs) {
        var inputs = document.getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++) {
            if ((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass)) {
                inputs[i].valueHtml = inputs[i].value;
                inputs[i].onfocus = function () {
                    if (this.valueHtml == this.value) this.value = "";
                    if (this.fake) {
                        inputsSwap(this, this.previousSibling);
                        this.previousSibling.focus();
                    }
                    if (o.addClassFocus && !this.fake) {
                        this.className += " " + o.addClassFocus;
                        this.parentNode.className += " parent-" + o.addClassFocus;
                    }
                }
                inputs[i].onblur = function () {
                    if (this.value == "") {
                        this.value = this.valueHtml;
                        if (o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
                    }
                    if (o.addClassFocus) {
                        this.className = this.className.replace(o.addClassFocus, "");
                        this.parentNode.className = this.parentNode.className.replace("parent-" + o.addClassFocus, "");
                    }
                }
                if (o.passwordFieldText && inputs[i].type == "password") {
                    var fakeInput = document.createElement("input");
                    fakeInput.type = "text";
                    fakeInput.value = inputs[i].value;
                    fakeInput.className = inputs[i].className;
                    fakeInput.fake = true;
                    inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
                    inputsSwap(inputs[i], null);
                }
            }
        }
    }
    if (o.clearTextareas) {
        var textareas = document.getElementsByTagName("textarea");
        for (var i = 0; i < textareas.length; i++) {
            if (textareas[i].className.indexOf(o.filterClass)) {
                textareas[i].valueHtml = textareas[i].value;
                textareas[i].onfocus = function () {
                    if (this.value == this.valueHtml) this.value = "";
                    if (o.addClassFocus) {
                        this.className += " " + o.addClassFocus;
                        this.parentNode.className += " parent-" + o.addClassFocus;
                    }
                }
                textareas[i].onblur = function () {
                    if (this.value == "") this.value = this.valueHtml;
                    if (o.addClassFocus) {
                        this.className = this.className.replace(o.addClassFocus, "");
                        this.parentNode.className = this.parentNode.className.replace("parent-" + o.addClassFocus, "");
                    }
                }
            }
        }
    }
    function inputsSwap(el, el2) {
        if (el) el.style.display = "none";
        if (el2) el2.style.display = "inline";
    }
}

