﻿
/**
* Initialize Spyder SlideShow
*/

// Used only by the picture viewer
var NURUN = {
    globals: {
        labels: {}
    },
    pages: {
        share: {}
    },
    widgets: {},
    util: {}
}

NURUN.pages.share.init = function() {

    // Initialize main gallery
    NURUN.globals.mainGallery = new NURUN.widgets.Gallery(
		"gallery",
		{
		    initialPageIndex: InitialPageIndex,
		    viewportHeight: 370,
		    scrollBy: 460,
		    rating: true,
		    comments: true,
		    commentLabels: {
		        header: SPYDERYUI.globals.labels.comments,
		        postComment: SPYDERYUI.globals.labels.postYourComment,
		        noComments: SPYDERYUI.globals.labels.noComments1,
		        writtenBy: SPYDERYUI.globals.labels.writtenBy
		    },
		    sortBy: InitialSort
		}
    );
    // Wire up Send to a Friend panel's show/hide button *Home page*
    var btn = document.getElementById("send-to-friend");

    if (btn) {

        anchor = btn.getElementsByTagName("a")[0];
        anchor.onclick = function(galleryEl) {
            return function() {
                var photoWrapper = YAHOO.util.Dom.getElementsByClassName("photo-wrapper", "div", galleryEl);
                if (photoWrapper.length > 0) {
                    var img = photoWrapper[0].getElementsByTagName("img")[0];
                    if (img) {
                        var GUID = img.src.split("?")[1].split("&")[0].split("=")[1]; // assumes MediaID is first param in querystring
                        if (GUID) {
                            var content = "<iframe width='915' marginwidth='0' marginheight='0' scrolling='no' frameborder='0' height='390' src='" + this.href + "?MediaID=" + GUID + "'></iframe>";
                            var pnl = SPYDERYUI.globals.modalPopup;
                            pnl.setBody(content);
                            pnl.render(document.body);
                            pnl.show();
                        }
                    }
                }
                return false;
            }
        } (NURUN.globals.mainGallery.galleryEl);
    }


    // Wire up download this picture
    btn = document.getElementById("liDownload");

    if (btn) {
        anchor = btn.getElementsByTagName("a")[0];
        anchor.onclick = function(galleryEl) {
            return function() {
                var photoWrapper = YAHOO.util.Dom.getElementsByClassName("photo-wrapper", "div", galleryEl);
                if (photoWrapper.length > 0) {
                    var img = photoWrapper[0].getElementsByTagName("img")[0];
                    if (img) {
                        var GUID = img.src.split("?")[1].split("&")[0].split("=")[1]; // assumes MediaID is first param in querystring

                        if (GUID) {
                            this.href = this.href.replace(/MediaID=.*/, 'MediaID=' + GUID);
                            downloadTracker._trackEvent('Pics');
                        }
                    }
                }
            }
        } (NURUN.globals.mainGallery.galleryEl);
    }

    // Wire up locate this picture
    var locateThisRyder = document.getElementById("locateRyder");

    if (locateThisRyder) {
        anchor = locateThisRyder.getElementsByTagName("a")[0];
        anchor.onclick = function(galleryEl) {
            return function() {
                var photoWrapper = YAHOO.util.Dom.getElementsByClassName("photo-wrapper", "div", galleryEl);
                if (photoWrapper.length > 0) {
                    var img = photoWrapper[0].getElementsByTagName("img")[0];
                    if (img) {
                        var GUID = img.src.split("?")[1].split("&")[0].split("=")[1]; // assumes MediaID is first param in querystring

                        if (GUID) {
                            this.href = this.href.replace(/MediaID=.*/, 'MediaID=' + GUID);
                        }
                    }
                }
            }
        } (NURUN.globals.mainGallery.galleryEl);
    }

    // Wire up share this photo
    var btn = document.getElementById("share-photo");

    if (btn) {
        anchor = btn.getElementsByTagName("a")[0];
        anchor.onclick = function(galleryEl) {
            return function() {
                var photoWrapper = YAHOO.util.Dom.getElementsByClassName("photo-wrapper", "div", galleryEl);
                if (photoWrapper.length > 0) {
                    var img = photoWrapper[0].getElementsByTagName("img")[0];
                    if (img) {
                        var GUID = img.src.split("?")[1].split("&")[0].split("=")[1]; // assumes MediaID is first param in querystring
                        if (GUID) {

                            var content = "<iframe width='668' marginwidth='0' marginheight='0' scrolling='no' frameborder='0' height='368' src='" + this.href + "?MediaID=" + GUID + "'></iframe>";
                            var pnl = SPYDERYUI.globals.tabPanel;
                            pnl.setBody(content);
                            pnl.render(document.body);
                            pnl.show();
                        }
                    }
                }
                return false;
            }
        } (NURUN.globals.mainGallery.galleryEl);
    }

    // Initialize Ryders' Reviews
    var threshold = 125;
    var reviews = YAHOO.util.Dom.getElementsByClassName("review", "li", "ryders_reviews");
    for (var i = 0; reviews[i]; i++) {
        YAHOO.util.Dom.addClass(reviews[i], "partial");

        var p = reviews[i].getElementsByTagName("p")[0];
        if (p) {
            var txt = p.innerText || p.textContent;
            if (txt.length > threshold) {
                var snippet = document.createElement("span");
                var snippetTxt = txt.substring(0,
					(txt.substring(threshold, threshold + 1) == " ") ?
						threshold :
						threshold + txt.substring(threshold, threshold + txt.length).indexOf(" ")
				);
                snippet.appendChild(document.createTextNode(snippetTxt));

                var ellipsis = document.createElement("span");
                ellipsis.className = "ellipsis";
                ellipsis.innerHTML = "&nbsp;&hellip;";

                var more = document.createElement("span");
                more.className = "more";
                var moreTxt = txt.substring(snippetTxt.length, txt.length);
                more.appendChild(document.createTextNode(moreTxt));

                p.innerHTML = "";
                p.appendChild(snippet);
                p.appendChild(ellipsis);
                p.appendChild(more);
            }
        }
        reviews[i].onclick = function(reviews) {
            return function() {
                if (YAHOO.util.Dom.hasClass(this, "full")) {
                    YAHOO.util.Dom.replaceClass(this, "full", "partial");
                } else {
                    YAHOO.util.Dom.replaceClass(this, "partial", "full");
                }

                for (var i = 0; reviews[i]; i++) {
                    if (reviews[i] != this) {
                        if (YAHOO.util.Dom.hasClass(this, "full")) {
                            YAHOO.util.Dom.replaceClass(reviews[i], "partial", "hidden");
                        } else {
                            YAHOO.util.Dom.replaceClass(reviews[i], "hidden", "partial");
                        }
                    }
                }
            }
        } (reviews);
        reviews[i].style.visibility = "visible"; // Initially hidden in initial-states.css
    }


    // Wire up the rating submit button
    var submitLi = document.getElementById("btnsubmit");
    if (submitLi) {
        var submitBtn = submitLi.getElementsByTagName("a")[0];
        if (submitBtn) {
            submitBtn.onclick = function() {

                if (SPYDERYUI.globals.IsAuthenticated) {
                    // Get GUID of photo
                    var photoWrapper = YAHOO.util.Dom.getElementsByClassName("photo-wrapper", "div", NURUN.globals.mainGallery.galleryEl);
                    if (photoWrapper.length > 0) {
                        var img = photoWrapper[0].getElementsByTagName("img")[0];
                        if (img) {
                            var GUID = img.src.split("?")[1].split("&")[0].split("=")[1]; // assumes MediaID is first param in querystring
                            if (GUID) {
                                NURUN.globals.mainGallery.ratingsWidget.submit(GUID);
                                NURUN.globals.mainGallery.toggleRating.call();
                            }
                        }
                    }
                }
                else {
                    var link = SPYDERYUI.globals.SignInUrl + "?ForceClose=1";
                    SPYDERYUI.globals.signInPopup.setBody("<iframe width='668' marginwidth='0' marginheight='0' scrolling='no' frameborder='0' height='368' src='" + link + "'></iframe>");
                    SPYDERYUI.globals.signInPopup.render();
                    SPYDERYUI.globals.signInPopup.show();
                }

                return false;
            }
        }
    }

    var btnSubmitComment = document.getElementById("lnkSubmitComment");
    if (btnSubmitComment) {
        btnSubmitComment.onclick = function() {
            // Get GUID of photo
            var photoWrapper = YAHOO.util.Dom.getElementsByClassName("photo-wrapper", "div", NURUN.globals.mainGallery.galleryEl);
            if (photoWrapper.length > 0) {
                var img = photoWrapper[0].getElementsByTagName("img")[0];
                if (img) {
                    var GUID = img.src.split("?")[1].split("&")[0].split("=")[1]; // assumes MediaID is first param in querystring
                    if (GUID) {
                        NURUN.globals.mainGallery.commentsWidget.submit(GUID);
                    }
                }
            }
        }
    }


    // Initialize small slideshow
    NURUN.globals.slideShow = new NURUN.widgets.Slideshow("slides", "slide-controls", { timer: 5000 });
};

