/**
 * 
 */

var c1x1Multibox = new Class(
    {
        options: {
            backcolor: '#000',
            frontcolor: '#444',
            lightcolor: '#FFF',
            openDuration: 500,
            sliderspeed: 500,
            shader_opacity: 0.6,
            outer_offset: [30,30],
            sliderheight: 200
        },
        contentsWidth: 600,
        contentsHeight: 600,
    
        //Objects
        shader: null,
        box: null,
        innerbox: null,
        sliderbox: null,
        currentitem: null,
        counter: null,
    
        // Flags
        enableSlider: true,
        elementCount: true,
    
        fx: {},

        // Data
        data: [],
        anchors: [],
        current: 0,
        effectstep: 0,
        type: 'image',
    
        //Callbacks
        onCurrent: null,
    
        //Methods
        initialize: function(options) 
        {
            if(!options || !options.container) return;
            this.container = document.id(options.container);
            if(options.mode == 'JSON')
            {
                this.data = JSON.decode(this.container.get('text'));
                this.container.empty();
            }
            else if(options.mode == 'both')
            {
                this.container.getElements('.c1x1_multibox_item').each(
                    function (item, index)
                    {
                        this.data.push(
                        {
                            preview: {
                                file: item.getElement('.c1x1_multibox_preview').get('src')
                            },
                            image:  {
                                file: item.getElement('.c1x1_multibox_image').get('src')
                            }
                        }
                        );
                    }.bind(this)
                    );
                this.container.empty();
            }
            this.initFirst();
        },
        initFirst: function ()
        {
            var i = new Element('img',{
                src:this.data[0].preview.file
                });
            i.addEvent('click',this.open.bind(this,0));
            i.inject(this.container);
        },
        onResize: function () {
            if(this.shader) this.shader.setStyle('height',window.getSize().y);
        },
        open: function ()
        {
            window.addEvent('resize',this.onResize.bind(this));
            this.shader = new Element('div',{
                'class': 'c1x1_multibox_shader'
            });
            this.shader.setStyles({
                'opacity':this.options.shader_opacity,
                'height':window.getSize().y});
            this.box = new Element('div',{
                'class': 'c1x1_multibox_box_outer',
                'styles':
                {
                    opacity: 0,
                    left: (window.getSize().x/2)-10,
                    width: 20,
                    height: 20,
                    top: (window.getSize().y/2)-10
                }
            });
            this.shader.addEvent('click',this.close.bind(this));
            this.shader.inject(document.body);
            this.box.inject(document.body);
            new Element('div',{
                'class':'c1x1_multibox_close'
            })
            .inject(this.box)
            .addEvent('click',this.close.bind(this));
            this.innerbox = new Element('div',{
                'class': 'c1x1_multibox_box_inner'
            }).inject(this.box);
        

            this.fx.box = new Fx.Morph(this.box,{
                duration: this.options.openDuration,
                link: 'chain'
            });
            
            this.fx.inner = new Fx.Morph(this.innerbox,{
                duration: 500,
                link: 'chain'
            });
            this.fx.box.start(
            {
                
                width: this.contentsWidth,
                left: (window.getSize().x/2) - ((this.contentsWidth+this.options.outer_offset[0])/2),
                'margin-left': 0,
                opacity: 1
            });
            this.fx.box.start({
                top: (window.getSize().y/2) - ((this.contentsHeight+this.options.outer_offset[1])/2),
                height: this.contentsHeight,
            }).chain(this.initbox.bind(this));

        },
        initbox: function ()
        {
            this.initCurrent();
            if(this.type == 'image')
                this.setCurrent(0);
            if(this.enableSlider)
                this.initSlider();
            if((!this.enableSlider || this.fullnav) && this.data.length > 1)
            {
                new Element('div',{
                    'class':'c1x1_multibox_nav_left'
                })
                .inject(this.box)
                .addEvent('click',this.goPrev.bind(this));
                new Element('div',{
                    'class':'c1x1_multibox_nav_right'
                }).inject(this.box)
                .addEvent('click',this.goNext.bind(this));
            }
            if(this.elementCount)
            {
                this.counter = new Element('div',{
                    'class': 'c1x1_multibox_counter',
                    'text': (this.current+1)+'/'+this.data.length
                    }).inject(this.box);
            }
        },
        initSlider: function ()
        {
            var sl = new Element('div',{
                'class': 'c1x1_multibox_box_slider_outer'
            }).inject(this.box);
            this.sliderbox = new Element('div',{
                'class': 'c1x1_multibox_box_slider'
            }).inject(sl);
            this.sliderbox.set('tween',{
                duration: this.options.sliderspeed
            });
            
            new Element('div',{
                'class':'c1x1_multibox_slider_left'
            })
            .inject(sl)
            .addEvent('click',this.goPrev.bind(this));
            
            new Element('div',{
                'class':'c1x1_multibox_slider_right'
            }).inject(sl)
            .addEvent('click',this.goNext.bind(this));
            this.sliderbox.setStyle('width',this.data.length*165);
            for(var i = 0; i < this.data.length; i++)
            {
var            si = new Element('div').setStyles({'float':'left','height': 120,'width': 160,'overflow': 'hidden'}).inject(this.sliderbox);
                new Element('img',{
                    src:this.data[i].preview.file
                    }).inject(si).
                addEvent('click',this.setCurrent.bind(this,i));
            }
        },
        goNext: function ()
        {
            if((this.current+1) >= this.data.length) this.current = -1;
            if(this.sliderbox)
            {
                var p = this.sliderbox.getElements('img')[this.current+1].getPosition(this.sliderbox);
                this.sliderbox.tween('left',p.x*-1);
            }
            this.setCurrent(this.current+1);
        },
        goPrev: function ()
        {
            if(this.current <= 0) this.current = (this.data.length);
            if(this.sliderbox)
            {
                var p = this.sliderbox.getElements('img')[this.current-1].getPosition(this.sliderbox);
                this.sliderbox.tween('left',p.x*-1);
            }
            this.setCurrent(this.current-1);
        },
        initCurrent: function ()
        {
            if(this.type == 'image')
            {
                this.currentitem = new Element('img')
                .inject(this.innerbox);
               // this.currentitem.setStyle('opacity',0);
            }
        },
        setCurrent: function (i)
        {
            this.current = i;
            if(this.counter)
                this.counter.set('text',(this.current+1)+'/'+this.data.length);

            this.fx.inner.start({'opacity':0}).chain(
                function (i)
                {
                    this.currentitem.set('src',this.data[i].image.file);
                    this.fx.inner.start({'opacity':1});
                    if(this.onCurrent)
                        this.onCurrent(this.data[i]);
                }.bind(this,i)
            );
            
        },
        close: function ()
        {
            this.fx.box.start('opacity',0);
            this.box.destroy();
            this.shader.destroy();
        },
        scanAnchors: function (strselect)
        {
            document.getElements(strselect).each(
                function(el)
                {
                    if (el.rel && el.rel.test(/^mediabox/i)){
                        el.addEvent('click',this.openAnchor.pass(el,this));
                        this.anchors.push(el);
                    }
                }.bind(this));
        },
        openAnchor: function(el)
        {
            if(!el || !el.getAttribute) return;
            var aDim = el.getAttribute('rel').match(/[0-9]+/g);													// videobox rel settings
            this.contentsWidth = parseInt((aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defaultWidth);
            this.contentsHeight = parseInt((aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defaultHeight);

            var videoId = null;
            this.enableSlider = false;
            url = el.getAttribute('href');
            if (url.match(/youtube\.com\/watch/i)) {
                // YouTube
                this.type = 'flash';
                videoId = url.split('=');
                this.videoID = videoId[1];
                this.currentitem = new SWFObject("http://www.youtube.com/v/"+this.videoID+"&autoplay=1", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
            } else if (url.match(/dailymotion\.com/i)) {
                // DailyMotion
                this.type = 'flash';
                this.currentitem = new SWFObject(url, "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000");
            } else if (url.match(/metacafe\.com\/watch/i)) {
                // Metacafe
                this.type = 'flash';
                videoId = url.split('/');
                this.videoID = videoId[4];
                this.currentitem = new SWFObject("http://www.metacafe.com/fplayer/"+this.videoID+"/.swf", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
            } else if (url.match(/google\.com\/videoplay/i)) {
                // Google Video
                this.type = 'flash';
                videoId = url.split('=');
                this.videoID = videoId[1];
                this.currentitem = new SWFObject("http://video.google.com/googleplayer.swf?docId="+this.videoID+"&autoplay=1&hl=en", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
            } else if (url.match(/\.swf/i)) {
                // Flash			.swf
                this.type = 'flash';
                this.currentitem = new SWFObject(url, "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
            } else if (url.match(/\.flv/i)) {
                // Flash Video		.flv
            
                this.type = 'flash';
                this.open();
                    this.currentitem = new Element('div',{'id': 'faplayerdiv'})
                    .inject(this.innerbox);
                    (function () {
                    playerOne = new FAVideo('faplayerdiv','',this.contentsWidth,this.contentsHeight,'','');
                    playerOne.play(url);
                    }).bind(this).delay(2500);
                return false;
           //     this.currentitem = new SWFObject(this.options.playerpath+"?file="+url+"&autostart=true&displayheight="+this.contentsHeight+"&usefullscreen=false&backcolor="+this.options.backcolor+"&frontcolor="+this.options.frontcolor+"&lightcolor="+this.options.lightcolor, "flvvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
            } else if (url.match(/\.mov/i)) {
                // Quicktime		.mov
                this.type = 'qt';
                if (navigator.plugins && navigator.plugins.length) {
                    this.currentitem = '<object id="mediabox" standby="loading quicktime..." type="video/quicktime" codebase="http://www.apple.com/qtactivex/qtplugin.cab" data="'+url+'" width="'+this.contentsWidth+'" height="'+this.contentsHeight+'"><param name="src" value="'+url+'" /><param name="scale" value="aspect" /><param name="controller" value="'+this.options.controller+'" /><param name="autoplay" value="'+this.options.autoplay+'" /><param name="bgcolor" value="'+this.options.bgcolor+'" /><param name="enablejavascript" value="true" /></object>';
                } else {
                    this.currentitem = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" standby="loading quicktime..." codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="'+this.contentsWidth+'" height="'+this.contentsHeight+'" id="mediabox"><param name="src" value="'+url+'" /><param name="scale" value="aspect" /><param name="controller" value="'+this.options.controller+'" /><param name="autoplay" value="'+this.options.autoplay+'" /><param name="bgcolor" value="'+this.options.bgcolor+'" /><param name="enablejavascript" value="true" /></object>';
                }
            } else if (url.match(/\.wmv/i)) {
                // Windows Media	.wmv
                this.type = 'qt';
                if (navigator.plugins && navigator.plugins.length) {
                    this.currentitem= '<object id="mediabox" standby="loading windows media..." type="video/x-ms-wmv" data="'+url+'" width="'+this.contentsWidth+'" height="'+this.contentsHeight+'" /><param name="src" value="'+url+'" /><param name="autoStart" value="'+this.options.autoplay+'" /></object>';
                } else {
                    this.currentitem = '<object id="mediabox" standby="loading windows media..." classid="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95" type="video/x-ms-wmv" data="'+url+'" width="'+this.contentsWidth+'" height="'+this.contentsHeight+'" /><param name="filename" value="'+url+'" /><param name="showcontrols" value="'+this.options.controller+'"><param name="autoStart" value="'+this.options.autoplay+'" /><param name="stretchToFit" value="true" /></object>';
                }
            }
            else {
                // iFrame content
                this.type = 'iframe';
                this.iframeId = "lbFrame_"+new Date().getTime();	// Safari would not update iframe content that has static id.
                this.currentitem = new Element('iframe').setProperties({
                    id: this.iframeId, 
                    width: this.contentsWidth, 
                    height: this.contentsHeight, 
                    frameBorder:0, 
                    scrolling:'auto', 
                    src:url
                });
            }
        
            this.open();
            if(this.currentitem.inject)
                this.currentitem.inject(this.innerbox);
            else
                this.innerbox.set('html',this.currentitem);
            return false;
        }
    
    });
