if (typeof Mxm == "undefined")
    var Mxm = {};

Mxm.Editos = {
    urlToXMLData : '',
    XMLData : '',
    editoDOMElement : null,
    imagesArray : null,
    thumbsSrcArray : null,
    imagesSrcArray : null,
    imagesLinkArray: null,
    activeIndex : null,
    isWorking : null,

    // initialize editos. Load data from xml, etc.
    init : function(type, url) {

        this.editoDOMElement = $('edito');
        if (this.editoDOMElement && type !== 'home') {
            var navButtonPrevious = this.editoDOMElement.down('.navButton.previous');
            // create carousel base: <container><items>
            var elmContainer = new Element('div');
            var elmItems     = new Element('div');

            elmContainer.className = 'container';
            elmContainer.style.position = 'relative';

            elmItems.className = 'items';
            elmItems.style.left = '0px';

            if (navButtonPrevious) {
                // we have navigation buttons, put the container after them
                navButtonPrevious.insert({'after' : elmContainer});
            }
            else {
                // no buttons, just put it at the begin of the div
                this.editoDOMElement.insert({'top' : elmContainer});
            }

            elmContainer.insert({'top' : elmItems});

        }

        switch(type) {
            case 'home':
                this.urlToXMLData = url;

                this.imagesSrcArray = new Array();
                this.thumbsSrcArray = new Array();
                this.imagesLinkArray= new Array();
                this.activeIndex = -1;
                this.isWorking = false;
                // processes XML data and creates DOM elements
                this.processHomeItems(this.urlToXMLData);
                this.isWorking = setInterval('Mxm.Editos.homeNext()', 10000);
                break;

            case 'collect':
                this.urlToXMLData = url;


                this.imagesArray = new Array();
                // create DOM elements for carousel
                // and load the carousel (start it)
                this.processXmlItems(this.urlToXMLData);
                break;

            case 'catalogue':
                this.urlToXMLData = url;

                this.imagesArray = new Array();

                // create DOM elements for carousel
                // and load the carousel (start it)
                this.processXmlItems(this.urlToXMLData);
                break;

            case 'fap':
                this.urlToXMLData = url;

                this.imagesSrcArray = new Array();
                this.thumbsSrcArray = new Array();
                this.imagesLinkArray= new Array();
                this.activeIndex = -1;
                this.isWorking = false;
                // processes XML data and creates DOM elements
                this.processHomeItems(this.urlToXMLData);
                this.isWorking = setInterval('Mxm.Editos.homeNext()', 10000);
                break;
            default:
        }
    },

    processHomeItems: function(url) {
        new Ajax.Request(
            url,
            {
                asynchronous: false,
                method : 'get',
                parameters : '',
                onComplete : function (transport) {
                },
                onSuccess : function (response) {
                    this.XMLData = response.responseXML.documentElement;

                    var imagesTags = this.XMLData.getElementsByTagName('image');
                    var countImg = imagesTags.length;

                    if (countImg > 0) {

                        for (var i = 0 ; i < countImg; ++i) {
                            this.imagesSrcArray.push(Mxm.elementAttributeValue(imagesTags[i], 'src'));
                            this.thumbsSrcArray.push(Mxm.elementAttributeValue(imagesTags[i], 'thumbnail'));
                            this.imagesLinkArray.push(Mxm.elementAttributeValue(imagesTags[i], 'link'));

                            this.createHomeItemDOM(
                                $('thumbsList'),
                                $('imagesList'),
                                $('activeImage'),
                                this.imagesLinkArray[i],
                                this.thumbsSrcArray[i],
                                this.imagesSrcArray[i],
                                i,
                                (i == 0 ? true : false)
                            );
                        }
                    }
                    else {
                        // remove edito div
                        Element.remove($('editoHome'));
                    }
                }.bind(this)
            }
        );
    },

    homeNext : function () {
        var thumbsList   = $('thumbsList');
        var imagesList   = $('imagesList');

        if (typeof(thumbsList) == 'undefined' || thumbsList == null || typeof(imagesList) == 'undefined')
            return;

        var countItems   = thumbsList.childNodes.length;
        var needsRewind  = (this.activeIndex == (countItems-1));

        var idxToActivate= needsRewind ? 0 : (this.activeIndex+1);
        for (var i = 0; i < countItems; ++i) {
            var spanIsActive = imagesList.down('div#image' + i).down(1);

            if (i == idxToActivate) {
                this.activateItem(i, $('activeImage'), imagesList);
                this.activeIndex = i;
                spanIsActive.innerHTML = 'true';
            }
            else {
                spanIsActive.innerHTML = 'false';
            }
        }
    },

    activateItem : function (index, activeElm, imagesList) {
        clearInterval(this.isWorking);
        var activeImgElm = activeElm;

        // set active
        var newActiveLink = new Element('a');
        var newActiveImg  = new Element('img');

        var linkToActivate = imagesList.down('div#image'+index).down('a');
        var imgToActivate  = imagesList.down('div#image'+index).down('a').down('img');

        var srcImg = Mxm.elementAttributeValue(imgToActivate, 'src');
        var extImg = srcImg.substr(srcImg.length - 3, 3);

        if (extImg == 'swf') {
            // GENERATE FLASH
            activeImgElm.innerHTML = '';

            var swfObjectIe = new Element('object');
            swfObjectIe.setAttribute('classid','clsid:D27CDB6E-AE6D-11cf-96B8-444553540000');
            swfObjectIe.setAttribute('width', '597');
            swfObjectIe.setAttribute('height', '215');

            var swfParamIe = new Element('param');
            swfParamIe.setAttribute('name', 'movie');
            swfParamIe.setAttribute('value', srcImg);

            var swfObjectFx = new Element('object');
            swfObjectFx.setAttribute('type', 'application/x-shockwave-flash');
            swfObjectFx.setAttribute('data', srcImg);
            swfObjectFx.setAttribute('width', '597');
            swfObjectFx.setAttribute('height', '215');

            var noFlash = new Element('a');
            noFlash.setAttribute('href', 'http://www.adobe.com/go/getflashplayer');
            noFlash.update('You need to get the latest flash player in order to view this animation.');

            Element.insert(activeImgElm, {'bottom' : swfObjectIe});
            Element.insert(swfObjectIe, {'bottom' : swfParamIe});
            Element.insert(swfObjectIe, {'bottom' : swfObjectFx});
            Element.insert(swfObjectFx, {'bottom' : noFlash});
        }
        else {

            // set link from imagesList's element
            newActiveLink.setAttribute('href', Mxm.elementAttributeValue(linkToActivate, 'href'));
            newActiveImg.setAttribute('src', Mxm.elementAttributeValue(imgToActivate, 'src'));

            activeImgElm.innerHTML = '';

            Element.insert(activeImgElm, {'bottom' : newActiveLink});
            Element.insert(newActiveLink, {'bottom' : newActiveImg});
        }

        this.activeIndex = index;
        this.isWorking = setInterval('Mxm.Editos.homeNext()', 10000);
    },

    processXmlItems : function(url) {

        new Ajax.Request(
            url,
            {
                // we should wait until request is done, before fetching anything
                // else.
                asynchronous : false,
                method : 'get',
                parameters : '',
                onComplete : function(transport) {
                    if (200 == transport.status) {
                    }
                    else {
                    }
                },
                onSuccess : function(response) {

                    try {

                        // interpret XMLDocument and create DOM elements
                        this.XMLData = response.responseXML.documentElement;

                        var imagesTags = this.XMLData.getElementsByTagName('rewardImage');
                        var categoriesTags = this.XMLData.getElementsByTagName('categoryName');
                        var linkIconTags = this.XMLData.getElementsByTagName('rewardLink');
                        var linkTitleTags = this.XMLData.getElementsByTagName('categoryLink');

                        if (imagesTags.length > 0) {

                            if (! this.editoDOMElement)
                                this.editoDOMElement = $('edito');

                            var itemsContainerElm = this.editoDOMElement.down('.container').down('.items');

                            var widthAccordingToCountItems = imagesTags.length * 150;

                            itemsContainerElm.setStyle({width: widthAccordingToCountItems + 'px'});

                            if (! this.imagesArray)
                                this.imagesArray = new Array();

                            var i = 0;
                            var j = i;
                            var count = imagesTags.length;
                            var maxLoop = count;
                            var activeItemIndex = Math.floor(count / 2);
                            var bSelected = false;

                            for ( ; i < maxLoop; ++i, ++j) {
                                if (j == count) {
                                    j = 0;
                                }
                                bSelected = (i == activeItemIndex);
                                Mxm.Editos.createItemDOM(
                                    itemsContainerElm,
                                    i,
                                    categoriesTags[j].childNodes[0].nodeValue,
                                    linkTitleTags[j].childNodes[0].nodeValue,
                                    linkTitleTags[j].childNodes[0].nodeValue,
                                    imagesTags[j].childNodes[0].nodeValue,
                                    false, bSelected
                               );
                            }

                            // Since elements are created, we can start the Slider
                            Mxm.Slider.Load();
                        }
                        else {
                            // remove edito element
                            Element.remove($('edito'));
                        }
                    } catch (e) {
                        $('edito').innerHTML = e.message;
                    }
                }
            }
        );
    },

    createHomeItemDOM : function (thumbsListElm, imagesListElm, activeImgElm, elmLink, elmThumbSrc, elmImgSrc, indexAt, isSelected) {
        var thumbDivElm = new Element('div');
        var imageDivElm = new Element('div');
        var thumbImgElm = new Element('img');
        var thumbLinkElm= new Element('a');
        var imageImgElm = new Element('img');
        var imageLinkElm= new Element('a');
        var imageIdxElm = new Element('span');
        var imageActElm = new Element('span');

        imageDivElm.setAttribute('id', 'image' + indexAt);

        thumbImgElm.setAttribute('src', elmThumbSrc);
        thumbImgElm.setStyle( {
            height: '35px',
            width: '70px'
        });

        imageImgElm.setAttribute('src', elmImgSrc);
        imageLinkElm.setAttribute('href', elmLink);

        thumbLinkElm.onclick = function()
        {
            Mxm.Editos.activateItem(indexAt, $('activeImage'), $('imagesList'));
            return false;
        }
        thumbLinkElm.setAttribute('href', '#');

        imageIdxElm.update(indexAt);
        imageActElm.update((isSelected ? 'true' : 'false'));

        Element.insert(thumbsListElm, {'bottom' : thumbDivElm});
        Element.insert(thumbDivElm, {'bottom' : thumbLinkElm});
        Element.insert(thumbLinkElm, {'bottom' : thumbImgElm});
        Element.insert(imagesListElm, {'bottom' : imageDivElm});
        Element.insert(imageDivElm, {'bottom' : imageActElm});
        Element.insert(imageDivElm, {'bottom' : imageIdxElm});
        Element.insert(imageDivElm, {'bottom' : imageLinkElm});
        Element.insert(imageLinkElm, {'bottom' : imageImgElm});

        if (isSelected) {
            var activeLink= new Element('a');
            var activeElm = new Element('img');
            activeLink.setAttribute('href', elmLink);
            activeElm.setAttribute('src', elmImgSrc);
            // clean activeImage
            activeImgElm.innerHTML = '';
            Element.insert(activeImgElm, {'bottom' : activeLink});
            Element.insert(activeLink, {'bottom' : activeElm});
            this.activeIndex = indexAt;
        }
    },

    // create a DOM element for an item
    // return CarouselItem instance
    createItemDOM : function (itemsElm, indexAt, captionTxt, captionLink, iconLinkHref, imgSrc, createObject, isSelected) {

        var itemDiv = new Element('div');
        itemDiv.className = 'item';
        if (isSelected) {
            itemDiv.className = 'item itemSelected';
        }

        var iconDiv     = new Element('div');
        var keyDiv      = new Element('div');
        var captionDiv  = new Element('div');
        var pictDiv     = new Element('div');

        var iconImg     = new Element('img');

        var imgLink     = new Element('a');

        iconDiv.className = 'icon';

        keyDiv.className = 'key';
        keyDiv.style.display = 'none';

        captionDiv.className = 'caption';
        captionDiv.style.display = 'none';

        pictDiv.className = 'picture';
        pictDiv.style.display = 'none';

        keyDiv.update('key' + indexAt);
        captionDiv.update(captionLink);
        pictDiv.update(captionTxt);

        iconImg.setAttribute('src', imgSrc);

        imgLink.setAttribute('href', iconLinkHref);

        Element.insert(itemsElm, {'bottom' : itemDiv});
        Element.insert(itemDiv, {'bottom' : keyDiv});
        Element.insert(itemDiv, {'bottom' : captionDiv});
        Element.insert(itemDiv, {'bottom' : iconDiv});
        Element.insert(itemDiv, {'bottom' : pictDiv});
        Element.insert(iconDiv, {'bottom' : imgLink});
        Element.insert(imgLink, {'bottom' : iconImg});

        if (createObject) {
            var itemObject = Mxm.Slider.PictureCarousel.options.itemParser(itemDiv);
            itemObject.index = indexAt;
            itemObject.key   = keyDiv.childNodes[0].nodeValue;
            itemObject.element = itemDiv;

            return itemObject;
        }
    }

};



