/**
 * 
 * RotatingBanner - display images in a row, moving to the left in a constant speed
 * which is stepInPixels / stepIntervalMilliseconds
 * usage: 
 *     HTML: <div id="div_where_the_images_will_rotate" style="width:XXpx;height:YYpx"></div>
 *    JS: <script>RotatingBanner.init("div_where_the_images_will_rotate", [
 *            'http://path.to/the_first/image.jpg',
 *            'http://path.to/the_second/image_url.jpg',
 *            '/local/absolute/path_image.jpg'
 *         ]);</script>
 *
 *         * the images may be also taken from global variable `ROTATINGBANNER`
 * 
 * 
 * @author Gregory Chris (gregory.chris@williamhill.com)
 * @since 28.07.13
 */
;(function(GLOB) {

    GLOB.RotatingBanner = {

        stepInPixels: 1,

        stepIntervalMilliseconds: 25,

        imagesMargin: 15, 
 
        // imagesList => ['http://../some_image.jpg', '/another/image.png', ...]
        init: function(divId, imagesList) {
            RotatingBanner._divId = divId;

            // check the images list
            if (imagesList && (imagesList instanceof Array) && imagesList.length) {
                ROTATINGBANNER = {'images': imagesList};
            } else if (typeof(ROTATINGBANNER) == 'undefined' || !ROTATINGBANNER || !ROTATINGBANNER['images']) {
                console.log('Error in ROTATINGBANNER, and no images supplied');
                return false;
            }

            // get the main div
            var targetElement = document.getElementById(divId);
            if (!targetElement) {
                console.log('No element with div "' + divId + '"');
                return false;
            }

            // apply css
            RotatingBanner._applyCss(targetElement, {
                'overflow': 'hidden',
                'position': 'relative'
            });

            var imagesWrapper = document.createElement('div');
            imagesWrapper.id = 'images-wrapper';
            RotatingBanner._applyCss(imagesWrapper, {
                position: 'absolute',
                left: '0',
                top: '0'
            });


            var getImageWithWrappingDiv = function(src) {
                var newDiv = document.createElement('div');
                RotatingBanner._applyCss(newDiv, {
                    display: 'inline-block',
                    margin: '0',
                    marginRight: RotatingBanner.imagesMargin + 'px',
                    padding: '0',
                    verticalAlign: 'top'
                });
                newDiv.innerHTML = '<img src="' + src + '" />';

                return newDiv;
            }

            // continue the rotating on all images load
            var fixHeightsAndStartRotation = function() {

                // get the max height and the total width
                var sumWidths = 0,
                    maxHeight = 0,
                    imagesWrappers = targetElement.firstChild.children;
                for (var i in imagesWrappers) {
                    sumWidths+= (imagesWrappers[i].firstChild ? imagesWrappers[i].firstChild.clientWidth : 0);
                    sumWidths+= RotatingBanner.imagesMargin;

                    var imgHeight = (imagesWrappers[i].firstChild ? imagesWrappers[i].firstChild.clientHeight : 0);
                    if (imgHeight > maxHeight) {
                        maxHeight = imgHeight;
                    }
                }

                var initialSumWidth = sumWidths, 
                    initialTargetWidth = targetElement.clientWidth;
                while (sumWidths < initialTargetWidth * 2) {
                    sumWidths+=initialSumWidth;
                    for (var i in ROTATINGBANNER['images']) {
                        targetElement.firstChild.appendChild(getImageWithWrappingDiv(ROTATINGBANNER['images'][i]));
                    }
                }

                // apply the width/height to the wrapper element
                RotatingBanner._applyCss(imagesWrapper, {
                    height: (maxHeight + 1) + 'px', 
                    width: (sumWidths + 1) + 'px'
                });
                
                // start the rotation
                RotatingBanner._startRotation(targetElement);
            }


            for (var i in ROTATINGBANNER['images']) {
                var currImage = ROTATINGBANNER['images'][i];
                var newDiv = getImageWithWrappingDiv(currImage);
                var newDivImage = newDiv.firstChild;

                // notify the loader
                RotatingBanner.loader.addImage();
                newDiv.firstChild.onload = function() {
                    RotatingBanner.loader.imageLoaded();

                    // check if all the images have loaded
                    if (RotatingBanner.loader.imagesLoaded()) {
                        fixHeightsAndStartRotation();
                    }
                }
                imagesWrapper.appendChild(newDiv);
            }

            // add the images to the main div
            targetElement.appendChild(imagesWrapper);

        },

        // images load count
        loader: {
            _loadStarted: false,
            _imagesNumber: 0,
            addImage: function() {
                RotatingBanner.loader._imagesNumber ++;
                RotatingBanner.loader._loadStarted = true;
            },
            imageLoaded: function() {
                RotatingBanner.loader._imagesNumber --;
            },
            imagesLoaded: function() {
                return (RotatingBanner.loader._loadStarted && RotatingBanner.loader._imagesNumber == 0);
            }
        },

        _divId: null,

        // targetElement - the main div (not the images wrapper)
        _startRotation: function(targetElement) {
             
             // initialize the main object
            var targetElement = document.getElementById(RotatingBanner._divId);
            if (!targetElement) return;

            // get sizes and positions
            var imagesContainer = targetElement.firstChild,
                left = parseInt(imagesContainer.style.left),
                width = imagesContainer.clientWidth,
                firstImageWrapper = imagesContainer.firstChild,
                containerWidth = targetElement.clientWidth;

            // check if the whole image is below zero
            if (left + firstImageWrapper.clientWidth + RotatingBanner.imagesMargin < 0) {
                
                // move the first image to the end of the list
                firstImageWrapper = imagesContainer.removeChild(firstImageWrapper);
                imagesContainer.appendChild(firstImageWrapper);

                // correct `left` of the images wrapper
                left+= firstImageWrapper.clientWidth + RotatingBanner.imagesMargin;
                RotatingBanner._applyCss(imagesContainer, {
                    left: left + 'px'
                });
            }


            RotatingBanner._applyCss(imagesContainer, {
                left: (left - RotatingBanner.stepInPixels) + 'px'
            });

            setTimeout(RotatingBanner._startRotation, RotatingBanner.stepIntervalMilliseconds);
        },

        _applyCss: function (elem, cssObj) {
            for (var j in cssObj) {
                elem.style[j] = cssObj[j];
            }
        }
    };


})(window);


