var monthsToShow = 12;
var cookieValidDays = 1;
var defaultSize = 'medium';
// clientID holds the virtDir.
// change condition if functionality relies on itdLPxx.
if (clientID && clientID === 'seTT') {
    defaultSize = 'DINA4';
} 
var date = new Date();
var curDay = date.getDate();
var curYear = date.getFullYear();
var curMonth = date.getMonth();
var isLeapYear = checkIfLeapYear(curYear);
var selectedDay = curDay;
var arrIdx = curMonth;
var isNextYear = false;
var f = null;
var dateObj = {};

dateObj.monthLen = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

dateObj.en = {
    monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
};
dateObj.de = {
    monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']
};
dateObj.fr = {
    monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Decembre']
};

var sizeObj = {
    en: ['panel', 'matrix'],
    de: ['panel', 'matrix'],
    fr: ['panel', 'matrix']
};



function checkIfLeapYear(y) {
    return (((y % 400) == "0") ? true : (((y % 100) == "0") ? false : (((y % 4) == "0") ? true : false)));
}



function setCookie(n, w, e) {
    var a = new Date();
    a = new Date(a.getTime() + e);
    document.cookie = n + '=' + w + '; expires=' + a.toGMTString() + ';';
}



function readCookie(n) {

    var a = document.cookie;
    var res = '';
    var cookieName, cookieValue;

    while (a != '') {
        while (a.substr(0, 1) == ' ') {
            a = a.substr(1, a.length);
        }
        cookieName = a.substring(0, a.indexOf('='));
        if (a.indexOf(';') != -1) {
            cookieValue = a.substring(a.indexOf('=') + 1, a.indexOf(';'));
        } else {
            cookieValue = a.substr(a.indexOf('=') + 1, a.length);
        }
        if (n == cookieName) {
            res = cookieValue;
        }
        i = a.indexOf(';') + 1;
        if (i == 0) {
            i = a.length;
        }
        a = a.substring(i, a.length);
    }

    return res;
}



function appendOption(selectList, value, text, isSelected) {

    if (!f) {
        return;
    }

    var el = document.createElement("option");
    el.setAttribute("value", value);
    el.innerHTML = text;
    if (isSelected) {
        el.setAttribute("selected", "selected");
    }
    f[selectList].appendChild(el);
    return true;
}



function clearList(list) {
    while (f[list].options.length > 0) {
        var last = f[list].lastChild;
        f[list].removeChild(last);
    }
}



function populateDayOptions(month) {

    var day = '',
        range = (month === 1 && isLeapYear === true) ? (dateObj.monthLen[month] + 1) : dateObj.monthLen[month];

    clearList('dateDay');

    for (var i = 1; i <= range; i++) {

        day = (i < 10) ? '0' + i : i;

        if (i == selectedDay) {
            appendOption('dateDay', day, day, true);
        } else {
            appendOption('dateDay', day, day, false);
        }
    }
}



function populateDayMonthOptions(month, year) {
    
    clearList('dateMonthYear');

    for (var j = 0; j < monthsToShow; j++) {

        if (arrIdx < monthsToShow && (isNextYear === false)) {
            var txt = dateObj[curLanguage].monthNames[arrIdx] + ' ' + curYear;
            var val = curYear + new String((arrIdx + 1 < 10) ? '0' + (arrIdx + 1) : arrIdx + 1);
        } else {
            if (isNextYear === false) {
                arrIdx = arrIdx - monthsToShow;
                isNextYear = true;
            }
            var txt = dateObj[curLanguage].monthNames[arrIdx] + ' ' + (curYear + 1);
            var val = (curYear + 1) + new String((arrIdx + 1 < 10) ? '0' + (arrIdx + 1) : arrIdx + 1);
        }

        //preselect if cookie date
        var ym = new String((month < 10) ? '0' + month : month);
        ym = year + ym;

        if (val === ym) {
            appendOption('dateMonthYear', val, txt, true);
        } else {
            appendOption('dateMonthYear', val, txt, false);
        }
        arrIdx++;
    }
}



function populateLayoutOptions(cookieVal) {

    var values = ['panel', 'matrix'];

    clearList('layout');

    for (var i = 0; i < values.length; i++) {

        if (arguments.length > 0 && values[i] === cookieVal) {
            appendOption('layout', values[i], values[i], true);
        } else {
            appendOption('layout', values[i], values[i], false);
        }
    }
}



