function getPricetableData(data) {
    var pdata = [];
    var emptyCols = [];

    var m1 = data.match(/<zeile>([\s\S\n]*?)<\/zeile>/g);
    if (m1) {
        for (var i=0; i<m1.length; i++) {
            var m2 = m1[i].match(/<zeile>\s*<typ>([\s\S\n]*?)<\/typ>(\s*<titel>([\s\S\n]*?)<\/titel>)?([\s\S\n]*?)<\/zeile>/);
            var typ = m2[1].trim();
            var title;
            if (m2[3]) {
                title = m2[3].trim();
            }

            var row = [title];
            var cols = 1;
            if (emptyCols.length == 0) {
                emptyCols.push(false);
            }

            var m3 = m2[4].match(/<text>([\s\S\n]*?)<\/text>/g);
            if (m3) {
                for (var j=0; j<m3.length; j++) {
                    var m4 = m3[j].match(/<text>([\s\S\n]*?)<\/text>/);

                    var s = m4[1];

                    cols++;

                    if (emptyCols.length < cols) {
                        emptyCols.push(true);
                    }
                    if (s && s != '') {
                        emptyCols[cols-1] = false;
                    }

                    row.push(s);
                }
                
                pdata.push({
                    'data': row,
                    'type': typ
                });
            }

        }
    }


    return {
        'pdata': pdata,
        'emptyCols': emptyCols
    };
}

function getPricetableStrData(data, pieces) {
    var res = getPricetableData(data);

    for (var i=0; i<res.pdata.length; i++) {
        var row = res.pdata[i];

        for (var j=1; j<row.data.length; j++) {
            var s = row.data[j];

            if (s != '') {
                switch (row.type) {
                    case '1':
                        var m = s.match(/^\s*([0-9]+)\s*$/);
                        if (m) {
                            s = formatFloat(m[1], 0, true);
                        }
                        s += ' ' + ((pieces) ? pieces : pieces_title);
                        break;

                    case '0':
                        if (s == -1) {
                            s = on_request;
                        } else {
                            s = formatFloat(s, 2, true) + '&nbsp;' + euro;
                        }
                        break;
                }
            }

            res.pdata[i].data[j] = s;
        }
    }

    return res;
}

function getPricetableExtensionData(data) {
    var res = [];

    var m1 = data.match(/<zeile>([\s\S\n]*?)<\/zeile>/g);
    if (m1) {
        for (var i=0; i<m1.length; i++) {
            var m2 = m1[i].match(/<zeile>([\s\S\n]*?)<\/zeile>/);

            var row = [];


            var m3 = m2[1].match(/<text>([\s\S\n]+?)<\/text>/g);
            if (m3) {
                for (var j=0; j<m3.length; j++) {
                    var m4 = m3[j].match(/<text>([\s\S\n]*?)<\/text>/);
                    var s = m4[1];

                    if (row.length < 2 || s != '') {
                        row.push(s);
                    }
                }

                res.push(row);
            }
        }
    }

    return res;
}

function getPricetableExtensionStrData(data) {
    var res = getPricetableExtensionData(data);

    for (var i=0; i<res.length; i++) {
        var row = res[i];

        for (var j=0; j<row.length; j++) {
            var s = row[j];

            s = s.replace_callback(/([0-9]+)((,|\.)(--?|[0-9]+))?\s*(EUR|€)/, function(m){

                var p = m[1]*1;

                if (m[4] && m[4] != '' && m[4] != '-' && m[4] != '--') {
                    p += m[4]/100;
                }

                return formatFloat(p, 2, true) + '&nbsp;' + euro;
            });

            res[i][j] = s;
        }
    }

    return res;
}

function getArticleItem(data, odd, key, title, html, htmlTitle) {
    var t = new Element('div');

    if (html) {
        t.set('html', data[key]);
    } else {
        t.set('text', data[key]);
    }

    return new Element('div', {
            'class': key+(odd ? ' odd' : ' even')

        }).adopt(new Element('h3', {
            'html': (htmlTitle ? data[title] : title)

        })).adopt(t);
}

