﻿/////////////////////
/// 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 false; }
        this.openButton = $(openButtonId);
        this.divPopup = $(divPopupId);
        this.closeButton = $(closeButtonId);

        if (!this.openButton || !this.closeButton || !this.divPopup) { return false; }

        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 false; }
        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));
        }
    }
}); 

///////////////////////
/// ShowAudioPlayer ///
///////////////////////
function showAudioPlayer(containerId, size, audioFileUrl) {
    if (!containerId || !size || !audioFileUrl) { return false; }
    
    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 false; }
        this.button = $(buttonId);
        if (!this.button) { return false; }

        this.counterDom = $(counterDomId);
        if (!this.counterDom) { return false; }

        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 false; }

        this.textControl = $(textControlId);
        this.validMessageControl = $(validMessageControlId);
        this.invalidMessageControl = $(invalidMessageControlId);
        this.regularExpression = regularExpression;

        if (!this.textControl || !this.validMessageControl || !this.invalidMessageControl) { return false; }

        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 false; }
        this.textBoxControl = $(textBoxControlId);

        if (!this.textBoxControl) { return false; }

        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() {
        var sb = new StringBuilder();
        if (this.childNodes.length) {
            sb.Append('<');
            sb.Append(this.tagName.toLowerCase());
            sb.Append(this.attributs());
            sb.Append('>');
            // 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) {
                    var myElement = $(this.childNodes[t]);
                    sb.Append(myElement.innerXML());
                }
                else {
                    sb.Append(this.childNodes[t].nodeValue);
                }
            }
            // We close the element
            sb.Append('</');
            sb.Append(this.tagName.toLowerCase());
            sb.Append('>');
        }
        else {
            sb.Append('<');
            sb.Append(this.tagName.toLowerCase());
            sb.Append(this.attributs());
            sb.Append(' />');
        }

        return sb.ToString();
    },
    attributs: function() {
        var sb = new StringBuilder();
        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].nodeValue.prototype && (!($chk(this.attributes[t].nodeValue.toLowerCase)) || (this.attributes[t].nodeValue.toLowerCase().indexOf('function(') == -1))){
                sb.Append(' ');
                sb.Append(this.attributes[t].nodeName.toLowerCase());
                sb.Append('="');
                sb.Append(this.attributes[t].nodeValue);
                sb.Append('"');
            }
        }

        return sb.ToString();
    }
});


////////////////////////
/// 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));
    },
    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];
            item.removeProperty('style');

            var img = item.getElement('img');
            if ($chk(img)) {
                img.erase('style');
                img.setStyles({
                    'width': '86px',
                    'height': '138px'
                });
            }

            var link = item.getElement('a');
            if ($chk(link)) {
                link.erase('style');
                link.setStyles({
                    'width': '86px',
                    'height': '138px'
                });
            }
        }

        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 len = this.liItems.length;
        for (index = 0; index < len; index++) {
            var item = this.liItems[index];
            item.removeProperty('style');
            itemX = (index * 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': '224px',
                        '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': '224px'
                    });
                }

                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'
                    });
                }
            }
        }

        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;
        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() {
                        link.setStyle('margin-top', '-5px');
                    });
                }
            }
            var link = item.getElement('img');
            if ($chk(link)) {
                link.addEvent('mouseout', function() {
                    link.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) {
    if (!carouselId) { return false; }
    var item = $(carouselId);
    if (!item) { return false; }

    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]
        },
        onPage: function() {
            this.makeThumbBackAndUp();
        }
    });
    myCarousel.position.now = myCarousel.trackSize - (myCarousel.knobSize + 2);
    myCarousel.content['scrollLeft'] = myCarousel.position.now * myCarousel.scrollRatio;
    myCarousel.knob.setStyle('left', myCarousel.position.now + 'px');
    myCarousel.makeThumbUp();
}

