Array.implement({
    'shuffle': function() {
        var temp;
        for (var i = this.length - 1; i > 0; i--) {
            var j = $random(0, i);
            temp = this[i];
            this[i] = this[j];
            this[j] = temp;
        }
        return this;
    }
});
var randombackground = new Class({
    Implements: [Events, Options],
    options: {
        backimages: [],
        rowHeight: 90,
        rowWidth: 100,
        maxMargin: 15,
        minMargin: 5,
        numStep: 7,
        maxPerRow: 10,
        backColor: "#CCCCCC",
        backgridColor: "#FFFFFF",
        movieWidth: 589,
        movieHeight: 430
    },
    initialize: function(movieArr, lbl) {

        this.curImg = 0;
        this.curVideoSwf = 0;

        var imagesObj = this._createImagesObject(movieArr);

        $("back").empty().addClass("cinema_back").setStyle("z-index", 0);

        this._populateDiv(imagesObj);

        this._isSafari2 = Browser.Engine.webkit && (Browser.Engine.version < 450);

        $("header").addEvent("click", this._reinit.bind(this));

        $("menu").addClass("overlay").setStyles({ "position": "absolute",
            "z-index": 10,
            "top": 0,
            "left": 0,
            "right": 0,
            "float": "none"
        });
        $("cinema").setStyle("position", "relative");
        movieArr.each(function(el) {
            var link = $(el.id).set("href", "javascript:void(0)");
            link.addEvents({ "click": this._linkClicked.pass([[el.id, el.movieURL]], this),
                "mouseover": this._menuRolled.pass([el.id, true], this),
                "mouseout": this._menuRolled.pass(["none", false], this)
            });
        }, this);
        var movieContainer = new Element("div", { "id": "movieContainer", "styles": { "display": "none", "position": "absolute", "width": this.options.movieWidth + 202} }).inject($("menu"));
        new Element("div", { "id": "movieSwiffContainer", "styles": { "background-color": "#000000",
            "width": this.options.movieWidth,
            "height": this.options.movieHeight,
            "float": "left"
        }
        }).inject(movieContainer, "top");
        new Element("div", { "class": "clearer" }).inject($("menu"));
        if (lbl && lbl != "") {
            var movieURL = ""
            imagesObj.each(function(arrItem) { if (arrItem[1] == lbl) { movieURL = arrItem[2] } });
            this._getMovie([lbl, movieURL]);
        }
    },
    _linkClicked : function(arr) {
    
        
        if($("movieContainer").getStyle("display") != "block")
            this._getMovie(arr);
        else
            this._reinit();
            
    },
    _createImagesObject: function(movieArr) {
        var imagesObj = [];
        movieArr.each(function(el) {
            el.images.each(function(img) { imagesObj.push([img, el.id, el.movieURL]) }, this);
        }, this);
        imagesObj = imagesObj.shuffle();
        return imagesObj;
    },
    _populateDiv: function(imagesObj) {
        var initwidth = window.getSize().x;
        var restRow, curRow;
        var restheight = window.getSize().y * 1.5;
        do {
            var bottommargin = 20;
            restRow = initwidth;
            curRow = new Element("div", { "styles": { "width": 2 * restRow,
                "height": this.options.rowHeight,
                "margin-bottom": bottommargin,
                "white-space": "nowrap"
            }
            }).inject($("back"));
            var numOfImage = 0;
            do {
                var rightmargin = 20;
                var imElt = this._getrandomImage(imagesObj, 1 - restRow / initwidth);
                imElt[0].setStyle("margin-right", rightmargin).inject(curRow);
                numOfImage += imElt[1];
                restRow -= rightmargin + this.options.rowWidth;
            } while (restRow > 0 && numOfImage < this.options.maxPerRow)
            restheight -= bottommargin + this.options.rowHeight;
        } while (restheight > 0)
    },
    _getRdmMargin: function() {
        return $random(this.options.maxMargin, this.options.minMargin);
    },
    _getrandomImage: function(imageArr, percentWidth) {

        var container = new Element("div", { "styles": { "background-color": this.options.backgridColor,
            "height": this.options.rowHeight,
            "min-width": this.options.rowWidth,
            "float": "left"
        }
        });
        var isShow = percentWidth > 0.1 && ($random(-70, 100) / 100 + percentWidth / 3) > 0.6;
        var imgItm = imageArr[this.curImg++ % imageArr.length];
        if (isShow) {
            var lkcont = new Element("a", { "events": { "click": this._getMovie.pass([[imgItm[1], imgItm[2]]], this),
                "mouseover": this._imageRolled.pass(imgItm[1], this),
                "mouseout": this._imageRolled.pass("none", this)
            },
                "styles": { "background-color": this.options.backColor,
                    "background-image": "url(" + imgItm[0] + "?height=" + this.options.rowHeight + "&t=brightness:.2|bw&dbl=true)",
                    "heigth": this.options.rowHeight,
                    "float": "left",
                    "display": "block",
                    "margin": "3px"
                },
                "rel": "url(" + imgItm[0] + "?height=" + this.options.rowHeight + "&t=brightness:.2|bw&dbl=true)",
                "class": imgItm[1]
            }).inject(container);
            new Element("img", { "src": imgItm[0] + "?height=" + this.options.rowHeight,
                "styles": { "height": this.options.rowHeight },
                "class": "img"
            }).inject(lkcont);
        } else {
            container.set({ "html": "&nbsp;", "styles": { "width": 100} });
        }
        return [container, isShow ? 1 : 0];
    },
    _reinit: function() {
        if ($("legendContainer")) $("legendContainer").empty();
        if ($("movieSwiffContainer")) $("movieSwiffContainer").empty();
        $("movieContainer").setStyle("display", "none");
        this._highLightMenu("none");
        $("menu").removeClass("inactive");
        if (!this._isSafari2) $("back").removeClass("hideImg");
        else this._hideAllimgSafari2(false);
    },
    _imageRolled: function(menuId) {
        if ($("menu").hasClass("inactive")) return;
        this._highLightMenu(menuId);
        if (!this._isSafari2) return;
        $("back").getElements("a").each(function(elt) { elt.setStyles({ "background-image": (elt.hasClass(menuId) ? "" : elt.get("rel")), "background-repeat": "no-repeat", "background-position": "left top" }); });

    },
    _hideAllimgSafari2: function(bool) {
        $("back").getElements("a").each(function(elt) { elt.setStyle("background-image", bool ? "" : elt.get("rel")); });
    },
    _menuRolled: function(menuId, bool) {
        $("back").getElements("a").each(function(elt) {
            if (elt.hasClass(menuId) && bool) elt.addClass("rolled");
            else elt.removeClass("rolled");
            if (this._isSafari2 && !$("menu").hasClass("inactive")) elt.setStyle("background-image", (elt.hasClass(menuId) && bool) ? "" : elt.get("rel"));
        }, this);
    },
    _highLightMenu: function(menuId) {
        $("menu").getElements("a").each(function(aelt) { if (aelt.get("id") == menuId) aelt.addClass("active"); else aelt.removeClass("active") });
    },
    _setImageVisited: function(menuId) {
        $("back").getElements("a." + menuId).each(function(elt) { elt.addClass("visited"); });
    },
    _getMovie: function(imgobj) {
        $("menu").addClass("inactive");
        this._highLightMenu(imgobj[0]);
        this._setImageVisited(imgobj[0]);
        if (!this._isSafari2) $("back").addClass("hideImg");
        else this._hideAllimgSafari2(true);
        $("movieContainer").setStyle("display", "block");
        if ($("legendContainer")) $("legendContainer").empty();

        if (Browser.Plugins.Flash.version >= 9) {
            if ($("movieSwiffContainer")) $("movieSwiffContainer").empty();
            var url = '/video.swf?r=' + $time();
            var swfElt = new Swiff(url, { "width": this.options.movieWidth,
                "height": this.options.movieHeight,
                "container": $("movieSwiffContainer"),
                vars: { 'urlVideo': imgobj[1],
                    'autoplay': 'true',
                    'fs': 'false',
                    'w': this.options.movieWidth,
                    'h': this.options.movieHeight
                },
                params: { 'scale': 'showall',
                    'allowFullScreen': 'true',
                    'allowScriptAccess': 'sameDomain'
                }
            });

            if (!$("legendContainer")) new Element("div", { "id": "legendContainer", "class": "legends" }).inject($("movieContainer"));
            if (!$chk(this.legendRequest)) this.legendRequest = new Request.HTML({ 'url': '/ajax/returnMovie.aspx',
                'update': $("legendContainer")
            });
            this.legendRequest.cancel().get({ 'lbl': imgobj[0] });
        } else new Element("a", { "text": "In order to view this movie, please install the last flash player here",
            "target": "_blank",
            "href": "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=shockwaveFlash",
            "styles": { "width": "100%",
                "height": this.options.movieHeight,
                "font-size": "10px",
                "color": "white",
                "text-align": "center",
                "line-height": this.options.movieHeight,
                "display": "block"
            }
        }).inject($("movieSwiffContainer"));
    }
});