SchCompat = new Class({
    Implements: Options,
    options: {
        cookiesDisabledContainer: null,
        isIe6Container: null,
        cookiesDisabledText: '',
        isIe6Text: '',
        decoder: null
    },
    initialize: function(options) {
        this.setOptions(options);

        if (this.options.cookiesDisabledContainer != null &&
            this.options.isIe6Container != null &&
            this.options.cookiesDisabledText != '' &&
            this.options.isIe6Text != '') {

            this.options.decoder = new Decoder();

            if (this.detectIe6()) {
                this.options.isIe6Container.set('html', this.options.decoder.decodeBase64(this.options.isIe6Text));
                this.options.isIe6Container.setStyles({ 'display': 'block' });
            }

            if (!this.detectCookies()) {
                this.options.cookiesDisabledContainer.set('html', this.options.decoder.decodeBase64(this.options.cookiesDisabledText));
                this.options.cookiesDisabledContainer.setStyles({ 'display': 'block' });
            }
        }
    },
    detectCookies: function() {
        Cookie.write('test', 'test');

        if (Cookie.read('test') == 'test') {
            Cookie.dispose('test');
            return true;
        }
        else
            return false;
    },
    detectIe6: function() {
        if (Browser.Engine.trident && Browser.Engine.version == 4)
            return true;
        else
            return false;
    }
});

SchConfirmSettings = new Class({
    Implements: Options,
    options: {
        confirmSettingsContainer: null,
        confirmHeadLine: '',
        confirmExplanation: '',
        confirmCountry: '',
        confirmLanguage: '',
        confirmCurrency: '',
        confirmProductType: '',
        cmdConfirmUserSettings: '',
        confirmToggleHelp: '',
        confirmHelp: '',
        decoder: null
    },
    initialize: function(options) {
        this.setOptions(options);

        if (this.options.confirmSettingsContainer != null) {
            this.options.decoder = new Decoder();

            this.options.confirmSettingsContainer.getElement('h3#ConfirmHeadLine').set('text',
                this.options.decoder.decodeBase64(this.options.confirmHeadLine));

            this.options.confirmSettingsContainer.getElement('p#ConfirmExplanation').set('text',
                this.options.decoder.decodeBase64(this.options.confirmExplanation));

            this.options.confirmSettingsContainer.getElement('td#ConfirmCountry').set('text',
                this.options.decoder.decodeBase64(this.options.confirmCountry));

            this.options.confirmSettingsContainer.getElement('td#ConfirmLanguage').set('text',
                this.options.decoder.decodeBase64(this.options.confirmLanguage));

            this.options.confirmSettingsContainer.getElement('td#ConfirmCurrency').set('text',
                this.options.decoder.decodeBase64(this.options.confirmCurrency));

            var elmConfirmProductType = this.options.confirmSettingsContainer.getElement('td#ctl00_ctl00_ConfirmProductTypeTd');
            if (elmConfirmProductType != null) {
                elmConfirmProductType.set('text', this.options.decoder.decodeBase64(this.options.confirmProductType));
            }

            this.options.confirmSettingsContainer.getElement('input#ctl00_ctl00_cmdConfirmUserSettings').set('value',
                this.options.decoder.decodeBase64(this.options.cmdConfirmUserSettings));

            this.options.confirmSettingsContainer.getElement('span#ConfirmToggleHelp').set('text',
                this.options.decoder.decodeBase64(this.options.confirmToggleHelp));

            this.options.confirmSettingsContainer.getElement('p#ConfirmHelp').set('html',
                this.options.decoder.decodeBase64(this.options.confirmHelp));
        }
    }
});

