var correctProtocol = function(url) {
    var uri = Ojay.URI.parse(url);
    uri.protocol = window.location.protocol.replace(/\W/g, '');
    uri.port = '';
    return uri.toString();
};


var ScoreWidget = new JS.Class({
	include: Ojay.Observable,
	
    initialize: function(element, url) {
        this._element = Ojay(element);
        this._settings = Ojay.URI.parse(url).params;
        setInterval(this.method('update'), 10*1000);
        this.update();
    },
    
    update: function() {
        Ojay.HTTP.GET(this.klass.FEED_URL, {}, {
            onSuccess: function(response) {
                try {
                    var data = response.parseJSON().filter(this.method('useMatch'));
                    this._element.setContent('');
                    if (data.length == 0)
                        this._element.setContent('<div class="error">Sorry, there are currently no games being played.</div>');
                    else
                        data.map(this.method('matchHTML')).forEach(this._element.method('insert'));
                    this.notifyObservers('update');
                } catch (e) {
                    this.notAvailable();
                }
            }.bind(this),
            
            onFailure: this.method('notAvailable')
        });
    },
    
    notAvailable: function() {
        this._element.setContent('<div class="error">Sorry, ECB Live Scores are not currently available.</div>');
    },
    
    useMatch: function(match) {
        if (this.getTeams().length == 0) return true;
        return this.getTeams().some(function(team) {
            return team == match.team1.id || team == match.team2.id;
        });
    },
    
    getTeams: function() {
        return ['counties', 'international', 'misc'].reduce(function(list, name) {
            var set = (this._settings[name + 'Teams'] || '').trim().split(/\s*,\s*/)
                      .filter(function(name) { return !isNaN(Number(name)); });
            return list.concat(set);
        }.bind(this), []);
    },
    
    matchHTML: function(match) {
        with (Ojay.HTML) {
            return div({className: "score-board"},
                div({className: "score-board-inner"},
                    table(
                        thead(
                            tr(
                                th({className: "team-one", scope: "col"},
                                    span(match.team1.abbreviation)
                                ),
                                th({className: "team-two", scope: "col"},
                                    span(match.team2.abbreviation)
                                )
                            )
                        ),
                        tr({className: 'teams'},
                            td({colSpan: 2},
	                            table(
		                            tr(
		                                td({className: "team-one"},
		                                    img({src:     correctProtocol(match.team1.logo.path),
		                                           height:  match.team1.logo.height,
		                                           width:   match.team1.logo.width}),
		                                    span({className: "score"}, match.team1.scores.join(" & "))
		                                ),
		                                td({className: "team-two"},
		                                    img({src:     correctProtocol(match.team2.logo.path),
		                                           height:  match.team2.logo.height,
		                                           width:   match.team2.logo.width}),
		                                    span({className: "score"}, match.team2.scores.join(" & "))
		                                )
		                            )
		                        )
		                    )
                        )
                    ),
                    p({className: "message"}, match.note),
                    a({href: match.scorecard_url, target: '_blank'}, "View scorecard on ecb.co.uk")
                )
            );
        };
    }
});

