/**
* @package XenCentral Ad Server
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @revision 97
* @version 2.0.0 beta 3 rev. 3
*/
var XenCentral_AdServer_Core = {
    pageIsActive: true,
    lastActivity: 0,
    jQuery: false,
    loadZone: function (zoneCode, reloadTimeout, zoneId) {
        if (this.jQuery === false) {
            setTimeout(function () {
                XenCentral_AdServer_Core.loadZone(zoneCode, reloadTimeout, zoneId);
            }, 100);
            return;
        }
        var $ = this.jQuery;
        var $container;
        if ($("#" + zoneId).prop('tagName') == 'SCRIPT') {
            // replace the script tag with container
            $container = $('<span></span>');
            $container.insertAfter($("#" + zoneId));
            $("#" + zoneId).remove();
            $container.attr('id', zoneId);
        } else {
            $container = $("#" + zoneId);
        }

        try {
            $container.html(zoneCode);
        } catch (ex) {
            console.log(ex.message);
        }

        this.adjustMultiBannerContainer($container.find('.multiBannerContainer'));
        this.adjustBannerColors($container);

        if (reloadTimeout) {
            var interval = setInterval(function () {
                if (!XenCentral_AdServer_Core.pageIsActive) {
                    return;
                }
                clearInterval(interval);
                var src = $("#" + zoneId).attr("data-reload");
                src = src.replace(/&t=\d+/, "");
                src += "&t=" + (new Date()).getTime();
                var head = document.getElementsByTagName("head")[0];
                var script = document.createElement("script");
                script.src = src;
                head.appendChild(script);
            }, reloadTimeout);
        }
    },
    init: function ($) {
        this.jQuery = $;
        $(document).mousemove(XenCentral_AdServer_Core.updateLastActivity).scroll(XenCentral_AdServer_Core.updateLastActivity);

        $(window).resize(function () {
            if (this.resizeTO) clearTimeout(this.resizeTO);
            this.resizeTO = setTimeout(function () {
                $(this).trigger('resizeEnd');
            }, 500);
        });
        $(window).bind('resizeEnd', function () {
            XenCentral_AdServer_Core.adjustMultiBannerContainers();
        });
        setInterval(XenCentral_AdServer_Core.updatePageActiveStatus, 1000);
        XenCentral_AdServer_Core.updateLastActivity();
    },
    getMultiBannerContainers: function () {
        return this.jQuery('.multiBannerContainer')
    },
    adjustMultiBannerContainers: function () {
        this.getMultiBannerContainers().each(function () {
            XenCentral_AdServer_Core.adjustMultiBannerContainer(XenCentral_AdServer_Core.jQuery(this));
        });
    },
    adjustBannerColors: function($container) {
        if (!$container.data('color_adjusted')) {
            $container.data('color_adjusted', true);
            var bgcolor = this.rgbToHex(this.getBackground($container));
            if (bgcolor) {
                $container.find('a').css({
                    'color': this.contrastingColor(bgcolor)
                });
            }

            var headerColor = this.rgbToHex(this.getBackground($container.find('.header')));
            if (headerColor) {
                $container.find('.header').css({
                    'color': this.contrastingColor(headerColor)
                });
            }

            var footerColor = this.rgbToHex(this.getBackground($container.find('.footer')));
            if (footerColor) {
                $container.find('.footer').css({
                    'color': this.contrastingColor(footerColor)
                });
            }
        }
    },
    adjustMultiBannerContainer: function ($container) {
        var width = +$container.data('width');
        var height = +$container.data('height');
        var cols = +$container.data('cols');
        var rows = +$container.data('rows');

        if(!width && !height && !cols && !rows) {
            // no sizing processing is needed
            return;
        }

        var $measureDiv = $container.prev('.measureDiv');
        if ($measureDiv.length == 0) {
            // create the element
            $measureDiv = $('<div class="measureDiv"></div>');
            $measureDiv.insertBefore($container);
        }
        $container.hide();

        var availableWidth = $measureDiv.width();
        $container.show();

        $container.css('display', 'block');

        if (!width) {
            width = availableWidth;
        }

        if (availableWidth > width) {
            $container.width(width);
            $container.css({
                'margin-left': 'auto',
                'margin-right': 'auto'
            });
        } else {
            $container.width(availableWidth);
            width = availableWidth;
        }

        var $bannerBlockContainer = $container.find('.bannerBlockContainer');
        if($bannerBlockContainer.length==0) {
            // no block container, no resizing needed
            return;
        }

        var $singleBannerWrappers = $bannerBlockContainer.find('.bannerOuterWrapper');

        if (height) {
            var availableHeight = height - $container.find('.header').height() - $container.find('.footer').height();
            $bannerBlockContainer.css({
                'max-height': availableHeight,
                'overflow-y': 'hidden'
            });
        }

        var itemWidth = Math.floor(width / cols);
        if (itemWidth < 50) {
            itemWidth = 50;
        }

        $singleBannerWrappers.css({
            width: itemWidth,
            float: 'left'
        });

        var requiredWidth = 0;

        $container.find('div.bannerBlockContainer div.link a').each(function () {
            requiredWidth = Math.max(requiredWidth, $(this).width());
        });

        if (requiredWidth > itemWidth) {
            var colCount = Math.floor(width / requiredWidth);
            requiredWidth = Math.floor(width / cols);
            $singleBannerWrappers.css({
                width: requiredWidth
            });

            itemWidth = requiredWidth;
        }

        $singleBannerWrappers.find('.thumb').css({
            height: itemWidth,
            'overflow': 'hidden'
        });

        var realHeight = $bannerBlockContainer.height();

        var parentPosition= $bannerBlockContainer.position().top;

        $singleBannerWrappers.each(function(index, el){
            var $el=$(el);
            $el.show();
            var bottomPosition= $el.position().top-parentPosition+ $el.height();
            if(bottomPosition>realHeight+5) { // 5px overlap
                $el.hide();
            }
        });
    },
    contrastingColor: function (color) {
        return (this.luma(color) >= 165) ? '#000000' : '#ffffff';
    },
    luma: function (color) // color can be a hx string or an array of RGB values 0-255
    {
        var rgb = (typeof color === 'string') ? this.hexToRGBArray(color) : color;
        return (0.2126 * rgb[0]) + (0.7152 * rgb[1]) + (0.0722 * rgb[2]); // SMPTE C, Rec. 709 weightings
    },
    getBackground: function (jqueryElement) {
        // Is current element's background color set?
        var color = jqueryElement.css("background-color");

        if ((color !== 'rgba(0, 0, 0, 0)') && (color !== 'transparent')) {
            // if so then return that color
            return color;
        }

        // if not: are you at the body element?
        if (jqueryElement.is("body")) {
            // return known 'false' value
            return false;
        } else {
            // call getBackground with parent item
            return this.getBackground(jqueryElement.parent());
        }
    },
    rgbToHex: function (color) {
        if (!color) {
            return false; // white by default
        }
        if (color.substr(0, 1) === "#") {
            return color;
        }
        var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
            r = parseInt(nums[2], 10).toString(16),
            g = parseInt(nums[3], 10).toString(16),
            b = parseInt(nums[4], 10).toString(16);
        return "" + (
                (r.length == 1 ? "0" + r : r) +
                (g.length == 1 ? "0" + g : g) +
                (b.length == 1 ? "0" + b : b)
            );
    },
    hexToRGBArray: function (color) {
        if (color.length === 3)
            color = color.charAt(0) + color.charAt(0) + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2);
        else if (color.length !== 6)
            throw('Invalid hex color: ' + color);
        var rgb = [];
        for (var i = 0; i <= 2; i++)
            rgb[i] = parseInt(color.substr(i * 2, 2), 16);
        return rgb;
    },
    updateLastActivity: function () {
        XenCentral_AdServer_Core.lastActivity = (new Date()).getTime();
    },
    updatePageActiveStatus: function () {
        if ((new Date()).getTime() - XenCentral_AdServer_Core.lastActivity > 30000) {
            XenCentral_AdServer_Core.pageIsActive = false;
        } else {
            XenCentral_AdServer_Core.pageIsActive = true;
        }
    }
};
XenCentral_AdServer_ResourceLoader.callWhenReady('jQuery', function () {
    XenCentral_AdServer_Core.init(jQuery);
});