SchInfoBoxText = new Class({
    Implements: Options,
    options: {
        infoBoxContainer: null,
        infoBoxHeadLine: '',
        infoBoxBody: '',
        infoBoxKeepClosed: '',
        infoBoxClose: '',
        cookieDuration: 0,
        decoder: null
    },
    initialize: function(options) {
        this.setOptions(options);

        if (this.options.infoBoxContainer != null) {
            this.options.decoder = new Decoder();

            this.options.infoBoxContainer.addEvent('click', function(e) {
                if ($(e.target).get('id') == 'InfoBoxClose') {
                    e.stop();

                    if (this.options.infoBoxContainer.getElement('input#chkInfoBoxSetDuration').checked)
                        fpCookie = Cookie.write('fpCookie', 'hide', { duration: this.options.cookieDuration });
                    else
                        fpCookie = Cookie.write('fpCookie', 'hide');

                    new Fx.Reveal(this.options.infoBoxContainer).dissolve();
                }
            } .bind(this));

            this.options.infoBoxContainer.getElement('h3#InfoBoxHeadLine').set('html',
                this.options.decoder.decodeBase64(this.options.infoBoxHeadLine));

            this.options.infoBoxContainer.getElement('td#InfoBoxClose').set('text',
                this.options.decoder.decodeBase64(this.options.infoBoxClose));

            this.options.infoBoxContainer.getElement('li#InfoBoxBody').set('html',
                this.options.decoder.decodeBase64(this.options.infoBoxBody));

            this.options.infoBoxContainer.getElement('span#InfoBoxKeepClosed').set('text',
                this.options.decoder.decodeBase64(this.options.infoBoxKeepClosed));
        }
    }
});

Decoder = new Class({
    Implements: Options,
    options: {
        keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
    },
    initialize: function(options) {
        this.setOptions(options);
    },
    decodeBase64: function(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {
            enc1 = this.options.keyStr.indexOf(input.charAt(i++));
            enc2 = this.options.keyStr.indexOf(input.charAt(i++));
            enc3 = this.options.keyStr.indexOf(input.charAt(i++));
            enc4 = this.options.keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }

        return this.decodeUtf8(output);
    },
    decodeUtf8: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {
            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }

        return string;
    }
});