//////////////////////
/// MediaSlideShow ///
//////////////////////
function AddMediaSlideShow(containerId, rowNumber) {

    if (!containerId) { return false; }
    var item = $(containerId);
    if (!item) { return false; }

    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() {
                this.getElement('img').setStyle('border', 'solid 1px black');
                this.getNext().getFirst().className = "iocRiaLegend_hover";
            },
            'mouseleave': function() {
                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 = "";
            }
        });

        item.getElement('span.iocRiaAddToPlayList').addEvent('click', function() {
            if (IsMediaInPlaylist(item.id))
                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 false; }
        this.languageCode = languageCode;
        this.content = $(content);
        this.ulAthleteList = $('ulAthleteList');
        if (!this.content || !this.ulAthleteList) { return false; }

        /*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
        // 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';

        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();
        this.retreiveAthletesData(true, 1, 50);
    },
    initializePlanes: function() {
        this.currentPageIndex = 1;
        this.firstPageIndex = 1;
        this.updatePlanes();
        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() {
        this.athleteItems_Array = this.content.getElements('li');
        var len = this.athleteItems_Array.length;

        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 false; }
        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 false; }
        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();
                }
                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();
                }
            }

            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);
    },
    /*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) {
        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;
        }

        // 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 false; }
        this.filterListWithQueryString = filterListWithQueryString;

        this.goButton = $(goButtonId);
        this.clearButton = $(clearButtonId);

        if (!goButtonForTextBoxId) {
            this.goButtonForTextBox = null;
        }
        else {
            this.goButtonForTextBox = $(goButtonForTextBoxId);
        }

        if (!this.filterListWithQueryString || !this.goButton) { return false; }

        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();
        }

        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);
                            }
                        }
                        else if (type == 'checkbox') {
                            this.addQueryString(queryString, item.checked);
                        }
                    }
                }
            }
        }

        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);
                        }
                        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.url.go();
    },
    executeSearch: function() {
        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 GoogleSearch = new Class({
    Implements: Events,
    initialize: function(searchBoxId, goButtonId, resultsUrl) {

        var t =1;

        if (!resultsUrl || !goButtonId || !searchBoxId) { return false; }

        // 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:;';
        }
        
        var _this = this;
        this.goButton.onclick = function() {
        var t = 1
            _this.executeSearch();
        };
    },
    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;

        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 false; }
        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 false; }
        var mediaPlayerContainer = $(mediaPlayerContainerId);
        if (!mediaPlayerContainer) { return false; }
        this.mediaListContainer = mediaPlayerContainer.getElement('.iocMediaPlayerListContainer');
        this.linkMixedDisplay = mediaPlayerContainer.getElement('.iocMediaPlayerFiltersMixedDisplay');
        if (!this.mediaListContainer) { return false; }
        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 false; }
        var item = $(containerId);
        if (!item) { return false; }

        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 false; }
        this.correctAnswerIndex = correctAnswerIndex;
        if (!quizBlockContainerId) { return false; } //if undefined do nothing
        this.quizBlockContainer = $(quizBlockContainerId);
        this.radioButtons = this.quizBlockContainer.getElements('input[type=radio]');
        if (!this.radioButtons) { return false; }
        this.submitButton = this.quizBlockContainer.getElement('.SmallButton');
        if (!this.submitButton) { return false; }
        var messages = this.quizBlockContainer.getElements('.iocQuizValidation');
        if (!messages) { return false; }
        this.correctAnswerMessage = messages[0];
        if (!this.correctAnswerMessage) { return false; }
        this.incorrectAnswerMessage = messages[1];
        if (!this.incorrectAnswerMessage) { return false; }
        this.divAnswerLink = this.quizBlockContainer.getElement('.iocQuizAnswerLink');
        if (!this.divAnswerLink) { return false; }

        //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');
        }
    }
});

//////////////////////
/// Extender block ///
//////////////////////
var ExtenderBlock = new Class(
{
    initialize: function(extenderContainerId, titleImageAltUrl, arrowUpImageUrl, arrowDownImageUrl, isStartingOpen) {
        //if undefined do nothing
        if ((!extenderContainerId) || (!titleImageAltUrl) || (!arrowUpImageUrl) || (!arrowDownImageUrl)) {
            return false;
        }

        this.titleImageAltUrl = 'url(' + titleImageAltUrl + ')';
        this.arrowUpImageUrl = arrowUpImageUrl;
        this.arrowDownImageUrl = arrowDownImageUrl;
        //find controls
        this.extenderContainer = $(extenderContainerId);
        if (!this.extenderContainer) { return false; }
        this.extenderTitleContainer = this.extenderContainer.getElement('.iocExtenderTitle');
        if (!this.extenderTitleContainer) { return false; }
        this.arrow = this.extenderTitleContainer.getElement('img');
        if (!this.arrow) { return false; }
        this.extenderContentContainer = this.extenderContainer.getElement('.iocExtenderContent');
        if (!this.extenderContentContainer) { return 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 false; }

        var tabsContainer = $(tabsContainerId);
        var divsContainer = $(divsContainerId);

        if (!tabsContainer || !divsContainer) { return false; }

        this.tabs = tabsContainer.getChildren();
        this.contents = divsContainer.getElements('div');

        if (!this.tabs || !this.contents || (this.tabs.length != this.contents.length)) { return false; }

        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 false; }
        var container = $(containerId);
        if (!container) { return false; }
        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 false; }
        this.tabbedBlockContainer = $(tabbedBlockContainerId);
        if (!this.tabbedBlockContainer) { return false; }

        this.titles = this.tabbedBlockContainer.getElements('.iocBlockTitle');
        if (this.titles.length < 2) { return false; }
        this.contents = this.tabbedBlockContainer.getElements(tabbedContentCssClassName);

        if (!this.titles || !this.contents || (this.titles.length != this.contents.length)) { return false; }

        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('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');
    }
});

/////////////////////////////
/// Custom Drop Down 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 SendToFriend = new Class(
{
    initialize: function(receiverAddressId, senderEmailId, sendFormId, copyFormId, successfulMessageControlId, unsuccessfulMessageControlId, sendButtonId, languageCode) {
        if (!receiverAddressId || !senderEmailId || !sendFormId || !copyFormId || !successfulMessageControlId || !unsuccessfulMessageControlId || !sendButtonId || !languageCode) { return false; } //if undefined do nothing
        this.languageCode = languageCode;
        this.receiverAddress = $(receiverAddressId);
        this.senderEmail = $(senderEmailId);
        this.sendForm = $(sendFormId);
        this.sendButton = $(sendButtonId);
        this.copyForm = $(copyFormId);
        this.successfulMessageControl = $(successfulMessageControlId);
        this.unsuccessfulMessageControl = $(unsuccessfulMessageControlId);
        if (!this.receiverAddress || !this.senderEmail || !this.sendForm || !this.sendButton || !this.copyForm || !this.successfulMessageControl || !this.unsuccessfulMessageControl) { return false; }

        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() {
        var parameters = new Object();
        parameters.receiver = this.receiverAddress.value;
        parameters.sender = this.senderEmail.value;
        parameters.copy = this.copyForm.checked;
        parameters.comment = this.sendForm.value;
        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.
        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');
    }
});

var AjaxCustomSelect = new Class(
{
    initialize: function(selectId, associatedSelectId, languageCode, serviceUrl, selectedValue) {
        this.languageCode = languageCode;
        this.selectedValue = selectedValue;
        if (!selectId || !associatedSelectId || !this.languageCode) { return false; } //if undefined do nothing
        this.selectElement = $(selectId);
        this.associatedSelect = $(associatedSelectId);
        if (!this.selectElement || !this.associatedSelect) { return false; }
        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.innerHTML = '';

            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 CustomSelect = new Class(
{
    initialize: function(selectContainerId) {
        if (!selectContainerId) { return false; } //if undefined do nothing
        var selectContainer = $(selectContainerId);
        if (!selectContainer) { return false; }
        this.selectElement = selectContainer.getElement('select');
        this.selectedOptionInList = false;
        this.isListOppenned = false;

        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': 100000 });
        }
    },
    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 false; } //if undefined do nothing
        this.checkBoxContainer = $(checkBoxContainerId);
        if (!this.checkBoxContainer) { return false; }
        this.checkBoxElement = $(checkBoxContainerId).getElement('input[type="checkbox"]');
        if (!this.checkBoxElement) { return false; }

        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 false; } //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 false; }
            this.radioButtons = document.getElements('input[name=' + radioButton.name + ']');
        }
        //get all radio buttons on the page

        if (!this.radioButtons) { return false; }

        this.customRadios = new Array();
        this.radioButtons.each(function(item, index) {
            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 OnClickPopup = new Class(
{
    Implements: Options,
    options: {
        hasOverlay: false,
        overlayOpacity: 0.8
    },
    initialize: function(openButtons, closeButtons, popupId, options) {
        if (!openButtons || !closeButtons || !popupId) { return false; } //if undefined do nothing

        this.openButtons = $$(openButtons);
        this.closeButtons = $$(closeButtons);
        this.toggleButtons = new Array();
        this.popup = $(popupId);
        this.setOptions(options);

        if (!this.openButtons || !this.closeButtons || !this.popup) { return false; } //if undefined do nothing


        if (this.options.hasOverlay) {//if  popup includes overlay
            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', function() {
                this.overlay.setStyles({ 'height': 0, 'top': 0, 'opacity': 0, 'width': '100%' });
            } .bind(this));
            this.overlay.addEvent('click', this.hide.bindWithEvent(this));
        }

        this.openButtons.each(function(item) {
            if (item.get('tag') == 'a') {//replace all href to javascript
                item.setProperty('href', 'javascript:;');
            }

            if (this.closeButtons.contains(item)) {//if a button can close as well move to toggle array
                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.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) {
            //additional logic for options
            if (this.options.hasOverlay) {//if  popup includes overlay
                var scrollSizeY = $(window).getScrollSize().y;
                var scrollTop = $(window).getScroll().y;
                var scrollSizeX = $(window).getScrollSize().x;
                var scrollLeft = $(window).getScroll().x;
                var windowSizeY = $(window).getSize().y;

                this.overlay.setStyles({ 'height': scrollSizeY + scrollTop, 'top': -scrollTop });
                this.FxOverlayFadeIn.start({ 'opacity': this.options.overlayOpacity });

                this.popup.setStyle('left', (scrollSizeX + scrollLeft) / 2 - this.popup.getSize().x / 2);
                this.popup.setStyle('margin-top', scrollTop + (windowSizeY / 2) - (this.popup.getSize().y / 2));
            }
            this.openned = true;
            this.FxPopupFadeInOut.start({
                'opacity': '1'
            });
        }
    },
    hide: function() {
        if (this.openned) {
            this.FxPopupFadeInOut.start({
                'opacity': '0'
            });

            if (this.options.hasOverlay) {//if  popup includes overlay
                this.FxOverlayFadeIn.start({ 'opacity': 0 });
            }

            this.openned = false;
        }
    },
    toggle: function() {
        if (this.openned) {
            this.hide();
        }
        else {
            this.show();
        }
    }
});

////////////////////
/// OnEnterPopup ///
////////////////////
var OnEnterPopup = new Class(
{
    initialize: function(toggleButtons, popupId) {
        if (!toggleButtons || !popupId) { return false; } //if undefined do nothing

        this.toggleButtons = $$(toggleButtons);
        this.popup = $(popupId);

        if (!this.toggleButtons || !this.popup) { return false; } //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 false; } //if undefined do nothing
        this.container = $(containerId);
        if (!this.container) { return false; }

        var selectElements = this.container.getElements('select');
        if (!selectElements || selectElements.length < 2) { return false; }

        this.lowerSelect = selectElements[0];
        this.upperSelect = selectElements[1];

        //if not same size something is wrong
        if (this.lowerSelect.length != this.upperSelect.length) { return false; }
        //if no options something is wrong
        if (this.lowerSelect.length == 0) { return false; }

        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 false; }
        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 ///
////////////////
var iocLightBox = new Class({
    Implements: Options,
    options: {
        overlayOpacity: 0.8
    },
    initialize: function(linkId, options) {
        if (!linkId) { return false; }
        this.link = $(linkId);
        if (!this.link) { return 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), 'opacity': 0} }).inject($(document.body));

        this.closeArea = new Element('div', { 'class': 'iocCloseArea' }).inject(this.center);
        this.closeTextElement = new Element('span').inject(this.closeArea);
        this.closeTextElement.innerHTML = 'close'; //has to come from common text at some point

        this.canvas = new Element('div', { 'class': 'iocCanvas' }).inject(this.center);
        this.image = new Element('img', { 'src': '/resources/Images/Misc/loading.gif' }).inject(this.canvas);

        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.imageOriginalWidth = this.image.width;
        this.imageOriginalHeight = this.image.height;

        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));
    },
    onAnchorClick: function(event) {
        event.stop();
        this.preloadImage(this.link.href);

        var thumbnail = this.link.getElement('img');

        if ($chk(thumbnail)) {
            this.titleElement.innerHTML = thumbnail.getProperty('title');
            this.descriptionElement.innerHTML = thumbnail.getProperty('alt');
        }

        var scrollSize = $(window).getScrollSize().y;
        var scrollTop = $(window).getScroll().y;
        this.overlay.setStyles({ 'height': scrollSize + scrollTop, 'top': -scrollTop });

        this.FxOverlayFadeIn.start({ 'opacity': this.options.overlayOpacity });
    },
    onFxOverlayFadeInCompleted: function() {
        this.isAnimationFinished = true;
        this.center.setStyle('opacity', 1);
        this.showImage();
    },
    onFxCanvasResizeCompleted: function() {
        var scrollSizeY = $(window).getScrollSize().y;
        var scrollTop = $(window).getScroll().y;
        var scrollSizeX = $(window).getScrollSize().x;
        var scrollLeft = $(window).getScroll().x;

        this.overlay.setStyles({ 'height': scrollSizeY + scrollTop, 'top': -scrollTop, 'width': scrollSizeX + scrollLeft });
        this.FxImageFadeIn.start({ 'opacity': 1 });

        this.textArea.setStyle('display', 'block');
        this.FxCenterResize.start({ 'height': this.textArea.getStyle('margin-top').toInt() +
                                              this.textArea.getSize().y +
                                              this.center.getSize().y
        });
    },
    onImagePreloaded: function() {
        this.isImagePreloaded = true;
        this.showImage();
    },
    onClosed: function() {
        this.overlay.setStyles({ 'height': 0, 'top': 0, 'opacity': 0, 'width': '100%' });
        this.center.setStyles({ 'opacity': 0, 'width': 300, 'height': 300, 'marginLeft': -(300 / 2) });
        this.canvas.setStyles({ 'width': 300, 'height': 300 });
        this.textArea.setStyle('display', 'none');
        this.image.src = '/resources/Images/Misc/loading.gif';
        this.image.width = this.imageOriginalWidth;
        this.image.height = this.imageOriginalHeight;
    },
    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.FxCenterResize.start({
                'height': this.image.height +
                          this.closeArea.getSize().y +
                          this.canvas.getStyle('padding-top').toInt() +
                          this.canvas.getStyle('padding-bottom').toInt(),
                'width': this.image.width +
                         this.canvas.getStyle('padding-left').toInt() +
                         this.canvas.getStyle('padding-right').toInt(),
                'margin-left': window.getSize().x > this.image.width ? -(this.image.width / 2) : -(window.getSize().x / 2)
            });
            this.FxCanvasResize.start({
                'height': this.image.height,
                'width': this.image.width
            });
        }
    },
    hide: function() {
        this.center.setStyle('opacity', 0);
        this.FxOverlayFadeOut.start({ 'opacity': 0 });
    }
});
