﻿/////////////////////
/// StringBuilder ///
/////////////////////
function StringBuilder() {
    this.buffer = new Array();
    this.Append = function append(string) { this.buffer.push(string); };
    this.ToString = function toString() { return this.buffer.join(''); };
}

////////////////////////////
/// RssRegistrationPopup ///
////////////////////////////
var RssRegistrationPopup = new Class({
    initialize: function(openButtonId, closeButtonId, divPopupId) {
        if (!openButtonId || !closeButtonId || !divPopupId) { return; }
        this.openButton = $(openButtonId);
        this.divPopup = $(divPopupId);
        this.closeButton = $(closeButtonId);

        if (!this.openButton || !this.closeButton || !this.divPopup) { return; }

        this.openned = false;

        this.originalHeight = this.divPopup.getSize().y;
        this.expendEffect = new Fx.Morph(this.divPopup, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });

        this.openButton.addEvent('click', this.show.bind(this));
        this.closeButton.addEvent('click', this.hide.bind(this));
        this.divPopup.setStyle('height', '0px');
    },
    show: function() {
        if (!this.openned) {
            //this.divPopup.setStyle('display', '');
            this.expendEffect.start({
                'height': this.originalHeight //Morphs the 'height' style from current to 0px.
            });
            this.openned = true;
        }
    },
    hide: function() {
        if (this.openned) {
            //this.divPopup.setStyle('display', 'none');
            this.expendEffect.start({
                'height': '0px' //Morphs the 'height' style from current to 0px.
            });
            this.openned = false;
        }
    }
});

///////////////////////
/// PlayAudioButton ///
///////////////////////
var PlayAudioButton = new Class({
    initialize: function(buttonId, audioFileUrl) {
        if (!buttonId || !audioFileUrl) { return; }
        this.button = $(buttonId);

        if ($chk(this.button)) {
            this.button.addEvent('click', function() {
                this.button.removeEvents('click');
                this.button.addClass('iocAudioButtonDisabled');

                var divAudioContainerId = buttonId + '_AudioContainer';
                var divAudioContainer = new Element('div', { 'id': divAudioContainerId });
                divAudioContainer.inject(this.button.getParent());

                showAudioPlayer(divAudioContainerId, 'small', audioFileUrl);
            } .bind(this));
        }
    }
});

///////////////////////
/// ShowVideoPlayer ///
///////////////////////
function showVideoPlayer(containerId, videoThumbnail, videoCurrentLow, videoCurrentHigh, videoCurrentHD) {
    if (!containerId || !videoThumbnail || (!videoCurrentLow && !videoCurrentHigh && !videoCurrentHD))
    { return; }

    var params = {
        salign: "TL",
        loop: "false",
        quality: "high",
        allowFullScreen: "true",
        allowScriptAccess: "always",
        wmode: "transparent"
    };

    var flashvars = {
        videoCurrentThumbnail: videoThumbnail,
        videoCurrentLow: videoCurrentLow,
        videoCurrentHigh: videoCurrentHigh,
        videoCurrentHD: videoCurrentHD,
        autoPlay: "true",
        videoPlayerLangCode: "en_GB",
        onPlay: "onPlay"
    };

    return swfobject.embedSWF("/Resources/Flash/RIA/VideoPlayer/moduleRIA-videoplayer.swf", containerId, "480", "360", "9.0.0", "", flashvars, params, null);
}


///////////////////////
/// ShowAudioPlayer ///
///////////////////////
function showAudioPlayer(containerId, size, audioFileUrl) {
    if (!containerId || !size || !audioFileUrl) { return; }

    var params = {
        audioFileUrl: 'always',
        loop: 'false',
        quality: 'high',
        salign: 'TL',
        allowFullScreen: 'true',
        wmode: 'transparent'
    };

    var flashvars = { soundUrl: audioFileUrl };

    if (size == 'small') {
        swfobject.embedSWF("/Resources/Flash/RIA/AudioPlayer/soundPlayer_small.swf", containerId, "320", "40", "9.0.0", "", flashvars, params, null);
    }
    else if (size == 'big') {
        swfobject.embedSWF("/Resources/Flash/RIA/AudioPlayer/soundPlayer.swf", containerId, "375", "40", "9.0.0", "", flashvars, params, null);
    }
}

//////////////////////////
/// Participate Button ///
//////////////////////////

var ParticipateButton = new Class({
    initialize: function(buttonId, statisticAccessClient, counterId, counterDomId) {
        if (!buttonId || !statisticAccessClient || !counterId || !counterDomId) { return; }
        this.button = $(buttonId);
        if (!this.button) { return; }

        this.counterDom = $(counterDomId);
        if (!this.counterDom) { return; }

        if (statisticAccessClient.wasCounterIncremented(counterId)) {
            this.disableButton();
        }
        else {
            statisticAccessClient.addEvent('counterIncremented', function(counterId) {
                this.disableButton();
            } .bind(this));

            this.button.addEvent('click', function() {
                var currentCounterValue = parseInt(this.counterDom.innerHTML);
                this.counterDom.innerHTML = currentCounterValue + 1;

                statisticAccessClient.incrementCounter(counterId);
                this.button.removeEvents('click');
            } .bind(this));
        }
    },
    disableButton: function() {
        this.button.addClass('iocParticipateDisabled');
    }
});

///////////////////////
/// CustomValidator ///
///////////////////////
var CustomValidator = new Class({
    initialize: function(textControlId, validMessageControlId, invalidMessageControlId, regularExpression) {

        if (!textControlId || !validMessageControlId || !invalidMessageControlId || !regularExpression) { return; }

        this.textControl = $(textControlId);
        this.validMessageControl = $(validMessageControlId);
        this.invalidMessageControl = $(invalidMessageControlId);
        this.regularExpression = regularExpression;

        if (!this.textControl || !this.validMessageControl || !this.invalidMessageControl) { return; }

        this.textControl.addEvent('keyup', this.check.bind(this));
    },
    check: function(e) {
        if (!this.textControl.value.test(this.regularExpression)) {
            this.invalidMessageControl.setStyle('display', 'block');
            this.invalidMessageControl.setStyle('visibility', 'visible');
            this.validMessageControl.setStyle('display', 'none');
        }
        else {
            this.validMessageControl.setStyle('visibility', 'visible');
            this.validMessageControl.setStyle('display', 'block');
            this.invalidMessageControl.setStyle('display', 'none');
        }
    }
});

//////////////////////
/// TextBoxClearer ///
//////////////////////
var TextBoxClearer = new Class({
    initialize: function(textBoxControlId) {
        if (!textBoxControlId) { return; }
        this.textBoxControl = $(textBoxControlId);

        if (!this.textBoxControl) { return; }

        if (this.textBoxControl.value.length > 0) {
            this.originalText = this.textBoxControl.value;
        }

        this.textBoxControl.addEvent('click', this.onClick.bind(this));
    },
    onClick: function() {
        if (this.textBoxControl.value == this.originalText) {
            this.textBoxControl.value = '';
        }
    },
    reset: function() {
        this.textBoxControl.value = this.originalText;
    }
});



////////////////////////
/// element.InnerXML ///
////////////////////////
Element.implement({
    innerXML: function(options) {
        var str = new String();
        if (this.childNodes.length) {
            str += '<' + this.tagName.toLowerCase() + this.attributs(options) + '>';
            // If the tag is a child node, we get it's content as XML, otherwise we get the text content
            for (var t = 0; t < this.childNodes.length; t++) {
                if (this.childNodes[t].tagName && this.childNodes[t].tagName != "!") {
                    var myElement = $(this.childNodes[t]);
                    if (myElement) {
                        str += myElement.innerXML(options);
                    }
                }
                else {
                    str += this.childNodes[t].nodeValue;
                }
            }
            // We close the element
            str += '</' + this.tagName.toLowerCase() + '>';
        }
        else {
            str += '<' + this.tagName.toLowerCase() + this.attributs(options) + ' />';
        }
        return str;
    },
    attributs: function(options) {
        var str = new String();
        if (options) {
            for (i = 0; i < options.attributes.length; i++) {
                str += ' ' + options.attributes[i] + '="' + this.getProperty(options.attributes[i]) + '"';
            }
        }
        else {
            for (var t = 0; t < this.attributes.length; t++) {
                // Specific IE test to remove empty attributes (like most of events and attributes specific to IE)
                if (
				this.attributes[t].nodeValue
				&& this.attributes[t].nodeValue != 'inherit'
				&& this.attributes[t].nodeName != 'match'
				&& this.attributes[t].nodeName != 'uid'
				&& this.attributes[t].nodeName.indexOf('$') == -1
				&& !this.attributes[t].nodeValue.prototype
				&& (typeof this.attributes[t].nodeValue == "string" && this.attributes[t].nodeValue.indexOf('function') == -1)
				) {
                    str += ' ' + this.attributes[t].nodeName.toLowerCase() + '="' + this.attributes[t].nodeValue + '"';
                }
            }
        }
        return str;
    }

});

////////////////////////
/// Generic Carousel ///
////////////////////////
var jsIocRiaGenericCarousel = new Class({
    Implements: Events,
    Extends: MooScroller,
    morphFx1: null,
    morphFx2: null,
    morphFx3: null,
    initialize: function(content, knob, options) {
        this.setOptions(options);
        this.horz = (this.options.mode == "horizontal");

        this.content = $(content).setStyle('overflow', 'hidden');
        this.ulContent = this.content.getFirst();
        this.liItems = this.ulContent.getChildren('li');

        this.knob = $(knob);
        this.track = this.knob.getParent();
        this.setPositions();

        if (this.horz && this.options.width) {
            this.wrapper = new Element('div');
            this.content.getChildren().each(function(child) {
                this.wrapper.adopt(child);
            });
            this.wrapper.injectInside(this.content).setStyle('width', this.options.width);
        }


        this.bound = {
            'start': this.start.bind(this),
            'end': this.end.bind(this),
            'drag': this.drag.bind(this),
            'wheel': this.wheel.bind(this),
            'page': this.page.bind(this)
        };

        this.position = {};
        this.mouse = {};
        this.update();
        this.attach();

        var clearScroll = function() {
            $clear(this.scrolling);
        } .bind(this);

        ['forward', 'back'].each(function(direction) {
            var lnk = $(this.options.scrollLinks[direction]);
            if (lnk) {
                lnk.addEvents({
                    mouseover: function() {
                        lnk.getElement('img').setProperty('src', '/Resources/Images/RIA/GenericCarousel/generic-carousel-' + direction + '-arrow-roll.gif');
                    } .bind(this),
                    mouseout: function() {
                        lnk.getElement('img').setProperty('src', '/Resources/Images/RIA/GenericCarousel/generic-carousel-' + direction + '-arrow.gif');
                    } .bind(this),
                    click: this[direction].bind(this, this.options.scrollSteps)
                });
            }
        }, this);
        this.knob.addEvent('click', clearScroll.bind(this));
        window.addEvent('load', function() {
            try {
                $(document.body).addEvent('mouseup', clearScroll.bind(this));
            } catch (e) { }
        } .bind(this));

        window.fireEvent('jsIocRiaGenericCarouselInitialized', this);
    },
    makeThumbBack: function() {
        if (this.morphFx1) this.morphFx1.cancel();
        if (this.morphFx2) this.morphFx2.cancel();
        if (this.morphFx3) this.morphFx3.cancel();

        var len = this.liItems.length;
        for (index = 0; index < len; index++) {
            var item = this.liItems[index];
            var display = item.style.display;
            item.removeProperty('style');
            item.style.display = display;

            var img = item.getElement('img');
            if ($chk(img)) {
                img.erase('style');
                img.setStyles({
                    'width': '86px',
                    'height': this.options.imageThumbnailHeight
                });
            }

            var link = item.getElement('a');
            if ($chk(link)) {
                link.erase('style');
                link.setStyles({
                    'width': '86px',
                    'height': this.options.imageThumbnailHeight
                });
            }
        }

        this.ulContent.setStyle('margin-left', '219px');
    },
    makeThumbUp: function() {
        ['forward', 'back'].each(function(direction) {
            var lnk = $(this.options.scrollLinks[direction]);
            if (lnk) {
                lnk.removeEvents('click');
            }
        } .bind(this));

        var visibleCounter = 0;

        var len = this.liItems.length;
        for (index = 0; index < len; index++) {
            var item = this.liItems[index];
            var display = item.style.display;
            item.removeProperty('style');
            item.style.display = display;

            if (display != 'none') {
                itemX = (visibleCounter * 92) - this.content['scrollLeft'] + 219;
                if (itemX < 290 && (itemX + 92) > 290) {
                    this.content['scrollLeft'] += itemX - 247;
                    item.setStyles({
                        'z-index': '1'
                    });

                    var link = item.getElement('a');
                    if ($chk(link)) {
                        this.morphFx1 = new Fx.Morph(link, {
                            duration: 700,
                            transition: Fx.Transitions.Sine.easeInOut
                        });
                        this.morphFx1.start({
                            'width': '140px',
                            'height': this.options.imageHeight,
                            'padding': '0 2px 0 2px',
                            'margin-top': '-27px'
                        });
                    }

                    var img = item.getElement('img');
                    if ($chk(img)) {
                        this.morphFx2 = new Fx.Morph(img, {
                            duration: 700,
                            transition: Fx.Transitions.Sine.easeInOut,
                            onComplete: function() {
                                ['forward', 'back'].each(function(direction) {
                                    var lnk = $(this.options.scrollLinks[direction]);
                                    if (lnk) {
                                        lnk.addEvent('click', this[direction].bind(this, this.options.scrollSteps));
                                    }
                                } .bind(this));
                            } .bind(this)
                        });
                        this.morphFx2.start({
                            'width': '140px',
                            'height': this.options.imageHeight
                        });
                    }

                    if ($(item.getPrevious())) {
                        this.morphFx3 = new Fx.Morph(this.ulContent, {
                            duration: 700,
                            transition: Fx.Transitions.Sine.easeInOut
                        });
                        this.morphFx3.start({
                            'margin-left': (this.ulContent.getStyle('margin-left').toInt() - 33) + 'px'
                        });
                    }
                }

                visibleCounter++;
            }
        }

        this.initializeMouseEvents();
    },
    makeThumbBackAndUp: function() {
        this.makeThumbBack();
        this.makeThumbUp();
    },
    start: function(event) {
        event = new Event(event);
        var axis = this.horz ? 'x' : 'y';
        this.mouse.start = event.page[axis];
        this.position.start = this.knob.getStyle(this.horz ? 'left' : 'top').toInt();
        document.addEvent('mousemove', this.bound.drag);
        document.addEvent('mouseup', this.bound.end);
        this.knob.addEvent('mouseup', this.bound.end);
        this.makeThumbBack();
        this.content.getElements('li').each(function(item, index) {
            item.removeEvents();
        });
        event.stop();
    },
    end: function(event) {
        event = new Event(event);
        document.removeEvent('mousemove', this.bound.drag);
        document.removeEvent('mouseup', this.bound.end);
        this.knob.removeEvent('mouseup', this.bound.end);
        this.makeThumbUp();
        event.stop();
    },
    initializeMouseEvents: function() {
        var len = this.liItems.length;
        var imageHeight = this.options.imageHeight;
        for (index = 0; index < len; index++) {
            var item = this.liItems[index];
            item.removeEvents();
            itemX = (index * 92) - this.content['scrollLeft'] + 219;
            if (!(itemX < 290 && (itemX + 92) > 290)) {
                var link = item.getElement('img');
                if ($chk(link)) {
                    link.addEvent('mouseover', function() {
                        if (this.getStyle('height') != imageHeight) {
                            this.setStyle('margin-top', '-5px');
                        }
                    });
                }
            }
            var link = item.getElement('img');
            if ($chk(link)) {
                link.addEvent('mouseout', function() {
                    if (this.getStyle('height') != imageHeight) {
                        this.setStyle('margin-top', '0');
                    }
                });
            }
        }
    },
    forward: function(steps) {
        this.makeThumbBack();
        steps = steps || this.options.scrollSteps;
        this.scroll(steps);
        this.makeThumbUp();
    },
    back: function(steps) {
        this.makeThumbBack();
        steps = steps || this.options.scrollSteps;
        this.scroll(-steps);
        this.makeThumbUp();
    }
});

function InitCarousel(carouselId, showArrows, leftText, rightText, imageHeight, imageThumbnailHeight, startPos) {
    if (!carouselId) { return; }
    var item = $(carouselId);
    if (!item) { return; }
    item.className = "iocRiaGenericCarousel horzscroller";
    var scrollarea = new Element('div', { 'class': 'scrollarea' });

    if ($chk(leftText)) {
        var leftTextElement = new Element('div', { 'class': 'scrollLeftText' });
        leftTextElement.innerHTML = leftText;
        leftTextElement.inject(scrollarea);
    }

    if ($chk(showArrows)) {
        var scrollBackElement = new Element('div', { 'class': 'scrollBack' });
        scrollBackElement.innerHTML = '<img src="/Resources/Images/RIA/GenericCarousel/generic-carousel-back-arrow.gif" alt="">';
        scrollBackElement.inject(scrollarea);
    }

    var scrollBarContainerElement = new Element('div', { 'class': 'scrollBarContainer' });
    scrollBarContainerElement.inject(scrollarea);
    var scrollBarBackgroundElement = new Element('div', { 'class': 'scrollBarBackground' });
    scrollBarBackgroundElement.inject(scrollBarContainerElement);
    var scrollKnobElement = new Element('div', { 'class': 'scrollKnob' });
    scrollKnobElement.innerHTML = '<img src="/Resources/Images/RIA/GenericCarousel//generic-carousel-knobcenter.gif"/>';
    scrollKnobElement.inject(scrollBarBackgroundElement);

    if ($chk(showArrows)) {
        var scrollForwardElement = new Element('div', { 'class': 'scrollForward' });
        scrollForwardElement.innerHTML = '<img src="/Resources/Images/RIA/GenericCarousel/generic-carousel-forward-arrow.gif" alt="">';
        scrollForwardElement.inject(scrollarea);
    }

    if ($chk(rightText)) {
        var rightTextElement = new Element('div', { 'class': 'scrollRightText' });
        rightTextElement.innerHTML = rightText;
        rightTextElement.inject(scrollarea);
    }

    item.appendChild(scrollarea);
    var content_width = item.getElements('div.iocRiaContent ul li').length * 92 + 275;
    item.getElements('ul').setStyle('margin-left', "219px");

    item.getElements('div.iocRiaContent ul')[0].setStyle('width', content_width + "px");

    var myCarousel = new jsIocRiaGenericCarousel(item.getElements('div.iocRiaContent')[0], item.getElements('div.scrollKnob')[0], {
        mode: 'horizontal',
        wheel: false,
        scrollSteps: 50,
        scrollLinks: {
            forward: item.getElements('div.scrollForward')[0],
            back: item.getElements('div.scrollBack')[0]
        },
        imageHeight: imageHeight,
        imageThumbnailHeight: imageThumbnailHeight,
        onPage: function() {
            this.makeThumbBackAndUp();
        }
    });


    myCarousel.position.now = myCarousel.trackSize - (myCarousel.knobSize + 2);

    if (!$chk(startPos) || startPos == 'right') {
        myCarousel.content['scrollLeft'] = myCarousel.position.now * myCarousel.scrollRatio;
        myCarousel.knob.setStyle('left', myCarousel.position.now + 'px');
    }
    else if (startPos == 'center') {
        myCarousel.content['scrollLeft'] = myCarousel.position.now * myCarousel.scrollRatio / 2;
        myCarousel.knob.setStyle('left', myCarousel.position.now / 2 + 'px');
    }

    myCarousel.makeThumbUp();
}

