﻿function TopNews(objRoot,newsCountPerPage,viewSubtitle,Interval,initJSON) {
    //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.rotating = false;

	// atbs
	this.newsItems = 0;
	this.numberOfPages = 0;
	this.initJSON = initJSON;

//    this.fetchAllNews();
    this.loadFromJSON();
}

TopNews.prototype = {
    //call 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: '/test.php',
            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);
    },

    initUI: function () {
        var that = this;
        this.getElement('.news_thumb tr td').hover(function () {
            that.rotating = false;
            if ($(this).is('.active')) {
                return false;
            }
            else {
                that.getElement('.news_thumb tr td').removeClass('active');
                $(this).addClass('active');
                that._currNewsIndex = (that._currPageIndex * that._newsCountPerPage) + $(this).prevAll('td').size()
                that.setTopOne();

            }
        }, function () {

            return false;

        });
        this.getElement('.pagerbar a.next').click(function () {
            that.movePage(true);
            return false;
        });
        this.getElement('.pagerbar a.prev').click(function () {
            that.movePage(false);
            return false;
        });

        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 tr td').length; i++) {
                        that.getElement('.toolbar ul').append('<td>&#8226</td>');
                    }


                    if (that._viewSubtitle)
                        that.getElement('.subtitlebar').cycle({ fx: 'scrollUp', random: 1, cleartype: 0, timeout: 6000 });

                    that.getElement('.news_thumb div.active tr td: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 tr td').length; i++) {
                        that.getElement('.toolbar ul').append('<td>&#8226</td>');
                    }
                    if (that._viewSubtitle)
                        that.getElement('.subtitlebar').cycle({ fx: 'scrollUp', random: 1, cleartype: 0, timeout: 6000 });

                    that.getElement('.news_thumb div.active tr td:first').click();
                    //                    });
                }
            }
        }).hover(function () {
            $(this).addClass('hover');
        }, function () {
            $(this).removeClass('hover');
        });
    },

    setTopOne: function () {
        //set variables
        //console.debug(this);
        var that = this;
        var imgSrc = this.news[this._currNewsIndex].imgSrc;
        var imgThumbSrc = this.news[this._currNewsIndex].imgThumbSrc;
        var imgSrcLink = this.news[this._currNewsIndex].imgSrcLink;
        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 .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('.Header .HeaderLink').attr('href', imgSrcLink);
            that.getElement('.HeaderLink').text(newsTitle);
            that.getElement('.toolbar td').html(newsDesc);
            that.getElement('.main_news .imgMain').html(imgSrc);
            that.getElement('.main_news .imgMainLink').attr('href', imgSrcLink);

        });

        this.getElement('.toolbar ul li').removeClass('active');
        this.getElement('.toolbar td ul li:eq(' + (this._currNewsIndex % this._newsCountPerPage) + ')').addClass('active');
    },

    BindTextNews: function () {
        this.newsItems = this.news.length;

        this.numberOfPages = Math.ceil(this.newsItems / this._newsCountPerPage) - 1;

        var endNum = this._newsCountPerPage;
        if (endNum > this.newsItems) endNum = this.newsItems;
        this.getElement('.pagerbar span').html('1 - ' + endNum + ' of ' + this.newsItems);
        $('<ul></ul>').appendTo($('#news_thumb'));

        for (var index = 0; index < this.news.length; index++) {

            $('<li><a class="image"><img width="79" height="46"/><br/></a></li>').appendTo($('#news_thumb ul'));
            $('#news_thumb ul li:last a img').attr('src', this.news[index].imgThumbSrc)
                .parent('a').attr('href', this.news[index].imgSrcLink)
                .after($('<a></a>').attr('href', this.news[index].imgSrcLink).text(this.news[index].Title));

            //$('<td align=center><em></em></td>').append($('<img width=101 height=41 />').attr('src', this.news[index].imgThumbSrc)).appendTo(this.getElement('.news_thumb div:last tr'));
            //this.getElement('.news_thumb tr td:last').append($('<h4></h4>').text(this.news[index].Title));
        }

//        this.getElement('.news_thumb div:first').addClass('active');
//        this.getElement('.news_thumb tr td:first').addClass('active');
//        this.getElement('.pagerbar td:eq(1) tr td:first').addClass('active');
    },

    BindNews: function () {
        this.BindTextNews();
        this.initUI();
        this.setTopOne()
        var that = this;
        if (that._slideShowInterval > 0) {
            that.rotating = true;
            setTimeout(function () { that.rotate(that) }, that._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);
    },

    loadFromJSON: function () {
        //  	var json = eval(this.initJSON);
        var json = this.initJSON;
        this.news = new Array();
        for (var i = 0; i < json.length; i++) {
            this.news[i] = new Array();
            this.news[i].imgSrc = json[i].Description;
            this.news[i].imgThumbSrc = json[i].Image;
            this.news[i].imgSrcLink = json[i].URL;
            this.news[i].Summary = json[i].Description;
            this.news[i].newsDate = '';
            this.news[i].newsDesc = '';
            this.news[i].Title = json[i].Name;
        }
        this.BindNews();
    },

    rotate: function (that) {
        if (that.rotating) {
            // figure out next item
            that._currNewsIndex++;
            if (that._currNewsIndex >= that.newsItems) that._currNewsIndex = 0;
            that.setTopOne();
            that.getElement('.news_thumb tr td').removeClass('active');

            // check if next item is on the same page
            if (that.getPage(that._currNewsIndex) != that._currPageIndex) {
                that.movePage(true);
            }

            // get the item's location on the page and set it active
            var itemOnPageLoc = that.getLocationOnPage(that._currNewsIndex);
            that.getElement('.news_thumb tr td:eq(' + itemOnPageLoc + ')').addClass('active');

            that = this;
            setTimeout(function () { that.rotate(that) }, that._slideShowInterval);
        }
    },

    getPage: function (itemIndex) {
        return Math.ceil(++itemIndex / this._newsCountPerPage);
    },
    getLocationOnPage: function (itemIndex) {
        var page = this.getPage(itemIndex);
        var res = itemIndex - (page * this._newsCountPerPage - this._newsCountPerPage);
        //console.log('Page: ' + page + " itemIndex: " + itemIndex + "Per page: " +this._newsCountPerPage + " Res: " + res);
        return res;
    },

    movePage: function (forward) {
        var that = this;
        var nextPage = 0;

        if (forward) {
            nextPage = that._currPageIndex + 1;
            if (that._currPageIndex >= that.numberOfPages) nextPage = 0;
        } else {
            nextPage = that._currPageIndex - 1;
            if (nextPage < 0) nextPage = that.numberOfPages;
        }

        //	alert('nextPage: ' + nextPage + 'currPageIndex' + that._currPageIndex);

        that.getElement('.news_thumb div').removeClass('active');
        that.getElement('.news_thumb div:eq(' + nextPage + ')').addClass('active');
        that._currPageIndex = nextPage;

        var startNum = (that._newsCountPerPage * nextPage) + 1;
        var endNum = that._newsCountPerPage * (nextPage + 1);
        if (endNum > that.newsItems) endNum = that.newsItems;

        this.getElement('.pagerbar span').html(startNum + ' - ' + endNum + ' of ' + that.newsItems);
    }
}