/**
* Creates an image gallery widget based on markup
* 
* @constructor
* @param {String|HTMLElement} id The element representing the gallery
* @param {Object} config An object literal with override config values
* @requires YAHOO.util.Dom Required for extended/normalized DOM manipulation
*/
NURUN.widgets.Gallery = function(id, config) {
    if (typeof id == "undefined") return false;
    if (typeof config == "undefined") config = {};

    this.galleryEl = YAHOO.util.Dom.get(id);

    if (this.galleryEl) {

        // Set config defaults
        this.config = {
            scroll: "horizontal",
            thumbsScrollerClassName: "scroller",
            thumbsViewportClassName: "viewport",
            thumbsClassName: "thumbs",
            thumbsTagName: "ul",
            prevImageClassName: "prevImage",
            prevImageText: "Previous image",
            prevClassName: "prev",
            prevText: "Previous",
            nextImageText: "Next image",
            nextImageClassName: "nextImage",
            nextClassName: "next",
            nextText: "Next",
            dataset: [],
            skipBy: 5,
            initialPageIndex: 1,
            rating: false,
            comments: false,
            commentsClassName: "comments",
            commentLabels: {
                header: SPYDERYUI.globals.labels.comments,
                postComment: SPYDERYUI.globals.labels.postYourComment,
                noComments: SPYDERYUI.globals.labels.noComments1,
                writtenBy: SPYDERYUI.globals.labels.writtenBy
            },
            ratingsElId: this.galleryEl.id + "-rating",
            leaveCommentsElId: this.galleryEl.id + "-leaveComments",
            viewportHeight: null,
            viewportWidth: null,
            scrollBy: null,
            sortBy: null
        };
    }
    else {
        return false;
    }


    // Override config defaults
    for (var item in config) {
        this.config[item] = config[item];
    }

    // Get all gallery related fields for future reference
    this.fields = {};

    var ratingInfo = YAHOO.util.Dom.getElementsByClassName("ratings", "div", this.galleryEl);
    ratingInfo = (ratingInfo.length > 0) ? ratingInfo[0] : undefined;

    var photo = YAHOO.util.Dom.getElementsByClassName("photo", "img", this.galleryEl);
    this.fields.photo = (photo.length > 0) ? photo[0] : undefined;
    var photoPanel = YAHOO.util.Dom.getElementsByClassName("photo-panel", "a", this.galleryEl);
    this.fields.photoPanel = (photoPanel.length > 0) ? photoPanel[0] : undefined;
    var photoInfo = YAHOO.util.Dom.getElementsByClassName("photo-info", "div", this.galleryEl);
    photoInfo = (photoInfo.length > 0) ? photoInfo[0] : undefined;
    var author = YAHOO.util.Dom.getElementsByClassName("author", "li", photoInfo);
    this.fields.author = (author.length > 0) ? author[0] : undefined;
    var city = YAHOO.util.Dom.getElementsByClassName("city", "li", photoInfo);
    this.fields.city = (city.length > 0) ? city[0] : undefined;
    var role = YAHOO.util.Dom.getElementsByClassName("role", "li", photoInfo);
    this.fields.role = (role.length > 0) ? role[0] : undefined;
    var title = YAHOO.util.Dom.getElementsByClassName("title", "li", photoInfo);
    this.fields.title = (title.length > 0) ? title[0] : undefined;
    var rating = YAHOO.util.Dom.getElementsByClassName("rating", "li", ratingInfo);
    this.fields.rating = (rating.length > 0) ? rating[0] : undefined;
    var stats = YAHOO.util.Dom.getElementsByClassName("stats", "li", ratingInfo);
    this.fields.stats = (stats.length > 0) ? stats[0] : undefined;
    var photoOptions = YAHOO.util.Dom.getElementsByClassName("photo-options", "ul", this.galleryEl);
    photoOptions = (photoOptions.length > 0) ? photoOptions[0] : undefined;
    var send = YAHOO.util.Dom.getElementsByClassName("send", "li", photoOptions);
    this.fields.send = (send.length > 0) ? send[0] : undefined;
    var rate = YAHOO.util.Dom.getElementsByClassName("rate", "li", photoOptions);
    this.fields.rate = (rate.length > 0) ? rate[0] : undefined;
    var galleryOptions = YAHOO.util.Dom.getElementsByClassName("gallery-options", "ul", this.galleryEl);
    galleryOptions = (galleryOptions.length > 0) ? galleryOptions[0] : undefined;
    var more = YAHOO.util.Dom.getElementsByClassName("more", "li", galleryOptions);
    this.fields.more = (more.length > 0) ? more[0] : undefined;
    var post = YAHOO.util.Dom.getElementsByClassName("post", "li", galleryOptions);
    this.fields.post = (post.length > 0) ? post[0] : undefined;
    
    // Grab first occurrence of .thumbs element
    this.thumbsEl = YAHOO.util.Dom.getElementsByClassName(
        this.config.thumbsClassName,
        this.config.thumbsTagName,
        this.galleryEl
    )[0];

    // Set up "done getting" event for "getMore" method
    this.doneGettingPrev = new YAHOO.util.CustomEvent("doneGettingPrev", this);
    this.doneGettingPrev.subscribe(this.animatePrev);
    this.doneGettingNext = new YAHOO.util.CustomEvent("doneGettingNext", this);
    this.doneGettingNext.subscribe(this.animateNext);

    // Initialize Gallery
    this.init();
}