//////////////////////
/// MediaSlideShow ///
//////////////////////
function AddMediaSlideShow(containerId, rowNumber) {

    if (!containerId) { return; }
    var item = $(containerId);
    if (!item) { return; }

    item.rowNumber = 1;

    if ($chk(rowNumber) && rowNumber != 0) {
        item.rowNumber = rowNumber;
    }

    var addToPlayListMask = new Element('span', { 'class': 'iocRiaMask' });
    addToPlayListMask.addEvent('click', function() { this.dispose(); });
    var carousel_length = item.getElements('li').length;
    item.getElements('div.iocRiaContent ul li').each(function(item, index) {
        item.getElement('span.iocRiaThumbnail').addEvents({
            'mouseenter': function() {
                //Modification of the properties
                this.getElement('img').setStyle('border', 'solid 1px black');
                this.getNext().getFirst().className = "iocRiaLegend_hover";
            },

            'mouseleave': function() {
                //Modification of the properties
                this.getElement('img').removeProperty('style');
                this.getNext().getFirst().className = "iocRiaLegend";
                this.getNext().getFirst().getFirst().className = "";
            }
        });
        item.getElement('span.iocRiaLegend').addEvents({
            'mouseenter': function() {
                this.getParent().getParent().getElement('img').setStyle('border', 'solid 1px black');
                this.className = "iocRiaLegend_hover";
            },
            'mouseleave': function() {
                this.getParent().getParent().getElement('img').removeProperty('style');
                this.className = "iocRiaLegend";
                this.getFirst().className = "";
            }
        });
        if ($('span.iocRiaAddToPlayList')) {
            item.getElement('span.iocRiaAddToPlayList').addEvent('click', function() {

                if (IsMediaInPlaylist(item.id, true)) {
                    addToPlayListMask.innerHTML = "<span>" + iocRiaCloseText + "</span><p>" + iocRiaNoticeKO + "</p>";
                }
                else {
                    addToPlayListMask.innerHTML = "<span>" + iocRiaCloseText + "</span><p>" + iocRiaNoticeOK + "</p>";
                }
                addToPlayListMask.inject(item, 'bottom');

                var totalHeight = 0;
                var iocRiaSlideShowTextTop = item.getElement('.iocRiaSlideShowText').getPosition(item).y;
                var iocRiaSlideShowTextHeight = item.getElement('.iocRiaSlideShowText').getSize().y;
                var iocRiaThumbnailTop = item.getElement('span.iocRiaThumbnail').getPosition(item).y;
                var iocRiaThumbnailHeight = item.getElement('span.iocRiaThumbnail').getSize().y;

                if (iocRiaSlideShowTextTop == iocRiaThumbnailTop) {
                    totalHeight = iocRiaThumbnailHeight;
                }
                else {
                    totalHeight = iocRiaThumbnailHeight + iocRiaSlideShowTextHeight;
                }

                addToPlayListMask.setStyles({
                    'opacity': '0.9',
                    'margin-top': -totalHeight + "px"
                });

                addToPlayListMask.getElement('p').setStyles({
                    'margin-top': addToPlayListMask.getSize().y / 2 - (addToPlayListMask.getElement('p').getSize().y / 2) - addToPlayListMask.getElement('span').getSize().y + "px"
                });
                return false;
            });
        }
    });

    var liElementsCount = item.getElements('div.iocRiaContent ul li').length;
    var liElementWidth = item.getElement('li').getSize().x;
    var rowNumber = item.rowNumber;

    //this makes sure we have got a mutiple of the number of rows to be able to retrieve the correct width.
    if (liElementsCount % rowNumber != 0) {
        liElementsCount += liElementsCount % rowNumber;
    }

    scroller_length = liElementsCount * liElementWidth / rowNumber;
    if (scroller_length < item.getElement('.iocRiaContent').getSize().x) {
        scroller_length = item.getElement('.iocRiaContent').getSize().x;
    }

    if (scroller_length.toInt() > item.getStyle('width').toInt()) {
        item.getElement('div.iocRiaContent ul').setStyle('width', scroller_length + "px");
        var scrollarea = new Element('div', { 'class': 'scrollarea' });
        scrollarea.innerHTML = '<div style="position: relative;" class="scrollBarContainer"><div class="scrollKnob"><img src="/resources/images/ria/slideshow/scrollknob_center.gif"/></div></div>';
        item.appendChild(scrollarea);
        new MooScroller(item.getElements('div.iocRiaContent')[0], item.getElements('div.scrollKnob')[0], {
            mode: 'horizontal'
        });
    }
    else {
        item.getElement('div.iocRiaContent').setStyle('width', 'auto');
    }
};

///////////////////
/// Athlete Ria ///
///////////////////
var RIA_Athletes = new Class({
    Implements: Events,
    initialize: function(content, associatedFilter, languageCode) {
        if (!content || !associatedFilter || !languageCode) { return; }
        this.languageCode = languageCode;

        this.content = $(content);
        this.ulAthleteList = $('ulAthleteList');
        if (!this.content || !this.ulAthleteList) { return; }

        /*additional bit for filters*/
        this.associatedFilter = associatedFilter;
        this.associatedFilter.addEvents({
            'cleared': this.filterCleared.bind(this),
            'filterExecuted': this.filterSearchExecuted.bind(this),
            'searchExecuted': this.textSearchExecuted.bind(this)
        });
        this.JSONConnection = new Request.JSON({ url: '/AjaxScripts/RetreiveAthletesData.aspx', onSuccess: this.onAthletesDataRetreived.bind(this) });
        /*end of additional bit for filters*/

        this.addEvents({
            'updateFinished': this.onFinished.bind(this),
            'animationFinished': this.onFinished.bind(this)
        });

        // BUILD UP CONTENT
        // BEGIN        
        var commands = new Element('div', {
            'id': 'commands'
        });
        this.out_arrow = new Element('img', {
            'id': 'img#up_arrow',
            'src': '/Resources/Images/RIA/Athletes/up_arrow_off.png',
            'styles': {
                'cursor': 'pointer',
                'width': '49px',
                'height': '20px'
            }
        });
        this.in_arrow = new Element('img', {
            'id': 'img#down_arrow',
            'src': '/Resources/Images/RIA/Athletes/down_arrow_off.png',
            'styles': {
                'cursor': 'pointer',
                'width': '49px',
                'height': '28px'
            }
        });

        this.out_arrow.inject(commands);
        this.in_arrow.inject(commands);
        commands.inject(this.content);

        // attach events:		
        this.bound = {
            'goOut': this.goOut.bind(this),
            'goIn': this.goIn.bind(this)
        };

        this.out_arrow.addEvents({
            'mouseenter': function() { if (this.src.indexOf("/Resources/Images/RIA/Athletes/up_arrow.png") != -1) this.src = "/Resources/Images/RIA/Athletes/up_arrow_roll.png" },
            'mouseleave': function() { if (this.src.indexOf("/Resources/Images/RIA/Athletes/up_arrow_roll.png") != -1) this.src = "/Resources/Images/RIA/Athletes/up_arrow.png" },
            'click': this.bound.goOut
        });

        this.in_arrow.addEvents({
            'mouseenter': function() { if (this.src.indexOf("down_arrow.png") != -1) this.src = "/Resources/Images/RIA/Athletes/down_arrow_roll.png" },
            'mouseleave': function() { if (this.src.indexOf("down_arrow_roll.png") != -1) this.src = "/Resources/Images/RIA/Athletes/down_arrow.png" },
            'click': this.bound.goIn
        });

        document.addEvent('keydown', this.catchKey.bindWithEvent(this));
        this.content.addEvent('mousewheel', this.catchWheel.bindWithEvent(this));

        //END		
        this.zindex_array = [4, 3, 2, 1];
        this.opacity_array = [0, 1, 0.50, 0.15];

        // get dimensions the various planes we will have
        this.positions_array = new Array();
        var positions_array_constructor = new Element('div', { 'style': 'display:none;' });
        positions_array_constructor.inject($('background_div'));
        for (i = 0; i < 40; i++) {
            positions_array_constructor.className = "plane" + Math.floor(i / 10) + "pos" + ((i % 10) + 1);
            this.positions_array[positions_array_constructor.className] =
				{
				    'width': positions_array_constructor.getStyle('width'),
				    'height': positions_array_constructor.getStyle('height'),
				    'left': positions_array_constructor.getStyle('left'),
				    'top': positions_array_constructor.getStyle('top'),
				    'z-index': positions_array_constructor.getStyle('z-index')
				}
        }
        positions_array_constructor.destroy();

        // check if we have display by names
        var url = new URI(document.location);
        var queryString = url.get('query');
        var valuesDictionary = new Object();

        if ($chk(queryString)) {
            valuesDictionary = queryString.parseQueryString();
        }

        if (valuesDictionary.ViewBy != 'FilterViewByNames') {
            this.retreiveAthletesData(true, 1, 50);
        }
    },
    initializePlanes: function() {
        this.currentPageIndex = 1;
        this.firstPageIndex = 1;
        this.updatePlanes(true);
        this.originalLastPageIndex = (Math.floor((this.athleteItems_Array.length - 1) / 10) + 1);
        this.lastPageIndex = this.originalLastPageIndex;
        this.setupMoreOutIn();
        this.animationFinished = false;
        this.updateFinished = false;
    },
    updatePlanes: function(first) {
        this.athleteItems_Array = this.content.getElements('li');
        var len = this.athleteItems_Array.length;
        if (first) {
            if (Browser.Engine.trident) {
                this.athleteItems_Array.sort(function(a1, b1) {
                    var a = ('' + a1).toLowerCase(),
                    b = ('' + b1).toLowerCase();
                    if (a > b) return 1;
                    if (a < b) return -1;
                    return 0;
                });
            } else {
                this.athleteItems_Array.sort(function(a, b) { return a - b });
            }
        }
        for (index = 0; index < len; index++) {
            var athleteItem = this.athleteItems_Array[index];
            athleteItem.plane = (Math.floor(index / 10) + 1);
            if (this.currentPageIndex > 1) {
                athleteItem.plane -= 1;
            }

            athleteItem.pos = ((index % 10) + 1);
            this.setAthleteDisponibility(athleteItem);
        }
    },
    setupMoreOutIn: function() {
        this.isMoreOut = false;
        this.isMoreIn = false;

        //find out if there is more up and in
        if (this.athleteItems_Array.length > 10) {
            this.isMoreOut = this.athleteItems_Array[0].hasClass('hid');
            var lastAthlete = this.athleteItems_Array[this.athleteItems_Array.length - 1];
            this.isMoreIn = lastAthlete.plane != 1;
        }

        if (this.isMoreOut == true) {
            this.out_arrow.src = "/Resources/Images/RIA/Athletes/up_arrow.png";
        }
        else {
            this.out_arrow.src = "/Resources/Images/RIA/Athletes/up_arrow_off.png";
        }

        if (this.isMoreIn == true) {
            this.in_arrow.src = "/Resources/Images/RIA/Athletes/down_arrow.png";
        }
        else {
            this.in_arrow.src = "/Resources/Images/RIA/Athletes/down_arrow_off.png";
        }
    },
    setAthleteDisponibility: function(athleteItem) {
        athleteItem.removeProperty('style');
        athleteItem.removeEvents();
        var aTag = athleteItem.getElement('a');

        if ($chk(aTag) && aTag.getProperty('href').indexOf('#') != -1) {
            aTag.setStyle('cursor', 'default');
        }

        athleteItem.className = "plane" + athleteItem.plane + "pos" + athleteItem.pos;
        if (athleteItem.plane < 1 || 3 < athleteItem.plane) {
            athleteItem.className += " hid";
        }
        else {
            athleteItem.setStyles({
                'z-index': this.zindex_array[athleteItem.plane],
                'opacity': this.opacity_array[athleteItem.plane]
            });
            if (athleteItem.plane == 1) {
                this.addMouseEnterLeaveEvents(athleteItem);
            }
        }
    },
    addMouseEnterLeaveEvents: function(athleteItem) {
        athleteItem.addEvents({
            'mouseenter': function() {
                var spanAthleteName = athleteItem.getElement('span.iocAthleteName');
                if ($chk(spanAthleteName)) {
                    spanAthleteName.className = "iocAthleteNameHover";
                }
            },
            'mouseleave': function() {
                var spanAthleteName = athleteItem.getElement('span.iocAthleteNameHover');
                if ($chk(spanAthleteName)) {
                    spanAthleteName.className = "iocAthleteName";
                }
            }
        });
    },
    catchKey: function(event) {
        if (event.key == 'up') {
            event.stop();
            this.goOut();
        }
        if (event.key == 'down') {
            event.stop();
            this.goIn();
        }
    },
    catchWheel: function(event) {
        event.stop();
        if (event.wheel > 0) this.goOut();
        if (event.wheel < 0) this.goIn();
    },
    goOut: function() {
        if (!$chk(this.isMoreOut)) { return; }
        this.isMoreOut = false;
        this.isMoreIn = false;

        this.morph_done = 0;
        this.direction = 'out';

        for (index = 0; index < this.athleteItems_Array.length; index++) {
            var athleteItem = this.athleteItems_Array[index];
            athleteItem.targetPlane = athleteItem.plane + 1;
            this.createMorphEffect(athleteItem);
        }

        if (this.currentPageIndex < 3) {
            this.athletesDataToLoad = null;
            this.updateFinished = true;
            this.fireEvent('updateFinished');
        }
        else {
            this.retreiveAthletesData(false, this.firstPageIndex - 1, 10);
        }

        this.currentPageIndex--;
    },
    goIn: function() {
        if (!$chk(this.isMoreIn)) { return; }
        this.isMoreOut = false;
        this.isMoreIn = false;

        this.morph_done = 0;
        this.direction = 'in';

        for (index = 0; index < this.athleteItems_Array.length; index++) {
            var athleteItem = this.athleteItems_Array[index];
            athleteItem.targetPlane = athleteItem.plane - 1;
            this.createMorphEffect(athleteItem);
        }

        if (this.currentPageIndex > 1) {
            this.retreiveAthletesData(false, this.lastPageIndex + 1, 10);
        }
        else {
            this.athletesDataToLoad = null;
            this.updateFinished = true;
            this.fireEvent('updateFinished');
        }

        this.currentPageIndex++;
    },
    createMorphEffect: function(athleteItem) {
        if (athleteItem.targetPlane > -1 && athleteItem.targetPlane < 4) {
            var myMorph1 = new Fx.Morph(athleteItem, {
                duration: 1500,
                transition: Fx.Transitions.Sine.easeOut,
                onComplete: this.onMorpComplete.bind(this)
            });
            athleteItem.set('tween', { duration: '1000' }).tween('opacity', this.opacity_array[athleteItem.targetPlane]);
            myMorph1.start(this.positions_array["plane" + athleteItem.targetPlane + "pos" + athleteItem.pos]);
        }
        else {
            athleteItem.plane = athleteItem.targetPlane;
            this.setAthleteDisponibility(athleteItem);
            this.morph_done++;
        }
    },
    onMorpComplete: function(athleteItem) {
        athleteItem.plane = athleteItem.targetPlane;
        this.setAthleteDisponibility(athleteItem);
        this.morph_done++;

        //if all animations finished		
        if (this.morph_done >= this.athleteItems_Array.length) {
            this.animationFinished = true;
            this.fireEvent('animationFinished');
        }
    },
    onAthletesDataRetreived: function(athletesData) {
        // ATM we only have two properties on the athletesData
        // 'content' and 'count'
        if ($chk(athletesData)) {
            if (this.filterParameters.changed == true) {
                this.ulAthleteList.innerHTML = athletesData.content;
                this.initializePlanes();
            }
            else {
                this.athletesDataToLoad = athletesData;
                this.updateFinished = true;
                this.fireEvent('updateFinished');
            }
        }
    },
    onFinished: function() {
        if (this.animationFinished == true && this.updateFinished == true) {
            //load new data and delete old ones
            if ($chk(this.athletesDataToLoad)) {
                if (this.direction == 'out') {
                    //remove after
                    for (i = 40; i < 50; i++) {
                        var athleteItem = this.athleteItems_Array[i];
                        if ($chk(athleteItem)) { athleteItem.destroy(); }
                    }
                    //add before					
                    this.ulAthleteList.innerHTML = this.athletesDataToLoad.content + this.ulAthleteList.innerHTML;
                    this.athleteItems_Array = this.content.getElements('li');
                    //update		

                    this.firstPageIndex--;
                    if ((this.lastPageIndex > this.firstPageIndex) && (this.lastPageIndex > this.originalLastPageIndex)) {
                        this.lastPageIndex--;
                    }

                    this.updatePlanes(false);
                }
                else {
                    //remove before
                    for (i = 0; i < 10; i++) {
                        var athleteItem = this.athleteItems_Array[i];
                        if ($chk(athleteItem)) { athleteItem.destroy(); }
                    }
                    // add after
                    this.ulAthleteList.innerHTML = this.ulAthleteList.innerHTML + this.athletesDataToLoad.content;
                    this.athleteItems_Array = this.content.getElements('li');
                    //update
                    this.lastPageIndex++;
                    if (this.firstPageIndex < (this.lastPageIndex + 1)) {
                        this.firstPageIndex++;
                    }
                    this.updatePlanes(false);
                }
            }

            this.setupMoreOutIn();

            this.animationFinished = false;
            this.updateFinished = false;
        }
    },
    /*/////////////////////////////////////////////*/
    /*///additional bit for filter functionality///*/
    /*/////////////////////////////////////////////*/
    filterCleared: function(values) {
        this.filterParameters = new Object();
        this.ulAthleteList.innerHTML = '';
        this.retreiveAthletesData(true, 1, 50);

        /**** Decochage des cases pour mise en cohérences des critères de l'athlete RIA****/
        var elements = document.getElementById('OptionnalCheckboxes').childNodes;
        var i = 0; var j = 0;
        for (i = 0; i < elements.length; i++) {

            if (elements[i].nodeName == "SPAN" &&
             elements[i].getAttribute('className') != "iocAthletesFilterCategory") {
                var SubElements = elements[i].childNodes;

                if (SubElements.length > 0)
                    for (j = 0; j < SubElements.length; j++) {
                    if (SubElements[j].nodeName == "SPAN") {
                        var classe = document.createAttribute("class");
                        classe.nodeValue = ""
                        SubElements[j].setAttributeNode(classe);
                    }
                }
            }
        }
        /**** ****/
    },
    /*the next two are different functions in case we want to give different sort parameters*/
    filterSearchExecuted: function(values) {
        this.filterParameters = values;
        this.ulAthleteList.innerHTML = '';
        this.retreiveAthletesData(true, 1, 50);
    },
    textSearchExecuted: function(values) {
        this.filterParameters = values;
        this.ulAthleteList.innerHTML = '';
        this.retreiveAthletesData(true, 1, 50);
    },
    retreiveAthletesData: function(changed, pageIndex, itemsPerPage) {
        // The control should scale well when Javascript is disabled To this effect, we have to add a class to the root of the control at run-time
        this.content.className = 'iocRiaAthletesModuleJavascript';

        if (!$chk(this.filterParameters)) {
            this.filterParameters = new Object();
        }

        this.filterParameters.changed = changed == true;
        //add pagination parameters
        this.filterParameters.resultsPage = 1;
        this.filterParameters.resultsPageIPP = 10;
        this.filterParameters.languageCode = this.languageCode;

        if ($chk(pageIndex)) {
            this.filterParameters.resultsPage = pageIndex;
        }

        if ($chk(itemsPerPage)) {
            this.filterParameters.resultsPageIPP = itemsPerPage;
        }

        if ($chk(this.filterParameters.ViewBy) && this.filterParameters.ViewBy == 'FilterViewByNames') {
            this.filterParameters.resultsPageIPP = 30;
            var url = new URI(document.location.href);
            url.clearData();
            url.setData(this.filterParameters);
            url.go();
        }
        else {
            // get the datas
            this.JSONConnection.get(this.filterParameters);
        }
    }
});

/////////////////////////
/// Filters Utilities ///
/////////////////////////

