﻿function TopNews(objRoot,newsCountPerPage,viewSubtitle,Interval) {
    //Init
    //root element in DOM.module container.used in jquery selector to gain unique objects
    this._root=objRoot;
    this._currPageIndex = 0;
    this._currNewsIndex = 0;
    this._slideShowInterval = Interval;
    this.nextNewsIntervalId = 0;
    this._newsCountPerPage = newsCountPerPage;
    this._viewSubtitle = viewSubtitle;
    this.news = new Array();
    this.baseHeight = 0;
    
    this.fetchAllNews();    
}

TopNews.prototype = {
    //call asp.net page method asynchronous (send and recives data in JSON format)
    PageMethod: function(fn, paramArray, successFn, errorFn) {
        var pagePath = window.location.pathname;
        var that = this;
        //Call the page method  
        $.ajax({
            type: "POST",
            url: pagePath + "?Callback=" + fn,
            contentType: "application/json; charset=utf-8",
            data: paramArray,
            dataType: "json",
            success: function(res) { successFn(res, that) },
            error: errorFn
        }); 
    },

    //override jquery selector to ensure selected DOM objects be unique in multiple instanse of module
    getElement: function(domElement) {
        return $(this._root).find(domElement);
    },

    ToggleDesc: function(itm) {
        var ht = this.getElement('.main_news').find('.block').height() - $(itm).parent().height();
        if (escape($(itm).text()) == '%u2500')
            this.getElement('.main_news .block').animate({ marginBottom: -ht }, 250, function() { $(itm).text('+'); });
        else
            this.getElement('.main_news .block').animate({ marginBottom: "0" }, 250, function() { $(itm).text(unescape('%u2500')); });
    },

    initUI: function() {
        var that = this;
        this.baseHeight = Math.ceil(this.getElement('.news_thumb div:first').height() / this.getElement('.news_thumb div:first ul li').length);
        var minHeight = this.getElement('.news_thumb div:first').height() > (this.baseHeight * 8) ? this.getElement('.news_thumb div:first').height() : (this.baseHeight * 8);
        this.getElement('.news_thumb').css({ 'height': minHeight + 'px', 'min-height': minHeight + 'px' });
        this.getElement('.news_thumb div').css({ 'height': minHeight + 'px', 'min-height': minHeight + 'px' });

        this.getElement('.main_news').height(this.getElement('.main_news').parent().height() - this.getElement('.main_news').siblings().height());
       
        this.getElement('.main_news').width(337);
       // this.getElement('.main_news').width(this.getElement('.main_news').height() * 1.5);

        this.getElement('.main_news .logo').animate({ opacity: 0.75 }, 1);

        for (var i = 0; i < this.getElement('.news_thumb div.active ul li').length; i++)
            this.getElement('.toolbar ul').append('<li>&#8226</li>');

        if (!this._viewSubtitle) {
            this.getElement('.subtitlebar').parents('tr:first').hide();
        }

        //add handlers
        this.getElement('#toggleDescIcon').click(function() { that.ToggleDesc(this); });
        this.getElement('.toolbar #btnPrev').click(function() { that.prevNews(); });
        this.getElement('.toolbar #btnNext').click(function() { that.nextNews(that); });
        this.getElement('.toolbar #btnPausePlay').click(function() { that.PausePlay(this); });
        this.getElement('.news_thumb ul li').click(function() {
            if ($(this).is('.active')) {
                return false;
            }
            else {
                that.getElement('.news_thumb ul li').removeClass('active');
                $(this).addClass('active');
                that._currNewsIndex = (that._currPageIndex * that._newsCountPerPage) + $(this).prevAll('li').size();
                that.setTopOne();
            }
            return false;
        }).hover(function() {
            $(this).addClass('hover');
        }, function() {
            $(this).removeClass('hover');
        });

        this.getElement('.pagerbar ul li').click(function() {
            if ($(this).is('.active')) {
                return false;
            }
            else {
                that.getElement('.pagerbar ul li').removeClass('active');
                $(this).addClass('active');

                var selectedPageIndex = $(this).prevAll('li').size();
                var ht = that.getElement('.news_thumb div.active').height();

                var step = Math.abs(selectedPageIndex - that._currPageIndex);

                if (selectedPageIndex > that._currPageIndex) {
                    var upStep = Math.abs(parseInt(that.getElement('.news_thumb div:first').css('margin-top'))) + (ht * step);
                    that.getElement('.news_thumb div:first').animate({ marginTop: -upStep }, 1000, function() {
                        that.getElement('.news_thumb div').removeClass('active');
                        that.getElement('.news_thumb div:eq(' + selectedPageIndex + ')').addClass('active');

                        that._currPageIndex = selectedPageIndex;

                        that.getElement('.toolbar ul').empty();
                        for (var i = 0; i < that.getElement('.news_thumb div.active ul li').length; i++) {
                            that.getElement('.toolbar ul').append('<li>&#8226</li>');
                        }

                        that.setSubtitle();
                        if (that._viewSubtitle)
                            that.getElement('.subtitlebar').cycle({ fx: 'scrollUp', random: 1, cleartype: 0, timeout: 6000 });

                        that.getElement('.news_thumb div.active ul li:first').click();
                    });
                }
                else {
                    var downStep = parseInt(that.getElement('.news_thumb div:first').css('margin-top')) + (ht * step);
                    that.getElement('.news_thumb div:first').animate({ marginTop: downStep }, 1000, function() {
                        that.getElement('.news_thumb div').removeClass('active');
                        that.getElement('.news_thumb div:eq(' + selectedPageIndex + ')').addClass('active');

                        that._currPageIndex = selectedPageIndex;

                        that.getElement('.toolbar ul').empty();
                        for (var i = 0; i < that.getElement('.news_thumb div.active ul li').length; i++) {
                            that.getElement('.toolbar ul').append('<li>&#8226</li>');
                        }

                        that.setSubtitle();
                        if (that._viewSubtitle)
                            that.getElement('.subtitlebar').cycle({ fx: 'scrollUp', random: 1, cleartype: 0, timeout: 6000 });

                        that.getElement('.news_thumb div.active ul li:first').click();
                    });
                }
            }
        }).hover(function() {
            $(this).addClass('hover');
        }, function() {
            $(this).removeClass('hover');
        });
    },

    setTopOne: function() {
        //set variables
        var that = this;
        var newsId=this.news[this._currNewsIndex].newsId;
        var imgSrc = this.news[this._currNewsIndex].imgSrc;
        var newsTitle = this.news[this._currNewsIndex].Title;
        var newsDesc = this.news[this._currNewsIndex].Summary;
        var newsDate = this.news[this._currNewsIndex].newsDate;
        var newsDescHeight = this.getElement('.main_news').find('.block').height();

        this.getElement('.main_news .desc').show();

        this.getElement('.main_news .block').animate({ opacity: 0, marginBottom: -newsDescHeight }, 250, function() {
            that.getElement('.main_news .block h4').text(newsTitle);
           // that.getElement('.main_news .block small').text(newsDate);
            that.getElement('.main_news .block p').text(newsDesc);
            that.getElement('.main_news .block').animate({ opacity: 0.75, marginBottom: "0" }, 250, function() { that.getElement('.main_news .block #toggleDescIcon').text(unescape('%u2500')); });
            that.getElement('.main_news #imgMain').attr('src', imgSrc);
            that.getElement('.main_news #nwsLink').attr('href', 'detaild.aspx?elmnt='+newsId);            
            that.getElement('.main_news #imgMain').hide(1, function() {
                
                if ($(this).height() > $(this).width())
                    $(this).css({ 'height': that.getElement('.main_news').height() });
                else
                    $(this).css({ 'width': that.getElement('.main_news').width() }); 
                $(this).show(1, function() { $(this).css('display', 'inline'); });
            });
        });

        this.getElement('.toolbar ul li').removeClass('active');
        this.getElement('.toolbar td ul li:eq(' + (this._currNewsIndex % this._newsCountPerPage) + ')').addClass('active');
    },

    BindTextNews: function() {
        for (var index = 0; index < this.news.length; index++) {
            if (index % this._newsCountPerPage == 0) {
                $('<div><ul></ul></div>').appendTo(this.getElement('.news_thumb'));
                this.getElement('.pagerbar td:eq(1) ul').append($('<li></li>').text(Math.floor(index / this._newsCountPerPage) + 1));
            }
            $('<li></li>').append($('<h4></h4>').text(this.news[index].Title)).appendTo(this.getElement('.news_thumb div:last ul'));
            this.getElement('.news_thumb div:last ul').append('<hr />');

        }

        this.getElement('.news_thumb div:first').addClass('active');
        this.getElement('.news_thumb ul li:first').addClass('active');

        this.getElement('.pagerbar td:eq(1) ul li:first').addClass('active');
    },

    setSubtitle: function() {
        if (this._viewSubtitle) {
            this.getElement('.subtitlebar').parents('tr:first').show();
            this.getElement('.subtitlebar').empty();

            var startIndex = this._currPageIndex * this._newsCountPerPage;
            var endIndex = startIndex + this.getElement('.news_thumb div.active ul li').length;
            for (var index = 0; index < this.news.length; index++) {
                if (index < startIndex || index >= endIndex) {
                    this.getElement('.subtitlebar').append($('<span></span>').text(this.news[index].Title));
                }
            }
            if (this.getElement('.subtitlebar span').length == 1)
                this.getElement('.subtitlebar').append('<span></span>');
        }

    },

    nextNews: function(that) {
        that.getElement('.news_thumb div.active ul li:eq(' + ((that._currNewsIndex + 1) % that._newsCountPerPage) % that.getElement('.news_thumb div.active ul li').length + ')').click();
    },

    prevNews: function() {
        if (this._currNewsIndex % this._newsCountPerPage == 0)
            this.getElement('.news_thumb div.active ul li:eq(' + (this.getElement('.news_thumb div.active ul li').length - 1) + ')').click();
        else
            this.getElement('.news_thumb div.active ul li:eq(' + ((this._currNewsIndex - 1) % this._newsCountPerPage) % this.getElement('.news_thumb div.active ul li').length + ')').click();
    },

    PausePlay: function(itm) {
        var str = new String($(itm).attr('src'));
        var pattern, s;
        if (str.toLowerCase().search('pause.png') != -1) {
            pattern = new RegExp('(Pause.png)', 'gi');
            s = $(itm).attr('src').replace(pattern, 'play.png');
            $(itm).attr('src', s);
            clearInterval(this.nextNewsIntervalId);
        }
        else {
            pattern = new RegExp('(play.png)', 'gi');
            s = $(itm).attr('src').replace(pattern, 'Pause.png');
            $(itm).attr('src', s);
            var that = this;
            this.nextNewsIntervalId = setInterval(function() { that.nextNews(that); }, this._slideShowInterval);
        }
    },

    BindNews: function() {
        this.BindTextNews();
        this.setSubtitle();
        this.initUI();
        this.setTopOne();
        if (this._viewSubtitle)
            this.getElement('.subtitlebar').cycle({ fx: 'scrollUp', random: 1, cleartype: 0, timeout: 6000 });
        var that = this;
        this.nextNewsIntervalId = setInterval(function() { that.nextNews(that); }, this._slideShowInterval);
    },

    SuccessFetchNews: function(response, that) {
        that.news = response;
        if (response.length == undefined)
            that.news = new Array(response);
        that.BindNews();
    },

    FailFetchNews: function(err) {
        alert('Error!  ' + err.responseText);
    },

    fetchAllNews: function() {
        this.PageMethod('fetchAllNews', '{}', this.SuccessFetchNews, this.FailFetchNews);
    }

}
 
 