/**
* Initializes the Gallery widget
* @requires YAHOO.util.Scroll Required for thumbnail scroll animation
*/
NURUN.widgets.Gallery.prototype.init = function() {
    /**
    * Create a master scroller wrapper for the whole thumbs scroller.
    * 
    * Create a viewport wrapper to place the thumbs list in which will serve
    *   as an overflow container for extra thumbnails.
    * 
    * Make sure to pass reset the thumbsEl DOM reference when moving it inside 
    *   the viewport by reassigning the value appendChild returns back to the
    *   thumbsEl variable.
    */
    this.scrollerEl = document.createElement("div");
    this.scrollerEl.className = this.config.thumbsScrollerClassName + " " + this.config.scroll;

    this.viewportEl = document.createElement("div");
    this.viewportEl.className = this.config.thumbsViewportClassName;
    this.viewportEl.style.position = "relative";
    this.viewportEl.style.overflow = "hidden";

    this.scrollerEl.appendChild(this.viewportEl);
    YAHOO.util.Dom.insertBefore(this.scrollerEl, this.thumbsEl);
    this.thumbsEl = this.viewportEl.appendChild(this.thumbsEl);
    //this.thumbsEl.style.position = "absolute";

    // Get all thumb items
    this.thumbItems = YAHOO.util.Dom.getChildren(this.thumbsEl);
    //this.thumbsPointer = this.config.initialPageIndex * this.config.skipBy; // the pointer in the thumbnail set array
    this.thumbsPointer = this.thumbItems.length;
    this.currentPageIndex = this.config.initialPageIndex;


    /**
    * Calculate thumbnail container width based on thumbnail elements' widths
    *  for horizontal scrolling
    */
    if (this.config.scroll == "horizontal") {
        var thumbsElWidth = 0;
        var tmp = 0;
        for (var i = 0; this.thumbItems[i]; i++) {
            tmp = parseFloat(YAHOO.util.Dom.getStyle(this.thumbItems[i], "width"));
            thumbsElWidth += (!isNaN(tmp)) ? tmp : 0;

            tmp = parseFloat(YAHOO.util.Dom.getStyle(this.thumbItems[i], "margin-right"));
            thumbsElWidth += (!isNaN(tmp)) ? tmp : 0;

            tmp = parseFloat(YAHOO.util.Dom.getStyle(this.thumbItems[i], "border-left-width"));
            thumbsElWidth += (!isNaN(tmp)) ? tmp : 0;

            tmp = parseFloat(YAHOO.util.Dom.getStyle(this.thumbItems[i], "border-right-width"));
            thumbsElWidth += (!isNaN(tmp)) ? tmp : 0;
        }
        this.thumbsEl.style.width = thumbsElWidth + "px";
    } else if (this.config.scroll == "vertical") {

        /**
        * Get the height and margins of the thumbnails container in order to
        *   get an accurate calculation of the viewport's height
        */

        if (this.config.viewportHeight === null) {
            var viewportHeight = parseFloat(YAHOO.util.Dom.getStyle(this.thumbsEl, "height"));
            viewportHeight += parseFloat(YAHOO.util.Dom.getStyle(this.thumbsEl, "margin-top"));
            viewportHeight += parseFloat(YAHOO.util.Dom.getStyle(this.thumbsEl, "margin-bottom"));
        } else {
            var viewportHeight = this.config.viewportHeight;
        }
        this.viewportEl.style.height = viewportHeight + "px";
        this.viewportEl.style.overflow = "hidden";
    }

    /**
    * Populate config.dataset with in-page thumbnail data
    */
    var initialPushIndex = (this.config.initialPageIndex - 1) * this.config.skipBy;
    this.config.dataset.length = initialPushIndex + this.thumbItems.length;


    if (this.thumbItems.length < this.config.skipBy) {
        this.lastPageIndex = this.config.initialPageIndex;
        //next.style.visibility = "hidden";
    }

    for (var i = 0; this.thumbItems[i]; i++) {
        var item = this.thumbItems[i];
        var anchor = item.getElementsByTagName("a")[0];

        var img = item.getElementsByTagName("img")[0];
        var content = YAHOO.util.Dom.getElementsByClassName("content", "div", item)[0];
        var meta = YAHOO.util.Dom.getElementsByClassName("meta", "ul", item)[0];
        if (meta) {
            var author = YAHOO.util.Dom.getElementsByClassName("author", "li", meta)[0];
            var city = YAHOO.util.Dom.getElementsByClassName("city", "li", meta)[0];
            var role = YAHOO.util.Dom.getElementsByClassName("role", "li", meta)[0];
            var rating = YAHOO.util.Dom.getElementsByClassName("rating", "li", meta)[0];
            var stats = YAHOO.util.Dom.getElementsByClassName("stats", "li", meta)[0];
            if (stats) {
                var ratings = YAHOO.util.Dom.getElementsByClassName("ratings", "span", stats)[0];
                var views = YAHOO.util.Dom.getElementsByClassName("views", "span", stats)[0];
            }
        }
        this.config.dataset[initialPushIndex + i] =
            {
                'ID': (item && item.id) ? item.id.substring(3) : "",
                'Type': 1,
                'ThumbUrl': (img) ? img.src : "",
                'MediumUrl': (anchor) ? anchor.href : "",
                'Title': (anchor) ? anchor.title : "",
                'Content': (content) ? content.innerHTML : "",
                'VideoStreamingID': '',
                'VideoProgUrl': '',
                'Author': (author) ? author.innerHTML : "",
                'City': (city) ? city.innerHTML : "",
                'Role': (role) ? role.innerHTML : "",
                'Rating': (rating) ? rating.innerHTML : "",
                'Ratings': (ratings) ? ratings.innerHTML : "",
                'Views': (views) ? views.innerHTML : ""
            };
        this.bindThumbnail(anchor, initialPushIndex + i);
    }

    //Set the first panel href
    this.fields.photoPanel.href = this.fields.photo.src.replace(/PictureViewer/, "PictureViewerPanel");
    /**
    * Create previous and next buttons for thumbnail scroll.
    * 
    * The YUI scroll object is created once (for speed purposes) and passed
    *   as a reference to the onclick event handlers who simply update the
    *   coordinates and call the animate method.
    * 
    * Using anchors makes it accessible as you can tab to them and press enter
    *   to activate the onclick event.
    */

    this.scrollAnim = new YAHOO.util.Scroll(this.viewportEl, null, 1, YAHOO.util.Easing.easeBoth);

    /**
    * Previous
    */
    var prev = document.createElement("a");
    prev.href = "#";
    prev.className = this.config.prevClassName;
    prev.appendChild(document.createTextNode(this.config.prevText));


    if (this.currentPageIndex === 1) {
        prev.style.visibility = "hidden";
    }
    prev.onclick = function(that) {
        return function() {
            next.style.visibility = "visible";
            nextImage.style.visibility = "visible";
            if (that.scrollAnim.isAnimated()) return false;

            if (that.config.dataset[((that.currentPageIndex - 2) * that.config.skipBy)]) {
                that.animatePrev();
                that.thumbsPointer -= that.config.skipBy;
                that.currentPageIndex--;
                var prevItemAnchor = that.thumbItems[that.thumbsPointer - 1].getElementsByTagName("a")[0];
                prevItemAnchor.onclick();

                if (that.currentPageIndex === 1) {
                    prev.style.visibility = "hidden";
                }
            } else {
                that.getMore(that, (that.currentPageIndex - 1), false);
            }

            return false;
        }
    } (this);

    YAHOO.util.Dom.insertBefore(prev, this.viewportEl);

    /**
    * Previous Single Image
    */
    var prevImage = document.createElement("a");
    prevImage.href = "#";
    prevImage.className = this.config.prevImageClassName;
    prevImage.appendChild(document.createTextNode(this.config.prevImageText));

    var selected = YAHOO.util.Dom.getElementsByClassName("img-selected", "a");
    img = selected[0].getElementsByTagName("img")[0];
    var GUID = img.src.split("?")[1].split("&")[0].split("=")[1];

    if (this.thumbItems[0].id === "img" + GUID && this.currentPageIndex === 1) {
        prevImage.style.visibility = "hidden";
    }
    prevImage.onclick = function(that) {
        return function() {
            var selected = YAHOO.util.Dom.getElementsByClassName("img-selected", "a");
            img = selected[0].getElementsByTagName("img")[0];

            /* Verify if selected MediaID is the same as the first thumbnail, then switch to previous slide */
            if (img) {

                nextImage.style.visibility = "visible";

                if (that.scrollAnim.isAnimated()) return false;

                var GUID = img.src.split("?")[1].split("&")[0].split("=")[1];

                var datasetIndex = 0;
                for (i in that.config.dataset) {
                    if (that.config.dataset[i].ID === GUID) {
                        datasetIndex = i;
                    }
                }

                /* Verify if selected MediaID is the same as the first thumbnail, then switch to next slide */
                if (parseInt(datasetIndex, 10) % that.config.skipBy === 0) {
                    if (that.scrollAnim.isAnimated()) return false;

                    if (that.config.dataset[((that.currentPageIndex - 1) * that.config.skipBy) - 1]) {
                        that.animatePrev();
                        that.thumbsPointer -= that.config.skipBy;
                        that.currentPageIndex--;
                        next.style.visibility = "visible";

                        // Set image to first in the slideshow
                        var currentSelectedItem = YAHOO.util.Dom.getAncestorByTagName(selected[0], "li");
                        var prevItem = YAHOO.util.Dom.getPreviousSibling(currentSelectedItem);
                        var prevItemAnchor = prevItem.getElementsByTagName("a")[0];
                        prevItemAnchor.onclick();

                    } else {
                        if (that.currentPageIndex > 1) {
                            that.getMore(that, (that.currentPageIndex - 1), false);
                        }
                    }
                    return false;
                }
                /* Only skip to other image*/
                else {
                    // Set image to previous in the slideshow
                    var currentSelectedItem = YAHOO.util.Dom.getAncestorByTagName(selected[0], "li");
                    var prevItem = YAHOO.util.Dom.getPreviousSibling(currentSelectedItem);
                    var prevItemAnchor = prevItem.getElementsByTagName("a")[0];
                    prevItemAnchor.onclick();
                }

                if (that.config.dataset[0] && ("img" + that.config.dataset[0].ID === prevItem.id)) {
                    prevImage.style.visibility = "hidden";
                }
                else {
                    prevImage.style.visibility = "visible";
                }

                if (that.currentPageIndex === 1) {
                    prev.style.visibility = "hidden";
                }
                return false;
            }
        }
    } (this);
    YAHOO.util.Dom.insertBefore(prevImage, this.viewportEl);



    /**
    * Next
    */
    var next = document.createElement("a");
    next.href = "#";
    next.className = this.config.nextClassName;
    next.appendChild(document.createTextNode(this.config.nextText));
    next.style.visibility = "visible";

    if (this.thumbsPointer < this.config.skipBy) {
        next.style.visibility = "hidden";
    }

    next.onclick = function(that) {
        return function() {
            prev.style.visibility = "visible";
            prevImage.style.visibility = "visible";
            if (that.scrollAnim.isAnimated()) return false;
            if (that.config.dataset[that.currentPageIndex * that.config.skipBy]) {
                that.animateNext();
                that.thumbsPointer += that.config.skipBy;
                that.currentPageIndex++;
                var nextItemAnchor = that.thumbItems[that.thumbsPointer - that.config.skipBy].getElementsByTagName("a")[0];
                nextItemAnchor.onclick();

                if (that.lastPageIndex === that.currentPageIndex) {
                    next.style.visibility = "hidden";

                    if (that.config.dataset.length === (that.currentPageIndex - 1) * that.config.skipBy + 1) {
                        nextImage.style.visibility = "hidden";
                    }
                }

            } else {
                that.getMore(that, (that.currentPageIndex + 1), true);
            }
            return false;
        }
    } (this);
    YAHOO.util.Dom.insertAfter(next, this.viewportEl);

    /**
    * Next Single Image
    */
    var nextImage = document.createElement("a");
    nextImage.href = "#";
    nextImage.className = this.config.nextImageClassName;
    nextImage.appendChild(document.createTextNode(this.config.nextImageText));


    var selected = YAHOO.util.Dom.getElementsByClassName("img-selected", "a");
    img = selected[0].getElementsByTagName("img")[0];
    var GUID = img.src.split("?")[1].split("&")[0].split("=")[1];

    if (this.config.dataset[this.config.dataset.length - 1].ID === GUID && this.currentPageIndex === this.lastPageIndex) {
        nextImage.style.visibility = "hidden";
    }

    nextImage.onclick = function(that) {
        return function() {
            var selected = YAHOO.util.Dom.getElementsByClassName("img-selected", "a");
            img = selected[0].getElementsByTagName("img")[0];


            if (img) {
                var GUID = img.src.split("?")[1].split("&")[0].split("=")[1];


                var datasetIndex = 0;
                for (i in that.config.dataset) {
                    if (that.config.dataset[i].ID === GUID) {
                        datasetIndex = i;
                    }
                }


                var lastItemId = that.thumbItems[that.thumbItems.length - 1].id.substring(3);

                prevImage.style.visibility = "visible";

                /* Verify if selected MediaID is the same as the last thumbnail, then switch to next slide */
                if ((parseInt(datasetIndex, 10) + 1) % that.config.skipBy == 0) {
                    if (that.scrollAnim.isAnimated()) return false;

                    prev.style.visibility = "visible";
                    if (that.config.dataset[that.currentPageIndex * that.config.skipBy]) {
                        that.animateNext();
                        that.thumbsPointer += that.config.skipBy;
                        that.currentPageIndex++;

                        if (that.lastPageIndex === that.currentPageIndex) {
                            next.style.visibility = "hidden";

                            if (parseInt(datasetIndex, 10) === that.config.dataset.length - 2) {
                                nextImage.style.visibility = "hidden";
                            }
                        }

                        // Set image to first in the slideshow
                        var currentSelectedItem = YAHOO.util.Dom.getAncestorByTagName(selected[0], "li");
                        var nextItem = YAHOO.util.Dom.getNextSibling(currentSelectedItem);
                        var nextItemAnchor = nextItem.getElementsByTagName("a")[0];
                        nextItemAnchor.onclick();

                    } else {
                        that.getMore(that, (that.currentPageIndex + 1), true); // animates 'next' when done getting
                    }
                    return false;
                }
                /* Only skip to other image*/
                else {
                    // Set image to first in the slideshow
                    var currentSelectedItem = YAHOO.util.Dom.getAncestorByTagName(selected[0], "li");
                    var nextItem = YAHOO.util.Dom.getNextSibling(currentSelectedItem);
                    var nextItemAnchor = nextItem.getElementsByTagName("a")[0];
                    nextItemAnchor.onclick();
                }
            }
        }
    } (this);
    YAHOO.util.Dom.insertBefore(nextImage, next);



    // Create and insert "loading" div
    this.loadingEl = document.createElement("div");
    this.loadingEl.className = "loading";
    this.loadingEl.style.position = "absolute";
    this.loadingEl.style.left = "-3000px";
    var viewportZindex = YAHOO.util.Dom.getStyle(this.viewportEl, "z-index");
    this.loadingEl.style.zIndex = 1 + ((viewportZindex == "auto") ? 0 : viewportZindex);
    this.loadingEl.style.width = this.viewportEl.offsetWidth + "px";
    this.loadingEl.style.height = this.viewportEl.offsetHeight + "px";
    YAHOO.util.Dom.insertAfter(this.loadingEl, prev);
    this.loadingEl.style.visibility = "hidden";
    YAHOO.util.Dom.setXY(this.loadingEl, YAHOO.util.Dom.getXY(this.viewportEl));
    this.loadingEl.style.display = "none";
    this.loadingEl.style.visibility = "visible";

    // Re-activate visibility
    this.scrollerEl.parentNode.style.visibility = "visible";


    // Initialize Comments Block
    if (this.config.comments === true) {
        var commentsWrapper = document.createElement("div");
        commentsWrapper.className = this.config.commentsClassName + "-wrapper";

        //var commentsHeader = document.createElement("h2");
        //commentsHeader.appendChild(document.createTextNode(SPYDERYUI.globals.labels.comments));

        var commentsContent = document.createElement("div");
        commentsContent.className = this.config.commentsClassName + "-content";

        var commentsFooter = document.createElement("div");
        commentsFooter.className = this.config.commentsClassName + "-footer";

        var commentsEl = document.createElement("ul");
        commentsEl.className = this.config.commentsClassName;

        //commentsWrapper.appendChild(commentsHeader);
        commentsContent.appendChild(commentsEl);
        commentsWrapper.appendChild(commentsContent);
        commentsWrapper.appendChild(commentsFooter);

        var gallerybottom = document.getElementById("add-title");
        YAHOO.util.Dom.insertBefore(commentsWrapper, gallerybottom);
        //gallerybottom.appendChild(commentsWrapper);

        this.commentsEl = commentsEl; // Store for later updating

        //Fix to load the comment 
        var selected = YAHOO.util.Dom.getElementsByClassName("img-selected", "a");
        var img = selected[0].getElementsByTagName("img")[0];
        if (img) {
            var GUID = img.src.split("?")[1].split("&")[0].split("=")[1];
            var pIndex = this.getDatasetPushIndexByID(GUID);
            if (pIndex > 0)
                initialPushIndex = pIndex;
        }


        // Populate first comment
        this.getComments(this, this.config.dataset[initialPushIndex]);

        // Define widget
        this.commentsWidget = new NURUN.widgets.Comments(this.config.leaveCommentsElId);
    }

    // Initialize Ratings widget
    if (this.config.rating === true) {
        this.ratingsWidget = new NURUN.widgets.Rating(this.config.ratingsElId);
    }
}

