/**
 * Meinl Sites 2011
 *
 * LICENSE
 *
 * This source file is subject to a propietary license.
 * You may not use, change, modify this file without explict permission of
 * the Scandio GmbH.
 * For any questions, permission request please contact: info@scandio.de
 *
 * @category MEINL_SITES2011
 * @package
 * @copyright Copyright (c) 2011 Scandio GmbH, Germany (http://www.scandio.de)
 * @license   Please mail: info@scandio.de
 * @version   $Id: $
 */

/**
 *
 *
 * @category   SC_MEINLROTATOR
 * @package    MeinlRotator
 * @license    Please mail: info@scandio.de
 * @author     $Author: $
 * @version    $Id: $
 *
 */

var ROTATOR_VIEW_FULL = '0';
var ROTATOR_VIEW_SHORT = '1';

var MAX_ROTATIONS = 48;

window.autoRotationCounter = 0;

var MeinlRotator = {

    ajaxUrl : 'www.meinldistribution.eu',
    ajaxDataType : 'json',
    typo3Key : 'sc_meinlrotator',
    tabs : null,

    view : 'full',

    "init" : function(view)
    {
        MeinlRotator.view = view;
        tabs = $('.tabs ul li a');
        tabs.bind('click', {rotator: this}, this.changeCategory);

        var  prev = $('a[rel="news-slider"].container-nav.prev');
        prev.bind('click', {rotator: this, direction:'prev'}, this.nextNews);

        var  next = $('a[rel="news-slider"].container-nav.next');
        next.bind('click', {rotator: this, direction:'next'}, this.nextNews);

        $('div.container.slider').bind("play", function() {
            autoRotate = setInterval(function() {
                if ((typeof window.hasOpenedDialog == "undefined"
                    || window.hasOpenedDialog == null
                    || window.hasOpenedDialog == false)
                    && window.autoRotationCounter < MAX_ROTATIONS) {
                    window.$('a[rel="news-slider"].container-nav.next').trigger("click");
                    window.autoRotationCounter++;

                    if (window.autoRotationCounter >= MAX_ROTATIONS) {
                        $( 'div.container.slider' ).trigger("pause");
                    }
                }
            }, 7000);
        });

        $('div.container.slider').bind("pause", function() {
            clearTimeout(autoRotate);
        })

        $('div.container.slider').hover(
            function() { $( 'div.container.slider' ).trigger("pause");
            },
            function() {
                window.autoRotationCounter = 0;
                $( 'div.container.slider' ).trigger("play");
            }
        );

        $('div.container.slider').trigger("play");
    },

    "ajax" : function (requestData)
    {
        requestData.dataType = MeinlRotator.ajaxDataType;
        requestData.eID = MeinlRotator.typo3Key;

        $.ajax({
            url: MeinlRotator.ajaxUrl,
            data: requestData,
            success: MeinlRotator.success,
            failure: MeinlRotator.failure,
            cache:false
          });

        purge(requestData);
    },

    "changeCategory" : function(event)
    {
       tabs.removeClass('active');
       $(this).addClass('active');

       var data = {};
       data['category'] = event.data.rotator.getActiveCategory();

       data['view'] = MeinlRotator.view;
       var newsRequest = {
           action: 'changeCategory',
           callback: 'changeCategorySuccess',
           module: 'news',
           data: data
       };

       MeinlRotator.ajax(newsRequest);
    },

    "changeCategorySuccess" : function(data)
    {
        var news = data['news'];
        var view = data['view'];
        MeinlRotator.fillNews(news, null, view);

        $('div.simpleSlide-tray[rel="news-slider"]').css('width', '976px');
        $('div.simpleSlide-tray[rel="news-slider"]').css('margin', '0');
    },

    "fillNews" : function(news, newsItem, view)
    {
        // get active news
        if (typeof newsItem == "undefined" || newsItem == null) {
            newsItem = $('div[rel="news-slider"].container-news.active');
        }

        // remove all old news
        $("div.container-news:not(.active)").remove();
        $('div[rel="news-slider"].container-news').removeClass('active');

        $('.news-content', newsItem).attr('id', "news-item_" + news[0].uid);
        newsItem.addClass('active');
        switch (view) {
            case ROTATOR_VIEW_FULL:

                $('.category a', newsItem).html(news[0].category);
                $('.category a', newsItem).attr("href", news[0].categoryUrl);

                $('.item-content .date', newsItem).html(news[0].datetime);
                $('.item-content h2', newsItem).html(news[0].title);
                $('.item-content p', newsItem).html(news[0].short);
                $('a.news-slider-articlelink', newsItem).attr("href", news[0].linkurl);
                $('.buttons .share', newsItem).attr("rel", news[0].absolutelinkurl);
                $('.buttons .share', newsItem).attr("title", news[0].title);

                $('.item-image a', newsItem).html(news[0].images[0]);

                if (news[0].imageDialog.length > 0) {
                    $('.media-links .images', newsItem).replaceWith(news[0].imageDialog);
                }
                else {
                    $('.media-links .images', newsItem).html('');
                }
                if (news[0].videoDialog.length > 0) {
                    $('.media-links .video', newsItem).replaceWith(news[0].videoDialog);
                }
                else {
                    $('.media-links .video', newsItem).html('');
                }

                break;
            case ROTATOR_VIEW_SHORT:
                $('.news-caption', newsItem).html('&gt; ' + news[0].title);
                $('.news-caption', newsItem).attr("href", news[0].linkurl);
                $('.item-image img', newsItem).replaceWith(news[0].images[0]);
                $('img', newsItem).replaceWith(news[0].images[0]);
                break;
            default:
                break;
        }

        purge(news);
        purge(newsItem);
        purge(view);
    },

    "nextNews" : function(event)
    {
        var category =  event.data.rotator.getActiveCategory();
        var news = $('.container-news.active div.news-content');
        var divId = "";

        if (typeof(news) != "undefined" && news.length > 0) {
            divId = news.attr('id');
        }

        if (divId.length > 0) {
            var idArr = divId.split("_");
            var data = {};
            data['uid'] = idArr[1];
            data['language'] = news.attr('data-langId');
            data['category'] = category;
            data['view'] = MeinlRotator.view;
            data['direction'] = event.data.direction;
            var newsRequest = {
                action: 'nextItem',
                callback: 'nextNewsSuccess',
                module: 'news',
                data: data
            };

            MeinlRotator.ajax(newsRequest);
            purge(idArr);
            purge(data);
            purge(newsRequest);
        }

        purge(category);
        purge(event);
        purge(divId);
    },

    "nextNewsSuccess" : function(data)
    {
        if (typeof(ScDialogSlider) != "undefined") {
            purge(ScDialogSlider);
        }
        var newsData = data['news'];
        var view = data['view'];

        var tray = $('div.simpleSlide-tray[rel="news-slider"]');
        var container = $('.container-news');
        var cloneNode  = container.first();

        MeinlRotator.fillNews(newsData, cloneNode, view);

        var direction = data['direction'];
        switch (direction) {
            case 'next':
                MeinlRotator.appendNextNode(tray, container, cloneNode);
                MeinlRotator.rotateNext();
                break;
            case 'prev':
                MeinlRotator.prependPreviousNode(tray, container, cloneNode);
                MeinlRotator.rotatePrev(view);
                break;
            default:
                break;
        }

        if (view == ROTATOR_VIEW_FULL) {
            var uid = newsData[0].uid;

             $('#news-item_' + uid + ' .media-links .images a.openDialog ').attr('onclick', '');
             $('#news-item_' + uid + ' .media-links .images a.openDialog ').unbind('click').bind('click', function() {
                ScDialogSlider.init('newsImageGallery_' + uid, 'newsPictures_'  + uid, 'image');
                ScDialogSlider.open('newsPictures_'  + uid);
             });

             $('#news-item_' + uid + ' .media-links .video a.openDialog ').attr('onclick', '');
             $('#news-item_' + uid + ' .media-links .video a.openDialog ').unbind('click').bind('click', function() {
                ScDialogSlider.init('newsVideoGallery_'  + uid, 'newsVideos_'  + uid, 'video');
                ScDialogSlider.open('newsVideos_'  + uid);
             });
        }

        // remove old layer and add new share button
        $('.layer-share').remove();
        $('#main .buttons-share .share').socialShareButton();

        purge(data);
        purge(cloneNode);
        purge(newsData);
        purge(tray);
        purge(direction);
    },

    "appendNextNode" : function(tray, container, node)
    {
        tray.append(node);

        purge(container);
        purge(tray);
        purge(node);
    },

    "prependPreviousNode" : function(tray, container, node)
    {
        node.attr("alt", 1);
        tray.css('width', '1952px');
        tray.css('margin', '0pt 0pt 0pt -976px');
        container.last().attr("alt", 2);
        tray.prepend(node);
    },

    "rotateNext" : function()
    {
        simpleSlide({'rel':'news-slider'});
        $(".right-button[rel='news-slider']").trigger('click');
    },

    "rotatePrev" : function(view)
    {
        simpleSlide({'rel':'news-slider'});
        var simpleSlider = $('.simpleSlide-tray[rel="news-slider"]');
        var marginLeft = (view == ROTATOR_VIEW_FULL) ? "-976px" : "-241px";
        simpleSlider.css("margin-left", marginLeft);
        simpleSlider.animate({
            'marginLeft': '0px'
        }, 250, "swing");

        $('.simpleSlideStatus-window .simpleSlideStatus-tray[rel="news-slider"]')
            .animate({
                'marginLeft': '0px'
        }, 250, "swing");

        $('.simpleSlideStatus-tray .simpleSlideStatus-window[rel="news-slider"]')
            .animate({
                'marginLeft': '0px'
        }, 250, "swing");
    },

    "getActiveCategory" : function()
    {
        var category = 0;
        var actTab = $('.tabs ul li a.active');

        if (actTab.length > 0) {
            var linkId = actTab.attr('id');

            if (linkId.length > 0) {
                var linkSplit = linkId.split("_");

                purge(actTab);
                purge(linkId);
                category = linkSplit[2];
            }
        }
        else {
            category = $('.container-news.active .news-content').attr('data-categoryId');
        }


        return category;
    },

    "success" : function(data)
    {
        if (typeof data != 'undefined') {
            if (data.callback.length) {
                switch (data.callback) {
                    case "changeCategorySuccess":
                        MeinlRotator.changeCategorySuccess(data.data);
                       break;
                    case "nextNewsSuccess":
                        MeinlRotator.nextNewsSuccess(data.data);
                       break;
                    default: "";
                }
            }
        }

        purge(data);
    },

    "failure" : function(data)
    {
       alert("failure");
    }
}


function purge(d) {
    if (typeof(d) != "undefined") {
        var a = d.attributes, i, l, n;
        if (a) {
            for (i=0, l=a.length; i<l; i++) {
                n = a[i].name;
                if (typeof d[n] === 'function') {
                    d[n] = null;
                }
            }
        }
        a = d.childNodes;
        if (a) {
            for (i=0, l=a.length; i<l; i++) {
                purge(d.childNodes[i]);
            }
         }
        delete d;
    }
}

