﻿$.fn.Table = function(options) {
    var defaults = {
        targeturl: "./season20078.xml",
        season: '2009/10',
        tournament: 'Wsyl League'
    }
    
    var opts = $.extend(defaults, options);
    var container = this;
    var _currentSeason;
    $(container).empty();

    $.ajax({
        type: "GET",
        url: opts.targeturl, //Requesting simple.xml
        dataType: "xml", //Make sure that you specify the type of file you expecting (XML)
        complete: function(data) {

            var tab = new Table(data, opts);
			var html = tab.Print();
            $(container).append(html);
        }
    });
};

function Table(xml, opts) {
    this.xml = xml;
    var data;

    $(this.xml.responseXML).find('Season').each(function() {
        var $item = $(this);

        if ($item.attr("Name") == opts.season) {
            $item.find('Tournament').each(function() {
                var $tournament = $(this);
                if ($tournament.attr("Name") == opts.tournament && $tournament.attr("Type") == "League") {
                    data = $tournament;
                }
                else if ($tournament.attr("Name") == opts.tournament && $tournament.attr("Type") == "Tour") {
                    data = $tournament;
                }
            });
        }
    });

    this.Print = function() {
        var html = "";

        if ($(data)[0].nodeName == "Tournament") {
            $(data).find('League').each(function() {

                var teamlist = new TeamList();

                //find each 'item' in the file and parse it
                $(this).find('Game').each(function() {

                    // if the game is in the future ignore.
//                    var dateFrom = $(this).attr("Date");
//                    var yr1 = parseInt(dateFrom.substring(0, 4), 10);
//                    var mon1 = parseInt(dateFrom.substring(4, 6), 10);
//                    var dt1 = parseInt(dateFrom.substring(6, 8), 10);

//                    var d1 = new Date(yr1, mon1 - 1, dt1);
//                    var d2 = new Date();

//                    var milli_d1 = d1.getTime();
//                    var milli_d2 = d2.getTime();
//                    var diff = milli_d2 - milli_d1;

                    //if( milli_d1 <= milli_d2){
                    var game = new Game();
                    $(this).find('Team').each(function() {
                        game.AddTeam($(this).attr("Name"), $(this).attr("Goals"));
                    });

                    teamlist.AddGame(game);
                    //}
                });

                html += teamlist.Print();
                for (var i = 0; i < teamlist.Count(); i++) {
                    html += ((teamlist.Get(i)).GetGames()).Print();
                }
            });
        }

        return html;
    }

}