registerMooFlowOptions('articles', {
    useSlider: true,
    useAutoPlay: false,
    useCaption: true,
    useWindowResize: false,
    useMouseWheel: true,
    useKeyInput: true,
    useViewer: false,
    useDetails: true,
    startCentered: true,
    vCentered: true,
    foc: 90,
    offsetY: -10, //-110
    factor: 140,
    bgColor: '#3d4145',
    initable: function() {
        return !this.MooFlow.hasClass('emptyGrid');
    },
    onRemoveDetails: function(mooFlow) {
        $$('.detailsNavigatorItem').each(function(i){
            var p = i.getPrevious();
            if (p) {
                p.addClass('last');
                p.removeEvents('click');
            }
            i.dispose();
        });
        $$('.backArrow').each(function(i){
            i.setStyle('display', 'block');
        });
    },
    onSetDetails: function(content, object, mooFlow) {
        $$('.backArrow').each(function(i){
            i.setStyle('display', 'none');
        });

        if (object.key) {
            requestData('data/articledetails.xml',
                (function(data){
                    if (data.length != 1) {
                            return;
                    }
                    data = data[0];

                    $$('.navigator ul').each((function(i){
                        var p = i.getLast();
                        if (p) {
                            p.removeClass('last');
                            p.addEvent('click', (function(){
                                this.mf.removeDetails();
                                return false;
                            }).bind({
                                mf: this.mf
                            }));
                        }

                        i.getElements('.detailsNavigatorItem').dispose();

                        i.adopt(
                            new Element('li', {
                                'class': (i.getChildren().length == 0 ? 'first' : '')
                            }).adopt(
                                new Element('a', {
                                    'href': isdefined('searchtext') ?
                                        domainDir+'?_resource=search.xml&st='+searchtext+'#mfkey:'+this.data.id+'d' :
                                        domainDir+'?_resource=articles.xml&cid='+category_id+'#mfkey:'+this.data.id+'d'
                                }).adopt(
                                    new Element('span', {
                                        'html': this.data.title
                                    })
                                )
                            ).addClass('detailsNavigatorItem')
                        );
                        
                    }).bind({
                        data: data,
                        mf: this.mf
                    }));

                    this.c.adopt(new Element('h2', {'html': data.title}));
                    this.c.adopt(new Element('div', {
                        'html': data.description,
                        'class': 'desc'
                    }));


                    loadSqueezeBox();

                    this.c.adopt(new Element('a', {
                        'class': 'order_sample',
                        'target': '_blank',
                        'href': dir + '?_resource=articlesample.xml&id='+data.id
                    }).adopt(
                        new Element('span', {
                            'html': order_sample
                        })
                    ).addEvent('click', (function(){

                        SqueezeBox.open(dir + '?_resource=articlesample.xml&hideclose=1&id='+this.id, {
                            handler: 'iframe',
                            size: {
                                x: 690,
                                y: 550
                            }
                        });

                        return false;

                    }).bind({
                        id: data.id
                    })));


                    var x = 0;
                    article_items.each((function(i){
                        
                        if (data[i[0]]) {
                            this.adopt(getArticleItem(data, (x++%2 == 0), i[0], i[1], i[2], i[3]));
                        }

                    }).bind(this.c));


                    var pdiv = new Element('div', {
                        'class': 'prices'+(x++%2 == 0 ? ' odd' : ' even')
                    });

                    if (data.prices_header) {
                        this.c.adopt(
                            pdiv.adopt(new Element('h3', {
                                'html': prices

                            })).adopt(new Element('div', {
                                'html': data.prices_header

                            }))
                        );
                    }

                    if (data.prices) {

                        var pRes = getPricetableStrData(data.prices, data.pieces);



                        var tb = new Element('tbody');

                        var t = new Element('table', {
                            'class': 'pricelist'
                        }).adopt(tb);
                        this.c.adopt(
                            pdiv.adopt(t)
                        );



                        for (var i=0; i<pRes.pdata.length; i++) {
                            var row = pRes.pdata[i];


                            var r = new Element('tr');
                            tb.adopt(r);

                            if (row.data.length > 0 && !pRes.emptyCols[0]) {
                                r.adopt(
                                    new Element('td', {
                                        'class': 'title',
                                        'html': row.data[0]
                                    })
                                );
                            }


                            for (var j=1; j<row.data.length; j++) {
                                if (pRes.emptyCols[j]) {
                                    continue;
                                }

                                var c = new Element('td', {
                                    'html': row.data[j]
                                });
                                r.adopt(c);
                            }
                        }
                    }


                    if (data.prices_extensions) {

                        var tb = new Element('tbody');
                        var t = new Element('table', {
                            'class': 'ext'
                        }).adopt(tb);
                        this.c.adopt(
                            pdiv.adopt(t)
                        );


                        var edata = getPricetableExtensionStrData(data.prices_extensions);
                        for (var i=0; i<edata.length; i++) {

                            var r = new Element('tr');
                            tb.adopt(r);

                            var row = edata[i];
                            for (var j=0; j<row.length; j++) {

                                var c = new Element('td', {
                                    'html': row[j],
                                    'colspan': 3-row.length
                                });
                                r.adopt(c);
                            }
                        }
                    }

                    if (data.attachments) {



                        var atts = data.attachments.split('|');

                        if (atts.length > 0) {
                            var s = new Element('ul');

                            new Element('div', {
                                'class': 'attachments'
                            }).adopt(
                                new Element('h3', {
                                    'html': attachments
                                })
                            ).inject(this.c).adopt(new Element('div', {
                                'class': 'simpleGrid'
                            }).adopt(s)).adopt(new Element('div').setStyle('clear', 'left'));

                            atts.each((function(i){
                                var m;
                                if (m = i.match(/^([0-9]+):([a-z0-9]+):([0-9]*):([0-9]*):(.*)$/)) {
                                    
                                    loadSqueezeBox();

                                    var li = new Element('li', {
                                    });

                                    if (m[2] == 'link') {
                                        li.addClass('active');

                                        var link = m[5];
                                        var text = null;
                                        var m2;
                                        if (m2 = link.match(/^(.*)<spacing>(.*)$/)) {
                                            link = m2[1];
                                            text = m2[2].trim();
                                        }

                                        li.adopt(
                                            new Element('a', {
                                                'target': '_blank',
                                                'href': link
                                            }).adopt(
                                                new Element('span', {
                                                    'html': (text != '') ? text : link
                                                })
                                            )
                                        );

                                    } else {
                                        li.addEvent('click', (function(i){

                                            var tc = null;
                                            if (SqueezeBox.win && SqueezeBox.win.text) {
                                                tc = SqueezeBox.win.text;
                                                
                                            } else {
                                                tc = new Element('div', {
                                                    'class': 'text'
                                                });
                                            }

                                            SqueezeBox.open(imgDir+attsdir+this.attid+'.'+this.type, {
                                                handler: (this.type == 'swf' ? this.type : null),
                                                size: {
                                                    x: this.width,
                                                    y: this.height
                                                },
                                                'onMove': (function(overlay, win){
                                                    if (win.text) {
                                                        var c = $('sbox-content');
                                                        win.text.inject(c, 'after');

                                                        c.setStyle('height', this.y+'px');
                                                        win.setStyle('height', (this.y+70)+'px');
                                                    }
                                                }).bind({
                                                    tc: tc,
                                                    y: this.height
                                                })
                                            });

                                            SqueezeBox.win.text = tc;
                                            

                                            var setText = function(i) {
                                                var text = null;
                                                if (i.length > 0 && i[0].text) {
                                                    text = i[0].text;
                                                }

                                                if (SqueezeBox.text) {
                                                    SqueezeBox.text.dispose();
                                                    SqueezeBox.text = null;
                                                }

                                                if (text) {
                                                    this.tc.set('html', text);
                                                }
                                            };

                                            requestData('data/articledetailtext.xml', setText.bind({tc: tc}), {
                                                id: this.id,
                                                aid: this.attid
                                            });

                                        }).bind({
                                            mf: this.mf,
                                            id: data.id,
                                            attid: m[1],
                                            type: m[2],
                                            width: m[3]*1,
                                            height: m[4]*1
                                        }));


                                        var img;
                                        img = new Asset.image(imgDir+attsdir+m[1]+'p_small.png', {
                                        'onload': (function(img) {
                                            img = img || this.img;
                                            if (!img) {
                                                return;
                                            }

                                            var w = img.get('width');
                                            var h = img.get('height');

                                            if (w > h) {
                                                img.addClass('width');
                                                h *= 50.0/w;
                                                w = 50
                                            } else {
                                                w *= 50.0/h;
                                                h = 50
                                            }

                                            img.removeProperties('width','height');

                                            img.inject(this.item, 'top');

                                            refreshMooScrolls();

                                        }).bind({
                                            item: li,
                                            mf: this.mf,
                                            id: data.id,
                                            attid: m[1],
                                            type: m[2],
                                            width: m[3],
                                            height: m[4],
                                            img: img
                                        }),

                                            'onerror': (function() {
                                                var img = new Element('img', {
                                                    'src': imgDir+'no-image-light.png',
                                                    'class': 'notfound'
                                                });

                                                img.inject(this.item, 'top');

                                                refreshMooScrolls();

                                            }).bind({
                                                item: li,
                                                mf: this.mf
                                            })
                                        });
                                    }


                                    this.list.adopt(li);
                                }

                            }).bind({
                                list: s,
                                mf: this.mf
                            }));
                        }
                    }


                    if (create_pdf == '1') {
                        var l;
                        var r;
                        var p;

                        var options = new Element('div', {
                            'class': 'pdf_options'
                        });
                        options.adopt(
                            l = createSelectInput(language, [
                                ['de', language_de],
                                ['en', language_en]
                            ]),
                            r = createSelectInput(resolution, [
                                ['72', '72 '+dpi],
                                ['300', '300 '+dpi]
                            ]),
                            p = createTextInput(price_factor, '1'),
                            createSubmitInput(do_create_pdf, (function(){
                                window.open(dir+'?_resource=pdfexport/articlepdf.xml'+
                                    '&id='+this.id+
                                    '&factor='+this.factor.get('value')+
                                    '&language='+this.language.get('value')+
                                    '&resolution='+this.resolution.get('value'), '_blank');
                                
                                this.div.setStyle('display', 'none');
                                return false;
                            }).bind({
                                div: options,
                                id: data.id,
                                language: l.getElements('select')[0],
                                resolution: r.getElements('select')[0],
                                factor: p.getElements('input')[0]
                            }))
                        ).setStyle('display', 'none');

                        new Element('div', {
                            'class': 'download_pdf'
                        }).adopt(
                            new Element('h3', {
                                'html': download_pdf
                            }),
                            new Element('a').addEvent('click',
                                (function(){
                                    this.options.setStyle('display', 'block');
                                    refreshMooScrolls();
                                    return false;
                                }).bind({options: options})
                            ),
                            options
                        ).inject(this.c);
                    }



                    if (data.similar) {
                        var similar = data.similar.split(']]|');

                        if (similar.length > 0) {
                            var s = new Element('ul');

                            new Element('div', {
                                'class': 'similar_articles'
                            }).adopt(
                                new Element('h3', {
                                    'html': similar_articles
                                })
                            ).inject(this.c).adopt(s).adopt(new Element('div').setStyle('clear', 'left'));

                            similar.each((function(i){
                                var m;
                                if (m = i.match(/^([0-9]+):([0-9]+):\[\[(.*?)(\]\])?$/)) {

                                    var li = new Element('li', {
                                    }).adopt(
                                        new Element('h4', {
                                            'html': m[3]
                                        })
                                    ).addEvent('click', (function(){
                                        if (!isdefined('category_id') || m[2] != category_id) {
                                            window.open(domainDir+'?cid='+m[2]+'&_resource=articles.xml#mfkey:'+m[1]+'d'+(this.mf.isFull ? 'f' : ''), '_self');
                                        } else {
                                            for (var j=0; j<this.mf.master.images.length; j++) {
                                                if (this.mf.master.images[j].key == m[1]) {
                                                    this.mf.showDetailsDirectly = true;
                                                    this.mf.glideTo(j);
                                                    return;
                                                }
                                            }
                                        }
                                    }).bind({
                                        mf: this.mf
                                    }));

                                    var img;
                                    img = new Asset.image(imgDir+filesdir+m[1]+'_small.png', {
                                    'onload': (function(img) {
                                        img = img || this.img;
                                        if (!img) {
                                            return;
                                        }

                                        var w = img.get('width');
                                        var h = img.get('height');

                                        if (w > h) {
                                            img.addClass('width');
                                            h *= 50.0/w;
                                            w = 50
                                        } else {
                                            w *= 50.0/h;
                                            h = 50
                                        }

                                        img.removeProperties('width','height');

                                        var d = new Element('div').adopt(img).inject(this.item, 'top');

                                        d.reflect({
                                            'img': img,
                                            'ref': this.mf.options.reflection,
                                            'height': h,
                                            'width': w,
                                            'color': this.mf.options.bgColor
                                        }).inject(d);
                                        
                                        refreshMooScrolls();

                                    }).bind({
                                        item: li,
                                        mf: this.mf,
                                        img: img
                                    }),
                                    
                                    'onerror': (function() {
                                        var img = new Element('img', {
                                            'src': imgDir+'no-image-light.png',
                                            'class': 'notfound'
                                        });

                                        var d = new Element('div').adopt(img).inject(this.item, 'top');

                                        d.reflect({
                                            'img': img,
                                            'ref': this.mf.options.reflection,
                                            'height': 50,
                                            'width': 50,
                                            'color': this.mf.options.bgColor
                                        }).inject(d);

                                        refreshMooScrolls();

                                    }).bind({
                                        item: li,
                                        mf: this.mf
                                    })
                                });

                                this.list.adopt(li);
                            }

                        }).bind({
                            list: s,
                            mf: this.mf
                        }));
                    }
                }



                if (data.tags) {
                    this.c.adopt(getArticleItem(data, (x++%2 == 0), 'tags', tags, false));
                }

                new Element('div', {
                    'class': 'clear'
                }).inject(this.c);



                refreshMooScrolls();

            }).bind({
                c: content,
                mf: mooFlow
            }), {
                id: object.key
            });
        }
    }/*,
    onClickView: function(obj) {
        if (obj.href) {
            window.open(obj.href, '_self');
        }
    }*/
});