var Filters = new Class({
    Implements: Options,
    options: {
        DefaultCheckBoxState: true,
        DefaultRadioState: true
    },
    initialize: function(filterListWithQueryString, goButtonId, clearButtonId, goButtonForTextBoxId, bookmark) {
        if (!filterListWithQueryString || !goButtonId) { return; }
        this.filterListWithQueryString = filterListWithQueryString;

        this.goButton = $(goButtonId);
        this.clearButton = $(clearButtonId);

        if (!goButtonForTextBoxId) {
            this.goButtonForTextBox = null;
        }
        else {
            this.goButtonForTextBox = $(goButtonForTextBoxId);
        }

        if (!this.filterListWithQueryString || !this.goButton) { return; }

        this.valuesDictionary = new Object();

        // make sure that all elements are mootools elements
        for (var queryString in this.filterListWithQueryString) {
            var item = this.filterListWithQueryString[queryString];
            if (!(item instanceof Function)) {//if not a function
                if (item instanceof Array) {
                    var radios = new Array();
                    item.each(function(radio, index) {
                        radios[index] = $(radio);
                    });
                    this.filterListWithQueryString[queryString] = radios;
                }
                else {
                    this.filterListWithQueryString[queryString] = $(item);
                }
            }
        }

        //find all textBoxes and add enter event:
        for (var queryString in this.filterListWithQueryString) {
            var item = this.filterListWithQueryString[queryString];
            if (!(item instanceof Function) && !(item instanceof Array)) {//if not a function or array
                var tag = item.get('tag');
                var type = item.get('type');
                if ((tag == 'input') && (type == 'text')) {
                    item.addEvent('keydown', this.textBoxKeyDown.bind(this));
                }
            }
        }

        // set uri
        this.url = new URI(document.location.href);

        // set bookmark (if supplied)
        if (bookmark)
            this.url.set('fragment', bookmark);

        // attach events
        if (this.goButton.get('tag') == 'a') {
            this.goButton.href = 'javascript:;';
        }

        if ($chk(this.clearButton) && (this.clearButton.get('tag') == 'a')) {
            this.clearButton.href = 'javascript:;';
        }

        if ($chk(this.goButtonForTextBox)) {
            if (this.goButtonForTextBox.get('tag') == 'a') {
                this.goButtonForTextBox.href = 'javascript:;';
            }
            this.goButtonForTextBox.addEvent('click', this.goButtonForTextBoxClick.bind(this));
        }

        this.goButton.addEvent('click', this.goButtonClick.bind(this));

        if ($chk(this.clearButton)) {
            this.clearButton.addEvent('click', this.clearButtonClick.bind(this));
        }
    },
    addQueryString: function(name, value) {
        var queryString = this.url.get('query');
        this.valuesDictionary = new Object();

        if ($chk(queryString)) {
            this.valuesDictionary = queryString.parseQueryString();
        }
        if (value == 'Enter a name' || value == 'Entrez un nom') value = '';
        this.valuesDictionary[name] = value;

        this.url.clearData();
        this.url.setData(this.valuesDictionary);
    },
    removeQueryString: function(name) {
        var queryString = this.url.get('query');
        this.valuesDictionary = new Object();

        if ($chk(queryString)) {
            this.valuesDictionary = queryString.parseQueryString();
        }

        delete this.valuesDictionary[name];

        this.url.clearData();
        this.url.setData(this.valuesDictionary);
    },
    goButtonClick: function() {
        for (var queryString in this.filterListWithQueryString) {
            var item = this.filterListWithQueryString[queryString];

            if (!(item instanceof Function)) {//if not a function
                if (item instanceof Array) {
                    item.each(function(radio) {
                        var type = radio.get('type');
                        if (type == 'radio' && radio.checked == true) {
                            this.addQueryString(queryString, radio.value);
                        }
                    }, this);
                }
                else {
                    var tag = item.get('tag');
                    var type = item.get('type');

                    if (tag == 'select') {
                        this.addQueryString(queryString, item.value);
                    }
                    else if (tag == 'input') {
                        if (type == 'text') {
                            if ($chk(this.goButtonForTextBox)) {
                                this.removeQueryString(queryString);
                            }
                            else {
                                this.addQueryString(queryString, item.value.replace("'", "%27"));
                            }
                        }
                        else if (type == 'checkbox') {
                            this.addQueryString(queryString, item.checked);
                        }
                        else if (type == 'hidden') {
                            this.addQueryString(queryString, item.value);
                        }
                    }
                    else if (tag == 'span') {
                        var inputRefArray = item.getElementsByTagName('input');
                        var chkcat = "";
                        for (var i = 0; i < inputRefArray.length; i++) {
                            var inputRef = inputRefArray[i];
                            if (inputRef.type.substr(0, 8) == 'checkbox') {
                                if (inputRef.checked == true)
                                    chkcat += "1";
                                else chkcat += "0";
                            }
                        }
                        this.addQueryString(queryString, chkcat);
                    }
                }
            }
        }

        this.executeFilter();
    },
    goButtonForTextBoxClick: function() {
        for (var queryString in this.filterListWithQueryString) {
            var item = this.filterListWithQueryString[queryString];
            if (!(item instanceof Function)) {//if not a function
                if (item instanceof Array) {
                    item.each(function(radio) {
                        var type = radio.get('type');
                        if (type == 'radio') {
                            this.removeQueryString(queryString);
                        }
                    }, this);
                }
                else {
                    var tag = item.get('tag');
                    var type = item.get('type');

                    if (tag == 'select') {
                        this.removeQueryString(queryString);
                    }
                    else if (tag == 'input') {
                        if (type == 'text') {
                            this.addQueryString(queryString, item.value.replace(/\</g, "&lt;").replace(/\>/g, "&gt;"));
                        }
                        else if (type == 'checkbox') {
                            this.removeQueryString(queryString);
                        }
                    }
                }
            }
        }

        this.executeSearch();
    },
    clearButtonClick: function() {
        for (var queryString in this.filterListWithQueryString) {
            var item = this.filterListWithQueryString[queryString];
            if (!(item instanceof Function)) {//if not a function
                if (item instanceof Array) {
                    item.each(function(radio) {
                        var type = radio.get('type');
                        if (type == 'radio') {
                            radio.checked = this.options.DefaultRadioState;
                            this.removeQueryString(queryString);
                            radio.fireEvent('changed'); //necessary to make sure the custom controls refresh
                        }
                    }, this);
                }
                else {
                    var tag = item.get('tag');
                    var type = item.get('type');

                    if (tag == 'select') {
                        item.value = item.options[0].value;
                        item.fireEvent('changed'); //necessary to make sure the custom controls refresh
                    }
                    else if (tag == 'input') {
                        if (type == 'text') {

                        }
                        else if (type == 'checkbox') {
                            item.checked = this.options.DefaultCheckBoxState;
                            item.fireEvent('changed'); //necessary to make sure the custom controls refresh
                        }
                    }
                }
            }
        }
        this.clear();
    },
    textBoxKeyDown: function(event) {
        if (event.key == 'enter') {
            if ($chk(this.goButtonForTextBox)) {
                this.goButtonForTextBoxClick();
            }
            else {
                this.goButtonClick();
            }
        }
    },
    clear: function() {

    },
    executeFilter: function() {
        this.removeQueryString('currentArticlesPage'); // museum event listing page
        this.url.go();
    },
    executeSearch: function() {
        this.removeQueryString('currentArticlesPage');
        this.url.go();
    }
});

var CloudFilters = new Class({
    Implements: Events,
    Extends: Filters,
    clear: function() {
        this.fireEvent('cleared', this.valuesDictionary);
    },
    executeFilter: function() {
        this.fireEvent('filterExecuted', this.valuesDictionary);
    },
    executeSearch: function() {
        this.fireEvent('searchExecuted', this.valuesDictionary);
    }
});


var OlympicGamesSearchFilters = new Class({
    Implements: Events,
    Extends: Filters,
    additionalInitialisation: function(javascriptCarouselObject, searchData, counterId) {
        this.counter = $(counterId);
        this.carousel = javascriptCarouselObject;
        this.searchData = searchData;

        this.ulContent = this.carousel.ulContent;
        this.defaultWidth = this.ulContent.style.width;

        this.carouselElements = new Array();

        var len = this.carousel.liItems.length;
        for (var i = 0; i < len; i++) {
            this.carouselElements.push(this.carousel.liItems[i].getElement('a'));
        }
    },

    updateCarouselPosition: function() {
        this.carousel.update();
        this.carousel.position.now = this.carousel.trackSize - (this.carousel.knobSize + 2);
        this.carousel.content['scrollLeft'] = this.carousel.position.now * this.carousel.scrollRatio;
        this.carousel.knob.setStyle('left', this.carousel.position.now + 'px');
        this.carousel.ulContent.setStyle('margin-left', '219px');
        this.carousel.makeThumbUp();
    },

    clear: function() {
        var len = this.carouselElements.length;

        for (var i = 0; i < len; i++) {
            var link = this.carouselElements[i];
            link.parentNode.parentNode.style.display = '';
        }

        this.counter.innerHTML = len;
        this.ulContent.style.width = this.defaultWidth;
        this.updateCarouselPosition();
    },
    executeFilter: function() {
        var summer = this.valuesDictionary['Summer'];
        var winter = this.valuesDictionary['Winter'];
        var continent = this.valuesDictionary['Continent'];
        var country = this.valuesDictionary['Country'];
        var gamesToShow = new Array();

        var len = this.searchData.length;

        for (var i = 0; i < len; i++) {
            var data = this.searchData[i];
            var remove = false;


            //alert(data.gameType + ' ; ' + data.continent + ' ; ' + data.country)

            if ((summer == 'false' && winter == 'true' && data.gameType == 'S') ||
                (summer == 'true' && winter == 'false' && data.gameType == 'W')) {
                remove = true;
            }

            if ($chk(continent) && data.continent.toLowerCase() != continent.toLowerCase()) {
                remove = true;
            }

            if ($chk(country) && data.country.toLowerCase() != country.toLowerCase()) {
                remove = true;
            }

            if (!remove) {
                gamesToShow.push(data.gameName.toLowerCase());
            }
        }

        len = this.carouselElements.length;
        var validCounter = 0;

        for (var i = 0; i < len; i++) {
            var link = this.carouselElements[i];
            var display = 'none';

            for (var j = 0; j < gamesToShow.length; j++) {
                if (link.title.toLowerCase() == gamesToShow[j]) {
                    display = '';
                    validCounter++;
                }
            }

            link.parentNode.parentNode.style.display = display;
        }

        this.ulContent.style.width = (validCounter * 92 + 275) + 'px';
        this.counter.innerHTML = validCounter;
        this.updateCarouselPosition();
    },
    executeSearch: function() {
        var gameName = this.valuesDictionary['GameName'];
        var len = this.carouselElements.length;
        var validCounter = 0;

        for (var i = 0; i < len; i++) {
            var link = this.carouselElements[i];
            if (link.title.toLowerCase().indexOf(gameName.toLowerCase()) != -1) {
                link.parentNode.parentNode.style.display = '';
                validCounter++;
            }
            else {
                link.parentNode.parentNode.style.display = 'none';
            }
        }

        this.ulContent.style.width = (validCounter * 92 + 275) + 'px';
        this.counter.innerHTML = validCounter;
        this.updateCarouselPosition();
    }
});


var AllMedallistSearchFilters = new Class({
    Implements: Events,
    Extends: Filters,
    executeFilter: function() {

        var AthleteResultsCount = 0;
        var AthleteName = this.valuesDictionary['athletename'];
        var Category = this.valuesDictionary['category'];
        var Games = this.valuesDictionary['games'];
        var Sport = this.valuesDictionary['sport'];
        var Event = this.valuesDictionary['event'];
        var Continent = this.valuesDictionary['continent'];
        var Country = this.valuesDictionary['country'];
        var GenderMen = this.valuesDictionary['mengender'];
        var GenderWomen = this.valuesDictionary['womengender'];
        var GenderMixed = this.valuesDictionary['mixedgender'];
        var ClassificationTeam = this.valuesDictionary['teamclassification'];
        var ClassificationIndividual = this.valuesDictionary['individualclassification'];
        var MedalGold = this.valuesDictionary['goldmedal'];
        var MedalSilver = this.valuesDictionary['silvermedal'];
        var MedalBronze = this.valuesDictionary['bronzemedal'];
        var RecordWorld = this.valuesDictionary['worldrecord'];
        var RecordOlympic = this.valuesDictionary['olympicrecord'];

        if ($chk(AthleteName && (AthleteName != "Enter a name" || AthleteName != "Entrez un nom"))) {
            AthleteResultsCount++;
        }

        if ($chk(Category)) {
            AthleteResultsCount++;
        }
        if ($chk(Games)) {
            AthleteResultsCount++;
        }
        if ($chk(Sport)) {
            AthleteResultsCount++;
        }
        if ($chk(Event)) {
            AthleteResultsCount++;
        }
        if ($chk(Continent)) {
            AthleteResultsCount++;
        }
        if ($chk(Country)) {
            AthleteResultsCount++;
        }
        if (GenderMen == 'true' || GenderWomen == 'true' || GenderMixed == 'true') {
            AthleteResultsCount++;
            if (GenderMen == 'true' && GenderWomen == 'true' && GenderMixed == 'true') {
                AthleteResultsCount--;
            }
        }
        if (ClassificationTeam == 'true' || ClassificationIndividual == 'true') {
            AthleteResultsCount++;
            if (ClassificationTeam == 'true' && ClassificationIndividual == 'true') {
                AthleteResultsCount--;
            }
        }
        if (MedalGold == 'true' || MedalSilver == 'true' || MedalBronze == 'true') {
            AthleteResultsCount++;
            if (MedalGold == 'true' && MedalSilver == 'true' && MedalBronze == 'true') {
                AthleteResultsCount--;
            }
        }
        if (RecordWorld == 'true' || RecordOlympic == 'true') {
            AthleteResultsCount++;
        }
        if (AthleteResultsCount >= 2) {
            this.url.go();
        }
        else {
            var allAthleteResultsError = $("iocResultsDataSearchOptionsError");
            allAthleteResultsError.style.display = "block";
        }
    }
});

var GoogleSearch = new Class({
    Implements: Events,
    initialize: function(searchBoxId, goButtonId, resultsUrl) {

        if (!resultsUrl || !goButtonId || !searchBoxId) { return; }

        // Set uri
        this.url = new URI(resultsUrl);

        this.goButton = $(goButtonId);
        this.searchBox = $(searchBoxId);

        // Attach events
        if (this.goButton.get('tag') == 'a') {
            this.goButton.href = 'javascript:;';
        }
        if (this.searchBox.get('tag') == 'a') {
            this.searchBox.href = 'javascript:;';
        }

        var _this = this;
        this.goButton.onclick = function() {
            _this.executeSearch();
        };

        this.searchBox.onkeypress = function(e) {
            var key;
            if (window.event) {
                key = window.event.keyCode;
            }   //IE
            else {
                key = e.which;
            }   //firefox
            if (key == 13) {
                _this.executeSearch();
                return false;
            }
        };
    },
    executeSearch: function() {
        var queryString = this.url.get('query');
        this.valuesDictionary = new Object();

        if ($chk(queryString)) {
            this.valuesDictionary = queryString.parseQueryString();
        }
        this.valuesDictionary["q"] = this.searchBox.value.replace("'", "%27");
        this.url.clearData();
        this.url.setData(this.valuesDictionary);
        this.url.go();
    }
});

var MediaPlayerFilters = new Class({
    Implements: Events,
    Extends: Filters,
    initialize: function(filterListWithQueryString, goButtonId, clearButtonId, goButtonForTextBoxId, tabQueryString, resultsTabIndex, mediaPlayerHomeUrl) {
        if (!tabQueryString || !resultsTabIndex || !mediaPlayerHomeUrl) { return; }
        this.tabQueryString = tabQueryString;
        this.resultsTabIndex = resultsTabIndex;
        this.parent(filterListWithQueryString, goButtonId, clearButtonId, goButtonForTextBoxId);
        this.url = new URI(mediaPlayerHomeUrl);
    },
    executeFilter: function() {
        this.addQueryString(this.tabQueryString, this.resultsTabIndex);
        this.url.go();
    },
    executeSearch: function() {
        this.addQueryString(this.tabQueryString, this.resultsTabIndex);
        this.url.go();
    }
});

///////////////////////////
/// MyPlaylistBehaviour ///
///////////////////////////
var MyPlaylist = new Class(
{
    initialize: function(mediaPlayerContainerId, isMediaPage, languageCode) {
        this.languageCode = languageCode;
        if (!mediaPlayerContainerId) { return; }
        var mediaPlayerContainer = $(mediaPlayerContainerId);
        if (!mediaPlayerContainer) { return; }
        this.mediaListContainer = mediaPlayerContainer.getElement('.iocMediaPlayerListContainer');
        this.linkMixedDisplay = mediaPlayerContainer.getElement('.iocMediaPlayerFiltersMixedDisplay');
        if (!this.mediaListContainer) { return; }
        var url = new URI(document.location.href);
        var queryString = url.get('query');
        this.parameters = new Object();

        if ($chk(queryString)) {
            this.parameters = queryString.parseQueryString();
        }

        if ($chk(isMediaPage) && !$chk(this.parameters['DisplayType'])) {
            this.parameters['DisplayType'] = 'mixed';
        }

        this.HTMLConnection = new Request.HTML({ url: '/AjaxScripts/RetrieveMediaItemsData.aspx', onSuccess: this.onDataRetrieved.bind(this) });
        this.retrieveData();
    },
    getPlaylistItemsInStringFormat: function() {
        var mediaPlaylist = JSON.decode(Cookie.read('mediaPlaylist'));

        if ($chk(mediaPlaylist)) {
            return mediaPlaylist.join(',');
        }
        return '';
    },
    retrieveData: function() {
        this.parameters.filter = this.getPlaylistItemsInStringFormat();
        this.parameters.languageCode = this.languageCode;
        this.HTMLConnection.get(this.parameters);
    },
    getSlider: function() {
        var slideShow = this.mediaListContainer.getElement('.iocRiaMediaSlideShow1Row');
        var rows = 1;
        if (!$chk(slideShow)) {
            slideShow = this.mediaListContainer.getElement('.iocRiaMediaSlideShow2Rows');
            rows = 2;
            if (!$chk(slideShow)) {
                slideShow = this.mediaListContainer.getElement('.iocRiaMediaSlideShow5Rows');
                rows = 5;
            }
        }

        if ($chk(slideShow)) {
            return { element: slideShow, rowCount: rows };
        }

        return null;
    },
    onDataRetrieved: function(responseTree, responseElements, responseHTML) {
        if ($chk(responseHTML)) {
            //this.mediaListContainer.innerHTML.destroy();
            var content = this.mediaListContainer.getFirst();
            if ($chk(content)) {
                content.destroy(); //cleanup resources
            }
            this.mediaListContainer.innerHTML = responseHTML;
            var newSlideShow = this.getSlider();
            if ($chk(newSlideShow)) {
                if ($chk(this.linkMixedDisplay)) {
                    var firstLink = newSlideShow.element.getElement('a');
                    if ($chk(firstLink)) {
                        var url = new URI(firstLink.href);
                        var queryString = url.get('query');
                        var valuesDictionary = new Object();

                        if ($chk(queryString)) {
                            valuesDictionary = queryString.parseQueryString();
                        }

                        valuesDictionary['DisplayType'] = 'mixed';

                        url.clearData();
                        url.setData(valuesDictionary);

                        this.linkMixedDisplay.href = url;
                    }
                }
                AddMediaSlideShow(newSlideShow.element.get('id'), newSlideShow.rowCount);
                this.tranformAddIntoRemove(newSlideShow.element.get('id'));
            }
        }
    },
    tranformAddIntoRemove: function(containerId) {
        if (!containerId) { return; }
        var item = $(containerId);
        if (!item) { return; }

        item.getElements('div.iocRiaContent ul li').each(function(item, index) {
            var addToPlaylistButton = item.getElement('span.iocRiaAddToPlayList');
            var link = addToPlaylistButton.getFirst();
            link.set('text', iocRiaRemoveText);
            link.set('title', iocRiaRemoveText);
            addToPlaylistButton.removeEvents('click');
            addToPlaylistButton.addEvent('click', function() {
                RemoveMediaInPlaylist(item.id);
                item.destroy();
            });
        });
    }
});

////////////////////////////
/// Quiz block behaviour ///
////////////////////////////

