var ui = {
    initialize: function() {
        this.menuButton = 'none';
        this.menuRollout = 'none';

        this.setContentHeight();

        $$('.btn_bestellen').each(function(btn) {
            Event.observe(btn, 'click', this.showOrderPopup.bindAsEventListener(this));
        } .bind(this));

        $$('.btn_login').each(function(btn) {
            Event.observe(btn, 'click', this.showLoginPopup.bindAsEventListener(this));
        } .bind(this));

        $$('#filter_inner a').each(function(el) {
            Event.observe(el, 'click', this.setFilter.bindAsEventListener(this));
        } .bind(this));

        $$('td.checkbox img').each(function(el) {
            Event.observe(el, 'click', this.setCheckBox.bindAsEventListener(this));
        } .bind(this));

        $$('#betaal_methodes .checkbox').each(function(el) {
            Event.observe(el, 'click', this.setPaymentCheckbox.bindAsEventListener(this));
        } .bind(this));

        $('sidebar_ie_background').setStyle({
            width: $('sidebar').getWidth()
        });
        $('sidebar_ie_background').setStyle({
            height: $('sidebar').getHeight()
        });

        $$('.tips_content ul li a').each(function(el) {
            Event.observe(el, 'click', this.toggleFaq.bindAsEventListener(this));
        } .bind(this));

    },

    dropElementsByClassName: function(elClass) {
        var listItems = $$('.' + elClass);
        for (i = 0; i < listItems.length; i++) {
            listItems[i].remove();
        }
    },

    getTarget: function(el) {
        el.tooltipid = el.title;
        el.removeAttribute('title');
    },

    setCheckBox: function(e) {
        if (e.element().tagName == "IMG") {
            this.target = e.element();
        } else {
            var children = e.element().childElements();
            children.each(function(child) {
                if (child.tagName == "IMG" && child.className == "checkbox") {
                    this.target = child;
                    return;
                }
            } .bind(this));
        }

        var expression = /(select\_[a-z]*)/i;
        var res = expression.exec(this.target.className);
        var callingClassName = res[0];

        $$('.' + callingClassName).each(function(img, index) {
            if (img.src.indexOf('checked') != -1) {
                img.src = '/images/box.gif';
                this.check = false;
                if (this.target == img) {
                    eval(this.deSelectCallback);
                    throw $break;
                }
            } else {
                img.src = '/images/box.gif';
                this.check = true;
            }
        } .bind(this));

        if (this.check) {
            this.target.src = '/images/box_checked.gif';
            eval(this.selectCallback);
            this.check = false;
        }
    },

    setContentHeight: function() {
        var content = $('content');
        var sidebar = $('sidebar');

        var sidebarHeight = sidebar.getHeight();
        var contentHeight = content.getHeight();

        if (sidebarHeight > contentHeight)
            content.setStyle({ height: sidebarHeight });

        $('footer').setStyle({ display: 'block' });
    },

    showLightBox: function() {

        var size = document.viewport.getDimensions();
        var offset = document.viewport.getScrollOffsets();

        var pageWidth;
        var pageHeight;

        if (window.innerHeight && window.scrollMaxY)// Firefox
        {
            pageWidth = window.innerWidth + window.scrollMaxX;
            pageHeight = window.innerHeight + window.scrollMaxY;
        }
        else if (document.body.scrollHeight > document.body.offsetHeight) // all but Explorer Mac
        {
            pageWidth = document.body.scrollWidth;
            pageHeight = document.body.scrollHeight;
        }
        else // works in Explorer 6 Strict, Mozilla (not FF) and Safari
        {
            pageWidth = document.body.offsetWidth + document.body.offsetLeft;
            pageHeight = document.body.offsetHeight + offset.top;
        }

        var popup = $(this.lightBoxId);
        var overlay = Builder.node('div', { id: 'overlay' });

        popup.setStyle({
            top: ((size.height / 2) - (popup.getHeight() / 2)) + offset.top + 'px',
            left: ((size.width / 2) - (popup.getWidth() / 2)) + offset.left + 'px',
            display: 'block'
        });

        overlay.setStyle({
            width: pageWidth + 'px',
            height: (pageHeight + 16) + 'px',
            left: '0px',
            top: '0px',
            bottom: '0px'
        });

        var iframe = Builder.node('iframe', { 'src': 'about:blank' });
        iframe.setStyle({
            width: pageWidth + 'px',
            height: (pageHeight + 16) + 'px',
            zIndex: '-1',
            display: 'block',
            left: '0px',
            top: '0px',
            bottom: '0px'
        });

        Event.observe(overlay, 'click', this.closeLightBox.bindAsEventListener(this));

        $$('.btn_close').each(function(btn) {
            Event.observe(btn, 'click', this.closeLightBox.bindAsEventListener(this));
        } .bind(this));
        
        if (jQuery.browser.msie && jQuery.browser.version < 7) {
            Event.observe(iframe, 'click', this.closeLightBox.bindAsEventListener(this));
            overlay.appendChild(iframe);
        }
        document.body.appendChild(overlay);

    },

    closeLightBox: function(e) {
        if (e.element().id == this.lightBoxId)
            return;

        if (this.lightBoxId == "popup") {
            $(hdn_product).value = '';
        }

        if ($('overlay'))
            document.body.removeChild($('overlay'));

        $(this.lightBoxId).setStyle({ display: 'none' });
    },

    showLoginPopup: function() {
        this.lightBoxId = "login";
        this.showLightBox();
    },

    showOrderPopup: function(e) {
        if (e.element().tagName == "A") {
            var target = e.element().href;
        }
        else {
            var target = e.element().ancestors()[0].href;
        }

        var targetParts = target.split("#");
        this.targetProduct = targetParts[targetParts.length - 1];

        this.targetScript = '/_services/ProductLookup.ashx';
        this.callBack = 'this.appendProductTypes()';
        this.requestParams = 'Product=' + this.targetProduct;

        this.doRequest();
        jQuery("[id$='cb_1']").attr("checked", "checked");
        jQuery(".QuantityOfPackagePicker").val("1");
        this.lightBoxId = "popup";
        this.showLightBox();
    },

    appendProductTypes: function() {
        productDetails = this.returnData.evalJSON(true);

        $$('.popup_description').each(function(el, index) {
            var packageType = el.className.split(' ')[1];
            $(packageType + '_price').innerHTML = roundVal(eval('productDetails.' + packageType + '.Price'))
            if ($(packageType + '_price_per_month'))
                $(packageType + '_price_per_month').innerHTML = roundVal(eval('productDetails.' + packageType + '.PricePerMonth'))
        } .bind(this));

        function roundVal(val) {
            var dec = 2;
            //var result = Math.round(val * Math.pow(10, dec)) / Math.pow(10, dec);
            var result = val.toFixed(2).replace(".", ",");
            return result;
        }

        $(hdn_product).value = this.targetProduct;
    },

    doRequest: function() {
        if (this.requestMethod)
            var reqMethod = this.requestMethod;
        else
            var reqMethod = 'get';

        new Ajax.Request(this.targetScript, {
            method: reqMethod,
            parameters: this.requestParams,
            onSuccess: (function(transport) {
                this.returnData = transport.responseText;
                eval(this.callBack);
            }).bind(this),
            onFailure: (function(transport) {
                alert("Fout: " + transport.readyState + ' HTTP status: ' + transport.status);
            }).bind(this)
        });
    },

    setFilter: function(e) {
        if (e.element().tagName == "A") {
            var target = e.element().href;
        } else {
            var target = e.element().ancestors()[0].href;
        }

        filterParts = target.split("#");
        this.filterCondition = filterParts[filterParts.length - 1];

        $$('.product_block').each(function(block) {
            block.setStyle({ display: 'block' });
        } .bind(this));

        this.selectCallback = 'this.filterProductList()';
        this.setCheckBox(e);
    },

    filterProductList: function() {
        $$('.product_block').each(function(block) {
            block.setStyle({ display: 'none' });
        } .bind(this));

        var condList = filterconditions.evalJSON(true);
        this.selectedCondition = new Array();

        condList.each(function(condition) {
            if (condition.Filter == this.filterCondition) {
                this.selectedCondition = condition.Products;
                throw $break;
            }
        } .bind(this));

        this.selectedCondition.each(function(product) {
            $('prod_' + product).setStyle({ display: 'block' });
        } .bind(this));
    },



    setPaymentCheckbox: function(e) {
        this.selectCallback = 'this.selectPayment()';
        this.deSelectCallback = 'this.deSelectPayment()';
        this.setCheckBox(e);
    },

    selectPayment: function() {
        var expression = /(incasso)|(factuur)|(ideal)/i;

        res = expression.exec(this.target.className);
        paymentClass = res[0];
        $$('#incasso input')[0].setStyle({ display: 'none' });

        switch (paymentClass) {
            case 'incasso':
                $$('#incasso input')[0].setStyle({ display: 'inline' });
                $$('#betaal_methodes .method_placeholder')[0].value = 'incasso';
                break;

            case 'factuur':
                $$('#betaal_methodes .method_placeholder')[0].value = 'factuur';
                break;

            case 'ideal':
                $$('#betaal_methodes .method_placeholder')[0].value = 'ideal';
                break;

            default:
                $$('#betaal_methodes .method_placeholder')[0].value = '';
        }
    },

    deSelectPayment: function() {
        $$('#incasso input')[0].setStyle({ display: 'none' });
        $$('#betaal_methodes .method_placeholder')[0].value = '';
    },

    toggleFaq: function(e) {
        if (e.element().tagName == 'LI') {
            this.faqTarget = e.element();
        } else {
            e.element().ancestors().each(function(el) {
                if (el.tagName == "LI") {
                    this.faqTarget = el;
                    throw $break;
                }
            } .bind(this));
        }

        if (this.faqTarget.open) {
            this.showHideFaq(this.faqTarget, 'hide');
            this.faqTarget.open = false;
            this.setContentHeight();
        } else {
            $$('.tips_content ul li').each(function(el) {
                if (el.open == true) {
                    this.showHideFaq(el, 'hide');
                    el.open = false;
                }
            } .bind(this));
            this.showHideFaq(this.faqTarget, 'show');
            this.faqTarget.open = true;
        }
    },

    showHideFaq: function(listElement, dir) {
        listElement.setStyle({ background: 'url(\'/images/menu_pointer_' + (dir == 'show' ? 'active' : 'grijs') + '.gif\') no-repeat top left' });
        listElement.childElements().each(function(el) {
            if (el.tagName == "P")
                el.setStyle({ display: (dir == 'show' ? 'block' : 'none') });
            if (el.tagName == "A")
                el.setStyle({ color: (dir == 'show' ? '#fb7c11' : '#666') });
        } .bind(this));

    },

    showHelp: function(e) {
        this.tooltip = $('hlp_tooltip')
        Element.clonePosition(this.tooltip, e.element(), { setWidth: false, setHeight: false, offsetLeft: 12, offsetTop: -70 });
        this.tooltip.setStyle({ display: 'block' });
        this.tooltip.innerHTML = eval('helpContent.' + e.element().id);
    },

    hideHelp: function(e) {
        this.tooltip.setStyle({ display: 'none' });
    }
}
