/* js/carousel.js */
YUI.add('uwc-carousel', function(Y) {
    Y.namespace('uwc');
    function Carousel(config){
        Carousel.superclass.constructor.apply(this, arguments);
    }
    Y.extend(Carousel, Y.Base, {
        initializer: function(cfg) {
            var nodeListSlides,
                nodeCarousel,
                nodeContainer = this.get("nodeContainer"),
                carouselClassName = this.get("carouselClassName");
            this.interval = null;
            this.curSlide = 0;
            nodeListSlides = this.getCarouselNodeList();
            this.nodeCarousel = nodeContainer.one("."+ carouselClassName);
            // Ensure Carousel is position: relative
            this.nodeCarousel.setStyle("position", "relative");
            this.numSlides = nodeListSlides.size();
            // init animation
            this.caroAnim = new Y.Anim({
                node: this.nodeCarousel
            });
            this.caroAnim.set("duration", this.get("slideAnimDuration"));
            this.caroAnim.set("easing", this.get("slideEasing"));
            this.caroAnim.on("end", function(){
                this.updatePagination();
            }, this);

            // Create next/prev
            this.generateControls();
            // Create Paging
            this.generatePagination();
            this.updatePagination();
            // We are ready display everything.
            this.nodeCarousel.removeClass("hidden");
            if (this.get("autoPlay")) {
                this.autoPlay();
            }
        },
        getCarouselNodeList: function() {
            var nodeContainer = this.get("nodeContainer"),
                carouselClassName = this.get("carouselClassName");
            return nodeContainer.all("." + carouselClassName + " li");
        },
        updatePagination: function() {
            var nodeContainer = this.get("nodeContainer"),
                paginationListItems;
            paginationListItems = nodeContainer.all(".pagination li a");
            paginationListItems.each(function(a){
                var nodeClassName = a.get("className");
                if (parseInt(nodeClassName.replace("p-", ""), 10) === this.curSlide) {
                    a.addClass("active");
                } else {
                    a.removeClass("active");
                }
            }, this);
        },
        generatePagination: function() {
            var pageText = 'Page',
                nodeContainer = this.get("nodeContainer"),
                ol = document.createElement('ol'),
                li, a, sp, txt;

            ol.className = "pagination";
            for (var i=0, j=this.numSlides; i < j; i++){
                li = document.createElement('li');
                a = document.createElement('a');
                sp = document.createElement('span');
                a.href = '#';
                txt = document.createTextNode(pageText+(i+1));
                sp.appendChild(txt);
                a.appendChild(sp);
                a.className = 'p-'+i;
                li.appendChild(a);
                ol.appendChild(li);
            }
            nodeContainer.append(ol);
            olNode = Y.one(ol);
            olNode.on("click", function(e){
                var targetClass;
                e.preventDefault();
                if (this.caroAnim.get("running") === false) {
                    if (e && this.autoPlayTimer) {
                        clearInterval(this.autoPlayTimer);
                    }
                    targetClass = e.target.get("className");
                    this.gotoSlide(parseInt(targetClass.replace("p-", ""), 10));
                }
            }, this);
            // Center pagination
            olNode.setStyle('left', parseInt((
                parseInt(olNode.get('parentNode').getComputedStyle('width')) -
                parseInt(olNode.getComputedStyle('width'))) / 2) + 'px');
        },
        generateControls: function() {
            var controlsContainer = this.get("controlsContainer");
            if (controlsContainer) {
                var prev = Y.Node.create('<a href="#" class="prev"><span>Previous Slide</span></a>'),
                    next = Y.Node.create('<a href="#" class="next"><span>Next Slide</span></a>');
                next.on("click", this.next, this);
                prev.on("click", this.prev, this);
                controlsContainer.appendChild(prev);
                controlsContainer.appendChild(next);
            }
        },
        advance: function(e, val){
            if (e) {
                e.preventDefault();
            }
            if (e && this.autoPlayTimer) {
                clearInterval(this.autoPlayTimer);
            }
            if (this.caroAnim.get("running") === true) {
                return;
            }
            this.gotoSlide(val);
        },
        next: function(e){
            this.advance(e, this.curSlide + 1);
        },
        prev: function(e){
            this.advance(e, this.curSlide - 1);
        },
        gotoSlide: function(nSlideIndex, duration) {
            var xOffSet, slideWidth;
            slideWidth = parseInt(this.nodeCarousel.one("li").getStyle("width"), 10);
            duration = (duration === 0) ? duration : (duration || this.get("slideAnimDuration"));
            this.nSlideIndex = nSlideIndex;
            if (nSlideIndex < 0) {
                this.animateTo(-(slideWidth * (this.numSlides-1)), duration);
                this.curSlide = this.numSlides - 1;
            } else if (nSlideIndex >= (this.numSlides)) {
                this.animateTo(0, duration);
                this.curSlide = 0;
            } else {
                xOffSet = -slideWidth * nSlideIndex;
                this.animateTo(xOffSet, duration);
                this.curSlide = nSlideIndex;
            }

        },
        autoPlay: function() {
            var that = this;
            this.autoPlayTimer = setInterval(function(){
               that.next();
            }, that.get("slideAnimInterval"));
        },
        animateTo: function(value, duration) {
            var origDuration;
            if (duration === 0) {
                this.nodeCarousel.setStyle("left", value);
            } else {
                if (duration) {
                    origDuration = this.caroAnim.get("duration");
                    this.caroAnim.set("duration", duration);
                }
                this.caroAnim.set("to", { "left": value });
                this.caroAnim.run();
                this.caroAnim.set("duration", origDuration);
            }
        }
    }, {
        NAME: "carousel",
        ATTRS: {
            carouselClassName: { value: "carouselol"},
            containerHeight: { value: null },
            containerWidth: { value: null },
            nodeContainer: {
                setter: function(sel) {
                    var n = Y.one(sel);
                    if (!n) {
                        Y.log('UWC:Carousel - invalid selector provided: ' + sel);
                    }
                    return n;
                }
            },
            controlsContainer: {
                setter: function(sel) {
                    return Y.one(sel);
                }
            },
            slideAnimDuration: { value: 1 },
            slideAnimInterval: { value: 5000 },
            slideEasing: { value: Y.Easing.easeBoth },
            autoPlay: { value: true }
        }
    });
    Y.uwc.Carousel = Carousel;
}, '0.0.1', {
    requires: ['base', 'node', 'anim', 'event','panel', 'transition']
});