var QuizBlock = new Class(
{
    initialize: function(quizBlockContainerId, correctAnswerIndex) {
        //find controls
        if (!correctAnswerIndex) { return; }
        this.correctAnswerIndex = correctAnswerIndex;
        if (!quizBlockContainerId) { return; } //if undefined do nothing
        this.quizBlockContainer = $(quizBlockContainerId);
        this.radioButtons = this.quizBlockContainer.getElements('input[type=radio]');
        if (!this.radioButtons) { return; }
        this.submitButton = this.quizBlockContainer.getElement('.SmallButton');
        if (!this.submitButton) { return; }
        var messages = this.quizBlockContainer.getElements('.iocQuizValidation');
        if (!messages) { return; }
        this.correctAnswerMessage = messages[0];
        if (!this.correctAnswerMessage) { return; }
        this.incorrectAnswerMessage = messages[1];
        if (!this.incorrectAnswerMessage) { return; }
        this.divAnswerLink = this.quizBlockContainer.getElement('.iocQuizAnswerLink');
        if (!this.divAnswerLink) { return; }

        //process control to remove postbacks:
        this.submitButton.setProperty('href', 'javascript:;');
        this.submitButton.addEvent('click', this.onSubmitClick.bindWithEvent(this));
    },
    getSelectedIndex: function() {
        var index = -1;

        for (i = 0; i < this.radioButtons.length; i++) {
            if (this.radioButtons[i].checked == true) {
                index = i;
                break;
            }
        }
        return index;
    },
    onSubmitClick: function(e) {
        var event = new Event(e);
        var selectedIndex = this.getSelectedIndex();

        if (selectedIndex != -1) {
            if (selectedIndex == this.correctAnswerIndex) {
                this.correctAnswerMessage.setStyle('display', '');
                this.incorrectAnswerMessage.setStyle('display', 'none');
                this.divAnswerLink.setStyle('display', '');
            }
            else {
                this.correctAnswerMessage.setStyle('display', 'none');
                this.incorrectAnswerMessage.setStyle('display', '');
                $(this.radioButtons[selectedIndex].parentNode.parentNode.getElementsByTagName("span")[2]).setStyle('text-decoration', 'line-through');
            }
        }
        else {
            this.correctAnswerMessage.setStyle('display', 'none');
            this.incorrectAnswerMessage.setStyle('display', 'none');
        }
    }
});

//////////////////////
/// Expend Extender///
//////////////////////

