var ImageGallery = new Class({
    Implements: Options,
    options:  {
        version: "standard",
        ratingOpen: 1,
        containerHeight: 200,
        iconPath: "",
        shareHTML: "",
        galleryJson: "",
        imageInterval: 1000,
        leftColWidth: "600px"
    },

    loadedImages: [],
    transitionSpeed: 700,
    thumbnailsShowing: false,
    captionsShowing: true,

    initialize: function(options)  {
        this.setOptions(options);

        this.info = this.options.galleryJson;
        this.displayedImageIndex = this.info['start_index'];
        $("slideshow_container").setStyle("height", 
           this.options.containerHeight + parseInt($("headline_bar").getStyle("height")))


        var img = new Element("img", {
            "class": "photo",
            src: this.info.images[this.displayedImageIndex]['src'],
            alt: this.info.images[this.displayedImageIndex]['caption'],
            width: this.info.images[this.displayedImageIndex]['width'],
            height: this.info.images[this.displayedImageIndex]['height']
        });
        var marginLeft = (parseInt(this.options.leftColWidth) - img.get("width")) / 2;
        var marginTop = (this.options.containerHeight - img.get("height")) / 2 - 4;
        img.setStyles({
            "margin-left": marginLeft,
            "margin-top": marginTop
        });

        var root = this;
        img.addEvent("click", function()  { 
            root.getNext(); 
            // stop rotating images
            if (root.intervalId)
            {
                clearInterval(root.intervalId);
                root.intervalId = null;
                $$('#playpause img')[0].set("src", root.options.iconPath + "/play_button.png");
                $$('#playpause img')[0].set("alt", "play");
                $$('#playpause img')[0].set("title", "play");
            }
        });

        img.inject($('slideshow_container'));
        var myFx = new Fx.Tween(img, { duration: this.transitionSpeed });
        myFx.start("opacity", 0, 1);
        this.loadedImages[this.displayedImageIndex] = img;

        var nextImage = this.displayedImageIndex + 1;
        if (nextImage >= this.info.images.length)
        {
            nextImage = 0;
        }
        this.preloadIndex(nextImage);

        var prevImage = this.displayedImageIndex - 1;
        if (prevImage < 0)
        {
            prevImage = this.info.images.length - 1;
        }
        this.preloadIndex(prevImage);

        this.drawControlPanel();
        this.startInterval();
        this.updateCounter();
    },

    showIndex: function(index)  {
        if (this.intervalId)
        {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
        if (this.thumbnailsShowing)
        {
            this.toggleThumbnails();
        }
        if (this.info.images[index] == undefined)
        {
            index = 0;
        }
        var img;
        var root = this;
        if (this.loadedImages[index] == undefined)
        {
            img = new Element("img", {
                "class": "photo",
                src: this.info.images[index]['src'],
                alt: this.info.images[index]['caption'],
                width: this.info.images[index]['width'],
                height: this.info.images[index]['height']
            });
            var marginLeft = (parseInt(this.options.leftColWidth) - img.get("width")) / 2;
            var marginTop = (this.options.containerHeight - img.get("height")) / 2 - 4;
            img.setStyles({
                "margin-left": marginLeft,
                "margin-top": marginTop
            });
            img.addEvent("click", function()  { 
                root.getNext(); 
                // stop rotating images
                if (root.intervalId)
                {
                    clearInterval(root.intervalId);
                    root.intervalId = null;
                    $$('#playpause img')[0].set("src", root.options.iconPath + "/play_button.png");
                    $$('#playpause img')[0].set("alt", "play");
                    $$('#playpause img')[0].set("title", "play");
                }
            });

            img.inject($('slideshow_container'));
            this.loadedImages[index] = img;
        }
        $$("#slideshow_container img.photo").each(function(item)  {
            item.setStyle("opacity", 0);
        });
        this.loadedImages[index].setStyle("opacity", 1);
        this.displayedImageIndex = index;
        this.updateCounter();

        var nextIndex = index + 1;
        if (nextIndex >= this.loadedImages.length)
        {
            nextIndex = 0;
        }
        this.preloadIndex(nextIndex);

        var prevIndex = index - 1;
        if (prevIndex < 0)
        {
            prevIndex = this.loadedImages.length - 1;
        }
        this.preloadIndex(prevIndex);
    },

    preloadIndex: function(index)
    {
        var root = this;
        if (this.loadedImages[index])
        {
            return;
        }
        var img = new Element("img", {
            "class": "photo",
            src: this.info.images[index]['src'],
            alt: this.info.images[index]['caption'],
            width: this.info.images[index]['width'],
            height: this.info.images[index]['height']
        });
        var marginLeft = (parseInt(this.options.leftColWidth) - img.get("width")) / 2;
        var marginTop = (this.options.containerHeight - img.get("height")) / 2 - 4;
        img.setStyles({
            "margin-left": marginLeft,
            "margin-top": marginTop,
            "visibility": "hidden"
        });
        img.addEvent("click", function()  { 
            root.getNext(); 
            // stop rotating images
            if (root.intervalId)
            {
                clearInterval(root.intervalId);
                root.intervalId = null;
                $$('#playpause img')[0].set("src", root.options.iconPath + "/play_button.png");
                $$('#playpause img')[0].set("alt", "play");
                $$('#playpause img')[0].set("title", "play");
            }
        });

        img.inject($('slideshow_container'));
        this.loadedImages[index] = img;
    },

    updateCounter: function()  {
        var current = this.displayedImageIndex + 1;
        var total = this.loadedImages.length;

        $('slideshow_counter').set("html", current + " / " + total);
        this.updateCaption();
        this.updateCredit();
      //  this.updateRatings();
        this.updateAnalytics();
      //  this.updateDisplayAd();
    },

    updateDisplayAd: function()  {
        if (this.adTimeoutID)
        {
            clearTimeout(this.adTimeoutID);
        }
        var rotateAd = function()  {
            // check to see if 1000x60 ad has content; if so, don't rotate this 300x250 out
            var imgs = $$('div#ss_1000x60_ad img');
            if (imgs[0])
            {
                var w = parseInt(imgs[0].get("width"));
                var h = parseInt(imgs[0].get("height"));
                if (w >= 10 && h >= 10)
                {
                    return;
                }
            }

            var iframes = $$('div#ss_1000x60_ad iframe');
            if (iframes[0])
            {
                return;
            }

            // rotate the 300x250 ad
            var src = $('ss_300x250_ad').get("src");
            $('ss_300x250_ad').set("src", src);
        };
        this.adTimeoutID = setTimeout(rotateAd, 700);
    },

    updateAnalytics: function()  {
        s.prop6 = s.pageName;
        s.t();
    },

    updateRatings: function()  {
        var highlight, off;
        if (this.options.version == 'standard')
        {
            highlight = this.options.iconPath + "/star_yellow.png";
            off = this.options.iconPath + "/star_gray.png";
        }
        else
        {
            highlight = this.options.iconPath + "/paw_yellow.png";
            off = this.options.iconPath + "/paw_gray.png";
        }

        if (this.info.images[this.displayedImageIndex]['rating_text'])
        {
            $('rating_text').setStyle("text-transform", "none");
            $('rating_text').set("html", this.info.images[this.displayedImageIndex]['rating_text']);
            for (var i = 1; i <= this.info.images[this.displayedImageIndex]['my_rating']; i++)
            {
                $$('#rating_stars img')[i-1].set("src", highlight);
            }
            for (var i = this.info.images[this.displayedImageIndex]['my_rating'] + 1; i <= 5; i++)
            {
                $$('#rating_stars img')[i-1].set("src", off);
            }
        }
        else
        {
            $('rating_text').setStyle("text-transform", "uppercase");
            $('rating_text').set("html", "Rate this image");
            for (var i = 1; i <= 5; i++)
            {
                $$('#rating_stars img')[i-1].set("src", off);
            }
        }
    },

    updateCredit: function()  {
        var credit = this.info.images[this.displayedImageIndex]['credit'];
        if (credit)
        {
            credit = "Photo by " + credit;
        }
        $('photog_credit').set("html", credit);
    },

    updateCaption: function()  {
        var caption = this.loadedImages[this.displayedImageIndex].get("alt");
        if (! this.captionsShowing)
        {
            $('image_caption').setStyle("display", "none");
            return;
        }
        else
        {
            $('image_caption').setStyle("display", "block");
            $('image_caption').setStyle("opacity", 0);
        }
        var leftMargin = (parseInt(this.options.leftColWidth) - this.loadedImages[this.displayedImageIndex].get("width")) / 2 + 10;
        var bottomMargin = (this.options.containerHeight - this.loadedImages[this.displayedImageIndex].get("height")) / 2 + 30;
        var width = this.loadedImages[this.displayedImageIndex].get("width") - 30;
        if (! caption)
        {
            $('image_caption').setStyle("opacity", 0);
        }
        else
        {
            $('image_caption').set("html", caption);
            $('image_caption').setStyles({
                left: leftMargin,
                bottom: bottomMargin,
                width: width
            });
            (function()  {
                $('image_caption').setStyle("opacity", 0.8);
            }).delay(this.transitionSpeed);
        }

    },

    toggleCaptions: function()  {
        if (this.captionsShowing)
        {
            $$('#captions_button img')[0].set("src", this.options.iconPath + "/captionshide_icon.png");
            this.captionsShowing = false;
        }
        else
        {
            $$('#captions_button img')[0].set("src", this.options.iconPath + "/captionsshow_icon.png");
            this.captionsShowing = true;
        }
        this.updateCaption();
    },

    magnifyImage: function()  {
        if (this.info.images[this.displayedImageIndex]['url'])
        {
            window.location.href = this.info.images[this.displayedImageIndex]['url'];
        }
    },

    startInterval: function()  {
        this.intervalId = setInterval(this.getNext, this.options.imageInterval);
    },

    getPrevious: function()  {
        var root = ig;
        myFx = new Fx.Tween(root.loadedImages[root.displayedImageIndex], { duration: root.transitionSpeed });
        myFx.start('opacity', 1, 0);
        root.displayedImageIndex--;
        if (root.displayedImageIndex < 0)
        {
            root.displayedImageIndex = root.loadedImages.length - 1;
        }

        myFx = new Fx.Tween(root.loadedImages[root.displayedImageIndex], { duration: root.transitionSpeed });
        myFx.start('opacity', 0, 1);
        var prev = root.displayedImageIndex - 1;
        if (prev < 0)
        {
            prev = root.loadedImages.length - 1;
        }
        root.preloadIndex(prev);
        root.updateCounter();
    },

    getNext: function()  {
        var root = ig;
        myFx = new Fx.Tween(root.loadedImages[root.displayedImageIndex], { duration: root.transitionSpeed });
        myFx.start('opacity', 1, 0);
        root.displayedImageIndex++;
        if (root.displayedImageIndex >= root.loadedImages.length)
        {
            root.displayedImageIndex = 0;
        }

        myFx = new Fx.Tween(root.loadedImages[root.displayedImageIndex], { duration: root.transitionSpeed });
        myFx.start('opacity', 0, 1);
        var next = root.displayedImageIndex + 1;
        if (next >= root.loadedImages.length)
        {
            next = 0;
        }
        root.preloadIndex(next);
        root.updateCounter();
    },

    drawControlPanel:  function()  {
        var cp = new Element("div", {
            id: "control_panel"
        });
        cp.setStyles({
            width: this.options.leftColWidth,
            height: "22px",
            background: "url(" + this.options.iconPath + "controlpanel_bg.gif)",
            position: "absolute",
            bottom: 0
        });

        // Play/pause button
        var div = new Element("div", {
            id: "playpause",
            "class": "button",
            html: "<img src='" + this.options.iconPath + "pause_button.png' alt='pause' title='pause' />"
        });
        div.setStyles({
            left: parseInt(this.options.leftColWidth) / 2,
            top: "3px"
        });
        var root = this;
        div.addEvent("click", function()  {
            if (root.intervalId)
            {
                clearInterval(root.intervalId);
                root.intervalId = null;
                $('playpause').set("html", "<img src='" + root.options.iconPath + "play_button.png' alt='play' title='play' />");
            }
            else
            {
                $('playpause').set("html", "<img src='" + root.options.iconPath + "pause_button.png' alt='play' title='play' />");
                root.startInterval();
                root.getNext();
            }
        });

        div.inject(cp);

        // Next button
        var div = new Element("div", {
            id: "next",
            "class": "button",
            html: "<img src='" + this.options.iconPath + "right_arrow.png' alt='next' title='next' />"
        });
        div.setStyles({
            left: parseInt(this.options.leftColWidth) / 2 + 22
        });
        div.addEvent("click", function()  {
            if (root.intervalId)
            {
                clearInterval(root.intervalId);
                root.intervalId = null;
                $('playpause').set("html", "<img src='" + root.options.iconPath + "play_button.png' alt='play' title='play' />");
            }
            root.getNext();
        });
        div.inject(cp);

        // Previous button
        var div = new Element("div", {
            id: "previous",
            "class": "button",
            html: "<img src='" + this.options.iconPath + "left_arrow.png' alt='previous' title='previous' />"
        });
        div.setStyles({
            left: parseInt(this.options.leftColWidth) / 2 - 16
        });
        div.addEvent("click", function()  {
            if (root.intervalId)
            {
                clearInterval(root.intervalId);
                root.intervalId = null;
                $('playpause').set("html", "<img src='" + root.options.iconPath + "play_button.png' alt='play' title='play' />");
            }
            root.getPrevious();
        });
        div.inject(cp);

        // Counter
        var div = new Element("div", {
            id: "slideshow_counter",
            html: "0 / 0"
        });
        div.setStyles({
            left: parseInt(this.options.leftColWidth) / 2 + 40
        });
        div.inject(cp);

        // Thumbnails button
        var div = new Element("div", {
            id: "thumbnails_button",
            "class": "button"
        });
        div.addEvent("click", function()  {
            root.toggleThumbnails();
        });
        div.set("html", "<img src='" + this.options.iconPath + "thumbnails_icon.png' alt='thumbnails' title='thumbnails' />");
        div.inject(cp);

        // Hide/show captions button
        div = new Element("div", {
            id: "captions_button",
            "class": "button"
        });
        div.addEvent("click", function()  {
            root.toggleCaptions();
        });
        div.set("html", "<img src='" + this.options.iconPath + "captionsshow_icon.png' alt='captions on/off' title='captions on/off' />");
        div.inject(cp);

        // Magnifying glass button
        div = new Element("div", {
            id: "magnifier_button",
            "class": "button"
        });
        div.addEvent("click", function()  {
            root.magnifyImage();
        });
        div.set("html", "<img src='" + this.options.iconPath + "viewimage_icon.png' alt='view current image' title='view current image' />");
        div.inject(cp);

        // Share image button
        div = new Element("div", {
            id: "share_image_button",
            "class": "button"
        });
        div.addEvent("click", function()  {
            root.shareImageDialog();
        });
        div.set("html", "<img src='" + this.options.iconPath + "shareimage_icon.png' alt='share current image' title='share current image' />");
        div.inject(cp);

        // Photog credit
        div = new Element("div", {
            id: "photog_credit"
        });
        div.inject(cp);

        // Rating
        div = new Element("div", {
            id: "rating_container"
        });

        var ratingText = new Element("div", {
            id: "rating_text",
            html: "Rate this image"
        });
        ratingText.setStyles({
            position: "relative",
            top: 0
        });
        ratingText.inject(div);

        var stars = new Element("div", {
            id: "rating_stars"
        });
        stars.setStyles({
            top: 0,
            right: 130
        });

        var src, over;
        if (this.options.version == 'standard')
        {
            src = this.options.iconPath + "/star_gray.png";
            over = this.options.iconPath + "/star_yellow.png";
        }
        else
        {
            src = this.options.iconPath + "/paw_gray.png";
            over = this.options.iconPath + "/paw_yellow.png";
        }

        for (var i = 1; i <= 5; i++)
        {
            var star = new Element("img", {
                src: src
            });
            star.rating = i;
            star.addEvent("click", function()  {
                if (root.info.images[root.displayedImageIndex]['rating_text'])
                {
                    return;
                }
                root.submitRating(this.rating);
            });
            star.addEvent("mouseenter", function()  {
                if (root.info.images[root.displayedImageIndex]['rating_text'])
                {
                    return;
                }
                var prev = this.getAllPrevious();
                prev.each(function(item)  {
                    item.set("src", over);
                });
                this.set("src", over);
            });
            star.addEvent("mouseleave", function()  {
                if (root.info.images[root.displayedImageIndex]['rating_text'])
                {
                    return;
                }
                var prev = this.getAllPrevious();
                prev.each(function(item)  {
                    item.set("src", src);
                });
                this.set("src", src);
            });
            star.setStyle("padding-right", 5);
            star.inject(stars);
        }

        if (! this.options.ratingOpen)
        {
            div.setStyle("display", "none");
        }

        stars.inject(div);
        div.inject(cp);

        cp.inject($('slideshow_container'));
    },

    submitRating: function(rating)  {
        var root = this;
        var req = new Request({
            url: "/apps/rate_asset/rate_asset/",
            method: "get",
            data: {
                "return_version": "ratingsxml",
                "rate_asset": 1,
                "rating": rating,
                "rate_id_asset": this.info.images[this.displayedImageIndex]['id_asset']
            },
            onSuccess: function(theText, theXML)  {
                if (! theXML)
                {
                    return;
                }

                var newRating = theXML.getElementsByTagName("new_rating").item(0).childNodes[0].nodeValue;
                var numVotes = theXML.getElementsByTagName("num_votes").item(0).childNodes[0].nodeValue;

                var votes = (numVotes > 1)
                    ? " votes"
                    : " vote";
                var stars = (newRating > 1)
                    ? " stars"
                    : " star"
                $("rating_text").setStyle("text-transform", "none");
                var ratingText = newRating + stars + " / " + numVotes + votes;
                $("rating_text").set("html", ratingText);
                root.info.images[root.displayedImageIndex]['rating_text'] = ratingText;
                root.info.images[root.displayedImageIndex]['my_rating'] = rating;
            }
        });
        req.send();
    },

    shareImageDialog: function()  {
        // stop rotating images
        if (this.intervalId)
        {
            clearInterval(this.intervalId);
            this.intervalId = null;
            $$('#playpause img')[0].set("src", this.options.iconPath + "/play_button.png");
            $$('#playpause img')[0].set("alt", "play");
            $$('#playpause img')[0].set("title", "play");
        }

        var div = new Element("div", {
            id: "share_image_dialog"
        });
        var html = 'Share this image:<br /><img src="' + this.info.images[this.displayedImageIndex]['tn'] + '" />';
        var shareHTML = this.options.shareHTML;
        var id_asset = this.info.images[this.displayedImageIndex]['id_asset'];
        var title = encodeURI(this.info['Title'] + " :: " + this.info.images[this.displayedImageIndex]['headline']);
        shareHTML = shareHTML.replace(/(<a\s+href=.*?)(url=.*?)(&amp;title=.*?)(&amp;.*?<\/a>)/g, "$1$2?image_id=" + id_asset + "&amp;title=" + title + "$4");
        shareHTML = shareHTML.replace(/(<a\s+href="\/rs\/page\/5019568\/\?id_asset_to_email=)\d+(".*?<\/a>)/, "$1" + id_asset + "$2");
        html += '<br /><br />' + shareHTML;
        div.set("html", html);

        div.setStyles({
            left: parseInt(this.options.leftColWidth) / 2 - 80,
            top: parseInt(this.options.containerHeight) / 2 - 75
        });
        div.inject($("slideshow_container"));

        var closeButtonDiv = new Element("div", {
            id: "share_close_button",
            html: "<img src='" + this.options.iconPath + "close_button.png' width='17' height='15' alt='close' />"
        });
        closeButtonDiv.addEvent("click", function()  {
            div.dispose();
        });

        closeButtonDiv.inject(div);

        var myFx = new Fx.Tween(div, { duration: 1000 });
        myFx.start("opacity", 0, 0.9);
    },

    toggleThumbnails: function()  {
        if ($('thumbnails_pane') == undefined)
        {
            var thumbnailsPane = new Element("div", {
                id: "thumbnails_pane"
            });

            thumbnailsPane.setStyles({
                top: this.options.containerHeight,
                height: this.options.containerHeight - parseInt($('control_panel').getStyle("height")) - 25,
                width: parseInt(this.options.leftColWidth) - 80
            });
            this.buildThumbnails(thumbnailsPane);
            thumbnailsPane.inject($('slideshow_container'));
        }

        var myFx = new Fx.Tween($("thumbnails_pane"), { duration: 500 });
        if (this.thumbnailsShowing)
        {
            myFx.start("top", this.options.containerHeight + parseInt($('control_panel').getStyle("height")));
            this.thumbnailsShowing = false;
        }
        else
        {
            myFx.start("top", this.options.containerHeight, 0);
            this.thumbnailsShowing = true;
        }
    },


    buildThumbnails: function(thumbnailPane)
    {
        var root = this;
        var div = new Element("div",  {
            "class": "wrapper"
        });

        var i = 0;
        while (i < this.info.images.length)
        {
            var rowContainer;
            if (i % 5 == 0)
            {
                rowContainer = new Element("div",  {
                    "class": "rowContainer"
                });
                rowContainer.setStyles({
                    width: "590px",
                    float: "none"
                });
            }

            var container = new Element("div");
            var img = new Element("img", {
                src: this.info.images[i]["tn"]
            })
            var marginTop = (75 - this.info.images[i]["tn_height"]) / 2;
            var marginLeft = (100 - this.info.images[i]["tn_width"]) / 2;
            img.setStyles({
                "margin-top": marginTop,
                "margin-left": marginLeft
            });
            img.ssidx = i;
            img.addEvent("click", function()  {
                root.showIndex(this.ssidx);
            });
            img.inject(container);
            container.inject(rowContainer);

            if (i % 5 == 4)
            {
                rowContainer.inject(div);
            }
            i++;
        }
        if (i % 5 != 4)
        {
            rowContainer.inject(div);
        }

        div.inject(thumbnailPane);

        div = new Element("div",  {
            id: "thumbnails_close_button",
            html: "<img src='" + this.options.iconPath + "close_button.png' width='17' height='15' alt='close' />"
        });
        div.addEvent("click", function()  {
            root.toggleThumbnails();
        });
        div.inject(thumbnailPane);
    }
});