function populateSizeOptions(cookieVal) {

    var values = ['small', 'medium', 'large', 'dynamic', 'default'];

    clearList('size');

    for (var i = 0; i < values.length; i++) {

        if (arguments.length > 0 && values[i] === cookieVal) {
            appendOption('size', values[i], values[i], true);
        } else {
            appendOption('size', values[i], values[i], false);
        }
    }
}



function initSelects() {

    var layout = '';
    var size = '';
    var dateDay = '';
    var dateMonthYear = '';
    
    f= document.forms[0];
    
    if (!f) {
        return;
    }
    
    if (typeof f.dateMonthYear==='undefined') {
        return;
    }
    
    if (document.cookie) {
        layout = readCookie('layout');
        size = readCookie('size');
        dateDay = readCookie('dateDay');
        dateMonthYear = readCookie('dateMonthYear');
    }
    
    // clientID holds the virtDir.
    // change condition if functionality relies on itdLPxx.
    
    // no layout box, no size box for the public interface
    if (clientID && clientID.toLowerCase().indexOf('stopspecifictt') != '-1') {
        if (size != '') {
            populateSizeOptions(size);
        } else {
            // set default
            populateSizeOptions(defaultSize);
        }
        if (layout != '') {
            populateLayoutOptions(layout);
        } else {
            // set default
            populateLayoutOptions();
        }
    }

    if (dateMonthYear != '') {
        var m = getMonth(dateMonthYear);
        populateDayMonthOptions(m, getYear(dateMonthYear));
        populateDayOptions(m - 1);
    } else {
        populateDayMonthOptions(curMonth, curYear);
        populateDayOptions(curMonth);
    }

    //override day selection if day cookie is set
    if (dateDay != '') {
        if (dateDay !== f['dateDay'].value) {
            f['dateDay'][dateDay - 1].selected = 'selected';
        }
    }

    function getMonth(dateMY) {
        var m = parseInt(dateMY.substring(4, 6), 10);
        return m;
    }



    function getYear(dateMY) {
        var y = parseInt(dateMY.substring(0, 4), 10);
        return y;
    }

    f['dateMonthYear'].onchange = function () {
        isLeapYear = checkIfLeapYear(getYear(this.value));
        selectedDay = f['dateDay'].value;
        populateDayOptions(getMonth(this.value) - 1);
        setCookie('dateMonthYear', this.value, 1000 * 60 * 60 * 24 * cookieValidDays);
    };
    f['dateDay'].onchange = function () {
        setCookie('dateDay', this.value, 1000 * 60 * 60 * 24 * cookieValidDays);
    };
    f['layout'].onchange = function () {
        setCookie('layout', this.value, 1000 * 60 * 60 * 24 * cookieValidDays);
    };
    f['size'].onchange = function () {
        setCookie('size', this.value, 1000 * 60 * 60 * 24 * cookieValidDays);
    };
}

function doSubmit(stopSelIndex, linePreSel) {
    if (arguments.length === 0) {
        alert('ERROR: no line index.');
        return false;
    }
    
    var form = document.forms[0];
    var appendField = function(n, v) {
        var elem = document.createElement('input');
        elem.name = n;
        elem.type = 'hidden';
        elem.value = v || '';
        form.appendChild(elem);
    }; 
    
    if (form['linePreSel']) {
       form['linePreSel'].value = linePreSel; 
    } else {
        appendField('linePreSel', linePreSel);
    }
    
    if (form['onlySrvChng']) {
    //   form['onlySrvChng'].value = 1; 
    } else {
         appendField('onlySrvChng', 1); 
    }
    
    form.action = 'XSLT_SEL_STT_REQUEST';
    form.target = '_blank';
    form.elements.stopSelIndex.value = stopSelIndex;
    form.submit();
}

function setFocusToField(id) {
    var inp = document.getElementById(id);
    if (inp) {
        inp.focus();
    }
}


function attachEventListener(target, eventType, functionRef, capture) {

    var oldListener;

    if (typeof target.addEventListener != "undefined") {
        target.addEventListener(eventType, functionRef, capture);
    } else if (typeof target.attachEvent != "undefined") {
        target.attachEvent("on" + eventType, functionRef);
    } else {
        eventType = "on" + eventType;
        if (typeof target[eventType] == "function") {
            oldListener = target[eventType];
            target[eventType] = function () {
                oldListener();
                return functionRef();
            };
        } else {
            target[eventType] = functionRef;
        }
    }
    return true;
}

attachEventListener(window, 'load', initSelects, false);
attachEventListener(window, 'load', function() { setFocusToField('lineName'); }, false);