NURUN.widgets.Gallery.prototype.showHideNavButtons = function() {

    var prev = YAHOO.util.Dom.getElementsByClassName(this.config.prevClassName, "a", this.galleryEl)[0];
    var prevImage = YAHOO.util.Dom.getElementsByClassName(this.config.prevImageClassName, "a", this.galleryEl)[0];
    var next = YAHOO.util.Dom.getElementsByClassName(this.config.nextClassName, "a", this.galleryEl)[0];
    var nextImage = YAHOO.util.Dom.getElementsByClassName(this.config.nextImageClassName, "a", this.galleryEl)[0];

    var selected = YAHOO.util.Dom.getElementsByClassName("img-selected", "a");
    img = selected[0].getElementsByTagName("img")[0];

    if (img) {
        var GUID = img.src.split("?")[1].split("&")[0].split("=")[1];

        var datasetIndex = 0;
        for (i in this.config.dataset) {
            if (this.config.dataset[i].ID === GUID) {
                datasetIndex = parseInt(i, 10);
            }
        }

        var pageIndex = Math.floor(datasetIndex / this.config.skipBy) + 1;

        // When the end of slideshow is reached, the slideshow presents images from two 
        // different page indexes (if number of images is not multiple of skipBy).
        // If the user is currently viewing an image from the lastPageIndex and clicks 
        // on an image from the previous page, we must animatePrev the slideshow.
        if (pageIndex < this.currentPageIndex) {
            this.animatePrev();
            this.thumbsPointer -= this.config.skipBy;
            this.currentPageIndex--;
        }

        if (datasetIndex === 0) {
            prevImage.style.visibility = "hidden";
        }
        else {
            prevImage.style.visibility = "visible";
        }

        if (pageIndex === 1) {
            prev.style.visibility = "hidden";
        }
        else {
            prev.style.visibility = "visible";
        }

        if (datasetIndex === this.config.dataset.length - 1 && pageIndex === this.lastPageIndex) {
            nextImage.style.visibility = "hidden";
        }
        else {
            nextImage.style.visibility = "visible";
        }

        if (pageIndex === this.lastPageIndex) {
            next.style.visibility = "hidden";
        }
        else {
            next.style.visibility = "visible";
        }
    }
}

