if (typeof UI == "undefined") { var UI = new Object(); }
UI.DataSlider = Class.create();

UI.DataSlider.prototype = {


    initialize: function(params) {
        this.options = Object.extend({
            visibleHeight: 2,
            visibleWidth: 2,
            autoScroll: 0,
            randomStartPosition: 0
            // some necessary to fetch the correct module
            //    module { 
            //        name
            //        type
            //        index
            //        categoryId
            //        partnerId
            //        length
            //    }
        },params || {});

        this.currentPage = 1; // page we're showing now 
        this.container = Element.select(this.options.containerElement, ".sliderRender")[0];
        this.swfPanels = [];

        // ajax call to load all items and get count
        new Ajax.Request("http://ringtones.thumbplay.com/data/moduleitemcontent.php", {
              method: "post",
              parameters: { 
                  categoryId: this.options.module.categoryId,
                  partnerId: this.options.module.partnerId,
                  handsetId: this.options.module.handsetId,
                  moduleName: this.options.module.name,
                  moduleType: this.options.module.type,
                  moduleIndex: this.options.module.index,
                  length: this.options.module.length
              },
              requestHeaders: { Accept: "text/javascript" },
              onSuccess: function(transport) {
                  alert(transport.responseText);
                  var json = transport.responseText.evalJSON();
                  
                  this.setupData(json);
              }.bind(this)
        });
    },

     // call back for ajax to load data
    setupData: function(data) {
        if ((!data) || (!data.items) || (data.items.length < 1)) {
            return; // we dont have anything to draw
        }

        if (this.options.randomStartPosition) { 
            var head = data.items.splice(Math.floor(Math.random()*data.items.length));
            data.items = head.concat(data.items);
        }
        this.data = data;

        var itemsPerPage = this.options.visibleHeight * this.options.visibleWidth;
        // count up items, figure out number of pages
        this.totalPages = Math.ceil(data.items.length / itemsPerPage);

        // build first page of items
        this.container.update("");
        this.container.setStyle({display: "block"});

        if (Prototype.Browser.IE) { 
            this.container.insert(this.buildPage(data, 0).outerHTML);
        } else { 
            this.container.insert(this.buildPage(data, 0));
        }

        this.ellipsizeText(this.container);

        for (var index=0; index<this.swfPanels.length; index++) {
            this.swfPanels[index].write("swfSliderItem" + index);
        }
        this.swfPanels = [];

        // attempt to cache images for subsequent pages after everything else loaded
        Event.observe(window, "load", function() {
            var images = new Array();
            var image = new Element("img");
            for (var l=(this.options.visibleHeight * this.options.visibleWidth); l<data.items.length; l++) {
                try { 
                   images.push(data.items[l].media.thumbUrl);
                } catch(err) { } // handle eithe promo panels or simple items
                try { 
                   images.push(data.items[l].largeImagePath);
                } catch(err) { }
            }
            Event.observe(image, "load", function() {
                if (images[0]) { 
                    this.src = images.shift();
                }
            });
            image.src = images.shift();
        }.bind(this));

        // TODO: build next page ahead of time?

        Event.observe(Element.select(this.options.containerElement, ".sliderPrev")[0], "click", this.doClickPrev.bindAsEventListener(this), false);
        Event.observe(Element.select(this.options.containerElement, ".sliderNext")[0], "click", this.doClickNext.bindAsEventListener(this), false);
        Event.observe(this.container, "mousedown", this.clearAutoScroll.bindAsEventListener(this), false);
        
        this.position = 0;

        // start timer as necessary.  
        // if too few pages, dont start timer and hide buttons
        if (this.totalPages > 1) {
            this.setAutoTimer();
        } else {
            try { 
                Element.select(this.options.containerElement, ".sliderPrev")[0].hide();
                Element.select(this.options.containerElement, ".sliderNext")[0].hide();
            } catch(err) { }
        }

    },

    buildPage: function(data, rangeStart) {

        var dimensions = this.container.up().getDimensions();

        this.pageSize  = dimensions.width;

        var singlePage = new Element("table", {"class": "sliderPage", "border": "0", "cellpadding": "0", "cellspacing": "0", "width": dimensions.width, "style": "float: left;"});

        var tbody = new Element("tbody");
        singlePage.insert(tbody);

        var row, cell;
        var itemIndex = rangeStart;

        var cellWidth = Math.floor(dimensions.width / this.options.visibleWidth);
        var cellHeight = Math.floor(dimensions.height / this.options.visibleHeight);

        for (var h=0; h<this.options.visibleHeight; h++) {
            row = new Element("tr");
            for (var w=0; w<this.options.visibleWidth; w++) {
                cell = new Element("td", { "width": cellWidth+ "px", "height": cellHeight + "px", "style": "vertical-align: top"});

                while (itemIndex >= data.items.length) { 
                    itemIndex -= (data.items.length);
                } 
                while (itemIndex < 0) {
                    itemIndex += (data.items.length);
                }

                if ((this.totalPages > 1) || (((h+1) * (w+1)) <= data.items.length)) { // dont autofill if only one page
                    cell.insert(this.generateItem(data.items[itemIndex]));
                } else {

                }

                itemIndex++;
                row.insert(cell);

            }
            singlePage.insert(row);
        }

        return singlePage;

    },

    generateItem: function(item) {

        if ((this.options.module.type == 'PSL') || (this.options.module.type == 'PSB')) {
            return this.generatePromo(item);
        } 

        if (this.options.module.type == 'PCS') { 

            return this.generateContentPromo(item);
        } 

        return this.generateSimple(item);

    },

    generateSimple: function(item) {

        // generate DOM for an item object

        var height = "75";
        var width = "75";
        var popupClass = " popupDetails";

        if (!item || !item.link) { return; }

        var link = item.link.purchaseUrl;

        if (item.contentType.id == 3) { height = "100"; }
        if (((item.contentType.id == 3) || (item.contentType.id == 5)) && (item.link.detailsUrl)) { 
            popupClass = ""; // no popup for games or videos
            link = item.link.detailsUrl;
        }

        var div = new Element("div", { "class": "contentItem contentItemSimple contentType" + item.contentType.id});
        var a = new Element("a", { "href": link });
        var img = new Element("img", { "src": item.media.thumbUrl, "class": "thumb" + popupClass, "alt": item.name + " - " + item.contentType.name, "height": height, "width": width });
        img.setAttribute("detailsimage", item.media.largeUrl);

        var title = new Element("p", { "class": "title" + popupClass });
        var titlelink = new Element("a", { "href": link, "class": "titleLink", "title": item.name }).update(item.name);

        div.insert(a.insert(img))
        div.insert(title.insert(titlelink));

        if (item.artist && item.artist.artistUrl && item.artist.name) {
            var artist = new Element("p", { "class": "artist" });
            var artistlink = new Element("a", { "href": item.artist.artistUrl, "class": "artistLink", "title": item.artist.name }).update(item.artist.name);
            div.insert(artist.insert(artistlink));
        }

        if ((item.contentType.id != 3) && (item.contentType.id != 5)) { 

            if (item.media.previewUrl) {
                var play = new Element("a", { "class": "play hide", "href": item.media.previewUrl});
                div.insert(play);
            }

            var getit = new Element("a", { "class": "getit hide", "href": item.link.purchaseUrl});
            div.insert(getit);

            var info = new Element("span", { "class": "info hide" });
            info.setAttribute("credits", item.credits);
            info.setAttribute("contentid", item.id);
            div.insert(info);

            var share = new Element("span", { "class": "sharecontentid hide" });
            share.setAttribute("contentid", item.id);
            div.insert(share);

        }

        return div;

    },

    generatePromo: function(item) {

        var panelWidth = 448;
        var panelHeight = 168;
        if (this.options.module.type == "PSB") { 
            panelWidth = 472;
            panelHeight = 218;
        }

        var index = this.data.items.indexOf(item);
       
        var div = new Element("div", { "class": "promo" });
        if (item.url) {
            var a = new Element("a", { "href": item.url });
        }
        if (item.largeImagePath) {
            var img = new Element("img", { "class": "promoImage", "src": (item.largeImagePath), "border": "0", "height": panelHeight, "width": panelWidth });
        }

        if (item.swfPath) {

            var span = new Element("span", { "id": ("swfSliderItem" + index), "class": "panelFlash" });

            // swfobject setup, insert later
            var swfPath = item.swfPath;
            var swfConfigPath = swfPath.sub(".swf$", ".xml");
            this.swfPanels[index] = new SWFObject(swfPath, "swfSliderItem" + index + "Object", panelWidth, panelHeight, "7", "#FFFFFF");
            this.swfPanels[index].addParam("wmode", "opaque");
            this.swfPanels[index].addParam("quality", "autohigh");
            this.swfPanels[index].addVariable("url", item.url);
            this.swfPanels[index].addVariable("config", swfConfigPath);
            this.swfPanels[index].addVariable("enablejs", "true");
            this.swfPanels[index].addVariable("javascriptid", "swfSliderItem" + index + "Object");

            if (img) { span.insert(img); }
            div.insert(span);

        } else { 

            if (a && img) { 
                a.insert(img);
                div.insert(a);
            } else if (img) {
                div.insert(img);
            }

        }

        return div;
    },

    generateContentPromo: function(item) {
        var panelWidth = 448;
        var panelHeight = 168;

        var div = new Element("div", { "class": "promo" });

        if (item.url) {
            var a = new Element("a", { "href": item.url });
        } else if (item.content.link.purchaseUrl) {
            var a = new Element("a", { "href": item.content.link.purchaseUrl });
        }

        if (item.largeImagePath) {
            var img = new Element("img", { "class": "promoImage", "src": (item.largeImagePath), "border": "0", "height": panelHeight, "width": panelWidth });
        }
        if (a && img) { 
            a.insert(img);
        } 
        if (a) { 
            div.insert(a);
        } else if (img) {
            div.insert(img);
        }

        if (item.content.link.purchaseUrl && item.content.name && item.content.contentType.name) {
            var geta = new Element("a", { "href": item.content.link.purchaseUrl });
            var getimg = new Element("img", { "class": "getit hoverbutton", "src": "/images/content/getit_btn.gif", "border": "0", "height": "24", "width": "47", "alt": "Download " + item.content.name + " " + item.content.contentType.name });
            geta.insert(getimg);
            div.insert(geta);
        }

        var playimg = new Element("img", {"class": "previewplay play", "src": "/images/content/levels_btn.gif", "alt": "Play", "height": "28", "width": "48"});
        playimg.setAttribute("previewpath", item.content.media.previewUrl);
        playimg.setAttribute("stop", "/images/content/levels-anim_btn.gif");
        div.insert(playimg);

        var ptitle = new Element("p", {"class": "title"});
        var spantitle = new Element("span", {});
        spantitle.update(item.content.contentType.name + " ")
        ptitle.insert(spantitle);
        ptitle.insert(item.content.name);
        div.insert(ptitle);

        if (item.content.artist.name) {
            var partist = new Element("p", {"class": "artist"});
            var spanartist = new Element("span", {});
            var aartist = new Element("a", {"href": item.content.artist.artistUrl});
            spanartist.update("Artist: ");
            partist.insert(spanartist);
            aartist.insert(item.content.artist.name);
            partist.insert(aartist);
            div.insert(partist);
        }

        // TODO : add hoverbutton functions ... 
        return div;
    },

    ellipsizeText: function(el) {

        var items = Element.select(el, "div.contentItem");
        items.each(
            function(item) {
                var title = Element.select(item, ".titleLink").first();
                var height = title.getHeight();

                var artist = Element.select(item, ".artistLink").first();
                if (artist) { 
                    height += artist.getHeight();
                }

                if ((height / 14) > 3) {
                    if (artist && (artist.innerHTML.length > 19)) {
                        artist.update(artist.innerHTML.truncate(19));
                    }
                    var titleClip = 30;
                    if (!artist || artist.innerHTML == "") {
                        titleClip = 50;
                    }
                    if (title.innerHTML.length > titleClip) {
                        title.update(title.innerHTML.truncate(titleClip));
                    }
                }

            }
        );

    },

    movePage: function(direction) {

        var itemsPerPage =  (this.options.visibleHeight * this.options.visibleWidth);

        if (direction == "back") { // add to back for next
            if (Prototype.Browser.IE) { 
                this.container.insert(this.buildPage(this.data, ((this.currentPage - 1) * itemsPerPage)).outerHTML);
            } else { 
                this.container.insert(this.buildPage(this.data, ((this.currentPage - 1) * itemsPerPage)));
            }
            this.ellipsizeText(this.container);
        }  else if (direction == "front") { // add to front for previous
            if (Prototype.Browser.IE) { 
                Element.insert(this.container, {top: this.buildPage(this.data, ((this.currentPage -1) * itemsPerPage)).outerHTML});
            } else { 
                Element.insert(this.container, {top: this.buildPage(this.data, ((this.currentPage -1) * itemsPerPage))});
            }
            this.ellipsizeText(this.container);
            this.position = this.position - this.pageSize;
            this.container.setStyle({left: (this.position + "px")});
        }
        for (var index=0; index<this.swfPanels.length; index++) {
            if (this.swfPanels[index]) { 
                this.swfPanels[index].write("swfSliderItem" + index);
            }
        }
        this.swfPanels = [];
    },

    doPrev: function() {
        this.currentPage--;

        if (this.currentPage < 1) {
            this.currentPage = this.totalPages;
        }

        this.movePage("front");
        this.position = this.position + this.pageSize;

        if (this.isAnimationBroken()) { 
            this.container.style.left = this.position + "px";
            this.finishPrev();
        } else { 
            this.container.morph({left: (this.position + "px")}, {duration: 0.5,  transition: Effect.Transitions.sinoidal, afterFinish: this.finishPrev.bind(this)});
        }

    },
    doNext: function() {
        this.currentPage++;

        this.position = this.position - this.pageSize;
        this.movePage("back");

        if (this.isAnimationBroken()) { 
            this.container.style.left = this.position + "px";
            this.finishNext();
        } else { 
            this.container.morph({left: (this.position + "px")}, {duration: 0.5,  transition: Effect.Transitions.sinoidal, afterFinish: this.finishNext.bind(this)});
        }

        if (this.currentPage > this.totalPages) {
            this.currentPage = 1;
        }       

    },

    // wrapper functions to differ between user click and auto-rotate
    doClickPrev: function() {
        this.clearAutoScroll();
        this.doPrev();
    },

    doClickNext: function() {
        this.clearAutoScroll();
        this.doNext();
    },

    finishPrev: function() {
        Element.remove(this.container.lastChild);
    },

    finishNext: function() {
        this.position = this.position + this.pageSize;
        Element.remove(this.container.firstChild);
        this.container.setStyle({left: (this.position + "px")});
    },

    setAutoTimer: function() {
        if (this.autoScrollTimer) {
            clearInterval(this.autoScrollTimer);
        }
        if (this.options.autoScroll > 0) {
            this.autoScrollTimer = setInterval(this.doNext.bindAsEventListener(this), (this.options.autoScroll * 1000));
        }
    },

    clearAutoScroll: function() {
        this.options.autoScroll = 0;
        this.setAutoTimer();
    },

    // if the browser is FF on Mac or Linux, or Safari on Mac, then there is an animation bug.
    // Flash elements will not obey z-index while being animated from one position to another.
    // They do after stopping though. 
    // So if we find that browser and the slider includes flash panels, 
    // we flag it as 'broken' and we dont animate, 
    // we just move the panel into position.

    isAnimationBroken: function() {
        if ( (Prototype.Browser.WebKit && navigator.platform.include("Mac")) || 
             (Prototype.Browser.Gecko  && navigator.platform.include("Mac")) ||
             (Prototype.Browser.Gecko  && navigator.platform.include("Linux")) ) {
            if (this.container.select('.panelFlash').length >= 1) {
                return true;
            }
        }
        return false;
    }

}
