﻿//max number of news to scroll
var maxCountNews = 5;
var pathToNewsPage = 'news.html';
var wsGetNewsItems = '../news/NewsProviderService.asmx/Preview';
var wsGetHtmlTemplate = '../news/NewsProviderService.asmx/Template';

//Colt server link
var ashxShowImage = 'http://www.ariane.com/NewsAdmin/ashx/ShowImage.ashx';

var run = null;
var speed = 3000;
var newsCount = 0;
var isPaused = false;
var isLoading = false;

var gettingTemplate = false;
var template = '';

function InitNewsPreview(countryCode) {
    $(document).ready(loadCountryNews(countryCode));
}


String.prototype.format = function () {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{' + i + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};

function getNewsItems(count, countryCode) {
    $.ajax({
        type: "POST",
        url: wsGetNewsItems,
        data: "{count:" + count + ", countryCode:'" + countryCode + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            //alert(msg.d);
            var obj = jQuery.parseJSON(msg.d);
            var ul = jQuery('#gallery');
            //ul.empty();
            newsCount = 0;
            var markup = [];

            //            while (gettingTemplate) {
            //            }

            jQuery.each(obj, function () {
                //ul.append("<li>" + this.Title + "</li>");
                markup.push(template.format(this.Title,
                                            this.Subtitle,
                                            this.Text,
                                            pathToNewsPage //+ "?" + countryCode 
                                                           + "#" + this.NewsID.toString()));
                newsCount = newsCount + 1;
            });
            ul.html(markup.join(""));
            processResponse();
        },
        error: function (e) {
            //alert(e.responseText);
            newsCount = 0;
            processResponse();
        }
    });
};

function getNews(count, countryCode) {
    //function getTemplate() {

    gettingTemplate = true;

    $.ajax({
        type: "POST",
        url: wsGetHtmlTemplate,
        data: "{name:'NewsPreviewContent'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            //alert(msg.d);
            template = msg.d;
            gettingTemplate = false;
            getNewsItems(count, countryCode);
        },
        error: function (e) {
            //alert(e.responseText);
            gettingTemplate = false;
        }
    });
};

function loadCountryNews(countryCode) {
    $('#slider').addClass('loading');
    $('#buttons').addClass('hide');

    unbindEvents();
    stopScrolling();
    showListItem($('#gallery li:first'));

    isLoading = true;
    jQuery('#gallery').empty();
    //getTemplate();
    getNews(maxCountNews, countryCode);
}

function processResponse() {
    $('#slider').removeClass('loading');

    if (newsCount > 0) {
        $('#buttons').removeClass('hide');

        bindEvents();
        startScrolling('loadCountryNews');

        isLoading = false;
    }
    else {
        jQuery('#gallery').append("<li>no news available for selected country</li>");
    }
}

function unbindEvents() {
    $('#btn-pause').unbind(); //unbind('click');
    $('#btn-play').unbind();
    $('#btn-next').unbind();
    $('#btn-prev').unbind();
    $('#slider').unbind(); //unbind('mouseenter mouseleave');
}

function bindEvents() {

    //You have to specify width and height in #slider CSS properties
    //After that, the following script will set the width and height accordingly
    $('#gallery li').width(265);
    $('#mask-gallery').width($('#slider').width());
    $('#gallery').width($('#slider').width() * $('#gallery li').length);

    $('#gallery li:first').addClass('selected');

    //Pause the slidershow with clearInterval
    $('#btn-pause').click(function () {
        pauseScrolling();
        return false;
    });

    //Continue the slideshow with setInterval
    $('#btn-play').click(function () {
        startScrolling('btn-play');
        return false;
    });

    //Next Slide by calling the function
    $('#btn-next').click(function () {
        pauseScrolling();
        newsScroller('next', 0);
        return false;
    });

    //Previous slide by passing prev=1
    $('#btn-prev').click(function () {
        pauseScrolling();
        newsScroller('previous', 1);
        return false;
    });

    //Mouse over, pause it, on mouse out, resume the slider show
    $('#slider').hover(function () { stopScrolling(); }, function () { restartScrolling('mouseout'); });
}

function stopScrolling() {
    if (run != null) {
        clearInterval(run);
        run = null;
    }
}

function pauseScrolling() {
    stopScrolling();
    isPaused = true;
}

function restartScrolling(sender) {
    if (isPaused == false && isLoading == false) {
        startScrolling(sender);
    }
}

function startScrolling(sender) {
    if (run != null) {
        stopScrolling();
    }
    run = setInterval('newsScroller(\'' + sender + '\', 0)', speed);
    isPaused = false;
}


function newsScroller(sender, prev) {
    if (newsCount == 0) {
        return;
    }
    //Get the current selected item (with selected class), if none was found, get the first item
    var current_image = $('#gallery li.selected').length ? $('#gallery li.selected') : $('#gallery li:first');

    //if prev is set to 1 (previous item)
    if (prev) {

        //Get previous sibling
        var next_image = (current_image.prev().length) ? current_image.prev() : $('#gallery li:last').prev();
        //next_image = (next_image.prev().length) ? next_image : $('#gallery li:last').prev();

        //if prev is set to 0 (next item)
    } else {

        //Get next sibling
        var next_image = (current_image.next().length) ? current_image.next() : $('#gallery li:first');
        next_image = (next_image.next().length) ? next_image : $('#gallery li:first');
    }

    showListItem(next_image);

}

function showListItem(next_image) {
    if (next_image && next_image.length && next_image.length > 0) {

        //clear the selected class
        $('#gallery li').removeClass('selected');

        //reassign the selected class to current items
        next_image.addClass('selected');

        //Scroll the items
        $('#mask-gallery').scrollTo(next_image, 800);
    }
}