/**
* Binds an onclick event to a thumbnail that updates the viewer with its
*   information when clicked.
* @param {HTMLElement} anchor  The anchor surrounding the thumbnail to assign the event to
* @param {Int} ptr  A pointer to the config.dataset array denoting which thumbnail to work on
*/
NURUN.widgets.Gallery.prototype.bindThumbnail = function(anchor, ptr) {
    var data = this.config.dataset[ptr];
    if (anchor) {
        anchor.onclick = function(that, ptr) {
            return function() {
                //Va chercher toutes les balises <a> qui ont une classe "img-selected", retourne un array
                var el = YAHOO.util.Dom.getElementsByClassName("img-selected", "a");

                //Pour chaque élément du tableau, reset la classe à normal 
                //(s'assurer qu'aucun élément n'est déjà sélectionné)
                for (var i = 0; el[i]; i++) {
                    el[i].className = "img-normal";
                }

                //Ensuite assigne la sélection à notre <a>
                anchor.className = "img-selected";

                //Track event
                pageTracker._trackEvent('Image', 'View', SPYDERYUI.globals.cultureId + '/Pictureviewer')

                that.fields.photo.style.visibility = "hidden";
                that.fields.photo.onload = function() {
                    this.style.visibility = "visible";

                }

                that.fields.photo.src = data.MediumUrl;
                that.fields.photoPanel.href = data.MediumUrl.replace(/PictureViewer/, "PictureViewerPanel");
                that.fields.author.innerHTML = data.Author;
                that.fields.author.className = "author " + data.Role;
                that.fields.city.innerHTML = data.City;
                //that.fields.role.innerHTML = data.Role;
                that.fields.title.innerHTML = data.Title;
                that.fields.rating.innerHTML = "<span>" + SPYDERYUI.globals.labels.ratings + ": " + data.Ratings + "</span>";
                that.fields.rating.className = "rating stars" + data.Rating.replace(".", "").replace(",", "");
                that.fields.stats.innerHTML = SPYDERYUI.globals.labels.views + ": " + data.Views;
                that.commentsWidget.toggleComments();
                that.toggleRating('none');
                if (that.config.comments === true) that.getComments(that, that.config.dataset[ptr]);

                that.showHideNavButtons();

                return false;
            }
        } (this, ptr)
    }
}


/**
* Makes an Ajax call to fetch more thumbnails
* @param {Object} that  A reference to the parent Gallery object for scope correction purposes
*/


NURUN.widgets.Gallery.prototype.getMore = function(that, pageIndex, forward) {
    this.loadingEl.style.display = "block";
    var targetUrl = "/SpyderMY09/WebServices/TrySpyder.asmx";
    var callback = {
        success: function(o) {
            var root = o.responseXML.documentElement;
            var resultNode = root.getElementsByTagName("GetFilteredMediaListResult")[0];
            if (resultNode) {
                var payload = eval("(" + (resultNode.childNodes[0].nodeValue) + ")");

                var startIndex = (pageIndex - 1) * that.config.skipBy;

                var counter = 0;
                var newItems = new Array();
                if (payload && payload.imageCount > 0) {
                    for (image in payload.images) {
                        if (payload.images.hasOwnProperty(image)) {

                            that.config.dataset[startIndex + counter] = payload.images[image];

                            // Create thumbnail
                            var i = payload.images[image];
                            var li = document.createElement("li");
                            li.id = "img" + i.ID;
                            var thumb = document.createElement("div");
                            thumb.className = "thumb";
                            thumb.style.visibility = "hidden";
                            if (that.fields.photo) {
                                var a = document.createElement("a");
                                a.href = i.MediumUrl;
                                thumb.style.visibility = "hidden";
                                /* Warning! Order matters here. For IE7's sake, the onload event
                                * needs to be assigned to the img object before the src attribute
                                * is assigned. Also, the reference to the anchor needs to be passed
                                * to the onload function because using this.parentNode doesn't seem
                                * to work in IE7. */
                                var img = document.createElement("img");
                                img.onload = function(thumb) {
                                    return function() {
                                        thumb.style.visibility = "visible";

                                    }
                                } (thumb);
                                img.src = i.ThumbUrl;

                                a.appendChild(img);
                                thumb.appendChild(a);
                            } else {
                                var img = document.createElement("img");
                                img.onload = function(thumb) {
                                    return function() {
                                        thumb.style.visibility = "visible";
                                    }
                                } (thumb);
                                img.src = i.ThumbUrl;
                                thumb.appendChild(img);
                            }
                            li.appendChild(thumb);

                            var content = document.createElement("div");
                            content.className = "content";
                            var contentP = document.createElement("p");
                            contentP.appendChild(document.createTextNode(i.Title));
                            content.appendChild(contentP);
                            li.appendChild(content);
                            that.bindThumbnail(a, startIndex + counter);

                            newItems.push(li);
                            counter++;
                        }
                    }


                    if (forward) {
                        for (var i = 0; i < newItems.length; i++) {
                            // Add thumbnail to list
                            that.thumbsEl.appendChild(newItems[i]);
                        }
                        // Increase Pointers
                        that.thumbsPointer += that.config.skipBy;
                        that.currentPageIndex++;
                    }
                    else {
                        for (var i = newItems.length - 1; i >= 0; i--) {
                            // Add thumbnail to list
                            that.thumbsEl.insertBefore(newItems[i], that.thumbsEl.childNodes[0]);
                        }
                        // No need to decrease thumbsPointer here, only currentPageIndex
                        that.currentPageIndex--;

                        if (that.currentPageIndex === 1) {
                            var galleryEl = that.galleryEl;
                            var prev = YAHOO.util.Dom.getElementsByClassName("prev", "a", galleryEl)[0];
                            prev.style.visibility = "hidden";
                        }
                    }
                }

                // Reset thumb items array with new data
                that.thumbItems = YAHOO.util.Dom.getChildren(that.thumbsEl);

                // Set image to first in the slideshow
                if (forward) {

                    for (var i = 0; i < that.thumbItems.length; i++) {
                        if (that.thumbItems[i].id === "img" + that.config.dataset[startIndex].ID) {
                            var nextItemAnchor = that.thumbItems[i].getElementsByTagName("a")[0];
                            nextItemAnchor.onclick();
                            break;
                        }
                    }
                    // Hide loading anim
                    that.loadingEl.style.display = "none";

                    // Fire "done" event
                    that.doneGettingNext.fire();
                }
                else {
                    for (var i = 0; i < that.thumbItems.length; i++) {
                        if (that.thumbItems[i].id === "img" + that.config.dataset[startIndex + that.config.skipBy - 1].ID) {
                            var prevItemAnchor = that.thumbItems[i].getElementsByTagName("a")[0];
                            prevItemAnchor.onclick();
                            break;
                        }
                    }
                    // Hide loading anim
                    that.loadingEl.style.display = "none";

                    // Fire "done" event
                    that.doneGettingPrev.fire();
                }

                if (payload.imageCount < that.config.skipBy) {
                    //if there's not more images
                    var galleryEl = that.galleryEl;
                    if (forward) {
                        that.lastPageIndex = that.currentPageIndex;
                        var next = YAHOO.util.Dom.getElementsByClassName("next", "a", galleryEl)[0];
                        next.style.visibility = "hidden";
                        if (payload.imageCount <= 1) {
                            var nextImage = YAHOO.util.Dom.getElementsByClassName("nextImage", "a", galleryEl)[0];
                            nextImage.style.visibility = "hidden";
                        }
                    }
                    else {
                        var prev = YAHOO.util.Dom.getElementsByClassName("prev", "a", galleryEl)[0];
                        prev.style.visibility = "hidden";
                        if (payload.imageCount <= 1) {
                            var prevImage = YAHOO.util.Dom.getElementsByClassName("prevImage", "a", galleryEl)[0];
                            prevImage.style.visibility = "hidden";
                        }
                    }
                }
            }
        },
        failure: function(o) {
            // Hide loading anim
            that.loadingEl.style.display = "none";
            var galleryEl = this.galleryEl;

            if (forward) {
                var next = YAHOO.util.Dom.getElementsByClassName("next", "a", galleryEl)[0];
                next.style.visibility = "hidden";
                var nextImage = YAHOO.util.Dom.getElementsByClassName("nextImage", "a", galleryEl)[0];
                nextImage.style.visibility = "hidden";
            }
            else {
                var prev = YAHOO.util.Dom.getElementsByClassName("prev", "a", galleryEl)[0];
                prev.style.visibility = "hidden";
                var prevImage = YAHOO.util.Dom.getElementsByClassName("prevImage", "a", galleryEl)[0];
                prevImage.style.visibility = "hidden";
            }
        },
        argument: {
            that: this
        }
    };

    var message = " \
	<soap:Envelope xmlns:xsi='http:\/\/www.w3.org\/2001\/XMLSchema-instance' xmlns:xsd='http:\/\/www.w3.org\/2001\/XMLSchema' xmlns:soap='http:\/\/schemas.xmlsoap.org\/soap\/envelope\/'> \
		<soap:Body> \
			<GetFilteredMediaList xmlns='http:\/\/spyderryder.brp.com\/TrySpyder\/WebServices\/'> \
			<userID>" + SPYDERYUI.globals.userId + "<\/userID> \
			<currentPageIndex>" + pageIndex + "<\/currentPageIndex> \
			<pageSize>" + that.config.skipBy + "<\/pageSize> \
			<cultureID>" + SPYDERYUI.globals.cultureId + "<\/cultureID> \
			<role>" + SPYDERYUI.globals.CategoryFilter + "<\/role> \
			<countryID>" + SPYDERYUI.globals.CountryFilter + "<\/countryID> \
			<stateID>" + SPYDERYUI.globals.StateFilter + "<\/stateID> \
			<location>" + SPYDERYUI.globals.EventFilter + "<\/location> \
			<userOnly>" + SPYDERYUI.globals.userOnly + "<\/userOnly> \
			<sortBy>" + that.config.sortBy + "<\/sortBy> \
			<\/GetFilteredMediaList> \
		<\/soap:Body> \
	<\/soap:Envelope>";

    // we need to set our own header.
    YAHOO.util.Connect._use_default_post_header = false;
    YAHOO.util.Connect.initHeader('Content-Type', 'text/xml', false);
    YAHOO.util.Connect.initHeader('Content-Length', 'length', false);
    YAHOO.util.Connect.initHeader('SOAPAction', 'http://spyderryder.brp.com/TrySpyder/WebServices/GetFilteredMediaList', false);
    var transaction = YAHOO.util.Connect.asyncRequest('POST', targetUrl, callback, message);
}

