Custom.Collections = {

    minDiscs: 7, // min number of discs to be present before switching to carousel
    imgPath: "/assets/img/collections/",
    imgPlatformPrefix: "logo_",
    platformID: "collectionPlatform",
    ratingClass: "discRating",
    linkImage: "collection_track_player_icon.gif",
    idKey: "discID",
    panelID: "collectionDetail",
    slideID: "collectionSlider",
    panelHeadID: "collectionDetailHead",
    triggerClass: "current",
    flashClass: "hasFlash",
    carouselID: "collectionCarousel",
    toggleSwitchId: "collectionsSwitch",
    toggleImgGrid: "collectionsview_grid.gif",
    toggleImgCarousel: "collectionsview_carousel.gif",
    carouselPath: "/assets/flash/CarouselApp.swf",
    carouselPlayerID: "carouselMovie",
    carouselPlayerWidth: 889,
    carouselPlayerHeight: 266,
    flashVersion: 8,
    noFlashMessage: '<p><a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW">Adobe Flash</a></p>',


    isFlash: function() {
        //detect if the user has at least the minimum version of Flash using SWFObject
        var instFlashVersion = deconcept.SWFObjectUtil.getPlayerVersion(Custom.Collections.flashVersion, false);
        if (instFlashVersion.major >= Custom.Collections.flashVersion) {
            return true;
        }
        return false;
    },
    getFlashData: function() {
        // Stringify the JSON data and send it to the Flash carousel for display
        return Json.toString(ssCollectionFlash);
    },
    insertFlash: function(initDisplay) {
        if (!Custom.Collections.carouselID) { return false }
        var carousel = new SWFObject(Custom.Collections.carouselPath, Custom.Collections.carouselPlayerID, Custom.Collections.carouselPlayerWidth, Custom.Collections.carouselPlayerHeight, Custom.Collections.flashVersion, "#FFFFFF", false);
        carousel.addVariable("image_path", ssCollectionFlash.discImgPath);
        carousel.addVariable("json_object", encodeURIComponent(Custom.Collections.getFlashData()));
        if (initDisplay) {
            carousel.addVariable('discID', initDisplay);
        }
        carousel.addParam("wmode", "transparent");
        carousel.write(Custom.Collections.carouselID);
        window.carouselMovie = document.getElementById('carouselMovie');
    },
    toggleView: function(initDisplay) {
        // check for presence of toggle switch
        // build switch
        // toggle views using .cont with additional class 'flashClass'
        // Identify holder for flash movie
        var contentHolder = $$('#collections .cont')[0];
        // Check for and build toggle
        if (!$(Custom.Collections.toggleSwitchId)) {
            var toggleShow = ssCollection.toggleStartView;
            //check for previous toggle state in querystring
            if (location.search.indexOf("toggleState=") != -1) {
                var togglePrevView = location.search.substring(location.search.indexOf("toggleState=") + 12);
            }
            var toggleHolder = $$('#collections .top .innerCont')[0];
            var togglePara = new Element('p');
            togglePara.id = Custom.Collections.toggleSwitchId;
            var toggleLink = new Element('a');
            toggleLink.href = '#';

            toggleLink.appendText(ssCollection.toggleText + " ")
            var toggleImg = new Element('img');
            toggleImg.src = Custom.Collections.imgPath + Custom.Collections.toggleImgCarousel;
            toggleImg.alt = (toggleShow == "Carousel") ? ssCollection.toggleTitleGrid : ssCollection.toggleTitleCarousel;
            toggleImg.width = '67';
            toggleImg.height = '19';
            toggleImg.injectInside(toggleLink);
            toggleLink.injectInside(togglePara);
            toggleLink.onclick = function() {
                Custom.Collections.toggleView(ssCollection.discs[0].discID);
                return false;
            }
            togglePara.injectInside(toggleHolder);
            // Keep track for later use
            Custom.Collections.toggle = togglePara;
            Custom.Collections.toggle.link = toggleLink;
            Custom.Collections.toggle.img = toggleImg;
            //set up links to carry current toggle state into url
            Custom.Collections.toggle.show = $pick(togglePrevView, toggleShow);
        }

        // Dump the info panel - avoids need for repositioning
        if ($(Custom.Collections.panelID)) {
            //save position of flash carousel
            if ($(Custom.Collections.carouselID) && Custom.Collections.toggle.show == "Grid") {
                Custom.Collections.activeDiscID = $('collectionDetailHead').getElement('h3').className.substring(5);
            }
            $(Custom.Collections.panelID).remove();
        }
        // Show/Hide views
        if (Custom.Collections.toggle.show == "Grid") {
            //WAS contentHolder.hasClass(Custom.Collections.flashClass)
            Custom.Collections.addToggleState($$('.collectionsFilter a'));
            var contentHolder = $$('#collections .cont')[0];
            contentHolder.removeClass('preJS');

            if ($(Custom.Collections.carouselID)) {
                if (window.ie) {
                    $(Custom.Collections.carouselID).setStyle('display', 'none');
                }
                else {
                    $(Custom.Collections.carouselID).setStyles({ 'textIndent': '-90000px', 'width': '0', 'height': '0', 'padding': '0' });
                }
            }
            contentHolder.removeClass(Custom.Collections.flashClass);
            if (initDisplay) {
                var gridLinks = $ES('a', contentHolder);
                var gridGoto = gridLinks.filter(function(gridLink) {
                    return gridLink.href.contains("discID=" + initDisplay);
                })[0];
                Custom.Collections.panelLinks(gridGoto);
                window.scrollTo(0, gridGoto.parentNode.parentNode.getCoordinates().top);
            }
            // Update toggle
            Custom.Collections.toggle.link.title = ssCollection.toggleTitleCarousel;
            Custom.Collections.toggle.img.src = Custom.Collections.imgPath + Custom.Collections.toggleImgGrid;
            Custom.Collections.toggle.img.alt = ssCollection.toggleAltGrid;
            Custom.Collections.toggle.show = "Carousel";
            Custom.doCapsuleHeights();
        } else {
            contentHolder.addClass(Custom.Collections.flashClass);
            Custom.Collections.addToggleState($$('.collectionsFilter a'));
            if (!$(Custom.Collections.carouselID)) {
                var carouselHolder = new Element('div');
                carouselHolder.id = Custom.Collections.carouselID;
                carouselHolder.innerHTML = Custom.Collections.noFlashMessage;
                carouselHolder.injectTop(contentHolder);
                // Insert flash carousel
                if (initDisplay) {
                    Custom.Collections.insertFlash(initDisplay);
                } else {
                    Custom.Collections.insertFlash();
                }
            }
            else {
                if (window.ie) {
                    $(Custom.Collections.carouselID).setStyle('display', 'block');
                }
                else {
                    $(Custom.Collections.carouselID).setStyles({ 'textIndent': '0', 'width': '950px', 'height': '266px', 'padding': '26px 30px 0' });
                }
            }
            Custom.Collections.toggle.show = "Grid";
            // Update toggle
            Custom.Collections.toggle.link.title = ssCollection.toggleTitleGrid;
            Custom.Collections.toggle.img.src = Custom.Collections.imgPath + Custom.Collections.toggleImgCarousel;
            Custom.Collections.toggle.img.alt = ssCollection.toggleAltCarousel;
            // Remove any link'tab' highlighting from Grid view
            if (Custom.Collections.currentTrigger) {
                Custom.Collections.currentTrigger.removeClass(Custom.Collections.triggerClass);
                Custom.Collections.currentTrigger.setStyle('background-color', 'transparent');
            }
            if (Custom.Collections.activeDiscID) {
                Custom.Collections.updatePanel(Custom.Collections.activeDiscID);
            }
        }

    },
    addToggleState: function(linksArray) {
        //add the existing toggle state to given hyperlinks so that the most recent toggle state can be picked up when the page refreshes
        linksArray.each(function(llink) {
            if (llink.href.indexOf("&toggleState=") != -1) {
                llink.href = llink.href.substring(0, llink.href.indexOf("&toggleState="));
            }
            //set up ? or & depending on whether there is already a querystring on the link href
            var appendQuery = (llink.search.length > 0) ? "&" : "?";
            //check for dynamically set toggle state, else set to grid
            var toggleState = (Custom.Collections.toggle) ? Custom.Collections.toggle.show : "Grid";
            llink.href += appendQuery + "toggleState=" + toggleState;
        });
    },
    populatePanel: function(discID, wrapperNode) {
        // update panel DOM with values for correct disc
        // and move it
        // moving is triggered by presence of wrapperNode

        // clear current cotent
        Custom.Collections.detailPanel.empty()
        // move the panel
        if (wrapperNode) { Custom.Collections.detailHolder.injectInside(wrapperNode); }
        // update content
        var discs = ssCollection.discs;
        // Clear this first so we dont get legacy colour values
        Custom.Collections.detailPanel.setStyle('background-color', 'transparent');
        discs.each(function(disc) {
        if (disc.discID == discID) {
                if (disc.discColour.length > 1)
                    Custom.Collections.detailPanel.setStyle('background-color', disc.discColour);
                    
                var discHead = new Element('div');
                discHead.id = Custom.Collections.panelHeadID;
                var discTitle = new Element('h3');
                discTitle.appendText(disc.discTitle.replace('&amp;', '&'));
                discTitle.addClass("disc_" + disc.discID);
                discTitle.injectInside(discHead);

                var discPlatform = new Element('p');
                discPlatform.addClass(Custom.Collections.platformID);
                var discPlatformImg = new Element('img');
                discPlatformImg.src = Custom.Collections.imgPath + Custom.Collections.imgPlatformPrefix + disc.discPlatform + ".gif";
                discPlatformImg.alt = disc.discPlatformAlt;
                discPlatformImg.injectInside(discPlatform);
                discPlatform.injectInside(discHead);

                var discRating = new Element('p');
                discRating.addClass(Custom.Collections.ratingClass);
                var discRatingLink = new Element('a');
                discRatingLink.href = disc.discRatingURL;
                if (disc.discRatingURL.indexOf("pegi.com") != -1) {
                    var pegiLang = ssCollection.cultureCode.substring(0, ssCollection.cultureCode.indexOf("-")).toLowerCase() + "/";
                    if (pegiLang == "nb") { pegiLang = "no"; } //handle bokmal(EPISERVER)/norwegian(PEGI) code differences.
                    discRatingLink.href = disc.discRatingURL//+pegiLang; - removed on request from Fab (dom)
                }
                discRatingLink.target = '_blank';
                var discRatingImg = new Element('img');
                discRatingImg.src = disc.discRatingImagePath;

                discRatingImg.alt = disc.discRatingText;
                discRatingImg.injectInside(discRatingLink);
                discRatingLink.injectInside(discRating);
                discRating.injectInside(discHead);

                var discExtract = new Element('p');
                discExtract.appendText(disc.discExtract.replace('&amp;', '&'));
                discExtract.injectInside(discHead);
                discHead.injectInside(Custom.Collections.detailPanel);

                var tracksTable = new Element('table');
                var tbdy = new Element('tbody');
                tracksTable.appendChild(tbdy);
                tracksTable.injectInside(Custom.Collections.detailPanel);

                // Build tracks table

                var tracks = disc.tracks;
                var maxTracks = Math.ceil(tracks.length / 3);
                var tracksPart1 = tracks.slice(0, maxTracks);
                var tracksPart2 = tracks.slice(maxTracks, maxTracks * 2);
                var tracksPart3 = tracks.slice(maxTracks * 2, maxTracks * 3);
                var trackParts = new Array(tracksPart1, tracksPart2, tracksPart3);
                var trackCount = 0;
                var row, cells;
                do {
                    row = new Element('tr');
                    if (trackCount % 2 == 0) { row.addClass('alt'); }
                    cells = [new Element('td'), new Element('td'), new Element('td')];
                    for (var i = 0; j = trackParts.length, i < j; i++) {
                        if (trackParts[i][trackCount]) { // check for empty cells
                            var trackArtist = new Element('strong');
                            trackArtist.appendText(unescape(trackParts[i][trackCount].trackArtist).replace('&amp;', '&'));
                            if (trackParts[i][trackCount].trackHref) {
                                var trackLink = new Element('a');
                                trackLink.href = trackParts[i][trackCount].trackHref;
                                // Dom added next 3 lines to make video work.
                                //Custom.Video.isSingStorePlayer=true;
                                Custom.Video.ajaxPath = Ajax_SongPlayer;
                                trackLink.addEvent('click', function(event) {
                                    event = new Event(event).stop();
                                    stringBits = Custom.getStringQueries(this.href);
                                    videoID = stringBits.song
                                    var remotePath = Custom.Video.ajaxPath + "?song=" + videoID + "&" + Custom.Locale.epsVarLang + "=" + LanguageContext;
                                    callback = function(videoID) {
                                        Custom.Video.handleLayout(videoID);
                                        $$(".playerActions img").addClass("hide");
                                    }
                                    Custom.Popup.open(remotePath, 'playerOverlay', 'cont', callback, videoID);
                                });
                                if (window.webkit) { trackLink.onclick = function() { return false; } } //safari
                                trackArtist.injectInside(trackLink);
                                trackLink.appendText(" - " + unescape(trackParts[i][trackCount].trackTitle).replace('&amp;', '&'));
                                var trackIcon = new Element('img');
                                trackIcon.src = Custom.Collections.imgPath + Custom.Collections.linkImage;
                                trackIcon.alt = ' ';
                                trackIcon.width = '14';
                                trackIcon.height = '9';
                                trackIcon.injectInside(trackLink);
                                trackLink.injectInside(cells[i]);
                            } else {
                                trackArtist.injectInside(cells[i]);
                                cells[i].appendText(" - " + unescape(trackParts[i][trackCount].trackTitle))
                            }
                        }
                        cells[i].injectInside(row);
                    }
                    row.injectInside(tbdy);
                    trackCount++;
                } while (tracksPart1[trackCount] != null)

            }
        });
    },
    updatePanel: function(discID, trigger) {
        // create initial DOM node
        // handle transitions
        // call populatePanel() to update content
        // Keep track of these here for scope reasons

        //if tracker is undefined, then the trigger is the flash movie, however if toggle.show is carousel then user has switched to grid view.  this prevents carousel's panel showing if user switches early.
        if (!$chk(trigger) && Custom.Collections.toggle.show == "Carousel") {
            Custom.Collections.activeDiscID = discID;
            return;
        }
        Custom.Collections.trackerDiscID = discID;
        Custom.Collections.trackerTrigger = trigger;
        // if no panel, create in DOM
        if (!$(Custom.Collections.panelID)) {
            var detailWrapper = new Element('div');
            detailWrapper.id = Custom.Collections.panelID;

            var detailSlide = new Element('div');
            detailSlide.id = Custom.Collections.slideID;
            detailSlide.injectInside(detailWrapper);

            var initialHolder = $$('#collections .cont')[0];
            detailWrapper.injectInside(initialHolder);

            Custom.Collections.detailHolder = detailWrapper;
            Custom.Collections.detailPanel = detailSlide;

            Custom.Collections.trackSlide = new Fx.Slide(detailSlide.id, { duration: 400 });
            Custom.Collections.trackSlide.hide();

            // On Slide complete check if we need to slide it back in
            Custom.Collections.trackSlide.addEvent('onComplete', function() {
                // Check if slide div is hidden. If true re-populate and slide in
                if (Custom.Collections.trackSlide.wrapper.getStyle('height') == "0px") {
                    if (trigger) {
                        // Grid view
                        Custom.Collections.populatePanel(Custom.Collections.trackerDiscID, Custom.Collections.trackerTrigger.parentNode.parentNode.parentNode);
                        Custom.Collections.panelLinkHighlight(Custom.Collections.trackerDiscID, Custom.Collections.trackerTrigger);
                    } else {
                        // Carousel view
                        Custom.Collections.populatePanel(Custom.Collections.trackerDiscID);
                    }
                    Custom.Collections.trackSlide.slideIn();
                    
                    //Web Trends tracking
                    if (typeof(dcsMultiTrack) != 'undefined')
                        dcsMultiTrack('DCS.dcsuri', 'discID=' + Custom.Collections.trackerDiscID);
                }
            }
			);
        }
        // Slide out panel - no transition if first call as is hidden
        Custom.Collections.trackSlide.slideOut();

    },
    panelLinkHighlight: function(discID, trigger) {
        // Switch trigger block colours in panel view
        if (Custom.Collections.currentTrigger) {
            Custom.Collections.currentTrigger.removeClass(Custom.Collections.triggerClass);
            Custom.Collections.currentTrigger.setStyle('background-color', 'transparent');
        }
        Custom.Collections.currentTrigger = trigger.parentNode.parentNode;
        Custom.Collections.currentTrigger.addClass(Custom.Collections.triggerClass);
        var discs = ssCollection.discs;
        discs.each(function(disc) {
            if (disc.discID == discID && disc.discColour.length > 1) {
                Custom.Collections.currentTrigger.setStyle('background-color', disc.discColour);
            }
        });
    },
    panelLinks: function(trigger) {
        // Interim step
        // call panel update
        var stringBits = Custom.getStringQueries(trigger.href);
        if (stringBits.discID) {
            Custom.Collections.updatePanel(stringBits.discID, trigger);
        }
    },
    setupLinks: function(initDisplay) {
        // find all links and assign function for click event
        triggers = $$('#collections .capPart h2 a', '#collections .capPart p.tracksTrigger a');
        triggers.each(function(trigger) {
            trigger.addEvent('click', function(event) {
                event = new Event(event).stop();
                Custom.Collections.panelLinks(this);
            });
            if (window.webkit) { trigger.onclick = function() { return false; } } //safari
            // Show initialDisplay disc immediately
            if (initDisplay) {
                if (trigger.href.contains("discID=" + initDisplay)) {
                    Custom.Collections.panelLinks(trigger);
                    window.scrollTo(0, trigger.parentNode.parentNode.getCoordinates().top);
                }
            }
        });
    },
    //looks for text in discNew (new, coming soon, etc) and inserts that text into the disc capsule
    showdiscNewFlag: function() {
        var discs = ssCollection.discs;
        discs.each(function(disc) {
            if (disc.discNew == "") { return false; }
            var discFlag = new Element("div");
            discFlag.className = "discFlag";
            var discFlagText = document.createTextNode(disc.discNew);
            discFlag.appendChild(discFlagText);
            var discIDLinks = $$('h2 a');
            discIDLinks.filter(function(discIDLink) {
                if (discIDLink.href.contains(disc.discID)) {
                    discFlag.injectInside(discIDLink.parentNode);
                    discIDLink.parentNode.parentNode.addClass("new");
                }
            });
        });
    },
    doCollection: function() {
        // get query string to check for discID
        var query = Custom.getStringQueries(unescape(location.search));
        Custom.Collections.showdiscNewFlag();
        var initialDiscID = ssCollection.discs[0].discID;
        if (query && query.discID) initialDiscID = query.discID;
        if (initialDiscID) {
            if (Custom.Collections.isFlash() && ssCollection.discs.length >= Custom.Collections.minDiscs) {
                // Show flash(+specified disc) and populate grid behaviours
                Custom.Collections.toggleView(initialDiscID);
                Custom.Collections.setupLinks();
            } else {
                // Populate grid behaviour and show specified disc
                Custom.Collections.setupLinks(initialDiscID);
                Custom.doCapsuleHeights();
                var contentHolder = $$('#collections .cont')[0];
                contentHolder.removeClass('preJS');
                Custom.Collections.addToggleState($$('.collectionsFilter a'));
            }
        } else {
            if (Custom.Collections.isFlash() && ssCollection.discs.length >= Custom.Collections.minDiscs) {
                Custom.Collections.toggleView();
            }
            else {
                Custom.doCapsuleHeights();
                var contentHolder = $$('#collections .cont')[0];
                contentHolder.removeClass('preJS');
                Custom.Collections.addToggleState($$('.collectionsFilter a'));
            }
            Custom.Collections.setupLinks();
        }

    }

}/* /Custom.Collections */

window.addEvent('domready', Custom.Collections.doCollection);