/**
* PromoBlocks class
*/
(function (root) {

    "use strict";

    /**
     * Common object params
     * @type {Object}
     */
    var common = {
            publicMethods: [],
            className: 'PromoBlocks'
        },

        /**
         * Main constructor
         * @return {Object} - this handle
         */
        Protected = function () {

            var self = this;

            Observer.subscribe('loadPage', function () {
                self.setEvents();
            });

            return this;
        };


    /**
     * Main prototype
     * @type {Object}
     */
    Protected.prototype = {

        ucFirst: function (string) {
            return string.charAt(0).toUpperCase() + string.slice(1);
        },


        /**
         * Set events to this module.
         * This code fire methods by 'data-action' attribute of '.promo-blocks-module-action' element 
         */
        setEvents: function () {

            var self = this;

            [].forEach.call(document.querySelectorAll('.promo-blocks-module-action'), function (action) {

                // try to get attribute
                action = 'action' + self.ucFirst(action.getAttribute('data-action'));
                
                // fire event action
                self[action] && self[action]();
            });


        },
        actionTemplate1: function () {

            [].forEach.call(document.querySelectorAll('.promo-blocks-template-1'), function (moduleContainer) {
                var container = moduleContainer.querySelector('.blocks-container'),
                    offset = 0,
                    blocks = container.querySelectorAll('.mini-block'), 
                    radius = (container.clientWidth / 2) + offset,
                    width = container.clientWidth,
                    height = container.clientHeight;


                [].forEach.call(blocks, function (elem, index) {
                    var angle = (180 / blocks.length + 1) * (index + 0.5),
                        x, y;
                    
                    angle = angle * (Math.PI/180);

                    x = Math.round(width/2 + radius * Math.cos(angle - (Math.PI/2)) - elem.clientWidth/2);
                    y = Math.round(height/2 + radius * Math.sin(angle - (Math.PI/2)) - elem.clientHeight/2);

                    elem.style.left = x + 'px';
                    elem.style.top = y + 'px';
                });
            });
        },



        actionTemplate2: function () {

            [].forEach.call(document.querySelectorAll('.promo-blocks-template-2 .promo-blocks'), function (container) {
                
                // check to odd
                if (container.querySelectorAll('.block-logo') %2 !== 0) {

                    var firstLineCollection = container.querySelectorAll('.block-line:first-child .promo-block'),
                        lastLineCollection = container.querySelectorAll('.block-line:last-child .promo-block');

                    if (firstLineCollection.length > lastLineCollection.length) {
                        var ghost = firstLineCollection[0].cloneNode(true);
                        ghost.classList.add('-ghost-block');
                        lastLineCollection[0].parentNode.appendChild(ghost);
                    }

                }


                var firstLineContainer = container.querySelector('.block-line:first-child'),
                    blocksFirstLine = container.querySelectorAll('.block-line:first-child .block-logo'),
                    blocksSecondLine = container.querySelectorAll('.block-line:last-child .block-logo');

                // set first line offset
                var delta = (Core.getPosition(blocksSecondLine[0]).x - Core.getPosition(blocksSecondLine[1]).x) / 2;
                delta = Math.abs(delta);

                if (container.querySelector('.-ghost-block')) {
                    container.classList.add('-has-ghost-block');
                    firstLineContainer.style.left = -delta + 'px';
                    container.style.left = (Math.abs(delta)) + 'px';
                
                } else {
                    firstLineContainer.style.left = -delta + 'px';
                    container.style.left = (Math.abs(delta) / 2) + 'px';
                }

                
                
                // calculate arrows
                [].forEach.call(blocksFirstLine, function (blockLogo, blockIndex) {


                    var blockLogo2 = blocksSecondLine[blockIndex],
                        arrow1 = blockLogo.parentNode.querySelector('.block-arrow'),
                        arrow2 = blockLogo2.parentNode.querySelector('.block-arrow'),
                        block1Position = Core.getPosition(blockLogo),
                        block2Position = Core.getPosition(blockLogo2),
                        point1 = {
                            x: block1Position.x - (blockLogo.clientWidth / 2),
                            y: block1Position.y - (blockLogo.clientHeight / 2)
                        },
                        point2 = {
                            x: block2Position.x - (blockLogo2.clientWidth / 2),
                            y: block2Position.y - (blockLogo2.clientHeight / 2)
                        },
                        angleDeg = Math.atan2(point2.y - point1.y, point2.x - point1.x) * 180 / Math.PI,
                        distance = Math.sqrt((point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y));


                    arrow1.style.left = (blockLogo.offsetLeft + blockLogo.clientWidth / 2) + 'px';
                    arrow1.style.top = (blockLogo.offsetTop + blockLogo.clientHeight / 2) + 'px';
                    arrow1.style.transformOrigin = '0 0 0';
                    arrow1.style.transform = 'rotateZ(' + (parseInt(angleDeg, 10)) + 'deg)';
                    arrow1.style.width = parseInt(distance, 10) + 'px';

                    arrow2.style.left = (blockLogo2.offsetLeft + blockLogo2.clientWidth / 2) + 'px';
                    arrow2.style.top = (blockLogo2.offsetTop + blockLogo2.clientHeight / 2) + 'px';
                    arrow2.style.transformOrigin = '0 0 0';
                    arrow2.style.transform = 'rotateZ(-' + (parseInt(angleDeg, 10)) + 'deg)';
                    arrow2.style.width = parseInt(distance, 10) + 'px';

                });
                
                container.classList.add('-loaded');
            });
        },

        actionTemplate3: function () {

            [].forEach.call(document.querySelectorAll('.promo-blocks-template-3 .promo-blocks'), function (container) {
                if (!container.classList.contains('-js-carousel-loaded')) {
                    container.classList.add('-js-carousel-loaded');
                    new JsSimpleSlider(container, {
                        slidesToScroll: 1,
                        itemsPerViewport: 3,
                        margin:0

                    }, function (imageCollection) {
                        container.classList.add('-loaded');

                        var imagesCollection = [];
                        
                        // create images
                        [].forEach.call(container.querySelectorAll('.block-logo'), function (block) {
                            var img = document.createElement('img');
                                img.src = block.style.backgroundImage.replace(/^url\(\"/, '').replace(/\"\)$/, '');

                            imagesCollection.push(img);
                        });



                        [].forEach.call(container.querySelectorAll('.block-logo'), function (block, index) {

                            if (!block.querySelector('.block-url')) {
                                block.style.cursor = 'pointer';
                                block.addEventListener('click', function () {

                                    // swap elements
                                    var current = imagesCollection[index];
                                    imagesCollection[index] = imagesCollection[0];
                                    imagesCollection[0] = current;

                                    new JsViewer(imagesCollection).show();

                                });
                            }
                        });
                    });

                }
            });
        }
        
    };

    /**
     * Encapsulation
     * @return {Object} - this handle
     */
    root[common.className] = function () {

        function construct(constructor, args) {

            function Class() {
                return constructor.apply(this, args);
            }

            Class.prototype = constructor.prototype;
            return new Class();
        }

        var publicly = construct(Protected, arguments),
            i,
            l = common.publicMethods.length;

        for (i = 0; i < l; i += 1) {

            (function () {
                var member = common.publicMethods[i];
                root[common.className].prototype[member] = function () {
                    return publicly[member].apply(publicly, arguments);
                };
            }());
        }

        return this;
    };

}(this));

document.addEventListener('DOMContentLoaded', function () {
    
    window.PromoBlocks = new PromoBlocks();

});