NURUN.widgets.Gallery.prototype.getDatasetPushIndexByID = function(id) {
    for (i = 1; i < this.config.dataset.length; i++) {
        if (this.config.dataset[i] != null) {
            if (this.config.dataset[i].ID == id)
                return i;
        }
    }
    return -1;
}

/**
* Makes an Ajax/SOAP call to get comments for a given image
* @param {Object} imgItem  A reference to an image item contained in the Gallery.userConfig.dataset[] array
*/
NURUN.widgets.Gallery.prototype.getComments = function(that, imgItem) {
    that.commentsEl.innerHTML = ""; // One way or another, clear comments

    var targetUrl = "/SpyderMY09/WebServices/TrySpyder.asmx";
    var callback = {
        success: function(o) {
            var root = o.responseXML.documentElement;
            var resultNode = root.getElementsByTagName("GetMediaCommentListResult")[0];
            if (resultNode) {
                var payload = eval("(" + (resultNode.childNodes[0].nodeValue) + ")");

                if (payload && payload.commentCount > 0) {
                    for (comment in payload.comments) {
                        if (payload.comments.hasOwnProperty(comment)) {
                            var comment = payload.comments[comment];
                            if (comment.Content.length > 0) {
                                var li = document.createElement("li");
                                li.id = comment.ID;

                                if (comment.PhotoId.length > 0) {
                                    var img = document.createElement("img");
                                    img.src = "/SpyderMY09/Image.ashx?Format=NewsThumbnail&ImageID=" + comment.PhotoId;
                                    li.appendChild(img);
                                }

                                var span = document.createElement("span");
                                span.className = "author";
                                //span.appendChild(document.createTextNode(SPYDERYUI.globals.labels.writtenBy));
                                span.appendChild(document.createTextNode(comment.Author));
                                li.appendChild(span);

                                var spanCreationDate = document.createElement("span");
                                spanCreationDate.className = "date";
                                spanCreationDate.appendChild(document.createTextNode(comment.CreationDate));
                                li.appendChild(spanCreationDate);

                                var spanComment = document.createElement("span");
                                spanComment.className = "comment";
                                spanComment.appendChild(document.createTextNode(comment.Content));
                                li.appendChild(spanComment);

                                that.commentsEl.appendChild(li);
                            }
                        }
                    }
                    YAHOO.util.Dom.addClass(li, "last");

                    var nbComment = document.getElementById('nbComments');
                    if (nbComment) {
                        nbComment.innerHTML = payload.commentCount;
                    }

                } else {

                    //Create link on phrase "Be the first to write a comment for this picture" 
                    var a = document.createElement("a");
                    a.className = "modify";
                    a.id = "nocomments";
                    a.style.visibility = "visible";
                    a.href = NURUN.globals.NoCommentUrl;

                    var li = document.createElement("li");
                    li.appendChild(document.createTextNode(SPYDERYUI.globals.labels.noComments1));
                    that.commentsEl.appendChild(li);

                    var nbComment = document.getElementById('nbComments');
                    if (nbComment) {
                        nbComment.innerHTML = payload.commentCount;
                    }
                }
            }
        },
        failure: function(o) {
            // Hide loading anim
        },
        argument: {
            that: this
        }
    };

    var message = " \
	<soap:Envelope xmlns:xsi='http:\/\/www.w3.org\/2001\/XMLSchema-instance' xmlns:xsd='http:\/\/www.w3.org\/2001\/XMLSchema' xmlns:soap='http:\/\/schemas.xmlsoap.org\/soap\/envelope\/'> \
	<soap:Body> \
		<GetMediaCommentList xmlns='http:\/\/spyderryder.brp.com\/TrySpyder\/WebServices\/'> \
		<mediaID>" + imgItem.ID + "<\/mediaID> \
		<cultureID>" + SPYDERYUI.globals.cultureId + "<\/cultureID> \
		<\/GetMediaCommentList> \
	<\/soap:Body> \
	<\/soap:Envelope>";

    // we need to set our own header.
    YAHOO.util.Connect._use_default_post_header = false;
    YAHOO.util.Connect.initHeader('Content-Type', 'text/xml', false);
    YAHOO.util.Connect.initHeader('Content-Length', 'length', false);
    YAHOO.util.Connect.initHeader('SOAPAction', 'http://spyderryder.brp.com/TrySpyder/WebServices/GetMediaCommentList', false);
    var transaction = YAHOO.util.Connect.asyncRequest('POST', targetUrl, callback, message);
}


/**
* Animates the thumbnails backward. 
*/
NURUN.widgets.Gallery.prototype.animatePrev = function() {
    if (this.config.scroll == "vertical") {
        var scrollBy = this.config.scrollBy || this.viewportEl.offsetHeight;

        var viewportScrollTop = this.viewportEl.scrollTop;
        if (viewportScrollTop > 0) {
            this.scrollAnim.attributes = {
                scroll: {
                    to: [0, viewportScrollTop - scrollBy]
                }
            };
            this.scrollAnim.animate();
        }
    } else if (this.config.scroll == "horizontal") {
    var scrollBy = this.config.scrollBy || this.viewportEl.offsetWidth;
    var viewportScrollLeft = this.viewportEl.scrollLeft;
        if (viewportScrollLeft > 0) {
            this.scrollAnim.attributes = {
                scroll: {
                    to: [viewportScrollLeft - scrollBy, 0]
                }
            };
            this.scrollAnim.animate();
        }
    }
}

/**
* Animates the thumbnails forward. 
*/
NURUN.widgets.Gallery.prototype.animateNext = function() {
    if (this.config.scroll == "vertical") {
        var scrollBy = this.config.scrollBy || this.viewportEl.offsetHeight;
        var thumbsHeight = this.thumbsEl.offsetHeight;
        var viewportScrollTop = this.viewportEl.scrollTop;
        if (thumbsHeight > scrollBy) {
            this.scrollAnim.attributes = {
                scroll: {
                    to: [0, viewportScrollTop + scrollBy]
                }
            };
            this.scrollAnim.animate();
        }

    } else if (this.config.scroll == "horizontal") {
        var scrollBy = this.config.scrollBy || this.viewportEl.offsetWidth;
        var thumbsElWidth = 0;
        var tmp = 0;
        for (var i = 0; this.thumbItems[i]; i++) {
            tmp = parseFloat(YAHOO.util.Dom.getStyle(this.thumbItems[i], "width"));
            thumbsElWidth += (!isNaN(tmp)) ? tmp : 0;

            tmp = parseFloat(YAHOO.util.Dom.getStyle(this.thumbItems[i], "margin-right"));
            thumbsElWidth += (!isNaN(tmp)) ? tmp : 0;

            tmp = parseFloat(YAHOO.util.Dom.getStyle(this.thumbItems[i], "border-left-width"));
            thumbsElWidth += (!isNaN(tmp)) ? tmp : 0;

            tmp = parseFloat(YAHOO.util.Dom.getStyle(this.thumbItems[i], "border-right-width"));
            thumbsElWidth += (!isNaN(tmp)) ? tmp : 0;
        }
        this.thumbsEl.style.width = thumbsElWidth + "px";
        var thumbsWidth = this.thumbsEl.offsetWidth;
        var viewportScrollLeft = this.viewportEl.scrollLeft;
        if (thumbsWidth > scrollBy) {
            this.scrollAnim.attributes = {
                scroll: {
                    to: [viewportScrollLeft + scrollBy, 0]
                }
            };
            this.scrollAnim.animate();

        }
    }
}