SchDropDown = new Class({
    Implements: Options,
    options: {
        select: null,
        ul: null,
        toggled: false,
        class_closed: 'schDropDownClosed',
        class_opened: 'schDropDownOpened',
        heightOpened: 0,
        heightClosed: 0,
        color_LiHover: '#ccc',
        useFancyStyle: false,
        scrollToOffset: -3
    },
    initialize: function (options) {
        this.setOptions(options);

        if (this.options.select != null) {
            this.createElements();
        }
    },
    createElements: function () {
        this.options.ul = new Element('ul', { 'class': this.options.class_closed });
        this.options.ul.selectedIndex = this.options.select.get('selectedIndex');
        this.options.ul.grps = [];

        var sizeOfSelect = this.options.select.measure(function () {
            return this.getSize();
        });

        var countLi = 0;
        this.options.ul.setStyles({ 'width': sizeOfSelect.x + 'px' });

        this.options.select.getChildren('option').each(function (option) {
            if (option.get('rel') != null) {
                if (this.options.ul.grps.contains(option.get('rel')) == false) {
                    this.options.ul.grps.push(option.get('rel'));

                    var liGrp = new Element('li', { 'text': option.get('rel'), 'class': 'grp', 'rel': 'disabled', 'value': option.get('value') });
                    this.options.ul.adopt(liGrp);
                }
            }

            var li = new Element('li', { 'text': option.get('text') });

            if (option.get('class') != null)
                li.set('class', option.get('class'));

            li.value = option.get('value');
            li.index = countLi;

            if (option.get('selected'))
                this.options.ul.selectedIndex = li.index;

            this.options.ul.adopt(li);
            countLi++;
        } .bind(this));

        /*var parent = this.options.select.getParent();*/
        this.options.ul.inject(this.options.select, 'before');

        var sizeOfUl = this.options.ul.measure(function () {
            return this.getSize();
        });

        var paddingTop = this.options.ul.getStyle('padding-top').toInt();
        var borderTop = this.options.ul.getStyle('border-top').toInt();
        var paddingBottom = this.options.ul.getStyle('padding-bottom').toInt();
        var borderBottom = this.options.ul.getStyle('border-bottom').toInt();

        var heightPrLi = Math.round((sizeOfUl.y - paddingTop - paddingBottom - borderTop - borderBottom) / countLi);
        this.options.heightClosed = heightPrLi;
        this.options.heightOpened = heightPrLi * 10;

        this.options.select.setStyles({ 'visibility': 'hidden' });
        this.addEvents();
        this.showSelected();
    },
    addEvents: function () {
        this.options.ul.getChildren('li').each(function (li) {
            if ((li.get('rel') != null && li.get('rel') == 'disabled') == false) {
                li.addEvent('click', function (e) {
                    e.stop();

                    if (this.options.toggled) {
                        this.options.ul.selectedIndex = this.options.select.selectedIndex = li.index;
                        li.setStyles({ 'background-color': 'inherit' });
                        this.showSelected();

                        var onchange = this.options.select.get('onchange');

                        if (onchange != null) {
                            eval(onchange.substring(11));
                        }
                    }
                    else {
                        this.showAll();
                    }

                } .bind(this));
                li.addEvent('mouseenter', function () {
                    if (this.options.toggled) {
                        li.setStyles({ 'background-color': this.options.color_LiHover });
                    }
                } .bind(this));
                li.addEvent('mouseleave', function () {
                    if (this.options.toggled) {
                        li.setStyles({ 'background-color': 'inherit' });
                    }
                } .bind(this));
            }
        } .bind(this))
    },
    showSelected: function () {
        this.options.toggled = false;
        document.removeEvent('click', this.showSelected);
        this.options.ul.set('class', this.options.class_closed);
        this.options.ul.setStyles({ 'height': this.options.heightClosed + 'px' });

        this.options.ul.getChildren('li').each(function (li) {
            if (li.index == this.options.ul.selectedIndex)
                li.setStyles({ 'display': 'list-item'/*, 'background': 'url(../images/standard-buttons.png) 100px -719px;'*/ });
            else
                li.setStyles({ 'display': 'none' });
        } .bind(this))
    },
    showAll: function () {
        this.options.toggled = true;
        document.addEvent('click', this.showSelected.bind(this));
        this.options.ul.set('class', this.options.class_opened);
        this.options.ul.setStyles({ 'height': this.options.heightOpened + 'px' });

        this.options.ul.getChildren('li').each(function (li) {
            li.setStyles({ 'display': 'list-item' });
        });

        var selectedLi = this.getSelectedLi();

        if (selectedLi != null) {
            this.options.ul.scrollTo(0, selectedLi.getPosition(this.options.ul).y + this.options.scrollToOffset);
        }
    },
    getSelectedLi: function () {
        var selectedLi = null;

        this.options.ul.getChildren('li').each(function (li) {
            if (li.index == this.options.ul.selectedIndex) {
                selectedLi = li;
            }
        } .bind(this));

        return selectedLi;
    }
});