var IsExtenderBlock = new Class(
{
    initialize: function(TopExtender, MiddleExtender, BottomExtender, TopArrowDownImgUrl, MiddleArrowDownImgUrl, BottomArrowDownImgUrl) {

        this.TopExtender = TopExtender;
        this.MiddleExtender = MiddleExtender;
        this.BottomExtender = BottomExtender;

        if (TopArrowDownImgUrl != null) { this.arrowDownImageUrl = TopArrowDownImgUrl; }
        else if (MiddleArrowDownImgUrl != null) { this.arrowDownImageUrl = MiddleArrowDownImgUrl; }
        else if (BottomArrowDownImgUrl != null) { this.arrowDownImageUrl = BottomArrowDownImgUrl; }

        this.arrowUpImageUrl = "/resources/Images/Misc/arrowUpBlack.gif";

        this.elementExtenderTopDiv = $(this.TopExtender.concat('_divExtender'));
        this.elementExtenderMiddleDiv = $(this.MiddleExtender.concat('_divExtender'));
        this.elementExtenderBottomDiv = $(this.BottomExtender.concat('_divExtender'));

        if (this.elementExtenderTopDiv != null) {
            this.extenderTitleTopContainer = this.elementExtenderTopDiv.getElement('.iocExtenderContent');
        }
        if (this.elementExtenderMiddleDiv != null) {
            this.extenderTitleMiddleContainer = this.elementExtenderMiddleDiv.getElement('.iocExtenderContent');
        }
        if (this.elementExtenderBottomDiv != null) {
            this.extenderTitleBottomContainer = this.elementExtenderBottomDiv.getElement('.iocExtenderContent');
        }

        if (this.elementExtenderTopDiv != null) {
            this.elementExtenderTopDiv.addEvent('click', this.onTitleClick.bindWithEvent(this, 1));
        }
        if (this.elementExtenderMiddleDiv != null) {
            this.elementExtenderMiddleDiv.addEvent('click', this.onTitleClick.bindWithEvent(this, 2));
        }
        if (this.elementExtenderBottomDiv != null) {
            this.elementExtenderBottomDiv.addEvent('click', this.onTitleClick.bindWithEvent(this, 3));
        }
    },

    onTitleClick: function(e, i) {
        var event = new Event(e);
        this.expendEffect1 = this.expendEffect2 = this.expendEffect3 = this.expendEffect4 = null; //init
        if (i == 1) {
            if (this.extenderTitleMiddleContainer != null) {
                this.arrow1 = this.elementExtenderMiddleDiv.getElement('img');
                this.expendEffect1 = new Fx.Morph(this.extenderTitleMiddleContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
            }
            if (this.extenderTitleBottomContainer != null) {
                this.arrow2 = this.elementExtenderBottomDiv.getElement('img');
                this.expendEffect2 = new Fx.Morph(this.extenderTitleBottomContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
            }

            if (this.extenderTitleTopContainer != null) {
                this.arrow3 = this.elementExtenderTopDiv.getElement('img');

                if (this.extended1 == true) {
                    this.expendEffect3 = new Fx.Morph(this.extenderTitleTopContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
                }
                else {
                    this.expendEffect4 = new Fx.Morph(this.extenderTitleTopContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
                }
            }
        }

        if (i == 2) {
            if (this.extenderTitleTopContainer != null) {
                this.arrow1 = this.elementExtenderTopDiv.getElement('img');
                this.expendEffect1 = new Fx.Morph(this.extenderTitleTopContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
            }
            if (this.extenderTitleBottomContainer != null) {
                this.arrow2 = this.elementExtenderBottomDiv.getElement('img');
                this.expendEffect2 = new Fx.Morph(this.extenderTitleBottomContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
            }
            if (this.extenderTitleMiddleContainer != null) {
                this.arrow3 = this.elementExtenderMiddleDiv.getElement('img');
                if (this.extended2 == true) {
                    this.expendEffect3 = new Fx.Morph(this.extenderTitleMiddleContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
                }
                else {
                    this.expendEffect4 = new Fx.Morph(this.extenderTitleMiddleContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
                }
            }
        }

        if (i == 3) {
            if (this.extenderTitleTopContainer != null) {
                this.arrow1 = this.elementExtenderTopDiv.getElement('img');
                this.expendEffect1 = new Fx.Morph(this.extenderTitleTopContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
            }
            if (this.extenderTitleMiddleContainer != null) {
                this.arrow2 = this.elementExtenderMiddleDiv.getElement('img');
                this.expendEffect2 = new Fx.Morph(this.extenderTitleMiddleContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
            }
            if (this.extenderTitleBottomContainer != null) {
                this.arrow3 = this.elementExtenderBottomDiv.getElement('img');
                if (this.extended3 == true) {
                    this.expendEffect3 = new Fx.Morph(this.extenderTitleBottomContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
                }
                else {
                    this.expendEffect4 = new Fx.Morph(this.extenderTitleBottomContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
                }
            }
        }

        if (this.expendEffect1 != null) {
            if (this.arrow1 != null) { this.arrow1.src = this.arrowDownImageUrl; }
            this.expendEffect1.start({
                'height': '0px' //Morphs the 'height' style from current to 0px.
            });
            if (this.expendEffect4 != null) { this.extended1 = this.extended2 = this.extended3 = false; }
        }
        if (this.expendEffect2 != null) {
            if (this.arrow2 != null) { this.arrow2.src = this.arrowDownImageUrl; }
            this.expendEffect2.start({
                'height': '0px' //Morphs the 'height' style from current to 0px.
            });
            if (this.expendEffect4 != null) { this.extended1 = this.extended2 = this.extended3 = false; }
        }

        //close action
        if (this.expendEffect3 != null) {
            if (this.arrow3 != null) { this.arrow3.src = this.arrowDownImageUrl; }
            this.expendEffect3.start({
                'height': '0px' //Morphs the 'height' style from current to 0px.
            });
            if (i == 1) { this.extended1 = false; }
            if (i == 2) { this.extended2 = false; }
            if (i == 3) { this.extended3 = false; }
        }

        //open action
        if (this.expendEffect4 != null) {
            if (this.arrow3 != null) { this.arrow3.src = this.arrowUpImageUrl; }
            this.expendEffect4.start({
                'height': this.originalHeight //Morphs the 'height' style from current to original size.
            });
            if (i == 1) { this.extended1 = true; }
            if (i == 2) { this.extended2 = true; }
            if (i == 3) { this.extended3 = true; }
        }
    }
});

//////////////////////
/// Extender block ///
//////////////////////
var ExtenderBlock = new Class(
{
    initialize: function(extenderContainerId, titleImageAltUrl, arrowUpImageUrl, arrowDownImageUrl, isStartingOpen, IsFuturePastGame) {
        //if undefined do nothing
        if ((!extenderContainerId) || (!titleImageAltUrl) || (!arrowUpImageUrl) || (!arrowDownImageUrl)) {
            return;
        }

        this.titleImageAltUrl = 'url(' + titleImageAltUrl + ')';
        this.arrowUpImageUrl = arrowUpImageUrl;
        this.arrowDownImageUrl = arrowDownImageUrl;
        //find controls
        this.extenderContainer = $(extenderContainerId);
        if (!this.extenderContainer) { return; }
        this.extenderTitleContainer = this.extenderContainer.getElement('.iocExtenderTitle');
        if (!this.extenderTitleContainer) { return; }
        this.arrow = this.extenderTitleContainer.getElement('img');
        if (!this.arrow) { return; }
        this.extenderContentContainer = this.extenderContainer.getElement('.iocExtenderContent');
        if (!this.extenderContentContainer) { return; }

        if (IsFuturePastGame == "False") {
            this.extenderTitleContainer.addEvent('click', this.onTitleClick.bindWithEvent(this));
        }
        this.extenderTitleContainer.addEvent('mouseover', this.onTitleMouseOver.bindWithEvent(this));
        this.extenderTitleContainer.addEvent('mouseout', this.onTitleMouseOut.bindWithEvent(this));

        this.originalHeight = this.extenderContentContainer.getSize().y;
        this.expendEffect = new Fx.Morph(this.extenderContentContainer, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });


        this.arrow.src = this.arrowDownImageUrl;

        if (!isStartingOpen) {
            this.extenderContentContainer.setStyle('height', '0px');
            this.extended = false;
        }
        else {
            this.extended = true;
        }
    },

    onTitleClick: function(e) {
        var event = new Event(e);
        if (this.extended) {
            this.arrow.src = this.arrowDownImageUrl;
            this.expendEffect.start({
                'height': '0px' //Morphs the 'height' style from current to 0px.
            });
            this.extended = false;
        }
        else {
            this.arrow.src = this.arrowUpImageUrl;
            this.expendEffect.start({
                'height': this.originalHeight //Morphs the 'height' style from current to original size.
            });
            this.extended = true;
        }
    },
    onTitleMouseOver: function(e) {
        var event = new Event(e);
        this.extenderTitleContainer.setStyle('backgroundImage', this.titleImageAltUrl);
    },
    onTitleMouseOut: function(e) {
        var event = new Event(e);
        this.extenderTitleContainer.setStyle('backgroundImage', '');
    }
});

//////////////////////
/// Glossary block ///
//////////////////////
var GlossaryBlock = new Class(
{
    initialize: function(tabsContainerId, divsContainerId) {
        if (!tabsContainerId || !divsContainerId) { return; }

        var tabsContainer = $(tabsContainerId);
        var divsContainer = $(divsContainerId);

        if (!tabsContainer || !divsContainer) { return; }

        this.tabs = tabsContainer.getChildren();
        this.contents = divsContainer.getElements('div');

        if (!this.tabs || !this.contents || (this.tabs.length != this.contents.length)) { return; }

        for (i = 0; i < this.tabs.length; i++) {

            var tabElement = this.tabs[i];
            var contentElement = this.contents[i];
            if (tabElement.get('tag') == 'a') {
                tabElement.setProperty('href', 'javascript:;');
                tabElement.addEvent('click', this.onTabClick.pass(contentElement, this));
            }
        }
    },
    onTabClick: function(contentElement) {

        for (i = 0; i < this.contents.length; i++) {
            this.contents[i].setStyle('display', 'none');
        }

        contentElement.setStyle('display', '');
    }
});


//////////////////
/// Tabulation ///
//////////////////
var Tabulation = new Class({
    initialize: function(containerId) {
        if (!containerId) { return; }
        var container = $(containerId);
        if (!container) { return; }
        var titles = container.getElements('.iocBlockTitle');
        var len = titles.length;

        for (i = 0; i < len; i++) {
            var title = titles[i];
            title.addEvent('mouseenter', this.tabEnter.pass(title));
            title.addEvent('mouseleave', this.tabLeave.pass(title));
        }
    },
    tabEnter: function(tab) {
        tab.addEvent('mouseenter', function() {
            if (tab.className != 'iocBlockTitle Selected') {
                tab.className = 'iocBlockTitle Over';
            }
        });
    },
    tabLeave: function(tab) {
        tab.addEvent('mouseleave', function() {
            if (tab.className != 'iocBlockTitle Selected') {
                tab.className = 'iocBlockTitle';
            }
        });
    }
});

////////////////////
/// Tabbed Block ///
////////////////////
var TabbedBlock = new Class(
{
    initialize: function(tabbedBlockContainerId, tabbedContentCssClassName) {
        if (!tabbedBlockContainerId || !tabbedContentCssClassName) { return; }
        this.tabbedBlockContainer = $(tabbedBlockContainerId);
        if (!this.tabbedBlockContainer) { return; }

        this.titles = this.tabbedBlockContainer.getElements('.iocBlockTitle');
        if (this.titles.length < 2) { return; }
        this.contents = this.tabbedBlockContainer.getElements(tabbedContentCssClassName);

        if (!this.titles || !this.contents || (this.titles.length != this.contents.length)) { return; }

        this.buildUpTabNavigation();
    },
    buildUpTabNavigation: function() {
        var i = this.titles.length - 1;
        while (i > -1) {
            var tabElement = this.titles[i];
            var contentElement = this.contents[i];
            tabElement.inject(this.tabbedBlockContainer, 'top');
            tabElement.addEvent('click', this.onTabClick.pass([tabElement, contentElement], this));
            tabElement.addEvent('mouseover', this.onTabMouseOver.pass(tabElement, this));
            tabElement.addEvent('mouseout', this.onTabMouseOut.pass(tabElement, this));
            tabElement.className = 'iocBlockTitleUnselected';
            tabElement.setStyles({
                'clear': 'none',
                'cursor': 'pointer',
                'margin-right': '1px'
            });
            tabElement.getElement('h2').setStyle('width', 'auto');
            tabElement.getElement('h3').setStyle('width', 'auto');
            contentElement.setStyle('margin-bottom', '0');
            contentElement.setStyle('display', 'none');
            i--;
        }

        if (this.titles.length > 0) {
            var selectedTabElement = this.titles[0];
            var selectedContentElement = this.contents[0];

            selectedTabElement.className = 'iocBlockTitle';
            selectedTabElement.setStyle('cursor', 'auto');
            selectedContentElement.setStyle('display', '');
        }
    },
    onTabClick: function(tabElement, contentElement) {

        for (i = 0; i < this.contents.length; i++) {
            this.contents[i].setStyle('display', 'none');
            this.titles[i].className = 'iocBlockTitleUnselected';
            this.titles.setStyle('cursor', 'pointer');
        }

        contentElement.setStyle('display', '');
        tabElement.className = 'iocBlockTitle';
        tabElement.setStyle('cursor', 'auto');
    },
    onTabMouseOver: function(tabElement) {
        if (tabElement.className != 'iocBlockTitle') {
            tabElement.className = 'iocBlockTitleOver';
        }
    },
    onTabMouseOut: function(tabElement) {
        if (tabElement.className == 'iocBlockTitleOver') {
            tabElement.className = 'iocBlockTitleUnselected';
        }
    }
});


////////////////////////////
/// Tabbed Content Block ///
////////////////////////////
var TabbedContentBlock = new Class({
    Extends: TabbedBlock,
    initialize: function(tabbedBlockContainerId) {
        this.parent(tabbedBlockContainerId, '.iocTabbedContentBlockCopy');
    }
});


////////////////////////////
/// Tabbed Video Block ///
////////////////////////////
var TabbedVideoBlock = new Class({
    Extends: TabbedBlock,
    initialize: function(tabbedBlockContainerId) {
        this.parent(tabbedBlockContainerId, '.iocVideoBlock');
    },
    onTabClick: function(tabElement, contentElement) {
        this.parent(tabElement, contentElement);
        if (!$chk(this.tabbedBlockContainer)) { return; }

        var flashObject = contentElement.getElement('object');
        var allFlashObject = this.tabbedBlockContainer.getElements('object');
        var length = allFlashObject.length;

        for (i = 0; i < length; i++) {
            var currentFlashObject = allFlashObject[i];
            if (currentFlashObject.id != flashObject.id) {
                try {
                    currentFlashObject.closeSwfVideoStream();
                }
                catch (e) {
                    //alert('function does not exist');
                }
            }
            else {
                try {
                    currentFlashObject.resumeSwfVideoStream();
                }
                catch (e) {
                    //alert('function does not exist');
                }
            }
        }
    }
});

////////////////////////
/// Send To A Friend ///
////////////////////////
var SendToFriend = new Class(
{
    initialize: function(receiverAddressId, senderEmailId, copyFormId, successfulMessageControlId, unsuccessfulMessageControlId, sendButtonId, languageCode, itemProperty) {
        if (!receiverAddressId || !senderEmailId || !copyFormId || !successfulMessageControlId || !unsuccessfulMessageControlId || !sendButtonId || !languageCode) { return; } //if undefined do nothing
        this.languageCode = languageCode;
        this.receiverAddress = $(receiverAddressId);
        this.senderEmail = $(senderEmailId);
        this.sendButton = $(sendButtonId);
        this.copyForm = $(copyFormId);
        this.itemProperty = itemProperty;
        this.successfulMessageControl = $(successfulMessageControlId);
        this.unsuccessfulMessageControl = $(unsuccessfulMessageControlId);
        if (!this.receiverAddress || !this.senderEmail || !this.sendButton || !this.copyForm || !this.successfulMessageControl || !this.unsuccessfulMessageControl) { return; }
        this.sendButton.set('href', 'javascript:;');
        this.JSONConnection = new Request.JSON({ url: "/AjaxScripts/SendToFriend.svc/send", onSuccess: this.onDataRetrieved.bind(this), onFailure: this.onFailure.bind(this) });
        this.sendButton.addEvent('click', this.retrieveData.bind(this));
    },
    // It looks what we need to be careful with the order to match the order of the WCF service
    retrieveData: function() {
        //Omniture Tag Send Email
        s.linkTrackVars = "events,prop7,prop8,eVar15";
        s.linkTrackEvents = "event14";
        s.prop7 = "Sent to a friend Complete";
        s.prop8 = this.itemProperty;
        s.events = "event14";
        s.eVar15 = this.itemProperty;
        s.tl(this, "o", "CIO-send-complete");
        var parameters = new Object();
        parameters.receiver = this.receiverAddress.value;
        parameters.sender = this.senderEmail.value;
        parameters.copy = this.copyForm.checked;
        parameters.languageCode = this.languageCode;
        this.JSONConnection.get(parameters);
    },
    onDataRetrieved: function(data) {
        // The REST service does not return anything. If the http response is 200, this is a success
        // If the status code is 500, it is a failure and it is dealt by onFailure.
        //omniture Tag Send Mail success
        this.unsuccessfulMessageControl.setStyle('display', 'none');
        this.successfulMessageControl.setStyle('visibility', 'visible');
        this.successfulMessageControl.setStyle('display', 'block');

    },
    onFailure: function() {
        this.successfulMessageControl.setStyle('display', 'none');
        this.unsuccessfulMessageControl.setStyle('visibility', 'visible');
        this.unsuccessfulMessageControl.setStyle('display', 'block');
    }
});

////////////////////////////
/// Custom Dropdown List ///
////////////////////////////
window.addEvent('load', function() {
    $$('.iocCustomSelect').each(function(item) { new CustomSelect(item); });
    $$('.iocPaginationCustomSelect').each(function(item) { new PaginationCustomSelect(item); });
    $$('.iocCustomCheckBox').each(function(item) { new CustomCheckBox(item); });
});

var AjaxCustomSelect = new Class(
{
    initialize: function(selectId, associatedSelectId, languageCode, serviceUrl, selectedValue) {
        this.languageCode = languageCode;
        this.selectedValue = selectedValue;
        if (!selectId || !associatedSelectId || !this.languageCode) { return; } //if undefined do nothing
        this.selectElement = $(selectId);
        this.associatedSelect = $(associatedSelectId);
        if (!this.selectElement || !this.associatedSelect) { return; }
        this.JSONConnection = new Request.JSON({ url: serviceUrl, onSuccess: this.onDataRetrieved.bind(this) });
        this.associatedSelect.addEvent('changed', this.retrieveData.bind(this));
        this.retrieveData();
    },
    retrieveData: function() {
        var parameters = new Object();
        parameters.filter = this.associatedSelect.value;
        parameters.languageCode = this.languageCode;
        this.JSONConnection.get(parameters);
    },
    onDataRetrieved: function(data) {
        if ($chk(data)) {
            var iocCustomSelect = this.selectElement.getParent();
            var selectContainer = this.selectElement.getParent().getElement('.selectContainer');

            if ($chk(selectContainer)) {
                selectContainer.destroy(); //remove events and all sub children
                iocCustomSelect.removeEvents();
            }

            this.selectElement.options.length = 0;

            var receivedOptions = data.content;
            var len = receivedOptions.length;

            for (i = 0; i < len; i++) {
                var receivedOption = receivedOptions[i];
                this.selectElement.options[i] = new Option(receivedOption.text, receivedOption.value);
                this.selectElement.options[i].selected = ($chk(this.selectedValue) && receivedOption.value == this.selectedValue);
            }

            this.customSelect = new CustomSelect(iocCustomSelect);
        }
    }
});

var CustomSelectCount = 0; /* Required for IE Positioning Bug */
var CustomSelect = new Class(
{
    initialize: function(selectContainerId) {
        if (!selectContainerId) { return; } // If undefined do nothing
        var selectContainer = $(selectContainerId);
        if (!selectContainer) { return; }
        this.selectElement = selectContainer.getElement('select');
        this.selectedOptionInList = false;
        this.isListOppenned = false;

        /* Required for IE Positioning Bug */
        if (selectContainer.getStyle('z-index') == 0) {
            selectContainer.setStyle('z-index', (6999 - CustomSelectCount));
            CustomSelectCount++;
        }

        var customSelectContainer = new Element('span', {
            'class': 'selectContainer'
        });

        this.selectedOptionContainer = new Element('span', {
            'class': 'selectedOptionContainer'
        });

        this.selectedOption = new Element('span', {
            'class': 'selectedOption'
        });

        this.optionsContainer = new Element('span', {
            'class': 'optionsContainer',
            'style': 'display:none;position:absolute;overflow-y:auto;overflow-x:hidden;'
        });

        selectContainer.addEvent('mouseenter', this.onMouseEnter.bindWithEvent(this));
        selectContainer.addEvent('mouseleave', this.onMouseLeave.bindWithEvent(this));

        this.selectedOptionContainer.addEvent('click', this.onCustomSelectClick.bindWithEvent(this));

        customSelectContainer.inject(selectContainerId, 'top');
        this.selectedOptionContainer.inject(customSelectContainer);
        this.selectedOption.inject(this.selectedOptionContainer);
        this.optionsContainer.inject(customSelectContainer);

        this.selectElement.addEvent('changed', this.onSelectedOptionChanged.bindWithEvent(this));

        //this part has been highly optimized dont touch unless you know exactly what you are doing.
        //this applies to any functions used within that part
        this.customOptions = new Array();

        var len = this.selectElement.length;

        for (i = 0; i < len; i++) {
            var option = this.selectElement[i];
            var newCustomOption = $(document.createElement('span'));
            newCustomOption.innerHTML = option.text;
            newCustomOption.title = option.text;
            newCustomOption.value = option.value;
            this.optionsContainer.appendChild(newCustomOption);
            this.customOptions[i] = newCustomOption;

            if (option.selected == true) {
                if (this.selectedOptionInList) { this.selectedOptionInList.className = ''; }
                this.selectedOptionInList = newCustomOption;
                newCustomOption.className = 'selectedOptionInList';
                this.selectedOption.innerHTML = option.text;
            }

            newCustomOption.addEvent('click', this.onOptionClick.bind(this))
        }
        //end of optimized part
        this.selectElement.setStyle('display', 'none'); //hide original select
    },
    onMouseEnter: function() {
        this.showRollover();
    },
    onMouseLeave: function() {
        if (this.isListOppenned == false) {
            this.hideRollover();
        }
    },
    onSelectedOptionChanged: function() {
        var len = this.customOptions.length;
        var selectedValue = this.selectElement.value;
        for (i = 0; i < len; i++) {
            var item = this.customOptions[i];
            if (selectedValue == item.value) {
                this.selectedOptionInList.className = '';
                item.className = 'selectedOptionInList';
                this.selectedOptionInList = item;
                this.selectedOption.innerHTML = this.selectedOptionInList.innerHTML;
            }
        }
    },
    onOptionClick: function(e) {
        this.selectElement.value = e.target.value;
        this.selectElement.fireEvent('changed');
    },
    onCustomSelectClick: function(e) {
        if (this.isListOppenned == true) {
            this.hideOptions();
        } else {
            new Event(e).stop();
            this.showOptions();
        }
    },
    showOptions: function() {
        if (this.isListOppenned == false) {
            this.isListOppenned = true;
            document.addEvent('click', this.hideOptions.bind(this));
            this.showRollover();
            this.optionsContainer.setStyles({ 'display': 'block', 'z-index': 9999 });
        }
    },
    hideOptions: function() {
        if (this.isListOppenned == true) {
            this.isListOppenned = false;
            document.removeEvent('click', this.hideOptions);
            this.hideRollover();
            this.optionsContainer.setStyles({ 'display': 'none', 'z-index': 1 });
        }
    },
    showRollover: function() {
        this.selectedOptionContainer.setStyle('background-position', '100% 100%');
        this.selectedOption.setStyle('background-position', '0% 100%');
    },
    hideRollover: function() {
        this.selectedOptionContainer.setStyle('background-position', '100% 0%');
        this.selectedOption.setStyle('background-position', '0% 0%');
    }
});

var PaginationCustomSelect = new Class({
    Implements: Events,
    Extends: CustomSelect,
    onSelectedOptionChanged: function() {
        var len = this.customOptions.length;
        var selectedValue = this.selectElement.value;
        location = selectedValue;
    }
});

////////////////////////
/// Custom check box ///
////////////////////////
var CustomCheckBox = new Class(
{
    initialize: function(checkBoxContainerId) {
        if (!checkBoxContainerId) { return; } //if undefined do nothing
        this.checkBoxContainer = $(checkBoxContainerId);
        if (!this.checkBoxContainer) { return; }
        this.checkBoxElement = $(checkBoxContainerId).getElement('input[type="checkbox"]');
        if (!this.checkBoxElement) { return; }

        this.customCheckBox = new Element('span', {
            'html': '&nbsp;'
        });

        if (this.checkBoxElement.checked == true) {
            this.customCheckBox.addClass('checked');
        }

        this.customCheckBox.inject(this.checkBoxElement, 'after');

        this.checkBoxElement.addEvent('changed', this.onChange.bind(this));
        this.checkBoxContainer.addEvent('click', this.onClick.bind(this));
        this.checkBoxElement.setStyle('display', 'none'); //hide original checkbox
    },
    onClick: function() {
        if (this.checkBoxElement.checked == true) {
            this.checkBoxElement.checked = false;
        }
        else {
            this.checkBoxElement.checked = true;
        }
        this.checkBoxElement.fireEvent('changed');
    },
    onChange: function() {
        if (this.checkBoxElement.checked == true) {
            this.customCheckBox.addClass('checked');
        }
        else {
            this.customCheckBox.removeClass('checked');
        }
    }
});


////////////////////////////////
/// Custom Radio button list ///
////////////////////////////////
/* Needs one of the RadioButton Id or Group Name to work.
It Will figure out all Radiobutton associated to the one specified*/
var CustomRadioButtonList = new Class(
{
    initialize: function(radioButtonIdOrGroupName) {
        if (!radioButtonIdOrGroupName) { return; } //if undefined do nothing
        var radioButton = document.getElementById(radioButtonIdOrGroupName); //try to get it by id
        if (!radioButton) {//if not defined then it was a group name
            this.radioButtons = document.getElements('input[name=' + radioButtonIdOrGroupName + ']');
        }
        else {//else use htmlElement to retrieve Group name
            if (!radioButton.name) { return; }
            this.radioButtons = document.getElements('input[name=' + radioButton.name + ']');
        }
        //get all radio buttons on the page

        if (!this.radioButtons) { return; }

        this.customRadios = new Array();
        this.radioButtons.each(function(item, index) {
            var OmnitureTag = item.getProperty('omnitureonclick');
            if ($chk(OmnitureTag)) {
                var customRadio = new Element('span', {
                    'onclick': OmnitureTag, 'html': '&nbsp;'
                });
            }
            else {
                var customRadio = new Element('span', {
                    'html': '&nbsp;'
                });
            }

            if (item.checked == true) {
                customRadio.addClass('checked');
            }

            customRadio.inject(item, 'after');
            item.setStyle('display', 'none'); //hide original radio

            item.addEvent('changed', this.onChange.bind(this));
            customRadio.getParent().addEvent('click', this.onClick.pass(item, this));

            this.customRadios[index] = customRadio;

        }, this);
    },
    onClick: function(radioElement) {
        if (radioElement.checked != true) {
            radioElement.checked = true;
        }
        radioElement.fireEvent('changed');
    },
    onChange: function() {
        this.radioButtons.each(function(item, index) {
            var customRadio = this.customRadios[index];

            if (item.checked == true) {
                customRadio.addClass('checked');
            }
            else {
                customRadio.removeClass('checked');
            }
        }, this);
    }
});

////////////////////
/// OnClickPopup ///
////////////////////
var OverlayPopups = new Array();
var OnClickPopup = new Class(
{
    Implements: Options,
    options: {
        hasOverlay: false,
        overlayOpacity: 0.8
    },
    initialize: function(openButtons, closeButtons, popupId, options) {

        if (!openButtons || !closeButtons || !popupId) { return; } //if undefined do nothing

        this.background = $('background_div');
        this.openButtons = $$(openButtons);
        this.closeButtons = $$(closeButtons);
        this.toggleButtons = new Array();
        this.popup = $(popupId);
        this.setOptions(options);

        if (!this.openButtons || !this.closeButtons || !this.popup || !this.background) { return; } //if undefined do nothing

        // If  popup includes overlay
        if (this.options.hasOverlay) {

            OverlayPopups.include(this.popup);
            this.overlay = new Element('div', { 'class': 'iocOverlay', 'styles': { 'opacity': 0, 'visibility': 'visible', 'height': 0, 'overflow': 'hidden'} }).inject($(document.body));
            this.popup.inject($(document.body));
            this.FxOverlayFadeIn = new Fx.Morph(this.overlay, { duration: 'short', transition: Fx.Transitions.Sine.easeInOut });
            this.FxOverlayFadeOut = new Fx.Morph(this.overlay, { duration: 'short', transition: Fx.Transitions.Sine.easeInOut });
            this.FxOverlayFadeOut.addEvent('complete', this.onFxOverlayFadeOutCompleted.bind(this));
            this.overlay.addEvent('click', this.hide.bindWithEvent(this));
        }

        this.openButtons.each(function(item) {
            // Replace all href to javascript
            if (item.get('tag') == 'a') {
                item.setProperty('href', 'javascript:;');
            }
            // If a button can close as well move to toggle array
            if (this.closeButtons.contains(item)) {
                this.toggleButtons.include(item);
                this.closeButtons.erase(item);
                this.openButtons.erase(item);
            }
            else {
                item.addEvent('click', this.show.bindWithEvent(this));
            }
        }, this);

        this.closeButtons.each(function(item) {
            if (item.get('tag') == 'a') {
                item.setProperty('href', 'javascript:;');
            }

            item.addEvent('click', this.hide.bindWithEvent(this));
        }, this);

        this.toggleButtons.each(function(item) {
            item.addEvent('click', this.toggle.bindWithEvent(this));
        }, this);

        this.FxPopupFadeIn = new Fx.Morph(this.popup, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
        this.FxPopupFadeOut = new Fx.Morph(this.popup, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
        this.FxPopupFadeIn.addEvent('complete', this.onFxPopupFadeInCompleted.bind(this));
        this.FxPopupFadeOut.addEvent('complete', this.onFxPopupFadeOutCompleted.bind(this));

        this.opened = false;
        this.popup.setStyle('opacity', '0');

        // Required to fix IE scrolling issue
        this.popup.setStyle('display', 'none');
    },
    show: function() {
        if (!this.opened) {
            // Required to fix IE scrolling issue, but must be first 
            // to ensure getSize function later returns correct value
            this.popup.setStyle('display', '');

            // If  popup includes overlay
            if (this.options.hasOverlay) {
                var scrollSizeY = $(window).getScrollSize().y;
                var scrollSizeX = $(window).getScrollSize().x;
                var scrollLeft = $(window).getScroll().x;
                var scrollTop = $(window).getScroll().y;
                var windowSizeY = $(window).getSize().y;
                var windowSizeX = $(window).getSize().x;
                var popupSizeX = this.popup.getSize().x;
                var popupSizeY = this.popup.getSize().y;

                this.overlay.setStyles({ 'height': scrollSizeY + scrollTop, 'top': -scrollTop, 'width': scrollSizeX });
                this.FxOverlayFadeIn.start({ 'opacity': this.options.overlayOpacity });

                this.popup.setStyle('left', '50%');
                this.popup.setStyle('margin-left', windowSizeX > popupSizeX ? -(popupSizeX / 2) + scrollLeft : -(windowSizeX / 2) + scrollLeft);
                this.popup.setStyle('margin-top', scrollTop + (windowSizeY / 2) - (popupSizeY / 2));
            }
            this.opened = true;
            this.FxPopupFadeIn.start({
                'opacity': '1'
            });
        }
    },
    onFxPopupFadeInCompleted: function() {
        if (this.options.hasOverlay) {
            var scrollSizeY = $(window).getScrollSize().y;
            var scrollSizeX = $(window).getScrollSize().x;

            // This needs to be on the popup fade in so that the popup width has
            // adjusted the scroll size before the overlay and background are updated
            this.overlay.setStyles({ 'height': scrollSizeY, 'top': 0, 'width': scrollSizeX });
            this.background.setStyle('width', scrollSizeX);
        }
    },
    onFxPopupFadeOutCompleted: function() {
        // Required to fix IE scrolling issue
        this.popup.setStyle('display', 'none');
    },
    onFxOverlayFadeOutCompleted: function() {
        if (this.options.hasOverlay) {
            this.background.setStyle('width', '100%');
            this.overlay.setStyles({ 'height': 0, 'top': 0, 'opacity': 0, 'width': '100%' });
        }
    },
    hide: function() {
        if (this.opened) {
            this.FxPopupFadeOut.start({
                'opacity': '0'
            });

            // If  popup includes overlay
            if (this.options.hasOverlay) {
                this.FxOverlayFadeOut.start({ 'opacity': 0 });
            }

            this.opened = false;
        }
    },
    toggle: function() {
        if (this.opened) {
            this.hide();
        }
        else {
            this.show();
        }
    }
});

////////////////////
var OverlayPopups = new Array();
var OnClickPopin = new Class(
{
    Implements: Options,
    options: {
        hasOverlay: false,
        overlayOpacity: 0.8
    },
    initialize: function(popupId, PopinId, options) {



        if (!popupId) { return; } //if undefined do nothing

        this.background = $('background_div');
        this.toggleButtons = new Array();
        this.popup = $(popupId);
        this.setOptions(options);

        if (!this.popup || !this.background) { return; } //if undefined do nothing

        // If  popup includes overlay
        if (this.options.hasOverlay) {

            OverlayPopups.include(this.popup);
            this.overlay = new Element('div', { 'class': 'iocOverlay', 'styles': { 'opacity': 0, 'visibility': 'visible', 'height': 0, 'overflow': 'hidden'} }).inject($(document.body));
            this.popup.inject($(document.body));
            this.FxOverlayFadeIn = new Fx.Morph(this.overlay, { duration: 'short', transition: Fx.Transitions.Sine.easeInOut });
            this.FxOverlayFadeOut = new Fx.Morph(this.overlay, { duration: 'short', transition: Fx.Transitions.Sine.easeInOut });
            this.FxOverlayFadeOut.addEvent('complete', this.onFxOverlayFadeOutCompleted.bind(this));
            // this.overlay.addEvent('click', this.hide.bindWithEvent(this));
        }

        this.toggleButtons.each(function(item) {
            item.addEvent('click', this.toggle.bindWithEvent(this));
        }, this);

        this.FxPopupFadeIn = new Fx.Morph(this.popup, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
        this.FxPopupFadeOut = new Fx.Morph(this.popup, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });
        this.FxPopupFadeIn.addEvent('complete', this.onFxPopupFadeInCompleted.bind(this));
        this.FxPopupFadeOut.addEvent('complete', this.onFxPopupFadeOutCompleted.bind(this));

        this.opened = false;
        this.popup.setStyle('opacity', '0');

        // Required to fix IE scrolling issue
        this.popup.setStyle('display', 'none');

        // PopIn
        if (Cookie.read("Popins") != null)
            var c = Cookie.read("Popins");
        else {
            var c = "";
        }

        var tabCookie = c.split(",");
        if (tabCookie.contains(PopinId)) {
            this.hide();
        }
        else {
            Cookie.write("Popins", c + "," + PopinId, { path: "/", duration: 365 });
            this.show();
        }

    },

    show: function() {
        if (!this.opened) {
            // Required to fix IE scrolling issue, but must be first
            // to ensure getSize function later returns correct value

            this.popup.setStyles({
                visibility: 'visible',
                display: ''
            });

            //  this.popup.setStyle('display', '');

            // If  popup includes overlay
            if (this.options.hasOverlay) {
                var scrollSizeY = $(window).getScrollSize().y;
                var scrollSizeX = $(window).getScrollSize().x;
                var scrollLeft = $(window).getScroll().x;
                var scrollTop = $(window).getScroll().y;
                var windowSizeY = $(window).getSize().y;
                var windowSizeX = $(window).getSize().x;
                var popupSizeX = this.popup.getSize().x;
                var popupSizeY = this.popup.getSize().y;

                this.overlay.setStyles({ 'height': scrollSizeY + scrollTop, 'top': -scrollTop, 'width': scrollSizeX });
                this.FxOverlayFadeIn.start({ 'opacity': this.options.overlayOpacity });

                this.popup.setStyle('left', '50%');
                this.popup.setStyle('margin-left', windowSizeX > popupSizeX ? -(popupSizeX / 2) + scrollLeft : -(windowSizeX / 2) + scrollLeft);
                this.popup.setStyle('margin-top', scrollTop + (windowSizeY / 2) - (popupSizeY / 2));
            }
            this.opened = true;

            this.FxPopupFadeIn.start({
                'opacity': '1'
            });
        }
    },
    onFxPopupFadeInCompleted: function() {
        if (this.options.hasOverlay) {
            var scrollSizeY = $(window).getScrollSize().y;
            var scrollSizeX = $(window).getScrollSize().x;

            // This needs to be on the popup fade in so that the popup width has
            // adjusted the scroll size before the overlay and background are updated
            this.overlay.setStyles({ 'height': scrollSizeY, 'top': 0, 'width': scrollSizeX });
            this.background.setStyle('width', scrollSizeX);
        }
    },
    onFxPopupFadeOutCompleted: function() {
        // Required to fix IE scrolling issue
        this.popup.setStyle('display', 'none');
    },
    onFxOverlayFadeOutCompleted: function() {
        if (this.options.hasOverlay) {
            this.background.setStyle('width', '100%');
            this.overlay.setStyles({ 'height': 0, 'top': 0, 'opacity': 0, 'width': '100%' });
        }
    },
    hide: function() {
        if (this.opened) {
            this.FxPopupFadeOut.start({
                'opacity': '0'
            });

            // If  popup includes overlay
            if (this.options.hasOverlay) {
                this.FxOverlayFadeOut.start({ 'opacity': 0 });
            }

            this.opened = false;
        }
    },
    toggle: function() {
        if (this.opened) {
            this.hide();
        }
        else {
            this.show();
        }
    }
});

////////////////////
/// OnEnterPopup ///
////////////////////
var OnEnterPopup = new Class(
{
    initialize: function(toggleButtons, popupId) {
        if (!toggleButtons || !popupId) { return; } //if undefined do nothing

        this.toggleButtons = $$(toggleButtons);
        this.popup = $(popupId);

        if (!this.toggleButtons || !this.popup) { return; } //if undefined do nothing

        this.toggleButtons.each(function(item) {
            item.addEvent('mouseenter', this.show.bindWithEvent(this));
            item.addEvent('mouseleave', this.hide.bindWithEvent(this));
        }, this);

        this.FxPopupFadeInOut = new Fx.Morph(this.popup, { duration: 'short', transition: Fx.Transitions.Sine.easeOut });

        this.openned = false;
        this.popup.setStyle('opacity', '0');
        this.popup.setStyle('display', '');

    },
    show: function() {
        if (!this.openned) {
            this.FxPopupFadeInOut.start({
                'opacity': '1'
            });
            this.openned = true;
        }
    },
    hide: function() {
        if (this.openned) {
            this.FxPopupFadeInOut.start({
                'opacity': '0'
            });

            this.openned = false;
        }
    }
});

//////////////////////////////
/// Custom Period Selector ///
//////////////////////////////
var CustomPeriodSelector = new Class(
{
    initialize: function(containerId) {
        if (!containerId) { return; } //if undefined do nothing
        this.container = $(containerId);
        if (!this.container) { return; }

        var selectElements = this.container.getElements('select');
        if (!selectElements || selectElements.length < 2) { return; }

        this.lowerSelect = selectElements[0];
        this.upperSelect = selectElements[1];

        //if not same size something is wrong
        if (this.lowerSelect.length != this.upperSelect.length) { return; }
        //if no options something is wrong
        if (this.lowerSelect.length == 0) { return; }

        var sliderContainer = new Element('div', { 'class': 'iocSliderContainer' });
        var slider = new Element('div', { 'class': 'iocSlider' });
        var leftKnob = new Element('div', { 'class': 'iocLeftKnob' });
        var rightKnob = new Element('div', { 'class': 'iocRightKnob' });
        this.clipedContent = new Element('div', { 'class': 'iocClippedContent' });
        this.limitsText = new Element('span', { 'class': 'iocLimitsText' });

        sliderContainer.inject(this.upperSelect, 'after');
        slider.inject(sliderContainer);
        this.clipedContent.inject(slider);
        leftKnob.inject(slider);
        rightKnob.inject(slider);
        this.limitsText.inject(sliderContainer, 'after');

        this.leftSlider = new CustomSlider(slider, leftKnob, this.lowerSelect.length);
        this.rightSlider = new CustomSlider(slider, rightKnob, this.lowerSelect.length);

        this.lowerSelect.addEvent('changed', this.reset.bind(this));
        this.upperSelect.addEvent('changed', this.reset.bind(this));

        this.leftSlider.addEvent('complete', this.onSlidersComplete.bindWithEvent(this));
        this.rightSlider.addEvent('complete', this.onSlidersComplete.bindWithEvent(this));

        this.leftSlider.addEvent('stepchanged', this.onSlidersStepChanged.bindWithEvent(this));
        this.rightSlider.addEvent('stepchanged', this.onSlidersStepChanged.bindWithEvent(this));

        this.leftSlider.addEvent('positionchanged', this.onSlidersPositionChanged.bindWithEvent(this));
        this.rightSlider.addEvent('positionchanged', this.onSlidersPositionChanged.bindWithEvent(this));

        this.leftSlider.addEvent('sliderclick', this.onClick.bindWithEvent(this));
        this.rightSlider.addEvent('sliderclick', this.onClick.bindWithEvent(this));

        this.rightSlider.setPosition(this.rightSlider.getContainerSize().x - this.rightSlider.getKnobSize().x);

        this.onSlidersComplete();

        var labelElements = this.container.getElements('label');

        for (i = 0; i < labelElements.length; i++) {
            labelElements[i].setStyle('display', 'none');
        }

        this.lowerSelect.setStyle('display', 'none');
        this.upperSelect.setStyle('display', 'none');
        this.container.setStyle('display', '');
    },
    onClick: function(position) {
        if (position > this.rightSlider.getPosition()) {
            this.rightSlider.setPosition(position - this.rightSlider.getKnobSize().x / 2);
        }
        else if (position < this.leftSlider.getPosition()) {
            this.leftSlider.setPosition(position - this.leftSlider.getKnobSize().x / 2);
        }
    },
    onSlidersComplete: function() {
        this.leftSlider.setMax(this.rightSlider.getPosition() - this.rightSlider.getKnobSize().x);
        this.rightSlider.setMin(this.leftSlider.getPosition() + this.leftSlider.getKnobSize().x);
    },
    onSlidersStepChanged: function() {
        this.lowerSelect.selectedIndex = this.leftSlider.step;
        this.upperSelect.selectedIndex = this.rightSlider.step;
        this.limitsText.innerHTML = this.lowerSelect.options[this.lowerSelect.selectedIndex].text + ' - ' + this.upperSelect.options[this.upperSelect.selectedIndex].text;
    },
    onSlidersPositionChanged: function() {
        var leftPos = this.leftSlider.getPosition() + this.leftSlider.getKnobSize().x / 2;
        var rightPos = this.rightSlider.getPosition() + this.rightSlider.getKnobSize().x / 2;
        var height = this.clipedContent.getSize().y;

        var clip = 'rect(0px, ' + rightPos + 'px,' + height + 'px,' + leftPos + 'px)';
        this.clipedContent.setStyle('clip', clip);
    },
    reset: function() {
        this.upperSelect.value = this.upperSelect.options[this.upperSelect.options.length - 1].value;
        this.leftSlider.setPosition(this.leftSlider.min);
        this.rightSlider.setPosition(this.rightSlider.max);
        this.onSlidersComplete();
    }
});

/////////////////////
/// Custom Slider ///
/////////////////////
var CustomSlider = new Class(
{
    Implements: Events,
    initialize: function(container, knob, stepCount) {
        if (!container || !knob || !stepCount) { return; }
        this.container = container;
        this.knob = knob;
        this.stepCount = stepCount;
        this.step = 0;

        this.min = 0;
        this.max = this.container.getSize().x - this.knob.getSize().x;

        this.knob.setStyle('left', 0);

        this.bound = {
            'onMouseUp': this.onMouseUp.bind(this),
            'onMouseMove': this.onMouseMove.bind(this),
            'onMouseDown': this.onMouseDown.bind(this),
            'onSliderClick': this.onSliderClick.bind(this)
        };

        this.knob.addEvent('mousedown', this.bound.onMouseDown);
        this.container.addEvent('click', this.bound.onSliderClick);
    },
    onSliderClick: function(e) {
        var evt = new Event(e);
        evt.stop();
        var position = evt.page.x - this.container.getPosition().x;
        this.fireEvent("sliderclick", position);
    },
    onMouseDown: function(e) {
        var evt = new Event(e);
        evt.stop();
        document.addEvent('mouseup', this.bound.onMouseUp);
        document.addEvent('mousemove', this.bound.onMouseMove);
    },
    onMouseUp: function(e) {
        var evt = new Event(e);
        evt.stop();
        document.removeEvent('mouseup', this.bound.onMouseUp);
        document.removeEvent('mousemove', this.bound.onMouseMove);
        this.fireEvent("complete");
    },
    onMouseMove: function(e) {
        var evt = new Event(e);
        evt.stop();
        var position = evt.page.x - this.container.getPosition().x - this.knob.getSize().x / 2;
        this.setPosition(position);
    },
    setMin: function(min) {
        this.min = min;
    },
    setMax: function(max) {
        this.max = max;
    },
    getPosition: function() {
        return this.knob.getStyle('left').toInt();
    },
    setPosition: function(position) {
        if (position > this.max) {
            this.knob.setStyle('left', this.max);
        }
        else if (position < this.min) {
            this.knob.setStyle('left', this.min);
        }
        else {
            this.knob.setStyle('left', position);
        }

        var finalPosition = this.knob.getStyle('left').toInt();

        var tempStep = Math.round(finalPosition * (this.stepCount - 1) / (this.container.getSize().x - this.knob.getSize().x));

        this.fireEvent("positionchanged");

        if (this.step != tempStep) {
            this.step = tempStep;
            this.fireEvent("stepchanged");
            this.fireEvent("complete");
        }
    },
    getKnobSize: function() {
        return this.knob.getSize();
    },
    getContainerSize: function() {
        return this.container.getSize();
    }
});

///////////////
/// Ratings ///
///////////////
var Rating = new Class(
{
    Implements: [Options],

    options: {
        containerId: "id",
        currentRating: 1,
        rateFunction: null,
        enabled: true
    },

    initialize: function(options) {
        this.setOptions(options);

        var container = $(options.containerId);
        if (container) {
            this.ratings = container.getElements('a');

            this.ratings.each(function(item, index) {
                item.addEvent('mouseenter', this.onRatingMouseEnter.bindWithEvent(this));
                item.addEvent('click', this.onRatingMouseClick.bindWithEvent(this));
            }, this);

            container.addEvent('mouseleave', this.onRatingMouseLeave.bindWithEvent(this));
        }

    },
    disable: function() {
        this.options.enabled = false;
    },
    onRatingMouseEnter: function(e) {
        if (this.options.enabled) {
            this.animate(e.target.innerHTML.toInt());
        }
    },
    onRatingMouseClick: function(e) {
        if (this.options.enabled) {
            e.stopPropagation();
            this.rate(e.target.innerHTML.toInt());
        }
    },
    onRatingMouseLeave: function(e) {
        if (this.options.enabled) {
            this.clear(this.options.currentRating);
        }
    },
    animate: function(number) {
        this.ratings.each(function(item, index) {
            if (index < number) {
                item.className = 'selected';
            }
            else {
                item.className = '';
            }
        });
    },
    rate: function(number) {
        this.options.rateFunction(number);
    },
    clear: function(number) {
        this.ratings.each(function(item, index) {
            if (index < number) {
                item.className = 'active';
            }
            else {
                item.className = '';
            }
        });
    }
});

/////////////////////////////////
/// LightBox + Popup Resizing ///
/////////////////////////////////

// Adjust the overlay when 
// the browser window is resized
window.addEvent('resize', function() {
    // Reset background width
    var background = $('background_div');
    if (!background) { return; }
    background.setStyles({ 'width': '100%' });

    // Get page container
    var page = $('center_content_div');
    if (!page) { return; }

    // Get important dimensions
    var pageSizeX = page.getSize().x;
    var backgroundSizeY = background.getSize().y;
    var windowSizeX = $(window).getSize().x;
    var windowSizeY = $(window).getSize().y;
    var scrollLeft = $(window).getScroll().x;
    var scrollTop = $(window).getScroll().y;

    var marginTop = 0;
    var marginLeft = 0;
    var contentSizeX = 0;
    var contentSizeY = 0;
    var contentOffsetX = 0;
    var contentOffsetY = 0;
    var windowOffsetX = (pageSizeX - windowSizeX) / 2;

    this.popupVisible = false;

    // Get lightbox
    var center = $(document.body).getElement('.iocCenter');
    if (center && center.getStyle('opacity') > 0) {
        contentSizeX = center.getSize().x;
        contentSizeY = center.getSize().y;

        marginTop = center.getStyle('top').toInt();
        if (windowSizeX > pageSizeX && windowSizeX > contentSizeX) {
            marginLeft = -(contentSizeX / 2);
        }
        else {
            marginLeft = windowSizeX > contentSizeX ? -(contentSizeX / 2) + scrollLeft : -(windowSizeX / 2) + scrollLeft;
        }

        contentOffsetX = (contentSizeX + marginLeft - windowOffsetX) - (pageSizeX / 2);
        contentOffsetY = (contentSizeY + (marginTop * 2)) - backgroundSizeY;

        center.setStyle('margin-left', marginLeft);
        this.popupVisible = true;
    }
    else {
        // Iterate through popups
        OverlayPopups.each(function(popup) {
            if (popup.getStyle('opacity') > 0) {
                contentSizeX = popup.getSize().x;
                contentSizeY = popup.getSize().y;

                marginTop = scrollTop + (windowSizeY / 2) - (contentSizeY / 2);
                if (windowSizeX > pageSizeX && windowSizeX > contentSizeX) {
                    marginLeft = -(contentSizeX / 2);
                }
                else {
                    marginLeft = windowSizeX > contentSizeX ? -(contentSizeX / 2) + scrollLeft : -(windowSizeX / 2) + scrollLeft;
                }

                contentOffsetX = (contentSizeX + marginLeft - windowOffsetX) - (pageSizeX / 2);
                contentOffsetY = (contentSizeY + marginTop * 2) - backgroundSizeY;

                popup.setStyle('margin-left', marginLeft);
                popup.setStyle('margin-top', marginTop);
                this.popupVisible = true;
            }
        }, this);
    }

    // There is no need to update the overlays if no popups are currently visible
    if (!this.popupVisible) { return; }

    // Set scroll size after center correction
    var scrollSizeY = $(window).getScrollSize().y;
    var scrollSizeX = $(window).getScrollSize().x;

    // Iterate through overlays
    this.overlays = $(document.body).getElements('.iocOverlay');
    if (!this.overlays) { return; }
    for (i = 0; i < this.overlays.length; i++) {
        overlay = this.overlays[i];
        if (overlay.getStyle('opacity') > 0) {

            var contentTotalX = pageSizeX + (contentOffsetX) + 1; // + 1px for IE centering issue
            var contentTotalY = backgroundSizeY + (contentOffsetY);

            // Correct horizontal
            if (windowSizeX <= pageSizeX) {
                if (contentTotalX <= pageSizeX) {
                    overlay.setStyle('width', pageSizeX);
                    background.setStyle('width', pageSizeX);
                }
                else {
                    overlay.setStyle('width', contentTotalX);
                    background.setStyle('width', contentTotalX);
                }
            }
            else {
                if (contentTotalX <= windowSizeX) {
                    overlay.setStyle('width', windowSizeX);
                    background.setStyle('width', windowSizeX);
                }
                else {
                    overlay.setStyle('width', contentTotalX);
                    background.setStyle('width', contentTotalX);
                }
            }

            // Correct vertical
            if (windowSizeY <= backgroundSizeY) {
                if (contentTotalY <= backgroundSizeY) {
                    overlay.setStyles({ 'height': backgroundSizeY, 'top': 0 });
                }
                else {
                    overlay.setStyles({ 'height': contentTotalY, 'top': 0 });
                }
            }
            else {
                if (contentTotalY <= windowSizeY) {
                    overlay.setStyles({ 'height': windowSizeY, 'top': 0 });
                }
                else {
                    overlay.setStyles({ 'height': contentTotalY, 'top': 0 });
                }
            }
        }
    }
});

////////////////////////////
/// LightBox MediaPlayer ///
////////////////////////////
var iocLightBox = new Class({
    Implements: Options,
    options: {
        overlayOpacity: 0.8
    },
    initialize: function(linkId, closeText, currentImageID, options) {

        if (!linkId) { return; }
        this.link = $(linkId);
        if (!this.link) { return; }

        if (!currentImageID) { return; }
        this.currentImage = $(currentImageID);
        if (!this.currentImage) { return; }

        this.background = $('background_div');

        if (!this.background) { return; }

        this.canvasCompleted = false;
        this.isAnimationFinished = false;
        this.isImagePreloaded = false;


        this.setOptions(options);
        this.overlay = new Element('div', { 'class': 'iocOverlay', 'styles': { 'opacity': 0, 'visibility': 'visible', 'height': 0, 'overflow': 'hidden'} }).inject($(document.body));
        this.center = new Element('div', { 'class': 'iocCenter', 'styles': { 'width': 300, 'height': 300, 'marginLeft': -(300 / 2), 'display': 'none', 'opacity': 0} }).inject($(document.body)); // Display style is required to fix IE scrolling issue
        this.closeArea = new Element('div', { 'class': 'iocCloseArea' }).inject(this.center);
        this.closeTextElement = new Element('a', { 'href': 'javascript:;', "title": closeText }).inject(this.closeArea);
        this.closeTextElement.innerHTML = closeText;

        this.canvas = new Element('div', { 'class': 'iocCanvas' }).inject(this.center);
        this.canvas.setStyles({ 'width': 300 - this.canvas.getStyle('padding-left').toInt() - this.canvas.getStyle('padding-right').toInt(), 'height': 300 - this.canvas.getStyle('padding-top').toInt() - this.canvas.getStyle('padding-bottom').toInt() - this.closeArea.getStyle('height').toInt() });

        this.imageTrans = new Element('img', { 'src': '/resources/Images/Misc/Transparent.gif', 'styles': { 'visibility': 'visible', 'position': 'absolute'} }).inject(this.canvas);
        this.image = new Element('img', { 'src': '/resources/Images/Misc/loading.gif' }).inject(this.canvas);
        this.imageOriginalWidth = 48;  // Was this.image.width but Firefox is unable retrieve this accurately at this point (14 not 48)
        this.imageOriginalHeight = 48; // Was this.image.height but Firefox is unable retrieve this accurately at this point (14 not 48)
        this.image.setStyles({ 'margin-top': (this.canvas.getStyle('height').toInt() / 2) - (this.imageOriginalHeight / 2) });

        this.textArea = new Element('div', { 'class': 'iocCenterText', 'styles': { 'display': 'none'} }).inject(this.center);
        this.titleElement = new Element('h5').inject(this.textArea);
        this.descriptionElement = new Element('div').inject(this.textArea);

        this.FxOverlayFadeIn = new Fx.Morph(this.overlay, { duration: 'normal', transition: Fx.Transitions.Sine.easeInOut });
        this.FxOverlayFadeOut = new Fx.Morph(this.overlay, { duration: 'normal', transition: Fx.Transitions.Sine.easeInOut });
        this.FxCenterResize = new Fx.Morph(this.center, { duration: 'normal', transition: Fx.Transitions.Sine.easeInOut });
        this.FxCanvasResize = new Fx.Morph(this.canvas, { duration: 'normal', transition: Fx.Transitions.Sine.easeInOut });
        this.FxImageFadeIn = new Fx.Morph(this.image, { duration: 'normal', transition: Fx.Transitions.Sine.easeInOut });

        this.link.addEvent('click', this.onAnchorClick.bind(this));
        this.overlay.addEvent('click', this.hide.bind(this));
        this.closeArea.addEvent('click', this.hide.bind(this));
        this.FxOverlayFadeIn.addEvent('complete', this.onFxOverlayFadeInCompleted.bind(this));
        this.FxOverlayFadeOut.addEvent('complete', this.onClosed.bind(this));
        this.FxCanvasResize.addEvent('complete', this.onFxCanvasResizeCompleted.bind(this));
        this.FxCenterResize.addEvent('complete', this.onFxCenterResizeCompleted.bind(this));
    },
    onAnchorClick: function(event) {
        event.stop();
        this.preloadImage(this.link.href);
        var thumbnail = this.currentImage;
        if ($chk(thumbnail)) {
            this.titleElement.innerHTML = thumbnail.getProperty('title');
            this.descriptionElement.innerHTML = thumbnail.getProperty('alt');
        }

        var scrollSizeY = $(window).getScrollSize().y;
        var scrollSizeX = $(window).getScrollSize().x;
        var scrollLeft = $(window).getScroll().x;

        this.center.setStyle('margin-left', this.center.getStyle('margin-left').toInt() + scrollLeft);
        this.overlay.setStyles({ 'height': scrollSizeY, 'top': 0, 'width': scrollSizeX });
        this.FxOverlayFadeIn.start({ 'opacity': this.options.overlayOpacity });
    },
    onFxOverlayFadeInCompleted: function() {
        this.isAnimationFinished = true;
        this.center.setStyles({ 'display': '', 'opacity': 1 }); // Display style is required to fix IE scrolling issue
        this.showImage();
    },
    onFxCanvasResizeCompleted: function() {
        var scrollSizeY = $(window).getScrollSize().y;
        var scrollSizeX = $(window).getScrollSize().x;

        this.canvasCompleted = true;
        this.overlay.setStyles({ 'height': scrollSizeY, 'top': 0, 'width': scrollSizeX });
        this.textArea.setStyles({ 'display': 'block', 'background-color': '#FFFFFF' });

        this.FxImageFadeIn.start({ 'opacity': 1 });
        this.FxCenterResize.start({ 'height': this.textArea.getStyle('margin-top').toInt() + this.textArea.getSize().y + this.center.getSize().y });
    },
    onFxCenterResizeCompleted: function() {
        if (this.canvasCompleted == true) {
            var scrollSizeY = $(window).getScrollSize().y;
            var scrollSizeX = $(window).getScrollSize().x;
            var backgroundSizeY = this.background.getSize().y;

            var marginTop = this.center.getStyle('top').toInt();
            var marginBottom = 0;

            // Required as IE doesn't always update this correctly via the animation
            var originalCenterSizeY = this.image.height + this.closeArea.getStyle('height').toInt() + this.canvas.getStyle('padding-top').toInt() + this.canvas.getStyle('padding-bottom').toInt();
            var correctedCenterSizeY = this.textArea.getStyle('margin-top').toInt() + this.textArea.getSize().y + originalCenterSizeY;
            this.center.setStyle('height', correctedCenterSizeY);

            if (correctedCenterSizeY + (marginTop * 2) > backgroundSizeY) {
                marginBottom = marginTop;
            }

            this.overlay.setStyles({ 'height': scrollSizeY + marginBottom, 'top': 0, 'width': scrollSizeX });
            this.background.setStyle('width', scrollSizeX);
        }
    },
    onImagePreloaded: function() {
        this.isImagePreloaded = true;
        this.showImage();
    },
    onClosed: function() {
        this.background.setStyle('width', '100%');
        this.overlay.setStyles({ 'height': 0, 'top': 0, 'opacity': 0, 'width': '100%' });
        this.center.setStyles({ 'width': 300, 'height': 300, 'marginLeft': -(300 / 2), 'display': 'none', 'opacity': 0 }); // Display style is required to fix IE scrolling issue
        this.canvas.setStyles({ 'width': 300 - this.canvas.getStyle('padding-left').toInt() - this.canvas.getStyle('padding-right').toInt(), 'height': 300 - this.canvas.getStyle('padding-top').toInt() - this.canvas.getStyle('padding-bottom').toInt() - this.closeArea.getStyle('height').toInt() });
        this.textArea.setStyle('display', 'none');

        this.image.src = '/resources/Images/Misc/loading.gif';
        this.image.width = this.imageOriginalWidth;
        this.image.height = this.imageOriginalHeight;
        this.image.setStyle('margin-top', (this.canvas.getStyle('height').toInt() / 2) - (this.imageOriginalHeight / 2));
    },
    preloadImage: function(src) {
        this.preloadedImage = $(new Image());
        this.preloadedImage.addEvent('load', this.onImagePreloaded.bind(this));
        this.preloadedImage.src = src;
    },
    showImage: function() {
        if (this.isAnimationFinished == true && this.isImagePreloaded == true) {
            this.isAnimationFinished = false;
            this.isImagePreloaded = false;
            this.image.setStyle('opacity', 0);
            this.image.src = this.preloadedImage.src;
            this.image.width = this.preloadedImage.width;
            this.image.height = this.preloadedImage.height;
            this.image.setStyle('margin-top', 0);
            this.imageTrans.width = this.preloadedImage.width;
            this.imageTrans.height = this.preloadedImage.height;

            var scrollLeft = $(window).getScroll().x;
            var windowSizeX = $(window).getSize().x;

            var centerSizeY = this.image.height + this.closeArea.getStyle('height').toInt() + this.canvas.getStyle('padding-top').toInt() + this.canvas.getStyle('padding-bottom').toInt();
            var centerSizeX = this.image.width + this.canvas.getStyle('padding-left').toInt() + this.canvas.getStyle('padding-right').toInt();

            this.FxCenterResize.start({
                'height': centerSizeY,
                'width': centerSizeX,
                'margin-left': windowSizeX > centerSizeX ? -(centerSizeX / 2) + scrollLeft : -(windowSizeX / 2) + scrollLeft
            });

            this.FxCanvasResize.start({
                'height': this.image.height,
                'width': this.image.width
            });
        }
    },
    hide: function() {
        this.center.setStyle('opacity', 0);
        this.FxOverlayFadeOut.start({ 'opacity': 0 });
    }
});

////////////////////////
/// TipsQuestionaire ///
////////////////////////
var TipsQuestionaire = new Class(
{
    initialize: function(containerId) {
        if (!containerId) { return; }
        this.container = $(containerId);
        if (!this.container) { return; }

        this.JSONConnection = new Request.JSON({ url: "/AjaxScripts/SendComments.svc/send", onSuccess: this.onMailSent.bind(this), onFailure: this.onFailure.bind(this) });

        this.questions = this.container.getElements('.iocTipsBlockQuestionaireQuestion');
        this.commentBlock = this.container.getElement('.iocTipsBlockQuestionaireLeaveComments');

        this.commentTextArea = this.commentBlock.getElement('textarea');

        //  var buttonSend = this.commentBlock.getElement('a');
        //   buttonSend.set('href', 'javascript:;');
        //   buttonSend.addEvent('click', this.sendEmail.bind(this));

        this.moveToNextQuestion();
    },
    moveToNextQuestion: function() {
        if (!$chk(this.currentQuestionIndex)) {
            this.currentQuestionIndex = 0;
            this.container.setStyle('display', 'block');
        }
        else {
            this.currentQuestionIndex++;
        }

        if (this.currentQuestionIndex < this.questions.length) {
            var currentQuestion = this.questions[this.currentQuestionIndex];
            currentQuestion.setStyle('display', 'block');
            var inputs = currentQuestion.getElements('input');
            this.currentThankYouBlock = currentQuestion.getElement('.iocTipsBlockQuestionaireResponseThankYou');
            this.currentYesNoBlock = currentQuestion.getElement('.iocTipsBlockQuestionaireResponseYesNo');

            inputs[0].addEvent('changed', function() {
                this.currentThankYouBlock.setStyle('display', 'block');
                this.currentYesNoBlock.setStyle('display', 'none');
                this.moveToNextQuestion();
            } .bind(this));

            inputs[1].addEvent('changed', function() {
                this.currentThankYouBlock.setStyle('display', 'block');
                this.currentYesNoBlock.setStyle('display', 'none');
                this.commentBlock.setStyle('display', 'block');
            } .bind(this));
        }
    },
    // It looks what we need to be careful with the order to match the order of the WCF service
    sendEmail: function() {
        var parameters = new Object();
        parameters.comment = this.commentTextArea.value;
        this.JSONConnection.get(parameters);
        this.commentBlock.setStyle('display', 'none');
    },
    onMailSent: function(data) {
        // The REST service does not return anything. If the http response is 200, this is a success
        // If the status code is 500, it is a failure and it is dealt by onFailure.
        //alert('success');
    },
    onFailure: function() {
        //alert('failed');
    }
});

function htmlEncode(input) {
    var t = document.createTextNode(input),
      e = document.createElement('div');
    e.appendChild(t);
    return e.innerHTML;
}
function htmlDecode(input) {
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes[0].nodeValue;
}

//////////////////////
/// SliderLightbox ///
//////////////////////

var SliderLightbox = new Class({
    Implements: [Options, Events],
    options: {//set all the options here
        overlayOpacity: 0.7,
        topPosition: 50,
        initialWidth: 250,
        initialHeight: 250,
        videoWidth: 480,
        videoHeight: 360,
        videoPlayerPath: '/Resources/Flash/RIA/VideoPlayer/moduleRIA-videoplayer.swf',
        canvasBorderWidth: '0px',
        canvasBorderColor: '#000000',
        canvasPadding: '0px',
        resizeDuration: 500,
        resizeTransition: 'sine:in:out',
        autoPlay: false,
        autoPlayDelay: 7,
        removeTitle: false,
        autoSize: true,
        maxHeight: 0, //only if autoSize==true
        imageOfText: ' / ',
        onXmlGalleries: $empty,
        onClosed: $empty,
        onFileReady: $empty
    },
    initialize: function(options) {
        this.setOptions(options);
        this.autoPlayBkup = { autoPlayDelay: this.options.autoPlayDelay, autoPlay: this.options.autoPlay };
        this.fullOptionsBkup = {};
        this.galleries = [];
        this.families = [];
        this.xmlFiles = [];
        this.loadedImages = []; //to check the preloaded images
        this.currentFile = null;
        this.currentIndex = null;
        this.currentGallery = null;
        this.currentRequest = null;
        this.currentResponse = null;
        this.mode = null; //'singleFile','fileGallery'
        this.closed = true;
        this.busy = true; //to control keyboard and autoplay events
        this.paused = true;
        this.fileReady = false; //to prevent overlapping loadFile calls via next_prev_aux()
        this.eventsok = false;
        this.first = true; //true if it's the first file since it opened
        this.activated = false; //true after initSliderLightbox
        this.intObj = null;
        this.formtags = null;
        this.prepareGalleries();
        if (this.options.overlayOpacity == 0) { this.options.overlayOpacity = 0.0001 }
        this.saveOptions(); //then use restoreOptions()
        if (this.galleries.length == 0) { return; };
        this.initSliderLightbox(true);
        this.showAutoLightbox(); //Show the autolightbox if it exists
    }, //end init
    initSliderLightbox: function(checkTags) {
        if (checkTags) { this.formtags = $$('select', 'textarea'); }
        this.prepareHTML();
        this.prepareEffects();
        this.prepareEvents();
        this.activated = true;
    },
    openSliderLightbox: function(gallery, index) {
        this.closed = false;
        if (this.formtags && this.formtags.length != 0) { this.formtags.setStyle('display', 'none') };
        this.overlay.setStyles({ 'top': -$(window).getScroll().y, 'height': $(window).getScrollSize().y + $(window).getScroll().y, 'position': 'absolute', 'z-index': 10000 });
        this.center.setStyles({ 'top': $(window).getScroll().y + this.options.topPosition, 'position': 'absolute', 'z-index': 10000 });
        this.currentGallery = gallery;
        this.currentIndex = index;
        this.overlay.tween('opacity', this.options.overlayOpacity); //onComplete: center.tween opacity
        if (gallery.length == 1) {
            this.mode = 'singleFile';
            this.caption.setStyles({ 'font-size': '12px', 'font-weight': 'bold' });
            this.loadFile(gallery[index], index);
        } else {
            this.mode = 'fileGallery';
            var playpauseWidth = 0;
            $$(this.prev, this.next, this.count).setStyle('display', 'block');
            if (this.options.autoPlay) {
                this.playpause.setStyle('display', 'block');
                playpauseWidth = this.playpause.getSize().x;
            }
            var border = this.center.getStyle('border-right-width').toInt(); //border-right is just ok for design purposes..
            var navWidth = this.prev.getSize().x + this.next.getSize().x + this.close.getSize().x + playpauseWidth + border;
            this.navigation.setStyle('width', navWidth);
            this.caption.setStyles({ 'margin-right': navWidth, 'font-size': '12px', 'font-weight': 'bold' });
            this.description.setStyle('margin-right', navWidth);
            var next = (index != gallery.length - 1) ? gallery[index + 1] : gallery[0];
            var prev = (index != 0) ? gallery[index - 1] : gallery[gallery.length - 1];
            var preloads = (prev == next) ? [prev] : [prev, next]; //if gallery.length == 2, then prev == next

            this.loadFile(gallery[index], preloads);
        }
    },
    loadFile: function(fileObj, preloads) {
        this.fileReady = false;
        var swf = this.checkFileType(fileObj, 'swf');
        if (!swf) {
            if (!this.loadedImages.contains(fileObj.retrieve('href'))) { this.center.addClass('mbLoading'); }
            this.loadImage(fileObj.retrieve('href'));
        } else {
            this.loadSwf(fileObj);
        }
        if (preloads) { this.preloadFiles(preloads); }
    },
    preloadFiles: function(preloads) {
        preloads.each(function(fileObj, index) {
            var swf = this.checkFileType(fileObj.retrieve('href'), "swf");
            if (!swf) { this.preloadImage(fileObj.retrieve('href')); }
        }, this);
    },
    loadImage: function(file) {
        var imageAsset = new Asset.image(file, { onload: function(img) {
            if (!this.loadedImages.contains(file)) { this.loadedImages.push(file); }; //see next/prev events
            this.currentFile = img;
            this.loadAux(this.currentFile);
        } .bindWithEvent(this)
        });
    },
    preloadImage: function(file) {
        if (!this.loadedImages.contains(file)) {
            var imageAsset = new Asset.image(file, { onload: function(img) {
                this.loadedImages.push(file);
            } .bindWithEvent(this)
            });
        }
    },
    loadSwf: function(swf) {
        var swfObj = new Swiff(this.options.videoPlayerPath + '?' + swf.retrieve('href').split('?')[1], {
            //var swfObj = new Swiff(swf.retrieve('href'), {
            width: swf.retrieve('width').toInt(),
            height: swf.retrieve('height').toInt(),
            params: { wMode: 'transparent', swLiveConnect: 'false', salign: 'TL',
                loop: 'false',
                quality: 'high',
                allowFullScreen: 'true',
                allowScriptAccess: 'always'
            }
        });
        this.currentFile = swfObj;
        this.loadAux(swf);
    },
    loadAux: function(file) {
        this.fileReady = true;
        this.fireEvent('fileReady');
        $$(this.caption, this.description, this.navigation).setStyle('visibility', 'hidden');
        this.navigation.setStyle('height', '');
        $$(this.next, this.prev, this.close).setStyle('backgroundPosition', '0 0');
        this.showFile(file);
    },
    showFile: function(file) {
        if (this.closed) { return; };
        var fileSize = new Hash();
        var centerSize = new Hash();
        var targetSize, canvasSize;
        var canvasAddSize, gap, b, p, d;
        targetSize = canvasSize = {};
        canvasAddSize = gap = b = p = d = 0;
        if (this.options.canvasBorderWidth.toInt() != 0 && this.canvas.getStyle('borderWidth').toInt() == 0) {
            b = this.options.canvasBorderWidth + ' solid ' + this.options.canvasBorderColor;
            this.canvas.setStyle('border', b);
        }
        if (this.options.canvasPadding.toInt() != 0 && this.canvas.getStyle('padding').toInt() == 0) {
            p = this.options.canvasPadding;
            this.canvas.setStyle('padding', p);
        }
        canvasSize = this.canvas.getSize();
        canvasAddSize = this.canvas.getStyle('borderWidth').toInt() * 2 + this.canvas.getStyle('padding').toInt() * 2;
        this.canvas.setStyles({ 'opacity': 0, 'width': '', 'height': '' });
        if (!file.retrieve('width')) {
            fileSize = fileSize.extend(file.getProperties('width', 'height')).map(function(item) { return item.toInt(); });
            if (this.options.autoSize) {
                fileSize = this.computeSize(fileSize);
                file.setProperties({ 'width': fileSize.width, 'height': fileSize.height });
                this.imageTrans.setProperties({ 'width': fileSize.width, 'height': fileSize.height });
            }
        } else {
            fileSize.extend({ 'height': file.retrieve('height').toInt(), 'width': file.retrieve('width').toInt() });
            this.imageTrans.setStyle('visibility', 'hidden');
        }
        centerSize = centerSize.extend(this.center.getStyles('width', 'height')).map(function(item) { return item.toInt(); });
        if (fileSize.width != centerSize.width) {
            targetSize.width = fileSize.width + canvasAddSize;
            targetSize.marginLeft = -(targetSize.width / 2).round();
        }
        gap = (canvasSize.y - canvasAddSize > 0) ? centerSize.height - canvasSize.y : 0;
        targetSize.height = fileSize.height + canvasAddSize + gap;
        this.canvas.setStyles({ 'width': fileSize.width, 'height': fileSize.height });
        this.center.removeClass('mbLoading');
        if (this.first) { d = 500; this.first = false; }
        (function() { this.center.morph(targetSize); }).delay(d, this)
    },
    computeSize: function(oSize) {
        var size = oSize;
        var wSize = window.getSize();
        var baseSize = { width: wSize.x - 60, height: wSize.y - 68 - this.options.topPosition * 2 };
        var ratio;
        var check;
        var max = Math.max(baseSize.height, baseSize.width);
        if (max == baseSize.width) {
            ratio = max / size.width;
            check = 'height';
        } else {
            ratio = max / size.height;
            check = 'width';
        }
        ratio = (ratio <= 1) ? ratio : 1;
        size = size.map(function(item) { return Math.floor(item * ratio); });
        ratio = (baseSize[check] / size[check] <= 1) ? baseSize[check] / size[check] : 1;
        size = size.map(function(item) { return Math.floor(item * ratio); });
        if (this.options.maxHeight > 0) {
            ratio = (this.options.maxHeight / size.height < 1) ? this.options.maxHeight / size.height : 1;
            size = size.map(function(item) { return Math.floor(item * ratio); });
        }
        return size;
    },
    showGallery: function(opt) {
        if (!opt || !opt.gallery) { return; }
        var fileIndex = ($chk(opt.index)) ? opt.index : 0;
        var g = this.getGallery(opt.gallery);
        var auto = false;
        var d;
        if (opt.autoplay || (g['options'] && g['options'].autoplay)) { auto = true; }
        if (g != -1 && !this.opened) {
            if (auto) {
                d = (opt && opt.delay) ? opt.delay : (g['options'] && g['options'].delay) ? g['options'].delay : this.autoPlayDelay;
                this.startAutoPlay({ gallery: g, index: fileIndex, delay: d });
            } else {
                this.openSliderLightbox(g, fileIndex);
            }
        }
    },
    addGalleries: function(xmlfile) {
        this.currentRequest = new Request({
            method: 'get',
            autoCancel: true,
            url: xmlfile,
            onRequest: function() {
                //placeholder
            } .bindWithEvent(this),
            onSuccess: function(text, xml) {
                var t = text.replace(/(<a.+)\/>/gi, "$1></a>");
                this.setGalleries(new Element('div', { html: t }), xmlfile);
            } .bindWithEvent(this),
            onFailure: function(transport) { alert('SliderLightbox :: addGalleries: XML file path error or local Ajax test: please test addGalleries() on-line'); }
        });
        this.currentRequest.send();
    },
    setGalleries: function(container, xmlfile) {
        if (!this.xmlFiles.contains(xmlfile)) { this.xmlFiles.push(xmlfile); }
        var c = container;
        var galleries = c.getElements('.gallery');
        var links = [];
        var aplist = [];
        galleries.each(function(gallery, i) {
            var obj = {
                gallery: gallery.getProperty('name'),
                autoplay: Boolean(gallery.getProperty('autoplay')),
                delay: Number(gallery.getProperty('delay'))
            }
            var l = gallery.getChildren('a');
            var lx = l.map(function(link) { return link.setProperty('rel', 'sliderLightbox[' + obj.gallery + ']'); });
            links.push(lx);
            if (obj.autoplay) { aplist.push(obj); }
        });
        this.prepareGalleries(links.flatten());
        this.setAutoPlay(aplist);
        if (!this.activated) { this.initSliderLightbox(); }
        this.fireEvent('xmlGalleries');
    },
    checkFileType: function(file, type) {
        var href = null;
        if ($type(file) != 'string') { href = file.retrieve('href'); }
        else { href = file; }
        var regexp = new RegExp("\.(" + type + ")$", "i");
        return href.split('?')[0].test(regexp);
    },
    getGallery: function(gallery) {
        var f = null;
        if (gallery.test(/^sliderLightbox/i)) {
            f = this.families;
        } else {
            f = this.families.map(function(item) {
                var trimmed = item.trim();
                var name = trimmed.slice(0, trimmed.length).substr(8);
                var cleanName = name.replace(/(.+)]$/, "$1");
                return cleanName;
            });
        }
        var i = f.indexOf(gallery);
        var g = (i != -1) ? this.galleries[i] : i;
        return g;
    },
    setFileProps: function(fileObj, propString) {
        if (propString == "") {
            propString = 'width:' + this.options.videoWidth + ',height:' + this.options.videoHeight;
        }
        var s = propString.split(',');
        s.each(function(p, i) {
            var clean = p.trim().split(':');
            fileObj.store(clean[0].trim(), clean[1].trim())
        }, this);
    },
    changeOptions: function(obj) {
        if (!obj) { return; }
        this.setOptions(obj);
        this.center.get('morph').setOptions({ transition: this.options.resizeTransition, duration: this.options.resizeDuration });
    },
    saveOptions: function(obj) {
        if ($chk(obj)) {
            this.fullOptionsBkup = obj;
        } else {
            this.fullOptionsBkup = this.options;
        }
    },
    restoreOptions: function() {
        this.setOptions(this.fullOptionsBkup);
        var b = this.options.canvasBorderWidth + ' solid ' + this.options.canvasBorderColor;
        this.canvas.setStyles({ 'border': b, 'padding': this.options.canvasPadding });
        this.center.get('morph').setOptions({ transition: this.options.resizeTransition, duration: this.options.resizeDuration });
    },
    reloadGalleries: function() {
        this.galleries = [];
        this.families = [];
        this.formtags = $$('select', 'textarea');
        if (!this.activated) { this.initSliderLightbox(false); }
        this.prepareGalleries();
        this.removeGalleriesEvents();
        this.setGalleriesEvents();
        if (this.xmlFiles.length == 0) { return; }
        this.xmlFiles.each(function(xmlfile, index) {
            this.addGalleries(xmlfile);
        } .bind(this));
    },
    setAutoPlay: function(list) {
        var l = ($type(list) == 'object') ? [list] : list;
        l.each(function(item) {
            var g = this.getGallery(item.gallery);
            if (g == -1) { return; }
            var a = (item.autoplay == true) ? item.autoplay : false;
            var d = ($chk(item.delay) && a) ? item.delay : this.options.autoPlayDelay;
            g['options'] = { autoplay: a, delay: d }
        }, this);
    },
    startAutoPlay: function(opt) {

        var g = -1;
        var i, d;
        if (opt && opt.gallery) {
            if ($type(opt.gallery) == 'array') { g = opt.gallery }
            else if ($type(opt.gallery) == 'string') {
                g = this.getGallery(opt.gallery);
            }
        }
        if (g == -1) { g = this.galleries[0]; }
        d = (opt && opt.delay && ($type(opt.delay) == 'number')) ? opt.delay * 1000 : (g['options'] && g['options'].delay) ? g['options'].delay * 1000 : this.options.autoPlayDelay * 1000;
        i = (opt && opt.index && ($type(opt.index) == 'number')) ? opt.index : 0;
        if (d < this.options.resizeDuration * 2) { d = this.options.resizeDuration * 2 };
        this.options.autoPlayDelay = d / 1000;
        if (!this.options.autoPlay) { this.setOptions({ autoPlay: true, autoPlayDelay: this.options.autoPlayDelay }); }
        if (this.closed) {
            this.openSliderLightbox(g, i);
            if (this.mode != 'fileGallery') { return; }
            this.addEvent('fileReady', function() {
                this.intObj = this.next_prev_aux.periodical(d, this, [null, 'next']);
                this.removeEvents('fileReady');
            } .bindWithEvent(this));
        } else {
            if (!this.closed) { this.next_prev_aux(null, 'next'); }
            this.intObj = this.next_prev_aux.periodical(d, this, [null, 'next']);
        }
        this.paused = false;
    },
    stopAutoPlay: function() {
        if (this.intObj) { $clear(this.intObj); this.intObj = null; }
        this.playpause.setStyle('backgroundPosition', '0 -44px');
        this.paused = true;
    },
    removeGalleriesEvents: function() {
        this.galleries.each(function(gallery) {
            $$(gallery).removeEvents('click');
        }, this);
    },
    setGalleriesEvents: function() {
        this.galleries.each(function(gallery) {
            $$(gallery).addEvent('click', function(e) {
                var button = ($(e.target).match('a')) ? $(e.target) : $(e.target).getParent('a');
                e.preventDefault();
                var g = this.getGallery(button.rel);
                if (g.options && g.options.autoplay) {
                    this.setOptions({ autoPlay: g.options.autoplay, autoPlayDelay: g.options.delay });
                }
                if (this.options.autoPlay) {
                    this.startAutoPlay({ gallery: gallery, index: gallery.indexOf(button) });
                } else {
                    this.openSliderLightbox(gallery, gallery.indexOf(button));
                }
            } .bindWithEvent(this));
        }, this);
    },
    prepareEvents: function(xml) {
        this.setGalleriesEvents();
        this.next.addEvent('click', this.next_prev_aux.bindWithEvent(this, 'next'));
        this.prev.addEvent('click', this.next_prev_aux.bindWithEvent(this, 'prev'));
        $$(this.next, this.prev, this.close).addEvents({
            'mouseover': function() { this.setStyle('backgroundPosition', '0 -22px'); },
            'mouseout': function() { this.setStyle('backgroundPosition', '0 0'); }
        });
        $(window.document).addEvent('keydown', function(e) {
            if (this.mode != 'fileGallery' || this.busy == true) { return; }
            if (e.key == 'right' || e.key == 'space') { this.next_prev_aux(e, 'next'); }
            else if (e.key == 'left') { this.next_prev_aux(e, 'prev'); }
            else if (e.key == 'esc') { this.closeSliderLightbox(); }
        } .bindWithEvent(this));
        this.playpause.addEvents({
            'mouseover': function(e) {
                if (this.paused == false) { this.playpause.setStyle('backgroundPosition', '0 -22px'); }
                else { this.playpause.setStyle('backgroundPosition', '0 -66px'); }
            } .bindWithEvent(this),
            'mouseout': function() {
                if (this.paused == false) { this.playpause.setStyle('backgroundPosition', '0 0'); }
                else { this.playpause.setStyle('backgroundPosition', '0 -44px'); }
            } .bindWithEvent(this),
            'click': function() {
                if (this.paused == false) {
                    this.stopAutoPlay();
                    this.paused = true;
                    this.playpause.setStyle('backgroundPosition', '0 -66px');
                } else {
                    var d = (this.currentGallery.options && this.currentGallery.options.delay) ? this.currentGallery.options.delay : this.options.autoPlayDelay;
                    this.startAutoPlay({ gallery: this.currentGallery, index: this.currentIndex + 1, delay: d });
                    this.paused = false;
                    this.playpause.setStyle('backgroundPosition', '0 0');
                }
            } .bindWithEvent(this)
        });
        this.overlay.get('tween').addEvent('onComplete', function() {
            if (this.overlay.getStyle('opacity') == this.options.overlayOpacity) {
                this.center.tween('opacity', 1);
            } else if (this.overlay.getStyle('opacity') == 0) {
                this.overlay.setStyles({ 'height': 0, 'top': '' });
            };
        } .bindWithEvent(this));
        this.center.get('morph').addEvent('onComplete', function() {
            if ($type(this.currentFile) == "element") {
                this.canvas.grab(this.imageTrans);
                this.canvas.grab(this.currentFile);
            } else {
                (function() { this.canvas.grab(this.imageTrans); this.canvas.grab(this.currentFile); }).delay(200, this);
            }
            this.canvas.tween('opacity', 1);
            var c = (!(this.mode == 'showThisImage')) ? this.currentGallery[this.currentIndex].retrieve('alt') : '';
            if ($chk(c)) { this.caption.innerHTML = c; };
            var d = (!(this.mode == 'showThisImage')) ? this.currentGallery[this.currentIndex].retrieve('title') : this.specialDescription;
            if ($chk(d)) {
                this.description.innerHTML = d;
                //this.description.innerHTML += '<br /><iframe src="http://www.facebook.com/plugins/like.php?href=' + this.currentGallery[this.currentIndex].retrieve('medialink') + '&amp;layout=standard&amp;show_faces=true&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true">';
                this.description.innerHTML += this.currentGallery[this.currentIndex].retrieve('medialink');
            };
            if (this.mode == 'fileGallery') {
                this.count.appendText((this.currentIndex + 1) + ' ' + this.options.imageOfText + ' ' + this.currentGallery.length);
            }
            var currentCenterHeight = this.center.getStyle('height').toInt();
            this.navigation.setStyle('height', this.bottom.getStyle('height').toInt()); //to have the right-border height == total bottom height
            var bottomSize = this.bottom.getSize().y;
            var targetOffset = (currentCenterHeight > this.canvas.getSize().y) ? (this.bottom.getSize().y + this.canvas.getSize().y) - currentCenterHeight : bottomSize;
            this.bottom.setStyle('display', 'none'); //to avoid rendering problems during setFinalHeight
            this.center.retrieve('setFinalHeight').start(currentCenterHeight, currentCenterHeight + targetOffset);
        } .bindWithEvent(this));
        this.center.retrieve('setFinalHeight').addEvent('onComplete', function() {
            this.bottom.setStyles({ 'visibility': 'visible', 'display': 'block' });
            $$(this.caption, this.description, this.navigation).setStyle('visibility', 'visible');
            var scrollSize = $(window).getScrollSize().y;
            var scrollTop = $(window).getScroll().y;
            this.overlay.setStyles({ 'height': scrollSize + scrollTop, 'top': -scrollTop });
            this.busy = false;
        } .bindWithEvent(this));
        window.addEvent('resize', function() {
            if (this.overlay.getStyle('opacity') == 0) { return; }; //resize only if visible
            var scrollSize = $(window).getScrollSize().y;
            var scrollTop = $(window).getScroll().y;
            this.overlay.setStyles({ 'height': scrollSize + scrollTop, 'top': -scrollTop });
        } .bindWithEvent(this));
        $$(this.overlay, this.close).addEvent('click', this.closeSliderLightbox.bindWithEvent(this));
        this.eventsok = true;
    },
    next_prev_aux: function(e, direction) {
        if (e) {
            e.preventDefault();
            this.stopAutoPlay();
        } else {
            if (this.busy || !this.fileReady) { return; } //stop autoplay()
        }
        this.busy = true; //for keyboard and autoplay
        var i, _i;
        if (direction == "next") {
            i = (this.currentIndex != this.currentGallery.length - 1) ? this.currentIndex += 1 : this.currentIndex = 0;
            _i = (this.currentIndex != this.currentGallery.length - 1) ? this.currentIndex + 1 : 0;
        } else {
            i = (this.currentIndex != 0) ? this.currentIndex -= 1 : this.currentIndex = this.currentGallery.length - 1;
            _i = (this.currentIndex != 0) ? this.currentIndex - 1 : this.currentGallery.length - 1;
        };
        this.canvas.empty();
        this.caption.empty();
        this.description.empty();
        this.count.empty();
        this.loadFile(this.currentGallery[i], [this.currentGallery[_i]]);
    },
    prepareEffects: function() {
        this.overlay.set('tween', { duration: 'short', link: 'cancel' });
        this.center.set('tween', { duration: 'short', link: 'chain' });
        this.center.set('morph', { duration: this.options.resizeDuration, link: 'chain', transition: this.options.resizeTransition });
        this.center.store('setFinalHeight', new Fx.Tween(this.center, { property: 'height', duration: 'short' }));
        this.canvas.set('tween', { link: 'chain' });
    },
    prepareGalleries: function(responseElements) {
        var sliderLightbox_a = [];
        var a_tags = (responseElements) ? responseElements : $$('a');
        a_tags.each(function(a) {
            if (a.rel && a.rel.test(/^sliderLightbox/i) && a.href.split('?')[0].test(/\.(gif|jpg|jpeg|png|swf)$/i)) {
                if (a.rel.length > 7 && !this.families.contains(a.rel)) { this.families.push(a.rel); };
                sliderLightbox_a.push(a);
            }
        }, this);
        sliderLightbox_a.each(function(a) {
            $(a).store('href', a.href);
            $(a).store('rel', a.rel);
            $(a).store('alt', a.getProperty('alt'));
            $(a).store('medialink', a.getProperty('medialink'));
            $(a).store('title', a.title);
            if (this.checkFileType(a.href, "swf")) { this.setFileProps($(a), a.rev); }
            if (this.options.removeTitle) { $(a).removeProperty('title'); }
            if (a.rel.length > 14) {
                this.families.each(function(f, i) {
                    if (a.rel == f) {
                        var gMounted = false;
                        var index;
                        this.galleries.each(function(g, k) {
                            if (g[0].rel == f) {
                                gMounted = true;
                                index = k;
                                return;
                            }
                        });
                        if (gMounted == true) { this.galleries[index].push($(a)); }
                        else { this.galleries.push([$(a)]); }
                    };
                }, this);
            } else { this.galleries.push([$(a)]); };
        }, this);
    },
    prepareHTML: function() {
        this.overlay = new Element('div', { 'id': 'mbOverlay', 'styles': { 'opacity': 0, 'visibility': 'visible', 'height': 0, 'overflow': 'hidden'} }).inject($(document.body));
        this.center = new Element('div', { 'id': 'mbCenter', 'styles': { 'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth / 2), 'opacity': 0} }).inject($(document.body));
        this.canvas = new Element('div', { 'id': 'mbCanvas' }).inject(this.center);
        this.imageTrans = new Element('img', { 'src': '/resources/Images/Misc/Transparent.gif', 'styles': { 'visibility': 'visible', 'position': 'absolute'} }).inject(this.canvas);
        this.bottom = new Element('div', { 'id': 'mbBottom' }).inject(this.center).setStyle('visibility', 'hidden');
        this.navigation = new Element('div', { 'id': 'mbNavigation' }).setStyle('visibility', 'hidden');
        this.caption = new Element('div', { 'id': 'mbCaption' }).setStyle('visibility', 'hidden');
        this.description = new Element('div', { 'id': 'mbDescription' }).setStyle('visibility', 'hidden');
        this.bottom.adopt(this.navigation, this.caption, this.description, new Element('div', { 'class': 'mbClear' }));
        this.close = new Element('a', { 'id': 'mbCloseLink' });
        this.next = new Element('a', { 'id': 'mbNextLink' });
        this.prev = new Element('a', { 'id': 'mbPrevLink' });
        this.playpause = new Element('a', { 'id': 'mbPlayPause' });
        this.count = new Element('span', { 'id': 'mbCount' });
        $$(this.next, this.prev, this.count, this.playpause).setStyle('display', 'none');
        this.navigation.adopt(this.close, this.next, this.prev, this.playpause, new Element('div', { 'class': 'mbClear' }), this.count);
    },
    closeSliderLightbox: function() {
        this.cancelAllEffects();
        this.stopAutoPlay();
        this.setOptions(this.autoPlayBkup);
        this.currentFile = null;
        this.currentIndex = null;
        this.currentGallery = null;
        this.currentRequest = null;
        this.currentResponse = null;
        $$(this.prev, this.next, this.playpause, this.count).setStyle('display', 'none');
        this.playpause.setStyle('backgroundPosition', '0 0');
        var border = this.center.getStyle('border-right-width').toInt();
        var navWidth = this.close.getSize().x + border;
        this.navigation.setStyles({ 'width': navWidth, 'height': '', 'visibility': 'hidden' });
        this.caption.setStyle('margin-right', navWidth);
        this.caption.empty();
        this.description.setStyle('margin-right', navWidth);
        this.description.empty();
        this.bottom.setStyles({ 'visibility': 'hidden', 'display': '' });
        this.canvas.setStyles({ 'opacity': 0, 'width': '', 'height': '' });
        this.canvas.empty();
        this.count.empty();
        this.center.setStyles({ 'opacity': 0, 'width': this.options.initialWidth, 'height': this.options.initialHeight, 'marginLeft': -(this.options.initialWidth / 2) });
        this.overlay.tween('opacity', 0); //see onComplete in prepareEvents() 
        if (this.formtags && this.formtags.length != 0) { this.formtags.setStyle('display', '') };
        this.mode = null;
        this.closed = true;
        this.first = true;
        this.fileReady = false;
        this.fireEvent('closed');
    },
    cancelAllEffects: function() {
        this.overlay.get('tween').cancel();
        this.center.get('morph').cancel();
        this.center.get('tween').cancel();
        this.center.retrieve('setFinalHeight').cancel();
        this.canvas.get('tween').cancel();
    },
    showAutoLightbox: function() {
        var autoGallery = this.getAutoLightboxGallery();
        if (autoGallery != undefined) {//If the page must show a lightbox by default
            this.openSliderLightbox(autoGallery, 0);
        }
    },
    getAutoLightboxGallery: function() {//Return the autolightbox's gallery if it exists
        var autoGallery = undefined;
        this.families.each(function(f, i) {
            if (f == "sliderLightbox[autoLightbox]") {
                autoGallery = this.galleries[i];
                return;
            }
        }, this);
        return autoGallery;
    }
});
window.addEvent('domready', function() {
    sliderLightbox = new SliderLightbox();
});

/////////////////////////
// OSCFilters Utilities /
/////////////////////////

var OSCFilters = new Class({
    initialize: function(filterListWithQueryString, goButtonId) {
        if (!filterListWithQueryString || !goButtonId) { return; }
        this.filterListWithQueryString = filterListWithQueryString;
        this.goButton = $(goButtonId);
        if (!this.filterListWithQueryString || !this.goButton) { return; }

        // this.filterListWithQueryString => "subcat:divSubCategories"
        this.valuesDictionary = new Object();

        // make sure that all elements are mootools elements
        for (var queryString in this.filterListWithQueryString) {
            var item = this.filterListWithQueryString[queryString];
            if (!(item instanceof Function)) {//if not a function
                this.filterListWithQueryString[queryString] = $(item);
            }
        }
        // set uri
        this.url = new URI(document.location.href);
        // attach events
        if (this.goButton.get('tag') == 'a') {
            this.goButton.href = 'javascript:;';
        }
        this.goButton.addEvent('click', this.goButtonClick.bind(this));
    },
    addQueryString: function(name, value) {
        var queryString = this.url.get('query');
        this.valuesDictionary = new Object();
        if ($chk(queryString)) {
            this.valuesDictionary = queryString.parseQueryString();
        }
        this.valuesDictionary[name] = value;
        this.url.clearData();
        this.url.setData(this.valuesDictionary);
    },
    removeQueryString: function(name) {
        var queryString = this.url.get('query');
        this.valuesDictionary = new Object();
        if ($chk(queryString)) {
            this.valuesDictionary = queryString.parseQueryString();
        }
        delete this.valuesDictionary[name];
        this.url.clearData();
        this.url.setData(this.valuesDictionary);
    },
    goButtonClick: function() {
        var count = 0;
        for (var queryString in this.filterListWithQueryString) {
            var initquery = this.filterListWithQueryString[queryString];
            var queryStringValues = '';
            if (!(initquery instanceof Function)) {//if not a function
                if (initquery.get('tag') == 'div') {
                    var children = document.getElementById(initquery.get('id')).getElementsByTagName('input');
                    if (!(children instanceof Function)) {
                        for (var item = 0; item < children.length; item++) {
                            var type = children[item].get('type');
                            //tag == 'input' && 
                            if (type == 'checkbox') {
                                if (children[item].checked == true) {
                                    count++;
                                    if (queryStringValues == '') {
                                        queryStringValues = children[item].value;
                                    }
                                    else {
                                        queryStringValues += '-' + children[item].value;
                                    }
                                }
                            }
                        }
                    }
                    this.removeQueryString(queryString);
                    if (count != children.length) {
                        this.addQueryString(queryString, queryStringValues);
                    }

                }
            }
        }
        this.executeFilter();
    },
    executeFilter: function() {
        this.url.go();
    }
});


/////////////////////////
//    YOG Utilities    //
/////////////////////////

var YogSearch = new Class({
    Implements: Events,
    initialize: function(searchBoxId, goButtonId, resultsUrl) {

        if (!resultsUrl || !goButtonId || !searchBoxId) { return; }

        // Set uri
        this.url = new URI(resultsUrl);

        this.goButton = $(goButtonId);
        this.searchBox = $(searchBoxId);

        // Attach events
        if (this.goButton.get('tag') == 'a') {
            this.goButton.href = 'javascript:;';
        }
        if (this.searchBox.get('tag') == 'a') {
            this.searchBox.href = 'javascript:;';
        }

        var _this = this;
        this.goButton.onclick = function() {
            _this.executeSearch();
        };

        this.searchBox.onkeypress = function(e) {
            var key;
            if (window.event) {
                key = window.event.keyCode;
            }   //IE
            else {
                key = e.which;
            }   //firefox
            if (key == 13) {
                _this.executeSearch();
                return false;
            }
        };
    },
    executeSearch: function() {
        var queryString = this.url.get('query');
        this.valuesDictionary = new Object();

        if ($chk(queryString)) {
            this.valuesDictionary = queryString.parseQueryString();
        }
        this.valuesDictionary["name"] = this.searchBox.value.replace("'", "%27");
        this.url.clearData();
        this.url.setData(this.valuesDictionary);
        this.url.go();
        this.url.go();
    }
});