NURUN.widgets.Gallery.prototype.toggleRating = function(state) {
    var galleryEl = this.galleryEl;
    var rateBox = document.getElementById("user-ratings");

    if (!state) {
        state = YAHOO.util.Dom.getStyle(rateBox, "display");
    }
    var optionsBar = YAHOO.util.Dom.getElementsByClassName("photo-options", "div", galleryEl)[0];
    var photoInfo = YAHOO.util.Dom.getElementsByClassName("photo-info", "div", galleryEl)[0];
    var ratings = YAHOO.util.Dom.getElementsByClassName("ratings", "div", galleryEl)[0];
    var thankyou = YAHOO.util.Dom.getElementsByClassName("thankyou", "span", galleryEl)[0];

    //Verify if the user is loged in to rate a photo
    if (SPYDERYUI.globals.IsAuthenticated) {
        if (state == "none") {
            rateBox.style.display = "block";
            thankyou.style.display = "none";
        } else {
            rateBox.style.display = "none";
            optionsBar.style.display = "block";
            photoInfo.style.display = "block";
            ratings.style.display = "block";
            var list = document.getElementById("gallery-rating");
            list.className = "rate";
            thankyou.style.display = "block";
        }

        return false;
    }
}



/**
* Creates an comment widget 
* 
* @constructor
* @param {String|HTMLElement} id The element containing the comment textarea
* @param {Object} config An object literal with override config values
* @requires YAHOO.util.Dom Required for extended/normalized DOM manipulation
*/
NURUN.widgets.Comments = function(id, config) {
    if (typeof id == "undefined") return false;
    if (typeof config == "undefined") config = {};

    this.commentsEl = YAHOO.util.Dom.get(id);

    // Set config defaults
    this.config = {};

    // Override config defaults
    for (var item in config) {
        this.config[item] = config[item];
    }

    // Get all gallery related fields for future reference
    this.fields = {};

    this.fields.divComment = YAHOO.util.Dom.getElementsByClassName("LeaveComment", "div", this.commentsEl)[0];
    this.fields.divCommentConfirmation = YAHOO.util.Dom.getElementsByClassName("LeaveCommentConfirmation", "div", this.commentsEl)[0];
    this.fields.divCommentUserMustLogin = YAHOO.util.Dom.getElementsByClassName("LeaveCommentUserMustLogin", "div", this.commentsEl)[0];

    // Initialize
    this.init();
}

NURUN.widgets.Comments.prototype.init = function() {
    this.toggleComments();
}

NURUN.widgets.Comments.prototype.toggleComments = function() {
    if (SPYDERYUI.globals.IsAuthenticated) {
        this.fields.divComment.style.display = 'block';
        this.fields.divCommentUserMustLogin.style.display = 'none';
        this.fields.divCommentConfirmation.style.display = 'none';
    }
    else {
        this.fields.divComment.style.display = 'none';
        this.fields.divCommentUserMustLogin.style.display = 'block';
        this.fields.divCommentConfirmation.style.display = 'none';
    }
}

NURUN.widgets.Comments.prototype.submit = function(GUID) {

    var targetUrl = "/SpyderMY09/WebServices/TrySpyder.asmx";
    var callback = {
        success: function(o) {

            var divComment = YAHOO.util.Dom.getElementsByClassName("LeaveComment", "div", this.commentsEl)[0];
            var divCommentConfirmation = YAHOO.util.Dom.getElementsByClassName("LeaveCommentConfirmation", "div", this.commentsEl)[0];

            divComment.style.display = 'none';
            divCommentConfirmation.style.display = 'block';

            var comment = document.getElementById('commentTextArea');
            comment.value = '';

        },
        failure: function(o) {

        },
        argument: {
            that: this
        }
    };

    var comment = document.getElementById('commentTextArea');

    var message = " \
    	    <soap:Envelope xmlns:xsi='http:\/\/www.w3.org\/2001\/XMLSchema-instance' xmlns:xsd='http:\/\/www.w3.org\/2001\/XMLSchema' xmlns:soap='http:\/\/schemas.xmlsoap.org\/soap\/envelope\/'> \
    	    <soap:Body> \
    		    <AddPictureComment xmlns='http:\/\/spyderryder.brp.com\/TrySpyder\/WebServices\/'> \
    		    <mediaID>" + GUID + "<\/mediaID> \
    		    <userID>" + SPYDERYUI.globals.userId + "<\/userID> \
    		    <cultureID>" + SPYDERYUI.globals.cultureId + "<\/cultureID> \
    		    <comment>" + comment.value + "<\/comment> \
    		    <\/AddPictureComment> \
    	    <\/soap:Body> \
    	    <\/soap:Envelope>";

    // we need to set our own header.
    YAHOO.util.Connect._use_default_post_header = false;
    YAHOO.util.Connect.initHeader('Content-Type', 'text/xml', false);
    YAHOO.util.Connect.initHeader('Content-Length', 'length', false);
    YAHOO.util.Connect.initHeader('SOAPAction', 'http://spyderryder.brp.com/TrySpyder/WebServices/AddPictureComment', false);
    var transaction = YAHOO.util.Connect.asyncRequest('POST', targetUrl, callback, message);

    pageTracker._trackPageview(SPYDERYUI.globals.TrackPage + '/Comment/Post/Confirmation');

}











/**
* Creates an star rating widget based on radio button list markup
* 
* @constructor
* @param {String|HTMLElement} id The element containing the radio button list
* @param {Object} config An object literal with override config values
* @requires YAHOO.util.Dom Required for extended/normalized DOM manipulation
*/
NURUN.widgets.Rating = function(id, config) {
    if (typeof id == "undefined") return false;
    if (typeof config == "undefined") config = {};

    this.ratingEl = YAHOO.util.Dom.get(id);

    // Set config defaults
    this.config = {
};

// Override config defaults
for (var item in config) {
    this.config[item] = config[item];
}

// All star tags containing radio/input elements
this.stars = YAHOO.util.Dom.getElementsByClassName("star", "span", this.ratingEl);
// Initialize
this.init();
}

NURUN.widgets.Rating.prototype.init = function() {
    for (var i = 0; this.stars[i]; i++) {
        this.stars[i].onmouseover = function() {
            YAHOO.util.Dom.addClass(this.parentNode, this.id);
        }
        this.stars[i].onmouseout = function() {
            YAHOO.util.Dom.removeClass(this.parentNode, this.id);
        }
        this.stars[i].onclick = function(input) {
            return function() {
                input.checked = "true";
                for (var i = 1; i < 6; i++) {
                    var cName = "star-" + i.toString() + "-clicked";
                    if (YAHOO.util.Dom.hasClass(input.parentNode.parentNode, cName)) {
                        YAHOO.util.Dom.removeClass(input.parentNode.parentNode, cName);
                    }
                }
                YAHOO.util.Dom.addClass(input.parentNode.parentNode, input.parentNode.id + "-clicked");
            }
        } (this.stars[i].getElementsByTagName("input")[0]);
    }
}