window.addEvent('domready', function() {
    function lastCarMenuSelection() {
        var carMenuCookie = Cookie.read('lastShownSeries');
        var selectedCarMenu = 2;
        if (carMenuCookie != null) {
            $$('li.serie').each(function(elm, index) {
                if (elm.id == carMenuCookie) {
                    selectedCarMenu = index;
                }

            });
        }

        return selectedCarMenu;
    };

    lastCarMenuSelected = lastCarMenuSelection();

    var carMenuAccordion = new Accordion($('series'), 'li.serie', 'ul.models', {
        opacity: false,
        onActive: function(toggler, element) {
            element.addClass('open');
        },
        onBackground: function(toggler, element) {
            toggler.removeClass('open');

        },
        show: lastCarMenuSelected
    });

    $$('ul#series li.serie').each(function(elm) {
        elm.addEvent('click', function() { Cookie.write('lastShownSeries', elm.id, { duration: 90, path: "/" }); });
    });

    $$('ul#series li ul li a').each(function(elm) {
        elm.addEvent('click', function() { Cookie.write('selectedModel', elm.id, { duration: 90, path: "/" }); });
    });

    //DROPDOWN MENU
    $$('ul#topMenu').getChildren('li').each(function(elm) {
        elm.addEvent('mouseover', function() { this.getChildren('ul').setStyles({ 'position': 'absolute', 'display': 'block', 'left': this.getPosition('topMenu').x, 'top': 14 }); });
        elm.addEvent('mouseout', function() { this.getChildren('ul').setStyle('display', 'none'); });
    });


    //LANGUAGE MENU
    $$('ul#ctl00_ctl00_lselect1_langSelect').getChildren('li').each(function(elm) {
        elm.addEvent('mouseover', function() { this.getChildren('ul').setStyles({ 'display': 'block' }); });
        elm.addEvent('mouseout', function() { this.getChildren('ul').setStyle('display', 'none'); });

    });

    //Cannot find it function
    //Delete update
    if ($('ctl00_ctl00_cphContentMiddle_btnCannotFindIt') != null && $('divCannotFindModel') != null) {
        $('ctl00_ctl00_cphContentMiddle_btnCannotFindIt').addEvent('click', function(e) {
            if (doSearch) {
                e.stop();
                new Fx.Reveal($('divCannotFindModel')).reveal().chain(function() { $('ctl00_ctl00_txtCannotFindName').focus(); });
            }
        });

        window.addEvent('keypress', function(e) { if (e.key == 'esc') { dissolveCannotFind(e); } });
        $(document.body).addEvent('click', function(e) { dissolveCannotFind(e); });
        $('ctl00_ctl00_lblCannotFindClose').addEvent('click', function(e) { dissolveCannotFind(e); });

        var btnCannotFindSend = $('ctl00_ctl00_btnCannotFindSend');
        btnCannotFindSend.addEvent('click', function(e) {
            e.stop();

            var origBtnTxt = btnCannotFindSend.get('text');
            var intervalId = null;

            var jsonRequest = new Request.JSON({
                url: '/WebService.asmx/CF',
                method: 'post',
                evalResponse: true,
                urlEncoded: false,
                data: { 'default': 'default' },
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                onRequest: function() {
                    btnCannotFindSend.setStyles({ 'width': btnCannotFindSend.getSize().x });
                    btnCannotFindSend.set('text', '.');
                    var animate = function() {
                        if (this.get('text') == '.....')
                            this.set('text', '.');
                        else
                            this.set('text', this.get('text') + '.');
                    };
                    intervalId = animate.periodical(500, btnCannotFindSend);
                },
                onComplete: function(msg) {
                    $clear(intervalId);
                    btnCannotFindSend.set('text', origBtnTxt);

                    if (msg != null) {
                        if (msg.d != null) {
                            if (typeof (msg.d) != 'undefined') {
                                $('lblCannotFindResult').set('text', msg.d.toString());
                            } else { $('lblCannotFindResult').set('text', errMsg); }
                        } else { $('lblCannotFindResult').set('text', errMsg); }
                    } else { $('lblCannotFindResult').set('text', errMsg); }
                }
            }).send(JSON.encode({
                'd': createCannotFindArray(),
                'sl': selectedLanguage,
                'pty': productType,
                'uc': productType
            }));
        });
    }

    if ($('ctl00_ctl00_cphContentMiddle_LeftMenu1_aCannotFindIt') != null && $('divCannotFindModel') != null) {
        $('ctl00_ctl00_cphContentMiddle_LeftMenu1_aCannotFindIt').addEvent('click', function (e) {
            if (doSearch) {
                e.stop();
                new Fx.Reveal($('divCannotFindModel')).reveal().chain(function () { $('ctl00_ctl00_txtCannotFindName').focus(); });
            }
        });

        window.addEvent('keypress', function (e) { if (e.key == 'esc') { dissolveCannotFind(e); } });
        $(document.body).addEvent('click', function (e) { dissolveCannotFind(e); });
        $('ctl00_ctl00_lblCannotFindClose').addEvent('click', function (e) { dissolveCannotFind(e); });

        var btnCannotFindSend = $('ctl00_ctl00_btnCannotFindSend');
        btnCannotFindSend.addEvent('click', function (e) {
            e.stop();

            var origBtnTxt = btnCannotFindSend.get('text');
            var intervalId = null;

            var jsonRequest = new Request.JSON({
                url: '/WebService.asmx/CF',
                method: 'post',
                evalResponse: true,
                urlEncoded: false,
                data: { 'default': 'default' },
                headers: { 'Content-Type': 'application/json; charset=utf-8' },
                onRequest: function () {
                    btnCannotFindSend.setStyles({ 'width': btnCannotFindSend.getSize().x });
                    btnCannotFindSend.set('text', '.');
                    var animate = function () {
                        if (this.get('text') == '.....')
                            this.set('text', '.');
                        else
                            this.set('text', this.get('text') + '.');
                    };
                    intervalId = animate.periodical(500, btnCannotFindSend);
                },
                onComplete: function (msg) {
                    $clear(intervalId);
                    btnCannotFindSend.set('text', origBtnTxt);

                    if (msg != null) {
                        if (msg.d != null) {
                            if (typeof (msg.d) != 'undefined') {
                                $('lblCannotFindResult').set('text', msg.d.toString());
                            } else { $('lblCannotFindResult').set('text', errMsg); }
                        } else { $('lblCannotFindResult').set('text', errMsg); }
                    } else { $('lblCannotFindResult').set('text', errMsg); }
                }
            }).send(JSON.encode({
                'd': createCannotFindArray(),
                'sl': selectedLanguage,
                'pty': productType,
                'uc': productType
            }));
        });
    }

    if ($('ctl00_ctl00_cphContentMiddle_cmdSearch') != null) {
        $('ctl00_ctl00_cphContentMiddle_cmdSearch').addEvent('focus', function() {
            doSearch = true;
        });

        $('ctl00_ctl00_cphContentMiddle_cmdSearch').addEvent('blur', function() {
            doSearch = false;
        });

        $('ctl00_ctl00_cphContentMiddle_cmdSearch').addEvent('click', function(e) {
            e.stop();

            if ($('txtSearch').value.length > 2) {
                document.location = getSearchUrl($('txtSearch').value, urlstrProductType, urlstrSearchByPn, 'dpsbsbpn');
            }
            else {
                if (doSearch)
                    alert(searchErrMsg);
            }
        });
    }

    if ($('txtSearch') != null) {
        $('txtSearch').addEvent('focus', function() {
            doSearch = false;
        });

        $('txtSearch').addEvent('blur', function() {
            doSearch = true;
        });

        $('txtSearch').addEvent("keydown", function(e) {

            if (e.key == 'enter') {
                e.stop();

                if ($('txtSearch').value.length > 2) {
                    document.location = getSearchUrl($('txtSearch').value, urlstrProductType, urlstrSearchByPn, 'dpsbsbpn');
                }
                else {
                    alert(searchErrMsg);
                }
            }
        });
    }

    if ($('ctl00_ctl00_cphContentMiddle_txtEmail') != null) {
        $('ctl00_ctl00_cphContentMiddle_txtEmail').addEvent('focus', function() {
            doSearch = false;
        });

        $('ctl00_ctl00_cphContentMiddle_txtEmail').addEvent('blur', function() {
            doSearch = true;
        });

        $('ctl00_ctl00_cphContentMiddle_txtEmail').addEvent('keydown', function(e) {
            if (e.key == 'enter') {
                e.stop();
                $('ctl00_ctl00_cphContentMiddle_txtPassword').select();
            }
        });
    }

    if ($('ctl00_ctl00_cphContentMiddle_txtPassword') != null) {
        $('ctl00_ctl00_cphContentMiddle_txtPassword').addEvent('focus', function() {
            doSearch = false;
        });

        $('ctl00_ctl00_cphContentMiddle_txtPassword').addEvent('blur', function() {
            doSearch = true;
        });

        $('ctl00_ctl00_cphContentMiddle_txtPassword').addEvent('keydown', function(e) {
            if (e.key == 'enter') {
                e.stop();
                eval(jsCmdLogin);
            }
        });
    }

    if ($('ctl00_ctl00_cphContentMiddle_chkRememberMe') != null) {
        $('ctl00_ctl00_cphContentMiddle_chkRememberMe').addEvent('focus', function() {
            doSearch = false;
        });

        $('ctl00_ctl00_cphContentMiddle_chkRememberMe').addEvent('blur', function() {
            doSearch = true;
        });

        $('ctl00_ctl00_cphContentMiddle_chkRememberMe').addEvent('keydown', function(e) {
            if (e.key == 'enter') {
                e.stop();
                eval(jsCmdLogin);
            }
        });
    }

    //Move to anchor
    var indexOfAnchor = location.href.indexOf('#');
    if (indexOfAnchor > -1) {
        location.hash = location.href.substr(indexOfAnchor + 1);
    }

    if ($('ConfirmToggleHelp') != null) {
        $('ConfirmToggleHelp').addEvent('click', function() {
            new Fx.Reveal($('ConfirmHelp')).toggle();
        });
    }
});