/* js/screenshots.js */
var setup_screenshots = function(num_screenshots, appName, combo_path, ajax_uri) {
    YUI({combine: true, comboBase: combo_path, root: 'yui/3.4.0/build/'}).use('io-base','uwc-carousel', function(Y) {
        if (num_screenshots == 0) {
            var uri = ajax_uri;
            function complete(id, obj) {
                var json = JSON.parse(obj.responseText);
                num_screenshots = json.length;
                if (num_screenshots > 0) {
                    var content_div = document.createElement('div');
                    content_div.className = 'carousel-wrapper';
                    var carousel_div = document.createElement('div');
                    carousel_div.id = 'screenshots-carousel';
                    carousel_div.className = 'carousel';
                    content_div.appendChild(carousel_div)
                    var ol = document.createElement('ol')
                    ol.className = 'carouselol';
                    carousel_div.appendChild(ol);
                    for (var i in json) {
                        var url = json[i];
                        var li = document.createElement('li');
                        li.className = 'slide';
                        ol.appendChild(li);
                        var img = document.createElement('img');
                        img.src = url;
                        li.appendChild(img);
                    }
                    var screenshots_div = Y.one('#screenshots_placeholder');
                    screenshots_div.get('childNodes').remove();
                    screenshots_div.appendChild(content_div);
                    setup_carousel();
                    setupViewerPanel();
                };
            };
            Y.on('io:complete', complete, Y);
            var request = Y.io(uri);
        } else {
            setup_carousel();
            setupViewerPanel();
        }

        function setupViewerPanel() {
            if (num_screenshots == 0) {
                return;
            }
            var panel = new Y.Panel({
                width: 860,
                centered: true,
                zIndex: 50,
                modal: true,
                visible: false,
                render: false,
                buttons: [
                    {
                        value: 'Close',
                        section: 'footer',
                        action: function(e) {
                            e.preventDefault();
                            panel.hide();
                        }
                    }
                ]
            });
            var bb = panel.get('boundingBox');
            var slides = Y.all('.slide img');
            slides.on("click", function(e){
                    var slide = e.currentTarget;
                    var url = slide.getAttribute('src');
                    url = url.replace('/225x170/', '/800x800/');
                    heading = appName + ' - screenshot ';
                    panel.setStdModContent(Y.WidgetStdMod.HEADER, heading);
                    panel.setStdModContent(Y.WidgetStdMod.BODY, '<img width="800" src="' + url +'"/>');
                    panel.render('#viewerPanel');
                    panel.show();
                }, this);
        }

        function setup_carousel() {
            if (num_screenshots < 2) {
                return;
            }
            var caro = new Y.uwc.Carousel({
                nodeContainer: "#screenshots-carousel",
                controlsContainer: "#nocontrols",
                autoPlay: false,
                slideAnimDuration: 0.6
            });
            Y.all('.slide').removeClass('disabled');
        }
    });
}

