﻿/**
* @author Colin Bailey - using jquery 1.4 and sifr
* @updated by Simon Williams - 25/10/11
**/
(function ($) {
    $.fn.xmlSlideShow = function (options) {

        var blankgif = '/_layouts/ctassets/images/en-gb/backgrounds/blank.gif';
        var opts = $.extend({}, $.fn.xmlSlideShow.defaults, options);
        opts.global = {};
        opts.global.position = {};
        opts.global.tracking = {};
        opts.global.text = {};
        opts.global.text.title = {};
        opts.global.text.subTitle = {};
        opts.global.text.button = {};
        opts.global.text.tabTitle = {};
        opts.global.tabs = {};
        opts.banners = [];

        var element = $(this);
        var slides = $(this).find('.slide');
        var controller;
        var loop;
        var slideIndex = 0;
        var rotationCount = 0;
        var stopRotation = false;
        var replaceSifr;


        $(document).ready(function () {

            requestXml();

            function requestXml() {
                $.ajax({
                    type: "GET",
                    url: opts.xmlPath,
                    dataType: "xml",
                    success: function (xml) {
                        getGlobalOptions(xml);
                        getBannerOptions(xml);
                        buildElements();
                        replaceSifr = function () { };
                        $.each(opts.banners, function (index, banner) {
                            buildBanner(banner, index);
                        });
                        buildFinalElements();
                        if ($.browser.msie && $.browser.version < 7) {
                            $('.pngfix').each(function (index, element) {
                                var img = $(element);
                                src = img.attr('src');
                                img.attr('src', blankgif).css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + src + "')");
                            });
                            $('.blueButton li, .pngBack').each(function () {
                                $(this).attr('writing-mode', 'tb-rl');
                                var background = $(this).css('background-image').replace(/^url|[\(\)]/g, '');
                                $(this).css('background-image', 'none');
                                $(this).css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + background + ',sizingMethod="scale")');
                            });
                            $(slides.selector).hide();
                            $($(slides.selector)[slideIndex]).show();
                        }
                        else {
                            $(slides.selector).css('opacity', '0');
                            $($(slides.selector)[slideIndex]).css('opacity', '1');
                        }

                        $($(controller).find('li a')[slideIndex]).addClass('sel');
                        $(element.selector).css('visibility', 'visible');

                        if (opts.global.rotation == -1)
                            stopRotation = true;
                        else
                            $.fn.xmlSlideShow.play(opts.banners[0].interval);
                    }
                });
            }

            ////
            // Retrieves global properties from the xml document
            ////
            function getGlobalOptions(xml) {

                opts.global.date = $(xml).find('global date').attr('value');
                opts.global.rotation = parseInt($(xml).find('global rotation').attr('value'));
                opts.global.interval = parseInt($(xml).find('global interval').attr('value')) * 1000;
                opts.global.fadeSpeed = parseFloat($(xml).find('global fadeSpeed').attr('value'));

                opts.global.position.y = parseInt($(xml).find('global position').attr('y'));
                opts.global.position.x = parseInt($(xml).find('global position').attr('x'));

                opts.global.tracking.CT = $(xml).find('global trackingFormatCT').attr('value').replace("' + date + '", opts.global.date);
                opts.global.tracking.BV = $(xml).find('global trackingFormatBV').attr('value').replace("' + date + '", opts.global.date);

                opts.global.text.title.fontClass = $(xml).find('global textParameters title').attr('fontClass');
                opts.global.text.title.size = parseInt($(xml).find('global textParameters title').attr('size'));
                opts.global.text.title.color = $(xml).find('global textParameters title').attr('color');
                opts.global.text.title.colorOver = $(xml).find('global textParameters title').attr('colorOver');

                opts.global.text.subTitle.fontClass = $(xml).find('global textParameters subTitle').attr('fontClass');
                opts.global.text.subTitle.size = parseInt($(xml).find('global textParameters subTitle').attr('size'));
                opts.global.text.subTitle.color = $(xml).find('global textParameters subTitle').attr('color');
                opts.global.text.subTitle.colorOver = $(xml).find('global textParameters subTitle').attr('colorOver');

                opts.global.text.button.fontClass = $(xml).find('global textParameters ctaBtnLabel').attr('fontClass');
                opts.global.text.button.size = parseInt($(xml).find('global textParameters ctaBtnLabel').attr('size'));
                opts.global.text.button.color = $(xml).find('global textParameters ctaBtnLabel').attr('color');
                opts.global.text.button.colorOver = $(xml).find('global textParameters ctaBtnLabel').attr('colorOver');

                opts.global.text.tabTitle.fontClass = $(xml).find('global textParameters tabTitle').attr('fontClass');
                opts.global.text.tabTitle.size = parseInt($(xml).find('global textParameters tabTitle').attr('size'));
                opts.global.text.tabTitle.color = $(xml).find('global textParameters tabTitle').attr('color');
                opts.global.text.tabTitle.colorOver = $(xml).find('global textParameters tabTitle').attr('colorOver');

                opts.global.tabs.count = parseInt($(xml).find('global tabsVisibleNum').attr('value'));
                opts.global.tabs.width = parseInt($(xml).find('global tabsWidth').attr('value'));
                opts.global.tabs.align = $(xml).find('global tabsAlign').attr('value');
                opts.global.tabs.alpha = parseInt($(xml).find('global tabsAlpha').attr('value'));
            }

            ////
            // Retrieves banner properties from the xml document 
            ////
            function getBannerOptions(root) {
                var banners = {};
                var lowestBanner;
                var lastorder = -1;
                $(root).find('banner').each(function (index, xml) {

                    banner = {};
                    banner.name = $(xml).attr('name');
                    banner.order = parseInt($(xml).attr('order'));

                    banner.title = {};
                    var titleText = $(xml).find('title').text();
                    if (/<(\S+).*>(.*)<\/\1>/.test(titleText)) {
                        banner.title.text = $(titleText).html().trim();
                        banner.title.color = $(titleText).attr('color');
                    }
                    else
                        banner.title.text = titleText.trim();

                    if ($(xml).find('subTitle')) {
                        banner.subTitle = {}
                        var subTitleText = $(xml).find('subTitle').text();
                        if (/<(\S+).*>(.*)<\/\1>/.test(subTitleText)) {
                            banner.subTitle.text = $(subTitleText).html();
                            banner.subTitle.color = $(subTitleText).attr('color');
                        }
                        else
                            banner.subTitle.text = subTitleText;
                    }

                    banner.interval = parseInt($(xml).find('interval').attr('value')) * 1000;
                    banner.media = $(xml).find('fileLoc').attr('value');

                    banner.tracking = {};
                    banner.tracking.CT = opts.global.tracking.CT.replace("' + order + '", banner.order).replace("' + name + '", banner.name);
                    banner.tracking.BV = opts.global.tracking.BV.replace("' + order + '", banner.order).replace("' + name + '", banner.name);

                    banner.position = {}
                    banner.position.y = parseInt($(xml).find('position').attr('y'));
                    banner.position.x = parseInt($(xml).find('position').attr('x'));

                    banner.button = {};
                    banner.button.text = $(xml).find('ctaBtnLabel').text();
                    banner.button.href = $(xml).find('clickCTA').attr('url');
                    banner.button.target = $(xml).find('clickCTA').attr('target');

                    if ($(xml).find('offsetPositon') != null) {
                        banner.offset = {};
                        banner.offset.title = {};
                        banner.offset.title.x = $(xml).find('offsetPositon titleOffset').attr('x');
                        banner.offset.title.y = $(xml).find('offsetPositon titleOffset').attr('y');
                        banner.offset.subTitle = {};
                        banner.offset.subTitle.x = $(xml).find('offsetPositon subTitleOffset').attr('x');
                        banner.offset.subTitle.y = $(xml).find('offsetPositon subTitleOffset').attr('y');
                        banner.offset.button = {};
                        banner.offset.button.x = $(xml).find('offsetPositon ctaOffset').attr('x');
                        banner.offset.button.y = $(xml).find('offsetPositon ctaOffset').attr('y');
                    }
                    banners[index] = banner;
                });

                for (var i = 0; i < 8; i++) {
                    $.each(banners, function (index, element) {
                        if (element) {
                            if (lowestBanner && lowestBanner.order == lastorder) {
                                lowestBanner = null;
                            }
                            if ((!lowestBanner && lastorder == -1) || element.order > lastorder) {
                                if (!lowestBanner || lowestBanner.order > element.order) {
                                    lowestBanner = element;
                                }
                            }
                        }
                        else
                            lowestBanner = null;
                    });
                    if (lowestBanner) {
                        opts.banners[i] = lowestBanner;
                        lastorder = lowestBanner.order;

                    }
                }
            }

            ////
            // Appends the container elements to the DOM tree 
            ////
            function buildElements() {

                $(element.selector).addClass('xmlSlideShow');

                controller = $(document.createElement('ul')).attr({
                    'class': 'controller'
                }).appendTo($(element.selector));

                var leftLi = $(document.createElement('li')).attr({
                    'class': 'left'
                });

                $(document.createElement('img')).attr({
                    'alt': '',
                    'src': '/_layouts/ctassets/images/en-gb/backgrounds/main_promo_nav_left.png',
                    'class': 'pngfix'
                }).css({
                    'width': '12px',
                    'height': '23px'
                }).appendTo(leftLi);

                leftLi.appendTo($(controller));

                if (opts.swoosh) {
                    this.swoosh = $(document.createElement('img')).attr({
                        'src': opts.swoosh,
                        'class': 'swoosh pngfix'
                    }).appendTo($(element.selector));
                    if (opts.banners.length > 0) {
                        swoosh.bind('click', function () {
                            if (opts.banners[0].button.target == '_self')
                                window.location = opts.banners[0].button.href;
                            else
                                window.open(opts.banners[0].button.href);
                        });
                    }
                }
            };

            function buildFinalElements() {
                $($(controller).find('li a')[opts.banners.length - 1]).css('margin-right', 0);
                var rightLi = $(document.createElement('li')).attr({
                    'class': 'right'
                });

                $(document.createElement('img')).attr({
                    'alt': '',
                    'src': '/_layouts/ctassets/images/en-gb/backgrounds/main_promo_nav_right.png',
                    'class': 'pngfix'
                }).css({
                    'width': '12px',
                    'height': '23px'
                }).appendTo(rightLi);

                rightLi.appendTo($(controller));

                var clearLi = $(document.createElement('li')).attr({
                    'class': 'clear'
                });

                clearLi.appendTo($(controller));
            };

            ////
            // Appends the tab container to the slideshow container
            ////
            function buildTabs() {
                var tabs = $(document.createElement('ul')).attr({
                    'class': 'tabContainer'
                }).css({
                    'width': opts.global.tabs.width,
                    'opacity': opts.global.tabs.alpha,
                    'left': opts.global.tabs.align == 'left' ? 0 : '',
                    'right': opts.global.tabs.align == 'right' ? 0 : ''
                }).appendTo($(element.selector));
            }

            ////
            // Appends an individual slide to the slideshow container
            ////
            function buildBanner(properties, bannerIndex) {

                //Build slide show container div
                var bannerContainer = $(document.createElement('div')).attr({
                    'class': 'slide'
                }).appendTo($(element.selector));

                if (bannerIndex == 0)
                    bannerContainer.css('z-index', 5);

                //Add inner div to slide container
                var bannerInner = $(document.createElement('div')).attr({
                    'id': 'banner' + properties.order,
                    'class': 'slideInner'
                }).appendTo(bannerContainer);

                //Build and add image/flash to inner div
                var media;
                if ($.fn.xmlSlideShow.IsSwf(properties.media)) {
                    swfobject.embedSWF(properties.media, 'banner' + properties.order, '740', '264', '6.0.0', '', {}, { wmode: "transparent" }, {});
                }
                else {
                    media = $(document.createElement('img')).attr({
                        'src': properties.media,
                        'alt': properties.name
                    });
                    media.bind('click', function () {
                        if (properties.button.target == '_self') {
                            //pageTracker._trackPageview(properties.tracking.CT);
                            _gaq.push(['_trackPageview', properties.tracking.CT]);
                            setTimeout('window.location = "' + properties.button.href + '"', 100);
                            return false;
                        }
                        else {
                            //pageTracker._trackPageview(properties.tracking.CT);
                            _gaq.push(['_trackPageview', properties.tracking.CT]);
                            setTimeout('window.open("' + properties.button.href + '")', 100);
                            //return false;
                        }
                    });
                    media.appendTo(bannerInner);
                }


                //Create default holder for slide content
                var content = $(document.createElement('div')).attr({
                    'class': 'slideContent'
                }).css({
                    'left': (properties.position.x) ? properties.position.x : opts.global.position.x,
                    'top': (properties.position.y) ? properties.position.y : opts.global.position.y
                }).bind('click', function () {
                    if (properties.button.target == '_self') {
                        //pageTracker._trackPageview(properties.tracking.CT);
                        _gaq.push(['_trackPageview', properties.tracking.CT]);
                        setTimeout('window.location = "' + properties.button.href + '"', 100);
                        return false;
                    }
                    else {
                        //pageTracker._trackPageview(properties.tracking.CT);
                        _gaq.push(['_trackPageview', properties.tracking.CT]);
                        setTimeout('window.open(' + properties.button.href + ')', 100);
                        return false;
                    }
                }).appendTo(bannerInner);

                addTitle(content, properties);

                if (properties.subTitle)
                    addSubTitle(content, properties);

                //Add Button
                if (properties.button.text) {
                    var slideButtonContainer = $(document.createElement('ul')).attr({
                        'class': 'slideButton'
                    }).css({
                        'margin-left': (properties.offset) ? properties.offset.button.x + 'px' : 0,
                        'margin-top': (properties.offset) ? properties.offset.button.y + 'px' : 0
                    }).appendTo(content);

                    var leftLi = $(document.createElement('li')).attr({
                        'class': 'left'
                    });

                    $(document.createElement('img')).attr({
                        'alt': '',
                        'src': '/_layouts/ctassets/images/en-gb/backgrounds/blue_btn_left.png',
                        'class': 'pngfix'
                    }).css({
                        'width': '12px',
                        'height': '25px'
                    }).appendTo(leftLi)

                    leftLi.appendTo(slideButtonContainer);

                    var linkContainer = $(document.createElement('li')).attr('class', 'pngBack').appendTo(slideButtonContainer);

                    $(document.createElement('a')).attr({
                        'href': properties.button.href,
                        'target': properties.button.target,
                        'rel': properties.tracking.CT
                    }).css({
                        'font-size': opts.global.text.button.size + 'px',
                        'color': opts.global.text.button.color.replace('0x', '#')
                    }).bind('click', function () {
                        if (properties.button.target == '_self') {
                            //pageTracker._trackPageview(properties.tracking.CT);
                            _gaq.push(['_trackPageview', properties.tracking.CT]);
                            setTimeout('window.location = "' + properties.button.href + '"', 100);
                            return false;
                        }
                        else {
                            //pageTracker._trackPageview(properties.tracking.CT);
                            _gaq.push(['_trackPageview', properties.tracking.CT]);
                            setTimeout('window.open("' + properties.button.href + '")', 100);
                            return false;
                        }
                    }).hover(
                        function () {
                            $(this).css('color', opts.global.text.button.colorOver.replace('0x', '#'));
                        },
                        function () {
                            $(this).css('color', opts.global.text.button.color.replace('0x', '#'));
                        }).appendTo(linkContainer).html(properties.button.text);

                    var rightLi = $(document.createElement('li')).attr({
                        'class': 'right'
                    });

                    $(document.createElement('img')).attr({
                        'alt': '',
                        'src': '/_layouts/ctassets/images/en-gb/backgrounds/blue_btn_right.png',
                        'class': 'pngfix'
                    }).css({
                        'width': '17px',
                        'height': '25px'
                    }).appendTo(rightLi)

                    rightLi.appendTo(slideButtonContainer);
                }

                //Create controller item
                if (bannerIndex < opts.global.tabs.count) {
                    var controlContainer = $(document.createElement('li')).attr('class', 'control' + (bannerIndex + 1)).appendTo($(controller));
                    $(document.createElement('a')).bind('click', function () {
                        $.fn.xmlSlideShow.jump(bannerIndex);
                    }).html(bannerIndex + 1).appendTo(controlContainer);
                    if ($.browser.msie && $.browser.version < 7) {
                        controlContainer.addClass("text");
                    }
                }
            };
        });

        ////
        //Adds a banner title with Sifr replacement
        ////
        function addTitle(content, properties) {
            var titleId = 'xmlTitle' + properties.order;
            var headerTitle = $(document.createElement('span')).attr({
                'class': 'slideTitle',
                'id': titleId
            }).css({
                'font-size': opts.global.text.title.size + 'px',
                'color': (properties.title.color) ? properties.title.color : opts.global.text.title.color.replace('0x', '#'),
                'margin-left': (properties.offset) ? properties.offset.title.x + 'px' : 0,
                'margin-top': (properties.offset) ? properties.offset.title.y + 'px' : 0
            }).html(properties.title.text).appendTo(content);

            var flashColor = (properties.title.color) ? properties.title.color : opts.global.text.title.color.replace('0x', '#');
            if (typeof sIFR == "function")
                sIFR.replaceElement(named({ sSelector: ('#' + titleId), sFlashSrc: '/_layouts/CTAssets/Flash/en-GB/sifr_H1_v2.swf', sColor: flashColor, sLinkColor: flashColor, sBgColor: "transparent", sHoverColor: flashColor, nPaddingTop: 0, nPaddingBottom: 0, sWmode: "transparent", sFlashVars: ("textalign=left&amp;offsetTop=0") }));
        }

        ////
        //Adds a banner subtitle with Sifr replacement
        ////
        function addSubTitle(content, properties) {
            var subTitleId = 'xmlSubTitle' + properties.order;
            var headerSubTitle = $(document.createElement('span')).attr({
                'class': 'slideSubTitle',
                'id': subTitleId
            }).css({
                'font-size': opts.global.text.subTitle.size + 'px',
                'color': (properties.subTitle.color) ? properties.subTitle.color : opts.global.text.subTitle.color.replace('0x', '#'),
                'margin-left': (properties.offset) ? properties.offset.subTitle.x + 'px' : 0,
                'margin-top': (properties.offset) ? properties.offset.subTitle.y + 'px' : 0
            }).html(properties.subTitle.text).appendTo(content);

            var flashColor = (properties.subTitle.color) ? properties.subTitle.color : opts.global.text.subTitle.color.replace('0x', '#');
            if (typeof sIFR == "function")
                sIFR.replaceElement(named({ sSelector: ('#' + subTitleId), sFlashSrc: '/_layouts/CTAssets/Flash/en-GB/sifr_H1_v2.swf', sColor: flashColor, sLinkColor: flashColor, sBgColor: "transparent", sHoverColor: flashColor, nPaddingTop: 0, nPaddingBottom: 0, sWmode: "transparent", sFlashVars: ("textalign=left&amp;offsetTop=0&amp;color=" + properties.subTitle.color) }));
        }


        ////
        //Animates the banner transitions
        ////
        function animateSlides() {
            _gaq.push(['_trackPageview', opts.banners[slideIndex].tracking.BV]);
            if ($.browser.msie && $.browser.version < 7) {
                $(slides.selector).hide();
                $($(slides.selector)[slideIndex]).show();
            }
            else {

                $(slides.selector).stop().animate({ 'opacity': 0 }, 1000, 'swing', function () {
                    $(slides.selector).css('z-index', 1)
                });
                $($(slides.selector)[slideIndex]).stop().animate({ 'opacity': 1 }, 1000, 'swing', function () {
                    $($(slides.selector)[slideIndex]).css('z-index', 5);
                });
            }
            if (this.swoosh) {
                $(this.swoosh).unbind('click').bind('click', function () {
                    var anchor = $($(slides.selector)[slideIndex]).find('a');
                    if (anchor.attr('target') == '_self') {
                        //window.location = anchor.attr('href');
                        //pageTracker._trackPageview(anchor.attr('rel'));
                        _gaq.push(['_trackPageview', anchor.attr('rel')]);
                        setTimeout('window.location = "' + anchor.attr('href') + '"', 100);
                        return false;
                    }
                    else {
                        //window.open(anchor.attr('href'));
                        //pageTracker._trackPageview(anchor.attr('rel'));
                        _gaq.push(['_trackPageview', anchor.attr('rel')]);
                        setTimeout('window.open("' + anchor.attr('href') + '")', 100);
                        return false;
                    }
                });
            }




            $(controller).find('li a').removeClass('sel');
            $($(controller).find('li a')[slideIndex]).addClass('sel');

            if (stopRotation)
                $.fn.xmlSlideShow.stop();
            else
                $.fn.xmlSlideShow.play(opts.banners[slideIndex].interval);
        }


        ////
        //Shows the next slide in the show
        ////
        $.fn.xmlSlideShow.showNext = function () {
            if ((slideIndex == opts.banners.length - 1) && opts.global.rotation > 0) {
                rotationCount++;
                if (rotationCount == opts.global.rotation)
                    stopRotation = true;
            }

            if (slideIndex < $(slides.selector).length - 1)
                slideIndex++;
            else
                slideIndex = 0;
            animateSlides();
        };

        ////
        //Initialises the slideshow loop
        ////
        $.fn.xmlSlideShow.play = function (delay) {
            if (!delay)
                delay = opts.global.interval;
            $.fn.xmlSlideShow.stop();
            loop = setInterval(function () { $.fn.xmlSlideShow.showNext(); }, delay);
        };

        ////
        //Stops the slideshow
        ////
        $.fn.xmlSlideShow.stop = function () {
            clearInterval(loop);
            loop = null;
        };

        ////
        //Skips to a specific banner in the slideshow
        ////
        $.fn.xmlSlideShow.jump = function (jumpIndex) {
            this.stop();
            slideIndex = jumpIndex;
            if (opts.global.rotation != 0)
                stopRotation = true;
            animateSlides();
        };

        ////
        //Determines if a specified path is a swf object
        ////
        $.fn.xmlSlideShow.IsSwf = function (url) {
            return url.length >= 3 && url.substr(url.length - 3) == 'swf';
        }

        $.fn.xmlSlideShow.defaults = {};
    };
})(jQuery);

jQuery.fn.sortElements = (function () {

    var sort = [].sort;

    return function (comparator, getSortable) {

        getSortable = getSortable || function () { return this; };

        var placements = this.map(function () {

            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,

            // Since the element itself will change position, we have
            // to have some way of storing its original position in
            // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );

            return function () {

                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }

                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);

            };

        });

        return sort.call(this, comparator).each(function (i) {
            placements[i].call(getSortable.call(this));
        });

    };

})();
