﻿var state = StateHandler.getInstance();
var allGenres = new Object();

$(document).ready(function() {
    state.readUrl();
    
    initGenres();
    $("#popFilterAll").click(function() { fireEvent("popFilter", "All"); });
    $("#popFilterPopular").click(function() { fireEvent("popFilter", "Popular"); });
    //setze aktive Filter
    initFilterState();
    $.fn.EndlessList.globals.currentPage = parseInt(state.getParam("cPage", "1")) - 1;
    $.fn.EndlessList.globals.loadList = loadList;
    $.fn.EndlessList.globals.loadElement = '/Service/Community.asmx/GetCommentDetail';
    $.fn.EndlessList.globals.template = $("#CommentDetailTemplate").html();
    $.fn.EndlessList.globals.pagerTop = ".pagerTop";
    $.fn.EndlessList.globals.pagerBottom = ".pagerBottom";
    $("#ListingBox").EndlessList();

});
function initFilterState() {
    $("#ListingFilterBox a").removeClass("active").parent().removeClass("active");
    $("#popFilter" + state.getParam("popFilter", "All")).addClass("active").parent().addClass("active");
}
function loadList(page, appsPerPage) {
    $.ajax({
        type: "POST",
        url: "/Service/Community.asmx/GetNewestCommentIds",
        data: "{'genreID':'" + state.getParam("genre", "0") + "','sort':'" + state.getParam("sorting", "ReleaseDate") + "','popFilter':'" + state.getParam("popFilter", "All") + "','page':'" + page + "','appsPerPage':'" + appsPerPage + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $.fn.EndlessList.loadedList(eval('(' + msg.d + ')'));
        }
    });
}
// hier werden die Genres geladen und die Elemente für Stateful aufbereitet.
function initGenres() {
    $.ajax({
        type: "POST",
        url: "/Service/listings.asmx/GetGenres",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(msg) {
            alert('error');
        },
        success: function(msg) {
            $("#FilterGenre").empty();
            var json = eval('(' + msg.d + ')');
            $("#FilterGenre").setTemplate($("#GenreTemplate").html());
            $("#FilterGenre").processTemplate(json);
            for (var k = 0; k < json.List.length; k++) {
                // speichere Genre in Array
                allGenres[json.List[k].ID] = json.List[k].Name;
            }
            $("#FilterGenre").AppZappDrowDown({
                clickEvent: function(relation) {
                    fireEvent("genre", relation);
                },
                cssPrefix: "FilterGenre_",
                activeRelation: state.getParam("genre", "0")
            });

            // muss hier nochmal gemacht werden, da die Elemente nachgeladen wurden.
            state.notifyListeners();
        }
    });
}	