NURUN.widgets.Rating.prototype.submit = function(GUID) {
    var rbls = this.ratingEl.getElementsByTagName("input");
    var rating = null;
    for (var i = 0; rbls[i]; i++) {
        if (rbls[i].checked) rating = rbls[i].value;
    }
    var callback = {
        success: function(o) {
        }
    }
    var targetUrl = "/SpyderMY09/WebServices/TrySpyder.asmx";
    var message = " \
	<soap:Envelope xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xmlns:xsd=\"http:\/\/www.w3.org\/2001\/XMLSchema\" xmlns:soap=\"http:\/\/schemas.xmlsoap.org\/soap\/envelope\/\"> \
		<soap:Body> \
			<RatePicture xmlns=\"http:\/\/spyderryder.brp.com\/TrySpyder\/WebServices\/\"> \
			<mediaID>" + GUID + "<\/mediaID> \
			<userID>" + SPYDERYUI.globals.userId + "<\/userID> \
			<rating>" + rating + "<\/rating> \
			<\/RatePicture> \
		<\/soap:Body> \
	<\/soap:Envelope>";

    // we need to set our own header.
    YAHOO.util.Connect._use_default_post_header = false;
    YAHOO.util.Connect.initHeader('Content-Type', 'text/xml', false);
    YAHOO.util.Connect.initHeader('Content-Length', 'length', false);
    YAHOO.util.Connect.initHeader('SOAPAction', 'http://spyderryder.brp.com/TrySpyder/WebServices/RatePicture', false);
    var transaction = YAHOO.util.Connect.asyncRequest('POST', targetUrl, callback, message);

    shareTracker._trackEvent('Rate');
}

/**
* Creates a slideshow with previous/next buttons and pips in between representing
* the current slide among the total number of slides in the show
*/
NURUN.widgets.Slideshow = function(slidesId, controlbarId, userConfig) {
    this.slidesEl = YAHOO.util.Dom.get(slidesId);
    this.controlBarEl = YAHOO.util.Dom.get(controlbarId);

    if (!this.slidesEl || !this.controlBarEl) return;

    //this.refreshSlidesElDims();
    this.slidesElDims = {
        xy: YAHOO.util.Dom.getXY(this.slidesEl),
        width: this.slidesEl.offsetWidth,
        height: this.slidesEl.offsetHeight
    };


    this.uc = userConfig || {};
    this.slides = YAHOO.util.Dom.getElementsByClassName("slide", this.uc.slidesElType || "li", this.slidesEl);
    this.numSlides = this.slides.length;

    this.slidesPtr = 0;
    this.currentSlide = function() { return this.slidesPtr + 1 }

    // Only create previous and next buttons if there is more than one slide
    if (this.numSlides > 1) {
        // Previous button
        this.prevBtn = document.createElement(this.uc.buttonNodeName || "span");
        this.prevBtn.innerHTML = "&larr;";
        this.prevBtn.className = this.uc.prevBtnClass || "prev";
        this.prevBtn.onclick = function(that) {
            return function() {
                that.goTo(-1);
                that.resetTimer();
                return false;
            }
        } (this);
        this.controlBarEl.appendChild(this.prevBtn);

        // Indicator
        this.indicator = document.createElement(this.uc.buttonNodeName || "span");
        this.indicator.className = this.uc.indicatorClass || "indicator";
        this.pips = [];
        for (var i = 0; i < this.numSlides; i++) {
            var pip = document.createElement("span");
            if ((i + 1) === this.currentSlide()) {
                pip.className = "current";
            }
            pip.onclick = function(that, num) {
                return function() {
                    var dir = (that.slidesPtr > num) ? 1 : -1;
                    that.goTo(dir, num);
                    that.resetTimer();
                }
            } (this, i);
            this.indicator.appendChild(pip);
            this.pips.push(pip);
        }
        this.controlBarEl.appendChild(this.indicator);

        // Next button
        this.nextBtn = document.createElement(this.uc.buttonNodeName || "span");
        this.nextBtn.innerHTML = "&rarr;";
        this.nextBtn.className = this.uc.nextBtnClass || "next";
        this.nextBtn.onclick = function(that) {
            return function() {
                that.goTo(1);
                that.resetTimer();
                return false;
            }
        } (this);
        this.controlBarEl.appendChild(this.nextBtn);

        // Get slides out of the way for Safari 2.0.x because they block page links
        for (var i = 1; this.slides[i]; i++) {
            this.slides[i].style.top = "-3000px";
            this.slides[i].style.left = "-3000px";
        }
    }
    this.goTo(0); // to initialize the first slide if it has a popup
    this.setTimer(); // set automated forward timer
}

NURUN.widgets.Slideshow.prototype.setTimer = function() {
    if (this.uc.timer) {
        this.slideShowInterval = window.setInterval(
			function(that) {
			    return function() {
			        that.goTo(1);
			    }
			} (this),
			this.uc.timer
		);
    }
}

NURUN.widgets.Slideshow.prototype.resetTimer = function() {
    if (this.slideShowInterval) {
        window.clearInterval(this.slideShowInterval);
        this.setTimer();
    }
}

NURUN.widgets.Slideshow.prototype.refreshSlidesElDims = function() {
    this.slidesElDims = {
        xy: YAHOO.util.Dom.getXY(this.slidesEl),
        width: this.slidesEl.offsetWidth,
        height: this.slidesEl.offsetHeight
    };
}

NURUN.widgets.Slideshow.prototype.goTo = function(dir, skipTo) {
    this.slidesElDims = {
        xy: YAHOO.util.Dom.getXY(this.slidesEl),
        width: this.slidesEl.offsetWidth,
        height: this.slidesEl.offsetHeight
    };

    var outSlide = this.slides[this.slidesPtr];
    var outSlideXY = YAHOO.util.Dom.getXY(outSlide);
    var outSlideWidth = outSlide.offsetWidth;

    if (dir == -1) {
        var outSlideAnim = new YAHOO.util.Motion(outSlide, {
            opacity: {
                from: 1,
                to: 0
            },
            points: {
                from: [
                        this.slidesElDims.xy[0],
                        this.slidesElDims.xy[1]
                    ],
                to: [
                        this.slidesElDims.xy[0] + this.slidesElDims.width,
                        this.slidesElDims.xy[1]
                    ]
            }
        }
        );
        outSlideAnim.onComplete.subscribe(
           function(el) {
               return function() {
                   el.style.top = "-3000px";
                   el.style.left = "-3000px";
               }
           } (outSlide)
        );
        outSlideAnim.duration = 0.5;
        outSlideAnim.method = YAHOO.util.Easing.easeOutStrong;

        this.slidesPtr = (this.slides[skipTo]) ? skipTo : this.slides[this.slidesPtr - 1] ? this.slidesPtr - 1 : this.numSlides - 1;
        var inSlide = this.slides[this.slidesPtr];
        var inSlideXY = YAHOO.util.Dom.getXY(inSlide);
        var inSlideAnim = new YAHOO.util.Motion(inSlide, {
            opacity: {
                from: 0,
                to: 1
            },
            points: {
                from: [
                        this.slidesElDims.xy[0] - this.slidesElDims.width,
                        this.slidesElDims.xy[1]
                    ],
                to: [
                        this.slidesElDims.xy[0],
                        this.slidesElDims.xy[1]
                    ]
            }
        }
        );
        inSlideAnim.duration = 0.5;
        inSlideAnim.method = YAHOO.util.Easing.easeOutStrong;

        outSlideAnim.animate();
        inSlideAnim.animate();


    } else if (dir == 1) {
        var outSlideAnim = new YAHOO.util.Motion(outSlide, {
            opacity: {
                from: 1,
                to: 0
            },
            points: {
                from: [
                        this.slidesElDims.xy[0],
                        this.slidesElDims.xy[1]
                    ],
                to: [
                        this.slidesElDims.xy[0] - this.slidesElDims.width,
                        this.slidesElDims.xy[1]
                    ]
            }
        }
        );
        outSlideAnim.onComplete.subscribe(
           function(el) {
               return function() {
                   el.style.top = "-3000px";
                   el.style.left = "-3000px";
               }
           } (outSlide)
        );
        outSlideAnim.duration = 0.5;
        outSlideAnim.method = YAHOO.util.Easing.easeOutStrong;

        this.slidesPtr = (this.slides[skipTo]) ? skipTo : this.slides[this.slidesPtr + 1] ? this.slidesPtr + 1 : 0;
        var inSlide = this.slides[this.slidesPtr];
        var inSlideXY = YAHOO.util.Dom.getXY(inSlide);
        var inSlideAnim = new YAHOO.util.Motion(inSlide, {
            opacity: {
                from: 0,
                to: 1
            },
            points: {
                from: [
                        this.slidesElDims.xy[0] + this.slidesElDims.width,
                        this.slidesElDims.xy[1]
                    ],
                to: [
                        this.slidesElDims.xy[0],
                        this.slidesElDims.xy[1]
                    ]
            }
        }
        );
        inSlideAnim.duration = 0.5;
        inSlideAnim.method = YAHOO.util.Easing.easeOutStrong;

        outSlideAnim.animate();
        inSlideAnim.animate();
    }

    if (this.indicator) {
        for (var i = 0; this.pips[i]; i++) {
            if ((i + 1) === this.currentSlide()) {
                this.pips[i].className = "current";
            } else {

                this.pips[i].className = "";
            }
        }
    }
}