//Cannot find it function
function dissolveCannotFind(e) {
    var control = $(e.target.id);

    if (control != null) {
        if ($('divCannotFindModel').getStyles('display')['display'].toString() == 'block' &&
        (!control.getParent('#divCannotFindContainer') ||
        control.get('id').toString() == 'ctl00_ctl00_lblCannotFindClose')) {
            $('lblCannotFindResult').set('text', '');
            var revCannotFind = new Fx.Reveal($('divCannotFindModel')).dissolve();
        }
    }
}

//Cannot find it function
function createCannotFindArray() {
    var details = new Array();

    details[0] = $('ctl00_ctl00_txtCannotFindName').get('value').toString();
    details[1] = $('ctl00_ctl00_txtCannotFindEmail').get('value').toString();
    details[2] = $('ctl00_ctl00_txtCannotFindCarModel').get('value').toString();
    details[3] = $('ctl00_ctl00_txtCannotFindCarSize').get('value').toString();
    details[4] = $('ctl00_ctl00_txtCannotFindCarVariant').get('value').toString();
    details[5] = $('ctl00_ctl00_txtCannotFindCarBuildYear').get('value').toString();
    details[6] = $('ctl00_ctl00_txtCannotFindCarFrameNumber').get('value').toString();
    details[7] = $('ctl00_ctl00_txtCannotFindRemark').get('value').toString();

    return details;
}

function getSearchUrl(query, sPty, sQry, qryType) {
    query = query.toString().trim();

    if (query.length < 2)
        return '';

    var useQuery = false;

    if (query[0] == '.' || query[query.length - 1] == '.')
        useQuery = true;

    if (!useQuery) {
        if (query.test('([\\/:*"<>|]+)')) {
            useQuery = true;
        }
    }

    if (useQuery) {
        return 'http://' + authority + '/displayproducts.aspx?o=' + qryType + '&q=' + query + '&pty=' + productType;
    }
    else {
        return 'http://' + authority + '/' + query + '/' + sPty + '/' + productType + '/' + sQry + '.aspx';
    }
}

function DHLtracker()
{
	window.open("http://dhlservicepoint.se/Spårapaket/tabid/115/Default.aspx/?tabname=Spåra paket&queryConsNo=" + $("ctl00_ctl00_cphContentMiddle_inputDHLtrack").value)
}