/**
 * Minified version
 */
(function(a){a.RotatingBanner={stepInPixels:1,stepIntervalMilliseconds:25,imagesMargin:15,init:function(k,h){RotatingBanner._divId=k;if(h&&(h instanceof Array)&&h.length){ROTATINGBANNER={images:h}}else{if(typeof(ROTATINGBANNER)=="undefined"||!ROTATINGBANNER||!ROTATINGBANNER.images){console.log("Error in ROTATINGBANNER, and no images supplied");return false}}var f=document.getElementById(k);if(!f){console.log('No element with div "'+k+'"');return false}RotatingBanner._applyCss(f,{overflow:"hidden",position:"relative"});var g=document.createElement("div");g.id="images-wrapper";RotatingBanner._applyCss(g,{position:"absolute",left:"0",top:"0"});var e=function(m){var i=document.createElement("div");RotatingBanner._applyCss(i,{display:"inline-block",margin:"0",marginRight:RotatingBanner.imagesMargin+"px",padding:"0",verticalAlign:"top"});i.innerHTML='<img src="'+m+'" />';return i};var l=function(){var n=0,q=0,s=f.firstChild.children;for(var o in s){n+=(s[o].firstChild?s[o].firstChild.clientWidth:0);n+=RotatingBanner.imagesMargin;var m=(s[o].firstChild?s[o].firstChild.clientHeight:0);if(m>q){q=m}}var p=n,r=f.clientWidth;while(n<r*2){n+=p;for(var o in ROTATINGBANNER.images){f.firstChild.appendChild(e(ROTATINGBANNER.images[o]))}}RotatingBanner._applyCss(g,{height:(q+1)+"px",width:(n+1)+"px"});RotatingBanner._startRotation(f)};for(var d in ROTATINGBANNER.images){var j=ROTATINGBANNER.images[d];var b=e(j);var c=b.firstChild;RotatingBanner.loader.addImage();b.firstChild.onload=function(){RotatingBanner.loader.imageLoaded();if(RotatingBanner.loader.imagesLoaded()){l()}};g.appendChild(b)}f.appendChild(g)},loader:{_loadStarted:false,_imagesNumber:0,addImage:function(){RotatingBanner.loader._imagesNumber++;RotatingBanner.loader._loadStarted=true},imageLoaded:function(){RotatingBanner.loader._imagesNumber--},imagesLoaded:function(){return(RotatingBanner.loader._loadStarted&&RotatingBanner.loader._imagesNumber==0)}},_divId:null,_startRotation:function(c){var c=document.getElementById(RotatingBanner._divId);if(!c){return}var b=c.firstChild,f=parseInt(b.style.left),d=b.clientWidth,g=b.firstChild,e=c.clientWidth;if(f+g.clientWidth+RotatingBanner.imagesMargin<0){g=b.removeChild(g);b.appendChild(g);f+=g.clientWidth+RotatingBanner.imagesMargin;RotatingBanner._applyCss(b,{left:f+"px"})}RotatingBanner._applyCss(b,{left:(f-RotatingBanner.stepInPixels)+"px"});setTimeout(RotatingBanner._startRotation,RotatingBanner.stepIntervalMilliseconds)},_applyCss:function(c,d){for(var b in d){c.style[b]=d[b]}}}})(window);